org.springframework.web.bind.annotation.RestController Java Examples

The following examples show how to use org.springframework.web.bind.annotation.RestController. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExceptionHandlerFacadeImpl.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ExceptionResponseType getExceptionResponseType(HandlerMethod handlerMethod) {
  ExceptionResponseType exceptionResponseType;

  Class<?> beanType = handlerMethod.getBeanType();
  if (ApiController.class.isAssignableFrom(beanType)) {
    exceptionResponseType = PROBLEM;
  } else if (handlerMethod.hasMethodAnnotation(ResponseStatus.class)
      || handlerMethod.hasMethodAnnotation(ResponseBody.class)
      || beanType.isAnnotationPresent(ResponseBody.class)
      || beanType.isAnnotationPresent(RestController.class)) {
    exceptionResponseType = ERROR_MESSAGES;
  } else {
    exceptionResponseType = MODEL_AND_VIEW;
  }

  return exceptionResponseType;
}
 
Example #2
Source File: SwaggerConfig.java    From java-tutorial with MIT License 6 votes vote down vote up
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .pathMapping("/")
            .select()
            .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
            .paths(PathSelectors.any())
            .build().apiInfo(new ApiInfoBuilder()
                    .title("OAuth2.0 API ")
                    .description("api docs")
                    .version("1.0")
                    .contact(new Contact("jarvis", "github.com", "[email protected]"))
                    .license("The Apache License")
                    .licenseUrl("https://www.github.com")
                    .build());
}
 
Example #3
Source File: SmartSwaggerDynamicGroupConfig.java    From smart-admin with MIT License 6 votes vote down vote up
private Predicate<RequestHandler> getControllerPredicate() {
    groupName = groupList.get(groupIndex);
    List<String> apiTags = groupMap.get(groupName);
    Predicate<RequestHandler> methodPredicate = (input) -> {
        Api api = null;
        Optional<Api> apiOptional = input.findControllerAnnotation(Api.class);
        if (apiOptional.isPresent()) {
            api = apiOptional.get();
        }
        List<String> tags = Arrays.asList(api.tags());
        if (api != null && apiTags.containsAll(tags)) {
            return true;
        }
        return false;
    };
    groupIndex++;
    return Predicates.and(RequestHandlerSelectors.withClassAnnotation(RestController.class), methodPredicate);
}
 
Example #4
Source File: ContextInterceptor.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler) {
    setRequestContext(request);
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    //判断当前请求是否为接口
    boolean hasResponseBody = method.isAnnotationPresent(ResponseBody.class);
    boolean hasRestController = handlerMethod.getBeanType().isAnnotationPresent(RestController.class);
    RequestContext requestContext = WebContextFacade.getRequestContext();
    requestContext.setApiRequest(hasResponseBody || hasRestController);
    WebContextFacade.setRequestContext(requestContext);
    return true;
}
 
Example #5
Source File: SwaggerConfig.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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
            );
}
 
Example #6
Source File: WebAopLog.java    From Jpom with MIT License 6 votes vote down vote up
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
    if (aopLogInterface != null) {
        aopLogInterface.before(joinPoint);
    }
    // 接收到请求,记录请求内容
    IS_LOG.set(ExtConfigBean.getInstance().isConsoleLogReqResponse());
    Signature signature = joinPoint.getSignature();
    if (signature instanceof MethodSignature) {
        MethodSignature methodSignature = (MethodSignature) signature;
        ResponseBody responseBody = methodSignature.getMethod().getAnnotation(ResponseBody.class);
        if (responseBody == null) {
            RestController restController = joinPoint.getTarget().getClass().getAnnotation(RestController.class);
            if (restController == null) {
                IS_LOG.set(false);
            }
        }
    }
}
 
Example #7
Source File: LogConfiguration.java    From seed with Apache License 2.0 6 votes vote down vote up
@Override
public Pointcut getPointcut() {
    return new StaticMethodMatcherPointcut(){
        @Override
        public boolean matches(Method method, Class<?> targetClass) {
            //若类上面注解了DisableLog,则不打印日志(仅此类,不包括该类中被调用的类)
            if(targetClass.isAnnotationPresent(DisableLog.class)){
                return false;
            }
            //若方法上面注解了DisableLog,则不打印日志
            if(method.isAnnotationPresent(DisableLog.class)){
                return false;
            }
            //若类上面注解了EnableLog,则打印日志
            if(targetClass.isAnnotationPresent(EnableLog.class)){
                return true;
            }
            //若方法上面注解了EnableLog,则打印日志
            if(method.isAnnotationPresent(EnableLog.class)){
                return true;
            }
            //默认的:打印标注了RestController的类、以及ResponseBody的方法,的日志
            return targetClass.isAnnotationPresent(RestController.class) || method.isAnnotationPresent(ResponseBody.class);
        }
    };
}
 
Example #8
Source File: WebUtil.java    From api-document with GNU General Public License v3.0 5 votes vote down vote up
private static boolean wasJsonApi(HandlerMethod handlerMethod) {
    // @ResponseBody can be annotation on method and class
    if (Tools.isNotBlank(getAnnotation(handlerMethod, ResponseBody.class))) {
        return true;
    } else {
        // @RestController just annotation on class
        return Tools.isNotBlank(getAnnotationByClass(handlerMethod, RestController.class));
    }
}
 
Example #9
Source File: SwaggerConfig.java    From hmily with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example #10
Source File: SwaggerConfig.java    From fileServer with Apache License 2.0 5 votes vote down vote up
@Bean
public Docket createRestApi() {
    Predicate<RequestHandler> predicate = new Predicate<RequestHandler>() {
        @Override
        public boolean apply(RequestHandler input) {
            Class<?> declaringClass = input.declaringClass();

            boolean isController = declaringClass.isAnnotationPresent(Controller.class);
            boolean isRestController = declaringClass.isAnnotationPresent(RestController.class);

            String className = declaringClass.getName();

            String pattern = "com\\.codingapi\\.file\\.local\\.server\\.controller\\..*Controller";
            boolean has =  Pattern.matches(pattern, className);
            if(has){
                if(isController){
                    if(input.isAnnotatedWith(ResponseBody.class)){
                        return true;
                    }
                }
                if(isRestController){
                    return true;
                }
                return false;
            }

            return false;
        }
    };
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .useDefaultResponseMessages(false)
            .select()
            .apis(predicate)
            .build();
}
 
Example #11
Source File: SpringMavenDocumentSource.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected Set<Class<?>> getValidClasses() {
    Set<Class<?>> result = super.getValidClasses();
    result.addAll(apiSource.getValidClasses(RestController.class));
    result.addAll(apiSource.getValidClasses(ControllerAdvice.class));
    return result;
}
 
Example #12
Source File: SystemExceptionHandler.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@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;
    }
}
 
Example #13
Source File: SwaggerConfig.java    From metron with Apache License 2.0 5 votes vote down vote up
@Bean
public Docket api() {
  List<String> activeProfiles = Arrays.asList(environment.getActiveProfiles());
  Docket docket = new Docket(DocumentationType.SWAGGER_2);
  if (activeProfiles.contains(KNOX_PROFILE)) {
    String knoxRoot = environment.getProperty(MetronRestConstants.KNOX_ROOT_SPRING_PROPERTY, String.class, "");
    docket = docket.pathProvider(new RelativePathProvider (servletContext) {
      @Override
      protected String applicationPath() {
        return knoxRoot;
      }

      @Override
      protected String getDocumentationPath() {
        return knoxRoot;
      }

      @Override
      public String getApplicationBasePath() {
        return knoxRoot;
      }

      @Override
      public String getOperationPath(String operationPath) {
        return knoxRoot + super.getOperationPath(operationPath);
      }
    });
  }
  return docket.select()
          .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
          .paths(PathSelectors.any())
          .build();
}
 
Example #14
Source File: ScopeAndAccessTokenSignatureTest.java    From kaif with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #15
Source File: JavaMelodyAutoConfiguration.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/**
 * 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 createMonitoringSpringAdvisorWithExclusions(
			new AnnotationMatchingPointcut(RestController.class),
			monitoredWithSpringAnnotationPointcut, asyncAnnotationPointcut,
			scheduledAnnotationPointcut);
}
 
Example #16
Source File: SwaggerUIConfig.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@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("http","https"))
            .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);

}
 
Example #17
Source File: AopAuthorizingController.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #18
Source File: AOPUtil.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 判断该类是否为Controller
 * @author Frodez
 * @date 2020-01-01
 */
public static boolean isController(Class<?> klass) {
	if (AnnotationUtils.findAnnotation(klass, Controller.class) != null) {
		return true;
	}
	if (AnnotationUtils.findAnnotation(klass, RestController.class) != null) {
		return true;
	}
	return false;
}
 
Example #19
Source File: SwaggerConfig.java    From myth with Apache License 2.0 5 votes vote down vote up
/**
 * Api docket.
 *
 * @return the docket
 */
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
            .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()));
}
 
Example #20
Source File: SwaggerConfiguration.java    From Spring-5.0-By-Example with MIT License 5 votes vote down vote up
@Bean
public Docket documentation() {
  return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
      .paths(PathSelectors.any())
      .build();
}
 
Example #21
Source File: SwaggerConfiguration.java    From Spring-5.0-By-Example with MIT License 5 votes vote down vote up
@Bean
public Docket documentation() {
  return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
      .paths(PathSelectors.any())
      .build();
}
 
Example #22
Source File: SwaggerConfiguration.java    From Spring-5.0-By-Example with MIT License 5 votes vote down vote up
@Bean
public Docket documentation() {
  return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
      .paths(PathSelectors.any())
      .build();
}
 
Example #23
Source File: SwaggerConfig.java    From myth with Apache License 2.0 5 votes vote down vote up
/**
 * Api docket.
 *
 * @return the docket
 */
@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()));
}
 
Example #24
Source File: SwaggerConfig.java    From hmily with Apache License 2.0 5 votes vote down vote up
/**
 * Api docket.
 *
 * @return the docket
 */
@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()));
}
 
Example #25
Source File: RestControllerClassAnnotationProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(SwaggerGenerator swaggerGenerator, RestController restController) {
  Swagger swagger = swaggerGenerator.getSwagger();
  if (StringUtils.isEmpty(swagger.getBasePath())) {
    swagger.setBasePath("/");
  }
}
 
Example #26
Source File: SwaggerConfig.java    From Raincat with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
            .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()));
}
 
Example #27
Source File: SwaggerConfig.java    From Raincat with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Api docket.
 *
 * @return the docket
 */
@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()));
}
 
Example #28
Source File: SwaggerConfig.java    From Raincat with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Api docket.
 *
 * @return the docket
 */
@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()));
}
 
Example #29
Source File: WebUtils.java    From xmanager with Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否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;
}
 
Example #30
Source File: SpringmvcAnnotationParser.java    From servicecomb-toolkit with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canProcess(Class<?> cls) {
  if (cls.getAnnotation(RestController.class) != null) {
    return true;
  }
  return false;
}