List of usage examples for java.lang.reflect Method getParameters
public Parameter[] getParameters()
From source file:com.angkorteam.framework.swagger.factory.SwaggerFactory.java
@Override public void afterPropertiesSet() throws Exception { Swagger swagger = new Swagger(); io.swagger.models.Info info = new io.swagger.models.Info(); swagger.setInfo(info);//from w ww .j av a 2 s .co m info.setTitle(title); info.setLicense(license); info.setContact(contact); info.setTermsOfService(termsOfService); info.setVersion(version); info.setDescription(description); swagger.setConsumes(consumes); swagger.setProduces(produces); swagger.setSchemes(schemes); swagger.setBasePath(basePath); swagger.setHost(host); swagger.setExternalDocs(externalDocs); ConfigurationBuilder config = new ConfigurationBuilder(); Set<String> acceptablePackages = new HashSet<>(); boolean allowAllPackages = false; if (resourcePackages != null && resourcePackages.length > 0) { for (String resourcePackage : resourcePackages) { if (resourcePackage != null && !"".equals(resourcePackage)) { acceptablePackages.add(resourcePackage); config.addUrls(ClasspathHelper.forPackage(resourcePackage)); } } } config.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()); Reflections reflections = new Reflections(config); Set<Class<?>> controllers = reflections.getTypesAnnotatedWith(Controller.class); Set<Class<?>> output = new HashSet<Class<?>>(); for (Class<?> cls : controllers) { if (allowAllPackages) { output.add(cls); } else { for (String pkg : acceptablePackages) { if (cls.getPackage().getName().startsWith(pkg)) { output.add(cls); } } } } Map<String, Path> paths = new HashMap<>(); swagger.setPaths(paths); Map<String, Model> definitions = new HashMap<>(); swagger.setDefinitions(definitions); Stack<Class<?>> modelStack = new Stack<>(); for (Class<?> controller : controllers) { List<String> clazzPaths = new ArrayList<>(); RequestMapping clazzRequestMapping = controller.getDeclaredAnnotation(RequestMapping.class); Api api = controller.getDeclaredAnnotation(Api.class); if (clazzRequestMapping != null) { clazzPaths = lookPaths(clazzRequestMapping); } if (clazzPaths.isEmpty()) { clazzPaths.add(""); } if (api != null) { if (!"".equals(api.description())) { for (String name : api.tags()) { if (!"".equals(name)) { io.swagger.models.Tag tag = new io.swagger.models.Tag(); tag.setDescription(api.description()); tag.setName(name); swagger.addTag(tag); } } } } else { io.swagger.models.Tag tag = new io.swagger.models.Tag(); tag.setDescription("Unknown"); tag.setName("Unknown"); swagger.addTag(tag); } Method[] methods = null; try { methods = controller.getDeclaredMethods(); } catch (NoClassDefFoundError e) { } if (methods != null && methods.length > 0) { for (Method method : methods) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); ApiResponses apiResponses = method.getAnnotation(ApiResponses.class); ApiHeaders apiHeaders = method.getAnnotation(ApiHeaders.class); List<String> methodPaths = new ArrayList<>(); if (requestMapping != null && apiOperation != null && apiResponses != null) { methodPaths = lookPaths(requestMapping); } if (methodPaths.isEmpty()) { methodPaths.add(""); } if (requestMapping != null && apiOperation != null && apiResponses != null) { for (String classPath : clazzPaths) { for (String methodPath : methodPaths) { RequestMethod[] requestMethods = requestMapping.method(); if (requestMethods == null || requestMethods.length == 0) { requestMethods = RequestMethod.values(); } Path path = new Path(); paths.put(classPath + methodPath, path); for (RequestMethod requestMethod : requestMethods) { Operation operation = new Operation(); operation.setDescription(apiOperation.description()); for (String consume : requestMapping.consumes()) { operation.addConsumes(consume); } for (String produce : requestMapping.produces()) { operation.addProduces(produce); } if (api != null) { if (!"".equals(api.description())) { for (String name : api.tags()) { if (!"".equals(name)) { operation.addTag(name); } } } } else { io.swagger.models.Tag tag = new io.swagger.models.Tag(); operation.addTag("Unknown"); } if (requestMethod == RequestMethod.DELETE) { path.delete(operation); } else if (requestMethod == RequestMethod.GET) { path.get(operation); } else if (requestMethod == RequestMethod.HEAD) { path.head(operation); } else if (requestMethod == RequestMethod.OPTIONS) { path.options(operation); } else if (requestMethod == RequestMethod.PATCH) { path.patch(operation); } else if (requestMethod == RequestMethod.POST) { path.post(operation); } else if (requestMethod == RequestMethod.PUT) { path.put(operation); } if (apiHeaders != null && apiHeaders.value() != null && apiHeaders.value().length > 0) { for (ApiHeader header : apiHeaders.value()) { HeaderParameter parameter = new HeaderParameter(); parameter.setName(header.name()); parameter.setType("string"); parameter.setDescription(header.description()); parameter.setRequired(header.required()); operation.addParameter(parameter); } } for (Parameter parameter : method.getParameters()) { PathVariable pathVariable = parameter.getAnnotation(PathVariable.class); RequestParam requestParam = parameter.getAnnotation(RequestParam.class); RequestBody requestBody = parameter.getAnnotation(RequestBody.class); RequestPart requestPart = parameter.getAnnotation(RequestPart.class); ApiParam apiParam = parameter.getAnnotation(ApiParam.class); if (apiParam != null && pathVariable != null && isSimpleScalar(parameter.getType())) { PathParameter pathParameter = new PathParameter(); pathParameter.setRequired(true); pathParameter.setDescription(apiParam.description()); pathParameter.setType(lookupType(parameter.getType())); pathParameter.setFormat(lookupFormat(parameter.getType(), apiParam)); pathParameter.setName(pathVariable.value()); operation.addParameter(pathParameter); continue; } if (requestMethod == RequestMethod.DELETE || requestMethod == RequestMethod.GET || requestMethod == RequestMethod.HEAD || requestMethod == RequestMethod.OPTIONS || requestMethod == RequestMethod.PATCH || requestMethod == RequestMethod.PUT) { if (apiParam != null && requestParam != null && isSimpleArray(parameter.getType())) { QueryParameter param = new QueryParameter(); param.setRequired(requestParam.required()); param.setDescription(apiParam.description()); param.setType("array"); if (!"".equals(requestParam.value())) { param.setName(requestParam.value()); } if (!"".equals(requestParam.name())) { param.setName(requestParam.name()); } param.setItems(lookupProperty(parameter.getType(), requestParam, apiParam)); operation.addParameter(param); continue; } if (apiParam != null && requestParam != null && isSimpleScalar(parameter.getType())) { QueryParameter param = new QueryParameter(); param.setRequired(requestParam.required()); param.setDescription(apiParam.description()); param.setType(lookupType(parameter.getType())); param.setFormat(lookupFormat(parameter.getType(), apiParam)); if (!"".equals(requestParam.value())) { param.setName(requestParam.value()); } if (!"".equals(requestParam.name())) { param.setName(requestParam.name()); } operation.addParameter(param); continue; } if (apiParam != null && requestBody != null && parameter.getType() == MultipartFile.class) { FormParameter param = new FormParameter(); param.setRequired(true); param.setIn("body"); param.setName("body"); param.setType("file"); param.setDescription(apiParam.description()); operation.addConsumes("application/octet-stream"); // BodyParameter param = new BodyParameter(); // param.setRequired(requestBody.required()); // param.setDescription(apiParam.description()); // param.setName("body"); // ModelImpl model = new ModelImpl(); // model.setType("file"); // param.setSchema(model); operation.addParameter(param); continue; } if (apiParam != null && requestBody != null && isSimpleArray(parameter.getType())) { BodyParameter param = new BodyParameter(); param.setRequired(requestBody.required()); param.setDescription(apiParam.description()); param.setName("body"); ArrayModel model = new ArrayModel(); StringProperty property = new StringProperty(); property.setType(lookupType(parameter.getType())); property.setFormat(lookupFormat(parameter.getType(), apiParam)); model.setItems(property); param.setSchema(model); operation.addParameter(param); continue; } if (apiParam != null && requestBody != null && isSimpleScalar(parameter.getType())) { BodyParameter param = new BodyParameter(); param.setRequired(requestBody.required()); param.setDescription(apiParam.description()); param.setName("body"); ModelImpl model = new ModelImpl(); model.setType(lookupType(parameter.getType())); model.setFormat(lookupFormat(parameter.getType(), apiParam)); param.setSchema(model); operation.addParameter(param); continue; } if (apiParam != null && requestBody != null && isModelArray(parameter.getType())) { BodyParameter param = new BodyParameter(); param.setRequired(requestBody.required()); param.setDescription(apiParam.description()); param.setName("body"); ArrayModel model = new ArrayModel(); RefProperty property = new RefProperty(); property.setType(lookupType(parameter.getType())); property.set$ref("#/definitions/" + parameter.getType().getComponentType().getSimpleName()); if (!modelStack.contains(parameter.getType().getComponentType())) { modelStack.push(parameter.getType().getComponentType()); } model.setItems(property); param.setSchema(model); operation.addParameter(param); continue; } if (apiParam != null && requestBody != null && isModelScalar(parameter.getType())) { BodyParameter param = new BodyParameter(); param.setRequired(requestBody.required()); param.setDescription(apiParam.description()); param.setName("body"); RefModel model = new RefModel(); model.set$ref( "#/definitions/" + parameter.getType().getSimpleName()); if (!modelStack.contains(parameter.getType())) { modelStack.push(parameter.getType()); } param.setSchema(model); operation.addParameter(param); continue; } } else if (requestMethod == RequestMethod.POST) { if (apiParam != null && requestParam != null && isSimpleArray(parameter.getType())) { FormParameter param = new FormParameter(); param.setRequired(requestParam.required()); param.setDescription(apiParam.description()); param.setType("array"); if (!"".equals(requestParam.value())) { param.setName(requestParam.value()); } if (!"".equals(requestParam.name())) { param.setName(requestParam.name()); } param.setItems(lookupProperty(parameter.getType(), requestParam, apiParam)); operation.addParameter(param); continue; } if (apiParam != null && requestParam != null && isSimpleScalar(parameter.getType())) { FormParameter param = new FormParameter(); param.setRequired(requestParam.required()); param.setDescription(apiParam.description()); param.setType(lookupType(parameter.getType())); param.setFormat(lookupFormat(parameter.getType(), apiParam)); if (!"".equals(requestParam.value())) { param.setName(requestParam.value()); } if (!"".equals(requestParam.name())) { param.setName(requestParam.name()); } operation.addParameter(param); continue; } if (apiParam != null && requestPart != null && isSimpleArray(parameter.getType())) { FormParameter param = new FormParameter(); param.setRequired(requestPart.required()); param.setDescription(apiParam.description()); param.setType("array"); if (!"".equals(requestPart.value())) { param.setName(requestPart.value()); } if (!"".equals(requestPart.name())) { param.setName(requestPart.name()); } param.setItems(lookupProperty(parameter.getType(), requestParam, apiParam)); operation.addParameter(param); continue; } if (apiParam != null && requestPart != null && isSimpleScalar(parameter.getType())) { FormParameter param = new FormParameter(); param.setRequired(requestPart.required()); param.setDescription(apiParam.description()); param.setType(lookupType(parameter.getType())); param.setFormat(lookupFormat(parameter.getType(), apiParam)); if (!"".equals(requestPart.value())) { param.setName(requestPart.value()); } if (!"".equals(requestPart.name())) { param.setName(requestPart.name()); } operation.addParameter(param); continue; } } } for (ApiResponse apiResponse : apiResponses.value()) { if (isSimpleScalar(apiResponse.response())) { if (apiResponse.array()) { Response response = new Response(); if (!"".equals(apiResponse.description())) { response.setDescription( apiResponse.httpStatus().getReasonPhrase()); } else { response.setDescription(apiResponse.description()); } ArrayProperty property = new ArrayProperty(); property.setItems( lookupProperty(apiResponse.response(), apiResponse)); response.setSchema(property); operation.addResponse( String.valueOf(apiResponse.httpStatus().value()), response); } else { Response response = new Response(); if ("".equals(apiResponse.description())) { response.setDescription( apiResponse.httpStatus().getReasonPhrase()); } else { response.setDescription(apiResponse.description()); } response.setSchema( lookupProperty(apiResponse.response(), apiResponse)); operation.addResponse( String.valueOf(apiResponse.httpStatus().value()), response); } } else if (isModelScalar(apiResponse.response())) { if (apiResponse.array()) { Response response = new Response(); if (!"".equals(apiResponse.description())) { response.setDescription( apiResponse.httpStatus().getReasonPhrase()); } else { response.setDescription(apiResponse.description()); } RefProperty property = new RefProperty(); property.set$ref( "#/definitions/" + apiResponse.response().getSimpleName()); if (!modelStack.contains(apiResponse.response())) { modelStack.push(apiResponse.response()); } ArrayProperty array = new ArrayProperty(); array.setItems(property); response.setSchema(array); operation.addResponse( String.valueOf(apiResponse.httpStatus().value()), response); } else { Response response = new Response(); if (!"".equals(apiResponse.description())) { response.setDescription( apiResponse.httpStatus().getReasonPhrase()); } else { response.setDescription(apiResponse.description()); } RefProperty property = new RefProperty(); property.set$ref( "#/definitions/" + apiResponse.response().getSimpleName()); if (!modelStack.contains(apiResponse.response())) { modelStack.push(apiResponse.response()); } response.setSchema(property); operation.addResponse( String.valueOf(apiResponse.httpStatus().value()), response); } } } } } } } } } } while (!modelStack.isEmpty()) { Class<?> scheme = modelStack.pop(); if (definitions.containsKey(scheme.getSimpleName())) { continue; } java.lang.reflect.Field[] fields = scheme.getDeclaredFields(); if (fields != null && fields.length > 0) { ModelImpl model = new ModelImpl(); model.setType("object"); for (Field field : fields) { ApiProperty apiProperty = field.getDeclaredAnnotation(ApiProperty.class); if (apiProperty != null) { if (apiProperty.array()) { Class<?> type = apiProperty.model(); ArrayProperty property = new ArrayProperty(); if (isSimpleScalar(type)) { property.setItems(lookupProperty(type, apiProperty)); } else if (isModelScalar(type)) { if (!definitions.containsKey(type.getSimpleName())) { modelStack.push(type); } RefProperty ref = new RefProperty(); ref.set$ref("#/definitions/" + type.getSimpleName()); property.setItems(ref); } model.addProperty(field.getName(), property); } else { Class<?> type = field.getType(); if (isSimpleScalar(type)) { model.addProperty(field.getName(), lookupProperty(type, apiProperty)); } else if (isModelScalar(type)) { if (!definitions.containsKey(type.getSimpleName())) { modelStack.push(type); } RefProperty ref = new RefProperty(); ref.set$ref("#/definitions/" + type.getSimpleName()); model.addProperty(field.getName(), ref); } } } } definitions.put(scheme.getSimpleName(), model); } } this.swagger = swagger; }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
public static APIResourceModel processRestClass(Class resource, String rootPath) { APIResourceModel resourceModel = new APIResourceModel(); resourceModel.setClassName(resource.getName()); resourceModel.setResourceName(/*from w ww. j a v a2 s. c o m*/ String.join(" ", StringUtils.splitByCharacterTypeCamelCase(resource.getSimpleName()))); APIDescription aPIDescription = (APIDescription) resource.getAnnotation(APIDescription.class); if (aPIDescription != null) { resourceModel.setResourceDescription(aPIDescription.value()); } Path path = (Path) resource.getAnnotation(Path.class); if (path != null) { resourceModel.setResourcePath(rootPath + "/" + path.value()); } RequireAdmin requireAdmin = (RequireAdmin) resource.getAnnotation(RequireAdmin.class); if (requireAdmin != null) { resourceModel.setRequireAdmin(true); } //class parameters mapParameters(resourceModel.getResourceParams(), resource.getDeclaredFields()); //methods ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); int methodId = 0; for (Method method : resource.getDeclaredMethods()) { APIMethodModel methodModel = new APIMethodModel(); methodModel.setId(methodId++); //rest method List<String> restMethods = new ArrayList<>(); GET getMethod = (GET) method.getAnnotation(GET.class); POST postMethod = (POST) method.getAnnotation(POST.class); PUT putMethod = (PUT) method.getAnnotation(PUT.class); DELETE deleteMethod = (DELETE) method.getAnnotation(DELETE.class); if (getMethod != null) { restMethods.add("GET"); } if (postMethod != null) { restMethods.add("POST"); } if (putMethod != null) { restMethods.add("PUT"); } if (deleteMethod != null) { restMethods.add("DELETE"); } methodModel.setRestMethod(String.join(",", restMethods)); if (restMethods.isEmpty()) { //skip non-rest methods continue; } //produces Produces produces = (Produces) method.getAnnotation(Produces.class); if (produces != null) { methodModel.setProducesTypes(String.join(",", produces.value())); } //consumes Consumes consumes = (Consumes) method.getAnnotation(Consumes.class); if (consumes != null) { methodModel.setConsumesTypes(String.join(",", consumes.value())); } aPIDescription = (APIDescription) method.getAnnotation(APIDescription.class); if (aPIDescription != null) { methodModel.setDescription(aPIDescription.value()); } path = (Path) method.getAnnotation(Path.class); if (path != null) { methodModel.setMethodPath(path.value()); } requireAdmin = (RequireAdmin) method.getAnnotation(RequireAdmin.class); if (requireAdmin != null) { methodModel.setRequireAdmin(true); } try { if (!(method.getReturnType().getSimpleName().equalsIgnoreCase(Void.class.getSimpleName()))) { APIValueModel valueModel = new APIValueModel(); DataType dataType = (DataType) method.getAnnotation(DataType.class); boolean addResponseObject = true; if ("javax.ws.rs.core.Response".equals(method.getReturnType().getName()) && dataType == null) { addResponseObject = false; } if (addResponseObject) { valueModel.setValueObjectName(method.getReturnType().getSimpleName()); ReturnType returnType = (ReturnType) method.getAnnotation(ReturnType.class); Class returnTypeClass; if (returnType != null) { returnTypeClass = returnType.value(); } else { returnTypeClass = method.getReturnType(); } if (!"javax.ws.rs.core.Response".equals(method.getReturnType().getName())) { if (ReflectionUtil.isCollectionClass(method.getReturnType()) == false) { try { valueModel.setValueObject( objectMapper.writeValueAsString(returnTypeClass.newInstance())); mapValueField(valueModel.getValueFields(), ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0])); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0]), false); aPIDescription = (APIDescription) returnTypeClass .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setValueDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", returnTypeClass)); } } } if (dataType != null) { String typeName = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeName = dataType.actualClassName(); } valueModel.setTypeObjectName(typeName); try { valueModel.setTypeObject( objectMapper.writeValueAsString(dataType.value().newInstance())); mapValueField(valueModel.getTypeFields(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0])); mapComplexTypes(valueModel.getAllComplexTypes(), ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), false); aPIDescription = (APIDescription) dataType.value() .getAnnotation(APIDescription.class); if (aPIDescription != null) { valueModel.setTypeDescription(aPIDescription.value()); } } catch (InstantiationException iex) { log.log(Level.WARNING, MessageFormat.format( "Unable to instantiated type: {0} make sure the type is not abstract.", dataType.value())); } } methodModel.setResponseObject(valueModel); } } } catch (IllegalAccessException | JsonProcessingException ex) { log.log(Level.WARNING, null, ex); } //method parameters mapMethodParameters(methodModel.getMethodParams(), method.getParameters()); //Handle Consumed Objects mapConsumedObjects(methodModel, method.getParameters()); resourceModel.getMethods().add(methodModel); } Collections.sort(resourceModel.getMethods(), new ApiMethodComparator<>()); return resourceModel; }
From source file:io.sinistral.proteus.server.tools.swagger.Reader.java
@SuppressWarnings("deprecation") private Operation parseMethod(Class<?> cls, Method method, AnnotatedMethod annotatedMethod, List<Parameter> globalParameters, List<ApiResponse> classApiResponses, List<String> pathParamNames) { Operation operation = new Operation(); if (annotatedMethod != null) { method = annotatedMethod.getAnnotated(); }/*from ww w. jav a 2s .co m*/ ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId; // check if it's an inherited or implemented method. boolean methodInSuperType = false; if (!cls.isInterface()) { methodInSuperType = ReflectionUtils.findMethod(method, cls.getSuperclass()) != null; } if (!methodInSuperType) { for (Class<?> implementedInterface : cls.getInterfaces()) { methodInSuperType = ReflectionUtils.findMethod(method, implementedInterface) != null; if (methodInSuperType) { break; } } } if (!methodInSuperType) { operationId = method.getName(); } else { operationId = this.getOperationId(method.getName()); } String responseContainer = null; Type responseType = null; Map<String, Property> defaultResponseHeaders = new LinkedHashMap<String, Property>(); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (operationId == null) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (!isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } if (!apiOperation.consumes().isEmpty()) { String[] consumesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.consumes() }); for (String consume : consumesAr) { operation.consumes(consume); } } if (!apiOperation.produces().isEmpty()) { String[] producesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.produces() }); for (String produce : producesAr) { operation.produces(produce); } } } /* * @TODO * Use apiOperation response class instead of unwrapping ServerResponse's inner type */ if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) { Response response = new Response().description(SUCCESSFUL_OPERATION); response.schema(new RefProperty(apiOperation.responseReference())); operation.addResponse(String.valueOf(apiOperation.code()), response); } else if (responseType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method {}", method); responseType = method.getGenericReturnType(); } if (responseType != null) { final JavaType javaType = TypeFactory.defaultInstance().constructType(responseType); if (!isVoid(javaType)) { final Class<?> responseCls = javaType.getRawClass(); if (responseCls != null) { if (responseCls.isAssignableFrom(ServerResponse.class)) { responseType = javaType.containedType(0); } else if (responseCls.isAssignableFrom(CompletableFuture.class)) { Class<?> futureCls = javaType.containedType(0).getRawClass(); if (futureCls.isAssignableFrom(ServerResponse.class)) { final JavaType futureType = TypeFactory.defaultInstance() .constructType(javaType.containedType(0)); responseType = futureType.containedType(0); } else { responseType = javaType.containedType(0); } } } } } if (isValidResponse(responseType)) { final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property); final int responseCode = (apiOperation == null) ? 200 : apiOperation.code(); operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION) .schema(responseProperty).headers(defaultResponseHeaders)); appendModels(responseType); } } operation.operationId(operationId); if (operation.getConsumes() == null || operation.getConsumes().isEmpty()) { final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) { operation.consumes(mediaType); } } } if (operation.getProduces() == null || operation.getProduces().isEmpty()) { final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : ReaderUtils.splitContentValues(produces.value())) { operation.produces(mediaType); } } } List<ApiResponse> apiResponses = new ArrayList<>(); if (responseAnnotation != null) { apiResponses.addAll(Arrays.asList(responseAnnotation.value())); } Class<?>[] exceptionTypes = method.getExceptionTypes(); for (Class<?> exceptionType : exceptionTypes) { ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class); if (exceptionResponses != null) { apiResponses.addAll(Arrays.asList(exceptionResponses.value())); } } for (ApiResponse apiResponse : apiResponses) { addResponse(operation, apiResponse); } // merge class level @ApiResponse for (ApiResponse apiResponse : classApiResponses) { String key = (apiResponse.code() == 0) ? "default" : String.valueOf(apiResponse.code()); if (operation.getResponses() != null && operation.getResponses().containsKey(key)) { continue; } addResponse(operation, apiResponse); } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } // process parameters for (Parameter globalParameter : globalParameters) { LOGGER.debug("globalParameters TYPE: " + globalParameter); operation.parameter(globalParameter); } Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method); java.lang.reflect.Parameter[] methodParameters = method.getParameters(); if (annotatedMethod == null) { Type[] genericParameterTypes = method.getGenericParameterTypes(); for (int i = 0; i < genericParameterTypes.length; i++) { Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); if (type.getTypeName().contains("Optional") || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) { if (type instanceof com.fasterxml.jackson.databind.type.SimpleType) { com.fasterxml.jackson.databind.type.SimpleType simpleType = (com.fasterxml.jackson.databind.type.SimpleType) type; type = simpleType.containedType(0); } } if (type.equals(ServerRequest.class) || type.equals(HttpServerExchange.class) || type.equals(HttpHandler.class) || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) { continue; } List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]), methodParameters[i], pathParamNames); for (Parameter parameter : parameters) { operation.parameter(parameter); } } } else { for (int i = 0; i < annotatedMethod.getParameterCount(); i++) { AnnotatedParameter param = annotatedMethod.getParameter(i); if (param.getParameterType().equals(ServerRequest.class) || param.getParameterType().equals(HttpServerExchange.class) || param.getParameterType().equals(HttpHandler.class) || param.getParameterType().getTypeName().contains("ServerResponse")) { continue; } Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]), methodParameters[i], pathParamNames); for (Parameter parameter : parameters) { operation.parameter(parameter); } } } if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.response(200, response); } processOperationDecorator(operation, method); return operation; }
From source file:ca.oson.json.Oson.java
<T> T newInstance(Map<String, Object> map, Class<T> valueType) { InstanceCreator creator = getTypeAdapter(valueType); if (creator != null) { return (T) creator.createInstance(valueType); }/*from www. ja v a2s . c o m*/ T obj = null; if (valueType != null) { obj = (T) getDefaultValue(valueType); if (obj != null) { return obj; } } if (map == null) { return null; } // @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = As.PROPERTY, property = "@class") //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class") String JsonClassType = null; if (valueType != null) { if (getAnnotationSupport()) { for (Annotation annotation : valueType.getAnnotations()) { if (annotation instanceof JsonTypeInfo) { JsonTypeInfo jsonTypeInfo = (JsonTypeInfo) annotation; JsonTypeInfo.Id use = jsonTypeInfo.use(); JsonTypeInfo.As as = jsonTypeInfo.include(); if ((use == JsonTypeInfo.Id.MINIMAL_CLASS || use == JsonTypeInfo.Id.CLASS) && as == As.PROPERTY) { JsonClassType = jsonTypeInfo.property(); } } } } } if (JsonClassType == null) { JsonClassType = getJsonClassType(); } String className = null; if (map.containsKey(JsonClassType)) { className = map.get(JsonClassType).toString(); } Class<T> classType = getClassType(className); // && (valueType == null || valueType.isAssignableFrom(classType) || Map.class.isAssignableFrom(valueType)) if (classType != null) { valueType = classType; } if (valueType == null) { return (T) map; // or null, which is better? } Constructor<?>[] constructors = null; Class implClass = null; if (valueType.isInterface() || Modifier.isAbstract(valueType.getModifiers())) { implClass = DeSerializerUtil.implementingClass(valueType.getName()); } if (implClass != null) { constructors = implClass.getDeclaredConstructors(); } else { constructors = valueType.getDeclaredConstructors();//.getConstructors(); } Object singleMapValue = null; Class singleMapValueType = null; if (map.size() == 1) { singleMapValue = map.get(valueType.getName()); if (singleMapValue != null) { singleMapValueType = singleMapValue.getClass(); if (singleMapValueType == String.class) { singleMapValue = StringUtil.unquote(singleMapValue.toString(), isEscapeHtml()); } try { if (valueType == Locale.class) { Constructor constructor = null; String[] parts = ((String) singleMapValue).split("_"); if (parts.length == 1) { constructor = valueType.getConstructor(String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(singleMapValue); } else if (parts.length == 2) { constructor = valueType.getConstructor(String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } else if (parts.length == 3) { constructor = valueType.getConstructor(String.class, String.class, String.class); constructor.setAccessible(true); obj = (T) constructor.newInstance(parts); } if (obj != null) { return obj; } } } catch (Exception e) { } Map<Class, Constructor> cmaps = new HashMap<>(); for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount == 1) { Class[] types = constructor.getParameterTypes(); cmaps.put(types[0], constructor); } } if (cmaps.size() > 0) { Constructor constructor = null; if ((cmaps.containsKey(Boolean.class) || cmaps.containsKey(boolean.class)) && BooleanUtil.isBoolean(singleMapValue.toString())) { constructor = cmaps.get(Boolean.class); if (constructor == null) { constructor = cmaps.get(boolean.class); } if (constructor != null) { try { constructor.setAccessible(true); obj = (T) constructor .newInstance(BooleanUtil.string2Boolean(singleMapValue.toString())); if (obj != null) { return obj; } } catch (Exception e) { } } } else if (StringUtil.isNumeric(singleMapValue.toString())) { Class[] classes = new Class[] { int.class, Integer.class, long.class, Long.class, double.class, Double.class, Byte.class, byte.class, Short.class, short.class, Float.class, float.class, BigDecimal.class, BigInteger.class, AtomicInteger.class, AtomicLong.class, Number.class }; for (Class cls : classes) { constructor = cmaps.get(cls); if (constructor != null) { try { obj = (T) constructor.newInstance(NumberUtil.getNumber(singleMapValue, cls)); if (obj != null) { return obj; } } catch (Exception e) { } } } } else if (StringUtil.isArrayOrList(singleMapValue.toString()) || singleMapValue.getClass().isArray() || Collection.class.isAssignableFrom(singleMapValue.getClass())) { for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); if (cls.isArray() || Collection.class.isAssignableFrom(cls)) { Object listObject = null; if (singleMapValue instanceof String) { JSONArray objArray = new JSONArray(singleMapValue.toString()); listObject = (List) fromJsonMap(objArray); } else { listObject = singleMapValue; } FieldData objectDTO = new FieldData(listObject, cls, true); listObject = json2Object(objectDTO); if (listObject != null) { try { obj = (T) constructor.newInstance(listObject); if (obj != null) { return obj; } } catch (Exception e) { } } } } } for (Entry<Class, Constructor> entry : cmaps.entrySet()) { Class cls = entry.getKey(); constructor = entry.getValue(); try { obj = (T) constructor.newInstance(singleMapValue); if (obj != null) { return obj; } } catch (Exception e) { } } } } } if (implClass != null) { valueType = implClass; } try { obj = valueType.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException e) { //e.printStackTrace(); } ///* for (Constructor constructor : constructors) { //Class[] parameterTypes = constructor.getParameterTypes(); int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Annotation[] annotations = constructor.getDeclaredAnnotations(); // getAnnotations(); for (Annotation annotation : annotations) { boolean isJsonCreator = false; if (annotation instanceof JsonCreator) { isJsonCreator = true; } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) { ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation; if (fieldMapper.jsonCreator() == BOOLEAN.TRUE) { isJsonCreator = true; } } if (isJsonCreator) { Parameter[] parameters = constructor.getParameters(); String[] parameterNames = ObjectUtil.getParameterNames(parameters); //parameterCount = parameters.length; Object[] parameterValues = new Object[parameterCount]; int i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameters[i].getType()); i++; } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } else { try { constructor.setAccessible(true); obj = (T) constructor.newInstance(); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } //*/ // try again for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); try { List<String> parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null && parameterNames.size() > 0) { Class[] parameterTypes = constructor.getParameterTypes(); int length = parameterTypes.length; if (length == parameterNames.size()) { Object[] parameterValues = new Object[length]; Object parameterValue; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } try { obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { //e.printStackTrace(); } } } } catch (IOException e1) { // e1.printStackTrace(); } } } // try more for (Constructor constructor : constructors) { int parameterCount = constructor.getParameterCount(); if (parameterCount > 0) { constructor.setAccessible(true); Class[] parameterTypes = constructor.getParameterTypes(); List<String> parameterNames; try { parameterNames = ObjectUtil.getParameterNames(constructor); if (parameterNames != null) { int length = parameterTypes.length; if (length > parameterNames.size()) { length = parameterNames.size(); } Object[] parameterValues = new Object[length]; for (int i = 0; i < length; i++) { parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i), parameterTypes[i]); } obj = (T) constructor.newInstance(parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | IOException e) { //e.printStackTrace(); } } } // try more try { Method[] methods = valueType.getMethods(); // .getMethod("getInstance", null); List<Method> methodList = new ArrayList<>(); if (methods != null) { for (Method method : methods) { String methodName = method.getName(); if (methodName.equals("getInstance") || methodName.equals("newInstance") || methodName.equals("createInstance") || methodName.equals("factory")) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType) && Modifier.isStatic(method.getModifiers())) { int parameterCount = method.getParameterCount(); if (parameterCount == 0) { try { obj = ObjectUtil.getMethodValue(null, method); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block //e.printStackTrace(); } } else { methodList.add(method); } } } } for (Method method : methodList) { try { int parameterCount = method.getParameterCount(); Object[] parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterCount == 1 && valueType != null && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(parameterTypes[0], singleMapValueType)) { try { obj = ObjectUtil.getMethodValue(null, method, singleMapValue); if (obj != null) { return obj; } } catch (IllegalArgumentException ex) { //ex.printStackTrace(); } } } else if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } obj = ObjectUtil.getMethodValue(null, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } catch (SecurityException e) { // e.printStackTrace(); } // try all static methods, if the return type is correct, get it as the final object Method[] methods = valueType.getDeclaredMethods(); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers())) { Class returnType = method.getReturnType(); if (valueType.isAssignableFrom(returnType)) { try { Object[] parameterValues = null; int parameterCount = method.getParameterCount(); if (parameterCount > 0) { if (parameterCount == 1 && map.size() == 1 && singleMapValue != null && singleMapValueType != null) { if (ObjectUtil.isSameDataType(method.getParameterTypes()[0], singleMapValueType)) { obj = ObjectUtil.getMethodValue(null, method, singleMapValueType); if (obj != null) { return obj; } } } parameterValues = new Object[parameterCount]; Object parameterValue; int i = 0; Class[] parameterTypes = method.getParameterTypes(); String[] parameterNames = ObjectUtil.getParameterNames(method); if (parameterNames != null && parameterNames.length == parameterCount) { for (String parameterName : ObjectUtil.getParameterNames(method)) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } else { // try annotation Parameter[] parameters = method.getParameters(); parameterNames = ObjectUtil.getParameterNames(parameters); parameterCount = parameters.length; parameterValues = new Object[parameterCount]; i = 0; for (String parameterName : parameterNames) { parameterValues[i] = getParameterValue(map, valueType, parameterName, parameterTypes[i]); i++; } } } obj = ObjectUtil.getMethodValue(obj, method, parameterValues); if (obj != null) { return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType); } } catch (IOException | IllegalArgumentException e) { //e.printStackTrace(); } } } } return null; }
From source file:ca.oson.json.Oson.java
<T> T deserialize2Object(FieldData objectDTO) { Object valueToProcess = objectDTO.valueToProcess; Map<String, Object> map = null; if (valueToProcess != null && Map.class.isAssignableFrom(valueToProcess.getClass())) { map = (Map) valueToProcess; } else {//from w w w .j a v a 2 s .c o m map = new HashMap<>(); } Class<T> valueType = objectDTO.returnType; T obj = (T) objectDTO.returnObj; Set<String> nameKeys = new HashSet(map.keySet()); if (valueType == null) { valueType = (Class<T>) obj.getClass(); } // first build up the class-level processing rules ClassMapper classMapper = objectDTO.classMapper; //if (classMapper == null) { // 1. Create a blank class mapper instance classMapper = new ClassMapper(valueType); // 2. Globalize it classMapper = globalize(classMapper); objectDTO.classMapper = classMapper; //} if (objectDTO.fieldMapper != null && isInheritMapping()) { classMapper = overwriteBy(classMapper, objectDTO.fieldMapper); } objectDTO.incrLevel(); try { boolean annotationSupport = getAnnotationSupport(); Annotation[] annotations = null; if (annotationSupport) { ca.oson.json.annotation.ClassMapper classMapperAnnotation = null; // 3. Apply annotations from other sources annotations = valueType.getAnnotations(); for (Annotation annotation : annotations) { if (ignoreClass(annotation)) { return null; } switch (annotation.annotationType().getName()) { case "ca.oson.json.annotation.ClassMapper": classMapperAnnotation = (ca.oson.json.annotation.ClassMapper) annotation; if (!(classMapperAnnotation.serialize() == BOOLEAN.BOTH || classMapperAnnotation.serialize() == BOOLEAN.FALSE)) { classMapperAnnotation = null; } break; case "ca.oson.json.annotation.ClassMappers": ca.oson.json.annotation.ClassMappers classMapperAnnotations = (ca.oson.json.annotation.ClassMappers) annotation; for (ca.oson.json.annotation.ClassMapper ann : classMapperAnnotations.value()) { if (ann.serialize() == BOOLEAN.BOTH || ann.serialize() == BOOLEAN.FALSE) { classMapperAnnotation = ann; // break; } } break; case "com.google.gson.annotations.Since": Since since = (Since) annotation; classMapper.since = since.value(); break; case "com.google.gson.annotations.Until": Until until = (Until) annotation; classMapper.until = until.value(); break; case "com.fasterxml.jackson.annotation.JsonIgnoreProperties": JsonIgnoreProperties jsonIgnoreProperties = (JsonIgnoreProperties) annotation; String[] jsonnames = jsonIgnoreProperties.value(); if (jsonnames != null && jsonnames.length > 0) { if (classMapper.jsonIgnoreProperties == null) { classMapper.jsonIgnoreProperties = new HashSet(); } classMapper.jsonIgnoreProperties.addAll(Arrays.asList(jsonnames)); } break; case "org.codehaus.jackson.annotate.JsonIgnoreProperties": org.codehaus.jackson.annotate.JsonIgnoreProperties jsonIgnoreProperties2 = (org.codehaus.jackson.annotate.JsonIgnoreProperties) annotation; String[] jsonnames2 = jsonIgnoreProperties2.value(); if (jsonnames2 != null && jsonnames2.length > 0) { if (classMapper.jsonIgnoreProperties == null) { classMapper.jsonIgnoreProperties = new HashSet(); } classMapper.jsonIgnoreProperties.addAll(Arrays.asList(jsonnames2)); } break; case "com.fasterxml.jackson.annotation.JsonPropertyOrder": // first come first serve if (classMapper.propertyOrders == null) { classMapper.propertyOrders = ((JsonPropertyOrder) annotation).value(); } break; case "org.codehaus.jackson.annotate.JsonPropertyOrder": // first come first serve if (classMapper.propertyOrders == null) { classMapper.propertyOrders = ((org.codehaus.jackson.annotate.JsonPropertyOrder) annotation) .value(); } break; case "com.fasterxml.jackson.annotation.JsonInclude": if (classMapper.defaultType == JSON_INCLUDE.NONE) { JsonInclude jsonInclude = (JsonInclude) annotation; switch (jsonInclude.content()) { case ALWAYS: classMapper.defaultType = JSON_INCLUDE.ALWAYS; break; case NON_NULL: classMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_ABSENT: classMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_EMPTY: classMapper.defaultType = JSON_INCLUDE.NON_EMPTY; break; case NON_DEFAULT: classMapper.defaultType = JSON_INCLUDE.NON_DEFAULT; break; case USE_DEFAULTS: classMapper.defaultType = JSON_INCLUDE.DEFAULT; break; } } break; case "com.fasterxml.jackson.annotation.JsonAutoDetect": JsonAutoDetect jsonAutoDetect = (JsonAutoDetect) annotation; if (jsonAutoDetect.fieldVisibility() == Visibility.NONE) { classMapper.useField = false; } else if (jsonAutoDetect.fieldVisibility() != Visibility.DEFAULT) { classMapper.useField = true; } if (jsonAutoDetect.setterVisibility() == Visibility.NONE) { classMapper.useAttribute = false; } else if (jsonAutoDetect.setterVisibility() != Visibility.DEFAULT) { classMapper.useAttribute = true; } break; case "org.codehaus.jackson.annotate.JsonAutoDetect": org.codehaus.jackson.annotate.JsonAutoDetect jsonAutoDetect2 = (org.codehaus.jackson.annotate.JsonAutoDetect) annotation; if (jsonAutoDetect2 .fieldVisibility() == org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE) { classMapper.useField = false; } if (jsonAutoDetect2 .getterVisibility() == org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.NONE) { classMapper.useAttribute = false; } break; case "org.junit.Ignore": classMapper.ignore = true; break; } } // 4. Apply annotations from Oson if (classMapperAnnotation != null) { classMapper = overwriteBy(classMapper, classMapperAnnotation); } } // 5. Apply Java configuration for this particular class ClassMapper javaClassMapper = getClassMapper(valueType); if (javaClassMapper != null) { classMapper = overwriteBy(classMapper, javaClassMapper); } // now processing at the class level if (classMapper.ignore()) { return null; } if (classMapper.since != null && classMapper.since > getVersion()) { return null; } else if (classMapper.until != null && classMapper.until <= getVersion()) { return null; } Function function = classMapper.deserializer; // = getDeserializer(valueType); if (function == null) { function = DeSerializerUtil.getDeserializer(valueType.getName()); } if (function != null) { try { Object returnedValue = null; if (function instanceof Json2DataMapperFunction) { DataMapper classData = new DataMapper(valueToProcess, valueType, obj, classMapper, objectDTO.level, getPrettyIndentation()); Json2DataMapperFunction f = (Json2DataMapperFunction) function; return (T) f.apply(classData); } else if (function instanceof Json2FieldDataFunction) { Json2FieldDataFunction f = (Json2FieldDataFunction) function; FieldData fieldData = objectDTO.clone(); returnedValue = f.apply(fieldData); } else { returnedValue = function.apply(obj); } if (returnedValue instanceof Optional) { Optional opt = (Optional) returnedValue; returnedValue = opt.orElse(null); } if (returnedValue == null) { return null; } else if (valueType.isAssignableFrom(returnedValue.getClass())) { return (T) returnedValue; } else { // not the correct returned object type, do nothing } } catch (Exception e) { e.printStackTrace(); } } Map<String, Method> getters = getGetters(valueType); Map<String, Method> setters = getSetters(valueType); Map<String, Method> otherMethods = getOtherMethods(valueType); Set<String> processedNameSet = new HashSet<>(); Method jsonAnySetterMethod = null; Field[] fields = getFields(valueType); // getFields(obj); FIELD_NAMING format = getFieldNaming(); // @Expose boolean exposed = false; if (isUseGsonExpose()) { // check if @exposed is used any where if (valueType.isAnnotationPresent(com.google.gson.annotations.Expose.class)) { exposed = true; } if (!exposed) { for (Field f : fields) { if (f.isAnnotationPresent(com.google.gson.annotations.Expose.class)) { exposed = true; break; } } } } for (Field f : fields) { String name = f.getName(); String fieldName = name; String lcfieldName = name.toLowerCase(); Class<?> returnType = f.getType(); // value.getClass(); if (Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) { setters.remove(lcfieldName); nameKeys.remove(name); continue; } f.setAccessible(true); // getter and setter methods Method getter = null; Method setter = null; if (getters != null) { getter = getters.get(lcfieldName); } if (setters != null) { setter = setters.get(lcfieldName); } if (ignoreModifiers(f.getModifiers(), classMapper.includeFieldsWithModifiers)) { if (setter != null) { if (ignoreModifiers(setter.getModifiers(), classMapper.includeFieldsWithModifiers)) { setters.remove(lcfieldName); nameKeys.remove(name); continue; } } else { continue; } } // 6. Create a blank field mapper instance // using valueType of enclosing obj FieldMapper fieldMapper = new FieldMapper(name, name, valueType); // 7. get the class mapper of returnType ClassMapper fieldClassMapper = getClassMapper(returnType); // 8. Classify this field mapper with returnType fieldMapper = classifyFieldMapper(fieldMapper, fieldClassMapper); // 9. Classify this field mapper with enclosing class type fieldMapper = classifyFieldMapper(fieldMapper, classMapper); FieldMapper javaFieldMapper = getFieldMapper(name, null, valueType); boolean ignored = false; if (setter != null) { setter.setAccessible(true); } Set<String> names = new HashSet<>(); if (annotationSupport) { annotations = f.getAnnotations(); if (setter != null && ((javaFieldMapper == null || javaFieldMapper.useAttribute == null) && (fieldMapper.useAttribute == null || fieldMapper.useAttribute)) || (javaFieldMapper != null && javaFieldMapper.isDeserializing() && javaFieldMapper.useAttribute != null && javaFieldMapper.useAttribute)) { annotations = Stream .concat(Arrays.stream(annotations), Arrays.stream(setter.getDeclaredAnnotations())) .toArray(Annotation[]::new); } // no annotations, then try get method if ((annotations == null || annotations.length == 0) && getter != null) { annotations = getter.getDeclaredAnnotations(); } ca.oson.json.annotation.FieldMapper fieldMapperAnnotation = null; boolean exposexists = false; for (Annotation annotation : annotations) { if (ignoreField(annotation, classMapper.ignoreFieldsWithAnnotations)) { ignored = true; break; } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) { fieldMapperAnnotation = (ca.oson.json.annotation.FieldMapper) annotation; if (!(fieldMapperAnnotation.serialize() == BOOLEAN.BOTH || fieldMapperAnnotation.serialize() == BOOLEAN.FALSE)) { fieldMapperAnnotation = null; } } else if (annotation instanceof ca.oson.json.annotation.FieldMappers) { ca.oson.json.annotation.FieldMappers fieldMapperAnnotations = (ca.oson.json.annotation.FieldMappers) annotation; for (ca.oson.json.annotation.FieldMapper ann : fieldMapperAnnotations.value()) { if (ann.serialize() == BOOLEAN.BOTH || ann.serialize() == BOOLEAN.FALSE) { fieldMapperAnnotation = ann; //break; to enable the last one wins } } } else { switch (annotation.annotationType().getName()) { case "com.fasterxml.jackson.annotation.JsonAnySetter": case "org.codehaus.jackson.annotate.JsonAnySetter": fieldMapper.jsonAnySetter = true; break; case "javax.persistence.Transient": fieldMapper.ignore = true; break; case "com.fasterxml.jackson.annotation.JsonIgnore": case "org.codehaus.jackson.annotate.JsonIgnore": fieldMapper.ignore = true; break; case "com.fasterxml.jackson.annotation.JsonIgnoreProperties": JsonIgnoreProperties jsonIgnoreProperties = (JsonIgnoreProperties) annotation; if (!jsonIgnoreProperties.allowSetters()) { fieldMapper.ignore = true; } else { fieldMapper.ignore = false; classMapper.jsonIgnoreProperties.remove(name); } break; case "com.google.gson.annotations.Expose": Expose expose = (Expose) annotation; if (!expose.deserialize()) { fieldMapper.ignore = true; } exposexists = true; break; case "com.google.gson.annotations.Since": Since since = (Since) annotation; fieldMapper.since = since.value(); break; case "com.google.gson.annotations.Until": Until until = (Until) annotation; fieldMapper.until = until.value(); break; case "com.google.gson.annotations.SerializedName": SerializedName serializedName = (SerializedName) annotation; String[] alternates = serializedName.alternate(); if (alternates != null && alternates.length > 0) { for (String alternate : alternates) { names.add(alternate); } } break; case "com.fasterxml.jackson.annotation.JsonInclude": if (fieldMapper.defaultType == JSON_INCLUDE.NONE) { JsonInclude jsonInclude = (JsonInclude) annotation; switch (jsonInclude.content()) { case ALWAYS: fieldMapper.defaultType = JSON_INCLUDE.ALWAYS; break; case NON_NULL: fieldMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_ABSENT: fieldMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_EMPTY: fieldMapper.defaultType = JSON_INCLUDE.NON_EMPTY; break; case NON_DEFAULT: fieldMapper.defaultType = JSON_INCLUDE.NON_DEFAULT; break; case USE_DEFAULTS: fieldMapper.defaultType = JSON_INCLUDE.DEFAULT; break; } } break; case "com.fasterxml.jackson.annotation.JsonRawValue": if (((JsonRawValue) annotation).value()) { fieldMapper.jsonRawValue = true; } break; case "org.codehaus.jackson.annotate.JsonRawValue": if (((org.codehaus.jackson.annotate.JsonRawValue) annotation).value()) { fieldMapper.jsonRawValue = true; } break; case "org.junit.Ignore": fieldMapper.ignore = true; break; case "javax.persistence.Enumerated": fieldMapper.enumType = ((Enumerated) annotation).value(); break; case "javax.validation.constraints.NotNull": fieldMapper.required = true; break; case "com.fasterxml.jackson.annotation.JsonProperty": JsonProperty jsonProperty = (JsonProperty) annotation; Access access = jsonProperty.access(); if (access == Access.READ_ONLY) { fieldMapper.ignore = true; } if (jsonProperty.required()) { fieldMapper.required = true; } if (fieldMapper.defaultValue == null) { fieldMapper.defaultValue = jsonProperty.defaultValue(); } break; case "javax.validation.constraints.Size": Size size = (Size) annotation; if (size.min() > 0) { fieldMapper.min = (long) size.min(); } if (size.max() < Integer.MAX_VALUE) { fieldMapper.max = (long) size.max(); } break; case "javax.persistence.Column": Column column = (Column) annotation; if (column.length() != 255) { fieldMapper.length = column.length(); } if (column.scale() > 0) { fieldMapper.scale = column.scale(); } if (column.precision() > 0) { fieldMapper.precision = column.precision(); } if (!column.nullable()) { fieldMapper.required = true; } break; } String fname = ObjectUtil.getName(annotation); if (!StringUtil.isEmpty(fname)) { names.add(fname); } } } if (exposed && !exposexists) { fieldMapper.ignore = true; } // 10. Apply annotations from Oson if (fieldMapperAnnotation != null) { fieldMapper = overwriteBy(fieldMapper, fieldMapperAnnotation, classMapper); } } if (ignored) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); setters.remove(lcfieldName); if (exposed) { setNull(f, obj); } continue; } // 11. Apply Java configuration for this particular field if (javaFieldMapper != null && javaFieldMapper.isDeserializing()) { fieldMapper = overwriteBy(fieldMapper, javaFieldMapper); } if (fieldMapper.ignore != null && fieldMapper.ignore) { if (setter != null) { setters.remove(lcfieldName); } nameKeys.remove(name); nameKeys.remove(fieldMapper.json); if (exposed) { setNull(f, obj); } continue; } // in the ignored list if (ObjectUtil.inSet(name, classMapper.jsonIgnoreProperties)) { setters.remove(lcfieldName); nameKeys.remove(name); continue; } if (fieldMapper.jsonAnySetter != null && fieldMapper.jsonAnySetter && setter != null) { setters.remove(lcfieldName); otherMethods.put(lcfieldName, setter); continue; } if (fieldMapper.useField != null && !fieldMapper.useField) { // both should not be used, just like ignore if (fieldMapper.useAttribute != null && !fieldMapper.useAttribute) { getters.remove(lcfieldName); } continue; } if (fieldMapper.since != null && fieldMapper.since > getVersion()) { if (setter != null) { setters.remove(lcfieldName); } continue; } else if (fieldMapper.until != null && fieldMapper.until <= getVersion()) { if (setter != null) { setters.remove(lcfieldName); } continue; } // get value for name in map Object value = null; boolean jnameFixed = false; String json = fieldMapper.json; int size = nameKeys.size(); if (json == null) { if (setter != null) { setters.remove(lcfieldName); } continue; } else if (!json.equals(name)) { name = json; value = getMapValue(map, name, nameKeys); jnameFixed = true; } if (!jnameFixed) { for (String jsoname : names) { if (!name.equals(jsoname) && !StringUtil.isEmpty(jsoname)) { name = jsoname; value = getMapValue(map, name, nameKeys); if (value != null) { jnameFixed = true; break; } } } } if (!jnameFixed) { value = getMapValue(map, name, nameKeys); jnameFixed = true; } fieldMapper.java = fieldName; fieldMapper.json = name; // either not null, or a null value exists in the value map if (value != null || size == nameKeys.size() + 1) { Object oldValue = value; FieldData fieldData = new FieldData(obj, f, value, returnType, true, fieldMapper, objectDTO.level, objectDTO.set); fieldData.setter = setter; Class fieldType = guessComponentType(fieldData); value = json2Object(fieldData); if (StringUtil.isNull(value)) { if (classMapper.defaultType == JSON_INCLUDE.NON_NULL || classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } else if (StringUtil.isEmpty(value)) { if (classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } else if (DefaultValue.isDefault(value, returnType)) { if (classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } try { if (value == null && oldValue != null && oldValue.equals(f.get(obj) + "")) { // keep original value } else { f.set(obj, value); } } catch (IllegalAccessException | IllegalArgumentException ex) { //ex.printStackTrace(); if (setter != null) { ObjectUtil.setMethodValue(obj, setter, value); } } } setters.remove(lcfieldName); nameKeys.remove(name); } for (Entry<String, Method> entry : setters.entrySet()) { String lcfieldName = entry.getKey(); Method setter = entry.getValue(); setter.setAccessible(true); String name = setter.getName(); if (name != null && name.length() > 3 && name.substring(0, 3).equals("set") && name.substring(3).equalsIgnoreCase(lcfieldName)) { name = StringUtil.uncapitalize(name.substring(3)); } // just use field name, even it might not be a field String fieldName = name; if (ignoreModifiers(setter.getModifiers(), classMapper.includeFieldsWithModifiers)) { nameKeys.remove(name); continue; } if (Modifier.isFinal(setter.getModifiers()) && Modifier.isStatic(setter.getModifiers())) { nameKeys.remove(name); continue; } // 6. Create a blank field mapper instance FieldMapper fieldMapper = new FieldMapper(name, name, valueType); Class returnType = null; Class[] types = setter.getParameterTypes(); if (types != null && types.length > 0) { returnType = types[0]; } // not a proper setter if (returnType == null) { continue; } // 7. get the class mapper of returnType ClassMapper fieldClassMapper = getClassMapper(returnType); // 8. Classify this field mapper with returnType fieldMapper = classifyFieldMapper(fieldMapper, fieldClassMapper); // 9. Classify this field mapper with enclosing class type fieldMapper = classifyFieldMapper(fieldMapper, classMapper); FieldMapper javaFieldMapper = getFieldMapper(name, null, valueType); boolean ignored = false; Method getter = getters.get(lcfieldName); Set<String> names = new HashSet<>(); if (annotationSupport) { annotations = setter.getDeclaredAnnotations(); // no annotations, then try get method if ((annotations == null || annotations.length == 0) && getter != null) { annotations = getter.getDeclaredAnnotations(); } ca.oson.json.annotation.FieldMapper fieldMapperAnnotation = null; for (Annotation annotation : annotations) { if (ignoreField(annotation, classMapper.ignoreFieldsWithAnnotations)) { ignored = true; break; } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) { fieldMapperAnnotation = (ca.oson.json.annotation.FieldMapper) annotation; if (!(fieldMapperAnnotation.serialize() == BOOLEAN.BOTH || fieldMapperAnnotation.serialize() == BOOLEAN.FALSE)) { fieldMapperAnnotation = null; } } else if (annotation instanceof ca.oson.json.annotation.FieldMappers) { ca.oson.json.annotation.FieldMappers fieldMapperAnnotations = (ca.oson.json.annotation.FieldMappers) annotation; for (ca.oson.json.annotation.FieldMapper ann : fieldMapperAnnotations.value()) { if (ann.serialize() == BOOLEAN.BOTH || ann.serialize() == BOOLEAN.FALSE) { fieldMapperAnnotation = ann; // break; } } } else { // to improve performance, using swith on string switch (annotation.annotationType().getName()) { case "com.fasterxml.jackson.annotation.JsonAnySetter": case "org.codehaus.jackson.annotate.JsonAnySetter": fieldMapper.jsonAnySetter = true; break; case "javax.persistence.Transient": fieldMapper.ignore = true; break; case "com.fasterxml.jackson.annotation.JsonIgnore": case "org.codehaus.jackson.annotate.JsonIgnore": fieldMapper.ignore = true; break; case "com.fasterxml.jackson.annotation.JsonIgnoreProperties": JsonIgnoreProperties jsonIgnoreProperties = (JsonIgnoreProperties) annotation; if (!jsonIgnoreProperties.allowSetters()) { fieldMapper.ignore = true; } else { fieldMapper.ignore = false; classMapper.jsonIgnoreProperties.remove(name); } break; case "com.google.gson.annotations.Expose": Expose expose = (Expose) annotation; if (!expose.deserialize()) { fieldMapper.ignore = true; } break; case "com.google.gson.annotations.Since": Since since = (Since) annotation; fieldMapper.since = since.value(); break; case "com.google.gson.annotations.Until": Until until = (Until) annotation; fieldMapper.until = until.value(); break; case "com.fasterxml.jackson.annotation.JsonInclude": if (fieldMapper.defaultType == JSON_INCLUDE.NONE) { JsonInclude jsonInclude = (JsonInclude) annotation; switch (jsonInclude.content()) { case ALWAYS: fieldMapper.defaultType = JSON_INCLUDE.ALWAYS; break; case NON_NULL: fieldMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_ABSENT: fieldMapper.defaultType = JSON_INCLUDE.NON_NULL; break; case NON_EMPTY: fieldMapper.defaultType = JSON_INCLUDE.NON_EMPTY; break; case NON_DEFAULT: fieldMapper.defaultType = JSON_INCLUDE.NON_DEFAULT; break; case USE_DEFAULTS: fieldMapper.defaultType = JSON_INCLUDE.DEFAULT; break; } } break; case "com.fasterxml.jackson.annotation.JsonRawValue": if (((JsonRawValue) annotation).value()) { fieldMapper.jsonRawValue = true; } break; case "org.codehaus.jackson.annotate.JsonRawValue": if (((org.codehaus.jackson.annotate.JsonRawValue) annotation).value()) { fieldMapper.jsonRawValue = true; } break; case "org.junit.Ignore": fieldMapper.ignore = true; break; case "javax.persistence.Enumerated": fieldMapper.enumType = ((Enumerated) annotation).value(); break; case "javax.validation.constraints.NotNull": fieldMapper.required = true; break; case "com.fasterxml.jackson.annotation.JsonProperty": JsonProperty jsonProperty = (JsonProperty) annotation; Access access = jsonProperty.access(); if (access == Access.READ_ONLY) { fieldMapper.ignore = true; } if (jsonProperty.required()) { fieldMapper.required = true; } if (fieldMapper.defaultValue == null) { fieldMapper.defaultValue = jsonProperty.defaultValue(); } break; case "javax.validation.constraints.Size": Size size = (Size) annotation; if (size.min() > 0) { fieldMapper.min = (long) size.min(); } if (size.max() < Integer.MAX_VALUE) { fieldMapper.max = (long) size.max(); } break; case "javax.persistence.Column": Column column = (Column) annotation; if (column.length() != 255) { fieldMapper.length = column.length(); } if (column.scale() > 0) { fieldMapper.scale = column.scale(); } if (column.precision() > 0) { fieldMapper.precision = column.precision(); } if (!column.nullable()) { fieldMapper.required = true; } break; } String fname = ObjectUtil.getName(annotation); if (fname != null) { names.add(fname); } } } // 10. Apply annotations from Oson if (fieldMapperAnnotation != null) { fieldMapper = overwriteBy(fieldMapper, fieldMapperAnnotation, classMapper); } } if (ignored) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } // 11. Apply Java configuration for this particular field if (javaFieldMapper != null && javaFieldMapper.isDeserializing()) { fieldMapper = overwriteBy(fieldMapper, javaFieldMapper); } if (fieldMapper.ignore != null && fieldMapper.ignore) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } // in the ignored list if (ObjectUtil.inSet(name, classMapper.jsonIgnoreProperties)) { nameKeys.remove(name); continue; } if (fieldMapper.useAttribute != null && !fieldMapper.useAttribute) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } if (fieldMapper.jsonAnySetter != null && fieldMapper.jsonAnySetter && setter != null) { setters.remove(lcfieldName); otherMethods.put(lcfieldName, setter); continue; } if (fieldMapper.since != null && fieldMapper.since > getVersion()) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } else if (fieldMapper.until != null && fieldMapper.until <= getVersion()) { nameKeys.remove(name); nameKeys.remove(fieldMapper.json); continue; } // get value for name in map Object value = null; boolean jnameFixed = false; String json = fieldMapper.json; if (json == null) { continue; } else if (!json.equals(name)) { name = json; value = getMapValue(map, name, nameKeys); jnameFixed = true; } if (!jnameFixed) { for (String jsoname : names) { if (!name.equals(jsoname) && !StringUtil.isEmpty(jsoname)) { name = jsoname; value = getMapValue(map, name, nameKeys); jnameFixed = true; break; } } } if (!jnameFixed) { value = getMapValue(map, name, nameKeys); jnameFixed = true; } fieldMapper.java = fieldName; fieldMapper.json = name; if (value != null) { FieldData fieldData = new FieldData(obj, null, value, returnType, true, fieldMapper, objectDTO.level, objectDTO.set); fieldData.setter = setter; Class fieldType = guessComponentType(fieldData); value = json2Object(fieldData); if (StringUtil.isNull(value)) { if (classMapper.defaultType == JSON_INCLUDE.NON_NULL || classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } else if (StringUtil.isEmpty(value)) { if (classMapper.defaultType == JSON_INCLUDE.NON_EMPTY || classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } else if (DefaultValue.isDefault(value, returnType)) { if (classMapper.defaultType == JSON_INCLUDE.NON_DEFAULT) { continue; } } ObjectUtil.setMethodValue(obj, setter, value); nameKeys.remove(name); } } if (annotationSupport) { //@JsonAnySetter if (nameKeys.size() > 0) { for (Entry<String, Method> entry : otherMethods.entrySet()) { Method method = entry.getValue(); if (ignoreModifiers(method.getModifiers(), classMapper.includeFieldsWithModifiers)) { continue; } if (method.isAnnotationPresent(JsonAnySetter.class)) { if (ignoreField(JsonAnySetter.class, classMapper.ignoreFieldsWithAnnotations)) { continue; } jsonAnySetterMethod = method; } else if (method.isAnnotationPresent(org.codehaus.jackson.annotate.JsonAnySetter.class)) { if (ignoreField(org.codehaus.jackson.annotate.JsonAnySetter.class, classMapper.ignoreFieldsWithAnnotations)) { continue; } jsonAnySetterMethod = method; } else if (method.isAnnotationPresent(ca.oson.json.annotation.FieldMapper.class)) { ca.oson.json.annotation.FieldMapper annotation = (ca.oson.json.annotation.FieldMapper) method .getAnnotation(ca.oson.json.annotation.FieldMapper.class); if (annotation.jsonAnySetter() == BOOLEAN.TRUE) { jsonAnySetterMethod = method; break; } } } } } if (jsonAnySetterMethod != null) { Parameter[] parameters = jsonAnySetterMethod.getParameters(); if (parameters != null && parameters.length == 2) { for (String name : nameKeys) { Object value = map.get(name); // json to java, check if this name is allowed or changed String java = json2Java(name); if (value != null && !StringUtil.isEmpty(java)) { ObjectUtil.setMethodValue(obj, jsonAnySetterMethod, java, value); } } } } return obj; // | InvocationTargetException } catch (IllegalArgumentException e) { e.printStackTrace(); } return null; }