/** * 判断请求是否是异步请求 * @param request * @param handler * @return */ public static boolean isAsyncRequest(HttpServletRequest request, Object handler){ boolean isAsync = false; if(handler instanceof HandlerMethod){ HandlerMethod handlerMethod = (HandlerMethod) handler; isAsync = handlerMethod.hasMethodAnnotation(ResponseBody.class); if(!isAsync){ Class<?> controllerClass = handlerMethod.getBeanType(); isAsync = controllerClass.isAnnotationPresent(ResponseBody.class) || controllerClass.isAnnotationPresent(RestController.class); } if(!isAsync){ isAsync = ResponseEntity.class.equals(handlerMethod.getMethod().getReturnType()); } } if(!isAsync){ isAsync = HttpUtils.isAsynRequest(request); } return isAsync; }
@Bean public Docket petApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(withClassAnnotation(RestController.class)) .build() .pathMapping("/") .enableUrlTemplating(true) .apiInfo(apiInfo()) .ignoredParameterTypes( HttpServletRequest.class, HttpServletResponse.class, HttpSession.class, Pageable.class, Errors.class ); }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Set<? extends Element> elementsAnnotatedWithRestController = roundEnv.getElementsAnnotatedWith(RestController.class); for (Element restControllerAnnotatedElement: elementsAnnotatedWithRestController) { if (restControllerAnnotatedElement.getKind() != ElementKind.CLASS) { error(restControllerAnnotatedElement, "@%s can be applied only to class", RestController.class.getSimpleName()); return true; } if (Objects.isNull(restControllerAnnotatedElement.getAnnotation(RequestMapping.class))) { warn(restControllerAnnotatedElement, "%s without @RequestMapping will not produce any @Test methods.", restControllerAnnotatedElement.getSimpleName().toString()); } // @RequestMapping 붙은 클래스 TypeElement restControllerTypeElement = (TypeElement) restControllerAnnotatedElement; // 분석용 래퍼 클래스 RestControllerModel restControllerModel = new RestControllerModel(restControllerTypeElement); generateStubFileFor(restControllerModel); } return false; }
private Annotation getSpringClassAnnotation(Class clazz) { Annotation classAnnotation = AnnotationUtils.findAnnotation(clazz, Component.class); if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Controller.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, RestController.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Service.class); } if (classAnnotation == null) { classAnnotation = AnnotationUtils.findAnnotation(clazz, Repository.class); } return classAnnotation; }
@Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) // .paths(paths()) .build().pathMapping("/").directModelSubstitute(LocalDate.class, String.class) .genericModelSubstitutes(ResponseEntity.class).useDefaultResponseMessages(false) .globalResponseMessage(RequestMethod.GET, newArrayList(new ResponseMessageBuilder().code(500).message("500 message") .responseModel(new ModelRef("Error")).build())); }
@Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .groupName("api") .select() .apis(withClassAnnotation(RestController.class)) .paths(PathSelectors.regex("/api/.+")) .build() .apiInfo(apiInfo()); }
@Bean public Docket internal() { return new Docket(DocumentationType.SWAGGER_2) .groupName("internal") .select() .apis(withClassAnnotation(RestController.class)) .paths(PathSelectors.regex("/internal/.+")) .build() .apiInfo(apiInfo()); }
private void init(ApplicationContext context) { init(); LOGGER.debug("Get All ExceptionHandlers"); List<Object> exceptionsHandlers = ReflectionUtils .proxyToObject(context.getBeansWithAnnotation(ControllerAdvice.class).values()); LOGGER.debug("Get All RestController"); exceptionsHandlers.forEach(this::buildHttpCodes); controllers .addAll(ReflectionUtils.proxyToObject(context.getBeansWithAnnotation(RestController.class).values())); LOGGER.debug("Get All Controller"); controllers.addAll(ReflectionUtils.proxyToObject(context.getBeansWithAnnotation(Controller.class).values())); }
/** * 判断是否ajax请求 * spring ajax 返回含有 ResponseBody 或者 RestController注解 * @param handlerMethod HandlerMethod * @return 是否ajax请求 */ public static boolean isAjax(HandlerMethod handlerMethod) { ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class); if (null != responseBody) { return true; } RestController restAnnotation = handlerMethod.getBeanType().getAnnotation(RestController.class); if (null != restAnnotation) { return true; } return false; }
/** * 判断整个类里的所有接口是否都返回json * * @param classz * @return */ protected boolean isJson(Class<?> classz) { Controller controllerAnno = classz.getAnnotation(Controller.class); RestController restControllerAnno = classz.getAnnotation(RestController.class); ResponseBody responseBody = classz.getAnnotation(ResponseBody.class); if (responseBody != null) { return true; } else if (controllerAnno != null) { return false; } else if (restControllerAnno != null) { return true; } return false; }
@Override public boolean filter(Class<?> classz) { if (classz.getAnnotation(RequestMapping.class) != null || classz.getAnnotation(Controller.class) != null || classz.getAnnotation(RestController.class) != null) { return true; } return false; }
@Override public boolean matches(Method method, Class<?> aClass) { boolean support = AopUtils.findAnnotation(aClass, Controller.class) != null || AopUtils.findAnnotation(aClass, RestController.class) != null || AopUtils.findAnnotation(aClass, method, Authorize.class) != null; if (support && autoParse) { defaultParser.parse(aClass, method); } return support; }
@Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .groupName("default") .select() .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) .paths(PathSelectors.any()) .build() .protocols(Sets.newHashSet(getSwaggerConfig().getString(SWAGGER_PROTOCOL))) .apiInfo(apiInfo()) .securitySchemes(newArrayList(securitySchema())) .securityContexts(newArrayList(securityContext())) // .operationOrdering(getOperationOrdering()) try with swagger 2.7.0 .tags( new Tag("alert triggers", "Operations to manage alert triggers"), new Tag("applications", "Operations to list organization applications"), new Tag("application document store", "Operations to manage generic documents storage"), new Tag("device configs", "Operations to manage device configurations"), new Tag("device credentials", "Operations to manage device credentials (username, password and URLs)"), new Tag("device firmwares", "Operations to manage device firmwares"), new Tag("device models", "Operations to manage device models"), new Tag("device status", "Operations to verify the device status"), new Tag("devices", "Operations to manage devices"), new Tag("devices custom data", "Operations to manage devices custom data"), new Tag("events", "Operations to query incoming and outgoing device events"), new Tag("gateways", "Operations to manage gateways"), new Tag("locations", "Operations to manage locations"), new Tag("rest destinations", "Operations to list organization REST destinations"), new Tag("rest transformations", "Operations to manage REST transformations"), new Tag("routes", "Operations to manage routes"), new Tag("users", "Operations to manage organization users"), new Tag("user subscription", "Operations to subscribe new users") ) .enableUrlTemplating(false); }
@Override public Set<String> getSupportedAnnotationTypes() { Set<String> annotataions = new LinkedHashSet<String>(); annotataions.add(org.springframework.web.bind.annotation.RestController.class.getCanonicalName()); return annotataions; }
@Override public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException { Map<RequestMethod, Integer> methodsCount = new HashMap<RequestMethod, Integer>(); String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { Class<?> type = beanFactory.getType(beanDefinitionName); RestController annotation = type.getAnnotation(RestController.class); if (annotation != null) { Method[] methods = type.getMethods(); processControllerMethods(methods, methodsCount); } } Integer allMethodCount = 0; for (Entry<RequestMethod, Integer> methodCount : methodsCount.entrySet()) { LOGGER.info("Http Method - {} : {}", methodCount.getKey(), methodCount.getValue()); allMethodCount += methodCount.getValue(); } LOGGER.info("All methods count: {}", allMethodCount); beanFactory.registerSingleton("httpMethodsCount", allMethodCount); beanFactory.registerSingleton("httpMethods", methodsCount); }
@Override public JAnnotationUse apply(ApiResourceMetadata controllerMetadata, JDefinedClass generatableType) { Class<? extends Annotation> annotationType; switch (springVersion) { case 3 : annotationType = Controller.class; break; case 4 : annotationType = RestController.class; break; default: throw new IllegalStateException("Spring Version not set"); } return generatableType.annotate(annotationType); }
@Test public void scanAll() throws Exception { List<Method> allMethods = ClassScanner.searchAnnotatedClasses("io.kaif.web.v1", RestController.class) .stream() .flatMap(cls -> Stream.of(cls.getDeclaredMethods())) .filter(method -> Modifier.isPublic(method.getModifiers())) .filter(method -> method.getAnnotation(RequestMapping.class) != null) .collect(toList()); logger.debug("total methods count: " + allMethods.size()); assertFalse("no method detected, may be scanner bug?", allMethods.isEmpty()); List<Method> badMethods = allMethods.stream() .filter((method) -> !isCorrectAnnotated(method)) .collect(toList()); if (!badMethods.isEmpty()) { logger.error("method should annotated @" + RequiredScope.class.getSimpleName() + " and one parameter is " + ClientAppUserAccessToken.class.getSimpleName()); logger.error("=============="); badMethods.forEach(method -> logger.error(method.toString())); logger.error("=============="); } String message = "some method missing ClientAppUserAccessToken argument or annotated @RequiredScope: \n" + badMethods.stream() .map(method -> method.getDeclaringClass().getSimpleName() + "." + method.getName()) .collect(joining("\n")) + "\n"; assertTrue(message, badMethods.isEmpty()); }
@Override protected com.speedment.common.codegen.model.Class makeCodeGenModel(File file) { return newBuilder(file, getClassOrInterfaceName()) .forEveryTable((clazz, table) -> { clazz.public_(); clazz.add(AnnotationUsage.of(RestController.class)); clazz.setSupertype(SimpleType.create( getSupport().basePackageName() + ".generated.Generated" + getSupport().typeName() + "Controller" )); }).build(); }
/** * {@inheritDoc} */ @Override public boolean supported(Object handler, Exception ex) { RestController rest = ((HandlerMethod) handler).getBean().getClass().getAnnotation(RestController.class); if (rest == null) { return true; } else { return false; } }
@Override protected Set<Class<?>> getValidClasses() { Set result = super.getValidClasses(); result.addAll(apiSource.getValidClasses(RestController.class)); result.addAll(apiSource.getValidClasses(ControllerAdvice.class)); return result; }
@Override public JavaClassSource decorateSource(UIExecutionContext context, Project project, JavaClassSource source) throws Exception { // Check that we have the spring-boot-starter-web dependency and add it if we don't SpringBootHelper.addSpringBootDependency(project, SpringBootFacet.SPRING_BOOT_STARTER_WEB_ARTIFACT); // Create Java Classes Greeting and GreetingProperties JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class); facet.saveJavaSource(createGreetingClass(source)); facet.saveJavaSource(createGreetingPropertiesClass(source)); final Properties properties = new Properties(); if (wrapped.getPath().hasValue()) { final String value = wrapped.getPath().getValue(); properties.put("server.contextPath", (value.startsWith("/") ? value : "/" + value)); } properties.put("greeting.message", "Hello, %s!"); SpringBootHelper.writeToApplicationProperties(project, properties); // Create the Controller source.addImport(AtomicLong.class); source.addAnnotation(RestController.class); source.addField().setPrivate().setFinal(false).setType("GreetingProperties").setName("properties").addAnnotation(Autowired.class); source.addField().setPrivate().setFinal(true).setType("AtomicLong").setName("counter").setLiteralInitializer("new AtomicLong()"); for (RestMethod restMethod : wrapped.getMethods().getValue()) { MethodSource<?> greeting = source.addMethod() .setPublic() .setName(restMethod.getMethodName()) .setReturnType("Greeting"); switch (restMethod) { case GET: greeting.addAnnotation(RequestMapping.class).setStringValue("/greeting"); greeting.addParameter(String.class, "name").addAnnotation(RequestParam.class).setLiteralValue("value", "\"name\"").setLiteralValue("defaultValue", "\"world\""); greeting.setBody("return new Greeting(this.counter.incrementAndGet(), String.format(this.properties.getMessage(), name));"); break; case POST: source.addImport(UriBuilder.class); // TODO break; case PUT: // TODO break; case DELETE: // TODO break; } } return source; }
private ServiceRequestProps createProps(AnnotationTarget<?> type) { Multimap<String, String> map = AnnotationUtils.getAnnotationAsMap(type, RequestMapping.class); ServiceRequestProps props = new ServiceRequestProps(map); props.setResponseBody(AnnotationUtils.hasAny(type, ResponseBody.class, RestController.class)); return props; }
@Override public List visitClass(final ClassTree node, final Void p) { final List<MappedElement> mappedElements = new ArrayList<>(); if (canceled || node == null) { return mappedElements; } final Element clazz = trees.getElement(new TreePath(rootPath, node)); if (clazz == null || (clazz.getAnnotation(Controller.class) == null && clazz.getAnnotation(RestController.class) == null)) { return mappedElements; } final RequestMapping parentRequestMapping = clazz.getAnnotation(RequestMapping.class); final Map<String, List<RequestMethod>> parentUrls = extractTypeLevelMappings(parentRequestMapping); for (Element enclosedElement : clazz.getEnclosedElements()) { if (enclosedElement.getKind() != ElementKind.METHOD) { continue; } final Map<String, List<RequestMethod>> elementUrls = new TreeMap<>(); final RequestMapping requestMapping = enclosedElement.getAnnotation(RequestMapping.class); if (requestMapping != null) { extractMethodLevelMappings(elementUrls, concatValues(requestMapping.value(), requestMapping.path()), requestMapping.method()); } final DeleteMapping deleteMapping = enclosedElement.getAnnotation(DeleteMapping.class); if (deleteMapping != null) { extractMethodLevelMappings(elementUrls, concatValues(deleteMapping.value(), deleteMapping.path()), new RequestMethod[]{RequestMethod.DELETE}); } final GetMapping getMapping = enclosedElement.getAnnotation(GetMapping.class); if (getMapping != null) { extractMethodLevelMappings(elementUrls, concatValues(getMapping.value(), getMapping.path()), new RequestMethod[]{RequestMethod.GET}); } final PatchMapping patchMapping = enclosedElement.getAnnotation(PatchMapping.class); if (patchMapping != null) { extractMethodLevelMappings(elementUrls, concatValues(patchMapping.value(), patchMapping.path()), new RequestMethod[]{RequestMethod.PATCH}); } final PostMapping postMapping = enclosedElement.getAnnotation(PostMapping.class); if (postMapping != null) { extractMethodLevelMappings(elementUrls, concatValues(postMapping.value(), postMapping.path()), new RequestMethod[]{RequestMethod.POST}); } final PutMapping putMapping = enclosedElement.getAnnotation(PutMapping.class); if (putMapping != null) { extractMethodLevelMappings(elementUrls, concatValues(putMapping.value(), putMapping.path()), new RequestMethod[]{RequestMethod.PUT}); } for (Map.Entry<String, List<RequestMethod>> methodLevelMapping : elementUrls.entrySet()) { for (Map.Entry<String, List<RequestMethod>> typeLevelMapping : parentUrls.entrySet()) { final String url = pathMatcher.combine(typeLevelMapping.getKey(), methodLevelMapping.getKey()); final List<RequestMethod> effectiveMethods = new ArrayList<>(); if (methodLevelMapping.getValue().isEmpty()) { effectiveMethods.add(null); } effectiveMethods.addAll(methodLevelMapping.getValue()); if (!typeLevelMapping.getValue().isEmpty()) { effectiveMethods.retainAll(typeLevelMapping.getValue()); } for (RequestMethod effectiveMethod : effectiveMethods) { mappedElements.add(new MappedElement(this.fileObject, enclosedElement, url, effectiveMethod)); } } } } return mappedElements; }
@Bean public MonitoringSpringAdvisor springRestControllerMonitoringAdvisor() { final MonitoringSpringAdvisor interceptor = new MonitoringSpringAdvisor(); interceptor.setPointcut(new AnnotationMatchingPointcut(RestController.class)); return interceptor; }
/** * Processes a Spring MVC REST controller class that is annotated with RestController. Also collects any required model objects based on parameters and * return types of each endpoint into the specified model classes set. * * @param clazz the class to process * * @throws MojoExecutionException if any errors were encountered. */ private void processRestControllerClass(Class<?> clazz) throws MojoExecutionException { // Get the Java class source information. JavaClassSource javaClassSource = sourceMap.get(clazz.getSimpleName()); if (javaClassSource == null) { throw new MojoExecutionException("No source resource found for class \"" + clazz.getName() + "\"."); } Api api = clazz.getAnnotation(Api.class); boolean hidden = api != null && api.hidden(); if ((clazz.getAnnotation(RestController.class) != null) && (!hidden)) { log.debug("Processing RestController class \"" + clazz.getName() + "\"."); // Default the tag name to the simple class name. String tagName = clazz.getSimpleName(); // See if the "Api" annotation exists. if (api != null && api.tags().length > 0) { // The "Api" annotation was found so use it's configured tag. tagName = api.tags()[0]; } else { // No "Api" annotation so try to get the tag name from the class name. If not, we will stick with the default simple class name. Matcher matcher = tagPattern.matcher(clazz.getSimpleName()); if (matcher.find()) { // If our class has the form tagName = matcher.group("tag"); } } log.debug("Using tag name \"" + tagName + "\"."); // Add the tag and process each method. swagger.addTag(new Tag().name(tagName)); for (Method method : clazz.getDeclaredMethods()) { // Get the method source information. List<Class<?>> methodParamClasses = new ArrayList<>(); for (Parameter parameter : method.getParameters()) { methodParamClasses.add(parameter.getType()); } MethodSource<JavaClassSource> methodSource = javaClassSource.getMethod(method.getName(), methodParamClasses.toArray(new Class<?>[methodParamClasses.size()])); if (methodSource == null) { throw new MojoExecutionException( "No method source found for class \"" + clazz.getName() + "\" and method name \"" + method.getName() + "\"."); } // Process the REST controller method along with its source information. processRestControllerMethod(method, clazz.getAnnotation(RequestMapping.class), tagName, methodSource); } } else { log.debug("Skipping class \"" + clazz.getName() + "\" because it is either not a RestController or it is hidden."); } }
/** * Monitoring of beans having the {@link RestController} annotation. * @return MonitoringSpringAdvisor */ @Bean @ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "spring-monitoring-enabled", matchIfMissing = true) public MonitoringSpringAdvisor monitoringSpringRestControllerAdvisor() { return new MonitoringSpringAdvisor(new AnnotationMatchingPointcut(RestController.class)); }
@SuppressWarnings("unchecked") @Override protected Class<? extends Annotation>[] getSupportedClassAnnotations() { return new Class[] { Controller.class, RestController.class, RequestMapping.class }; }
@SuppressWarnings("unchecked") @Override protected Class<? extends Annotation>[] getSupportedClassAnnotations() { return new Class[] { Controller.class, RestController.class }; }
@Override protected Map<RamlActionType, String> getHttpMethodAndName(Class<?> clazz, Method method) { RequestMapping methodMapping = getRequestMapping(method); RequestMapping classMapping = getAnnotation(clazz, RequestMapping.class, false); RestController classRestController = getAnnotation(clazz, RestController.class, false); Controller classController = getAnnotation(method.getDeclaringClass(), Controller.class, false); RequestMethod[] verbs = methodMapping.method(); if (verbs == null || verbs.length == 0) { verbs = RequestMethod.values(); } String name = ""; if (classMapping != null && classMapping.value() != null && classMapping.value().length > 0) { name += NamingHelper.resolveProperties(classMapping.value()[0]); } if (classRestController != null && classRestController.value() != null) { name += NamingHelper.resolveProperties(classRestController.value()); } if (classController != null && classController.value() != null) { name += NamingHelper.resolveProperties(classController.value()); } if (methodMapping.value() != null && methodMapping.value().length > 0) { if (name.endsWith("/") && methodMapping.value()[0].startsWith("/")) { name = name.substring(0, name.length() - 1); } else if (name != "" && !name.endsWith("/") && !methodMapping.value()[0].startsWith("/")) { name += "/"; } name += NamingHelper.resolveProperties(methodMapping.value()[0]); } Map<RamlActionType, String> outMap = new HashMap<>(); for (RequestMethod rm : verbs) { try { RamlActionType apiAction = RamlActionType.valueOf(rm.name()); outMap.put(apiAction, name); } catch (Exception ex) { // skip verb not supported by RAML logger.warn("Skipping unknown verb " + rm); } } return outMap;// TODO sort value out }
public RestControllerBuilder() { super(RestController.class.getName()); }
private static boolean isHtmlRequest(HandlerMethod handlerMethod) { return !(handlerMethod.hasMethodAnnotation(ResponseBody.class) || handlerMethod.hasMethodAnnotation( ResponseStatus.class) || handlerMethod.getBeanType().isAnnotationPresent(ResponseBody.class) || handlerMethod.getBeanType().isAnnotationPresent(RestController.class)); }