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.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* @author romulo
*/
public class Session {
private static final Logger LOGGER = Logger.getLogger(Session.class.getName());
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) {
Pattern pattern = Pattern.compile("\\[(.*?)]");
Matcher matcher = pattern.matcher(storedField);
while (matcher.find()) {
String found = matcher.group();
storedField = storedField.replace(found, "[$]");
}
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) {
LOGGER.log(Level.SEVERE, ex.getMessage());
break;
}
request.fire();
this.requests.add(request);
probability = random.nextInt(100);
}
}
public void execute() {
for (Iterator<Request> iterator = this.requests.iterator(); iterator.hasNext(); ) {
Request request = iterator.next();
request.fire();
iterator.remove();
}
}
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);
}
}