Résultats CPD

Le document suivant contient les résultats de l'inspection CPD CPD 7.7.0.

Duplicatas

Fichier Projet Ligne
fr/agroclim/sava/jakarta/SavaFilter.java SAVA library for Jakarta 24
fr/agroclim/sava/javaee/SavaFilter.java SAVA library for Java EE 24
@Log4j2
@WebFilter(filterName = SavaFilter.NAME, //
urlPatterns = {"/*"}, //
initParams = {//
        @WebInitParam(name = "http.request.precision", value = "min"), //
        @WebInitParam(name = "http.request.buckets", value = "0.0001;0.0005;0.001;0.005;0.01;0.1;1") //
})
public class SavaFilter implements Filter {

    /**
     * The name of the filter.
     */
    public static final String NAME = "SAVA_FILTER";

    /**
     * To setup buckets, assign values separated by ";" with this key.
     */
    public static final String PARAM_BUCKETS = "http.request.buckets";

    /**
     * To setup precision (application scoped or server scoped), assign a value (max or min) with this key.
     *
     * Default value is "min" (only label is after the context path).
     */
    public static final String PARAM_PATH_PRECISION = "http.request.precision";

    /**
     * Http request histogram collector.
     */
    private Histogram histogram;

    /**
     * Path precision.
     */
    private PathPrecision pathPrecision = PathPrecision.MIN;

    @Override
    public void destroy() {
        // Nothing to do.
    }

    /**
     * Time and register by method and path every request that come to any servlet
     * of the application. These values are next exposed on the /metrics servlet
     * with the name "http_request".
     */
    @Override
    public final void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain filterChain)
            throws IOException, ServletException {
        Timer timer = null;
        if (req instanceof HttpServletRequest) {
            final HttpServletRequest httpRequest = (HttpServletRequest) req;
            String path = httpRequest.getServletPath();
            if (PathPrecision.MIN.equals(pathPrecision)) {
                final String cp = httpRequest.getContextPath();
                path = httpRequest.getRequestURI().substring(cp.length());
            }
            timer = histogram.labelValues(path, httpRequest.getMethod()).startTimer();
        }
        filterChain.doFilter(req, resp);
        if (timer != null) {
            timer.close();
        }
    }

    @Override
    public final void init(final FilterConfig filterConfig) throws ServletException {
        double[] buckets = new double[0];
        if (filterConfig.getInitParameter(PARAM_BUCKETS) != null
                && !filterConfig.getInitParameter(PARAM_BUCKETS).isEmpty()) {
            final String[] bucketString = filterConfig.getInitParameter(PARAM_BUCKETS).split(";");
            buckets = new double[bucketString.length];
            for (int i = 0; i < buckets.length; i++) {
                try {
                    buckets[i] = Double.parseDouble(bucketString[i]);
                } catch (final NumberFormatException e) {
                    LOGGER.error("{} {} has no double value. Couldn't initialize SavaFilter.", PARAM_BUCKETS,
                            bucketString[i]);
                    LOGGER.catching(e);
                    buckets = new double[0];
                    break;
                }
            }
        }
        final var precisionValue = filterConfig.getInitParameter(PARAM_PATH_PRECISION);
        if (precisionValue != null) {
            pathPrecision = PathPrecision.valueOf(precisionValue.toUpperCase());
        }
        histogram = SavaUtils.addHistogram("http_requests", "Time and register every http request.", buckets, "path",
                "method");
    }

    /**
     * Precision of stored path.
     */
    private enum PathPrecision {
        /**
         * To get servlet path.
         */
        MIN,
        /**
         * To get request URI, without servlet context.
         */
        MAX;
    }

}
Fichier Projet Ligne
fr/agroclim/sava/jakarta/MetricsBasicAuthServlet.java SAVA library for Jakarta 20
fr/agroclim/sava/javaee/MetricsBasicAuthServlet.java SAVA library for Java EE 20
@Log4j2
public class MetricsBasicAuthServlet extends PrometheusMetricsServlet {

    /**
     * UID.
     */
    private static final long serialVersionUID = 8287757024145960994L;

    /**
     * Key, coming from context.
     */
    private String key = null;

    /**
     * Pass, coming from context.
     */
    private String pass = null;

    /**
     * Initialize values to key and pass, coming from context init parameters.
     * @exception ServletException if an exception occurs that interrupts the servlet's normal operation
     */
    @Override
    public void init() throws ServletException {
        super.init();
        key = getServletContext().getInitParameter("sava.key");
        pass = getServletContext().getInitParameter("sava.pass");
        if (key == null || pass == null) {
            throw new ServletException(
                    "SAVA context value ('sava.key', 'sava.pass') were not set. "
                            + "SAVA /metrics servlet cannot be initialized");
        }
        // init values and JVM gauges
        SavaUtils.addDefaultMetrics();
        SavaUtils.addCounter("tomcat_version", "Version number of Tomcat", "", "version");
        final String info = getServletContext().getServerInfo();
        SavaUtils.incrementCounter("tomcat_version", info);
        SavaUtils.addCounter("run_since", "Server run date", "", "instant");
        SavaUtils.incrementCounter("run_since", LocalDateTime.now().toString());
    }

    /**
     * doGet with simple authentification.
     *
     * @param req   an {@link HttpServletRequest} object that contains the request the client has made of the servlet
     * @param resp  an {@link HttpServletResponse} object that contains the response the servlet sends to the client
     * @exception IOException   if an input or output error is detected when the servlet handles the GET request or if
     * the request for the GET could not be handled
     */
    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
        // basic_auth associate to the request a header "Authorization"
        if (req.getHeader("Authorization") != null) {
            // credentials are encoded in Base64, prefixed with "Basic " removing the prefix
            final String trimmed = req.getHeader("Authorization").replace("Basic ", "");
            if (trimmed.isBlank()) {
                resp.getWriter().write("Missing value for 'Authorization Basic'.");
                resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            // decoding the sentence
            final byte[] decodedBytes = Base64.getDecoder().decode(trimmed);
            final String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
            // the credentials are given in the form username:password splitting the sentence
            final String[] decodedSplitted = decoded.split(":");
            // making the checks
            if (decodedSplitted.length == 2 && key.equals(decodedSplitted[0])
                    && pass.equals(decodedSplitted[1])) {
                SavaUtils.actuateJvmValues();
                // continue with the servlet
                super.doGet(req, resp);
                return;
            }
        }
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
    }

    /**
     * doPost with simple authentification.
     *
     * @param req   an {@link HttpServletRequest} object that contains the request the client has made of the servlet
     * @param resp  an {@link HttpServletResponse} object that contains the response the servlet sends to the client
     * @exception IOException   if an input or output error is detected when the servlet handles the GET request or if
     * the request for the GET could not be handled
     */
    @Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}