Example usage for javax.lang.model.element TypeElement getEnclosedElements

List of usage examples for javax.lang.model.element TypeElement getEnclosedElements

Introduction

In this page you can find the example usage for javax.lang.model.element TypeElement getEnclosedElements.

Prototype

@Override
List<? extends Element> getEnclosedElements();

Source Link

Document

Returns the fields, methods, constructors, and member types that are directly declared in this class or interface.

Usage

From source file:com.dspot.declex.action.Actions.java

private void createInformationForAction(String actionHolder, boolean isExternal) {

    TypeElement typeElement = env.getProcessingEnvironment().getElementUtils().getTypeElement(actionHolder);
    TypeElement generatedHolder = env.getProcessingEnvironment().getElementUtils()
            .getTypeElement(TypeUtils.getGeneratedClassName(typeElement, env));

    ActionFor actionForAnnotation = null;
    try {/*from www . ja v  a 2  s.co m*/
        actionForAnnotation = typeElement.getAnnotation(ActionFor.class);
    } catch (Exception e) {
        LOGGER.error("An error occurred processing the @ActionFor annotation", e);
    }

    if (actionForAnnotation != null) {

        for (String name : actionForAnnotation.value()) {

            ACTION_HOLDER_ELEMENT_FOR_ACTION.put("$" + name, typeElement);

            //Get model info
            final ActionInfo actionInfo = new ActionInfo(actionHolder);
            actionInfo.isGlobal = actionForAnnotation.global();
            actionInfo.isTimeConsuming = actionForAnnotation.timeConsuming();

            if (isExternal) {
                actionInfo.generated = false;
            }

            //This will work only for cached classes
            if (generatedHolder != null) {
                for (Element elem : generatedHolder.getEnclosedElements()) {
                    if (elem instanceof ExecutableElement) {
                        final String elemName = elem.getSimpleName().toString();
                        final List<? extends VariableElement> params = ((ExecutableElement) elem)
                                .getParameters();

                        if (elemName.equals("onViewChanged") && params.size() == 1 && params.get(0).asType()
                                .toString().equals(HasViews.class.getCanonicalName())) {
                            actionInfo.handleViewChanges = true;
                            break;
                        }
                    }
                }
            }

            addAction(name, actionHolder, actionInfo, false);

            String javaDoc = env.getProcessingEnvironment().getElementUtils().getDocComment(typeElement);
            actionInfo.setReferences(javaDoc);

            List<DeclaredType> processors = annotationHelper.extractAnnotationClassArrayParameter(typeElement,
                    ActionFor.class.getCanonicalName(), "processors");

            //Load processors
            if (processors != null) {
                for (DeclaredType processor : processors) {

                    Class<ActionProcessor> processorClass = null;

                    try {

                        ClassLoader loader = classLoaderForProcessor.get(processor.toString());
                        if (loader != null) {
                            processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(), true,
                                    loader);
                        } else {
                            processorClass = (Class<ActionProcessor>) Class.forName(processor.toString());
                        }

                    } catch (ClassNotFoundException e) {

                        Element element = env.getProcessingEnvironment().getElementUtils()
                                .getTypeElement(processor.toString());
                        if (element == null) {
                            LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded",
                                    typeElement);
                        } else {

                            try {
                                //Get the file from which the class was loaded
                                java.lang.reflect.Field field = element.getClass().getField("classfile");
                                field.setAccessible(true);
                                JavaFileObject classfile = (JavaFileObject) field.get(element);

                                String jarUrl = classfile.toUri().toURL().toString();
                                jarUrl = jarUrl.substring(0, jarUrl.lastIndexOf('!') + 2);

                                //Create or use a previous created class loader for the given file
                                ClassLoader loader;
                                if (classLoaderForProcessor.containsKey(jarUrl)) {
                                    loader = classLoaderForProcessor.get(jarUrl);
                                } else {
                                    loader = new URLClassLoader(new URL[] { new URL(jarUrl) },
                                            Actions.class.getClassLoader());
                                    classLoaderForProcessor.put(processor.toString(), loader);
                                    classLoaderForProcessor.put(jarUrl, loader);
                                }

                                processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(),
                                        true, loader);

                            } catch (Throwable e1) {
                                LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded: "
                                        + e1.getMessage(), typeElement);
                            }

                        }

                    } catch (ClassCastException e) {
                        LOGGER.error("Processor \"" + processor.toString() + "\" is not an Action Processor",
                                typeElement);
                    }

                    if (processorClass != null) {
                        try {
                            actionInfo.processors.add(processorClass.newInstance());
                        } catch (Throwable e) {
                            LOGGER.info("Processor \"" + processor.toString() + "\" couldn't be instantiated",
                                    typeElement);
                        }
                    }

                }
            }

            createInformationForMethods(typeElement, actionInfo);
        }

    }

}

From source file:org.androidtransfuse.adapter.element.ASTElementFactory.java

private ASTType buildType(TypeElement typeElement) {
    log.debug("ASTElementType building: " + typeElement.getQualifiedName());
    //build placeholder for ASTElementType and contained data structures to allow for children population
    //while avoiding back link loops
    PackageClass packageClass = buildPackageClass(typeElement);

    if (blacklist.containsKey(packageClass)) {
        return blacklist.get(packageClass);
    }//  ww w . jav  a  2  s  .co  m

    ASTTypeVirtualProxy astTypeProxy = new ASTTypeVirtualProxy(packageClass);
    typeCache.put(typeElement, astTypeProxy);

    ASTType superClass = null;
    if (typeElement.getSuperclass() != null) {
        superClass = typeElement.getSuperclass().accept(astTypeBuilderVisitor, null);
    }

    ImmutableSet<ASTType> interfaces = FluentIterable.from(typeElement.getInterfaces())
            .transform(astTypeBuilderVisitor).toSet();

    ImmutableSet.Builder<ASTAnnotation> annotations = ImmutableSet.builder();
    ImmutableSet.Builder<ASTConstructor> constructors = ImmutableSet.builder();
    ImmutableSet.Builder<ASTField> fields = ImmutableSet.builder();
    ImmutableSet.Builder<ASTMethod> methods = ImmutableSet.builder();

    //iterate and build the contained elements within this TypeElement
    annotations.addAll(getAnnotations(typeElement));
    constructors.addAll(transformAST(typeElement.getEnclosedElements(), ASTConstructor.class));
    fields.addAll(transformAST(typeElement.getEnclosedElements(), ASTField.class));
    methods.addAll(transformAST(typeElement.getEnclosedElements(), ASTMethod.class));

    ASTType astType = new ASTElementType(buildAccessModifier(typeElement), packageClass, typeElement,
            constructors.build(), methods.build(), fields.build(), superClass, interfaces, annotations.build());

    astTypeProxy.load(astType);

    return astType;
}

From source file:org.androidannotations.helper.ValidatorHelper.java

public void unannotatedMethodReturnsRestTemplate(TypeElement typeElement, IsValid valid) {
    List<? extends Element> enclosedElements = typeElement.getEnclosedElements();
    boolean foundGetRestTemplateMethod = false;
    boolean foundSetRestTemplateMethod = false;
    boolean foundSetAuthenticationMethod = false;
    boolean foundSetBearerAuthMethod = false;
    boolean foundSetRootUrlMethod = false;
    boolean foundGetCookieMethod = false;
    boolean foundGetHeaderMethod = false;
    boolean foundGetRootUrlMethod = false;

    for (Element enclosedElement : enclosedElements) {
        if (enclosedElement.getKind() != ElementKind.METHOD) {
            valid.invalidate();//from  w  ww  . jav  a2 s. com
            annotationHelper.printError(enclosedElement, "Only methods are allowed in a "
                    + TargetAnnotationHelper.annotationName(Rest.class) + " annotated interface");
        } else {

            boolean hasRestAnnotation = false;
            for (Class<? extends Annotation> annotationClass : REST_ANNOTATION_CLASSES) {
                if (enclosedElement.getAnnotation(annotationClass) != null) {
                    hasRestAnnotation = true;
                    break;
                }
            }

            if (!hasRestAnnotation) {

                ExecutableElement executableElement = (ExecutableElement) enclosedElement;
                TypeMirror returnType = executableElement.getReturnType();
                String simpleName = executableElement.getSimpleName().toString();

                if (returnType.toString().equals(CanonicalNameConstants.REST_TEMPLATE)) {
                    if (executableElement.getParameters().size() > 0) {
                        valid.invalidate();
                        annotationHelper.printError(enclosedElement,
                                "The method returning a RestTemplate should not declare any parameter in a "
                                        + TargetAnnotationHelper.annotationName(Rest.class)
                                        + " annotated interface");
                    } else {
                        if (foundGetRestTemplateMethod) {
                            valid.invalidate();
                            annotationHelper.printError(enclosedElement,
                                    "Only one method should declare returning a RestTemplate in a "
                                            + TargetAnnotationHelper.annotationName(Rest.class)
                                            + " annotated interface");
                        } else {
                            foundGetRestTemplateMethod = true;
                        }
                    }
                } else if (simpleName.equals(METHOD_NAME_GET_ROOT_URL)) {
                    if (!returnType.toString().equals(CanonicalNameConstants.STRING)) {
                        valid.invalidate();
                        annotationHelper.printError(enclosedElement,
                                "The method getRootUrl must return String on a "
                                        + TargetAnnotationHelper.annotationName(Rest.class)
                                        + " annotated interface");
                    }

                    if (executableElement.getParameters().size() != 0) {
                        valid.invalidate();
                        annotationHelper.printError(enclosedElement,
                                "The method getRootUrl cannot have parameters on a "
                                        + TargetAnnotationHelper.annotationName(Rest.class)
                                        + " annotated interface");
                    }

                    if (!foundGetRootUrlMethod) {
                        foundGetRootUrlMethod = true;
                    } else {
                        valid.invalidate();
                        annotationHelper.printError(enclosedElement,
                                "The can be only one getRootUrl method on a "
                                        + TargetAnnotationHelper.annotationName(Rest.class)
                                        + " annotated interface");
                    }
                } else if (returnType.getKind() == TypeKind.VOID) {
                    List<? extends VariableElement> parameters = executableElement.getParameters();
                    if (parameters.size() == 1) {
                        VariableElement firstParameter = parameters.get(0);
                        if (firstParameter.asType().toString().equals(CanonicalNameConstants.REST_TEMPLATE)) {
                            if (!foundSetRestTemplateMethod) {
                                foundSetRestTemplateMethod = true;
                            } else {
                                valid.invalidate();
                                annotationHelper.printError(enclosedElement,
                                        "You can only have oneRestTemplate setter method on a "
                                                + TargetAnnotationHelper.annotationName(Rest.class)
                                                + " annotated interface");

                            }
                        } else if (executableElement.getSimpleName().toString().equals(METHOD_NAME_SET_ROOT_URL)
                                && !foundSetRootUrlMethod) {
                            foundSetRootUrlMethod = true;
                        } else if (executableElement.getSimpleName().toString()
                                .equals(METHOD_NAME_SET_AUTHENTICATION) && !foundSetAuthenticationMethod) {
                            foundSetAuthenticationMethod = true;
                        } else if (executableElement.getSimpleName().toString()
                                .equals(METHOD_NAME_SET_BEARER_AUTH) && !foundSetBearerAuthMethod) {
                            foundSetBearerAuthMethod = true;
                        } else {
                            valid.invalidate();
                            annotationHelper.printError(enclosedElement,
                                    "The method to set a RestTemplate should have only one RestTemplate parameter on a "
                                            + TargetAnnotationHelper.annotationName(Rest.class)
                                            + " annotated interface");

                        }
                    } else if (parameters.size() == 2) {
                        VariableElement firstParameter = parameters.get(0);
                        VariableElement secondParameter = parameters.get(1);
                        if (!(firstParameter.asType().toString().equals(CanonicalNameConstants.STRING)
                                && secondParameter.asType().toString().equals(CanonicalNameConstants.STRING))) {
                            valid.invalidate();
                            annotationHelper.printError(enclosedElement,
                                    "The method to set headers, cookies, or HTTP Basic Auth should have only String parameters on a "
                                            + TargetAnnotationHelper.annotationName(Rest.class)
                                            + " annotated interface");
                        }
                    } else {
                        valid.invalidate();
                        annotationHelper.printError(enclosedElement,
                                "The method to set a RestTemplate should have only one RestTemplate parameter on a "
                                        + TargetAnnotationHelper.annotationName(Rest.class)
                                        + " annotated interface");
                    }
                } else if (returnType.toString().equals(CanonicalNameConstants.STRING)) {
                    List<? extends VariableElement> parameters = executableElement.getParameters();
                    if (parameters.size() == 1) {
                        VariableElement firstParameter = parameters.get(0);
                        if (firstParameter.asType().toString().equals(CanonicalNameConstants.STRING)) {
                            if (executableElement.getSimpleName().toString().equals(METHOD_NAME_GET_COOKIE)
                                    && !foundGetCookieMethod) {
                                foundGetCookieMethod = true;
                            } else if (executableElement.getSimpleName().toString()
                                    .equals(METHOD_NAME_GET_HEADER) && !foundGetHeaderMethod) {
                                foundGetHeaderMethod = true;
                            } else {
                                valid.invalidate();
                                annotationHelper.printError(enclosedElement,
                                        "Only one getCookie(String) and one getHeader(String) method are allowed on a "
                                                + TargetAnnotationHelper.annotationName(Rest.class)
                                                + " annotated interface");
                            }
                        } else {
                            valid.invalidate();
                            annotationHelper.printError(enclosedElement,
                                    "Only getCookie(String) and getHeader(String) can return a String on a "
                                            + TargetAnnotationHelper.annotationName(Rest.class)
                                            + " annotated interface");
                        }

                    } else {
                        valid.invalidate();
                        annotationHelper.printError(enclosedElement,
                                "The only methods that can return a String on a "
                                        + TargetAnnotationHelper.annotationName(Rest.class)
                                        + " annotated interface are getCookie(String) and getHeader(String)");
                    }
                } else {
                    valid.invalidate();
                    annotationHelper.printError(enclosedElement, "All methods should be annotated in a "
                            + TargetAnnotationHelper.annotationName(Rest.class)
                            + " annotated interface, except the ones that returns or set a RestTemplate");
                }
            }
        }
    }
}

From source file:auto.parse.processor.AutoParseProcessor.java

private void findLocalAndInheritedMethods(TypeElement type, List<ExecutableElement> methods) {
    note("Looking at methods in " + type);
    Types typeUtils = processingEnv.getTypeUtils();
    Elements elementUtils = processingEnv.getElementUtils();
    for (TypeMirror superInterface : type.getInterfaces()) {
        findLocalAndInheritedMethods((TypeElement) typeUtils.asElement(superInterface), methods);
    }//from   w  w w  . j  ava  2s  .co  m
    if (type.getSuperclass().getKind() != TypeKind.NONE) {
        // Visit the superclass after superinterfaces so we will always see the implementation of a
        // method after any interfaces that declared it.
        findLocalAndInheritedMethods((TypeElement) typeUtils.asElement(type.getSuperclass()), methods);
    }
    // Add each method of this class, and in so doing remove any inherited method it overrides.
    // This algorithm is quadratic in the number of methods but it's hard to see how to improve
    // that while still using Elements.overrides.
    List<ExecutableElement> theseMethods = ElementFilter.methodsIn(type.getEnclosedElements());
    eclipseHack().sortMethodsIfSimulatingEclipse(theseMethods);
    for (ExecutableElement method : theseMethods) {
        if (!method.getModifiers().contains(Modifier.PRIVATE)) {
            boolean alreadySeen = false;
            for (Iterator<ExecutableElement> methodIter = methods.iterator(); methodIter.hasNext();) {
                ExecutableElement otherMethod = methodIter.next();
                if (elementUtils.overrides(method, otherMethod, type)) {
                    methodIter.remove();
                } else if (method.getSimpleName().equals(otherMethod.getSimpleName())
                        && method.getParameters().equals(otherMethod.getParameters())) {
                    // If we inherit this method on more than one path, we don't want to add it twice.
                    alreadySeen = true;
                }
            }
            if (!alreadySeen) {
                methods.add(method);
            }
        }
    }
}

From source file:com.googlecode.androidannotations.processing.rest.RestProcessor.java

@Override
public void process(Element element, JCodeModel codeModel, EBeansHolder activitiesHolder) throws Exception {

    RestImplementationHolder holder = restImplementationHolder.create(element);

    TypeElement typeElement = (TypeElement) element;

    holder.urlPrefix = typeElement.getAnnotation(Rest.class).value();

    String interfaceName = typeElement.getQualifiedName().toString();

    String implementationName = interfaceName + ModelConstants.GENERATION_SUFFIX;

    // holder.restImplementationClass = codeModel._class(JMod.PUBLIC |
    // JMod.ABSTRACT, implementationName, ClassType.CLASS);
    holder.restImplementationClass = codeModel._class(JMod.PUBLIC, implementationName, ClassType.CLASS);
    JClass interfaceClass = holder.refClass(interfaceName);
    holder.restImplementationClass._implements(interfaceClass);

    // RestTemplate field
    JClass restTemplateClass = holder.refClass(SPRING_REST_TEMPLATE_QUALIFIED_NAME);
    holder.restTemplateField = holder.restImplementationClass.field(JMod.PRIVATE, restTemplateClass,
            "restTemplate");

    // Default constructor
    JMethod defaultConstructor = holder.restImplementationClass.constructor(JMod.PUBLIC);
    defaultConstructor.body().assign(holder.restTemplateField, JExpr._new(restTemplateClass));

    // RestTemplate constructor
    JMethod restTemplateConstructor = holder.restImplementationClass.constructor(JMod.PUBLIC);
    JVar restTemplateParam = restTemplateConstructor.param(restTemplateClass, "restTemplate");
    restTemplateConstructor.body().assign(JExpr._this().ref(holder.restTemplateField), restTemplateParam);

    // RequestFactory constructor
    JMethod requestFactoryConstructor = holder.restImplementationClass.constructor(JMod.PUBLIC);
    JClass requestFactoryClass = holder.refClass("org.springframework.http.client.ClientHttpRequestFactory");
    JVar requestFactoryParam = requestFactoryConstructor.param(requestFactoryClass, "requestFactory");
    requestFactoryConstructor.body().assign(holder.restTemplateField,
            JExpr._new(restTemplateClass).arg(requestFactoryParam));

    // Implement getRestTemplate method
    List<? extends Element> enclosedElements = typeElement.getEnclosedElements();
    List<ExecutableElement> methods = ElementFilter.methodsIn(enclosedElements);
    for (ExecutableElement method : methods) {
        if (method.getParameters().size() == 0
                && method.getReturnType().toString().equals(SPRING_REST_TEMPLATE_QUALIFIED_NAME)) {
            String methodName = method.getSimpleName().toString();
            JMethod getRestTemplateMethod = holder.restImplementationClass.method(JMod.PUBLIC,
                    restTemplateClass, methodName);
            getRestTemplateMethod.annotate(Override.class);
            getRestTemplateMethod.body()._return(holder.restTemplateField);
            break; // Only one implementation
        }//from  www  .j a v a2 s  . co m
    }

    for (ExecutableElement method : methods) {
        List<? extends VariableElement> parameters = method.getParameters();
        if (parameters.size() == 1 && method.getReturnType().getKind() == TypeKind.VOID) {
            VariableElement firstParameter = parameters.get(0);
            if (firstParameter.asType().toString().equals(SPRING_REST_TEMPLATE_QUALIFIED_NAME)) {
                String methodName = method.getSimpleName().toString();
                JMethod setRestTemplateMethod = holder.restImplementationClass.method(JMod.PUBLIC,
                        codeModel.VOID, methodName);
                setRestTemplateMethod.annotate(Override.class);

                JVar restTemplateSetterParam = setRestTemplateMethod.param(restTemplateClass,
                        firstParameter.getSimpleName().toString());

                setRestTemplateMethod.body().assign(_this().ref(holder.restTemplateField),
                        restTemplateSetterParam);
                break; // Only one implementation
            }
        }
    }

}