Java Code Examples for org.eclipse.jface.operation.ModalContext#checkCanceled()

The following examples show how to use org.eclipse.jface.operation.ModalContext#checkCanceled() . 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: TracePackageExportOperation.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private Node exportCommon(IProgressMonitor monitor, Node tmfNode, TracePackageTraceElement tracePackageElement, String elementString) throws InterruptedException, CoreException {
    TmfCommonProjectElement commonElement = tracePackageElement.getTraceElement();
    Element commonXmlElement = tmfNode.getOwnerDocument().createElement(elementString);
    commonXmlElement.setAttribute(ITracePackageConstants.TRACE_NAME_ATTRIB, commonElement.getResource().getName());
    commonXmlElement.setAttribute(ITracePackageConstants.TRACE_TYPE_ATTRIB, commonElement.getTraceType());
    Node commonNode = tmfNode.appendChild(commonXmlElement);

    for (TracePackageElement element : tracePackageElement.getChildren()) {
        ModalContext.checkCanceled(monitor);
        if (!element.isChecked()) {
            continue;
        }
        if (element instanceof TracePackageSupplFilesElement) {
            exportSupplementaryFiles(monitor, commonNode, commonElement, (TracePackageSupplFilesElement) element);
        } else if (element instanceof TracePackageBookmarkElement) {
            exportBookmarks(monitor, commonNode, (TracePackageBookmarkElement) element);
        } else if (element instanceof TracePackageFilesElement && commonElement instanceof TmfTraceElement) {
            exportTraceFiles(monitor, commonNode, (TracePackageFilesElement) element);
        }

        monitor.worked(1);
    }
    return commonNode;
}
 
Example 2
Source File: TracePackageExportOperation.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private static void exportBookmarks(IProgressMonitor monitor, Node commonNode, TracePackageBookmarkElement element) throws CoreException, InterruptedException {
    Document doc = commonNode.getOwnerDocument();
    IFile bookmarksFile = ((TracePackageTraceElement) element.getParent()).getTraceElement().getBookmarksFile();
    if (bookmarksFile != null && bookmarksFile.exists()) {
        IMarker[] findMarkers = bookmarksFile.findMarkers(IMarker.BOOKMARK, false, IResource.DEPTH_ZERO);
        if (findMarkers.length > 0) {
            Element bookmarksXmlElement = doc.createElement(ITracePackageConstants.BOOKMARKS_ELEMENT);
            Node bookmarksNode = commonNode.appendChild(bookmarksXmlElement);

            for (IMarker marker : findMarkers) {
                ModalContext.checkCanceled(monitor);

                Element singleBookmarkXmlElement = doc.createElement(ITracePackageConstants.BOOKMARK_ELEMENT);
                for (String key : marker.getAttributes().keySet()) {
                    singleBookmarkXmlElement.setAttribute(key, marker.getAttribute(key).toString());
                }

                bookmarksNode.appendChild(singleBookmarkXmlElement);
            }
        }
    }
}
 
Example 3
Source File: JarFileExportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void exportExternalClassFolderElement(IJavaElement javaElement, IPath classFolderPath, IProgressMonitor progressMonitor) throws JavaModelException, InterruptedException {
	if (javaElement instanceof IClassFile) {
		IClassFile classFile= (IClassFile) javaElement;
		IPath path= classFile.getPath();

		IPath destination= path.removeFirstSegments(classFolderPath.segmentCount()).setDevice(null);

		try {
			((IJarBuilderExtension) fJarBuilder).writeFile(path.toFile(), destination);
		} catch (CoreException e) {
			handleCoreExceptionOnExport(e);
		} finally {
			progressMonitor.worked(1);
			ModalContext.checkCanceled(progressMonitor);
		}
	} else if (javaElement instanceof IPackageFragment) {
		IJavaElement[] children= ((IPackageFragment) javaElement).getChildren();
		for (int i= 0; i < children.length; i++) {
			exportExternalClassFolderElement(children[i], classFolderPath, progressMonitor);
		}
	}
}
 
Example 4
Source File: JarFileExportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void exportResource(IProgressMonitor progressMonitor, IResource resource, int leadingSegmentsToRemove) throws InterruptedException {
	if (resource instanceof IContainer) {
		IContainer container= (IContainer)resource;
		IResource[] children;
		try {
			children= container.members();
		} catch (CoreException e) {
			// this should never happen because an #isAccessible check is done before #members is invoked
			addWarning(Messages.format(JarPackagerMessages.JarFileExportOperation_errorDuringExport, BasicElementLabels.getPathLabel(container.getFullPath(), false)), e);
			return;
		}
		for (int i= 0; i < children.length; i++)
			exportResource(progressMonitor, children[i], leadingSegmentsToRemove);
	} else if (resource instanceof IFile) {
		try {
			IPath destinationPath= resource.getFullPath().removeFirstSegments(leadingSegmentsToRemove);
			progressMonitor.subTask(Messages.format(JarPackagerMessages.JarFileExportOperation_exporting, BasicElementLabels.getPathLabel(destinationPath, false)));
			fJarBuilder.writeFile((IFile)resource, destinationPath);
		} catch (CoreException ex) {
			handleCoreExceptionOnExport(ex);
		} finally {
			progressMonitor.worked(1);
			ModalContext.checkCanceled(progressMonitor);
		}
	}
}
 
Example 5
Source File: TracePackageExportOperation.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private void exportSupplementaryFiles(IProgressMonitor monitor, Node commonNode, TmfCommonProjectElement commonElement, TracePackageSupplFilesElement element) throws InterruptedException, CoreException {
    Document doc = commonNode.getOwnerDocument();
    if (element.getChildren().length > 0) {

        IPath projectPath = commonElement.getProject().getPath();

        for (TracePackageElement child : element.getChildren()) {
            TracePackageSupplFileElement supplFile = (TracePackageSupplFileElement) child;
            ModalContext.checkCanceled(monitor);
            IResource res = supplFile.getResource();
            // project/.tracing/A/B/statistics.ht -> .tracing/A/B/statistics.ht
            IPath relativeToExportFolder = res.getFullPath().makeRelativeTo(projectPath);

            // project/.traceExport/.tracing/A/B
            IFolder folder = fExportFolder.getFolder(relativeToExportFolder.removeLastSegments(1));
            TraceUtils.createFolder(folder, SubMonitor.convert(monitor));

            res.refreshLocal(0, SubMonitor.convert(monitor));
            createExportResource(folder, res);
            Element suppFileElement = doc.createElement(ITracePackageConstants.SUPPLEMENTARY_FILE_ELEMENT);

            suppFileElement.setAttribute(ITracePackageConstants.SUPPLEMENTARY_FILE_NAME_ATTRIB, relativeToExportFolder.toString());
            commonNode.appendChild(suppFileElement);
        }

        IFolder suppFilesFolder = fExportFolder.getFolder(TmfCommonConstants.TRACE_SUPPLEMENTARY_FOLDER_NAME);
        fResources.add(suppFilesFolder);
    }
}
 
Example 6
Source File: TraceValidateAndImportOperation.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Extract all file system elements (File) to destination folder (typically
 * workspace/TraceProject/.traceImport)
 */
private void extractAllArchiveFiles(List<TraceFileSystemElement> fileSystemElements, IFolder destFolder, IPath baseSourceContainerPath, IProgressMonitor progressMonitor) throws InterruptedException, CoreException, InvocationTargetException {
    SubMonitor subMonitor = SubMonitor.convert(progressMonitor, fileSystemElements.size());
    ListIterator<TraceFileSystemElement> fileSystemElementsIter = fileSystemElements.listIterator();
    while (fileSystemElementsIter.hasNext()) {
        ModalContext.checkCanceled(subMonitor);

        SubMonitor elementProgress = subMonitor.newChild(1);
        TraceFileSystemElement element = fileSystemElementsIter.next();
        elementProgress.setTaskName(Messages.ImportTraceWizard_ExamineOperationTaskName + " " + element.getFileSystemObject().getAbsolutePath()); //$NON-NLS-1$
        File archiveFile = (File) element.getFileSystemObject().getRawFileSystemObject();
        boolean isArchiveFileElement = element.getFileSystemObject() instanceof FileFileSystemObject && ArchiveUtil.isArchiveFile(archiveFile);
        if (isArchiveFileElement) {
            elementProgress = SubMonitor.convert(elementProgress, 4);
            IPath makeAbsolute = baseSourceContainerPath.makeAbsolute();
            IPath relativeToSourceContainer = new Path(element.getFileSystemObject().getAbsolutePath()).makeRelativeTo(makeAbsolute);
            IFolder folder = safeCreateExtractedFolder(destFolder, relativeToSourceContainer, elementProgress.newChild(1));
            extractArchiveToFolder(archiveFile, folder, elementProgress.newChild(1));

            // Delete original archive, we don't want to import this, just
            // the extracted content
            IFile fileRes = destFolder.getFile(relativeToSourceContainer);
            fileRes.delete(true, elementProgress.newChild(1));
            IPath newPath = destFolder.getFullPath().append(relativeToSourceContainer);
            // Rename extracted folder (.extract) to original archive name
            folder.move(newPath, true, elementProgress.newChild(1));
            folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(newPath);
            elementProgress.subTask(""); //$NON-NLS-1$

            // Create the new import provider and root element based on
            // the newly extracted temporary folder
            FileSystemObjectImportStructureProvider importStructureProvider = new FileSystemObjectImportStructureProvider(FileSystemStructureProvider.INSTANCE, null);
            IFileSystemObject rootElement = importStructureProvider.getIFileSystemObject(new File(folder.getLocation().toOSString()));
            TraceFileSystemElement newElement = TraceFileSystemElement.createRootTraceFileElement(rootElement, importStructureProvider);
            List<TraceFileSystemElement> extractedChildren = new ArrayList<>();
            newElement.getAllChildren(extractedChildren);
            extractAllArchiveFiles(extractedChildren, folder, folder.getLocation(), progressMonitor);
        }
    }
}
 
Example 7
Source File: TraceValidateAndImportOperation.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Extract all file system elements (Tar, Zip elements) to destination
 * folder (typically workspace/TraceProject/.traceImport or a subfolder of
 * it)
 */
private void extractArchiveContent(Iterator<TraceFileSystemElement> fileSystemElementsIter, IFolder tempFolder, IProgressMonitor progressMonitor) throws InterruptedException,
        InvocationTargetException {
    List<TraceFileSystemElement> subList = new ArrayList<>();
    // Collect all the elements
    while (fileSystemElementsIter.hasNext()) {
        ModalContext.checkCanceled(progressMonitor);
        TraceFileSystemElement element = fileSystemElementsIter.next();
        if (element.isDirectory()) {
            Object[] array = element.getFiles().getChildren();
            for (int i = 0; i < array.length; i++) {
                subList.add((TraceFileSystemElement) array[i]);
            }
        }
        subList.add(element);
    }

    if (subList.isEmpty()) {
        return;
    }

    TraceFileSystemElement root = getRootElement(subList.get(0));

    ImportProvider fileSystemStructureProvider = new ImportProvider();

    IOverwriteQuery myQueryImpl = file -> IOverwriteQuery.NO_ALL;

    progressMonitor.setTaskName(Messages.ImportTraceWizard_ExtractImportOperationTaskName);
    IPath containerPath = tempFolder.getFullPath();
    ImportOperation operation = new ImportOperation(containerPath, root, fileSystemStructureProvider, myQueryImpl, subList);
    operation.setContext(fShell);

    operation.setCreateContainerStructure(true);
    operation.setOverwriteResources(false);
    operation.setVirtualFolders(false);

    operation.run(SubMonitor.convert(progressMonitor).newChild(subList.size()));
}
 
Example 8
Source File: RemoteGenerateManifestOperation.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Scan traceFolder for files that match the patterns specified in the
 * template file. When there is a match, the trace package element is used
 * to determine the trace name and trace type.
 *
 * @param traceGroup
 *                The parent trace group element
 * @param parentElement
 *                The immediate parent trace group or folder element
 * @param traceFolder
 *                The folder to scan
 * @param recursionLevel
 *                The recursion level (needed to find directory traces under the traceFolder
 * @param monitor
 *                The progress monitor
 * @throws CoreException
 *                Thrown by the file system implementation
 * @throws InterruptedException
 *                Thrown if operation was cancelled
 */
private void generateElementsFromArchive(
        final RemoteImportTraceGroupElement traceGroup,
        final TracePackageElement parentElement,
        final IFileStore traceFolder,
        final int recursionLevel,
        IProgressMonitor monitor)
                throws CoreException, InterruptedException {

    int localRecursionLevel = recursionLevel + 1;
    IFileStore[] sources = traceFolder.childStores(EFS.NONE, monitor);

    for (int i = 0; i < sources.length; i++) {
        ModalContext.checkCanceled(monitor);
        SubMonitor subMonitor = SubMonitor.convert(monitor, sources.length);

        IFileStore fileStore = sources[i];
        IPath fullArchivePath = TmfTraceCoreUtils.newSafePath(fileStore.toURI().getPath());

        IFileInfo sourceInfo = fileStore.fetchInfo();
        if (!sourceInfo.isDirectory()) {

            String rootPathString = traceGroup.getRootImportPath();
            IPath rootPath = TmfTraceCoreUtils.newSafePath(rootPathString);
            IPath relativeTracePath = Path.EMPTY;
            if (rootPath.isPrefixOf(fullArchivePath)) {
                relativeTracePath = fullArchivePath.makeRelativeTo(rootPath);
            }
            Entry<Pattern, TracePackageTraceElement> matchingTemplateEntry = getMatchingTemplateElement(relativeTracePath);
            if (matchingTemplateEntry != null) {
                TracePackageTraceElement matchingTemplateElement = matchingTemplateEntry.getValue();
                String traceType = matchingTemplateElement.getTraceType();

                // If a single file is part of a directory trace, use the parent directory instead
                TracePackageElement parent = parentElement;
                if (matchesDirectoryTrace(relativeTracePath, matchingTemplateEntry)) {
                    fullArchivePath = fullArchivePath.removeLastSegments(1);
                    fDirectoryTraces.add(fullArchivePath);
                    fileStore = fileStore.getParent();
                    sourceInfo = fileStore.fetchInfo();
                    parent = parentElement.getParent();
                    // Let the auto-detection choose the best trace type
                    traceType = null;
                } else if ((localRecursionLevel > 1) && (!traceGroup.isRecursive())) {
                    // Don't consider file traces on level 2 if it's not recursive
                    continue;
                }

                if (sourceInfo.getLength() > 0 || sourceInfo.isDirectory()) {
                    // Only add non-empty files
                    String traceName = fullArchivePath.lastSegment();
                    String fileName = fileStore.getName();
                    // create new elements to decouple from input elements
                    TracePackageTraceElement traceElement = new TracePackageTraceElement(parent, traceName, traceType);
                    RemoteImportTraceFilesElement tracePackageFilesElement = new RemoteImportTraceFilesElement(traceElement, fileName, fileStore);
                    tracePackageFilesElement.setVisible(false);
                }
            }
        } else {
            if (traceGroup.isRecursive() || localRecursionLevel < 2) {
                RemoteImportFolderElement folder = new RemoteImportFolderElement(parentElement, fileStore.getName());
                generateElementsFromArchive(traceGroup, folder, fileStore, localRecursionLevel, subMonitor);
            }
        }
    }
}
 
Example 9
Source File: TracePackageImportOperation.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
private void doRun(IProgressMonitor progressMonitor) {
    try {
        setStatus(deleteExistingTraces(progressMonitor));
        if (!getStatus().isOK()) {
            return;
        }

        List<TracePackageExperimentElement> experimentPackageElements = new ArrayList<>();
        for (TracePackageElement packageElement : fImportTraceElements) {

            TracePackageTraceElement traceElement = (TracePackageTraceElement) packageElement;
            if (!isFilesChecked(packageElement)) {
                continue;
            }
            if (packageElement instanceof TracePackageExperimentElement) {
                experimentPackageElements.add((TracePackageExperimentElement) packageElement);
                continue;
            }
            TracePackageElement[] children = traceElement.getChildren();
            for (TracePackageElement element : children) {
                ModalContext.checkCanceled(progressMonitor);

                if (element instanceof TracePackageFilesElement) {
                    TracePackageFilesElement traceFilesElement = (TracePackageFilesElement) element;
                    setStatus(importTraceFiles(traceFilesElement, traceElement, progressMonitor));
                }

                if (!getStatus().isOK()) {
                    return;
                }
            }
            setStatus(importSupplFiles(traceElement, progressMonitor));
            if (!getStatus().isOK()) {
                return;
            }
        }
        for (TracePackageExperimentElement experimentPackageElement : experimentPackageElements) {
            ModalContext.checkCanceled(progressMonitor);
            importExperiment(experimentPackageElement, progressMonitor);
            if (!getStatus().isOK()) {
                return;
            }
        }

    } catch (InterruptedException e) {
        setStatus(Status.CANCEL_STATUS);
        Thread.currentThread().interrupt();
    }
}
 
Example 10
Source File: TraceValidateAndImportOperation.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Import a collection of file system elements into the workspace.
 */
private void importFileSystemElements(IProgressMonitor monitor, List<TraceFileSystemElement> fileSystemElements)
        throws InterruptedException, TmfTraceImportException, CoreException, InvocationTargetException {
    SubMonitor subMonitor = SubMonitor.convert(monitor, fileSystemElements.size());
    // Sort the elements in a sensible order to make it more predictable to
    // the user when there can be name clashes. Otherwise, the order can
    // seem pretty random depending on the OS/Filesystem.
    fileSystemElements.sort(new FileObjectPathComparator());

    ListIterator<TraceFileSystemElement> fileSystemElementsIter = fileSystemElements.listIterator();

    // Map to remember already imported directory traces
    final Map<String, TraceFileSystemElement> directoryTraces = new HashMap<>();
    while (fileSystemElementsIter.hasNext()) {
        ModalContext.checkCanceled(monitor);
        fCurrentPath = null;
        TraceFileSystemElement element = fileSystemElementsIter.next();
        IFileSystemObject fileSystemObject = element.getFileSystemObject();
        String resourcePath = element.getFileSystemObject().getAbsolutePath();
        element.setDestinationContainerPath(computeDestinationContainerPath(new Path(resourcePath)));

        fCurrentPath = resourcePath;
        SubMonitor sub = subMonitor.split(1, SubMonitor.SUPPRESS_BEGINTASK | SubMonitor.SUPPRESS_SUBTASK);
        if (element.isDirectory()) {
            if (!directoryTraces.containsKey(resourcePath) && isDirectoryTrace(element)) {
                directoryTraces.put(resourcePath, element);
                validateAndImportTrace(element, sub);
            }
        } else {
            TraceFileSystemElement parentElement = (TraceFileSystemElement) element.getParent();
            String parentPath = parentElement.getFileSystemObject().getAbsolutePath();
            parentElement.setDestinationContainerPath(computeDestinationContainerPath(new Path(parentPath)));
            fCurrentPath = parentPath;
            if (!directoryTraces.containsKey(parentPath)) {
                if (isDirectoryTrace(parentElement)) {
                    directoryTraces.put(parentPath, parentElement);
                    validateAndImportTrace(parentElement, sub);
                } else {
                    boolean validateFile = true;
                    TraceFileSystemElement grandParentElement = (TraceFileSystemElement) parentElement.getParent();
                    // Special case for LTTng trace that may contain index
                    // directory and files
                    if (grandParentElement != null) {
                        String grandParentPath = grandParentElement.getFileSystemObject().getAbsolutePath();
                        grandParentElement.setDestinationContainerPath(computeDestinationContainerPath(new Path(parentPath)));
                        fCurrentPath = grandParentPath;
                        if (directoryTraces.containsKey(grandParentPath)) {
                            validateFile = false;
                        } else if (isDirectoryTrace(grandParentElement)) {
                            directoryTraces.put(grandParentPath, grandParentElement);
                            validateAndImportTrace(grandParentElement, sub);
                            validateFile = false;
                        }
                    }
                    if (validateFile && (fileSystemObject.exists())) {
                        validateAndImportTrace(element, sub);
                    }
                }
            }
        }
    }
}