Simulator.java

62 lines | 1.97 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 com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

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

    private static final Logger logger = Logger.getLogger(Simulator.class.getName());

    public static final void simulate(Profile profile, long time) {
        simulate(profile, time, 1);
    }

    public static final void simulate(Profile profile, long time, int users) {
        Collection<Thread> threads = new ArrayList<>();
        List<List<List<JsonObject>>> logs = new ArrayList<>();
        for (int i = 0; i < users; i++) {
            Thread thread = new Thread(() -> {
                profile.run(time);
                List<List<JsonObject>> profileLogs = profile.getLogs();
                logs.add(profileLogs);
            });
            threads.add(thread);
            thread.start();
        }
        threads.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException ex) {
                Logger.getLogger(Simulator.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
        String logPath = System.getenv("SIMULATOR_LOG_PATH");
        if (logPath != null) {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            try (Writer writer = new FileWriter(logPath)) {
                gson.toJson(logs, writer);
            } catch (IOException ex) {
                Logger.getLogger(Simulator.class.getName()).log(Level.SEVERE, "invalid log path");
            }
        }
    }
}