Skip to content

Instantly share code, notes, and snippets.

@noobmobile
Created October 15, 2019 13:43
Show Gist options
  • Save noobmobile/e8bc200f49a92ad633ec90d245aeedbd to your computer and use it in GitHub Desktop.
Save noobmobile/e8bc200f49a92ad633ec90d245aeedbd to your computer and use it in GitHub Desktop.
Evento matemático, realizar expressões aritméticas por comando. Feito usando engine do javascript e em async
package com.cloudcraft.beta;
import java.util.concurrent.ExecutionException;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.libs.joptsimple.internal.Strings;
import com.cloudcraft.beta.Calculator.CalculadoraException;
public class CalcCommand implements CommandExecutor{
public CalcCommand(Main main) {
main.getCommand("calc").setExecutor(this);
}
@Override
public boolean onCommand(CommandSender sender, Command commands, String arg2, String[] args) {
String expression = Strings.join(args, " ");
sender.sendMessage("§e-----------");
sender.sendMessage("§eCalculando: §f"+expression);
long now = System.currentTimeMillis();
try {
double result = Calculator.getInstance().calculate(expression);
long after = System.currentTimeMillis();
sender.sendMessage("§eResultado: §f"+result + " ("+(after-now)+"ms)");
} catch (CalculadoraException | InterruptedException | ExecutionException e) {
sender.sendMessage("§eOcorreu um erro: §f"+e.getLocalizedMessage());
}
return false;
}
}
package com.cloudcraft.beta;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Stack;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.bukkit.Bukkit;
/**
* by don't feito com async pra dar um tchan a mais
*/
public class Calculator {
private final static ScriptEngine ENGINE = new ScriptEngineManager().getEngineByName("JavaScript");
private final static Calculator instance = new Calculator();
private final ExecutorService executor;
private final HashMap<String, Double> constants;
public Calculator() {
executor = Executors.newFixedThreadPool(3);
constants = new HashMap<>();
constants.put("pi", Math.PI);
constants.put("e", Math.E);
}
public static Calculator getInstance() {
return instance;
}
public double calculate(String expression) throws CalculadoraException, InterruptedException, ExecutionException {
if (expression == null || expression.isEmpty()) {
throw new CalculadoraException("nenhum argumento inserido");
}
for (Entry<String, Double> entry : constants.entrySet()) {
expression = expression.replace(entry.getKey(), entry.getValue() + "");
}
if (expression.contains(";")) {
throw new CalculadoraException("a expressão digitada contém caracteres inválidos."); // evita passar códigos maliciosos pelo eval
}
Future<Double> task = executor.submit(new CalculatorTask(expression));
while (!task.isDone()) {
Thread.sleep(1);
}
return task.get();
}
private static class CalculatorTask implements Callable<Double> {
private final String expression;
public CalculatorTask(String expression) {
this.expression = expression;
}
@Override
public Double call() throws Exception {
double toReturn = 0;
try {
Object object = ENGINE.eval(expression);
if (object instanceof Integer) toReturn = (Integer) object;
else toReturn = (Double) object;
} catch (ScriptException e) {
throw new CalculadoraException("a expressão digitada é inválida");
} catch (ClassCastException e) {
throw new CalculadoraException("a expressão digitada não retornou um número válido");
}
return toReturn;
}
}
public static class CalculadoraException extends Exception {
public CalculadoraException(String paramString) {
super(paramString);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment