/** * Actually resolve the given exception that got thrown during on handler execution, returning a * ModelAndView that represents a specific error page if appropriate. * * <p>May be overridden in subclasses, in order to apply specific exception checks. Note that this * template method will be invoked <i>after</i> checking whether this resolved applies * ("mappedHandlers" etc), so an implementation may simply proceed with its actual exception * handling. * * @param request current HTTP request * @param response current HTTP response * @param handler the executed handler, or {@code null} if none chosen at the time of the * exception (for example, if multipart resolution failed) * @param ex the exception that got thrown during handler execution * @return a corresponding ModelAndView to forward to, or {@code null} for default processing */ @Override protected ModelAndView doResolveException( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { // Expose ModelAndView for chosen error view. String viewName = determineViewName(ex, request); if (viewName != null) { // Apply HTTP status code for error views, if specified. // Only apply it if we're processing a top-level request. Integer statusCode = determineStatusCode(request, viewName); { if (handler instanceof HandlerMethod) { HandlerMethod hm = (HandlerMethod) handler; RequestMapping rm = hm.getMethodAnnotation(RequestMapping.class); if (Arrays.binarySearch(rm.produces(), MediaType.APPLICATION_JSON_VALUE) > -1) { setDefaultErrorView("/common/errAjax"); } } } if (statusCode != null) { applyStatusCodeIfPossible(request, response, statusCode); } return getModelAndView(viewName, ex, request); } else { return null; } }
private ApiInfo addApiInfo(HandlerMethod method) throws Exception { String key = getKey(method); ApiInfo apiInfo = new ApiInfo(); if (method.getMethodAnnotation(Api.class) != null) { RequestMapping requestMapping = method.getMethodAnnotation(RequestMapping.class); String pattern = requestMapping.value()[0]; if (pattern.contains(PathVariables.USER_KEY)) { apiInfo.setHasUserKeyInPath(true); pattern = pattern.replace(PathVariables.USER_KEY, WILD_CARD_CHAR); } else { apiInfo.setHasUserKeyInPath(false); } apiInfo.setLevel(method.getMethodAnnotation(Api.class).level()); apiInfo.setRequestMappingPattern(pattern); } else { logger.debug("Invalid api identity!"); throw new UnexpectedErrorException(); } this.apiInfoCache.put(key, apiInfo); logger.debug("ApiInfoMapper.addApiInfo: key=" + key); logger.debug("ApiInfoMapper.addApiInfo: apiInfo=" + apiInfo.toString()); return apiInfo; }
@PostConstruct void init() { rootType = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1]; kendoUiGridService.getSqlRoot().select().target("p").getRoot().from().target(rootType, "p"); RequestMapping rm = AnnotationUtils.findAnnotation(this.getClass(), RequestMapping.class); String[] modulePaths = rm.value(); moduleName = modulePaths[0].substring(1); }
@Override protected RequestMappingInfo createRequestMappingInfo( RequestMapping annotation, RequestCondition<?> customCondition) { String[] patterns = resolveEmbeddedValuesInPatterns(annotation.value()); RequestMethod[] methods = annotation.method(); // BPC的默认方法为POST if (methods == null || methods.length <= 0) { methods = new RequestMethod[] {RequestMethod.POST}; } return new RequestMappingInfo( annotation.name(), new PatternsRequestCondition( patterns, getUrlPathHelper(), getPathMatcher(), this.useSuffixPatternMatch(), this.useTrailingSlashMatch(), this.getFileExtensions()), new RequestMethodsRequestCondition(methods), new ParamsRequestCondition(annotation.params()), new HeadersRequestCondition(annotation.headers()), new ConsumesRequestCondition(annotation.consumes(), annotation.headers()), new ProducesRequestCondition( annotation.produces(), annotation.headers(), this.getContentNegotiationManager()), customCondition); }
private RequestMethod getRequestMethod( ExecutableElement executableElement, TypeElement cls, RequestMapping anno) { if (anno.method().length != 1) { throw new IllegalStateException( String.format( "The RequestMapping annotation for %s.%s is not parseable. Exactly one request method (GET/POST/etc) is required.", cls.getQualifiedName(), executableElement.getSimpleName())); } else { return anno.method()[0]; } }
private HttpMethod getHttpMethod(RequestMapping classMapping, RequestMapping methodMapping) { HttpMethod httpMethod; if (methodMapping != null && isNotEmpty(methodMapping.method())) { httpMethod = getHttpMethod(methodMapping); } else if (classMapping != null && isNotEmpty(classMapping.method())) { httpMethod = getHttpMethod(classMapping); } else { // TODO add warning to the logs throw new SpringRestClientConfigurationException("Can't identify HTTP method!"); } return httpMethod; }
private static String getMethodRequestMapping(Method method) { RequestMapping annot = AnnotationUtils.findAnnotation(method, RequestMapping.class); if (annot == null) { throw new IllegalArgumentException("No @RequestMapping on: " + method.toGenericString()); } if (ObjectUtils.isEmpty(annot.value()) || StringUtils.isEmpty(annot.value()[0])) { return "/"; } if (annot.value().length > 1 && logger.isWarnEnabled()) { logger.warn("Multiple paths on method " + method.toGenericString() + ", using first one"); } return annot.value()[0]; }
private String addMethodPathComponent( ExecutableElement executableElement, TypeElement cls, String path, RequestMapping anno) { if (anno == null) { throw new IllegalArgumentException( String.format( "Method %s should have Request mapping annotation", executableElement.getSimpleName())); } if (anno.value() != null && anno.value().length > 0) { return Utils.joinPaths(path, anno.value()[0]); } return path; }
private static String getTypeRequestMapping(Class<?> controllerType) { Assert.notNull(controllerType, "'controllerType' must not be null"); RequestMapping annot = AnnotationUtils.findAnnotation(controllerType, RequestMapping.class); if (annot == null || ObjectUtils.isEmpty(annot.value()) || StringUtils.isEmpty(annot.value()[0])) { return "/"; } if (annot.value().length > 1 && logger.isWarnEnabled()) { logger.warn("Multiple paths on controller " + controllerType.getName() + ", using first one"); } return annot.value()[0]; }
protected String defaultViewPrefix() { String currentViewPrefix = ""; RequestMapping requestMapping = AnnotationUtils.findAnnotation(getClass(), RequestMapping.class); if (requestMapping != null && requestMapping.value().length > 0) { currentViewPrefix = requestMapping.value()[0]; } if (StringUtils.isEmpty(currentViewPrefix)) { currentViewPrefix = this.entityClass.getSimpleName(); } return currentViewPrefix; }
/** * Check for an @RequestMapping annotation on the class and, if present, store the RequestMethod * and the URL mapping */ public void initialize() { Annotation ann = clazz.getAnnotation(RequestMapping.class); if (ann != null && (ann instanceof RequestMapping)) { RequestMapping rm = (RequestMapping) ann; RequestMethod[] reqMethod = rm.method(); if (reqMethod.length > 0) { this.methodName = reqMethod[0].name(); } String[] classValue = rm.value(); if (classValue.length > 0) { this.path = classValue[0]; } } }
private String getClassLevelUrlPath(TypeElement cls) { RestApiMountPoint mountPoint = cls.getAnnotation(RestApiMountPoint.class); String path = mountPoint == null ? "/" : mountPoint.value(); RequestMapping clsAnno = cls.getAnnotation(RequestMapping.class); if (clsAnno == null || clsAnno.value().length == 0) { return path; } else if (clsAnno.value().length == 1) { return Utils.joinPaths(path, clsAnno.value()[0]); } else { throw new IllegalStateException( String.format( "The RequestMapping annotation of class %s has multiple value strings. Only zero or one value is supported", cls.getQualifiedName())); } }
private Map<String, List<Method>> collectApisByRequestMapping(List<Method> methods) { Map<String, List<Method>> apiMethodMap = new HashMap<String, List<Method>>(); for (Method method : methods) { if (method.isAnnotationPresent(RequestMapping.class)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); String path = ""; if (requestMapping.value() != null && requestMapping.value().length != 0) { path = generateFullPath(requestMapping.value()[0]); } else { path = resourcePath; } if (apiMethodMap.containsKey(path)) { apiMethodMap.get(path).add(method); } else { List<Method> ms = new ArrayList<Method>(); ms.add(method); apiMethodMap.put(path, ms); } } } return apiMethodMap; }
/** Created a RequestMappingInfo from a RequestMapping annotation. */ private RequestMappingInfo createRequestMappingInfo( RequestMapping annotation, RequestCondition<?> customCondition) { return new RequestMappingInfo( new PatternsRequestCondition( annotation.value(), getUrlPathHelper(), getPathMatcher(), this.useSuffixPatternMatch, this.useTrailingSlashMatch), new RequestMethodsRequestCondition(annotation.method()), new ParamsRequestCondition(annotation.params()), new HeadersRequestCondition(annotation.headers()), new ConsumesRequestCondition(annotation.consumes(), annotation.headers()), new ProducesRequestCondition(annotation.produces(), annotation.headers()), customCondition); }
// Helper method for loadDocuments() private Map<String, SpringResource> analyzeController( Class<?> clazz, Map<String, SpringResource> resourceMap, String description) throws ClassNotFoundException { String controllerCanonicalName = clazz.getCanonicalName(); String[] controllerRequestMappingValues = null; // Determine if we will use class-level requestmapping or dummy string if (clazz.getAnnotation(RequestMapping.class) != null && clazz.getAnnotation(RequestMapping.class).value() != null) { controllerRequestMappingValues = clazz.getAnnotation(RequestMapping.class).value(); } else { controllerRequestMappingValues = new String[1]; controllerRequestMappingValues[0] = ""; } // Iterate over all value attributes of the class-level RequestMapping annotation for (int i = 0; i < controllerRequestMappingValues.length; i++) { // Iterate over all methods inside the controller Method[] methods = clazz.getMethods(); for (Method method : methods) { RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class); // Look for method-level @RequestMapping annotation if (methodRequestMapping instanceof RequestMapping) { RequestMethod[] requestMappingRequestMethods = methodRequestMapping.method(); // For each method-level @RequestMapping annotation, iterate over HTTP Verb for (RequestMethod requestMappingRequestMethod : requestMappingRequestMethods) { String[] methodRequestMappingValues = methodRequestMapping.value(); // Check for cases where method-level @RequestMapping#value is not set, and use the // controllers @RequestMapping if (methodRequestMappingValues == null || methodRequestMappingValues.length == 0) { // The map key is a concat of the following: // 1. The controller package // 2. The controller class name // 3. The controller-level @RequestMapping#value String resourceKey = controllerCanonicalName + controllerRequestMappingValues[i] + requestMappingRequestMethod; if ((!(resourceMap.containsKey(resourceKey)))) { resourceMap.put( resourceKey, new SpringResource( clazz, controllerRequestMappingValues[i], resourceKey, description)); } resourceMap.get(resourceKey).addMethod(method); } else { // Here we know that method-level @RequestMapping#value is populated, so // iterate over all the @RequestMapping#value attributes, and add them to the resource // map. for (String methodRequestMappingValue : methodRequestMappingValues) { String resourceName = methodRequestMappingValue; // The map key is a concat of the following: // 1. The controller package // 2. The controller class name // 3. The controller-level @RequestMapping#value // 4. The method-level @RequestMapping#value // 5. The method-level @RequestMapping#method String resourceKey = controllerCanonicalName + controllerRequestMappingValues[i] + resourceName + requestMappingRequestMethod; if (!(resourceName.equals(""))) { if ((!(resourceMap.containsKey(resourceKey)))) { resourceMap.put( resourceKey, new SpringResource(clazz, resourceName, resourceKey, description)); } resourceMap.get(resourceKey).addMethod(method); } } } } } } } clazz.getFields(); clazz .getDeclaredFields(); // <--In case developer declares a field without an associated // getter/setter. // this will allow NoClassDefFoundError to be caught before it triggers bamboo failure. return resourceMap; }
private String getPath(RequestMapping classMapping) { if (classMapping != null && isNotEmpty(classMapping.value())) { return classMapping.value()[0]; } return null; }
private HttpMethod getHttpMethod(RequestMapping mapping) { return HttpMethod.valueOf(mapping.method()[0].name()); }
private Operation parseMethod(Method method) { Operation operation = new Operation(); RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); Class<?> responseClass = null; List<String> produces = new ArrayList<String>(); List<String> consumes = new ArrayList<String>(); String responseContainer = null; String operationId = method.getName(); Map<String, Property> defaultResponseHeaders = null; Set<Map<String, Object>> customExtensions = null; ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); if (apiOperation.hidden()) return null; if (!"".equals(apiOperation.nickname())) operationId = apiOperation.nickname(); defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); customExtensions = parseCustomExtensions(apiOperation.extensions()); if (customExtensions != null) { for (Map<String, Object> extension : customExtensions) { if (extension != null) { for (Map.Entry<String, Object> map : extension.entrySet()) { operation.setVendorExtension( map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue()); } } } } if (apiOperation.response() != null && !Void.class.equals(apiOperation.response())) responseClass = apiOperation.response(); if (!"".equals(apiOperation.responseContainer())) responseContainer = apiOperation.responseContainer(); /// security if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) operation.security(sec); } } if (responseClass == null) { // pick out response from method declaration LOG.info("picking up response class from method " + method); Type t = method.getGenericReturnType(); responseClass = method.getReturnType(); if (responseClass.equals(ResponseEntity.class)) { responseClass = getGenericSubtype(method.getReturnType(), method.getGenericReturnType()); } if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString()) && responseClass.getAnnotation(Api.class) == null) { LOG.info("reading model " + responseClass); Map<String, Model> models = ModelConverters.getInstance().readAll(t); } } if (responseClass != null && !responseClass.equals(Void.class) && !responseClass.equals(ResponseEntity.class) && responseClass.getAnnotation(Api.class) == null) { if (isPrimitive(responseClass)) { Property responseProperty = null; Property property = ModelConverters.getInstance().readAsProperty(responseClass); if (property != null) { if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(property); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(property); else responseProperty = property; operation.response( 200, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString())) { Map<String, Model> models = ModelConverters.getInstance().read(responseClass); if (models.size() == 0) { Property pp = ModelConverters.getInstance().readAsProperty(responseClass); operation.response( 200, new Response() .description("successful operation") .schema(pp) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = null; if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(new RefProperty().asDefault(key)); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(new RefProperty().asDefault(key)); else responseProperty = new RefProperty().asDefault(key); operation.response( 200, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } models = ModelConverters.getInstance().readAll(responseClass); for (String key : models.keySet()) { swagger.model(key, models.get(key)); } } } operation.operationId(operationId); if (requestMapping.produces() != null) { for (String str : Arrays.asList(requestMapping.produces())) { if (!produces.contains(str)) { produces.add(str); } } } if (requestMapping.consumes() != null) { for (String str : Arrays.asList(requestMapping.consumes())) { if (!consumes.contains(str)) { consumes.add(str); } } } ApiResponses responseAnnotation = method.getAnnotation(ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } else { ResponseStatus responseStatus = method.getAnnotation(ResponseStatus.class); if (responseStatus != null) { operation.response( responseStatus.value().value(), new Response().description(responseStatus.reason())); } } boolean isDeprecated = false; Deprecated annotation = method.getAnnotation(Deprecated.class); if (annotation != null) isDeprecated = true; boolean hidden = false; if (apiOperation != null) hidden = apiOperation.hidden(); // process parameters Class[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); // paramTypes = method.getParameterTypes // genericParamTypes = method.getGenericParameterTypes for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); return operation; }
private List<ResourceInfo> findMethods(Map<String, Object> handlerMap, Set<String> urls) { SortedSet<ResourceInfo> result = new TreeSet<ResourceInfo>(); for (String key : urls) { Object handler = handlerMap.get(key); Class<?> handlerType = ClassUtils.getUserClass(handler); HandlerMethodResolver resolver = new HandlerMethodResolver(); resolver.init(handlerType); String[] typeMappings = null; RequestMapping typeMapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class); if (typeMapping != null) { typeMappings = typeMapping.value(); } Set<Method> handlerMethods = resolver.getHandlerMethods(); for (Method method : handlerMethods) { RequestMapping mapping = method.getAnnotation(RequestMapping.class); Collection<String> computedMappings = new HashSet<String>(); if (typeMappings != null) { computedMappings.addAll(Arrays.asList(typeMappings)); } for (String path : mapping.value()) { if (typeMappings != null) { for (String parent : computedMappings) { if (parent.endsWith("/")) { parent = parent.substring(0, parent.length() - 1); } computedMappings.add(parent + path); } } else { computedMappings.add(path); } } logger.debug( "Analysing mappings for method:" + method.getName() + ", key:" + key + ", computed mappings: " + computedMappings); if (computedMappings.contains(key)) { RequestMethod[] methods = mapping.method(); if (methods != null && methods.length > 0) { for (RequestMethod requestMethod : methods) { logger.debug( "Added explicit mapping for path=" + key + "to RequestMethod=" + requestMethod); result.add(new ResourceInfo(key, requestMethod)); } } else { logger.debug("Added implicit mapping for path=" + key + "to RequestMethod=GET"); result.add(new ResourceInfo(key, RequestMethod.GET)); } } } if (handlerMethods.isEmpty()) { result.add(new ResourceInfo(key, RequestMethod.GET)); } } return new ArrayList<ResourceInfo>(result); }
public Swagger read(SpringResource resource) { if (swagger == null) { swagger = new Swagger(); } String description; List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); // Add the description from the controller api Class<?> controller = resource.getControllerClass(); RequestMapping controllerRM = controller.getAnnotation(RequestMapping.class); String[] controllerProduces = new String[0]; String[] controllerConsumes = new String[0]; if (controllerRM != null) { controllerConsumes = controllerRM.consumes(); controllerProduces = controllerRM.produces(); } if (controller != null && controller.isAnnotationPresent(Api.class)) { Api api = controller.getAnnotation(Api.class); if (!canReadApi(false, api)) { return swagger; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); description = api.description(); } resourcePath = resource.getControllerMapping(); // collect api from method with @RequestMapping Map<String, List<Method>> apiMethodMap = collectApisByRequestMapping(methods); for (String path : apiMethodMap.keySet()) { for (Method method : apiMethodMap.get(path)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (requestMapping == null) { continue; } ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); if (apiOperation == null || apiOperation.hidden()) { continue; } String httpMethod = null; Map<String, String> regexMap = new HashMap<String, String>(); String operationPath = parseOperationPath(path, regexMap); // http method for (RequestMethod requestMethod : requestMapping.method()) { httpMethod = requestMethod.toString().toLowerCase(); Operation operation = parseMethod(method); updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation); updateOperationProtocols(apiOperation, operation); String[] apiProduces = requestMapping.produces(); String[] apiConsumes = requestMapping.consumes(); apiProduces = (apiProduces == null || apiProduces.length == 0) ? controllerProduces : apiProduces; apiConsumes = (apiConsumes == null || apiProduces.length == 0) ? controllerConsumes : apiConsumes; apiConsumes = updateOperationConsumes(new String[0], apiConsumes, operation); apiProduces = updateOperationProduces(new String[0], apiProduces, operation); updateTagsForOperation(operation, apiOperation); updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); updatePath(operationPath, httpMethod, operation); } } } return swagger; }