org.eclipse.jdt.core.dom.IAnnotationBinding Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.IAnnotationBinding. 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: ASTUtils.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
private static String getPageDoc(
        IAnnotationBinding[] annotations, AcceptableLocales locales) {
    Map<Locale, String> allPages = getAllPageDocs(annotations);
    if (allPages.isEmpty()) {
        return null; // no @Page found
    }

    for (Locale locale : locales.getLocales()) {
        String value = allPages.get(locale);
        if (value != null) {
            return value;
        }
    }
    // set empty string if no locale matched data is found
    return "";
}
 
Example #2
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void setParameterNamesAndAnnotations(IMethodBinding method, ITypeBinding[] parameterTypes,
		String[] parameterNames, JvmExecutable result) {
	InternalEList<JvmFormalParameter> parameters = (InternalEList<JvmFormalParameter>)result.getParameters();
	for (int i = 0; i < parameterTypes.length; i++) {
		IAnnotationBinding[] parameterAnnotations;
		try {
			parameterAnnotations = method.getParameterAnnotations(i);
		} catch(AbortCompilation aborted) {
			parameterAnnotations = null;
		}
		ITypeBinding parameterType = parameterTypes[i];
		String parameterName = parameterNames == null ? null /* lazy */ : i < parameterNames.length ? parameterNames[i] : "arg" + i;
		JvmFormalParameter formalParameter = createFormalParameter(parameterType, parameterName, parameterAnnotations);
		parameters.addUnique(formalParameter);
	}
}
 
Example #3
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void createAnnotationValues(IBinding annotated, JvmAnnotationTarget result) {
	try {
		resolveAnnotations.start();
		IAnnotationBinding[] annotationBindings = annotated.getAnnotations();
		if (annotationBindings.length != 0) {
			InternalEList<JvmAnnotationReference> annotations = (InternalEList<JvmAnnotationReference>)result.getAnnotations();
			for (IAnnotationBinding annotation : annotationBindings) {
				annotations.addUnique(createAnnotationReference(annotation));
			}
		}
	} catch(AbortCompilation aborted) {
		if (aborted.problem.getID() == IProblem.IsClassPathCorrect) {
			// ignore
		} else {
			log.info("Couldn't resolve annotations of "+annotated, aborted);
		}
	} finally {
		resolveAnnotations.stop();
	}
}
 
Example #4
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.4
 */
protected JvmAnnotationReference createAnnotationReference(/* @NonNull */ IAnnotationBinding annotation) {
	JvmAnnotationReference annotationReference = TypesFactory.eINSTANCE.createJvmAnnotationReference();
	ITypeBinding annotationType = annotation.getAnnotationType();
	annotationReference.setAnnotation(createAnnotationProxy(annotationType));
	InternalEList<JvmAnnotationValue> values = (InternalEList<JvmAnnotationValue>)annotationReference.getExplicitValues();
	IMemberValuePairBinding[] allMemberValuePairs = annotation.getDeclaredMemberValuePairs();
	for (IMemberValuePairBinding memberValuePair : allMemberValuePairs) {
		IMethodBinding methodBinding = memberValuePair.getMethodBinding();
		if (methodBinding != null) {
			try {
				values.addUnique(createAnnotationValue(annotationType, memberValuePair.getValue(), methodBinding));
			} catch(NullPointerException npe) {
				// memberValuePair#getValue may throw an NPE if the methodBinding has no return type
				if (methodBinding.getReturnType() != null) {
					throw npe;
				} else {
					if (log.isDebugEnabled()) {
						log.debug(npe.getMessage(), npe);
					}
				}
			}
		}
	}
	return annotationReference;
}
 
Example #5
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private JvmAnnotationValue createAnnotationAnnotationValue(Object value) {
	JvmAnnotationAnnotationValue annotationValue = TypesFactory.eINSTANCE.createJvmAnnotationAnnotationValue();
	if (value != null) {
		InternalEList<JvmAnnotationReference> values = (InternalEList<JvmAnnotationReference>)annotationValue.getValues();
		if (value instanceof Object[]) {
			for (Object element : (Object[])value) {
				if (element instanceof IAnnotationBinding) {
					values.addUnique(createAnnotationReference((IAnnotationBinding)element));
				}
			}
		} else if (value instanceof IAnnotationBinding) {
			values.addUnique(createAnnotationReference((IAnnotationBinding)value));
		}
	}
	return annotationValue;
}
 
Example #6
Source File: ValidationSuppressionVisitor.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private void processAnnotationBinding(
    IAnnotationBinding resolvedAnnotationBinding) {
  if (resolvedAnnotationBinding != null) {
    ITypeBinding annotationType = resolvedAnnotationBinding.getAnnotationType();
    if (annotationType != null) {
      if (annotationType.getQualifiedName().equals(
          SuppressWarnings.class.getName())) {
        IMemberValuePairBinding[] allMemberValuePairs = resolvedAnnotationBinding.getAllMemberValuePairs();
        for (IMemberValuePairBinding iMemberValuePairBinding : allMemberValuePairs) {
          if (computeSuppressWarning(iMemberValuePairBinding)) {
            suppressValidation = true;
            break;
          }
        }
      }
    }
  }
}
 
Example #7
Source File: ModelUtils.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return an empty optional if the given package binding is not the top
 *         package of a JtxtUML model; otherwise an optional of the name of
 *         the model (the name is the name of the package if not specified)
 */
public static Optional<String> findModelNameInTopPackage(IPackageBinding packageBinding) {
	List<IAnnotationBinding> annots = Stream.of(packageBinding.getAnnotations())
			.filter(a -> a.getAnnotationType().getQualifiedName().equals(Model.class.getCanonicalName()))
			.collect(Collectors.toList());

	if (annots.size() == 1) {
		Optional<String> name = Stream.of(annots.get(0).getDeclaredMemberValuePairs())
				.filter(p -> p.getName().equals("value")).map(p -> (String) p.getValue()).findAny();
		if (name.isPresent()) {
			return name;
		} else {
			return Optional.of(packageBinding.getName());
		}
	}

	return Optional.empty();
}
 
Example #8
Source File: SharedUtils.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
public static ITypeBinding obtainTypeLiteralAnnotation(BodyDeclaration declaration, Class<?> annotationClass, String name) {
	//TODO NA: need a better solution instead of string literals..
	IAnnotationBinding annot = obtainAnnotationBinding(declaration, annotationClass);
	if (annot != null) {
		for(IMemberValuePairBinding annotValue : annot.getAllMemberValuePairs()) {
			if(annotValue.getName().equals(name)) {
				Object value = annotValue.getValue();
				if(value instanceof ITypeBinding) {
					return (ITypeBinding) value;
				}
				
			}
			
		}
	}		
	return null;
}
 
Example #9
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 6 votes vote down vote up
private void createAnnotationInstanceFromAnnotationInstanceBinding(IAnnotationBinding annotationInstanceBinding,
		ITypeBinding annotationTypeBinding, AnnotationInstance annotationInstance) {
	AnnotationType annotationType = (AnnotationType) ensureTypeFromTypeBinding(annotationTypeBinding);
	annotationInstance.setAnnotationType(annotationType);
	IMemberValuePairBinding[] allMemberValuePairs = annotationInstanceBinding.getAllMemberValuePairs();
	for (IMemberValuePairBinding memberValueBinding : allMemberValuePairs) {
		try {
			Object value = memberValueBinding.getValue();
			AnnotationInstanceAttribute annotationInstanceAttribute = new AnnotationInstanceAttribute();

			annotationInstanceAttribute.setValue(annotationInstanceAttributeValueString(value));
			annotationInstance.addAttributes(annotationInstanceAttribute);
			repository.add(annotationInstanceAttribute);

			annotationInstanceAttribute.setAnnotationTypeAttribute(
					ensureAnnotationTypeAttribute(annotationType, memberValueBinding.getName()));
		} catch (NullPointerException npe) {
			logger.error(
					"Null pointer exception in jdt core when getting the value of annotation instance attribute "
							+ memberValueBinding.getKey());
		}
	}
}
 
Example #10
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void addAnnotation(StringBuffer buf, IJavaElement element, IAnnotationBinding annotation) throws URISyntaxException {
	IJavaElement javaElement= annotation.getAnnotationType().getJavaElement();
	buf.append('@');
	if (javaElement != null) {
		String uri= JavaElementLinks.createURI(JavaElementLinks.JAVADOC_SCHEME, javaElement);
		addLink(buf, uri, annotation.getName());
	} else {
		buf.append(annotation.getName());
	}
	
	IMemberValuePairBinding[] mvPairs= annotation.getDeclaredMemberValuePairs();
	if (mvPairs.length > 0) {
		buf.append('(');
		for (int j= 0; j < mvPairs.length; j++) {
			if (j > 0) {
				buf.append(JavaElementLabels.COMMA_STRING);
			}
			IMemberValuePairBinding mvPair= mvPairs[j];
			String memberURI= JavaElementLinks.createURI(JavaElementLinks.JAVADOC_SCHEME, mvPair.getMethodBinding().getJavaElement());
			addLink(buf, memberURI, mvPair.getName());
			buf.append('=');
			addValue(buf, element, mvPair.getValue());
		}
		buf.append(')');
	}
}
 
Example #11
Source File: ASTUtils.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
public static IAnnotationBinding getAnnotationBinding(
        IAnnotationBinding[] annotations, String annotationClassName) {
    if (annotations == null) {
        return null;
    }
    if (annotationClassName == null) {
        throw new NullPointerException();
    }

    for (IAnnotationBinding annotation : annotations) {
        String qName = annotation.getAnnotationType().getBinaryName();
        assert qName != null;
        // TODO if multiple annotations for annotationClassName exists
        if (qName.equals(annotationClassName)) {
            return annotation;
        }
    }
    return null;
}
 
Example #12
Source File: ASTUtils.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
private static Object getAnnotationValue(IAnnotationBinding annotation, String varName) {
    if (annotation == null) {
        throw new NullPointerException();
    }
    if (varName == null) {
        throw new NullPointerException();
    }
    for (IMemberValuePairBinding value : annotation.getDeclaredMemberValuePairs()) {
        if (value.getName() != null && value.getName().equals(varName)) {
            assert value.getValue() != null; // annotation value cannot be null
            assert !(value.getValue() instanceof IVariableBinding);
            return value.getValue();
        }
    }
    return null;
}
 
Example #13
Source File: ASTUtils.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
private static String getEnumAnnotationFieldName(IAnnotationBinding annotation, String varName) {
    if (annotation == null) {
        throw new NullPointerException();
    }
    if (varName == null) {
        throw new NullPointerException();
    }
    for (IMemberValuePairBinding value : annotation.getDeclaredMemberValuePairs()) {
        if (value.getName() != null && value.getName().equals(varName)) {
            assert value.getValue() != null; // annotation value cannot be null
            assert value.getValue() instanceof IVariableBinding;
            IVariableBinding varBinding = (IVariableBinding) value.getValue();
            assert varBinding.isEnumConstant();
            return varBinding.getName();
        }
    }
    return null;
}
 
Example #14
Source File: ASTUtils.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
private static Pair<String, CaptureStyle> getTestDoc(
        IAnnotationBinding[] annotations, AcceptableLocales locales) {
    Pair<Map<Locale, String>, CaptureStyle> allTestDocs = getAllTestDocs(annotations);
    Map<Locale, String> testDocMap = allTestDocs.getLeft();
    if (testDocMap.isEmpty()) {
        return Pair.of(null, CaptureStyle.getDefault()); // no @TestDoc found
    }

    String testDoc = null;
    for (Locale locale : locales.getLocales()) {
        String value = testDocMap.get(locale);
        if (value != null) {
            testDoc = value;
            break;
        }
    }
    if (testDoc == null) {
        // set empty string if no locale matched data is found
        return Pair.of("", allTestDocs.getRight());
    } else {
        return Pair.of(testDoc, allTestDocs.getRight());
    }
}
 
Example #15
Source File: JsInteropUtils.java    From j2cl with Apache License 2.0 5 votes vote down vote up
/**
 * Simply resolve the JsInfo from annotations. Do not do any extra computations. For example, if
 * there is no "name" is specified in the annotation, just returns null for JsName.
 */
public static JsInfo getJsInfo(IMethodBinding methodBinding) {
  IAnnotationBinding annotation = JsInteropAnnotationUtils.getJsMethodAnnotation(methodBinding);
  if (annotation == null) {
    annotation = JsInteropAnnotationUtils.getJsConstructorAnnotation(methodBinding);
  }
  if (annotation == null) {
    annotation = JsInteropAnnotationUtils.getJsPropertyAnnotation(methodBinding);
  }

  boolean isPropertyAccessor =
      JsInteropAnnotationUtils.getJsPropertyAnnotation(methodBinding) != null;
  return getJsInfo(
      methodBinding, methodBinding.getDeclaringClass(), annotation, isPropertyAccessor);
}
 
Example #16
Source File: ASTUtils.java    From sahagin-java with Apache License 2.0 5 votes vote down vote up
private static IAnnotationBinding getAnnotationBinding(
        IAnnotationBinding[] annotations, Class<?> annotationClass) {
    if (annotationClass == null) {
        throw new NullPointerException();
    }
    return getAnnotationBinding(annotations, annotationClass.getCanonicalName());
}
 
Example #17
Source File: ASTUtils.java    From sahagin-java with Apache License 2.0 5 votes vote down vote up
private static CaptureStyle getAnnotationCaptureStyleValue(
        IAnnotationBinding annotation, String varName) {
    String fieldName = getEnumAnnotationFieldName(annotation, varName);
    if (fieldName == null) {
        return CaptureStyle.getDefault();
    }
    CaptureStyle resultCaptureStyle = CaptureStyle.valueOf(fieldName);
    if (resultCaptureStyle == null) {
        throw new RuntimeException("invalid captureStyle: " + fieldName);
    }
    return resultCaptureStyle;
}
 
Example #18
Source File: JsInteropUtils.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private static JsInfo getJsInfo(
    IBinding member,
    ITypeBinding declaringType,
    IAnnotationBinding memberAnnotation,
    boolean isAccessor) {

  boolean jsOverlay = isJsOverlay(member);
  boolean jsAsync = isJsAsync(member);

  if (JsInteropAnnotationUtils.getJsIgnoreAnnotation(member) == null) {
    boolean publicMemberOfJsType =
        isJsType(declaringType) && Modifier.isPublic(member.getModifiers());
    boolean isJsEnumConstant =
        isJsEnum(declaringType)
            && member instanceof IVariableBinding
            && ((IVariableBinding) member).isEnumConstant();
    boolean memberOfNativeType = isJsNativeType(declaringType) && !isJsEnum(declaringType);
    if (memberAnnotation != null
        || ((publicMemberOfJsType || isJsEnumConstant || memberOfNativeType) && !jsOverlay)) {
      return JsInfo.newBuilder()
          .setJsMemberType(getJsMemberType(member, isAccessor))
          .setJsName(JsInteropAnnotationUtils.getJsName(memberAnnotation))
          .setJsNamespace(JsInteropAnnotationUtils.getJsNamespace(memberAnnotation))
          .setJsOverlay(jsOverlay)
          .setJsAsync(jsAsync)
          .build();
    }
  }

  return JsInfo.newBuilder()
      .setJsMemberType(JsMemberType.NONE)
      .setJsOverlay(jsOverlay)
      .setJsAsync(jsAsync)
      .build();
}
 
Example #19
Source File: ASTUtils.java    From sahagin-java with Apache License 2.0 5 votes vote down vote up
private static Locale getAnnotationLocaleValue(
        IAnnotationBinding annotation, String varName) {
    String fieldName = getEnumAnnotationFieldName(annotation, varName);
    if (fieldName == null) {
        return Locale.getDefault();
    }
    Locale resultLocale = Locale.valueOf(fieldName);
    if (resultLocale == null) {
        throw new RuntimeException("invalid locale: " + fieldName);
    }
    return resultLocale;
}
 
Example #20
Source File: MultiplicityProvider.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
private static Integer getExplicitMultiplicity(ITypeBinding typeDeclaration, String annotationName) {
	for (IAnnotationBinding annot : typeDeclaration.getAnnotations()) {
		if (annot.getName().equals(annotationName)) {
			for (IMemberValuePairBinding pair : annot.getAllMemberValuePairs()) {
				if (pair.getName().equals("value")) {
					return (Integer) pair.getValue();
				}
			}
		}
	}
	return null;
}
 
Example #21
Source File: ElementTypeTeller.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isBehavioralPort(TypeDeclaration typeDeclaration) {
	for (IAnnotationBinding annot : typeDeclaration.resolveBinding().getAnnotations()) {
		if (annot.getAnnotationType().getQualifiedName().equals(BehaviorPort.class.getCanonicalName())) {
			return true;
		}
	}
	return false;
}
 
Example #22
Source File: SharedUtils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return the annotation binding if it is present on the declaration or null
 */
public static IAnnotationBinding obtainAnnotation(IBinding binding, Class<?> annotationClass) {
	for (IAnnotationBinding annotation : binding.getAnnotations()) {
		if (identicalAnnotations(annotation, annotationClass)) {
			return annotation;
		}
	}
	return null;
}
 
Example #23
Source File: SharedUtils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
public static IAnnotationBinding obtainAnnotationBinding(BodyDeclaration declaration, Class<?> annotationClass) {
	for (Object mod : declaration.modifiers()) {
		IExtendedModifier modifier = (IExtendedModifier) mod;
		if (modifier.isAnnotation()) {
			Annotation annotation = (Annotation) modifier;
			if (identicalAnnotations(annotation, annotationClass)) {
				return annotation.resolveAnnotationBinding();
			}
		}
	}
	return null;
}
 
Example #24
Source File: ValidationSuppressionVisitor.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(SingleMemberAnnotation node) {
  IAnnotationBinding resolvedAnnotationBinding = node.resolveAnnotationBinding();
  processAnnotationBinding(resolvedAnnotationBinding);
  
  // Don't visit this node's children; they don't impact the result    
  return false;
}
 
Example #25
Source File: ValidationSuppressionVisitor.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(NormalAnnotation node) {
  IAnnotationBinding resolvedAnnotationBinding = node.resolveAnnotationBinding();
  processAnnotationBinding(resolvedAnnotationBinding);
  
  // Don't visit this node's children; they don't impact the result
  return false;
}
 
Example #26
Source File: RedundantNullnessTypeAnnotationsFilter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public IAnnotationBinding[] removeUnwantedTypeAnnotations(IAnnotationBinding[] annotations, TypeLocation location, ITypeBinding type) {
	if (location == TypeLocation.OTHER) {
		return NO_ANNOTATIONS;
	}
	if(type.isTypeVariable() || type.isWildcardType()) {
		return annotations;
	}
	boolean excludeAllNullAnnotations = NEVER_NULLNESS_LOCATIONS.contains(location);
	if (excludeAllNullAnnotations || fNonNullByDefaultLocations.contains(location)) {
		ArrayList<IAnnotationBinding> list= new ArrayList<>(annotations.length);
		for (IAnnotationBinding annotation : annotations) {
			ITypeBinding annotationType= annotation.getAnnotationType();
			if (annotationType != null) {
				if (annotationType.getQualifiedName().equals(fNonNullAnnotationName)) {
					// ignore @NonNull
				} else if (excludeAllNullAnnotations && annotationType.getQualifiedName().equals(fNullableAnnotationName)) {
					// also ignore @Nullable
				} else {
					list.add(annotation);
				}
			} else {
				list.add(annotation);
			}
		}
		return list.size() == annotations.length ? annotations : list.toArray(new IAnnotationBinding[list.size()]);
	} else {
		return annotations;
	}
}
 
Example #27
Source File: RedundantNullnessTypeAnnotationsFilter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static EnumSet<TypeLocation> determineNonNullByDefaultLocations(ASTNode astNode, String nonNullByDefaultName) {
	// look for first @NonNullByDefault
	while (astNode != null) {
		IAnnotationBinding annot= getNNBDAnnotation(astNode, nonNullByDefaultName);
		if (annot != null) {
			return determineNNBDValue(annot);
		}
		astNode= astNode.getParent();
	}
	return EnumSet.noneOf(TypeLocation.class);
}
 
Example #28
Source File: TypeAnnotationRewrite.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IAnnotationBinding findTargetAnnotation(IAnnotationBinding[] metaAnnotations) {
	for (int i= 0; i < metaAnnotations.length; i++) {
		IAnnotationBinding binding= metaAnnotations[i];
		ITypeBinding annotationType= binding.getAnnotationType();
		if (annotationType != null && annotationType.getQualifiedName().equals(Target.class.getName())) {
			return binding;
		}
	}
	return null;
}
 
Example #29
Source File: TypeAnnotationRewrite.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean isPureTypeAnnotation(Annotation annotation) {
	IAnnotationBinding binding= annotation.resolveAnnotationBinding();
	if (binding == null) {
		return false;
	}
	IAnnotationBinding targetAnnotationBinding= findTargetAnnotation(binding.getAnnotationType().getAnnotations());

	if (targetAnnotationBinding == null) {
		return false;
	}
	return isTypeUseOnly(targetAnnotationBinding);
}
 
Example #30
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 5 votes vote down vote up
public AnnotationInstance createAnnotationInstanceFromAnnotationBinding(NamedEntity entity,
		IAnnotationBinding annotationInstanceBinding) {
	ITypeBinding annotationTypeBinding = annotationInstanceBinding.getAnnotationType();
	AnnotationInstance annotationInstance = new AnnotationInstance();
	annotationInstance.setAnnotatedEntity(entity);
	if (annotationInstanceBinding != null) {
		createAnnotationInstanceFromAnnotationInstanceBinding(annotationInstanceBinding, annotationTypeBinding,
				annotationInstance);
	}
	repository.add(annotationInstance);
	return annotationInstance;
}