Search in sources :

Example 1 with XMLModifier

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

the class ConverterViewModel method convert.

/**
	 * 正向转换
	 * @param sourceItem
	 * @param monitor
	 * @return ;
	 */
private Map<String, String> convert(final IConversionItem sourceItem, IProgressMonitor monitor) throws ConverterException {
    Map<String, String> result = null;
    boolean convertFlg = false;
    String xliffDir = ConverterUtil.toLocalPath(configBean.getXliffDir());
    String targetFile = ConverterUtil.toLocalPath(configBean.getTarget());
    String skeletonFile = ConverterUtil.toLocalPath(configBean.getSkeleton());
    // 转换前的准备
    ConverterContext converterContext = new ConverterContext(configBean);
    final Map<String, String> configuration = converterContext.getConvertConfiguration();
    // 转换前,生成临时的XLIFF文件,用此文件生成指定目标语言的XLIFF文件
    File targetTempFile = null;
    try {
        targetTempFile = File.createTempFile("tempxlf", "xlf");
    } catch (IOException e) {
        LOGGER.error(Messages.getString("model.ConverterViewModel.msg10"), e);
    }
    configuration.put(Converter.ATTR_XLIFF_FILE, targetTempFile.getAbsolutePath());
    if (configBean.getFileType().equals(FileFormatUtils.MS)) {
        IPreferenceStore ps = net.heartsome.cat.ts.ui.Activator.getDefault().getPreferenceStore();
        String path = ps.getString(ITranslationPreferenceConstants.PATH_OF_OPENOFFICE);
        String port = ps.getString(ITranslationPreferenceConstants.PORT_OF_OPENOFFICE);
        configuration.put("ooPath", path);
        configuration.put("ooPort", port);
    }
    // 创建skeleton文件
    File skeleton = new File(skeletonFile);
    if (!skeleton.exists()) {
        try {
            File parent = skeleton.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            skeleton.createNewFile();
        } catch (IOException e) {
            String message = MessageFormat.format(Messages.getString("model.ConverterViewModel.msg11"), skeletonFile);
            LOGGER.error(message, e);
            IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message + "\n" + e.getMessage());
            throw new ConverterException(status);
        }
    }
    try {
        // 执行转换
        Converter converter = getConverter();
        if (converter == null) {
            // Build a message
            String message = Messages.getString("model.ConverterViewModel.msg2") + configBean.getFileType();
            // Build a new IStatus
            IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message);
            throw new ConverterException(status);
        }
        result = converter.convert(configuration, monitor);
        final String alert = result.get("ttx2xlfAlert39238409230481092830");
        if (result.containsKey("ttx2xlfAlert39238409230481092830")) {
            //ttx 转 xlf 时,提示含有未预翻译,不推荐,但没办法。
            Display.getDefault().syncExec(new Runnable() {

                public void run() {
                    MessageDialog.openWarning(Display.getCurrent().getActiveShell(), Messages.getString("handler.PreviewTranslationHandler.msgTitle"), alert);
                }
            });
        }
        // 处理骨架文件,将骨架文件路径修改为项目相对路径,此路径写入external-file节点的href属性
        String projectPath = sourceItem.getProject().getLocation().toOSString();
        String sklPath = skeletonFile.replace(projectPath, "");
        // 处理目标语言, 创建多个目标语言的文件
        List<Language> tgtLang = configBean.getHasSelTgtLangList();
        if (tgtLang != null && tgtLang.size() > 0) {
            // 解析XLIFF文件
            File f = new File(targetTempFile.getAbsolutePath());
            FileInputStream is = null;
            byte[] b = new byte[(int) f.length()];
            try {
                is = new FileInputStream(f);
                is.read(b);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            VTDGen vg = new VTDGen();
            vg.setDoc(b);
            try {
                vg.parse(true);
            } catch (VTDException e) {
                String message = Messages.getString("model.ConverterViewModel.msg12");
                LOGGER.error(message, e);
                IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message + "\n" + e.getMessage());
                throw new ConverterException(status);
            }
            VTDNav vn = vg.getNav();
            VTDUtils vu = new VTDUtils();
            // 生成多个XLIFF文件,只是修改目标语言和骨架文件路径
            for (Language lang : tgtLang) {
                // 修复 bug 2949 ,当文件名中出现 XLIFF 时,文件名获取失败,下面注释代码为之前的代码。	--robert	2013-04-01
                //					String[] pathArray = targetFile.split(Constant.FOLDER_XLIFF);
                //					StringBuffer xlffPath = new StringBuffer(pathArray[0]);
                //					xlffPath.append(Constant.FOLDER_XLIFF).append(File.separator).append(lang.getCode())
                //							.append(pathArray[1]);
                String fileName = targetFile.substring(xliffDir.length());
                StringBuffer xlfPahtSB = new StringBuffer();
                xlfPahtSB.append(xliffDir);
                xlfPahtSB.append(File.separator);
                xlfPahtSB.append(lang.getCode());
                xlfPahtSB.append(fileName);
                File tmpFile = new File(xlfPahtSB.toString());
                generateTgtFileList.add(tmpFile);
                if (!tmpFile.exists()) {
                    File parent = tmpFile.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    try {
                        tmpFile.createNewFile();
                    } catch (IOException e) {
                        String message = Messages.getString("model.ConverterViewModel.msg13");
                        LOGGER.error(message, e);
                        IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message + "\n" + e.getMessage());
                        throw new ConverterException(status);
                    }
                }
                try {
                    vu.bind(vn.duplicateNav());
                } catch (NavException e) {
                    LOGGER.error("", e);
                }
                XMLModifier xm = vu.update("/xliff/file/@target-language", lang.getCode(), VTDUtils.CREATE_IF_NOT_EXIST);
                xm = vu.update(null, xm, "/xliff/file/header/skl/external-file/@href", TextUtil.cleanString(sklPath));
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(tmpFile);
                    // 写入文件
                    xm.output(fos);
                } catch (Exception e) {
                    String message = Messages.getString("model.ConverterViewModel.msg13");
                    LOGGER.error(message, e);
                    IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message + "\n" + e.getMessage());
                    throw new ConverterNotFoundException(status);
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            LOGGER.error("", e);
                        }
                    }
                }
            }
            vg.clear();
        }
        convertFlg = true;
    } catch (OperationCanceledException e) {
        LOGGER.info("ConverterViewerModel: 取消转换");
    } finally {
        if (!convertFlg) {
            for (File f : generateTgtFileList) {
                if (f != null && f.exists()) {
                    f.delete();
                }
            }
            if (skeleton != null && skeleton.exists()) {
                skeleton.delete();
            }
        }
        targetTempFile.delete();
        sourceItem.refresh();
    }
    return result;
}
Also used : ConverterException(net.heartsome.cat.converter.ConverterException) XMLModifier(com.ximpleware.XMLModifier) IStatus(org.eclipse.core.runtime.IStatus) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) Language(net.heartsome.cat.common.locale.Language) VTDException(com.ximpleware.VTDException) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) Converter(net.heartsome.cat.converter.Converter) ValidationStatus(org.eclipse.core.databinding.validation.ValidationStatus) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) NavException(com.ximpleware.NavException) VTDGen(com.ximpleware.VTDGen) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) NavException(com.ximpleware.NavException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ConverterException(net.heartsome.cat.converter.ConverterException) IOException(java.io.IOException) VTDException(com.ximpleware.VTDException) JobRunnable(net.heartsome.cat.convert.ui.job.JobRunnable) FileOutputStream(java.io.FileOutputStream) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) File(java.io.File) VTDNav(com.ximpleware.VTDNav)

Example 2 with XMLModifier

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

the class LanguageConfiger method deleteLanguageByCode.

public void deleteLanguageByCode(String code) {
    if (code != null && !code.equals("")) {
        try {
            XMLModifier xm = vu.delete("/languages/lang[@code='" + code + "']");
            vu.bind(xm.outputAndReparse());
            saveToFile(xm, langConfigFile);
        } catch (Exception e) {
            LOGGER.error(Messages.getString("file.LanguageConfiger.logger2"), e);
        }
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) XPathParseException(com.ximpleware.XPathParseException) NavException(com.ximpleware.NavException) IOException(java.io.IOException) ModifyException(com.ximpleware.ModifyException) ParseException(com.ximpleware.ParseException) TranscodeException(com.ximpleware.TranscodeException) XPathEvalException(com.ximpleware.XPathEvalException)

Example 3 with XMLModifier

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

the class LanguageConfiger method addLanguage.

/**
	 * 添加一种语言
	 * @param newLanguage
	 *            ;
	 */
public void addLanguage(Language newLanguage) {
    String content = generateLangNode(newLanguage);
    if (!content.equals("")) {
        try {
            XMLModifier xm = vu.insert("/languages/text()", content);
            vu.bind(xm.outputAndReparse());
            saveToFile(xm, langConfigFile);
        } catch (Exception e) {
            LOGGER.error(Messages.getString("file.LanguageConfiger.logger3"), e);
        }
        ap.resetXPath();
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) XPathParseException(com.ximpleware.XPathParseException) NavException(com.ximpleware.NavException) IOException(java.io.IOException) ModifyException(com.ximpleware.ModifyException) ParseException(com.ximpleware.ParseException) TranscodeException(com.ximpleware.TranscodeException) XPathEvalException(com.ximpleware.XPathEvalException)

Example 4 with XMLModifier

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

the class LanguageConfiger method updateLanguageByCode.

/**
	 * 通过Code,更新一种语言
	 * @param code
	 *            语言代码
	 * @param newLanguage
	 *            更新后的语言;
	 */
public void updateLanguageByCode(String code, Language newLanguage) {
    String newValue = generateLangNode(newLanguage);
    XMLModifier xm = vu.update("/languages/lang[@code='" + code + "']", newValue);
    try {
        vu.bind(xm.outputAndReparse());
        saveToFile(xm, langConfigFile);
    } catch (Exception e) {
        LOGGER.error(Messages.getString("file.LanguageConfiger.logger1"), e);
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) XPathParseException(com.ximpleware.XPathParseException) NavException(com.ximpleware.NavException) IOException(java.io.IOException) ModifyException(com.ximpleware.ModifyException) ParseException(com.ximpleware.ParseException) TranscodeException(com.ximpleware.TranscodeException) XPathEvalException(com.ximpleware.XPathEvalException)

Example 5 with XMLModifier

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

the class ImportTbx method saveTermEntryWithOverwrite.

private void saveTermEntryWithOverwrite(Map<String, String> dbTermEntry, AutoPilot langSetAp, AutoPilot termAp) throws XPathParseException, XPathEvalException, NavException, SQLException, EncodingException, EOFException, EntityException, ParseException, TranscodeException, ModifyException, IOException {
    VTDGen vg = new VTDGen();
    VTDUtils vtdUtiles = new VTDUtils();
    String content = dbTermEntry.get("CONTENT");
    String termEntryPk = dbTermEntry.get("BTEPKID");
    if (!content.equals(vu.getElementFragment())) {
        String prelang = "";
        vu.getVTDNav().push();
        while (langSetAp.evalXPath() != -1) {
            String curlang = getElementAttribute("xml:lang");
            String langSetValue = vu.getElementFragment();
            vg.setDoc(content.getBytes());
            vg.parse(true);
            vtdUtiles.bind(vg.getNav());
            if (!prelang.endsWith(curlang)) {
                prelang = curlang;
                dbOperator.deleteTerm(termEntryPk, curlang);
                AutoPilot ap = new AutoPilot(vtdUtiles.getVTDNav());
                ap.declareXPathNameSpace("xml", vtdUtiles.XML_NAMESPACE_URL);
                XMLModifier xm = new XMLModifier(vtdUtiles.getVTDNav());
                vtdUtiles.delete(ap, xm, "/termEntry/langSet[@xml:lang='" + curlang + "']");
                vtdUtiles.bind(xm.outputAndReparse());
            }
            XMLModifier xm = vtdUtiles.insert("/termEntry/langSet", langSetValue);
            vtdUtiles.bind(xm.outputAndReparse());
            vu.getVTDNav().push();
            while (termAp.evalXPath() != -1) {
                String pureText = DocUtils.getTmxTbxPureText(vu);
                String fullText = vu.getElementContent();
                // 当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();
        }
        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());
        }
        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());
        }
        if (noteContentBf.length() != 0) {
            XMLModifier xm = vtdUtiles.insert("/termEntry/text()", noteContentBf.toString());
            vtdUtiles.bind(xm.outputAndReparse());
        }
        content = vtdUtiles.getElementFragment();
        dbOperator.updateTermEntry(content, termEntryPk);
        vu.getVTDNav().pop();
    }
}
Also used : XMLModifier(com.ximpleware.XMLModifier) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) ArrayList(java.util.ArrayList) VTDGen(com.ximpleware.VTDGen) HashMap(java.util.HashMap) Map(java.util.Map)

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