List of usage examples for java.lang Class getDeclaredAnnotation
@Override @SuppressWarnings("unchecked") public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass)
From source file:io.stallion.dataAccess.db.DB.java
private Schema annotatedModelToSchema(Class cls) { Table table = (Table) cls.getDeclaredAnnotation(Table.class); if (table == null) { throw new UsageException("Trying to register model with database, but it has no @Table annotation: " + cls.getCanonicalName()); }//ww w . jav a 2 s . co m if (empty(table.name())) { throw new UsageException( "Trying to register model with database, but it has no name for the @Table annotation: " + cls.getCanonicalName()); } Schema schema = new Schema(table.name(), cls); Object inst = null; try { inst = cls.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } ExtraKeyDefinitions keyDefinitions = (ExtraKeyDefinitions) cls .getDeclaredAnnotation(ExtraKeyDefinitions.class); if (keyDefinitions != null) { for (String def : keyDefinitions.value()) { schema.getExtraKeyDefinitions().add(def); } } for (Method method : cls.getMethods()) { if (!method.getName().startsWith("get") && !method.getName().startsWith("is")) { continue; } // If a property starts with "is", the type must be boolean, or else we continue; if (method.getName().startsWith("is") && (!method.getReturnType().isAssignableFrom(boolean.class)) && !method.getReturnType().isAssignableFrom(Boolean.class)) { continue; } String propertyName = ""; if (method.getName().startsWith("is")) { propertyName = method.getName().substring(2); } else { propertyName = method.getName().substring(3); } if (empty(propertyName)) { continue; } propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); Column columnAnno = method.getAnnotation(Column.class); if (columnAnno == null) { continue; } String columnName = propertyName.toLowerCase(); if (!StringUtils.isBlank(columnAnno.name())) { columnName = columnAnno.name(); } Col col = new Col(); col.setPropertyName(propertyName); col.setName(columnName); col.setUpdateable(columnAnno.updatable()); col.setjType(method.getReturnType()); col.setInsertable(columnAnno.insertable()); col.setDbType(columnAnno.columnDefinition()); col.setNullable(columnAnno.nullable()); col.setLength(columnAnno.length()); // If the column cannot be null, we need a default value if (!columnAnno.nullable()) { col.setDefaultValue(PropertyUtils.getProperty(inst, propertyName)); } VirtualColumn virtualAnno = method.getAnnotation(VirtualColumn.class); if (virtualAnno != null) { col.setVirtual(true); col.setInsertable(false); col.setUpdateable(false); } Converter converterAnno = method.getDeclaredAnnotation(Converter.class); Log.finest("Adding schema Column {0}", columnName); if (converterAnno != null) { Log.finest("ConverterAnno {0} {1} {2} ", columnName, converterAnno, converterAnno.name()); if (empty(converterAnno.name())) { try { AttributeConverter converter = (AttributeConverter) converterAnno.cls().newInstance(); if (converter instanceof TypedCollectionAttributeConverter) { if (converterAnno.elementClass() == null || converterAnno.elementClass().equals(Object.class)) { throw new UsageException( "You used a TypedCollectionAttributeConverter but did not set the value for elementClass which controls the type of object that you want to convert to. "); } ((TypedCollectionAttributeConverter) converter) .setElementClass(converterAnno.elementClass()); } col.setAttributeConverter(converter); //col.setConverterClassName(converterAnno.cls().getCanonicalName()); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } else { col.setConverterClassName(converterAnno.name()); } } if (method.getAnnotation(AlternativeKey.class) != null) { col.setAlternativeKey(true); schema.getKeyNames().add(col.getName()); } if (method.getAnnotation(UniqueKey.class) != null) { col.setUniqueKey(true); UniqueKey uk = (UniqueKey) method.getAnnotation(UniqueKey.class); col.setCaseInsensitive(uk.caseInsensitive()); schema.getKeyNames().add(col.getName()); } if (columnAnno.unique()) { col.setUniqueKey(true); schema.getKeyNames().add(col.getName()); } schema.getColumns().add(col); } return schema; }
From source file:org.springframework.core.annotation.AnnotationUtils.java
/** * Perform the search algorithm for {@link #findAnnotation(Class, Class)}, * avoiding endless recursion by tracking which annotations have already * been <em>visited</em>.//from w w w . j a va 2s . com * @param clazz the class to look for annotations on * @param annotationType the type of annotation to look for * @param visited the set of annotations that have already been visited * @return the first matching annotation, or {@code null} if not found */ @Nullable private static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType, Set<Annotation> visited) { try { A annotation = clazz.getDeclaredAnnotation(annotationType); if (annotation != null) { return annotation; } for (Annotation declaredAnn : clazz.getDeclaredAnnotations()) { Class<? extends Annotation> declaredType = declaredAnn.annotationType(); if (!isInJavaLangAnnotationPackage(declaredType) && visited.add(declaredAnn)) { annotation = findAnnotation(declaredType, annotationType, visited); if (annotation != null) { return annotation; } } } } catch (Throwable ex) { handleIntrospectionFailure(clazz, ex); return null; } for (Class<?> ifc : clazz.getInterfaces()) { A annotation = findAnnotation(ifc, annotationType, visited); if (annotation != null) { return annotation; } } Class<?> superclass = clazz.getSuperclass(); if (superclass == null || Object.class == superclass) { return null; } return findAnnotation(superclass, annotationType, visited); }
From source file:org.springframework.core.annotation.AnnotationUtils.java
/** * Determine whether an annotation of the specified {@code annotationType} * is declared locally (i.e., <em>directly present</em>) on the supplied * {@code clazz}.//from www . ja v a2s. c om * <p>The supplied {@link Class} may represent any type. * <p>Meta-annotations will <em>not</em> be searched. * <p>Note: This method does <strong>not</strong> determine if the annotation * is {@linkplain java.lang.annotation.Inherited inherited}. For greater * clarity regarding inherited annotations, consider using * {@link #isAnnotationInherited(Class, Class)} instead. * @param annotationType the annotation type to look for * @param clazz the class to check for the annotation on * @return {@code true} if an annotation of the specified {@code annotationType} * is <em>directly present</em> * @see java.lang.Class#getDeclaredAnnotations() * @see java.lang.Class#getDeclaredAnnotation(Class) * @see #isAnnotationInherited(Class, Class) */ public static boolean isAnnotationDeclaredLocally(Class<? extends Annotation> annotationType, Class<?> clazz) { Assert.notNull(annotationType, "Annotation type must not be null"); Assert.notNull(clazz, "Class must not be null"); try { return (clazz.getDeclaredAnnotation(annotationType) != null); } catch (Throwable ex) { handleIntrospectionFailure(clazz, ex); return false; } }
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);/* w w w .j ava2 s. com*/ 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; }