org.glassfish.jersey.server.monitoring.RequestEvent Java Examples

The following examples show how to use org.glassfish.jersey.server.monitoring.RequestEvent. 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: SFRestApiListener.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(RequestEvent requestEvent) {
    switch (requestEvent.getType()) {
        case RESOURCE_METHOD_START:
            methodStartTime = System.currentTimeMillis();
            break;
        case RESOURCE_METHOD_FINISHED:
            long methodExecution = System.currentTimeMillis() - methodStartTime;
            String methodName = requestEvent.getUriInfo().getMatchedResourceMethod().getInvocable().getHandlingMethod().getName();
            logger.debug("Method '{}' executed. Processing time: {} ms", methodName, methodExecution);
            break;
        case ON_EXCEPTION:
        	logger.error("Problem with API request", requestEvent.getException());
        	break;
        default:
            break;
    }
}
 
Example #2
Source File: SpanCustomizingApplicationEventListenerTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Test
public void onRequest_retunrs_self_for_START_otherwise_null() {
    for (RequestEvent.Type type : RequestEvent.Type.values()) {
        // given
        doReturn(type).when(requestEventMock).getType();
        boolean expectNonNullResult = (type == RequestEvent.Type.START);

        // when
        RequestEventListener result = implSpy.onRequest(requestEventMock);

        // then
        if (expectNonNullResult) {
            assertThat(result).isSameAs(implSpy);
        }
        else {
            assertThat(result).isNull();
        }
    }
}
 
Example #3
Source File: JerseyTags.java    From micrometer with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@code uri} tag based on the URI of the given {@code event}. Uses the
 * {@link ExtendedUriInfo#getMatchedTemplates()} if
 * available. {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND} for 404 responses.
 * @param event the request event
 * @return the uri tag derived from the request event
 */
public static Tag uri(RequestEvent event) {
    ContainerResponse response = event.getContainerResponse();
    if (response != null) {
        int status = response.getStatus();
        if (isRedirection(status)) {
            return URI_REDIRECTION;
        }
        if (status == 404) {
            return URI_NOT_FOUND;
        }
    }
    String matchingPattern = getMatchingPattern(event);
    if (matchingPattern.equals("/")) {
        return URI_ROOT;
    }
    return Tag.of("uri", matchingPattern);
}
 
Example #4
Source File: TimingApplicationEventListener.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void onEvent(RequestEvent event) {
  switch (event.getType()) {
  case RESOURCE_METHOD_START:
    callId = ticker.nextId();
    ticker.tick("callRes", callId);
    break;
  case RESOURCE_METHOD_FINISHED:
    ticker.tock("callRes", callId);
    break;
  case FINISHED:
    ticker.tock("req", reqEId);
    ContainerRequest req = event.getContainerRequest();
    String endpoint = req.getMethod() + " " + req.getRequestUri().toString().substring(req.getBaseUri().toString().length());
    ticker.log(reqId, endpoint);
    Timer.release();
    break;
    default: // do nothing
  }
}
 
Example #5
Source File: MetricsResourceMethodApplicationListener.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
private MethodMetrics getMethodMetrics(RequestEvent event) {
  ResourceMethod method = event.getUriInfo().getMatchedResourceMethod();
  if (method == null) {
    return null;
  }

  RequestScopedMetrics metrics = this.metrics.get(method.getInvocable().getDefinitionMethod());
  if (metrics == null) {
    return null;
  }

  Map tags = (Map) event.getContainerRequest().getProperty(REQUEST_TAGS_PROP_KEY);
  if (tags == null) {
    return metrics.metrics();
  }

  // we have additional tags, find the appropriate metrics holder
  return metrics.metrics(tags);
}
 
Example #6
Source File: SpanCustomizingApplicationEventListenerTest.java    From brave with Apache License 2.0 6 votes vote down vote up
/** Don't clobber user-defined properties! */
@Test public void onEvent_skipsErrorWhenSet() {
  setEventType(RequestEvent.Type.FINISHED);
  setBaseUri("/");

  when(request.getProperty(SpanCustomizer.class.getName())).thenReturn(span);

  Exception error = new Exception();
  when(requestEvent.getException()).thenReturn(error);
  when(request.getProperty("error")).thenReturn("madness");

  listener.onEvent(requestEvent);

  verify(request).getProperty(SpanCustomizer.class.getName());
  verify(request).getProperty("error");
  verify(request).getUriInfo();
  verify(request).setProperty("http.route", ""); // empty means no route found
  verifyNoMoreInteractions(request); // no setting of error
}
 
Example #7
Source File: SpanCustomizingApplicationEventListenerTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Test
public void onEvent_for_RequestEvent_handles_REQUEST_MATCHED_only_and_sets_HTTP_ROUTE_to_result_of_route_method() {
    for (RequestEvent.Type type : RequestEvent.Type.values()) {
        // given
        doReturn(type).when(requestEventMock).getType();

        boolean expectHandled = (type == RequestEvent.Type.REQUEST_MATCHED);

        String routeMethodResult = "route-" + UUID.randomUUID().toString();
        doReturn(routeMethodResult).when(implSpy).route(any(ContainerRequest.class));

        // when
        implSpy.onEvent(requestEventMock);

        // then
        if (expectHandled) {
            verify(requestMock).setProperty(KnownZipkinTags.HTTP_ROUTE, routeMethodResult);
        }
        else {
            verifyZeroInteractions(requestMock);
        }
    }
}
 
Example #8
Source File: SpanCustomizingApplicationEventListener.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void onEvent(RequestEvent event) {
  // Note: until REQUEST_MATCHED, we don't know metadata such as if the request is async or not
  if (event.getType() != FINISHED) return;
  ContainerRequest request = event.getContainerRequest();
  Object maybeSpan = request.getProperty(SpanCustomizer.class.getName());
  if (!(maybeSpan instanceof SpanCustomizer)) return;

  // Set the HTTP route attribute so that TracingFilter can see it
  request.setProperty("http.route", route(request));

  Throwable error = unwrapError(event);
  // Set the error attribute so that TracingFilter can see it
  if (error != null && request.getProperty("error") == null) request.setProperty("error", error);

  parser.requestMatched(event, (SpanCustomizer) maybeSpan);
}
 
Example #9
Source File: DefaultJerseyTagsProviderTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private static RequestEvent event(Integer status, Exception exception, String baseUri, String... uriTemplateStrings) {
    Builder builder = new RequestEventImpl.Builder();

    ContainerRequest containerRequest = mock(ContainerRequest.class);
    when(containerRequest.getMethod()).thenReturn("GET");
    builder.setContainerRequest(containerRequest);

    ContainerResponse containerResponse = mock(ContainerResponse.class);
    when(containerResponse.getStatus()).thenReturn(status);
    builder.setContainerResponse(containerResponse);

    builder.setException(exception, null);

    ExtendedUriInfo extendedUriInfo = mock(ExtendedUriInfo.class);
    when(extendedUriInfo.getBaseUri()).thenReturn(
        URI.create("http://localhost:8080" + (baseUri == null ? "/" : baseUri)));
    List<UriTemplate> uriTemplates = uriTemplateStrings == null ? Collections.emptyList()
        : Arrays.stream(uriTemplateStrings).map(uri -> new UriTemplate(uri))
        .collect(Collectors.toList());
    // UriTemplate are returned in reverse order
    Collections.reverse(uriTemplates);
    when(extendedUriInfo.getMatchedTemplates()).thenReturn(uriTemplates);
    builder.setExtendedUriInfo(extendedUriInfo);

    return builder.build(Type.FINISHED);
}
 
Example #10
Source File: MetricsRequestEventListener.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private Set<Timed> annotations(RequestEvent event) {
    final Set<Timed> timed = new HashSet<>();

    final ResourceMethod matchingResourceMethod = event.getUriInfo().getMatchedResourceMethod();
    if (matchingResourceMethod != null) {
        // collect on method level
        timed.addAll(timedFinder.findTimedAnnotations(matchingResourceMethod.getInvocable().getHandlingMethod()));

        // fallback on class level
        if (timed.isEmpty()) {
            timed.addAll(timedFinder.findTimedAnnotations(matchingResourceMethod.getInvocable().getHandlingMethod()
                .getDeclaringClass()));
        }
    }
    return timed;
}
 
Example #11
Source File: MetricsRequestEventListener.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private Set<Timer> shortTimers(Set<Timed> timed, RequestEvent event) {
    /*
     * Given we didn't find any matching resource method, 404s will be only
     * recorded when auto-time-requests is enabled. On par with WebMVC
     * instrumentation.
     */
    if ((timed == null || timed.isEmpty()) && autoTimeRequests) {
        return Collections.singleton(registry.timer(metricName, tagsProvider.httpRequestTags(event)));
    }

    if (timed == null) {
        return Collections.emptySet();
    }

    return timed.stream()
        .map(t -> Timer.builder(t, metricName).tags(tagsProvider.httpRequestTags(event)).register(registry))
        .collect(Collectors.toSet());
}
 
Example #12
Source File: SpanCustomizingApplicationEventListener.java    From brave with Apache License 2.0 5 votes vote down vote up
@Nullable static Throwable unwrapError(RequestEvent event) {
  Throwable error = event.getException();
  // For example, if thrown in an async controller
  if (error instanceof MappableException && error.getCause() != null) {
    error = error.getCause();
  }
  // Don't create error messages for normal HTTP status codes.
  if (error instanceof WebApplicationException) return error.getCause();
  return error;
}
 
Example #13
Source File: SpanCustomizingApplicationEventListenerTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    implSpy = spy(SpanCustomizingApplicationEventListener.create());
    requestEventMock = mock(RequestEvent.class);
    requestMock = mock(ContainerRequest.class);
    extendedUriInfoMock = mock(ExtendedUriInfo.class);

    doReturn(RequestEvent.Type.REQUEST_MATCHED).when(requestEventMock).getType();
    doReturn(requestMock).when(requestEventMock).getContainerRequest();
    doReturn(extendedUriInfoMock).when(requestMock).getUriInfo();
}
 
Example #14
Source File: TracingApplicationEventListener.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * This keeps the span in scope as long as possible. In synchronous methods, the span remains in
 * scope for the whole request/response lifecycle. {@linkplain ManagedAsync} and {@linkplain
 * Suspended} requests are the worst case: the span is only visible until request filters
 * complete.
 */
@Override
public void onEvent(RequestEvent event) {
  Scope maybeScope;
  switch (event.getType()) {
    // Note: until REQUEST_MATCHED, we don't know metadata such as if the request is async or not
    case REQUEST_MATCHED:
      parser.requestMatched(event, span);
      async = async(event);
      break;
    case REQUEST_FILTERED:
    case RESOURCE_METHOD_FINISHED:
      // If we scoped above, we have to close that to avoid leaks.
      // Jersey-specific @ManagedAsync stays on the request thread until REQUEST_FILTERED
      // Normal async methods sometimes stay on a thread until RESOURCE_METHOD_FINISHED, but
      // this is not reliable. So, we eagerly close the scope from request filters, and re-apply
      // it later when the resource method starts.
      if (!async || (maybeScope = getAndSet(null)) == null) break;
      maybeScope.close();
      break;
    case RESOURCE_METHOD_START:
      // If we are async, we have to re-scope the span as the resource method invocation is
      // is likely on a different thread than the request filtering.
      if (!async || get() != null) break;
      set(currentTraceContext.newScope(span.context()));
      break;
    case FINISHED:
      handler.handleSend(new RequestEventWrapper(event), span);
      // In async FINISHED can happen before RESOURCE_METHOD_FINISHED, and on different threads!
      // Don't close the scope unless it is a synchronous method.
      if (!async && (maybeScope = getAndSet(null)) != null) {
        maybeScope.close();
      }
      break;
    default:
  }
}
 
Example #15
Source File: OpenCensusApplicationEventListener.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Override
public RequestEventListener onRequest(RequestEvent requestEvent) {
    if (requestEvent.getType() == RequestEvent.Type.START) {
        Span requestSpan = handleRequestStart(requestEvent.getContainerRequest());
        return new OpenCensusRequestEventListener(requestSpan);
    }
    return null;
}
 
Example #16
Source File: JerseyApplicationEventListenerTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnOpenSessionInViewFilterOnRequestEvent() {
	DatabaseConfiguration configuration = mock(DatabaseConfiguration.class);
	JerseyApplicationEventListener listener = new JerseyApplicationEventListener(configuration);
	RequestEvent requestEvent = mock(RequestEvent.class);
	RequestEventListener eventListener = listener.onRequest(requestEvent);
	assertTrue(eventListener instanceof OpenSessionInViewFilter);
	assertEquals(((OpenSessionInViewFilter)eventListener).getConfiguration(), configuration);
}
 
Example #17
Source File: MetricsResourceMethodApplicationListener.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Indicate that a request has failed with an exception.
 */
public void exception(final RequestEvent event) {
  final int statusCode = event.getException() instanceof WebApplicationException
      ? ((WebApplicationException) event.getException()).getResponse().getStatus() : 0;
  int idx = statusCode / 100;
  // Index 0 means "unknown" status codes.
  idx = idx < 0 || idx >= 6 ? 0 : idx;

  errorSensorByStatus[idx].record();
  errorSensor.record();
}
 
Example #18
Source File: ExceptionLogger.java    From jqm with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(RequestEvent paramRequestEvent)
{
    if (paramRequestEvent.getType() == Type.ON_EXCEPTION)
    {
        log.info("a REST call failed with an exception", paramRequestEvent.getException());
    }
}
 
Example #19
Source File: EventParser.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked prior to request invocation during {@link RequestEventListener#onEvent(RequestEvent)}
 * where the event type is {@link RequestEvent.Type#REQUEST_MATCHED}
 *
 * <p>Adds the tags {@link #RESOURCE_CLASS} and {@link #RESOURCE_METHOD}. Override or use {@link
 * #NOOP} to change this behavior.
 */
protected void requestMatched(RequestEvent event, SpanCustomizer customizer) {
  ResourceMethod method = event.getContainerRequest().getUriInfo().getMatchedResourceMethod();
  if (method == null) return; // This case is extremely odd as this is called on REQUEST_MATCHED!
  Invocable i = method.getInvocable();
  customizer.tag(RESOURCE_CLASS, i.getHandler().getHandlerClass().getSimpleName());
  customizer.tag(RESOURCE_METHOD, i.getHandlingMethod().getName());
}
 
Example #20
Source File: OpenSessionInViewFilter.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(RequestEvent event) {
	logger.trace("Received the event {}", event);
	switch (event.getType()) {
	case REQUEST_MATCHED:
		requestReceived(event.getContainerRequest());
		break;
	case FINISHED:
		requestCompleted(event.getContainerRequest(), event.getContainerResponse());
		break;
	default:
		break;
	}
}
 
Example #21
Source File: SpanCustomizingApplicationEventListener.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(RequestEvent event) {
    // We only care about the REQUEST_MATCHED event.
    if (event.getType() != REQUEST_MATCHED) {
        return;
    }

    ContainerRequest request = event.getContainerRequest();
    // Setting the http.route as a setProperty() on this ContainerRequest will bubble out to the
    //      HttpServletRequest as a request attribute.
    request.setProperty(KnownZipkinTags.HTTP_ROUTE, route(request));
}
 
Example #22
Source File: SpanCustomizingApplicationEventListener.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Override
public RequestEventListener onRequest(RequestEvent requestEvent) {
    if (requestEvent.getType() == RequestEvent.Type.START) {
        return this;
    }

    return null;
}
 
Example #23
Source File: TimingApplicationEventListener.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public RequestEventListener onRequest(RequestEvent event) {
  if (Timer.enabled()) {
    return new TimingRequestEventListener(nextReqId ++);
  }
  return null;
}
 
Example #24
Source File: MetricsRequestEventListener.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private Set<LongTaskTimer> longTaskTimers(Set<Timed> timed, RequestEvent event) {
    return timed.stream()
        .filter(Timed::longTask)
        .map(LongTaskTimer::builder)
        .map(b -> b.tags(tagsProvider.httpLongRequestTags(event)).register(registry))
        .collect(Collectors.toSet());
}
 
Example #25
Source File: MetricsRequestEventListener.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(RequestEvent event) {
    ContainerRequest containerRequest = event.getContainerRequest();
    Set<Timed> timedAnnotations;

    switch (event.getType()) {
        case ON_EXCEPTION:
            if (!(event.getException() instanceof NotFoundException)) {
                break;
            }
        case REQUEST_MATCHED:
            timedAnnotations = annotations(event);

            timedAnnotationsOnRequest.put(containerRequest, timedAnnotations);
            shortTaskSample.put(containerRequest, Timer.start(registry));

            List<LongTaskTimer.Sample> longTaskSamples = longTaskTimers(timedAnnotations, event).stream().map(LongTaskTimer::start).collect(Collectors.toList());
            if (!longTaskSamples.isEmpty()) {
                this.longTaskSamples.put(containerRequest, longTaskSamples);
            }
            break;
        case FINISHED:
            timedAnnotations = timedAnnotationsOnRequest.remove(containerRequest);
            Timer.Sample shortSample = shortTaskSample.remove(containerRequest);

            if (shortSample != null) {
                for (Timer timer : shortTimers(timedAnnotations, event)) {
                    shortSample.stop(timer);
                }
            }

            Collection<LongTaskTimer.Sample> longSamples = this.longTaskSamples.remove(containerRequest);
            if (longSamples != null) {
                for (LongTaskTimer.Sample longSample : longSamples) {
                    longSample.stop();
                }
            }
            break;
    }
}
 
Example #26
Source File: SpanCustomizingApplicationEventListenerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void onEvent_setsErrorWhenNotAlreadySet() {
  setEventType(RequestEvent.Type.FINISHED);
  setBaseUri("/");

  when(request.getProperty(SpanCustomizer.class.getName())).thenReturn(span);

  Exception error = new Exception();
  when(requestEvent.getException()).thenReturn(error);
  when(request.getProperty("error")).thenReturn(null);

  listener.onEvent(requestEvent);

  verify(request).setProperty("error", error);
}
 
Example #27
Source File: SpanCustomizingApplicationEventListenerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void onEvent_toleratesMissingCustomizer() {
  setEventType(RequestEvent.Type.FINISHED);
  setBaseUri("/");

  listener.onEvent(requestEvent);

  verifyNoMoreInteractions(parser);
}
 
Example #28
Source File: JerseyTags.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private static String getMatchingPattern(RequestEvent event) {
    ExtendedUriInfo uriInfo = event.getUriInfo();
    List<UriTemplate> templates = uriInfo.getMatchedTemplates();

    StringBuilder sb = new StringBuilder();
    sb.append(uriInfo.getBaseUri().getPath());
    for (int i = templates.size() - 1; i >= 0; i--) {
        sb.append(templates.get(i).getTemplate());
    }
    String multipleSlashCleaned = MULTIPLE_SLASH_PATTERN.matcher(sb.toString()).replaceAll("/");
    if (multipleSlashCleaned.equals("/")) {
        return multipleSlashCleaned;
    }
    return TRAILING_SLASH_PATTERN.matcher(multipleSlashCleaned).replaceAll("");
}
 
Example #29
Source File: SpanCustomizingApplicationEventListenerTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void onEvent_ignoresNotFinished() {
  for (RequestEvent.Type type : RequestEvent.Type.values()) {
    if (type == RequestEvent.Type.FINISHED) return;

    setEventType(type);

    listener.onEvent(requestEvent);

    verifyNoMoreInteractions(span);
  }
}
 
Example #30
Source File: TracingApplicationEventListener.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public RequestEventListener onRequest(RequestEvent event) {
  if (event.getType() != RequestEvent.Type.START) return null;
  Span span = handler.handleReceive(new ContainerRequestWrapper(event.getContainerRequest()));
  return new TracingRequestEventListener(span, currentTraceContext.newScope(span.context()));
}