<commit_before>package com.github.dreamhead.moco.handler.failover;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.github.dreamhead.moco.HttpRequest;
import com.github.dreamhead.moco.model.*;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.collect.ImmutableList.of;
import static com.google.common.collect.Iterables.tryFind;

public class DefaultFailover implements Failover {
    private static final Logger logger = LoggerFactory.getLogger(DefaultFailover.class);
    private final TypeFactory factory = TypeFactory.defaultInstance();
    private final ObjectMapper mapper = new ObjectMapper();
    private final File file;

    public DefaultFailover(File file) {
        this.file = file;
    }

    public void onCompleteResponse(FullHttpRequest request, FullHttpResponse response) {
        try {
            ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
            Session targetSession = Session.newSession(MessageFactory.createRequest(request), MessageFactory.createResponse(response));
            writer.writeValue(this.file, prepareTargetSessions(targetSession));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private ImmutableList<Session> prepareTargetSessions(Session targetSession) {
        if (file.length() == 0) {
            return of(targetSession);
        }

        ImmutableList<Session> sessions = restoreSessions(this.file);
        Optional<Session> session = tryFind(sessions, isForRequest(targetSession.getRequest()));
        if (session.isPresent()) {
            session.get().setResponse(targetSession.getResponse());
            return sessions;
        }

        ImmutableList.Builder<Session> builder = ImmutableList.builder();
        return builder.addAll(sessions).add(targetSession).build();
    }

    private ImmutableList<Session> restoreSessions(File file) {
        try {
            List<Session> sessions = mapper.readValue(file, factory.constructCollectionType(List.class, Session.class));
            return copyOf(sessions);
        } catch (JsonMappingException jme) {
            logger.error("exception found", jme);
            return of();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void failover(FullHttpRequest request, FullHttpResponse response) {
        Response dumpedResponse = failoverResponse(request);
        response.setProtocolVersion(HttpVersion.valueOf(dumpedResponse.getVersion()));
        response.setStatus(HttpResponseStatus.valueOf(dumpedResponse.getStatusCode()));<commit_msg>removed session setter usage in default failover<commit_after>package com.github.dreamhead.moco.handler.failover;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.github.dreamhead.moco.HttpRequest;
import com.github.dreamhead.moco.model.HttpRequestFailoverMatcher;
import com.github.dreamhead.moco.model.MessageFactory;
import com.github.dreamhead.moco.model.Response;
import com.github.dreamhead.moco.model.Session;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.google.common.base.Predicates.not;
import static com.google.common.collect.FluentIterable.from;
import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.collect.ImmutableList.of;
import static com.google.common.collect.Iterables.tryFind;

public class DefaultFailover implements Failover {
    private static final Logger logger = LoggerFactory.getLogger(DefaultFailover.class);
    private final TypeFactory factory = TypeFactory.defaultInstance();
    private final ObjectMapper mapper = new ObjectMapper();
    private final File file;

    public DefaultFailover(File file) {
        this.file = file;
    }

    public void onCompleteResponse(FullHttpRequest request, FullHttpResponse response) {
        try {
            ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
            Session targetSession = Session.newSession(MessageFactory.createRequest(request), MessageFactory.createResponse(response));
            writer.writeValue(this.file, prepareTargetSessions(targetSession));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private ImmutableList<Session> prepareTargetSessions(Session targetSession) {
        if (file.length() == 0) {
            return of(targetSession);
        }

        return ImmutableList.<Session>builder().addAll(toUniqueSessions(targetSession, restoreSessions(this.file))).add(targetSession).build();
    }

    private Iterable<Session> toUniqueSessions(Session targetSession, ImmutableList<Session> sessions) {
        Optional<Session> session = tryFind(sessions, isForRequest(targetSession.getRequest()));
        if (session.isPresent()) {
            return from(sessions).filter(not(isForRequest(targetSession.getRequest())));
        }

        return sessions;
    }

    private ImmutableList<Session> restoreSessions(File file) {
        try {
            List<Session> sessions = mapper.readValue(file, factory.constructCollectionType(List.class, Session.class));
            return copyOf(sessions);
        } catch (JsonMappingException jme) {
            logger.error("exception found", jme);
            return of();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void failover(FullHttpRequest request, FullHttpResponse response) {
        Response dumpedResponse = failoverResponse(request);
        response.setProtocolVersion(HttpVersion.valueOf(dumpedResponse.getVersion()));
        response.setStatus(HttpResponseStatus.valueOf(dumpedResponse.getStatusCode()));
{'fraction_non_alphanumeric': 0.0985635044801593, 'fraction_numerical': 0.0008533636751528943, 'mean_word_length': 3.997867803837953, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 8}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2148315', 'n_tokens_mistral': 1915, 'n_tokens_neox': 1848, 'n_words': 351}