Files
src
build.gradle
README.md
settings.gradle
Code
6 294
src/main/java/com/zynxstock/ZynxStock.java
package com.zynxstock;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
public final class ZynxStock extends JavaPlugin {
private static final long INTERVAL = 3L * 60 * 60 * 1000;
private static final double MIN_PRICE = 0.00000001;
private static final double MAX_PRICE = 1.0e100;
private final Map<String, Stock> stocks = new LinkedHashMap<>();
private File dataFile;
private long nextUpdate;
private static final class Stock {
double price;
double previous;
double highest;
double lowest;
double percentage;
List<Map<String, Object>> history = new ArrayList<>();
Stock(double price) {
this.price = price;
this.previous = price;
this.highest = price;
this.lowest = price;
}
}
@Override
public void onEnable() {
saveDefaultConfig();
dataFile = new File(getDataFolder(), "data.yml");
try {
loadData();
loadInitialStocks();
if (nextUpdate <= 0) {
nextUpdate = System.currentTimeMillis() + INTERVAL;
}
updateDue();
saveData();
} catch (IOException | InvalidConfigurationException | IllegalArgumentException e) {
getLogger().severe("Data saham tidak dapat dimuat/disimpan: " + e.getMessage());
getServer().getPluginManager().disablePlugin(this);
return;
}
getServer().getScheduler().runTaskTimer(this, this::tick, 20L, 20L);
}
private void loadData() throws IOException, InvalidConfigurationException {
if (!dataFile.exists()) return;
YamlConfiguration yaml = new YamlConfiguration();
yaml.load(dataFile);
nextUpdate = yaml.getLong("next-update", 0L);
ConfigurationSection section = yaml.getConfigurationSection("stocks");
if (section == null) throw new IllegalArgumentException("Bagian stocks tidak ditemukan di data.yml");
for (String name : section.getKeys(false)) {
ConfigurationSection entry = section.getConfigurationSection(name);
if (entry == null || !validName(name)) throw new IllegalArgumentException("Data saham tidak valid: " + name);
double price = entry.getDouble("price", Double.NaN);
double previous = entry.getDouble("previous", Double.NaN);
double highest = entry.getDouble("highest", Double.NaN);
double lowest = entry.getDouble("lowest", Double.NaN);
double percentage = entry.getDouble("percentage", Double.NaN);
if (!validPrice(price) || !validPrice(previous) || !validPrice(highest) || !validPrice(lowest) || !Double.isFinite(percentage)) {
throw new IllegalArgumentException("Harga atau perubahan tidak valid: " + name);
}
Stock stock = new Stock(price);
stock.previous = previous;
stock.highest = highest;
stock.lowest = lowest;
stock.percentage = percentage;
for (Map<?, ?> item : entry.getMapList("history")) {
Map<String, Object> record = new LinkedHashMap<>();
for (Map.Entry<?, ?> field : item.entrySet()) record.put(String.valueOf(field.getKey()), field.getValue());
stock.history.add(record);
}
stocks.put(name.toUpperCase(Locale.ROOT), stock);
}
}
private void loadInitialStocks() {
ConfigurationSection section = getConfig().getConfigurationSection("stocks");
if (section == null) throw new IllegalArgumentException("Bagian stocks tidak ditemukan di config.yml");
for (String name : section.getKeys(false)) {
double price = section.getDouble(name, Double.NaN);
if (!validName(name) || !validPrice(price)) throw new IllegalArgumentException("Saham awal tidak valid: " + name);
stocks.putIfAbsent(name.toUpperCase(Locale.ROOT), new Stock(price));
}
}
private boolean validName(String name) {
return name.matches("[A-Za-z0-9_-]{1,32}");
}
private boolean validPrice(double price) {
return Double.isFinite(price) && price >= MIN_PRICE && price <= MAX_PRICE;
}
private void tick() {
if (System.currentTimeMillis() < nextUpdate) return;
updateDue();
try {
saveData();
} catch (IOException e) {
getLogger().severe("Gagal menyimpan data saham: " + e.getMessage());
}
}
private void updateDue() {
long now = System.currentTimeMillis();
while (nextUpdate <= now) {
for (Stock stock : stocks.values()) {
int roll = ThreadLocalRandom.current().nextInt(100);
int change = ThreadLocalRandom.current().nextInt(1, 11);
double factor = roll < 45 ? 1.0 + change / 100.0 : roll < 85 ? 1.0 - change / 100.0 : 1.0;
double price = Math.max(MIN_PRICE, Math.min(MAX_PRICE, stock.price * factor));
recordChange(stock, price, nextUpdate, "otomatis");
}
nextUpdate += INTERVAL;
}
}
private void recordChange(Stock stock, double price, long time, String source) {
stock.previous = stock.price;
stock.price = price;
stock.percentage = (price / stock.previous - 1.0) * 100.0;
stock.highest = Math.max(stock.highest, price);
stock.lowest = Math.min(stock.lowest, price);
Map<String, Object> record = new LinkedHashMap<>();
record.put("time", time);
record.put("source", source);
record.put("previous", stock.previous);
record.put("price", price);
record.put("percentage", stock.percentage);
stock.history.add(record);
}
private void saveData() throws IOException {
YamlConfiguration yaml = new YamlConfiguration();
yaml.set("next-update", nextUpdate);
yaml.createSection("stocks");
for (Map.Entry<String, Stock> entry : stocks.entrySet()) {
String path = "stocks." + entry.getKey() + ".";
Stock stock = entry.getValue();
yaml.set(path + "price", stock.price);
yaml.set(path + "previous", stock.previous);
yaml.set(path + "highest", stock.highest);
yaml.set(path + "lowest", stock.lowest);
yaml.set(path + "percentage", stock.percentage);
yaml.set(path + "history", stock.history);
}
File temporary = new File(getDataFolder(), "data.yml.tmp");
yaml.save(temporary);
try {
Files.move(temporary.toPath(), dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temporary.toPath(), dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length >= 1 && args[0].equalsIgnoreCase("trend") && args.length <= 2) {
if (args.length == 2) {
Stock stock = stocks.get(args[1].toUpperCase(Locale.ROOT));
if (stock == null) sender.sendMessage(ChatColor.RED + "Saham tidak ditemukan.");
else showTrend(sender, args[1].toUpperCase(Locale.ROOT), stock);
} else if (stocks.isEmpty()) {
sender.sendMessage(ChatColor.YELLOW + "Belum ada saham.");
} else {
stocks.forEach((name, stock) -> showTrend(sender, name, stock));
}
return true;
}
if (args.length >= 1 && args[0].equalsIgnoreCase("set")) {
if (!sender.hasPermission("zynxstock.admin")) {
sender.sendMessage(ChatColor.RED + "Anda tidak memiliki izin untuk mengatur harga.");
return true;
}
if (args.length != 3) {