Session.java

84 lines | 2.448 kB Blame History Raw Download
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufrgs.inf.prosoft.requestssimulator;

import br.ufrgs.inf.prosoft.requestssimulator.requests.Request;
import br.ufrgs.inf.prosoft.requestssimulator.requests.RequestPlan;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 *
 * @author romulo
 */
public class Session {

    private final Collection<RequestPlan> roots;
    private final Map<String, String> storedValues;
    private List<JsonObject> logs;

    public Session(Collection<RequestPlan> roots) {
        this.roots = roots;
        this.storedValues = new HashMap<>();
    }

    public Session storeValue(String field, String value) {
        this.storedValues.put(field, value);
        return this;
    }

    public String getStoredValue(String storedField) {
        return this.storedValues.get(storedField);
    }

    public List<JsonObject> getLogs() {
        return logs;
    }

    public void run() {
        this.logs = new ArrayList<>();
        Random random = new Random();
        Request request = null;
        int probability = 0;
        while (probability < 70) {
            try {
                request = pickNextRequest(request);
            } catch (RuntimeException ex) {
                break;
            }
            request.fire();
            JsonObject logRequest = request.toJsonObject();
            this.logs.add(logRequest);
            probability = random.nextInt(100);
        }
    }

    public Request pickNextRequest(Request currentRequest) {
        if (currentRequest == null) {
            if (this.roots == null || this.roots.isEmpty()) {
                throw new RuntimeException("root within cycle");
            }
            if (this.roots.size() == 1) {
                RequestPlan requestPlan = this.roots.stream().findAny().get();
                try {
                    return requestPlan.build(this);
                } catch (RuntimeException ex) {
                    return requestPlan.pickNextRequest(this);
                }
            }
            currentRequest = RequestPlan.get("root")
                    .addLinks(this.roots)
                    .build(this);
        }
        return currentRequest.pickNextRequest(this);
    }
}