Java Code Examples for org.glassfish.jersey.server.monitoring.RequestEvent#getType()

The following examples show how to use org.glassfish.jersey.server.monitoring.RequestEvent#getType() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
Source File: TransactionEventListener.java    From registry with Apache License 2.0 4 votes vote down vote up
@Override
public void onEvent(RequestEvent event) {
    final RequestEvent.Type eventType = event.getType();

    if (eventType == RequestEvent.Type.RESOURCE_METHOD_START) {

        // Start transaction before invoking the resource method for the request

        Optional<UnitOfWork> unitOfWork = methodMap.computeIfAbsent(event.getUriInfo()
                                                                         .getMatchedResourceMethod(),
                                                                    UnitOfWorkEventListener::registerUnitOfWorkAnnotations);

        // get property whether to have unitOfWork with DB default transaction by default
        useTransactionForUnitOfWork =
                unitOfWork.map(UnitOfWork::transactional).orElse(runWithTxnIfNotConfigured);

        TransactionIsolation transactionIsolation =
                unitOfWork.map(x -> {
                            TransactionIsolation result = x.transactionIsolation();
                            if (result == TransactionIsolation.APPLICATION_DEFAULT) {
                                result = defaultTransactionIsolation == null ? TransactionIsolation.DATABASE_SENSITIVE : defaultTransactionIsolation;
                            }
                            return result;
                        }
                ).orElse(TransactionIsolation.DATABASE_SENSITIVE);

        if (useTransactionForUnitOfWork) {
            transactionManager.beginTransaction(transactionIsolation);
            isTransactionActive = true;
        }
    } else if (eventType == RequestEvent.Type.RESP_FILTERS_START) {

        // Once the response from the resource method is available we should either rollback or commit the
        // transaction. In case the resource method throws an error, ON_EXCEPTION is called first which will
        // rollback the transaction and eventually RESP_FILTERS_START is called (which won't do anything)
        // after exception mapper handles the exception. In case the exception is not thrown, RESP_FILTERS_START
        // is called which then commits the transaction.
        //      Its not advisable to handle rollbacks and commits when the request transitions to FINISHED state.
        // For example, we might have a client which add an entity (E1) and lets say entity id is returned as a response.
        // Lets say the client then adds a second entity (E2) which has foreign key reference to the first entity (E1).
        // If we commit the transaction in FINISHED state, then the client received the entity id after adding E1
        // at time say t1 and adding entity E2 at t2, then we might run into a scenario where we might commit the changes
        // to E1 only after t2 as responses to the client are dispatched before FINISHED, then client will receive
        // an error that E1 is not found even thought the operation of adding E1 had succeeded from the client's point of view.

        if (useTransactionForUnitOfWork && isTransactionActive) {
            if (event.getContainerResponse().getStatus() < 400) {
                transactionManager.commitTransaction();
            } else {
                transactionManager.rollbackTransaction();
            }

            isTransactionActive = false;
        }
    } else if (eventType == RequestEvent.Type.ON_EXCEPTION) {

        // Rollback the transaction in case an exception is thrown from the resource method.

        if (useTransactionForUnitOfWork && isTransactionActive) {
            transactionManager.rollbackTransaction();
            isTransactionActive = false;
        }
    }
}
 
Example 12
Source File: SpanCustomizingApplicationEventListener.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public RequestEventListener onRequest(RequestEvent requestEvent) {
  if (requestEvent.getType() == RequestEvent.Type.START) return this;
  return null;
}
 
Example 13
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()));
}