Simulator.java

80 lines | 2.464 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) {
        simulate(profile, time, users, null);
    }

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

    public static final void simulate(Profile profile, long time, int users, String logPath) {
        Collection<Thread> threads = new ArrayList<>();
        List<List<List<JsonObject>>> logs = new ArrayList<>();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                writeLog(logPath, logs);
            }
        });
        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.log(Level.SEVERE, null, ex);
            }
        });
        writeLog(logPath, logs);
    }

    private static void writeLog(String logPath, List<List<List<JsonObject>>> logs) {
        if (logPath != null) {
            LOGGER.log(Level.INFO, "writing log");
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            try (Writer writer = new FileWriter(logPath)) {
                gson.toJson(logs, writer);
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, "invalid log path");
            }
        }
    }
}