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());
}
}
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);
}));
}
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();
}
});
}
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;
}
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;
}
Aggregations