<commit_before>/**
 * Copyright 2017 Pivotal Software, Inc.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.jersey2.server;

import static java.util.Objects.requireNonNull;

import java.lang.reflect.AnnotatedElement;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.model.ResourceMethod;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;

import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.Timer.Builder;

/**
 * Micrometer {@link RequestEventListener} recording metrics for Jersey server
 * requests.
 * 
 * @author <NAME>
 */
public class MicrometerRequestEventListener implements RequestEventListener {

    private static final Logger log = Logger
            .getLogger(MicrometerRequestEventListener.class.getSimpleName());

    private static final Map<ContainerRequest, Long> longTaskTimerIds = Collections
            .synchronizedMap(new IdentityHashMap<>());

    private final MeterRegistry meterRegistry;

    private final JerseyTagsProvider tagsProvider;

    private final String metricName;

    private final boolean autoTimeRequests;

    private final boolean recordRequestPercentiles;

    private Long startTime;

    public MicrometerRequestEventListener(MeterRegistry meterRegistry,
            JerseyTagsProvider tagsProvider, String metricName, boolean autoTimeRequests,
            boolean recordRequestPercentiles) {
        this.meterRegistry = requireNonNull(meterRegistry);
        this.tagsProvider = requireNonNull(tagsProvider);
        this.metricName = requireNonNull(metricName);
        this.autoTimeRequests = autoTimeRequests;
        this.recordRequestPercentiles = recordRequestPercentiles;
    }

    @Override
    public void onEvent(RequestEvent event) {
        switch (event.getType()) {
        case ON_EXCEPTION:
            if (startTime == null) {
                startTime = Long.valueOf(System.nanoTime());
            }
            break;
        case REQUEST_MATCHED:
            if (startTime == null) {
                startTime = Long.valueOf(System.nanoTime());
            }
            timerConfigs(event, true).stream().forEach((config) -> {
                if (config.getName() == null) {
                    log.warning("Unable to perform metrics timing for request '"
                            + event.getUriInfo().getRequestUri()
                            + "': @Timed annotation must have a value used to name the metric");
                    return;
                }
                longTaskTimerIds.put(event.getContainerRequest(),
                        longTaskTimer(event, config).start());
            });
            break;
        case FINISHED:
            if (startTime != null) {
                final long duration = System.nanoTime() - startTime.longValue();

                // time the request
                timerConfigs(event, false).forEach((config) -> {
                    final Builder builder = timerBuilder(event, config);
                    builder.register(meterRegistry).record(duration, TimeUnit.NANOSECONDS);
                });

                // time any long running task
                timerConfigs(event, true).stream().forEach((config) -> {
                    final Long timerId = longTaskTimerIds.remove(event.getContainerRequest());
                    if (timerId != null) {
                        final LongTaskTimer longTaskTimer = longTaskTimer(event, config);
                        longTaskTimer.stop(timerId);
                    }
                });
            }
            break;
        default:
            break;
        }
    }

    private Set<TimerConfig> timerConfigs(RequestEvent event, boolean selectLongTasks) {
        final Set<Timed> annotations = annotations(event, selectLongTasks);
        final Set<TimerConfig> timerConfigs = annotations.stream().map(a -> timerConfig(a))
                .collect(Collectors.toSet());

        /*
         * 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 (timerConfigs.isEmpty() && autoTimeRequests) {
            timerConfigs.add(new TimerConfig(metricName, recordRequestPercentiles));
        }

        return timerConfigs;
    }

    private Set<Timed> annotations(RequestEvent event, boolean selectLongTasks) {
        final Set<Timed> timed = new HashSet<>();

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

            // fallback on class level
            if (timed.isEmpty()) {
                timed.addAll(annotations(matchingResourceMethod.getInvocable().getHandlingMethod()
                        .getDeclaringClass()));
            }
        }
        return timed.stream().filter(a -> a.longTask() == selectLongTasks)
                .collect(Collectors.toSet());
    }

    private Set<Timed> annotations(AnnotatedElement annotated) {
        final Timed[] annotations = annotated.getAnnotationsByType(Timed.class);
        if (annotations != null) {
            return new HashSet<Timed>(Arrays.asList(annotations));
        }
        return Collections.emptySet();
    }

    private TimerConfig timerConfig(Timed annotation) {
        return new TimerConfig(annotation, () -> metricName);
    }

    private Timer.Builder timerBuilder(RequestEvent event, TimerConfig config) {
        final Timer.Builder builder = Timer.builder(config.getName())
                .tags(this.tagsProvider.httpRequestTags(event)).tags(config.getExtraTags())
                .description("Timer of servlet request")
                .publishPercentileHistogram(config.isHistogram());
        if (config.getPercentiles().length > 0) {
            builder.publishPercentiles(config.getPercentiles());
        }
        return builder;
    }

    private LongTaskTimer longTaskTimer(RequestEvent event, TimerConfig config) {
        return LongTaskTimer.builder(config.getName())
                .tags(this.tagsProvider.httpLongRequestTags(event)).tags(config.getExtraTags())
                .description("Timer of long servlet request").register(meterRegistry);
    }

    /**
     * An adjusted copy from WebMvcMetrics. (Move to core?)
     */
    private static class TimerConfig {

        private final String name;

        private final Iterable<Tag> extraTags;

        private final double[] percentiles;

        private final boolean histogram;

        TimerConfig(String name, boolean histogram) {
            this.name = name;
            this.extraTags = Collections.emptyList();
            this.percentiles = new double[0];
            this.histogram = histogram;
        }

        TimerConfig(Timed timed, Supplier<String> name) {
            this.name = buildName(timed, name);<commit_msg>Guard against Jersey instrumentation bugs<commit_after>/**
 * Copyright 2017 Pivotal Software, Inc.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.jersey2.server;

import static java.util.Objects.requireNonNull;

import java.lang.reflect.AnnotatedElement;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.model.ResourceMethod;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;

import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.Timer.Builder;

/**
 * Micrometer {@link RequestEventListener} recording metrics for Jersey server
 * requests.
 * 
 * @author <NAME>
 */
public class MicrometerRequestEventListener implements RequestEventListener {

    private static final Logger log = Logger
            .getLogger(MicrometerRequestEventListener.class.getSimpleName());

    private static final Map<ContainerRequest, Long> longTaskTimerIds = Collections
            .synchronizedMap(new IdentityHashMap<>());

    private final MeterRegistry meterRegistry;

    private final JerseyTagsProvider tagsProvider;

    private final String metricName;

    private final boolean autoTimeRequests;

    private final boolean recordRequestPercentiles;

    private Long startTime;

    public MicrometerRequestEventListener(MeterRegistry meterRegistry,
            JerseyTagsProvider tagsProvider, String metricName, boolean autoTimeRequests,
            boolean recordRequestPercentiles) {
        this.meterRegistry = requireNonNull(meterRegistry);
        this.tagsProvider = requireNonNull(tagsProvider);
        this.metricName = requireNonNull(metricName);
        this.autoTimeRequests = autoTimeRequests;
        this.recordRequestPercentiles = recordRequestPercentiles;
    }

    @Override
    public void onEvent(RequestEvent event) {
        try {
            switch (event.getType()) {
            case ON_EXCEPTION:
                if (startTime == null) {
                    startTime = Long.valueOf(System.nanoTime());
                }
                break;
            case REQUEST_MATCHED:
                if (startTime == null) {
                    startTime = Long.valueOf(System.nanoTime());
                }
                timerConfigs(event, true).stream().forEach((config) -> {
                    if (config.getName() == null) {
                        logWarning(event,
                                "@Timed annotation must have a value used to name the metric",
                                null);
                        return;
                    }
                    longTaskTimerIds.put(event.getContainerRequest(),
                            longTaskTimer(event, config).start());
                });
                break;
            case FINISHED:
                if (startTime != null) {
                    final long duration = System.nanoTime() - startTime.longValue();

                    // time the request
                    timerConfigs(event, false).forEach((config) -> {
                        final Builder builder = timerBuilder(event, config);
                        builder.register(meterRegistry).record(duration, TimeUnit.NANOSECONDS);
                    });

                    // time any long running task
                    timerConfigs(event, true).stream().forEach((config) -> {
                        final Long timerId = longTaskTimerIds.remove(event.getContainerRequest());
                        if (timerId != null) {
                            final LongTaskTimer longTaskTimer = longTaskTimer(event, config);
                            longTaskTimer.stop(timerId);
                        }
                    });
                }
                break;
            default:
                break;
            }
        } catch (Exception e) {
            logWarning(event, "Unhandled instrumentation error", e);
        }
    }

    private Set<TimerConfig> timerConfigs(RequestEvent event, boolean selectLongTasks) {
        final Set<Timed> annotations = annotations(event, selectLongTasks);
        final Set<TimerConfig> timerConfigs = annotations.stream().map(a -> timerConfig(a))
                .collect(Collectors.toSet());

        /*
         * 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 (timerConfigs.isEmpty() && autoTimeRequests) {
            timerConfigs.add(new TimerConfig(metricName, recordRequestPercentiles));
        }

        return timerConfigs;
    }

    private Set<Timed> annotations(RequestEvent event, boolean selectLongTasks) {
        final Set<Timed> timed = new HashSet<>();

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

            // fallback on class level
            if (timed.isEmpty()) {
                timed.addAll(annotations(matchingResourceMethod.getInvocable().getHandlingMethod()
                        .getDeclaringClass()));
            }
        }
        return timed.stream().filter(a -> a.longTask() == selectLongTasks)
                .collect(Collectors.toSet());
    }

    private Set<Timed> annotations(AnnotatedElement annotated) {
        final Timed[] annotations = annotated.getAnnotationsByType(Timed.class);
        if (annotations != null) {
            return new HashSet<Timed>(Arrays.asList(annotations));
        }
        return Collections.emptySet();
    }

    private TimerConfig timerConfig(Timed annotation) {
        return new TimerConfig(annotation, () -> metricName);
    }

    private Timer.Builder timerBuilder(RequestEvent event, TimerConfig config) {
        final Timer.Builder builder = Timer.builder(config.getName())
                .tags(this.tagsProvider.httpRequestTags(event)).tags(config.getExtraTags())
                .description("Timer of servlet request")
                .publishPercentileHistogram(config.isHistogram());
        if (config.getPercentiles().length > 0) {
            builder.publishPercentiles(config.getPercentiles());
        }
        return builder;
    }

    private LongTaskTimer longTaskTimer(RequestEvent event, TimerConfig config) {
        return LongTaskTimer.builder(config.getName())
                .tags(this.tagsProvider.httpLongRequestTags(event)).tags(config.getExtraTags())
                .description("Timer of long servlet request").register(meterRegistry);
    }

    private void logWarning(RequestEvent event, String message, Throwable thrown) {
        final String uri = event.getUriInfo() != null && event.getUriInfo().getRequestUri() != null
                ? event.getUriInfo().getRequestUri().toString()
                : "unknown";
        log.log(Level.WARNING, "Failed timing request '" + uri + "': " + message, thrown);
    }

    /**
     * An adjusted copy from WebMvcMetrics. (Move to core?)
     */
    private static class TimerConfig {

        private final String name;

        private final Iterable<Tag> extraTags;

        private final double[] percentiles;

        private final boolean histogram;

        TimerConfig(String name, boolean histogram) {
            this.name = name;
            this.extraTags = Collections.emptyList();
            this.percentiles = new double[0];
            this.histogram = histogram;
        }

        TimerConfig(Timed timed, Supplier<String> name) {
            this.name = buildName(timed, name);
{'fraction_non_alphanumeric': 0.09276481254021174, 'fraction_numerical': 0.0016377142188688074, 'mean_word_length': 2.4464825639991936, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 49, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '988361', 'n_tokens_mistral': 4369, 'n_tokens_neox': 4143, 'n_words': 1034}