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()); }
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; }
@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 } }
@Override public void onEvent(final RequestEvent event) { if (event.getType() == RequestEvent.Type.RESOURCE_METHOD_START) { final UnitOfWork unitOfWork = this.methodMap.get(event.getUriInfo() .getMatchedResourceMethod().getInvocable().getDefinitionMethod()); this.unitOfWorkAspect.beforeStart(unitOfWork); } else if (event.getType() == RequestEvent.Type.RESP_FILTERS_START) { try { this.unitOfWorkAspect.afterEnd(); } catch (final Exception e) { throw new MappableException(e); } } else if (event.getType() == RequestEvent.Type.ON_EXCEPTION) { this.unitOfWorkAspect.onError(); } }
@Override public void onEvent(RequestEvent event) { switch (event.getType()) { case RESOURCE_METHOD_START: ExtendedUriInfo uriInfo = event.getUriInfo(); ResourceMethod method = uriInfo.getMatchedResourceMethod(); ContainerRequest containerRequest = event.getContainerRequest(); LOG.info(requestNumber+" Resource method " + method.getHttpMethod() + " started for request " + requestNumber); LOG.info(requestNumber+" Headers: "+ render(containerRequest.getHeaders())); LOG.info(requestNumber+" Path: "+uriInfo.getPath()); LOG.info(requestNumber+" PathParameters: "+ render(uriInfo.getPathParameters())); LOG.info(requestNumber+" QueryParameters: "+ render(uriInfo.getQueryParameters())); LOG.info(requestNumber+" Body: "+getBody(containerRequest)); break; case FINISHED: LOG.info("Request " + requestNumber + " finished. Processing time " + (System.currentTimeMillis() - startTime) + " ms."); break; default: break; } }
@Before public void setUp() throws SQLException, NoSuchMethodException { when(dataSource.getConnection()).thenReturn(connection); when(appEvent.getType()).thenReturn(ApplicationEvent.Type.INITIALIZATION_APP_FINISHED); when(requestFinishEvent.getType()).thenReturn(RequestEvent.Type.FINISHED); when(requestMethodExceptionEvent.getType()).thenReturn(RequestEvent.Type.ON_EXCEPTION); when(requestFinishEvent.getUriInfo()).thenReturn(uriInfo); when(requestMethodExceptionEvent.getUriInfo()).thenReturn(uriInfo); when(containerRequest.getProperty(ConfigurationFactory.CONNECTION_PROVIDER_PROPERTY)).thenReturn(connectionProvider); when(requestFinishEvent.getContainerRequest()).thenReturn(containerRequest); when(requestMethodExceptionEvent.getContainerRequest()).thenReturn(containerRequest); requestFinishEvent.getContainerRequest().getProperty(ConfigurationFactory.CONNECTION_PROVIDER_PROPERTY); }
@Override public void onEvent(RequestEvent event) { final RequestEvent.Type eventType = event.getType(); if (eventType == RequestEvent.Type.RESOURCE_METHOD_START) { UnitOfWork unitOfWork = methodMap.get(event.getUriInfo() .getMatchedResourceMethod().getInvocable().getDefinitionMethod()); unitOfWorkAspect.beforeStart(unitOfWork); } else if (eventType == RequestEvent.Type.RESP_FILTERS_START) { try { unitOfWorkAspect.afterEnd(); } catch (Exception e) { throw new MappableException(e); } } else if (eventType == RequestEvent.Type.ON_EXCEPTION) { unitOfWorkAspect.onError(); } else if (eventType == RequestEvent.Type.FINISHED) { EntityManagerContext.unBindAll(EntityManager::close); } }
@Test public void closesAnyEntityManagerBoundToTheContext() throws Exception { final EntityManager otherEntityManager = mock(EntityManager.class); final EntityManagerFactory otherEntityManagerFactory = mock(EntityManagerFactory.class); when(otherEntityManagerFactory.createEntityManager()).thenReturn(otherEntityManager); when(otherEntityManager.getEntityManagerFactory()).thenReturn(otherEntityManagerFactory); EntityManagerContext.bind(entityManager); EntityManagerContext.bind(otherEntityManager); doAnswer(invocation -> { assertThat(EntityManagerContext.hasBind(entityManagerFactory)).isTrue(); assertThat(EntityManagerContext.hasBind(otherEntityManagerFactory)).isTrue(); return RequestEvent.Type.RESOURCE_METHOD_START; }).when(requestMethodStartEvent).getType(); prepareAppEvent("methodNotAnnotated"); execute(); verify(entityManager).close(); verify(otherEntityManager).close(); assertThat(EntityManagerContext.hasBind(entityManagerFactory)).isFalse(); assertThat(EntityManagerContext.hasBind(otherEntityManagerFactory)).isFalse(); }
@Override public void onEvent(RequestEvent requestEvent) { switch (requestEvent.getType()) { case RESOURCE_METHOD_START: logger.info("Resource method started"); break; case FINISHED: logger.info("Resource method finished"); long endTime = System.currentTimeMillis(); logger.info("Time taken....{} ms.", endTime - startTime); break; } }
/** The req listener. */ /* * (non-Javadoc) * * @see * org.glassfish.jersey.server.monitoring.ApplicationEventListener#onRequest(org.glassfish.jersey.server.monitoring * .RequestEvent) */ @Override public RequestEventListener onRequest(RequestEvent requestEvent) { // Request start events are sent to application listener and not request listener if (RequestEvent.Type.START == requestEvent.getType()) { MetricsService metricsSvc = LensServices.get().getService(MetricsService.NAME); if (metricsSvc != null) { metricsSvc.incrCounter(LensRequestListener.class, LensRequestListener.HTTP_REQUESTS_STARTED); } } return new LensRequestListener(); }
@Before public void setUp() throws Exception { when(sessionFactory.openSession()).thenReturn(session); when(session.getSessionFactory()).thenReturn(sessionFactory); when(session.beginTransaction()).thenReturn(transaction); when(session.getTransaction()).thenReturn(transaction); when(transaction.isActive()).thenReturn(true); when(appEvent.getType()).thenReturn(ApplicationEvent.Type.INITIALIZATION_APP_FINISHED); when(requestMethodStartEvent.getType()).thenReturn(RequestEvent.Type.RESOURCE_METHOD_START); when(responseFiltersStartEvent.getType()).thenReturn(RequestEvent.Type.RESP_FILTERS_START); when(requestMethodExceptionEvent.getType()).thenReturn(RequestEvent.Type.ON_EXCEPTION); when(requestMethodStartEvent.getUriInfo()).thenReturn(uriInfo); when(responseFiltersStartEvent.getUriInfo()).thenReturn(uriInfo); when(requestMethodExceptionEvent.getUriInfo()).thenReturn(uriInfo); prepareAppEvent("methodWithDefaultAnnotation"); }
private static int statusCode(RequestEvent event) { Throwable exception = event.getException(); if (exception != null) { if (exception instanceof WebApplicationException) { return ((WebApplicationException) exception).getResponse().getStatus(); } return Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); } return event.getContainerResponse().getStatus(); }
private static String templatedUri(RequestEvent event) { final ExtendedUriInfo uriInfo = event.getUriInfo(); final List<UriTemplate> matchedTemplates = new ArrayList<>(uriInfo.getMatchedTemplates()); if (matchedTemplates.size() > 1) { Collections.reverse(matchedTemplates); } final StringBuilder sb = new StringBuilder(); sb.append(uriInfo.getBaseUri().getPath()); for (UriTemplate uriTemplate : matchedTemplates) { sb.append(uriTemplate.getTemplate()); } return sb.toString().replaceAll("//+", "/"); }
@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; } }
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()); }
private static RequestEvent event(String method, Integer status, Exception exception, String baseUri, String... uriTemplateStrings) { Builder builder = new RequestEventImpl.Builder(); ContainerRequest containerRequest = mock(ContainerRequest.class); when(containerRequest.getMethod()).thenReturn(method); 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); }
@Override public void onEvent(RequestEvent event) { switch (event.getType()) { case RESOURCE_METHOD_START: controller.increase(); break; case FINISHED: controller.decrease(); break; } }
@Override public RequestEventListener onRequest(RequestEvent event) { if (Timer.enabled()) { return new TimingRequestEventListener(nextReqId ++); } return null; }
@Override public void onEvent(RequestEvent event) { switch (event.getType()) { case ON_EXCEPTION: Throwable t = event.getException(); mLog.error(event.getType(), t); t.printStackTrace(); } }
@Before public void setUp() throws Exception { this.listener.registerBundle(RemoteCredentialHibernateBundle.DEFAULT_NAME, this.bundle); this.listener.registerBundle("analytics", this.analyticsBundle); final SessionHolders sessionHolders = mock(SessionHolders.class); when(this.bundle.getSessionHolders()).thenReturn(sessionHolders); when(this.analyticsBundle.getSessionHolders()).thenReturn(sessionHolders); when(this.bundle.getSessionFactory()).thenReturn(this.sessionFactory); when(this.analyticsBundle.getSessionFactory()) .thenReturn(this.analyticsSessionFactory); when(this.sessionFactory.openSession()).thenReturn(this.session); when(this.session.getSessionFactory()).thenReturn(this.sessionFactory); when(this.session.beginTransaction()).thenReturn(this.transaction); when(this.session.getTransaction()).thenReturn(this.transaction); when(this.transaction.isActive()).thenReturn(true); when(this.analyticsSessionFactory.openSession()).thenReturn(this.analyticsSession); when(this.analyticsSession.getSessionFactory()).thenReturn(this.analyticsSessionFactory); when(this.analyticsSession.beginTransaction()).thenReturn(this.analyticsTransaction); when(this.analyticsSession.getTransaction()).thenReturn(this.analyticsTransaction); when(this.analyticsTransaction.isActive()).thenReturn(true); when(this.appEvent.getType()).thenReturn(ApplicationEvent.Type.INITIALIZATION_APP_FINISHED); when(this.requestMethodStartEvent.getType()) .thenReturn(RequestEvent.Type.RESOURCE_METHOD_START); when(this.responseFiltersStartEvent.getType()) .thenReturn(RequestEvent.Type.RESP_FILTERS_START); when(this.requestMethodExceptionEvent.getType()).thenReturn(RequestEvent.Type.ON_EXCEPTION); when(this.requestMethodStartEvent.getUriInfo()).thenReturn(this.uriInfo); when(this.responseFiltersStartEvent.getUriInfo()).thenReturn(this.uriInfo); when(this.requestMethodExceptionEvent.getUriInfo()).thenReturn(this.uriInfo); this.prepareAppEvent("methodWithDefaultAnnotation"); }
@Override public void onEvent(RequestEvent event) { final RequestEvent.Type eventType = event.getType(); if (eventType == RequestEvent.Type.RESOURCE_METHOD_START) { Optional<UnitOfWork> unitOfWork = methodMap.computeIfAbsent(event.getUriInfo() .getMatchedResourceMethod(), UnitOfWorkEventListener::registerUnitOfWorkAnnotations); // get property whether to have unitOfWork with DB default transaction by default useTransactionForUnitOfWork = unitOfWork.isPresent() ? unitOfWork.get().transactional() : runWithTxnIfNotConfigured; TransactionIsolation transactionIsolation = unitOfWork.map(UnitOfWork::transactionIsolation) .orElse(TransactionIsolation.DEFAULT); if (useTransactionForUnitOfWork) { transactionManager.beginTransaction(transactionIsolation); isTransactionActive = true; } } else if (eventType == RequestEvent.Type.RESP_FILTERS_START) { // not supporting transactions to filters } else if (eventType == RequestEvent.Type.ON_EXCEPTION) { if (useTransactionForUnitOfWork && isTransactionActive) { transactionManager.rollbackTransaction(); isTransactionActive = false; } } else if (eventType == RequestEvent.Type.FINISHED) { if (useTransactionForUnitOfWork && event.isSuccess()) { transactionManager.commitTransaction(); isTransactionActive = false; } else if (useTransactionForUnitOfWork && !event.isSuccess() && isTransactionActive) { transactionManager.rollbackTransaction(); isTransactionActive = false; } } }
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { listener.registerEntityManagerFactory(EntityManagerBundle.DEFAULT_NAME, entityManagerFactory); listener.registerEntityManagerFactory("analytics", analyticsEntityManagerFactory); when(entityManagerFactory.createEntityManager()).thenReturn(entityManager); when(entityManager.getEntityManagerFactory()).thenReturn(entityManagerFactory); when(entityManager.getSession()).thenReturn(session); when(entityManager.getTransaction()).thenReturn(transaction); when(transaction.isActive()).thenReturn(true); when(analyticsEntityManagerFactory.createEntityManager()).thenReturn(analyticsEntityManager); when(analyticsEntityManager.getEntityManagerFactory()).thenReturn(analyticsEntityManagerFactory); when(analyticsEntityManager.getSession()).thenReturn(analyticsSession); when(analyticsEntityManager.getTransaction()).thenReturn(analyticsTransaction); when(analyticsTransaction.isActive()).thenReturn(true); when(appEvent.getType()).thenReturn(ApplicationEvent.Type.INITIALIZATION_APP_FINISHED); when(requestMethodStartEvent.getType()).thenReturn(RequestEvent.Type.RESOURCE_METHOD_START); when(responseFiltersStartEvent.getType()).thenReturn(RequestEvent.Type.RESP_FILTERS_START); when(responseFinishedEvent.getType()).thenReturn(RequestEvent.Type.FINISHED); when(requestMethodExceptionEvent.getType()).thenReturn(RequestEvent.Type.ON_EXCEPTION); when(requestMethodStartEvent.getUriInfo()).thenReturn(uriInfo); when(responseFiltersStartEvent.getUriInfo()).thenReturn(uriInfo); when(responseFinishedEvent.getUriInfo()).thenReturn(uriInfo); when(requestMethodExceptionEvent.getUriInfo()).thenReturn(uriInfo); prepareAppEvent("methodWithDefaultAnnotation"); }
@Override public void onEvent(final RequestEvent event) { switch (event.getType()) { case RESOURCE_METHOD_START: this.eventListener .getCircuitBreakerName(event.getUriInfo().getMatchedResourceMethod()) .ifPresent(actualCircuitName -> { if (this.circuitBreakerManager.isCircuitOpen(actualCircuitName)) { this.meterMap.get(actualCircuitName + OPEN_CIRCUIT_SUFFIX).mark(); log.warn("Circuit breaker open, returning 503 Service Unavailable: " + actualCircuitName + OPEN_CIRCUIT_SUFFIX); throw new WebApplicationException( Response.Status.SERVICE_UNAVAILABLE); } }); break; case ON_EXCEPTION: this.eventListener .getCircuitBreakerName(event.getUriInfo().getMatchedResourceMethod()) .ifPresent(actualCircuitName -> { if (!this.circuitBreakerManager.isCircuitOpen(actualCircuitName)) { this.meterMap.get(actualCircuitName).mark(); } }); break; default: break; } }
private MethodMetrics getMethodMetrics(RequestEvent event) { ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); if (method == null) { return null; } return this.metrics.get(method.getInvocable().getDefinitionMethod()); }
@Override public void onEvent(RequestEvent paramRequestEvent) { if (paramRequestEvent.getType() == Type.ON_EXCEPTION) { log.info("a REST call failed with an exception", paramRequestEvent.getException()); } }
@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; } }
@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); }
@Override public void onEvent(RequestEvent event) { switch (event.getType()){ case ON_EXCEPTION: Throwable t = event.getException(); logger.error("Found exception for requestType: "+event.getType(), t); } }
@Override public Iterable<Tag> httpRequestTags(RequestEvent event) { final int statusCode = statusCode(event); return Arrays.asList(method(event), uri(event, statusCode), status(statusCode), exception(event, statusCode)); }
@Override public Iterable<Tag> httpLongRequestTags(RequestEvent event) { return Arrays.asList(method(event), uri(event, 0)); }
private static Tag method(RequestEvent event) { final String httpMethod = event.getContainerRequest().getMethod(); return Tag.of(TAG_METHOD, httpMethod); }
@Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new MetricsRequestEventListener(meterRegistry, tagsProvider, metricName, autoTimeRequests, annotationFinder); }
@Override public RequestEventListener onRequest(RequestEvent requestEvent) { return null; }
@Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new APIxRequestEventListener(); }
@Override public synchronized RequestEventListener onRequest(RequestEvent requestEvent) { return null; }
@Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new ExceptionRequestEventListener(); }
@Override public RequestEventListener onRequest(final RequestEvent event) { return new UnitOfWorkEventListener(this.methodMap, this.bundles); }
@Override public RequestEventListener onRequest(RequestEvent requestEvent) { return null; // no request processing }
@Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new UnitOfWorkEventListener(methodMap, transactionManager, runWithTxnIfNotConfigured); }