Search in sources :

Example 46 with OperationCanceledException

use of org.eclipse.core.runtime.OperationCanceledException in project tdi-studio-se by Talend.

the class ComponentProjectManager method initializeClasspath.

/**
     * DOC ycbai Initialize classpath of project.
     * 
     * @param project
     * @param monitor
     * @throws OperationCanceledException
     * @throws CoreException
     */
private void initializeClasspath(IJavaProject project, IProgressMonitor monitor) throws OperationCanceledException, CoreException {
    if (monitor != null && monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    if (project == null)
        return;
    IClasspathEntry[] entries = null;
    List<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
    cpEntries.addAll(Arrays.asList(getDefaultJREClasspathEntries()));
    cpEntries.addAll(getDefaultUtilClasspathEntries());
    entries = (IClasspathEntry[]) cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
    if (monitor != null)
        monitor.worked(1);
    IPath output = getOutputLocation();
    IProgressMonitor subProgressMonitor = monitor == null ? new NullProgressMonitor() : new SubProgressMonitor(monitor, 2);
    project.setRawClasspath(entries, output, subProgressMonitor);
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IPath(org.eclipse.core.runtime.IPath) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor)

Example 47 with OperationCanceledException

use of org.eclipse.core.runtime.OperationCanceledException in project translationstudio8 by heartsome.

the class ImportAbstract method doImport.

/**
	 * 导入文件内容
	 * @param fileContent
	 * @param srcLang
	 * @param monitor
	 * @return ;
	 * @throws ImportException
	 */
public int doImport(String fileContent, String srcLang, IProgressMonitor monitor) throws ImportException {
    if (monitor == null) {
        this.monitor = new NullProgressMonitor();
    } else {
        this.monitor = monitor;
    }
    // 解析文件
    String message = "";
    VTDGen vg = new VTDGen();
    vg.setDoc(fileContent.getBytes());
    try {
        vg.parse(true);
    } catch (EncodingException e) {
        logger.error(Messages.getString("document.ImportAbstract.logger1"), e);
        message = Messages.getString("document.ImportAbstract.msg1");
        throw new ImportException(message + e.getMessage());
    } catch (EOFException e) {
        logger.error("", e);
        message = Messages.getString("document.ImportAbstract.tbx.msg1");
        throw new ImportException(message + e.getMessage());
    } catch (EntityException e) {
        logger.error("", e);
        message = Messages.getString("document.ImportAbstract.tbx.msg1");
        throw new ImportException(message + e.getMessage());
    } catch (ParseException e) {
        logger.error(Messages.getString("document.ImportAbstract.logger3"), e);
        String errMsg = e.getMessage();
        if (errMsg.indexOf("invalid encoding") != -1) {
            // 编码异常
            message = Messages.getString("document.ImportAbstract.msg1");
        } else {
            message = Messages.getString("document.ImportAbstract.tbx.msg1");
        }
        throw new ImportException(message + e.getMessage());
    }
    try {
        // 构建VTD解析工具
        vu = new VTDUtils(vg.getNav());
        dbOperator.beginTransaction();
        // 执行导入
        executeImport(srcLang);
        dbOperator.commit();
    } catch (VTDException e) {
        logger.error("", e);
        try {
            dbOperator.rollBack();
        } catch (SQLException e1) {
            logger.error("", e);
        }
        return FAILURE_4;
    } catch (SQLException e) {
        logger.error("", e);
        try {
            dbOperator.rollBack();
        } catch (SQLException e1) {
            logger.error("", e1);
        }
        throw new ImportException(Messages.getString("document.ImportAbstract.tbx.importDbError") + e.getMessage());
    } catch (OperationCanceledException e) {
        logger.error("", e);
        try {
            dbOperator.rollBack();
        } catch (SQLException e1) {
            logger.error("", e1);
            return CANCEL;
        }
    } catch (Exception e) {
        logger.error("", e);
        try {
            dbOperator.rollBack();
        } catch (SQLException e1) {
            logger.error("", e1);
        }
        throw new ImportException(Messages.getString("document.ImportAbstract.tbx.importDbError") + e.getMessage());
    }
    return SUCCESS;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) EncodingException(com.ximpleware.EncodingException) SQLException(java.sql.SQLException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) EntityException(com.ximpleware.EntityException) VTDGen(com.ximpleware.VTDGen) NavException(com.ximpleware.NavException) EncodingException(com.ximpleware.EncodingException) SQLException(java.sql.SQLException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ImportException(net.heartsome.cat.common.core.exception.ImportException) TranscodeException(com.ximpleware.TranscodeException) XPathEvalException(com.ximpleware.XPathEvalException) EOFException(com.ximpleware.EOFException) XPathParseException(com.ximpleware.XPathParseException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ModifyException(com.ximpleware.ModifyException) ParseException(com.ximpleware.ParseException) VTDException(com.ximpleware.VTDException) EntityException(com.ximpleware.EntityException) ImportException(net.heartsome.cat.common.core.exception.ImportException) VTDUtils(net.heartsome.xml.vtdimpl.VTDUtils) VTDException(com.ximpleware.VTDException) EOFException(com.ximpleware.EOFException) XPathParseException(com.ximpleware.XPathParseException) ParseException(com.ximpleware.ParseException)

Example 48 with OperationCanceledException

use of org.eclipse.core.runtime.OperationCanceledException 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 49 with OperationCanceledException

use of org.eclipse.core.runtime.OperationCanceledException in project translationstudio8 by heartsome.

the class ConverterViewModel method reverseConvert.

/**
	 * 逆向转换
	 * @param sourceItem
	 * @param monitor
	 * @return ;
	 */
private Map<String, String> reverseConvert(IConversionItem sourceItem, IProgressMonitor monitor) throws ConverterException {
    Map<String, String> result = null;
    String sourcePathStr = configBean.getSource();
    String targetFile = ConverterUtil.toLocalPath(configBean.getTarget());
    boolean convertSuccessful = false;
    File target = null;
    try {
        target = new File(targetFile);
        if (!target.exists()) {
            try {
                File parent = target.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                target.createNewFile();
            } catch (IOException e) {
                if (LOGGER.isErrorEnabled()) {
                    String msg = Messages.getString("model.ConverterViewModel.logger4");
                    Object[] args = { targetFile };
                    LOGGER.error(new MessageFormat(msg).format(args), e);
                }
            }
        }
        Converter converter = getConverter();
        if (converter == null) {
            // Build a message
            String message = Messages.getString("model.ConverterViewModel.msg3") + configBean.getFileType();
            // Build a new IStatus
            IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message);
            throw new ConverterNotFoundException(status);
        }
        ConverterContext converterContext = new ConverterContext(configBean);
        final Map<String, String> configuration = converterContext.getReverseConvertConfiguraion();
        if (configBean.getFileType().equals("x-msoffice2003")) {
            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);
        }
        result = converter.convert(configuration, monitor);
        convertSuccessful = true;
    } catch (OperationCanceledException e) {
        // 捕获用户取消操作的异常
        LOGGER.info(Messages.getString("model.ConverterViewModel.logger2"), e);
        throw e;
    } catch (ConverterNotFoundException e) {
        // Let the StatusManager handle the Status and provide a hint
        StatusManager.getManager().handle(e.getStatus(), StatusManager.LOG | StatusManager.SHOW);
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(e.getMessage(), e);
        }
        throw e;
    } catch (ConverterException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(MessageFormat.format(Messages.getString("model.ConverterViewModel.logger3"), sourcePathStr), e);
        }
        throw e;
    } finally {
        if (!convertSuccessful) {
            // 在转换失败或用户取消转换时,清除目标文件和骨架文件
            if (target != null && target.exists()) {
                target.delete();
            }
        }
        sourceItem.refresh();
    }
    return result;
}
Also used : ValidationStatus(org.eclipse.core.databinding.validation.ValidationStatus) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) ConverterException(net.heartsome.cat.converter.ConverterException) IStatus(org.eclipse.core.runtime.IStatus) MessageFormat(java.text.MessageFormat) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IOException(java.io.IOException) Converter(net.heartsome.cat.converter.Converter) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) File(java.io.File)

Example 50 with OperationCanceledException

use of org.eclipse.core.runtime.OperationCanceledException in project applause by applause.

the class ApplauseEclipseResourceFileSystemAccess2 method generateFile.

public void generateFile(String fileName, String outputName, CharSequence contents) {
    if (monitor.isCanceled())
        throw new OperationCanceledException();
    OutputConfiguration outputConfig = getOutputConfig(outputName);
    if (!ensureOutputConfigurationDirectoryExists(outputConfig))
        return;
    IFile file = getFile(fileName, outputName);
    IFile traceFile = getTraceFile(file);
    try {
        String encoding = getEncoding(file);
        CharSequence postProcessedContent = postProcess(fileName, outputName, contents, encoding);
        String contentsAsString = postProcessedContent.toString();
        if (file.exists()) {
            if (outputConfig.isOverrideExistingResources()) {
                StringInputStream newContent = getInputStream(contentsAsString, encoding);
                if (hasContentsChanged(file, newContent)) {
                    // reset to offset zero allows to reuse internal byte[]
                    // no need to convert the string twice
                    newContent.reset();
                    file.setContents(newContent, true, true, monitor);
                } else {
                    file.touch(getMonitor());
                }
                if (file.isDerived() != outputConfig.isSetDerivedProperty()) {
                    setDerived(file, outputConfig.isSetDerivedProperty());
                }
                if (traceFile != null)
                    updateTraceInformation(traceFile, postProcessedContent, outputConfig.isSetDerivedProperty());
                if (callBack != null)
                    callBack.afterFileUpdate(file);
            }
        } else {
            ensureParentExists(file);
            file.create(getInputStream(contentsAsString, encoding), true, monitor);
            if (outputConfig.isSetDerivedProperty()) {
                setDerived(file, true);
            }
            if (traceFile != null)
                updateTraceInformation(traceFile, postProcessedContent, outputConfig.isSetDerivedProperty());
            if (callBack != null)
                callBack.afterFileCreation(file);
        }
    } catch (CoreException e) {
        throw new RuntimeIOException(e);
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
}
Also used : RuntimeIOException(org.eclipse.xtext.util.RuntimeIOException) StringInputStream(org.eclipse.xtext.util.StringInputStream) IFile(org.eclipse.core.resources.IFile) CoreException(org.eclipse.core.runtime.CoreException) OutputConfiguration(org.eclipse.xtext.generator.OutputConfiguration) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) RuntimeIOException(org.eclipse.xtext.util.RuntimeIOException) IOException(java.io.IOException)

Aggregations

OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)134 CoreException (org.eclipse.core.runtime.CoreException)38 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)37 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)34 ArrayList (java.util.ArrayList)25 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)24 IOException (java.io.IOException)21 IFile (org.eclipse.core.resources.IFile)21 IStatus (org.eclipse.core.runtime.IStatus)21 InvocationTargetException (java.lang.reflect.InvocationTargetException)20 Status (org.eclipse.core.runtime.Status)16 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)16 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)16 File (java.io.File)15 SubMonitor (org.eclipse.core.runtime.SubMonitor)10 Job (org.eclipse.core.runtime.jobs.Job)9 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)9 IProject (org.eclipse.core.resources.IProject)8 HashSet (java.util.HashSet)7 IRunnableWithProgress (org.eclipse.jface.operation.IRunnableWithProgress)7