org.eclipse.ltk.core.refactoring.RefactoringStatus Java Examples

The following examples show how to use org.eclipse.ltk.core.refactoring.RefactoringStatus. 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: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks whether there are any refactorings to be executed which need a
 * source attachment, but none exists.
 *
 * @param monitor
 *            the progress monitor
 * @return a status describing the outcome of the check
 */
protected RefactoringStatus checkSourceAttachmentRefactorings(final IProgressMonitor monitor) {
	final RefactoringStatus status= new RefactoringStatus();
	try {
		if (!canUseSourceAttachment()) {
			final RefactoringDescriptorProxy[] proxies= getRefactoringHistory().getDescriptors();
			monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, proxies.length * 100);
			for (int index= 0; index < proxies.length; index++) {
				final RefactoringDescriptor descriptor= proxies[index].requestDescriptor(new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
				if (descriptor != null) {
					final int flags= descriptor.getFlags();
					if ((flags & JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT) != 0)
						status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(JarImportMessages.BinaryRefactoringHistoryWizard_error_missing_source_attachment, descriptor.getDescription())));
				}
			}
		} else
			monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 1);
	} finally {
		monitor.done();
	}
	return status;
}
 
Example #2
Source File: N4JSRenameStrategy.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This method uses parser of rule IdentifierName to make sure names follow the rule.
 */
@Override
public RefactoringStatus validateNewName(String newName) {
	// N4JS already contains N4JSX grammar
	IParser parser = N4LanguageUtils.getServiceForContext("n4js", IParser.class).get();
	Grammar grammar = this.getTypeExpressionsGrammar();
	ParserRule parserRule = (ParserRule) GrammarUtil.findRuleForName(grammar,
			"org.eclipse.n4js.ts.TypeExpressions.IdentifierName");

	// Parse the new name using the IdentifierName rule of the parser
	IParseResult parseResult = parser.parse(parserRule, new StringReader(newName));
	if (parseResult.hasSyntaxErrors()) {
		String parseErrorMessages = Joiner.on("\n").join(Iterables.transform(parseResult.getSyntaxErrors(),
				(node) -> node.getSyntaxErrorMessage().getMessage()));
		return RefactoringStatus.createFatalErrorStatus(parseErrorMessages);
	}

	RefactoringStatus status = new RefactoringStatus();
	return status;
}
 
Example #3
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected static FieldDeclaration createNewFieldDeclarationNode(final ASTRewrite rewrite, final CompilationUnit unit, final IField field, final VariableDeclarationFragment oldFieldFragment, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor, final RefactoringStatus status, final int modifiers) throws JavaModelException {
	final VariableDeclarationFragment newFragment= rewrite.getAST().newVariableDeclarationFragment();
	copyExtraDimensions(oldFieldFragment, newFragment);
	if (oldFieldFragment.getInitializer() != null) {
		Expression newInitializer= null;
		if (mapping.length > 0)
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), mapping, rewrite);
		else
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), rewrite);
		newFragment.setInitializer(newInitializer);
	}
	newFragment.setName(((SimpleName) ASTNode.copySubtree(rewrite.getAST(), oldFieldFragment.getName())));
	final FieldDeclaration newField= rewrite.getAST().newFieldDeclaration(newFragment);
	final FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, unit);
	copyJavadocNode(rewrite, oldField, newField);
	copyAnnotations(oldField, newField);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(rewrite.getAST(), modifiers));
	final Type oldType= oldField.getType();
	Type newType= null;
	if (mapping.length > 0) {
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), mapping, rewrite);
	} else
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), rewrite);
	newField.setType(newType);
	return newField;
}
 
Example #4
Source File: GenerateHashCodeEqualsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
RefactoringStatus checkMember(Object memberBinding) {
	RefactoringStatus status= new RefactoringStatus();
	IVariableBinding variableBinding= (IVariableBinding)memberBinding;
	ITypeBinding fieldsType= variableBinding.getType();
	if (fieldsType.isArray())
		fieldsType= fieldsType.getElementType();
	if (!fieldsType.isPrimitive() && !fieldsType.isEnum() && !alreadyCheckedMemberTypes.contains(fieldsType) && !fieldsType.equals(fTypeBinding)) {
		status.merge(checkHashCodeEqualsExists(fieldsType, false));
		alreadyCheckedMemberTypes.add(fieldsType);
	}
	if (Modifier.isTransient(variableBinding.getModifiers()))
		status.addWarning(Messages.format(ActionMessages.GenerateHashCodeEqualsAction_transient_field_included_error, BasicElementLabels.getJavaElementName(variableBinding.getName())),
				createRefactoringStatusContext(variableBinding.getJavaElement()));
	return status;
}
 
Example #5
Source File: FileEventHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static WorkspaceEdit getRenameEdit(IJavaElement targetElement, String newName, IProgressMonitor monitor) throws CoreException {
	RenameSupport renameSupport = RenameSupport.create(targetElement, newName, RenameSupport.UPDATE_REFERENCES);
	if (renameSupport == null) {
		return null;
	}

	if (targetElement instanceof IPackageFragment) {
		((RenamePackageProcessor) renameSupport.getJavaRenameProcessor()).setRenameSubpackages(true);
	}

	RenameRefactoring renameRefactoring = renameSupport.getRenameRefactoring();
	RefactoringTickProvider rtp = renameRefactoring.getRefactoringTickProvider();
	SubMonitor submonitor = SubMonitor.convert(monitor, "Creating rename changes...", rtp.getAllTicks());
	CheckConditionsOperation checkConditionOperation = new CheckConditionsOperation(renameRefactoring, CheckConditionsOperation.ALL_CONDITIONS);
	checkConditionOperation.run(submonitor.split(rtp.getCheckAllConditionsTicks()));
	if (checkConditionOperation.getStatus().getSeverity() >= RefactoringStatus.FATAL) {
		JavaLanguageServerPlugin.logError(checkConditionOperation.getStatus().getMessageMatchingSeverity(RefactoringStatus.ERROR));
	}

	Change change = renameRefactoring.createChange(submonitor.split(rtp.getCreateChangeTicks()));
	change.initializeValidationData(new NotCancelableProgressMonitor(submonitor.split(rtp.getInitializeChangeTicks())));
	return ChangeUtil.convertToWorkspaceEdit(change);
}
 
Example #6
Source File: RenameTypeProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Checks whether one of the given methods, which will all be renamed to
 * "newName", shares a type with another already registered method which is
 * renamed to the same new name and shares the same parameters.
 *
 * @param methods
 *            methods to check
 * @param newName
 *            the new name
 * @return status
 *
 * @see #checkForConflictingRename(IField, String)
 */
private RefactoringStatus checkForConflictingRename(IMethod[] methods, String newName) {
	RefactoringStatus status = new RefactoringStatus();
	for (Iterator<IJavaElement> iter = fFinalSimilarElementToName.keySet().iterator(); iter.hasNext();) {
		IJavaElement element = iter.next();
		if (element instanceof IMethod) {
			IMethod alreadyRegisteredMethod = (IMethod) element;
			String alreadyRegisteredMethodName = fFinalSimilarElementToName.get(element);
			for (int i = 0; i < methods.length; i++) {
				IMethod method2 = methods[i];
				if ((alreadyRegisteredMethodName.equals(newName)) && (method2.getDeclaringType().equals(alreadyRegisteredMethod.getDeclaringType())) && (sameParams(alreadyRegisteredMethod, method2))) {
					String message = Messages.format(RefactoringCoreMessages.RenameTypeProcessor_cannot_rename_methods_same_new_name,
							new String[] { BasicElementLabels.getJavaElementName(alreadyRegisteredMethod.getElementName()), BasicElementLabels.getJavaElementName(method2.getElementName()),
									BasicElementLabels.getJavaElementName(alreadyRegisteredMethod.getDeclaringType().getFullyQualifiedName('.')), BasicElementLabels.getJavaElementName(newName) });
					status.addFatalError(message);
					return status;
				}
			}
		}
	}
	return status;
}
 
Example #7
Source File: JavaDeleteProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	Assert.isNotNull(fDeleteQueries);//must be set before checking activation
	RefactoringStatus result= new RefactoringStatus();
	result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotLinked(fResources))));
	IResource[] javaResources= ReorgUtils.getResources(fJavaElements);
	result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotNulls(javaResources))));
	for (int i= 0; i < fJavaElements.length; i++) {
		IJavaElement element= fJavaElements[i];
		if (element instanceof IType && ((IType)element).isAnonymous()) {
			// work around for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=44450
			// result.addFatalError("Currently, there isn't any support to delete an anonymous type.");
		}
	}
	return result;
}
 
Example #8
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static ICopyPolicy createCopyPolicy(RefactoringStatus status, JavaRefactoringArguments arguments) {
	final String policy= arguments.getAttribute(ATTRIBUTE_POLICY);
	if (policy != null && !"".equals(policy)) { //$NON-NLS-1$
		if (CopyFilesFoldersAndCusPolicy.POLICY_COPY_RESOURCE.equals(policy)) {
			return new CopyFilesFoldersAndCusPolicy(null, null, null);
		} else if (CopyPackageFragmentRootsPolicy.POLICY_COPY_ROOTS.equals(policy)) {
			return new CopyPackageFragmentRootsPolicy(null);
		} else if (CopyPackagesPolicy.POLICY_COPY_PACKAGES.equals(policy)) {
			return new CopyPackagesPolicy(null);
		} else if (CopySubCuElementsPolicy.POLICY_COPY_MEMBERS.equals(policy)) {
			return new CopySubCuElementsPolicy(null);
		} else {
			status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new String[] { policy, ATTRIBUTE_POLICY})));
		}
	} else {
		status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_POLICY)));
	}
	return null;
}
 
Example #9
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks whether a method with the proposed name already exists in the
 * target type.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param status
 *            the status of the condition checking
 * @throws JavaModelException
 *             if the declared methods of the target type could not be
 *             retrieved
 */
protected void checkConflictingMethod(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
	Assert.isNotNull(monitor);
	Assert.isNotNull(status);
	final IMethod[] methods= fTargetType.getMethods();
	int newParamCount= fMethod.getParameterTypes().length;
	if (!fTarget.isField())
		newParamCount--; // moving to a parameter
	if (needsTargetNode())
		newParamCount++; // will add a parameter for the old 'this'
	try {
		monitor.beginTask("", methods.length); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
		IMethod method= null;
		for (int index= 0; index < methods.length; index++) {
			method= methods[index];
			if (method.getElementName().equals(fMethodName) && method.getParameterTypes().length == newParamCount)
				status.merge(RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_method_already_exists, new String[] { BasicElementLabels.getJavaElementName(fMethodName), BasicElementLabels.getJavaElementName(fTargetType.getElementName()) }), JavaStatusContext.create(method)));
			monitor.worked(1);
		}
		if (fMethodName.equals(fTargetType.getElementName()))
			status.merge(RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_method_type_clash, BasicElementLabels.getJavaElementName(fMethodName)), JavaStatusContext.create(fTargetType)));
	} finally {
		monitor.done();
	}
}
 
Example #10
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private MethodDeclaration createNewMethodDeclarationNode(final CompilationUnitRewrite sourceRewrite, final CompilationUnitRewrite targetRewrite, final IMethod sourceMethod, final MethodDeclaration oldMethod, final TypeVariableMaplet[] mapping, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
	final ASTRewrite rewrite= targetRewrite.getASTRewrite();
	final AST ast= rewrite.getAST();
	final MethodDeclaration newMethod= ast.newMethodDeclaration();
	if (!getDestinationType().isInterface())
		copyBodyOfPulledUpMethod(sourceRewrite, targetRewrite, sourceMethod, oldMethod, newMethod, mapping, monitor);
	newMethod.setConstructor(oldMethod.isConstructor());
	copyExtraDimensions(oldMethod, newMethod);
	copyJavadocNode(rewrite, oldMethod, newMethod);
	int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, sourceMethod.getFlags(), adjustments, monitor, true, status);
	if (fDeletedMethods.length == 0 || getDestinationType().isInterface()) {
		modifiers&= ~Flags.AccFinal;
	}

	if (oldMethod.isVarargs())
		modifiers&= ~Flags.AccVarargs;
	copyAnnotations(oldMethod, newMethod);
	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));
	newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, oldMethod.getName())));
	copyReturnType(rewrite, getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyParameters(rewrite, getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyThrownExceptions(oldMethod, newMethod);
	copyTypeParameters(oldMethod, newMethod);
	return newMethod;
}
 
Example #11
Source File: DefaultRenameStrategy.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public RefactoringStatus validateNewName(String newName) {
	RefactoringStatus status = super.validateNewName(newName);
	if(nameRuleName != null) {
		try {
			String value = getNameAsValue(newName);
			String text = getNameAsText(value);
			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;
}
 
Example #12
Source File: TargetProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static TargetProvider create(MethodDeclaration declaration) {
	IMethodBinding method= declaration.resolveBinding();
	if (method == null)
		return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_method_declaration_not_unique));
	ITypeBinding type= method.getDeclaringClass();
	if (type.isLocal()) {
		if (((IType) type.getJavaElement()).isBinary()) {
			return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_cannot_local_method_in_binary));
		} else {
			IType declaringClassOfLocal= (IType) type.getDeclaringClass().getJavaElement();
			return new LocalTypeTargetProvider(declaringClassOfLocal.getCompilationUnit(), declaration);
		}
	} else {
		return new MemberTypeTargetProvider(declaration.resolveBinding());
	}
}
 
Example #13
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected RefactoringStatus verifyDestination(IJavaElement javaElement) throws JavaModelException {
	Assert.isNotNull(javaElement);
	if (!fCheckDestination)
		return new RefactoringStatus();
	if (!javaElement.exists())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_cannot1);
	if (javaElement instanceof IJavaModel)
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_jmodel);
	if (!(javaElement instanceof IJavaProject))
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2proj);
	if (javaElement.isReadOnly())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2writable);
	if (ReorgUtils.isPackageFragmentRoot(javaElement.getJavaProject()))
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_src2nosrc);
	return new RefactoringStatus();
}
 
Example #14
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Expression getAssignedValue(ParameterObjectFactory pof, String parameterName, IJavaProject javaProject, RefactoringStatus status, ASTRewrite rewrite, ParameterInfo pi, boolean useSuper, ITypeBinding typeBinding, Expression qualifier, ASTNode replaceNode, ITypeRoot typeRoot) {
	AST ast= rewrite.getAST();
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(javaProject);
	Expression assignedValue= handleSimpleNameAssignment(replaceNode, pof, parameterName, ast, javaProject, useSuper);
	if (assignedValue == null) {
		NullLiteral marker= qualifier == null ? null : ast.newNullLiteral();
		Expression fieldReadAccess= pof.createFieldReadAccess(pi, parameterName, ast, javaProject, useSuper, marker);
		assignedValue= GetterSetterUtil.getAssignedValue(replaceNode, rewrite, fieldReadAccess, typeBinding, is50OrHigher);
		boolean markerReplaced= replaceMarker(rewrite, qualifier, assignedValue, marker);
		if (markerReplaced) {
			switch (qualifier.getNodeType()) {
				case ASTNode.METHOD_INVOCATION:
				case ASTNode.CLASS_INSTANCE_CREATION:
				case ASTNode.SUPER_METHOD_INVOCATION:
				case ASTNode.PARENTHESIZED_EXPRESSION:
					status.addWarning(RefactoringCoreMessages.ExtractClassRefactoring_warning_semantic_change, JavaStatusContext.create(typeRoot, replaceNode));
					break;
			}
		}
	}
	return assignedValue;
}
 
Example #15
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkConstructorParameterNames() {
	RefactoringStatus result= new RefactoringStatus();
	CompilationUnit cuNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(fType.getCompilationUnit(), false);
	MethodDeclaration[] nodes= getConstructorDeclarationNodes(findTypeDeclaration(fType, cuNode));
	for (int i= 0; i < nodes.length; i++) {
		MethodDeclaration constructor= nodes[i];
		for (Iterator<SingleVariableDeclaration> iter= constructor.parameters().iterator(); iter.hasNext();) {
			SingleVariableDeclaration param= iter.next();
			if (fEnclosingInstanceFieldName.equals(param.getName().getIdentifier())) {
				String[] keys= new String[] { BasicElementLabels.getJavaElementName(param.getName().getIdentifier()), BasicElementLabels.getJavaElementName(fType.getElementName())};
				String msg= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_name_used, keys);
				result.addError(msg, JavaStatusContext.create(fType.getCompilationUnit(), param));
			}
		}
	}
	return result;
}
 
Example #16
Source File: ExtractConstantWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected RefactoringStatus validateTextField(String text) {
	try {
		getExtractConstantRefactoring().setConstantName(text);
		updatePreviewLabel();
		RefactoringStatus result= getExtractConstantRefactoring().checkConstantNameOnChange();
		if (fOriginalMessageType == IMessageProvider.INFORMATION && result.getSeverity() == RefactoringStatus.OK)
			return RefactoringStatus.createInfoStatus(fOriginalMessage);
		else
			return result;
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
		return RefactoringStatus.createFatalErrorStatus(RefactoringMessages.ExtractConstantInputPage_Internal_Error);
	}
}
 
Example #17
Source File: RenameTypeProcessor.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 {
	IType primary= (IType) fType.getPrimaryElement();
	if (primary == null || !primary.exists()) {
		String qualifiedTypeName= JavaElementLabels.getElementLabel(fType, JavaElementLabels.F_FULLY_QUALIFIED);
		String message= Messages.format(RefactoringCoreMessages.RenameTypeRefactoring_does_not_exist, new String[] { BasicElementLabels.getJavaElementName(qualifiedTypeName), BasicElementLabels.getFileName(fType.getCompilationUnit())});
		return RefactoringStatus.createFatalErrorStatus(message);
	}
	fType= primary;
	return Checks.checkIfCuBroken(fType);
}
 
Example #18
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 #19
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public RefactoringStatus verifyDestination(IReorgDestination destination) throws JavaModelException {
	if (!(destination instanceof JavaElementDestination))
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ReorgPolicyFactory_invalidDestinationKind);

	JavaElementDestination javaElementDestination= (JavaElementDestination) destination;
	return verifyDestination(javaElementDestination.getJavaElement(), javaElementDestination.getLocation());
}
 
Example #20
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Map<ICompilationUnit, SearchMatch[]> createConstructorReferencesMapping(IProgressMonitor pm, RefactoringStatus status) throws JavaModelException {
	SearchResultGroup[] groups= ConstructorReferenceFinder.getConstructorReferences(fType, pm, status);
	Map<ICompilationUnit, SearchMatch[]> result= new HashMap<ICompilationUnit, SearchMatch[]>();
	for (int i= 0; i < groups.length; i++) {
		SearchResultGroup group= groups[i];
		ICompilationUnit cu= group.getCompilationUnit();
		if (cu == null)
			continue;
		result.put(cu, group.getSearchResults());
	}
	return result;
}
 
Example #21
Source File: RenamePackageProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
void doRename(IProgressMonitor pm, RefactoringStatus result) throws CoreException {
	pm.beginTask("", 16); //$NON-NLS-1$
	if (fProcessor.getUpdateReferences()){
		pm.setTaskName(RefactoringCoreMessages.RenamePackageRefactoring_searching);

		String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , getElementLabel(fPackage));
		ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);

		fOccurrences= getReferences(new SubProgressMonitor(pm, 4), binaryRefs, result);
		fReferencesToTypesInNamesakes= getReferencesToTypesInNamesakes(new SubProgressMonitor(pm, 4), result);
		fReferencesToTypesInPackage= getReferencesToTypesInPackage(new SubProgressMonitor(pm, 4), binaryRefs, result);
		binaryRefs.addErrorIfNecessary(result);

		pm.setTaskName(RefactoringCoreMessages.RenamePackageRefactoring_checking);
		result.merge(analyzeAffectedCompilationUnits());
		pm.worked(1);
	} else {
		fOccurrences= new SearchResultGroup[0];
		pm.worked(13);
	}

	if (result.hasFatalError())
		return;

	if (fProcessor.getUpdateReferences())
		addReferenceUpdates(new SubProgressMonitor(pm, 3));
	else
		pm.worked(3);

	pm.done();
}
 
Example #22
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void checkSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
	String newCuSource= fChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);

	IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCuRewrite.getRoot());
	for (int i= 0; i < newProblems.length; i++) {
		IProblem problem= newProblems[i];
		if (problem.isError())
			result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
	}
}
 
Example #23
Source File: DynamicValidationStateChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void workspaceChanged() {
	long currentTime = System.currentTimeMillis();
	if (currentTime - fTimeStamp < LIFE_TIME) {
		return;
	}
	fValidationState = RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.DynamicValidationStateChange_workspace_changed);
	// remove listener from workspace tracker
	WorkspaceTracker.INSTANCE.removeListener(this);
	fListenerRegistered = false;
	// clear up the children to not hang onto too much memory
	Change[] children = clear();
	for (int i = 0; i < children.length; i++) {
		final Change change = children[i];
		SafeRunner.run(new ISafeRunnable() {
			@Override
			public void run() throws Exception {
				change.dispose();
			}

			@Override
			public void handleException(Throwable exception) {
				JavaLanguageServerPlugin.logException("Exception happened inside DynamicValidationStateChange: ", exception);
			}
		});
	}
}
 
Example #24
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean processCompilerError(RefactoringStatus result, ASTNode node) {
	Message[] messages = ASTNodes.getMessages(node, ASTNodes.INCLUDE_ALL_PARENTS);
	if (messages.length == 0) {
		return false;
	}
	result.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_compiler_errors_field, new String[] { BasicElementLabels.getJavaElementName(fField.getElementName()), messages[0].getMessage() }));
	return true;
}
 
Example #25
Source File: JavaCopyProcessor.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= new RefactoringStatus();
	result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotNulls(fCopyPolicy.getResources()))));
	IResource[] javaResources= ReorgUtils.getResources(fCopyPolicy.getJavaElements());
	result.merge(RefactoringStatus.create(Resources.checkInSync(ReorgUtils.getNotNulls(javaResources))));
	return result;
}
 
Example #26
Source File: LoggedCreateTargetChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public RefactoringStatus isValid(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
	if (fSelection instanceof IJavaElement) {
		final IJavaElement element= (IJavaElement) fSelection;
		if (!Checks.isAvailable(element)) {
			RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.RenameResourceChange_does_not_exist, JavaElementLabels.getTextLabel(fSelection, JavaElementLabels.ALL_DEFAULT)));
		}
	} else if (fSelection instanceof IResource) {
		final IResource resource= (IResource) fSelection;
		if (!resource.exists()) {
			RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.RenameResourceChange_does_not_exist, JavaElementLabels.getTextLabel(fSelection, JavaElementLabels.ALL_DEFAULT)));
		}
	}
	return new RefactoringStatus();
}
 
Example #27
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkClashesInConstructors() {
	Assert.isTrue(fInitializeIn == INITIALIZE_IN_CONSTRUCTOR);
	Assert.isTrue(!isDeclaredInAnonymousClass());
	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) getMethodDeclaration().getParent();
	if (declaration instanceof TypeDeclaration) {
		MethodDeclaration[] methods= ((TypeDeclaration) declaration).getMethods();
		for (int i= 0; i < methods.length; i++) {
			MethodDeclaration method= methods[i];
			if (!method.isConstructor())
				continue;
			NameCollector nameCollector= new NameCollector(method) {
				@Override
				protected boolean visitNode(ASTNode node) {
					return true;
				}
			};
			method.accept(nameCollector);
			List<String> names= nameCollector.getNames();
			if (names.contains(fFieldName)) {
				String[] keys= { BasicElementLabels.getJavaElementName(fFieldName), BindingLabelProvider.getBindingLabel(method.resolveBinding(), JavaElementLabels.ALL_FULLY_QUALIFIED)};
				String msg= Messages.format(RefactoringCoreMessages.PromoteTempToFieldRefactoring_Name_conflict, keys);
				return RefactoringStatus.createFatalErrorStatus(msg);
			}
		}
	}
	return null;
}
 
Example #28
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private RefactoringStatus checkExpressionFragmentIsRValue() throws JavaModelException {
	switch (Checks.checkExpressionIsRValue(getSelectedExpression().getAssociatedExpression())) {
		case Checks.NOT_RVALUE_MISC:
			return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractTempRefactoring_select_expression, null, IConstants.PLUGIN_ID, RefactoringStatusCodes.EXPRESSION_NOT_RVALUE, null);
		case Checks.NOT_RVALUE_VOID:
			return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractTempRefactoring_no_void, null, IConstants.PLUGIN_ID, RefactoringStatusCodes.EXPRESSION_NOT_RVALUE_VOID, null);
		case Checks.IS_RVALUE_GUESSED:
		case Checks.IS_RVALUE:
			return new RefactoringStatus();
		default:
			Assert.isTrue(false);
			return null;
	}
}
 
Example #29
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public final RefactoringParticipant[] loadParticipants(RefactoringStatus status, RefactoringProcessor processor, String[] natures, SharableParticipants shared) throws CoreException {
	RefactoringModifications modifications= getModifications();
	if (modifications != null) {
		return modifications.loadParticipants(status, processor, natures, shared);
	} else {
		return new RefactoringParticipant[0];
	}
}
 
Example #30
Source File: CleanUpRefactoring.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 {
	if (pm != null) {
		pm.beginTask("", 1); //$NON-NLS-1$
		pm.worked(1);
		pm.done();
	}
	return new RefactoringStatus();
}