Java Code Examples for org.eclipse.jdt.internal.corext.util.JavaModelUtil#is50OrHigher()

The following examples show how to use org.eclipse.jdt.internal.corext.util.JavaModelUtil#is50OrHigher() . 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: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 7 votes vote down vote up
private Statement createAddArrayHashCode(IVariableBinding binding) {
	MethodInvocation invoc= fAst.newMethodInvocation();
	if (JavaModelUtil.is50OrHigher(fRewrite.getCu().getJavaProject())) {
		invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
		invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS));
		invoc.arguments().add(getThisAccessForHashCode(binding.getName()));
	} else {
		invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
		final IJavaElement element= fType.getJavaElement();
		if (element != null && !"".equals(element.getElementName())) //$NON-NLS-1$
			invoc.setExpression(fAst.newSimpleName(element.getElementName()));
		invoc.arguments().add(getThisAccessForHashCode(binding.getName()));
		ITypeBinding type= binding.getType().getElementType();
		if (!Bindings.isVoidType(type)) {
			if (!type.isPrimitive() || binding.getType().getDimensions() >= 2)
				type= fAst.resolveWellKnownType(JAVA_LANG_OBJECT);
			if (!fCustomHashCodeTypes.contains(type))
				fCustomHashCodeTypes.add(type);
		}
	}
	return prepareAssignment(invoc);
}
 
Example 2
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the resource handle that corresponds to the element that was created or
 * will be created.
 * @return A resource or null if the page contains illegal values.
 * @since 3.0
 */
public IResource getModifiedResource() {
	IPackageFragmentRoot root= getPackageFragmentRoot();
	if (root != null) {
		IPackageFragment pack= root.getPackageFragment(getPackageText());
		IResource packRes= pack.getResource();
		if (isCreatePackageDocumentation()) {
			if (JavaModelUtil.is50OrHigher(getJavaProject())) {
				return pack.getCompilationUnit(PACKAGE_INFO_JAVA_FILENAME).getResource();
			} else if (packRes instanceof IFolder){
				return ((IFolder) packRes).getFile(PACKAGE_HTML_FILENAME);
			}
		}

		return packRes;
	}
	return null;
}
 
Example 3
Source File: GetterSetterCorrectionSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static Expression getAssignedValue(ProposalParameter context) {
	ASTNode parent = context.accessNode.getParent();
	ASTRewrite astRewrite = context.astRewrite;
	IJavaProject javaProject = context.compilationUnit.getJavaProject();
	IMethodBinding getter = findGetter(context);
	Expression getterExpression = null;
	if (getter != null) {
		getterExpression = astRewrite.getAST().newSimpleName("placeholder"); //$NON-NLS-1$
	}
	ITypeBinding type = context.variableBinding.getType();
	boolean is50OrHigher = JavaModelUtil.is50OrHigher(javaProject);
	Expression result = GetterSetterUtil.getAssignedValue(parent, astRewrite, getterExpression, type, is50OrHigher);
	if (result != null && getterExpression != null && getterExpression.getParent() != null) {
		getterExpression.getParent().setStructuralProperty(getterExpression.getLocationInParent(), createMethodInvocation(context, getter, null));
	}
	return result;
}
 
Example 4
Source File: Java50Fix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static Java50Fix createFix(CompilationUnit compilationUnit, IProblemLocation problem, String annotation, String label) {
	ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement();
	if (!JavaModelUtil.is50OrHigher(cu.getJavaProject()))
		return null;

	ASTNode selectedNode= problem.getCoveringNode(compilationUnit);
	if (selectedNode == null)
		return null;

	ASTNode declaringNode= getDeclaringNode(selectedNode);
	if (!(declaringNode instanceof BodyDeclaration))
		return null;

	BodyDeclaration declaration= (BodyDeclaration) declaringNode;

	AnnotationRewriteOperation operation= new AnnotationRewriteOperation(declaration, annotation);

	return new Java50Fix(label, compilationUnit, new CompilationUnitRewriteOperation[] {operation});
}
 
Example 5
Source File: ConvertLoopFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean convertForLoops, boolean convertIterableForLoops, boolean makeFinal) {
	if (!JavaModelUtil.is50OrHigher(compilationUnit.getJavaElement().getJavaProject()))
		return null;

	if (!convertForLoops && !convertIterableForLoops)
		return null;

	List<ConvertLoopOperation> operations= new ArrayList<ConvertLoopOperation>();
	ControlStatementFinder finder= new ControlStatementFinder(convertForLoops, convertIterableForLoops, makeFinal, operations);
	compilationUnit.accept(finder);

	if (operations.isEmpty())
		return null;

	CompilationUnitRewriteOperation[] ops= operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
	return new ConvertLoopFix(FixMessages.ControlStatementsFix_change_name, compilationUnit, ops, null);
}
 
Example 6
Source File: NullAnnotationsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, IProblemLocation[] locations, int problemID) {
	ICompilationUnit cu= (ICompilationUnit) compilationUnit.getJavaElement();
	if (!JavaModelUtil.is50OrHigher(cu.getJavaProject()))
		return null;

	List<CompilationUnitRewriteOperation> operations= new ArrayList<CompilationUnitRewriteOperation>();
	if (locations == null) {
		org.eclipse.jdt.core.compiler.IProblem[] problems= compilationUnit.getProblems();
		locations= new IProblemLocation[problems.length];
		for (int i= 0; i < problems.length; i++) {
			if (problems[i].getID() == problemID)
				locations[i]= new ProblemLocation(problems[i]);
		}
	}

	createAddNullAnnotationOperations(compilationUnit, locations, operations);
	createRemoveRedundantNullAnnotationsOperations(compilationUnit, locations, operations);
	if (operations.size() == 0)
		return null;
	CompilationUnitRewriteOperation[] operationsArray= operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
	return new NullAnnotationsFix(FixMessages.NullAnnotationsFix_add_annotation_change_name, compilationUnit, operationsArray);
}
 
Example 7
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 8
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void createAbstractMethod(final IMethod sourceMethod, final CompilationUnitRewrite sourceRewriter, final CompilationUnit declaringCuNode, final AbstractTypeDeclaration destination, final TypeVariableMaplet[] mapping, final CompilationUnitRewrite targetRewrite, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
	final MethodDeclaration oldMethod= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode);
	if (JavaModelUtil.is50OrHigher(sourceMethod.getJavaProject()) && (fSettings.overrideAnnotation || JavaCore.ERROR.equals(sourceMethod.getJavaProject().getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION, true)))) {
		final MarkerAnnotation annotation= sourceRewriter.getAST().newMarkerAnnotation();
		annotation.setTypeName(sourceRewriter.getAST().newSimpleName("Override")); //$NON-NLS-1$
		sourceRewriter.getASTRewrite().getListRewrite(oldMethod, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(annotation, sourceRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_override_annotation, SET_PULL_UP));
	}
	final MethodDeclaration newMethod= targetRewrite.getAST().newMethodDeclaration();
	newMethod.setBody(null);
	newMethod.setConstructor(false);
	copyExtraDimensions(oldMethod, newMethod);
	newMethod.setJavadoc(null);
	int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, Modifier.ABSTRACT | JdtFlags.clearFlag(Modifier.NATIVE | Modifier.FINAL, sourceMethod.getFlags()), adjustments, monitor, false, status);
	if (oldMethod.isVarargs())
		modifiers&= ~Flags.AccVarargs;
	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(targetRewrite.getAST(), modifiers));
	newMethod.setName(((SimpleName) ASTNode.copySubtree(targetRewrite.getAST(), oldMethod.getName())));
	copyReturnType(targetRewrite.getASTRewrite(), getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyParameters(targetRewrite.getASTRewrite(), getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyThrownExceptions(oldMethod, newMethod);
	copyTypeParameters(oldMethod, newMethod);
	ImportRewriteContext context= new ContextSensitiveImportRewriteContext(destination, targetRewrite.getImportRewrite());
	ImportRewriteUtil.addImports(targetRewrite, context, oldMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false);
	targetRewrite.getASTRewrite().getListRewrite(destination, destination.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, destination.bodyDeclarations()), targetRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_abstract_method, SET_PULL_UP));
}
 
Example 9
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private InlineTargetCompilationUnit(CompilationUnitRewrite cuRewrite, Name[] references, InlineConstantRefactoring refactoring, HashSet<SimpleName> staticImportsInInitializer) {
	fInitializer= refactoring.getInitializer();
	fInitializerUnit= refactoring.getDeclaringCompilationUnit();

	fCuRewrite= cuRewrite;
	fSourceRangeComputer= new TightSourceRangeComputer();
	fCuRewrite.getASTRewrite().setTargetSourceRangeComputer(fSourceRangeComputer);
	if (refactoring.getRemoveDeclaration() && refactoring.getReplaceAllReferences() && cuRewrite.getCu().equals(fInitializerUnit))
		fDeclarationToRemove= refactoring.getDeclaration();
	else
		fDeclarationToRemove= null;

	fOriginalDeclaration= refactoring.getDeclaration();

	fReferences= new Expression[references.length];
	for (int i= 0; i < references.length; i++)
		fReferences[i]= getQualifiedReference(references[i]);

	fIs15= JavaModelUtil.is50OrHigher(cuRewrite.getCu().getJavaProject());
	fStaticImportsInInitializer= fIs15 ? staticImportsInInitializer : new HashSet<SimpleName>(0);
}
 
Example 10
Source File: JavaContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor, ICompilationUnit cu) throws JavaModelException {
	boolean is50OrHigher= JavaModelUtil.is50OrHigher(cu.getJavaProject());

	int typeKinds= SimilarElementsRequestor.ALL_TYPES;
	if (nameNode != null) {
		typeKinds= ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher);
	}

	ArrayList<TypeNameMatch> typeInfos= new ArrayList<TypeNameMatch>();
	TypeNameMatchCollector requestor= new TypeNameMatchCollector(typeInfos);
	new SearchEngine().searchAllTypeNames(null, 0, simpleTypeName.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, getSearchForConstant(typeKinds), searchScope, requestor, IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor);

	ArrayList<TypeNameMatch> typeRefsFound= new ArrayList<TypeNameMatch>(typeInfos.size());
	for (int i= 0, len= typeInfos.size(); i < len; i++) {
		TypeNameMatch curr= typeInfos.get(i);
		if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package
			if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr, cu)) {
				typeRefsFound.add(curr);
			}
		}
	}
	return typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
}
 
Example 11
Source File: ImportReferencesCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ImportReferencesCollector(IJavaProject project, CompilationUnit astRoot, Region rangeLimit, boolean skipMethodBodies, Collection<SimpleName> resultingTypeImports, Collection<SimpleName> resultingStaticImports) {
	super(processJavadocComments(astRoot));
	fTypeImports= resultingTypeImports;
	fStaticImports= resultingStaticImports;
	fSubRange= rangeLimit;
	if (project == null || !JavaModelUtil.is50OrHigher(project)) {
		fStaticImports= null; // do not collect
	}
	fASTRoot= astRoot; // can be null
	fSkipMethodBodies= skipMethodBodies;
}
 
Example 12
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Hook method that gets called when the superclass name has changed. The method
 * validates the superclass name and returns the status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus superClassChanged() {
	StatusInfo status= new StatusInfo();
	IPackageFragmentRoot root= getPackageFragmentRoot();
	fSuperClassDialogField.enableButton(root != null);

	fSuperClassStubTypeContext= null;

	String sclassName= getSuperClass();
	if (sclassName.length() == 0) {
		// accept the empty field (stands for java.lang.Object)
		return status;
	}

	if (root != null) {
		Type type= TypeContextChecker.parseSuperClass(sclassName);
		if (type == null) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_InvalidSuperClassName);
			return status;
		}
		if (type instanceof ParameterizedType && ! JavaModelUtil.is50OrHigher(root.getJavaProject())) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_SuperClassNotParameterized);
			return status;
		}
	} else {
		status.setError(""); //$NON-NLS-1$
	}
	return status;
}
 
Example 13
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createMethodComment(MethodDeclaration newDeclaration, IMethodBinding copyFrom) throws CoreException {
	if (fSettings.createComments) {
		String string= CodeGeneration.getMethodComment(fRewrite.getCu(), fType.getQualifiedName(), newDeclaration, copyFrom, StubUtility.getLineDelimiterUsed(fRewrite.getCu()));
		if (string != null) {
			Javadoc javadoc= (Javadoc) fRewrite.getASTRewrite().createStringPlaceholder(string, ASTNode.JAVADOC);
			newDeclaration.setJavadoc(javadoc);
		}
	}
	IJavaProject project= fUnit.getJavaElement().getJavaProject();
	if (fSettings.overrideAnnotation && JavaModelUtil.is50OrHigher(project))
		StubUtility2.addOverrideAnnotation(project, fRewrite.getASTRewrite(), newDeclaration, copyFrom);
}
 
Example 14
Source File: ModifierCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addOverridingDeprecatedMethodProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {

		ICompilationUnit cu= context.getCompilationUnit();

		ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
		if (!(selectedNode instanceof MethodDeclaration)) {
			return;
		}
		boolean is50OrHigher= JavaModelUtil.is50OrHigher(cu.getJavaProject());
		MethodDeclaration methodDecl= (MethodDeclaration) selectedNode;
		AST ast= methodDecl.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);
		if (is50OrHigher) {
			Annotation annot= ast.newMarkerAnnotation();
			annot.setTypeName(ast.newName("Deprecated")); //$NON-NLS-1$
			rewrite.getListRewrite(methodDecl, methodDecl.getModifiersProperty()).insertFirst(annot, null);
		}
		Javadoc javadoc= methodDecl.getJavadoc();
		if (javadoc != null || !is50OrHigher) {
			if (!is50OrHigher) {
				javadoc= ast.newJavadoc();
				rewrite.set(methodDecl, MethodDeclaration.JAVADOC_PROPERTY, javadoc, null);
			}
			TagElement newTag= ast.newTagElement();
			newTag.setTagName(TagElement.TAG_DEPRECATED);
			JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
		}

		String label= CorrectionMessages.ModifierCorrectionSubProcessor_overrides_deprecated_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.OVERRIDES_DEPRECATED, image);
		proposals.add(proposal);
	}
 
Example 15
Source File: TypeMismatchSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addIncompatibleReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws JavaModelException {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (selectedNode == null) {
		return;
	}
	MethodDeclaration decl= ASTResolving.findParentMethodDeclaration(selectedNode);
	if (decl == null) {
		return;
	}
	IMethodBinding methodDeclBinding= decl.resolveBinding();
	if (methodDeclBinding == null) {
		return;
	}

	ITypeBinding returnType= methodDeclBinding.getReturnType();
	IMethodBinding overridden= Bindings.findOverriddenMethod(methodDeclBinding, false);
	if (overridden == null || overridden.getReturnType() == returnType) {
		return;
	}


	ICompilationUnit cu= context.getCompilationUnit();
	IMethodBinding methodDecl= methodDeclBinding.getMethodDeclaration();
	ITypeBinding overriddenReturnType= overridden.getReturnType();
	if (! JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaProject())) {
		overriddenReturnType= overriddenReturnType.getErasure();
	}
	proposals.add(new TypeChangeCorrectionProposal(cu, methodDecl, astRoot, overriddenReturnType, false, IProposalRelevance.CHANGE_RETURN_TYPE));

	ICompilationUnit targetCu= cu;

	IMethodBinding overriddenDecl= overridden.getMethodDeclaration();
	ITypeBinding overridenDeclType= overriddenDecl.getDeclaringClass();

	if (overridenDeclType.isFromSource()) {
		targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, overridenDeclType);
		if (targetCu != null && ASTResolving.isUseableTypeInContext(returnType, overriddenDecl, false)) {
			TypeChangeCorrectionProposal proposal= new TypeChangeCorrectionProposal(targetCu, overriddenDecl, astRoot, returnType, false, IProposalRelevance.CHANGE_RETURN_TYPE_OF_OVERRIDDEN);
			if (overridenDeclType.isInterface()) {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofimplemented_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			} else {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofoverridden_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			}
			proposals.add(proposal);
		}
	}
}
 
Example 16
Source File: NullAnnotationsRewriteOperations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static SignatureAnnotationRewriteOperation createAddAnnotationToOverriddenOperation(CompilationUnit compilationUnit, IProblemLocation problem, String annotationToAdd,
		String annotationToRemove, boolean allowRemove) {
	ICompilationUnit cu= (ICompilationUnit) compilationUnit.getJavaElement();
	if (!JavaModelUtil.is50OrHigher(cu.getJavaProject()))
		return null;

	ASTNode selectedNode= problem.getCoveringNode(compilationUnit);
	if (selectedNode == null)
		return null;

	ASTNode declaringNode= getDeclaringNode(selectedNode);
	switch (problem.getProblemId()) {
		case IProblem.IllegalDefinitionToNonNullParameter:
		case IProblem.IllegalRedefinitionToNonNullParameter:
			break;
		case IProblem.IllegalReturnNullityRedefinition:
			if (declaringNode == null)
				declaringNode= selectedNode;
			break;
		default:
			return null;
	}

	String annotationNameLabel= annotationToAdd;
	int lastDot= annotationToAdd.lastIndexOf('.');
	if (lastDot != -1)
		annotationNameLabel= annotationToAdd.substring(lastDot + 1);
	annotationNameLabel= BasicElementLabels.getJavaElementName(annotationNameLabel);

	if (declaringNode instanceof MethodDeclaration) {
		// complaint is in signature of this method
		MethodDeclaration declaration= (MethodDeclaration) declaringNode;
		switch (problem.getProblemId()) {
			case IProblem.IllegalDefinitionToNonNullParameter:
			case IProblem.IllegalRedefinitionToNonNullParameter:
				return createChangeOverriddenParameterOperation(compilationUnit, cu, declaration, selectedNode, allowRemove, annotationToAdd, annotationToRemove, annotationNameLabel);
			case IProblem.IllegalReturnNullityRedefinition:
				if (hasNullAnnotation(declaration)) { // don't adjust super if local has no explicit annotation (?)
					return createChangeOverriddenReturnOperation(compilationUnit, cu, declaration, allowRemove, annotationToAdd, annotationToRemove, annotationNameLabel);
				}
		}
	}
	return null;
}
 
Example 17
Source File: OrganizeImportsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static TextEdit wrapStaticImports(TextEdit edit, CompilationUnit root, ICompilationUnit unit) throws MalformedTreeException, CoreException {
	String[] favourites = PreferenceManager.getPrefs(unit.getResource()).getJavaCompletionFavoriteMembers();
	if (favourites.length == 0) {
		return edit;
	}
	IJavaProject project = unit.getJavaProject();
	if (JavaModelUtil.is50OrHigher(project)) {
		List<SimpleName> typeReferences = new ArrayList<>();
		List<SimpleName> staticReferences = new ArrayList<>();
		ImportReferencesCollector.collect(root, project, null, typeReferences, staticReferences);
		if (staticReferences.isEmpty()) {
			return edit;
		}
		ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite(root, true);
		AST ast = root.getAST();
		ASTRewrite astRewrite = ASTRewrite.create(ast);
		for (SimpleName node : staticReferences) {
			addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, true);
			addImports(root, unit, favourites, importRewrite, ast, astRewrite, node, false);
		}
		TextEdit staticEdit = importRewrite.rewriteImports(null);
		if (staticEdit != null && staticEdit.getChildrenSize() > 0) {
			TextEdit lastStatic = staticEdit.getChildren()[staticEdit.getChildrenSize() - 1];
			if (lastStatic instanceof DeleteEdit) {
				if (edit.getChildrenSize() > 0) {
					TextEdit last = edit.getChildren()[edit.getChildrenSize() - 1];
					if (last instanceof DeleteEdit && lastStatic.getOffset() == last.getOffset() && lastStatic.getLength() == last.getLength()) {
						edit.removeChild(last);
					}
				}
			}
			TextEdit firstStatic = staticEdit.getChildren()[0];
			if (firstStatic instanceof InsertEdit) {
				if (edit.getChildrenSize() > 0) {
					TextEdit firstEdit = edit.getChildren()[0];
					if (firstEdit instanceof InsertEdit) {
						if (areEqual((InsertEdit) firstEdit, (InsertEdit) firstStatic)) {
							edit.removeChild(firstEdit);
						}
					}
				}
			}
			try {
				staticEdit.addChild(edit);
				return staticEdit;
			} catch (MalformedTreeException e) {
				JavaLanguageServerPlugin.logException("Failed to resolve static organize imports source action", e);
			}
		}
	}
	return edit;
}
 
Example 18
Source File: Java50Fix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
		boolean addOverrideAnnotation,
		boolean addOverrideInterfaceAnnotation,
		boolean addDeprecatedAnnotation,
		boolean rawTypeReference) {

	ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement();
	if (!JavaModelUtil.is50OrHigher(cu.getJavaProject()))
		return null;

	if (!addOverrideAnnotation && !addDeprecatedAnnotation && !rawTypeReference)
		return null;

	List<CompilationUnitRewriteOperation> operations= new ArrayList<CompilationUnitRewriteOperation>();

	IProblem[] problems= compilationUnit.getProblems();
	IProblemLocation[] locations= new IProblemLocation[problems.length];
	for (int i= 0; i < problems.length; i++) {
		locations[i]= new ProblemLocation(problems[i]);
	}

	if (addOverrideAnnotation)
		createAddOverrideAnnotationOperations(compilationUnit, addOverrideInterfaceAnnotation, locations, operations);

	if (addDeprecatedAnnotation)
		createAddDeprecatedAnnotationOperations(compilationUnit, locations, operations);

	if (rawTypeReference)
		createRawTypeReferenceOperations(compilationUnit, locations, operations);

	if (operations.size() == 0)
		return null;

	String fixName;
	if (rawTypeReference) {
		fixName= FixMessages.Java50Fix_add_type_parameters_change_name;
	} else {
		fixName= FixMessages.Java50Fix_add_annotations_change_name;
	}

	CompilationUnitRewriteOperation[] operationsArray= operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
	return new Java50Fix(fixName, compilationUnit, operationsArray);
}
 
Example 19
Source File: TypeMismatchSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static void addIncompatibleReturnTypeProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (selectedNode == null) {
		return;
	}
	MethodDeclaration decl= ASTResolving.findParentMethodDeclaration(selectedNode);
	if (decl == null) {
		return;
	}
	IMethodBinding methodDeclBinding= decl.resolveBinding();
	if (methodDeclBinding == null) {
		return;
	}

	ITypeBinding returnType= methodDeclBinding.getReturnType();
	IMethodBinding overridden= Bindings.findOverriddenMethod(methodDeclBinding, false);
	if (overridden == null || overridden.getReturnType() == returnType) {
		return;
	}


	ICompilationUnit cu= context.getCompilationUnit();
	IMethodBinding methodDecl= methodDeclBinding.getMethodDeclaration();
	ITypeBinding overriddenReturnType= overridden.getReturnType();
	if (! JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaProject())) {
		overriddenReturnType= overriddenReturnType.getErasure();
	}
	proposals.add(new TypeChangeCorrectionProposal(cu, methodDecl, astRoot, overriddenReturnType, false, IProposalRelevance.CHANGE_RETURN_TYPE));

	ICompilationUnit targetCu= cu;

	IMethodBinding overriddenDecl= overridden.getMethodDeclaration();
	ITypeBinding overridenDeclType= overriddenDecl.getDeclaringClass();

	if (overridenDeclType.isFromSource()) {
		targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, overridenDeclType);
		if (targetCu != null && ASTResolving.isUseableTypeInContext(returnType, overriddenDecl, false)) {
			TypeChangeCorrectionProposal proposal= new TypeChangeCorrectionProposal(targetCu, overriddenDecl, astRoot, returnType, false, IProposalRelevance.CHANGE_RETURN_TYPE_OF_OVERRIDDEN);
			if (overridenDeclType.isInterface()) {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofimplemented_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			} else {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofoverridden_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			}
			proposals.add(proposal);
		}
	}
}
 
Example 20
Source File: FillArgumentNamesCompletionProposalCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns <code>true</code> if generic proposals should be allowed,
 * <code>false</code> if not. Note that even though code (in a library)
 * may be referenced that uses generics, it is still possible that the
 * current source does not allow generics.
 *
 * @param project the Java project
 * @return <code>true</code> if the generic proposals should be allowed,
 *         <code>false</code> if not
 */
private final boolean shouldProposeGenerics(IJavaProject project) {
	String sourceVersion;
	if (project != null)
		sourceVersion= project.getOption(JavaCore.COMPILER_SOURCE, true);
	else
		sourceVersion= JavaCore.getOption(JavaCore.COMPILER_SOURCE);

	return JavaModelUtil.is50OrHigher(sourceVersion);
}