Search in sources :

Example 6 with AnnotatedMethod

use of com.fasterxml.jackson.databind.introspect.AnnotatedMethod in project jackson-module-afterburner by FasterXML.

the class SerializerModifier method findProperties.

protected PropertyAccessorCollector findProperties(Class<?> beanClass, SerializationConfig config, List<BeanPropertyWriter> beanProperties) {
    PropertyAccessorCollector collector = new PropertyAccessorCollector(beanClass);
    ListIterator<BeanPropertyWriter> it = beanProperties.listIterator();
    while (it.hasNext()) {
        BeanPropertyWriter bpw = it.next();
        AnnotatedMember member = bpw.getMember();
        Member jdkMember = member.getMember();
        // 11-Sep-2015, tatu: Let's skip virtual members (related to #57)
        if (jdkMember == null) {
            continue;
        }
        // We can't access private fields or methods, skip:
        if (Modifier.isPrivate(jdkMember.getModifiers())) {
            continue;
        }
        // 30-Jul-2012, tatu: [#6]: Needs to skip custom serializers, if any.
        if (bpw.hasSerializer()) {
            if (!isDefaultSerializer(config, bpw.getSerializer())) {
                continue;
            }
        }
        // [#9]: also skip unwrapping stuff...
        if (bpw.isUnwrapping()) {
            continue;
        }
        /* 04-Mar-2015, tatu: This might be too restrictive, as core databind has some 
             *   other sub-classes; if this becomes problematic may start using annotation
             *   to indicate "standard" implementations. But for now this solves the issue.
             */
        if (bpw.getClass() != BeanPropertyWriter.class) {
            continue;
        }
        Class<?> type = bpw.getType().getRawClass();
        boolean isMethod = (member instanceof AnnotatedMethod);
        if (type.isPrimitive()) {
            if (type == Integer.TYPE) {
                if (isMethod) {
                    it.set(collector.addIntGetter(bpw));
                } else {
                    it.set(collector.addIntField(bpw));
                }
            } else if (type == Long.TYPE) {
                if (isMethod) {
                    it.set(collector.addLongGetter(bpw));
                } else {
                    it.set(collector.addLongField(bpw));
                }
            } else if (type == Boolean.TYPE) {
                if (isMethod) {
                    it.set(collector.addBooleanGetter(bpw));
                } else {
                    it.set(collector.addBooleanField(bpw));
                }
            }
        } else {
            if (type == String.class) {
                if (isMethod) {
                    it.set(collector.addStringGetter(bpw));
                } else {
                    it.set(collector.addStringField(bpw));
                }
            } else {
                // any other Object types; we can at least call accessor
                if (isMethod) {
                    it.set(collector.addObjectGetter(bpw));
                } else {
                    it.set(collector.addObjectField(bpw));
                }
            }
        }
    }
    return collector;
}
Also used : AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) AnnotatedMember(com.fasterxml.jackson.databind.introspect.AnnotatedMember) Member(java.lang.reflect.Member) AnnotatedMember(com.fasterxml.jackson.databind.introspect.AnnotatedMember)

Example 7 with AnnotatedMethod

use of com.fasterxml.jackson.databind.introspect.AnnotatedMethod in project jackson-module-afterburner by FasterXML.

the class TestAccessorGeneration method testSingleIntAccessorGeneration.

/*
    /**********************************************************************
    /* Test methods
    /**********************************************************************
     */
public void testSingleIntAccessorGeneration() throws Exception {
    Method method = Bean1.class.getDeclaredMethod("getX");
    AnnotatedMethod annMethod = new AnnotatedMethod(null, method, null, null);
    PropertyAccessorCollector coll = new PropertyAccessorCollector(Bean1.class);
    BeanPropertyWriter bpw = new BeanPropertyWriter(SimpleBeanPropertyDefinition.construct(null, annMethod, new PropertyName("x")), annMethod, null, null, null, null, null, false, null);
    coll.addIntGetter(bpw);
    BeanPropertyAccessor acc = coll.findAccessor(null);
    Bean1 bean = new Bean1();
    int value = acc.intGetter(bean, 0);
    assertEquals(bean.getX(), value);
}
Also used : PropertyName(com.fasterxml.jackson.databind.PropertyName) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) Method(java.lang.reflect.Method) BeanPropertyWriter(com.fasterxml.jackson.databind.ser.BeanPropertyWriter)

Example 8 with AnnotatedMethod

use of com.fasterxml.jackson.databind.introspect.AnnotatedMethod in project jackson-module-afterburner by FasterXML.

the class TestAccessorGeneration method testDualIntAccessorGeneration.

public void testDualIntAccessorGeneration() throws Exception {
    PropertyAccessorCollector coll = new PropertyAccessorCollector(Bean3.class);
    String[] methodNames = new String[] { "getX", "getY", "get3" };
    for (String methodName : methodNames) {
        Method method = Bean3.class.getDeclaredMethod(methodName);
        AnnotatedMethod annMethod = new AnnotatedMethod(null, method, null, null);
        // should we translate from method name to property name?
        coll.addIntGetter(new BeanPropertyWriter(SimpleBeanPropertyDefinition.construct(null, annMethod, new PropertyName(methodName)), annMethod, null, null, null, null, null, false, null));
    }
    BeanPropertyAccessor acc = coll.findAccessor(null);
    Bean3 bean = new Bean3();
    assertEquals(bean.getX(), acc.intGetter(bean, 0));
    assertEquals(bean.getY(), acc.intGetter(bean, 1));
    assertEquals(bean.get3(), acc.intGetter(bean, 2));
}
Also used : PropertyName(com.fasterxml.jackson.databind.PropertyName) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) Method(java.lang.reflect.Method) BeanPropertyWriter(com.fasterxml.jackson.databind.ser.BeanPropertyWriter)

Example 9 with AnnotatedMethod

use of com.fasterxml.jackson.databind.introspect.AnnotatedMethod in project swagger-core by swagger-api.

the class Reader method read.

private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) {
    Map<String, Tag> tags = new LinkedHashMap<String, Tag>();
    List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
    String[] consumes = new String[0];
    String[] produces = new String[0];
    final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class);
    Api api = ReflectionUtils.getAnnotation(cls, Api.class);
    boolean hasPathAnnotation = (ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class) != null);
    boolean hasApiAnnotation = (api != null);
    boolean isApiHidden = hasApiAnnotation && api.hidden();
    // class readable only if annotated with ((@Path and @Api) or isSubresource ) - and @Api not hidden
    boolean classReadable = ((hasPathAnnotation && hasApiAnnotation) || isSubresource) && !isApiHidden;
    // with scanAllResources true in config and @Api not hidden scan only if it has also @Path annotation or is subresource
    boolean scanAll = !isApiHidden && config.isScanAllResources() && (hasPathAnnotation || isSubresource);
    // readable if classReadable or scanAll
    boolean readable = classReadable || scanAll;
    if (!readable) {
        return swagger;
    }
    // api readable only if @Api present; cannot be hidden because checked in classReadable.
    boolean apiReadable = hasApiAnnotation;
    if (apiReadable) {
        // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present
        Set<String> tagStrings = extractTags(api);
        for (String tagString : tagStrings) {
            Tag tag = new Tag().name(tagString);
            tags.put(tagString, tag);
        }
        for (String tagName : tags.keySet()) {
            swagger.tag(tags.get(tagName));
        }
        if (!api.produces().isEmpty()) {
            produces = ReaderUtils.splitContentValues(new String[] { api.produces() });
        }
        if (!api.consumes().isEmpty()) {
            consumes = ReaderUtils.splitContentValues(new String[] { api.consumes() });
        }
        globalSchemes.addAll(parseSchemes(api.protocols()));
        for (Authorization auth : api.authorizations()) {
            if (auth.value() != null && !auth.value().isEmpty()) {
                SecurityRequirement security = new SecurityRequirement();
                security.setName(auth.value());
                for (AuthorizationScope scope : auth.scopes()) {
                    if (scope.scope() != null && !scope.scope().isEmpty()) {
                        security.addScope(scope.scope());
                    }
                }
                securities.add(security);
            }
        }
    }
    if (readable) {
        if (isSubresource) {
            if (parentTags != null) {
                tags.putAll(parentTags);
            }
        }
        // merge consumes, produces
        if (consumes.length == 0 && cls.getAnnotation(Consumes.class) != null) {
            consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value());
        }
        if (produces.length == 0 && cls.getAnnotation(Produces.class) != null) {
            produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value());
        }
        // look for method-level annotated properties
        // handle sub-resources by looking at return type
        final List<Parameter> globalParameters = new ArrayList<Parameter>();
        // look for constructor-level annotated properties
        globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, swagger));
        // look for field-level annotated properties
        globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, swagger));
        // build class/interface level @ApiResponse list
        ApiResponses classResponseAnnotation = ReflectionUtils.getAnnotation(cls, ApiResponses.class);
        List<ApiResponse> classApiResponses = new ArrayList<ApiResponse>();
        if (classResponseAnnotation != null) {
            classApiResponses.addAll(Arrays.asList(classResponseAnnotation.value()));
        }
        // parse the method
        final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class);
        JavaType classType = TypeFactory.defaultInstance().constructType(cls);
        BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType);
        Method[] methods = cls.getMethods();
        for (Method method : methods) {
            AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes());
            if (ReflectionUtils.isOverriddenMethod(method, cls)) {
                continue;
            }
            javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class);
            String operationPath = getPath(apiPath, methodPath, parentPath);
            Map<String, String> regexMap = new LinkedHashMap<String, String>();
            operationPath = PathUtils.parsePath(operationPath, regexMap);
            if (operationPath != null) {
                if (isIgnored(operationPath)) {
                    continue;
                }
                final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
                String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain());
                Operation operation = null;
                if (apiOperation != null || config.isScanAllResources() || httpMethod != null || methodPath != null) {
                    operation = parseMethod(cls, method, annotatedMethod, globalParameters, classApiResponses);
                }
                if (operation == null) {
                    continue;
                }
                if (parentParameters != null) {
                    for (Parameter param : parentParameters) {
                        operation.parameter(param);
                    }
                }
                for (Parameter param : operation.getParameters()) {
                    if (regexMap.get(param.getName()) != null) {
                        String pattern = regexMap.get(param.getName());
                        param.setPattern(pattern);
                    }
                }
                if (apiOperation != null) {
                    for (Scheme scheme : parseSchemes(apiOperation.protocols())) {
                        operation.scheme(scheme);
                    }
                }
                if (operation.getSchemes() == null || operation.getSchemes().isEmpty()) {
                    for (Scheme scheme : globalSchemes) {
                        operation.scheme(scheme);
                    }
                }
                String[] apiConsumes = consumes;
                if (parentConsumes != null) {
                    Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiConsumes));
                    both.addAll(new LinkedHashSet<String>(Arrays.asList(parentConsumes)));
                    if (operation.getConsumes() != null) {
                        both.addAll(new LinkedHashSet<String>(operation.getConsumes()));
                    }
                    apiConsumes = both.toArray(new String[both.size()]);
                }
                String[] apiProduces = produces;
                if (parentProduces != null) {
                    Set<String> both = new LinkedHashSet<String>(Arrays.asList(apiProduces));
                    both.addAll(new LinkedHashSet<String>(Arrays.asList(parentProduces)));
                    if (operation.getProduces() != null) {
                        both.addAll(new LinkedHashSet<String>(operation.getProduces()));
                    }
                    apiProduces = both.toArray(new String[both.size()]);
                }
                final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method);
                if (subResource != null && !scannedResources.contains(subResource)) {
                    scannedResources.add(subResource);
                    read(subResource, operationPath, httpMethod, true, apiConsumes, apiProduces, tags, operation.getParameters(), scannedResources);
                    // remove the sub resource so that it can visit it later in another path
                    // but we have a room for optimization in the future to reuse the scanned result
                    // by caching the scanned resources in the reader instance to avoid actual scanning
                    // the the resources again
                    scannedResources.remove(subResource);
                }
                // can't continue without a valid http method
                httpMethod = (httpMethod == null) ? parentMethod : httpMethod;
                if (httpMethod != null) {
                    if (apiOperation != null) {
                        for (String tag : apiOperation.tags()) {
                            if (!"".equals(tag)) {
                                operation.tag(tag);
                                swagger.tag(new Tag().name(tag));
                            }
                        }
                        operation.getVendorExtensions().putAll(BaseReaderUtils.parseExtensions(apiOperation.extensions()));
                    }
                    if (operation.getConsumes() == null) {
                        for (String mediaType : apiConsumes) {
                            operation.consumes(mediaType);
                        }
                    }
                    if (operation.getProduces() == null) {
                        for (String mediaType : apiProduces) {
                            operation.produces(mediaType);
                        }
                    }
                    if (operation.getTags() == null) {
                        for (String tagString : tags.keySet()) {
                            operation.tag(tagString);
                        }
                    }
                    // Only add global @Api securities if operation doesn't already have more specific securities
                    if (operation.getSecurity() == null) {
                        for (SecurityRequirement security : securities) {
                            operation.security(security);
                        }
                    }
                    Path path = swagger.getPath(operationPath);
                    if (path == null) {
                        path = new Path();
                        swagger.path(operationPath, path);
                    }
                    path.set(httpMethod, operation);
                    readImplicitParameters(method, operation);
                    readExternalDocs(method, operation);
                }
            }
        }
    }
    return swagger;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ModelConverters(io.swagger.converter.ModelConverters) Scheme(io.swagger.models.Scheme) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) ArrayList(java.util.ArrayList) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.models.Operation) ApiResponse(io.swagger.annotations.ApiResponse) LinkedHashMap(java.util.LinkedHashMap) Authorization(io.swagger.annotations.Authorization) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(io.swagger.models.Path) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) Method(java.lang.reflect.Method) HttpMethod(javax.ws.rs.HttpMethod) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) JavaType(com.fasterxml.jackson.databind.JavaType) Produces(javax.ws.rs.Produces) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) HeaderParameter(io.swagger.models.parameters.HeaderParameter) AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter) Tag(io.swagger.models.Tag) Api(io.swagger.annotations.Api) AuthorizationScope(io.swagger.annotations.AuthorizationScope) SecurityRequirement(io.swagger.models.SecurityRequirement)

Aggregations

AnnotatedMethod (com.fasterxml.jackson.databind.introspect.AnnotatedMethod)9 Method (java.lang.reflect.Method)5 PropertyName (com.fasterxml.jackson.databind.PropertyName)3 AnnotatedField (com.fasterxml.jackson.databind.introspect.AnnotatedField)3 BeanPropertyWriter (com.fasterxml.jackson.databind.ser.BeanPropertyWriter)3 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 AnnotatedClass (com.fasterxml.jackson.databind.introspect.AnnotatedClass)2 AnnotatedParameter (com.fasterxml.jackson.databind.introspect.AnnotatedParameter)2 FormParameter (io.swagger.models.parameters.FormParameter)2 HeaderParameter (io.swagger.models.parameters.HeaderParameter)2 Parameter (io.swagger.models.parameters.Parameter)2 PathParameter (io.swagger.models.parameters.PathParameter)2 QueryParameter (io.swagger.models.parameters.QueryParameter)2 ArrayList (java.util.ArrayList)2 AnnotationIntrospector (com.fasterxml.jackson.databind.AnnotationIntrospector)1 JavaType (com.fasterxml.jackson.databind.JavaType)1 Annotated (com.fasterxml.jackson.databind.introspect.Annotated)1 AnnotatedMember (com.fasterxml.jackson.databind.introspect.AnnotatedMember)1 BeanPropertyDefinition (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition)1