Session.java
Home
/
src /
main /
java /
br /
ufrgs /
inf /
prosoft /
requestssimulator /
Session.java
/*
* 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 java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Stream;
/**
*
* @author romulo
*/
public class Session {
private final Collection<RequestPlan> roots;
private final Map<String, String> storedValues;
private final List<Request> requests;
public Session(Collection<RequestPlan> roots) {
this.roots = roots;
this.storedValues = new HashMap<>();
this.requests = new ArrayList<>();
}
public Session(List<Request> requests) {
this.roots = null;
this.storedValues = new HashMap<>();
this.requests = requests;
}
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 Stream<Request> requests() {
return this.requests.stream();
}
public void simulate() {
Random random = new Random();
Request request = null;
int probability = 0;
while (probability < 70) {
try {
request = pickNextRequest(request);
} catch (RuntimeException ex) {
break;
}
request.fire();
this.requests.add(request);
probability = random.nextInt(100);
}
}
public void execute() {
this.requests.forEach(Request::fire);
}
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);
}
}