Example usage for javax.lang.model.type TypeMirror getKind

List of usage examples for javax.lang.model.type TypeMirror getKind

Introduction

In this page you can find the example usage for javax.lang.model.type TypeMirror getKind.

Prototype

TypeKind getKind();

Source Link

Document

Returns the kind of this type.

Usage

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

private boolean ancestorIsAndroidAutoParse(TypeElement type) {
    while (true) {
        TypeMirror parentMirror = type.getSuperclass();
        if (parentMirror.getKind() == TypeKind.NONE) {
            return false;
        }// w  w w.  j  av a2  s.  co m
        Types typeUtils = processingEnv.getTypeUtils();
        TypeElement parentElement = (TypeElement) typeUtils.asElement(parentMirror);
        if (parentElement.getAnnotation(AutoParse.class) != null) {
            return true;
        }
        type = parentElement;
    }
}

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

String jsonSchemaFromTypeMirror(TypeMirror type) {
    String serializedSchema = null;

    if (type.getKind().isPrimitive() || type.getKind() == TypeKind.VOID) {
        return null;
    }//from  w ww.  ja v a2s  . c  om

    // we need the dto class to generate schema using jackson json-schema module
    // note: Types.erasure() provides canonical names whereas Class.forName() wants a "regular" name,
    // so forName will fail for nested and inner classes as "regular" names use $ between parent and child.
    Class dtoClass = null;
    StringBuffer erasure = new StringBuffer(_typeUtils.erasure(type).toString());
    for (boolean done = false; !done;) {
        try {
            dtoClass = Class.forName(erasure.toString());
            done = true;
        } catch (ClassNotFoundException e) {
            if (erasure.lastIndexOf(".") != -1) {
                erasure.setCharAt(erasure.lastIndexOf("."), '$');
            } else {
                done = true;
            }
        }
    }

    // if we were able to figure out the dto class, use jackson json-schema module to serialize it
    Exception e = null;
    if (dtoClass != null) {
        try {
            ObjectMapper m = new ObjectMapper();
            m.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
            m.registerModule(new JodaModule());
            SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();
            m.acceptJsonFormatVisitor(m.constructType(dtoClass), visitor);
            serializedSchema = m.writeValueAsString(visitor.finalSchema());
        } catch (Exception ex) {
            e = ex;
        }
    }

    // report warning if we were not able to generate schema for non-primitive type
    if (serializedSchema == null) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
                "cannot generate json-schema for class " + type.toString() + " (erasure " + erasure + "), "
                        + ((e != null) ? ("exception: " + e.getMessage()) : "class not found"));
    }

    return serializedSchema;
}

From source file:org.lambdamatic.mongodb.apt.template.TemplateType.java

/**
 * Returns the {@link TemplateType} for the given {@link VariableType}, or throws a
 * {@link MetadataGenerationException} if it was not a known or supported type.
 * //www .  jav  a  2  s.c  o m
 * @param variableType the variable to analyze
 * @return the corresponding {@link TemplateType}
 * @throws MetadataGenerationException if the given variable type is not supported
 */
private static TemplateType getMetadataFieldType(final TypeMirror variableType,
        final BiFunction<PrimitiveType, ProcessingEnvironment, TemplateType> primitiveTypeToTemplateType,
        final Function<DeclaredType, TemplateType> embeddedDocumentToTemplateType,
        final BiFunction<TypeMirror, ProcessingEnvironment, TemplateType> collectionToTemplateType,
        final BiFunction<DeclaredType, ProcessingEnvironment, TemplateType> mapToTemplateType,
        final Function<DeclaredType, TemplateType> declaredTypeToTemplateType,
        final ProcessingEnvironment processingEnv) throws MetadataGenerationException {
    if (variableType instanceof PrimitiveType) {
        return primitiveTypeToTemplateType.apply((PrimitiveType) variableType, processingEnv);
    } else if (variableType instanceof DeclaredType) {
        final DeclaredType declaredType = (DeclaredType) variableType;
        final TypeElement declaredElement = (TypeElement) declaredType.asElement();
        if (declaredElement.getAnnotation(EmbeddedDocument.class) != null) {
            // embedded documents
            return embeddedDocumentToTemplateType.apply(declaredType);
        } else if (ElementUtils.isAssignable(declaredType, Collection.class)) {
            // collections (list/set)
            return collectionToTemplateType.apply(declaredType.getTypeArguments().get(0), processingEnv);
        } else if (ElementUtils.isAssignable(declaredType, Map.class)) {
            // map
            return mapToTemplateType.apply(declaredType, processingEnv);
        } else {
            return declaredTypeToTemplateType.apply(declaredType);
        }
    } else if (variableType.getKind() == TypeKind.ARRAY) {
        final TypeMirror componentType = ((ArrayType) variableType).getComponentType();
        if (componentType instanceof PrimitiveType) {
            final PrimitiveType primitiveType = (PrimitiveType) componentType;
            final TypeElement boxedClass = processingEnv.getTypeUtils().boxedClass(primitiveType);
            return collectionToTemplateType.apply(boxedClass.asType(), processingEnv);
        }
        return collectionToTemplateType.apply(componentType, processingEnv);
    }
    throw new MetadataGenerationException("Unexpected variable type: " + variableType);
}

From source file:org.kie.workbench.common.stunner.core.processors.MainProcessor.java

private boolean processDefinitionSets(final Set<? extends TypeElement> set, final Element e,
        final RoundEnvironment roundEnv) throws Exception {
    final Messager messager = processingEnv.getMessager();
    final boolean isClass = e.getKind() == ElementKind.CLASS;
    if (isClass) {
        TypeElement classElement = (TypeElement) e;
        PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();
        messager.printMessage(Diagnostic.Kind.NOTE,
                "Discovered definition set class [" + classElement.getSimpleName() + "]");
        final String packageName = packageElement.getQualifiedName().toString();
        final String className = classElement.getSimpleName().toString();
        processingContext.setDefinitionSet(packageName, className);
        String defSetClassName = packageName + "." + className;
        // Description fields.
        processFieldName(classElement, defSetClassName, ANNOTATION_DESCRIPTION,
                processingContext.getDefSetAnnotations().getDescriptionFieldNames(), true);
        // Definitions identifiers.
        DefinitionSet definitionSetAnn = e.getAnnotation(DefinitionSet.class);
        List<? extends TypeMirror> mirrors = null;
        try {//from www . j  a  v  a2 s .  c om
            Class<?>[] defsClasses = definitionSetAnn.definitions();
        } catch (MirroredTypesException mte) {
            mirrors = mte.getTypeMirrors();
        }
        if (null == mirrors) {
            throw new RuntimeException("No graph class class specifyed for the @DefinitionSet.");
        }
        Set<String> defIds = new LinkedHashSet<>();
        for (TypeMirror mirror : mirrors) {
            if (mirror.getKind().equals(TypeKind.DECLARED)) {
                final TypeElement t = (TypeElement) ((DeclaredType) mirror).asElement();
                processingContext.getDefinitionElements().add(t);
            }
            String fqcn = mirror.toString();
            defIds.add(fqcn);
        }
        processingContext.getDefSetAnnotations().getDefinitionIds().addAll(defIds);
        // Builder class.
        processDefinitionSetModelBuilder(e, defSetClassName,
                processingContext.getDefSetAnnotations().getBuilderFieldNames());
        // Graph factory type.
        TypeMirror mirror = null;
        try {
            Class<?> graphClass = definitionSetAnn.graphFactory();
        } catch (MirroredTypeException mte) {
            mirror = mte.getTypeMirror();
        }
        if (null == mirror) {
            throw new RuntimeException("No graph factory class specifyed for the @DefinitionSet.");
        }
        String fqcn = mirror.toString();
        processingContext.getDefSetAnnotations().getGraphFactoryTypes().put(defSetClassName, fqcn);
        // Definition Set's qualifier.
        try {
            Class<?> qualifierClass = definitionSetAnn.qualifier();
        } catch (MirroredTypeException mte) {
            mirror = mte.getTypeMirror();
        }
        if (null == mirror) {
            throw new RuntimeException("No qualifier class specifyed for the @DefinitionSet.");
        }
        processingContext.getDefSetAnnotations().getQualifiers().put(defSetClassName, mirror.toString());
    }
    return true;
}

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

private JsonType jsonTypeFromTypeMirror(TypeMirror typeMirror, Collection<String> typeRecursionGuard) {

    JsonType type;//w ww .  j  ava2 s .  c o m

    if (_memoizedTypeMirrors.containsKey(typeMirror)) {
        return _memoizedTypeMirrors.get(typeMirror);
    }

    if (isJsonPrimitive(typeMirror)) {
        type = new JsonPrimitive(typeMirror.toString());
    } else if (typeMirror.getKind() == TypeKind.DECLARED) {
        // some sort of object... walk it
        DeclaredType declaredType = (DeclaredType) typeMirror;
        type = jsonTypeForDeclaredType(declaredType, declaredType.getTypeArguments(), typeRecursionGuard);
    } else if (typeMirror.getKind() == TypeKind.VOID) {
        type = null;
    } else if (typeMirror.getKind() == TypeKind.ARRAY) {
        TypeMirror componentType = ((ArrayType) typeMirror).getComponentType();
        type = jsonTypeFromTypeMirror(componentType, typeRecursionGuard);
    } else if (typeMirror.getKind() == TypeKind.ERROR) {
        type = new JsonPrimitive("(unresolvable type)");
    } else {
        throw new UnsupportedOperationException(typeMirror.toString());
    }

    _memoizedTypeMirrors.put(typeMirror, type);
    return type;
}

From source file:com.googlecode.androidannotations.helper.ValidatorHelper.java

public void returnTypeIsVoid(ExecutableElement executableElement, IsValid valid) {
    TypeMirror returnType = executableElement.getReturnType();

    if (returnType.getKind() != TypeKind.VOID) {
        valid.invalidate();/*from   ww  w.  j  av a 2 s .com*/
        annotationHelper.printAnnotationError(executableElement,
                "%s can only be used on a method with a void return type");
    }
}

From source file:com.googlecode.androidannotations.helper.ValidatorHelper.java

public void returnTypeNotGenericUnlessResponseEntity(ExecutableElement element, IsValid valid) {
    TypeMirror returnType = element.getReturnType();
    TypeKind returnKind = returnType.getKind();
    if (returnKind == TypeKind.DECLARED) {
        DeclaredType declaredReturnType = (DeclaredType) returnType;
        if (!declaredReturnType.toString().startsWith("org.springframework.http.ResponseEntity<")
                && declaredReturnType.getTypeArguments().size() > 0) {
            valid.invalidate();/*w  w  w.  j  av  a  2s.  c  o m*/
            annotationHelper.printAnnotationError(element,
                    "%s annotated methods cannot return parameterized types, except for ResponseEntity");
        }
    }
}

From source file:com.googlecode.androidannotations.helper.ValidatorHelper.java

public void returnTypeIsVoidOrBoolean(ExecutableElement executableElement, IsValid valid) {
    TypeMirror returnType = executableElement.getReturnType();

    TypeKind returnKind = returnType.getKind();

    if (returnKind != TypeKind.BOOLEAN && returnKind != TypeKind.VOID
            && !returnType.toString().equals("java.lang.Boolean")) {
        valid.invalidate();//  www .  j  ava2  s .c om
        annotationHelper.printAnnotationError(executableElement,
                "%s can only be used on a method with a boolean or a void return type");
    }
}

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

public void returnTypeIsNotVoid(ExecutableElement executableElement, IsValid valid) {
    TypeMirror returnType = executableElement.getReturnType();

    if (returnType.getKind() == TypeKind.VOID) {
        valid.invalidate();//from ww w  . j  av  a2s  .c o  m
        annotationHelper.printAnnotationError(executableElement,
                "%s can only be used on a method with a return type non void");
    }
}

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

public void returnTypeIsVoidOrBoolean(ExecutableElement executableElement, IsValid valid) {
    TypeMirror returnType = executableElement.getReturnType();

    TypeKind returnKind = returnType.getKind();

    if (returnKind != TypeKind.BOOLEAN && returnKind != TypeKind.VOID
            && !returnType.toString().equals(CanonicalNameConstants.BOOLEAN)) {
        valid.invalidate();/* ww w.java 2 s  .  c om*/
        annotationHelper.printAnnotationError(executableElement,
                "%s can only be used on a method with a boolean or a void return type");
    }
}