<commit_before>package edu.kit.ipd.crowdcontrol.objectservice.rest.resources;

import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.*;
import edu.kit.ipd.crowdcontrol.objectservice.database.operations.*;
import edu.kit.ipd.crowdcontrol.objectservice.database.transforms.AnswerRatingTransform;
import edu.kit.ipd.crowdcontrol.objectservice.database.transforms.ExperimentTransform;
import edu.kit.ipd.crowdcontrol.objectservice.database.transforms.TagConstraintTransform;
import edu.kit.ipd.crowdcontrol.objectservice.proto.*;
import edu.kit.ipd.crowdcontrol.objectservice.proto.Answer;
import edu.kit.ipd.crowdcontrol.objectservice.proto.Experiment;
import edu.kit.ipd.crowdcontrol.objectservice.proto.Rating;
import edu.kit.ipd.crowdcontrol.objectservice.rest.Paginated;
import edu.kit.ipd.crowdcontrol.objectservice.rest.exceptions.BadRequestException;
import edu.kit.ipd.crowdcontrol.objectservice.rest.exceptions.InternalServerErrorException;
import edu.kit.ipd.crowdcontrol.objectservice.rest.exceptions.NotFoundException;
import spark.Request;
import spark.Response;

import java.util.*;
import java.util.stream.Collectors;

import static edu.kit.ipd.crowdcontrol.objectservice.rest.RequestUtil.getParamInt;
import static edu.kit.ipd.crowdcontrol.objectservice.rest.RequestUtil.getQueryBool;
import static edu.kit.ipd.crowdcontrol.objectservice.rest.RequestUtil.getQueryInt;

/**
 * Created by marcel on 25.01.16.
 */
public class ExperimentResource {
    private final ExperimentOperations experimentOperations;
    private final AnswerRatingOperations answerRatingOperations;
    private final CalibrationOperations calibrationOperations;
    private final TagConstraintsOperations tagConstraintsOperations;
    private final WorkerOperations workerOperations;
    private final PlatformOperations platformOperations;

    public ExperimentResource(ExperimentOperations experimentOperations, AnswerRatingOperations answerRatingOperations, CalibrationOperations calibrationOperations, TagConstraintsOperations tagConstraintsOperations, WorkerOperations workerOperations, PlatformOperations platformOperations) {
        this.experimentOperations = experimentOperations;
        this.answerRatingOperations = answerRatingOperations;
        this.calibrationOperations = calibrationOperations;
        this.tagConstraintsOperations = tagConstraintsOperations;
        this.workerOperations = workerOperations;
        this.platformOperations = platformOperations;
    }

    /**
     * get the value of a optional or end with a NotFoundException
     * @param c The optional to unbox
     * @param <U> The typ which should be in the optional
     * @return The type which was in the optional
     */
    private <U> U R(Optional<U> c) {
        return c.orElseThrow(() -> new NotFoundException("Resource not found!"));
    }

    /**
     * List all experiments
     * @param request  Request provided by Spark.
     * @param response Response provided by Spark.
     * @return 20 experiments
     */
    public Paginated<Integer> all(Request request, Response response) {
        int from = getQueryInt(request, "from", 0);
        boolean asc = getQueryBool(request, "asc", true);

        return experimentOperations.getExperimentsFrom(from, asc, 20)
                .map(experimentRecord -> {
                    Experiment.State state = Experiment.State.DRAFT;
                    return ExperimentTransform.toProto(experimentRecord, state,
                            Collections.emptyList(),
                            Collections.emptyList(),
                            Collections.emptyList());
                })
                .constructPaginated(ExperimentList.newBuilder(),ExperimentList.Builder::addAllItems);
    }

    private List<ExperimentsCalibrationRecord> convertToRecords(Experiment experiment) {
        List<Experiment.PlatformPopulation> calibrations = experiment.getPlatformPopulationsList();
        List<ExperimentsCalibrationRecord> result = new ArrayList<>();

        calibrations.forEach(platformCalibrations ->
                platformCalibrations.getPopulationsList().forEach(calibration -> {

                    //check if this calibration exists
                    if (!calibrationOperations.getCalibration(calibration.getId()).isPresent())
                        throw new IllegalArgumentException("Calibration "+calibration.getId()+" does not exists");

                    //go through all possible answers and add them
                    calibration.getAcceptedAnswersList().forEach(s ->
                    {
                        ExperimentsCalibrationRecord pops = new ExperimentsCalibrationRecord(null, experiment.getId(),
                                R(calibrationOperations.getCalibrationAnswerOptionFromCalibrations(
                                        calibration.getId(), s))
                                        .getIdCalibrationAnswerOption(),
                                platformCalibrations.getPlatformId()+"", false); /*FIXME*/
                        result.add(pops);
                    });

                })
        );

        return result;
    }

    /**
     * Create a new experiment
     * @param request  Request provided by Spark.
     * @param response Response provided by Spark.
     * @return The new created experiment
     */
    public Experiment put(Request request, Response response) {
        Experiment experiment = request.attribute("input");

        ExperimentRecord record = ExperimentTransform.toRecord(experiment);
        List<TagRecord> tags = TagConstraintTransform.getTags(experiment);
        List<ConstraintRecord> constraints = TagConstraintTransform.getConstraints(experiment);
        List<ExperimentsCalibrationRecord> calibrations = convertToRecords(experiment);

        int id = experimentOperations.insertNewExperiment(record);

        tags = tags.stream()<commit_msg>experimentresource: use real state<commit_after>package edu.kit.ipd.crowdcontrol.objectservice.rest.resources;

import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records.*;
import edu.kit.ipd.crowdcontrol.objectservice.database.operations.*;
import edu.kit.ipd.crowdcontrol.objectservice.database.transforms.AnswerRatingTransform;
import edu.kit.ipd.crowdcontrol.objectservice.database.transforms.ExperimentTransform;
import edu.kit.ipd.crowdcontrol.objectservice.database.transforms.TagConstraintTransform;
import edu.kit.ipd.crowdcontrol.objectservice.proto.*;
import edu.kit.ipd.crowdcontrol.objectservice.proto.Answer;
import edu.kit.ipd.crowdcontrol.objectservice.proto.Experiment;
import edu.kit.ipd.crowdcontrol.objectservice.proto.Rating;
import edu.kit.ipd.crowdcontrol.objectservice.rest.Paginated;
import edu.kit.ipd.crowdcontrol.objectservice.rest.exceptions.BadRequestException;
import edu.kit.ipd.crowdcontrol.objectservice.rest.exceptions.InternalServerErrorException;
import edu.kit.ipd.crowdcontrol.objectservice.rest.exceptions.NotFoundException;
import spark.Request;
import spark.Response;

import java.util.*;
import java.util.stream.Collectors;

import static edu.kit.ipd.crowdcontrol.objectservice.rest.RequestUtil.getParamInt;
import static edu.kit.ipd.crowdcontrol.objectservice.rest.RequestUtil.getQueryBool;
import static edu.kit.ipd.crowdcontrol.objectservice.rest.RequestUtil.getQueryInt;

/**
 * Created by marcel on 25.01.16.
 */
public class ExperimentResource {
    private final ExperimentOperations experimentOperations;
    private final AnswerRatingOperations answerRatingOperations;
    private final CalibrationOperations calibrationOperations;
    private final TagConstraintsOperations tagConstraintsOperations;
    private final WorkerOperations workerOperations;
    private final PlatformOperations platformOperations;

    public ExperimentResource(ExperimentOperations experimentOperations, AnswerRatingOperations answerRatingOperations, CalibrationOperations calibrationOperations, TagConstraintsOperations tagConstraintsOperations, WorkerOperations workerOperations, PlatformOperations platformOperations) {
        this.experimentOperations = experimentOperations;
        this.answerRatingOperations = answerRatingOperations;
        this.calibrationOperations = calibrationOperations;
        this.tagConstraintsOperations = tagConstraintsOperations;
        this.workerOperations = workerOperations;
        this.platformOperations = platformOperations;
    }

    /**
     * get the value of a optional or end with a NotFoundException
     * @param c The optional to unbox
     * @param <U> The typ which should be in the optional
     * @return The type which was in the optional
     */
    private <U> U R(Optional<U> c) {
        return c.orElseThrow(() -> new NotFoundException("Resource not found!"));
    }

    /**
     * List all experiments
     * @param request  Request provided by Spark.
     * @param response Response provided by Spark.
     * @return 20 experiments
     */
    public Paginated<Integer> all(Request request, Response response) {
        int from = getQueryInt(request, "from", 0);
        boolean asc = getQueryBool(request, "asc", true);

        return experimentOperations.getExperimentsFrom(from, asc, 20)
                .map(experimentRecord -> ExperimentTransform.toProto(experimentRecord,
                        experimentOperations.getExperimentState(experimentRecord.getIdExperiment()),
                        Collections.emptyList(),
                        Collections.emptyList(),
                        Collections.emptyList()))
                .constructPaginated(ExperimentList.newBuilder(),ExperimentList.Builder::addAllItems);
    }

    private List<ExperimentsCalibrationRecord> convertToRecords(Experiment experiment) {
        List<Experiment.PlatformPopulation> calibrations = experiment.getPlatformPopulationsList();
        List<ExperimentsCalibrationRecord> result = new ArrayList<>();

        calibrations.forEach(platformCalibrations ->
                platformCalibrations.getPopulationsList().forEach(calibration -> {

                    //check if this calibration exists
                    if (!calibrationOperations.getCalibration(calibration.getId()).isPresent())
                        throw new IllegalArgumentException("Calibration "+calibration.getId()+" does not exists");

                    //go through all possible answers and add them
                    calibration.getAcceptedAnswersList().forEach(s ->
                    {
                        ExperimentsCalibrationRecord pops = new ExperimentsCalibrationRecord(null, experiment.getId(),
                                R(calibrationOperations.getCalibrationAnswerOptionFromCalibrations(
                                        calibration.getId(), s))
                                        .getIdCalibrationAnswerOption(),
                                platformCalibrations.getPlatformId()+"", false); /*FIXME*/
                        result.add(pops);
                    });
                })
        );

        return result;
    }

    /**
     * Create a new experiment
     * @param request  Request provided by Spark.
     * @param response Response provided by Spark.
     * @return The new created experiment
     */
    public Experiment put(Request request, Response response) {
        Experiment experiment = request.attribute("input");

        ExperimentRecord record = ExperimentTransform.toRecord(experiment);
        List<TagRecord> tags = TagConstraintTransform.getTags(experiment);
        List<ConstraintRecord> constraints = TagConstraintTransform.getConstraints(experiment);
        List<ExperimentsCalibrationRecord> calibrations = convertToRecords(experiment);

        int id = experimentOperations.insertNewExperiment(record);

        tags = tags.stream()
{'fraction_non_alphanumeric': 0.08177589852008457, 'fraction_numerical': 0.0018604651162790699, 'mean_word_length': 3.204052612868823, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '22311', 'n_tokens_mistral': 2946, 'n_tokens_neox': 2855, 'n_words': 588}