Example usage for org.eclipse.jdt.core.dom Annotation resolveAnnotationBinding

List of usage examples for org.eclipse.jdt.core.dom Annotation resolveAnnotationBinding

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom Annotation resolveAnnotationBinding.

Prototype

public IAnnotationBinding resolveAnnotationBinding() 

Source Link

Document

Resolves and returns the resolved annotation for this annotation.

Usage

From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java

License:Open Source License

@Override
public boolean visit(TypeDeclaration type) {
    if (!Modifier.isPublic(type.getModifiers())) {
        // non-public types cannot be (or have nested) components
        if (errorLevel.isNone())
            return false;

        Annotation annotation = findComponentAnnotation(type);
        if (annotation != null)
            reportProblem(annotation, null, problems,
                    NLS.bind(Messages.AnnotationProcessor_invalidComponentImplementationClass,
                            type.getName().getIdentifier()),
                    type.getName().getIdentifier());

        return true;
    }//w w  w.  j a v  a 2  s  .  c  o m

    Annotation annotation = findComponentAnnotation(type);
    if (annotation != null) {
        if (type.isInterface() || Modifier.isAbstract(type.getModifiers())
                || (!type.isPackageMemberTypeDeclaration() && !isNestedPublicStatic(type))
                || !hasDefaultConstructor(type)) {
            // interfaces, abstract types, non-static/non-public nested types, or types with no default constructor cannot be components
            reportProblem(annotation, null, problems,
                    NLS.bind(Messages.AnnotationProcessor_invalidComponentImplementationClass,
                            type.getName().getIdentifier()),
                    type.getName().getIdentifier());
        } else {
            ITypeBinding typeBinding = type.resolveBinding();
            if (typeBinding == null) {
                if (debug.isDebugging())
                    debug.trace(String.format("Unable to resolve binding for type: %s", type)); //$NON-NLS-1$
            } else {
                IAnnotationBinding annotationBinding = annotation.resolveAnnotationBinding();
                if (annotationBinding == null) {
                    if (debug.isDebugging())
                        debug.trace(String.format("Unable to resolve binding for annotation: %s", annotation)); //$NON-NLS-1$
                } else {
                    IDSModel model = processComponent(type, typeBinding, annotation, annotationBinding,
                            problems);
                    models.add(model);
                }
            }
        }
    }

    return true;
}

From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java

License:Open Source License

private Annotation findComponentAnnotation(AbstractTypeDeclaration type) {
    for (Object item : type.modifiers()) {
        if (!(item instanceof Annotation))
            continue;

        Annotation annotation = (Annotation) item;
        IAnnotationBinding annotationBinding = annotation.resolveAnnotationBinding();
        if (annotationBinding == null) {
            if (debug.isDebugging())
                debug.trace(String.format("Unable to resolve binding for annotation: %s", annotation)); //$NON-NLS-1$

            continue;
        }/*from w ww .j av a  2  s  . c o  m*/

        if (COMPONENT_ANNOTATION.equals(annotationBinding.getAnnotationType().getQualifiedName()))
            return annotation;
    }

    return null;
}

From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java

License:Open Source License

private IDSModel processComponent(TypeDeclaration type, ITypeBinding typeBinding, Annotation annotation,
        IAnnotationBinding annotationBinding, Collection<DSAnnotationProblem> problems) {
    HashMap<String, Object> params = new HashMap<String, Object>();
    for (IMemberValuePairBinding pair : annotationBinding.getDeclaredMemberValuePairs()) {
        params.put(pair.getName(), pair.getValue());
    }/*from  ww w.j  a  v a  2  s .com*/

    boolean requiresV12 = false;

    String implClass = typeBinding.getBinaryName();

    String name = implClass;
    Object value;
    if ((value = params.get("name")) instanceof String) { //$NON-NLS-1$
        name = (String) value;
        validateComponentName(annotation, name, problems);
    }

    Collection<String> services;
    if ((value = params.get("service")) instanceof Object[]) { //$NON-NLS-1$
        Object[] elements = (Object[]) value;
        services = new LinkedHashSet<String>(elements.length);
        Map<String, Integer> serviceDuplicates = errorLevel.isNone() ? null : new HashMap<String, Integer>();
        for (int i = 0; i < elements.length; ++i) {
            ITypeBinding serviceType = (ITypeBinding) elements[i];
            String serviceName = serviceType.getBinaryName();
            if (!errorLevel.isNone()) {
                if (serviceDuplicates.containsKey(serviceName)) {
                    reportProblem(annotation, "service", i, problems, //$NON-NLS-1$
                            Messages.AnnotationProcessor_duplicateServiceDeclaration, serviceName);
                    Integer pos = serviceDuplicates.put(serviceName, null);
                    if (pos != null)
                        reportProblem(annotation, "service", pos.intValue(), problems, //$NON-NLS-1$
                                Messages.AnnotationProcessor_duplicateServiceDeclaration, serviceName);
                } else {
                    serviceDuplicates.put(serviceName, i);
                }
            }

            services.add(serviceName);
            validateComponentService(annotation, typeBinding, serviceType, i, problems);
        }
    } else {
        ITypeBinding[] serviceTypes = typeBinding.getInterfaces();
        services = new ArrayList<String>(serviceTypes.length);
        for (int i = 0; i < serviceTypes.length; ++i) {
            services.add(serviceTypes[i].getBinaryName());
        }
    }

    String factory = null;
    if ((value = params.get("factory")) instanceof String) { //$NON-NLS-1$
        factory = (String) value;
        validateComponentFactory(annotation, factory, problems);
    }

    Boolean serviceFactory = null;
    if ((value = params.get("servicefactory")) instanceof Boolean) { //$NON-NLS-1$
        serviceFactory = (Boolean) value;
    }

    Boolean enabled = null;
    if ((value = params.get("enabled")) instanceof Boolean) { //$NON-NLS-1$
        enabled = (Boolean) value;
    }

    Boolean immediate = null;
    if ((value = params.get("immediate")) instanceof Boolean) { //$NON-NLS-1$
        immediate = (Boolean) value;
    }

    String[] properties;
    if ((value = params.get("property")) instanceof Object[]) { //$NON-NLS-1$
        Object[] elements = (Object[]) value;
        ArrayList<String> list = new ArrayList<String>(elements.length);
        for (int i = 0; i < elements.length; ++i) {
            if (elements[i] instanceof String)
                list.add((String) elements[i]);
        }

        properties = list.toArray(new String[list.size()]);
    } else {
        properties = new String[0];
    }

    String[] propertyFiles;
    if ((value = params.get("properties")) instanceof Object[]) { //$NON-NLS-1$
        Object[] elements = (Object[]) value;
        ArrayList<String> list = new ArrayList<String>(elements.length);
        for (int i = 0; i < elements.length; ++i) {
            if (elements[i] instanceof String)
                list.add((String) elements[i]);
        }

        propertyFiles = list.toArray(new String[list.size()]);
        validateComponentPropertyFiles(annotation,
                ((IType) typeBinding.getJavaElement()).getJavaProject().getProject(), propertyFiles, problems);
    } else {
        propertyFiles = new String[0];
    }

    String configPolicy = null;
    if ((value = params.get("configurationPolicy")) instanceof IVariableBinding) { //$NON-NLS-1$
        IVariableBinding configPolicyBinding = (IVariableBinding) value;
        ConfigurationPolicy configPolicyLiteral = ConfigurationPolicy.valueOf(configPolicyBinding.getName());
        if (configPolicyLiteral != null)
            configPolicy = configPolicyLiteral.toString();
    }

    String configPid = null;
    if ((value = params.get("configurationPid")) instanceof String) { //$NON-NLS-1$
        configPid = (String) value;
        validateComponentConfigPID(annotation, configPid, problems);
        requiresV12 = true;
    }

    DSModel model = new DSModel(new Document(), false);
    IDSComponent component = model.getDSComponent();

    if (name != null)
        component.setAttributeName(name);

    if (factory != null)
        component.setFactory(factory);

    if (enabled != null)
        component.setEnabled(enabled.booleanValue());

    if (immediate != null)
        component.setImmediate(immediate.booleanValue());

    if (configPolicy != null)
        component.setConfigurationPolicy(configPolicy);

    if (configPid != null)
        component.setXMLAttribute("configuration-pid", configPid); //$NON-NLS-1$

    IDSDocumentFactory dsFactory = component.getModel().getFactory();
    IDSImplementation impl = dsFactory.createImplementation();
    component.setImplementation(impl);
    impl.setClassName(implClass);

    if (!services.isEmpty()) {
        IDSService service = dsFactory.createService();
        component.setService(service);
        for (String serviceName : services) {
            IDSProvide provide = dsFactory.createProvide();
            service.addProvidedService(provide);
            provide.setInterface(serviceName);
        }

        if (serviceFactory != null)
            service.setServiceFactory(serviceFactory.booleanValue());
    }

    if (properties.length > 0) {
        HashMap<String, IDSProperty> map = new HashMap<String, IDSProperty>(properties.length);
        for (int i = 0; i < properties.length; ++i) {
            String propertyStr = properties[i];
            String[] pair = propertyStr.split("=", 2); //$NON-NLS-1$
            int colon = pair[0].indexOf(':');
            String propertyName, propertyType;
            if (colon == -1) {
                propertyName = pair[0];
                propertyType = null;
            } else {
                propertyName = pair[0].substring(0, colon);
                propertyType = pair[0].substring(colon + 1);
            }

            String propertyValue = pair.length > 1 ? pair[1].trim() : null;

            IDSProperty property = map.get(propertyName);
            if (property == null) {
                // create a new property
                property = dsFactory.createProperty();
                component.addPropertyElement(property);
                map.put(propertyName, property);
                property.setPropertyName(propertyName);
                property.setPropertyType(propertyType);
                property.setPropertyValue(propertyValue);
                validateComponentProperty(annotation, propertyName, propertyType, propertyValue, i, problems);
            } else {
                // property exists; make it multi-valued
                String content = property.getPropertyElemBody();
                if (content == null) {
                    content = property.getPropertyValue();
                    property.setPropertyElemBody(content);
                    property.setPropertyValue(null);
                }

                if (!errorLevel.isNone()) {
                    String expected = property.getPropertyType() == null || property.getPropertyType().isEmpty()
                            || String.class.getSimpleName().equals(property.getPropertyType())
                                    ? Messages.AnnotationProcessor_stringOrEmpty
                                    : property.getPropertyType();
                    String actual = propertyType == null || String.class.getSimpleName().equals(propertyType)
                            ? Messages.AnnotationProcessor_stringOrEmpty
                            : propertyType;
                    if (!actual.equals(expected))
                        reportProblem(annotation, "property", i, problems, //$NON-NLS-1$
                                NLS.bind(Messages.AnnotationProcessor_inconsistentComponentPropertyType, actual,
                                        expected),
                                actual);
                    else
                        validateComponentProperty(annotation, propertyName, propertyType, propertyValue, i,
                                problems);
                }

                if (propertyValue != null)
                    property.setPropertyElemBody(content + "\n" + pair[1]); //$NON-NLS-1$
            }
        }
    }

    if (propertyFiles.length > 0) {
        for (String propertyFile : propertyFiles) {
            IDSProperties propertiesElement = dsFactory.createProperties();
            component.addPropertiesElement(propertiesElement);
            propertiesElement.setEntry(propertyFile);
        }
    }

    String activate = null;
    Annotation activateAnnotation = null;
    String deactivate = null;
    Annotation deactivateAnnotation = null;
    String modified = null;
    Annotation modifiedAnnotation = null;

    ArrayList<IDSReference> references = new ArrayList<IDSReference>();
    HashMap<String, Annotation> referenceNames = new HashMap<String, Annotation>();

    for (MethodDeclaration method : type.getMethods()) {
        for (Object modifier : method.modifiers()) {
            if (!(modifier instanceof Annotation))
                continue;

            Annotation methodAnnotation = (Annotation) modifier;
            IAnnotationBinding methodAnnotationBinding = methodAnnotation.resolveAnnotationBinding();
            if (methodAnnotationBinding == null) {
                if (debug.isDebugging())
                    debug.trace(
                            String.format("Unable to resolve binding for annotation: %s", methodAnnotation)); //$NON-NLS-1$

                continue;
            }

            String annotationName = methodAnnotationBinding.getAnnotationType().getQualifiedName();

            if (ACTIVATE_ANNOTATION.equals(annotationName)) {
                if (activate == null) {
                    activate = method.getName().getIdentifier();
                    activateAnnotation = methodAnnotation;
                    validateLifeCycleMethod(methodAnnotation, "activate", method, problems); //$NON-NLS-1$
                } else if (!errorLevel.isNone()) {
                    reportProblem(methodAnnotation, null, problems,
                            Messages.AnnotationProcessor_duplicateActivateMethod,
                            method.getName().getIdentifier());
                    if (activateAnnotation != null) {
                        reportProblem(activateAnnotation, null, problems,
                                Messages.AnnotationProcessor_duplicateActivateMethod, activate);
                        activateAnnotation = null;
                    }
                }

                continue;
            }

            if (DEACTIVATE_ANNOTATION.equals(annotationName)) {
                if (deactivate == null) {
                    deactivate = method.getName().getIdentifier();
                    deactivateAnnotation = methodAnnotation;
                    validateLifeCycleMethod(methodAnnotation, "deactivate", method, problems); //$NON-NLS-1$
                } else if (!errorLevel.isNone()) {
                    reportProblem(methodAnnotation, null, problems,
                            Messages.AnnotationProcessor_duplicateDeactivateMethod,
                            method.getName().getIdentifier());
                    if (deactivateAnnotation != null) {
                        reportProblem(deactivateAnnotation, null, problems,
                                Messages.AnnotationProcessor_duplicateDeactivateMethod, deactivate);
                        deactivateAnnotation = null;
                    }
                }

                continue;
            }

            if (MODIFIED_ANNOTATION.equals(annotationName)) {
                if (modified == null) {
                    modified = method.getName().getIdentifier();
                    modifiedAnnotation = methodAnnotation;
                    validateLifeCycleMethod(methodAnnotation, "modified", method, problems); //$NON-NLS-1$
                } else if (!errorLevel.isNone()) {
                    reportProblem(methodAnnotation, null, problems,
                            Messages.AnnotationProcessor_duplicateModifiedMethod,
                            method.getName().getIdentifier());
                    if (modifiedAnnotation != null) {
                        reportProblem(modifiedAnnotation, null, problems,
                                Messages.AnnotationProcessor_duplicateModifiedMethod, modified);
                        modifiedAnnotation = null;
                    }
                }

                continue;
            }

            if (REFERENCE_ANNOTATION.equals(annotationName)) {
                IMethodBinding methodBinding = method.resolveBinding();
                if (methodBinding == null) {
                    if (debug.isDebugging())
                        debug.trace(String.format("Unable to resolve binding for method: %s", method)); //$NON-NLS-1$
                } else {
                    requiresV12 |= processReference(method, methodBinding, methodAnnotation,
                            methodAnnotationBinding, dsFactory, references, referenceNames, problems);
                }

                continue;
            }
        }
    }

    if (activate != null)
        component.setActivateMethod(activate);

    if (deactivate != null)
        component.setDeactivateMethod(deactivate);

    if (modified != null)
        component.setModifiedeMethod(modified);

    if (!references.isEmpty()) {
        // references must be declared in ascending lexicographical order of their names
        Collections.sort(references, REF_NAME_COMPARATOR);
        for (IDSReference reference : references) {
            component.addReference(reference);
        }
    }

    String xmlns = null;
    if ((value = params.get("xmlns")) instanceof String) { //$NON-NLS-1$
        xmlns = (String) value;
        validateComponentXMLNS(annotation, xmlns, requiresV12, problems);
    } else if (requiresV12) {
        xmlns = NAMESPACE_1_2;
    }

    if (xmlns != null)
        component.setNamespace(xmlns);

    return model;
}

From source file:com.google.devtools.j2objc.InputFilePreprocessor.java

License:Apache License

private void extractPackagePrefix(InputFile file, CompilationUnit unit) {
    // We should only reach here if it's a package-info.java file.
    assert file.getUnitName().endsWith("package-info.java");
    @SuppressWarnings("unchecked")
    List<Annotation> annotations = (List<Annotation>) unit.getPackage().annotations();
    for (Annotation annotation : annotations) {
        // getFullyQualifiedName() might not actually return a fully qualified name.
        String name = annotation.getTypeName().getFullyQualifiedName();
        if (name.endsWith("ObjectiveCName")) {
            // Per Eclipse docs, binding resolution can be a resource hog.
            if (annotation.resolveAnnotationBinding().getAnnotationType().getQualifiedName()
                    .equals(ObjectiveCName.class.getCanonicalName())) {
                String key = unit.getPackage().getName().getFullyQualifiedName();
                String val = (String) ((SingleMemberAnnotation) annotation).getValue()
                        .resolveConstantExpressionValue();
                String previousVal = Options.addPackagePrefix(key, val);
                if (previousVal != null && !previousVal.equals(val)) {
                    ErrorUtil.error(String.format(
                            "Package %s has name %s defined in file %s, but" + "is already named %s", key, val,
                            file.getPath(), previousVal));
                }/* w  ww .  j  a  v a 2s .  c  om*/
            }
        }
    }
}

From source file:com.google.devtools.j2objc.PackageInfoPreProcessor.java

License:Apache License

protected void processUnit(InputFile file, CompilationUnit unit) {
    // We should only reach here if it's a package-info.java file.
    assert file.getUnitName().endsWith("package-info.java");
    @SuppressWarnings("unchecked")
    List<Annotation> annotations = (List<Annotation>) unit.getPackage().annotations();
    for (Annotation annotation : annotations) {
        // getFullyQualifiedName() might not actually return a fully qualified name.
        String name = annotation.getTypeName().getFullyQualifiedName();
        if (name.endsWith("ObjectiveCName")) {
            // Per Eclipse docs, binding resolution can be a resource hog.
            if (annotation.resolveAnnotationBinding().getAnnotationType().getQualifiedName()
                    .equals(ObjectiveCName.class.getCanonicalName())) {
                String key = unit.getPackage().getName().getFullyQualifiedName();
                String val = (String) ((SingleMemberAnnotation) annotation).getValue()
                        .resolveConstantExpressionValue();
                String previousVal = Options.addPackagePrefix(key, val);
                if (previousVal != null && !previousVal.equals(val)) {
                    ErrorUtil.error(String.format(
                            "Package %s has name %s defined in file %s, but" + "is already named %s", key, val,
                            file.getPath(), previousVal));
                }/*from  w  w  w.java2  s  .  co m*/
            }
        }
    }
}

From source file:com.google.devtools.j2objc.pipeline.InputFilePreprocessor.java

License:Apache License

private void extractPackagePrefix(InputFile file, CompilationUnit unit) {
    // We should only reach here if it's a package-info.java file.
    assert file.getUnitName().endsWith("package-info.java");
    @SuppressWarnings("unchecked")
    List<Annotation> annotations = (List<Annotation>) unit.getPackage().annotations();
    for (Annotation annotation : annotations) {
        // getFullyQualifiedName() might not actually return a fully qualified name.
        String name = annotation.getTypeName().getFullyQualifiedName();
        if (name.endsWith("ObjectiveCName")) {
            // Per Eclipse docs, binding resolution can be a resource hog.
            if (annotation.resolveAnnotationBinding().getAnnotationType().getQualifiedName()
                    .equals(ObjectiveCName.class.getCanonicalName())) {
                String key = unit.getPackage().getName().getFullyQualifiedName();
                String val = (String) ((SingleMemberAnnotation) annotation).getValue()
                        .resolveConstantExpressionValue();
                Options.addPackagePrefix(key, val);
            }//from w  ww . java  2s  . com
        }
    }
}

From source file:com.google.gdt.eclipse.core.JavaASTUtils.java

License:Open Source License

/**
 * Returns the fully-qualified name of an annotation, or <code>null</code> if
 * the annotation's type could not be resolved.
 *///ww w  .  j a  va 2 s. co m
public static String getAnnotationTypeName(Annotation annotation) {
    IAnnotationBinding binding = annotation.resolveAnnotationBinding();
    if (binding != null) {
        ITypeBinding annotationTypeBinding = binding.getAnnotationType();
        if (annotationTypeBinding != null) {
            return annotationTypeBinding.getQualifiedName();
        }
    }
    return null;
}

From source file:com.servoy.eclipse.docgenerator.parser.JavadocExtractor.java

License:Open Source License

private void handleAnnotation(Annotation node) {
    if (!annotationsStack.isEmpty()) {
        AnnotationMetaModel annotationMM;
        IAnnotationBinding bind = node.resolveAnnotationBinding();
        if (bind != null) {
            annotationMM = (AnnotationMetaModel) extractAnnotationValue(bind);
        } else {//w ww. ja va 2  s.c  om
            annotationMM = new AnnotationMetaModel(node.getTypeName().getFullyQualifiedName());
            if (node instanceof NormalAnnotation) {
                NormalAnnotation na = (NormalAnnotation) node;
                for (Object pair : na.values()) {
                    if (pair instanceof MemberValuePair) {
                        MemberValuePair mvPair = (MemberValuePair) pair;
                        String key = mvPair.getName().getFullyQualifiedName();
                        Object valObj = mvPair.getValue().resolveConstantExpressionValue();
                        if (valObj != null) {
                            annotationMM.addAttribute(key, valObj.toString());
                        } else {
                            warning(WarningType.Other, "Cannot retrieve value for attribute '" + key
                                    + "' of annotation: " + node.toString());
                            annotationMM.addAttribute(key, mvPair.getValue().toString());
                        }
                    }
                }
            } else if (node instanceof SingleMemberAnnotation) {
                SingleMemberAnnotation sma = (SingleMemberAnnotation) node;
                Object value = sma.getValue().resolveConstantExpressionValue();
                if (value != null) {
                    annotationMM.addAttribute("value", value.toString());
                } else {
                    warning(WarningType.Other,
                            "Cannot retrieve value from single member annotation: " + node.toString());
                    annotationMM.addAttribute("value", sma.getValue().toString());
                }
            }
        }
        annotationsStack.peek().add(annotationMM.getName(), annotationMM);
    }
}

From source file:edu.cmu.cs.plural.states.PluralAnnotationAnalysis.java

License:Open Source License

/**
 * Returns the value of the annotation parameter with the given name, or
 * NONE if it is not <b>declared</b>in the given annotation.
 *//*from  w  ww  .j  a  v  a  2s.  c o  m*/
private static Option<Object> getDeclaredAttribute(Annotation anno, String p_name) {
    for (IMemberValuePairBinding p : anno.resolveAnnotationBinding().getDeclaredMemberValuePairs()) {
        if (p_name.equals(p.getName())) {
            return Option.some(p.getValue());
        }
    }
    return Option.none();
}

From source file:edu.cmu.cs.plural.states.PluralAnnotationAnalysis.java

License:Open Source License

/**
 * Returns the given annotation attribute as an array, which will
 * be empty if the attribute is not <b>defined</b>.
 *///from   w ww.ja v  a 2 s .  c o m
private static Object[] getArrayAttribute(Annotation anno, String p_name) {
    for (IMemberValuePairBinding p : anno.resolveAnnotationBinding().getAllMemberValuePairs()) {
        if (p_name.equals(p.getName())) {
            Object result = p.getValue();
            if (result instanceof Object[])
                return (Object[]) result;
            return new Object[] { result };
        }
    }
    return new Object[0];
}