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

The following examples show how to use org.eclipse.ltk.core.refactoring.RefactoringStatus#isOK() . 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: RenameMethodProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public final RefactoringStatus checkNewElementName(String newName) {
	Assert.isNotNull(newName, "new name"); //$NON-NLS-1$

	RefactoringStatus status= Checks.checkName(newName, JavaConventionsUtil.validateMethodName(newName, fMethod));
	if (status.isOK() && !Checks.startsWithLowerCase(newName)) {
		status= RefactoringStatus.createWarningStatus(fIsComposite
				? Messages.format(RefactoringCoreMessages.Checks_method_names_lowercase2, new String[] { BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel()})
				: RefactoringCoreMessages.Checks_method_names_lowercase);
	}

	if (Checks.isAlreadyNamed(fMethod, newName)) {
		status.addFatalError(fIsComposite
				? Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_same_name2, new String[] { BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel() } )
				: RefactoringCoreMessages.RenameMethodRefactoring_same_name,
				JavaStatusContext.create(fMethod));
	}
	return status;
}
 
Example 2
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public final RefactoringStatus checkInitialConditions(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
	Assert.isNotNull(monitor);
	final RefactoringStatus status= new RefactoringStatus();
	try {
		monitor.beginTask("", 4); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
		status.merge(Checks.checkIfCuBroken(fMethod));
		if (!status.hasError()) {
			checkMethodDeclaration(new SubProgressMonitor(monitor, 1), status);
			if (status.isOK()) {
				final MethodDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
				checkGenericTypes(new SubProgressMonitor(monitor, 1), declaration, status);
				checkMethodBody(new SubProgressMonitor(monitor, 1), declaration, status);
				checkPossibleTargets(new SubProgressMonitor(monitor, 1), declaration, status);
			}
		}
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 3
Source File: RenameMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public final RefactoringStatus checkNewElementName(String newName) {
	Assert.isNotNull(newName, "new name"); //$NON-NLS-1$

	RefactoringStatus status= Checks.checkName(newName, JavaConventionsUtil.validateMethodName(newName, fMethod));
	if (status.isOK() && !Checks.startsWithLowerCase(newName))
		status= RefactoringStatus.createWarningStatus(fIsComposite
				? Messages.format(RefactoringCoreMessages.Checks_method_names_lowercase2, new String[] { BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel()})
				: RefactoringCoreMessages.Checks_method_names_lowercase);

	if (Checks.isAlreadyNamed(fMethod, newName))
		status.addFatalError(fIsComposite
				? Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_same_name2, new String[] { BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel() } )
				: RefactoringCoreMessages.RenameMethodRefactoring_same_name,
				JavaStatusContext.create(fMethod));
	return status;
}
 
Example 4
Source File: ExtractClassRefactoring.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, OperationCanceledException {
	RefactoringStatus result= new RefactoringStatus();
	pm.beginTask(RefactoringCoreMessages.ExtractClassRefactoring_progress_msg_check_initial_condition, 5);
	try {
		result.merge(fDescriptor.validateDescriptor());
		if (!result.isOK())
			return result;
		IType type= fDescriptor.getType();
		result.merge(Checks.checkAvailability(type));
		if (!result.isOK())
			return result;
		pm.worked(1);
		Field[] fields= ExtractClassDescriptor.getFields(fDescriptor.getType());
		pm.worked(1);
		if (pm.isCanceled())
			throw new OperationCanceledException();
		fVariables= new LinkedHashMap<String, FieldInfo>();
		if (fields.length == 0) {
			result.addFatalError(RefactoringCoreMessages.ExtractClassRefactoring_error_no_usable_fields, JavaStatusContext.create(type));
			return result;
		}
		for (int i= 0; i < fields.length; i++) {
			Field field= fields[i];
			String fieldName= field.getFieldName();
			IField declField= type.getField(fieldName);
			ParameterInfo info= new ParameterInfo(Signature.toString(declField.getTypeSignature()), fieldName, i);
			fVariables.put(fieldName, new FieldInfo(info, declField));
			if (pm.isCanceled())
				throw new OperationCanceledException();
		}
		pm.worked(3);
	} finally {
		pm.done();
	}
	return result;
}
 
Example 5
Source File: InferTypeArgumentsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus initialize(JavaRefactoringArguments arguments) {
	final String clone= arguments.getAttribute(ATTRIBUTE_CLONE);
	if (clone != null) {
		fAssumeCloneReturnsSameType= Boolean.valueOf(clone).booleanValue();
	} else
		return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_CLONE));
	final String leave= arguments.getAttribute(ATTRIBUTE_LEAVE);
	if (leave != null) {
		fLeaveUnconstrainedRaw= Boolean.valueOf(leave).booleanValue();
	} else
		return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_LEAVE));
	int count= 1;
	final List<IJavaElement> elements= new ArrayList<IJavaElement>();
	String handle= null;
	String attribute= JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT + count;
	final RefactoringStatus status= new RefactoringStatus();
	while ((handle= arguments.getAttribute(attribute)) != null) {
		final IJavaElement element= JavaRefactoringDescriptorUtil.handleToElement(arguments.getProject(), handle, false);
		if (element == null || !element.exists())
			return JavaRefactoringDescriptorUtil.createInputFatalStatus(element, getName(), IJavaRefactorings.INFER_TYPE_ARGUMENTS);
		else
			elements.add(element);
		count++;
		attribute= JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT + count;
	}
	fElements= elements.toArray(new IJavaElement[elements.size()]);
	if (elements.isEmpty())
		return JavaRefactoringDescriptorUtil.createInputFatalStatus(null, getName(), IJavaRefactorings.INFER_TYPE_ARGUMENTS);
	if (!status.isOK())
		return status;
	return new RefactoringStatus();
}
 
Example 6
Source File: ParameterEditDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IStatus validateType() {
	if (fType == null)
		return null;
	String type= fType.getText();

	RefactoringStatus status= TypeContextChecker.checkParameterTypeSyntax(type, fContext.getCuHandle().getJavaProject());
	if (status == null || status.isOK())
		return Status.OK_STATUS;
	if (status.hasError())
		return createErrorStatus(status.getEntryWithHighestSeverity().getMessage());
	else
		return createWarningStatus(status.getEntryWithHighestSeverity().getMessage());
}
 
Example 7
Source File: ExtractMethodRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ASTNode[] createCallNodes(SnippetFinder.Match duplicate, int modifiers) {
	List<ASTNode> result = new ArrayList<>(2);

	IVariableBinding[] locals = fAnalyzer.getCallerLocals();
	for (int i = 0; i < locals.length; i++) {
		result.add(createDeclaration(locals[i], null));
	}

	MethodInvocation invocation = fAST.newMethodInvocation();
	invocation.setName(fAST.newSimpleName(fMethodName));
	ASTNode typeNode = ASTResolving.findParentType(fAnalyzer.getEnclosingBodyDeclaration());
	RefactoringStatus status = new RefactoringStatus();
	while (fDestination != typeNode) {
		fAnalyzer.checkInput(status, fMethodName, typeNode);
		if (!status.isOK()) {
			SimpleName destinationTypeName = fAST.newSimpleName(ASTNodes.getEnclosingType(fDestination).getName());
			if ((modifiers & Modifier.STATIC) == 0) {
				ThisExpression thisExpression = fAST.newThisExpression();
				thisExpression.setQualifier(destinationTypeName);
				invocation.setExpression(thisExpression);
			} else {
				invocation.setExpression(destinationTypeName);
			}
			break;
		}
		typeNode = typeNode.getParent();
	}

	List<Expression> arguments = invocation.arguments();
	for (int i = 0; i < fParameterInfos.size(); i++) {
		ParameterInfo parameter = fParameterInfos.get(i);
		arguments.add(ASTNodeFactory.newName(fAST, getMappedName(duplicate, parameter)));
	}
	if (fLinkedProposalModel != null) {
		LinkedProposalPositionGroupCore nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
		nameGroup.addPosition(fRewriter.track(invocation.getName()), true);
	}

	ASTNode call;
	int returnKind = fAnalyzer.getReturnKind();
	switch (returnKind) {
		case ExtractMethodAnalyzer.ACCESS_TO_LOCAL:
			IVariableBinding binding = fAnalyzer.getReturnLocal();
			if (binding != null) {
				VariableDeclarationStatement decl = createDeclaration(getMappedBinding(duplicate, binding), invocation);
				call = decl;
			} else {
				Assignment assignment = fAST.newAssignment();
				assignment.setLeftHandSide(ASTNodeFactory.newName(fAST, getMappedBinding(duplicate, fAnalyzer.getReturnValue()).getName()));
				assignment.setRightHandSide(invocation);
				call = assignment;
			}
			break;
		case ExtractMethodAnalyzer.RETURN_STATEMENT_VALUE:
			ReturnStatement rs = fAST.newReturnStatement();
			rs.setExpression(invocation);
			call = rs;
			break;
		default:
			call = invocation;
	}

	if (call instanceof Expression && !fAnalyzer.isExpressionSelected()) {
		call = fAST.newExpressionStatement((Expression) call);
	}
	result.add(call);

	// We have a void return statement. The code looks like
	// extracted();
	// return;
	if (returnKind == ExtractMethodAnalyzer.RETURN_STATEMENT_VOID && !fAnalyzer.isLastStatementSelected()) {
		result.add(fAST.newReturnStatement());
	}
	return result.toArray(new ASTNode[result.size()]);
}
 
Example 8
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;
}
 
Example 9
Source File: InlineMethodRefactoring.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 {
	pm.beginTask("", 20); //$NON-NLS-1$
	fChangeManager= new TextChangeManager();
	RefactoringStatus result= new RefactoringStatus();
	fSourceProvider.initialize();
	fTargetProvider.initialize();

	pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
	RefactoringStatus searchStatus= new RefactoringStatus();
	String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
	ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);
	ICompilationUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
	binaryRefs.addErrorIfNecessary(searchStatus);
	if (searchStatus.hasFatalError()) {
		result.merge(searchStatus);
		return result;
	}

	IFile[] filesToBeModified= getFilesToBeModified(units);
	result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
	if (result.hasFatalError())
		return result;
	result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
	checkOverridden(result, new SubProgressMonitor(pm, 4));
	IProgressMonitor sub= new SubProgressMonitor(pm, 15);
	sub.beginTask("", units.length * 3); //$NON-NLS-1$
	for (int c= 0; c < units.length; c++) {
		ICompilationUnit unit= units[c];
		sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing,  BasicElementLabels.getFileName(unit)));
		CallInliner inliner= null;
		try {
			boolean added= false;
			MultiTextEdit root= new MultiTextEdit();
			CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit);
			change.setEdit(root);
			BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
			if (bodies.length == 0)
				continue;
			inliner= new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
			for (int b= 0; b < bodies.length; b++) {
				BodyDeclaration body= bodies[b];
				inliner.initialize(body);
				RefactoringStatus nestedInvocations= new RefactoringStatus();
				ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit,
					fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
				for (int i= 0; i < invocations.length; i++) {
					ASTNode invocation= invocations[i];
					result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
					if (result.hasFatalError())
						break;
					if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
						added= true;
						TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
						change.addTextEditGroup(group);
						result.merge(inliner.perform(group));
					} else {
						fDeleteSource= false;
					}
				}
				// do this after we have inlined the method calls. We still want
				// to generate the modifications.
				if (!nestedInvocations.isOK()) {
					result.merge(nestedInvocations);
					fDeleteSource= false;
				}
			}
			if (!added) {
				fChangeManager.remove(unit);
			} else {
				root.addChild(inliner.getModifications());
				ImportRewrite rewrite= inliner.getImportEdit();
				if (rewrite.hasRecordedChanges()) {
					TextEdit edit= rewrite.rewriteImports(null);
					if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) {
						root.addChild(edit);
						change.addTextEditGroup(
							new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit}));
					}
				}
			}
		} finally {
			if (inliner != null)
				inliner.dispose();
		}
		sub.worked(1);
		if (sub.isCanceled())
			throw new OperationCanceledException();
	}
	result.merge(searchStatus);
	sub.done();
	pm.done();
	return result;
}
 
Example 10
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTNode[] createCallNodes(SnippetFinder.Match duplicate, int modifiers) {
	List<ASTNode> result= new ArrayList<ASTNode>(2);

	IVariableBinding[] locals= fAnalyzer.getCallerLocals();
	for (int i= 0; i < locals.length; i++) {
		result.add(createDeclaration(locals[i], null));
	}

	MethodInvocation invocation= fAST.newMethodInvocation();
	invocation.setName(fAST.newSimpleName(fMethodName));
	ASTNode typeNode= ASTResolving.findParentType(fAnalyzer.getEnclosingBodyDeclaration());
	RefactoringStatus status= new RefactoringStatus();
	while (fDestination != typeNode) {
		fAnalyzer.checkInput(status, fMethodName, typeNode);
		if (!status.isOK()) {
			SimpleName destinationTypeName= fAST.newSimpleName(ASTNodes.getEnclosingType(fDestination).getName());
			if ((modifiers & Modifier.STATIC) == 0) {
				ThisExpression thisExpression= fAST.newThisExpression();
				thisExpression.setQualifier(destinationTypeName);
				invocation.setExpression(thisExpression);
			} else {
				invocation.setExpression(destinationTypeName);
			}
			break;
		}
		typeNode= typeNode.getParent();
	}

	List<Expression> arguments= invocation.arguments();
	for (int i= 0; i < fParameterInfos.size(); i++) {
		ParameterInfo parameter= fParameterInfos.get(i);
		arguments.add(ASTNodeFactory.newName(fAST, getMappedName(duplicate, parameter)));
	}
	if (fLinkedProposalModel != null) {
		LinkedProposalPositionGroup nameGroup= fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
		nameGroup.addPosition(fRewriter.track(invocation.getName()), false);
	}

	ASTNode call;
	int returnKind= fAnalyzer.getReturnKind();
	switch (returnKind) {
		case ExtractMethodAnalyzer.ACCESS_TO_LOCAL:
			IVariableBinding binding= fAnalyzer.getReturnLocal();
			if (binding != null) {
				VariableDeclarationStatement decl= createDeclaration(getMappedBinding(duplicate, binding), invocation);
				call= decl;
			} else {
				Assignment assignment= fAST.newAssignment();
				assignment.setLeftHandSide(ASTNodeFactory.newName(fAST,
						getMappedBinding(duplicate, fAnalyzer.getReturnValue()).getName()));
				assignment.setRightHandSide(invocation);
				call= assignment;
			}
			break;
		case ExtractMethodAnalyzer.RETURN_STATEMENT_VALUE:
			ReturnStatement rs= fAST.newReturnStatement();
			rs.setExpression(invocation);
			call= rs;
			break;
		default:
			call= invocation;
	}

	if (call instanceof Expression && !fAnalyzer.isExpressionSelected()) {
		call= fAST.newExpressionStatement((Expression)call);
	}
	result.add(call);

	// We have a void return statement. The code looks like
	// extracted();
	// return;
	if (returnKind == ExtractMethodAnalyzer.RETURN_STATEMENT_VOID && !fAnalyzer.isLastStatementSelected()) {
		result.add(fAST.newReturnStatement());
	}
	return result.toArray(new ASTNode[result.size()]);
}
 
Example 11
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Checks if the given name is a valid Java method name.
 *
 * @param name the java method name.
 * @param context an {@link IJavaElement} or <code>null</code>
 * @return a refactoring status containing the error message if the
 *  name is not a valid java method name.
 */
public static RefactoringStatus checkMethodName(String name, IJavaElement context) {
	RefactoringStatus status= checkName(name, JavaConventionsUtil.validateMethodName(name, context));
	if (status.isOK() && !startsWithLowerCase(name))
		return RefactoringStatus.createWarningStatus(RefactoringCoreMessages.Checks_method_names_lowercase);
	else
		return status;
}