Search in sources :

Example 6 with OperationCanceledException

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

the class NewFolderDialogOfHs method createNewFolder.

/**
		 * Creates a new folder with the given name and optionally linking to
		 * the specified link target.
		 * 
		 * @param folderName name of the new folder
		 * @param linkTarget name of the link target folder. may be null.
		 * @return IFolder the new folder
		 */
private IFolder createNewFolder(String folderName, final URI linkTarget) {
    final IFolder folderHandle = createFolderHandle(folderName);
    WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {

        public void execute(IProgressMonitor monitor) throws CoreException {
            try {
                monitor.beginTask(IDEWorkbenchMessages.NewFolderDialog_progress, 2000);
                if (monitor.isCanceled()) {
                    throw new OperationCanceledException();
                }
                if (linkTarget == null) {
                    folderHandle.create(false, true, monitor);
                } else {
                    folderHandle.createLink(linkTarget, IResource.ALLOW_MISSING_LOCAL, monitor);
                }
                if (monitor.isCanceled()) {
                    throw new OperationCanceledException();
                }
            } finally {
                monitor.done();
            }
        }
    };
    try {
        PlatformUI.getWorkbench().getProgressService().busyCursorWhile(operation);
    } catch (InterruptedException exception) {
        return null;
    } catch (InvocationTargetException exception) {
        if (exception.getTargetException() instanceof CoreException) {
            ErrorDialog.openError(getShell(), // no special message
            IDEWorkbenchMessages.NewFolderDialog_errorTitle, // no special message
            null, ((CoreException) exception.getTargetException()).getStatus());
        } else {
            // CoreExceptions are handled above, but unexpected runtime exceptions and errors may still occur.
            IDEWorkbenchPlugin.log(getClass(), "createNewFolder", //$NON-NLS-1$
            exception.getTargetException());
            MessageDialog.openError(getShell(), IDEWorkbenchMessages.NewFolderDialog_errorTitle, NLS.bind(IDEWorkbenchMessages.NewFolderDialog_internalError, exception.getTargetException().getMessage()));
        }
        return null;
    }
    return folderHandle;
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) WorkspaceModifyOperation(org.eclipse.ui.actions.WorkspaceModifyOperation) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IFolder(org.eclipse.core.resources.IFolder)

Example 7 with OperationCanceledException

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

the class ConverterUtils method throwConverterException.

/**
	 * Throw converter exception.
	 * @param plugin
	 *            the plugin
	 * @param message
	 *            the message
	 * @param e
	 *            the e
	 * @throws ConverterException
	 *             the converter exception
	 * @author John Zhu
	 */
public static void throwConverterException(String plugin, String message, Throwable e) throws ConverterException {
    if (e instanceof OperationCanceledException) {
        return;
    }
    IStatus status = new Status(IStatus.ERROR, plugin, IStatus.ERROR, message, e);
    ConverterException ce = new ConverterException(status);
    throw ce;
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) ConverterException(net.heartsome.cat.converter.ConverterException) IStatus(org.eclipse.core.runtime.IStatus) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException)

Example 8 with OperationCanceledException

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

the class SplitXliff method splitTheXliff.

/**
	 * 切割Xliff文件 注意:源文本没有解析,因为xlfhandler是从xlfeditor取过来的,因此不用再解析一次。
	 */
public boolean splitTheXliff(IProgressMonitor monitor) {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }
    monitor.beginTask(Messages.getString("splitAndMergeXliff.SplitXliff.task1"), splitPointsIndex.size());
    String xlfPath = splitFile.getLocation().toOSString();
    if (xlfPath != null) {
        File f = new File(xlfPath);
        // 如果文件不存在,提示并退出操作
        if (!f.exists()) {
            f = null;
            Display.getDefault().asyncExec(new Runnable() {

                public void run() {
                    MessageDialog.openInformation(shell, Messages.getString("splitAndMergeXliff.SplitXliff.msgTitle1"), MessageFormat.format(Messages.getString("splitAndMergeXliff.SplitXliff.msg1"), new Object[] { splitFile.getFullPath().toOSString() }));
                }
            });
            return false;
        } else {
            Map<String, String> newInfo = null;
            File src = new File(xlfPath);
            String fileName = null;
            String splitXliffName = null;
            try {
                splitXliffName = src.getName();
                // 源文件的文件名
                fileName = new String(splitXliffName.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                LOGGER.error("", e1);
                e1.printStackTrace();
            }
            // 判断分割后生成的子文件是否重复,如果重复就进行提示
            String copyFiles = "";
            LinkedList<String> newSplitedFilesName = model.getNewSplitedFilesName();
            for (int i = 0; i < newSplitedFilesName.size(); i++) {
                final String newXlfPath = model.getSplitXlfsContainer().getLocation().append(newSplitedFilesName.get(i)).toOSString();
                File newXlfFile = new File(newXlfPath);
                if (newXlfFile.exists()) {
                    copyFiles += getFullPath(newXlfPath) + "\n";
                    repeateFileList.add(ResourceUtils.fileToIFile(newXlfPath));
                }
            }
            final String copyFilesTip = copyFiles.substring(0, copyFiles.length());
            // 如果新生成的文件已经存在,那么提示是否覆盖
            if (copyFiles.length() > 0) {
                try {
                    Display.getDefault().syncExec(new Runnable() {

                        public void run() {
                            boolean response = MessageDialog.openConfirm(shell, Messages.getString("splitAndMergeXliff.SplitXliff.msgTitle2"), MessageFormat.format(Messages.getString("splitAndMergeXliff.SplitXliff.msg2"), new Object[] { copyFilesTip }));
                            if (!response) {
                                needCover = true;
                            }
                        }
                    });
                } catch (Exception e) {
                    LOGGER.error("", e);
                    e.printStackTrace();
                }
                if (needCover) {
                    return false;
                }
            }
            // 先删除重复的文件,再关闭已经打开的重复文件的编辑器
            Display.getDefault().syncExec(new Runnable() {

                public void run() {
                    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
                    try {
                        IEditorReference[] refrences = window.getActivePage().getEditorReferences();
                        for (IEditorReference refrence : refrences) {
                            if (refrence.getEditor(true).getEditorSite().getId().equals(NATABLE_ID)) {
                                XLIFFEditorImplWithNatTable nattable = (XLIFFEditorImplWithNatTable) refrence.getEditor(true);
                                if (nattable.isMultiFile()) {
                                    for (File file : nattable.getMultiFileList()) {
                                        if (repeateFileList.indexOf(ResourceUtils.fileToIFile(file.getAbsolutePath())) >= 0) {
                                            window.getActivePage().closeEditor(nattable, true);
                                            break;
                                        }
                                    }
                                } else {
                                    if (repeateFileList.indexOf(((FileEditorInput) nattable.getEditorInput()).getFile()) >= 0) {
                                        window.getActivePage().closeEditor(nattable, true);
                                    }
                                }
                            }
                        }
                        for (IFile iFile : repeateFileList) {
                            ResourceUtil.getFile(iFile).delete(true, null);
                        }
                        model.getSplitFile().getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
                    } catch (Exception e) {
                        LOGGER.error("", e);
                    }
                }
            });
            // 得到当前的时间, 开始进行循环切割
            long splitTime = System.currentTimeMillis();
            for (int i = CONSTANT_ONE, pointsSize = (splitPointsIndex.size() + 1); i <= pointsSize; i++) {
                newInfo = getNewSplitInfo(fileName, oldInfo, i, pointsSize, splitTime);
                monitor.subTask(Messages.getString("splitAndMergeXliff.SplitXliff.task2") + newInfo.get("name"));
                // 创建新的XLIFF的文件路径
                final String newXlfPath = model.getSplitXlfsContainer().getLocation().append(getSplitFileName(splitXliffName, oldInfo, i)).toOSString();
                String xliffNodeHeader = xlfhandler.getNodeHeader(xlfPath, "xliff", "/xliff");
                createNewSplitXliff(newXlfPath, xliffNodeHeader);
                // 打开这个新创建的xliff文件,将xliff与file,header等节点写入进去
                Map<String, Object> newResultMap = splitHandler.openFile(newXlfPath);
                if (newResultMap == null || Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) newResultMap.get(Constant.RETURNVALUE_RESULT)) {
                    Display.getDefault().asyncExec(new Runnable() {

                        public void run() {
                            MessageDialog.openError(shell, Messages.getString("splitAndMergeXliff.SplitXliff.msgTitle3"), Messages.getString("splitAndMergeXliff.SplitXliff.msg3"));
                        }
                    });
                    return false;
                }
                if (fileInfo == null) {
                    fileInfo = xlfhandler.getFileInfo(xlfPath);
                }
                // 获取当前分割段的首末rowId
                String startRowId = xlfhandler.getNextRowId(xlfPath, i == CONSTANT_ONE ? "start" : splitPointsRowId.get(i - 2));
                String endRowId = (i == pointsSize) ? xlfhandler.getNextRowId(xlfPath, "end") : splitPointsRowId.get(// 因为这里的I是从1开始的,故要减1
                i - CONSTANT_ONE);
                // 获取分割段的file,与body第一子节点的序列
                Map<String, Integer> startNodeIdxMap = xlfhandler.getSplitNodeIdx(xlfPath, i == CONSTANT_ONE ? "start" : splitPointsRowId.get(i - 2));
                Map<String, Integer> endNodeIdxMap = (i == pointsSize) ? xlfhandler.getSplitNodeIdx(xlfPath, "end") : xlfhandler.getSplitNodeIdx(xlfPath, splitPointsRowId.get(i - CONSTANT_ONE));
                // 获取当前起始rowId所在的file节点的序列号
                int startFileNodeIdx = startNodeIdxMap.get("fileNodeIdx");
                int endFileNodeIdx = endNodeIdxMap.get("fileNodeIdx");
                int startBodyChildIdx = startNodeIdxMap.get("bodyChildNodeIdx");
                // 开始循环每一个file节点,进行获取相关数据
                // 这是新生成的xliff文件中的file的序列号
                int n = 1;
                for (int fileIdx = startFileNodeIdx; fileIdx <= endFileNodeIdx; fileIdx++) {
                    // 开始将数据存入新切割的xliff文件中,先存放file节点的头
                    String fileNodeHeader = xlfhandler.getNodeHeader(xlfPath, "file", "/xliff/file[" + fileIdx + "]");
                    splitHandler.addDataToXlf(newXlfPath, fileNodeHeader, "/xliff");
                    String headerFrag = xlfhandler.getNodeFrag(xlfPath, "/xliff/file[" + fileIdx + "]/header");
                    splitHandler.addDataToXlf(newXlfPath, headerFrag, "/xliff/file[" + n + "]");
                    // 向新生成xliff文件添加body元素
                    String bodyNodeHeader = xlfhandler.getNodeHeader(xlfPath, "body", "/xliff/file[" + fileIdx + "]/body");
                    splitHandler.addDataToXlf(newXlfPath, bodyNodeHeader, "/xliff/file[" + n + "]");
                    boolean isLastOfFile = false;
                    if (i == pointsSize && fileIdx == endFileNodeIdx) {
                        isLastOfFile = true;
                    }
                    // UNDO 分割这里还要好发测试一下,针对不同情况。
                    String tuData = xlfhandler.getSplitTuData(xlfPath, fileIdx, n == 1 ? startBodyChildIdx : 1, n == 1 ? startRowId : null, endRowId, n == 1, isLastOfFile);
                    splitHandler.addDataToXlf(newXlfPath, tuData, "/xliff/file[" + n + "]/body");
                    n++;
                }
                if (monitor.isCanceled()) {
                    throw new OperationCanceledException(Messages.getString("splitAndMergeXliff.SplitXliff.msg3"));
                }
                monitor.worked(1);
                // 添加新的切割信息
                splitHandler.addNewInfoToSplitXlf(newXlfPath, newInfo);
            }
            monitor.done();
        }
    }
    return true;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) XLIFFEditorImplWithNatTable(net.heartsome.cat.ts.ui.xliffeditor.nattable.editor.XLIFFEditorImplWithNatTable) IFile(org.eclipse.core.resources.IFile) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IEditorReference(org.eclipse.ui.IEditorReference) IFile(org.eclipse.core.resources.IFile) File(java.io.File)

Example 9 with OperationCanceledException

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

the class LockTMSegment method executeTranslation.

/**
	 * 根据构建参数执行预翻译 ;
	 * @return false:标识用户点击退出按钮,不再执行
	 */
public boolean executeTranslation(IProgressMonitor monitor) {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }
    if (monitor != null && monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    //首先获取所有文件的tu节点的总数
    int allTuSize = 0;
    for (String xlfPath : xlfFiles) {
        int curTuSize = xlfHandler.getNodeCount(xlfPath, XPATH_ALL_TU);
        //初始化结果集
        tuNumResult.put(xlfPath, curTuSize);
        if (lockedFullMatchResult.get(xlfPath) == null) {
            lockedFullMatchResult.put(xlfPath, 0);
        }
        if (lockedContextResult.get(xlfPath) == null) {
            lockedContextResult.put(xlfPath, 0);
        }
        if (needLockRowIdMap.get(xlfPath) == null) {
            needLockRowIdMap.put(xlfPath, new ArrayList<String>());
        }
        allTuSize += curTuSize;
    }
    monitor.beginTask(Messages.getString("translation.LockTMSegment.task1"), allTuSize);
    boolean canTmMatch = tmMatcher.checkTmMatcher(curProject);
    if (!canTmMatch) {
        monitorWork(monitor, allTuSize);
        return true;
    }
    Map<String, String> srcTextMap = null;
    for (String xlfPath : xlfFiles) {
        int fileNodeSum = xlfHandler.getNodeCount(xlfPath, XP_FILE);
        for (int fileNodeIdx = CONSTANT_ONE; fileNodeIdx <= fileNodeSum; fileNodeIdx++) {
            String source_lan = xlfHandler.getNodeAttribute(xlfPath, "/xliff/file[" + fileNodeIdx + "]", SRCLANG);
            String target_lan = xlfHandler.getNodeAttribute(xlfPath, "/xliff/file[" + fileNodeIdx + "]", TAGLANG);
            if (source_lan == null || source_lan.equals("")) {
                continue;
            }
            if (target_lan == null || target_lan.equals("")) {
                continue;
            }
            //获取每一个tu节点的相关信息
            int curFileNodeTuSize = xlfHandler.getNodeCount(xlfPath, "/xliff/file[" + fileNodeIdx + "]/body/descendant::trans-unit[source/text()!='' or source/*]");
            for (int tuNodeIdx = CONSTANT_ONE; tuNodeIdx <= curFileNodeTuSize; tuNodeIdx++) {
                String tuXpath = "/xliff/file[" + fileNodeIdx + "]/descendant::trans-unit[" + tuNodeIdx + "]";
                srcTextMap = xlfHandler.getTUsrcText(xlfPath, tuXpath, contextSize);
                if (srcTextMap == null || srcTextMap.size() < 0) {
                    return true;
                }
                searchTmAndLockTu(xlfPath, source_lan, target_lan, srcTextMap);
                if (!monitorWork(monitor, allTuSize)) {
                    return false;
                }
            }
        }
    }
    return true;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException)

Example 10 with OperationCanceledException

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

the class ImportProjectWizardPage method createProjects.

/**
	 * Create the selected projects
	 * 
	 * @return boolean <code>true</code> if all project creations were
	 * 	successful.
	 */
public boolean createProjects() {
    saveWidgetValues();
    final Object[] selected = projectsList.getCheckedElements();
    createdProjects = new ArrayList();
    WorkspaceModifyOperation op = new WorkspaceModifyOperation() {

        protected void execute(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                //$NON-NLS-1$
                monitor.beginTask("", selected.length);
                if (monitor.isCanceled()) {
                    throw new OperationCanceledException();
                }
                for (int i = 0; i < selected.length; i++) {
                    createExistingProject((ProjectRecord) selected[i], new SubProgressMonitor(monitor, 1));
                }
            } finally {
                monitor.done();
            }
        }
    };
    // run the new project creation operation
    try {
        getContainer().run(true, true, op);
    } catch (InterruptedException e) {
        return false;
    } catch (InvocationTargetException e) {
        // one of the steps resulted in a core exception
        Throwable t = e.getTargetException();
        String message = DataTransferMessages.WizardExternalProjectImportPage_errorMessage;
        IStatus status;
        if (t instanceof CoreException) {
            status = ((CoreException) t).getStatus();
        } else {
            status = new Status(IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH, 1, message, t);
        }
        ErrorDialog.openError(getShell(), message, null, status);
        return false;
    }
    ArchiveFileManipulations.closeStructureProvider(structureProvider, getShell());
    return true;
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IStatus(org.eclipse.core.runtime.IStatus) WorkspaceModifyOperation(org.eclipse.ui.actions.WorkspaceModifyOperation) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException)

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