Search in sources :

Example 31 with HandlerMethod

use of org.springframework.web.method.HandlerMethod in project apm-agent-java by elastic.

the class ApmHandlerInterceptor method setTransactionName.

private void setTransactionName(Object handler, Transaction transaction) {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = ((HandlerMethod) handler);
        transaction.getName().setLength(0);
        transaction.getName().append(handlerMethod.getBeanType().getSimpleName()).append('#').append(handlerMethod.getMethod().getName());
    } else {
        transaction.setName(handler.getClass().getSimpleName());
    }
}
Also used : HandlerMethod(org.springframework.web.method.HandlerMethod)

Example 32 with HandlerMethod

use of org.springframework.web.method.HandlerMethod in project spring-cloud-sleuth by spring-cloud.

the class TraceWebFilter method filter.

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    if (tracer().currentSpan() != null) {
        // clear any previous trace
        tracer().withSpanInScope(null);
    }
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    String uri = request.getPath().pathWithinApplication().value();
    if (log.isDebugEnabled()) {
        log.debug("Received a request to uri [" + uri + "]");
    }
    Span spanFromAttribute = getSpanFromAttribute(exchange);
    final String CONTEXT_ERROR = "sleuth.webfilter.context.error";
    return chain.filter(exchange).compose(f -> f.then(Mono.subscriberContext()).onErrorResume(t -> Mono.subscriberContext().map(c -> c.put(CONTEXT_ERROR, t))).flatMap(c -> {
        // reactivate span from context
        Span span = spanFromContext(c);
        Mono<Void> continuation;
        Throwable t = null;
        if (c.hasKey(CONTEXT_ERROR)) {
            t = c.get(CONTEXT_ERROR);
            continuation = Mono.error(t);
        } else {
            continuation = Mono.empty();
        }
        Object attribute = exchange.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
        if (attribute instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) attribute;
            addClassMethodTag(handlerMethod, span);
            addClassNameTag(handlerMethod, span);
        }
        addResponseTagsForSpanWithoutParent(exchange, response, span);
        handler().handleSend(response, t, span);
        if (log.isDebugEnabled()) {
            log.debug("Handled send of " + span);
        }
        return continuation;
    }).subscriberContext(c -> {
        Span span;
        if (c.hasKey(Span.class)) {
            Span parent = c.get(Span.class);
            span = tracer().nextSpan(TraceContextOrSamplingFlags.create(parent.context())).start();
            if (log.isDebugEnabled()) {
                log.debug("Found span in reactor context" + span);
            }
        } else {
            if (spanFromAttribute != null) {
                span = spanFromAttribute;
                if (log.isDebugEnabled()) {
                    log.debug("Found span in attribute " + span);
                }
            } else {
                span = handler().handleReceive(extractor(), request.getHeaders(), request);
                if (log.isDebugEnabled()) {
                    log.debug("Handled receive of span " + span);
                }
            }
            exchange.getAttributes().put(TRACE_REQUEST_ATTR, span);
        }
        return c.put(Span.class, span);
    }));
}
Also used : HttpTracing(brave.http.HttpTracing) Ordered(org.springframework.core.Ordered) Tracer(brave.Tracer) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) TraceContextOrSamplingFlags(brave.propagation.TraceContextOrSamplingFlags) HttpHeaders(org.springframework.http.HttpHeaders) Context(reactor.util.context.Context) Span(brave.Span) Mono(reactor.core.publisher.Mono) TraceContext(brave.propagation.TraceContext) ServerWebExchange(org.springframework.web.server.ServerWebExchange) TraceKeys(org.springframework.cloud.sleuth.TraceKeys) HandlerMethod(org.springframework.web.method.HandlerMethod) WebFilter(org.springframework.web.server.WebFilter) BeanFactory(org.springframework.beans.factory.BeanFactory) Propagation(brave.propagation.Propagation) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) HttpServerHandler(brave.http.HttpServerHandler) HandlerMapping(org.springframework.web.reactive.HandlerMapping) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) WebFilterChain(org.springframework.web.server.WebFilterChain) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Span(brave.Span) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) HandlerMethod(org.springframework.web.method.HandlerMethod)

Example 33 with HandlerMethod

use of org.springframework.web.method.HandlerMethod in project spring-boot-api-seed-project by selfassu.

the class WebMvcConfigurer method configureHandlerExceptionResolvers.

@Override
protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    exceptionResolvers.add(new HandlerExceptionResolver() {

        @Nullable
        @Override
        public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception exception) {
            Result result = new Result();
            if (exception instanceof ApplicationException) {
                // 业务失败的异常,手动抛出的异常
                result.setCode(ResultCode.FAILED).setMessage(exception.getMessage());
                logger.info(exception.getMessage());
            } else if (exception instanceof NoHandlerFoundException) {
                // 请求路径没有找到
                result.setCode(ResultCode.NOT_FOUND).setMessage("接口 {" + request.getRequestURI() + "} 不存在,请检查");
                logger.info(exception.getMessage());
            } else if (exception instanceof ServletException) {
                result.setCode(ResultCode.FAILED).setMessage(exception.getMessage());
                logger.info(exception.getMessage());
            } else {
                result.setCode(ResultCode.SERVER_ERROR).setMessage("服务器出错!接口 {" + request.getRequestURI() + "} 无法执行,请联系管理员!");
                String message;
                if (handler instanceof HandlerMethod) {
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常详细信息:%s", request.getRequestURI(), handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod().getName(), exception.getMessage());
                } else {
                    message = exception.getMessage();
                }
                logger.error(message, exception);
            }
            responseResult(response, result);
            return new ModelAndView();
        }
    });
}
Also used : HandlerExceptionResolver(org.springframework.web.servlet.HandlerExceptionResolver) ModelAndView(org.springframework.web.servlet.ModelAndView) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletException(javax.servlet.ServletException) NoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException) ApplicationException(com.company.project.core.ApplicationException) HandlerMethod(org.springframework.web.method.HandlerMethod) Result(com.company.project.core.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ApplicationException(com.company.project.core.ApplicationException) NoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException) Nullable(org.springframework.lang.Nullable)

Example 34 with HandlerMethod

use of org.springframework.web.method.HandlerMethod in project workbench by all-of-us.

the class AuthInterceptor method preHandle.

/**
 * Returns true iff the request is auth'd and should proceed. Publishes authenticated user info
 * using Spring's SecurityContext.
 * @param handler The Swagger-generated ApiController. It contains our handler as a private
 *     delegate.
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // OPTIONS methods requests don't need authorization.
    if (request.getMethod().equals(HttpMethods.OPTIONS)) {
        return true;
    }
    HandlerMethod method = (HandlerMethod) handler;
    boolean isAuthRequired = false;
    ApiOperation apiOp = AnnotationUtils.findAnnotation(method.getMethod(), ApiOperation.class);
    if (apiOp != null) {
        for (Authorization auth : apiOp.authorizations()) {
            if (auth.value().equals(authName)) {
                isAuthRequired = true;
                break;
            }
        }
    }
    if (!isAuthRequired) {
        return true;
    }
    String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
        log.warning("No bearer token found in request");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    String token = authorizationHeader.substring("Bearer".length()).trim();
    Userinfoplus userInfo;
    try {
        userInfo = userInfoService.getUserInfo(token);
    } catch (HttpResponseException e) {
        log.log(Level.WARNING, "{0} response getting user info for bearer token {1}: {2}", new Object[] { e.getStatusCode(), token, e.getStatusMessage() });
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    // TODO: check Google group membership to ensure user is in registered user group
    String userEmail = userInfo.getEmail();
    WorkbenchConfig workbenchConfig = workbenchConfigProvider.get();
    if (workbenchConfig.auth.serviceAccountApiUsers.contains(userEmail)) {
        // Whitelisted service accounts are able to make API calls, too.
        // TODO: stop treating service accounts as normal users, have a separate table for them,
        // administrators.
        User user = userDao.findUserByEmail(userEmail);
        if (user == null) {
            user = userService.createServiceAccountUser(userEmail);
        }
        SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.SERVICE_ACCOUNT));
        log.log(Level.INFO, "{0} service account in use", userInfo.getEmail());
        return true;
    }
    String gsuiteDomainSuffix = "@" + workbenchConfig.googleDirectoryService.gSuiteDomain;
    if (!userEmail.endsWith(gsuiteDomainSuffix)) {
        try {
            // If the email isn't in our GSuite domain, try FireCloud; we could be dealing with a
            // pet service account. In both AofU and FireCloud, the pet SA is treated as if it were
            // the user it was created for.
            userEmail = fireCloudService.getMe().getUserInfo().getUserEmail();
        } catch (ApiException e) {
            log.log(Level.INFO, "FireCloud lookup for {0} failed, can't access the workbench: {1}", new Object[] { userInfo.getEmail(), e.getMessage() });
            response.sendError(e.getCode());
            return false;
        }
        if (!userEmail.endsWith(gsuiteDomainSuffix)) {
            log.log(Level.INFO, "User {0} isn't in domain {1}, can't access the workbench", new Object[] { userEmail, gsuiteDomainSuffix });
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }
    }
    User user = userDao.findUserByEmail(userEmail);
    if (user == null) {
        // TODO(danrodney): start populating contact email in Google account, use it here.
        user = userService.createUser(userInfo.getGivenName(), userInfo.getFamilyName(), userInfo.getEmail(), null);
    } else {
        if (user.getDisabled()) {
            throw new ForbiddenException(ExceptionUtils.errorResponse(ErrorCode.USER_DISABLED, "This user account has been disabled."));
        }
    }
    SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user, userInfo, token, UserType.RESEARCHER));
    // TODO: setup this in the context, get rid of log statement
    log.log(Level.INFO, "{0} logged in", userInfo.getEmail());
    if (!hasRequiredAuthority(method, user)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }
    return true;
}
Also used : Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) WorkbenchConfig(org.pmiops.workbench.config.WorkbenchConfig) ForbiddenException(org.pmiops.workbench.exceptions.ForbiddenException) User(org.pmiops.workbench.db.model.User) HttpResponseException(com.google.api.client.http.HttpResponseException) UserAuthentication(org.pmiops.workbench.auth.UserAuthentication) HandlerMethod(org.springframework.web.method.HandlerMethod) Authorization(io.swagger.annotations.Authorization) ApiOperation(io.swagger.annotations.ApiOperation) ApiException(org.pmiops.workbench.firecloud.ApiException)

Example 35 with HandlerMethod

use of org.springframework.web.method.HandlerMethod in project spring-boot-throttling by weddini.

the class ThrottlingInterceptor method preHandle.

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    if (HandlerMethod.class.isInstance(handler)) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Throttling annotation = handlerMethod.getMethod().getAnnotation(Throttling.class);
        if (annotation != null) {
            String evaluatedValue = throttlingEvaluator.evaluate(annotation, handlerMethod.getBean(), handlerMethod.getBeanType(), handlerMethod.getMethod(), handlerMethod.getMethodParameters());
            ThrottlingKey key = ThrottlingKey.builder().method(handlerMethod.getMethod()).annotation(annotation).evaluatedValue(evaluatedValue).build();
            boolean isHandlingAllowed = throttlingService.throttle(key, evaluatedValue);
            if (!isHandlingAllowed) {
                if (logger.isDebugEnabled()) {
                    logger.debug("cannot proceed with a handling http request [" + request.getRequestURI() + "] due to @Throttling configuration, type=" + annotation.type() + ", value=" + evaluatedValue);
                }
                throw new ThrottlingException();
            }
        }
    }
    return true;
}
Also used : Throttling(com.weddini.throttling.Throttling) ThrottlingKey(com.weddini.throttling.ThrottlingKey) ThrottlingException(com.weddini.throttling.ThrottlingException) HandlerMethod(org.springframework.web.method.HandlerMethod)

Aggregations

HandlerMethod (org.springframework.web.method.HandlerMethod)235 Test (org.junit.jupiter.api.Test)87 Method (java.lang.reflect.Method)68 ModelAndView (org.springframework.web.servlet.ModelAndView)44 InvocableHandlerMethod (org.springframework.web.method.support.InvocableHandlerMethod)42 ArrayList (java.util.ArrayList)28 MappingJackson2HttpMessageConverter (org.springframework.http.converter.json.MappingJackson2HttpMessageConverter)26 MethodParameter (org.springframework.core.MethodParameter)25 HttpMessageConverter (org.springframework.http.converter.HttpMessageConverter)25 StringHttpMessageConverter (org.springframework.http.converter.StringHttpMessageConverter)24 Test (org.junit.Test)19 ByteArrayHttpMessageConverter (org.springframework.http.converter.ByteArrayHttpMessageConverter)19 ResourceHttpMessageConverter (org.springframework.http.converter.ResourceHttpMessageConverter)17 AllEncompassingFormHttpMessageConverter (org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter)17 MappingJackson2XmlHttpMessageConverter (org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter)17 IOException (java.io.IOException)14 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)14 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)14 Map (java.util.Map)13 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)12