All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.devsecops.engine.domain.sonar.utils.SonarMeasureMapper Maven / Gradle / Ivy

There is a newer version: 3.4.0
Show newest version
package io.github.devsecops.engine.domain.sonar.utils;

import io.github.devsecops.engine.domain.sonar.model.Metric;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Map;
import java.util.Optional;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toMap;

public class SonarMeasureMapper {

    private static final Integer NOT_FOUND_VALUE = -1;

    public Map toMeasures(final String response) {
        final JSONArray measuresJsonArray = new JSONObject(response)
                .getJSONObject("component")
                .getJSONArray("measures");
        return asList(Metric.values())
                .stream()
                .collect(toMap(i -> i, metric -> getMetricValue(metric, measuresJsonArray)));
    }

    private Integer getMetricValue(final Metric metric, final JSONArray measuresJsonArray) {
        return getStringMetricValue(metric, measuresJsonArray)
                .map(value -> toInteger(metric, value))
                .orElse(NOT_FOUND_VALUE);
    }

    private Optional getStringMetricValue(final Metric metric, final JSONArray measuresJsonArray) {
        for (int i = 0; i < measuresJsonArray.length(); i++) {
            final JSONObject jsonObject = measuresJsonArray.getJSONObject(i);
            final String currentMetric = jsonObject.getString("metric");
            if (metric.getName().equals(currentMetric)) {
                final String output = jsonObject.getString("value");
                return Optional.of(output.trim());
            }
        }
        return Optional.empty();
    }

    private Integer toInteger(Metric metric, String value) {
        switch (metric.getType()) {
            case INTEGER:
                return Integer.valueOf(value);
            case DOUBLE:
            case RATING:
                return (int) Double.parseDouble(value);
            default:
                return NOT_FOUND_VALUE;
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy