Search in sources :

Example 41 with Annotation

use of java.lang.annotation.Annotation in project ig-json-parser by Instagram.

the class JsonAnnotationProcessor method isFieldAnnotationValid.

private boolean isFieldAnnotationValid(Class<? extends Annotation> annotationClass, Element element) {
    TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
    // Verify containing type.
    if (enclosingElement.getKind() != CLASS) {
        error(enclosingElement, "@%s field may only be contained in classes. (%s.%s)", annotationClass.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
        return false;
    }
    Annotation annotation = enclosingElement.getAnnotation(JsonType.class);
    if (annotation == null) {
        error(enclosingElement, "@%s field may only be contained in classes annotated with @%s (%s.%s)", annotationClass.getSimpleName(), JsonType.class.toString(), enclosingElement.getQualifiedName(), element.getSimpleName());
        return false;
    }
    // Verify containing class visibility is not private.
    if (enclosingElement.getModifiers().contains(PRIVATE)) {
        error(enclosingElement, "@%s %s may not be contained in private classes. (%s.%s)", annotationClass.getSimpleName(), enclosingElement.getQualifiedName(), element.getSimpleName());
        return false;
    }
    return true;
}
Also used : JsonType(com.instagram.common.json.annotation.JsonType) TypeElement(javax.lang.model.element.TypeElement) Annotation(java.lang.annotation.Annotation)

Example 42 with Annotation

use of java.lang.annotation.Annotation in project ig-json-parser by Instagram.

the class TypeUtils method getParseType.

public ParseType getParseType(TypeMirror typeMirror, Class<? extends Annotation> typeAnnotationClass) {
    if (typeMirror == null) {
        return ParseType.UNSUPPORTED;
    } else if (JAVA_LANG_STRING.equals(typeMirror.toString())) {
        return ParseType.STRING;
    } else if (typeMirror.getKind() == TypeKind.BOOLEAN) {
        return ParseType.BOOLEAN;
    } else if (JAVA_LANG_BOOLEAN.equals(typeMirror.toString())) {
        return ParseType.BOOLEAN_OBJECT;
    } else if (typeMirror.getKind() == TypeKind.INT) {
        return ParseType.INTEGER;
    } else if (JAVA_LANG_INTEGER.equals(typeMirror.toString())) {
        return ParseType.INTEGER_OBJECT;
    } else if (typeMirror.getKind() == TypeKind.LONG) {
        return ParseType.LONG;
    } else if (JAVA_LANG_LONG.equals(typeMirror.toString())) {
        return ParseType.LONG_OBJECT;
    } else if (typeMirror.getKind() == TypeKind.FLOAT) {
        return ParseType.FLOAT;
    } else if (JAVA_LANG_FLOAT.equals(typeMirror.toString())) {
        return ParseType.FLOAT_OBJECT;
    } else if (typeMirror.getKind() == TypeKind.DOUBLE) {
        return ParseType.DOUBLE;
    } else if (JAVA_LANG_DOUBLE.equals(typeMirror.toString())) {
        return ParseType.DOUBLE_OBJECT;
    } else if (typeMirror instanceof DeclaredType) {
        DeclaredType type = (DeclaredType) typeMirror;
        Element element = type.asElement();
        Annotation annotation = element.getAnnotation(typeAnnotationClass);
        if (annotation != null) {
            return ParseType.PARSABLE_OBJECT;
        }
        // is it an enum?
        if (element instanceof TypeElement) {
            TypeElement typeElement = (TypeElement) element;
            TypeMirror superclass = typeElement.getSuperclass();
            if (superclass instanceof DeclaredType) {
                DeclaredType superclassDeclaredType = (DeclaredType) superclass;
                if (JAVA_LANG_ENUM.equals(getCanonicalTypeName(superclassDeclaredType))) {
                    return ParseType.ENUM_OBJECT;
                }
            }
        }
    }
    return ParseType.UNSUPPORTED;
}
Also used : TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) TypeParameterElement(javax.lang.model.element.TypeParameterElement) Annotation(java.lang.annotation.Annotation) DeclaredType(javax.lang.model.type.DeclaredType)

Example 43 with Annotation

use of java.lang.annotation.Annotation in project midpoint by Evolveum.

the class MidpointAbstractProvider method readFrom.

@Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    if (entityStream == null) {
        return null;
    }
    PrismParser parser = getParser(entityStream);
    T object;
    try {
        LOGGER.info("type of request: {}", type);
        if (PrismObject.class.isAssignableFrom(type)) {
            object = (T) parser.parse();
        } else {
            // TODO consider prescribing type here (if no convertor is specified)
            object = parser.parseRealValue();
        }
        if (object != null && !type.isAssignableFrom(object.getClass())) {
            // TODO treat multivalues here
            Optional<Annotation> convertorAnnotation = Arrays.stream(annotations).filter(a -> a instanceof Convertor).findFirst();
            if (convertorAnnotation.isPresent()) {
                Class<? extends ConvertorInterface> convertorClass = ((Convertor) convertorAnnotation.get()).value();
                ConvertorInterface convertor;
                try {
                    convertor = convertorClass.newInstance();
                } catch (InstantiationException | IllegalAccessException e) {
                    throw new SystemException("Couldn't instantiate convertor class " + convertorClass, e);
                }
                object = (T) convertor.convert(object);
            }
        }
        return object;
    } catch (SchemaException ex) {
        throw new WebApplicationException(ex);
    }
}
Also used : Arrays(java.util.Arrays) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Autowired(org.springframework.beans.factory.annotation.Autowired) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) Trace(com.evolveum.midpoint.util.logging.Trace) AbstractConfigurableProvider(org.apache.cxf.jaxrs.provider.AbstractConfigurableProvider) OperationResultType(com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType) MediaType(javax.ws.rs.core.MediaType) com.evolveum.midpoint.prism(com.evolveum.midpoint.prism) OutputStream(java.io.OutputStream) IOException(java.io.IOException) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) List(java.util.List) Type(java.lang.reflect.Type) SystemException(com.evolveum.midpoint.util.exception.SystemException) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) QName(javax.xml.namespace.QName) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) InputStream(java.io.InputStream) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) WebApplicationException(javax.ws.rs.WebApplicationException) Annotation(java.lang.annotation.Annotation) SystemException(com.evolveum.midpoint.util.exception.SystemException)

Example 44 with Annotation

use of java.lang.annotation.Annotation in project fastjson by alibaba.

the class JavaBeanInfo method build.

public static JavaBeanInfo build(Class<?> clazz, Type type, PropertyNamingStrategy propertyNamingStrategy) {
    JSONType jsonType = clazz.getAnnotation(JSONType.class);
    Class<?> builderClass = getBuilderClass(jsonType);
    Field[] declaredFields = clazz.getDeclaredFields();
    Method[] methods = clazz.getMethods();
    Constructor<?> defaultConstructor = getDefaultConstructor(builderClass == null ? clazz : builderClass);
    Constructor<?> creatorConstructor = null;
    Method buildMethod = null;
    List<FieldInfo> fieldList = new ArrayList<FieldInfo>();
    if (defaultConstructor == null && !(clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()))) {
        creatorConstructor = getCreatorConstructor(clazz);
        if (creatorConstructor != null) {
            // 基于标记 JSONCreator 注解的构造方法
            TypeUtils.setAccessible(creatorConstructor);
            Class<?>[] types = creatorConstructor.getParameterTypes();
            if (types.length > 0) {
                Annotation[][] paramAnnotationArrays = creatorConstructor.getParameterAnnotations();
                for (int i = 0; i < types.length; ++i) {
                    Annotation[] paramAnnotations = paramAnnotationArrays[i];
                    JSONField fieldAnnotation = null;
                    for (Annotation paramAnnotation : paramAnnotations) {
                        if (paramAnnotation instanceof JSONField) {
                            fieldAnnotation = (JSONField) paramAnnotation;
                            break;
                        }
                    }
                    if (fieldAnnotation == null) {
                        throw new JSONException("illegal json creator");
                    }
                    Class<?> fieldClass = types[i];
                    Type fieldType = creatorConstructor.getGenericParameterTypes()[i];
                    Field field = TypeUtils.getField(clazz, fieldAnnotation.name(), declaredFields);
                    final int ordinal = fieldAnnotation.ordinal();
                    final int serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
                    final int parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
                    FieldInfo fieldInfo = new FieldInfo(fieldAnnotation.name(), clazz, fieldClass, fieldType, field, ordinal, serialzeFeatures, parserFeatures);
                    add(fieldList, fieldInfo);
                }
            }
            return new JavaBeanInfo(clazz, builderClass, null, creatorConstructor, null, null, jsonType, fieldList);
        }
        // 基于标记 JSONCreator 注解的工厂方法
        Method factoryMethod = getFactoryMethod(clazz, methods);
        if (factoryMethod != null) {
            TypeUtils.setAccessible(factoryMethod);
            Class<?>[] types = factoryMethod.getParameterTypes();
            if (types.length > 0) {
                Annotation[][] paramAnnotationArrays = factoryMethod.getParameterAnnotations();
                for (int i = 0; i < types.length; ++i) {
                    Annotation[] paramAnnotations = paramAnnotationArrays[i];
                    JSONField fieldAnnotation = null;
                    for (Annotation paramAnnotation : paramAnnotations) {
                        if (paramAnnotation instanceof JSONField) {
                            fieldAnnotation = (JSONField) paramAnnotation;
                            break;
                        }
                    }
                    if (fieldAnnotation == null) {
                        throw new JSONException("illegal json creator");
                    }
                    Class<?> fieldClass = types[i];
                    Type fieldType = factoryMethod.getGenericParameterTypes()[i];
                    Field field = TypeUtils.getField(clazz, fieldAnnotation.name(), declaredFields);
                    final int ordinal = fieldAnnotation.ordinal();
                    final int serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
                    final int parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
                    FieldInfo fieldInfo = new FieldInfo(fieldAnnotation.name(), clazz, fieldClass, fieldType, field, ordinal, serialzeFeatures, parserFeatures);
                    add(fieldList, fieldInfo);
                }
            }
            return new JavaBeanInfo(clazz, builderClass, null, null, factoryMethod, null, jsonType, fieldList);
        }
        throw new JSONException("default constructor not found. " + clazz);
    }
    if (defaultConstructor != null) {
        TypeUtils.setAccessible(defaultConstructor);
    }
    if (builderClass != null) {
        String withPrefix = null;
        JSONPOJOBuilder builderAnno = builderClass.getAnnotation(JSONPOJOBuilder.class);
        if (builderAnno != null) {
            withPrefix = builderAnno.withPrefix();
        }
        if (withPrefix == null || withPrefix.length() == 0) {
            withPrefix = "with";
        }
        for (Method method : builderClass.getMethods()) {
            if (Modifier.isStatic(method.getModifiers())) {
                continue;
            }
            if (!(method.getReturnType().equals(builderClass))) {
                continue;
            }
            int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0;
            JSONField annotation = method.getAnnotation(JSONField.class);
            if (annotation == null) {
                annotation = TypeUtils.getSuperMethodAnnotation(clazz, method);
            }
            if (annotation != null) {
                if (!annotation.deserialize()) {
                    continue;
                }
                ordinal = annotation.ordinal();
                serialzeFeatures = SerializerFeature.of(annotation.serialzeFeatures());
                parserFeatures = Feature.of(annotation.parseFeatures());
                if (annotation.name().length() != 0) {
                    String propertyName = annotation.name();
                    add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, null, null));
                    continue;
                }
            }
            String methodName = method.getName();
            if (!methodName.startsWith(withPrefix)) {
                continue;
            }
            if (methodName.length() <= withPrefix.length()) {
                continue;
            }
            char c0 = methodName.charAt(withPrefix.length());
            if (!Character.isUpperCase(c0)) {
                continue;
            }
            StringBuilder properNameBuilder = new StringBuilder(methodName.substring(withPrefix.length()));
            properNameBuilder.setCharAt(0, Character.toLowerCase(c0));
            String propertyName = properNameBuilder.toString();
            add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, null, null));
        }
        if (builderClass != null) {
            JSONPOJOBuilder builderAnnotation = builderClass.getAnnotation(JSONPOJOBuilder.class);
            String buildMethodName = null;
            if (builderAnnotation != null) {
                buildMethodName = builderAnnotation.buildMethod();
            }
            if (buildMethodName == null || buildMethodName.length() == 0) {
                buildMethodName = "build";
            }
            try {
                buildMethod = builderClass.getMethod(buildMethodName);
            } catch (NoSuchMethodException e) {
            // skip
            } catch (SecurityException e) {
            // skip
            }
            if (buildMethod == null) {
                try {
                    buildMethod = builderClass.getMethod("create");
                } catch (NoSuchMethodException e) {
                // skip
                } catch (SecurityException e) {
                // skip
                }
            }
            if (buildMethod == null) {
                throw new JSONException("buildMethod not found.");
            }
            TypeUtils.setAccessible(buildMethod);
        }
    }
    for (Method method : methods) {
        //
        int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0;
        String methodName = method.getName();
        if (methodName.length() < 4) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        // support builder set
        if (!(method.getReturnType().equals(Void.TYPE) || method.getReturnType().equals(method.getDeclaringClass()))) {
            continue;
        }
        Class<?>[] types = method.getParameterTypes();
        if (types.length != 1) {
            continue;
        }
        JSONField annotation = method.getAnnotation(JSONField.class);
        if (annotation == null) {
            annotation = TypeUtils.getSuperMethodAnnotation(clazz, method);
        }
        if (annotation != null) {
            if (!annotation.deserialize()) {
                continue;
            }
            ordinal = annotation.ordinal();
            serialzeFeatures = SerializerFeature.of(annotation.serialzeFeatures());
            parserFeatures = Feature.of(annotation.parseFeatures());
            if (annotation.name().length() != 0) {
                String propertyName = annotation.name();
                add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, null, null));
                continue;
            }
        }
        if (!methodName.startsWith("set")) {
            // TODO "set"的判断放在 JSONField 注解后面,意思是允许非 setter 方法标记 JSONField 注解?
            continue;
        }
        char c3 = methodName.charAt(3);
        String propertyName;
        if (//
        Character.isUpperCase(c3) || // for unicode method name
        c3 > 512) {
            if (TypeUtils.compatibleWithJavaBean) {
                propertyName = TypeUtils.decapitalize(methodName.substring(3));
            } else {
                propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
            }
        } else if (c3 == '_') {
            propertyName = methodName.substring(4);
        } else if (c3 == 'f') {
            propertyName = methodName.substring(3);
        } else if (methodName.length() >= 5 && Character.isUpperCase(methodName.charAt(4))) {
            propertyName = TypeUtils.decapitalize(methodName.substring(3));
        } else {
            continue;
        }
        Field field = TypeUtils.getField(clazz, propertyName, declaredFields);
        if (field == null && types[0] == boolean.class) {
            String isFieldName = "is" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
            field = TypeUtils.getField(clazz, isFieldName, declaredFields);
        }
        JSONField fieldAnnotation = null;
        if (field != null) {
            fieldAnnotation = field.getAnnotation(JSONField.class);
            if (fieldAnnotation != null) {
                if (!fieldAnnotation.deserialize()) {
                    continue;
                }
                ordinal = fieldAnnotation.ordinal();
                serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
                parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
                if (fieldAnnotation.name().length() != 0) {
                    propertyName = fieldAnnotation.name();
                    add(fieldList, new FieldInfo(propertyName, method, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, fieldAnnotation, null));
                    continue;
                }
            }
        }
        if (propertyNamingStrategy != null) {
            propertyName = propertyNamingStrategy.translate(propertyName);
        }
        add(fieldList, new FieldInfo(propertyName, method, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, annotation, fieldAnnotation, null));
    }
    for (Field field : clazz.getFields()) {
        // public static fields
        int modifiers = field.getModifiers();
        if ((modifiers & Modifier.STATIC) != 0) {
            continue;
        }
        if ((modifiers & Modifier.FINAL) != 0) {
            Class<?> fieldType = field.getType();
            boolean supportReadOnly = Map.class.isAssignableFrom(fieldType) || Collection.class.isAssignableFrom(fieldType) || //
            AtomicLong.class.equals(fieldType) || //
            AtomicInteger.class.equals(fieldType) || AtomicBoolean.class.equals(fieldType);
            if (!supportReadOnly) {
                continue;
            }
        }
        boolean contains = false;
        for (FieldInfo item : fieldList) {
            if (item.name.equals(field.getName())) {
                contains = true;
                // 已经是 contains = true,无需继续遍历
                break;
            }
        }
        if (contains) {
            continue;
        }
        int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0;
        String propertyName = field.getName();
        JSONField fieldAnnotation = field.getAnnotation(JSONField.class);
        if (fieldAnnotation != null) {
            if (!fieldAnnotation.deserialize()) {
                continue;
            }
            ordinal = fieldAnnotation.ordinal();
            serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
            parserFeatures = Feature.of(fieldAnnotation.parseFeatures());
            if (fieldAnnotation.name().length() != 0) {
                propertyName = fieldAnnotation.name();
            }
        }
        if (propertyNamingStrategy != null) {
            propertyName = propertyNamingStrategy.translate(propertyName);
        }
        add(fieldList, new FieldInfo(propertyName, null, field, clazz, type, ordinal, serialzeFeatures, parserFeatures, null, fieldAnnotation, null));
    }
    for (Method method : clazz.getMethods()) {
        // getter methods
        String methodName = method.getName();
        if (methodName.length() < 4) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        if (methodName.startsWith("get") && Character.isUpperCase(methodName.charAt(3))) {
            if (method.getParameterTypes().length != 0) {
                continue;
            }
            if (//
            Collection.class.isAssignableFrom(method.getReturnType()) || //
            Map.class.isAssignableFrom(method.getReturnType()) || //
            AtomicBoolean.class == method.getReturnType() || //
            AtomicInteger.class == method.getReturnType() || //
            AtomicLong.class == method.getReturnType()) {
                String propertyName;
                JSONField annotation = method.getAnnotation(JSONField.class);
                if (annotation != null && annotation.deserialize()) {
                    continue;
                }
                if (annotation != null && annotation.name().length() > 0) {
                    propertyName = annotation.name();
                } else {
                    propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
                }
                FieldInfo fieldInfo = getField(fieldList, propertyName);
                if (fieldInfo != null) {
                    continue;
                }
                if (propertyNamingStrategy != null) {
                    propertyName = propertyNamingStrategy.translate(propertyName);
                }
                add(fieldList, new FieldInfo(propertyName, method, null, clazz, type, 0, 0, 0, annotation, null, null));
            }
        }
    }
    return new JavaBeanInfo(clazz, builderClass, defaultConstructor, null, null, buildMethod, jsonType, fieldList);
}
Also used : ArrayList(java.util.ArrayList) JSONPOJOBuilder(com.alibaba.fastjson.annotation.JSONPOJOBuilder) JSONField(com.alibaba.fastjson.annotation.JSONField) JSONField(com.alibaba.fastjson.annotation.JSONField) Field(java.lang.reflect.Field) JSONException(com.alibaba.fastjson.JSONException) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Type(java.lang.reflect.Type) JSONType(com.alibaba.fastjson.annotation.JSONType) AtomicLong(java.util.concurrent.atomic.AtomicLong) JSONType(com.alibaba.fastjson.annotation.JSONType)

Example 45 with Annotation

use of java.lang.annotation.Annotation in project android_frameworks_base by AOSPA.

the class Filter method addAnnotatedPorts.

private final void addAnnotatedPorts() {
    Class filterClass = getClass();
    Annotation annotation;
    for (Field field : filterClass.getDeclaredFields()) {
        if ((annotation = field.getAnnotation(GenerateFieldPort.class)) != null) {
            GenerateFieldPort generator = (GenerateFieldPort) annotation;
            addFieldGenerator(generator, field);
        } else if ((annotation = field.getAnnotation(GenerateProgramPort.class)) != null) {
            GenerateProgramPort generator = (GenerateProgramPort) annotation;
            addProgramGenerator(generator, field);
        } else if ((annotation = field.getAnnotation(GenerateProgramPorts.class)) != null) {
            GenerateProgramPorts generators = (GenerateProgramPorts) annotation;
            for (GenerateProgramPort generator : generators.value()) {
                addProgramGenerator(generator, field);
            }
        }
    }
}
Also used : Field(java.lang.reflect.Field) Annotation(java.lang.annotation.Annotation)

Aggregations

Annotation (java.lang.annotation.Annotation)1784 Method (java.lang.reflect.Method)412 ArrayList (java.util.ArrayList)245 Field (java.lang.reflect.Field)172 Test (org.junit.Test)164 Type (java.lang.reflect.Type)149 HashMap (java.util.HashMap)146 HashSet (java.util.HashSet)129 Map (java.util.Map)95 List (java.util.List)92 IOException (java.io.IOException)71 Set (java.util.Set)71 ParameterizedType (java.lang.reflect.ParameterizedType)62 InvocationTargetException (java.lang.reflect.InvocationTargetException)53 Collection (java.util.Collection)52 LinkedHashMap (java.util.LinkedHashMap)36 Collectors (java.util.stream.Collectors)36 Constructor (java.lang.reflect.Constructor)33 LinkedHashSet (java.util.LinkedHashSet)32 Optional (java.util.Optional)32