Java Code Examples for org.eclipse.ltk.core.refactoring.RefactoringStatus#addError()

The following examples show how to use org.eclipse.ltk.core.refactoring.RefactoringStatus#addError() . 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: XtendRenameStrategy.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public RefactoringStatus validateNewName(String newName) {
	if (grammarAccess.getFunctionIDRule().getName().equals(nameRuleName)) {
		if (operatorMapping.getOperator(QualifiedName.create(newName)) != null) {
			RefactoringStatus status = new RefactoringStatus();
			if(nameRuleName != null) {
				try {
					String value = getNameAsValue(newName, grammarAccess.getValidIDRule().getName());
					String text = getNameAsText(value, grammarAccess.getValidIDRule().getName());
					if(!equal(text, newName)) {
						status.addError("Illegal name: '" + newName + "'. Consider using '" + text + "' instead.");
					}
				} catch(ValueConverterException vce) {
					status.addFatalError("Illegal name: " + notNull(vce.getMessage()));
				}
			}
			return status;
		}
	} 
	return super.validateNewName(newName);
}
 
Example 2
Source File: NewFeatureNameUtil.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
public void checkNewFeatureName(String newFeatureName, boolean isLookupInScope, RefactoringStatus status) {
	if (isEmpty(newFeatureName)) { 
		status.addFatalError("Choose a name");
		return;
	}
	try {
		Object value = valueConverterService.toValue(newFeatureName, "ValidID", null);
		valueConverterService.toString(value, "ValidID");
	} catch(ValueConverterException exc) {
		status.addFatalError(exc.getMessage());
	}
	if (Character.isUpperCase(newFeatureName.charAt(0))) 
		status.addError("Discouraged name '" + newFeatureName + "'. Name should start with a lowercase letter. ");
	if (isKeyword(newFeatureName)) 
		status.addFatalError("'" + newFeatureName + "' is keyword.");
	@SuppressWarnings("restriction")
	Class<?> asPrimitive = org.eclipse.xtext.common.types.access.impl.Primitives.forName(newFeatureName);
	if(asPrimitive != null) 
		status.addFatalError("'" + newFeatureName + "' is reserved.");
	if (isLookupInScope && featureCallScope != null && isAlreadyDefined(newFeatureName)) 
		status.addError("The name '" + newFeatureName + "' is already defined in this scope.");
}
 
Example 3
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks if the new method is already used in the given type.
 * @param type
 * @param methodName
 * @param parameters
 * @return the status
 */
public static RefactoringStatus checkMethodInType(ITypeBinding type, String methodName, ITypeBinding[] parameters) {
	RefactoringStatus result= new RefactoringStatus();
	IMethodBinding method= org.eclipse.jdt.internal.corext.dom.Bindings.findMethodInType(type, methodName, parameters);
	if (method != null) {
		if (method.isConstructor()) {
			result.addWarning(Messages.format(RefactoringCoreMessages.Checks_methodName_constructor,
					new Object[] { BasicElementLabels.getJavaElementName(type.getName()) }));
		} else {
			result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_exists,
					new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(type.getName()) }),
					JavaStatusContext.create(method));
		}
	}
	return result;
}
 
Example 4
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public RefactoringStatus validateFields() {
	RefactoringStatus status= new RefactoringStatus();
	Field[] fields= fDescriptor.getFields();
	Set<String> names= new HashSet<String>();
	for (int i= 0; i < fields.length; i++) {
		Field field= fields[i];
		if (field.isCreateField()) {
			if (names.contains(field.getNewFieldName())) {
				status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_duplicate_field_name, BasicElementLabels.getJavaElementName(field.getNewFieldName())));
			}
			names.add(field.getNewFieldName());
			status.merge(Checks.checkFieldName(field.getNewFieldName(), fDescriptor.getType()));
		}
	}
	if (names.size() == 0) {
		status.addError(RefactoringCoreMessages.ExtractClassRefactoring_error_msg_one_field);
	}
	validateFieldNames(status, fDescriptor.getFieldName(), fDescriptor.getType());
	return status;
}
 
Example 5
Source File: RenameCompilationUnitProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
	try{
		if (fWillRenameType && (!fCu.isStructureKnown())){
			RefactoringStatus result1= new RefactoringStatus();

			RefactoringStatus result2= new RefactoringStatus();
			result2.merge(Checks.checkCompilationUnitNewName(fCu, removeFileNameExtension(getNewElementName())));
			if (result2.hasFatalError()) {
				result1.addError(Messages.format(RefactoringCoreMessages.RenameCompilationUnitRefactoring_not_parsed_1, BasicElementLabels.getFileName(fCu)));
			} else {
				result1.addError(Messages.format(RefactoringCoreMessages.RenameCompilationUnitRefactoring_not_parsed, BasicElementLabels.getFileName(fCu)));
			}
			result1.merge(result2);
		}

		if (fWillRenameType) {
			return fRenameTypeProcessor.checkFinalConditions(pm, context);
		} else {
			return Checks.checkCompilationUnitNewName(fCu, removeFileNameExtension(getNewElementName()));
		}
	} finally{
		pm.done();
	}
}
 
Example 6
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks if the parameter names are valid.
 * @return validation status
 */
public RefactoringStatus checkParameterNames() {
	RefactoringStatus result= new RefactoringStatus();
	for (Iterator<ParameterInfo> iter= fParameterInfos.iterator(); iter.hasNext();) {
		ParameterInfo parameter= iter.next();
		result.merge(Checks.checkIdentifier(parameter.getNewName(), fCUnit));
		for (Iterator<ParameterInfo> others= fParameterInfos.iterator(); others.hasNext();) {
			ParameterInfo other= others.next();
			if (parameter != other && other.getNewName().equals(parameter.getNewName())) {
				result.addError(Messages.format(
					RefactoringCoreMessages.ExtractMethodRefactoring_error_sameParameter,
					BasicElementLabels.getJavaElementName(other.getNewName())));
				return result;
			}
		}
		if (parameter.isRenamed() && fUsedNames.contains(parameter.getNewName())) {
			result.addError(Messages.format(
				RefactoringCoreMessages.ExtractMethodRefactoring_error_nameInUse,
				BasicElementLabels.getJavaElementName(parameter.getNewName())));
			return result;
		}
	}
	return result;
}
 
Example 7
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkAccessedTypes(IType[] subclasses, IProgressMonitor pm) throws JavaModelException {
	RefactoringStatus result= new RefactoringStatus();
	IType[] accessedTypes= getTypesReferencedInMovedMembers(pm);
	for (int index= 0; index < subclasses.length; index++) {
		IType targetClass= subclasses[index];
		ITypeHierarchy targetSupertypes= targetClass.newSupertypeHierarchy(null);
		for (int offset= 0; offset < accessedTypes.length; offset++) {
			IType type= accessedTypes[offset];
			if (!canBeAccessedFrom(type, targetClass, targetSupertypes)) {
				String message= Messages.format(RefactoringCoreMessages.PushDownRefactoring_type_not_accessible, new String[] { JavaElementLabels.getTextLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(targetClass, JavaElementLabels.ALL_FULLY_QUALIFIED) });
				result.addError(message, JavaStatusContext.create(type));
			}
		}
	}
	pm.done();
	return result;
}
 
Example 8
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkAccessedFields(IType[] subclasses, IProgressMonitor pm) throws JavaModelException {
	RefactoringStatus result= new RefactoringStatus();
	IMember[] membersToPushDown= MemberActionInfo.getMembers(getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass());
	List<IMember> pushedDownList= Arrays.asList(membersToPushDown);
	IField[] accessedFields= ReferenceFinderUtil.getFieldsReferencedIn(membersToPushDown, pm);
	for (int i= 0; i < subclasses.length; i++) {
		IType targetClass= subclasses[i];
		ITypeHierarchy targetSupertypes= targetClass.newSupertypeHierarchy(null);
		for (int j= 0; j < accessedFields.length; j++) {
			IField field= accessedFields[j];
			boolean isAccessible= pushedDownList.contains(field) || canBeAccessedFrom(field, targetClass, targetSupertypes) || Flags.isEnum(field.getFlags());
			if (!isAccessible) {
				String message= Messages.format(RefactoringCoreMessages.PushDownRefactoring_field_not_accessible, new String[] { JavaElementLabels.getTextLabel(field, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(targetClass, JavaElementLabels.ALL_FULLY_QUALIFIED) });
				result.addError(message, JavaStatusContext.create(field));
			}
		}
	}
	pm.done();
	return result;
}
 
Example 9
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private RefactoringStatus checkTypesInCompilationUnit() {
	RefactoringStatus result = new RefactoringStatus();
	if (!Checks.isTopLevel(fType)) { //the other case checked in checkTypesInPackage
		IType siblingType = fType.getDeclaringType().getType(getNewElementName());
		if (siblingType.exists()) {
			String msg = Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_member_type_exists,
					new String[] { getNewElementLabel(), BasicElementLabels.getJavaElementName(fType.getDeclaringType().getFullyQualifiedName('.')) });
			result.addError(msg, JavaStatusContext.create(siblingType));
		}
	}
	return result;
}
 
Example 10
Source File: InlineMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void removeNestedCalls(RefactoringStatus status, ICompilationUnit unit, ASTNode[] parents, ASTNode[] invocations, int index) {
	ASTNode invocation= invocations[index];
	for (int i= 0; i < parents.length; i++) {
		ASTNode parent= parents[i];
		while (parent != null) {
			if (parent == invocation) {
				status.addError(RefactoringCoreMessages.InlineMethodRefactoring_nestedInvocation,
					JavaStatusContext.create(unit, parent));
				invocations[index]= null;
			}
			parent= parent.getParent();
		}
	}
}
 
Example 11
Source File: RenameTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkTypesInCompilationUnit() {
	RefactoringStatus result= new RefactoringStatus();
	if (! Checks.isTopLevel(fType)){ //the other case checked in checkTypesInPackage
		IType siblingType= fType.getDeclaringType().getType(getNewElementName());
		if (siblingType.exists()){
			String msg= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_member_type_exists,
				new String[] { getNewElementLabel(), BasicElementLabels.getJavaElementName(fType.getDeclaringType().getFullyQualifiedName('.'))});
			result.addError(msg, JavaStatusContext.create(siblingType));
		}
	}
	return result;
}
 
Example 12
Source File: RenameFieldProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkNewAccessor(IMethod existingAccessor, String newAccessorName) throws CoreException{
	RefactoringStatus result= new RefactoringStatus();
	IMethod accessor= JavaModelUtil.findMethod(newAccessorName, existingAccessor.getParameterTypes(), false, fField.getDeclaringType());
	if (accessor == null || !accessor.exists())
		return null;

	String message= Messages.format(RefactoringCoreMessages.RenameFieldRefactoring_already_exists,
			new String[]{JavaElementUtil.createMethodSignature(accessor), BasicElementLabels.getJavaElementName(fField.getDeclaringType().getFullyQualifiedName('.'))});
	result.addError(message, JavaStatusContext.create(accessor));
	return result;
}
 
Example 13
Source File: RefactoringAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static RefactoringStatus reportProblemNodes(String modifiedWorkingCopySource, SimpleName[] problemNodes) {
	RefactoringStatus result= new RefactoringStatus();
	for (int i= 0; i < problemNodes.length; i++) {
		RefactoringStatusContext context= new JavaStringStatusContext(modifiedWorkingCopySource, SourceRangeFactory.create(problemNodes[i]));
		result.addError(Messages.format(RefactoringCoreMessages.RefactoringAnalyzeUtil_name_collision, BasicElementLabels.getJavaElementName(problemNodes[i].getIdentifier())), context);
	}
	return result;
}
 
Example 14
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkReferencesToPushedDownMembers(IProgressMonitor monitor) throws JavaModelException {
	List<IMember> fields= new ArrayList<IMember>(fMemberInfos.length);
	for (int index= 0; index < fMemberInfos.length; index++) {
		MemberActionInfo info= fMemberInfos[index];
		if (info.isToBePushedDown())
			fields.add(info.getMember());
	}
	IMember[] membersToPush= fields.toArray(new IMember[fields.size()]);
	RefactoringStatus result= new RefactoringStatus();
	List<IMember> movedMembers= Arrays.asList(MemberActionInfo.getMembers(getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass()));
	monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_check_references, membersToPush.length);
	for (int index= 0; index < membersToPush.length; index++) {
		IMember member= membersToPush[index];
		String label= createLabel(member);
		IJavaElement[] referencing= getReferencingElementsFromSameClass(member, new SubProgressMonitor(monitor, 1), result);
		for (int offset= 0; offset < referencing.length; offset++) {
			IJavaElement element= referencing[offset];
			if (movedMembers.contains(element))
				continue;
			if (!(element instanceof IMember))
				continue;
			IMember referencingMember= (IMember) element;
			Object[] keys= { label, createLabel(referencingMember) };
			String msg= Messages.format(RefactoringCoreMessages.PushDownRefactoring_referenced, keys);
			result.addError(msg, JavaStatusContext.create(referencingMember));
		}
	}
	monitor.done();
	return result;
}
 
Example 15
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void checkMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding returnType, ITypeBinding[] parameters, RefactoringStatus result, boolean reUseMethod) {
	IMethodBinding method= Bindings.findMethodInHierarchy(type, methodName, parameters);
	if (method != null) {
		boolean returnTypeClash= false;
		ITypeBinding methodReturnType= method.getReturnType();
		if (returnType != null && methodReturnType != null) {
			String returnTypeKey= returnType.getKey();
			String methodReturnTypeKey= methodReturnType.getKey();
			if (returnTypeKey == null && methodReturnTypeKey == null) {
				returnTypeClash= returnType != methodReturnType;
			} else if (returnTypeKey != null && methodReturnTypeKey != null) {
				returnTypeClash= !returnTypeKey.equals(methodReturnTypeKey);
			}
		}
		ITypeBinding dc= method.getDeclaringClass();
		if (returnTypeClash) {
			result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_returnTypeClash,
				new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}),
				JavaStatusContext.create(method));
		} else {
			if (!reUseMethod)
				result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides,
						new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}),
					JavaStatusContext.create(method));
		}
	} else {
		if (reUseMethod){
			result.addError(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_nosuchmethod_status_fatalError,
					BasicElementLabels.getJavaElementName(methodName)),
					JavaStatusContext.create(method));
		}
	}
}
 
Example 16
Source File: CombinedJvmJdtRenameProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context)
		throws CoreException, OperationCanceledException {
	SubMonitor monitor = SubMonitor.convert(pm, jvmElements2jdtProcessors.size() + 1);
	RefactoringStatus status = super.checkFinalConditions(monitor.newChild(1), context);
	ResourceSet resourceSet = getResourceSet(getRenameElementContext());
	getRenameArguments().getRenameStrategy().applyDeclarationChange(getNewName(), resourceSet);
	for (Iterator<Map.Entry<URI, JavaRenameProcessor>> entryIterator = jvmElements2jdtProcessors.entrySet().iterator();
			entryIterator.hasNext();) {
		Map.Entry<URI, JavaRenameProcessor> jvmElement2jdtRefactoring = entryIterator.next();
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
		URI renamedJvmElementURI = getRenameArguments().getNewElementURI(jvmElement2jdtRefactoring.getKey());
		EObject renamedJvmElement = resourceSet.getEObject(renamedJvmElementURI, false);
		if (!(renamedJvmElement instanceof JvmIdentifiableElement) || renamedJvmElement.eIsProxy()) {
			status.addError("Cannot find inferred JVM element after refactoring.");
		} else {
			JavaRenameProcessor jdtRefactoring = jvmElement2jdtRefactoring.getValue();
			String newName = ((JvmIdentifiableElement) renamedJvmElement).getSimpleName();
			if(jdtRefactoring.getCurrentElementName().equals(newName)) {
				entryIterator.remove();
			} else {
				jdtRefactoring.setNewElementName(newName);
				status.merge(jdtRefactoring.checkFinalConditions(monitor.newChild(1), context));
			}
		}
	}
	getRenameArguments().getRenameStrategy().revertDeclarationChange(resourceSet);
	return status;
}
 
Example 17
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private FieldDeclaration performFieldRewrite(IType type, ParameterObjectFactory pof, RefactoringStatus status) throws CoreException {
	fBaseCURewrite= new CompilationUnitRewrite(type.getCompilationUnit());
	SimpleName name= (SimpleName) NodeFinder.perform(fBaseCURewrite.getRoot(), type.getNameRange());
	TypeDeclaration typeNode= (TypeDeclaration) ASTNodes.getParent(name, ASTNode.TYPE_DECLARATION);
	ASTRewrite rewrite= fBaseCURewrite.getASTRewrite();
	int modifier= Modifier.PRIVATE;
	TextEditGroup removeFieldGroup= fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_remove_field);
	FieldDeclaration lastField= null;
	initializeDeclaration(typeNode);
	for (Iterator<FieldInfo> iter= fVariables.values().iterator(); iter.hasNext();) {
		FieldInfo pi= iter.next();
		if (isCreateField(pi)) {
			VariableDeclarationFragment vdf= pi.declaration;
			FieldDeclaration parent= (FieldDeclaration) vdf.getParent();
			if (lastField == null)
				lastField= parent;
			else if (lastField.getStartPosition() < parent.getStartPosition())
				lastField= parent;

			ListRewrite listRewrite= rewrite.getListRewrite(parent, FieldDeclaration.FRAGMENTS_PROPERTY);
			removeNode(vdf, removeFieldGroup, fBaseCURewrite);
			if (listRewrite.getRewrittenList().size() == 0) {
				removeNode(parent, removeFieldGroup, fBaseCURewrite);
			}

			if (fDescriptor.isCreateTopLevel()) {
				IVariableBinding binding= vdf.resolveBinding();
				ITypeRoot typeRoot= fBaseCURewrite.getCu();
				if (binding == null || binding.getType() == null){
					status.addFatalError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_fatal_error_cannot_resolve_binding, BasicElementLabels.getJavaElementName(pi.name)), JavaStatusContext.create(typeRoot, vdf));
				} else {
					ITypeBinding typeBinding= binding.getType();
					if (Modifier.isPrivate(typeBinding.getModifiers())){
						status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_private_class, BasicElementLabels.getJavaElementName(typeBinding.getName())), JavaStatusContext.create(typeRoot, vdf));
					} else if (Modifier.isProtected(typeBinding.getModifiers())){
						ITypeBinding declaringClass= typeBinding.getDeclaringClass();
						if (declaringClass != null) {
							IPackageBinding package1= declaringClass.getPackage();
							if (package1 != null && !fDescriptor.getPackage().equals(package1.getName())){
								status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_protected_class, new String[] {BasicElementLabels.getJavaElementName(typeBinding.getName()), BasicElementLabels.getJavaElementName(fDescriptor.getPackage())}), JavaStatusContext.create(typeRoot, vdf));
							}
						}
					}
				}
			}
			Expression initializer= vdf.getInitializer();
			if (initializer != null)
				pi.initializer= initializer;
			int modifiers= parent.getModifiers();
			if (!MemberVisibilityAdjustor.hasLowerVisibility(modifiers, modifier)){
				modifier= modifiers;
			}
		}
	}
	FieldDeclaration fieldDeclaration= createParameterObjectField(pof, typeNode, modifier);
	ListRewrite bodyDeclList= rewrite.getListRewrite(typeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	if (lastField != null)
		bodyDeclList.insertAfter(fieldDeclaration, lastField, null);
	else
		bodyDeclList.insertFirst(fieldDeclaration, null);
	return fieldDeclaration;
}
 
Example 18
Source File: ReplaceRefactoring.java    From Pydev with Eclipse Public License 1.0 4 votes vote down vote up
private TextChange createFileChange(IFile file, Pattern pattern, Collection<Match> matches,
        RefactoringStatus resultingStatus, Collection<MatchGroup> matchGroups)
                throws PatternSyntaxException, CoreException {
    PositionTracker tracker = InternalSearchUI.getInstance().getPositionTracker();

    TextFileChange change = new SynchronizedTextFileChange(MessageFormat.format(
            SearchMessages.ReplaceRefactoring_group_label_change_for_file, file.getName()), file);
    change.setEdit(new MultiTextEdit());

    ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager();
    manager.connect(file.getFullPath(), LocationKind.IFILE, null);
    try {
        ITextFileBuffer textFileBuffer = manager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
        if (textFileBuffer == null) {
            resultingStatus
                    .addError(MessageFormat.format(SearchMessages.ReplaceRefactoring_error_accessing_file_buffer,
                            file.getName()));
            return null;
        }
        IDocument document = textFileBuffer.getDocument();
        String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);

        for (Iterator<Match> iterator = matches.iterator(); iterator.hasNext();) {
            Match match = iterator.next();
            int offset = match.getOffset();
            int length = match.getLength();
            Position currentPosition = tracker.getCurrentPosition(match);
            if (currentPosition != null) {
                offset = currentPosition.offset;
                if (length != currentPosition.length) {
                    resultingStatus.addError(MessageFormat.format(
                            SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
                    continue;
                }
            }

            String originalText = getOriginalText(document, offset, length);
            if (originalText == null) {
                resultingStatus.addError(MessageFormat.format(
                        SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
                continue;
            }

            String replacementString = computeReplacementString(pattern, originalText, fReplaceString,
                    lineDelimiter);
            if (replacementString == null) {
                resultingStatus.addError(MessageFormat.format(
                        SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
                continue;
            }

            ReplaceEdit replaceEdit = new ReplaceEdit(offset, length, replacementString);
            change.addEdit(replaceEdit);
            TextEditChangeGroup textEditChangeGroup = new TextEditChangeGroup(change, new TextEditGroup(
                    SearchMessages.ReplaceRefactoring_group_label_match_replace, replaceEdit));
            change.addTextEditChangeGroup(textEditChangeGroup);
            matchGroups.add(new MatchGroup(textEditChangeGroup, match));
        }
    } finally {
        manager.disconnect(file.getFullPath(), LocationKind.IFILE, null);
    }
    return change;
}
 
Example 19
Source File: RenameTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus checkConflictingTypes(IProgressMonitor pm) throws CoreException {
	RefactoringStatus result= new RefactoringStatus();
	IJavaSearchScope scope= RefactoringScopeFactory.create(fType);
	SearchPattern pattern= SearchPattern.createPattern(getNewElementName(),
			IJavaSearchConstants.TYPE, IJavaSearchConstants.ALL_OCCURRENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	ICompilationUnit[] cusWithReferencesToConflictingTypes= RefactoringSearchEngine.findAffectedCompilationUnits(pattern, scope, pm, result);
	if (cusWithReferencesToConflictingTypes.length == 0)
		return result;
	ICompilationUnit[] 	cusWithReferencesToRenamedType= getCus(fReferences);

	Set<ICompilationUnit> conflicts= getIntersection(cusWithReferencesToRenamedType, cusWithReferencesToConflictingTypes);
	if (cusWithReferencesToConflictingTypes.length > 0) {
		cus: for (ICompilationUnit cu : cusWithReferencesToConflictingTypes) {
			String packageName= fType.getPackageFragment().getElementName();
			if (((IPackageFragment) cu.getParent()).getElementName().equals(packageName)) {
				boolean hasOnDemandImport= false;
				IImportDeclaration[] imports= cu.getImports();
				for (IImportDeclaration importDecl : imports) {
					if (importDecl.isOnDemand()) {
						hasOnDemandImport= true;
					} else {
						String importName= importDecl.getElementName();
						int packageLength= importName.length() - getNewElementName().length() - 1;
						if (packageLength > 0
								&& importName.endsWith(getNewElementName())
								&& importName.charAt(packageLength) == '.') {
							continue cus; // explicit import from another package => no problem
						}
					}
				}
				if (hasOnDemandImport) {
					// the renamed type in the same package will shadow the *-imported type
					conflicts.add(cu);
				}
			}
		}
	}
	
	for (ICompilationUnit conflict : conflicts) {
		RefactoringStatusContext context= JavaStatusContext.create(conflict);
		String message= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_another_type,
			new String[] { getNewElementLabel(), BasicElementLabels.getFileName(conflict)});
		result.addError(message, context);
	}
	return result;
}
 
Example 20
Source File: ReferencesInBinaryContext.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public void addErrorIfNecessary(RefactoringStatus status) {
	if (getMatches().size() != 0) {
		status.addError(RefactoringCoreMessages.ReferencesInBinaryContext_binaryRefsNotUpdated, this);
	}
}