Search in sources :

Example 81 with OperationCanceledException

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

the class RefactoringHistoryManager method readRefactoringDescriptorProxies.

/**
	 * Reads refactoring descriptor proxies.
	 *
	 * @param store
	 *            the file store to read
	 * @param project
	 *            the name of the project, or <code>null</code> for the
	 *            workspace
	 * @param collection
	 *            the collection of proxies to fill in
	 * @param start
	 *            the start time stamp, inclusive
	 * @param end
	 *            the end time stamp, inclusive
	 * @param monitor
	 *            the progress monitor to use
	 * @param task
	 *            the task label to use
	 * @throws CoreException
	 *             if an error occurs
	 */
private static void readRefactoringDescriptorProxies(final IFileStore store, final String project, final Collection collection, final long start, final long end, final IProgressMonitor monitor, final String task) throws CoreException {
    try {
        monitor.beginTask(RefactoringCoreMessages.RefactoringHistoryService_retrieving_history, 22);
        final IFileInfo info = store.fetchInfo(EFS.NONE, new SubProgressMonitor(monitor, 2, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
        if (!info.isDirectory() && info.exists() && store.getName().equalsIgnoreCase(RefactoringHistoryService.NAME_INDEX_FILE)) {
            InputStream stream = null;
            try {
                stream = store.openInputStream(EFS.NONE, new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
                final RefactoringDescriptorProxy[] proxies = readRefactoringDescriptorProxies(stream, project, start, end);
                for (int index = 0; index < proxies.length; index++) collection.add(proxies[index]);
                monitor.worked(1);
            } catch (IOException exception) {
                throw createCoreException(exception);
            } finally {
                monitor.worked(1);
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException exception) {
                    // Do nothing
                    }
                }
                monitor.worked(1);
            }
        } else
            monitor.worked(4);
        if (monitor.isCanceled())
            throw new OperationCanceledException();
        final IFileStore[] stores = store.childStores(EFS.NONE, new SubProgressMonitor(monitor, 2, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
        final IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 12);
        try {
            subMonitor.beginTask(task, stores.length);
            for (int index = 0; index < stores.length; index++) readRefactoringDescriptorProxies(stores[index], project, collection, start, end, new SubProgressMonitor(subMonitor, 1), task);
        } finally {
            subMonitor.done();
        }
    } finally {
        monitor.done();
    }
}
Also used : IFileInfo(org.eclipse.core.filesystem.IFileInfo) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) RefactoringDescriptorProxy(org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IFileStore(org.eclipse.core.filesystem.IFileStore) IOException(java.io.IOException) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor)

Example 82 with OperationCanceledException

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

the class LocalFile method internalDelete.

/**
	 * Deletes the given file recursively, adding failure info to
	 * the provided status object.  The filePath is passed as a parameter
	 * to optimize java.io.File object creation.
	 */
private boolean internalDelete(File target, String pathToDelete, MultiStatus status, IProgressMonitor monitor) {
    //first try to delete - this should succeed for files and symbolic links to directories
    if (monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    if (target.delete() || !target.exists())
        return true;
    if (target.isDirectory()) {
        monitor.subTask(NLS.bind(Messages.deleting, target));
        String[] list = target.list();
        if (list == null)
            list = EMPTY_STRING_ARRAY;
        int parentLength = pathToDelete.length();
        boolean failedRecursive = false;
        for (int i = 0, imax = list.length; i < imax; i++) {
            if (monitor.isCanceled()) {
                throw new OperationCanceledException();
            }
            //optimized creation of child path object
            StringBuffer childBuffer = new StringBuffer(parentLength + list[i].length() + 1);
            childBuffer.append(pathToDelete);
            childBuffer.append(File.separatorChar);
            childBuffer.append(list[i]);
            String childName = childBuffer.toString();
            // try best effort on all children so put logical OR at end
            failedRecursive = !internalDelete(new File(childName), childName, status, monitor) || failedRecursive;
            monitor.worked(1);
        }
        try {
            // don't try to delete the root if one of the children failed
            if (!failedRecursive && target.delete())
                return true;
        } catch (Exception e) {
            // we caught a runtime exception so log it
            String message = NLS.bind(Messages.couldnotDelete, target.getAbsolutePath());
            status.add(new Status(IStatus.ERROR, Policy.PI_FILE_SYSTEM, EFS.ERROR_DELETE, message, e));
            return false;
        }
    }
    //if we got this far, we failed
    String message = null;
    if (fetchInfo().getAttribute(EFS.ATTRIBUTE_READ_ONLY))
        message = NLS.bind(Messages.couldnotDeleteReadOnly, target.getAbsolutePath());
    else
        message = NLS.bind(Messages.couldnotDelete, target.getAbsolutePath());
    status.add(new Status(IStatus.ERROR, Policy.PI_FILE_SYSTEM, EFS.ERROR_DELETE, message, null));
    return false;
}
Also used : MultiStatus(org.eclipse.core.runtime.MultiStatus) Status(org.eclipse.core.runtime.Status) IStatus(org.eclipse.core.runtime.IStatus) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) File(java.io.File) CoreException(org.eclipse.core.runtime.CoreException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException)

Example 83 with OperationCanceledException

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

the class RippleMethodFinder2 method findAllRippleMethods.

private IMethod[] findAllRippleMethods(IProgressMonitor pm, WorkingCopyOwner owner) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 4);
    findAllDeclarations(new SubProgressMonitor(pm, 1), owner);
    //check for bug 81058:
    if (!fDeclarations.contains(fMethod))
        //$NON-NLS-1$
        Assert.isTrue(false, "Search for method declaration did not find original element: " + fMethod.toString());
    createHierarchyOfDeclarations(new SubProgressMonitor(pm, 1), owner);
    createTypeToMethod();
    createUnionFind();
    if (pm.isCanceled())
        throw new OperationCanceledException();
    fHierarchy = null;
    fRootTypes = null;
    Map<IType, List<IType>> partitioning = new HashMap<IType, List<IType>>();
    for (Iterator<IType> iter = fTypeToMethod.keySet().iterator(); iter.hasNext(); ) {
        IType type = iter.next();
        IType rep = fUnionFind.find(type);
        List<IType> types = partitioning.get(rep);
        if (types == null)
            types = new ArrayList<IType>();
        types.add(type);
        partitioning.put(rep, types);
    }
    Assert.isTrue(partitioning.size() > 0);
    if (partitioning.size() == 1)
        return fDeclarations.toArray(new IMethod[fDeclarations.size()]);
    //Multiple partitions; must look out for nasty marriage cases
    //(types inheriting method from two ancestors, but without redeclaring it).
    IType methodTypeRep = fUnionFind.find(fMethod.getDeclaringType());
    List<IType> relatedTypes = partitioning.get(methodTypeRep);
    boolean hasRelatedInterfaces = false;
    List<IMethod> relatedMethods = new ArrayList<IMethod>();
    for (Iterator<IType> iter = relatedTypes.iterator(); iter.hasNext(); ) {
        IType relatedType = iter.next();
        relatedMethods.add(fTypeToMethod.get(relatedType));
        if (relatedType.isInterface())
            hasRelatedInterfaces = true;
    }
    //Definition: An alien type is a type that is not a related type. The set of
    // alien types diminishes as new types become related (a.k.a marry a relatedType).
    List<IMethod> alienDeclarations = new ArrayList<IMethod>(fDeclarations);
    fDeclarations = null;
    alienDeclarations.removeAll(relatedMethods);
    List<IType> alienTypes = new ArrayList<IType>();
    boolean hasAlienInterfaces = false;
    for (Iterator<IMethod> iter = alienDeclarations.iterator(); iter.hasNext(); ) {
        IMethod alienDeclaration = iter.next();
        IType alienType = alienDeclaration.getDeclaringType();
        alienTypes.add(alienType);
        if (alienType.isInterface())
            hasAlienInterfaces = true;
    }
    if (//no nasty marriage scenarios without types to marry with...
    alienTypes.size() == 0)
        return relatedMethods.toArray(new IMethod[relatedMethods.size()]);
    if (//no nasty marriage scenarios without interfaces...
    !hasRelatedInterfaces && !hasAlienInterfaces)
        return relatedMethods.toArray(new IMethod[relatedMethods.size()]);
    //find all subtypes of related types:
    HashSet<IType> relatedSubTypes = new HashSet<IType>();
    List<IType> relatedTypesToProcess = new ArrayList<IType>(relatedTypes);
    while (relatedTypesToProcess.size() > 0) {
        //TODO: would only need subtype hierarchies of all top-of-ripple relatedTypesToProcess
        for (Iterator<IType> iter = relatedTypesToProcess.iterator(); iter.hasNext(); ) {
            if (pm.isCanceled())
                throw new OperationCanceledException();
            IType relatedType = iter.next();
            ITypeHierarchy hierarchy = getCachedHierarchy(relatedType, owner, new SubProgressMonitor(pm, 1));
            if (hierarchy == null)
                hierarchy = relatedType.newTypeHierarchy(owner, new SubProgressMonitor(pm, 1));
            IType[] allSubTypes = hierarchy.getAllSubtypes(relatedType);
            for (int i = 0; i < allSubTypes.length; i++) relatedSubTypes.add(allSubTypes[i]);
        }
        //processed; make sure loop terminates
        relatedTypesToProcess.clear();
        HashSet<IType> marriedAlienTypeReps = new HashSet<IType>();
        for (Iterator<IType> iter = alienTypes.iterator(); iter.hasNext(); ) {
            if (pm.isCanceled())
                throw new OperationCanceledException();
            IType alienType = iter.next();
            IMethod alienMethod = fTypeToMethod.get(alienType);
            ITypeHierarchy hierarchy = getCachedHierarchy(alienType, owner, new SubProgressMonitor(pm, 1));
            if (hierarchy == null)
                hierarchy = alienType.newTypeHierarchy(owner, new SubProgressMonitor(pm, 1));
            IType[] allSubtypes = hierarchy.getAllSubtypes(alienType);
            for (int i = 0; i < allSubtypes.length; i++) {
                IType subtype = allSubtypes[i];
                if (relatedSubTypes.contains(subtype)) {
                    if (JavaModelUtil.isVisibleInHierarchy(alienMethod, subtype.getPackageFragment())) {
                        marriedAlienTypeReps.add(fUnionFind.find(alienType));
                    } else {
                    // not overridden
                    }
                }
            }
        }
        if (marriedAlienTypeReps.size() == 0)
            return relatedMethods.toArray(new IMethod[relatedMethods.size()]);
        for (Iterator<IType> iter = marriedAlienTypeReps.iterator(); iter.hasNext(); ) {
            IType marriedAlienTypeRep = iter.next();
            List<IType> marriedAlienTypes = partitioning.get(marriedAlienTypeRep);
            for (Iterator<IType> iterator = marriedAlienTypes.iterator(); iterator.hasNext(); ) {
                IType marriedAlienInterfaceType = iterator.next();
                relatedMethods.add(fTypeToMethod.get(marriedAlienInterfaceType));
            }
            //not alien any more
            alienTypes.removeAll(marriedAlienTypes);
            //process freshly married types again
            relatedTypesToProcess.addAll(marriedAlienTypes);
        }
    }
    fRootReps = null;
    fRootHierarchies = null;
    fTypeToMethod = null;
    fUnionFind = null;
    return relatedMethods.toArray(new IMethod[relatedMethods.size()]);
}
Also used : HashMap(java.util.HashMap) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) IType(org.eclipse.jdt.core.IType) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) ArrayList(java.util.ArrayList) List(java.util.List) IMethod(org.eclipse.jdt.core.IMethod) HashSet(java.util.HashSet)

Example 84 with OperationCanceledException

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

the class IntroduceIndirectionRefactoring method checkFinalConditions.

@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    RefactoringStatus result = new RefactoringStatus();
    fTextChangeManager = new TextChangeManager();
    fIntermediaryFirstParameterType = null;
    fIntermediaryTypeBinding = null;
    for (Iterator<CompilationUnitRewrite> iter = fRewrites.values().iterator(); iter.hasNext(); ) iter.next().clearASTAndImportRewrites();
    int startupTicks = 5;
    int hierarchyTicks = 5;
    int visibilityTicks = 5;
    int referenceTicks = fUpdateReferences ? 30 : 5;
    int creationTicks = 5;
    //$NON-NLS-1$
    pm.beginTask("", startupTicks + hierarchyTicks + visibilityTicks + referenceTicks + creationTicks);
    pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions);
    result.merge(Checks.checkMethodName(fIntermediaryMethodName, fIntermediaryType));
    if (result.hasFatalError())
        return result;
    if (fIntermediaryType == null)
        return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_run_without_intermediary_type);
    // intermediary type is already non binary/non-enum
    CompilationUnitRewrite imRewrite = getCachedCURewrite(fIntermediaryType.getCompilationUnit());
    fIntermediaryTypeBinding = typeToBinding(fIntermediaryType, imRewrite.getRoot());
    fAdjustor = new MemberVisibilityAdjustor(fIntermediaryType, fIntermediaryType);
    fIntermediaryAdjustments = new HashMap<IMember, IncomingMemberVisibilityAdjustment>();
    // check static method in non-static nested type
    if (fIntermediaryTypeBinding.isNested() && !Modifier.isStatic(fIntermediaryTypeBinding.getModifiers()))
        return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_cannot_create_in_nested_nonstatic, JavaStatusContext.create(fIntermediaryType));
    pm.worked(startupTicks);
    if (pm.isCanceled())
        throw new OperationCanceledException();
    if (fUpdateReferences) {
        //$NON-NLS-1$
        pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions + " " + RefactoringCoreMessages.IntroduceIndirectionRefactoring_looking_for_references);
        result.merge(updateReferences(new NoOverrideProgressMonitor(pm, referenceTicks)));
        pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions);
    } else {
        // only update the declaration and/or a selected method invocation
        if (fSelectionMethodInvocation != null) {
            fIntermediaryFirstParameterType = getExpressionType(fSelectionMethodInvocation);
            final IMember enclosing = getEnclosingInitialSelectionMember();
            // create an edit for this particular call
            result.merge(updateMethodInvocation(fSelectionMethodInvocation, enclosing, getCachedCURewrite(fSelectionCompilationUnit)));
            if (!isRewriteKept(fSelectionCompilationUnit))
                createChangeAndDiscardRewrite(fSelectionCompilationUnit);
            // does call see the intermediary method?
            // => increase visibility of the type of the intermediary method.
            result.merge(adjustVisibility(fIntermediaryType, enclosing.getDeclaringType(), new NoOverrideProgressMonitor(pm, 0)));
        }
        pm.worked(referenceTicks);
    }
    if (pm.isCanceled())
        throw new OperationCanceledException();
    if (fIntermediaryFirstParameterType == null)
        fIntermediaryFirstParameterType = fTargetMethodBinding.getDeclaringClass();
    // The target type and method may have changed - update them
    IType actualTargetType = (IType) fIntermediaryFirstParameterType.getJavaElement();
    if (!fTargetMethod.getDeclaringType().equals(actualTargetType)) {
        IMethod actualTargetMethod = new MethodOverrideTester(actualTargetType, actualTargetType.newSupertypeHierarchy(null)).findOverriddenMethodInHierarchy(actualTargetType, fTargetMethod);
        fTargetMethod = actualTargetMethod;
        fTargetMethodBinding = findMethodBindingInHierarchy(fIntermediaryFirstParameterType, actualTargetMethod);
        Assert.isNotNull(fTargetMethodBinding);
    }
    result.merge(checkCanCreateIntermediaryMethod());
    createIntermediaryMethod();
    pm.worked(creationTicks);
    //$NON-NLS-1$
    pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions + " " + RefactoringCoreMessages.IntroduceIndirectionRefactoring_adjusting_visibility);
    result.merge(updateTargetVisibility(new NoOverrideProgressMonitor(pm, 0)));
    result.merge(updateIntermediaryVisibility(new NoOverrideProgressMonitor(pm, 0)));
    pm.worked(visibilityTicks);
    pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions);
    createChangeAndDiscardRewrite(fIntermediaryType.getCompilationUnit());
    result.merge(Checks.validateModifiesFiles(getAllFilesToModify(), getValidationContext()));
    pm.done();
    return result;
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) IncomingMemberVisibilityAdjustment(org.eclipse.jdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment) MethodOverrideTester(org.eclipse.jdt.internal.corext.util.MethodOverrideTester) MemberVisibilityAdjustor(org.eclipse.jdt.internal.corext.refactoring.structure.MemberVisibilityAdjustor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IMember(org.eclipse.jdt.core.IMember) IType(org.eclipse.jdt.core.IType) IMethod(org.eclipse.jdt.core.IMethod) TextChangeManager(org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager)

Example 85 with OperationCanceledException

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

the class IndexManager method getIndexes.

/**
     * Returns all the existing indexes for a list of index locations.
     * Note that this may trigger some indexes recreation work
     *
     * @param locations
     *         The list of of the index files path
     * @return The corresponding indexes list.
     */
public Index[] getIndexes(IndexLocation[] locations, IProgressMonitor progressMonitor) {
    // acquire the in-memory indexes on the fly
    int length = locations.length;
    Index[] locatedIndexes = new Index[length];
    int count = 0;
    if (this.javaLikeNamesChanged) {
        this.javaLikeNamesChanged = hasJavaLikeNamesChanged();
    }
    for (int i = 0; i < length; i++) {
        if (progressMonitor != null && progressMonitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        // may trigger some index recreation work
        IndexLocation indexLocation = locations[i];
        Index index = getIndex(indexLocation);
        if (index == null) {
            // only need containerPath if the index must be built
            IPath containerPath = (IPath) this.indexLocations.keyForValue(indexLocation);
            if (containerPath != null) {
                // sanity check
                index = getIndex(containerPath, indexLocation, true, /*reuse index file*/
                false);
                if (index != null && this.javaLikeNamesChanged && !index.isIndexForJar()) {
                    // When a change in java like names extension has been detected, all
                    // non jar files indexes (i.e. containing sources) need to be rebuilt.
                    // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=286379
                    File indexFile = index.getIndexFile();
                    if (indexFile.exists()) {
                        if (DEBUG)
                            //$NON-NLS-1$
                            Util.verbose("Change in javaLikeNames - removing index file for " + containerPath);
                        indexFile.delete();
                    }
                    this.indexes.put(indexLocation, null);
                    rebuildIndex(indexLocation, containerPath);
                    index = null;
                }
            } else {
                if (indexLocation.isParticipantIndex() && indexLocation.exists()) {
                    // the index belongs to non-jdt search participant
                    try {
                        IPath container = getParticipantsContainer(indexLocation);
                        if (container != null) {
                            index = new Index(indexLocation, container.toOSString(), true);
                            this.indexes.put(indexLocation, index);
                        }
                    } catch (IOException e) {
                    // ignore
                    }
                }
            }
        }
        if (index != null)
            // only consider indexes which are ready
            locatedIndexes[count++] = index;
    }
    if (this.javaLikeNamesChanged) {
        writeJavaLikeNamesFile();
        this.javaLikeNamesChanged = false;
    }
    if (count < length) {
        System.arraycopy(locatedIndexes, 0, locatedIndexes = new Index[count], 0, count);
    }
    return locatedIndexes;
}
Also used : IPath(org.eclipse.core.runtime.IPath) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) FileIndexLocation(org.eclipse.jdt.internal.core.index.FileIndexLocation) IndexLocation(org.eclipse.jdt.internal.core.index.IndexLocation) DiskIndex(org.eclipse.jdt.internal.core.index.DiskIndex) Index(org.eclipse.jdt.internal.core.index.Index) IOException(java.io.IOException) IFile(org.eclipse.core.resources.IFile) File(java.io.File)

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