protected Insight doEvaluateRequest()

in core/src/main/java/org/apache/sling/cms/core/insights/impl/providers/PageSpeedInsightProvider.java [84:130]


    protected Insight doEvaluateRequest(InsightRequest request) throws Exception {
        Insight insight = new Insight(this, request);
        PageInsightRequest pageRequest = (PageInsightRequest) request;
        String publishedUrl = pageRequest.getPage().getPublishedUrl();
        String checkUrl = String.format(REQUEST_FORMAT, URLEncoder.encode(publishedUrl, "UTF-8"), PARAMETERS,
                config.apikey());

        HttpGet httpGet = new HttpGet(checkUrl);

        CloseableHttpResponse response = null;
        JsonReader reader = null;
        try (CloseableHttpClient client = HttpClients.createDefault()) {

            I18NDictionary dictionary = i18nProvider.getDictionary(request.getResource().getResourceResolver());

            log.debug("Requesting page speed via: {}", checkUrl);
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            reader = Json.createReader(new StringReader(EntityUtils.toString(entity)));
            JsonObject resp = reader.readObject();

            log.debug("Retrieved response: {}", resp);

            insight.setScored(true);
            double score = resp.getJsonObject("ruleGroups").getJsonObject("SPEED").getJsonNumber("score").doubleValue()
                    / 100.0;
            insight.setScore(score);
            log.debug("Parsed pagespeed score {}", score);

            if (score < 0.65) {
                insight.setPrimaryMessage(Message.danger(dictionary.get(MESSAGE_RESULT_DANGER)));
            } else if (score < 0.8) {
                insight.setPrimaryMessage(Message.warn(dictionary.get(MESSAGE_RESULT_WARN)));
            } else {
                insight.setPrimaryMessage(Message.success(dictionary.get(MESSAGE_RESULT_SUCCESS)));
            }
            insight.setMoreDetailsLink(String.format(PAGESPEED_FORMAT, URLEncoder.encode(publishedUrl, "UTF-8")));

            log.debug("Response parsed successfully");

        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return insight;
    }