001/*
002 * The contents of this file are subject to the license and copyright
003 * detailed in the LICENSE and NOTICE files at the root of the source
004 * tree.
005 */
006package org.fcrepo.http.commons.metrics;
007
008import io.micrometer.core.instrument.MeterRegistry;
009import io.micrometer.jersey2.server.DefaultJerseyTagsProvider;
010import io.micrometer.jersey2.server.MetricsApplicationEventListener;
011import org.springframework.web.context.support.WebApplicationContextUtils;
012
013import javax.servlet.ServletContext;
014import javax.ws.rs.core.Context;
015import javax.ws.rs.core.Feature;
016import javax.ws.rs.core.FeatureContext;
017
018/**
019 * Enables Micrometer metrics on Jersey APIs (still must be annotated with @Timed)
020 *
021 * @author pwinckles
022 */
023public class MicrometerFeature implements Feature {
024
025    @Context
026    private ServletContext servletContext;
027
028    @Override
029    public boolean configure(final FeatureContext context) {
030        if (this.servletContext == null) {
031            return false;
032        }
033        final var appCtx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
034        if (appCtx == null) {
035            return false;
036        }
037
038        final var registry = appCtx.getBean(MeterRegistry.class);
039
040        final var micrometerListener = new MetricsApplicationEventListener(
041                registry,
042                new DefaultJerseyTagsProvider(),
043                "http.server.requests",
044                false);
045
046        context.register(micrometerListener);
047
048        return true;
049    }
050
051}