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

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

Introduction

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

Prototype

@Override
<A extends Annotation> A getAnnotation(Class<A> annotationType);

Source Link

Usage

From source file:org.versly.rest.wsdoc.AnnotationProcessor.java

private void processRequestMappingMethod(ExecutableElement executableElement,
        RestImplementationSupport implementationSupport) {
    TypeElement cls = (TypeElement) executableElement.getEnclosingElement();

    for (final String basePath : getClassLevelUrlPaths(cls, implementationSupport)) {
        for (final String requestPath : implementationSupport.getRequestPaths(executableElement, cls)) {
            String fullPath = Utils.joinPaths(basePath, requestPath);
            String meth;//from w ww.  j  a v  a  2 s.  c o m
            try {
                meth = implementationSupport.getRequestMethod(executableElement, cls);
            } catch (IllegalStateException ex) {
                // if something is bad with the request method annotations (no PATCH support currently, for example),
                // then just warn and continue, so the docs don't break the dev process.
                this.processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
                        "error processing element: " + ex.getMessage(), executableElement);
                continue;
            }

            // both spring and jersey permit colon delimited regexes in path annotations which are not compatible with RAML
            // which expects resource identifiers to comply with RFC-6570 URI template semantics - so remove regex portion
            fullPath = fullPath.replaceAll(":.*}", "}");

            // set documentation and metadata on api
            RestDocumentation.RestApi api = null;
            DocumentationRestApi apidoc = cls.getAnnotation(DocumentationRestApi.class);
            if (null != apidoc) {
                api = _docs.getRestApi(apidoc.id());
                api.setApiTitle(apidoc.title());
                api.setApiVersion(apidoc.version());
                api.setMount(apidoc.mount());
            } else {
                api = _docs.getRestApi(RestDocumentation.RestApi.DEFAULT_IDENTIFIER);
                api.setApiTitle("");
                api.setApiVersion("");
                api.setMount("");
            }

            api.setApiDocumentation(processingEnv.getElementUtils().getDocComment(cls));

            // set documentation text on method
            RestDocumentation.RestApi.Resource resource = api.getResourceDocumentation(fullPath);
            RestDocumentation.RestApi.Resource.Method method = resource.newMethodDocumentation(meth);
            method.setCommentText(processingEnv.getElementUtils().getDocComment(executableElement));

            // set documentation scope on method (doc scope is non-scalar, methods can be part of multiple doc scopes)
            {
                HashSet<String> docScopes = new HashSet<String>();
                DocumentationScope clsDocScopes = cls.getAnnotation(DocumentationScope.class);
                if (null != clsDocScopes) {
                    docScopes.addAll(Arrays.asList(clsDocScopes.value()));
                }
                DocumentationScope methodDocScopes = executableElement.getAnnotation(DocumentationScope.class);
                if (null != methodDocScopes) {
                    docScopes.addAll(Arrays.asList(methodDocScopes.value()));
                }
                method.setDocScopes(docScopes);
            }

            // set authorization scope on method (auth scope is non-scalar, methods can have multiple auth scopes)
            {
                HashSet<String> authScopes = new HashSet<String>();
                AuthorizationScope clsAuthScopes = cls.getAnnotation(AuthorizationScope.class);
                if (null != clsAuthScopes) {
                    authScopes.addAll(Arrays.asList(clsAuthScopes.value()));
                }
                AuthorizationScope methodAuthScopes = executableElement.getAnnotation(AuthorizationScope.class);
                if (null != methodAuthScopes) {
                    authScopes.addAll(Arrays.asList(methodAuthScopes.value()));
                }
                method.setAuthScopes(authScopes);
            }

            // set traits on method (traits is non-scalar, methods may have multiple traits)
            {
                HashSet<String> traits = new HashSet<String>(method.getDocScopes());
                DocumentationTraits clsTraits = cls.getAnnotation(DocumentationTraits.class);
                if (null != clsTraits) {
                    traits.addAll(Arrays.asList(clsTraits.value()));
                }
                DocumentationTraits methodTraits = executableElement.getAnnotation(DocumentationTraits.class);
                if (null != methodTraits) {
                    traits.addAll(Arrays.asList(methodTraits.value()));
                }
                method.setTraits(traits);
            }

            // add method's traits as included with overall API traits (used in RAML for uniform documentation)
            api.getTraits().addAll(method.getTraits());

            // set path and query parameter information on method
            buildParameterData(executableElement, method, implementationSupport);

            // set response entity data information on method
            buildResponseFormat(unwrapReturnType(executableElement.getReturnType()), method);
        }
    }
}

From source file:org.jraf.android.prefs.compiler.PrefsProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (TypeElement te : annotations) {
        for (Element element : roundEnv.getElementsAnnotatedWith(te)) {
            TypeElement classElement = (TypeElement) element;
            PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();

            String classComment = processingEnv.getElementUtils().getDocComment(classElement);

            List<Pref> prefList = new ArrayList<Pref>();
            // Iterate over the fields of the class
            for (VariableElement variableElement : ElementFilter.fieldsIn(classElement.getEnclosedElements())) {
                if (variableElement.getModifiers().contains(Modifier.STATIC)) {
                    // Ignore constants
                    continue;
                }/* w  w w  . j a  va 2  s.  c  om*/

                TypeMirror fieldType = variableElement.asType();
                boolean isAllowedType = PrefType.isAllowedType(fieldType);
                if (!isAllowedType) {
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                            fieldType + " is not allowed here, only these types are allowed: "
                                    + PrefType.getAllowedTypes(),
                            variableElement);
                    // Problem detected: halt
                    return true;
                }

                String fieldName = variableElement.getSimpleName().toString();
                org.jraf.android.prefs.Name fieldNameAnnot = variableElement
                        .getAnnotation(org.jraf.android.prefs.Name.class);
                String prefName = getPrefName(fieldName, fieldNameAnnot);

                String prefDefaultValue = getDefaultValue(variableElement, fieldType);
                if (prefDefaultValue == null) {
                    // Problem detected: halt
                    return true;
                }

                String fieldComment = processingEnv.getElementUtils().getDocComment(variableElement);
                Pref pref = new Pref(fieldName, prefName, PrefType.from(fieldType), prefDefaultValue,
                        fieldComment);
                prefList.add(pref);
            }

            Map<String, Object> args = new HashMap<String, Object>();

            // File name (optional - also use 'value' for this)
            org.jraf.android.prefs.Prefs prefsAnnot = classElement
                    .getAnnotation(org.jraf.android.prefs.Prefs.class);
            String fileName = prefsAnnot.value();
            if (fileName.isEmpty()) {
                fileName = prefsAnnot.fileName();
            }
            if (!fileName.isEmpty())
                args.put("fileName", fileName);

            // File mode (must only appear if fileName is defined)
            int fileMode = prefsAnnot.fileMode();
            if (fileMode != -1) {
                if (fileName.isEmpty()) {
                    // File mode set, but not file name (which makes no sense)
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                            "fileMode must only be set if fileName (or value) is also set", classElement);
                    // Problem detected: halt
                    return true;
                }
                args.put("fileMode", fileMode);
            }

            // Disable @Nullable generation
            args.put("disableNullable", prefsAnnot.disableNullable());

            JavaFileObject javaFileObject = null;
            try {
                // SharedPreferencesWrapper
                javaFileObject = processingEnv.getFiler()
                        .createSourceFile(classElement.getQualifiedName() + SUFFIX_PREF_WRAPPER);
                Template template = getFreemarkerConfiguration().getTemplate("prefwrapper.ftl");
                args.put("package", packageElement.getQualifiedName());
                args.put("comment", classComment);
                args.put("prefWrapperClassName", classElement.getSimpleName() + SUFFIX_PREF_WRAPPER);
                args.put("editorWrapperClassName", classElement.getSimpleName() + SUFFIX_EDITOR_WRAPPER);
                args.put("prefList", prefList);
                Writer writer = javaFileObject.openWriter();
                template.process(args, writer);
                IOUtils.closeQuietly(writer);

                // EditorWrapper
                javaFileObject = processingEnv.getFiler()
                        .createSourceFile(classElement.getQualifiedName() + "EditorWrapper");
                template = getFreemarkerConfiguration().getTemplate("editorwrapper.ftl");
                writer = javaFileObject.openWriter();
                template.process(args, writer);
                IOUtils.closeQuietly(writer);

            } catch (Exception e) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                        "En error occurred while generating Prefs code " + e.getClass() + e.getMessage(),
                        element);
                e.printStackTrace();
                // Problem detected: halt
                return true;
            }
        }
    }
    return true;
}