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

The following examples show how to use org.eclipse.ltk.core.refactoring.RefactoringStatus#hasFatalError() . 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: RenameTypeParameterProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected RefactoringStatus doCheckFinalConditions(IProgressMonitor monitor, CheckConditionsContext context) throws CoreException, OperationCanceledException {
	Assert.isNotNull(monitor);
	Assert.isNotNull(context);
	RefactoringStatus status= new RefactoringStatus();
	try {
		monitor.beginTask("", 5); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.RenameTypeParameterRefactoring_checking);
		status.merge(Checks.checkIfCuBroken(fTypeParameter.getDeclaringMember()));
		monitor.worked(1);
		if (!status.hasFatalError()) {
			status.merge(checkNewElementName(getNewElementName()));
			monitor.worked(1);
			monitor.setTaskName(RefactoringCoreMessages.RenameTypeParameterRefactoring_searching);
			status.merge(createRenameChanges(new SubProgressMonitor(monitor, 2)));
			monitor.setTaskName(RefactoringCoreMessages.RenameTypeParameterRefactoring_checking);
			if (status.hasFatalError())
				return status;
			monitor.worked(1);
		}
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 2
Source File: ExtractInterfaceProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks whether the type name is valid.
 *
 * @param name
 *            the name to check
 * @return the status of the condition checking
 */
public final RefactoringStatus checkTypeName(final String name) {
	Assert.isNotNull(name);
	try {
		final RefactoringStatus result= Checks.checkTypeName(name, fSubType);
		if (result.hasFatalError())
			return result;
		final String unitName= JavaModelUtil.getRenamedCUName(fSubType.getCompilationUnit(), name);
		result.merge(Checks.checkCompilationUnitName(unitName, fSubType));
		if (result.hasFatalError())
			return result;
		final IPackageFragment fragment= fSubType.getPackageFragment();
		if (fragment.getCompilationUnit(unitName).exists()) {
			result.addFatalError(Messages.format(RefactoringCoreMessages.ExtractInterfaceProcessor_existing_compilation_unit, new String[] { BasicElementLabels.getResourceName(unitName), JavaElementLabels.getElementLabel(fragment, JavaElementLabels.ALL_DEFAULT) }));
			return result;
		}
		result.merge(checkSuperType());
		return result;
	} catch (JavaModelException exception) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractInterfaceProcessor_internal_error);
	}
}
 
Example 3
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public RefactoringStatus checkInitialConditions(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
	try {
		monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 1);
		final RefactoringStatus status= new RefactoringStatus();
		status.merge(checkDeclaringType(new SubProgressMonitor(monitor, 1)));
		if (status.hasFatalError())
			return status;
		status.merge(checkIfMembersExist());
		if (status.hasFatalError())
			return status;
		return status;
	} finally {
		monitor.done();
	}
}
 
Example 4
Source File: ExtractConstantRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private RefactoringStatus checkExpression() throws JavaModelException {
	RefactoringStatus result = new RefactoringStatus();
	result.merge(checkExpressionBinding());
	if (result.hasFatalError()) {
		return result;
	}
	checkAllStaticFinal();

	IExpressionFragment selectedExpression = getSelectedExpression();
	Expression associatedExpression = selectedExpression.getAssociatedExpression();
	if (associatedExpression instanceof NullLiteral) {
		result.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_null_literals));
	} else if (!ConstantChecks.isLoadTimeConstant(selectedExpression)) {
		result.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_not_load_time_constant));
	} else if (associatedExpression instanceof SimpleName) {
		if (associatedExpression.getParent() instanceof QualifiedName && associatedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY
				|| associatedExpression.getParent() instanceof FieldAccess && associatedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_select_expression);
		}
	}

	return result;
}
 
Example 5
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkExpression() throws JavaModelException {
	RefactoringStatus result= new RefactoringStatus();
	result.merge(checkExpressionBinding());
	if(result.hasFatalError())
		return result;
	checkAllStaticFinal();

	IExpressionFragment selectedExpression= getSelectedExpression();
	Expression associatedExpression= selectedExpression.getAssociatedExpression();
	if (associatedExpression instanceof NullLiteral)
		result.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_null_literals));
	else if (!ConstantChecks.isLoadTimeConstant(selectedExpression))
		result.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_not_load_time_constant));
	else if (associatedExpression instanceof SimpleName) {
		if (associatedExpression.getParent() instanceof QualifiedName && associatedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY
				|| associatedExpression.getParent() instanceof FieldAccess && associatedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_select_expression);
	}

	return result;
}
 
Example 6
Source File: N4JSRenameElementProcessor.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor monitor, CheckConditionsContext context)
		throws CoreException, OperationCanceledException {
	RefactoringStatus status = new RefactoringStatus();
	status.merge(super.checkFinalConditions(monitor, context));

	if (status.hasFatalError()) {
		return status;
	}

	String newName = this.getNewName();
	EObject targetElement = this.getTargetElement();

	List<EObject> realTargetElements = TypeModelUtils.getRealElements(targetElement);
	realTargetElements.stream()
			.forEach((realTargetElement) -> status.merge(checkDuplicateName(realTargetElement, newName)));

	return status;
}
 
Example 7
Source File: MoveStaticMembersProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
	fTarget= null;
	try {
		pm.beginTask(RefactoringCoreMessages.MoveMembersRefactoring_checking, 10);

		RefactoringStatus result= new RefactoringStatus();

		fSource.clearASTAndImportRewrites();

		result.merge(checkDestinationType());
		if (result.hasFatalError())
			return result;

		result.merge(checkDestinationInsideTypeToMove());
		if (result.hasFatalError())
			return result;

		result.merge(MemberCheckUtil.checkMembersInDestinationType(fMembersToMove, fDestinationType));
		if (result.hasFatalError())
			return result;

		result.merge(checkNativeMovedMethods(new SubProgressMonitor(pm, 1)));

		if (result.hasFatalError())
			return result;

		List<ICompilationUnit> modifiedCus= new ArrayList<ICompilationUnit>();
		createChange(modifiedCus, result, new SubProgressMonitor(pm, 7));
		IFile[] changedFiles= getAllFilesToModify(modifiedCus);
		ResourceChangeChecker checker= (ResourceChangeChecker)context.getChecker(ResourceChangeChecker.class);
		for (int i= 0; i < changedFiles.length; i++) {
			checker.getDeltaFactory().change(changedFiles[i]);
		}

		return result;
	} finally {
		pm.done();
	}
}
 
Example 8
Source File: CodeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected final void checkSelectedNodes() {
	super.checkSelectedNodes();
	RefactoringStatus status= getStatus();
	if (status.hasFatalError())
		return;
	ASTNode node= getFirstSelectedNode();
	if (node instanceof ArrayInitializer) {
		status.addFatalError(RefactoringCoreMessages.CodeAnalyzer_array_initializer, JavaStatusContext.create(fCUnit, node));
	}
}
 
Example 9
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor monitor, CheckConditionsContext context) throws CoreException, OperationCanceledException {
	try {
		monitor.beginTask(RefactoringCoreMessages.PushDownRefactoring_checking, 5);
		clearCaches();
		ICompilationUnit unit= getDeclaringType().getCompilationUnit();
		if (fLayer)
			unit= unit.findWorkingCopy(fOwner);
		resetWorkingCopies(unit);
		final RefactoringStatus result= new RefactoringStatus();
		result.merge(checkMembersInDestinationClasses(new SubProgressMonitor(monitor, 1)));
		result.merge(checkElementsAccessedByModifiedMembers(new SubProgressMonitor(monitor, 1)));
		result.merge(checkReferencesToPushedDownMembers(new SubProgressMonitor(monitor, 1)));
		if (!JdtFlags.isAbstract(getDeclaringType()) && getAbstractDeclarationInfos().length != 0)
			result.merge(checkConstructorCalls(getDeclaringType(), new SubProgressMonitor(monitor, 1)));
		else
			monitor.worked(1);
		if (result.hasFatalError())
			return result;
		List<IMember> members= new ArrayList<IMember>(fMemberInfos.length);
		for (int index= 0; index < fMemberInfos.length; index++) {
			if (fMemberInfos[index].getAction() != MemberActionInfo.NO_ACTION)
				members.add(fMemberInfos[index].getMember());
		}
		fMembersToMove= members.toArray(new IMember[members.size()]);
		fChangeManager= createChangeManager(new SubProgressMonitor(monitor, 1), result);
		if (result.hasFatalError())
			return result;

		Checks.addModifiedFilesToChecker(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()), context);

		return result;
	} finally {
		monitor.done();
	}
}
 
Example 10
Source File: RefactoringExecutionStarter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void startChangeSignatureRefactoring(final IMethod method, final SelectionDispatchAction action, final Shell shell) throws JavaModelException {
	if (!RefactoringAvailabilityTester.isChangeSignatureAvailable(method))
		return;
	try {
		ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method);
		RefactoringStatus status= processor.checkInitialConditions(new NullProgressMonitor());
		if (status.hasFatalError()) {
			final RefactoringStatusEntry entry= status.getEntryMatchingSeverity(RefactoringStatus.FATAL);
			if (entry.getCode() == RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD || entry.getCode() == RefactoringStatusCodes.METHOD_DECLARED_IN_INTERFACE) {
				Object element= entry.getData();
				if (element != null) {
					String message= Messages.format(RefactoringMessages.RefactoringErrorDialogUtil_okToPerformQuestion, entry.getMessage());
					if (MessageDialog.openQuestion(shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, message)) {
						IStructuredSelection selection= new StructuredSelection(element);
						// TODO: should not hijack this
						// ModifiyParametersAction.
						// The action is set up on an editor, but we use it
						// as if it were set up on a ViewPart.
						boolean wasEnabled= action.isEnabled();
						action.selectionChanged(selection);
						if (action.isEnabled()) {
							action.run(selection);
						} else {
							MessageDialog.openInformation(shell, ActionMessages.ModifyParameterAction_problem_title, ActionMessages.ModifyParameterAction_problem_message);
						}
						action.setEnabled(wasEnabled);
					}
				}
				return;
			}
		}

		Refactoring refactoring= new ProcessorBasedRefactoring(processor);
		ChangeSignatureWizard wizard= new ChangeSignatureWizard(processor, refactoring);
		new RefactoringStarter().activate(wizard, shell, wizard.getDefaultPageTitle(), RefactoringSaveHelper.SAVE_REFACTORING);
	} catch (CoreException e) {
		ExceptionHandler.handle(e, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringMessages.RefactoringStarter_unexpected_exception);
	}
}
 
Example 11
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static RefactoringStatus checkTempName(String newName, IJavaElement context) {
	RefactoringStatus result= Checks.checkIdentifier(newName, context);
	if (result.hasFatalError())
		return result;
	if (! Checks.startsWithLowerCase(newName))
		result.addWarning(RefactoringCoreMessages.ExtractTempRefactoring_convention);
	return result;
}
 
Example 12
Source File: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private RefactoringStatus analyzeCompilationUnits() throws CoreException {
	if (fOccurrences.length == 0) {
		return null;
	}

	RefactoringStatus result= new RefactoringStatus();
	fOccurrences= Checks.excludeCompilationUnits(fOccurrences, result);
	if (result.hasFatalError()) {
		return result;
	}

	result.merge(Checks.checkCompileErrorsInAffectedFiles(fOccurrences));

	return result;
}
 
Example 13
Source File: PotentialProgrammingProblemsCleanUp.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public RefactoringStatus checkPreConditions(IJavaProject project, ICompilationUnit[] compilationUnits, IProgressMonitor monitor) throws CoreException {
	RefactoringStatus superStatus= super.checkPreConditions(project, compilationUnits, monitor);
	if (superStatus.hasFatalError())
		return superStatus;

	return PotentialProgrammingProblemsFix.checkPreConditions(project, compilationUnits, monitor,
			isEnabled(CleanUpConstants.ADD_MISSING_SERIAL_VERSION_ID) && isEnabled(CleanUpConstants.ADD_MISSING_SERIAL_VERSION_ID_GENERATED),
			isEnabled(CleanUpConstants.ADD_MISSING_SERIAL_VERSION_ID) && isEnabled(CleanUpConstants.ADD_MISSING_SERIAL_VERSION_ID_DEFAULT),
			false);
}
 
Example 14
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask("", 7); //$NON-NLS-1$

		RefactoringStatus result= Checks.validateEdit(fCu, getValidationContext());
		if (result.hasFatalError())
			return result;
		pm.worked(1);

		if (fCuRewrite == null) {
			CompilationUnit cuNode= RefactoringASTParser.parseWithASTProvider(fCu, true, new SubProgressMonitor(pm, 3));
			fCuRewrite= new CompilationUnitRewrite(fCu, cuNode);
		} else {
			pm.worked(3);
		}
		result.merge(checkSelection(new SubProgressMonitor(pm, 3)));

		if (result.hasFatalError())
			return result;

		if (isLiteralNodeSelected())
			fReplaceAllOccurrences= false;

		if (isInTypeDeclarationAnnotation(getSelectedExpression().getAssociatedNode())) {
			fVisibility= JdtFlags.VISIBILITY_STRING_PACKAGE;
		}
		
		ITypeBinding targetType= getContainingTypeBinding();
		if (targetType.isInterface()) {
			fTargetIsInterface= true;
			fVisibility= JdtFlags.VISIBILITY_STRING_PUBLIC;
		}

		return result;
	} finally {
		pm.done();
	}
}
 
Example 15
Source File: IntroduceParameterRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkSelection(CompilationUnitRewrite cuRewrite, IProgressMonitor pm) {
		try {
			if (fSelectedExpression == null){
				String message= RefactoringCoreMessages.IntroduceParameterRefactoring_select;
				return CodeRefactoringUtil.checkMethodSyntaxErrors(fSelectionStart, fSelectionLength, cuRewrite.getRoot(), message);
			}

			MethodDeclaration methodDeclaration= (MethodDeclaration) ASTNodes.getParent(fSelectedExpression, MethodDeclaration.class);
			if (methodDeclaration == null || ASTNodes.getParent(fSelectedExpression, Annotation.class) != null)
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_expression_in_method);
			if (methodDeclaration.resolveBinding() == null)
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceParameterRefactoring_no_binding);
			//TODO: check for rippleMethods -> find matching fragments, consider callers of all rippleMethods

			RefactoringStatus result= new RefactoringStatus();
			result.merge(checkExpression());
			if (result.hasFatalError())
				return result;

			result.merge(checkExpressionBinding());
			if (result.hasFatalError())
				return result;

//			if (isUsedInForInitializerOrUpdater(getSelectedExpression().getAssociatedExpression()))
//				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("ExtractTempRefactoring.for_initializer_updater")); //$NON-NLS-1$
//			pm.worked(1);
//
//			if (isReferringToLocalVariableFromFor(getSelectedExpression().getAssociatedExpression()))
//				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("ExtractTempRefactoring.refers_to_for_variable")); //$NON-NLS-1$
//			pm.worked(1);

			return result;
		} finally {
			if (pm != null)
				pm.done();
		}
	}
 
Example 16
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	RefactoringStatus result= Checks.validateModifiesFiles(
		ResourceUtil.getFiles(new ICompilationUnit[]{fCu}),
		getValidationContext());
	if (result.hasFatalError())
		return result;

	initAST(pm);

	if (fTempDeclarationNode == null)
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_select_declaration);

	if (! Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class))
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_only_declared_in_methods);

	if (isMethodParameter())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_method_parameters);

	if (isTempAnExceptionInCatchBlock())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_exceptions);

	ASTNode declaringType= ASTResolving.findParentType(fTempDeclarationNode);
	if (declaringType instanceof TypeDeclaration && ((TypeDeclaration) declaringType).isInterface())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_interface_methods);
	
	result.merge(checkTempTypeForLocalTypeUsage());
	if (result.hasFatalError())
	    return result;

	checkTempInitializerForLocalTypeUsage();

	if (!fSelfInitializing)
		initializeDefaults();
	return result;
}
 
Example 17
Source File: RenameVirtualMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor monitor) throws CoreException {
	RefactoringStatus result= super.checkInitialConditions(monitor);
	if (result.hasFatalError()) {
		return result;
	}
	try{
		monitor.beginTask("", 3); //$NON-NLS-1$
		if (!fActivationChecked) {
			// the following code may change the method to be changed.
			IMethod method= getMethod();
			fOriginalMethod= method;

			ITypeHierarchy hierarchy= null;
			IType declaringType= method.getDeclaringType();
			if (!declaringType.isInterface()) {
				hierarchy= getCachedHierarchy(declaringType, new SubProgressMonitor(monitor, 1));
			}

			IMethod topmost= getMethod();
			if (MethodChecks.isVirtual(topmost)) {
				topmost= MethodChecks.getTopmostMethod(getMethod(), hierarchy, monitor);
			}
			if (topmost != null) {
				initialize(topmost);
			}
			fActivationChecked= true;
		}
	} finally{
		monitor.done();
	}
	return result;
}
 
Example 18
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@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;

	pm.beginTask("", startupTicks + hierarchyTicks + visibilityTicks + referenceTicks + creationTicks); //$NON-NLS-1$
	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) {
		pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions + " " + RefactoringCoreMessages.IntroduceIndirectionRefactoring_looking_for_references); //$NON-NLS-1$
		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);

	pm.setTaskName(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_conditions + " " + RefactoringCoreMessages.IntroduceIndirectionRefactoring_adjusting_visibility); //$NON-NLS-1$
	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;
}
 
Example 19
Source File: UseSuperTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the text change manager for this processor.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param status
 *            the refactoring status
 * @return the created text change manager
 * @throws JavaModelException
 *             if the method declaration could not be found
 * @throws CoreException
 *             if the changes could not be generated
 */
protected final TextEditBasedChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException, CoreException {
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 300); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.UseSuperTypeProcessor_creating);
		final TextEditBasedChangeManager manager= new TextEditBasedChangeManager();
		final IJavaProject project= fSubType.getJavaProject();
		final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setWorkingCopyOwner(fOwner);
		parser.setResolveBindings(true);
		parser.setProject(project);
		parser.setCompilerOptions(RefactoringASTParser.getCompilerOptions(project));
		if (fSubType.isBinary() || fSubType.isReadOnly()) {
			final IBinding[] bindings= parser.createBindings(new IJavaElement[] { fSubType, fSuperType }, new SubProgressMonitor(monitor, 50));
			if (bindings != null && bindings.length == 2 && bindings[0] instanceof ITypeBinding && bindings[1] instanceof ITypeBinding) {
				solveSuperTypeConstraints(null, null, fSubType, (ITypeBinding) bindings[0], (ITypeBinding) bindings[1], new SubProgressMonitor(monitor, 100), status);
				if (!status.hasFatalError())
					rewriteTypeOccurrences(manager, null, null, null, null, new HashSet<String>(), status, new SubProgressMonitor(monitor, 150));
			}
		} else {
			parser.createASTs(new ICompilationUnit[] { fSubType.getCompilationUnit() }, new String[0], new ASTRequestor() {

				@Override
				public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
					try {
						final CompilationUnitRewrite subRewrite= new CompilationUnitRewrite(fOwner, unit, node);
						final AbstractTypeDeclaration subDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(fSubType, subRewrite.getRoot());
						if (subDeclaration != null) {
							final ITypeBinding subBinding= subDeclaration.resolveBinding();
							if (subBinding != null) {
								final ITypeBinding superBinding= findTypeInHierarchy(subBinding, fSuperType.getFullyQualifiedName('.'));
								if (superBinding != null) {
									solveSuperTypeConstraints(subRewrite.getCu(), subRewrite.getRoot(), fSubType, subBinding, superBinding, new SubProgressMonitor(monitor, 100), status);
									if (!status.hasFatalError()) {
										rewriteTypeOccurrences(manager, this, subRewrite, subRewrite.getCu(), subRewrite.getRoot(), new HashSet<String>(), status, new SubProgressMonitor(monitor, 200));
										final TextChange change= subRewrite.createChange(true);
										if (change != null)
											manager.manage(subRewrite.getCu(), change);
									}
								}
							}
						}
					} catch (CoreException exception) {
						JavaPlugin.log(exception);
						status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.UseSuperTypeProcessor_internal_error));
					}
				}

				@Override
				public final void acceptBinding(final String key, final IBinding binding) {
					// Do nothing
				}
			}, new NullProgressMonitor());
		}
		return manager;
	} finally {
		monitor.done();
	}
}
 
Example 20
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public final RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context) throws CoreException, OperationCanceledException {
	Assert.isNotNull(monitor);
	Assert.isNotNull(context);
	Assert.isNotNull(fTarget);
	final RefactoringStatus status= new RefactoringStatus();
	fChangeManager= new TextChangeManager();
	try {
		monitor.beginTask("", 4); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
		status.merge(Checks.checkIfCuBroken(fMethod));
		if (!status.hasError()) {
			checkGenericTarget(new SubProgressMonitor(monitor, 1), status);
			if (status.isOK()) {
				final IType type= getTargetType();
				if (type != null) {
					if (type.isBinary() || type.isReadOnly() || !fMethod.exists() || fMethod.isBinary() || fMethod.isReadOnly())
						status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_binary, JavaStatusContext.create(fMethod)));
					else {
						status.merge(Checks.checkIfCuBroken(type));
						if (!status.hasError()) {
							if (!type.exists() || type.isBinary() || type.isReadOnly())
								status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_binary, JavaStatusContext.create(fMethod)));
							checkConflictingTarget(new SubProgressMonitor(monitor, 1), status);
							checkConflictingMethod(new SubProgressMonitor(monitor, 1), status);

							Checks.addModifiedFilesToChecker(computeModifiedFiles(fMethod.getCompilationUnit(), type.getCompilationUnit()), context);

							monitor.worked(1);
							if (!status.hasFatalError())
								fChangeManager= createChangeManager(status, new SubProgressMonitor(monitor, 1));
						}
					}
				} else
					status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_resolved_target, JavaStatusContext.create(fMethod)));
			}
		}
	} finally {
		monitor.done();
	}
	return status;
}