file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
ItemUtils.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/ItemUtils.java | package gyurix.spigotutils;
import com.google.common.collect.Lists;
import gyurix.api.VariableAPI;
import gyurix.chat.ChatTag;
import gyurix.nbt.NBTCompound;
import gyurix.nbt.NBTList;
import gyurix.nbt.NBTPrimitive;
import gyurix.protocol.utils.ItemStackWrapper;
import gyurix.spigotlib.Items;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import net.md_5.bungee.api.chat.BaseComponent;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.bukkit.*;
import org.bukkit.FireworkEffect.Builder;
import org.bukkit.FireworkEffect.Type;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.PotionData;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.potion.PotionType;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import static gyurix.protocol.Reflection.ver;
import static gyurix.spigotlib.Items.*;
import static gyurix.spigotlib.SU.*;
import static gyurix.spigotutils.ServerVersion.*;
/**
* Utils for managing items
*/
public class ItemUtils {
/**
* Adds the given item to the given inventory with the default max stack size
*
* @param inv - The inventory to which the item should be added
* @param is - The addable item
* @return The remaining items after the addition
*/
public static int addItem(Inventory inv, ItemStack is) {
return addItem(inv, is, is.getMaxStackSize());
}
/**
* Adds the given item to the given inventory
*
* @param inv - The inventory to which the item should be added
* @param is - The addable item
* @param maxStack - Maximal stack size of the item
* @return The remaining items after the addition
*/
public static int addItem(Inventory inv, ItemStack is, int maxStack) {
int left = is.getAmount();
int size = inv instanceof PlayerInventory ? 36 : inv.getSize();
for (int i = 0; i < size; i++) {
ItemStack current = inv.getItem(i);
if (itemSimilar(current, is)) {
int am = current.getAmount();
int canPlace = maxStack - am;
if (canPlace >= left) {
current.setAmount(am + left);
return 0;
} else if (canPlace > 0) {
current.setAmount(am + canPlace);
left -= canPlace;
}
}
}
for (int i = 0; i < size; i++) {
ItemStack current = inv.getItem(i);
if (current == null || current.getType() == Material.AIR) {
current = is.clone();
if (maxStack >= left) {
current.setAmount(left);
inv.setItem(i, current);
return 0;
} else {
current.setAmount(maxStack);
left -= maxStack;
inv.setItem(i, current);
}
}
}
return left;
}
public static ItemStack addLore(ItemStack is, String... lore) {
if (is == null || is.getType() == Material.AIR)
return is;
is = is.clone();
ItemMeta meta = is.getItemMeta();
List<String> fullLore = meta.getLore();
if (fullLore == null)
fullLore = new ArrayList<>();
fullLore.addAll(Arrays.asList(lore));
meta.setLore(fullLore);
is.setItemMeta(meta);
return is;
}
public static ItemStack addLore(ItemStack is, List<String> lore, Object... vars) {
if (is == null || is.getType() == Material.AIR)
return is;
is = is.clone();
ItemMeta meta = is.getItemMeta();
List<String> fullLore = meta.getLore();
if (fullLore == null)
fullLore = new ArrayList<>();
fullLore.addAll(SU.fillVariables(lore, vars));
meta.setLore(fullLore);
is.setItemMeta(meta);
return is;
}
/**
* Adds the given lore storage meta to the given item
*
* @param is - Modifiable item
* @param values - Array of storage format and values
* @return The modified item
*/
public static ItemStack addLoreStorageMeta(ItemStack is, Object... values) {
if (is == null || is.getType() == Material.AIR)
return is;
is = is.clone();
ItemMeta meta = is.getItemMeta();
List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>();
boolean key = true;
int id = -1;
String prefix = "";
String suffix = "";
for (Object o : values) {
if (key) {
id = -1;
prefix = (String) o;
int id2 = prefix.indexOf("<value>");
suffix = prefix.substring(id2 + 7);
prefix = prefix.substring(0, id2);
for (int i = 0; i < lore.size(); ++i) {
String s = lore.get(i);
if (s.startsWith(prefix) && s.endsWith(suffix)) {
id = i;
break;
}
}
key = false;
continue;
}
if (id == -1)
lore.add(prefix + o + suffix);
else
lore.set(id, prefix + o + suffix);
key = true;
}
meta.setLore(lore);
is.setItemMeta(meta);
return is;
}
/**
* A truth check if an iterable contains the given typed item or not
*
* @param source ItemStack iterable
* @param is checked ItemStack
* @return True if the ItemStack iterable contains the checked ItemStack in any amount, false otherwise.
*/
public static boolean containsItem(Iterable<ItemStack> source, ItemStack is) {
for (ItemStack i : source) {
if (itemSimilar(i, is))
return true;
}
return false;
}
/**
* Counts the given item in the given inventory
*
* @param inv - The inventory in which the item should be counted
* @param is - The countable item, the amount of the item is ignored (calculated as 1)
* @return The amount of the item which is in the inventory
*/
public static int countItem(Inventory inv, ItemStack is) {
int count = 0;
int size = inv instanceof PlayerInventory ? 36 : inv.getSize();
for (int i = 0; i < size; i++) {
ItemStack current = inv.getItem(i);
if (ItemUtils.itemSimilar(is, current))
count += current.getAmount();
}
return count;
}
/**
* Counts the available space for the given item in the given inventory
*
* @param inv - The inventory to which the item should be added
* @param is - The addable item
* @param maxStack - Maximal stack size of the item
* @return The maximum amount
*/
public static int countItemSpace(Inventory inv, ItemStack is, int maxStack) {
int space = 0;
int size = inv instanceof PlayerInventory ? 36 : inv.getSize();
for (int i = 0; i < size; i++) {
ItemStack current = inv.getItem(i);
if (current == null || current.getType() == Material.AIR)
space += maxStack;
else if (itemSimilar(current, is))
space += maxStack - current.getAmount();
}
return space;
}
/**
* Fill variables in a ItemStack
* Available special variables:
* #amount: the amount value of the item
* #id: the id of the item
* #sub: the subid of the item
*
* @param is - The ItemStack in which the variables should be filled
* @param vars - The fillable variables
* @return A clone of the original ItemStack with filled variables
*/
public static ItemStack fillVariables(ItemStack is, Object... vars) {
if (is == null || is.getType() == Material.AIR)
return is;
is = is.clone();
String last = null;
for (Object v : vars) {
if (last == null)
last = (String) v;
else {
switch (last) {
case "#amount":
is.setAmount(Integer.valueOf(String.valueOf(v)));
break;
case "#id":
String vs = String.valueOf(v);
try {
is.setType(getMaterial(Integer.valueOf(vs)));
} catch (Throwable e) {
try {
is.setType(Material.valueOf(vs.toUpperCase()));
} catch (Throwable e2) {
try {
is.setType(Material.valueOf("LEGACY_" + vs.toUpperCase()));
} catch (Throwable e3) {
error(cs, e2, "SpigotLib", "gyurix");
}
}
}
break;
case "#sub":
is.setDurability(Short.valueOf(String.valueOf(v)));
break;
case "#owner":
try {
SkullMeta sm = (SkullMeta) is.getItemMeta();
sm.setOwner(String.valueOf(v));
is.setItemMeta(sm);
} catch (Throwable ignored) {
}
break;
}
last = null;
}
}
if (is.hasItemMeta() && is.getItemMeta() != null) {
ItemMeta meta = is.getItemMeta();
if (meta.hasDisplayName() && meta.getDisplayName() != null)
meta.setDisplayName(SU.fillVariables(meta.getDisplayName(), vars));
if (meta.hasLore() && meta.getLore() != null) {
List<String> lore = meta.getLore();
for (int i = 0; i < lore.size(); i++)
lore.set(i, SU.fillVariables(lore.get(i), vars));
ArrayList<String> newLore = new ArrayList<>();
for (String l : lore) {
Collections.addAll(newLore, l.split("\n"));
}
meta.setLore(newLore);
}
is.setItemMeta(meta);
}
return is;
}
public static ItemStack fillVariables(Player plr, ItemStack is) {
if (is == null || is.getType() == Material.AIR)
return is;
is = is.clone();
if (is.hasItemMeta() && is.getItemMeta() != null) {
ItemMeta meta = is.getItemMeta();
if (meta.hasDisplayName() && meta.getDisplayName() != null)
meta.setDisplayName(VariableAPI.fillVariables(meta.getDisplayName(), plr));
if (meta.hasLore() && meta.getLore() != null) {
List<String> lore = meta.getLore();
for (int i = 0; i < lore.size(); i++)
lore.set(i, VariableAPI.fillVariables(lore.get(i), plr));
ArrayList<String> newLore = new ArrayList<>();
for (String l : lore)
Collections.addAll(newLore, l.split("\n"));
meta.setLore(newLore);
}
if (meta instanceof SkullMeta)
((SkullMeta) meta).setOwner(plr.getName());
is.setItemMeta(meta);
}
return is;
}
/**
* Get the numeric id of the given itemname, it works for both numeric and text ids.
*
* @param name the case insensitive material name of the item or the numeric id of the item.
* @return the numeric id of the requested item or 1, if the given name is incorrect or null
*/
public static ItemStack getItem(String name) {
return Items.getItem(name);
}
/**
* Gets the given lore storage meta from the given ItemStack
*
* @param is - The checkable ItemStack
* @param format - The format of the storage meta
* @param def - Default value to return if the meta was not found.
* @return The first found compatible lore storage meta or def if not found any.
*/
public static String getLoreStorageMeta(ItemStack is, String format, String def) {
if (is == null || is.getType() == Material.AIR || !is.hasItemMeta())
return def;
is = is.clone();
ItemMeta meta = is.getItemMeta();
if (!meta.hasLore())
return def;
int id2 = format.indexOf("<value>");
String prefix = format.substring(0, id2);
String suffix = format.substring(id2 + 7);
for (String s : meta.getLore()) {
if (s.startsWith(prefix) && s.endsWith(suffix))
return s.substring(prefix.length(), s.length() - suffix.length());
}
return def;
}
/**
* Gets the name of the given item
*
* @param is - The item which name we would like to get
* @return The name of the item
*/
public static String getName(ItemStack is) {
if (is == null || is.getType() == Material.AIR)
return "Air";
return is.getItemMeta().hasDisplayName() ? is.getItemMeta().getDisplayName() : toCamelCase(is.getType().name());
}
/**
* Makes item glowing by adding luck 1 enchant to it and hide enchants attribute
*
* @param item - The glowable item
* @return The glowing item
*/
public static ItemStack glow(ItemStack item) {
if (item == null || item.getType() == Material.AIR)
return item;
item = item.clone();
ItemMeta meta = item.getItemMeta();
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
item.setItemMeta(meta);
item.addUnsafeEnchantment(Enchantment.LUCK, 1);
return item;
}
/**
* A truth check for two items, if they are actually totally same or not
*
* @param item1 first item of the equal checking
* @param item2 second item of the equal checking
* @return True if the two itemstack contains exactly the same abilities (id, count, durability, metadata), false
* otherwise
*/
public static boolean itemEqual(ItemStack item1, ItemStack item2) {
return itemToString(item1).equals(itemToString(item2));
}
/**
* Converts an NBT JSON String to an ItemStack
*
* @param str - Convertable NBT JSON String
* @return Conversion result
*/
public static ItemStack itemFromNBTJson(String str) {
return null;
}
/**
* A truth check for two items, if they type is actually totally same or not.
* The only allowed difference between the stacks could be only their count.
*
* @param item1 first item of the similiar checking
* @param item2 second item of the similiar checking
* @return True if the two itemstack contains exactly the same abilities (id, durability, metadata), the item counts
* could be different; false otherwise.
*/
public static boolean itemSimilar(ItemStack item1, ItemStack item2) {
if (item1 == item2)
return true;
if (item1 == null || item2 == null || item1.getType() == Material.AIR || item2.getType() == Material.AIR)
return false;
item1 = item1.clone();
item1.setAmount(1);
item2 = item2.clone();
item2.setAmount(1);
return itemToString(item1).equals(itemToString(item2));
}
/**
* Converts an item to NBT Json format
*
* @param is - Convertable item
* @return Conversion result
*/
public static String itemToNBTJson(ItemStack is) {
return new ItemStackWrapper(is).getNbtData().toNMS().toString();
}
/**
* Converts an ItemStack to it's representing string
*
* @param in convertable ItemStack
* @return the conversion output String or "0:-1 0" if the given ItemStack is null
*/
public static String itemToString(ItemStack in) {
return itemToString(in, false);
}
/**
* Converts an ItemStack to it's representing string with the option to store all NBT tags of the item
*
* @param in - The convertable ItemStack
* @param useNBT - Store every nbt tag of the item
* @return The conversion output String or "0:-1 0" if the given ItemStack is null
*/
public static String itemToString(ItemStack in, boolean useNBT) {
if (in == null)
return "0:-1 0";
StringBuilder out = new StringBuilder();
out.append(Items.getName(new BlockData(in.getType(), in.getDurability())));
if (in.getDurability() != 0)
out.append(':').append(in.getDurability());
if (in.getAmount() != 1)
out.append(' ').append(in.getAmount());
if (useNBT) {
out.append(" nbt:").append(escapeText(new ItemStackWrapper(in).getMetaData().toNMS().toString()));
return out.toString();
}
ItemMeta meta = in.getItemMeta();
if (meta == null)
return out.toString();
if (ver.isAbove(v1_8))
for (ItemFlag f : meta.getItemFlags())
out.append(" hide:").append(f.name().substring(5));
if (meta.hasDisplayName())
out.append(" name:").append(escapeText(meta.getDisplayName()));
if (meta.hasLore())
out.append(" lore:").append(escapeText(StringUtils.join(meta.getLore(), '\n')));
for (Entry<Enchantment, Integer> ench : meta.getEnchants().entrySet()) {
out.append(' ').append(getEnchantName(ench.getKey())).append(':').append(ench.getValue());
}
if (meta instanceof BookMeta) {
BookMeta bmeta = (BookMeta) meta;
if (bmeta.hasAuthor())
out.append(" author:").append(bmeta.getAuthor());
if (bmeta.hasTitle())
out.append(" title:").append(bmeta.getTitle());
if (ver.isAbove(v1_13)) {
for (BaseComponent[] components : bmeta.spigot().getPages())
out.append(" page:").append(escapeText(ChatTag.fromBaseComponents(components).toExtraString()));
out.append(" generation:").append(bmeta.getGeneration());
} else {
for (String page : bmeta.getPages())
out.append(" page:").append(escapeText(page));
}
}
if (ver.isAbove(v1_8) && (meta instanceof BannerMeta)) {
BannerMeta bmeta = (BannerMeta) meta;
out.append(" color:").append(bmeta.getBaseColor() == null ? "BLACK" : bmeta.getBaseColor().name());
for (Pattern p : bmeta.getPatterns())
out.append(' ').append(p.getPattern().getIdentifier()).append(':').append(p.getColor().name());
} else if (meta instanceof LeatherArmorMeta) {
LeatherArmorMeta bmeta = (LeatherArmorMeta) meta;
Color c = bmeta.getColor();
if (!c.equals(Bukkit.getItemFactory().getDefaultLeatherColor()))
out.append(" color:").append(Integer.toHexString(c.asRGB()));
} else if (meta instanceof FireworkMeta) {
FireworkMeta bmeta = (FireworkMeta) meta;
out.append(" power:").append(bmeta.getPower());
for (FireworkEffect e : bmeta.getEffects()) {
out.append(' ').append(e.getType().name()).append(':');
boolean pref = false;
if (!e.getColors().isEmpty()) {
pref = true;
out.append("colors:");
for (Color c : e.getColors()) {
out.append(c.getRed()).append(',').append(c.getGreen()).append(',').append(c.getBlue()).append(';');
}
out.setLength(out.length() - 1);
}
if (!e.getFadeColors().isEmpty()) {
if (pref)
out.append('|');
else
pref = true;
out.append("fades:");
for (Color c : e.getFadeColors()) {
out.append(c.getRed()).append(',').append(c.getGreen()).append(',').append(c.getBlue()).append(';');
}
out.setLength(out.length() - 1);
}
if (e.hasFlicker()) {
if (pref)
out.append('|');
else
pref = true;
out.append("flicker");
}
if (e.hasTrail()) {
if (pref)
out.append('|');
out.append("trail");
}
}
} else if (meta instanceof PotionMeta) {
PotionMeta bmeta = (PotionMeta) meta;
if (ver.isAbove(v1_9)) {
PotionData pd = bmeta.getBasePotionData();
if (pd != null) {
out.append(" potion:").append(pd.getType().name());
if (pd.isExtended())
out.append(":E");
if (pd.isUpgraded())
out.append(":U");
}
}
for (PotionEffect e : bmeta.getCustomEffects()) {
out.append(' ').append(e.getType().getName()).append(':').append(e.getDuration()).append(':').append(e.getAmplifier());
if (ver.isAbove(v1_8))
if (!e.hasParticles())
out.append(":np");
if (!e.isAmbient())
out.append(":na");
}
} else if (meta instanceof SkullMeta) {
SkullMeta bmeta = (SkullMeta) meta;
if (bmeta.hasOwner())
out.append(" owner:").append(bmeta.getOwner());
} else if (meta instanceof EnchantmentStorageMeta) {
for (Entry<Enchantment, Integer> e : ((EnchantmentStorageMeta) meta).getStoredEnchants().entrySet()) {
out.append(" +").append(getEnchantName(e.getKey())).append(':').append(e.getValue());
}
}
if (in.getType().name().contains("MONSTER_EGG")) {
NBTPrimitive idNbt = (NBTPrimitive) new ItemStackWrapper(in).getMetaData().getCompound("EntityTag").get("id");
if (idNbt != null && idNbt.getData() instanceof String)
out.append(" mob:").append(((String) idNbt.getData()).replace("minecraft:", ""));
}
return out.toString();
}
/**
* Converts a map representation of a saved inventory to an actual Inventory.
* Completely overrides all the existing items in the inventory.
*
* @param map - The map containing the items and their slots of the saved inventory
*/
public static void loadInv(Map<Integer, ItemStack> map, Inventory inv) {
int size = inv instanceof PlayerInventory ? ver.isAbove(v1_9) ? 41 : 40 : inv.getSize();
for (int i = 0; i < size; ++i)
inv.setItem(i, map.get(i));
}
public static ItemStack makeItem(Material type, int amount, short sub, String name, String... lore) {
ItemStack is = new ItemStack(type, amount, sub);
ItemMeta im = is.getItemMeta();
im.setDisplayName(name);
im.setLore(Arrays.asList(lore));
is.setItemMeta(im);
return is;
}
public static ItemStack makeItem(Material type, String name, String... lore) {
ItemStack is = new ItemStack(type, 1, (short) 0);
ItemMeta im = is.getItemMeta();
im.setDisplayName(name);
im.setLore(Arrays.asList(lore));
is.setItemMeta(im);
return is;
}
public static ItemStack makeItem(Material type, int amount, short sub, String name, ArrayList<String> lore, Object... vars) {
ItemStack is = new ItemStack(type, amount, sub);
ItemMeta im = is.getItemMeta();
im.setDisplayName(name);
im.setLore(lore);
is.setItemMeta(im);
return fillVariables(is, vars);
}
/**
* Removes the given item from the given inventory
*
* @param inv - The inventory from which the item should be removed
* @param is - The removable item
* @return The remaining amount of the removable item
*/
public static int removeItem(Inventory inv, ItemStack is) {
int left = is.getAmount();
boolean pi = inv instanceof PlayerInventory;
int size = pi ? 36 : inv.getSize();
Iterator<Integer> it = new Iterator<Integer>() {
boolean first = true;
int id = 0;
@Override
public boolean hasNext() {
return id < size;
}
@Override
public Integer next() {
if (first) {
first = false;
if (pi)
return ((PlayerInventory) inv).getHeldItemSlot();
}
return id++;
}
};
while (it.hasNext()) {
Integer i = it.next();
ItemStack current = inv.getItem(i);
if (itemSimilar(current, is)) {
int am = current.getAmount();
if (left == am) {
inv.setItem(i, null);
return 0;
} else if (left < am) {
current.setAmount(am - left);
inv.setItem(i, current);
return 0;
} else {
inv.setItem(i, null);
left -= am;
}
}
}
return left;
}
/**
* Saves an inventory to a TreeMap containing the slots and the items of the given inventory
*
* @param inv - The saveable inventory
* @return The saving result
*/
public static TreeMap<Integer, ItemStack> saveInv(Inventory inv) {
int size = inv instanceof PlayerInventory ? ver.isAbove(v1_9) ? 41 : 40 : inv.getSize();
TreeMap<Integer, ItemStack> out = new TreeMap<>();
for (int i = 0; i < size; ++i) {
ItemStack is = inv.getItem(i);
if (is != null && is.getType() != Material.AIR)
out.put(i, is);
}
return out;
}
/**
* Converts an ItemStack representing string back to the ItemStack
*
* @param in string represantation of an ItemStack
* @return The conversion output ItemStack, or null if the given string is null
*/
public static ItemStack stringToItemStack(String in) {
if (in == null)
return null;
String[] parts = in.split(" ");
String[] idParts = parts[0].split(":");
ItemStack out = getItem(idParts[0]);
if (out == null)
return null;
int st = 1;
try {
out.setDurability(Short.valueOf(idParts[1]));
} catch (Throwable ignored) {
}
try {
out.setAmount(Short.valueOf(parts[1]));
st = 2;
} catch (Throwable ignored) {
}
int l = parts.length;
ItemMeta meta = out.getItemMeta();
ArrayList<String[]> remaining = new ArrayList<>();
ArrayList<String> attributes = new ArrayList<>();
for (int i = st; i < l; i++) {
String[] s = parts[i].split(":", 2);
s[0] = s[0].toUpperCase();
try {
Enchantment enc = getEnchant(s[0]);
if (enc == null)
enc = Enchantment.getByName(s[0].toUpperCase());
if (enc == null) {
if (ver.isAbove(v1_8)) {
if (s[0].equals("HIDE"))
meta.addItemFlags(ItemFlag.valueOf("HIDE_" + s[1].toUpperCase()));
}
switch (s[0]) {
case "NAME":
meta.setDisplayName(unescapeText(s[1]));
break;
case "LORE":
meta.setLore(Lists.newArrayList(unescapeText(s[1]).split("\n")));
break;
case "NBT":
return Bukkit.getUnsafe().modifyItemStack(out, unescapeText(s[1]));
case "ATTR":
attributes.add(s[1]);
break;
default:
remaining.add(s);
break;
}
} else {
meta.addEnchant(enc, Integer.valueOf(s[1]), true);
}
} catch (Throwable e) {
log(Main.pl, "§cError on deserializing §eItemMeta§c data of item \"§f" + in + "§c\"");
error(cs, e, "SpigotLib", "gyurix");
}
}
if (meta instanceof BookMeta) {
BookMeta bmeta = (BookMeta) meta;
for (String[] s : remaining) {
try {
String text = unescapeText(s[1]);
switch (s[0]) {
case "AUTHOR":
bmeta.setAuthor(text);
break;
case "TITLE":
bmeta.setTitle(text);
break;
case "PAGE":
if (ver.isAbove(v1_13))
bmeta.spigot().addPage(ChatTag.fromExtraText(text).toBaseComponents());
else
bmeta.addPage(text);
break;
case "GENERATION":
bmeta.setGeneration(BookMeta.Generation.valueOf(text.toUpperCase()));
break;
}
} catch (Throwable e) {
log(Main.pl, "§cError on deserializing §eBookMeta§c data of item \"§f" + in + "§c\"");
error(cs, e, "SpigotLib", "gyurix");
}
}
}
if (ver.isAbove(v1_8))
if (meta instanceof BannerMeta) {
BannerMeta bmeta = (BannerMeta) meta;
for (String[] s : remaining) {
try {
PatternType type = PatternType.getByIdentifier(s[0].toLowerCase());
if (type == null) {
if (s[0].equals("COLOR")) {
bmeta.setBaseColor(DyeColor.valueOf(s[1].toUpperCase()));
} else {
PatternType pt = PatternType.getByIdentifier(s[0].toLowerCase());
if (pt != null) {
bmeta.addPattern(new Pattern(DyeColor.valueOf(s[1].toUpperCase()), pt));
}
}
} else {
bmeta.addPattern(new Pattern(DyeColor.valueOf(s[1].toUpperCase()), type));
}
} catch (Throwable e) {
log(Main.pl, "§cError on deserializing §eBannerMeta§c data of item \"§f" + in + "§c\"");
error(cs, e, "SpigotLib", "gyurix");
}
}
}
if (meta instanceof LeatherArmorMeta) {
LeatherArmorMeta bmeta = (LeatherArmorMeta) meta;
for (String[] s : remaining) {
try {
if (s[0].equals("COLOR")) {
String[] color = s[1].split(",", 3);
if (color.length == 3)
bmeta.setColor(Color.fromRGB(Integer.valueOf(color[0]), Integer.valueOf(color[1]), Integer.valueOf(color[2])));
else
bmeta.setColor(Color.fromRGB(Integer.parseInt(color[0], 16)));
}
} catch (Throwable e) {
log(Main.pl, "§cError on deserializing §eLeatherArmorMeta§c data of item \"§f" + in + "§c\"");
error(cs, e, "SpigotLib", "gyurix");
}
}
} else if (meta instanceof FireworkMeta) {
FireworkMeta bmeta = (FireworkMeta) meta;
for (String[] s : remaining) {
try {
if (s[0].equals("FPOWER")) {
bmeta.setPower(Integer.valueOf(s[1]));
} else {
Type type = Type.valueOf(s[0]);
Builder build = FireworkEffect.builder().with(type);
for (String d : s[1].toUpperCase().split("\\|")) {
String[] d2 = d.split(":", 2);
switch (d2[0]) {
case "COLORS":
for (String colors : d2[1].split(";")) {
String[] color = colors.split(",", 3);
build.withColor(Color.fromRGB(Integer.valueOf(color[0]), Integer.valueOf(color[1]), Integer.valueOf(color[2])));
}
break;
case "FADES":
for (String fades : d2[1].split(";")) {
String[] fade = fades.split(",", 3);
build.withFade(Color.fromRGB(Integer.valueOf(fade[0]), Integer.valueOf(fade[1]), Integer.valueOf(fade[2])));
}
break;
case "FLICKER":
build.withFlicker();
break;
case "TRAIL":
build.withTrail();
break;
}
}
bmeta.addEffect(build.build());
}
} catch (Throwable e) {
log(Main.pl, "§cError on deserializing §eFireworkMeta§c data of item \"§f" + in + "§c\"");
error(cs, e, "SpigotLib", "gyurix");
}
}
} else if (meta instanceof PotionMeta) {
PotionMeta bmeta = (PotionMeta) meta;
for (String[] s : remaining) {
try {
if (ver.isAbove(v1_9) && s[0].equalsIgnoreCase("potion")) {
String[] s2 = s[1].split(":");
boolean ext = false;
boolean upg = false;
if (s2.length > 1) {
if (s2[1].equals("E"))
ext = true;
else if (s2[1].equals("U"))
upg = true;
}
if (s2.length > 2) {
if (s2[2].equals("E"))
ext = true;
else if (s2[2].equals("U"))
upg = true;
}
PotionData pd = new PotionData(PotionType.valueOf(s2[0].toUpperCase()), ext, upg);
bmeta.setBasePotionData(pd);
continue;
}
PotionEffectType type = PotionEffectType.getByName(s[0]);
if (type != null) {
String[] s2 = s[1].split(":");
if (ver.isAbove(v1_8)) {
bmeta.addCustomEffect(new PotionEffect(type, Integer.valueOf(s2[0]), Integer.valueOf(s2[1]),
!ArrayUtils.contains(s2, "na"), !ArrayUtils.contains(s2, "np")), false);
} else {
bmeta.addCustomEffect(new PotionEffect(type, Integer.valueOf(s2[0]), Integer.valueOf(s2[1]),
!ArrayUtils.contains(s2, "na")), false);
}
}
} catch (Throwable e) {
log(Main.pl, "§cError on deserializing §ePotionMeta§c data of item \"§f" + in + "§c\"");
error(cs, e, "SpigotLib", "gyurix");
}
}
} else if (meta instanceof SkullMeta) {
SkullMeta bmeta = (SkullMeta) meta;
for (String[] s : remaining) {
try {
if (s[0].equals("OWNER")) {
bmeta.setOwner(s[1]);
}
} catch (Throwable e) {
log(Main.pl, "§cError on deserializing §eSkullMeta§c data of item \"§f" + in + "§c\"");
error(cs, e, "SpigotLib", "gyurix");
}
}
} else if (meta instanceof EnchantmentStorageMeta) {
EnchantmentStorageMeta bmeta = (EnchantmentStorageMeta) meta;
for (String[] s : remaining) {
try {
String en = s[0].substring(1);
Enchantment enc = getEnchant(en);
if (enc != null)
bmeta.addStoredEnchant(enc, Integer.valueOf(s[1]), true);
} catch (Throwable e) {
log(Main.pl, "§cError on deserializing §eEnchantmentStorageMeta§c data of item \"§f" + in + "§c\"");
error(cs, e, "SpigotLib", "gyurix");
}
}
}
out.setItemMeta(meta);
if (out.getType().name().equals("MONSTER_EGG")) {
for (String[] s : remaining) {
if (s[0].equals("MOB")) {
ItemStackWrapper isw = new ItemStackWrapper(out);
isw.getMetaData().getCompound("EntityTag").set("id", "minecraft:" + s[1].toLowerCase());
return isw.toBukkitStack();
}
}
}
if (!attributes.isEmpty()) {
ItemStackWrapper isw = new ItemStackWrapper(out);
NBTList attrs = new NBTList();
AtomicInteger id = new AtomicInteger();
attributes.forEach((k) -> {
String[] d = k.split(":", 2);
char op = d[1].charAt(0);
int operation = op == '*' ? 1 : op == 'o' ? 2 : 0;
double am = Double.valueOf(d[1].substring(1));
if (op == '-')
am = -am;
NBTCompound attr = new NBTCompound();
attr.set("AttributeName", d[0]);
attr.set("Name", "a" + (id.incrementAndGet()));
attr.set("Operation", operation);
attr.set("Amount", am);
attr.set("UUIDLeast", rand.nextLong());
attr.set("UUIDMost", rand.nextLong());
attrs.add(attr);
});
isw.getMetaData().set("AttributeModifiers", attrs);
out = isw.toBukkitStack();
}
return out;
}
}
| 33,983 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
LocationData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/LocationData.java | package gyurix.spigotutils;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.protocol.utils.BlockLocation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.util.Vector;
public class LocationData implements StringSerializable {
public float pitch;
public String world;
public double x;
public double y;
public float yaw;
public double z;
public LocationData(String in) {
String[] d = in.split(" ");
switch (d.length) {
case 3:
x = Double.valueOf(d[0]);
y = Double.valueOf(d[1]);
z = Double.valueOf(d[2]);
return;
case 4:
world = d[0];
x = Double.valueOf(d[1]);
y = Double.valueOf(d[2]);
z = Double.valueOf(d[3]);
return;
case 5:
x = Double.valueOf(d[0]);
y = Double.valueOf(d[1]);
z = Double.valueOf(d[2]);
yaw = Float.valueOf(d[3]).floatValue();
pitch = Float.valueOf(d[4]).floatValue();
return;
case 6:
world = d[0];
x = Double.valueOf(d[1]);
y = Double.valueOf(d[2]);
z = Double.valueOf(d[3]);
yaw = Float.valueOf(d[4]).floatValue();
pitch = Float.valueOf(d[5]).floatValue();
return;
}
}
public LocationData() {
}
public LocationData(LocationData ld) {
this(ld.world, ld.x, ld.y, ld.z, ld.yaw, ld.pitch);
}
public LocationData(String world, double x, double y, double z, float yaw, float pitch) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
this.yaw = yaw;
this.pitch = pitch;
}
public LocationData(BlockLocation bl) {
this(bl.x, bl.y, bl.z);
}
public LocationData(double x, double y, double z) {
this(null, x, y, z, 0.0f, 0.0f);
}
public LocationData(Vector v) {
this(v.getX(), v.getY(), v.getZ());
}
public LocationData(String world, double x, double y, double z) {
this(world, x, y, z, 0.0f, 0.0f);
}
public LocationData(double x, double y, double z, float yaw, float pitch) {
this(null, x, y, z, yaw, pitch);
}
public LocationData(Block bl) {
this(bl.getWorld().getName(), bl.getX(), bl.getY(), bl.getZ(), 0.0f, 0.0f);
}
public LocationData(Location loc) {
this(loc.getWorld().getName(), loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch());
}
public LocationData add(LocationData ld) {
return ld == null ? this : add(ld.x, ld.y, ld.z);
}
public LocationData add(double nx, double ny, double nz) {
x += nx;
y += ny;
z += nz;
return this;
}
public LocationData add(double num) {
x += num;
y += num;
z += num;
return this;
}
public double dist(LocationData loc) {
return Math.sqrt((loc.x - x) * (loc.x - x) + (loc.y - y) * (loc.y - y) + (loc.z - z) * (loc.z - z));
}
public double distNoY(LocationData loc) {
return Math.sqrt((loc.x - x) * (loc.x - x) + (loc.z - z) * (loc.z - z));
}
public Block getBlock() {
if (!isAvailable()) {
return null;
}
return Bukkit.getWorld(world).getBlockAt((int) (x < 0 ? x - 0.999 : x), (int) y, (int) (z < 0 ? z - 0.999 : z));
}
public BlockLocation getBlockLocation() {
return new BlockLocation((int) x, (int) y, (int) z);
}
public Vector getDirection() {
Vector vector = new Vector();
vector.setY(-Math.sin(Math.toRadians(pitch)));
double xz = Math.cos(Math.toRadians(pitch));
vector.setX(-xz * Math.sin(Math.toRadians(yaw)));
vector.setZ(xz * Math.cos(Math.toRadians(yaw)));
return vector;
}
public LocationData setDirection(Vector vector) {
double x = vector.getX();
double z = vector.getZ();
if (x == 0.0 && z == 0.0) {
pitch = vector.getY() > 0.0 ? -90 : 90;
return this;
}
double theta = Math.atan2(-x, z);
yaw = (float) Math.toDegrees((theta + 6.283185307179586) % 6.283185307179586);
double x2 = x * x;
double z2 = z * z;
double xz = Math.sqrt(x2 + z2);
pitch = (float) Math.toDegrees(Math.atan(-vector.getY() / xz));
return this;
}
public Location getLocation() {
return new Location(world == null ? null : Bukkit.getWorld(world), x, y, z, yaw, pitch);
}
public Location getLocation(World w) {
return new Location(w, x, y, z, yaw, pitch);
}
public World getWorld() {
return Bukkit.getWorld(world);
}
public int hashCode() {
int hash = 57 + (world != null ? world.hashCode() : 0);
hash = 19 * hash + (int) (Double.doubleToLongBits(x) ^ Double.doubleToLongBits(x) >>> 32);
hash = 19 * hash + (int) (Double.doubleToLongBits(y) ^ Double.doubleToLongBits(y) >>> 32);
hash = 19 * hash + (int) (Double.doubleToLongBits(z) ^ Double.doubleToLongBits(z) >>> 32);
hash = 19 * hash + Float.floatToIntBits(pitch);
hash = 19 * hash + Float.floatToIntBits(yaw);
return hash;
}
public boolean equals(Object obj) {
if (!(obj instanceof LocationData))
return false;
LocationData ld = (LocationData) obj;
return (world == null && ld.world == null || world != null && ld.world != null && world.equals(ld.world)) && x == ld.x && y == ld.y && z == ld.z && yaw == ld.yaw && pitch == ld.pitch;
}
public LocationData clone() {
return new LocationData(this);
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
if (world != null)
out.append(' ').append(world);
out.append(' ').append(to2Digit(x)).append(' ').append(to2Digit(y)).append(' ').append(to2Digit(z));
if (yaw != 0.0f || pitch != 0.0f)
out.append(' ').append(to2Digit(yaw)).append(' ').append(to2Digit(pitch));
return out.substring(1);
}
public boolean isAvailable() {
return world != null && Bukkit.getWorld(world) != null;
}
public LocationData multiple(LocationData ld) {
return ld == null ? this : multiple(ld.x, ld.y, ld.z);
}
public LocationData multiple(double nx, double ny, double nz) {
x *= nx;
y *= ny;
z *= nz;
return this;
}
public LocationData multiple(double num) {
x *= num;
y *= num;
z *= num;
return this;
}
public LocationData subtract(LocationData ld) {
return ld == null ? this : subtract(ld.x, ld.y, ld.z);
}
public LocationData subtract(double nx, double ny, double nz) {
x -= nx;
y -= ny;
z -= nz;
return this;
}
public LocationData subtract(double num) {
x -= num;
y -= num;
z -= num;
return this;
}
public double to2Digit(double in) {
return ((long) (in * 100)) / 100.0;
}
public BlockLocation toBlockLocation() {
return new BlockLocation((int) (x < 0 ? (x - 1) : x), (int) y, (int) (z < 0 ? (z - 1) : z));
}
public String toLongString() {
StringBuilder out = new StringBuilder();
out.append(world).append(' ').append(x).append(' ').append(y).append(' ').append(z).append(' ').append(yaw).append(' ').append(pitch);
return out.substring(1);
}
public Vector toVector() {
return new Vector(x, y, z);
}
}
| 7,086 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
SafeTools.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/SafeTools.java | package gyurix.spigotutils;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import org.bukkit.plugin.Plugin;
import java.util.function.Consumer;
public class SafeTools {
public static void async(SafeRunnable sr) {
async(detectPlugin(sr), sr);
}
private static void async(Plugin pl, SafeRunnable sr) {
SU.sch.runTaskAsynchronously(pl, of(sr));
}
public static <T> void async(SafeCallable<T> callable, SafeConsumer<T> consumer) {
async(detectPlugin(callable), () -> consumer.accept(of(callable).call()));
}
public static <T> void async(SafeConsumer<T> consumer, T data) {
async(detectPlugin(consumer), () -> consumer.accept(data));
}
private static Plugin detectPlugin(Object o) {
return o == null ? Main.pl : SU.getPlugin(o.getClass());
}
public static Runnable of(SafeRunnable sr) {
return () -> {
try {
sr.run();
} catch (Throwable e) {
Plugin p = SU.getPlugin(sr.getClass());
String pln = p == null ? "Server" : p.getName();
SU.error(SU.cs, e, pln, "gyurix");
}
};
}
public static <T> CleanCallable<T> of(SafeCallable<T> sc) {
return () -> {
try {
return sc.call();
} catch (Throwable e) {
Plugin p = SU.getPlugin(sc.getClass());
String pln = p == null ? "Server" : p.getName();
SU.error(SU.cs, e, pln, "gyurix");
}
return null;
};
}
public <T> Consumer<T> of(SafeConsumer<T> sc) {
return (data) -> {
try {
sc.accept(data);
} catch (Throwable e) {
Plugin p = SU.getPlugin(sc.getClass());
String pln = p == null ? "Server" : p.getName();
SU.error(SU.cs, e, pln, "gyurix");
}
};
}
public interface CleanCallable<T> {
T call();
}
public interface SafeCallable<T> {
T call() throws Throwable;
}
public interface SafeConsumer<T> {
void accept(T data) throws Throwable;
}
public interface SafeRunnable {
void run() throws Throwable;
}
}
| 2,021 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
MultiIntData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/MultiIntData.java | package gyurix.spigotutils;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.spigotlib.SU;
/**
* Created by GyuriX.
*/
public class MultiIntData implements StringSerializable {
int[] minValues, maxValues;
public MultiIntData(String in) {
String[] ss = in.split(", *");
minValues = new int[ss.length];
maxValues = new int[ss.length];
int i = 0;
for (String s : ss) {
String[] d = s.split("=", 2);
int first = Integer.valueOf(d[0]);
minValues[i] = first;
if (d.length == 2) {
int second = Integer.valueOf(d[1]);
maxValues[i] = second;
} else maxValues[i] = first;
++i;
}
}
public boolean contains(int value) {
for (int i = 0; i < minValues.length; i++) {
if (minValues[i] <= value && maxValues[i] >= value)
return true;
}
return false;
}
public int random() {
int id = SU.rand.nextInt(minValues.length);
return minValues[id] + SU.rand.nextInt(maxValues[id] - minValues[id] + 1);
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < minValues.length; i++) {
sb.append(',');
sb.append(minValues[i]);
if (minValues[i] != maxValues[i]) {
sb.append('=');
sb.append(maxValues[i]);
}
}
return sb.length() == 0 ? "" : sb.substring(1);
}
}
| 1,387 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BlockUtils.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/BlockUtils.java | package gyurix.spigotutils;
import gyurix.protocol.utils.Direction;
import gyurix.spigotlib.SU;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.util.Vector;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import static gyurix.protocol.Reflection.*;
import static java.lang.Math.*;
/**
* Created by GyuriX on 2016. 07. 13..
*/
public class BlockUtils {
private static Method getBlockByIdM;
private static Method getCombinedIdM;
private static Field matIdF, bdStateF, blockF;
private static Map<Integer, Material> materialById;
private static Method nmsBlockToMaterialM;
static {
try {
Class<?> blCl = getNMSClass("Block");
Class<?> bdCl = getNMSClass("IBlockData");
blockF = getFirstFieldOfType(bdCl, blCl);
matIdF = getField(Material.class, "id");
materialById = new HashMap<>();
for (Material m : Material.values())
materialById.put(matIdF.getInt(m), m);
if (ver.isAbove(ServerVersion.v1_13)) {
bdStateF = getField(getOBCClass("block.data.CraftBlockData"), "state");
nmsBlockToMaterialM = getMethod(getOBCClass("util.CraftMagicNumbers"), "getMaterial", blCl);
}
getBlockByIdM = getMethod(blCl, "getByCombinedId", int.class);
getCombinedIdM = getMethod(blCl, "getCombinedId", bdCl);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public static BlockData combinedIdToBlockData(int id) {
if (ver.isAbove(ServerVersion.v1_13)) {
try {
return new BlockData((Material) nmsBlockToMaterialM.invoke(null, blockF.get(combinedIdToNMSBlockData(id))));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
return new BlockData(materialById.get(id & 4095), (short) (id >> 12 & 15));
}
public static Object combinedIdToNMSBlockData(int id) {
try {
return getBlockByIdM.invoke(null, id);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public static int getCombinedId(BlockData bd) {
if (ver.isAbove(ServerVersion.v1_13)) {
try {
return getCombinedId(bdStateF.get(bd.getType().createBlockData()));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
return (((int) bd.data) << 12) + bd.getType().getId();
}
public static int getCombinedId(Object nmsBlock) {
try {
return (int) getCombinedIdM.invoke(null, nmsBlock);
} catch (Throwable e) {
e.printStackTrace();
}
return 0;
}
public static Vector getDirection(float yaw, float pitch) {
double xz = cos(toRadians(pitch));
return new Vector(-xz * sin(toRadians(yaw)), -sin(toRadians(pitch)), xz * cos(toRadians(yaw)));
}
public static float getPitch(Vector vec) {
double x = vec.getX();
double z = vec.getZ();
if (x == 0 && z == 0)
return vec.getY() == 0 ? 0 : vec.getY() > 0 ? 90 : -90;
return (float) toDegrees(atan(-vec.getY() / sqrt(x * x + z * z)));
}
public static byte getSignDurability(float yaw) {
yaw -= 168.75f;
while (yaw < 0)
yaw += 360;
return (byte) (yaw / 22.5f);
}
public static Direction getSimpleDirection(float yaw, float pitch) {
while (yaw < 45)
yaw += 360;
yaw -= 45;
return pitch > 45 ? Direction.DOWN : pitch < -45 ? Direction.UP : Direction.values()[(int) (yaw / 90 + 2)];
}
public static Location getYMax(World world, int minx, int minz) {
for (int y = 255; y > 0; y--) {
Block b = world.getBlockAt(minx, y, minz);
if (b.getType().isSolid())
return b.getLocation();
}
return new Location(world, minx, 1, minz);
}
public static float getYaw(Vector vec) {
return (float) ((toDegrees(atan2(-vec.getX(), vec.getZ())) + 720) % 360);
}
}
| 3,958 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CuboidArea.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/CuboidArea.java | package gyurix.spigotutils;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.protocol.utils.BlockLocation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import static gyurix.spigotlib.SU.rand;
import static java.lang.Integer.MIN_VALUE;
/**
* Class representing a CuboidArea, with a first and second block location and
* with or without world parameter
*/
public class CuboidArea extends Area implements StringSerializable, Cloneable {
/**
* The first position of this CuboidArea, containing the minX, minY and minZ coordinates
*/
public BlockLocation pos1;
/**
* The second position of this CuboidArea, containing the maxX, maxY and maxZ coordinates
*/
public BlockLocation pos2;
/**
* Constructs a new not properly set up CuboidArea
*/
public CuboidArea() {
}
/**
* Constructs a new CuboidArea from the given String
*
* @param in - The String from which the CuboidArea should be constructed
* Accepted input String formats:
* world
* minX minY minZ maxX maxY maxZ
* world minX minY minZ maxX maxY maxZ
*/
public CuboidArea(String in) {
try {
String[] d = in.split(" ", 7);
if (d.length == 1) {
world = d[0];
return;
} else if (d.length == 6) {
pos1 = new BlockLocation(Integer.parseInt(d[0]), Integer.parseInt(d[1]), Integer.parseInt(d[2]));
pos2 = new BlockLocation(Integer.parseInt(d[3]), Integer.parseInt(d[4]), Integer.parseInt(d[5]));
} else {
world = d[0];
pos1 = new BlockLocation(Integer.parseInt(d[1]), Integer.parseInt(d[2]), Integer.parseInt(d[3]));
pos2 = new BlockLocation(Integer.parseInt(d[4]), Integer.parseInt(d[5]), Integer.parseInt(d[6]));
}
fix();
} catch (Throwable e) {
e.printStackTrace();
}
}
public CuboidArea(String world, BlockLocation pos1, BlockLocation pos2) {
this.world = world;
this.pos1 = pos1;
this.pos2 = pos2;
}
public CuboidArea(LocationData pos1, LocationData pos2) {
this.pos1 = pos1.getBlockLocation();
this.pos2 = pos2.getBlockLocation();
}
public CuboidArea(BlockLocation pos1, BlockLocation pos2) {
this.pos1 = pos1;
this.pos2 = pos2;
}
public static void resetOutlineBlock(Block block, Player plr) {
plr.sendBlockChange(block.getLocation(), block.getType(), block.getData());
}
public CuboidArea add(int x, int y, int z) {
return new CuboidArea(world, new BlockLocation(pos1.x + x, pos1.y + y, pos1.z + z), new BlockLocation(pos2.x + x, pos2.y + y, pos2.z + z));
}
/**
* Makes a clone of the CuboidArea by keeping all of it's properties
*
* @return The cloned version of this CuboidArea
*/
public CuboidArea clone() {
return new CuboidArea(world, pos1.clone(), pos2.clone());
}
@Override
public String toString() {
return world == null ? pos1 + " " + pos2 : world + ' ' + pos1 + ' ' + pos2;
}
/**
* Makes a clone of this CuboidArea and fixes it's pos1 and pos2 using the @see fix method
*
* @return The cloned and fixed version of this CuboidArea
*/
public CuboidArea cloneFixed() {
CuboidArea area = clone();
area.fix();
return area;
}
public boolean contains(Location loc) {
return loc.getX() + 0.5 >= pos1.x && loc.getY() >= pos1.y && loc.getZ() + 0.5 >= pos1.z && loc.getX() - 1.5 <= pos2.x && loc.getY() <= pos2.y && loc.getZ() - 1.5 <= pos2.z;
}
public boolean contains(Block loc) {
return loc.getX() >= pos1.x && loc.getY() >= pos1.y && loc.getZ() >= pos1.z
&& loc.getX() <= pos2.x && loc.getY() <= pos2.y && loc.getZ() <= pos2.z;
}
public boolean contains(LocationData loc) {
return !(world != null && loc.world != null && !world.equals(loc.world)) && loc.x + 0.5 >= pos1.x && loc.y >= pos1.y && loc.z + 0.5 >= pos1.z && loc.x - 1.5 <= pos2.x && loc.y <= pos2.y && loc.z - 1.5 <= pos2.z;
}
public boolean contains(BlockLocation loc) {
return loc.x >= pos1.x && loc.y >= pos1.y && loc.z >= pos1.z
&& loc.x <= pos2.x && loc.y <= pos2.y && loc.z <= pos2.z;
}
public boolean contains(int x, int z) {
return pos1.x <= x && pos2.x >= x && pos1.z <= z && pos2.z >= z;
}
/**
* Fix the min and max points for ensuring that the pos1 contains the minX, minY and minZ, while
* the pos2 contains the maxX, maxY and maxZ and they does not contain these informations oppositely
*/
public void fix() {
int tmp;
if (pos1.x > pos2.x) {
tmp = pos1.x;
pos1.x = pos2.x;
pos2.x = tmp;
}
if (pos1.y > pos2.y) {
tmp = pos1.y;
pos1.y = pos2.y;
pos2.y = tmp;
}
if (pos1.z > pos2.z) {
tmp = pos1.z;
pos1.z = pos2.z;
pos2.z = tmp;
}
}
@Override
public List<Block> getBlocks(World w) {
List<Block> blocks = new ArrayList<>();
for (int x = pos1.x; x <= pos2.x; ++x)
for (int z = pos1.z; z <= pos2.z; ++z)
for (int y = pos1.y; y <= pos2.y; ++y) {
blocks.add(w.getBlockAt(x, y, z));
}
return blocks;
}
public LocationData getCenter() {
return new LocationData(0.5 + (pos1.x + pos2.x) / 2D, (pos1.y + pos2.y) / 2D, (pos1.z + pos2.z) / 2D);
}
@Override
public List<Block> getOutlineBlocks(World w) {
List<Block> outlineBlocks = new ArrayList<>();
for (int x = pos1.x + 1; x < pos2.x; x++) {
outlineBlocks.add(w.getBlockAt(x, pos1.y, pos1.z));
outlineBlocks.add(w.getBlockAt(x, pos1.y, pos2.z));
outlineBlocks.add(w.getBlockAt(x, pos2.y, pos1.z));
outlineBlocks.add(w.getBlockAt(x, pos2.y, pos2.z));
}
for (int y = pos1.y + 1; y < pos2.y; y++) {
outlineBlocks.add(w.getBlockAt(pos1.x, y, pos1.z));
outlineBlocks.add(w.getBlockAt(pos1.x, y, pos2.z));
outlineBlocks.add(w.getBlockAt(pos2.x, y, pos1.z));
outlineBlocks.add(w.getBlockAt(pos2.x, y, pos2.z));
}
for (int z = pos1.z; z <= pos2.z; z++) {
outlineBlocks.add(w.getBlockAt(pos1.x, pos1.y, z));
outlineBlocks.add(w.getBlockAt(pos1.x, pos2.y, z));
outlineBlocks.add(w.getBlockAt(pos2.x, pos1.y, z));
outlineBlocks.add(w.getBlockAt(pos2.x, pos2.y, z));
}
return outlineBlocks;
}
public boolean isBorder(int x, int z) {
return (x == pos1.x || z == pos1.z || x == pos2.x || z == pos2.z) && contains(x, z);
}
public boolean isDefined() {
return pos1 != null && pos2 != null && pos1.isDefined() && pos2.isDefined();
}
public Location randomLoc(World w) {
return new Location(w, rand(pos1.x, pos2.x), rand(pos1.y, pos2.y), rand(pos1.z, pos2.z));
}
public Location randomLoc() {
return new Location(Bukkit.getWorld(world), rand(pos1.x, pos2.x), rand(pos1.y, pos2.y), rand(pos1.z, pos2.z));
}
public int size() {
return (pos2.x - pos1.x + 1) * (pos2.y - pos1.y + 1) * (pos2.z - pos1.z + 1);
}
public CuboidArea subtract(int x, int y, int z) {
return add(-x, -y, -z);
}
/**
* Converts this CuboidArea to an @see UnlimitedYArea
*
* @return The conversion result
*/
public UnlimitedYArea toUnlimitedYArea() {
return new UnlimitedYArea(pos1 == null ? MIN_VALUE : pos1.x, pos1 == null ? MIN_VALUE : pos1.z, pos2 == null ? MIN_VALUE : pos2.x, pos2 == null ? MIN_VALUE : pos2.z);
}
}
| 7,481 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Orderable.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/Orderable.java | package gyurix.spigotutils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeSet;
/**
* Created by GyuriX on 2015.12.29..
*/
public class Orderable<K, V extends Comparable> implements Comparable<Orderable<K, V>> {
public final K key;
public final V value;
public Orderable(K key, V value) {
this.key = key;
this.value = value;
}
public static <K, V extends Comparable> HashMap<K, Integer> makeMap(ArrayList<Orderable<K, V>> topList) {
HashMap<K, Integer> map = new HashMap<>();
int id = 1;
for (Orderable<K, V> o : topList) {
map.put(o.key, id++);
}
return map;
}
public static <K, V extends Comparable> TreeSet<Orderable<K, V>> order(Map<K, V> data) {
TreeSet<Orderable<K, V>> out = new TreeSet<>();
for (Entry<K, V> e : data.entrySet()) {
out.add(new Orderable(e.getKey(), e.getValue()));
}
return out;
}
@Override
public int compareTo(Orderable<K, V> o) {
if (value.compareTo(o.value) == 0)
return key.toString().compareTo(o.key.toString());
return 0 - value.compareTo(o.value);
}
@Override
public int hashCode() {
return key.hashCode() * 100000 + value.hashCode();
}
@Override
public String toString() {
return key + " - " + value;
}
}
| 1,338 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Area.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/Area.java | package gyurix.spigotutils;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import java.util.List;
public abstract class Area {
/**
* The world of this Area, might be null, if it's not defined
*/
public String world;
public List<Block> getBlocks() {
if (world == null)
throw new RuntimeException("No world argument provided");
return getBlocks(Bukkit.getWorld(world));
}
public abstract List<Block> getBlocks(World w);
public List<Block> getOutlineBlocks() {
if (world == null)
throw new RuntimeException("No world argument provided");
return getOutlineBlocks(Bukkit.getWorld(world));
}
public abstract List<Block> getOutlineBlocks(World w);
public void resetOutlineWithBlock(Player plr) {
getBlocks(plr.getWorld()).forEach(b -> new BlockData(b).sendChange(plr, b.getLocation()));
}
public void showOutlineWithBlock(Player plr, BlockData bd) {
getBlocks(plr.getWorld()).forEach(b -> bd.sendChange(plr, b.getLocation()));
}
}
| 1,067 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BlockData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/BlockData.java | package gyurix.spigotutils;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.protocol.Reflection;
import gyurix.protocol.utils.WrappedData;
import gyurix.spigotlib.Items;
import gyurix.spigotlib.SU;
import lombok.SneakyThrows;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* Class used for storing the data of a block, or an item
*/
public class BlockData implements StringSerializable, Comparable<BlockData>, WrappedData {
/**
* True if the BlockData can be applied to any subtype of the block
*/
public boolean anydata = true;
/**
* The requested subtype of the block
*/
public short data;
/**
* The requested type of the block
*/
public Material material;
/**
* Constructs a new BlockData representing the type of the given block
*
* @param b - Target Block
*/
public BlockData(Block b) {
material = b.getType();
if (Reflection.ver.isAbove(ServerVersion.v1_14)) {
anydata = true;
return;
}
data = b.getData();
anydata = false;
}
/**
* Constructs a new BlockData representing the type of the given block state
*
* @param b - Target Block
*/
public BlockData(BlockState b) {
material = b.getType();
data = b.getRawData();
anydata = false;
}
/**
* Makes a new Block data from a String, which should have format [itemId|itemName][:subType]
*
* @param in - The convertable String
*/
public BlockData(String in) {
String[] s = in.split(":", 2);
try {
try {
material = Material.valueOf(s[0].toUpperCase());
} catch (Throwable e) {
material = Items.getMaterial(Integer.parseInt(s[0]));
}
} catch (Throwable e) {
SU.cs.sendMessage("§cInvalid item: §e" + in);
}
if (s.length == 2)
try {
data = Short.parseShort(s[1]);
anydata = false;
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
/**
* Makes a new BlockData from an ItemStack
*
* @param is - The convertable ItemStack
*/
public BlockData(ItemStack is) {
if (is == null || is.getType() == Material.AIR)
return;
material = is.getType();
data = is.getDurability();
anydata = false;
}
public BlockData(Material type) {
material = type;
}
public BlockData(Material type, short durability) {
material = type;
data = durability;
anydata = false;
}
@Override
public int compareTo(BlockData o) {
return Integer.compare(hashCode(), o.hashCode());
}
public Material getType() {
return material;
}
public int hashCode() {
return (material.ordinal() << 5) + (anydata ? 16 : data);
}
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != BlockData.class) {
return false;
}
BlockData bd = (BlockData) obj;
return bd.material == material && (bd.data == data || bd.anydata || anydata);
}
/**
* Makes a copy of the BlockData, storing all it's parameters
*
* @return The copy of the BlockData
*/
public BlockData clone() {
return anydata ? new BlockData(material) : new BlockData(material, data);
}
@Override
public String toString() {
return anydata ? material.name() : material.name() + ':' + data;
}
/**
* Checks if the given block has the same type as this block data.
*
* @param b - Checkable block
* @return True if the block's type is the same as this block data
*/
public boolean isBlock(Block b) {
byte bdata = b.getData();
return material == b.getType() && (anydata || bdata == data);
}
public void sendChange(Player plr, Location loc) {
plr.sendBlockChange(loc, getType(), (byte) data);
}
/**
* Sets the given blocks type and id to the one stored by this BlockData with allowing Minecraft physics calculations.
*
* @param b - Setable block
*/
@SneakyThrows
public void setBlock(Block b) {
b.setType(getType());
if (Reflection.ver.isBellow(ServerVersion.v1_12))
Reflection.getMethod(Block.class, "setData", byte.class).invoke(b, (byte) data);
}
/**
* Sets the given blocks type and id to the one stored by this BlockData without allowing Minecraft physics calculations.
*
* @param b - Setable block
*/
@SneakyThrows
public void setBlockNoPhysics(Block b) {
b.setType(getType());
if (Reflection.ver.isBellow(ServerVersion.v1_12))
Reflection.getMethod(Block.class, "setData", byte.class, boolean.class).invoke(b, (byte) data, false);
}
/**
* Converts this block data to an item
*
* @return The conversion result
*/
public ItemStack toItem() {
return new ItemStack(getType(), 1, data);
}
@Override
public Object toNMS() {
return BlockUtils.combinedIdToNMSBlockData(BlockUtils.getCombinedId(this));
}
}
| 5,004 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
TPSMeter.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/TPSMeter.java | package gyurix.spigotutils;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.spigotlib.Config;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class TPSMeter implements Runnable {
/**
* Update the servers tps metrics result in every here configured milliseconds
*/
public static long checkTime = 10000;
/**
* Make TPS meter toggleable in the config
*/
public static boolean enabled = true;
/**
* The tps limit, if the servers tps is bellow this value, then you will see a warning in the console
*/
public static int limit = 15;
/**
* The instance of the TPS meter future, it is stopped on SpigotLib shutdown
*/
@ConfigOptions(serialize = false)
public static ScheduledFuture meter;
/**
* Amount of detected 0 TPS before crash is reported
*/
public static int reportCrashAfter = 4;
/**
* Ticks elapsed from the last tps metrics result update
*/
@ConfigOptions(serialize = false)
public static int ticks;
/**
* Total elapsed tick count from server startup
*/
@ConfigOptions(serialize = false)
public static int totalTicks;
/**
* The current tps value of the server
*/
@ConfigOptions(serialize = false)
public static double tps = 20.0;
/**
* Amount of detected 0 TPS in a row.
*/
@ConfigOptions(serialize = false)
public static int zeroTpsCount = 0;
@Override
public void run() {
tps = ticks * 1000.0 / checkTime;
ticks = 0;
if (tps < limit)
SU.cs.sendMessage("§9[§b TPS Meter §9]§e The server's TPS is bellow §c" + tps + "§e, is it lagging or crashed?");
if (tps == 0) {
++zeroTpsCount;
if (zeroTpsCount == reportCrashAfter) {
StringBuilder sb = new StringBuilder();
sb.append("============== SpigotLib Crash Reporter ==============\n" + "Your server has been detected having 0 TPS ")
.append(reportCrashAfter)
.append(" times a row, which means that with high probability it crashed / frozen down. ")
.append("This crash report will help for your developers to detect what's causing the crash." +
" This is NOT an error in SpigotLib, but it's one of it's features, so only contact gyuriX" +
" for fixing the error caused this crash if you can pay for it.\n").append("\n");
TreeMap<Thread, StackTraceElement[]> map = new TreeMap<>(Comparator.comparing(Thread::getName));
map.putAll(Thread.getAllStackTraces());
for (Map.Entry<Thread, StackTraceElement[]> e : map.entrySet()) {
sb.append("\n \n \n§e=====@ §bTHREAD ")
.append(e.getKey().getName())
.append("(§fstate=")
.append(e.getKey().getState())
.append(", priority=")
.append(e.getKey().getPriority())
.append("§b)")
.append(" §e@=====");
int i = 0;
for (StackTraceElement el : e.getValue()) {
sb.append("\n§c #").append(++i)
.append(": §eLINE §a").append(el.getLineNumber())
.append("§e in FILE §6").append(el.getFileName())
.append("§e (§7").append(el.getClassName())
.append("§e.§b").append(el.getMethodName())
.append("§e)");
}
}
sb.append("\n======================================================");
SU.cs.sendMessage(sb.toString());
if (Config.disablePluginsOnCrash) {
for (Plugin p : SU.pm.getPlugins()) {
p.onDisable();
}
}
}
} else
zeroTpsCount = 0;
}
public void start() {
meter = Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(this, checkTime, checkTime, TimeUnit.MILLISECONDS);
Bukkit.getScheduler().scheduleSyncRepeatingTask(Main.pl, () -> {
++ticks;
++totalTicks;
}, 0, 1);
}
}
| 4,261 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ParticleOffset.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/ParticleOffset.java | package gyurix.spigotutils;
import gyurix.configfile.ConfigSerialization;
import lombok.Data;
@Data
public class ParticleOffset implements ConfigSerialization.StringSerializable {
private float x, y, z;
public ParticleOffset(String in) {
String[] d = in.split(" ", 3);
x = Float.valueOf(d[0]);
y = Float.valueOf(d[1]);
z = Float.valueOf(d[2]);
}
@Override
public String toString() {
return x + " " + y + " " + z;
}
}
| 453 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
XZ.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/XZ.java | package gyurix.spigotutils;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.protocol.Reflection;
import gyurix.protocol.utils.WrappedData;
import gyurix.spigotlib.SU;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* An utility class for storing an X and Z coordinate pair
*/
public class XZ implements StringSerializable, Comparable<XZ>, WrappedData {
@ConfigOptions(serialize = false)
private static final Class nmsClass = Reflection.getNMSClass("ChunkCoordIntPair");
@ConfigOptions(serialize = false)
private static final Constructor con = Reflection.getConstructor(nmsClass, int.class, int.class);
@ConfigOptions(serialize = false)
private static final Field xField = Reflection.getField(nmsClass, "x"), zField = Reflection.getField(nmsClass, "z");
public int x, z;
public XZ(String in) {
String[] d = in.split(" ", 2);
x = Integer.parseInt(d[0]);
z = Integer.parseInt(d[1]);
}
public XZ(int x, int z) {
this.x = x;
this.z = z;
}
public XZ(Block bl) {
x = bl.getX();
z = bl.getZ();
}
public XZ(Object nms) {
try {
x = xField.getInt(nms);
z = zField.getInt(nms);
} catch (IllegalAccessException e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public XZ(Chunk c) {
x = c.getX();
z = c.getZ();
}
@Override
public int compareTo(XZ o) {
return Integer.compare(hashCode(), o.hashCode());
}
@Override
public int hashCode() {
return x << 16 + z;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof XZ))
return false;
XZ xz = (XZ) obj;
return x == xz.x && z == xz.z;
}
@Override
public String toString() {
return x + " " + z;
}
public UnlimitedYArea toArea() {
return new UnlimitedYArea((x << 4), (z << 4), (x << 4) + 15, (z << 4) + 15);
}
public Chunk toChunk(World w) {
return w.getChunkAt(x, z);
}
@Override
public Object toNMS() {
try {
return con.newInstance(x, z);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
}
| 2,292 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
PlayerData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/PlayerData.java | package gyurix.spigotutils;
import gyurix.protocol.Reflection;
import gyurix.scoreboard.NametagBar;
import gyurix.scoreboard.ScoreboardAPI;
import gyurix.scoreboard.Sidebar;
import gyurix.scoreboard.Tabbar;
import gyurix.spigotlib.SU;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import java.util.ArrayList;
import static gyurix.spigotutils.ServerVersion.v1_9;
/**
* Created by GyuriX on 9/6/2016.
*/
public class PlayerData {
public static final int maxslot = Reflection.ver.isAbove(v1_9) ? 41 : 40;
public boolean allowFlight, isFlying;
public Sidebar board;
public String displayName, playerListName;
public GameMode gm;
public double hp, maxhp;
public ArrayList<ItemStack> inv = new ArrayList<ItemStack>();
public int level, foodLevel;
public Location loc, compassTarget;
public NametagBar nametagBar;
public ArrayList<PotionEffect> pes = new ArrayList<PotionEffect>();
public String pln;
public Tabbar tabBar;
public float xp, saturation, exhausion, walkSpeed, flySpeed;
public PlayerData(Player plr, GameMode setGm, Location setLoc) {
pln = plr.getName();
loc = plr.getLocation();
xp = plr.getExp();
saturation = plr.getSaturation();
exhausion = plr.getExhaustion();
hp = plr.getHealth();
maxhp = plr.getMaxHealth();
level = plr.getLevel();
foodLevel = plr.getFoodLevel();
PlayerInventory pi = plr.getInventory();
for (int i = 0; i < maxslot; i++) {
inv.add(pi.getItem(i));
pi.setItem(i, null);
}
for (PotionEffect pe : plr.getActivePotionEffects()) {
pes.add(pe);
plr.removePotionEffect(pe.getType());
}
gm = plr.getGameMode();
allowFlight = plr.getAllowFlight();
isFlying = plr.isFlying();
displayName = plr.getDisplayName();
playerListName = plr.getPlayerListName();
board = (Sidebar) ScoreboardAPI.sidebars.get(plr.getName()).active;
nametagBar = (NametagBar) ScoreboardAPI.nametags.get(plr.getName()).active;
tabBar = (Tabbar) ScoreboardAPI.tabbars.get(plr.getName()).active;
walkSpeed = plr.getWalkSpeed();
flySpeed = plr.getFlySpeed();
compassTarget = plr.getCompassTarget();
plr.teleport(setLoc);
plr.setGameMode(setGm);
plr.setFoodLevel(20);
}
public void restore() {
Player plr = SU.getPlayer(pln);
plr.teleport(loc);
plr.setLevel(level);
plr.setExp(xp);
plr.setSaturation(saturation);
plr.setExhaustion(exhausion);
plr.setMaxHealth(maxhp);
plr.setHealth(hp);
plr.setFoodLevel(foodLevel);
PlayerInventory pi = plr.getInventory();
for (int i = 0; i < maxslot; i++)
pi.setItem(i, inv.get(i));
for (PotionEffect pe : plr.getActivePotionEffects())
plr.removePotionEffect(pe.getType());
for (PotionEffect pe : pes)
plr.addPotionEffect(pe);
plr.setGameMode(gm);
plr.setAllowFlight(allowFlight);
plr.setFlying(isFlying);
plr.setDisplayName(displayName);
plr.setWalkSpeed(walkSpeed);
plr.setFlySpeed(flySpeed);
plr.setCompassTarget(compassTarget);
plr.setPlayerListName(playerListName);
ScoreboardAPI.setSidebar(plr, board);
ScoreboardAPI.setNametagBar(plr, nametagBar);
ScoreboardAPI.setTabbar(plr, tabBar);
}
}
| 3,382 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BackendType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/BackendType.java | package gyurix.spigotutils;
/**
* Types of player data backend
*/
public enum BackendType {
FILE, MYSQL
}
| 111 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
UnlimitedYArea.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/UnlimitedYArea.java | package gyurix.spigotutils;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import java.util.ArrayList;
import java.util.List;
import static gyurix.spigotutils.BlockUtils.getYMax;
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Integer.MIN_VALUE;
/**
* Created by GyuriX on 2016.05.15..
*/
public class UnlimitedYArea extends Area implements StringSerializable {
public int minx = MIN_VALUE, minz = MIN_VALUE, maxx = MIN_VALUE, maxz = MIN_VALUE;
public UnlimitedYArea(String in) {
String[] d = in.split(" ", 4);
minx = Integer.parseInt(d[0]);
minz = Integer.parseInt(d[1]);
maxx = Integer.parseInt(d[2]);
maxz = Integer.parseInt(d[3]);
}
public UnlimitedYArea(Location loc, int radius) {
this(loc.getBlockX(), loc.getBlockZ(), radius);
}
public UnlimitedYArea(int x, int z, int radius) {
minx = x - radius;
minz = z - radius;
maxx = x + radius;
maxz = z + radius;
}
public UnlimitedYArea(UnlimitedYArea area) {
minx = area.minx;
minz = area.minz;
maxx = area.maxx;
maxz = area.maxz;
}
public UnlimitedYArea(LocationData pos1, LocationData pos2) {
this((int) pos1.x, (int) pos1.z, (int) pos2.x, (int) pos2.z);
}
public UnlimitedYArea(int minX, int minZ, int maxX, int maxZ) {
minx = minX;
minz = minZ;
maxx = maxX;
maxz = maxZ;
fix();
}
public static Block getTopY(World w, int x, int z) {
Block b = null;
for (int y = 255; y > 0; y--) {
b = w.getBlockAt(x, y, z);
if (b.getType() != Material.AIR)
return b;
}
return b;
}
public UnlimitedYArea cloneFixed() {
UnlimitedYArea area = new UnlimitedYArea(this);
area.fix();
return area;
}
public boolean contains(Location loc) {
return contains(loc.getBlockX(), loc.getBlockZ());
}
public boolean contains(int x, int z) {
return x >= minx && z >= minz && x <= maxx && z <= maxz;
}
public void fix() {
int tmp;
if (minx > maxx) {
tmp = minx;
minx = maxx;
maxx = tmp;
}
if (minz > maxz) {
tmp = minz;
minz = maxz;
maxz = tmp;
}
}
@Override
public List<Block> getBlocks(World w) {
List<Block> blocks = new ArrayList<>();
for (int x = minx; x <= maxx; ++x) {
for (int z = minx; z <= maxz; ++z) {
for (int y = 0; y <= 255; ++y) {
blocks.add(w.getBlockAt(x, y, z));
}
}
}
return blocks;
}
@Override
public List<Block> getOutlineBlocks(World w) {
List<Block> out = new ArrayList<>();
for (int x = minx; x <= maxx; ++x) {
out.add(getTopY(w, x, minz));
out.add(getTopY(w, x, maxz));
}
for (int z = minz + 1; z < maxz; ++z) {
out.add(getTopY(w, minx, z));
out.add(getTopY(w, maxx, z));
}
return out;
}
public Location getYMaxPos1(World world) {
return getYMax(world, minx, minz);
}
public Location getYMaxPos2(World world) {
return getYMax(world, maxx, maxz);
}
public boolean isBorder(int x, int z) {
return x == minx || z == minz || x == maxx || z == maxz;
}
public boolean isDefined() {
return minx != MIN_VALUE && minz != MIN_VALUE && maxx != MIN_VALUE && maxz != MAX_VALUE;
}
public boolean isPos1Defined() {
return minx != MIN_VALUE && minz != MIN_VALUE;
}
public boolean isPos2Defined() {
return maxx != MIN_VALUE && maxz != MIN_VALUE;
}
public void pos1(int x, int z) {
minx = x;
minz = z;
}
public void pos2(int x, int z) {
maxx = x;
maxz = z;
}
public int size() {
return (maxx - minx + 1) * (maxz - minz + 1);
}
@Override
public String toString() {
return minx + " " + minz + " " + maxx + " " + maxz;
}
}
| 3,871 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
RomanNumsAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/RomanNumsAPI.java | package gyurix.spigotutils;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
/**
* An API for converting latin numbers to roman and vice versa
*/
public class RomanNumsAPI {
private static NavigableMap<Integer, String> reversed;
private static TreeMap<Integer, String> romanNums = new TreeMap<>();
static {
romanNums.put(1, "I");
romanNums.put(4, "IV");
romanNums.put(5, "V");
romanNums.put(9, "IX");
romanNums.put(10, "X");
romanNums.put(40, "XL");
romanNums.put(50, "L");
romanNums.put(90, "XC");
romanNums.put(100, "C");
romanNums.put(400, "CD");
romanNums.put(500, "D");
romanNums.put(900, "CM");
romanNums.put(1000, "M");
romanNums.put(4000, "MV̅");
romanNums.put(5000, "V̅");
romanNums.put(9000, "MX̅");
romanNums.put(10000, "X̅");
romanNums.put(40000, "X̅L̅");
romanNums.put(50000, "L̅");
romanNums.put(90000, "X̅C̅");
romanNums.put(100000, "C̅");
romanNums.put(400000, "C̅D̅");
romanNums.put(500000, "D̅");
romanNums.put(900000, "C̅M̅");
romanNums.put(1000000, "M̅");
reversed = romanNums.descendingMap();
}
/**
* Convert the given roman number to latin
*
* @param roman - The roman number
* @return The latin number (conversion result)
*/
public static int fromRoman(String roman) {
roman = roman.toUpperCase();
int out = 0;
for (Map.Entry<Integer, String> e : reversed.entrySet()) {
String st = e.getValue();
int am = e.getKey();
while (roman.startsWith(st)) {
out += am;
roman = roman.substring(st.length());
}
}
return out;
}
/**
* Convert the given latin number to roman
*
* @param num - The latin number
* @return The roman number (conversion result)
*/
public static String toRoman(int num) {
StringBuilder out = new StringBuilder();
while (num > 0) {
Map.Entry<Integer, String> e = romanNums.floorEntry(num);
num -= e.getKey();
out.append(e.getValue());
}
return out.toString();
}
}
| 2,100 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
TimeUtils.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/TimeUtils.java | package gyurix.spigotutils;
import gyurix.spigotlib.Main;
import org.bukkit.entity.Player;
import java.util.HashMap;
/**
* Utils for managing time in your plugins
*/
public class TimeUtils {
/**
* Returns a language remaining time until the given time
*
* @param plr - Target player
* @param time - Expire time
* @return The language based time string
*/
public static String getExpire(Player plr, Long time) {
if (time == null || time <= 0 || time == Long.MAX_VALUE) {
return Main.lang.get(plr, "time.never");
}
return getTime(plr, time - System.currentTimeMillis());
}
/**
* Returns the language based time message of the given time.
*
* @param plr - Target player
* @param time - The formatable time in milliseconds
* @return The language based time string
*/
public static String getTime(Player plr, Long time) {
time /= 1000;
if (time == null || time >= Long.MAX_VALUE / 1000) {
return Main.lang.get(plr, "time.never");
}
if (time < 0)
time = 0L;
int w = (int) (time / 604800);
int d = (int) (time % 604800 / 86400);
int h = (int) (time % 86400 / 3600);
int m = (int) (time % 3600 / 60);
int s = (int) (time % 60);
StringBuilder sb = new StringBuilder();
String sep = ", ";
if (w > 0)
sb.append(Main.lang.get(plr, "time." + (w > 1 ? "wp" : "w"), "w", "" + w)).append(sep);
if (d > 0)
sb.append(Main.lang.get(plr, "time." + (d > 1 ? "dp" : "d"), "d", "" + d)).append(sep);
if (h > 0)
sb.append(Main.lang.get(plr, "time." + (h > 1 ? "hp" : "h"), "h", "" + h)).append(sep);
if (m > 0)
sb.append(Main.lang.get(plr, "time." + (m > 1 ? "mp" : "m"), "m", "" + m)).append(sep);
if (sb.length() == 0 || s > 0)
sb.append(Main.lang.get(plr, "time." + (s > 1 ? "sp" : "s"), "s", "" + s)).append(sep);
return sb.substring(0, sb.length() - sep.length());
}
/**
* Converts user entered time to milliseconds
*
* @param plr - Target player
* @param in - The input string
* @return The entered time in long
*/
public static long toTime(Player plr, String in) {
in = in.replace(" ", "").replace(",", "");
long out = 0;
long cur = 0;
HashMap<String, Long> multipliers = new HashMap<>();
for (String s : Main.lang.get(plr, "time.marks.w").split(", *"))
multipliers.put(s, 604800L);
for (String s : Main.lang.get(plr, "time.marks.d").split(", *"))
multipliers.put(s, 86400L);
for (String s : Main.lang.get(plr, "time.marks.h").split(", *"))
multipliers.put(s, 3600L);
for (String s : Main.lang.get(plr, "time.marks.m").split(", *"))
multipliers.put(s, 60L);
for (String s : Main.lang.get(plr, "time.marks.s").split(", *"))
multipliers.put(s, 1L);
StringBuilder curP = new StringBuilder();
for (char c : in.toCharArray()) {
if (c > 47 && c < 58) {
if (curP.length() > 0) {
out += cur * NullUtils.to0(multipliers.get(curP.toString()));
curP.setLength(0);
cur = 0;
}
cur = cur * 10 + (c - 48);
} else
curP.append(c);
}
if (curP.length() > 0) {
out += cur * NullUtils.to0(multipliers.get(curP.toString()));
cur = 0;
}
return (out + cur) * 1000L;
}
}
| 3,315 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ServerVersion.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/ServerVersion.java | package gyurix.spigotutils;
/**
* Created by GyuriX on 2016.03.06..
*/
public enum ServerVersion {
UNKNOWN, v1_7, v1_8, v1_9, v1_10, v1_11, v1_12, v1_13, v1_14, v1_15, v1_16;
public boolean isAbove(ServerVersion version) {
return compareTo(version) >= 0;
}
public boolean isBellow(ServerVersion version) {
return compareTo(version) <= 0;
}
}
| 365 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
DualMap.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/DualMap.java | package gyurix.spigotutils;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DualMap<K, V> implements Map<K, V> {
final HashMap<K, V> keys = new HashMap<>();
final HashMap<V, K> values = new HashMap<>();
public K getKey(V value) {
return values.get(value);
}
private void putAllValue(Map<K, V> m) {
for (Entry<K, V> e : m.entrySet()) {
values.put(e.getValue(), e.getKey());
}
}
public K removeValue(V value) {
K key = values.remove(value);
keys.remove(key);
return key;
}
public int size() {
return keys.size();
}
public boolean isEmpty() {
return keys.isEmpty();
}
public boolean containsKey(Object key) {
return keys.containsKey(key);
}
public boolean containsValue(Object value) {
return values.containsKey((V) value);
}
public V get(Object key) {
return keys.get(key);
}
public V put(K key, V value) {
keys.remove(values.get(value));
V o = keys.put(key, value);
values.put(value, key);
return o;
}
public V remove(Object key) {
V o = keys.remove(key);
values.remove(o);
return o;
}
public void putAll(Map m) {
keys.putAll(m);
putAllValue(m);
}
public void clear() {
keys.clear();
values.clear();
}
public Set<K> keySet() {
return keys.keySet();
}
public Collection<V> values() {
return values.keySet();
}
public Set<Entry<K, V>> entrySet() {
return keys.entrySet();
}
} | 1,523 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
EntityUtils.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/EntityUtils.java | package gyurix.spigotutils;
import gyurix.nbt.NBTApi;
import gyurix.nbt.NBTCompound;
import gyurix.nbt.NBTPrimitive;
import gyurix.protocol.utils.DataWatcher;
import gyurix.protocol.utils.WorldType;
import gyurix.spigotlib.SU;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.projectiles.ProjectileSource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import static gyurix.protocol.Reflection.*;
/**
* Created by GyuriX on 2016. 06. 09..
*/
public class EntityUtils {
public static final Class craftEntity = getOBCClass("entity.CraftEntity"),
nmsEntityCL = getNMSClass("Entity"),
craftWorldCL = getOBCClass("CraftWorld"),
nmsWorldCL = getNMSClass("World"),
nmsWorldDataCL = getNMSClass("WorldData"),
nmsEntityInsentientCL = getNMSClass("EntityInsentient"),
nmsPathfinderGoalSelCL = getNMSClass("PathfinderGoalSelector");
public static final Method setLocationM = getMethod(nmsEntityCL, "setLocation", double.class, double.class, double.class, float.class, float.class),
bukkitEntityM = getMethod(nmsEntityCL, "getBukkitEntity");
public static Field goalSelectorField = getField(nmsEntityInsentientCL, "goalSelector"),
targetSelectorField = getField(nmsEntityInsentientCL, "targetSelector"),
pathfinderList1Field = getFirstFieldOfType(nmsPathfinderGoalSelCL, List.class), pathfinderList2Field = getLastFieldOfType(nmsPathfinderGoalSelCL, List.class);
public static Field killerField = getField(getNMSClass("EntityLiving"), "killer"),
nmsEntityF = getField(craftEntity, "entity"),
nmsWorldF = getField(craftWorldCL, "world"),
nmsWorldTypeF = getFirstFieldOfType(nmsWorldDataCL, WorldType.worldTypeCl),
nmsWorldDataF = getField(nmsWorldCL, "worldData"),
dataWatcherF = getField(nmsEntityCL, "datawatcher"),
craftWorldF = getField(nmsWorldCL, "world");
/**
* Converts the given NMS entity to a Bukkit entity
*
* @param ent - The NMS entity
* @return The Bukkit entity
*/
public static Entity getBukkitEntity(Object ent) {
try {
return (Entity) bukkitEntityM.invoke(ent);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
/**
* Converts the given NMS World or WorldServer to Bukkit World
*
* @param world - The Bukkit world
* @return The NMS entity
*/
public static World getBukkitWorld(Object world) {
try {
return (World) craftWorldF.get(world);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
/**
* Wraps the data watcher of the given entity
*
* @param ent - The Bukkit entity
* @return The wrapped data watcher of the entity
*/
public static DataWatcher getDataWatcher(Entity ent) {
try {
return new DataWatcher(dataWatcherF.get(nmsEntityF.get(ent)));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public static Entity getEntityDamager(Entity ent) {
if (ent instanceof Projectile) {
ProjectileSource src = ((Projectile) ent).getShooter();
if (src instanceof Entity)
return (Entity) src;
return null;
}
return ent;
}
/**
* Converts the given Bukkit entity to an NMS entity
*
* @param ent - The Bukkit entity
* @return The NMS entity
*/
public static Object getNMSEntity(Entity ent) {
try {
return nmsEntityF.get(ent);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
/**
* Converts the given Bukkit world to an NMS WorldServer
*
* @param world - The Bukkit world
* @return The NMS entity
*/
public static Object getNMSWorld(World world) {
try {
return nmsWorldF.get(world);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public static Player getPlayerDamager(Entity ent) {
if (ent instanceof Player)
return (Player) ent;
else if (ent instanceof Projectile) {
ProjectileSource src = ((Projectile) ent).getShooter();
if (src instanceof Player)
return (Player) src;
}
return null;
}
/**
* Get the nms WorldData of a world
*
* @param w - The world
* @return The nms WorldData of the world
*/
public static Object getWorldData(World w) {
try {
return nmsWorldDataF.get(nmsWorldF.get(w));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
/**
* Get the type of a world
*
* @param worldData - The world data
* @return The type of the given world data
*/
public static WorldType getWorldType(Object worldData) {
try {
return WorldType.fromVanillaWorldType(nmsWorldTypeF.get(worldData));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
/**
* Checks if the given entity is in NoAI mode
*
* @param ent - Target entity
* @return The NoAI mode of the given entity
*/
public static boolean hasNoAI(LivingEntity ent) {
if (ent == null)
return false;
NBTCompound nbt = NBTApi.getNbtData(ent);
NBTPrimitive noAI = (NBTPrimitive) nbt.get("NoAI");
return noAI != null && (int) noAI.getData() == 1;
}
/**
* Sets the data watcher of the given entity
*
* @param ent - The Bukkit entity
* @param dw - The DataWatcher
*/
public static void setDataWatcher(Entity ent, DataWatcher dw) {
try {
dataWatcherF.set(nmsEntityF.get(ent), dw.toNMS());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
/**
* Sets the killer of the given entity
*
* @param ent - The entity
* @param killer - The new killer of the entity
*/
public static void setKiller(LivingEntity ent, Player killer) {
Object nmsEnt = getNMSEntity(ent);
try {
killerField.set(nmsEnt, killer == null ? null : getNMSEntity(killer));
} catch (IllegalAccessException e) {
}
}
/**
* Sets the NoAI mode of the given entity
*
* @param ent - The entity
* @param noAi - The new NoAI mode
*/
public static void setNoAI(LivingEntity ent, boolean noAi) {
if (ent == null)
return;
if (ver.isAbove(ServerVersion.v1_8)) {
NBTCompound nbt = NBTApi.getNbtData(ent);
nbt.set("NoAI", noAi ? 1 : 0);
NBTApi.setNbtData(ent, nbt);
} else if (noAi) {
Object nmsEntity = getNMSEntity(ent);
try {
Object goalSelector = goalSelectorField.get(nmsEntity);
Object targetSelector = targetSelectorField.get(nmsEntity);
((List) pathfinderList1Field.get(goalSelector)).clear();
((List) pathfinderList2Field.get(goalSelector)).clear();
((List) pathfinderList1Field.get(targetSelector)).clear();
((List) pathfinderList2Field.get(targetSelector)).clear();
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
}
/**
* Teleport an entity to the given location without being blocked by passengers
*
* @param ent - The entity
* @param loc - Teleport destination
*/
public static void teleport(Entity ent, Location loc) {
try {
setLocationM.invoke(nmsEntityF.get(ent), loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch());
} catch (Throwable e) {
e.printStackTrace();
}
}
}
| 7,705 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Sidebar.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/Sidebar.java | package gyurix.scoreboard;
import java.util.ArrayList;
import static gyurix.scoreboard.ScoreboardAPI.id;
public class Sidebar extends ScoreboardBar {
/**
* The lines of the Sidebar (0-14)
*/
public final ArrayList<SidebarLine> lines = new ArrayList<>();
/**
* Default sidebar constructor
*/
public Sidebar() {
super("SB" + id, "SB" + id++, 1);
for (int i = 1; i < 16; ++i)
lines.add(new SidebarLine(this, (char) (280 + i + id % 30000), "§6§lLine - §e§l" + i, 100 - i));
}
public void hideLine(int line) {
if (line < 1 || line > 15)
return;
lines.get(line - 1).hide();
}
public boolean isShown(int line) {
if (line < 1 || line > 15)
return false;
return !lines.get(line - 1).hidden;
}
public void setLine(int line, String text) {
if (line < 1 || line > 15)
return;
lines.get(line - 1).setText(text);
}
public void setNumber(int line, int number) {
if (line < 1 || line > 15)
return;
lines.get(line - 1).setNumber(number);
}
public void showLine(int line) {
if (line < 1 || line > 15)
return;
lines.get(line - 1).show();
}
}
| 1,164 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
NametagBar.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/NametagBar.java | package gyurix.scoreboard;
import gyurix.scoreboard.team.CollisionRule;
import gyurix.scoreboard.team.NameTagVisibility;
import gyurix.scoreboard.team.TeamData;
import gyurix.spigotlib.SU;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListSet;
import static gyurix.scoreboard.ScoreboardAPI.id;
public class NametagBar extends ScoreboardBar {
int nextId = 0;
@Getter
@Setter
private boolean useRealTeamNames = true;
public NametagBar() {
super("NB" + id, "NB" + id++, 2);
}
public void addPlayers(String team, String... players) {
TeamData td = getTeam(team);
td.players.addAll(Arrays.asList(players));
updateTeam(td);
}
public void addPlayers(String team, Collection<String> players) {
TeamData td = getTeam(team);
td.players.addAll(players);
updateTeam(td);
}
public void createTeam(String team, String prefix, String suffix, int color, String... players) {
TeamData td = getTeam(team);
td.prefix = prefix;
td.suffix = suffix;
td.color = color;
td.players.addAll(Arrays.asList(players));
updateTeam(td);
}
public void createTeam(String team, String prefix, String suffix, int color, Collection<String> players) {
TeamData td = getTeam(team);
td.prefix = prefix;
td.suffix = suffix;
td.color = color;
td.players.addAll(players);
updateTeam(td);
}
public TeamData getTeam(String team) {
TeamData curTeam = currentData.teams.get(team);
if (curTeam == null) {
curTeam = new TeamData(useRealTeamNames ? team : (currentData.barname + "-" + ++nextId), team, "", "", false, true, NameTagVisibility.always, CollisionRule.always, 0, new ConcurrentSkipListSet<>());
currentData.teams.put(team, curTeam);
}
return curTeam;
}
public void removePlayers(String team, String... players) {
TeamData td = getTeam(team);
td.players.removeAll(Arrays.asList(players));
updateTeam(td);
}
public void removePlayers(String team, Collection<String> players) {
TeamData td = getTeam(team);
td.players.removeAll(players);
updateTeam(td);
}
public void removeTeam(String team) {
currentData.teams.remove(team);
active.keySet().removeIf((p) -> Bukkit.getPlayerExact(p) == null);
loaded.keySet().removeIf((p) -> Bukkit.getPlayerExact(p) == null);
for (Map.Entry<String, BarData> e : loaded.entrySet()) {
BarData oldBar = e.getValue();
TeamData old = oldBar.teams.remove(team);
if (old != null) {
SU.tp.sendPacket(Bukkit.getPlayerExact(e.getKey()), old.getRemovePacket());
}
}
}
public void setCollisionRule(String team, CollisionRule value) {
TeamData td = getTeam(team);
td.collisionRule = value;
updateTeam(td);
}
public void setColor(String team, int color) {
TeamData td = getTeam(team);
td.color = color;
updateTeam(td);
}
public void setFriendlyFire(String team, boolean value) {
TeamData td = getTeam(team);
td.friendlyFire = value;
updateTeam(td);
}
public void setNametagVisibility(String team, NameTagVisibility value) {
TeamData td = getTeam(team);
td.nameTagVisibility = value;
updateTeam(td);
}
public void setPrefix(String team, String value) {
TeamData td = getTeam(team);
td.prefix = value;
updateTeam(td);
}
public void setSeeInvisible(String team, boolean value) {
TeamData td = getTeam(team);
td.seeInvisible = value;
updateTeam(td);
}
public void setSuffix(String team, String value) {
TeamData td = getTeam(team);
td.suffix = value;
updateTeam(td);
}
public void updateTeam(TeamData td) {
active.keySet().removeIf((p) -> Bukkit.getPlayerExact(p) == null);
loaded.keySet().removeIf((p) -> Bukkit.getPlayerExact(p) == null);
for (Map.Entry<String, BarData> e : loaded.entrySet()) {
BarData oldBar = e.getValue();
TeamData old = oldBar.teams.get(td.name);
td.update(Bukkit.getPlayerExact(e.getKey()), old);
oldBar.teams.put(td.name, td.clone());
}
}
}
| 4,185 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
PlayerBars.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/PlayerBars.java | package gyurix.scoreboard;
import java.util.HashSet;
/**
* Created by GyuriX on 2016. 12. 03..
*/
public class PlayerBars {
public ScoreboardBar active;
public HashSet<ScoreboardBar> loaded = new HashSet<>();
}
| 219 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ScoreboardAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/ScoreboardAPI.java | package gyurix.scoreboard;
import gyurix.spigotlib.SU;
import org.bukkit.entity.Player;
import java.util.HashMap;
public class ScoreboardAPI {
public static long id = 1;
public static HashMap<String, PlayerBars> nametags = new HashMap<>();
public static HashMap<String, PlayerBars> sidebars = new HashMap<>();
public static HashMap<String, PlayerBars> tabbars = new HashMap<>();
public static void playerJoin(Player plr) {
String pln = plr.getName();
nametags.put(pln, new PlayerBars());
sidebars.put(pln, new PlayerBars());
tabbars.put(pln, new PlayerBars());
}
public static void playerLeave(Player plr) {
String pln = plr.getName();
unload(plr, nametags.remove(pln));
unload(plr, sidebars.remove(pln));
unload(plr, tabbars.remove(pln));
}
private static boolean set(Player plr, PlayerBars info, ScoreboardBar to) {
if (plr == null || info == null)
return false;
ScoreboardBar from = info.active;
if (from == to)
return false;
info.active = to;
if (from != null)
from.unload(plr);
if (to != null)
to.load(plr);
return true;
}
public static void setNametagBar(Player plr, NametagBar bar) {
set(plr, nametags.get(plr.getName()), bar);
}
public static void setSidebar(Player plr, Sidebar bar) {
set(plr, sidebars.get(plr.getName()), bar);
}
public static void setTabbar(Player plr, Tabbar bar) {
set(plr, tabbars.get(plr.getName()), bar);
}
public static String[] specialSplit(String in, char uniqueChar) {
if ((in = SU.optimizeColorCodes(in)).length() < 17)
return new String[]{in, "§" + uniqueChar, ""};
String[] out = new String[3];
out[0] = in.substring(0, 16);
if (out[0].endsWith("§")) {
out[0] = out[0].substring(0, 15);
in = out[0] + ' ' + in.substring(15);
}
StringBuilder formats = new StringBuilder();
int prev = 32;
for (int i = 0; i < 16; ++i) {
char c = in.charAt(i);
if (prev == 167) {
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f')
formats.setLength(0);
formats.append('§').append(c);
}
prev = c;
}
in = SU.setLength(formats + in.substring(16), 54);
if (in.length() < 17) {
out[1] = "§" + uniqueChar;
out[2] = in;
} else {
int id = in.length() - 16;
out[1] = "§" + uniqueChar + in.substring(0, id);
out[2] = in.substring(id);
}
return out;
}
public static void unload(Player plr, PlayerBars bars) {
if (bars == null || bars.loaded == null)
return;
for (ScoreboardBar bar : bars.loaded) {
try {
bar.drop(plr);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
}
}
| 2,761 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BarData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/BarData.java | package gyurix.scoreboard;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutScoreboardObjective;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutScoreboardScore;
import gyurix.scoreboard.team.TeamData;
import gyurix.spigotlib.SU;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
import static gyurix.protocol.wrappers.outpackets.PacketPlayOutScoreboardScore.ScoreAction.CHANGE;
import static gyurix.protocol.wrappers.outpackets.PacketPlayOutScoreboardScore.ScoreAction.REMOVE;
/**
* Created by GyuriX on 2016. 12. 03..
*/
public class BarData {
public final String barname;
public final HashMap<String, Integer> scores = new HashMap<>();
public final HashMap<String, TeamData> teams = new HashMap<>();
protected ScoreboardDisplayMode displayMode;
protected String title;
protected boolean visible;
public BarData(String barname, String title, ScoreboardDisplayMode displayMode, boolean visible) {
this.barname = barname;
this.title = title;
this.displayMode = displayMode;
this.visible = visible;
}
public BarData clone() {
BarData out = new BarData(barname, title, displayMode, visible);
for (Map.Entry<String, TeamData> e : teams.entrySet())
out.teams.put(e.getKey(), e.getValue().clone());
for (Map.Entry<String, Integer> e : scores.entrySet())
out.scores.put(e.getKey(), e.getValue());
return out;
}
public void load(Player plr) {
SU.tp.sendPacket(plr, new PacketPlayOutScoreboardObjective(barname, title, displayMode, 0));
for (Map.Entry<String, TeamData> e : teams.entrySet())
SU.tp.sendPacket(plr, e.getValue().getCreatePacket());
for (Map.Entry<String, Integer> e : scores.entrySet())
SU.tp.sendPacket(plr, new PacketPlayOutScoreboardScore(CHANGE, barname, e.getKey(), e.getValue()));
}
public void unload(Player plr) {
SU.tp.sendPacket(plr, new PacketPlayOutScoreboardObjective(barname, title, displayMode, 1));
for (Map.Entry<String, TeamData> e : teams.entrySet())
SU.tp.sendPacket(plr, e.getValue().getRemovePacket());
}
public void update(Player plr, BarData old) {
if (!old.title.equals(title) || old.displayMode != displayMode)
SU.tp.sendPacket(plr, new PacketPlayOutScoreboardObjective(barname, title, displayMode, 2));
for (Map.Entry<String, Integer> e : old.scores.entrySet()) {
String pln = e.getKey();
int oldScore = e.getValue();
Integer newscore = scores.get(pln);
if (newscore == null)
SU.tp.sendPacket(plr, new PacketPlayOutScoreboardScore(REMOVE, barname, pln, 0));
else if (newscore != oldScore)
SU.tp.sendPacket(plr, new PacketPlayOutScoreboardScore(CHANGE, barname, pln, newscore));
}
for (Map.Entry<String, Integer> e : scores.entrySet()) {
String pln = e.getKey();
if (!old.scores.containsKey(pln))
SU.tp.sendPacket(plr, new PacketPlayOutScoreboardScore(CHANGE, barname, pln, e.getValue()));
}
for (Map.Entry<String, TeamData> e : old.teams.entrySet()) {
String teamName = e.getKey();
TeamData oldTeam = e.getValue();
TeamData newTeam = teams.get(teamName);
if (newTeam == null)
SU.tp.sendPacket(plr, oldTeam.getRemovePacket());
else
newTeam.update(plr, oldTeam);
}
for (TeamData td : teams.values())
if (!old.teams.containsKey(td.name))
SU.tp.sendPacket(plr, td.getCreatePacket());
}
}
| 3,453 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
SidebarLine.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/SidebarLine.java | package gyurix.scoreboard;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutScoreboardScore;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutScoreboardScore.ScoreAction;
import gyurix.scoreboard.team.CollisionRule;
import gyurix.scoreboard.team.NameTagVisibility;
import gyurix.scoreboard.team.TeamData;
import gyurix.spigotlib.SU;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListSet;
import static gyurix.protocol.wrappers.outpackets.PacketPlayOutScoreboardScore.ScoreAction.CHANGE;
import static gyurix.protocol.wrappers.outpackets.PacketPlayOutScoreboardScore.ScoreAction.REMOVE;
public class SidebarLine {
public final Sidebar bar;
public final char uniqueChar;
public boolean hidden;
public int number;
public TeamData team, oldTeam;
public String teamName;
public SidebarLine(Sidebar bar, char ch, String text, int number) {
this.bar = bar;
uniqueChar = ch;
teamName = bar.teamNamePrefix + "§" + uniqueChar;
String[] set = ScoreboardAPI.specialSplit(text, uniqueChar);
ConcurrentSkipListSet cset = new ConcurrentSkipListSet();
cset.add(set[1]);
oldTeam = team = new TeamData(teamName, teamName, set[0], set[2], false, false, NameTagVisibility.always, CollisionRule.always, 0, cset);
this.number = number;
bar.currentData.scores.put(set[1], number);
bar.currentData.teams.put(team.name, team);
}
public String getText() {
return team.prefix + team.players.iterator().next() + team.suffix;
}
public void setText(String text) {
oldTeam = team.clone();
String[] set = ScoreboardAPI.specialSplit(text, uniqueChar);
team.prefix = set[0];
team.players.clear();
team.players.add(set[1]);
team.suffix = set[2];
String oldUser = oldTeam.players.iterator().next();
if (!set[1].equals(oldUser))
bar.currentData.scores.remove(oldUser);
if (hidden)
return;
synchronized (bar.active) {
Iterator<Map.Entry<String, BarData>> it = bar.active.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, BarData> e = it.next();
String pln = e.getKey();
BarData bd = e.getValue();
TeamData td = bd.teams.get(team.name);
Player plr = Bukkit.getPlayer(pln);
if (plr == null) {
it.remove();
continue;
}
team.update(plr, td);
td.prefix = set[0];
td.players.clear();
td.players.add(set[1]);
td.suffix = set[2];
}
if (!set[1].equals(oldUser)) {
bar.currentData.scores.put(set[1], number);
Object packet = new PacketPlayOutScoreboardScore(ScoreAction.REMOVE, bar.currentData.barname, oldUser, number).getVanillaPacket();
Object packet2 = new PacketPlayOutScoreboardScore(PacketPlayOutScoreboardScore.ScoreAction.CHANGE, bar.currentData.barname, set[1], number).getVanillaPacket();
for (Map.Entry<String, BarData> e : bar.active.entrySet()) {
e.getValue().scores.remove(oldUser);
e.getValue().scores.put(set[1], number);
SU.tp.sendPacket(Bukkit.getPlayer(e.getKey()), packet2);
SU.tp.sendPacket(Bukkit.getPlayer(e.getKey()), packet);
}
}
}
}
public boolean hide() {
if (hidden)
return false;
String user = team.players.iterator().next();
bar.currentData.scores.remove(user);
for (Map.Entry<String, BarData> e : bar.active.entrySet()) {
e.getValue().scores.remove(user);
SU.tp.sendPacket(Bukkit.getPlayer(e.getKey()), new PacketPlayOutScoreboardScore(REMOVE, bar.currentData.barname, user, number));
}
hidden = true;
return true;
}
public void setNumber(int value) {
if (number == value)
return;
number = value;
if (hidden)
return;
String user = team.players.iterator().next();
bar.currentData.scores.put(user, number);
Object packet = new PacketPlayOutScoreboardScore(PacketPlayOutScoreboardScore.ScoreAction.CHANGE, bar.currentData.barname, user, number).getVanillaPacket();
for (Map.Entry<String, BarData> e : bar.active.entrySet()) {
e.getValue().scores.put(user, number);
SU.tp.sendPacket(Bukkit.getPlayer(e.getKey()), packet);
}
}
public boolean show() {
if (!hidden)
return false;
String user = team.players.iterator().next();
bar.currentData.scores.put(user, number);
for (Map.Entry<String, BarData> e : bar.active.entrySet()) {
e.getValue().scores.put(user, number);
SU.tp.sendPacket(Bukkit.getPlayer(e.getKey()), new PacketPlayOutScoreboardScore(CHANGE, bar.currentData.barname, user, number));
}
hidden = false;
return true;
}
}
| 4,763 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ScoreboardDisplayMode.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/ScoreboardDisplayMode.java | package gyurix.scoreboard;
import gyurix.protocol.Reflection;
import java.lang.reflect.Method;
public enum ScoreboardDisplayMode {
INTEGER,
HEARTS;
private static Method valueOf;
static {
valueOf = Reflection.getMethod(Reflection.getNMSClass("IScoreboardCriteria$EnumScoreboardHealthDisplay"), "valueOf", String.class);
}
ScoreboardDisplayMode() {
}
public Object toNMS() {
try {
return valueOf.invoke(null, name());
} catch (Throwable e) {
return null;
}
}
} | 511 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Tabbar.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/Tabbar.java | package gyurix.scoreboard;
public class Tabbar extends ScoreboardBar {
public String footer = "§c§l--------------------\nTabbar, made by gyuriX\n§c§l--------------------";
public String header = "§b§lTest header";
public Tabbar() {
super("SBAPI-tabbar", "SLTB", 0);
}
}
| 292 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ScoreboardBar.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/ScoreboardBar.java | package gyurix.scoreboard;
import gyurix.protocol.event.PacketOutType;
import gyurix.spigotlib.SU;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import static gyurix.scoreboard.ScoreboardDisplayMode.INTEGER;
public abstract class ScoreboardBar {
public final HashMap<String, BarData> active = new HashMap<>();
public final BarData currentData;
public final HashMap<String, BarData> loaded = new HashMap<>();
public final Object showPacket, hidePacket;
public final String teamNamePrefix;
/**
* Construct new ScoreboardBar
*
* @param barname - The name of this ScoreboardBar
* @param teamNamePrefix - The prefix of the Scoreboard team packets
* @param displaySlot - The slot of this ScoreboardBar (0: list, 1: sidebar, 2: below name)
*/
public ScoreboardBar(String barname, String teamNamePrefix, int displaySlot) {
this.currentData = new BarData(barname, barname, INTEGER, true);
this.teamNamePrefix = teamNamePrefix;
showPacket = PacketOutType.ScoreboardDisplayObjective.newPacket(displaySlot, barname);
hidePacket = PacketOutType.ScoreboardDisplayObjective.newPacket(displaySlot, "");
}
/**
* Reactivates this ScoreboardBar for the given player, if it is loaded, but deactivated currently
*
* @param plr - Target Player
* @return True if this ScoreboardBar was not active for the given player before
*/
public boolean activate(Player plr) {
if (active.containsKey(plr.getName()))
return false;
BarData bd = loaded.get(plr.getName());
if (bd == null)
return false;
BarData newBd = currentData.clone();
newBd.update(plr, bd);
loaded.put(plr.getName(), newBd);
active.put(plr.getName(), newBd);
if (currentData.visible)
SU.tp.sendPacket(plr, showPacket);
return true;
}
/**
* Deactivates this ScoreboardBar for the given player, but keeps it loaded and ready to fast switch back
*
* @param plr - Target Player
* @return True if this ScoreboardBar was active for the given player before
*/
public boolean deActivate(Player plr) {
return active.remove(plr.getName()) != null;
}
/**
* Removes the data stored about the given players loaded state (useful for handling player quits)
*
* @param plr - Target player
* @return True if this ScoreboardBar was loaded for the player before
*/
public boolean drop(Player plr) {
if (loaded.remove(plr.getName()) == null)
return false;
active.remove(plr.getName());
return true;
}
/**
* Get the display mode of the Scoreboard
*
* @return The scoreboards display mode
*/
public ScoreboardDisplayMode getDisplayMode() {
return currentData.displayMode;
}
/**
* Sets the display mode of this Scoreboard, it has no effect on sidebar.
*
* @param mode - The new displaymode
*/
public void setDisplayMode(ScoreboardDisplayMode mode) {
if (currentData.displayMode == mode)
return;
currentData.displayMode = mode;
}
/**
* Gets the title of this scoreboard bar
*
* @return - The title of this scoreboard bar
*/
public String getTitle() {
return currentData.title;
}
/**
* Sets the title of this scoreboard bar.
*
* @param newtitle - The new title
*/
public void setTitle(String newtitle) {
newtitle = SU.setLength(newtitle, 32);
if (currentData.title.equals(newtitle))
return;
currentData.title = newtitle;
update();
}
/**
* Checks if this ScoreboardBar is active for the given player or not
*
* @param plr - Target Player
* @return True if this ScoreboardBar is active for the given player
*/
public boolean isActive(Player plr) {
return active.containsKey(plr.getName());
}
/**
* Checks if this ScoreboardBar is already loaded for the given player or not
*
* @param plr - Target Player
* @return True if this ScoreboardBar is already loaded for the given player
*/
public boolean isLoaded(Player plr) {
return loaded.containsKey(plr.getName());
}
/**
* Check if this scoreboard bar is visible or not
*
* @return The scoreboard bars visibility
*/
public boolean isVisible() {
return currentData.visible;
}
/**
* Toggles the visibility of this scoreboard bar
*
* @param visible - The new visibility state
*/
public void setVisible(boolean visible) {
if (visible != currentData.visible) {
currentData.visible = visible;
update();
}
}
/**
* Attempts to load this ScoreboardBar for the given player
*
* @param plr - Target Player
* @return True if this ScoreboardBar hasn't been loaded for the player before
*/
public boolean load(Player plr) {
if (loaded.containsKey(plr.getName()))
return false;
BarData bd = currentData.clone();
bd.load(plr);
loaded.put(plr.getName(), bd);
if (currentData.visible)
SU.tp.sendPacket(plr, showPacket);
active.put(plr.getName(), bd);
return true;
}
/**
* Attempts to unload this ScoreboardBar for the given player
*
* @param plr - Target Player
* @return True if this ScoreboardBar has been loaded for the player before
*/
public boolean unload(Player plr) {
BarData bd = loaded.remove(plr.getName());
if (bd == null)
return false;
active.remove(plr.getName());
bd.unload(plr);
return true;
}
public void update() {
Iterator<Map.Entry<String, BarData>> it = active.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, BarData> e = it.next();
BarData newBd = currentData.clone();
Player plr = Bukkit.getPlayer(e.getKey());
if (plr == null)
it.remove();
newBd.update(plr, e.getValue());
if (!e.getValue().visible && newBd.visible)
SU.tp.sendPacket(plr, showPacket);
if (e.getValue().visible && !newBd.visible)
SU.tp.sendPacket(plr, hidePacket);
e.setValue(newBd);
}
}
}
| 6,063 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CollisionRule.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/team/CollisionRule.java | package gyurix.scoreboard.team;
/**
* Created by GyuriX on 11/15/2016.
*/
public enum CollisionRule {
always, pushOtherTeams, pushOwnTeam, never
}
| 152 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
NameTagVisibility.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/team/NameTagVisibility.java | package gyurix.scoreboard.team;
/**
* Created by GyuriX on 11/15/2016.
*/
public enum NameTagVisibility {
always, never, hideForOtherTeams, hideForOwnTeam
}
| 162 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
TeamData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/scoreboard/team/TeamData.java | package gyurix.scoreboard.team;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutScoreboardTeam;
import gyurix.spigotlib.SU;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentSkipListSet;
/**
* Created by GyuriX on 2016. 12. 03..
*/
public class TeamData {
public CollisionRule collisionRule;
public int color;
public boolean friendlyFire, seeInvisible;
public String name, displayName, prefix, suffix;
public NameTagVisibility nameTagVisibility;
public ConcurrentSkipListSet<String> players = new ConcurrentSkipListSet<>();
public TeamData(String name, String displayName, String prefix, String suffix, boolean friendlyFire, boolean seeInvisible, NameTagVisibility nameTagVisibility, CollisionRule collisionRule, int color, ConcurrentSkipListSet<String> players) {
this.name = name;
this.displayName = displayName;
this.prefix = prefix;
this.suffix = suffix;
this.friendlyFire = friendlyFire;
this.seeInvisible = seeInvisible;
this.nameTagVisibility = nameTagVisibility;
this.collisionRule = collisionRule;
this.color = color;
this.players = players;
}
public TeamData(PacketPlayOutScoreboardTeam p) {
apply(p);
}
public void apply(PacketPlayOutScoreboardTeam p) {
switch (p.action) {
case 0: //create team
name = p.name;
displayName = p.displayName;
prefix = p.prefix;
suffix = p.suffix;
friendlyFire = (p.friendFlags & 1) == 1;
seeInvisible = (p.friendFlags & 2) == 2;
nameTagVisibility = p.nameTagVisibility;
collisionRule = p.collisionRule;
color = p.color;
players.addAll(p.players);
return;
case 2: //update team info
displayName = p.displayName;
prefix = p.prefix;
suffix = p.suffix;
friendlyFire = (p.friendFlags & 1) == 1;
seeInvisible = (p.friendFlags & 2) == 2;
nameTagVisibility = p.nameTagVisibility;
collisionRule = p.collisionRule;
color = p.color;
return;
case 3: //add players to team
players.addAll(p.players);
return;
case 4: //remove players from team
players.removeAll(p.players);
}
}
public TeamData clone() {
return new TeamData(name, displayName, prefix, suffix, friendlyFire, seeInvisible, nameTagVisibility, collisionRule, color, new ConcurrentSkipListSet<>(players));
}
public PacketPlayOutScoreboardTeam getCreatePacket() {
return new PacketPlayOutScoreboardTeam(name, displayName, prefix, suffix, nameTagVisibility, collisionRule, color,
new ArrayList<>(players), 0, (friendlyFire ? 1 : 0) + (seeInvisible ? 2 : 0));
}
public PacketPlayOutScoreboardTeam getRemovePacket() {
return new PacketPlayOutScoreboardTeam(name, 1);
}
public PacketPlayOutScoreboardTeam getUpdatePacket() {
return new PacketPlayOutScoreboardTeam(name, displayName, prefix, suffix, nameTagVisibility, collisionRule, color,
null, 2, (friendlyFire ? 1 : 0) + (seeInvisible ? 2 : 0));
}
public void update(Player plr, TeamData oldTeam) {
if (oldTeam == null) {
SU.tp.sendPacket(plr, getCreatePacket());
return;
}
//Update info
if (!oldTeam.displayName.equals(displayName) || !oldTeam.prefix.equals(prefix) || !oldTeam.suffix.equals(suffix) ||
oldTeam.friendlyFire != friendlyFire || oldTeam.seeInvisible != seeInvisible || oldTeam.nameTagVisibility != nameTagVisibility ||
oldTeam.collisionRule != collisionRule || oldTeam.color != color)
SU.tp.sendPacket(plr, getUpdatePacket());
//Remove players
ArrayList<String> list = new ArrayList<>();
for (String p : oldTeam.players)
if (!players.contains(p))
list.add(p);
if (!list.isEmpty())
SU.tp.sendPacket(plr, new PacketPlayOutScoreboardTeam(name, 4, list));
//Add players
list = new ArrayList<>();
for (String p : players)
if (!oldTeam.players.contains(p))
list.add(p);
if (!list.isEmpty())
SU.tp.sendPacket(plr, new PacketPlayOutScoreboardTeam(name, 3, list));
}
}
| 4,156 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ChatTag.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/chat/ChatTag.java | package gyurix.chat;
import com.google.common.collect.Lists;
import gyurix.json.JsonAPI;
import gyurix.json.JsonSettings;
import gyurix.spigotlib.ChatAPI;
import gyurix.spigotlib.SU;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.chat.TranslatableComponent;
import java.util.ArrayList;
import static gyurix.spigotutils.NullUtils.to0;
public class ChatTag {
@JsonSettings(defaultValue = "false")
public boolean bold, italic, underlined, strikethrough, obfuscated;
public ChatClickEvent clickEvent;
public ChatColor color;
public ArrayList<ChatTag> extra;
public ChatHoverEvent hoverEvent;
public ChatScoreData score;
public String text, translate, selector, insertion;
public ArrayList<ChatTag> with;
public ChatTag() {
}
public ChatTag(String in) {
text = in;
}
public static ChatTag fromBaseComponent(BaseComponent comp) {
ChatTag tag = new ChatTag();
net.md_5.bungee.api.ChatColor color = comp.getColorRaw();
if (color != null)
tag.color = ChatColor.valueOf(color.name().toLowerCase());
tag.obfuscated = to0(comp.isObfuscatedRaw());
tag.bold = to0(comp.isObfuscatedRaw());
tag.strikethrough = to0(comp.isStrikethroughRaw());
tag.underlined = to0(comp.isUnderlinedRaw());
tag.italic = to0(comp.isItalicRaw());
if (comp instanceof TextComponent) {
tag.text = ((TextComponent) comp).getText();
} else if (comp instanceof TranslatableComponent) {
TranslatableComponent tc = (TranslatableComponent) comp;
tag.translate = tc.getTranslate();
tag.with = new ArrayList<>();
tc.getWith().forEach(c -> tag.with.add(ChatTag.fromBaseComponent(c)));
}
if (comp.getHoverEvent() != null)
tag.hoverEvent = new ChatHoverEvent(comp.getHoverEvent());
if (comp.getClickEvent() != null)
tag.clickEvent = new ChatClickEvent(comp.getClickEvent());
tag.insertion = comp.getInsertion();
if (comp.getExtra() != null) {
tag.extra = new ArrayList<>();
for (BaseComponent c : comp.getExtra())
tag.extra.add(ChatTag.fromBaseComponent(c));
}
return tag;
}
public static ChatTag fromBaseComponents(BaseComponent[] comps) {
if (comps.length == 1)
return fromBaseComponent(comps[0]);
ChatTag tag = new ChatTag("");
tag.extra = new ArrayList<>();
for (BaseComponent c : comps)
tag.extra.add(ChatTag.fromBaseComponent(c));
return tag;
}
public static ChatTag fromColoredText(String colText) {
colText = SU.optimizeColorCodes(colText);
ArrayList<ChatTag> ctl = new ArrayList<>();
ChatTag ct = new ChatTag();
boolean col = false;
StringBuilder sb = new StringBuilder();
for (char c : colText.toCharArray()) {
if (col) {
ChatColor color = ChatColor.forId(c);
if (color == ChatColor.reset)
color = ChatColor.white;
if (sb.length() != 0) {
ct.text = sb.toString();
sb.setLength(0);
ctl.add(ct);
ct = color.isFormat() ? ct.cloneFormat(new ChatTag()) : new ChatTag();
}
if (color.isFormat()) {
switch (color) {
case obfuscated:
ct.obfuscated = true;
break;
case bold:
ct.bold = true;
break;
case strikethrough:
ct.strikethrough = true;
break;
case underline:
ct.underlined = true;
break;
case italic:
ct.italic = true;
break;
}
} else {
ct.color = color;
}
col = false;
} else {
if (c == '§')
col = true;
else
sb.append(c);
}
}
if (col)
sb.append('§');
ct.text = sb.toString();
ctl.add(ct);
return fromSeveralTag(ctl);
}
public static ChatTag fromExtraText(String extraText) {
String[] parts = extraText.split("\\\\\\|");
ArrayList<ChatTag> tags = new ArrayList<>();
for (String part : parts) {
String[] sa = part.split("\\\\-");
ChatTag tag = fromColoredText(SU.optimizeColorCodes(sa[0]));
for (int i = 1; i < sa.length; i++) {
if (sa[i].length() > 0)
tag.setExtra(sa[i].charAt(0), SU.optimizeColorCodes(sa[i].substring(1)));
}
tags.add(tag);
}
return fromSeveralTag(tags);
}
public static ChatTag fromICBC(Object icbc) {
return JsonAPI.deserialize(ChatAPI.toJson(icbc), ChatTag.class);
}
public static ChatTag fromSeveralTag(ArrayList<ChatTag> ctl) {
if (ctl.size() == 1)
return ctl.iterator().next();
ChatTag out = new ChatTag("");
out.extra = ctl;
return out;
}
public static String stripExtras(String extraText) {
String[] parts = extraText.split("\\\\\\|");
StringBuilder out = new StringBuilder();
for (String p : parts) {
out.append(p.split("\\\\-")[0]);
}
return out.toString();
}
public ChatTag cloneFormat(ChatTag target) {
target.bold = bold;
target.italic = italic;
target.underlined = underlined;
target.strikethrough = strikethrough;
target.obfuscated = obfuscated;
target.color = color;
return target;
}
public String getFormatPrefix() {
StringBuilder pref = new StringBuilder();
if (color != null)
pref.append('§').append(color.id);
if (obfuscated)
pref.append("§k");
if (bold)
pref.append("§l");
if (strikethrough)
pref.append("§m");
if (underlined)
pref.append("§n");
if (italic)
pref.append("§o");
return pref.toString();
}
public boolean isSimpleText() {
return translate == null && selector == null && insertion == null && with == null && score == null && extra == null &&
!(bold == italic == underlined == strikethrough == obfuscated) && color == null && clickEvent == null && hoverEvent == null;
}
/**
* Sets an extra data for this ChatTag. Available extra types:
* # - Translation
* \@ - Selector
* A - Hover event, show achievement
* D - Click event, twitch user data
* E - Hover event, show entity
* F - Click event, open file
* I - Hover event, show item
* P - Click event, change page
* R - Click event, run command
* S - Click event, suggest command
* T - Hover event, show text
* U - Click event, open url
* W - Translate with
* + - Insertion (on shift click)
*
* @param extraType The character representing the extra type
* @param value A String representing the value of this extra
* @return This chat tag
*/
public ChatTag setExtra(char extraType, String value) {
switch (extraType) {
case '#':
translate = value;
return this;
case 'W':
with.add(ChatTag.fromColoredText(value));
return this;
case '@':
selector = value;
return this;
case '+':
insertion = value;
return this;
}
ChatHoverEventType he = ChatHoverEventType.forId(extraType);
if (he != null) {
hoverEvent = new ChatHoverEvent(he, value);
return this;
}
ChatClickEventType ce = ChatClickEventType.forId(extraType);
if (ce != null)
clickEvent = new ChatClickEvent(ce, value);
return this;
}
public BaseComponent toBaseComponent() {
BaseComponent out = translate != null ? toTranslatableComponent() : toTextComponent();
if (obfuscated)
out.setObfuscated(obfuscated);
if (bold)
out.setBold(bold);
if (strikethrough)
out.setStrikethrough(strikethrough);
if (underlined)
out.setUnderlined(underlined);
if (italic)
out.setItalic(italic);
if (color != null)
out.setColor(color.toSpigotChatColor());
if (clickEvent != null)
out.setClickEvent(clickEvent.toSpigotClickEvent());
if (hoverEvent != null)
out.setHoverEvent(hoverEvent.toSpigotHoverEvent());
if (insertion != null)
out.setInsertion(insertion);
if (extra != null)
extra.forEach(e -> out.addExtra(e.toBaseComponent()));
return out;
}
public BaseComponent[] toBaseComponents() {
if (extra == null) {
return new BaseComponent[]{toBaseComponent()};
}
BaseComponent[] baseComponents = new BaseComponent[extra.size()];
for (int i = 0; i < extra.size(); ++i) {
baseComponents[i] = extra.get(i).toBaseComponent();
}
return baseComponents;
}
public String toColoredString() {
ArrayList<ChatTag> tags = extra == null ? Lists.newArrayList(this) : extra;
StringBuilder out = new StringBuilder();
for (ChatTag tag : tags) {
if (tag.text != null) {
out.append(tag.getFormatPrefix());
out.append(tag.text);
} else if (tag.translate != null) {
out.append(tag.translate);
}
}
return SU.optimizeColorCodes(out.toString());
}
public String toExtraString() {
ArrayList<ChatTag> tags = extra == null ? Lists.newArrayList(this) : extra;
StringBuilder out = new StringBuilder();
for (ChatTag tag : tags) {
if (tag.extra != null) {
for (ChatTag t : tag.extra) {
out.append("\\|").append(t.toExtraString());
}
continue;
}
out.append("\\|");
out.append(tag.getFormatPrefix());
if (tag.text != null)
out.append(tag.text);
if (tag.selector != null)
out.append("\\-@").append(tag.selector);
if (tag.translate != null)
out.append("\\-#").append(tag.translate);
if (tag.with != null) {
StringBuilder sb2 = new StringBuilder();
tag.with.forEach(w -> sb2.append(w.toColoredString()));
out.append(SU.optimizeColorCodes(sb2.toString()));
}
if (tag.hoverEvent != null)
out.append("\\-").append(tag.hoverEvent.action.id).append(tag.hoverEvent.value.toColoredString());
if (tag.clickEvent != null)
out.append("\\-").append(tag.clickEvent.action.id).append(tag.clickEvent.value);
if (tag.insertion != null)
out.append("\\-+").append(tag.insertion);
}
return out.substring(2);
}
public String toFormatlessString() {
ArrayList<ChatTag> tags = extra == null ? Lists.newArrayList(this) : extra;
StringBuilder out = new StringBuilder();
for (ChatTag tag : tags) {
if (tag.text != null)
out.append(tag.text);
}
return out.toString();
}
public Object toICBC() {
return ChatAPI.toICBC(JsonAPI.serialize(this));
}
@Override
public String toString() {
return JsonAPI.serialize(this);
}
private TextComponent toTextComponent() {
return new TextComponent(text);
}
private TranslatableComponent toTranslatableComponent() {
TranslatableComponent out = new TranslatableComponent(translate);
with.forEach(t -> out.addWith(t.toBaseComponent()));
return out;
}
}
| 10,946 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ChatClickEventType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/chat/ChatClickEventType.java | package gyurix.chat;
import net.md_5.bungee.api.chat.ClickEvent;
import java.util.HashMap;
public enum ChatClickEventType {
open_url('U'),
open_file('F'),
twitch_user_info('D'),
run_command('R'),
change_page('P'),
suggest_command('S');
static final HashMap<Character, ChatClickEventType> byId = new HashMap<>();
static {
for (ChatClickEventType t : values()) {
byId.put(t.id, t);
}
}
final char id;
ChatClickEventType(char id) {
this.id = id;
}
public static ChatClickEventType forId(char id) {
return byId.get(id);
}
public char getId() {
return id;
}
public ClickEvent.Action toSpigotClickAction() {
return ClickEvent.Action.valueOf(name().toUpperCase());
}
}
| 738 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ChatScoreData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/chat/ChatScoreData.java | package gyurix.chat;
/**
* Created by gyurix on 22/11/2015.
*/
public class ChatScoreData {
public String name, objective, value;
}
| 137 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ChatColor.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/chat/ChatColor.java | package gyurix.chat;
import java.util.HashMap;
/**
* An enum for handling chat colors;
*/
public enum ChatColor {
black('0'), dark_blue('1'), dark_green('2'), dark_aqua('3'), dark_red('4'), dark_purple('5'), gold('6'), gray('7'),
dark_gray('8'), blue('9'), green('a'), aqua('b'), red('c'), light_purple('d'), yellow('e'), white('f'),
obfuscated('k', true), bold('l', true), strikethrough('m', true), underline('n', true), italic('o', true), reset('r');
static final HashMap<Character, ChatColor> byId = new HashMap<>();
static {
for (ChatColor cc : values()) {
byId.put(cc.getId(), cc);
}
}
final boolean format;
final char id;
ChatColor(char id) {
this.id = id;
format = false;
}
ChatColor(char id, boolean format) {
this.id = id;
this.format = format;
}
public static ChatColor forId(char id) {
ChatColor cc = byId.get(id);
if (cc == null)
cc = white;
return cc;
}
public char getId() {
return id;
}
public boolean isFormat() {
return format;
}
public net.md_5.bungee.api.ChatColor toSpigotChatColor() {
return net.md_5.bungee.api.ChatColor.valueOf(name().toUpperCase());
}
}
| 1,191 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ChatClickEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/chat/ChatClickEvent.java | package gyurix.chat;
import net.md_5.bungee.api.chat.ClickEvent;
public class ChatClickEvent {
public ChatClickEventType action;
public String value;
public ChatClickEvent() {
}
public ChatClickEvent(ChatClickEventType action, String value) {
this.action = action;
this.value = value;
}
public ChatClickEvent(ClickEvent spigotClick) {
action = ChatClickEventType.valueOf(spigotClick.getAction().name().toLowerCase());
value = spigotClick.getValue();
}
public ClickEvent toSpigotClickEvent() {
return new ClickEvent(action.toSpigotClickAction(), value);
}
}
| 604 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ChatHoverEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/chat/ChatHoverEvent.java | package gyurix.chat;
import net.md_5.bungee.api.chat.HoverEvent;
public class ChatHoverEvent {
public ChatHoverEventType action;
public ChatTag value;
public ChatHoverEvent(ChatHoverEventType action, String value) {
this.action = action;
this.value = action == ChatHoverEventType.show_text ? ChatTag.fromColoredText(value) : new ChatTag(value);
}
public ChatHoverEvent(HoverEvent spigotHoverEvent) {
action = ChatHoverEventType.valueOf(spigotHoverEvent.getAction().name().toLowerCase());
value = ChatTag.fromBaseComponents(spigotHoverEvent.getValue());
}
public HoverEvent toSpigotHoverEvent() {
return new HoverEvent(action.toSpigotHoverAction(), value.toBaseComponents());
}
}
| 721 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ChatHoverEventType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/chat/ChatHoverEventType.java | package gyurix.chat;
import net.md_5.bungee.api.chat.HoverEvent;
import java.util.HashMap;
/**
* Created by gyurix on 22/11/2015.
*/
public enum ChatHoverEventType {
show_text('T'), show_item('I'), show_achievement('A'), show_entity('E');
static final HashMap<Character, ChatHoverEventType> byId = new HashMap<>();
static {
for (ChatHoverEventType t : values()) {
byId.put(t.id, t);
}
}
final char id;
ChatHoverEventType(char id) {
this.id = id;
}
public static ChatHoverEventType forId(char id) {
return byId.get(id);
}
public char getId() {
return id;
}
public HoverEvent.Action toSpigotHoverAction() {
return HoverEvent.Action.valueOf(name().toUpperCase());
}
}
| 733 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BungeeAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/api/BungeeAPI.java | package gyurix.api;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import gyurix.commands.Command;
import gyurix.json.JsonAPI;
import gyurix.spigotlib.Config;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;
import java.util.Collection;
import java.util.HashMap;
import java.util.UUID;
import static gyurix.spigotlib.Config.debug;
/**
* BungeeAPI is the implementation of the
* <a href=https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/>Spigot - Bungee communication protocol</a>
*/
public class BungeeAPI implements PluginMessageListener {
public static boolean enabled, schedulePacketAPI;
private static HashMap<UUID, String> ips = new HashMap<>();
private static int playerCountRID, playerListRID, serversRID, currentServerRID, uuidAllRID, serverIPRID;
private static HashMap<String, Integer> playerCounts = new HashMap<>();
private static HashMap<String, String[]> players = new HashMap<>();
private static HashMap<UUID, Integer> ports = new HashMap<>();
private static HashMap<String, String> serverIps = new HashMap<>();
private static String serverName = "N/A";
private static HashMap<String, Short> serverPorts = new HashMap<>();
private static String[] servers = new String[0];
private static HashMap<String, UUID> uuids = new HashMap<>();
public static boolean executeBungeeCommands(String[] commands, String... players) {
if (!enabled)
return false;
String json = JsonAPI.serialize(commands);
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("BungeeCommand");
out.writeUTF(StringUtils.join(players, ","));
out.writeUTF(json);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
return true;
}
public static boolean executePlayerCommands(Command[] commands, String... players) {
if (!enabled)
return false;
String json = JsonAPI.serialize(commands);
return forwardToPlayer("CommandExecution", json.getBytes(), players);
}
public static boolean executeServerCommands(String[] commands, String... servers) {
if (!enabled)
return false;
String json = JsonAPI.serialize(commands);
return forwardToServer("CommandExecution", json.getBytes(), servers);
}
public static boolean executeServerCommands(Command[] commands, String... servers) {
if (!enabled)
return false;
String json = JsonAPI.serialize(commands);
return forwardToServer("CommandExecution", json.getBytes(), servers);
}
public static boolean forwardToAllServer(String channel, byte[] message) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Forward");
out.writeUTF("ALL");
out.writeUTF(channel);
out.writeShort(message.length);
out.write(message);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
return true;
}
public static boolean forwardToPlayer(String channel, byte[] message, String... players) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("ForwardToPlayer");
out.writeUTF(s);
out.writeUTF(channel);
out.writeShort(message.length);
out.write(message);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean forwardToPlayer(String channel, byte[] message, Iterable<String> players) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("ForwardToPlayer");
out.writeUTF(s);
out.writeUTF(channel);
out.writeShort(message.length);
out.write(message);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean forwardToServer(String channel, byte[] message, String... servers) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
for (String s : servers) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Forward");
out.writeUTF(s);
out.writeUTF(channel);
out.writeShort(message.length);
out.write(message);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static String getIp(Player plr) {
return ips.get(plr.getUniqueId());
}
public static Integer getPort(Player plr) {
return ports.get(plr.getUniqueId());
}
public static String getServerIp(String server) {
return serverIps.get(server);
}
public static String getServerName() {
return serverName;
}
public static Short getServerPort(String server) {
return serverPorts.get(server);
}
public static UUID getUUID(Player plr) {
return uuids.get(plr.getName());
}
public static UUID getUUID(String pln) {
return uuids.get(pln);
}
public static boolean kick(String message, String... players) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("KickPlayer");
out.writeUTF(s);
out.writeUTF(message);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean kick(String message, Iterable<String> players) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("KickPlayer");
out.writeUTF(s);
out.writeUTF(message);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static Integer playerCount(String server) {
return playerCounts.get(server);
}
public static String[] playerList(String server) {
return players.get(server);
}
public static boolean requestCurrentServerName() {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("GetServer");
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
return true;
}
public static void requestIP(Player... players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("IP");
byte[] data = out.toByteArray();
for (Player p : players) {
p.sendPluginMessage(Main.pl, "BungeeCord", data);
}
}
public static void requestIP(Iterable<Player> players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("IP");
byte[] data = out.toByteArray();
for (Player p : players) {
p.sendPluginMessage(Main.pl, "BungeeCord", data);
}
}
public static boolean requestPlayerCount(Iterable<String> servers) {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
for (String s : servers) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("PlayerCount");
out.writeUTF(s);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean requestPlayerCount(String... servers) {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
for (String s : servers) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("PlayerCount");
out.writeUTF(s);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean requestPlayerList(Iterable<String> servers) {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
for (String s : servers) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("PlayerList");
out.writeUTF(s);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean requestPlayerList(String... servers) {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
for (String s : servers) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("PlayerList");
out.writeUTF(s);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean requestServerIP(Iterable<String> servers) {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
for (String s : servers) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("ServerIP");
out.writeUTF(s);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean requestServerIP(String... servers) {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
for (String s : servers) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("ServerIP");
out.writeUTF(s);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean requestServerNames() {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("GetServers");
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
return true;
}
public static boolean requestUUID(Iterable<String> players) {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("UUIDOther");
out.writeUTF(s);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean requestUUID(String... players) {
if (!enabled)
return false;
Collection<Player> pls = (Collection<Player>) SU.srv.getOnlinePlayers();
if (pls.size() == 0)
return false;
Player p = pls.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("UUIDOther");
out.writeUTF(s);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static void send(String server, Player... players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(server);
for (Player p : players) {
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
}
public static void send(String server, Collection<Player> players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(server);
for (Player p : players) {
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
}
public static boolean send(String server, String... players) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("ConnectOther");
out.writeUTF(s);
out.writeUTF(server);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean send(String server, Iterable<String> players) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("ConnectOther");
out.writeUTF(s);
out.writeUTF(server);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean sendMessage(String msg, String... players) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Message");
out.writeUTF(s);
out.writeUTF(msg);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static boolean sendMessage(String msg, Iterable<String> players) {
if (!enabled)
return false;
Collection<Player> pc = (Collection<Player>) Bukkit.getOnlinePlayers();
if (pc.isEmpty())
return false;
Player p = pc.iterator().next();
for (String s : players) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Message");
out.writeUTF(s);
out.writeUTF(msg);
p.sendPluginMessage(Main.pl, "BungeeCord", out.toByteArray());
}
return true;
}
public static String[] serverNames() {
return servers;
}
public static boolean start() {
if (!enabled)
return false;
if (Config.BungeeAPI.servers > 0) {
serversRID = SU.sch.scheduleSyncRepeatingTask(Main.pl, BungeeAPI::requestServerNames, 0, Config.BungeeAPI.servers);
}
if (Config.BungeeAPI.currentServerName > 0) {
currentServerRID = SU.sch.scheduleSyncRepeatingTask(Main.pl, BungeeAPI::requestCurrentServerName, 0, Config.BungeeAPI.currentServerName);
}
if (Config.BungeeAPI.playerCount > 0) {
playerCountRID = SU.sch.scheduleSyncRepeatingTask(Main.pl, () -> {
requestPlayerCount(servers);
requestPlayerCount("ALL");
}, 2, Config.BungeeAPI.playerCount);
}
if (Config.BungeeAPI.playerList > 0) {
playerListRID = SU.sch.scheduleSyncRepeatingTask(Main.pl, () -> {
requestPlayerList(servers);
requestPlayerList("ALL");
}, 2, Config.BungeeAPI.playerList);
}
if (Config.BungeeAPI.uuidAll > 0) {
uuidAllRID = SU.sch.scheduleSyncRepeatingTask(Main.pl, () -> requestUUID(totalPlayerList()), 4, Config.BungeeAPI.uuidAll);
}
if (Config.BungeeAPI.serverIP > 0) {
serverIPRID = SU.sch.scheduleSyncRepeatingTask(Main.pl, () -> requestServerIP(servers), 4, Config.BungeeAPI.serverIP);
}
if (Config.BungeeAPI.ipOnJoin) {
SU.sch.scheduleSyncDelayedTask(Main.pl, () -> requestIP((Collection<Player>) Bukkit.getOnlinePlayers()), 4);
}
return true;
}
public static Integer totalPlayerCount() {
return playerCounts.get("ALL");
}
public static String[] totalPlayerList() {
return players.get("ALL");
}
@Override
public void onPluginMessageReceived(String channel, final Player player, byte[] bytes) {
try {
if (!channel.equals("BungeeCord"))
return;
ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
String sub = in.readUTF();
UUID uid = player.getUniqueId();
debug.msg("Bungee", "Received plugin message from player " + player.getName() + ": " + sub + " " + new String(bytes));
switch (sub) {
case "CommandExecution":
final Command[] commands = JsonAPI.deserialize(in.readUTF(), Command[].class);
SU.sch.scheduleSyncDelayedTask(Main.pl, () -> {
for (Command c : commands) {
c.execute(player);
}
});
return;
case "IP":
ips.put(uid, in.readUTF());
ports.put(uid, in.readInt());
return;
case "PlayerCount":
playerCounts.put(in.readUTF(), in.readInt());
return;
case "PlayerList":
players.put(in.readUTF(), in.readUTF().split(", "));
return;
case "GetServers":
servers = in.readUTF().split(", ");
return;
case "GetServer":
serverName = in.readUTF();
return;
case "UUID":
uuids.put(player.getName(), UUID.fromString(in.readUTF().replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")));
return;
case "UUIDOther":
uuids.put(in.readUTF(), UUID.fromString(in.readUTF().replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")));
return;
case "ServerIP":
String server = in.readUTF();
serverIps.put(server, in.readUTF());
serverPorts.put(server, in.readShort());
}
} catch (Throwable ignored) {
}
}
}
| 18,893 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
VariableAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/api/VariableAPI.java | package gyurix.api;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.PHAHook;
import gyurix.spigotlib.SU;
import me.clip.placeholderapi.PlaceholderAPI;
import org.apache.commons.lang.StringUtils;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/**
* VariableAPI - Used for advanced placeholder filling in Strings
*/
public class VariableAPI {
/**
* Available VariableHandlers
*/
public static final HashMap<String, VariableHandler> handlers = new HashMap();
/**
* Empty list, used for quickly being passed to VariableHandlers if the placeholder does not have parameters
*/
private static final ArrayList<Object> emptyList = new ArrayList<>();
/**
* List of placeholders, which were used in messages, and their handler throwed an error.
* Since this is a high frequently used API, this field is required to only show an error once
* instead of spamming the console with it.
*/
private static final HashSet<String> errorVars = new HashSet<>();
/**
* List of placeholders, which were used in messages, but does not have a handler
* Since this is a high frequently used API, this field is required to only show a missing
* handler warning once instead of spamming the console with it.
*/
private static final HashSet<String> missingHandlers = new HashSet<>();
/**
* Field for checking and setting the PlaceholderAPI hook status, true = hook enabled, false = hook disabled
*/
public static boolean phaHook;
/**
* Fills variables in the given message from the given character <b>recursively</b>.
*
* @param msg - The message containing placeholders
* @param from - Index of character from which the variables should be filled
* @param plr - The Player whose data should be used in the message filling
* @param extArgs - External object arguments
* @return The first element is always the position of the last read character, the rest are
* the objects generated by the VariableHandlers for the placeholders found in the message
*/
public static ArrayList<Object> fill(String msg, int from, Player plr, Object[] extArgs) {
int msgLength = msg.length();
int placeholderStart = from;
ArrayList<Object> out = new ArrayList<>();
/* Loop through every character of the message from the given one
until reaching the end of the message */
for (int charId = from; charId < msgLength; ++charId) {
char curChar = msg.charAt(charId);
switch (curChar) {
//Check if we found a placeholder beginning
case '<': {
/* Add the substring of the input message from the last ended placeholder
* until the current position for making sure that we don't lose that information.
* If we don't have any characters between these two positions, then we are
* not adding an empty string to the output for boosting client softwares performance
*/
if (placeholderStart < charId)
out.add(msg.substring(placeholderStart, charId));
//Call this fill method recursively to find inner placeholders of this placeholder
ArrayList<Object> d = fill(msg, charId + 1, plr, extArgs);
//Skip checking characters already checked by calling the fill method recursively
charId = (Integer) d.get(0);
placeholderStart = charId + 1;
//Remove the current position data from the recursive calls output
d.remove(0);
//Fill the found placeholders using VariableHandlers and add them to the output
out.add(fillVar(plr, d, extArgs));
continue;
}
//Check if we found a placeholder ending
case '>': {
//Add the placeholders text to the output
if (placeholderStart < charId)
out.add(msg.substring(placeholderStart, charId));
//Make sure the first element of the output will be the position of the last read character
out.add(0, charId);
return out;
}
}
}
//Add remaining text to the output
if (placeholderStart < msg.length())
out.add(msg.substring(placeholderStart, msg.length()));
//Make sure the first element of the output will be the index of the last character of the message
out.add(0, msg.length() - 1);
return out;
}
/**
* Fills variables in the given list of objects.
*
* @param plr - The player whose data should be used in the variable filling
* @param inside - List of objects were the variables should be filled
* @param extArgs - External arguments for the VariableHandler
* @return The variable filled object
*/
private static Object fillVar(Player plr, List<Object> inside, Object[] extArgs) {
//StringBuilder for calculating the placeholders full name
StringBuilder nameBuilder = new StringBuilder();
int listSize = inside.size();
//Loop through the whole list of objects
for (int readPos = 0; readPos < listSize; ++readPos) {
String placeholder = String.valueOf(inside.get(readPos));
int nameParamsSep = placeholder.indexOf(':');
//Check if we found a parameterized placeholder in the readingPosition
if (nameParamsSep != -1) {
//Split it to placeholder name and placeholder parameters
nameBuilder.append(placeholder.substring(0, nameParamsSep));
ArrayList<Object> parameters = new ArrayList<>(inside.subList(readPos + 1, listSize));
parameters.add(0, placeholder.substring(nameParamsSep + 1));
//Calculate the value of the placeholder
return handle(nameBuilder.toString(), plr, parameters, extArgs);
}
//If not, then then our placeholders name will be longer
nameBuilder.append(placeholder);
}
//If our placeholder was not a parametered one, calculate it's value without using parameters
return handle(nameBuilder.toString(), plr, emptyList, extArgs);
}
/**
* Fills all the placeholders in the given message
*
* @param msg - The variable fillable message
* @param plr - Player whose data should be used for variable filling
* @param extArgs - External arguments passed to the VariableHandlers
* @return The variable filled message
*/
public static String fillVariables(String msg, Player plr, Object... extArgs) {
if (phaHook)
msg = PlaceholderAPI.setPlaceholders(plr, msg);
ArrayList<Object> out = fill(msg.replace("\\<", "\u0000").replace("\\>", "\u0001"), 0, plr, extArgs);
out.remove(0);
return StringUtils.join(out, "").replace('\u0000', '<').replace('\u0001', '>');
}
/**
* Calculates the value of one placeholder using it's VariableHandler
*
* @param var - The calculateable variable
* @param plr - The player whose data should be used for the calculation
* @param inside - Parameters of the placeholder
* @param extArgs - External arguments, which should be passed to VariableHandler
* @return The variable filling result
*/
private static Object handle(String var, Player plr, ArrayList<Object> inside, Object[] extArgs) {
VariableHandler vh = handlers.get(var);
//Check and report missing handlers only once during the execution of the whole software
if (vh == null) {
if (missingHandlers.add(var))
SU.log(Main.pl, "§cMissing handler for variable §f" + var + "§c!");
return "<" + var + ">";
}
//Check and report error throwing handlers only once during the execution of the whole software
try {
return vh.getValue(plr, inside, extArgs);
} catch (Throwable e) {
if (errorVars.add(var)) {
SU.log(Main.pl, "§cError on calculating variable §f" + var + "§c!");
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return '<' + var + '>';
}
}
/**
* Initializes the VariableAPI. This method is coded for <b>internal usage</b>, it's only public
* for being callable from the plugins core
*/
public static void init() {
if (VariableAPI.phaHook)
new PHAHook();
}
/**
* Custom VariableHandlers should implement this interface and add themselves to the handlers map, for
* being used during the variable filling process
*/
public interface VariableHandler {
/**
* Method for processing variable filling requests
*
* @param plr - The player which data should be used for the filling
* @param args - Arguments being inside the placeholder
* @param eArgs - External arguments
* @return The proper replacement of the fillable placeholder
*/
Object getValue(Player plr, ArrayList<Object> args, Object[] eArgs);
}
}
| 8,787 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
TitleAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/api/TitleAPI.java | package gyurix.api;
import gyurix.chat.ChatTag;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutTitle;
import gyurix.spigotutils.NullUtils;
import org.bukkit.entity.Player;
import java.util.Collection;
import static gyurix.protocol.wrappers.outpackets.PacketPlayOutTitle.TitleAction.*;
import static gyurix.spigotlib.SU.tp;
/**
* TitleAPI - API for managing title, subtitle and actionbar messages for server versions 1.8.8 and later
*/
public class TitleAPI {
/**
* Clears the title message of the given collection of players
*
* @param players - The collection of players whose title bar should be cleared
*/
public static void clear(Collection<? extends Player> players) {
Object packet = new PacketPlayOutTitle(CLEAR, null, 0, 0, 0).getVanillaPacket();
players.forEach((p) -> tp.sendPacket(p, packet));
}
/**
* Clears the title message of the given players
*
* @param players - The players whose title bar should be cleared
*/
public static void clear(Player... players) {
Object packet = new PacketPlayOutTitle(CLEAR, null, 0, 0, 0).getVanillaPacket();
for (Player p : players)
tp.sendPacket(p, packet);
}
/**
* Resets the title message of the given collection of players
*
* @param players - The players whose title bar should be reset
*/
public static void reset(Collection<? extends Player> players) {
Object packet = new PacketPlayOutTitle(RESET, null, 0, 0, 0).getVanillaPacket();
players.forEach((p) -> tp.sendPacket(p, packet));
}
/**
* Resets the title message of the given players
*
* @param players - The players whose title bar should be reset
*/
public static void reset(Player... players) {
Object packet = new PacketPlayOutTitle(RESET, null, 0, 0, 0).getVanillaPacket();
for (Player p : players)
tp.sendPacket(p, packet);
}
/**
* Sends a title message to the given collection of players
*
* @param title - Title text of the title message
* @param subtitle - Subtitle text of the title message
* @param fadeIn - Fade in time in ticks (1 tick = 0.05 sec)
* @param showtime - Show time in ticks
* @param fadeOut - Fade out time in ticks
* @param players - Receivers of the title message
*/
public static void set(String title, String subtitle, int fadeIn, int showtime, int fadeOut, Collection<? extends Player> players) {
setShowTime(fadeIn, showtime, fadeOut, players);
setSubTitle(NullUtils.to0(subtitle), players);
setTitle(title, players);
}
/**
* Sends a title message to the given players
*
* @param title - Title text of the title message
* @param subtitle - Subtitle text of the title message
* @param fadeIn - Fade in time in ticks (1 tick = 0.05 sec)
* @param showtime - Show time in ticks
* @param fadeOut - Fade out time in ticks
* @param players - Receivers of the title message
*/
public static void set(String title, String subtitle, int fadeIn, int showtime, int fadeOut, Player... players) {
setShowTime(fadeIn, showtime, fadeOut, players);
setSubTitle(NullUtils.to0(subtitle), players);
setTitle(title, players);
}
/**
* Sets the title timings of the given collection of players
*
* @param fadein - Fade in time in ticks (1 tick = 0.05 sec)
* @param show - Show time in ticks
* @param fadeout - Fade out time in ticks
* @param players - Players whose title timings should be changed
*/
public static void setShowTime(int fadein, int show, int fadeout, Collection<? extends Player> players) {
Object packet = new PacketPlayOutTitle(TIMES, null, fadein, show, fadeout).getVanillaPacket();
for (Player p : players)
tp.sendPacket(p, packet);
}
/**
* Sets the title timings of the given players
*
* @param fadein - Fade in time in ticks (1 tick = 0.05 sec)
* @param show - Show time in ticks
* @param fadeout - Fade out time in ticks
* @param players - Players whose title timings should be changed
*/
public static void setShowTime(int fadein, int show, int fadeout, Player... players) {
Object packet = new PacketPlayOutTitle(TIMES, null, fadein, show, fadeout).getVanillaPacket();
for (Player p : players)
tp.sendPacket(p, packet);
}
/**
* Sets the subtitle of the given collection of players.
* Subtitle will only become visible when the title is shown using the set title method.
* If you only want to show a subtitle without any title, you should call the setTitle method
* with empty String passed as title argument
*
* @param subtitle - The new subtitle of the title message
* @param players - Players whose subtitle should be changed
*/
public static void setSubTitle(String subtitle, Collection<? extends Player> players) {
Object packet = new PacketPlayOutTitle(SUBTITLE, ChatTag.fromColoredText(subtitle), 0, 0, 0).getVanillaPacket();
for (Player p : players)
tp.sendPacket(p, packet);
}
/**
* Sets the subtitle of the given players.
* Subtitle will only become visible when the title is shown using the set title method.
* If you only want to show a subtitle without any title, you should call the setTitle method
* with empty String passed as title argument
*
* @param subtitle - The new subtitle of the title message
* @param players - Players whose subtitle should be changed
*/
public static void setSubTitle(String subtitle, Player... players) {
Object packet = new PacketPlayOutTitle(SUBTITLE, ChatTag.fromColoredText(subtitle), 0, 0, 0).getVanillaPacket();
for (Player p : players)
tp.sendPacket(p, packet);
}
/**
* Sets the title of the given collection of players and shows the title message.
* Make sure to set the subtitle and the title timings before using this method.
*
* @param title - The showable title message
* @param players - Receivers of the title message
*/
public static void setTitle(String title, Collection<? extends Player> players) {
Object packet = new PacketPlayOutTitle(TITLE, ChatTag.fromColoredText(title), 0, 0, 0).getVanillaPacket();
players.forEach((p) -> tp.sendPacket(p, packet));
}
/**
* Sets the title of the given players and shows the title message.
* Make sure to set the subtitle and the title timings before using this method.
*
* @param title - The showable title message
* @param players - Receivers of the title message
*/
public static void setTitle(String title, Player... players) {
Object packet = new PacketPlayOutTitle(TITLE, ChatTag.fromColoredText(title), 0, 0, 0).getVanillaPacket();
for (Player p : players)
tp.sendPacket(p, packet);
}
}
| 6,741 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
TabAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/api/TabAPI.java | package gyurix.api;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.Collection;
import static gyurix.protocol.event.PacketOutType.PlayerListHeaderFooter;
import static gyurix.spigotlib.ChatAPI.TextToJson;
import static gyurix.spigotlib.ChatAPI.toICBC;
import static gyurix.spigotlib.SU.tp;
/**
* TabAPI - Used for setting global and local player list headers and footers
*/
public class TabAPI {
/**
* Sets the player list header and footer for every online player
*
* @param header - The new header
* @param footer - The new footer
*/
public static void setGlobalHeaderFooter(String header, String footer) {
setLocalHeaderFooter(header, footer, Bukkit.getOnlinePlayers());
}
/**
* Sets the player list header and footer for the given collection of players
*
* @param header - The new header
* @param footer - The new footer
* @param plrs - Target players
*/
public static void setLocalHeaderFooter(String header, String footer, Collection<? extends Player> plrs) {
Object headerComponent = toICBC(TextToJson(header));
Object footerComponent = toICBC(TextToJson(footer));
Object packet = PlayerListHeaderFooter.newPacket(headerComponent, footerComponent);
plrs.forEach((p) -> tp.sendPacket(p, packet));
}
/**
* Sets the player list header and footer for the given players
*
* @param header - The new header
* @param footer - The new footer
* @param plrs - Target players
*/
public static void setLocalHeaderFooter(String header, String footer, Player... plrs) {
Object headerComponent = toICBC(TextToJson(header));
Object footerComponent = toICBC(TextToJson(footer));
Object packet = PlayerListHeaderFooter.newPacket(headerComponent, footerComponent);
for (Player p : plrs)
tp.sendPacket(p, packet);
}
}
| 1,856 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
MySQLDatabase.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/mysql/MySQLDatabase.java | package gyurix.mysql;
import com.mysql.jdbc.Connection;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.json.JsonAPI;
import gyurix.json.JsonSettings;
import gyurix.spigotlib.Config;
import gyurix.spigotlib.SU;
import org.apache.commons.lang.StringUtils;
import java.sql.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static gyurix.spigotlib.Main.pl;
/**
* Class representing a MySQL storage connection and containing the required methods and utils
* for executing MySQL queries
*/
public class MySQLDatabase {
@JsonSettings(serialize = false)
@ConfigOptions(serialize = false)
public static ExecutorService batchThread = Executors.newSingleThreadExecutor();
public String table;
@JsonSettings(serialize = false)
@ConfigOptions(serialize = false)
private Connection con;
private String database;
private String host;
private String password;
private int timeout = 10000;
private String username;
public MySQLDatabase() {
}
/**
* @param host - The host of the MySQL server
* @param database - The name of the database
* @param username - The username to the MySQL server
* @param password - The password to the MySQL server
*/
public MySQLDatabase(String host, String database, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
this.database = database;
openConnection();
}
public static String escape(String in) {
StringBuilder out = new StringBuilder();
for (char c : in.toCharArray()) {
switch (c) {
case '\u0000':
out.append("\\0");
break;
case '\u001a':
out.append("\\Z");
break;
case '\n':
out.append("\\n");
break;
case '\r':
out.append("\\r");
break;
case '\'':
out.append("\\'");
break;
case '"':
out.append("\\\"");
break;
case '\\':
out.append("\\\\");
break;
default:
out.append(c);
}
}
return out.toString();
}
public void batch(Iterable<String> commands) {
batchThread.submit(new MySQLBatch(commands, null));
}
public void batch(Iterable<String> commands, Runnable r) {
batchThread.submit(new MySQLBatch(commands, r));
}
public void batchNoAsync(Iterable<String> commands) {
try {
Statement st = getConnection().createStatement();
for (String s : commands)
st.addBatch(s);
st.executeBatch();
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public void close() {
try {
Connection con = getConnection();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean command(String cmd) {
PreparedStatement st;
try {
st = getConnection().prepareStatement(cmd);
return st.execute();
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return false;
}
public boolean command(String cmd, Object... args) {
try {
return prepare(cmd, args).execute();
} catch (Throwable e) {
SU.log(pl, "MySQL - Command", cmd, StringUtils.join(args, ", "));
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return false;
}
/**
* @return - The Connection
*/
public Connection getConnection() {
try {
if (con == null || !con.isValid(timeout)) {
openConnection();
}
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return con;
}
/**
* @return True on successful connection otherwise false
*/
public boolean openConnection() {
try {
con = (Connection) DriverManager.getConnection("jdbc:mysql://" + host + "/" + database + "?autoReconnect=true&useSSL=" + Config.mysqlSSL, username, password);
con.setAutoReconnect(true);
con.setConnectTimeout(timeout);
} catch (Throwable e) {
SU.cs.sendMessage("§cFailed to connect to MySQL, please check the plugins configuration, settings are " +
JsonAPI.serialize(this));
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return false;
}
return true;
}
private PreparedStatement prepare(String cmd, Object... args) throws Throwable {
PreparedStatement st = getConnection().prepareStatement(cmd);
for (int i = 0; i < args.length; ++i)
st.setObject(i + 1, args[i] instanceof Enum ? ((Enum) args[i]).name() :
String.valueOf(args[i]));
return st;
}
public ResultSet query(String cmd) {
ResultSet rs;
PreparedStatement st;
try {
st = getConnection().prepareStatement(cmd);
rs = st.executeQuery();
return rs;
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
public ResultSet query(String cmd, Object... args) {
try {
return prepare(cmd, args).executeQuery();
} catch (Throwable e) {
SU.log(pl, "MySQL - Query", cmd, StringUtils.join(args, ", "));
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
public int update(String cmd) {
PreparedStatement st;
try {
st = getConnection().prepareStatement(cmd);
return st.executeUpdate();
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return -1;
}
}
public int update(String cmd, Object... args) {
try {
return prepare(cmd, args).executeUpdate();
} catch (Throwable e) {
SU.log(pl, "MySQL - Update", cmd, StringUtils.join(args, ", "));
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return -1;
}
}
public class MySQLBatch implements Runnable {
private final Iterable<String> ps;
private final Runnable r;
public MySQLBatch(Iterable<String> cmds, Runnable r) {
ps = cmds;
this.r = r;
}
@Override
public void run() {
try {
Statement st = getConnection().createStatement();
for (String s : ps) {
st.addBatch(s);
}
st.executeBatch();
if (r != null)
r.run();
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
}
}
| 6,344 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
MySQLManager.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/mysql/MySQLManager.java | package gyurix.mysql;
import gyurix.configfile.ConfigData;
import gyurix.protocol.Reflection;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.function.Consumer;
import static gyurix.spigotutils.SafeTools.async;
public class MySQLManager {
private MySQLDatabase db;
public MySQLManager(MySQLDatabase db) {
this.db = db;
}
public void delete(String key) {
async(() ->
db.command("DELETE FROM `" + db.table + "` WHERE " +
"`key`=\"" + MySQLDatabase.escape(key) + "\""));
}
public void deleteAll(String key) {
async(() ->
db.command("DELETE FROM `" + db.table + "` WHERE " +
"`key` LIKE \"" + MySQLDatabase.escape(key) + "%\""));
}
public void insert(String key, Object value) {
async(() -> {
String k = MySQLDatabase.escape(key);
String val = MySQLDatabase.escape(new ConfigData(value).toString());
int done = db.update("UPDATE `" + db.table + "` " +
"SET `value`=\"" + val + "\" " +
"WHERE `key`=\"" + k + "\"");
if (done == 0)
db.command("INSERT INTO `" + db.table + "` (`key`,`value`) VALUES " +
"(\"" + MySQLDatabase.escape(k) + "\", \"" + val + "\")");
});
}
private void loadField(String parentKey, Object parent, Field field) {
}
private <T> T loadObject(String key, Class<T> cl) {
Object obj = Reflection.newInstance(cl);
return (T) obj;
}
public void with(String key, Consumer<ResultSet> con) {
async(() -> {
ResultSet rs = db.query("SELECT * FROM `" + db.table + "` WHERE `key` LIKE \"" + MySQLDatabase.escape(key) + ".%\"");
rs.close();
});
}
}
| 1,711 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
EconomyVaultHook.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/EconomyVaultHook.java | package gyurix.economy;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import net.milkbowl.vault.economy.EconomyResponse.ResponseType;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.ServicePriority;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* A simple class for vault compatibility.
*/
public class EconomyVaultHook implements Economy {
/**
* Initializes Vault hook, DO NOT USE THIS METHOD.
*/
public static void init() {
Bukkit.getServicesManager().register(Economy.class, new EconomyVaultHook(), Main.pl, ServicePriority.Highest);
}
public EconomyResponse bankMemberOwner(String bankName) {
return new EconomyResponse(0, 0, ResponseType.FAILURE, "§cBanks doesn't have members and owners.");
}
public boolean isEnabled() {
return true;
}
public String getName() {
return "SpigotLib - EconomyAPI";
}
public boolean hasBankSupport() {
return true;
}
public int fractionalDigits() {
return Integer.MAX_VALUE;
}
public String format(double v) {
return EconomyAPI.getBalanceType("default").format(new BigDecimal(v));
}
public String currencyNamePlural() {
return EconomyAPI.getBalanceType("default").getSuffixPlural();
}
public String currencyNameSingular() {
return EconomyAPI.getBalanceType("default").getSuffix();
}
public boolean hasAccount(String s) {
return true;
}
public boolean hasAccount(OfflinePlayer offlinePlayer) {
return true;
}
public boolean hasAccount(String s, String s1) {
return true;
}
public boolean hasAccount(OfflinePlayer offlinePlayer, String s) {
return true;
}
public double getBalance(String s) {
return EconomyAPI.getBalance(SU.getUUID(s)).doubleValue();
}
public double getBalance(OfflinePlayer offlinePlayer) {
UUID id = offlinePlayer.getUniqueId();
if (id == null)
id = SU.getUUID(offlinePlayer.getName());
return EconomyAPI.getBalance(id).doubleValue();
}
public double getBalance(String s, String world) {
return EconomyAPI.getBalance(SU.getUUID(s)).doubleValue();
}
public double getBalance(OfflinePlayer offlinePlayer, String world) {
return EconomyAPI.getBalance(offlinePlayer.getUniqueId()).doubleValue();
}
public boolean has(String s, double v) {
return EconomyAPI.getBalance(SU.getUUID(s)).doubleValue() >= v;
}
public boolean has(OfflinePlayer offlinePlayer, double v) {
return EconomyAPI.getBalance(offlinePlayer.getUniqueId()).doubleValue() >= v;
}
public boolean has(String player, String world, double v) {
return EconomyAPI.getBalance(SU.getUUID(player)).doubleValue() >= v;
}
public boolean has(OfflinePlayer offlinePlayer, String world, double v) {
return EconomyAPI.getBalance(offlinePlayer.getUniqueId()).doubleValue() >= v;
}
public EconomyResponse withdrawPlayer(String player, double v) {
UUID id = SU.getUUID(player);
boolean success = EconomyAPI.addBalance(id, new BigDecimal(0 - v));
return new EconomyResponse(v, EconomyAPI.getBalance(id).doubleValue(),
success ? ResponseType.SUCCESS : ResponseType.FAILURE, success ? "§aSuccess." : "§cNot enough money.");
}
public EconomyResponse withdrawPlayer(OfflinePlayer offlinePlayer, double v) {
UUID id = offlinePlayer.getUniqueId();
if (id == null)
id = SU.getUUID(offlinePlayer.getName());
boolean success = EconomyAPI.addBalance(id, new BigDecimal(0 - v));
return new EconomyResponse(v, EconomyAPI.getBalance(id).doubleValue(),
success ? ResponseType.SUCCESS : ResponseType.FAILURE, success ? "§aSuccess." : "§cNot enough money.");
}
public EconomyResponse withdrawPlayer(String player, String world, double v) {
UUID id = SU.getUUID(player);
boolean success = EconomyAPI.addBalance(id, new BigDecimal(0 - v));
return new EconomyResponse(v, EconomyAPI.getBalance(id).doubleValue(),
success ? ResponseType.SUCCESS : ResponseType.FAILURE, success ? "§aSuccess." : "§cNot enough money.");
}
public EconomyResponse withdrawPlayer(OfflinePlayer offlinePlayer, String world, double v) {
UUID id = offlinePlayer.getUniqueId();
if (id == null)
id = SU.getUUID(offlinePlayer.getName());
boolean success = EconomyAPI.addBalance(id, new BigDecimal(0 - v));
return new EconomyResponse(v, EconomyAPI.getBalance(id).doubleValue(),
success ? ResponseType.SUCCESS : ResponseType.FAILURE, success ? "§aSuccess." : "§cNot enough money.");
}
public EconomyResponse depositPlayer(String player, double v) {
return withdrawPlayer(player, 0 - v);
}
public EconomyResponse depositPlayer(OfflinePlayer offlinePlayer, double v) {
return withdrawPlayer(offlinePlayer, 0 - v);
}
public EconomyResponse depositPlayer(String player, String world, double v) {
return withdrawPlayer(player, v);
}
public EconomyResponse depositPlayer(OfflinePlayer offlinePlayer, String world, double v) {
return withdrawPlayer(offlinePlayer, v);
}
public EconomyResponse createBank(String bankName, String s1) {
return new EconomyResponse(0, 0, ResponseType.SUCCESS, "§2Banks are handled automatically, there is no need to create them.");
}
public EconomyResponse createBank(String bankName, OfflinePlayer offlinePlayer) {
return new EconomyResponse(0, 0, ResponseType.SUCCESS, "§2Banks are handled automatically, there is no need to create them.");
}
public EconomyResponse deleteBank(String bankName) {
double bal = EconomyAPI.getBankBalance(bankName).doubleValue();
SU.pf.removeData("bankbalance." + bankName);
return new EconomyResponse(0, bal, ResponseType.SUCCESS, "§2Bank §a§l" + bankName + "§2 has been removed successfully.");
}
public EconomyResponse bankBalance(String bankName) {
return new EconomyResponse(0, EconomyAPI.getBankBalance(bankName).doubleValue(), ResponseType.SUCCESS, "§aSuccess.");
}
public EconomyResponse bankHas(String bankName, double v) {
double bal = EconomyAPI.getBankBalance(bankName).doubleValue();
if (v > bal) {
return new EconomyResponse(v, bal, ResponseType.FAILURE, "§cNot enough money.");
}
return new EconomyResponse(v, bal, ResponseType.SUCCESS, "§aSuccess.");
}
public EconomyResponse bankWithdraw(String bankName, double v) {
EconomyAPI.addBankBalance(bankName, new BigDecimal(0 - v));
return new EconomyResponse(v, EconomyAPI.getBankBalance(bankName).doubleValue(), ResponseType.SUCCESS, "§aSuccess.");
}
public EconomyResponse bankDeposit(String bankName, double v) {
EconomyAPI.addBankBalance(bankName, new BigDecimal(v));
return new EconomyResponse(v, EconomyAPI.getBankBalance(bankName).doubleValue(), ResponseType.SUCCESS, "§aSuccess.");
}
public EconomyResponse isBankOwner(String bankName, String s1) {
return bankMemberOwner(bankName);
}
public EconomyResponse isBankOwner(String bankName, OfflinePlayer offlinePlayer) {
return bankMemberOwner(bankName);
}
public EconomyResponse isBankMember(String bankName, String s1) {
return bankMemberOwner(bankName);
}
public EconomyResponse isBankMember(String bankName, OfflinePlayer offlinePlayer) {
return bankMemberOwner(bankName);
}
public List<String> getBanks() {
return new ArrayList<String>(SU.pf.getStringKeyList("bankbalance"));
}
public boolean createPlayerAccount(String s) {
return false;
}
public boolean createPlayerAccount(OfflinePlayer offlinePlayer) {
return false;
}
public boolean createPlayerAccount(String s, String s1) {
return false;
}
public boolean createPlayerAccount(OfflinePlayer offlinePlayer, String s) {
return false;
}
}
| 7,900 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Prices.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/Prices.java | package gyurix.economy;
import org.apache.commons.lang.StringUtils;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
/**
* Class used for managing multiple typed balance cost items
*/
public class Prices implements Iterable<Price> {
private final List<Price> prices = new ArrayList<>();
/**
* Creates a new Prices instance, generates the price list
* according to the input parameters
*
* @param types - The used balance types
* @param cost - Space separated list of costs
*/
public Prices(List<String> types, String cost) {
int len = types.size();
String[] d = cost.split(" ");
for (int i = 0; i < len; ++i)
prices.add(new Price(types.get(i), d[i]));
}
/**
* Returns an alphabetically ordered comma separated list of
* balance types of which the given Player does not have enough
*
* @param plr - Target Player
* @return - An alphabetically ordered comma separated list of
* balance types of which the given Player does not have enough
*/
public String getNotEnough(Player plr) {
TreeSet<String> notHave = new TreeSet<>();
for (Price p : prices)
if (!p.has(plr))
notHave.add(EconomyAPI.getBalanceType(p.getType()).getFullName());
return StringUtils.join(notHave, ", ");
}
/**
* Give all the prices to the given player
*
* @param plr
*/
public void give(Player plr) {
for (Price p : prices)
p.give(plr);
}
/**
* Checks if the given player is able to pay all the prices,
* this method should be used before using the take method
*
* @param plr - Target Player
* @return true if the player is able to pay all the prices, false otherwise
*/
public boolean has(Player plr) {
for (Price p : prices)
if (!p.has(plr))
return false;
return true;
}
/**
* Iterates through the prices
*
* @return The Price iterator
*/
@Override
public Iterator<Price> iterator() {
return prices.iterator();
}
/**
* Takes all the prices from the give Player
*
* @param plr - Target Player
*/
public void take(Player plr) {
for (Price p : prices)
p.take(plr);
}
/**
* Returns a comma separated list of prices
*/
@Override
public String toString() {
return StringUtils.join(prices, ", ");
}
}
| 2,406 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Price.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/Price.java | package gyurix.economy;
import lombok.Getter;
import org.bukkit.entity.Player;
import java.math.BigDecimal;
/**
* Class for managing a single balance type - value pair
*/
@Getter
public class Price {
private String type;
private BigDecimal value;
public Price(String type, String value) {
this.type = type;
this.value = new BigDecimal(value);
}
/**
* Gives the amount of money represented by this Price object to the given Player.
*
* @param plr - Target Player
*/
public void give(Player plr) {
EconomyAPI.addBalance(plr.getUniqueId(), type, value);
}
/**
* Checks if the given Player has the amount of money represented by this Price object
*
* @param plr - Target Player
* @return True of the Player has enough money, false otherwise
*/
public boolean has(Player plr) {
return EconomyAPI.getBalance(plr.getUniqueId(), type).compareTo(value) >= 0;
}
/**
* Takes the amount of money represented by this Price object from the given Player.
* You should use the has method before using this one.
*
* @param plr - Target Player
*/
public void take(Player plr) {
EconomyAPI.addBalance(plr.getUniqueId(), type, new BigDecimal("-" + value));
}
/**
* Gets the formatted String of this Price according to the balanceTypes configuration settings
*
* @return The formatted String of this Price
*/
@Override
public String toString() {
return EconomyAPI.getBalanceType(type).format(value);
}
}
| 1,505 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
EconomyAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/EconomyAPI.java | package gyurix.economy;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.economy.custom.BalanceType;
import gyurix.spigotlib.SU;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.UUID;
import static gyurix.spigotlib.Config.debug;
/**
* API used for managing multiple balance types on the server
*/
public class EconomyAPI {
@Getter
private static HashMap<String, BalanceType> balanceTypes = new HashMap<>();
@ConfigOptions(comment = "Migrate all the Economy data through Vault from an other Economy plugin, i.e. Essentials.")
@Getter
@Setter
private static boolean migrate;
@ConfigOptions(comment = "The type of SpigotLibs vault hook, available options:\n" +
"NONE - do NOT hook to Vault at all (not suggested)\n" +
"USER - hook to Vault as an Economy user (suggested if you don't want to use SpigotLibs Economy management)\n" +
"PROVIDER - hook to Vault as an Economy provider (override other Economy plugins, like Essentials)")
@Getter
@Setter
private static VaultHookType vaultHookType;
/**
* Adds / Takes the given typed balance from players account
*
* @param plr - Target players UUID
* @param balanceType - Balance type
* @param balance - Amount to add (positive values) or take (negative values)
* @return True if the transaction was successful, false otherwise
*/
public static boolean addBalance(UUID plr, String balanceType, BigDecimal balance) {
try {
BigDecimal bd = getBalance(plr, balanceType).add(balance);
return bd.compareTo(new BigDecimal(0)) >= 0 && setBalance(plr, balanceType, bd);
} catch (Throwable e) {
debug.msg("Economy", "§cError on adding " + balance + ' ' + balanceType + " balance to player " + plr + '.');
debug.msg("Economy", e);
return false;
}
}
/**
* Adds / Takes default balance from players account
*
* @param plr - Target players UUID
* @param balance - Amount to add (positive values) or take (negative values)
* @return True if the transaction was successful, false otherwise
*/
public static boolean addBalance(UUID plr, BigDecimal balance) {
return addBalance(plr, "default", balance);
}
/**
* Adds / Takes default typed balance from bank accounts
*
* @param bank - The banks name
* @param balance - Amount to add (positive values) or take (negative values)
* @return True if the transaction was successful, false otherwise
*/
public static boolean addBankBalance(String bank, BigDecimal balance) {
return setBankBalance(bank, getBankBalance(bank).add(balance));
}
/**
* Adds / Takes the given typed balance from bank accounts
*
* @param bank - The banks name
* @param balanceType - Balance type
* @param balance - Amount to add (positive values) or take (negative values)
* @return True if the transaction was successful, false otherwise
*/
public static boolean addBankBalance(String bank, String balanceType, BigDecimal balance) {
return setBankBalance(bank, balanceType, getBankBalance(bank, balanceType).add(balance));
}
/**
* Get the given typed balance of the given player
*
* @param plr - Target Player
* @param balanceType - Balance type
* @return The given typed balance of the given player or 0 if there was an error
*/
public static BigDecimal getBalance(UUID plr, String balanceType) {
try {
BalanceType bd = balanceTypes.get(balanceType);
if (bd == null)
throw new Throwable("Balance type " + balanceType + " is not defined.");
return bd.get(plr);
} catch (Throwable e) {
debug.msg("Economy", "§cError on getting " + balanceType + " balance of player " + plr);
debug.msg("Economy", e);
return new BigDecimal(0);
}
}
/**
* Get the default typed balance of the given player
*
* @param plr - Target Player
* @return The given typed balance of the given player or 0 if there was an error
*/
public static BigDecimal getBalance(UUID plr) {
try {
return getBalance(plr, "default");
} catch (Throwable e) {
debug.msg("Economy", "§cError on getting default balance of player " + plr);
debug.msg("Economy", e);
return new BigDecimal(0);
}
}
/**
* Get the settings of the given balance type
*
* @param type - Target balance type
* @return - The settings of the given balance type
*/
public static BalanceData getBalanceType(String type) {
BalanceData bd = balanceTypes.get(type);
return bd == null ? new BalanceData(type) : bd;
}
/**
* Gets the default typed balance of the given bank
*
* @param bank - The banks name
* @return The amount of default typed balance what the given bank has or 0 if there was an error
*/
public static BigDecimal getBankBalance(String bank) {
return getBankBalance(bank, "default");
}
/**
* Gets the given typed balance of the given bank
*
* @param bank - The banks name
* @param balanceType - Balance type
* @return The amount of the given typed balance what the given bank has or 0 if there was an error
*/
public static BigDecimal getBankBalance(String bank, String balanceType) {
try {
BalanceType bd = balanceTypes.get(balanceType);
if (bd == null)
throw new Throwable("Balance type " + balanceType + " is not defined.");
return bd.getBank(bank);
} catch (Throwable e) {
debug.msg("Economy", "§cError on getting " + balanceType + " balance of bank " + bank);
debug.msg("Economy", e);
return new BigDecimal(0);
}
}
public static void registerBalanceType(String name, BalanceType item) {
balanceTypes.put(name, item);
}
/**
* @param sender
* @param receiver
* @param balance
* @return
*/
public static boolean sendBalance(UUID sender, UUID receiver, BigDecimal balance) {
if (balance.compareTo(new BigDecimal(0)) < 0) {
return false;
}
if (!addBalance(sender, new BigDecimal(0).subtract(balance))) {
return false;
}
addBalance(receiver, balance);
return true;
}
/**
* @param sender
* @param receiver
* @param balanceType
* @param balance
* @return
*/
public static boolean sendBalance(UUID sender, UUID receiver, String balanceType, BigDecimal balance) {
if (balance.compareTo(new BigDecimal(0)) < 0) {
return false;
}
if (!addBalance(sender, new BigDecimal(0).subtract(balance))) {
return false;
}
addBalance(receiver, balanceType, balance);
return true;
}
/**
* @param sender
* @param bank
* @param balance
* @return
*/
public static boolean sendBalanceToBank(UUID sender, String bank, BigDecimal balance) {
if (!addBalance(sender, new BigDecimal(0).subtract(balance))) {
return false;
}
addBankBalance(bank, balance);
return true;
}
/**
* @param sender
* @param bank
* @param balanceType
* @param balance
* @return
*/
public static boolean sendBalanceToBank(UUID sender, String bank, String balanceType, BigDecimal balance) {
if (!addBalance(sender, balanceType, new BigDecimal(0).subtract(balance))) {
return false;
}
addBankBalance(bank, balanceType, balance);
return true;
}
/**
* @param plr
* @param balance
* @return True if the transaction was successful, false otherwise
*/
public static boolean setBalance(UUID plr, BigDecimal balance) {
return setBalance(plr, "default", balance);
}
/**
* @param plr - The UUID of the player whose balance should be set
* @param balanceType - The type of the set
* @param balance
* @return True if the transaction was successful, false otherwise
*/
public static boolean setBalance(UUID plr, String balanceType, BigDecimal balance) {
try {
BalanceType bd = balanceTypes.get(balanceType);
if (bd == null)
throw new Throwable("Balance type " + balanceType + " is not defined.");
BalanceUpdateEvent e = new BalanceUpdateEvent(plr, getBalance(plr, balanceType), balance, bd);
SU.pm.callEvent(e);
if (!e.isCancelled())
return bd.set(plr, balance);
} catch (Throwable e) {
debug.msg("Economy", "§cError on setting " + balanceType + " balance of player " + plr + " to " + balance);
debug.msg("Economy", e);
}
return false;
}
/**
* @param bank
* @param balance
* @return True if the transaction was successful, false otherwise
*/
public static boolean setBankBalance(String bank, BigDecimal balance) {
return setBankBalance(bank, "default", balance);
}
/**
* @param bank
* @param balanceType
* @param balance
* @return True if the transaction was successful, false otherwise
*/
public static boolean setBankBalance(String bank, String balanceType, BigDecimal balance) {
try {
BalanceType bd = balanceTypes.get(balanceType);
if (bd == null)
throw new Throwable("Balance type " + balanceType + " is not defined.");
BankBalanceUpdateEvent e = new BankBalanceUpdateEvent(bank, getBankBalance(bank, balanceType), balance, bd);
SU.pm.callEvent(e);
if (!e.isCancelled()) {
SU.pf.setObject("bankbalance." + bank + '.' + balanceType, balance);
return true;
}
return false;
} catch (Throwable e) {
debug.msg("Economy", "§cError on setting " + balanceType + " balance of bank " + bank + " to " + balance);
debug.msg("Economy", e);
return false;
}
}
/**
* Checks if plugin Vault should be used as the provider service for default balance type or not
*
* @return True if Vault should be used, false otherwise
*/
public static boolean useVaultProvider() {
return vaultHookType == VaultHookType.USER && SU.vault && SU.econ != null;
}
/**
* Types of possible hooks to plugin Vault
*/
public enum VaultHookType {
/**
* Do not hook to Vault at all
*/
NONE,
/**
* Use Vault as an Economy provider service
*/
USER,
/**
* Provide Economy services
*/
PROVIDER
}
}
| 10,273 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BalanceUpdateEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/BalanceUpdateEvent.java | package gyurix.economy;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import java.math.BigDecimal;
import java.util.UUID;
public final class BalanceUpdateEvent
extends Event
implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final BalanceData balanceType;
private final BigDecimal before;
private final UUID target;
private BigDecimal after;
private boolean cancel;
BalanceUpdateEvent(UUID target, BigDecimal before, BigDecimal after, BalanceData balanceType) {
this.target = target;
this.before = before;
this.after = after;
this.balanceType = balanceType;
}
public static HandlerList getHandlerList() {
return handlers;
}
public BigDecimal getAfter() {
return after;
}
public void setAfter(BigDecimal after) {
this.after = after;
}
public BalanceData getBalanceType() {
return balanceType;
}
public BigDecimal getBefore() {
return before;
}
public HandlerList getHandlers() {
return handlers;
}
public UUID getTarget() {
return target;
}
public boolean isCancelled() {
return cancel;
}
public void setCancelled(boolean cancel) {
this.cancel = cancel;
}
}
| 1,295 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BalanceData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/BalanceData.java | package gyurix.economy;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.configfile.PostLoadable;
import gyurix.spigotutils.NullUtils;
import lombok.Data;
import java.math.BigDecimal;
import java.text.DecimalFormat;
@Data
public class BalanceData implements PostLoadable {
/**
* Default amount of this balance, what new players and new banks get
*/
protected BigDecimal defaultValue = new BigDecimal(0);
/**
* DecimalFormat used for formatting
*/
protected String format;
/**
* The whole name of this balance type
*/
protected String fullName;
/**
* Name of the balance type
*/
protected String name;
/**
* Text written before amount
*/
protected String prefix = "";
/**
* Text written before amount, if amount is plural
*/
protected String prefixPlural;
/**
* Text written after amount, if amount
*/
protected String suffix = "";
/**
* Text written after amount, if amount is plural
*/
protected String suffixPlural;
/**
* Use K (10^3), M (10^6), B (10^9), T (10^12) suffixes instead of
* the whole balance amount
*/
protected boolean useKMBT;
@ConfigOptions(serialize = false)
private DecimalFormat df;
private BalanceData() {
this.name = null;
}
/**
* Constructs a new BalanceData, sets it's name and full name
* to the balance type represented by this BalanceData
*
* @param name - The balance type represented by this BalanceData
*/
public BalanceData(String name) {
this.name = name;
this.fullName = name;
postLoad();
}
/**
* Constructs a new BalanceData, by copying all
* the properties of the given BalanceData
*
* @param bd - The BalanceData which having the copyable properties
*/
public BalanceData(BalanceData bd) {
this.name = bd.name;
this.defaultValue = bd.defaultValue;
this.format = bd.format;
this.fullName = bd.fullName;
this.prefix = bd.prefix;
this.prefixPlural = bd.prefixPlural;
this.suffix = bd.suffix;
this.suffixPlural = bd.suffixPlural;
this.useKMBT = bd.useKMBT;
postLoad();
}
/**
* Formats the given amount of balance with applying both prefix and suffix
*
* @param amount - The balance amount
* @return The formatting result
*/
public String format(BigDecimal amount) {
if (amount == null)
amount = new BigDecimal(0);
boolean pl = !(amount.compareTo(new BigDecimal(-1)) >= 0 && amount.compareTo(new BigDecimal(1)) <= 0);
String pf = NullUtils.to0(pl ? getPrefixPlural() : prefix);
String sf = NullUtils.to0(pl ? getSuffixPlural() : suffix);
String f = getKMBT(amount);
return pf + f + sf;
}
/**
* Formats the given amount of balance without applying prefix or suffix
*
* @param amount - The balance amount
* @return The formatting result
*/
public String formatRaw(BigDecimal amount) {
return getKMBT(amount == null ? new BigDecimal(0) : amount);
}
private String getKMBT(BigDecimal amount) {
if (useKMBT) {
BigDecimal qi = new BigDecimal(1000_000_000_000_000_000L);
BigDecimal q = new BigDecimal(1000_000_000_000_000L);
BigDecimal t = new BigDecimal(1000_000_000_000L);
BigDecimal b = new BigDecimal(1000_000_000L);
BigDecimal m = new BigDecimal(1000_000L);
BigDecimal k = new BigDecimal(1000L);
if (amount.compareTo(qi) > -1)
return df.format(amount.divide(qi, BigDecimal.ROUND_DOWN)) + "Qi";
if (amount.compareTo(q) > -1)
return df.format(amount.divide(q, BigDecimal.ROUND_DOWN)) + "Q";
if (amount.compareTo(t) > -1)
return df.format(amount.divide(t, BigDecimal.ROUND_DOWN)) + "T";
if (amount.compareTo(b) > -1)
return df.format(amount.divide(b, BigDecimal.ROUND_DOWN)) + "B";
if (amount.compareTo(m) > -1)
return df.format(amount.divide(m, BigDecimal.ROUND_DOWN)) + "M";
if (amount.compareTo(k) > -1)
return df.format(amount.divide(k, BigDecimal.ROUND_DOWN)) + "K";
}
return df.format(amount);
}
public String getPrefixPlural() {
return NullUtils.to0(prefixPlural != null ? prefixPlural : prefix);
}
public String getSuffixPlural() {
return NullUtils.to0(suffixPlural != null ? suffixPlural : suffix);
}
@Override
public void postLoad() {
df = new DecimalFormat(format == null ? "###,###,###,###,###,###,##0.##" : format);
}
} | 4,435 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BankBalanceUpdateEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/BankBalanceUpdateEvent.java | package gyurix.economy;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import java.math.BigDecimal;
public final class BankBalanceUpdateEvent
extends Event
implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final BalanceData balanceType;
private final BigDecimal before;
private final String target;
private BigDecimal after;
private boolean cancel;
BankBalanceUpdateEvent(String target, BigDecimal before, BigDecimal after, BalanceData balanceType) {
this.target = target;
this.before = before;
this.after = after;
this.balanceType = balanceType;
}
public static HandlerList getHandlerList() {
return handlers;
}
public BigDecimal getAfter() {
return after;
}
public void setAfter(BigDecimal after) {
this.after = after;
}
public BalanceData getBalanceType() {
return balanceType;
}
public BigDecimal getBefore() {
return before;
}
public HandlerList getHandlers() {
return handlers;
}
public String getTarget() {
return target;
}
public boolean isCancelled() {
return cancel;
}
public void setCancelled(boolean cancel) {
this.cancel = cancel;
}
}
| 1,286 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
VaultBalanceType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/custom/VaultBalanceType.java | package gyurix.economy.custom;
import gyurix.economy.BalanceData;
import gyurix.spigotlib.SU;
import org.bukkit.Bukkit;
import java.math.BigDecimal;
import java.util.UUID;
public class VaultBalanceType extends BalanceType {
public VaultBalanceType(BalanceData bd) {
super(bd);
}
@Override
public BigDecimal get(UUID plr) {
return new BigDecimal(SU.econ.getBalance(Bukkit.getOfflinePlayer(plr)));
}
@Override
public BigDecimal getBank(String bank) {
return new BigDecimal(SU.econ.bankBalance(bank).balance);
}
@Override
public boolean set(UUID plr, BigDecimal value) {
BigDecimal has = get(plr);
int out = has.compareTo(value);
if (out == 0)
return true;
if (out < 0)
return SU.econ.depositPlayer(Bukkit.getOfflinePlayer(plr), value.subtract(has).doubleValue()).transactionSuccess();
return SU.econ.withdrawPlayer(Bukkit.getOfflinePlayer(plr), has.subtract(value).doubleValue()).transactionSuccess();
}
@Override
public boolean setBank(String bank, BigDecimal value) {
BigDecimal has = getBank(bank);
int out = has.compareTo(value);
if (out == 0)
return true;
if (out < 0)
return SU.econ.bankWithdraw(bank, has.subtract(value).doubleValue()).transactionSuccess();
return SU.econ.bankDeposit(bank, value.subtract(has).doubleValue()).transactionSuccess();
}
}
| 1,368 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ExpBalanceType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/custom/ExpBalanceType.java | package gyurix.economy.custom;
import gyurix.economy.BalanceData;
import gyurix.spigotlib.SU;
import java.math.BigDecimal;
import java.util.UUID;
public class ExpBalanceType extends BalanceType {
public ExpBalanceType(BalanceData bd) {
super(bd);
}
@Override
public BigDecimal get(UUID plr) {
return new BigDecimal(SU.getPlayer(plr).getLevel());
}
@Override
public boolean set(UUID plr, BigDecimal value) {
SU.getPlayer(plr).setLevel(value.intValue());
return true;
}
}
| 507 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ItemBalanceType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/custom/ItemBalanceType.java | package gyurix.economy.custom;
import gyurix.economy.BalanceData;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.ItemUtils;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.math.BigDecimal;
import java.util.UUID;
public class ItemBalanceType extends BalanceType {
@Getter
@Setter
private ItemStack item;
public ItemBalanceType(BalanceData bd) {
super(bd);
}
@Override
public BigDecimal get(UUID plr) {
Player p = SU.getPlayer(plr);
if (p == null)
throw new RuntimeException("Player " + plr + " was not found.");
return new BigDecimal(ItemUtils.countItem(p.getInventory(), item));
}
@Override
public boolean set(UUID plr, BigDecimal value) {
Player p = SU.getPlayer(plr);
int has = ItemUtils.countItem(p.getInventory(), item);
int goal = value.intValue();
if (goal < 0)
return false;
if (has == goal)
return true;
else if (goal > has) {
ItemStack is = item.clone();
is.setAmount(goal - has);
int left = ItemUtils.addItem(p.getInventory(), is);
if (left > 0)
p.getWorld().dropItem(p.getLocation(), is);
return true;
}
ItemStack is = item.clone();
is.setAmount(has - goal);
ItemUtils.removeItem(p.getInventory(), is);
return true;
}
}
| 1,362 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BalanceTypeWrapper.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/custom/BalanceTypeWrapper.java | package gyurix.economy.custom;
import java.math.BigDecimal;
import java.util.UUID;
public interface BalanceTypeWrapper {
BigDecimal get(UUID plr);
boolean set(UUID plr, BigDecimal value);
}
| 197 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BalanceType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/economy/custom/BalanceType.java | package gyurix.economy.custom;
import gyurix.economy.BalanceData;
import gyurix.spigotlib.SU;
import java.math.BigDecimal;
import java.util.UUID;
public class BalanceType extends BalanceData {
protected BalanceTypeWrapper wrapper;
public BalanceType(BalanceData bd, BalanceTypeWrapper wrapper) {
super(bd);
this.wrapper = wrapper;
}
public BalanceType(BalanceData bd) {
super(bd);
}
public BigDecimal get(UUID plr) {
if (wrapper != null)
return wrapper.get(plr);
BigDecimal bd = SU.getPlayerConfig(plr).getObject("balance." + name, BigDecimal.class);
return bd == null ? defaultValue : bd;
}
public BigDecimal getBank(String bank) {
BigDecimal bd = SU.pf.getObject("bankbalance." + bank + "." + name, BigDecimal.class);
return bd == null ? defaultValue : bd;
}
public boolean set(UUID plr, BigDecimal value) {
if (wrapper != null)
return wrapper.set(plr, value);
SU.getPlayerConfig(plr).setObject("balance." + name, value);
return true;
}
public boolean setBank(String bank, BigDecimal value) {
SU.pf.setObject("bankbalance." + bank + "." + name, value);
return true;
}
}
| 1,171 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ConfigSerialization.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/configfile/ConfigSerialization.java | package gyurix.configfile;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.DualMap;
import org.apache.commons.lang.ClassUtils;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
public class ConfigSerialization {
private static final DualMap<Class, String> aliases = new DualMap<>();
private static final DualMap<Class, Class> interfaceBasedClasses = new DualMap<>();
private static final HashMap<Class, Serializer> serializers = new HashMap<>();
static {
DefaultSerializers.init();
}
public static String calculateClassName(Class type, Class objectClass) {
if (!objectClass.getName().equals(type.getName())) {
Class c = interfaceBasedClasses.get(type);
c = c == null ? type : c;
if (c != objectClass) {
return '-' + getAlias(objectClass);
}
}
return "";
}
public static String getAlias(Class c) {
if (c.isArray())
c = Array.class;
String al = aliases.get(c);
if (al == null) {
Class i = interfaceBasedClasses.getKey(c);
if (i != null) {
al = aliases.get(i);
return al == null ? i.getName() : al;
}
return c.getName();
}
return al;
}
public static DualMap<Class, String> getAliases() {
return aliases;
}
public static DualMap<Class, Class> getInterfaceBasedClasses() {
return interfaceBasedClasses;
}
public static Class getNotInterfaceClass(Class cl) {
Class c = interfaceBasedClasses.get(cl);
return c == null ? cl : c;
}
public static Serializer getSerializer(Class cl) {
Class c = cl;
if (cl.isArray()) {
return serializers.get(Array.class);
}
Serializer s = serializers.get(c);
for (; ; ) {
if (s != null)
return s;
c = c.getSuperclass();
if (c == null || c == Object.class)
break;
s = serializers.get(c);
}
for (Class i : (List<Class>) ClassUtils.getAllInterfaces(cl)) {
s = serializers.get(i);
if (s != null) {
return s;
}
}
return serializers.get(Object.class);
}
public static HashMap<Class, Serializer> getSerializers() {
return serializers;
}
public static Class realClass(String alias) {
Class alC = aliases.getKey(alias);
try {
Class c = alC == null ? Class.forName(alias) : alC;
Class c2 = interfaceBasedClasses.get(c);
return c2 == null ? c : c2;
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ConfigOptions {
String comment() default "";
String defaultValue() default "null";
boolean serialize() default true;
}
public interface Serializer {
Object fromData(ConfigData paramConfigData, Class paramClass, Type... paramVarArgs);
default ConfigData postSerialize(Object o, ConfigData data) {
return data;
}
default Class resolveType(ConfigData data) {
return Object.class;
}
ConfigData toData(Object paramObject, Type... paramVarArgs);
}
public interface StringSerializable {
String toString();
}
} | 3,394 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ValueClassSelector.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/configfile/ValueClassSelector.java | package gyurix.configfile;
import java.lang.reflect.Type;
/**
* ValueClassSelector is a special ability for keys for being able to choose the type of their values. The most common
* usage of this interface is in EnumMaps.
*/
public interface ValueClassSelector {
Class getValueClass();
Type[] getValueTypes();
}
| 322 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ConfigReader.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/configfile/ConfigReader.java | package gyurix.configfile;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class ConfigReader {
final int blockLvl;
final ConfigData key;
final ConfigData value;
private boolean keyRead, noList;
ConfigReader(int lvl, ConfigData data) {
blockLvl = lvl;
value = data;
key = null;
}
ConfigReader(int lvl, ConfigData key, ConfigData value) {
blockLvl = lvl;
this.key = key;
this.value = value;
}
public ConfigReader(int lvl, ConfigData value, boolean noList) {
blockLvl = lvl;
this.value = value;
key = null;
this.noList = noList;
}
public void addComment(String com) {
ConfigData data = getData();
if (data.comment == null) {
data.comment = com;
} else {
data.comment += '\n' + com;
}
}
public ConfigData getData() {
return keyRead ? key : value;
}
public void handleInput(ArrayList<ConfigReader> readers, String line, int lvl) {
ConfigData data = getData();
if (!noList && line.equals("-") || line.equals(">") || line.indexOf(':') == line.length() - 1)
line += ' ';
if (!noList && line.startsWith("- ")) {
if (data.listData == null)
data.listData = new ArrayList();
ConfigData d = new ConfigData();
data.listData.add(d);
ConfigReader r = new ConfigReader(lvl + 1, d, true);
readers.add(r);
r.handleInput(readers, line.substring(2), lvl + 2);
} else if (line.startsWith("> ")) {
ConfigData key = new ConfigData(ConfigData.unescape(line.substring(2)));
ConfigData value = new ConfigData();
ConfigReader reader = new ConfigReader(lvl, key, value);
reader.keyRead = true;
if (lvl == blockLvl) {
int size = readers.size() - 2;
readers.remove(size + 1);
readers.get(size).getData().mapData.put(key, value);
} else {
if (data.mapData == null)
data.mapData = new LinkedHashMap();
data.mapData.put(key, value);
}
readers.add(reader);
} else if (keyRead && line.startsWith(": ")) {
keyRead = false;
value.stringData = ConfigData.unescape(line.substring(2));
} else {
String[] s = line.startsWith(": ") ? new String[]{line} : line.split(" *: +", 2);
if (s.length == 2) {
ConfigData key;
if (keyRead) {
this.key.stringData += ConfigData.unescape('\n' + s[0]);
key = this.key;
} else {
key = new ConfigData(ConfigData.unescape(s[0]));
}
ConfigData value = new ConfigData(ConfigData.unescape(s[1]));
ConfigReader reader = new ConfigReader(lvl, key, value);
if (lvl == blockLvl) {
int size = readers.size() - 2;
readers.remove(size + 1);
data = readers.get(size).getData();
if (data.mapData == null)
data.mapData = new LinkedHashMap();
data.mapData.put(key, value);
} else {
if (data.mapData == null)
data.mapData = new LinkedHashMap();
data.mapData.put(key, value);
}
readers.add(reader);
} else if (data.stringData == null) {
data.stringData = ConfigData.unescape(line);
} else {
data.stringData += ConfigData.unescape('\n' + line);
}
}
}
} | 3,296 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ConfigFile.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/configfile/ConfigFile.java | package gyurix.configfile;
import gyurix.mysql.MySQLDatabase;
import gyurix.spigotlib.SU;
import org.apache.commons.lang.ArrayUtils;
import java.io.*;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static gyurix.spigotlib.SU.*;
/**
* Data structure used for managing plugins configurations.
*/
public class ConfigFile {
private static final String addressSplit = "\\.";
private static final ExecutorService ioThread = Executors.newFixedThreadPool(1);
/**
* The core of this ConfigFile
*/
public ConfigData data = new ConfigData();
/**
* The MySQLDatabase settings used for storing and loading the configuration from MySQL
*/
public MySQLDatabase db;
/**
* The MySQLDatabase settings used for storing and loading the configuration from MySQL
*/
public String dbTable, dbKey, dbValue, dbArgs;
/**
* The file used for storing and loading the configuration
*/
public File file;
/**
* Constructs an empty ConfigFile
*/
public ConfigFile() {
}
/**
* Constructs an empty ConfigFile and loads it from the given InputStream
*
* @param stream - The InputStream containing the loadable configuration
*/
public ConfigFile(InputStream stream) {
load(stream);
}
/**
* Constructs an empty ConfigFile and loads it from the given InputStream
*
* @param file - The File containing the loadable configuration
*/
public ConfigFile(File file) {
load(file);
}
/**
* Constructs an empty ConfigFile and loads it from MySQL
*
* @param mysql - The MySQLDatabase containing the loadable configuration
*/
public ConfigFile(MySQLDatabase mysql) {
db = mysql;
dbTable = mysql.table;
dbKey = "key";
dbValue = "value";
}
/**
* Constructs an empty ConfigFile and loads it from MySQL
*
* @param mysql - The MySQLDatabase containing the loadable configuration
* @param table - The table which contains the configuration, usually <b>mysql.table</b>
* @param key - The columns name which should be used for storing configurations addresses, usually <b>"key"</b>
* @param value - The columns name which should be used for storing configurations values, usually <b>"value"</b>
*/
public ConfigFile(MySQLDatabase mysql, String table, String key, String value) {
db = mysql;
dbTable = table;
dbKey = key;
dbValue = value;
}
/**
* Constructs an empty ConfigFile and loads it from the given String
*
* @param in - The String containing the loadable configuration
*/
public ConfigFile(String in) {
load(in);
}
/**
* Wrap an already existing ConfigData
*
* @param d - The wrapable ConfigData
*/
public ConfigFile(ConfigData d) {
data = d;
}
/**
* Get the given typed Object from the ConfigFiles given address. If the given address does not exist
* then it will be created automatically
*
* @param adress - The address
* @param cl - The requested Objects type
* @param <T> - The requested Objects type
* @return The requested Object
*/
public <T> T get(String adress, Class<T> cl) {
return getData(adress, true).deserialize(cl);
}
/**
* Get the given typed Object from the ConfigFiles given address. If the given address does not exist
* then it will be created automatically
*
* @param adress - The address
* @param cl - The requested Objects type
* @param types - The parameter types of the requested Object
* @param <T> - The requested Objects type
* @return The requested Object
*/
public <T> T get(String adress, Class<T> cl, Type... types) {
return getData(adress, true).deserialize(cl, types);
}
/**
* Get a boolean variable from the configuration
*
* @param address - The address used for storing the value
* @param def - Default value which should be returned if the address does not exist
* @return The requested boolean variable or def it it was not found
*/
public boolean getBoolean(String address, boolean def) {
return getObject(address, Boolean.class, def);
}
/**
* Get a boolean variable from the configuration
*
* @param address - The address used for storing the value
* @return The requested byte variable or 0 if it was not found
*/
public boolean getBoolean(String address) {
return getObject(address, Boolean.class, false);
}
/**
* Get a byte variable from the configuration
*
* @param address - The address used for storing the value
* @param def - Default value which should be returned if the address does not exist
* @return The requested byte variable or def it it was not found
*/
public byte getByte(String address, byte def) {
return getObject(address, Byte.class, def);
}
/**
* Get a byte variable from the configuration
*
* @param address - The address used for storing the value
* @return The requested byte variable or 0 if it was not found
*/
public byte getByte(String address) {
return getObject(address, Byte.class, (byte) 0);
}
/**
* Get data found in the given address
*
* @param address - Requested address
* @return The data found on the given address or empty ConfigData, if it can
* not be found.
*/
public ConfigData getData(String address) {
String[] parts = address.split(addressSplit);
ConfigData d = data;
for (String p : parts) {
if (p.matches("#\\d+")) {
int num = Integer.valueOf(p.substring(1));
if (d.listData == null || d.listData.size() <= num)
return new ConfigData("");
d = d.listData.get(num);
} else {
ConfigData key = new ConfigData(p);
if (d.mapData == null)
return new ConfigData("");
if (d.mapData.containsKey(key)) {
d = d.mapData.get(key);
} else {
return new ConfigData("");
}
}
}
return d;
}
/**
* Get data found in the given address.
*
* @param address - Requested address
* @param autoCreate - Automatically create the road for accessing the given address
* @return The data found on the given address or empty ConfigData, if it can
* not be found.
*/
public ConfigData getData(String address, boolean autoCreate) {
if (!autoCreate)
return getData(address);
String[] parts = address.split(addressSplit);
ConfigData d = data;
for (String p : parts) {
if (p.matches("#\\d+")) {
int num = Integer.valueOf(p.substring(1));
if (d.listData == null) {
d.listData = new ArrayList<>();
}
while (d.listData.size() <= num) {
d.listData.add(new ConfigData(""));
}
d = d.listData.get(num);
} else {
ConfigData key = new ConfigData(p);
if (d.mapData == null)
d.mapData = new LinkedHashMap<>();
if (d.mapData.containsKey(key)) {
d = d.mapData.get(key);
} else {
d.mapData.put(key, d = new ConfigData(""));
}
}
}
return d;
}
/**
* Get a double variable from the configuration
*
* @param address - The address used for storing the value
* @param def - Default value which should be returned if the address does not exist
* @return The requested double variable or def it it was not found
*/
public double getDouble(String address, double def) {
return getObject(address, Double.class, def);
}
/**
* Get a double variable from the configuration
*
* @param address - The address used for storing the value
* @return The requested double variable or 0 if it was not found
*/
public double getDouble(String address) {
return getObject(address, Double.class, 0D);
}
/**
* Get a float variable from the configuration
*
* @param address - The address used for storing the value
* @param def - Default value which should be returned if the address does not exist
* @return The requested float variable or def it it was not found
*/
public float getFloat(String address, float def) {
return getObject(address, Float.class, def);
}
/**
* Get a float variable from the configuration
*
* @param address - The address used for storing the value
* @return The requested float variable or 0 if it was not found
*/
public float getFloat(String address) {
return getObject(address, Float.class, 0f);
}
/**
* Get an int variable from the configuration
*
* @param address - The address used for storing the value
* @param def - Default value which should be returned if the address does not exist
* @return The requested int variable or def it it was not found
*/
public int getInt(String address, int def) {
return getObject(address, Integer.class, def);
}
/**
* Get an int variable from the configuration
*
* @param address - The address used for storing the value
* @return The requested int variable or 0 if it was not found
*/
public int getInt(String address) {
return getObject(address, Integer.class, 0);
}
/**
* Get a long variable from the configuration
*
* @param address - The address used for storing the value
* @param def - Default value which should be returned if the address does not exist
* @return The requested long variable or def it it was not found
*/
public long getLong(String address, long def) {
return getObject(address, Long.class, def);
}
/**
* Get a long variable from the configuration
*
* @param address - The address used for storing the value
* @return The requested long variable or 0 if it was not found
*/
public long getLong(String address) {
return getObject(address, Long.class, 0L);
}
/**
* Get the given typed Object from the ConfigFile
*
* @param adress - The address of the Object
* @param cl - The objects type
* @param types - Object type parameters
* @param <T> - The type of the Object
* @return The requested Object or null if it was not found.
*/
public <T> T getObject(String adress, Class<T> cl, Type... types) {
return getObject(adress, cl, null, types);
}
/**
* Get the given typed Object from the ConfigFile
*
* @param adress - The address of the Object
* @param cl - The objects type
* @param def - Default return Object used, when Object can not be found under the given key
* @param types - Object type parameters
* @param <T> - The type of the Object
* @return The requested Object or def if it was not found.
*/
public <T> T getObject(String adress, Class<T> cl, T def, Type... types) {
ConfigData cd = getData(adress);
return cd.isEmpty() ? def : cd.deserialize(cl, types);
}
/**
* Get a short variable from the configuration
*
* @param address - The address used for storing the value
* @param def - Default value which should be returned if the address does not exist
* @return The requested short variable or def it it was not found
*/
public short getShort(String address, short def) {
return getObject(address, Short.class, def);
}
/**
* Get a short variable from the configuration
*
* @param address - The address used for storing the value
* @return The requested short variable or 0 if it was not found
*/
public short getShort(String address) {
return getObject(address, Short.class, (short) 0);
}
/**
* Get a String variable from the configuration
*
* @param address - The address used for storing the value
* @param def - Default value which should be returned if the address does not exist
* @return The requested String variable or def it it was not found
*/
public String getString(String address, String def) {
return getObject(address, String.class, def);
}
/**
* Get a String variable from the configuration
*
* @param address - The address used for storing the value
* @return The requested String variable or empty string if it was not found
*/
public String getString(String address) {
return getObject(address, String.class, "");
}
/**
* Get all the main sub keys of this configuration
*
* @return The list of main sub keys of this configuration
*/
public ArrayList<String> getStringKeyList() {
ArrayList<String> out = new ArrayList<>();
try {
for (ConfigData cd : data.mapData.keySet())
out.add(cd.stringData);
} catch (Throwable ignored) {
}
return out;
}
/**
* Get all the main sub keys of this configuration which are under the root key
*
* @param key - Root key
* @return The list of main sub keys under the root key
*/
public ArrayList<String> getStringKeyList(String key) {
ArrayList<String> out = new ArrayList<>();
try {
for (ConfigData cd : getData(key).mapData.keySet()) {
out.add(cd.stringData);
}
} catch (Throwable ignored) {
}
return out;
}
/**
* Load configuration from an InputStream
*
* @param is - The loadable InputStream
* @return The success of the load
*/
public boolean load(InputStream is) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
for (int len = is.read(buf); len > 0; len = is.read(buf))
bos.write(buf, 0, len);
is.close();
return load(new String(bos.toByteArray(), utf8));
} catch (Throwable e) {
error(cs, e, "SpigotLib", "gyurix");
}
return false;
}
/**
* Load configuration from a String
*
* @param in - The loadable String
* @return The success of the load
*/
public boolean load(String in) {
in = in.replaceAll("&([0-9a-fk-or])", "§$1");
ArrayList<ConfigReader> readers = new ArrayList<>();
readers.add(new ConfigReader(-1, data));
for (String s : in.split("\r?\n")) {
int blockLvl = 0;
while (s.length() > blockLvl && s.charAt(blockLvl) == ' ')
blockLvl++;
s = s.substring(blockLvl);
int id = readers.size() - 1;
if (!s.isEmpty()) {
if (s.startsWith("#")) {
readers.get(id).addComment(s.substring(1));
} else {
while (readers.get(id).blockLvl > blockLvl) {
readers.remove(id);
id--;
}
readers.get(id).handleInput(readers, s, blockLvl);
}
}
}
return true;
}
/**
* Load configuration from a File
*
* @param f - The loadable File
* @return The success of the load
*/
public boolean load(File f) {
try {
file = f;
f.createNewFile();
byte[] b = Files.readAllBytes(f.toPath());
load(new String(b, utf8));
return true;
} catch (Throwable e) {
error(cs, e, "SpigotLib", "gyurix");
}
return false;
}
/**
* Load the given address of this configuration from MySQL
*
* @param address - The loadable address
* @param args - Arguments of the MySQL WHERE clause
*/
public void mysqlLoad(String address, String args) {
String q = "SELECT `" + dbKey + "`, `" + dbValue + "` FROM " + dbTable + " WHERE " + args;
try {
ResultSet rs = db.query(q);
while (rs.next()) {
String k = rs.getString(dbKey);
String v = rs.getString(dbValue);
setData(address + "." + k, new ConfigFile(v).data);
}
} catch (Throwable e) {
cs.sendMessage("§cFailed to load data from MySQL storage.\n" +
"The used query command:\n");
error(cs, e, "SpigotLib", "gyurix");
e.printStackTrace();
}
}
/**
* Load the configuration from MySQL
*/
public void mysqlLoad() {
String q = "SELECT `" + dbKey + "`, `" + dbValue + "` FROM " + dbTable;
try {
if (db == null || !db.openConnection())
return;
ResultSet rs = db.query(q);
while (rs.next()) {
String k = rs.getString(dbKey);
String v = rs.getString(dbValue);
setData(k, new ConfigFile(v).data);
}
} catch (Throwable e) {
cs.sendMessage("§cFailed to load data from MySQL storage.\n" +
"The used query command:\n");
error(cs, e, "SpigotLib", "gyurix");
e.printStackTrace();
}
}
/**
* Add to the given list the MySQL commands required for updating the storage based on this Configuration
*
* @param l - The list
* @param args - The arguments which should be passed after MySQL WHERE clause.
*/
public void mysqlUpdate(ArrayList<String> l, String args) {
if (dbTable == null)
return;
l.add("DELETE FROM " + dbTable + (dbArgs == null ? "" : (" WHERE " + dbArgs)));
if (args == null)
args = dbArgs == null ? "'<key>','<value>'" : dbArgs.substring(dbArgs.indexOf('=') + 1) + ",'<key>','<value>'";
data.saveToMySQL(l, dbTable, args, "");
}
/**
* Reloads the configuration from the file used in initialization
*
* @return The success of reload
*/
public boolean reload() {
if (file == null) {
SU.cs.sendMessage("§cError on reloading ConfigFile, missing file data.");
return false;
}
data = new ConfigData();
return load(file);
}
/**
* Remove the given address from the configuration
*
* @param address - The removable address
* @return True if the data was removed, false otherwise
*/
public boolean removeData(String address) {
String[] allParts = address.split(addressSplit);
int len = allParts.length - 1;
String[] parts = (String[]) ArrayUtils.subarray(allParts, 0, len);
ConfigData d = data;
for (String p : parts) {
if (p.matches("#\\d+")) {
if (d.listData == null)
return false;
int num = Integer.valueOf(p.substring(1));
if (d.listData.size() >= num)
return false;
d = d.listData.get(num);
} else {
ConfigData key = new ConfigData(p);
if (d.mapData == null || !d.mapData.containsKey(key))
return false;
else
d = d.mapData.get(key);
}
}
if (allParts[len].matches("#\\d+")) {
int id = Integer.valueOf(allParts[len].substring(1));
return d.listData.remove(id) != null;
}
return d.mapData == null || d.mapData.remove(new ConfigData(allParts[len])) != null;
}
/**
* Saves the configuration asynchronously.
*
* @return The success rate of the saving.
*/
public boolean save() {
if (db != null) {
ArrayList<String> sl = new ArrayList<>();
mysqlUpdate(sl, dbArgs);
db.batch(sl, null);
return true;
} else if (file != null) {
final String data = toString();
ioThread.submit(() -> saveDataToFile(data));
return true;
}
SU.cs.sendMessage("§cFailed to save ConfigFile: §eMissing file / valid MySQL data.");
return false;
}
/**
* Saves the configuration to the given OutputStream.
*
* @return The success rate of the saving.
*/
public boolean save(OutputStream out) {
try {
byte[] data = toString().getBytes(utf8);
out.write(data);
out.flush();
out.close();
return true;
} catch (Throwable e) {
e.printStackTrace();
return false;
}
}
private void saveDataToFile(String data) {
try {
File tempf = new File(file + ".tmp");
tempf.createNewFile();
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempf), utf8));
if (data != null)
w.write(data.replaceAll("§([0-9a-fk-or])", "&$1"));
w.close();
file.delete();
tempf.renameTo(file);
} catch (Throwable e) {
error(cs, e, "SpigotLib", "gyurix");
}
}
/**
* Save the config file without using async thread.
*
* @return The sucess rate of the saving
*/
public boolean saveNoAsync() {
if (db != null) {
ArrayList<String> sl = new ArrayList<>();
mysqlUpdate(sl, dbArgs);
db.batchNoAsync(sl);
return true;
} else if (file != null) {
saveDataToFile(toString());
return true;
}
System.err.println("Failed to save ConfigFile: Missing file / valid MySQL data.");
return false;
}
/**
* Serializes the ConfigData for being able to throw all the object references
*/
public void serialize() {
data = new ConfigFile(data.toString()).data;
}
/**
* Set the given the given address to the given ConfigData
*
* @param address - The changable address
* @param cd - Target ConfigData
*/
public void setData(String address, ConfigData cd) {
String[] parts = address.split(addressSplit);
ConfigData last = data;
ConfigData lastKey = data;
ConfigData d = data;
for (String p : parts) {
ConfigData key = new ConfigData(p);
if (d.mapData == null)
d.mapData = new LinkedHashMap<>();
last = d;
lastKey = key;
if (d.mapData.containsKey(key)) {
d = d.mapData.get(key);
} else {
d.mapData.put(key, d = new ConfigData(""));
}
}
last.mapData.put(lastKey, cd);
}
/**
* Set the given address to the given Object.
*
* @param address - The setable address
* @param obj - Target Object
*/
public void setObject(String address, Object obj) {
getData(address, true).objectData = obj;
}
/**
* Set the given address to the given String.
*
* @param address - The setable address
* @param value - Target String
*/
public void setString(String address, String value) {
getData(address, true).stringData = value;
}
/**
* Get the given sub section of this ConfigFile
*
* @param address - Sub sections address
* @return The requested sub section of this ConfigFile
*/
public ConfigFile subConfig(String address) {
return new ConfigFile(getData(address, true));
}
/**
* Get the given sub section of this ConfigFile referring to
*
* @param address - Sub sections address
* @param dbArgs - The MySQL arguments which should be used for saving this sub section
* @return The requested sub section of this ConfigFile
*/
public ConfigFile subConfig(String address, String dbArgs) {
ConfigFile kf = new ConfigFile(getData(address, true));
kf.db = db;
kf.dbTable = dbTable;
kf.dbKey = dbKey;
kf.dbValue = dbValue;
kf.dbArgs = dbArgs;
return kf;
}
/**
* Convert this ConfigFile to a String
*
* @return The same result as data.toString()
*/
public String toString() {
String str = data.toString();
return str.startsWith("\n") ? str.substring(1) : str;
}
} | 22,852 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
PostLoadable.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/configfile/PostLoadable.java | package gyurix.configfile;
/**
* The PostLoadable interface allows objects to have a postLoad method which will be executed after loading it from configuration.
*/
public interface PostLoadable {
void postLoad();
}
| 220 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
DefaultSerializers.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/configfile/DefaultSerializers.java | package gyurix.configfile;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.configfile.ConfigSerialization.Serializer;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.nbt.NBTCompound;
import gyurix.nbt.NBTList;
import gyurix.nbt.NBTTag;
import gyurix.protocol.Primitives;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.DualMap;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import static gyurix.configfile.ConfigData.serializeObject;
import static gyurix.protocol.Reflection.newInstance;
import static gyurix.spigotlib.Config.debug;
public class DefaultSerializers {
public static final Type[] emptyTypeArray = new Type[0];
public static int leftPad;
public static boolean includeClassName(Class objCl, Class expectedCl) {
return objCl != expectedCl
&& !Map.class.isAssignableFrom(objCl)
&& !ItemStack.class.isAssignableFrom(objCl)
&& !Collection.class.isAssignableFrom(objCl);
}
public static void init() {
HashMap<Class, Serializer> serializers = ConfigSerialization.getSerializers();
NBTTag.NBTSerializer nbtSerializer = new NBTTag.NBTSerializer();
serializers.put(NBTTag.class, nbtSerializer);
serializers.put(String.class, new StringSerializer());
serializers.put(Class.class, new ClassSerializer());
serializers.put(UUID.class, new UUIDSerializer());
serializers.put(ConfigData.class, new ConfigDataSerializer());
NumberSerializer numSerializer = new NumberSerializer();
serializers.put(Array.class, new ArraySerializer());
serializers.put(Boolean.class, new BooleanSerializer());
serializers.put(Byte.class, numSerializer);
serializers.put(Character.class, new CharacterSerializer());
serializers.put(Collection.class, new CollectionSerializer());
serializers.put(NBTList.class, new CollectionSerializer(NBTTag.class, nbtSerializer));
serializers.put(Double.class, numSerializer);
serializers.put(Float.class, numSerializer);
serializers.put(Integer.class, numSerializer);
serializers.put(Long.class, numSerializer);
serializers.put(Map.class, new MapSerializer());
serializers.put(NBTCompound.class, new MapSerializer(String.class, NBTTag.class, nbtSerializer));
serializers.put(Object.class, new ObjectSerializer());
serializers.put(Pattern.class, new PatternSerializer());
serializers.put(Short.class, numSerializer);
serializers.put(SimpleDateFormat.class, new SimpleDateFormatSerializer());
serializers.put(Map.Entry.class, new EntrySerializer());
DualMap<Class, String> aliases = ConfigSerialization.getAliases();
aliases.put(Array.class, "[]");
aliases.put(Boolean.class, "bool");
aliases.put(Byte.class, "b");
aliases.put(Character.class, "c");
aliases.put(Collection.class, "{}");
aliases.put(Double.class, "d");
aliases.put(Float.class, "f");
aliases.put(Integer.class, "i");
aliases.put(LinkedHashMap.class, "<L>");
aliases.put(LinkedHashSet.class, "{LS}");
aliases.put(List.class, "{L}");
aliases.put(Long.class, "l");
aliases.put(Map.class, "<>");
aliases.put(Object.class, "?");
aliases.put(Set.class, "{S}");
aliases.put(Short.class, "s");
aliases.put(String.class, "str");
aliases.put(TreeMap.class, "<T>");
aliases.put(TreeSet.class, "{TS}");
aliases.put(UUID.class, "uuid");
aliases.put(Map.Entry.class, "<KV>");
DualMap<Class, Class> ifbClasses = ConfigSerialization.getInterfaceBasedClasses();
ifbClasses.put(List.class, ArrayList.class);
ifbClasses.put(Set.class, HashSet.class);
ifbClasses.put(NavigableSet.class, TreeSet.class);
ifbClasses.put(Map.class, HashMap.class);
ifbClasses.put(NavigableMap.class, TreeMap.class);
ifbClasses.put(Entry.class, AbstractMap.SimpleEntry.class);
}
public static boolean shouldSkip(Class cl) {
return cl == Class.class || cl.getName().startsWith("java.lang.reflect.") || cl.getName().startsWith("sun.");
}
public static class ArraySerializer implements Serializer {
public Object fromData(ConfigData input, Class fixClass, Type... parameterTypes) {
Class cl = Object.class;
Type[] types = emptyTypeArray;
if (parameterTypes.length >= 1) {
if (parameterTypes[0] instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) parameterTypes[0];
cl = (Class) pt.getRawType();
types = pt.getActualTypeArguments();
} else {
cl = (Class) parameterTypes[0];
}
}
if (input.listData != null) {
Object ar = Array.newInstance(cl, input.listData.size());
int i = 0;
for (ConfigData d : input.listData) {
Array.set(ar, i++, d.deserialize(cl, types));
}
return ar;
} else {
String[] sd = input.stringData.split(";");
Object ar = Array.newInstance(cl, sd.length);
int i = 0;
for (String d : sd) {
Array.set(ar, i++, new ConfigData(d).deserialize(cl, types));
}
return ar;
}
}
public ConfigData toData(Object input, Type... parameters) {
Class cl = parameters.length >= 1 ? (Class) parameters[0] : Object.class;
ConfigData d = new ConfigData();
d.listData = new ArrayList<>();
if (input instanceof Object[])
for (Object o : (Object[]) input) {
d.listData.add(serializeObject(o, includeClassName(o.getClass(), cl)));
}
else {
int len = Array.getLength(input);
for (int i = 0; i < len; ++i) {
Object o = Array.get(input, i);
d.listData.add(serializeObject(o, includeClassName(o.getClass(), cl)));
}
}
return d;
}
}
public static class BooleanSerializer implements Serializer {
public Object fromData(ConfigData input, Class cl, Type... parameters) {
String s = input.stringData;
return s != null && (s.equals("+") || s.equals("true") || s.equals("yes"));
}
public ConfigData toData(Object in, Type... parameters) {
return new ConfigData((boolean) in ? "+" : "-");
}
}
public static class CharacterSerializer implements Serializer {
public Object fromData(ConfigData input, Class cl, Type... parameters) {
return input.stringData.charAt(0);
}
public ConfigData toData(Object in, Type... parameters) {
return new ConfigData(String.valueOf(in));
}
}
private static class ClassSerializer implements Serializer {
ClassSerializer() {
}
public Object fromData(ConfigData input, Class cl, Type... parameters) {
try {
return Class.forName(input.stringData);
} catch (ClassNotFoundException e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public ConfigData toData(Object input, Type... parameters) {
return new ConfigData(((Class) input).getName());
}
}
public static class CollectionSerializer implements Serializer {
private Serializer childSerializer;
private Class defaultKeyClass;
public CollectionSerializer() {
defaultKeyClass = Object.class;
}
public CollectionSerializer(Class<NBTTag> defaultKeyClass, Serializer childSerializer) {
this.defaultKeyClass = defaultKeyClass;
this.childSerializer = childSerializer;
}
public Object fromData(ConfigData input, Class fixClass, Type... parameterTypes) {
try {
Class cl = ConfigSerialization.getNotInterfaceClass(fixClass);
Collection col = cl == null ? new ArrayList() : (Collection) cl.newInstance();
Type[] types;
ParameterizedType pt;
cl = defaultKeyClass;
types = emptyTypeArray;
if (parameterTypes.length >= 1) {
if (parameterTypes[0] instanceof ParameterizedType) {
pt = (ParameterizedType) parameterTypes[0];
cl = (Class) pt.getRawType();
types = pt.getActualTypeArguments();
} else {
cl = (Class) parameterTypes[0];
}
}
if (input.listData != null) {
for (ConfigData d : input.listData) {
col.add(d.deserialize(cl, types));
}
} else if (input.stringData != null && !input.stringData.isEmpty()) {
for (String s : input.stringData.split("[;,] *"))
col.add(new ConfigData(s).deserialize(cl, types));
}
return col;
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public ConfigData toData(Object input, Type... parameters) {
Type[] types = emptyTypeArray;
Class keyClass = defaultKeyClass;
if (parameters.length >= 1) {
if (parameters[0] instanceof ParameterizedType) {
ParameterizedType key = (ParameterizedType) parameters[0];
types = key.getActualTypeArguments();
keyClass = (Class) key.getRawType();
} else {
keyClass = (Class) parameters[0];
}
}
if (((Collection) input).isEmpty())
return new ConfigData("");
ConfigData d = new ConfigData();
d.listData = new ArrayList<>();
for (Object o : (Collection) input)
d.listData.add(serializeObject(o, o.getClass() != keyClass, types));
return childSerializer == null ? d : childSerializer.postSerialize(input, d);
}
}
public static class ConfigDataSerializer implements Serializer {
public Object fromData(ConfigData data, Class cl, Type... type) {
return data;
}
public ConfigData toData(Object data, Type... type) {
return (ConfigData) data;
}
}
public static class MapSerializer implements Serializer {
private Serializer child;
private Class defaultKeyClass, defaultValueClass;
public MapSerializer() {
this.defaultKeyClass = Object.class;
this.defaultValueClass = Object.class;
}
public MapSerializer(Class defaultKeyClass, Class defaultValueClass, Serializer child) {
this.defaultKeyClass = defaultKeyClass;
this.defaultValueClass = defaultValueClass;
this.child = child;
}
public Object fromData(ConfigData input, Class fixClass, Type... parameterTypes) {
try {
Map map;
if (fixClass == EnumMap.class)
map = new EnumMap((Class) parameterTypes[0]);
else if (Reflection.getConstructor(fixClass) != null)
map = (Map) fixClass.getConstructor().newInstance();
else
map = new LinkedHashMap();
Class keyClass;
Type[] keyTypes;
Class valueClass;
Type[] valueTypes;
ParameterizedType pt;
if (input.mapData != null) {
keyClass = defaultKeyClass;
keyTypes = emptyTypeArray;
if (parameterTypes.length >= 1) {
if (parameterTypes[0] instanceof ParameterizedType) {
pt = (ParameterizedType) parameterTypes[0];
keyClass = (Class) pt.getRawType();
keyTypes = pt.getActualTypeArguments();
} else {
keyClass = (Class) parameterTypes[0];
}
}
boolean dynamicValueCl = ValueClassSelector.class.isAssignableFrom(keyClass);
valueClass = defaultValueClass;
valueTypes = emptyTypeArray;
if (!dynamicValueCl && parameterTypes.length >= 2) {
if (parameterTypes[1] instanceof ParameterizedType) {
pt = (ParameterizedType) parameterTypes[1];
valueClass = (Class) pt.getRawType();
valueTypes = pt.getActualTypeArguments();
} else {
valueClass = (Class) parameterTypes[1];
}
}
if (dynamicValueCl) {
for (Entry<ConfigData, ConfigData> e : input.mapData.entrySet()) {
try {
ValueClassSelector key = (ValueClassSelector) e.getKey().deserialize(keyClass, keyTypes);
map.put(key, e.getValue().deserialize(key.getValueClass(), key.getValueTypes()));
} catch (Throwable err) {
SU.cs.sendMessage("§cMap element deserialization error:\n§eKey = §f" + e.getKey() + "§e; Value = §f" + e.getValue());
SU.error(SU.cs, err, "SpigotLib", "gyurix");
}
}
} else {
for (Entry<ConfigData, ConfigData> e : input.mapData.entrySet()) {
try {
map.put(e.getKey().deserialize(keyClass, keyTypes), e.getValue().deserialize(valueClass, valueTypes));
} catch (Throwable err) {
SU.log(Main.pl, "§cMap element deserialization error:\n§eKey = §f" + e.getKey() + "§e; Value = §f" + e.getValue());
SU.error(SU.cs, err, "SpigotLib", "gyurix");
}
}
}
}
return map;
} catch (Throwable e) {
e.printStackTrace();
//SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public ConfigData toData(Object input, Type... parameters) {
try {
if (((Map) input).isEmpty())
return new ConfigData();
Class keyClass = defaultKeyClass;
Class valueClass = defaultValueClass;
Type[] keyTypes = emptyTypeArray;
Type[] valueTypes = emptyTypeArray;
if (parameters.length >= 1) {
if (parameters[0] instanceof ParameterizedType) {
ParameterizedType key = (ParameterizedType) parameters[0];
keyTypes = key.getActualTypeArguments();
keyClass = (Class) key.getRawType();
} else {
keyClass = (Class) parameters[0];
}
}
boolean valueClassSelector = keyClass.isAssignableFrom(ValueClassSelector.class);
if (!valueClassSelector && parameters.length >= 2) {
if (parameters[1] instanceof ParameterizedType) {
ParameterizedType value = (ParameterizedType) parameters[1];
valueTypes = value.getActualTypeArguments();
valueClass = (Class) value.getRawType();
} else {
valueClass = (Class) parameters[1];
}
}
ConfigData d = new ConfigData();
d.mapData = new LinkedHashMap();
for (Entry<?, ?> e : ((Map<?, ?>) input).entrySet()) {
Object key = e.getKey();
Object value = e.getValue();
if (key != null && value != null)
d.mapData.put(serializeObject(key, includeClassName(key.getClass(), keyClass), keyTypes),
serializeObject(value, !valueClassSelector &&
includeClassName(value.getClass(), valueClass), valueTypes));
}
return child == null ? d : child.postSerialize(input, d);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
}
public static class EntrySerializer implements Serializer {
private Class defaultKeyClass, defaultValueClass;
public EntrySerializer() {
this.defaultKeyClass = Object.class;
this.defaultValueClass = Object.class;
}
public Object fromData(ConfigData input, Class fixClass, Type... parameterTypes) {
try {
Class keyClass;
Type[] keyTypes;
Class valueClass;
Type[] valueTypes;
ParameterizedType pt;
keyClass = defaultKeyClass;
keyTypes = emptyTypeArray;
if (parameterTypes.length >= 1) {
if (parameterTypes[0] instanceof ParameterizedType) {
pt = (ParameterizedType) parameterTypes[0];
keyClass = (Class) pt.getRawType();
keyTypes = pt.getActualTypeArguments();
} else {
keyClass = (Class) parameterTypes[0];
}
}
valueClass = defaultValueClass;
valueTypes = emptyTypeArray;
if (parameterTypes.length >= 2) {
if (parameterTypes[1] instanceof ParameterizedType) {
pt = (ParameterizedType) parameterTypes[1];
valueClass = (Class) pt.getRawType();
valueTypes = pt.getActualTypeArguments();
} else {
valueClass = (Class) parameterTypes[1];
}
}
String[] d = input.stringData.split(" ", 2);
return new AbstractMap.SimpleEntry<>(new ConfigData(SU.unescapeText(d[0])).deserialize(keyClass, keyTypes),
new ConfigData(SU.unescapeText(d[1])).deserialize(valueClass, valueTypes));
} catch (Throwable e) {
e.printStackTrace();
//SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public ConfigData toData(Object input, Type... parameters) {
try {
Class keyClass = defaultKeyClass;
Class valueClass = defaultValueClass;
Type[] keyTypes = emptyTypeArray;
Type[] valueTypes = emptyTypeArray;
if (parameters.length >= 1) {
if (parameters[0] instanceof ParameterizedType) {
ParameterizedType key = (ParameterizedType) parameters[0];
keyTypes = key.getActualTypeArguments();
keyClass = (Class) key.getRawType();
} else {
keyClass = (Class) parameters[0];
}
}
if (parameters.length >= 2) {
if (parameters[1] instanceof ParameterizedType) {
ParameterizedType value = (ParameterizedType) parameters[1];
valueTypes = value.getActualTypeArguments();
valueClass = (Class) value.getRawType();
} else {
valueClass = (Class) parameters[1];
}
}
Map.Entry<Object, Object> e = (Entry<Object, Object>) input;
Object key = e.getKey();
Object value = e.getValue();
return new ConfigData(
SU.escapeText(serializeObject(key, includeClassName(key.getClass(), keyClass), keyTypes).toString()) + " " +
SU.escapeText(serializeObject(value, includeClassName(value.getClass(), valueClass), valueTypes)
.toString()));
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
}
public static class NumberSerializer implements Serializer {
public static final HashMap<Class, Method> methods = new HashMap();
static {
try {
methods.put(Short.class, Short.class.getMethod("decode", String.class));
methods.put(Integer.class, Integer.class.getMethod("decode", String.class));
methods.put(Long.class, Long.class.getMethod("decode", String.class));
methods.put(Float.class, Float.class.getMethod("valueOf", String.class));
methods.put(Double.class, Double.class.getMethod("valueOf", String.class));
methods.put(Byte.class, Byte.class.getMethod("valueOf", String.class));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public Object fromData(ConfigData input, Class fixClass, Type... parameters) {
Method m = methods.get(Primitives.wrap(fixClass));
try {
String s = StringUtils.stripStart(input.stringData.replace(" ", ""), "0");
return m.invoke(null, s.isEmpty() ? "0" : s);
} catch (Throwable e) {
debug.msg("Config", "INVALID NUMBER: " + fixClass.getName() + " - " + input);
debug.msg("Config", e);
try {
return m.invoke(null, "0");
} catch (Throwable e2) {
debug.msg("Config", "Not a number class: " + fixClass.getSimpleName());
debug.msg("Config", e);
}
}
return null;
}
public ConfigData toData(Object input, Type... parameters) {
String s = input.toString();
int id = (s + ".").indexOf(".");
return new ConfigData(StringUtils.leftPad(s, Math.max(leftPad + s.length() - id, 0), '0'));
}
}
public static class ObjectSerializer implements Serializer {
public Object fromData(ConfigData input, Class fixClass, Type... parameters) {
if (Thread.currentThread().getStackTrace().length > 100) {
SU.cs.sendMessage("§ePossible infinite loop - " + fixClass.getName());
return null;
}
try {
if (fixClass == Object.class)
return input.stringData;
if (ArrayUtils.contains(fixClass.getInterfaces(), StringSerializable.class) || fixClass == BigDecimal.class || fixClass == BigInteger.class) {
if (input.stringData == null || input.stringData.equals(""))
return null;
return fixClass.getConstructor(String.class).newInstance(input.stringData);
}
if (fixClass.isEnum() || fixClass.getSuperclass() != null && fixClass.getSuperclass().isEnum()) {
if (input.stringData == null || input.stringData.equals(""))
return null;
for (Object en : fixClass.getEnumConstants()) {
if (en.toString().equals(input.stringData))
return en;
}
return null;
}
} catch (Throwable e) {
System.err.println("Error on deserializing \"" + input.stringData + "\" to a " + fixClass.getName() + " object.");
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
Object obj = newInstance(fixClass);
if (input.mapData == null)
return obj;
for (Field f : Reflection.getAllFields(fixClass)) {
f.setAccessible(true);
try {
if (shouldSkip(f.getType()))
continue;
String fn = f.getName();
ConfigData d = input.mapData.get(new ConfigData(fn));
Class cl = Primitives.wrap(f.getType());
if (d != null) {
Type[] types = f.getGenericType() instanceof ParameterizedType ?
((ParameterizedType) f.getGenericType()).getActualTypeArguments() : cl.isArray() ? new Type[]{cl.getComponentType()} : emptyTypeArray;
Object out = d.deserialize(ConfigSerialization.getNotInterfaceClass(cl), types);
if (out instanceof Map) {
Map oldMap = (Map) f.get(obj);
if (oldMap != null) {
oldMap.clear();
oldMap.putAll((Map) out);
continue;
}
} else if (out instanceof Collection) {
Collection oldCol = (Collection) f.get(obj);
if (oldCol != null) {
oldCol.clear();
oldCol.addAll((Collection) out);
}
}
if (out != null)
f.set(obj, out);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
try {
if (obj instanceof PostLoadable)
((PostLoadable) obj).postLoad();
} catch (Throwable e) {
SU.log(Main.pl, "§cError on post loading §e" + fixClass.getName() + "§c object.");
SU.error(SU.cs, e, SU.getPlugin(fixClass).getName(), "gyurix");
}
return obj;
}
public ConfigData toData(Object obj, Type... parameters) {
if (Thread.currentThread().getStackTrace().length > 100) {
SU.cs.sendMessage("§ePossible infinite loop - " + obj.getClass().getName());
return null;
}
Class c = Primitives.wrap(obj.getClass());
if (c.isEnum() || c.getSuperclass() != null && c.getSuperclass().isEnum() || ArrayUtils.contains(c.getInterfaces(), StringSerializable.class) || c == BigDecimal.class || c == BigInteger.class) {
return new ConfigData(obj.toString());
}
ConfigOptions dfOptions = (ConfigOptions) c.getAnnotation(ConfigOptions.class);
String dfValue = dfOptions == null ? "null" : dfOptions.defaultValue();
boolean dfSerialize = dfOptions == null || dfOptions.serialize();
String comment = dfOptions == null ? "" : dfOptions.comment();
ConfigData out = new ConfigData();
if (!comment.isEmpty())
out.comment = comment;
out.mapData = new LinkedHashMap();
for (Field f : Reflection.getAllFields(c)) {
try {
String dffValue = dfValue;
comment = "";
ConfigOptions options = f.getAnnotation(ConfigOptions.class);
if (options != null) {
if (!options.serialize() || Modifier.isTransient(f.getModifiers()))
continue;
dffValue = options.defaultValue();
comment = options.comment();
}
if (!dfSerialize)
continue;
Object o = f.get(obj);
if (o != null && !o.toString().matches(dffValue) && !((o instanceof Iterable) && !((Iterable) o).iterator().hasNext())) {
String cn = "";
if (!(o instanceof Collection) && !(o instanceof Map))
cn = ConfigSerialization.calculateClassName(Primitives.wrap(f.getType()), o.getClass());
Class check = f.getType().isArray() ? f.getType().getComponentType() : f.getType();
if (shouldSkip(check))
continue;
String fn = f.getName();
Type t = f.getGenericType();
debug.msg("Config", "§bSerializing field §e" + f.getName() + "§b of class §e" + c.getName() + "§b having type §e" + o.getClass().getName());
ConfigData value = serializeObject(o, !cn.isEmpty(),
t instanceof ParameterizedType ?
((ParameterizedType) t).getActualTypeArguments() :
((Class) t).isArray() ?
new Type[]{((Class) t).getComponentType()} :
emptyTypeArray);
out.mapData.put(new ConfigData(fn, comment), value);
}
} catch (Throwable e) {
debug.msg("Config", e);
}
}
return out;
}
}
public static class PatternSerializer implements Serializer {
public Object fromData(ConfigData data, Class paramClass, Type... paramVarArgs) {
return Pattern.compile(data.stringData);
}
public ConfigData toData(Object pt, Type... paramVarArgs) {
return new ConfigData(((Pattern) pt).pattern());
}
}
public static class SimpleDateFormatSerializer implements Serializer {
public static final Field patternF = Reflection.getField(SimpleDateFormat.class, "pattern");
public Object fromData(ConfigData input, Class cl, Type... parameters) {
return new SimpleDateFormat(input.stringData);
}
public ConfigData toData(Object input, Type... parameters) {
try {
return new ConfigData((String) patternF.get(input));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return new ConfigData();
}
}
public static class StringSerializer implements Serializer {
public Object fromData(ConfigData input, Class cl, Type... parameters) {
return input.stringData;
}
public ConfigData toData(Object input, Type... parameters) {
return new ConfigData((String) input);
}
}
public static class UUIDSerializer implements Serializer {
public Object fromData(ConfigData input, Class cl, Type... parameters) {
return UUID.fromString(input.stringData);
}
public ConfigData toData(Object input, Type... parameters) {
return new ConfigData(input.toString());
}
}
} | 27,660 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ConfigData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/configfile/ConfigData.java | package gyurix.configfile;
import com.google.common.primitives.Primitives;
import gyurix.configfile.ConfigSerialization.Serializer;
import gyurix.mysql.MySQLDatabase;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import javax.annotation.Nonnull;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import static gyurix.configfile.DefaultSerializers.leftPad;
public class ConfigData implements Comparable<ConfigData> {
public String comment;
public ArrayList<ConfigData> listData;
public LinkedHashMap<ConfigData, ConfigData> mapData;
public Object objectData;
public String stringData;
public Type[] types;
public ConfigData() {
}
public ConfigData(String stringData) {
this.stringData = stringData;
}
public ConfigData(Object obj) {
objectData = obj;
}
public ConfigData(String stringData, String comment) {
this.stringData = stringData;
if (comment != null && !comment.isEmpty())
this.comment = comment;
}
public static String escape(String in) {
StringBuilder out = new StringBuilder();
String escSpace = "\n:>";
char prev = '\n';
for (char c : in.toCharArray()) {
switch (c) {
case ' ':
out.append(escSpace.contains(String.valueOf(prev)) ? "\\" + c : c);
break;
case '‼':
if (prev == '\\')
out.deleteCharAt(out.length() - 1);
out.append('‼');
break;
case '\t':
out.append("\\t");
break;
case '\r':
out.append("\\r");
break;
case '\b':
out.append("\\b");
break;
case '\\':
out.append("\\\\");
break;
default:
out.append(c);
}
prev = c;
}
if (prev == '\n' && out.length() != 0) {
out.setCharAt(out.length() - 1, '\\');
out.append('n');
}
return out.toString();
}
public static ConfigData serializeObject(Object obj, boolean className, Type... parameters) {
if (obj == null)
return null;
Class c = Primitives.wrap(obj.getClass());
if (c.isArray())
parameters = new Type[]{c.getComponentType()};
Serializer s = ConfigSerialization.getSerializer(c);
ConfigData cd = parameters == null ? s.toData(obj) : s.toData(obj, parameters);
if (cd.stringData != null && cd.stringData.startsWith("‼"))
cd.stringData = '\\' + cd.stringData;
if (className && !c.isEnum() && !c.getSuperclass().isEnum()) {
StringBuilder prefix = new StringBuilder('‼' + ConfigSerialization.getAlias(obj.getClass()));
for (Type t : parameters) {
prefix.append('-').append(ConfigSerialization.getAlias((Class) t));
}
prefix.append('‼');
cd.stringData = prefix + (cd.stringData == null ? "" : cd.stringData);
}
return cd;
}
public static ConfigData serializeObject(Object obj, Type... parameters) {
return serializeObject(obj, false, parameters);
}
public static String unescape(String in) {
StringBuilder out = new StringBuilder(in.length());
String uchars = "0123456789abcdef0123456789ABCDEF";
boolean escape = false;
int ucode = -1;
for (char c : in.toCharArray()) {
if (ucode != -1) {
int id = uchars.indexOf(c) % 16;
if (id == -1) {
out.append((char) ucode);
ucode = -1;
} else {
ucode = ucode * 16 + id;
continue;
}
}
if (escape) {
switch (c) {
case 'u':
ucode = 0;
break;
case 'n':
out.append('\n');
break;
case 'r':
out.append('\r');
break;
case 't':
out.append('\t');
break;
case 'b':
out.append('\b');
break;
case ' ':
case '-':
case '>':
case '\\':
out.append(c);
}
escape = false;
} else if (!(escape = c == '\\')) {
out.append(c);
}
}
if (ucode != -1)
out.append((char) ucode);
return out.toString().replaceAll("\n +#", "\n#");
}
@Override
public int compareTo(@Nonnull ConfigData o) {
return toString().compareTo(o.toString());
}
public <T> T deserialize(Class<T> c, Type... types) {
try {
c = Primitives.wrap(c);
this.types = types;
if (objectData != null)
return (T) objectData;
String str = stringData == null ? "" : stringData;
if (str.startsWith("‼")) {
str = str.substring(1);
int id = str.indexOf("‼");
if (id != -1) {
str = str.substring(0, id);
String[] classNames = str.split("-");
c = ConfigSerialization.realClass(classNames[0]);
types = new Type[classNames.length - 1];
for (int i = 1; i < classNames.length; i++) {
types[i - 1] = ConfigSerialization.realClass(classNames[i]);
}
stringData = stringData.substring(id + 2);
Serializer ser = ConfigSerialization.getSerializer(c);
objectData = ser.fromData(this, c, types);
}
} else {
Serializer ser = ConfigSerialization.getSerializer(c);
objectData = ser.fromData(this, c, types);
}
stringData = null;
mapData = null;
listData = null;
return (T) objectData;
} catch (Throwable e) {
SU.log(Main.pl, "§eError on deserializing \"§f" + this + "§e\" to class §f" + c.getName() + "§e.");
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
public ConfigData getUnWrapped() {
if (objectData != null)
return serializeObject(objectData, types);
ConfigData out = new ConfigData(stringData);
if (mapData != null) {
out.mapData = new LinkedHashMap<>();
for (Entry<ConfigData, ConfigData> e : mapData.entrySet())
out.mapData.put(e.getKey().getUnWrapped(), e.getValue().getUnWrapped());
}
if (listData != null) {
out.listData = new ArrayList<>();
for (ConfigData cd : listData)
out.listData.add(cd.getUnWrapped());
}
return out;
}
public int hashCode() {
return stringData == null ? objectData == null ? listData == null ? mapData == null ? 0 :
mapData.hashCode() : listData.hashCode() : objectData.hashCode() : stringData.hashCode();
}
public boolean equals(Object obj) {
return obj instanceof ConfigData && ((ConfigData) obj).stringData.equals(stringData);
}
public String toString() {
StringBuilder out = new StringBuilder();
if (objectData != null)
return getUnWrapped().toString();
if (stringData != null && !stringData.isEmpty())
out.append(escape(stringData));
if (mapData != null && !mapData.isEmpty()) {
for (Entry<ConfigData, ConfigData> d : mapData.entrySet()) {
ConfigData v = d.getValue();
String value = d.getValue().toString();
if (d.getKey().comment != null)
out.append("\n#").append(d.getKey().comment.replace("\n", "\n#"));
if (v.mapData != null)
value = value.replace("\n", "\n ");
if (!value.startsWith("\n") && !value.isEmpty())
value = " " + value;
String key = d.getKey().toString();
out.append('\n');
if (key.contains("\n"))
out.append("> ").append(key).append("\n:").append(value);
else
out.append(key).append(":").append(value);
}
}
if (listData != null && !listData.isEmpty()) {
for (ConfigData d : listData) {
String data = d.toString();
if (d.comment != null)
out.append('\n').append('#').append(d.comment.replace("\n", "\n#"));
out.append('\n').append("- ").append(data.replace("\n", "\n "));
}
}
return out.toString();
}
public boolean isEmpty() {
return (stringData == null || stringData.isEmpty()) && listData == null && mapData == null && objectData == null;
}
public void saveToMySQL(ArrayList<String> l, String dbTable, String args, String key) {
leftPad = 16;
ConfigData cd = objectData == null ? this : serializeObject(objectData, types);
if (cd.mapData != null) {
if (!key.isEmpty())
key += ".";
for (Entry<ConfigData, ConfigData> e : cd.mapData.entrySet()) {
e.getValue().saveToMySQL(l, dbTable, args.replace("<key>", MySQLDatabase.escape(key) + "<key>"), e.getKey().toString());
}
} else {
String value = cd.toString();
if (value != null)
l.add("INSERT INTO `" + dbTable + "` VALUES (" + args.replace("<key>", MySQLDatabase.escape(key)).replace("<value>", MySQLDatabase.escape(value)) + ')');
}
leftPad = 0;
}
public void unWrap() {
if (objectData == null)
return;
ConfigData cd = serializeObject(objectData, types);
objectData = null;
types = null;
listData = cd.listData;
mapData = cd.mapData;
stringData = cd.stringData;
}
public void unWrapAll() {
if (objectData != null) {
unWrap();
return;
}
if (mapData != null)
for (Entry<ConfigData, ConfigData> e : mapData.entrySet()) {
e.getKey().unWrapAll();
e.getValue().unWrapAll();
}
if (listData != null)
for (ConfigData cd : listData)
cd.unWrapAll();
}
} | 9,432 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Debugger.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/debug/Debugger.java | package gyurix.debug;
import gyurix.spigotlib.SU;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import java.util.HashSet;
import static gyurix.configfile.ConfigSerialization.ConfigOptions;
import static gyurix.spigotlib.Main.lang;
@Data
public class Debugger {
private HashSet<String> channels;
private HashSet<String> enabledChannels = new HashSet<>();
@ConfigOptions(serialize = false)
private Plugin plugin;
public Debugger() {
}
public Debugger(Plugin pl) {
this.plugin = pl;
}
public String getPluginName() {
return plugin == null ? "Test" : plugin.getName();
}
public void handleCommand(CommandSender sender, String cmd, String[] args) {
if (args.length == 0) {
lang.msg(sender, "debug.list", "channels", StringUtils.join(enabledChannels, ", "));
return;
}
args[0] = Character.toUpperCase(args[0].charAt(0)) + args[0].substring(1).toLowerCase();
if (enabledChannels.remove(args[0])) {
lang.msg(sender, "debug.disabled", "channel", args[0]);
return;
}
enabledChannels.add(args[0]);
lang.msg(sender, "debug.enabled", "channel", args[0]);
}
public boolean isEnabled(String channel) {
return enabledChannels.contains(channel);
}
public void msg(String channel, Throwable e) {
if (enabledChannels.contains(channel))
SU.error(SU.cs, e, getPluginName() + " - " + channel, plugin.getDescription().getMain().replaceFirst("\\..*", ""));
}
public void msg(String channel, Object msg) {
if (enabledChannels.contains(channel))
SU.cs.sendMessage("§a[" + getPluginName() + " - DEBUG - " + channel + "]§f " + msg);
}
}
| 1,735 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Command.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/Command.java | package gyurix.commands;
import gyurix.api.BungeeAPI;
import gyurix.api.TitleAPI;
import gyurix.api.VariableAPI;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.economy.EconomyAPI;
import gyurix.spigotlib.ChatAPI;
import gyurix.spigotlib.ChatAPI.ChatMessageType;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.ItemUtils;
import org.bukkit.*;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.*;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import static gyurix.api.BungeeAPI.executeBungeeCommands;
import static gyurix.api.BungeeAPI.executeServerCommands;
public class Command implements StringSerializable {
public static HashMap<String, CustomCommandHandler> customCommands = new HashMap();
static {
customCommands.put("ABM", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
ChatAPI.sendJsonMsg(ChatMessageType.ACTION_BAR, text, plr);
} else {
cs.sendMessage("§cABM:§f " + text);
}
return true;
});
customCommands.put("BUNGEE", (cs, text, args) -> {
if (cs instanceof Entity) {
Entity plr = (Entity) cs;
executeBungeeCommands(new String[]{text}, plr.getName());
}
return true;
});
customCommands.put("CHANCE", (cs, text, args) -> SU.rand.nextDouble() < Double.valueOf(text));
customCommands.put("CLOSEINV", (cs, text, args) -> {
if (cs instanceof Player) {
((Player) cs).closeInventory();
return true;
}
return false;
});
customCommands.put("CONSOLE", (cs, text, args) -> {
SU.srv.dispatchCommand(SU.cs, text);
return true;
});
customCommands.put("DAMAGE", (cs, text, args) -> {
if (cs instanceof LivingEntity) {
LivingEntity plr = (LivingEntity) cs;
plr.damage(Double.valueOf(text));
return true;
}
return false;
});
customCommands.put("ECON", (cs, text, args) -> {
if (cs instanceof Entity) {
Entity plr = (Entity) cs;
String[] data = text.split(" ", 2);
return data.length != 0 && (data.length == 1 ? EconomyAPI.addBalance(plr.getUniqueId(), new BigDecimal(data[0])) :
EconomyAPI.addBalance(plr.getUniqueId(), data[0], new BigDecimal(data[1])));
}
return false;
});
customCommands.put("ECONSET", (cs, text, args) -> {
if (cs instanceof Entity) {
Entity plr = (Entity) cs;
String[] data = text.split(" ", 2);
return data.length != 0 && (data.length == 1 ? EconomyAPI.setBalance(plr.getUniqueId(), new BigDecimal(data[0])) :
EconomyAPI.setBalance(plr.getUniqueId(), data[0], new BigDecimal(data[1])));
}
return false;
});
customCommands.put("EXPLOSION", (cs, text, args) -> {
if (cs instanceof Entity) {
Entity plr = (Entity) cs;
Location loc = plr.getLocation();
plr.getWorld().createExplosion(loc.getX(), loc.getY(), loc.getZ(), Float.valueOf(text), false, false);
}
return false;
});
customCommands.put("FIREWORK", (cs, text, args) -> {
if (cs instanceof Entity) {
Entity plr = (Entity) cs;
Location loc = plr.getLocation();
Firework fw = (Firework) plr.getWorld().spawnEntity(loc, EntityType.FIREWORK);
fw.setFireworkMeta((FireworkMeta) ItemUtils.stringToItemStack(text).getItemMeta());
}
return false;
});
customCommands.put("GNOTE", (cs, text, args) -> {
String[] data = text.split(" ");
Location loc = null;
int firstId = 1;
if (!data[0].equals("*")) {
firstId = 4;
loc = new Location(Bukkit.getWorld(data[0]), Double.valueOf(data[1]), Double.valueOf(data[2]), Double.valueOf(data[3]));
}
int length = data.length;
for (int id = firstId; id < length; id++) {
String[] d = data[id].split(":");
Instrument instrument = Instrument.valueOf(d[0]);
Note note = new Note(Integer.valueOf(d[1]));
for (Player p : loc == null ? Bukkit.getOnlinePlayers() : loc.getWorld().getPlayers())
p.playNote(loc == null ? p.getLocation() : loc, instrument, note);
}
return true;
});
customCommands.put("GPARTICLE", (cs, text, args) -> {
String[] data = text.split(" ");
Location loc = new Location(Bukkit.getWorld(data[0]), Double.valueOf(data[1]), Double.valueOf(data[2]), Double.valueOf(data[3]));
loc.getWorld().playEffect(loc, Effect.valueOf(data[4]), Integer.valueOf(data[5]));
return true;
});
customCommands.put("GSOUND", (cs, text, args) -> {
String[] data = text.split(" ", 7);
if (data.length == 6) {
Location loc = new Location(Bukkit.getWorld(data[0]), Double.valueOf(data[1]), Double.valueOf(data[2]), Double.valueOf(data[3]));
loc.getWorld().playSound(loc, data[4], Float.valueOf(data[5]), Float.valueOf(data[6]));
} else if (data.length == 3) {
Location loc = ((Entity) cs).getLocation();
loc.getWorld().playSound(loc, data[0], Float.valueOf(data[1]), Float.valueOf(data[2]));
}
return true;
});
customCommands.put("HP", (cs, text, args) -> {
if (cs instanceof LivingEntity) {
LivingEntity plr = (LivingEntity) cs;
plr.setHealth(Math.min(Double.valueOf(text), plr.getMaxHealth()));
return true;
}
return false;
});
customCommands.put("FORCE", (cs, text, args) -> {
String[] d = text.split(" ", 2);
if (d.length < 2)
return false;
if (d[0].equalsIgnoreCase("console")) {
Bukkit.dispatchCommand(SU.cs, d[1]);
return true;
}
Player p = Bukkit.getPlayer(d[0]);
if (p == null)
return false;
p.chat(d[1]);
return true;
});
customCommands.put("OPFORCE", (cs, text, args) -> {
String[] d = text.split(" ", 2);
if (d.length < 2)
return false;
if (d[0].equalsIgnoreCase("console")) {
Bukkit.dispatchCommand(SU.cs, d[1]);
return true;
}
Player p = Bukkit.getPlayer(d[0]);
if (p == null)
return false;
boolean was = p.isOp();
p.setOp(true);
p.chat(d[1]);
p.setOp(was);
return true;
});
customCommands.put("KICK", (cs, text, args) -> {
if (cs instanceof Player) {
((Player) cs).kickPlayer(text);
return true;
}
return false;
});
customCommands.put("LOG", (cs, text, args) -> {
SU.cs.sendMessage(text);
return true;
});
customCommands.put("MAXHP", (cs, text, args) -> {
if (cs instanceof LivingEntity) {
LivingEntity plr = (LivingEntity) cs;
plr.setMaxHealth(Double.valueOf(text));
return true;
}
return false;
});
customCommands.put("MSG", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
ChatAPI.sendJsonMsg(ChatMessageType.SYSTEM, text, plr);
} else {
cs.sendMessage(text);
}
return true;
});
customCommands.put("NOCMD", (cs, text, args) -> true);
customCommands.put("NORMAL", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
plr.chat(text);
return true;
}
return false;
});
customCommands.put("NOTE", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
String[] data = text.split(" ");
Location loc = plr.getLocation();
int firstId = 1;
if (!data[0].equals("*")) {
firstId = 4;
loc = new Location(Bukkit.getWorld(data[0]), Double.valueOf(data[1]), Double.valueOf(data[2]), Double.valueOf(data[3]));
}
int length = data.length;
for (int id = firstId; id < length; id++) {
String[] d = data[id].split(":");
Instrument instrument = Instrument.valueOf(d[0]);
Note note = new Note(Integer.valueOf(d[1]));
plr.playNote(loc, instrument, note);
}
return true;
}
return false;
});
customCommands.put("OP", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
boolean wasOp = plr.isOp();
plr.setOp(true);
plr.chat(text);
plr.setOp(wasOp);
return true;
}
return false;
});
customCommands.put("PARTICLE", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
String[] data = text.split(" ");
Location loc = new Location(plr.getWorld(), Double.valueOf(data[0]), Double.valueOf(data[1]), Double.valueOf(data[2]));
plr.playEffect(loc, Effect.valueOf(data[3]), Integer.valueOf(data[4]));
return true;
}
return false;
});
customCommands.put("PERMADD", (cs, text, args) -> cs instanceof Player && SU.perm.playerAdd((Player) cs, text));
customCommands.put("PERMREM", (cs, text, args) -> cs instanceof Player && SU.perm.playerRemove((Player) cs, text));
customCommands.put("POTION", (cs, text, args) -> {
if (cs instanceof LivingEntity) {
LivingEntity ent = (LivingEntity) cs;
ArrayList<PotionEffect> effects = new ArrayList<>();
for (String s : text.split(" ")) {
try {
String[] d = s.split(":");
PotionEffectType type = PotionEffectType.getByName(d[0]);
boolean particles = !(d[d.length - 1].equals("NP") || d[d.length - 2].equals("NP"));
boolean ambient = !(d[d.length - 1].equals("NA") || d[d.length - 2].equals("NA"));
int c = (particles ? 0 : 1) + (ambient ? 0 : 1) + 1;
int duration = Integer.valueOf(d[d.length - c]);
int level = d.length == c + 2 ? 0 : Integer.valueOf(d[1]);
effects.add(new PotionEffect(type, duration, level, ambient, particles));
} catch (Throwable e) {
e.printStackTrace();
}
}
ent.addPotionEffects(effects);
return true;
}
return false;
});
customCommands.put("SEND", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
BungeeAPI.send(text, plr);
return true;
}
return false;
});
customCommands.put("SERVER", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
String[] d = text.split(" ", 2);
String[] servers = d[0].split("[,;]");
executeServerCommands(d[1].split(";"), servers);
}
return true;
});
customCommands.put("SETITEM", (cs, text, args) -> {
if (cs instanceof Player) {
PlayerInventory pi = ((Player) cs).getInventory();
String[] d = text.split(" ", 2);
pi.setItem(Integer.valueOf(d[0]), ItemUtils.stringToItemStack(d[1]));
return true;
}
return false;
});
customCommands.put("SOUND", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
String[] data = text.split(" ", 6);
if (data.length == 6) {
Location loc = new Location(plr.getWorld(), Double.valueOf(data[0]), Double.valueOf(data[1]), Double.valueOf(data[2]));
plr.playSound(loc, data[3], Float.valueOf(data[4]), Float.valueOf(data[5]));
} else if (data.length == 3) {
plr.playSound(plr.getLocation(), data[0], Float.valueOf(data[1]), Float.valueOf(data[2]));
}
return true;
}
return false;
});
customCommands.put("SUBTITLE", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
TitleAPI.setSubTitle(text, plr);
} else {
cs.sendMessage("§bSUBTITLE:§f " + text);
}
return true;
});
customCommands.put("TS", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
String[] times = text.split(" ", 3);
TitleAPI.setShowTime(Integer.valueOf(times[0]), Integer.valueOf(times[1]), Integer.valueOf(times[2]), plr);
return true;
}
return false;
});
customCommands.put("TITLE", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
TitleAPI.setTitle(text, plr);
} else {
cs.sendMessage("§eTITLE:§f " + text);
}
return true;
});
customCommands.put("XPLEVEL", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
plr.setLevel(Integer.valueOf(text));
return true;
}
return false;
});
customCommands.put("XP", (cs, text, args) -> {
if (cs instanceof Player) {
Player plr = (Player) cs;
plr.setExp(Math.max(Math.min(Float.valueOf(text), 1), 0));
return true;
}
return false;
});
}
public String cmd;
public int delay = -1;
public String type = "CONSOLE";
public Command(String in) {
if (in.startsWith("{")) {
int id = in.indexOf('}');
delay = Integer.valueOf(in.substring(1, id));
in = in.substring(id + 1);
}
String[] s = in.split(":", 2);
if (s.length == 1) {
cmd = in;
} else {
cmd = s[1];
type = s[0];
}
}
@Deprecated
public static boolean executeAll(CommandSender sender, ArrayList<Command> list, Object... args) {
return executeAll(sender, (Collection<Command>) list, args);
}
public static boolean executeAll(CommandSender sender, Collection<Command> list, Object... args) {
if (sender == null || list == null)
return false;
for (Command c : list)
if (!c.execute(sender, args))
return false;
return true;
}
@Deprecated
public static boolean executeAll(Iterable<String> plns, ArrayList<Command> list, Object... args) {
return executeAll(plns, (Collection<Command>) list, args);
}
public static boolean executeAll(Iterable<String> plns, Collection<Command> list, Object... args) {
if (plns == null || list == null)
return false;
for (String pln : plns) {
Entity p = Bukkit.getPlayerExact(pln);
if (p == null)
continue;
for (Command c : list)
c.execute(p, args);
}
return true;
}
@Deprecated
public static boolean executeAll(Iterable<? extends Entity> pls, Entity plr, ArrayList<Command> list, Object... args) {
return executeAll(pls, plr, (Collection<Command>) list, args);
}
public static boolean executeAll(Iterable<? extends Entity> pls, Entity plr, Collection<Command> list, Object... args) {
if (list == null || pls == null)
return false;
for (Entity p : pls) {
if (p != plr)
for (Command c : list)
c.execute(p, args);
}
return true;
}
public boolean execute(CommandSender sender, Object... args) {
if (sender == null)
return false;
if (delay < 0)
return executeNow(sender, args);
SU.sch.scheduleSyncDelayedTask(Main.pl, new DelayedCommandExecutor(this, sender, args), delay);
return true;
}
public boolean executeNow(CommandSender sender, Object... args) {
if (sender == null)
return false;
Player plr = sender instanceof Player ? (Player) sender : null;
String text = VariableAPI.fillVariables(cmd, plr, args);
try {
CustomCommandHandler h = customCommands.get(type);
if (h == null) {
sender.sendMessage("§cCommandAPI: §eHandler for command \"§f" + type + "§e\" was not found.");
return false;
}
return h.handle(sender, text, args);
} catch (Throwable e) {
SU.cs.sendMessage("§cCommandAPI: §eError on executing command \"§b" + type + ":§f" + text + "§e\" for sender " + (sender == null ? "null" : sender.getName()) + ".");
SU.error(sender, e, "SpigotLib", "gyurix");
return false;
}
}
@Override
public String toString() {
return (delay > -1 ? "{" + delay + '}' + type : type) + ':' + cmd;
}
}
| 16,324 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CustomCommandMap.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/CustomCommandMap.java | package gyurix.commands;
import gyurix.commands.event.*;
import gyurix.spigotlib.SU;
import org.bukkit.command.Command;
import org.bukkit.command.*;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static gyurix.protocol.Reflection.getField;
import static gyurix.spigotlib.SU.*;
/**
* Created by GyuriX on 2016.08.23..
*/
public class CustomCommandMap extends SimpleCommandMap {
private static final Field cmdMapF1 = getField(srv.getClass(), "commandMap");
private static final Field cmdMapF2 = getField(pm.getClass(), "commandMap");
private static final Field knownCmdsF = getField(SimpleCommandMap.class, "knownCommands");
public static SimpleCommandMap backend;
public static Map<String, Command> knownCommands;
public CustomCommandMap() {
super(srv);
try {
backend = (SimpleCommandMap) cmdMapF1.get(srv);
cmdMapF1.set(srv, this);
cmdMapF2.set(pm, this);
knownCommands = (Map<String, Command>) knownCmdsF.get(backend);
knownCmdsF.set(this, knownCommands);
} catch (Throwable e) {
cs.sendMessage("§2[§aStartup§2]§c Failed to initialize CustomCommandMap :(");
error(cs, e, "SpigotLib", "gyurix");
}
}
public static void unhook() {
try {
cmdMapF1.set(pm, backend);
cmdMapF2.set(srv, backend);
} catch (Throwable e) {
}
}
public void setFallbackCommands() {
backend.setFallbackCommands();
}
@Override
public void registerAll(String fallbackPrefix, List<Command> commands) {
backend.registerAll(fallbackPrefix, commands);
}
@Override
public boolean register(String fallbackPrefix, Command command) {
if (backend == null)
return false;
return backend.register(fallbackPrefix, command);
}
@Override
public boolean register(String label, String fallbackPrefix, Command command) {
return backend.register(label, fallbackPrefix, command);
}
@Override
public boolean dispatch(CommandSender sender, String cmd) throws CommandException {
{
CommandExecuteEvent e = new CommandExecuteEvent(sender, cmd);
pm.callEvent(e);
if (e.isCancelled())
return true;
sender = e.getSender();
cmd = e.getCommand();
}
Command c = knownCommands.get(cmd.split(" ", 2)[0].toLowerCase());
try {
boolean unknown = !backend.dispatch(sender, cmd);
if (unknown) {
CommandUnknownEvent e = new CommandUnknownEvent(sender, cmd);
pm.callEvent(e);
if (e.isCancelled())
return true;
}
return !unknown;
} catch (CommandException err) {
CommandErrorEvent e = new CommandErrorEvent(sender, cmd, err);
pm.callEvent(e);
if (e.isCancelled())
return true;
boolean out = sender.getName().equalsIgnoreCase("gyurix") || sender.hasPermission("spigotlib.debug");
(out ? sender : SU.cs).sendMessage("§cError on executing command§e /" + cmd);
error((out ? sender : SU.cs), err.getCause(), c instanceof PluginCommand ? ((PluginCommand) c).getPlugin().getName() : "CommandAPI", "gyurix");
return !out;
}
}
@Override
public void clearCommands() {
backend.clearCommands();
}
@Override
public Command getCommand(String name) {
return backend.getCommand(name);
}
@Override
public List<String> tabComplete(CommandSender sender, String cmdLine) throws IllegalArgumentException {
{
PreTabCompleteEvent e = new PreTabCompleteEvent(sender, cmdLine);
pm.callEvent(e);
if (e.isCancelled())
return e.getResult();
}
List<String> list = backend.tabComplete(sender, cmdLine);
PostTabCompleteEvent e = new PostTabCompleteEvent(sender, cmdLine, list);
pm.callEvent(e);
if (e.isCancelled())
return e.getResult();
return list;
}
public Collection<Command> getCommands() {
return Collections.unmodifiableCollection(knownCommands.values());
}
public void registerServerAliases() {
backend.registerServerAliases();
}
}
| 4,084 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CustomCommandHandler.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/CustomCommandHandler.java | package gyurix.commands;
import org.bukkit.command.CommandSender;
public interface CustomCommandHandler {
boolean handle(CommandSender cs, String text, Object... args);
}
| 176 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
DelayedCommandExecutor.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/DelayedCommandExecutor.java | package gyurix.commands;
import org.bukkit.command.CommandSender;
/**
* Created by gyurix on 20/12/2015.
*/
public class DelayedCommandExecutor implements Runnable {
private final Object[] args;
private final Command c;
private final CommandSender sender;
public DelayedCommandExecutor(Command c, CommandSender sender, Object[] args) {
this.args = args;
this.sender = sender;
this.c = c;
}
@Override
public void run() {
c.executeNow(sender, args);
}
}
| 490 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
SpigotLibCommands.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/SpigotLibCommands.java | package gyurix.commands;
import gyurix.api.VariableAPI;
import gyurix.configfile.ConfigData;
import gyurix.configfile.ConfigFile;
import gyurix.nbt.NBTCompound;
import gyurix.protocol.utils.ItemStackWrapper;
import gyurix.spigotlib.Config;
import gyurix.spigotlib.GlobalLangFile;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.BackendType;
import gyurix.spigotutils.ItemUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import static com.google.common.collect.Lists.newArrayList;
import static gyurix.spigotlib.Config.PlayerFile.backend;
import static gyurix.spigotlib.Config.PlayerFile.mysql;
import static gyurix.spigotlib.Config.allowAllPermsForAuthor;
import static gyurix.spigotlib.Config.purgePF;
import static gyurix.spigotlib.Main.*;
import static gyurix.spigotlib.SU.*;
public class SpigotLibCommands implements CommandExecutor, TabCompleter {
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
try {
Player plr = sender instanceof Player ? (Player) sender : null;
String cmd = args.length == 0 ? "help" : args[0].toLowerCase();
if (!sender.hasPermission("spigotlib.command." + cmd) && !(allowAllPermsForAuthor && plr != null && plr.getUniqueId().equals(author))) {
lang.msg(sender, "noperm");
return true;
}
ArrayList<Player> pls = plr == null ? newArrayList() : newArrayList(plr);
int stripArg = 1;
if (args.length > 1) {
if (args[1].equals("*")) {
stripArg = 2;
pls = new ArrayList<>(Bukkit.getOnlinePlayers());
} else if (args[1].startsWith("p:")) {
stripArg = 2;
pls.clear();
for (String s : args[1].substring(2).split(",")) {
Player p = getPlayer(s);
if (p == null) {
lang.msg(sender, "player.notfound", "player", p.getName());
continue;
}
pls.add(p);
}
}
}
args = (String[]) ArrayUtils.subarray(args, stripArg, args.length);
String fullMsg = StringUtils.join(args, ' ');
if (fullMsg.contains("<eval:") && plr != null && !Config.playerEval) {
lang.msg(plr, "vars.noeval");
return true;
}
fullMsg = VariableAPI.fillVariables(fullMsg, plr);
switch (cmd) {
case "help":
lang.msg(sender, "help", "version", version);
return true;
case "nbt": {
String nms = new ConfigData(new ItemStackWrapper(plr.getItemInHand()).getNbtData()).toString();
sender.sendMessage(nms);
ItemStackWrapper isw = new ItemStackWrapper(new ConfigFile(nms).data.deserialize(NBTCompound.class));
sender.sendMessage("After load:\n" + new ConfigData(isw));
plr.setItemInHand(isw.toBukkitStack());
return true;
}
case "cmd":
for (Player p : pls) {
for (String s : fullMsg.split(";"))
new gyurix.commands.Command(s).execute(p);
}
return true;
case "vars":
if (args.length == 0)
lang.msg(sender, "vars", "vars", StringUtils.join(new TreeSet<>(VariableAPI.handlers.keySet()), ", "));
else
lang.msg(sender, "vars.filled", "result", fullMsg);
return true;
case "perm":
if (args.length == 0) {
String f = lang.get(plr, "perms.fillformat");
String denyperm = lang.get(plr, "perms.denyformat");
String allowperm = lang.get(plr, "perms.allowformat");
StringBuilder sb = new StringBuilder();
for (Player p : pls) {
p.getEffectivePermissions().forEach((permInfo) -> {
sb.append('\n');
permInfo.getAttachment().getPermissions().forEach((perm, value) ->
sb.append('\n').append(fillVariables(value ? allowperm : denyperm, "perm", perm)));
});
sender.sendMessage(fillVariables(f, "player", p.getName(), "<perms>", sb.toString()));
}
return true;
}
for (Player p : pls)
lang.msg(sender, p.hasPermission(args[0]) ? "perms.yes" : "perms.no", "player", p.getName(), "perm", args[0]);
return true;
case "debug":
Config.debug.handleCommand(sender, "sl", args);
return true;
case "class":
sender.sendMessage("Classes in package " + args[0] + ": " + StringUtils.join(getClasses(args[0]), '\n'));
return true;
case "purge":
lang.msg(sender, "purge.pf");
purgePF = true;
kf.save();
return true;
case "pf":
int page = 1;
boolean pageChange = false;
try {
page = Integer.parseInt(args[args.length - 1]);
pageChange = true;
} catch (Throwable ignored) {
}
if (page < 1)
page = 1;
if (args.length > (pageChange ? 1 : 0)) {
if (args[0].equalsIgnoreCase("console")) {
String[] txt = splitPage(getPlayerConfig((UUID) null).toString(), 10);
if (page > txt.length)
page = txt.length;
sender.sendMessage("§6§lPlayerFileViewer - §e§lCONSOLE§6§l - page §e§l" + page + "§6§l of §e§l" + txt.length + "\n§f" + txt[page - 1]);
return true;
}
Player p = getPlayer(args[0]);
loadPlayerConfig(p.getUniqueId());
String[] txt = splitPage(getPlayerConfig(p.getUniqueId()).toString(), 10);
if (page > txt.length)
page = txt.length;
sender.sendMessage("§6§lPlayerFileViewer - §e§l" + p.getName() + "§6§l - page §e§l" + page + "§6§l of §e§l" + txt.length + "\n§f" + txt[page - 1]);
return true;
}
String[] txt = splitPage(pf.toString(), 10);
if (page > txt.length)
page = txt.length;
sender.sendMessage("§6§lPlayerFileViewer - page " + page + " of " + txt.length + "\n§f" + txt[page - 1]);
return true;
case "reload":
if (args.length == 0) {
lang.msg(sender, "reload");
return true;
}
switch (args[0]) {
case "config":
kf.reload();
kf.data.deserialize(Config.class);
lang.msg(sender, "reload.config");
return true;
case "lf":
GlobalLangFile.unloadLF(lang);
saveResources(pl, "lang.yml");
lang = GlobalLangFile.loadLF("spigotlib", pl.getResource("lang.yml"), pl.getDataFolder() + File.separator + "lang.yml");
lang.msg(sender, "reload.lf");
return true;
case "pf":
if (backend == BackendType.FILE) {
pf.reload();
} else {
pf.data.mapData = new LinkedHashMap<>();
for (Player pl : Bukkit.getOnlinePlayers()) {
unloadPlayerConfig(pl.getUniqueId());
loadPlayerConfig(pl.getUniqueId());
}
unloadPlayerConfig(null);
loadPlayerConfig(null);
}
lang.msg(sender, "reload.pf");
return true;
}
lang.msg(sender, "invalidcmd");
return true;
case "save":
if (args.length == 0) {
lang.msg(sender, "save");
return true;
}
switch (args[0]) {
case "pf": {
if (backend == BackendType.FILE)
pf.save();
else {
for (ConfigData cd : new ArrayList<>(pf.data.mapData.keySet())) {
savePlayerConfig(cd.stringData.length() == 40 ? UUID.fromString(cd.stringData) : null);
}
}
break;
}
case "config": {
kf.save();
break;
}
default: {
lang.msg(sender, "invalidcmd");
return true;
}
}
lang.msg(sender, "save." + args[0]);
return true;
case "vel":
case "velocity":
org.bukkit.util.Vector v = new Vector(Double.parseDouble(args[0]), Double.parseDouble(args[1]), Double.parseDouble(args[2]));
for (Player p : pls) {
p.setVelocity(v);
lang.msg(sender, "velocity.set");
}
return true;
case "world": {
if (args.length == 0) {
lang.msg(sender, "world.list", "worlds", Bukkit.getWorlds().stream().map(World::getName).sorted().collect(Collectors.joining(", ")));
return true;
}
World w = Bukkit.getWorld(args[0]);
if (w == null) {
lang.msg(sender, "world.wrong", "world", args[0]);
return true;
}
for (Player p : pls) {
p.teleport(w.getSpawnLocation());
lang.msg(sender, "world.tp", "world", w.getName());
}
return true;
}
case "migratetodb":
pf.db = mysql;
pf.dbKey = "key";
pf.dbValue = "value";
pf.dbTable = mysql.table;
lang.msg(sender, "migrate.start");
ArrayList<String> l = new ArrayList<>();
l.add("DROP TABLE IF EXISTS " + mysql.table);
l.add("CREATE TABLE `" + mysql.table + "` (`uuid` VARCHAR(40) NOT NULL PRIMARY KEY, `data` MEDIUMTEXT)");
if (pf.data.mapData != null && !pf.data.mapData.isEmpty()) {
StringBuilder sb = new StringBuilder("INSERT INTO `" + mysql.table + "` (`uuid`,`data`) VALUES ");
pf.data.mapData.forEach((key, value) ->
sb.append("('").append(key).append("','").append(StringEscapeUtils.escapeSql(value.toString())).append("'),\n"));
l.add(sb.substring(0, sb.length() - 2));
}
mysql.batch(l, () -> lang.msg(sender, "migrate.end"));
backend = BackendType.MYSQL;
kf.save();
return true;
case "lang":
if (args.length == 0) {
lang.msg(sender, "lang.list", "langs", StringUtils.join(GlobalLangFile.map.keySet(), ", "));
for (Player p : pls) {
String lng = getPlayerConfig(p).getString("lang");
if (lng == null)
lng = Config.defaultLang;
lang.msg(sender, "lang." + (p == sender ? "own" : "other"), "player", sender.getName(), "lang", lng);
}
return true;
}
args[0] = args[0].toLowerCase();
for (Player p : pls) {
getPlayerConfig(p).setString("lang", args[0]);
CommandSender cs = p == null ? SU.cs : p;
lang.msg(sender, "lang.set" + (p == sender ? "" : ".other"), "player", cs.getName(), "lang", args[0]);
}
return true;
case "item":
if (args.length == 0) {
for (Player p : pls)
lang.msg(sender, p == sender ? "item.own" : "item.player", "name", p.getName(), "item", ItemUtils.itemToString(p.getItemInHand()));
return true;
}
boolean give = fullMsg.startsWith("give ");
if (give)
fullMsg = fullMsg.substring(5);
ItemStack is = ItemUtils.stringToItemStack(fullMsg);
fullMsg = ItemUtils.itemToString(is);
if (give)
for (Player p : pls) {
ItemUtils.addItem(p.getInventory(), is, is.getMaxStackSize());
lang.msg(sender, "item.give", "player", p.getName(), "item", fullMsg);
}
else
for (Player p : pls) {
plr.setItemInHand(is);
lang.msg(sender, "item.set", "player", p.getName(), "item", fullMsg);
}
return true;
default:
lang.msg(sender, "help", "version", version);
return true;
}
} catch (Throwable e) {
error(sender, e, "SpigotLib", "gyurix");
}
return true;
}
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
ArrayList<String> out = new ArrayList<>();
if (!sender.hasPermission("spigotlib.use")) {
//lang.msg(sender, "noperm");
return out;
}
if (args.length == 1) {
args[0] = args[0].toLowerCase();
for (String cmd : commands) {
if (!cmd.startsWith(args[0]) || !sender.hasPermission("spigotlib.command." + cmd)) continue;
out.add(cmd);
}
} else if (args.length == 2) {
if (args[0].equals("reload")) {
return filterStart(new String[]{"config", "pf", "lf"}, args[1]);
}
}
return out;
}
}
| 13,308 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Async.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/plugin/Async.java | package gyurix.commands.plugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE})
public @interface Async {
boolean async() default true;
}
| 362 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CustomMatcher.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/plugin/CustomMatcher.java | package gyurix.commands.plugin;
import java.lang.reflect.Type;
public interface CustomMatcher {
Object convert(String arg, Type type);
}
| 141 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Arg.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/plugin/Arg.java | package gyurix.commands.plugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Arg {
String value();
}
| 326 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Aliases.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/plugin/Aliases.java | package gyurix.commands.plugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Aliases {
String[] value();
}
| 309 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ArgRange.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/plugin/ArgRange.java | package gyurix.commands.plugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ArgRange {
String max() default "1000000000";
String min() default "1";
}
| 359 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CommandMatcher.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/plugin/CommandMatcher.java | package gyurix.commands.plugin;
import gyurix.protocol.Primitives;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.ItemUtils;
import lombok.Getter;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.*;
import java.util.*;
import static gyurix.spigotlib.Main.lang;
import static gyurix.spigotlib.Main.pl;
import static java.util.Collections.EMPTY_LIST;
public class CommandMatcher implements Comparable<CommandMatcher> {
private static final String[] noSub = new String[0];
private static HashMap<Class, CustomMatcher> customMatchers = new HashMap<>();
private static HashMap<Class, Integer> parameterWeights = new HashMap<>();
@Getter
private TreeSet<String> aliases = new TreeSet<>();
private boolean async;
private TreeMap<String, CommandMatcher> children = new TreeMap<>();
@Getter
private String command;
private Method executor;
private Object executorOwner;
private TreeSet<CommandMatcher> matchers = new TreeSet<>();
private Parameter[] parameters;
private String pluginName;
private Class senderType;
private String subOf;
public CommandMatcher(String pluginName, String command) {
this.pluginName = pluginName;
this.command = command;
}
public CommandMatcher(String pluginName, String command, String subOf, Object executorOwner, Method executor) {
this.pluginName = pluginName;
this.command = command;
this.subOf = subOf;
this.executorOwner = executorOwner;
this.executor = executor;
Aliases al = executor.getAnnotation(Aliases.class);
if (al != null)
aliases.addAll(Arrays.asList(al.value()));
Async async = executorOwner.getClass().getAnnotation(Async.class);
if (async != null)
this.async = async.async();
Parameter[] pars = executor.getParameters();
for (Parameter p : pars) {
Async as = p.getAnnotation(Async.class);
if (as != null) {
this.async = as.async();
break;
}
as = p.getType().getAnnotation(Async.class);
if (as != null && as.async()) {
this.async = true;
break;
}
}
this.senderType = pars[0].getType();
this.parameters = new Parameter[pars.length - 1];
System.arraycopy(pars, 1, parameters, 0, parameters.length);
}
public static void addCustomMatcher(CustomMatcher m, Class... classes) {
for (Class cl : classes)
customMatchers.put(cl, m);
}
private static Object convert(String arg, Type type) {
Class cl = (Class) (type instanceof ParameterizedType ? ((ParameterizedType) type).getRawType() : type);
cl = Primitives.wrap(cl);
if (cl == String.class)
return arg;
CustomMatcher cm = customMatchers.get(cl);
if (cm != null)
return cm.convert(arg, type);
if (Collection.class.isAssignableFrom(cl)) {
String[] d = arg.split(",");
Type target = ((ParameterizedType) type).getActualTypeArguments()[0];
if (cl == List.class)
cl = ArrayList.class;
if (cl == Set.class)
cl = LinkedHashSet.class;
Collection out = (Collection) Reflection.newInstance(cl);
for (String subArg : d)
out.add(convert(subArg, target));
return out;
} else if (cl.isArray()) {
String[] d = arg.split(",");
int len = d.length;
Class target = cl.getComponentType();
Object out = Array.newInstance(target, len);
for (int i = 0; i < len; ++i)
Array.set(out, i, convert(d[i], target));
return out;
} else if (Map.class.isAssignableFrom(cl)) {
String[] d = arg.split(",");
Type targetKey = ((ParameterizedType) type).getActualTypeArguments()[0];
Type targetValue = ((ParameterizedType) type).getActualTypeArguments()[0];
if (cl == Map.class)
cl = LinkedHashMap.class;
Map out = (Map) Reflection.newInstance(cl);
for (String subArg : d) {
String[] d2 = subArg.split("=", 2);
out.put(convert(d2[0], targetKey), convert(d2[1], targetValue));
}
return out;
}
try {
Method m = cl.getMethod("valueOf", String.class);
try {
if (Number.class.isAssignableFrom(cl)) {
String mults = "kmbtqi";
int mult = mults.indexOf(Character.toLowerCase(arg.charAt(arg.length() - 1)));
if (mult > -1) {
StringBuilder argBuilder = new StringBuilder(arg.replaceAll("[ kKmMbBtTqQiI]", ""));
for (int i = 0; i <= mult; ++i)
argBuilder.append("000");
arg = argBuilder.toString();
}
}
return m.invoke(null, arg);
} catch (Throwable e) {
return m.invoke(null, arg.toUpperCase());
}
} catch (NoSuchMethodException ignored) {
} catch (Throwable e) {
return null;
}
try {
return cl.getConstructor(String.class).newInstance(arg);
} catch (NoSuchMethodException ignored) {
} catch (Throwable e) {
return null;
}
try {
return cl.getMethod("fromString", String.class).invoke(null, arg);
} catch (NoSuchMethodException ignored) {
} catch (Throwable e) {
return null;
}
try {
return cl.getMethod("of", String.class).invoke(null, arg);
} catch (NoSuchMethodException ignored) {
} catch (Throwable e) {
return null;
}
return null;
}
private static String getParameterName(Parameter p) {
Arg a = p.getAnnotation(Arg.class);
if (a != null)
return a.value();
a = p.getType().getAnnotation(Arg.class);
if (a != null)
return a.value();
return p.getType().getSimpleName().toLowerCase();
}
public static void registerCustomMatchers() {
setParameterWeight(9, List.class, Set.class, ArrayList.class, LinkedList.class, HashSet.class, TreeSet.class);
setParameterWeight(8, String.class, StringBuilder.class);
setParameterWeight(7, Float.class, Double.class, Long.class);
setParameterWeight(6, Integer.class);
setParameterWeight(5, Byte.class);
setParameterWeight(4, Boolean.class);
addCustomMatcher((arg, type) -> {
try {
return Bukkit.getPlayer(UUID.fromString(arg));
} catch (Throwable ignored) {
}
return Bukkit.getPlayer(arg);
}, Player.class);
addCustomMatcher((arg, type) -> Bukkit.getWorld(arg), World.class);
addCustomMatcher((arg, type) -> ItemUtils.stringToItemStack(arg), ItemStack.class);
addCustomMatcher((arg, type) -> arg.charAt(0), Character.class);
addCustomMatcher((arg, type) -> arg.equalsIgnoreCase("on") ||
arg.equalsIgnoreCase("true") ||
arg.equalsIgnoreCase("enable") ||
arg.equalsIgnoreCase("yes") ||
arg.equalsIgnoreCase("y") ||
arg.equalsIgnoreCase(""), boolean.class, Boolean.class);
}
public static void removeCustomMatcher(Class... classes) {
for (Class cl : classes)
customMatchers.remove(cl);
}
public static void setParameterWeight(int weight, Class... classes) {
for (Class cl : classes)
parameterWeights.put(cl, weight);
}
public void addMatcher(CommandMatcher cm) {
matchers.add(cm);
}
public boolean checkParameters(CommandSender sender, String[] args) {
if (args.length > 0) {
CommandMatcher child = children.get(args[0].toLowerCase());
if (child != null)
return child.checkParameters(sender, subArgs(args));
}
for (CommandMatcher m : matchers)
if (m.checkParameters(sender, args))
return true;
if (executor == null)
return false;
if (!senderMatch(sender))
return false;
if (args.length < parameters.length)
return false;
String[] usedArgs = new String[parameters.length];
if (parameters.length > 0) {
if (args.length > parameters.length) {
System.arraycopy(args, 0, usedArgs, 0, parameters.length - 1);
usedArgs[parameters.length - 1] = StringUtils.join(args, ' ', parameters.length - 1, args.length);
} else
System.arraycopy(args, 0, usedArgs, 0, parameters.length);
}
for (int id = 0; id < parameters.length; ++id) {
Object res = convert(usedArgs[id], parameters[id].getParameterizedType());
if (res == null)
return false;
ArgRange as = parameters[id].getAnnotation(ArgRange.class);
if (as != null) {
Comparable min = (Comparable) convert(as.min(), parameters[id].getParameterizedType());
Comparable max = (Comparable) convert(as.max(), parameters[id].getParameterizedType());
return min.compareTo(res) <= 0 && max.compareTo(res) >= 0;
}
}
return true;
}
@Override
public int compareTo(CommandMatcher o) {
int parL = -Integer.compare(parameters.length, o.parameters.length);
if (parL != 0)
return parL;
return Long.compare(getParameterWeight(), o.getParameterWeight());
}
public void execute(CommandSender sender, String[] args) {
if (args.length > 0) {
CommandMatcher m = children.get(args[0].toLowerCase());
if (m != null) {
m.execute(sender, subArgs(args));
return;
}
}
for (CommandMatcher m : matchers) {
if (m.checkParameters(sender, args)) {
m.execute(sender, args);
return;
}
}
if (executor == null)
return;
if (!senderType.isAssignableFrom(sender.getClass())) {
lang.msg("", sender, "command.noconsole");
return;
}
if (async)
executeNow(sender, args);
SU.sch.scheduleSyncDelayedTask(pl, () -> executeNow(sender, args));
}
private void executeNow(CommandSender sender, String[] args) {
Object[] out = new Object[parameters.length + 1];
out[0] = sender;
if (parameters.length > 0 && args.length > parameters.length)
args[parameters.length - 1] = StringUtils.join(args, ' ', parameters.length - 1, args.length);
System.arraycopy(args, 0, out, 1, parameters.length);
for (int i = 0; i < parameters.length; ++i) {
Object res = convert(args[i], parameters[i].getParameterizedType());
if (res == null) {
lang.msg("", sender, "command.wrongarg", "type", getParameterName(parameters[i]), "value", args[i]);
return;
}
ArgRange as = parameters[i].getAnnotation(ArgRange.class);
if (as != null) {
Comparable min = (Comparable) convert(as.min(), parameters[i].getParameterizedType());
Comparable max = (Comparable) convert(as.max(), parameters[i].getParameterizedType());
if (min.compareTo(res) > 0) {
lang.msg("", sender, "command.toolow", "type", getParameterName(parameters[i]), "value", min);
return;
}
if (max.compareTo(res) < 0) {
lang.msg("", sender, "command.toohigh", "type", getParameterName(parameters[i]), "value", max);
return;
}
}
out[i + 1] = res;
}
try {
executor.invoke(executorOwner, out);
} catch (Throwable e) {
SU.log(pl, executorOwner, StringUtils.join(out, ", "));
for (int i = 0; i < out.length; ++i) {
SU.log(pl, "should", executor.getParameterTypes()[i]);
SU.log(pl, "is", i, out[i].getClass().getSimpleName());
}
SU.error(sender, e.getCause() == null ? e : e.getCause(), pluginName, "gyurix");
}
}
public CommandMatcher getOrAddChild(String pluginName, String command) {
return children.computeIfAbsent(command, (cmd) -> new CommandMatcher(pluginName, command));
}
private long getParameterWeight() {
long weight = 0;
for (Parameter p : parameters)
weight = weight * 10 + parameterWeights.getOrDefault(Primitives.wrap(p.getType()), 0);
return weight;
}
public List<String> getUsage(CommandSender sender, String[] args) {
StringBuilder prefixBuilder = new StringBuilder(
subOf == null ? "§a/" + command : "§a/" + subOf + " §a<" + command);
for (String s : getAliases())
prefixBuilder.append('|').append(s);
if (subOf != null)
prefixBuilder.append('>');
String prefix = prefixBuilder.toString();
List<String> out = new ArrayList<>();
if (!children.isEmpty()) {
String[] sub = subArgs(args);
if (args.length > 0) {
CommandMatcher c = children.get(args[0].toLowerCase());
if (c != null) {
for (String s : c.getUsage(sender, sub))
out.add(prefix + " " + s.substring(3));
return out;
}
}
for (CommandMatcher cm : new LinkedHashSet<>(children.values())) {
for (String s : cm.getUsage(sender, sub))
out.add(prefix + " §6" + s.substring(3).replaceFirst("§6", "§e"));
}
}
for (CommandMatcher cm : matchers)
out.addAll(cm.getUsage(sender, args));
if (executor != null)
out.add(getUsageOfThis(prefix, sender, args));
return out;
}
private String getUsageOfThis(String prefix, CommandSender sender, String[] args) {
StringBuilder sb = new StringBuilder(prefix);
int i = 0;
for (Parameter p : parameters) {
if (args.length == i)
sb.append(" §6<");
else if (args.length < i)
sb.append(" §e<");
else if (isValidParameter(sender, args, i))
sb.append(" §a<");
else
sb.append(" §4<");
sb.append(getParameterName(p)).append('>');
++i;
}
return sb.toString();
}
public boolean isValidParameter(CommandSender sender, String[] args, int id) {
if (args.length > 0) {
CommandMatcher child = children.get(args[0].toLowerCase());
if (child != null)
return child.isValidParameter(sender, subArgs(args), id - 1);
}
if (executor == null)
return false;
if (!senderMatch(sender))
return false;
if (parameters.length > 0 && args.length > parameters.length)
args[parameters.length - 1] = StringUtils.join(args, ' ', parameters.length - 1, args.length);
Object res = convert(args[id], parameters[id].getParameterizedType());
if (res == null)
return false;
ArgRange as = parameters[id].getAnnotation(ArgRange.class);
if (as != null) {
Comparable min = (Comparable) convert(as.min(), parameters[id].getParameterizedType());
Comparable max = (Comparable) convert(as.min(), parameters[id].getParameterizedType());
return min.compareTo(res) <= 0 && max.compareTo(res) >= 0;
}
return true;
}
public boolean senderMatch(CommandSender sender) {
return senderType.isAssignableFrom(sender.getClass());
}
private String[] subArgs(String[] args) {
if (args.length < 2)
return noSub;
String[] out = new String[args.length - 1];
System.arraycopy(args, 1, out, 0, out.length);
return out;
}
public List<String> tabComplete(CommandSender sender, String[] args) {
if (args.length == 1)
return SU.filterStart(children.keySet(), args[0]);
return EMPTY_LIST;
}
} | 15,028 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
PluginCommands.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/plugin/PluginCommands.java | package gyurix.commands.plugin;
import gyurix.spigotlib.SU;
import lombok.SneakyThrows;
import org.bukkit.command.*;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
import static gyurix.spigotlib.Main.lang;
import static gyurix.spigotlib.SU.error;
import static gyurix.spigotlib.SU.sch;
import static java.util.Collections.EMPTY_LIST;
public class PluginCommands {
private static final String[] emptyStringArray = new String[0];
public PluginCommands(JavaPlugin pl, Object executor) {
String pln = pl.getDescription().getName();
HashMap<String, CommandMatcher> executors = new HashMap<>();
SubOf subOfAnnotation = executor.getClass().getAnnotation(SubOf.class);
String subOf = subOfAnnotation == null ? null : subOfAnnotation.value();
String permPrefix = subOf == null || !subOfAnnotation.permPrefix() ? "" : subOf + ".";
for (Method m : executor.getClass().getMethods()) {
String mn = m.getName();
if (!mn.startsWith("cmd"))
continue;
String[] cmd = mn.substring(3).toLowerCase().split("_");
CommandMatcher cm = executors.computeIfAbsent(cmd[0], (s) -> new CommandMatcher(pln, cmd[0]));
if (cmd.length == 1) {
cm.addMatcher(new CommandMatcher(pln, cmd[0], subOf, executor, m));
continue;
}
CommandMatcher cur = cm;
for (int i = 1; i < cmd.length; ++i) {
cur = cur.getOrAddChild(pln, cmd[i]);
}
cur.addMatcher(new CommandMatcher(pln, cmd[cmd.length - 1], null, executor, m));
}
if (subOf == null) {
executors.forEach((cmd, exec) -> {
PluginCommand pcmd = pl.getCommand(cmd);
if (pcmd == null) {
error(SU.cs, new Exception("Command " + cmd + " should be added to plugin.yml."), pln, pl.getDescription().getMain());
return;
}
ExtendedCommandExecutor ece = register(pl, cmd, exec, permPrefix);
pcmd.setExecutor(ece);
pcmd.setTabCompleter(ece);
});
return;
}
HashMap<String, ExtendedCommandExecutor> mapping = new HashMap<>();
executors.forEach((cmd, exec) -> {
ExtendedCommandExecutor ee = register(pl, cmd, exec, permPrefix);
mapping.put(cmd, ee);
for (String a : ee.getAliases())
mapping.put(a, ee);
});
PluginCommand pc = pl.getCommand(subOf);
if (pc == null) {
error(SU.cs, new Exception("Command " + subOf + " should be added to plugin.yml."), pln, pl.getDescription().getMain());
return;
}
pc.setExecutor((sender, command, s, args) -> {
String sub = args.length == 0 ? "" : args[0].toLowerCase();
ExtendedCommandExecutor exec = mapping.get(sub);
if (args.length == 0 && exec == null)
exec = mapping.get("help");
if (exec == null) {
lang.msg("", sender, "command.wrongsub");
return true;
}
String[] subArgs = args.length < 2 ? emptyStringArray : new String[args.length - 1];
if (args.length > 1)
System.arraycopy(args, 1, subArgs, 0, subArgs.length);
exec.onCommand(sender, command, s, subArgs);
return true;
});
pc.setTabCompleter((sender, command, s, args) -> {
ArrayList<String> out = new ArrayList<>();
if (args.length == 1) {
for (String sub : mapping.keySet()) {
if (sender.hasPermission(pln.toLowerCase() + ".command." + sub))
out.add(sub);
}
return SU.filterStart(out, args[0]);
}
String sub = args[0].toLowerCase();
if (!sender.hasPermission(pln.toLowerCase() + ".command." + sub))
return EMPTY_LIST;
ExtendedCommandExecutor exec = mapping.get(sub);
if (exec == null)
return EMPTY_LIST;
String[] subArgs = args.length < 2 ? emptyStringArray : new String[args.length - 1];
if (args.length > 1)
System.arraycopy(args, 1, subArgs, 0, subArgs.length);
return exec.onTabComplete(sender, command, s, subArgs);
});
}
private ExtendedCommandExecutor register(JavaPlugin pl, String cmd, CommandMatcher m, String permPrefix) {
TreeSet<String> al = m.getAliases();
String permission = pl.getName().toLowerCase() + ".command." + permPrefix + cmd;
return new ExtendedCommandExecutor() {
public void executeNow(CommandSender sender, String[] args) {
try {
if (m.checkParameters(sender, args)) {
m.execute(sender, args);
return;
}
lang.msg("", sender, "command.usage");
for (String s : new TreeSet<>(m.getUsage(sender, args)))
sender.sendMessage(s);
} catch (Throwable e) {
error(sender, e, "SpigotLib", "gyurix");
}
}
@Override
public TreeSet<String> getAliases() {
return al;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] args) {
if (!sender.hasPermission(permission)) {
lang.msg("", sender, "command.noperm");
return true;
}
sch.runTaskAsynchronously(pl, () -> executeNow(sender, args));
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String s, String[] args) {
return m.tabComplete(sender, args);
}
};
}
private interface ExtendedCommandExecutor extends CommandExecutor, TabCompleter {
TreeSet<String> getAliases();
}
@SneakyThrows
public static void registerCommands(JavaPlugin pl, Class... classes) {
for (Class c : classes) {
new PluginCommands(pl, c.newInstance());
}
}
}
| 5,723 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
SubOf.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/plugin/SubOf.java | package gyurix.commands.plugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SubOf {
String value();
boolean permPrefix() default false;
}
| 342 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
PreTabCompleteEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/event/PreTabCompleteEvent.java | package gyurix.commands.event;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
import java.util.ArrayList;
import java.util.List;
public class PreTabCompleteEvent extends CommandEvent {
private static final HandlerList hl = new HandlerList();
private List<String> result = new ArrayList<>();
public PreTabCompleteEvent(CommandSender sender, String command) {
super(sender, command);
}
public static HandlerList getHandlerList() {
return hl;
}
@Override
public HandlerList getHandlers() {
return hl;
}
public List<String> getResult() {
return result;
}
public void setResult(List<String> result) {
this.result = result;
}
}
| 709 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CommandErrorEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/event/CommandErrorEvent.java | package gyurix.commands.event;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
public class CommandErrorEvent extends CommandEvent {
private static final HandlerList hl = new HandlerList();
private final Throwable error;
public CommandErrorEvent(CommandSender sender, String command, Throwable error) {
super(sender, command);
this.error = error;
}
public static HandlerList getHandlerList() {
return hl;
}
public Throwable getError() {
return error;
}
@Override
public HandlerList getHandlers() {
return hl;
}
}
| 592 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CommandEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/event/CommandEvent.java | package gyurix.commands.event;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
public abstract class CommandEvent extends Event implements Cancellable {
private boolean cancel;
private String command;
private CommandSender sender;
public CommandEvent(CommandSender sender, String command) {
this.sender = sender;
this.command = command;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public CommandSender getSender() {
return sender;
}
public void setSender(CommandSender sender) {
this.sender = sender;
}
@Override
public boolean isCancelled() {
return cancel;
}
@Override
public void setCancelled(boolean cancel) {
this.cancel = cancel;
}
}
| 854 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CommandUnknownEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/event/CommandUnknownEvent.java | package gyurix.commands.event;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
public class CommandUnknownEvent extends CommandEvent {
private static final HandlerList hl = new HandlerList();
public CommandUnknownEvent(CommandSender sender, String command) {
super(sender, command);
}
public static HandlerList getHandlerList() {
return hl;
}
@Override
public HandlerList getHandlers() {
return hl;
}
}
| 467 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
PostTabCompleteEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/event/PostTabCompleteEvent.java | package gyurix.commands.event;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
import java.util.List;
public class PostTabCompleteEvent extends CommandEvent {
private static final HandlerList hl = new HandlerList();
private List<String> result;
public PostTabCompleteEvent(CommandSender sender, String command, List<String> result) {
super(sender, command);
this.result = result;
}
public static HandlerList getHandlerList() {
return hl;
}
@Override
public HandlerList getHandlers() {
return hl;
}
public List<String> getResult() {
return result;
}
public void setResult(List<String> result) {
this.result = result;
}
}
| 710 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CommandExecuteEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/commands/event/CommandExecuteEvent.java | package gyurix.commands.event;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
public class CommandExecuteEvent extends CommandEvent {
private static final HandlerList hl = new HandlerList();
public CommandExecuteEvent(CommandSender sender, String command) {
super(sender, command);
}
public static HandlerList getHandlerList() {
return hl;
}
@Override
public HandlerList getHandlers() {
return hl;
}
}
| 467 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Protocol.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/Protocol.java | package gyurix.protocol;
import com.google.common.collect.Lists;
import gyurix.protocol.event.PacketInEvent;
import gyurix.protocol.event.PacketInType;
import gyurix.protocol.event.PacketOutEvent;
import gyurix.protocol.event.PacketOutType;
import gyurix.spigotlib.SU;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public abstract class Protocol implements Listener {
private static final HashMap<PacketInListener, PacketInType> inListenerTypes = new HashMap<>();
private static final HashMap<PacketInType, ArrayList<PacketInListener>> inListeners = new HashMap<>();
private static final HashMap<PacketOutListener, PacketOutType> outListenerTypes = new HashMap<>();
private static final HashMap<PacketOutType, ArrayList<PacketOutListener>> outListeners = new HashMap<>();
private static final String pa = "§5[§dPacketAPI§5] §e";
private static final HashMap<Plugin, ArrayList<PacketInListener>> pluginInListeners = new HashMap<>();
private static final HashMap<Plugin, ArrayList<PacketOutListener>> pluginOutListeners = new HashMap<>();
private static final HashSet<String> missingInPackets = new HashSet<>();
private static final HashSet<String> missingOutPackets = new HashSet<>();
/**
* Dispatches an incoming packet event
*
* @param event - The packet event
*/
public static void dispatchPacketInEvent(PacketInEvent event) {
if (event.getType() == null) {
String name = event.getPacket().getClass().getName();
if (missingInPackets.add(name))
SU.cs.sendMessage(pa + "Missing in packet type:§c " + name + "§e.");
return;
}
ArrayList<PacketInListener> ll = inListeners.get(event.getType());
if (ll != null)
for (PacketInListener l : new ArrayList<>(ll)) {
try {
l.onPacketIN(event);
} catch (Throwable e) {
SU.cs.sendMessage(pa + "Error on dispatching PacketInEvent for packet type:§c " + event.getType() + "§e in listener §c" + l.getClass().getName() + "§e:");
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
}
/**
* Dispatches an outgoing packet event
*
* @param event - The packet event
*/
public static void dispatchPacketOutEvent(PacketOutEvent event) {
if (event.getType() == null) {
String name = event.getPacket().getClass().getName();
if (missingOutPackets.add(name))
SU.cs.sendMessage(pa + "Missing out packet type:§c " + name + "§e.");
return;
}
ArrayList<PacketOutListener> ll = outListeners.get(event.getType());
if (ll != null)
for (PacketOutListener l : new ArrayList<>(ll)) {
try {
l.onPacketOUT(event);
} catch (Throwable e) {
SU.cs.sendMessage(pa + "Error on dispatching PacketOutEvent for packet type:§c " + event.getType() + "§e in listener §c" + l.getClass().getName() + "§e:");
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
}
/**
* Closes the PacketAPI
*/
public void close() throws Throwable {
HandlerList.unregisterAll(this);
unregisterServerChannelHandler();
SU.srv.getOnlinePlayers().forEach(this::uninjectPlayer);
}
/**
* Returns the channel of a Player
*
* @param plr - The target Player
* @return The channel of the target Player
*/
public abstract Object getChannel(Player plr);
/**
* Returns the Player belonging to the given channel
*
* @param channel - The target Player
* @return The Player for who is the given channel belongs to, or null if the Channel and the Player object is not yet matched.
*/
public abstract Player getPlayer(Object channel);
/**
* Initializes the PacketAPI
*
* @throws Throwable if something failed in the initialization
*/
public abstract void init() throws Throwable;
public abstract void injectPlayer(Player plr);
public abstract void printPipeline(Iterable<Map.Entry<String, ?>> pipeline);
/**
* Simulates receiving the given vanilla packet from a player
*
* @param player - The sender player
* @param packet - The sendable packet
*/
public void receivePacket(Player player, Object packet) {
Object channel = getChannel(player);
if (channel == null || packet == null) {
SU.error(SU.cs, new RuntimeException("§cFailed to receive packet " + packet + " from player " + (player == null ? "null" : player.getName())), "SpigotLib", "gyurix");
return;
}
receivePacket(channel, packet);
}
/**
* Simulates receiving the given vanilla packet from a channel
*
* @param channel - The sender players channel
* @param packet - The sendable packet
*/
public abstract void receivePacket(Object channel, Object packet);
/**
* Registers an incoming packet listener
*
* @param plugin - The plugin for which the listener belongs to
* @param listener - The packet listener
* @param packetType - The listenable packet type
*/
public void registerIncomingListener(Plugin plugin, PacketInListener listener, PacketInType packetType) {
if (inListenerTypes.containsKey(listener))
throw new RuntimeException("The given listener is already registered.");
ArrayList<PacketInListener> pil = inListeners.get(packetType);
if (pil == null)
inListeners.put(packetType, Lists.newArrayList(listener));
else
pil.add(listener);
inListenerTypes.put(listener, packetType);
pil = pluginInListeners.get(plugin);
if (pil == null)
pluginInListeners.put(plugin, Lists.newArrayList(listener));
else
pil.add(listener);
}
/**
* Registers an outgoing packet listener
*
* @param plugin - The plugin for which the listener belongs to
* @param listener - The packet listener
* @param packetType - The listenable packet type
*/
public void registerOutgoingListener(Plugin plugin, PacketOutListener listener, PacketOutType packetType) {
if (outListenerTypes.containsKey(listener))
throw new RuntimeException("The given listener is already registered.");
ArrayList<PacketOutListener> pol = outListeners.get(packetType);
if (pol == null)
outListeners.put(packetType, Lists.newArrayList(listener));
else
pol.add(listener);
outListenerTypes.put(listener, packetType);
pol = pluginOutListeners.get(plugin);
if (pol == null)
pluginOutListeners.put(plugin, Lists.newArrayList(listener));
else
pol.add(listener);
}
public abstract void registerServerChannelHook() throws Throwable;
public abstract void removeHandler(Object ch, String handler);
/**
* Sends the given vanilla packet to a player
*
* @param player - The target player
* @param packet - The sendable packet
*/
public void sendPacket(Player player, Object packet) {
if (!player.isOnline())
return;
Object channel = getChannel(player);
if (channel == null || packet == null) {
SU.error(SU.cs, new RuntimeException("§cFailed to send packet " + packet + " to player " + (player == null ? "null" : player.getName())), "SpigotLib", "gyurix");
return;
}
sendPacket(channel, packet);
}
/**
* Sends the given vanilla packet to a channel
*
* @param channel - The target players channel
* @param packet - The sendable packet
*/
public abstract void sendPacket(Object channel, Object packet);
public void uninjectChannel(Object ch) {
removeHandler(ch, "SpigotLibInit");
removeHandler(ch, "SpigotLib");
}
public void uninjectPlayer(Player player) {
uninjectChannel(getChannel(player));
}
/**
* Unregisters ALL the incoming packet listeners of a plugin
*
* @param pl - Target plugin
*/
public void unregisterIncomingListener(Plugin pl) {
ArrayList<PacketInListener> pol = pluginInListeners.remove(pl);
if (pol == null)
return;
for (PacketInListener l : pol)
inListeners.remove(inListenerTypes.remove(l));
}
public void unregisterIncomingListener(PacketInListener listener) {
inListeners.get(inListenerTypes.remove(listener)).remove(listener);
}
public void unregisterOutgoingListener(PacketOutListener listener) {
outListeners.get(outListenerTypes.remove(listener)).remove(listener);
}
/**
* Unregisters ALL the outgoing packet listeners of a plugin
*
* @param pl - Target plugin
*/
public void unregisterOutgoingListener(Plugin pl) {
ArrayList<PacketOutListener> pol = pluginOutListeners.remove(pl);
if (pol == null)
return;
for (PacketOutListener l : pol)
outListeners.remove(outListenerTypes.remove(l));
}
public abstract void unregisterServerChannelHandler() throws IllegalAccessException;
/**
* Interface used for listening to incoming packets
*/
public interface PacketInListener {
void onPacketIN(PacketInEvent e);
}
/**
* Interface used for listening to outgoing packets
*/
public interface PacketOutListener {
void onPacketOUT(PacketOutEvent e);
}
}
| 9,190 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Reflection.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/Reflection.java | package gyurix.protocol;
import com.google.common.primitives.Primitives;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.ServerVersion;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import sun.reflect.ReflectionFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import static gyurix.spigotlib.Config.debug;
import static gyurix.spigotutils.ServerVersion.*;
import static org.apache.commons.lang.ArrayUtils.EMPTY_CLASS_ARRAY;
import static org.apache.commons.lang.ArrayUtils.EMPTY_OBJECT_ARRAY;
@SuppressWarnings("rawtypes")
public class Reflection {
public static final ReflectionFactory rf = ReflectionFactory.getReflectionFactory();
private static final Map<Class, Field[]> allFieldCache = Collections.synchronizedMap(new WeakHashMap<>());
private static final ConcurrentHashMap<String, String> nmsRenames = new ConcurrentHashMap();
/**
* The version of the current server
*/
public static ServerVersion ver = UNKNOWN;
public static String version;
private static Field modifiersField;
static {
try {
modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
} catch (Throwable ignored) {
}
}
/**
* Compares two arrays of classes
*
* @param l1 - The first array of classes
* @param l2 - The second array of classes
* @return True if the classes matches in the 2 arrays, false otherwise
*/
public static boolean classArrayCompare(Class[] l1, Class[] l2) {
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i])
return false;
}
return true;
}
/**
* Compares two arrays of classes
*
* @param l1 - The first array of classes
* @param l2 - The second array of classes
* @return True if each of the second arrays classes is assignable from the first arrays classes
*/
public static boolean classArrayCompareLight(Class[] l1, Class[] l2) {
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (!Primitives.wrap(l2[i]).isAssignableFrom(Primitives.wrap(l1[i])))
return false;
}
return true;
}
public static <T> T convert(Object in, Class<T> to) {
if (in == null)
return null;
System.out.println("Convert - " + in + "(" + in.getClass().getName() + ") to " + to.getName());
to = Primitives.wrap(to);
String inS = in.getClass().isEnum() ? ((Enum) in).name() : in.toString();
try {
Constructor<T> con = to.getConstructor(String.class);
con.setAccessible(true);
return con.newInstance(inS);
} catch (Throwable ignored) {
}
try {
Method m = to.getMethod("valueOf", String.class);
m.setAccessible(true);
return (T) m.invoke(null, inS);
} catch (Throwable ignored) {
}
try {
Method m = to.getMethod("fromString", String.class);
m.setAccessible(true);
return (T) m.invoke(null, inS);
} catch (Throwable ignored) {
}
debug.msg("Reflection", "§cFailed to convert §f" + in + "§e(§f" + in.getClass().getName() + "§e)§c to class §f" + to.getName() + "§c.");
return null;
}
public static Field[] getAllFields(Class c) {
Field[] fs = allFieldCache.get(c);
if (fs != null)
return fs;
ArrayList<Field> out = new ArrayList<>();
while (c != null) {
ConfigOptions co = (ConfigOptions) c.getAnnotation(ConfigOptions.class);
if (co == null || co.serialize())
for (Field f : c.getDeclaredFields()) {
ConfigOptions co2 = f.getAnnotation(ConfigOptions.class);
if (!f.getName().contains("$") && (co2 == null || co2.serialize()))
out.add(setFieldAccessible(f));
}
c = c.getSuperclass();
}
Field[] oa = new Field[out.size()];
out.toArray(oa);
allFieldCache.put(c, oa);
return oa;
}
/**
* Gets a class or an inner class
*
* @param className - The name of the gettable class
* @return The found class or null if it was not found.
*/
public static Class getClass(String className) {
try {
String[] classNames = className.split("\\$");
Class c = Class.forName(classNames[0]);
for (int i = 1; i < classNames.length; i++)
c = getInnerClass(c, classNames[i]);
return c;
} catch (Throwable ignored) {
}
debug.msg("Reflection", new Throwable("Class §f" + className + "§e was not found."));
return null;
}
/**
* Gets the constructor of the given class
*
* @param cl - The class
* @param classes - The parameters of the constructor
* @return The found constructor or null if it was not found.
*/
public static Constructor getConstructor(Class cl, Class... classes) {
try {
Constructor c = cl.getDeclaredConstructor(classes);
c.setAccessible(true);
return c;
} catch (Throwable e) {
debug.msg("Reflection", e);
}
return null;
}
public static Object getData(Object obj, List<Object> data) {
try {
Class ocl = obj.getClass();
Object[] input = EMPTY_OBJECT_ARRAY;
Class[] classes = EMPTY_CLASS_ARRAY;
for (Object o : data) {
Class cl = o.getClass();
if (cl.isArray()) {
input = (Object[]) o;
classes = new Class[input.length];
for (int i = 0; i < input.length; i++)
classes[i] = input[i].getClass();
continue;
}
for (String name : String.valueOf(o).split("\\.")) {
if (input.length == 0) {
Field f = getField(ocl, name);
if (f != null) {
obj = f.get(obj);
ocl = obj.getClass();
continue;
}
}
Method m = getSimiliarMethod(ocl, name, classes);
Class[] parCls = m.getParameterTypes();
Object[] pars = new Object[parCls.length];
for (int i = 0; i < parCls.length; i++) {
pars[i] = convert(input[i], parCls[i]);
}
obj = m.invoke(obj, pars);
if (obj == null) {
throw new RuntimeException("Null return value of method call (method " + m.getName() + ", entered parameters: " + StringUtils.join(pars, ", ") + ".");
}
ocl = obj.getClass();
input = EMPTY_OBJECT_ARRAY;
classes = EMPTY_CLASS_ARRAY;
}
}
} catch (Throwable e) {
debug.msg("Reflection", "§cFailed to handle §f" + StringUtils.join(data, "§f.") + "§c request.");
debug.msg("Reflection", e);
return null;
}
return obj;
}
public static Object getEnum(Class enumType, String value) {
try {
return enumType.getMethod("valueOf", String.class).invoke(null, value);
} catch (Throwable e) {
debug.msg("Reflection", e);
return null;
}
}
public static Field getField(Class clazz, String name) {
Field f = null;
while (clazz != null) {
try {
return setFieldAccessible(clazz.getDeclaredField(name));
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
}
return null;
}
public static Object getFieldData(Class clazz, String name) {
return getFieldData(clazz, name, null);
}
public static Object getFieldData(Class clazz, String name, Object object) {
try {
return setFieldAccessible(clazz.getDeclaredField(name)).get(object);
} catch (Throwable e) {
debug.msg("Reflection", e);
return null;
}
}
public static Field getFirstFieldOfType(Class clazz, Class type) {
try {
for (Field f : clazz.getDeclaredFields()) {
if (f.getType().equals(type))
return setFieldAccessible(f);
}
for (Field f : clazz.getDeclaredFields())
if (type.isAssignableFrom(f.getType()))
return setFieldAccessible(f);
} catch (Throwable e) {
debug.msg("Reflection", e);
}
return null;
}
public static Class getInnerClass(Class cl, String name) {
try {
name = cl.getName() + "$" + name;
for (Class c : cl.getDeclaredClasses())
if (c.getName().equals(name))
return c;
} catch (Throwable e) {
debug.msg("Reflection", e);
}
return null;
}
public static Field getLastFieldOfType(Class clazz, Class type) {
Field field = null;
for (Field f : clazz.getDeclaredFields()) {
if (f.getType().equals(type))
field = f;
}
if (field == null) {
for (Field f : clazz.getDeclaredFields())
if (type.isAssignableFrom(f.getType()))
field = f;
}
return setFieldAccessible(field);
}
public static Method getMethod(Class cl, String name, Class... args) {
if (cl == null || name == null || ArrayUtils.contains(args, null))
return null;
String originalClassName = cl.getName();
if (args.length == 0) {
while (cl != null) {
Method m = methodCheckNoArg(cl, name);
if (m != null) {
m.setAccessible(true);
return m;
}
cl = cl.getSuperclass();
}
debug.msg("Reflection", "Method §f" + name + "§e with no parameters was not found in class §f" + originalClassName + "§e.");
} else {
while (cl != null) {
Method m = methodCheck(cl, name, args);
if (m != null) {
m.setAccessible(true);
return m;
}
cl = cl.getSuperclass();
}
StringBuilder sb = new StringBuilder();
for (Class c : args)
sb.append(", ").append(c.getName());
debug.msg("Reflection", "Method §f" + name + "§e with parameters §f" + sb.substring(2) + "§e was not found in class §f" + originalClassName + "§e.");
}
return null;
}
public static Class getNMSClass(String className) {
String newName = nmsRenames.get(className);
if (newName != null) {
className = newName;
if (className.contains("."))
return getClass(className);
}
return getClass("net.minecraft.server." + version + className);
}
public static Class getOBCClass(String className) {
return getClass("org.bukkit.craftbukkit." + version + className);
}
public static Method getSimiliarMethod(Class ocl, String name, Class[] classes) {
Method m = getMethod(ocl, name, classes);
if (m == null) {
m = getMethod(ocl, "get" + name, classes);
if (m == null)
m = getMethod(ocl, "is" + name, classes);
}
if (m != null)
return m;
name = name.toLowerCase();
Class origCl = ocl;
while (ocl != null) {
for (Method m2 : ocl.getDeclaredMethods()) {
if (m2.getParameterTypes().length != classes.length)
continue;
String mn = m2.getName().toLowerCase();
if (mn.endsWith(name) && (mn.startsWith(name) || mn.startsWith("get") || mn.startsWith("is")))
return m2;
}
ocl = ocl.getSuperclass();
}
debug.msg("Reflection", "§cFailed to get similiar method to §e" + name + "§c in class §e" + origCl.getName() + "§c.");
return null;
}
public static Class getUtilClass(String className) {
if (ver.isAbove(v1_8))
return getClass(className);
return getClass("net.minecraft.util." + className);
}
public static void init() {
String name = Bukkit.getServer().getClass().getPackage().getName();
version = name.substring(name.lastIndexOf('.') + 1);
ver = valueOf(version.substring(0, version.length() - 3));
SU.cs.sendMessage("§2[§aStartup§2]§e Detected server version:§a " + ver + "§e (§f" + version + "§e) - §f" + Bukkit.getServer().getVersion());
if (Reflection.ver == v1_7) {
nmsRenames.put("PacketLoginOutSetCompression", "org.spigotmc.ProtocolInjector$PacketLoginCompression");
nmsRenames.put("PacketPlayOutTitle", "org.spigotmc.ProtocolInjector$PacketTitle");
nmsRenames.put("PacketPlayOutPlayerListHeaderFooter", "org.spigotmc.ProtocolInjector$PacketTabHeader");
nmsRenames.put("PacketPlayOutResourcePackSend", "org.spigotmc.ProtocolInjector$PacketPlayResourcePackSend");
nmsRenames.put("PacketPlayInResourcePackStatus", "org.spigotmc.ProtocolInjector$PacketPlayResourcePackStatus");
}
if (!version.equals("v1_8_R1")) {
nmsRenames.put("PacketPlayInLook", "PacketPlayInFlying$PacketPlayInLook");
nmsRenames.put("PacketPlayInPosition", "PacketPlayInFlying$PacketPlayInPosition");
nmsRenames.put("PacketPlayInPositionLook", "PacketPlayInFlying$PacketPlayInPositionLook");
nmsRenames.put("PacketPlayInRelPositionLook", "PacketPlayInFlying$PacketPlayInPositionLook");
nmsRenames.put("PacketPlayOutEntityLook", "PacketPlayOutEntity$PacketPlayOutEntityLook");
nmsRenames.put("PacketPlayOutRelEntityMove", "PacketPlayOutEntity$PacketPlayOutRelEntityMove");
nmsRenames.put("PacketPlayOutRelEntityMoveLook", "PacketPlayOutEntity$PacketPlayOutRelEntityMoveLook");
}
if (Reflection.ver.isAbove(v1_9))
nmsRenames.put("WorldSettings$EnumGamemode", "EnumGamemode");
version += ".";
}
private static Method methodCheck(Class cl, String name, Class[] args) {
try {
return cl.getDeclaredMethod(name, args);
} catch (Throwable e) {
Method[] mtds = cl.getDeclaredMethods();
for (Method met : mtds)
if (classArrayCompare(args, met.getParameterTypes()) && met.getName().equals(name))
return met;
for (Method met : mtds)
if (classArrayCompareLight(args, met.getParameterTypes()) && met.getName().equals(name))
return met;
for (Method met : mtds)
if (classArrayCompare(args, met.getParameterTypes()) && met.getName().equalsIgnoreCase(name))
return met;
for (Method met : mtds)
if (classArrayCompareLight(args, met.getParameterTypes()) && met.getName().equalsIgnoreCase(name))
return met;
return null;
}
}
private static Method methodCheckNoArg(Class cl, String name) {
try {
return cl.getDeclaredMethod(name);
} catch (Throwable e) {
Method[] mtds = cl.getDeclaredMethods();
for (Method met : mtds)
if (met.getParameterTypes().length == 0 && met.getName().equalsIgnoreCase(name))
return met;
return null;
}
}
/**
* Constructs a new instance of the given class
*
* @param cl - The class
* @param classes - The parameters of the constructor
* @param objs - The objects, passed to the constructor
* @return The object constructed, with the found constructor or null if there was an error.
*/
public static Object newInstance(Class cl, Class[] classes, Object... objs) {
try {
Constructor c = cl.getDeclaredConstructor(classes);
c.setAccessible(true);
return c.newInstance(objs);
} catch (NoSuchMethodException e) {
if (debug.isEnabled("Reflection")) {
StringBuilder sb = new StringBuilder();
for (Class c : classes)
sb.append(", ").append(c.getName());
debug.msg("Reflection", "§eConstructor §f" + cl.getName() + "§e( §f" + sb + "§e ) was not found.");
}
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
/**
* Constructs a new instance of the given class
*
* @param cl - The class
*/
public static Object newInstance(Class cl) {
try {
try {
return cl.newInstance();
} catch (Throwable err) {
return rf.newConstructorForSerialization(cl, Object.class.getDeclaredConstructor()).newInstance();
}
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public static Field setFieldAccessible(Field f) {
if (f == null)
return null;
try {
f.setAccessible(true);
int modifiers = modifiersField.getInt(f);
modifiersField.setInt(f, modifiers & -17);
return f;
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
} | 16,297 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Primitives.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/Primitives.java | package gyurix.protocol;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public final class Primitives {
private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER_TYPE;
private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE_TYPE;
static {
Map<Class<?>, Class<?>> primToWrap = new HashMap<>(16);
Map<Class<?>, Class<?>> wrapToPrim = new HashMap<>(16);
add(primToWrap, wrapToPrim, boolean.class, Boolean.class);
add(primToWrap, wrapToPrim, byte.class, Byte.class);
add(primToWrap, wrapToPrim, char.class, Character.class);
add(primToWrap, wrapToPrim, double.class, Double.class);
add(primToWrap, wrapToPrim, float.class, Float.class);
add(primToWrap, wrapToPrim, int.class, Integer.class);
add(primToWrap, wrapToPrim, long.class, Long.class);
add(primToWrap, wrapToPrim, short.class, Short.class);
add(primToWrap, wrapToPrim, void.class, Void.class);
PRIMITIVE_TO_WRAPPER_TYPE = Collections.unmodifiableMap(primToWrap);
WRAPPER_TO_PRIMITIVE_TYPE = Collections.unmodifiableMap(wrapToPrim);
}
private static void add(Map<Class<?>, Class<?>> forward,
Map<Class<?>, Class<?>> backward, Class<?> key, Class<?> value) {
forward.put(key, value);
backward.put(value, key);
}
public static <T> Class<T> unwrap(Class<T> type) {
Class<T> unwrapped = (Class<T>) WRAPPER_TO_PRIMITIVE_TYPE.get(type);
return unwrapped == null ? type : unwrapped;
}
public static <T> Class<T> wrap(Class<T> type) {
Class<T> wrapped = (Class<T>) PRIMITIVE_TO_WRAPPER_TYPE.get(type);
return wrapped == null ? type : wrapped;
}
} | 1,671 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
WorldType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/WorldType.java | package gyurix.protocol.utils;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import org.bukkit.Difficulty;
import org.bukkit.GameMode;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Created by GyuriX on 2016.02.28..
*/
public enum WorldType implements WrappedData {
DEFAULT, FLAT, LARGEBIOMES, AMPLIFIED, CUSTOMIZED, DEBUG_ALL_BLOCK_STATES, DEFAULT_1_1;
public static final Method enumDifficultyVO;
public static final Class enumGmCl = Reflection.getNMSClass("WorldSettings$EnumGamemode"),
enumDifficultyCl = Reflection.getNMSClass("EnumDifficulty"),
worldTypeCl = Reflection.getNMSClass("WorldType");
public static final Method enumGmVO = Reflection.getMethod(enumGmCl, "valueOf", String.class);
private static Field name = Reflection.getField(Reflection.getNMSClass("WorldType"), "name");
private static Method valueOf = Reflection.getMethod(worldTypeCl, "getType", String.class);
static {
enumDifficultyVO = Reflection.getMethod(enumDifficultyCl, "getById", int.class);
}
public static WorldType fromVanillaWorldType(Object vanilla) {
try {
return valueOf(((String) name.get(vanilla)).toUpperCase());
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public static Object toVanillaDifficulty(Difficulty mode) {
try {
return enumDifficultyVO.invoke(null, mode.getValue());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public static Object toVanillaGameMode(GameMode mode) {
try {
return enumGmVO.invoke(null, mode.name());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public Object toNMS() {
try {
return valueOf.invoke(null, name());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
}
| 1,934 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Vector.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/Vector.java | package gyurix.protocol.utils;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class Vector implements WrappedData {
private static final Class cl = Reflection.getNMSClass("Vec3D");
private static final Constructor con = Reflection.getConstructor(cl, double.class, double.class, double.class);
private static final Field xf;
private static final Field yf;
private static final Field zf;
static {
Field[] f = cl.getFields();
int i = f[0].getType() == double.class ? 0 : 1;
xf = f[i++];
yf = f[i++];
zf = f[i];
}
public double x;
public double y;
public double z;
public Vector() {
}
public Vector(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public Vector(Object vanillaVector) {
try {
x = (Double) xf.get(vanillaVector);
y = (Double) yf.get(vanillaVector);
z = (Double) zf.get(vanillaVector);
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override
public Object toNMS() {
try {
return con.newInstance(x, y, z);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
}
| 1,265 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
WrapperFactory.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/WrapperFactory.java | package gyurix.protocol.utils;
import com.google.common.primitives.Primitives;
import gyurix.protocol.Reflection;
import gyurix.protocol.utils.GameProfile.Property;
import gyurix.spigotlib.SU;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
/**
* Created by GyuriX on 2016.03.08..
*/
public class WrapperFactory {
public static final HashMap<Class, Method> enumWrap = new HashMap<>();
public static final HashMap<Class, Constructor> wrap = new HashMap<>();
public static void init() {
try {
wrap.put(Reflection.getNMSClass("BaseBlockPosition"), BlockLocation.class.getConstructor(Object.class));
wrap.put(Reflection.getNMSClass("DataWatcher"), DataWatcher.class.getConstructor(Object.class));
enumWrap.put(Reflection.getNMSClass("EnumDirection"), Direction.class.getMethod("valueOf", String.class));
wrap.put(Reflection.getUtilClass("com.mojang.authlib.GameProfile"), GameProfile.class.getConstructor(Object.class));
wrap.put(Reflection.getUtilClass("com.mojang.authlib.properties.Property"), Property.class.getConstructor(Object.class));
wrap.put(Reflection.getNMSClass("ItemStack"), ItemStackWrapper.class.getConstructor(Object.class));
wrap.put(Reflection.getNMSClass("Vec3D"), Vector.class.getConstructor(Object.class));
wrap.put(Reflection.getNMSClass("Vector3f"), Rotation.class.getConstructor(Object.class));
enumWrap.put(Reflection.getNMSClass("WorldType"), WorldType.class.getMethod("valueOf", String.class));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public static Object unwrap(Object o) {
if (o == null)
return null;
if (o instanceof WrappedData)
return ((WrappedData) o).toNMS();
return o;
}
public static Object wrap(Object o) {
if (o == null)
return null;
Class cl = Primitives.unwrap(o.getClass());
try {
Constructor con = wrap.get(cl);
if (con != null)
return con.newInstance(o);
Method m = enumWrap.get(cl);
if (m != null)
return m.invoke(null, o.toString());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return o;
}
}
| 2,235 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
InventoryClickType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/InventoryClickType.java | package gyurix.protocol.utils;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.ServerVersion;
import java.lang.reflect.Method;
/**
* Created by GyuriX on 2016.04.06..
*/
public enum InventoryClickType implements WrappedData {
PICKUP,
QUICK_MOVE,
SWAP,
CLONE,
THROW,
QUICK_CRAFT,
PICKUP_ALL;
static Method valueOf;
static {
if (Reflection.ver.isAbove(ServerVersion.v1_9))
valueOf = Reflection.getMethod(Reflection.getNMSClass("InventoryClickType"), "valueOf", String.class);
}
@Override
public Object toNMS() {
if (Reflection.ver.isAbove(ServerVersion.v1_9))
try {
return valueOf.invoke(null, name());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return ordinal();
}
}
| 818 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ItemStackWrapper.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/ItemStackWrapper.java | package gyurix.protocol.utils;
import gyurix.json.JsonSettings;
import gyurix.nbt.NBTCompound;
import gyurix.nbt.NBTPrimitive;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.ServerVersion;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import static gyurix.configfile.ConfigSerialization.ConfigOptions;
import static gyurix.nbt.NBTTagType.tag;
import static gyurix.protocol.Reflection.getFieldData;
import static gyurix.protocol.Reflection.getNMSClass;
public class ItemStackWrapper implements WrappedData {
@ConfigOptions(serialize = false)
@JsonSettings(serialize = false)
public static final HashMap<Integer, String> itemNames = new HashMap<>();
private static final Constructor bukkitStack, nmsStackFromNBTC;
@ConfigOptions(serialize = false)
@JsonSettings(serialize = false)
private static final Object cmnObj;
private static final Method getType, nmsCopy, saveStack, getID, nmsStackFromNBTM;
private static final Field itemName;
private static final Class nmsClass;
static {
Class nmsItem = getNMSClass("Item");
nmsClass = getNMSClass("ItemStack");
Class nbt = getNMSClass("NBTTagCompound");
Class obc = Reflection.getOBCClass("inventory.CraftItemStack");
Class cmn = Reflection.getOBCClass("util.CraftMagicNumbers");
cmnObj = getFieldData(cmn, "INSTANCE");
nmsStackFromNBTC = Reflection.getConstructor(nmsClass, nbt);
nmsStackFromNBTM = Reflection.getMethod(nmsClass, "createStack", nbt);
saveStack = Reflection.getMethod(nmsClass, "save", nbt);
nmsCopy = Reflection.getMethod(obc, "asNMSCopy", ItemStack.class);
bukkitStack = Reflection.getConstructor(obc, nmsClass);
getType = Reflection.getMethod(cmn, "getMaterialFromInternalName", String.class);
getID = Reflection.getMethod(nmsItem, "getId", nmsItem);
try {
if (Reflection.ver.isBellow(ServerVersion.v1_13))
for (Map.Entry<?, ?> e : ((Map<?, ?>) getFieldData(getNMSClass("RegistryMaterials"), "b", getFieldData(nmsItem, "REGISTRY"))).entrySet()) {
itemNames.put((Integer) getID.invoke(null, e.getKey()), e.getValue().toString());
}
} catch (Throwable err) {
SU.error(SU.cs, err, "SpigotLib", "gyurix");
}
itemName = Reflection.getField(nmsItem, "name");
}
@Getter
@Setter
private NBTCompound nbtData = new NBTCompound();
public ItemStackWrapper() {
}
public ItemStackWrapper(NBTCompound nbt) {
this.nbtData = nbt;
}
public ItemStackWrapper(ItemStack is) {
loadFromBukkitStack(is);
}
public ItemStackWrapper(Object vanillaStack) {
loadFromVanillaStack(vanillaStack);
}
public byte getCount() {
return (byte) ((NBTPrimitive) nbtData.get("Count")).getData();
}
public void setCount(byte count) {
nbtData.put("Count", tag(count));
}
public short getDamage() {
try {
return (Short) ((NBTPrimitive) nbtData.get("Damage")).getData();
} catch (Throwable e) {
e.printStackTrace();
return 0;
}
}
public void setDamage(int damage) {
if (Reflection.ver.isAbove(ServerVersion.v1_13)) {
getMetaData().set("Damage", damage);
return;
}
nbtData.put("Damage", tag((short) damage));
}
public String getId() {
if (nbtData.get("id") == null)
return "minecraft:air";
return (String) ((NBTPrimitive) nbtData.get("id")).getData();
}
public void setId(String newId) {
nbtData.put("id", tag(newId));
}
public NBTCompound getMetaData() {
return nbtData.getCompound("tag");
}
public int getNumericId() {
return getType().getId();
}
public void setNumericId(int newId) {
try {
nbtData.put("id", tag(itemNames.get(newId)));
} catch (Throwable e) {
e.printStackTrace();
}
}
public Material getType() {
try {
return (Material) getType.invoke(cmnObj, getId());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return Material.AIR;
}
}
public boolean hasMetaData() {
return nbtData.containsKey("tag");
}
public boolean isUnbreakable() {
return getMetaData() != null && getMetaData().getBoolean("Unbreakable");
}
public void setUnbreakable(boolean unbreakable) {
if (unbreakable) {
getMetaData().put("Unbreakable", tag((byte) 1));
} else {
getMetaData().remove("Unbreakable");
}
}
public void loadFromBukkitStack(ItemStack is) {
try {
if (is != null) {
Object nms = nmsCopy.invoke(null, is);
if (nms != null)
nbtData = (NBTCompound) tag(saveStack.invoke(nms, new NBTCompound().toNMS()));
}
} catch (Throwable e) {
e.printStackTrace();
}
}
public void loadFromVanillaStack(Object is) {
try {
if (is != null)
nbtData = (NBTCompound) tag(saveStack.invoke(is, new NBTCompound().toNMS()));
} catch (Throwable e) {
e.printStackTrace();
}
}
public void removeMetaData() {
nbtData.remove("tag");
}
public ItemStack toBukkitStack() {
try {
Object nms = toNMS();
return (ItemStack) bukkitStack.newInstance(nms);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
@Override
public Object toNMS() {
try {
if (nmsStackFromNBTC == null)
return nmsStackFromNBTM.invoke(null, nbtData.toNMS());
return nmsStackFromNBTC.newInstance(nbtData.toNMS());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
@Override
public String toString() {
return nbtData.toString();
}
}
| 5,823 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
DataWatcher.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/DataWatcher.java | package gyurix.protocol.utils;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.json.JsonAPI;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.ChatAPI;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.ServerVersion;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.util.gnu.trove.map.TObjectIntMap;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.*;
import java.util.Map.Entry;
public class DataWatcher implements WrappedData, StringSerializable {
private static Constructor<?> con;
private static Field dwField, dwoField, itemField, idField;
private static Constructor<?> itc;
private static Class<?> nmsDW, nmsItem, dwo;
private static Constructor<?> objcon;
private static Map<Class<?>, Object> serializers;
static {
try {
nmsDW = Reflection.getNMSClass("DataWatcher");
con = Reflection.getConstructor(nmsDW, Reflection.getNMSClass("Entity"));
Class<?> mapType = Reflection.getClass("org.bukkit.craftbukkit.libs.it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap");
if (mapType == null)
mapType = Reflection.getClass("it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap");
if (mapType == null)
mapType = Map.class;
dwField = Reflection.getLastFieldOfType(nmsDW, mapType);
if (Reflection.ver.isAbove(ServerVersion.v1_9)) {
Class<?> dwr = Reflection.getNMSClass("DataWatcherRegistry");
nmsItem = Reflection.getInnerClass(nmsDW, "Item");
itc = nmsItem.getConstructors()[0];
itemField = Reflection.getFirstFieldOfType(nmsItem, Object.class);
dwo = Reflection.getNMSClass("DataWatcherObject");
dwoField = Reflection.getFirstFieldOfType(nmsItem, dwo);
idField = Reflection.getFirstFieldOfType(dwo, int.class);
objcon = Reflection.getConstructor(dwo, int.class, Reflection.getNMSClass("DataWatcherSerializer"));
serializers = new HashMap<>();
serializers.put(Byte.class, dwr.getField("a").get(null));
serializers.put(Integer.class, dwr.getField("b").get(null));
serializers.put(Float.class, dwr.getField("c").get(null));
serializers.put(String.class, dwr.getField("d").get(null));
serializers.put(ChatAPI.icbcClass, dwr.getField("e").get(null));
if (Reflection.ver.isAbove(ServerVersion.v1_14)) {
serializers.put(Optional.class, dwr.getField("f").get(null));
serializers.put(Reflection.getNMSClass("ItemStack"), dwr.getField("g").get(null));
serializers.put(Reflection.getNMSClass("IBlockData"), dwr.getField("h").get(null));
serializers.put(Boolean.class, dwr.getField("i").get(null));
serializers.put(Reflection.getNMSClass("ParticleParam"), dwr.getField("j").get(null));
serializers.put(Reflection.getNMSClass("Vector3f"), dwr.getField("k").get(null));
serializers.put(Reflection.getNMSClass("BlockPosition"), dwr.getField("m").get(null));
serializers.put(Reflection.getNMSClass("EnumDirection"), dwr.getField("n").get(null));
}
else {
serializers.put(Reflection.getNMSClass("ItemStack"), dwr.getField("f").get(null));
serializers.put(Reflection.getNMSClass("IBlockData"), dwr.getField("g").get(null));
serializers.put(Boolean.class, dwr.getField("h").get(null));
serializers.put(Reflection.getNMSClass("Vector3f"), dwr.getField("i").get(null));
serializers.put(Reflection.getNMSClass("BlockPosition"), dwr.getField("k").get(null));
serializers.put(Reflection.getNMSClass("EnumDirection"), dwr.getField("l").get(null));
serializers.put(UUID.class, dwr.getField("m").get(null));
}
} else {
nmsItem = Reflection.getNMSClass(Reflection.ver.isAbove(ServerVersion.v1_8) ? "DataWatcher$WatchableObject" : "WatchableObject");
itc = nmsItem.getConstructors()[0];
itemField = Reflection.getFirstFieldOfType(nmsItem, Object.class);
idField = Reflection.getField(nmsItem, "b");
if (Reflection.ver.isAbove(ServerVersion.v1_8))
serializers = (Map<Class<?>, Object>) Reflection.getFirstFieldOfType(nmsDW, Map.class).get(null);
else {
serializers = new HashMap<>();
Object mapObj = Reflection.getField(nmsDW, "classToId").get(null);
if (mapObj instanceof TObjectIntMap) {
((TObjectIntMap<?>) mapObj).forEachEntry((o, i) -> {
serializers.put((Class<?>) o, i);
return true;
});
} else if (mapObj instanceof Object2IntOpenHashMap) {
((Object2IntOpenHashMap<?>) mapObj).forEach((o, i) -> serializers.put((Class<?>) o, i));
}
}
}
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public TreeMap<Integer, Object> map = new TreeMap<>();
public DataWatcher() {
}
public DataWatcher(Iterable<WrappedItem> list) {
try {
for (WrappedItem wi : list)
map.put(wi.id, wi.data);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public DataWatcher(Object nmsData) {
try {
if (nmsData == null)
return;
if (nmsData instanceof Iterable) {
for (WrappedItem wi : wrapNMSItems((Iterable<Object>) nmsData))
map.put(wi.id, wi.data);
return;
}
Map<Integer, Object> m = (Map<Integer, Object>) dwField.get(nmsData);
for (Entry<Integer, Object> e : m.entrySet()) {
map.put(e.getKey(), itemField.get(e.getValue()));
}
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public static ArrayList<Object> convertToNmsItems(Iterable<WrappedItem> in) {
ArrayList<Object> out = new ArrayList<>();
for (WrappedItem wi : in) {
try {
Object o = WrapperFactory.unwrap(wi.data);
if (o != null) {
if (Reflection.ver.isAbove(ServerVersion.v1_9))
out.add(itc.newInstance(objcon.newInstance(wi.id, serializers.get(o.getClass())), o));
else {
out.add(itc.newInstance(serializers.get(o.getClass()), wi.id, o));
}
}
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyuriX");
}
}
return out;
}
public static ArrayList<WrappedItem> wrapNMSItems(Iterable<Object> in) {
ArrayList<WrappedItem> out = new ArrayList<>();
for (Object o : in) {
try {
System.out.println("WRAP - " + o);
out.add(new WrappedItem(o));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyuriX");
}
}
return out;
}
@Override
public Object toNMS() {
Object dw = null;
try {
dw = con.newInstance(null);
Map<Integer, Object> m = (Map<Integer, Object>) dwField.get(dw);
for (Entry<Integer, Object> e : map.entrySet()) {
Object o = WrapperFactory.unwrap(e.getValue());
if (o == null)
continue;
try {
if (Reflection.ver.isAbove(ServerVersion.v1_9)) {
m.put(e.getKey(), itc.newInstance(objcon.newInstance(e.getKey(), serializers.get(o.getClass())), o));
} else {
int type = (int) serializers.get(o.getClass());
m.put(e.getKey(), itc.newInstance(type, e.getKey(), o));
}
} catch (Throwable err) {
SU.cs.sendMessage("§e[DataWatcher] §cError on getting serializer for object #" + e.getKey() + " - §f" + o + "§c having class §f" + o.getClass().getSimpleName());
SU.error(SU.cs, err, "SpigotLib", "gyurix");
}
}
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return dw;
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
for (Entry<Integer, Object> e : map.entrySet()) {
out.append("§e, §b").append(e.getKey()).append("§e: §f").append(JsonAPI.serialize(e.getValue()));
}
return out.length() == 0 ? "§e{}" : "§e{§b" + out.substring(6) + "§e}";
}
public static class WrappedItem implements WrappedData {
public Object data;
public int id;
public WrappedItem(int id, Object data) {
this.id = id;
this.data = data;
}
public WrappedItem(Object o) {
try {
data = WrapperFactory.wrap(itemField.get(o));
if (Reflection.ver.isAbove(ServerVersion.v1_9))
id = idField.getInt(dwoField.get(o));
else
id = idField.getInt(o);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
@Override
public Object toNMS() {
try {
if (Reflection.ver.isAbove(ServerVersion.v1_9))
return itc.newInstance(objcon.newInstance(id, serializers.get(data.getClass())), data);
else
return itc.newInstance(serializers.get(data.getClass()), id, data);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
}
}
| 9,096 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Direction.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/Direction.java | package gyurix.protocol.utils;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.BlockUtils;
import org.bukkit.block.BlockFace;
import org.bukkit.util.Vector;
import java.lang.reflect.Method;
public enum Direction implements WrappedData {
DOWN(new Vector(0, -1, 0)), UP(new Vector(0, 1, 0)), SOUTH(new Vector(0, 0, 1)), WEST(new Vector(-1, 0, 0)), NORTH(new Vector(0, 0, -1)), EAST(new Vector(1, 0, 0));
private static final Method valueOf = Reflection.getMethod(Reflection.getNMSClass("EnumDirection"), "valueOf", String.class);
private Vector v;
private float yaw, pitch;
Direction(Vector v) {
this.v = v;
yaw = BlockUtils.getYaw(v);
pitch = BlockUtils.getPitch(v);
}
public static Direction get(int id) {
if (id >= 0 && id < 6)
return Direction.values()[id];
return null;
}
public static Direction get(BlockFace face) {
return valueOf(face.name());
}
public static Direction get(Vector v) {
return get(BlockUtils.getYaw(v), BlockUtils.getPitch(v));
}
private static Direction get(float yaw, float pitch) {
yaw = (yaw + 405) % 360;
return pitch > 45 ? DOWN : pitch < -45 ? UP : yaw < 90 ? SOUTH : yaw < 180 ? WEST : yaw < 270 ? NORTH : EAST;
}
public static void main(String[] args) {
}
public float getPitch() {
return pitch;
}
public float getYaw() {
return yaw;
}
public BlockFace toBlockFace() {
return BlockFace.valueOf(name());
}
@Override
public Object toNMS() {
try {
return valueOf.invoke(null, name());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
public Vector toVector() {
return v.clone();
}
}
| 1,745 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BlockLocation.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/BlockLocation.java | package gyurix.protocol.utils;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.LocationData;
import gyurix.spigotutils.ServerVersion;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.util.Vector;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class BlockLocation implements WrappedData, StringSerializable {
public static final BlockLocation notDefined = new BlockLocation(0, 0, 0);
private static final Class baseCl = Reflection.getNMSClass("BaseBlockPosition");
private static final Class cl = Reflection.getNMSClass("BlockPosition");
private static final Constructor con = Reflection.getConstructor(cl, int.class, int.class, int.class);
private static final Method getX = Reflection.getMethod(Reflection.ver.isAbove(ServerVersion.v1_9) ? cl : baseCl, "getX");
private static final Method getY = Reflection.getMethod(Reflection.ver.isAbove(ServerVersion.v1_9) ? cl : baseCl, "getY");
private static final Method getZ = Reflection.getMethod(Reflection.ver.isAbove(ServerVersion.v1_9) ? cl : baseCl, "getZ");
public int x;
public int y;
public int z;
public BlockLocation() {
}
public BlockLocation(String in) {
String[] d = in.split(" ", 3);
x = Integer.valueOf(d[0]);
y = Integer.valueOf(d[1]);
z = Integer.valueOf(d[2]);
}
public BlockLocation(Block bl) {
this(bl.getX(), bl.getY(), bl.getZ());
}
public BlockLocation(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public BlockLocation(Location loc) {
this(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
}
public BlockLocation(LocationData loc) {
this.x = (int) loc.x;
this.y = (int) loc.y;
this.z = (int) loc.z;
}
public BlockLocation(Object nmsData) {
try {
x = (int) getX.invoke(nmsData);
y = (int) getY.invoke(nmsData);
z = (int) getZ.invoke(nmsData);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public BlockLocation add(BlockLocation bl) {
return add(bl.x, bl.y, bl.z);
}
public BlockLocation add(Vector v) {
return add(v.getBlockX(), v.getBlockY(), v.getBlockZ());
}
public BlockLocation add(int x, int y, int z) {
this.x += x;
this.y += y;
this.z += z;
return this;
}
public Block getBlock(World w) {
return w.getBlockAt(x, y, z);
}
public Location getLocation(World w) {
return new Location(w, x, y, z);
}
@Override
public int hashCode() {
return (x << 20) + (y << 12) + z;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BlockLocation))
return false;
BlockLocation bl = (BlockLocation) obj;
return bl.x == x && bl.y == y && bl.z == z;
}
public BlockLocation clone() {
return new BlockLocation(x, y, z);
}
@Override
public String toString() {
return x + " " + y + ' ' + z;
}
public boolean isDefined() {
return x != 0 || y != 0 || z != 0;
}
public BlockLocation subtract(Vector v) {
return add(v.clone().multiply(-1));
}
public BlockLocation subtract(BlockLocation bl) {
return add(-bl.x, -bl.y, -bl.z);
}
public BlockLocation subtract(int x, int y, int z) {
return add(-x, -y, -z);
}
@Override
public Object toNMS() {
try {
return con.newInstance(x, y, z);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
}
| 3,590 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
WrappedData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/WrappedData.java | package gyurix.protocol.utils;
/**
* Created by GyuriX on 2016.03.08..
*/
public interface WrappedData {
Object toNMS();
}
| 128 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
HandType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/HandType.java | package gyurix.protocol.utils;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import java.lang.reflect.Method;
/**
* Created by GyuriX on 2016.03.26..
*/
public enum HandType implements WrappedData {
MAIN_HAND,
OFF_HAND;
Method valueOf = Reflection.getMethod(Reflection.getNMSClass("EnumHand"), "valueOf", String.class);
@Override
public Object toNMS() {
try {
return valueOf.invoke(null, name());
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
}
| 546 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
GameProfile.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/GameProfile.java | package gyurix.protocol.utils;
import com.google.common.collect.Multimap;
import gyurix.json.JsonAPI;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.ServerVersion;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Created by GyuriX on 2015.12.25..
*/
public class GameProfile implements WrappedData {
public static final Class cl = Reflection.getUtilClass("com.mojang.authlib.GameProfile");
public static final Constructor con = Reflection.getConstructor(cl, UUID.class, String.class);
public static final Field fid = Reflection.getField(cl, "id"),
fname = Reflection.getField(cl, "name"),
fproperties = Reflection.getField(cl, "properties"),
flegacy = Reflection.getField(cl, "legacy");
public boolean demo;
public UUID id;
public boolean legacy;
public String name;
public List<Property> properties = new ArrayList<>();
public GameProfile() {
}
public GameProfile(String n) {
name = n;
id = UUID.nameUUIDFromBytes(("OfflinePlayer:" + n).getBytes());
}
public GameProfile(String n, UUID uid) {
name = n;
id = uid;
}
public GameProfile(String n, UUID uid, List<Property> props) {
name = n;
id = uid;
properties = props;
}
public GameProfile(Object nmsProfile) {
try {
id = (UUID) fid.get(nmsProfile);
name = (String) fname.get(nmsProfile);
legacy = flegacy.getBoolean(nmsProfile);
if (Reflection.ver.isAbove(ServerVersion.v1_8))
for (Object obj : ((Multimap) fproperties.get(nmsProfile)).values())
properties.add(new Property(obj));
else
for (Object obj : ((net.minecraft.util.com.google.common.collect.Multimap) fproperties.get(nmsProfile)).values())
properties.add(new Property(obj));
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public GameProfile clone() {
GameProfile out = new GameProfile(name, id);
out.demo = demo;
out.legacy = legacy;
for (Property p : properties)
if (p != null)
out.properties.add(p.clone());
return out;
}
@Override
public String toString() {
return JsonAPI.serialize(this);
}
@Override
public Object toNMS() {
try {
Object o = con.newInstance(id, name);
flegacy.set(o, legacy);
if (Reflection.ver.isAbove(ServerVersion.v1_8)) {
Multimap m = (Multimap) fproperties.get(o);
for (Property p : properties) {
if (p != null)
m.put(p.name, p.toNMS());
}
} else {
net.minecraft.util.com.google.common.collect.Multimap m = (net.minecraft.util.com.google.common.collect.Multimap) fproperties.get(o);
for (Property p : properties) {
if (p != null)
m.put(p.name, p.toNMS());
}
}
return o;
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
public static class Property implements WrappedData {
private static final Class cl = Reflection.getUtilClass("com.mojang.authlib.properties.Property");
private static final Constructor con = Reflection.getConstructor(cl, String.class, String.class, String.class);
private static final Field fname = Reflection.getField(cl, "name"),
fvalue = Reflection.getField(cl, "value"),
fsignature = Reflection.getField(cl, "signature");
public String name;
public String signature;
public String value;
public Property(Object o) {
try {
name = (String) fname.get(o);
value = (String) fvalue.get(o);
signature = (String) fsignature.get(o);
} catch (Throwable ignored) {
}
}
public Property(String name, String value, String signature) {
this.name = name;
this.value = value;
this.signature = signature;
}
public Property clone() {
return new Property(name, value, signature);
}
@Override
public String toString() {
return JsonAPI.serialize(this);
}
public Object toNMS() {
try {
return con.newInstance(name, value, signature);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
}
} | 4,378 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Rotation.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/utils/Rotation.java | package gyurix.protocol.utils;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class Rotation implements WrappedData {
private static final Class cl = Reflection.getNMSClass("Vector3f");
private static final Constructor con = Reflection.getConstructor(cl, float.class, float.class, float.class);
private static final Field xf;
private static final Field yf;
private static final Field zf;
static {
xf = Reflection.getField(cl, "x");
yf = Reflection.getField(cl, "y");
zf = Reflection.getField(cl, "z");
}
public float x;
public float y;
public float z;
public Rotation() {
}
public Rotation(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
public Rotation(Object vanillaVector) {
try {
x = (Float) xf.get(vanillaVector);
y = (Float) yf.get(vanillaVector);
z = (Float) zf.get(vanillaVector);
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override
public Object toNMS() {
try {
return con.newInstance(x, y, z);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
}
| 1,248 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ProtocolImpl.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/protocol/manager/ProtocolImpl.java | package gyurix.protocol.manager;
import com.mojang.authlib.GameProfile;
import gyurix.protocol.Protocol;
import gyurix.protocol.Reflection;
import gyurix.protocol.event.PacketInEvent;
import gyurix.protocol.event.PacketInType;
import gyurix.protocol.event.PacketOutEvent;
import gyurix.protocol.wrappers.WrappedPacket;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.EntityUtils;
import gyurix.spigotutils.ServerVersion;
import io.netty.channel.*;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import static gyurix.protocol.Reflection.*;
import static gyurix.spigotlib.Main.pl;
public final class ProtocolImpl extends Protocol {
static final Field getGameProfile = getFirstFieldOfType(getNMSClass("PacketLoginInStart"), GameProfile.class),
playerConnectionF = getField(getNMSClass("EntityPlayer"), "playerConnection"),
networkManagerF = getField(getNMSClass("PlayerConnection"), "networkManager"),
channelF = getField(getNMSClass("NetworkManager"), "channel");
private static final Map<String, Channel> channelLookup = Collections.synchronizedMap(new HashMap<>());
private static final Class<?> minecraftServerClass = getNMSClass("MinecraftServer");
private static final Map<String, Object> networkManagers = Collections.synchronizedMap(new HashMap<>());
private static final Method sendPacketM = getMethod(getNMSClass("NetworkManager"),
ver.isAbove(ServerVersion.v1_9) ? "sendPacket" : "handle", getNMSClass("Packet"));
private static final Class<?> serverConnectionClass = getNMSClass("ServerConnection");
private static Object oldH;
private static Field oldHChildF;
private ChannelFuture cf;
public ProtocolImpl() {
}
@Override
public Channel getChannel(Player plr) {
if (plr == null)
return null;
Channel c = channelLookup.get(plr.getName());
if (c == null)
try {
Object nmsPlayer = EntityUtils.getNMSEntity(plr);
Object playerConnection = playerConnectionF.get(nmsPlayer);
if (playerConnection == null)
return null;
Object networkManager = networkManagerF.get(playerConnection);
networkManagers.put(plr.getName(), networkManager);
Channel channel = (Channel) channelF.get(networkManager);
channelLookup.put(plr.getName(), c = channel);
} catch (Throwable err) {
SU.error(SU.cs, err, "SpigotLib", "gyurix");
}
return c;
}
@Override
public Player getPlayer(Object channel) {
ClientChannelHook ch = ((Channel) channel).pipeline().get(ClientChannelHook.class);
if (ch == null)
return null;
return ch.player;
}
@Override
public void init() throws Throwable {
Object minecraftServer = getFirstFieldOfType(getOBCClass("CraftServer"), minecraftServerClass).get(SU.srv);
Object serverConnection = getFirstFieldOfType(minecraftServerClass, serverConnectionClass).get(minecraftServer);
cf = (ChannelFuture) ((List<?>) getFirstFieldOfType(serverConnectionClass, List.class).get(serverConnection)).iterator().next();
registerServerChannelHook();
SU.srv.getOnlinePlayers().forEach(this::injectPlayer);
}
@Override
public void injectPlayer(final Player plr) {
Channel ch = getChannel(plr);
if (ch != null) {
ClientChannelHook cch = ch.pipeline().get(ClientChannelHook.class);
if (cch != null)
cch.player = plr;
}
}
@Override
public void printPipeline(Iterable<Map.Entry<String, ?>> pipeline) {
ArrayList<String> list = new ArrayList<>();
pipeline.forEach((e) -> list.add(e.getKey()));
SU.cs.sendMessage("§ePipeline: §f" + StringUtils.join(list, ", "));
}
@Override
public void receivePacket(Object channel, Object packet) {
if (packet instanceof WrappedPacket)
packet = ((WrappedPacket) packet).getVanillaPacket();
((Channel) channel).pipeline().context("encoder").fireChannelRead(packet);
}
@Override
public void registerServerChannelHook() throws Throwable {
Channel serverCh = cf.channel();
oldH = serverCh.pipeline().get(Reflection.getClass("io.netty.bootstrap.ServerBootstrap$ServerBootstrapAcceptor"));
oldHChildF = getField(oldH.getClass(), "childHandler");
serverCh.pipeline().addFirst("SpigotLibServer", new ServerChannelHook((ChannelHandler) oldHChildF.get(oldH)));
}
@Override
public void removeHandler(Object ch, String handler) {
try {
((Channel) ch).pipeline().remove(handler);
} catch (Throwable ignored) {
}
}
@Override
public void sendPacket(Player player, Object packet) {
try {
if (!player.isOnline())
return;
if (packet instanceof WrappedPacket)
packet = ((WrappedPacket) packet).getVanillaPacket();
sendPacketM.invoke(getNetworkManager(player), packet);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
@Override
public void sendPacket(Object channel, Object packet) {
if (channel == null || packet == null) {
SU.error(SU.cs, new RuntimeException("§cFailed to send packet " + packet + " to channel " + channel), "SpigotLib", "gyurix");
return;
}
if (packet instanceof WrappedPacket)
packet = ((WrappedPacket) packet).getVanillaPacket();
((Channel) channel).pipeline().writeAndFlush(packet);
}
@Override
public void unregisterServerChannelHandler() throws IllegalAccessException {
removeHandler(cf.channel(), "SpigotLibServer");
}
public Object getNetworkManager(Player plr) {
Object nm = networkManagers.get(plr.getName());
if (nm == null)
try {
Object nmsPlayer = EntityUtils.getNMSEntity(plr);
Object playerConnection = playerConnectionF.get(nmsPlayer);
if (playerConnection == null)
return null;
Object networkManager = networkManagerF.get(playerConnection);
networkManagers.put(plr.getName(), nm = networkManager);
Channel channel = (Channel) channelF.get(networkManager);
channelLookup.put(plr.getName(), channel);
} catch (Throwable err) {
SU.error(SU.cs, err, "SpigotLib", "gyurix");
}
return nm;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent e) {
injectPlayer(e.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerQuit(final PlayerQuitEvent e) {
final String pln = e.getPlayer().getName();
SU.sch.scheduleSyncDelayedTask(pl, () -> {
Player p = Bukkit.getPlayer(pln);
if (p == null)
channelLookup.remove(pln);
});
}
public class ClientChannelHook extends ChannelDuplexHandler {
public Player player;
public void channelRead(ChannelHandlerContext ctx, Object packet) throws Exception {
try {
Channel channel = ctx.channel();
PacketInEvent e = new PacketInEvent(channel, player, packet);
if (e.getType() == PacketInType.LoginInStart) {
GameProfile profile = (GameProfile) getGameProfile.get(packet);
channelLookup.put(profile.getName(), channel);
networkManagers.put(profile.getName(), ctx.pipeline().get("packet_handler"));
}
dispatchPacketInEvent(e);
packet = e.getPacket();
if (!e.isCancelled())
ctx.fireChannelRead(packet);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public void write(ChannelHandlerContext ctx, Object packet, ChannelPromise promise) throws Exception {
try {
PacketOutEvent e = new PacketOutEvent(ctx.channel(), player, packet);
dispatchPacketOutEvent(e);
packet = e.getPacket();
if (!e.isCancelled())
ctx.write(packet, promise);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
}
public class ServerChannelHook extends ChannelInboundHandlerAdapter {
public final ChannelHandler childHandler;
public ServerChannelHook(ChannelHandler childHandler) {
this.childHandler = childHandler;
}
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (childHandler.getClass().getName().equals("lilypad.bukkit.connect.injector.NettyChannelInitializer"))
getField(childHandler.getClass(), "oldChildHandler").set(childHandler, oldHChildF.get(oldH));
Channel c = (Channel) msg;
c.pipeline().addLast("SpigotLibInit", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object o) throws Exception {
ChannelPipeline pipeline = ctx.pipeline();
pipeline.remove("SpigotLibInit");
pipeline.addBefore("packet_handler", "SpigotLib", new ClientChannelHook());
ctx.fireChannelRead(o);
}
});
ctx.fireChannelRead(msg);
}
}
}
| 9,172 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.