3
0
Mirror von https://github.com/TheSilentPro/HeadDB.git synchronisiert 2024-12-26 02:50:07 +01:00
Dieser Commit ist enthalten in:
Silent 2020-10-19 17:34:36 +02:00
Commit f941d2f367
20 geänderte Dateien mit 4336 neuen und 0 gelöschten Zeilen

8
.gitignore vendored Normale Datei
Datei anzeigen

@ -0,0 +1,8 @@
target/
.idea/
dependency-reduced-pom.xml
.classpath
.project
*.iml

59
pom.xml Normale Datei
Datei anzeigen

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>tsp.headdb</groupId>
<artifactId>HeadDB</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>jar</packaging>
<name>HeadDB</name>
<description>Head Database</description>
<repositories>
<repository>
<id>papermc</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
</repository>
<repository>
<id>mojang-repo</id>
<url>https://libraries.minecraft.net/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.destroystokyo.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.16.3-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.mojang</groupId>
<artifactId>authlib</artifactId>
<version>1.5.21</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

Datei anzeigen

@ -0,0 +1,50 @@
package tsp.headdb;
import org.bukkit.plugin.java.JavaPlugin;
import tsp.headdb.api.HeadAPI;
import tsp.headdb.command.Command_headdb;
import tsp.headdb.database.HeadDatabase;
import tsp.headdb.listener.PagedPaneListener;
import tsp.headdb.listener.MenuListener;
import tsp.headdb.util.Config;
import tsp.headdb.util.Log;
import tsp.headdb.util.Metrics;
import tsp.headdb.util.Utils;
public class HeadDB extends JavaPlugin {
private static HeadDB instance;
private static Config config;
@Override
public void onEnable() {
instance = this;
Log.info("Loading HeadDB - " + getDescription().getVersion());
saveDefaultConfig();
config = new Config("plugins/HeadDB/config.yml");
Log.debug("Starting metrics...");
new Metrics(this, Utils.METRICS_ID);
Log.debug("Registering listeners...");
new PagedPaneListener(this);
new MenuListener(this);
Log.debug("Registering commands...");
getCommand("headdb").setExecutor(new Command_headdb());
Log.debug("Initializing Database...");
HeadDatabase.update();
Log.info("Done!");
}
public static Config getCfg() {
return config;
}
public static HeadDB getInstance() {
return instance;
}
}

Datei anzeigen

@ -0,0 +1,139 @@
package tsp.headdb.api;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import org.apache.commons.lang.Validate;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import tsp.headdb.database.Category;
import tsp.headdb.util.Log;
import tsp.headdb.util.Utils;
import tsp.headdb.util.XMaterial;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.UUID;
public class Head {
private String name;
private UUID uuid;
private String value;
private Category category;
private int id;
public ItemStack getItemStack() {
Validate.notNull(name, "name must not be null!");
Validate.notNull(uuid, "uuid must not be null!");
Validate.notNull(value, "value must not be null!");
Validate.notNull(category, "category must not be null!");
ItemStack item = XMaterial.PLAYER_HEAD.parseItem();
if (item != null) {
SkullMeta meta = (SkullMeta) item.getItemMeta();
meta.setDisplayName(Utils.colorize(category.getColor() + name));
// set skull owner
GameProfile profile = new GameProfile(uuid, name);
profile.getProperties().put("textures", new Property("textures", value));
Field profileField;
try {
profileField = meta.getClass().getDeclaredField("profile");
profileField.setAccessible(true);
profileField.set(meta, profile);
} catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e1) {
Log.error("Could not set skull owner for " + uuid.toString() + " | Stack Trace:");
e1.printStackTrace();
}
meta.setLore(Collections.singletonList(Utils.colorize("&cID: " + id)));
item.setItemMeta(meta);
}
return item;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UUID getUUID() {
return uuid;
}
public void setUUID(UUID uuid) {
this.uuid = uuid;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public static class Builder {
private String name;
private UUID uuid;
private String value;
private Category category;
private int id;
public Builder withName(String name) {
this.name = name;
return this;
}
public Builder withUUID(UUID uuid) {
this.uuid = uuid;
return this;
}
public Builder withValue(String value) {
this.value = value;
return this;
}
public Builder withCategory(Category category) {
this.category = category;
return this;
}
public Builder withId(int id) {
this.id = id;
return this;
}
public Head build() {
Head head = new Head();
head.setName(name);
head.setUUID(uuid);
head.setValue(value);
head.setCategory(category);
head.setId(id);
return head;
}
}
}

Datei anzeigen

@ -0,0 +1,57 @@
package tsp.headdb.api;
import org.bukkit.entity.Player;
import tsp.headdb.database.Category;
import tsp.headdb.database.HeadDatabase;
import tsp.headdb.inventory.InventoryUtils;
import java.util.List;
import java.util.UUID;
public class HeadAPI {
public static void openDatabase(Player player) {
InventoryUtils.openDatabase(player);
}
public static void openDatabase(Player player, Category category) {
InventoryUtils.openCategoryDatabase(player, category);
}
public static void openDatabase(Player player, String search) {
InventoryUtils.openSearchDatabase(player, search);
}
public static Head getHeadByID(int id) {
return HeadDatabase.getHeadByID(id);
}
public static Head getHeadByUUID(UUID uuid) {
return HeadDatabase.getHeadByUUID(uuid);
}
public static List<Head> getHeadsByName(String name) {
return HeadDatabase.getHeadsByName(name);
}
public static List<Head> getHeadsByName(Category category, String name) {
return HeadDatabase.getHeadsByName(category, name);
}
public static Head getHeadByValue(String value) {
return HeadDatabase.getHeadByValue(value);
}
public static List<Head> getHeads(Category category) {
return HeadDatabase.getHeads(category);
}
public static List<Head> getHeads() {
return HeadDatabase.getHeads();
}
public static void updateDatabase() {
HeadDatabase.update();
}
}

Datei anzeigen

@ -0,0 +1,116 @@
package tsp.headdb.command;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import tsp.headdb.HeadDB;
import tsp.headdb.api.Head;
import tsp.headdb.api.HeadAPI;
import tsp.headdb.inventory.InventoryUtils;
import tsp.headdb.util.Utils;
public class Command_headdb implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {
if (args.length == 0) {
if (!sender.hasPermission("headdb.open")) {
Utils.sendMessage(sender, "&cNo permission!");
return true;
}
if (!(sender instanceof Player)) {
Utils.sendMessage(sender, "&cOnly players may open the database.");
return true;
}
Player player = (Player) sender;
Utils.sendMessage(player, "Opening &cHead Database");
InventoryUtils.openDatabase(player);
return true;
}
String sub = args[0];
if (sub.equalsIgnoreCase("info") || sub.equalsIgnoreCase("i")) {
Utils.sendMessage(sender, "Running &cHeadDB v" + HeadDB.getInstance().getDescription().getVersion());
Utils.sendMessage(sender, "Created by &c" + HeadDB.getInstance().getDescription().getAuthors());
return true;
}
if (sub.equalsIgnoreCase("search") || sub.equalsIgnoreCase("s")) {
if (!sender.hasPermission("headdb.search")) {
Utils.sendMessage(sender, "&cNo permission!");
return true;
}
if (args.length < 2) {
Utils.sendMessage(sender, "&c/hdb search <name>");
return true;
}
if (!(sender instanceof Player)) {
Utils.sendMessage(sender, "&cOnly players may open the database.");
return true;
}
Player player = (Player) sender;
StringBuilder builder = new StringBuilder();
for (int i = 1; i < args.length; i++) {
builder.append(args[i]).append(" ");
}
String name = builder.toString();
Utils.sendMessage(sender, "Searching for &e" + name);
InventoryUtils.openSearchDatabase(player, name);
return true;
}
if (sub.equalsIgnoreCase("give") || sub.equalsIgnoreCase("g")) {
if (!sender.hasPermission("headdb.give")) {
Utils.sendMessage(sender, "&cNo permission!");
return true;
}
if (args.length < 3) {
Utils.sendMessage(sender, "&c/hdb give <id> <player> &6[amount]");
return true;
}
try {
int id = Integer.parseInt(args[1]);
Player target = Bukkit.getPlayer(args[2]);
if (target == null) {
Utils.sendMessage(sender, "&cPlayer is not online!");
return true;
}
int amount = 1;
if (args.length > 3) {
amount = Integer.parseInt(args[3]);
}
Head head = HeadAPI.getHeadByID(id);
ItemStack item = head.getItemStack();
if (item == null) {
Utils.sendMessage(sender, "&cCould not find head with id &e" + id);
return true;
}
item.setAmount(amount);
target.getInventory().addItem(item);
Utils.sendMessage(sender, "Given &c" + target.getName() + " &ex" + amount + " " + head.getName());
return true;
} catch (NumberFormatException nfe) {
Utils.sendMessage(sender, "&cID/Amount must be a number!");
return true;
}
}
Utils.sendMessage(sender, " ");
Utils.sendMessage(sender, "&c&lHeadDB &c- &5Commands");
Utils.sendMessage(sender, "&7&oParameters:&c command &9(aliases) &7- Description");
Utils.sendMessage(sender, " > &c/hdb &7- Opens the database");
Utils.sendMessage(sender, " > &c/hdb info &9(i) &7- Plugin Information");
Utils.sendMessage(sender, " > &c/hdb search &9(s) &c<name> &7- Search for heads matching a name");
Utils.sendMessage(sender, " > &c/hdb give &9(g) &c<id> <player> &6[amount] &7- Give player a head");
Utils.sendMessage(sender, " ");
return true;
}
}

Datei anzeigen

@ -0,0 +1,66 @@
package tsp.headdb.database;
import org.bukkit.ChatColor;
import org.bukkit.inventory.ItemStack;
import tsp.headdb.api.Head;
import tsp.headdb.api.HeadAPI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public enum Category {
ALPHABET("alphabet", ChatColor.YELLOW),
ANIMALS("animals", ChatColor.DARK_AQUA),
BLOCKS("blocks", ChatColor.DARK_GRAY),
DECORATION("decoration", ChatColor.LIGHT_PURPLE),
FOOD_DRINKS("food-drinks", ChatColor.GOLD),
HUMANS("humans", ChatColor.DARK_BLUE),
HUMANOID("humanoid", ChatColor.AQUA),
MISCELLANEOUS("miscellaneous", ChatColor.DARK_GREEN),
MONSTERS("monsters", ChatColor.RED),
PLANTS("plants", ChatColor.GREEN);
private final String name;
private final ChatColor color;
private final Map<Category, Head> item = new HashMap<>();
Category(String name, ChatColor color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public ChatColor getColor() {
return color;
}
public ItemStack getItem() {
if (item.containsKey(this)) {
return item.get(this).getItemStack();
}
item.put(this, HeadAPI.getHeads(this).get(0));
return getItem();
}
public static Category getByName(String name) {
for (Category category : Category.values()) {
if (category.getName().equals(name)) {
return category;
}
}
return null;
}
public static List<Category> getCategories() {
return Arrays.asList(Category.values());
}
}

Datei anzeigen

@ -0,0 +1,167 @@
package tsp.headdb.database;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import tsp.headdb.HeadDB;
import tsp.headdb.api.Head;
import tsp.headdb.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class HeadDatabase {
private static final Map<Category, List<Head>> HEADS = new HashMap<>();
private static final String URL = "https://minecraft-heads.com/scripts/api.php?cat=";
private static long updated;
public static Head getHeadByValue(String value) {
List<Head> heads = getHeads();
for (Head head : heads) {
if (head.getValue().equals(value)) {
return head;
}
}
return null;
}
public static Head getHeadByID(int id) {
List<Head> heads = getHeads();
for (Head head : heads) {
if (head.getId() == id) {
return head;
}
}
return null;
}
public static Head getHeadByUUID(UUID uuid) {
List<Head> heads = getHeads();
for (Head head : heads) {
if (head.getUUID().equals(uuid)) {
return head;
}
}
return null;
}
public static List<Head> getHeadsByName(Category category, String name) {
List<Head> result = new ArrayList<>();
List<Head> heads = getHeads(category);
for (Head head : heads) {
if (head.getName().toLowerCase().contains(name.toLowerCase())) {
result.add(head);
}
}
return result;
}
public static List<Head> getHeadsByName(String name) {
List<Head> result = new ArrayList<>();
List<Head> heads = getHeads();
for (Head head : heads) {
if (head.getName().toLowerCase().contains(name.toLowerCase())) {
result.add(head);
}
}
return result;
}
public static List<Head> getHeads(Category category) {
return HEADS.get(category);
}
public static List<Head> getHeads() {
if (!HEADS.isEmpty() && !isLastUpdateOld()) {
List<Head> heads = new ArrayList<>();
for (Category category : HEADS.keySet()) {
heads.addAll(HEADS.get(category));
}
return heads;
}
update();
return getHeads();
}
public static Map<Category, List<Head>> getHeadsNoCache() {
Map<Category, List<Head>> result = new HashMap<>();
List<Category> categories = Category.getCategories();
for (Category category : categories) {
Log.debug("Caching heads from: " + category.getName());
List<Head> heads = new ArrayList<>();
try {
String line;
StringBuilder response = new StringBuilder();
URLConnection connection = new URL(URL + category.getName()).openConnection();
connection.setConnectTimeout(5000);
connection.setRequestProperty("User-Agent", "HeadDB");
try (BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()))) {
while ((line = in.readLine()) != null) {
response.append(line);
}
}
JSONParser parser = new JSONParser();
JSONArray array = (JSONArray) parser.parse(response.toString());
int id = 1;
for (Object o : array) {
JSONObject obj = (JSONObject) o;
Head head = new Head.Builder()
.withName(obj.get("name").toString())
.withUUID(UUID.fromString(obj.get("uuid").toString()))
.withValue(obj.get("value").toString())
.withCategory(category)
.withId(id)
.build();
id++;
heads.add(head);
}
} catch (ParseException | IOException e) {
Log.error("Failed to fetch heads (no-cache) | Stack Trace:");
e.printStackTrace();
}
updated = System.nanoTime();
result.put(category, heads);
}
return result;
}
public static void update() {
Map<Category, List<Head>> heads = getHeadsNoCache();
HEADS.clear();
for (Map.Entry<Category, List<Head>> entry : heads.entrySet()) {
HEADS.put(entry.getKey(), entry.getValue());
}
}
public static long getLastUpdate() {
long now = System.nanoTime();
long elapsed = now - updated;
return TimeUnit.NANOSECONDS.toSeconds(elapsed);
}
public static boolean isLastUpdateOld() {
if (HeadDB.getCfg() == null && getLastUpdate() >= 3600) return true;
return getLastUpdate() >= HeadDB.getCfg().getLong("refresh");
}
}

Datei anzeigen

@ -0,0 +1,81 @@
package tsp.headdb.inventory;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import java.util.Objects;
import java.util.function.Consumer;
/**
* A button
*/
public class Button {
private static int counter;
private final int ID = counter++;
private ItemStack itemStack;
private Consumer<InventoryClickEvent> action;
/**
* @param itemStack The Item
*/
@SuppressWarnings("unused")
public Button(ItemStack itemStack) {
this(itemStack, event -> {
});
}
/**
* @param itemStack The Item
* @param action The action
*/
public Button(ItemStack itemStack, Consumer<InventoryClickEvent> action) {
this.itemStack = itemStack;
this.action = action;
}
/**
* @return The icon
*/
@SuppressWarnings("WeakerAccess")
public ItemStack getItemStack() {
return itemStack;
}
/**
* @param action The new action
*/
@SuppressWarnings("unused")
public void setAction(Consumer<InventoryClickEvent> action) {
this.action = action;
}
/**
* @param event The event that triggered it
*/
@SuppressWarnings("WeakerAccess")
public void onClick(InventoryClickEvent event) {
action.accept(event);
}
// We do not want equals collisions. The default hashcode would not fulfil this contract.
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Button)) {
return false;
}
Button button = (Button) o;
return ID == button.ID;
}
@Override
public int hashCode() {
return Objects.hash(ID);
}
}

Datei anzeigen

@ -0,0 +1,98 @@
package tsp.headdb.inventory;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import tsp.headdb.api.Head;
import tsp.headdb.api.HeadAPI;
import tsp.headdb.database.Category;
import tsp.headdb.util.Utils;
import tsp.headdb.util.XMaterial;
import java.util.ArrayList;
import java.util.List;
public class InventoryUtils {
public static void openSearchDatabase(Player player, String search) {
PagedPane pane = new PagedPane(4, 6, Utils.colorize("&c&lHeadDB - &eSearch: " + search));
List<Head> heads = HeadAPI.getHeadsByName(search);
for (Head head : heads) {
pane.addButton(new Button(head.getItemStack(), e -> {
if (e.getClick() == ClickType.SHIFT_LEFT) {
ItemStack item = head.getItemStack();
item.setAmount(64);
player.getInventory().addItem(item);
return;
}
player.getInventory().addItem(head.getItemStack());
}));
}
pane.open(player);
}
public static void openCategoryDatabase(Player player, Category category) {
PagedPane pane = new PagedPane(4, 6, Utils.colorize("&c&lHeadDB - &e" + category.getName()));
List<Head> heads = HeadAPI.getHeads(category);
for (Head head : heads) {
pane.addButton(new Button(head.getItemStack(), e -> {
if (e.getClick() == ClickType.SHIFT_LEFT) {
ItemStack item = head.getItemStack();
item.setAmount(64);
player.getInventory().addItem(item);
return;
}
player.getInventory().addItem(head.getItemStack());
}));
}
pane.open(player);
}
public static void openDatabase(Player player) {
Inventory inventory = Bukkit.createInventory(null, 54, Utils.colorize("&c&lHeadDB"));
fillBorder(inventory, XMaterial.BLACK_STAINED_GLASS_PANE.parseItem());
for (Category category : Category.getCategories()) {
ItemStack item = category.getItem();
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(Utils.colorize(category.getColor() + "&l" + category.getName().toUpperCase()));
List<String> lore = new ArrayList<>();
lore.add(Utils.colorize("&e" + HeadAPI.getHeads(category).size() + " heads"));
meta.setLore(lore);
item.setItemMeta(meta);
inventory.addItem(item);
}
player.openInventory(inventory);
}
public static void fillBorder(Inventory inv, ItemStack item) {
int size = inv.getSize();
int rows = (size + 1) / 9;
// Fill top
for (int i = 0; i < 9; i++) {
inv.setItem(i, item);
}
// Fill bottom
for (int i = size - 9; i < size; i++) {
inv.setItem(i, item);
}
// Fill sides
for (int i = 2; i <= rows - 1; i++) {
int[] slots = new int[]{i * 9 - 1, (i - 1) * 9};
inv.setItem(slots[0], item);
inv.setItem(slots[1], item);
}
}
}

Datei anzeigen

@ -0,0 +1,373 @@
package tsp.headdb.inventory;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import tsp.headdb.api.HeadAPI;
import tsp.headdb.util.Utils;
import tsp.headdb.util.XMaterial;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
/**
* A paged pane. Credits @ I Al Ianstaan
*/
public class PagedPane implements InventoryHolder {
private Inventory inventory;
private SortedMap<Integer, Page> pages = new TreeMap<>();
private int currentIndex;
private int pageSize;
@SuppressWarnings("WeakerAccess")
protected Button controlBack;
@SuppressWarnings("WeakerAccess")
protected Button controlNext;
/**
* @param pageSize The page size. inventory rows - 2
*/
public PagedPane(int pageSize, int rows, String title) {
Objects.requireNonNull(title, "title can not be null!");
if (rows > 6) {
throw new IllegalArgumentException("Rows must be <= 6, got " + rows);
}
if (pageSize > 6) {
throw new IllegalArgumentException("Page size must be <= 6, got" + pageSize);
}
this.pageSize = pageSize;
inventory = Bukkit.createInventory(this, rows * 9, color(title));
pages.put(0, new Page(pageSize));
}
/**
* @param button The button to add
*/
public void addButton(Button button) {
for (Entry<Integer, Page> entry : pages.entrySet()) {
if (entry.getValue().addButton(button)) {
if (entry.getKey() == currentIndex) {
reRender();
}
return;
}
}
Page page = new Page(pageSize);
page.addButton(button);
pages.put(pages.lastKey() + 1, page);
reRender();
}
/**
* @param button The Button to remove
*/
@SuppressWarnings("unused")
public void removeButton(Button button) {
for (Iterator<Entry<Integer, Page>> iterator = pages.entrySet().iterator(); iterator.hasNext(); ) {
Entry<Integer, Page> entry = iterator.next();
if (entry.getValue().removeButton(button)) {
// we may need to delete the page
if (entry.getValue().isEmpty()) {
// we have more than one page, so delete it
if (pages.size() > 1) {
iterator.remove();
}
// the currentIndex now points to a page that does not exist. Correct it.
if (currentIndex >= pages.size()) {
currentIndex--;
}
}
// if we modified the current one, re-render
// if we deleted the current page, re-render too
if (entry.getKey() >= currentIndex) {
reRender();
}
return;
}
}
}
/**
* @return The amount of pages
*/
@SuppressWarnings("WeakerAccess")
public int getPageAmount() {
return pages.size();
}
/**
* @return The number of the current page (1 based)
*/
@SuppressWarnings("WeakerAccess")
public int getCurrentPage() {
return currentIndex + 1;
}
/**
* @param index The index of the new page
*/
@SuppressWarnings("WeakerAccess")
public void selectPage(int index) {
if (index < 0 || index >= getPageAmount()) {
throw new IllegalArgumentException(
"Index out of bounds s: " + index + " [" + 0 + " " + getPageAmount() + ")"
);
}
if (index == currentIndex) {
return;
}
currentIndex = index;
reRender();
}
/**
* Renders the inventory again
*/
@SuppressWarnings("WeakerAccess")
public void reRender() {
inventory.clear();
pages.get(currentIndex).render(inventory);
controlBack = null;
controlNext = null;
createControls(inventory);
}
/**
* @param event The {@link InventoryClickEvent}
*/
@SuppressWarnings("WeakerAccess")
public void onClick(InventoryClickEvent event) {
event.setCancelled(true);
// back item
if (event.getSlot() == inventory.getSize() - 8) {
if (controlBack != null) {
controlBack.onClick(event);
}
return;
}
// next item
else if (event.getSlot() == inventory.getSize() - 2) {
if (controlNext != null) {
controlNext.onClick(event);
}
return;
}
pages.get(currentIndex).handleClick(event);
}
/**
* Get the object's inventory.
*
* @return The inventory.
*/
@Override
public Inventory getInventory() {
return inventory;
}
/**
* Creates the controls
*
* @param inventory The inventory
*/
@SuppressWarnings("WeakerAccess")
protected void createControls(Inventory inventory) {
// create separator
fillRow(
inventory.getSize() / 9 - 2,
XMaterial.BLACK_STAINED_GLASS_PANE.parseItem(),
inventory
);
if (getCurrentPage() > 1) {
String name = String.format(
Locale.ROOT,
"&3&lPage &a&l%d &7/ &c&l%d",
getCurrentPage() - 1, getPageAmount()
);
String lore = String.format(
Locale.ROOT,
"&7Previous: &c%d",
getCurrentPage() - 1
);
ItemStack itemStack = setMeta(HeadAPI.getHeadByValue("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODY1MmUyYjkzNmNhODAyNmJkMjg2NTFkN2M5ZjI4MTlkMmU5MjM2OTc3MzRkMThkZmRiMTM1NTBmOGZkYWQ1ZiJ9fX0=").getItemStack(), name, lore);
controlBack = new Button(itemStack, event -> selectPage(currentIndex - 1));
inventory.setItem(inventory.getSize() - 8, itemStack);
}
if (getCurrentPage() < getPageAmount()) {
String name = String.format(
Locale.ROOT,
"&3&lPage &a&l%d &7/ &c&l%d",
getCurrentPage() + 1, getPageAmount()
);
String lore = String.format(
Locale.ROOT,
"&7Next: &c%d",
getCurrentPage() + 1
);
ItemStack itemStack = setMeta(HeadAPI.getHeadByValue("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMmEzYjhmNjgxZGFhZDhiZjQzNmNhZThkYTNmZTgxMzFmNjJhMTYyYWI4MWFmNjM5YzNlMDY0NGFhNmFiYWMyZiJ9fX0=").getItemStack(), name, lore);
controlNext = new Button(itemStack, event -> selectPage(getCurrentPage()));
inventory.setItem(inventory.getSize() - 2, itemStack);
}
{
String name = String.format(
Locale.ROOT,
"&3&lPage &a&l%d &7/ &c&l%d",
getCurrentPage(), getPageAmount()
);
String lore = String.format(
Locale.ROOT,
"&7Current: &a%d",
getCurrentPage()
);
ItemStack itemStack = setMeta(HeadAPI.getHeadByValue("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvY2Q5MWY1MTI2NmVkZGM2MjA3ZjEyYWU4ZDdhNDljNWRiMDQxNWFkYTA0ZGFiOTJiYjc2ODZhZmRiMTdmNGQ0ZSJ9fX0=").getItemStack(), name, lore);
inventory.setItem(inventory.getSize() - 5, itemStack);
}
}
private void fillRow(int rowIndex, ItemStack itemStack, Inventory inventory) {
int yMod = rowIndex * 9;
for (int i = 0; i < 9; i++) {
int slot = yMod + i;
inventory.setItem(slot, itemStack);
}
}
protected ItemStack setMeta(ItemStack itemStack, String name, String... lore) {
ItemMeta meta = itemStack.getItemMeta();
meta.setDisplayName(Utils.colorize(name));
meta.setLore(Arrays.stream(lore).map(this::color).collect(Collectors.toList()));
itemStack.setItemMeta(meta);
return itemStack;
}
@SuppressWarnings("WeakerAccess")
@Deprecated
protected ItemStack getItemStack(Material type, int durability, String name, String... lore) {
ItemStack itemStack = new ItemStack(type, 1, (short) durability);
ItemMeta itemMeta = itemStack.getItemMeta();
if (name != null) {
itemMeta.setDisplayName(color(name));
}
if (lore != null && lore.length != 0) {
itemMeta.setLore(Arrays.stream(lore).map(this::color).collect(Collectors.toList()));
}
itemStack.setItemMeta(itemMeta);
return itemStack;
}
@SuppressWarnings("WeakerAccess")
protected String color(String input) {
return ChatColor.translateAlternateColorCodes('&', input);
}
/**
* @param player The {@link Player} to open it for
*/
public void open(Player player) {
reRender();
player.openInventory(getInventory());
}
private static class Page {
private List<Button> buttons = new ArrayList<>();
private int maxSize;
Page(int maxSize) {
this.maxSize = maxSize;
}
/**
* @param event The click event
*/
void handleClick(InventoryClickEvent event) {
// user clicked in his own inventory. Silently drop it
if (event.getRawSlot() > event.getInventory().getSize()) {
return;
}
// user clicked outside of the inventory
if (event.getSlotType() == InventoryType.SlotType.OUTSIDE) {
return;
}
if (event.getSlot() >= buttons.size()) {
return;
}
Button button = buttons.get(event.getSlot());
button.onClick(event);
}
/**
* @return True if there is space left
*/
boolean hasSpace() {
return buttons.size() < maxSize * 9;
}
/**
* @param button The {@link Button} to add
*
* @return True if the button was added, false if there was no space
*/
boolean addButton(Button button) {
if (!hasSpace()) {
return false;
}
buttons.add(button);
return true;
}
/**
* @param button The {@link Button} to remove
*
* @return True if the button was removed
*/
boolean removeButton(Button button) {
return buttons.remove(button);
}
/**
* @param inventory The inventory to render in
*/
void render(Inventory inventory) {
for (int i = 0; i < buttons.size(); i++) {
Button button = buttons.get(i);
inventory.setItem(i, button.getItemStack());
}
}
/**
* @return True if this page is empty
*/
boolean isEmpty() {
return buttons.isEmpty();
}
}
}

Datei anzeigen

@ -0,0 +1,48 @@
package tsp.headdb.listener;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import tsp.headdb.database.Category;
import tsp.headdb.inventory.InventoryUtils;
import tsp.headdb.util.Utils;
import tsp.headdb.util.XMaterial;
public class MenuListener implements Listener {
public MenuListener(JavaPlugin plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void click(InventoryClickEvent e) {
if (!(e.getWhoClicked() instanceof Player)) {
return;
}
if (e.getView().getTitle().startsWith(Utils.colorize("&c&lHeadDB"))) {
e.setCancelled(true);
Inventory inventory = e.getClickedInventory();
if (inventory != null) {
int slot = e.getSlot();
ItemStack item = inventory.getItem(slot);
if (item != null && item.getType() != XMaterial.AIR.parseMaterial()) {
String name = ChatColor.stripColor(item.getItemMeta().getDisplayName().toLowerCase());
Category category = Category.getByName(name);
if (category != null) {
InventoryUtils.openCategoryDatabase((Player) e.getWhoClicked(), category);
}
}
}
}
}
}

Datei anzeigen

@ -0,0 +1,27 @@
package tsp.headdb.listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.plugin.java.JavaPlugin;
import tsp.headdb.inventory.PagedPane;
/**
* Listens for click events for the {@link PagedPane}
*/
public class PagedPaneListener implements Listener {
public PagedPaneListener(JavaPlugin plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler
public void onClick(InventoryClickEvent event) {
InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof PagedPane) {
((PagedPane) holder).onClick(event);
}
}
}

Datei anzeigen

@ -0,0 +1,115 @@
package tsp.headdb.util;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* @author TheSilentPro
*/
public class Config {
private final File file;
private FileConfiguration config;
public Config(File file) {
this.file = file;
this.config = YamlConfiguration.loadConfiguration(file);
}
public Config(String path) {
this.file = new File(path);
this.config = YamlConfiguration.loadConfiguration(file);
}
public Config(Config config) {
this.file = config.getFile();
this.config = config.getConfig();
}
public String getString(String path) {
return Utils.colorize(config.getString(path));
}
public boolean getBoolean(String path) {
return config.getBoolean(path);
}
public List<String> getStringList(String path) {
return config.getStringList(path);
}
public int getInt(String path) {
return config.getInt(path);
}
public long getLong(String path) {
return config.getLong(path);
}
public Set<String> getKeys(boolean deep) {
return config.getKeys(deep);
}
public ConfigurationSection getConfigurationSection(String path) {
return config.getConfigurationSection(path);
}
public Set<String> getKeys(ConfigurationSection configurationSection, boolean b) {
return configurationSection.getKeys(b);
}
public void set(String path, Object value) {
config.set(path, value);
}
public Object get(String path) {
return config.get(path);
}
public FileConfiguration getConfig() {
return config;
}
public File getFile() {
return file;
}
public boolean exists() {
return file.exists();
}
public void reload() {
this.config = YamlConfiguration.loadConfiguration(file);
}
public boolean create() {
if (!file.exists()) {
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public boolean save() {
try {
config.save(file);
return true;
} catch (IOException e) {
Log.error("Failed to save " + file.getName() + " | Stack Trace:");
e.printStackTrace();
}
return false;
}
}

Datei anzeigen

@ -0,0 +1,84 @@
package tsp.headdb.util;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* @author TheSilentPro
*/
public class Log {
private static String name = "&cHeadDB";
public static void info(String message) {
log(LogLevel.INFO, message);
}
public static void warning(String message) {
log(LogLevel.WARNING, message);
}
public static void error(String message) {
log(LogLevel.ERROR, message);
}
public static void error(Throwable ex) {
log(ex);
}
public static void debug(String message) {
log(LogLevel.DEBUG, message);
}
public static void log(LogLevel level, String message) {
Bukkit.getConsoleSender().sendMessage(Utils.colorize("&7[&9&l" + name + "&7] " + level.getColor() + "[" + level.name() + "]: " + message));
}
public static void log(Throwable ex) {
Bukkit.getConsoleSender().sendMessage(Utils.colorize("&7[" + name + "&7] " + "&4&l[EXCEPTION]: " + ex.getMessage()));
Bukkit.getConsoleSender().sendMessage(Utils.colorize("&4&l[StackTrace]: " + getStackTrace(ex)));
}
public static void setName(String logName) {
name = logName;
}
public static String getName() {
return name;
}
public static String getStackTrace(Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
public enum LogLevel {
INFO,
WARNING,
ERROR,
DEBUG;
private ChatColor getColor() {
switch (this) {
case INFO:
return ChatColor.GREEN;
case WARNING:
return ChatColor.YELLOW;
case ERROR:
return ChatColor.DARK_RED;
case DEBUG:
return ChatColor.DARK_AQUA;
default:
return ChatColor.WHITE;
}
}
}
}

Datei anzeigen

@ -0,0 +1,720 @@
package tsp.headdb.util;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics {
static {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Is bStats enabled on this server?
private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests;
// Should the sent data be logged?
private static boolean logSentData;
// Should the response text be logged?
private static boolean logResponseStatusText;
// The uuid of the server
private static String serverUUID;
// The plugin
private final Plugin plugin;
// The plugin id
private final int pluginId;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
* @param pluginId The id of the plugin.
* It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
*/
public Metrics(Plugin plugin, int pluginId) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
this.pluginId = pluginId;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
config.addDefault("logSentData", false);
// Should the response text be logged?
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JsonObject getPluginData() {
JsonObject data = new JsonObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.addProperty("pluginName", pluginName); // Append the name of the plugin
data.addProperty("id", pluginId); // Append the id of the plugin
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
JsonArray customCharts = new JsonArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JsonObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.add("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JsonObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
String bukkitName = Bukkit.getName();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JsonObject data = new JsonObject();
data.addProperty("serverUUID", serverUUID);
data.addProperty("playerAmount", playerAmount);
data.addProperty("onlineMode", onlineMode);
data.addProperty("bukkitVersion", bukkitVersion);
data.addProperty("bukkitName", bukkitName);
data.addProperty("javaVersion", javaVersion);
data.addProperty("osName", osName);
data.addProperty("osArch", osArch);
data.addProperty("osVersion", osVersion);
data.addProperty("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JsonObject data = getServerData();
JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility
try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object);
}
} catch (ClassNotFoundException e) {
// minecraft version 1.14+
if (logFailedRequests) {
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
}
}
}
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
}
} catch (NoSuchFieldException ignored) { }
}
data.add("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(() -> {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger instance.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data);
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.write(compressedData);
}
StringBuilder builder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
}
if (logResponseStatusText) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder);
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
gzip.write(str.getBytes(StandardCharsets.UTF_8));
}
return outputStream.toByteArray();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
private JsonObject getRequestJsonObject() {
JsonObject chart = new JsonObject();
chart.addProperty("chartId", chartId);
try {
JsonObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.add("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JsonObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.addProperty("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JsonObject value = new JsonObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.addProperty(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.add(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.addProperty("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.addProperty(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JsonArray categoryValues = new JsonArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(new JsonPrimitive(categoryValue));
}
values.add(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.add("values", values);
return data;
}
}
}

Datei anzeigen

@ -0,0 +1,18 @@
package tsp.headdb.util;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
public class Utils {
public static final int METRICS_ID = 9152;
public static void sendMessage(CommandSender sender, String message) {
sender.sendMessage(colorize(message));
}
public static String colorize(String string) {
return ChatColor.translateAlternateColorCodes('&', ChatColor.GRAY + string);
}
}

Datei-Diff unterdrückt, da er zu groß ist Diff laden

Datei anzeigen

@ -0,0 +1,5 @@
# If the cached heads are older than these amount of seconds, the plugin will refresh the database
refresh: 3600
# Debug Mode
debug: true

Datei anzeigen

@ -0,0 +1,26 @@
name: HeadDB
description: Head Database
main: tsp.headdb.HeadDB
version: 1.0
author: Silent
commands:
headdb:
usage: /headdb <arguments>
description: Open the database
aliases: [hdb, headdatabase]
permissions:
headdb.admin:
default: op
children:
headdb.open: true
headdb.search: true
headdb.give: true
headdb.open:
default: op
headdb.search:
default: op
headdb.give:
default: op