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

The following examples show how to use org.eclipse.ltk.core.refactoring.RefactoringStatusEntry. 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
/**
 * {@inheritDoc}
 */
@Override
protected boolean selectStatusEntry(final RefactoringStatusEntry entry) {
	if (fSourceFolder != null) {
		final IPath source= fSourceFolder.getFullPath();
		final RefactoringStatusContext context= entry.getContext();
		if (context instanceof JavaStatusContext) {
			final JavaStatusContext extended= (JavaStatusContext) context;
			final ICompilationUnit unit= extended.getCompilationUnit();
			if (unit != null) {
				final IResource resource= unit.getResource();
				if (resource != null && source.isPrefixOf(resource.getFullPath()))
					return false;
			}
		}
	}
	return super.selectStatusEntry(entry);
}
 
Example #2
Source File: ExtractClassWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void updateDecoration(ControlDecoration decoration, RefactoringStatus status) {
	RefactoringStatusEntry highestSeverity= status.getEntryWithHighestSeverity();
	if (highestSeverity != null) {
		Image newImage= null;
		FieldDecorationRegistry registry= FieldDecorationRegistry.getDefault();
		switch (highestSeverity.getSeverity()) {
			case RefactoringStatus.INFO:
				newImage= registry.getFieldDecoration(FieldDecorationRegistry.DEC_INFORMATION).getImage();
				break;
			case RefactoringStatus.WARNING:
				newImage= registry.getFieldDecoration(FieldDecorationRegistry.DEC_WARNING).getImage();
				break;
			case RefactoringStatus.FATAL:
			case RefactoringStatus.ERROR:
				newImage= registry.getFieldDecoration(FieldDecorationRegistry.DEC_ERROR).getImage();
		}
		decoration.setDescriptionText(highestSeverity.getMessage());
		decoration.setImage(newImage);
		decoration.show();
	} else {
		decoration.setDescriptionText(null);
		decoration.hide();
	}
}
 
Example #3
Source File: RefactoringSearchEngine2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public final void acceptSearchMatch(final SearchMatch match) throws CoreException {
	final SearchMatch accepted= fRequestor.acceptSearchMatch(match);
	if (accepted != null) {
		final IResource resource= accepted.getResource();
		if (!resource.equals(fLastResource)) {
			final IJavaElement element= JavaCore.create(resource);
			if (element instanceof ICompilationUnit)
				fCollectedUnits.add((ICompilationUnit) element);
		}
		if (fInaccurate && accepted.getAccuracy() == SearchMatch.A_INACCURATE && !fInaccurateMatches.contains(accepted)) {
			fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_inaccurate_match, BasicElementLabels.getResourceName(accepted.getResource())), null, null, RefactoringStatusEntry.NO_CODE);
			fInaccurateMatches.add(accepted);
		}
	}
}
 
Example #4
Source File: RefactoringSearchEngine2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public final void acceptSearchMatch(final SearchMatch match) throws CoreException {
	final SearchMatch accepted= fRequestor.acceptSearchMatch(match);
	if (accepted != null) {
		fCollectedMatches.add(accepted);
		final IResource resource= accepted.getResource();
		if (!resource.equals(fLastResource)) {
			if (fBinary) {
				final IJavaElement element= JavaCore.create(resource);
				if (!(element instanceof ICompilationUnit)) {
					final IProject project= resource.getProject();
					if (!fGrouping)
						fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_binary_match_ungrouped, BasicElementLabels.getResourceName(project)), null, null, RefactoringStatusEntry.NO_CODE);
					else if (!fBinaryResources.contains(resource))
						fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_binary_match_grouped, BasicElementLabels.getResourceName(project)), null, null, RefactoringStatusEntry.NO_CODE);
					fBinaryResources.add(resource);
				}
			}
			if (fInaccurate && accepted.getAccuracy() == SearchMatch.A_INACCURATE && !fInaccurateMatches.contains(accepted)) {
				fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_inaccurate_match, BasicElementLabels.getResourceName(resource)), null, null, RefactoringStatusEntry.NO_CODE);
				fInaccurateMatches.add(accepted);
			}
		}
	}
}
 
Example #5
Source File: RefactoringSearchEngine2.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public final void acceptSearchMatch(final SearchMatch match) throws CoreException {
	final SearchMatch accepted= fRequestor.acceptSearchMatch(match);
	if (accepted != null) {
		final IResource resource= accepted.getResource();
		if (!resource.equals(fLastResource)) {
			final IJavaElement element= JavaCore.create(resource);
			if (element instanceof ICompilationUnit) {
				fCollectedUnits.add((ICompilationUnit) element);
			}
		}
		if (fInaccurate && accepted.getAccuracy() == SearchMatch.A_INACCURATE && !fInaccurateMatches.contains(accepted)) {
			fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_inaccurate_match, BasicElementLabels.getResourceName(accepted.getResource())), null, null, RefactoringStatusEntry.NO_CODE);
			fInaccurateMatches.add(accepted);
		}
	}
}
 
Example #6
Source File: RefactoringSearchEngine2.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public final void acceptSearchMatch(final SearchMatch match) throws CoreException {
	final SearchMatch accepted= fRequestor.acceptSearchMatch(match);
	if (accepted != null) {
		fCollectedMatches.add(accepted);
		final IResource resource= accepted.getResource();
		if (!resource.equals(fLastResource)) {
			if (fBinary) {
				final IJavaElement element= JavaCore.create(resource);
				if (!(element instanceof ICompilationUnit)) {
					final IProject project= resource.getProject();
					if (!fGrouping) {
						fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_binary_match_ungrouped, BasicElementLabels.getResourceName(project)), null, null, RefactoringStatusEntry.NO_CODE);
					} else if (!fBinaryResources.contains(resource)) {
						fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_binary_match_grouped, BasicElementLabels.getResourceName(project)), null, null, RefactoringStatusEntry.NO_CODE);
					}
					fBinaryResources.add(resource);
				}
			}
			if (fInaccurate && accepted.getAccuracy() == SearchMatch.A_INACCURATE && !fInaccurateMatches.contains(accepted)) {
				fStatus.addEntry(fSeverity, Messages.format(RefactoringCoreMessages.RefactoringSearchEngine_inaccurate_match, BasicElementLabels.getResourceName(resource)), null, null, RefactoringStatusEntry.NO_CODE);
				fInaccurateMatches.add(accepted);
			}
		}
	}
}
 
Example #7
Source File: CallInliner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void checkMethodDeclaration(RefactoringStatus result, int severity) {
	MethodDeclaration methodDeclaration= fSourceProvider.getDeclaration();
	// it is not allowed to inline constructor invocation only if it is used for class instance creation
	// if constructor is invoked from another constructor then we can inline such invocation
	if (fInvocation.getNodeType() != ASTNode.CONSTRUCTOR_INVOCATION && methodDeclaration.isConstructor()) {
		result.addEntry(new RefactoringStatusEntry(
			severity,
			RefactoringCoreMessages.CallInliner_constructors,
			JavaStatusContext.create(fCUnit, fInvocation)));
	}
	if (fSourceProvider.hasSuperMethodInvocation() && fInvocation.getNodeType() == ASTNode.METHOD_INVOCATION) {
		Expression receiver= ((MethodInvocation)fInvocation).getExpression();
		if (receiver instanceof ThisExpression) {
			result.addEntry(new RefactoringStatusEntry(
				severity,
				RefactoringCoreMessages.CallInliner_super_into_this_expression,
				JavaStatusContext.create(fCUnit, fInvocation)));
		}
	}
}
 
Example #8
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkCompilationofDeclaringCu() throws CoreException {
	ICompilationUnit cu= getCu();
	TextChange change= fChangeManager.get(cu);
	String newCuSource= change.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, cu, true, false, null);
	IProblem[] problems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fBaseCuRewrite.getRoot());
	RefactoringStatus result= new RefactoringStatus();
	for (int i= 0; i < problems.length; i++) {
		IProblem problem= problems[i];
		if (shouldReport(problem, newCUNode))
			result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem))));
	}
	return result;
}
 
Example #9
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Adjusts the visibility of the referenced body declaration.
 *
 * @param member the member where to adjust the visibility
 * @param threshold the visibility keyword representing the required visibility, or <code>null</code> for default visibility
 * @param template the message template to use
 * @throws JavaModelException if an error occurs
 */
private void adjustOutgoingVisibility(final IMember member, final ModifierKeyword threshold, final String template) throws JavaModelException {
	Assert.isTrue(!member.isBinary() && !member.isReadOnly());
	boolean adjust= true;
	final IType declaring= member.getDeclaringType();
	if (declaring != null && (JavaModelUtil.isInterfaceOrAnnotation(declaring)
			|| (member instanceof IField) && Flags.isEnum(member.getFlags()) 
			|| declaring.equals(fReferenced)))
		adjust= false;
	if (adjust && hasLowerVisibility(member.getFlags(), keywordToVisibility(threshold)) && needsVisibilityAdjustment(member, threshold))
		fAdjustments.put(member, new OutgoingMemberVisibilityAdjustment(member, threshold, RefactoringStatus.createStatus(fVisibilitySeverity, Messages.format(template, new String[] { JavaElementLabels.getTextLabel(member, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.ALL_FULLY_QUALIFIED), getLabel(threshold)}), JavaStatusContext.create(member), null, RefactoringStatusEntry.NO_CODE, null)));
}
 
Example #10
Source File: RenameAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static RefactoringStatus analyzeCompileErrors(String newCuSource, CompilationUnit newCUNode, CompilationUnit oldCUNode) {
	RefactoringStatus result= new RefactoringStatus();
	IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, oldCUNode);
	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))));
	}
	return result;
}
 
Example #11
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void checkNewSource(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, fCompilationUnitNode);
	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 #12
Source File: CallInliner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addEntry(RefactoringStatus result, String message, int code, int severity) {
	result.addEntry(new RefactoringStatusEntry(
		severity, message,
		JavaStatusContext.create(fCUnit, fInvocation),
		Corext.getPluginId(),
		code, null));
}
 
Example #13
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 #14
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 #15
Source File: RefactoringExecutionStarter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void startIntroduceParameterObject(IMethod method, Shell shell) throws CoreException {
	RefactoringStatus availability= Checks.checkAvailability(method);
	if (availability.hasError()){
		MessageDialog.openError(shell, RefactoringMessages.RefactoringExecutionStarter_IntroduceParameterObject_problem_title, RefactoringMessages.RefactoringExecutionStarter_IntroduceParameterObject_problem_description);
		return;
	}
	IntroduceParameterObjectDescriptor ipod= RefactoringSignatureDescriptorFactory.createIntroduceParameterObjectDescriptor();
	ipod.setMethod(method);

	IntroduceParameterObjectProcessor processor= new IntroduceParameterObjectProcessor(ipod);

	final 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) {
			final Object element= entry.getData();
			IMethod superMethod= (IMethod) element;
			availability= Checks.checkAvailability(superMethod);
			if (availability.hasError()){
				MessageDialog.openError(shell, RefactoringMessages.RefactoringExecutionStarter_IntroduceParameterObject_problem_title, RefactoringMessages.RefactoringExecutionStarter_IntroduceParameterObject_problem_description);
				return;
			}
			String message= Messages.format(RefactoringMessages.RefactoringErrorDialogUtil_okToPerformQuestion, entry.getMessage());
			if (element != null && MessageDialog.openQuestion(shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, message)) {
				ipod= RefactoringSignatureDescriptorFactory.createIntroduceParameterObjectDescriptor();
				ipod.setMethod(superMethod);
				processor= new IntroduceParameterObjectProcessor(ipod);
			}
			else processor=null;
		}
	}
	if (processor != null) {
		Refactoring refactoring= new ProcessorBasedRefactoring(processor);
		IntroduceParameterObjectWizard wizard= new IntroduceParameterObjectWizard(processor, refactoring);
		new RefactoringStarter().activate(wizard, shell, RefactoringMessages.OpenRefactoringWizardAction_refactoring, RefactoringSaveHelper.SAVE_REFACTORING);
	}
}
 
Example #16
Source File: RefactoringSearchEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean containsStatusEntry(final RefactoringStatus status, final RefactoringStatusEntry other) {
	return status.getEntries(new IRefactoringStatusEntryComparator() {
		public final int compare(final RefactoringStatusEntry entry1, final RefactoringStatusEntry entry2) {
			return entry1.getMessage().compareTo(entry2.getMessage());
		}
	}, other).length > 0;
}
 
Example #17
Source File: ExtractClassWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected RefactoringStatus validateRefactoring() {
	RefactoringStatus status= new RefactoringStatus();
	setErrorMessage(null);
	setMessage(null);
	setPageComplete(true);
	status.merge(validateTopLevel());
	status.merge(validateClassName());
	status.merge(validateParameterName());
	status.merge(validateFields());
	RefactoringStatusEntry highestSeverity= status.getEntryWithHighestSeverity();
	if (highestSeverity != null) {
		switch (highestSeverity.getSeverity()) {
			case RefactoringStatus.ERROR:
			case RefactoringStatus.FATAL:
				setErrorMessage(highestSeverity.getMessage());
				setPageComplete(false);
				break;
			case RefactoringStatus.WARNING:
				setMessage(highestSeverity.getMessage(), IMessageProvider.WARNING);
				break;
			case RefactoringStatus.INFO:
				setMessage(highestSeverity.getMessage(), IMessageProvider.INFORMATION);
				break;
		}
	}
	return status;
}
 
Example #18
Source File: RefactoringLocalTestBase.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
protected void checkStatus(RefactoringStatus status, boolean expectError) {
    RefactoringStatusEntry err = status.getEntryMatchingSeverity(RefactoringStatus.ERROR);
    RefactoringStatusEntry fatal = status.getEntryMatchingSeverity(RefactoringStatus.FATAL);

    if (!expectError) {
        assertNull(err != null ? err.getMessage() : "", err);
        assertNull(fatal != null ? fatal.getMessage() : "", fatal);
    } else {
        assertNotNull(err);
        assertNotNull(fatal);
    }
}
 
Example #19
Source File: MemberVisibilityAdjustor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Adjusts the visibility of the specified member.
 *
 * @param element the "source" point from which to calculate the visibility
 * @param referencedMovedElement the moved element which may be adjusted in visibility
 * @param monitor the progress monitor to use
 * @throws JavaModelException if the visibility adjustment could not be computed
 */
private void adjustIncomingVisibility(final IJavaElement element, IMember referencedMovedElement, final IProgressMonitor monitor) throws JavaModelException {
	final ModifierKeyword threshold= getVisibilityThreshold(element, referencedMovedElement, monitor);
	int flags= referencedMovedElement.getFlags();
	IType declaring= referencedMovedElement.getDeclaringType();
	if (declaring != null && declaring.isInterface() || referencedMovedElement instanceof IField && Flags.isEnum(referencedMovedElement.getFlags()))
		return;
	if (hasLowerVisibility(flags, threshold == null ? Modifier.NONE : threshold.toFlagValue()) && needsVisibilityAdjustment(referencedMovedElement, threshold))
		fAdjustments.put(referencedMovedElement, new IncomingMemberVisibilityAdjustment(referencedMovedElement, threshold, RefactoringStatus.createStatus(fVisibilitySeverity, Messages.format(getMessage(referencedMovedElement), new String[] { getLabel(referencedMovedElement), getLabel(threshold)}), JavaStatusContext.create(referencedMovedElement), null, RefactoringStatusEntry.NO_CODE, null)));
}
 
Example #20
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean containsStatusEntry(final RefactoringStatus status, final RefactoringStatusEntry other) {
	return status.getEntries(new IRefactoringStatusEntryComparator() {

		public final int compare(final RefactoringStatusEntry entry1, final RefactoringStatusEntry entry2) {
			return entry1.getMessage().compareTo(entry2.getMessage());
		}
	}, other).length > 0;
}
 
Example #21
Source File: RefactoringSearchEngine.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean containsStatusEntry(final RefactoringStatus status, final RefactoringStatusEntry other) {
	return status.getEntries(new IRefactoringStatusEntryComparator() {
		@Override
		public final int compare(final RefactoringStatusEntry entry1, final RefactoringStatusEntry entry2) {
			return entry1.getMessage().compareTo(entry2.getMessage());
		}
	}, other).length > 0;
}
 
Example #22
Source File: ExtractConstantRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.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(IASTSharedValues.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: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void checkNewSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException {
	String newCuSource = fChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor);
	IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCompilationUnitNode);
	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 #24
Source File: RenameAnalyzeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static RefactoringStatus analyzeCompileErrors(String newCuSource, CompilationUnit newCUNode, CompilationUnit oldCUNode) {
	RefactoringStatus result= new RefactoringStatus();
	IProblem[] newProblems= RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, oldCUNode);
	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))));
		}
	}
	return result;
}
 
Example #25
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the necessary changes to create the delegate method with the
 * original method body.
 *
 * @param document
 *            the buffer containing the source of the source compilation
 *            unit
 * @param declaration
 *            the method declaration to use as source
 * @param rewrite
 *            the ast rewrite to use for the copy of the method body
 * @param rewrites
 *            the compilation unit rewrites
 * @param adjustments
 *            the map of elements to visibility adjustments
 * @param status
 *            the refactoring status
 * @param monitor
 *            the progress monitor to display progress
 * @throws CoreException
 *             if an error occurs
 */
protected void createMethodCopy(IDocument document, MethodDeclaration declaration, ASTRewrite rewrite, Map<ICompilationUnit, CompilationUnitRewrite> rewrites, Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, RefactoringStatus status, IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(document);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	Assert.isNotNull(rewrites);
	Assert.isNotNull(adjustments);
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	final CompilationUnitRewrite rewriter= getCompilationUnitRewrite(rewrites, getTargetType().getCompilationUnit());
	try {
		rewrite.set(declaration, MethodDeclaration.NAME_PROPERTY, rewrite.getAST().newSimpleName(fMethodName), null);
		boolean same= false;
		final IMethodBinding binding= declaration.resolveBinding();
		if (binding != null) {
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null && Bindings.equals(declaring.getPackage(), fTarget.getType().getPackage()))
				same= true;
			final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
			ModifierRewrite modifierRewrite= ModifierRewrite.create(rewrite, declaration);
			if (JdtFlags.isDefaultMethod(binding) && getTargetType().isClass()) {
				// Remove 'default' modifier and add 'public' visibility
				modifierRewrite.setVisibility(Modifier.PUBLIC, null);
				modifierRewrite.setModifiers(Modifier.NONE, Modifier.DEFAULT, null);
			} else if (!JdtFlags.isDefaultMethod(binding) && getTargetType().isInterface()) {
				// Remove visibility modifiers and add 'default'
				modifierRewrite.setModifiers(Modifier.DEFAULT, Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE, null);
			} else if (MemberVisibilityAdjustor.hasLowerVisibility(binding.getModifiers(), same ? Modifier.NONE : keyword == null ? Modifier.NONE : keyword.toFlagValue())
					&& MemberVisibilityAdjustor.needsVisibilityAdjustments(fMethod, keyword, adjustments)) {
				final MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment adjustment= new MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment(fMethod, keyword, RefactoringStatus.createStatus(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning, new String[] { MemberVisibilityAdjustor.getLabel(fMethod), MemberVisibilityAdjustor.getLabel(keyword) }), JavaStatusContext.create(fMethod), null, RefactoringStatusEntry.NO_CODE, null));
				modifierRewrite.setVisibility(keyword == null ? Modifier.NONE : keyword.toFlagValue(), null);
				adjustment.setNeedsRewriting(false);
				adjustments.put(fMethod, adjustment);
			}
		}
		for (IExtendedModifier modifier : (List<IExtendedModifier>) declaration.modifiers()) {
			if (modifier.isAnnotation()) {
				Annotation annotation= (Annotation) modifier;
				ITypeBinding typeBinding= annotation.resolveTypeBinding();
				if (typeBinding != null && typeBinding.getQualifiedName().equals("java.lang.Override")) { //$NON-NLS-1$
					rewrite.remove(annotation, null);
				}
			}
		}
		createMethodArguments(rewrites, rewrite, declaration, adjustments, status);
		createMethodTypeParameters(rewrite, declaration, status);
		createMethodComment(rewrite, declaration);
		createMethodBody(rewriter, rewrite, declaration);
	} finally {
		if (fMethod.getCompilationUnit().equals(getTargetType().getCompilationUnit()))
			rewriter.clearImportRewrites();
	}
}
 
Example #26
Source File: RenameRefactoringXpectMethod.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Rename refactoring Xpect method
 */
// Note: arg1=OFFSET makes the 'offset' parameter contain the right offset value
@ParameterParser(syntax = "('at' arg2=OFFSET 'to' arg3=STRING) ('resource' arg4=STRING)?")
@Xpect
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void renameRefactoring(
		@StringDiffExpectation(whitespaceSensitive = false) IStringDiffExpectation expectation, // arg0
		@ThisResource XtextResource resource, // arg1
		IEObjectCoveringRegion offset, // arg2
		String newName, // arg3
		String specifiedResourcePath, // arg4
		@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectedResult)
		throws Exception {
	try {
		EObject context = offset.getEObject();
		EObject selectedElement = offsetHelper.resolveElementAt((XtextResource) context.eResource(),
				offset.getOffset());

		// LiteralOrComputedPropertyName does not have a type model but its container does
		if (selectedElement instanceof LiteralOrComputedPropertyName) {
			selectedElement = selectedElement.eContainer();
		}

		// An IdentifierRef refers to an AST FormalParameter and not TFormalParameter
		if (!(selectedElement instanceof FormalParameter)
				&& (N4JSLanguageUtils.getDefinedTypeModelElement(selectedElement) != null)) {
			selectedElement = N4JSLanguageUtils.getDefinedTypeModelElement(selectedElement);
		}

		// while (selectedElement != null) {
		// while (Display.getCurrent().readAndDispatch())
		// ;
		// Display.getCurrent().sleep();
		// }

		URI targetResourceUri = context.eResource().getURI();
		Optional<XtextEditor> editorOp = EditorsUtil.openXtextEditor(targetResourceUri,
				N4JSActivator.ORG_ECLIPSE_N4JS_N4JS);
		XtextEditor editor = editorOp.get();
		final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();

		IRenameElementContext renameElementContext = renameContextFactory
				.createRenameElementContext(
						selectedElement, editor, selection, resource);

		IRenameSupport renameSupport = renameSupportFactory.create(renameElementContext, newName);

		// HACK, use reflection to obtain the private field 'renameRefactoring' since we need it to verify the
		// conditions
		// Field field = renameSupport.getClass().getDeclaredField("renameRefactoring");
		// field.setAccessible(true);
		ProcessorBasedRefactoring refactoring = (ProcessorBasedRefactoring) ReflectionUtil.getFieldValue(
				renameSupport,
				"renameRefactoring");

		RefactoringStatus status = refactoring.checkAllConditions(new NullProgressMonitor());
		// If rename refactoring's conditions are not satisfied, validate the error message
		if (status.hasError()) {
			RefactoringStatusEntry[] entries = status.getEntries();
			List<String> errorMessages = Arrays.stream(entries).map(statusEntry -> statusEntry.getMessage())
					.collect(Collectors.toList());

			expectedResult.assertEquals(errorMessages);
		} else {
			String beforeRenameContent = getResourceContentWithoutXpectComment(specifiedResourcePath, resource);
			renameSupport.startDirectRefactoring();
			String afterRenameContent = getResourceContentWithoutXpectComment(specifiedResourcePath, resource);

			expectation.assertDiffEquals(beforeRenameContent, afterRenameContent);
		}
	} finally {
		EditorsUtil.forceCloseAllEditors();
	}
}
 
Example #27
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createCompilationUnitRewrite(final ITypeBinding[] parameters, final CompilationUnitRewrite targetRewrite, final Map<ICompilationUnit, SearchMatch[]> typeReferences, final Map<ICompilationUnit, SearchMatch[]> constructorReferences, boolean visibilityWasAdjusted, final ICompilationUnit sourceUnit, final ICompilationUnit targetUnit, final boolean remove, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(parameters);
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(typeReferences);
	Assert.isNotNull(constructorReferences);
	Assert.isNotNull(sourceUnit);
	Assert.isNotNull(targetUnit);
	final CompilationUnit root= targetRewrite.getRoot();
	final ASTRewrite rewrite= targetRewrite.getASTRewrite();
	if (targetUnit.equals(sourceUnit)) {
		final AbstractTypeDeclaration declaration= findTypeDeclaration(fType, root);
		final TextEditGroup qualifierGroup= fSourceRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_qualifier);
		ITypeBinding binding= declaration.resolveBinding();
		if (!remove) {
			if (!JdtFlags.isStatic(fType) && fCreateInstanceField) {
				if (JavaElementUtil.getAllConstructors(fType).length == 0)
					createConstructor(declaration, rewrite);
				else
					modifyConstructors(declaration, rewrite);
				addInheritedTypeQualifications(declaration, targetRewrite, qualifierGroup);
				addEnclosingInstanceDeclaration(declaration, rewrite);
			}
			fTypeImports= new HashSet<ITypeBinding>();
			fStaticImports= new HashSet<IBinding>();
			ImportRewriteUtil.collectImports(fType.getJavaProject(), declaration, fTypeImports, fStaticImports, false);
			if (binding != null)
				fTypeImports.remove(binding);
		}
		addEnclosingInstanceTypeParameters(parameters, declaration, rewrite);
		modifyAccessToEnclosingInstance(targetRewrite, declaration, monitor);
		if (binding != null) {
			modifyInterfaceMemberModifiers(binding);
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null)
				declaration.accept(new TypeReferenceQualifier(binding, null));
		}
		final TextEditGroup groupMove= targetRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_label);
		if (remove) {
			rewrite.remove(declaration, groupMove);
			targetRewrite.getImportRemover().registerRemovedNode(declaration);
		} else {
			// Bug 101017/96308: Rewrite the visibility of the element to be
			// moved and add a warning.

			// Note that this cannot be done in the MemberVisibilityAdjustor, as the private and
			// static flags must always be cleared when moving to new type.
			int newFlags= JdtFlags.clearFlag(Modifier.STATIC, declaration.getModifiers());

			if (!visibilityWasAdjusted) {
				if (Modifier.isPrivate(declaration.getModifiers()) || Modifier.isProtected(declaration.getModifiers())) {
					newFlags= JdtFlags.clearFlag(Modifier.PROTECTED | Modifier.PRIVATE, newFlags);
					final RefactoringStatusEntry entry= new RefactoringStatusEntry(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_visibility_type_warning, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)}), JavaStatusContext.create(fSourceRewrite.getCu()));
					if (!containsStatusEntry(status, entry))
						status.addEntry(entry);
				}
			}

			ModifierRewrite.create(rewrite, declaration).setModifiers(newFlags, groupMove);
		}
	}
	ASTNode[] references= getReferenceNodesIn(root, typeReferences, targetUnit);
	for (int index= 0; index < references.length; index++)
		updateTypeReference(parameters, references[index], targetRewrite, targetUnit);
	references= getReferenceNodesIn(root, constructorReferences, targetUnit);
	for (int index= 0; index < references.length; index++)
		updateConstructorReference(parameters, references[index], targetRewrite, targetUnit);
}
 
Example #28
Source File: StatusWrapper.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public void add(int severity, String message, Object... params) {
	status.addEntry(new RefactoringStatusEntry(severity, format(message, params)));
}
 
Example #29
Source File: StatusWrapper.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public void add(int severity, String message, Exception exc, Logger log) {
	String formatted = format(message, exc);
	status.addEntry(new RefactoringStatusEntry(severity, formatted + ".\nSee log for details."));
	log.error(formatted, exc);
}
 
Example #30
Source File: StatusWrapper.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public void add(int severity, String message, EObject element, ITextRegion region) {
	status.addEntry(new RefactoringStatusEntry(severity, notNull(message), createContext(element, region)));
}