Java Code Examples for org.eclipse.core.runtime.IProgressMonitor#isCanceled()
The following examples show how to use
org.eclipse.core.runtime.IProgressMonitor#isCanceled() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PyEditNotifier.java From Pydev with Eclipse Public License 1.0 | 6 votes |
/** * Notifies the available listeners that the input has changed for the editor. * * @param oldInput the old input of the editor * @param input the new input of the editor */ public void notifyInputChanged(final IEditorInput oldInput, final IEditorInput input) { final BaseEditor edit = pyEdit.get(); if (edit == null) { return; } INotifierRunnable runnable = new INotifierRunnable() { @Override public void run(IProgressMonitor monitor) { for (IPyEditListener listener : edit.getAllListeners()) { if (listener instanceof IPyEditListener3) { IPyEditListener3 pyEditListener3 = (IPyEditListener3) listener; try { if (!monitor.isCanceled()) { pyEditListener3.onInputChanged(edit, oldInput, input, monitor); } } catch (Exception e) { //must not fail Log.log(e); } } } } }; runIt(runnable); }
Example 2
Source File: TreeDataLoader.java From elexis-3-core with Eclipse Public License 1.0 | 6 votes |
public IStatus work(IProgressMonitor monitor, HashMap<String, Object> params){ monitor.beginTask(Messages.PersistentObjectLoader_LoadingData, IProgressMonitor.UNKNOWN); //$NON-NLS-1$ synchronized (qbe) { root.clear(); setQuery("NIL"); for (PersistentObject po : qbe.execute()) { new Tree<PersistentObject>(root, po); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } monitor.worked(1); } monitor.done(); UiDesk.asyncExec(new Runnable() { public void run(){ ((TreeViewer) cv.getViewerWidget()).setChildCount(cv.getViewerWidget() .getInput(), root.getChildren().size()); } }); } return Status.OK_STATUS; }
Example 3
Source File: FilteredItemsSelectionDialog.java From tlaplus with MIT License | 6 votes |
protected IStatus run(IProgressMonitor monitor) { if (monitor.isCanceled()) { return new Status(IStatus.CANCEL, WorkbenchPlugin.PI_WORKBENCH, IStatus.CANCEL, EMPTY_STRING, null); } if (FilteredItemsSelectionDialog.this != null) { GranualProgressMonitor wrappedMonitor = new GranualProgressMonitor( monitor); FilteredItemsSelectionDialog.this.reloadCache(true, wrappedMonitor); } if (!monitor.isCanceled()) { refreshJob.schedule(); } return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, IStatus.OK, EMPTY_STRING, null); }
Example 4
Source File: InstallWizardOpener.java From statecharts with Eclipse Public License 1.0 | 6 votes |
public void open(Map<String, Set<String>> features, IProgressMonitor monitor) { try { IProvisioningAgent agent = agentProvider.get(); IMetadataRepositoryManager manager = (IMetadataRepositoryManager) agent .getService(IMetadataRepositoryManager.SERVICE_NAME); Set<IInstallableUnit> units = collectIUs(features, manager, monitor); if (monitor.isCanceled()) return; List<URI> knownRepos = Arrays.asList(manager.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL)); InstallOperation op = new OperationFactory().createInstallOperation(units, knownRepos, monitor); agent.stop(); open(units, op); } catch (ProvisionException e) { e.printStackTrace(); } }
Example 5
Source File: TestAnalysis.java From tracecompass with Eclipse Public License 2.0 | 6 votes |
@Override protected boolean executeAnalysis(final IProgressMonitor monitor) { Object parameter = getParameter(PARAM_TEST); if (!(parameter instanceof Integer)) { throw new RuntimeException("The parameter should be set"); } int integer = ((Integer) parameter).intValue(); /* If PARAM_TEST is set to 0, simulate cancellation */ fOutput = integer; if (integer == 0) { return false; } else if (integer == 999) { /* just stay in an infinite loop until cancellation */ while (!monitor.isCanceled()) { try { Thread.sleep(0); } catch (InterruptedException e) { break; } } return !monitor.isCanceled(); } return true; }
Example 6
Source File: ExtractMethodRefactoring.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask(RefactoringCoreMessages.ExtractMethodRefactoring_checking_new_name, 2); pm.subTask(EMPTY); RefactoringStatus result = checkMethodName(); result.merge(checkParameterNames()); result.merge(checkVarargOrder()); pm.worked(1); if (pm.isCanceled()) { throw new OperationCanceledException(); } BodyDeclaration node = fAnalyzer.getEnclosingBodyDeclaration(); if (node != null) { fAnalyzer.checkInput(result, fMethodName, fDestination); pm.worked(1); } pm.done(); return result; }
Example 7
Source File: PyEditNotifier.java From Pydev with Eclipse Public License 1.0 | 6 votes |
/** * @param document the document just set */ public void notifyOnSetDocument(final IDocument document) { final BaseEditor edit = pyEdit.get(); if (edit == null) { return; } INotifierRunnable runnable = new INotifierRunnable() { @Override public void run(IProgressMonitor monitor) { for (IPyEditListener listener : edit.getAllListeners()) { try { if (!monitor.isCanceled()) { listener.onSetDocument(document, edit, monitor); } } catch (Exception e) { //must not fail Log.log(e); } } } }; runIt(runnable); }
Example 8
Source File: CompilationUnitEditor.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 5 votes |
public void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=58245 JavaPlugin javaPlugin= JavaPlugin.getDefault(); if (javaPlugin == null) return; // Always notify AST provider javaPlugin.getASTProvider().reconciled(ast, getInputJavaElement(), progressMonitor); // Notify listeners Object[] listeners = fReconcilingListeners.getListeners(); for (int i = 0, length= listeners.length; i < length; ++i) ((IJavaReconcilingListener)listeners[i]).reconciled(ast, forced, progressMonitor); // Update Java Outline page selection if (!forced && !progressMonitor.isCanceled()) { Shell shell= getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().asyncExec(new Runnable() { public void run() { selectionChanged(); } }); } } }
Example 9
Source File: UpdateCheck.java From cppcheclipse with Apache License 2.0 | 5 votes |
@Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask(getName(), 1); if (monitor.isCanceled()) return Status.CANCEL_STATUS; UpdateCheckCommand updateCheck = new UpdateCheckCommand(); Version newVersion; try { newVersion = updateCheck.run(monitor, Console.getInstance(), binaryPath); DateFormat format = new SimpleDateFormat(DATE_PATTERN); IPersistentPreferenceStore configuration = CppcheclipsePlugin .getConfigurationPreferenceStore(); configuration.setValue( IPreferenceConstants.P_LAST_UPDATE_CHECK, format .format(new Date())); configuration.save(); Display display = Display.getDefault(); display.syncExec(new UpdateCheckNotifier(newVersion)); } catch (Exception e) { if (!isSilent) { CppcheclipsePlugin .showError("Error checking for update", e); //$NON-NLS-1$ } else { CppcheclipsePlugin.logError("Error checking for update", e); } } return Status.OK_STATUS; }
Example 10
Source File: AbstractSegmentStatisticsAnalysis.java From tracecompass with Eclipse Public License 2.0 | 5 votes |
private @Nullable IStatistics<ISegment> getTotalStats(long start, long end, IProgressMonitor monitor) { Iterable<@NonNull ISegment> store = getSegmentStore(start, end); if (store == null) { return null; } if (monitor.isCanceled()) { return null; } return calculateTotalManual(store, monitor); }
Example 11
Source File: MarkerUpdaterImpl.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public void updateMarkers(Delta delta, /* @Nullable */ ResourceSet resourceSet, IProgressMonitor monitor) throws OperationCanceledException { if (monitor.isCanceled()) { throw new OperationCanceledException(); } processDelta(delta, resourceSet, monitor); }
Example 12
Source File: ImportFromDBManagerBase.java From erflute with Apache License 2.0 | 5 votes |
protected void cashColumnDataX(String schemaPattern, String tableName, List<DBObject> dbObjectList, IProgressMonitor monitor) throws SQLException, InterruptedException { try (ResultSet columnSet = metaData.getColumns(null, schemaPattern, tableName, null)) { while (columnSet.next()) { tableName = columnSet.getString("TABLE_NAME"); final String schema = columnSet.getString("TABLE_SCHEM"); final String tableNameWithSchema = dbSetting.getTableNameWithSchema(tableName, schema); monitor.subTask("reading : " + tableNameWithSchema); Map<String, ColumnData> cash = columnDataCash.get(tableNameWithSchema); if (cash == null) { cash = new LinkedHashMap<>(); columnDataCash.put(tableNameWithSchema, cash); } final ColumnData columnData = createColumnData(columnSet); cashOtherColumnData(tableName, schema, columnData); cash.put(columnData.columnName, columnData); if (monitor.isCanceled()) { throw new InterruptedException("Cancel has been requested."); } } } }
Example 13
Source File: SelfEncapsulateFieldRefactoring.java From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 | 4 votes |
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask(NO_NAME, 12); pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions); RefactoringStatus result= new RefactoringStatus(); fRewriter= ASTRewrite.create(fRoot.getAST()); fChangeManager.clear(); boolean usingLocalGetter=isUsingLocalGetter(); boolean usingLocalSetter=isUsingLocalSetter(); result.merge(checkMethodNames(usingLocalGetter,usingLocalSetter)); pm.worked(1); if (result.hasFatalError()) return result; pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits); final SubProgressMonitor subPm= new SubProgressMonitor(pm, 5); ICompilationUnit[] affectedCUs= RefactoringSearchEngine.findAffectedCompilationUnits( SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(fField, fConsiderVisibility), subPm, result, true); checkInHierarchy(result, usingLocalGetter, usingLocalSetter); if (result.hasFatalError()) return result; pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing); IProgressMonitor sub= new SubProgressMonitor(pm, 5); sub.beginTask(NO_NAME, affectedCUs.length); IVariableBinding fieldIdentifier= fFieldDeclaration.resolveBinding(); ITypeBinding declaringClass= ((AbstractTypeDeclaration)ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class)).resolveBinding(); List<TextEditGroup> ownerDescriptions= new ArrayList<TextEditGroup>(); ICompilationUnit owner= fField.getCompilationUnit(); fImportRewrite= StubUtility.createImportRewrite(fRoot, true); for (int i= 0; i < affectedCUs.length; i++) { ICompilationUnit unit= affectedCUs[i]; sub.subTask(BasicElementLabels.getFileName(unit)); CompilationUnit root= null; ASTRewrite rewriter= null; ImportRewrite importRewrite; List<TextEditGroup> descriptions; if (owner.equals(unit)) { root= fRoot; rewriter= fRewriter; importRewrite= fImportRewrite; descriptions= ownerDescriptions; } else { root= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(unit, true); rewriter= ASTRewrite.create(root.getAST()); descriptions= new ArrayList<TextEditGroup>(); importRewrite= StubUtility.createImportRewrite(root, true); } checkCompileErrors(result, root, unit); AccessAnalyzer analyzer= new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite); root.accept(analyzer); result.merge(analyzer.getStatus()); if (!fSetterMustReturnValue) fSetterMustReturnValue= analyzer.getSetterMustReturnValue(); if (result.hasFatalError()) { fChangeManager.clear(); return result; } descriptions.addAll(analyzer.getGroupDescriptions()); if (!owner.equals(unit)) createEdits(unit, rewriter, descriptions, importRewrite); sub.worked(1); if (pm.isCanceled()) throw new OperationCanceledException(); } ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(),usingLocalSetter, usingLocalGetter)); createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite); sub.done(); IFile[] filesToBeModified= ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()); result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext())); if (result.hasFatalError()) return result; ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)); return result; }
Example 14
Source File: TmfEventTableDataProvider.java From tracecompass with Eclipse Public License 2.0 | 4 votes |
private TableEventRequest filteredTableRequest(int queryCount, long queryIndex, Map<Long, ITmfEventAspect<?>> aspects, ITmfFilter filter, @Nullable ITmfFilter searchFilter, boolean forwardSearch, @Nullable ITmfFilter collapseFilter, @Nullable IProgressMonitor monitor) { applyFilter(filter); Entry<Long, Long> nearestEntry = fIndexToRankMap.floorEntry(queryIndex); long startingRank = nearestEntry != null ? nearestEntry.getValue() : 0L; Long startingIndex = nearestEntry != null ? nearestEntry.getKey() : 0L; return new TableEventRequest(startingRank) { private long currentIndex = startingIndex; private long rank = startingRank; @Override public void handleData(@NonNull ITmfEvent event) { super.handleData(event); if (monitor != null && monitor.isCanceled()) { cancel(); return; } List<EventTableLine> events = getEventLines(); if (filter.matches(event) && (collapseFilter == null || collapseFilter.matches(event))) { if (searchFilter == null || searchFilter.matches(event)) { if (events.size() < queryCount && queryIndex <= currentIndex) { events.add(buildEventTableLine(aspects, event, currentIndex, rank)); } if (currentIndex % INDEX_STORING_INTERVAL == 0) { fIndexToRankMap.put(currentIndex, rank); fRankToIndexMap.put(rank, currentIndex); } } currentIndex++; incrementCount(); } else if (collapseFilter != null && !events.isEmpty()) { // If a collapse filter is present, we need to update the last event we have in // our list to increment the repeat count value. int lastIndex = events.size() - 1; EventTableLine prevLine = events.get(lastIndex); long prevRepeatCount = prevLine.getRepeatCount(); events.set(lastIndex, new EventTableLine(prevLine.getCells(), prevLine.getIndex(), prevLine.getTimestamp(), prevLine.getRank(), prevRepeatCount++)); } if (searchFilter != null && ((!forwardSearch && getCurrentCount() == queryCount) || events.size() == queryCount)) { done(); return; } rank++; } @Override public long getCurrentCount() { long currentCount = super.getCurrentCount(); if (fFilteredCount == -1L) { fFilteredCount = currentCount; } return fFilteredCount; } }; }
Example 15
Source File: ProgressUtils.java From TranskribusCore with GNU General Public License v3.0 | 4 votes |
public static boolean isCanceled(IProgressMonitor monitor) { return monitor == null ? false : monitor.isCanceled(); }
Example 16
Source File: Html2Xliff.java From tmxeditor8 with GNU General Public License v2.0 | 4 votes |
/** * Builds the tables. * @param iniFile * the ini file * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. * @throws ParserConfigurationException * the parser configuration exception */ private void buildTables(String iniFile, IProgressMonitor monitor) throws SAXException, IOException, ParserConfigurationException { SAXBuilder builder = new SAXBuilder(); Catalogue cat = new Catalogue(catalogue); builder.setEntityResolver(cat); Document doc = builder.build(iniFile); Element root = doc.getRootElement(); List<Element> tags = root.getChildren("tag"); //$NON-NLS-1$ startsSegment = new Hashtable<String, String>(); translatableAttributes = new Hashtable<String, Vector<String>>(); entities = new Hashtable<String, String>(); ctypes = new Hashtable<String, String>(); keepFormating = new Hashtable<String, String>(); int size = tags.size(); monitor.beginTask(Messages.getString("html.Html2Xliff.task3"), size); monitor.subTask(""); Iterator<Element> i = tags.iterator(); while (i.hasNext()) { if (monitor.isCanceled()) { // 用户取消操作 throw new OperationCanceledException(Messages.getString("html.cancel")); } monitor.worked(1); Element t = i.next(); if (t.getAttributeValue("hard-break", "inline").equals("segment")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ startsSegment.put(t.getText(), "yes"); //$NON-NLS-1$ } if (t.getAttributeValue("keep-format", "no").equals("yes")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ keepFormating.put(t.getText(), "yes"); //$NON-NLS-1$ } String attributes = t.getAttributeValue("attributes", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (!attributes.equals("")) { //$NON-NLS-1$ StringTokenizer tokenizer = new StringTokenizer(attributes, ";"); //$NON-NLS-1$ int count = tokenizer.countTokens(); Vector<String> v = new Vector<String>(count); for (int j = 0; j < count; j++) { v.add(tokenizer.nextToken()); } translatableAttributes.put(t.getText(), v); } String ctype = t.getAttributeValue("ctype", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (!ctype.equals("")) { //$NON-NLS-1$ ctypes.put(t.getText(), ctype); } t = null; } tags = null; List<Element> ents = root.getChildren("entity"); //$NON-NLS-1$ Iterator<Element> it = ents.iterator(); while (it.hasNext()) { Element e = it.next(); entities.put("&" + e.getAttributeValue("name") + ";", e.getText()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } root = null; doc = null; builder = null; monitor.done(); }
Example 17
Source File: JavaProjectBasedBuilderParticipant.java From xtext-eclipse with Eclipse Public License 2.0 | 4 votes |
@Override public void build(IBuildContext context, IProgressMonitor monitor) throws CoreException { final IProject builtProject = context.getBuiltProject(); IJavaProject javaProject = JavaCore.create(builtProject); if (!javaProject.exists()) return; final IFolder srcGenFolder = getSrcGenFolder(builtProject); if (!srcGenFolder.exists()) return; if (!isValidOutputFolder(javaProject, srcGenFolder)) return; for (IResourceDescription.Delta delta : context.getDeltas()) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } final Set<String> oldFiles = newHashSet(); if (sourceTargetMap.containsKey(delta.getUri())) { oldFiles.addAll(sourceTargetMap.get(delta.getUri())); } final Set<String> newFiles = newHashSet(); IFileSystemAccess fileSystemAccess = getConfiguredFileSystemAccess(srcGenFolder, new IAcceptor<String>() { @Override public void accept(String fileName) { oldFiles.remove(fileName); newFiles.add(fileName); } }); if (delta.getNew() == null) { handleDeletion(delta, context, fileSystemAccess); } else { try { handleChangedContents(delta, context, fileSystemAccess); } catch (Exception e) { logger.error("Error during compilation of '"+delta.getUri()+"'.", e); } } for (String removeFile : oldFiles) { fileSystemAccess.deleteFile(removeFile); } if (!newFiles.isEmpty()) { sourceTargetMap.put(delta.getUri(), newFiles); } } }
Example 18
Source File: LoopNodesImportProgressDialog.java From pentaho-kettle with Apache License 2.0 | 4 votes |
@SuppressWarnings( "unchecked" ) private String[] doScan( IProgressMonitor monitor ) throws Exception { monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ScanningFile", filename ), 1 ); SAXReader reader = XMLParserFactoryProducer.getSAXReader( null ); monitor.worked( 1 ); if ( monitor.isCanceled() ) { return null; } // Validate XML against specified schema? if ( meta.isValidating() ) { reader.setValidation( true ); reader.setFeature( "http://apache.org/xml/features/validation/schema", true ); } else { // Ignore DTD reader.setEntityResolver( new IgnoreDTDEntityResolver() ); } monitor.worked( 1 ); monitor .beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingDocument" ), 1 ); if ( monitor.isCanceled() ) { return null; } InputStream is = null; try { Document document = null; if ( !Utils.isEmpty( filename ) ) { is = KettleVFS.getInputStream( filename ); document = reader.read( is, encoding ); } else { if ( !Utils.isEmpty( xml ) ) { document = reader.read( new StringReader( xml ) ); } else { document = reader.read( new URL( url ) ); } } monitor.worked( 1 ); monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.DocumentOpened" ), 1 ); monitor.worked( 1 ); monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingNode" ), 1 ); if ( monitor.isCanceled() ) { return null; } List<Node> nodes = document.selectNodes( document.getRootElement().getName() ); monitor.worked( 1 ); monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes" ) ); if ( monitor.isCanceled() ) { return null; } for ( Node node : nodes ) { if ( monitor.isCanceled() ) { return null; } if ( !listpath.contains( node.getPath() ) ) { nr++; monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes", String.valueOf( nr ) ) ); monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.AddingNode", node .getPath() ) ); listpath.add( node.getPath() ); addLoopXPath( node, monitor ); } } monitor.worked( 1 ); } finally { try { if ( is != null ) { is.close(); } } catch ( Exception e ) { /* Ignore */ } } String[] list_xpath = listpath.toArray( new String[listpath.size()] ); monitor.setTaskName( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.NodesReturned" ) ); monitor.done(); return list_xpath; }
Example 19
Source File: DocumentRelation.java From translationstudio8 with GNU General Public License v2.0 | 4 votes |
public void monitorWork(IProgressMonitor monitor){ monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } }
Example 20
Source File: Xliff2Docx.java From tmxeditor8 with GNU General Public License v2.0 | 4 votes |
/** * Run. * @param args * the args * @param monitor * the monitor * @return the map< string, string> * @throws ConverterException * the converter exception */ public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); ReverseConversionInfoLogRecord infoLogger = ConverterUtils.getReverseConversionInfoLogRecord(); infoLogger.startConversion(); Map<String, String> result = new HashMap<String, String>(); // 备注,这个 xliffFile 文件是原xliff,不做任何修改,要执行修改的是下面的 tempXLiffFile String xliffFile = args.get(Converter.ATTR_XLIFF_FILE); String outputFile = args.get(Converter.ATTR_TARGET_FILE); String skeleton = args.get(Converter.ATTR_SKELETON_FILE); try { File tempXLiffFile = File.createTempFile("tempxliff", "hsxliff"); tempXLiffFile.deleteOnExit(); CommonFunctions.copyFile(new File(xliffFile), tempXLiffFile); // 把转换过程分为三部分共 20 个任务,解压压缩各1个,页眉,页脚,批注,脚注,尾注各1个,其余 13 个为处理主文档 monitor.beginTask("", 20); // infoLogger.logConversionFileInfo(catalogue, null, xliffFile, null); // IProgressMonitor separateMonitor = Progress.getSubMonitor(monitor, 8); // long startTime = 0; // LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger1"), startTime); monitor.setTaskName(Messages.getString("xlf2Docx.task6")); String tempFolder = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + new File(skeleton).getName(); String docxFolderPath = ZipUtil.upZipFile(skeleton, tempFolder); pathUtil = new PathUtil(docxFolderPath); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } // 定义一个 hsxliff 的读入器 XliffInputer xlfInput = new XliffInputer(tempXLiffFile.getAbsolutePath(), pathUtil); // 正转换是从 主文档入手的,而逆转换则是从 word/_rels/document.xml.rels 入手,先处理掉 页眉,页脚,脚注,批注,尾注 String docRelsPath = pathUtil.getPackageFilePath(PathConstant.DOCUMENTRELS, false); DocumentRelation docRels = new DocumentRelation(docRelsPath, pathUtil); docRels.arrangeRelations(xlfInput, monitor); // 这里用掉 5 个格子 // 再处理主文档 pathUtil.setSuperRoot(); String docPath = pathUtil.getPackageFilePath(PathConstant.DOCUMENT, false); DocumentPart documentPart = new DocumentPart(docPath, xlfInput, monitor); documentPart.reverseConvert(); monitor.setTaskName(Messages.getString("xlf2Docx.task6")); ZipUtil.zipFolder(outputFile, pathUtil.getSuperRoot()); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } }catch (Exception e) { e.printStackTrace(); if (Converter.DEBUG_MODE) { e.printStackTrace(); } ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("xlf2Docx.msg1"), e); } finally { deleteFileOrFolder(new File(pathUtil.getSuperRoot())); monitor.done(); } infoLogger.endConversion(); result.put(Converter.ATTR_TARGET_FILE, outputFile); return result; }