Search in sources :

Example 1 with IField

use of org.eclipse.jdt.core.IField in project che by eclipse.

the class RenameTypeProcessor method initializeSimilarElementsRenameProcessors.

// --------- Similar names
/**
	 * Creates and initializes the refactoring processors for similarly named elements
	 * @param progressMonitor progress monitor
	 * @param context context
	 * @return status
	 * @throws CoreException should not happen
	 */
private RefactoringStatus initializeSimilarElementsRenameProcessors(IProgressMonitor progressMonitor, CheckConditionsContext context) throws CoreException {
    Assert.isNotNull(fPreloadedElementToName);
    Assert.isNotNull(fPreloadedElementToSelection);
    final RefactoringStatus status = new RefactoringStatus();
    final Set<IMethod> handledTopLevelMethods = new HashSet<IMethod>();
    final Set<Warning> warnings = new HashSet<Warning>();
    final List<RefactoringProcessor> processors = new ArrayList<RefactoringProcessor>();
    fFinalSimilarElementToName = new HashMap<IJavaElement, String>();
    CompilationUnit currentResolvedCU = null;
    ICompilationUnit currentCU = null;
    int current = 0;
    final int max = fPreloadedElementToName.size();
    //$NON-NLS-1$
    progressMonitor.beginTask("", max * 3);
    progressMonitor.setTaskName(RefactoringCoreMessages.RenameTypeProcessor_checking_similarly_named_declarations_refactoring_conditions);
    for (Iterator<IJavaElement> iter = fPreloadedElementToName.keySet().iterator(); iter.hasNext(); ) {
        final IJavaElement element = iter.next();
        current++;
        progressMonitor.worked(3);
        // not selected? -> skip
        if (!(fPreloadedElementToSelection.get(element)).booleanValue())
            continue;
        // already registered? (may happen with overridden methods) -> skip
        if (fFinalSimilarElementToName.containsKey(element))
            continue;
        // CompilationUnit changed? (note: fPreloadedElementToName is sorted by CompilationUnit)
        ICompilationUnit newCU = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (!newCU.equals(currentCU)) {
            checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
            if (status.hasFatalError())
                return status;
            // reset values
            currentResolvedCU = null;
            currentCU = newCU;
            processors.clear();
        }
        final String newName = fPreloadedElementToName.get(element);
        RefactoringProcessor processor = null;
        if (element instanceof ILocalVariable) {
            final ILocalVariable currentLocal = (ILocalVariable) element;
            if (currentResolvedCU == null)
                currentResolvedCU = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(currentCU, true);
            processor = createLocalRenameProcessor(currentLocal, newName, currentResolvedCU);
            if (status.hasFatalError())
                return status;
            fFinalSimilarElementToName.put(currentLocal, newName);
        }
        if (element instanceof IField) {
            final IField currentField = (IField) element;
            processor = createFieldRenameProcessor(currentField, newName);
            status.merge(checkForConflictingRename(currentField, newName));
            if (status.hasFatalError())
                return status;
            fFinalSimilarElementToName.put(currentField, newName);
        }
        if (element instanceof IMethod) {
            IMethod currentMethod = (IMethod) element;
            if (MethodChecks.isVirtual(currentMethod)) {
                final IType declaringType = currentMethod.getDeclaringType();
                ITypeHierarchy hierarchy = null;
                if (!declaringType.isInterface())
                    hierarchy = declaringType.newTypeHierarchy(new NullProgressMonitor());
                final IMethod topmost = MethodChecks.getTopmostMethod(currentMethod, hierarchy, new NullProgressMonitor());
                if (topmost != null)
                    currentMethod = topmost;
                if (handledTopLevelMethods.contains(currentMethod))
                    continue;
                handledTopLevelMethods.add(currentMethod);
                final IMethod[] ripples = RippleMethodFinder2.getRelatedMethods(currentMethod, new NullProgressMonitor(), null);
                if (checkForWarnings(warnings, newName, ripples))
                    continue;
                status.merge(checkForConflictingRename(ripples, newName));
                if (status.hasFatalError())
                    return status;
                processor = createVirtualMethodRenameProcessor(currentMethod, newName, ripples, hierarchy);
                fFinalSimilarElementToName.put(currentMethod, newName);
                for (int i = 0; i < ripples.length; i++) {
                    fFinalSimilarElementToName.put(ripples[i], newName);
                }
            } else {
                status.merge(checkForConflictingRename(new IMethod[] { currentMethod }, newName));
                if (status.hasFatalError())
                    break;
                fFinalSimilarElementToName.put(currentMethod, newName);
                processor = createNonVirtualMethodRenameProcessor(currentMethod, newName);
            }
        }
        progressMonitor.subTask(Messages.format(RefactoringCoreMessages.RenameTypeProcessor_progress_current_total, new Object[] { String.valueOf(current), String.valueOf(max) }));
        status.merge(processor.checkInitialConditions(new NoOverrideProgressMonitor(progressMonitor, 1)));
        if (status.hasFatalError())
            return status;
        status.merge(processor.checkFinalConditions(new NoOverrideProgressMonitor(progressMonitor, 1), context));
        if (status.hasFatalError())
            return status;
        processors.add(processor);
        progressMonitor.worked(1);
        if (progressMonitor.isCanceled())
            throw new OperationCanceledException();
    }
    // check last CU
    checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
    status.merge(addWarnings(warnings));
    progressMonitor.done();
    return status;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IType(org.eclipse.jdt.core.IType) ILocalVariable(org.eclipse.jdt.core.ILocalVariable) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) IMethod(org.eclipse.jdt.core.IMethod) HashSet(java.util.HashSet) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IField(org.eclipse.jdt.core.IField) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) RefactoringProcessor(org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor)

Example 2 with IField

use of org.eclipse.jdt.core.IField in project che by eclipse.

the class RenameTypeProcessor method addSimilarElementsTextualUpdates.

// ----------- Edit creation -----------
/**
	 * Updates textual matches for fields.
	 *
	 * Strategy for matching text matches: Match and replace all fully qualified
	 * field names, but non-qualified field names only iff there are no fields
	 * which have the same original, but a different new name. Don't add java
	 * references; duplicate edits may be created but do not matter.
	 * @param manager text change manager
	 * @param monitor progress monitor
	 * @throws CoreException if updating failed
	 */
private void addSimilarElementsTextualUpdates(TextChangeManager manager, IProgressMonitor monitor) throws CoreException {
    final Map<String, String> simpleNames = new HashMap<String, String>();
    final List<String> forbiddenSimpleNames = new ArrayList<String>();
    for (Iterator<IJavaElement> iter = fFinalSimilarElementToName.keySet().iterator(); iter.hasNext(); ) {
        final IJavaElement element = iter.next();
        if (element instanceof IField) {
            if (forbiddenSimpleNames.contains(element.getElementName()))
                continue;
            final String registeredNewName = simpleNames.get(element.getElementName());
            final String newNameToCheck = fFinalSimilarElementToName.get(element);
            if (registeredNewName == null)
                simpleNames.put(element.getElementName(), newNameToCheck);
            else if (!registeredNewName.equals(newNameToCheck))
                forbiddenSimpleNames.add(element.getElementName());
        }
    }
    for (Iterator<IJavaElement> iter = fFinalSimilarElementToName.keySet().iterator(); iter.hasNext(); ) {
        final IJavaElement element = iter.next();
        if (element instanceof IField) {
            final IField field = (IField) element;
            final String newName = fFinalSimilarElementToName.get(field);
            TextMatchUpdater.perform(monitor, RefactoringScopeFactory.create(field), field.getElementName(), field.getDeclaringType().getFullyQualifiedName(), newName, manager, new SearchResultGroup[0], forbiddenSimpleNames.contains(field.getElementName()));
        }
    }
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IField(org.eclipse.jdt.core.IField)

Example 3 with IField

use of org.eclipse.jdt.core.IField in project che by eclipse.

the class RenameTypeProcessor method initializeReferences.

/**
	 * Initializes the references to the type and the similarly named elements. This
	 * method creates both the fReferences and the fPreloadedElementToName
	 * fields.
	 *
	 * May be called from the UI.
	 * @param monitor progress monitor
	 * @return initialization status
	 * @throws JavaModelException some fundamental error with the underlying model
	 * @throws OperationCanceledException if user canceled the task
	 *
	 */
public RefactoringStatus initializeReferences(IProgressMonitor monitor) throws JavaModelException, OperationCanceledException {
    Assert.isNotNull(fType);
    Assert.isNotNull(getNewElementName());
    if (fReferences != null && (getNewElementName().equals(fCachedNewName)) && (fCachedRenameSimilarElements == getUpdateSimilarDeclarations()) && (fCachedRenamingStrategy == fRenamingStrategy))
        return fCachedRefactoringStatus;
    fCachedNewName = getNewElementName();
    fCachedRenameSimilarElements = fUpdateSimilarElements;
    fCachedRenamingStrategy = fRenamingStrategy;
    fCachedRefactoringStatus = new RefactoringStatus();
    try {
        SearchPattern pattern = SearchPattern.createPattern(fType, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
        String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(fType.getElementName()));
        ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
        fReferences = RefactoringSearchEngine.search(pattern, RefactoringScopeFactory.create(fType, true, false), new TypeOccurrenceCollector(fType, binaryRefs), monitor, fCachedRefactoringStatus);
        binaryRefs.addErrorIfNecessary(fCachedRefactoringStatus);
        fReferences = Checks.excludeCompilationUnits(fReferences, fCachedRefactoringStatus);
        fPreloadedElementToName = new LinkedHashMap<IJavaElement, String>();
        fPreloadedElementToSelection = new HashMap<IJavaElement, Boolean>();
        final String unQualifiedTypeName = fType.getElementName();
        //$NON-NLS-1$
        monitor.beginTask("", fReferences.length);
        if (getUpdateSimilarDeclarations()) {
            RenamingNameSuggestor sugg = new RenamingNameSuggestor(fRenamingStrategy);
            for (int i = 0; i < fReferences.length; i++) {
                final ICompilationUnit cu = fReferences[i].getCompilationUnit();
                if (cu == null)
                    continue;
                final SearchMatch[] results = fReferences[i].getSearchResults();
                for (int j = 0; j < results.length; j++) {
                    if (!(results[j] instanceof TypeReferenceMatch))
                        continue;
                    final TypeReferenceMatch match = (TypeReferenceMatch) results[j];
                    final List<IJavaElement> matches = new ArrayList<IJavaElement>();
                    if (match.getLocalElement() != null) {
                        if (match.getLocalElement() instanceof ILocalVariable) {
                            matches.add(match.getLocalElement());
                        }
                    // else don't update (e.g. match in type parameter, annotation, ...)
                    } else {
                        matches.add((IJavaElement) match.getElement());
                    }
                    final IJavaElement[] others = match.getOtherElements();
                    if (others != null)
                        matches.addAll(Arrays.asList(others));
                    for (Iterator<IJavaElement> iter = matches.iterator(); iter.hasNext(); ) {
                        final IJavaElement element = iter.next();
                        if (!(element instanceof IMethod) && !(element instanceof IField) && !(element instanceof ILocalVariable))
                            continue;
                        if (!isInDeclaredType(match.getOffset(), element))
                            continue;
                        if (element instanceof IField) {
                            final IField currentField = (IField) element;
                            final String newFieldName = sugg.suggestNewFieldName(currentField.getJavaProject(), currentField.getElementName(), Flags.isStatic(currentField.getFlags()), unQualifiedTypeName, getNewElementName());
                            if (newFieldName != null)
                                fPreloadedElementToName.put(currentField, newFieldName);
                        } else if (element instanceof IMethod) {
                            final IMethod currentMethod = (IMethod) element;
                            addMethodRename(unQualifiedTypeName, sugg, currentMethod);
                        } else if (element instanceof ILocalVariable) {
                            final ILocalVariable currentLocal = (ILocalVariable) element;
                            final boolean isParameter;
                            if (currentLocal.isParameter()) {
                                addMethodRename(unQualifiedTypeName, sugg, (IMethod) currentLocal.getParent());
                                isParameter = true;
                            } else
                                isParameter = false;
                            final String newLocalName = sugg.suggestNewLocalName(currentLocal.getJavaProject(), currentLocal.getElementName(), isParameter, unQualifiedTypeName, getNewElementName());
                            if (newLocalName != null)
                                fPreloadedElementToName.put(currentLocal, newLocalName);
                        }
                    }
                }
                if (monitor.isCanceled())
                    throw new OperationCanceledException();
            }
        }
        for (Iterator<IJavaElement> iter = fPreloadedElementToName.keySet().iterator(); iter.hasNext(); ) {
            IJavaElement element = iter.next();
            fPreloadedElementToSelection.put(element, Boolean.TRUE);
        }
        fPreloadedElementToNameDefault = new LinkedHashMap<IJavaElement, String>(fPreloadedElementToName);
    } catch (OperationCanceledException e) {
        fReferences = null;
        fPreloadedElementToName = null;
        throw new OperationCanceledException();
    }
    return fCachedRefactoringStatus;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IField(org.eclipse.jdt.core.IField) ILocalVariable(org.eclipse.jdt.core.ILocalVariable) ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) SearchPattern(org.eclipse.jdt.core.search.SearchPattern) IMethod(org.eclipse.jdt.core.IMethod) TypeReferenceMatch(org.eclipse.jdt.core.search.TypeReferenceMatch)

Example 4 with IField

use of org.eclipse.jdt.core.IField in project che by eclipse.

the class RenameEnumConstProcessor method createRefactoringDescriptor.

@Override
protected RenameJavaElementDescriptor createRefactoringDescriptor() {
    final IField field = getField();
    String project = null;
    IJavaProject javaProject = field.getJavaProject();
    if (javaProject != null)
        project = javaProject.getElementName();
    int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE;
    final IType declaring = field.getDeclaringType();
    try {
        if (!Flags.isPrivate(declaring.getFlags()))
            flags |= RefactoringDescriptor.MULTI_CHANGE;
        if (declaring.isAnonymous() || declaring.isLocal())
            flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
    } catch (JavaModelException exception) {
        JavaPlugin.log(exception);
    }
    final String description = Messages.format(RefactoringCoreMessages.RenameEnumConstProcessor_descriptor_description_short, BasicElementLabels.getJavaElementName(fField.getElementName()));
    final String header = Messages.format(RefactoringCoreMessages.RenameEnumConstProcessor_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(field.getElementName()), JavaElementLabels.getElementLabel(field.getParent(), JavaElementLabels.ALL_FULLY_QUALIFIED), BasicElementLabels.getJavaElementName(getNewElementName()) });
    final String comment = new JDTRefactoringDescriptorComment(project, this, header).asString();
    final RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_ENUM_CONSTANT);
    descriptor.setProject(project);
    descriptor.setDescription(description);
    descriptor.setComment(comment);
    descriptor.setFlags(flags);
    descriptor.setJavaElement(field);
    descriptor.setNewName(getNewElementName());
    descriptor.setUpdateReferences(fUpdateReferences);
    descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches);
    return descriptor;
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) IJavaProject(org.eclipse.jdt.core.IJavaProject) IField(org.eclipse.jdt.core.IField) RenameJavaElementDescriptor(org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor) IType(org.eclipse.jdt.core.IType) JDTRefactoringDescriptorComment(org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment)

Example 5 with IField

use of org.eclipse.jdt.core.IField in project che by eclipse.

the class RenameFieldProcessor method checkNestedHierarchy.

private RefactoringStatus checkNestedHierarchy(IType type) throws CoreException {
    IType[] nestedTypes = type.getTypes();
    if (nestedTypes == null)
        return null;
    RefactoringStatus result = new RefactoringStatus();
    for (int i = 0; i < nestedTypes.length; i++) {
        IField otherField = nestedTypes[i].getField(getNewElementName());
        if (otherField.exists()) {
            String msg = Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_hiding, new String[] { BasicElementLabels.getJavaElementName(fField.getElementName()), BasicElementLabels.getJavaElementName(getNewElementName()), BasicElementLabels.getJavaElementName(nestedTypes[i].getFullyQualifiedName('.')) });
            result.addWarning(msg, JavaStatusContext.create(otherField));
        }
        result.merge(checkNestedHierarchy(nestedTypes[i]));
    }
    return result;
}
Also used : RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IField(org.eclipse.jdt.core.IField) IType(org.eclipse.jdt.core.IType)

Aggregations

IField (org.eclipse.jdt.core.IField)47 IType (org.eclipse.jdt.core.IType)30 IMethod (org.eclipse.jdt.core.IMethod)15 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)15 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)14 IJavaElement (org.eclipse.jdt.core.IJavaElement)14 ArrayList (java.util.ArrayList)13 RenameJavaElementDescriptor (org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor)9 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)6 Test (org.junit.Test)6 List (java.util.List)5 ILocalVariable (org.eclipse.jdt.core.ILocalVariable)5 JavaModelException (org.eclipse.jdt.core.JavaModelException)5 RenameArguments (org.eclipse.ltk.core.refactoring.participants.RenameArguments)5 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)4 IJavaProject (org.eclipse.jdt.core.IJavaProject)4 IMember (org.eclipse.jdt.core.IMember)4 ISourceRange (org.eclipse.jdt.core.ISourceRange)4 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)4 Field (org.eclipse.che.ide.ext.java.shared.dto.model.Field)3