Search in sources :

Example 1 with NavException

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

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

the class LanguageConfiger method getAllLanguage.

/**
	 * 返回所有语言列表,key:code,value:<code>Language</code>
	 */
public Map<String, Language> getAllLanguage() {
    Map<String, Language> result = new HashMap<String, Language>();
    AutoPilot tempAp = new AutoPilot(vu.getVTDNav());
    String codeAttr = "code";
    String bidiAttr = "bidi";
    String imgAttr = "image";
    String bidiYes = "Yes";
    try {
        tempAp.selectXPath("/languages/lang");
        while (tempAp.evalXPath() != -1) {
            Map<String, String> attrs = vu.getCurrentElementAttributs();
            String code = attrs.get(codeAttr);
            String bidi = attrs.get(bidiAttr);
            String img = attrs.get(imgAttr);
            String langName = vu.getElementPureText();
            boolean isBidi = false;
            if (code != null && langName != null) {
                if (bidi != null && bidi.equals(bidiYes)) {
                    isBidi = true;
                }
                result.put(code, new Language(code, langName, img == null ? "" : img, isBidi));
            }
        }
    } catch (XPathParseException e) {
        LOGGER.error("", e);
    } catch (XPathEvalException e) {
        LOGGER.error("", e);
    } catch (NavException e) {
        LOGGER.error("", e);
    }
    return result;
}
Also used : XPathParseException(com.ximpleware.XPathParseException) Language(net.heartsome.cat.common.locale.Language) HashMap(java.util.HashMap) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException)

Example 3 with NavException

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

the class LanguageConfiger method getLanguageByCode.

/**
	 * 返回Code对应的Language对象,如果在配置中找到则返回null
	 * @param code
	 * @return ;
	 */
public Language getLanguageByCode(String code) {
    AutoPilot tempAp = new AutoPilot(vu.getVTDNav());
    String bidiAttr = "bidi";
    String imgAttr = "image";
    String bidiYes = "Yes";
    try {
        tempAp.selectXPath("/languages/lang[@code='" + code + "']");
        if (tempAp.evalXPath() != -1) {
            Map<String, String> attrs = vu.getCurrentElementAttributs();
            String bidi = attrs.get(bidiAttr);
            String img = attrs.get(imgAttr);
            String langName = vu.getElementPureText();
            boolean isBidi = false;
            if (code != null && langName != null) {
                if (bidi != null && bidi.equals(bidiYes)) {
                    isBidi = true;
                }
                return new Language(code, langName, img == null ? "" : img, isBidi);
            }
        }
    } catch (XPathParseException e) {
        LOGGER.error("", e);
    } catch (XPathEvalException e) {
        LOGGER.error("", e);
    } catch (NavException e) {
        LOGGER.error("", e);
    }
    return null;
}
Also used : XPathParseException(com.ximpleware.XPathParseException) Language(net.heartsome.cat.common.locale.Language) AutoPilot(com.ximpleware.AutoPilot) XPathEvalException(com.ximpleware.XPathEvalException) NavException(com.ximpleware.NavException)

Example 4 with NavException

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

the class VTDUtils method getElementFragment.

/**
	 * 获得整个节点的段落
	 * @return 整个节点的段落,例如:&lt;ph id="1"&gt;a&lt;/ph&gt;
	 * @throws NavException
	 *             ;
	 */
public String getElementFragment() throws NavException {
    long l = vn.getElementFragment();
    int offset = (int) l;
    int len = (int) (l >> 32);
    /* 区别编码。在解析 UTF-16 等部分编码的时候索引会变为2倍。 */
    if (vn.getEncoding() > VTDGen.FORMAT_WIN_1258) {
        offset = offset >> 1;
        len = len >> 1;
    }
    // 处理这种情况下获取内容错误的情况 <ph>...</ph> 1><ph>...</ph> robert 2012-09-13
    String fragment = "";
    try {
        fragment = vn.toRawString(offset, len);
    } catch (NavException e) {
        if (e.getMessage().contains("encoding error")) {
            byte[] doc = vn.getXML().getBytes();
            if (vn.getEncoding() == VTDNav.FORMAT_UTF_16LE || vn.getEncoding() == VTDNav.FORMAT_UTF_16BE) {
                offset = offset << 1;
            }
            String line = formatLineNumber(doc, offset, vn);
            throw new NavException("encoding error:" + line);
        }
        throw e;
    }
    int length = fragment.length();
    int realEndIdx = fragment.indexOf(">", fragment.lastIndexOf("<"));
    if (realEndIdx != length - 1) {
        fragment = fragment.substring(0, fragment.indexOf(">", fragment.lastIndexOf("<")) + 1);
    }
    return fragment;
}
Also used : NavException(com.ximpleware.NavException)

Example 5 with NavException

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

the class DocUtils method isTBX.

/**
	 * 判断是否是正确的 TBX 文件
	 * @param fileName
	 *            TBX 文件的全路径
	 * @return 反回null,验证失败
	 * @throws ParseException
	 * @throws EntityException
	 * @throws EOFException
	 * @throws EncodingException
	 * @throws FileNotFoundException
	 */
public static VTDUtils isTBX(String fileName) throws EncodingException, ParseException, FileNotFoundException {
    VTDGen vg = new VTDGen();
    FileInputStream fis = null;
    File f = null;
    try {
        f = new File(fileName);
        fis = new FileInputStream(f);
        byte[] b = new byte[(int) f.length()];
        int offset = 0;
        int numRead = 0;
        // I choose this value randomally,
        int numOfBytes = 1048576;
        // any other (not too big) value also can be here.
        if (b.length - offset < numOfBytes) {
            numOfBytes = b.length - offset;
        }
        while (offset < b.length && (numRead = fis.read(b, offset, numOfBytes)) >= 0) {
            offset += numRead;
            if (b.length - offset < numOfBytes) {
                numOfBytes = b.length - offset;
            }
        }
        vg.setDoc(b);
        vg.parse(true);
    } catch (IOException e) {
        LOGGER.error(Messages.getString("document.DocUtils.logger1"), e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
    }
    VTDNav vn = vg.getNav();
    AutoPilot ap = new AutoPilot(vn);
    String rootPath = "/martif";
    VTDUtils vtdUtils = new VTDUtils();
    try {
        vtdUtils.bind(vn);
        ap.selectXPath(rootPath);
        if (ap.evalXPath() == -1) {
            // } else {
            return null;
        }
    } catch (NavException e) {
        LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
        return null;
    } catch (XPathEvalException e) {
        LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
        return null;
    } catch (XPathParseException e) {
        LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
        return null;
    } finally {
        vg.clear();
    }
    return vtdUtils;
}
Also used : NavException(com.ximpleware.NavException) XPathEvalException(com.ximpleware.XPathEvalException) VTDGen(com.ximpleware.VTDGen) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) EOFException(com.ximpleware.EOFException) XPathParseException(com.ximpleware.XPathParseException) NavException(com.ximpleware.NavException) IOException(java.io.IOException) EncodingException(com.ximpleware.EncodingException) FileNotFoundException(java.io.FileNotFoundException) ParseException(com.ximpleware.ParseException) XPathEvalException(com.ximpleware.XPathEvalException) EntityException(com.ximpleware.EntityException) XPathParseException(com.ximpleware.XPathParseException) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) AutoPilot(com.ximpleware.AutoPilot) File(java.io.File) VTDNav(com.ximpleware.VTDNav)

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