Merge branch 'develop' of github.com:Mineplex-LLC/Minecraft-PC into develop

This commit is contained in:
Jonathan Williams 2016-04-15 12:30:32 -05:00
commit cf3141ddc0
355 changed files with 19386 additions and 4753 deletions

1
.gitignore vendored
View File

@ -9,6 +9,7 @@ bin
MagicMC
.externalToolBuilders/
/Plugins/Mineplex.Core/.externalToolBuilders/Core Builder.launch
/Plugins/Mineplex.AntiCheat

View File

@ -56,12 +56,12 @@ public class MotdManager implements Listener, Runnable
//String motdLine = "§f§l◄ §c§lMaintenance§f§l ►";
//String motdLine = "§f§l◄ §a§lCarl the Creeper§f§l ►";
// String motdLine = " §2§l§n M O N S T E R M A Z E B E T A §f";
String motdLine = " §f❄ §2§lMerry Christmas §f❄ §2§lElf Presents §f❄";
String motdLine = " §f> §4§lCLANS BETA §f- §c§lOpen to Everyone §f<";
// String motdLine = " §f❄ §2§lServer Maintenance §f❄ §2§lBe Back Soon §f❄";
//String motdLine = " §d§lRank Sale §a§l40% Off");
//String motdLine = " §f§l◄§c§lMAINTENANCE§f§l►");
updateMainMotd(" §c§m §f§m §c§m §f§m §2§l§m[ §r §c§lMineplex§r §f§lGames§r §2§l§m ]§f§m §c§m §f§m §c§m §r", motdLine);
updateMainMotd(" §f§m §8§l§m[ §r §9§lMineplex§r §f§lGames§r §8§l§m ]§f§m §r", motdLine);
System.out.println("Updated Bungee MOTD");
}
}

View File

@ -69,7 +69,7 @@ public class PlayerCache
PlayerInfo info = getPlayer(uuid);
return info == null ? -1 : info.getAccountId();
}
public void clean()
{
_repository.clean();

View File

@ -0,0 +1,35 @@
package mineplex.core.common;
import java.util.HashMap;
import java.util.function.Function;
public class DefaultHashMap<K, V>
{
private HashMap<K, V> _map;
private Function<K, V> _defaultPopulator;
public DefaultHashMap(Function<K, V> defaultPopulator)
{
_map = new HashMap<K, V>();
_defaultPopulator = defaultPopulator;
}
public V get(K key)
{
_map.putIfAbsent(key, _defaultPopulator.apply(key));
return _map.get(key);
}
public void put(K key, V value)
{
_map.put(key, value);
}
public void remove(K key)
{
_map.remove(key);
}
}

View File

@ -0,0 +1,80 @@
package mineplex.core.common;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
public class GsonLocation
{
private String _world;
private double _posX;
private double _posY;
private double _posZ;
private float _yaw;
private float _pitch;
public GsonLocation(Location location)
{
_world = location.getWorld().getName();
_posX = location.getX();
_posY = location.getY();
_posZ = location.getZ();
_yaw = location.getYaw();
_pitch = location.getPitch();
}
public GsonLocation(String world, double x, double y, double z)
{
this(Bukkit.getWorld(world), x, y, z, .0f, .0f);
}
public GsonLocation(String world, double x, double y, double z, float yaw, float pitch)
{
this(Bukkit.getWorld(world), x, y, z, yaw, pitch);
}
public GsonLocation(World world, double x, double y, double z, float yaw, float pitch)
{
_world = world.getName();
_posX = x;
_posY = y;
_posZ = z;
_yaw = yaw;
_pitch = pitch;
}
public GsonLocation(double x, double y, double z)
{
this(x, y, z, .0f, .0f);
}
public GsonLocation(double x, double y, double z, float yaw, float pitch)
{
this("world", x, y, z, yaw, pitch);
}
public Location bukkit()
{
return new Location(Bukkit.getWorld(_world), _posX, _posY, _posZ);
}
public String getWorld()
{
return _world;
}
public double getX()
{
return _posX;
}
public double getY()
{
return _posY;
}
public double getZ()
{
return _posZ;
}
}

View File

@ -0,0 +1,46 @@
package mineplex.core.common;
import org.bukkit.Material;
public class MaterialData
{
private final Material _material;
private final byte _data;
private MaterialData(Material material, byte data)
{
_material = material;
_data = data;
}
public static MaterialData of(Material material)
{
return new MaterialData(material, (byte) 0);
}
public static MaterialData of(Material material, byte data)
{
return new MaterialData(material, data);
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MaterialData that = (MaterialData) o;
if (_data != that._data) return false;
return _material == that._material;
}
@Override
public int hashCode()
{
int result = _material.hashCode();
result = 31 * result + (int) _data;
return result;
}
}

View File

@ -0,0 +1,8 @@
package mineplex.core.common;
public enum MinecraftVersion
{
ALL,
Version1_9,
Version1_8
}

View File

@ -8,7 +8,7 @@ public class Pair<L, R> implements Serializable {
private L left;
private R right;
public static <L, R> Pair<L, R> create(L left, R right)
{
return new Pair<L, R>(left, right);

View File

@ -0,0 +1,83 @@
package mineplex.core.common.block;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import org.bukkit.DyeColor;
import org.bukkit.Location;
public class DataLocationMap
{
private EnumMap<DyeColor, List<Location>> _goldDataMap;
private EnumMap<DyeColor, List<Location>> _ironDataMap;
private EnumMap<DyeColor, List<Location>> _spongeDataMap;
public DataLocationMap()
{
_goldDataMap = new EnumMap<>(DyeColor.class);
_ironDataMap = new EnumMap<>(DyeColor.class);
_spongeDataMap = new EnumMap<>(DyeColor.class);
}
public List<Location> getGoldLocations(DyeColor color)
{
List<Location> list = _goldDataMap.get(color);
return list == null ? Collections.emptyList() : list;
}
public void addGoldLocation(DyeColor color, Location location)
{
if (_goldDataMap.containsKey(color))
{
_goldDataMap.get(color).add(location);
}
else
{
List<Location> list = new ArrayList<>();
list.add(location);
_goldDataMap.put(color, list);
}
}
public List<Location> getIronLocations(DyeColor color)
{
List<Location> list = _ironDataMap.get(color);
return list == null ? Collections.emptyList() : list;
}
public void addIronLocation(DyeColor color, Location location)
{
if (_ironDataMap.containsKey(color))
{
_ironDataMap.get(color).add(location);
}
else
{
List<Location> list = new ArrayList<>();
list.add(location);
_ironDataMap.put(color, list);
}
}
public void addSpongeLocation(DyeColor color, Location location) {
if (_spongeDataMap.containsKey(color))
{
_spongeDataMap.get(color).add(location);
}
else
{
List<Location> list = new ArrayList<>();
list.add(location);
_spongeDataMap.put(color, list);
}
}
public List<Location> getSpongeLocations(DyeColor color)
{
List<Location> list = _spongeDataMap.get(color);
return list == null ? Collections.emptyList() : list;
}
}

View File

@ -1,8 +1,11 @@
package mineplex.core.common.block.schematic;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import mineplex.core.common.block.DataLocationMap;
import mineplex.core.common.util.UtilBlock;
public class Schematic
{
@ -21,8 +24,10 @@ public class Schematic
_blockData = blockData;
}
public void paste(Location originLocation)
public DataLocationMap paste(Location originLocation, boolean ignoreAir)
{
DataLocationMap locationMap = new DataLocationMap();
int startX = originLocation.getBlockX();
int startY = originLocation.getBlockY();
int startZ = originLocation.getBlockZ();
@ -34,21 +39,107 @@ public class Schematic
for (int z = 0; z < _length; z++)
{
int index = getIndex(x, y, z);
Block block = originLocation.getWorld().getBlockAt(startX + x, startY + y, startZ + z);
// some blocks were giving me negative id's in the schematic (like stairs)
// not sure why but the math.abs is my simple fix
int materialId = Math.abs(_blocks[index]);
Material material = Material.getMaterial(materialId);
if (material == null)
if (ignoreAir && materialId == 0) // Air
{
System.out.println(materialId + " data: " + _blockData[index]);
continue;
}
block.setTypeIdAndData(materialId, _blockData[index], false);
else if (materialId == 147) // Gold Plate
{
// Check for data wool at location below the gold plate
if (addDataWool(locationMap, true, originLocation, x, y - 1, z))
continue;
}
else if (materialId == 148) // Iron Plate
{
// Check for data wool at location below the gold plate
if (addDataWool(locationMap, false, originLocation, x, y - 1, z))
continue;
}
else if (materialId == Material.SPONGE.getId())
{
if (addSpongeLocation(locationMap, originLocation, x, y + 1, z))
continue;
}
else if (materialId == 35)
{
// Check if this is a dataloc so we can skip setting the block
int aboveIndex = getIndex(x, y + 1, z);
if (hasIndex(aboveIndex))
{
if (Math.abs(_blocks[aboveIndex]) == Material.GOLD_PLATE.getId() || Math.abs(_blocks[aboveIndex]) == Material.IRON_PLATE.getId())
continue;
}
int belowIndex = getIndex(x, y - 1, z);
if (hasIndex(belowIndex))
{
if(Math.abs(_blocks[belowIndex]) == Material.SPONGE.getId())
continue;
}
}
UtilBlock.setQuick(originLocation.getWorld(), startX + x, startY + y, startZ + z, materialId, _blockData[index]);
}
}
}
return locationMap;
}
/**
* Checks the schematic location for x, y, z and adds the a Location to the DataLocationMap if it is a wool block
*
* @return true if a location was added to the DataLocationMap
*/
private boolean addDataWool(DataLocationMap map, boolean gold, Location origin, int x, int y, int z)
{
int index = getIndex(x, y, z);
if (hasIndex(index))
{
int materialId = Math.abs(_blocks[index]);
if (materialId == 35) // WOOL
{
byte data = _blockData[index];
DyeColor color = DyeColor.getByWoolData(data);
if (color != null)
{
if (gold)
{
map.addGoldLocation(color, origin.clone().add(x, y, z));
}
else
{
map.addIronLocation(color, origin.clone().add(x, y, z));
}
return true;
}
}
}
return false;
}
private boolean addSpongeLocation(DataLocationMap map, Location origin, int x, int y, int z)
{
int index = getIndex(x, y, z);
if (hasIndex(index))
{
int materialId = Math.abs(_blocks[index]);
if (materialId == 35) // WOOL
{
byte data = _blockData[index];
DyeColor color = DyeColor.getByWoolData(data);
if (color != null)
{
map.addSpongeLocation(color, origin.clone().add(x, y - 1, z));
return true;
}
}
}
return false;
}
public int getSize()
@ -61,6 +152,11 @@ public class Schematic
return y * _width * _length + z * _width + x;
}
public boolean hasIndex(int index)
{
return index < _blocks.length;
}
public short getBlock(int x, int y, int z)
{
return _blocks[getIndex(x, y, z)];
@ -99,6 +195,6 @@ public class Schematic
@Override
public String toString()
{
return String.format("width: %d, length: %d, height: %d, blockLength: %d, blockDataLength: %d", _width, _length, _height, _blocks.length, _blockData.length);
return String.format("Schematic [width: %d, length: %d, height: %d, blockLength: %d, blockDataLength: %d]", _width, _length, _height, _blocks.length, _blockData.length);
}
}

View File

@ -0,0 +1,52 @@
package mineplex.core.common.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class PlayerRecieveBroadcastEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private Player _player;
private String _message;
private boolean _cancelled;
public PlayerRecieveBroadcastEvent(Player player, String message)
{
_player = player;
_message = message;
}
public Player getPlayer()
{
return _player;
}
public boolean isCancelled()
{
return _cancelled;
}
public String getMessage()
{
return _message;
}
public void setCancelled(boolean cancelled)
{
_cancelled = cancelled;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -0,0 +1,7 @@
package mineplex.core.common.function;
@FunctionalInterface
public interface Result<T>
{
public void Get(T result);
}

View File

@ -0,0 +1,15 @@
package mineplex.core.common.generator;
import java.util.Random;
import org.bukkit.World;
import org.bukkit.generator.ChunkGenerator;
public class VoidGenerator extends ChunkGenerator
{
@Override
public ChunkData generateChunkData(World world, Random random, int x, int z, BiomeGrid biome)
{
return createChunkData(world);
}
}

View File

@ -19,7 +19,6 @@ import net.minecraft.server.v1_8_R3.NBTTagString;
public class SkinData
{
private static long _nameCount = -99999999999999L;
public final static SkinData MOOSHROOM = new SkinData("eyJ0aW1lc3RhbXAiOjE0NDk4NzI0OTU0MTcsInByb2ZpbGVJZCI6ImE5ZDBjMDcyYmYxOTQwYTFhMTkzNjhkMDlkNTAwMjZlIiwicHJvZmlsZU5hbWUiOiJTcGlyaXR1c1NhbmN0dXMiLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzIxOWJlYTU0Y2FkN2Q1OGFiNWRhNDA2YjBhOTJhYjNhODI0MjI1MjY2Nzc3ZTUzNGI3ZGI2YzM3MmRkZmY3ZiJ9fX0=","UoSif81+UyvkcaanU8KAMYBpw9mefAmWehE2liDUFvk+y0X/9NovsxTYVpIDCltTSpLW3sNgamvbj4Ybs+s6DbudPiEkvh0ER7Bv2v29UJw7RzIdr6/1g548X12zcnh5iPGz/P75uNRnSfTFQx0ed8P/GNkPIjWpDuJFxEj6KcPzrCAGMx+BVw1VwryBIYf9cCDHky8z0bxR89rjiIvPTBFI6MRhqI3vgpEBTySHDS+Ki0Hwl5oa3PwS6+jgYx/4RSfFsb+BawcvDk2Xpkt5UimvqZ5BceYLIfCt4KbShYipgLXLfYUZrntjPemd3SxthjxUuA07i44UxRdiC8uqy1twLT/HUS28gpk68lA/id9tKFwu1CUzshgcmvQPt3ghtNViNziR/2t7D/+5D31Vzmhf6n7Pnpdirt/5frMi2BKMMs7pLa0EF8CrrDU7QCwPav+EZVGFvVZbxSkCDq+n3IQ3PUWSCzy6KPxpdOlUjD0pAfLoiNj0P8u4+puQtID76r/St8ExchYl2dodUImu1ZETWeFUClF3ZGat62evx8uRQEI2W4dsVwj40VUfjaAuvyDzuouaKTrCzJXLQZZjR1B8URvuK61fGX0nhW607mEi6DE+nxP2ZoBrROEX4e37Ap6+TQn9Q8tKDPdcxtwSOpPO4Qkncjn/mGtP9lZU/DQ=");
@ -33,6 +32,9 @@ public class SkinData
public final static SkinData LOVESTRUCK = new SkinData("eyJ0aW1lc3RhbXAiOjE0NTUxMTAyNDMyNjUsInByb2ZpbGVJZCI6ImE5ZDBjMDcyYmYxOTQwYTFhMTkzNjhkMDlkNTAwMjZlIiwicHJvZmlsZU5hbWUiOiJTcGlyaXR1c1NhbmN0dXMiLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzczMTY5YWQwZTUyYjM1N2NiZGYxZDU0NGVkNGNmOWJmOTI4YmI0ZWNlMDhlY2YyY2M0YmYyYTlmMjJhODI4MmQifX19", "LL4RiSKQoTZamRQ4QG6izpvhgFu5gAqW4eZxcWAihk7GkhyxifpJpBTOzKrj5hH9fCUfYkkijVWUYTEcVSVRWhocp2HXW59TbKfxOeMvHU5vTMwgpwm6PnUfwuTsRPSLC7WMnEreI3cjOxPVmXbTniOSd+o8j4oOIgwFS+VLPiYLh5Jl16i5I/9ekafl3/x41NISKWl62geqO2jPWehlk+r3soiRJsxaKw20T61GSNLu19iA96Rz2T2tUHB4opm8hbLgoiNL2g1affTjq3cZPLHH4JWF3vPhqLB5uw6xb55vFLM/PP0YiEMIi7YZOfRGeaPp7uXbXgHeew+7PG9UDVMfqbwANQY4ndECijZoei54+xX3MDXkMhQsc5S+FLnGH6e4d008v81eEOyzJUPkKbGxLCBgTUb1s4IHwomCr30twPlo1IuFBOY1qeVvZUfAfPJsREuj5q/oCAoYFgupmb3ClWECnwwaH/T4wdHjfSBHoZQdLzcgDOAl0b5EXxWmYBECqk/WA4TrYIDVGdwkqjI0RkPLUoxTj6135KO+F7P7PwhU9WBGeW8hHq918DBL0fjQVHjrzvolTqwmw6nySSePnPOxFX/iwtHWzpBa9V6kUNNN+V7OGTgRr0H/yUxB+oq1F8UBqyqT4YpqxXCSD36derF/Xt5IdpTbEbGBpm0=");
public final static SkinData SECRET_PACKAGE = new SkinData("eyJ0aW1lc3RhbXAiOjE0NTUxMTAzNzE3OTIsInByb2ZpbGVJZCI6ImE5ZDBjMDcyYmYxOTQwYTFhMTkzNjhkMDlkNTAwMjZlIiwicHJvZmlsZU5hbWUiOiJTcGlyaXR1c1NhbmN0dXMiLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2QyNWI5YTRjOWRhOThkZTliZmIwZDNjOWI1M2MzMjJhMjgxN2IyMTMxOTQzY2E1YWM2NTBjZThmMzEzZjdhIn19fQ==", "Wb5T0Zhp1RVt78V/i8dYrwZCNT0xZIRe3LvL0bngH498f8Jrl43KHgTi4f299zE9giVynkTogGhJ8inq/xqFCRctl7Nn9L3LVu78uQwt+fs+o+kw/Qc+lggFSjEIc+fc13AZndpec0Df46Kh/OGD7NXbtbLb6TE/0dU2RwQlvZrZ/QHYJb8OJ6aUcnHvAZim8NUtG/nlZtSClepHVSuKdNnfzoF9rFVFA/x4jTr6mZYPZ33YgQd2oTAPk+qE3iN+0InjZQNs2YLoKFmFrgzn+tGvNApC0siF0HEZGQCFIwJOtnBsasGoxujIrln/ZdOil+5ac4VWInXr8lKgY0Q3Ocy8/0cJl+E/XqB+ztG29zhB8B1zdHBfJr+MgeSIqBCPx4SCtY6r7gnMlQYG+uVx5NP3S5aJW/cEfDyXmpCykIcBPzeErnKC0SiAqXkCVNjWJpX6qRWvWMXqS69w6ht6qHvEY2GxlZUb5AP+JgFlsl3hJDms6EPvM4zNL0Ko4oWIBzwYRQXiemrP9TGgyo0aL1RcQ0JgBFO2hSo37PK0YL3tUPgteJXzm21wu0TiZLkLCWSgMUfYfvVnhTa+xzod0xvfujpN6Y1DUTdcf8WS8TRYw2JigSkWrRW0fXPBCtTtQN5jiwM5/HrTpNLzg03J6SpfZ+rr8Rhq0S/8beQOMas=");
public final static SkinData CHISS = new SkinData("eyJ0aW1lc3RhbXAiOjE0NTk1NDI5NjgyNDEsInByb2ZpbGVJZCI6IjFkMmJmZTYxN2ViZDQ0NWRiYTdkODM1NGEwZmZkMWVhIiwicHJvZmlsZU5hbWUiOiJDaGlzcyIsInNpZ25hdHVyZVJlcXVpcmVkIjp0cnVlLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTg3MmNkMzRjY2IzMTIxYjRjNmEzOGFjM2JmOGVkM2UwMzk3YmQ2YTg4NDI4YjdhZmM2ZTUyNTI4NTVhMzQzIiwibWV0YWRhdGEiOnsibW9kZWwiOiJzbGltIn19fX0=", "hNTLRA2acZYx2dM90lnJN8FMK/ceD3+AxKNdD5FrXzxGtYL4C1Jr/vbTE0UosmwFP3wScNEW/fuDOjeZRjZHMJdvgDZMlMK/5KDhOY6sj/RS9RckztsgummSyjH/hdDn7TWWfhZLMbiia/K0VReI9eq2yD6zGQpvMlz5hB/5SX5YHWXvCah3TL4UzYSlSVDlwY/Q3sVuIZUr8m/LIXJwniJKLGo6tUgtiJd9eseOsbBpVjzCUtLD8A9WBe2/eODgmLfqEvXESIoDRG8vL2nPSXWma/YolYHIl32/i+ZxVD7dRRaXQFYSiLI24EtzX1pPhMjyaTLazP9abH43J6J31w02pKM7N/xTa62020L/YfRRKGT5lygEDb1NMoSpAjszPxah+Ra2/L+yUWEI8cMES6I4mIJ00tclPjWK01xhIn3tqg+y2gqsGHwPhu/7vmF5NirNfKFw0qciKNBfbCAF7ae+mkUKjmAPuvBUBqQb7BOcpNVWsCo/XvzmiZZYsf5P4Uwz8LqUK4uH6V/5dg7lY2Xg3+IUylsrDqLGFDI8iy/NdjIQMbuRadh4IDO6DcmxBri2Ax4JNBPBTnRezge8uq37MZcft/IXQgFWKB9RtidVEACaTOkRj27k+Ojnkki+j44k0wZB47hiXFUHMCHl3a0SVdQe15ZbVsQj/HAvAS0=");
public final static SkinData DEFEK7 = new SkinData("eyJ0aW1lc3RhbXAiOjE0NTk1NDI3ODkwNTksInByb2ZpbGVJZCI6Ijg5ZDQ2M2Y3MjNlYzQ3MGE4MjQ0NDU3ZjBjOGQ4NjFjIiwicHJvZmlsZU5hbWUiOiJkZWZlazciLCJzaWduYXR1cmVSZXF1aXJlZCI6dHJ1ZSwidGV4dHVyZXMiOnsiU0tJTiI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2JmYWNjOWM4ZjhlY2E1OWU0NTE4MTUxZmE4OGFiMDZjOTFmNjM3OTE2NzJmMTRlNGYzODY3YTI2OTVlN2NmYmYifSwiQ0FQRSI6eyJ1cmwiOiJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzIyYjljNWVhNzYzYzg2ZmM1Y2FlYTMzZDgyYjBmYTY1YTdjMjI4ZmQzMjFiYTU0NzY2ZWE5NWEzZDBiOTc5MyJ9fX0=", "jBoRvkhQXz+nap8yJJIZ+4HClMItWODumeSOYjXytP3WWKHK0UMq0xC/keXsnmvo89lMRdRbknPt2ZX5Flgyjgr4Rt0KtDvpL/hG4BUsTWryUZZMKxdd6DkZXYRtTogLUfHeDYIz+cZQ0aXGMtvX/ZYTXJfMi6FYbIHY/qEEDnWhDX5y+SPpaJaZByPsvzi+qbfcFGnJ6nqi9ccyZYnYpnI2IVBM/yO/VRXWHxfqvJ0VVvv5KsGmVbko2Jxo0SDCxUL2UTH2+eol53FxhkkC+m2geC14k1zsZQLHDF3BgAG9+kFJ4UEoYRKF2Gy1FxeDCJtjYNdrYR8fdaUKRMcpBgEs+ZGe2U9EVVS/ZcBCjB7S+1Ne2bPzPFzTQPuBoMgggo1xbxBmQ5NyhYo4gwgj/xjSLIhb+5h7ioN1URfSRcfYdVv6RRO9l/u9l09jEom8y/jGRviefpEr+/e9iAl5Dd/6nzQgosBQja3NSfqYZmyuet2eI9zu61CObDTpR6yaCbNgBe/lWofRfULdpJpgjb4UNTBom3q82FcCiOe02OekGPw4+YlilhICBhajF5JzN8FKAdqI1osDcX3KuJgikYIW3voNaOP5YN3GXgilJNdou20KFC8ICq68HglgX7/0rLrWKIEoswnINIM6HcJbQuXncVPwQhV6K34Hlt/Na60=");
private Property _skinProperty;
public SkinData(String value, String signature)

View File

@ -75,6 +75,8 @@ public class C
public static String chatAdminHead = "" + ChatColor.DARK_PURPLE;
public static String chatAdminBody = "" + ChatColor.LIGHT_PURPLE;
public static String cClansNether = "" + ChatColor.RED;
public static String listTitle = "" + ChatColor.WHITE;
public static String listValue = "" + ChatColor.YELLOW;
public static String listValueOn = "" + ChatColor.GREEN;

View File

@ -0,0 +1,31 @@
package mineplex.core.common.util;
public class EnclosedObject<T>
{
private T _value;
public EnclosedObject()
{
this((T) null);
}
public EnclosedObject(T t)
{
_value = t;
}
public T Get()
{
return _value;
}
public T Set(T value)
{
return _value = value;
}
public String toString()
{
return _value.toString();
}
}

View File

@ -48,7 +48,7 @@ public class F
{
return C.mElem + elem.toString() + ChatColor.RESET + C.mBody;
}
public static String name(String elem)
{
return C.mElem + elem + C.mBody;
@ -215,4 +215,9 @@ public class F
? "an" : "a";
}
public static String clansNether(String word)
{
return C.cClansNether + word + C.mBody;
}
}

View File

@ -7,7 +7,7 @@ import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileUtil
public class FileUtil
{
public static void DeleteFolder(File folder)
{

View File

@ -0,0 +1,27 @@
package mineplex.core.common.util;
import java.util.HashMap;
import java.util.Map;
public class MapBuilder<K, V>
{
private Map<K, V> _map;
public MapBuilder()
{
_map = new HashMap<>();
}
public MapBuilder<K, V> Put(K key, V value)
{
_map.put(key, value);
return this;
}
public Map<K, V> GetMap()
{
return _map;
}
}

View File

@ -5,11 +5,22 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class NautArrayList<Elem>
public class NautArrayList<Elem> implements Iterable<Elem>
{
private ArrayList<Elem> _wrappedArrayList = new ArrayList<Elem>();
public NautArrayList()
{
}
public NautArrayList(Elem[] elements)
{
UtilCollections.addAll(elements, _wrappedArrayList);
}
public boolean add(Elem elem)
{
return _wrappedArrayList.add(elem);
@ -129,4 +140,19 @@ public class NautArrayList<Elem>
{
return _wrappedArrayList.toArray();
}
public void forEach(Consumer<? super Elem> consumer)
{
_wrappedArrayList.forEach(consumer);
}
public Stream<Elem> stream()
{
return _wrappedArrayList.stream();
}
public List<Elem> getWrapped()
{
return _wrappedArrayList;
}
}

View File

@ -3,12 +3,26 @@ package mineplex.core.common.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import org.apache.commons.lang3.Validate;
import java.util.Set;
public class NautHashMap<KeyType, ValueType>
{
private HashMap<KeyType, ValueType> _wrappedHashMap = new HashMap<KeyType, ValueType>();
public NautHashMap()
{
}
public NautHashMap(KeyType[] keys, ValueType[] values)
{
Validate.isTrue(keys.length == values.length, "Keys array and values array must be the same size when making a Map");
UtilCollections.loop(0, keys.length, i -> _wrappedHashMap.put(keys[i.intValue()], values[i.intValue()]));
}
public boolean containsKey(KeyType key)
{
return _wrappedHashMap.containsKey(key);

View File

@ -1,33 +0,0 @@
package mineplex.core.common.util;
public class NonFinalInteger
{
private int _value;
public NonFinalInteger()
{
this(0);
}
public NonFinalInteger(int value)
{
_value = value;
}
public NonFinalInteger add(int value)
{
_value += value;
return this;
}
public NonFinalInteger subtract(int value)
{
_value -= value;
return this;
}
public int get()
{
return _value;
}
}

View File

@ -0,0 +1,28 @@
package mineplex.core.common.util;
public class NumberFloater
{
private double _min;
private double _max;
private double _modifyPerCall;
private double _cur;
private boolean _up;
public NumberFloater(double min, double max, double modify)
{
_min = min;
_max = max;
_modifyPerCall = modify;
}
public double pulse()
{
if (_up && (_cur = UtilMath.clamp(_cur += _modifyPerCall, _min, _max)) >= _max)
_up = false;
else if ((_cur = UtilMath.clamp(_cur -= _modifyPerCall, _min, _max)) <= _min)
_up = true;
return _cur;
}
}

View File

@ -1,42 +0,0 @@
package mineplex.core.common.util;
public class NumericalPulser
{
private double _min;
private double _max;
private double _modifyPerCall;
private double _cur;
private boolean _up;
public NumericalPulser(double min, double max, double modify)
{
_min = min;
_max = max;
_modifyPerCall = modify;
}
public double pulse()
{
if (_up)
{
_cur = UtilMath.clamp(_cur += _modifyPerCall, _min, _max);
if (_cur >= _max)
{
_up = false;
}
}
else
{
_cur = UtilMath.clamp(_cur -= _modifyPerCall, _min, _max);
if (_cur <= _min)
{
_up = true;
}
}
return _cur;
}
}

View File

@ -88,7 +88,7 @@ public class ProfileLoader
}
catch (Exception e)
{
; // Failed to load skin
e.printStackTrace();
}
}

View File

@ -1,5 +1,7 @@
package mineplex.core.common.util;
import org.bukkit.util.Vector;
public class RGBData
{
private double _red;
@ -50,4 +52,19 @@ public class RGBData
+ "green=" + (int) (_green * 255) + ", "
+ "blue=" + (int) (_blue * 255) + "]";
}
public Vector ToVector()
{
return new Vector(Math.max(0.001, _red), _green, _blue);
}
public RGBData Darken()
{
return new RGBData(getFullRed() - 25, getFullGreen() - 25, getFullBlue() - 25);
}
public RGBData Lighten()
{
return new RGBData(getFullRed() + 25, getFullGreen() + 25, getFullBlue() + 25);
}
}

View File

@ -2,10 +2,14 @@ package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Stream;
import org.bukkit.Location;
import org.bukkit.block.Block;
@ -167,6 +171,34 @@ public class UtilAlg
return element;
}
public static List<Block> getBox(Block cornerA, Block cornerB)
{
if (cornerA == null || cornerB == null || (cornerA.getWorld() != cornerB.getWorld()))
return Collections.emptyList();
ArrayList<Block> list = new ArrayList<>();
int minX = Math.min(cornerA.getX(), cornerB.getX());
int minY = Math.min(cornerA.getY(), cornerB.getY());
int minZ = Math.min(cornerA.getZ(), cornerB.getZ());
int maxX = Math.max(cornerA.getX(), cornerB.getX());
int maxY = Math.max(cornerA.getY(), cornerB.getY());
int maxZ = Math.max(cornerA.getZ(), cornerB.getZ());
for (int x = minX; x <= maxX; x++)
{
for (int y = minY; y <= maxY; y++)
{
for (int z = minZ; z <= maxZ; z++)
{
list.add(cornerA.getWorld().getBlockAt(x, y, z));
}
}
}
return list;
}
public static boolean inBoundingBox(Location loc, Location cornerA, Location cornerB)
{
if (loc.getX() <= Math.min(cornerA.getX(), cornerB.getX())) return false;
@ -218,7 +250,7 @@ public class UtilAlg
return cross(vec, getRight(vec));
}
public static Location getAverageLocation(ArrayList<Location> locs)
public static Location getAverageLocation(List<Location> locs)
{
if (locs.isEmpty())
return null;
@ -236,8 +268,27 @@ public class UtilAlg
return vec.toLocation(locs.get(0).getWorld());
}
public static Location getAverageBlockLocation(List<Block> locs)
{
if (locs.isEmpty())
return null;
Vector vec = new Vector(0,0,0);
double amount = 0;
for (Block loc : locs)
{
vec.add(loc.getLocation().toVector());
amount++;
}
vec.multiply(1d/amount);
return vec.toLocation(locs.get(0).getWorld());
}
public static Vector getAverageBump(Location source, ArrayList<Location> locs)
public static Vector getAverageBump(Location source, List<Location> locs)
{
if (locs.isEmpty())
return null;
@ -550,4 +601,25 @@ public class UtilAlg
return new AxisAlignedBB(a.getX(), a.getY(), a.getZ(), b.getX(), b.getY(), b.getZ());
}
public static Location moveForward(Location location, double strength, float yaw, boolean reverse)
{
double x = location.getX();
double z = location.getZ();
double rad = Math.toRadians(yaw);
x = reverse ? (x + strength * Math.sin(rad)) : (x - strength * Math.sin(rad));
z = reverse ? (z - strength * Math.cos(rad)) : (z + strength * Math.cos(rad));
return new Location(location.getWorld(), x, location.getY(), z, location.getYaw(), location.getPitch());
}
public static Location getRandomLocation(Location center, int radius)
{
Random r = new Random();
int x = r.nextInt(radius * 2) - radius;
int y = r.nextInt(radius * 2) - radius;
int z = r.nextInt(radius * 2) - radius;
return center.clone().add(x, y, z);
}
}

View File

@ -3,6 +3,7 @@ package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Queue;
import org.bukkit.Location;
import org.bukkit.Material;
@ -30,6 +31,7 @@ import org.bukkit.material.Bed;
import net.minecraft.server.v1_8_R3.BlockPosition;
import net.minecraft.server.v1_8_R3.Blocks;
import net.minecraft.server.v1_8_R3.EnumDirection;
import net.minecraft.server.v1_8_R3.IBlockData;
import net.minecraft.server.v1_8_R3.Item;
import net.minecraft.server.v1_8_R3.MathHelper;
import net.minecraft.server.v1_8_R3.MinecraftKey;
@ -467,7 +469,12 @@ public class UtilBlock
public static Block getHighest(World world, Location location)
{
return getHighest(world, location.getBlockX(), location.getBlockZ(), null);
return getHighest(world, location.getBlockX(), location.getBlockZ());
}
public static Block getHighest(World world, Block block)
{
return getHighest(world, block.getLocation());
}
public static Block getHighest(World world, int x, int z, HashSet<Material> ignore)
@ -1423,4 +1430,54 @@ public class UtilBlock
return itemStacks;
}
public static Location nearestFloor(Location location)
{
if (!UtilItem.isBoundless(location.getBlock().getType()))
{
return location.clone();
}
Location gr = location.clone();
while (UtilItem.isBoundless(gr.getBlock().getType()) && gr.getY() > 0)
{
gr.subtract(0, 0.5, 0);
}
return gr.getBlock().getLocation();
}
public static boolean setSilent(Block block, Material type)
{
return setSilent(block, type, (byte) 0);
}
/**
* Sets block data without causing a block update.
*/
public static boolean setSilent(Block block, Material type, byte data)
{
BlockState state = block.getState();
state.setType(type);
state.setRawData(data);
return state.update(false, false);
}
public static void setQuick(World world, int x, int y, int z, int type, byte data)
{
int cx = x >> 4;
int cz = z >> 4;
if (!world.isChunkLoaded(cx, cz))
{
world.loadChunk(cx, cz, true);
}
net.minecraft.server.v1_8_R3.Chunk chunk = ((CraftWorld) world).getHandle().getChunkAt(x >> 4, z >> 4);
BlockPosition pos = new BlockPosition(x, y, z);
IBlockData ibd = net.minecraft.server.v1_8_R3.Block.getById(type).fromLegacyData(data);
chunk.a(pos, ibd);
}
}

View File

@ -0,0 +1,278 @@
package mineplex.core.common.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import com.google.common.collect.Lists;
public class UtilCollections
{
public static Random Random = new Random();
@SafeVarargs
public static <E> NautArrayList<E> newNautList(E... elements)
{
return new NautArrayList<E>(elements);
}
public static <E> NautArrayList<E> newNautList()
{
return new NautArrayList<E>();
}
public static <K, V> NautHashMap<K, V> newNautMap(K[] keys, V[] values)
{
return new NautHashMap<K, V>(keys, values);
}
public static <K, V> NautHashMap<K, V> newNautMap()
{
return new NautHashMap<K, V>();
}
public static <T> T getLast(List<T> list)
{
return list.isEmpty() ? null : list.get(list.size() - 1);
}
public static <T> T getFirst(List<T> list)
{
return list.isEmpty() ? null : list.get(0);
}
public static <T> T getLast(NautArrayList<T> list)
{
return list.isEmpty() ? null : list.get(list.size() - 1);
}
public static <T> T getFirst(NautArrayList<T> list)
{
return list.isEmpty() ? null : list.get(0);
}
public static <E> void forEach(E[] elements, Function<E, E> filter, Consumer<E> consumer)
{
for (int i = 0; i < elements.length; i++)
{
consumer.accept(filter.apply(elements[i]));
}
}
public static <E> void forEach(E[] elements, Consumer<E> consumer)
{
for (int i = 0; i < elements.length; i++)
{
consumer.accept(elements[i]);
}
}
public static <E> void forEach(E[] elements, BiConsumer<Integer, E> consumer)
{
for (int i = 0; i < elements.length; i++)
{
consumer.accept(Integer.valueOf(i), elements[i]);
}
}
public static <E> void addAll(E[] elements, Collection<E> collection)
{
forEach(elements, collection::add);
}
public static void loop(int min, int max, Consumer<Integer> consumer)
{
for (int i = min; i < max; i++)
{
consumer.accept(Integer.valueOf(i));
}
}
public static byte[] ensureSize(byte[] array, int size)
{
if (array.length <= size)
{
return array;
}
return Arrays.copyOf(array, size);
}
public static boolean[] ensureSize(boolean[] array, int size)
{
if (array.length <= size)
{
return array;
}
return Arrays.copyOf(array, size);
}
public static int[] ensureSize(int[] array, int size)
{
if (array.length <= size)
{
return array;
}
return Arrays.copyOf(array, size);
}
public static long[] ensureSize(long[] array, int size)
{
if (array.length <= size)
{
return array;
}
return Arrays.copyOf(array, size);
}
public static short[] ensureSize(short[] array, int size)
{
if (array.length <= size)
{
return array;
}
return Arrays.copyOf(array, size);
}
public static char[] ensureSize(char[] array, int size)
{
if (array.length <= size)
{
return array;
}
return Arrays.copyOf(array, size);
}
public static float[] ensureSize(float[] array, int size)
{
if (array.length <= size)
{
return array;
}
return Arrays.copyOf(array, size);
}
public static double[] ensureSize(double[] array, int size)
{
if (array.length <= size)
{
return array;
}
return Arrays.copyOf(array, size);
}
public static <T> T[] ensureSize(T[] array, int size)
{
if (array.length <= size)
{
return array;
}
return Arrays.copyOf(array, size);
}
public static byte random(byte[] array)
{
return array[Random.nextInt(array.length)];
}
public static short random(short[] array)
{
return array[Random.nextInt(array.length)];
}
public static char random(char[] array)
{
return array[Random.nextInt(array.length)];
}
public static boolean random(boolean[] array)
{
return array[Random.nextInt(array.length)];
}
public static int random(int[] array)
{
return array[Random.nextInt(array.length)];
}
public static long random(long[] array)
{
return array[Random.nextInt(array.length)];
}
public static double random(double[] array)
{
return array[Random.nextInt(array.length)];
}
public static float random(float[] array)
{
return array[Random.nextInt(array.length)];
}
public static <T> T random(T[] array)
{
return array[Random.nextInt(array.length)];
}
public static <T> List<? extends T> toList(T[] array)
{
return Lists.newArrayList(array);
}
public static <T1, T2> boolean equal(T1[] array1, T2[] array2)
{
return Arrays.equals(array1, array2);
}
public static <X> void ForEach(List<X> list, Consumer<X> consumer)
{
Iterator<X> iterator = list.iterator();
while (iterator.hasNext())
{
consumer.accept(iterator.next());
}
}
@SafeVarargs
public static <X> List<? extends X> newList(X... elements)
{
return toList(elements);
}
public static <X> String combine(X[] data, String delimiter)
{
StringBuilder total = new StringBuilder();
int loops = 0;
for (X x : data)
{
if (delimiter != null && loops != 0)
{
total.append(delimiter);
}
total.append(x.toString());
loops++;
}
return total.toString();
}
}

View File

@ -10,6 +10,8 @@ public class UtilColor
public static final RGBData RgbRed = hexToRgb(0xee0100);
public static final RGBData RgbGold = hexToRgb(0xffd014);
public static final RGBData RgbLightBlue = hexToRgb(0x61fff7);
public static final RGBData RgbLightRed = hexToRgb(0xeb1c1c);
public static final RGBData RgbPurple = hexToRgb(0x9c17a3);
public static byte chatColorToClayData(ChatColor chatColor)
{
@ -84,4 +86,9 @@ public class UtilColor
{
return (red << 16 | green << 8 | blue);
}
public static RGBData rgb(int r, int g, int b)
{
return new RGBData(r, g, b);
}
}

View File

@ -5,24 +5,6 @@ import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.server.v1_8_R3.AxisAlignedBB;
import net.minecraft.server.v1_8_R3.EntityBat;
import net.minecraft.server.v1_8_R3.EntityCreature;
import net.minecraft.server.v1_8_R3.EntityEnderDragon;
import net.minecraft.server.v1_8_R3.EntityHuman;
import net.minecraft.server.v1_8_R3.EntityInsentient;
import net.minecraft.server.v1_8_R3.EntityLiving;
import net.minecraft.server.v1_8_R3.EntityTrackerEntry;
import net.minecraft.server.v1_8_R3.NavigationAbstract;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntity;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityHeadRotation;
import net.minecraft.server.v1_8_R3.PathfinderGoal;
import net.minecraft.server.v1_8_R3.PathfinderGoalLookAtPlayer;
import net.minecraft.server.v1_8_R3.PathfinderGoalMoveTowardsRestriction;
import net.minecraft.server.v1_8_R3.PathfinderGoalRandomLookaround;
import net.minecraft.server.v1_8_R3.PathfinderGoalSelector;
import net.minecraft.server.v1_8_R3.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
@ -40,8 +22,29 @@ import org.bukkit.entity.EntityType;
import org.bukkit.entity.Giant;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.util.Vector;
import net.minecraft.server.v1_8_R3.AxisAlignedBB;
import net.minecraft.server.v1_8_R3.EntityBat;
import net.minecraft.server.v1_8_R3.EntityCreature;
import net.minecraft.server.v1_8_R3.EntityEnderDragon;
import net.minecraft.server.v1_8_R3.EntityHuman;
import net.minecraft.server.v1_8_R3.EntityInsentient;
import net.minecraft.server.v1_8_R3.EntityLiving;
import net.minecraft.server.v1_8_R3.EntityTrackerEntry;
import net.minecraft.server.v1_8_R3.NavigationAbstract;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntity;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityHeadRotation;
import net.minecraft.server.v1_8_R3.PathfinderGoal;
import net.minecraft.server.v1_8_R3.PathfinderGoalLookAtPlayer;
import net.minecraft.server.v1_8_R3.PathfinderGoalMoveTowardsRestriction;
import net.minecraft.server.v1_8_R3.PathfinderGoalRandomLookaround;
import net.minecraft.server.v1_8_R3.PathfinderGoalSelector;
import net.minecraft.server.v1_8_R3.WorldServer;
public class UtilEnt
{
@ -163,7 +166,7 @@ public class UtilEnt
if (entity instanceof CraftCreature)
{
EntityCreature creature = ((CraftCreature)entity).getHandle();
EntityCreature creature = ((CraftCreature) entity).getHandle();
if (_bsRestrictionGoal == null)
{
@ -176,26 +179,26 @@ public class UtilEnt
if (((CraftEntity)entity).getHandle() instanceof EntityInsentient)
{
EntityInsentient creature = (EntityInsentient)((CraftEntity)entity).getHandle();
EntityInsentient creature = (EntityInsentient) ((CraftEntity) entity).getHandle();
creature.setVegetated(true);
creature.setSilent(mute);
((List) _pathfinderBList.get(((PathfinderGoalSelector)_goalSelector.get(creature)))).clear();
((List)_pathfinderCList.get(((PathfinderGoalSelector)_goalSelector.get(creature)))).clear();
((List<?>) _pathfinderBList.get(((PathfinderGoalSelector) _goalSelector.get(creature)))).clear();
((List<?>) _pathfinderCList.get(((PathfinderGoalSelector) _goalSelector.get(creature)))).clear();
((List)_pathfinderBList.get(((PathfinderGoalSelector)_targetSelector.get(creature)))).clear();
((List)_pathfinderCList.get(((PathfinderGoalSelector)_targetSelector.get(creature)))).clear();
((List<?>) _pathfinderBList.get(((PathfinderGoalSelector) _targetSelector.get(creature)))).clear();
((List<?>) _pathfinderCList.get(((PathfinderGoalSelector) _targetSelector.get(creature)))).clear();
}
if (((CraftEntity)entity).getHandle() instanceof EntityBat)
{
((EntityBat)((CraftEntity)entity).getHandle()).setVegetated(true);
((EntityBat) ((CraftEntity) entity).getHandle()).setVegetated(true);
}
if (((CraftEntity)entity).getHandle() instanceof EntityEnderDragon)
if (((CraftEntity) entity).getHandle() instanceof EntityEnderDragon)
{
EntityEnderDragon creature = (EntityEnderDragon)((CraftEntity)entity).getHandle();
EntityEnderDragon creature = (EntityEnderDragon) ((CraftEntity) entity).getHandle();
creature.setVegetated(true);
}
@ -255,6 +258,34 @@ public class UtilEnt
}
}
public static void Rotate(LivingEntity entity, float yaw, float pitch)
{
EntityLiving handle = ((CraftLivingEntity) entity).getHandle();
while (yaw < -180.0F) yaw += 360.0F;
while (yaw >= 180.0F) yaw -= 360.0F;
handle.yaw = yaw;
handle.aK = yaw;
handle.aI = yaw;
handle.aL = yaw;
handle.pitch = pitch;
}
public static void LookAt(LivingEntity entity, Location location)
{
if (!(entity.getWorld().equals(location.getWorld())))
return;
Vector dir = entity.getEyeLocation().toVector().subtract(location.toVector()).normalize();
Location loc = entity.getEyeLocation().clone();
loc.setYaw(180 - (float) Math.toDegrees(Math.atan2(dir.getX(), dir.getZ())));
loc.setPitch(90 - (float) Math.toDegrees(Math.acos(dir.getY())));
Rotate(entity, loc.getYaw(), loc.getPitch());
}
public static void populate()
{
if (creatureMap.isEmpty())
@ -442,7 +473,7 @@ public class UtilEnt
if (offset < dR)
{
ents.put(ent, 1 - (offset/dR));
ents.put(ent, Double.valueOf(1 - (offset/dR)));
continue;
}
@ -451,7 +482,7 @@ public class UtilEnt
if (offset < dR)
{
ents.put(ent, 1 - (offset/dR));
ents.put(ent, Double.valueOf(1 - (offset/dR)));
continue;
}
}
@ -473,7 +504,7 @@ public class UtilEnt
if (offset < dR)
{
ents.put(cur, 1 - (offset/dR));
ents.put(cur, Double.valueOf(1 - (offset/dR)));
continue;
}
}
@ -775,7 +806,7 @@ public class UtilEnt
field.setAccessible(true);
int entityId = field.getInt(null);
if (modifynumber) {
field.set(null, entityId+1);
field.set(null, Integer.valueOf(entityId + 1));
}
return entityId;
}
@ -815,9 +846,37 @@ public class UtilEnt
((EntityInsentient)e.getHandle()).k(!ai);
}
}
public static double getBlockSizeOfSlime(int size)
{
return .51 * ((double) size);
}
public static boolean inWater(LivingEntity ent)
{
return ent.getLocation().getBlock().getTypeId() == 8 || ent.getLocation().getBlock().getTypeId() == 9;
}
public static void SetMetadata(Entity entity, String key, Object value)
{
entity.setMetadata(key, new FixedMetadataValue(UtilServer.getPlugin(), value));
}
// Nicer than doing entity.getMetadata(key).get(0);
public static Object GetMetadata(Entity entity, String key)
{
if (!entity.hasMetadata(key))
{
return null;
}
return entity.getMetadata(key).get(0);
}
public static void SetItemInHand(LivingEntity entity, ItemStack item)
{
EntityEquipment equipment = entity.getEquipment();
equipment.setItemInHand(item);
}
}

View File

@ -1,310 +1,53 @@
package mineplex.core.common.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class UtilFile
{
public static void writePlainFile(File file, String text) throws FileNotFoundException
{
PrintWriter writer = new PrintWriter(file);
writer.print(text);
writer.close();
}
/**
* Will read the specified file, and return the contents, or a null value,
* if an exception is thrown. Will handle all exceptions, and simply ignore
* them and return null. No stack trace printed or anything.
*/
public static String readIgnoreErrors(File file)
public static String read(File file)
{
try
{
return readToStr(file);
return new String(readBytes(file));
}
catch (IOException exception)
catch (IOException e)
{
return null;
}
}
public static String readToStr(File file) throws IOException
{
return new String(readAllBytes(file));
}
public static byte[] readAllBytes(File file) throws IOException
{
return Files.readAllBytes(Paths.get(file.toURI()));
}
public static void writePlainFile(String file, String text) throws FileNotFoundException
{
writePlainFile(new File(file), text);
}
/**
* Will read the specified file, and return the contents, or a null value,
* if an exception is thrown. Will handle all exceptions, and simply ignore
* them and return null. No stack trace printed or anything.
* @param file
* @return
* @throws IOException
*/
public static String readIgnoreErrors(String file)
public static byte[] readBytes(File file) throws IOException
{
return readIgnoreErrors(new File(file));
}
public static String readToStr(String file) throws IOException
{
return readToStr(new File(file));
}
public static byte[] readAllBytes(String file) throws IOException
{
return readAllBytes(new File(file));
}
public static void writeDataFile(File file, DataFileChunk... chunks) throws IOException
{
DataOutputStream stream = new DataOutputStream(new FileOutputStream(file));
for (DataFileChunk chunk : chunks)
FileInputStream stream = new FileInputStream(file);
byte[] bytes = new byte[stream.available() /* estimated bytes available */];
int pointer = 0;
while (true)
{
chunk.writeTo(stream);
int read = stream.read();
if (read == -1)
{
break;
}
bytes = UtilCollections.ensureSize(bytes, bytes.length + 1);
bytes[pointer] = (byte) read;
++pointer;
}
stream.close();
return bytes;
}
public static DataFileReader beginReading(String file) throws FileNotFoundException
{
return beginReading(new File(file));
}
public static DataFileReader beginReading(File file) throws FileNotFoundException
{
return new DataFileReader(file);
}
public static void writeDataFile(String file, DataFileChunk... chunks) throws IOException
{
writeDataFile(new File(file), chunks);
}
public static class DataFileChunk
{
private ChunkType _type;
private Object _value;
public DataFileChunk(ChunkType type, Object value)
{
if (type == null)
{
throw new RuntimeException("ChunkType can NOT be null.");
}
_type = type;
if (!_type.isValid(value))
{
throw new RuntimeException("Invalid value provided for the specified ChunkType.");
}
_value = value;
}
public void writeTo(DataOutputStream stream) throws IOException
{
_type.writeTo(stream, _value);
}
}
public static enum ChunkType
{
STRING(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
String str = (String) value;
INTEGER.writeTo(stream, str.length());
for (char b : str.toCharArray())
{
CHAR.writeTo(stream, b);
}
}
public boolean isValid(Object value)
{
return value.getClass().equals(String.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
int length = (int) INTEGER.readFrom(stream);
StringBuilder string = new StringBuilder();
for (int i = 0; i < length; i++)
{
string.append(CHAR.readFrom(stream));
}
return string.toString();
}
}),
DOUBLE(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
double number = (double) value;
stream.writeDouble(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Double.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readDouble();
}
}),
INTEGER(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
int number = (int) value;
stream.writeInt(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Integer.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readInt();
}
}),
BYTE(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
byte number = (byte) value;
stream.writeByte(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Byte.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readByte();
}
}),
CHAR(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
char number = (char) value;
stream.writeChar(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Character.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readChar();
}
}),
LONG(new ChunkImpl()
{
public void writeTo(DataOutputStream stream, Object value) throws IOException
{
long number = (long) value;
stream.writeLong(number);
}
public boolean isValid(Object value)
{
return value.getClass().equals(Long.class);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return stream.readLong();
}
});
private ChunkImpl _impl;
ChunkType(ChunkImpl impl)
{
_impl = impl;
}
protected void writeTo(DataOutputStream stream, Object value) throws IOException
{
_impl.writeTo(stream, value);
}
protected boolean isValid(Object value)
{
return value != null && _impl.isValid(value);
}
public Object readFrom(DataInputStream stream) throws IOException
{
return _impl.readFrom(stream);
}
}
public static class DataFileReader
{
private DataInputStream _stream;
public DataFileReader(File file) throws FileNotFoundException
{
_stream = new DataInputStream(new FileInputStream(file));
}
public Object readChunk(ChunkType type) throws IOException
{
return type.readFrom(_stream);
}
public void close() throws IOException
{
_stream.close();
}
}
protected interface ChunkImpl
{
void writeTo(DataOutputStream stream, Object value) throws IOException;
Object readFrom(DataInputStream stream) throws IOException;
boolean isValid(Object value);
}
}

View File

@ -74,10 +74,10 @@ public class UtilFirework
public static void packetPlayFirework(Player player, Location loc, Type type, Color color, boolean flicker, boolean trail)
{
Firework firework = (Firework) loc.getWorld().spawn(loc, Firework.class);
Firework firework = loc.getWorld().spawn(loc, Firework.class);
FireworkEffect effect = FireworkEffect.builder().flicker(flicker).withColor(color).with(type).trail(trail).build();
FireworkMeta data = (FireworkMeta) firework.getFireworkMeta();
FireworkMeta data = firework.getFireworkMeta();
data.clearEffects();
data.setPower(1);
data.addEffect(effect);
@ -98,4 +98,14 @@ public class UtilFirework
UtilPlayer.sendPacket(viewing, packet);
}
}
public static void spawnRandomFirework(Location location)
{
playFirework(location,
Type.values()[UtilMath.r(Type.values().length)],
Color.fromRGB(UtilMath.r(256), UtilMath.r(256), UtilMath.r(256)),
UtilMath.random.nextBoolean(),
UtilMath.random.nextBoolean()
);
}
}

View File

@ -396,4 +396,61 @@ public class UtilInv
return amount;
}
public static ItemStack decrement(ItemStack item)
{
ItemStack newItem;
if (item.getAmount() == 1)
{
newItem = null;
}
else
{
newItem = item;
newItem.setAmount(newItem.getAmount() - 1);
}
return newItem;
}
public static boolean HasSpace(Player player, Material material, int amount)
{
int slotsFree = 0;
for (int slot = 0; slot < player.getInventory().getSize(); slot++)
{
if (player.getInventory().getItem(slot) == null)
{
slotsFree++;
if (slotsFree >= amount / 64)
{
return true;
}
}
else if (player.getInventory().getItem(slot).getType().equals(material) && amount <= (64 - player.getInventory().getItem(slot).getAmount()))
{
return true;
}
}
return false;
}
public static void give(Player player, Material material)
{
give(player, material, 1);
}
public static void give(Player player, Material material, int amount)
{
give(player, material, amount, (byte) 0);
}
public static void give(Player shooter, Material material, int amount, byte data)
{
shooter.getInventory().addItem(new ItemStack(material, amount, data));
}
}

View File

@ -878,6 +878,16 @@ public class UtilItem
return isLeaf(stack == null ? null : stack.getType());
}
public static boolean isDoor(Material type)
{
return type == null ? false : (contains(type, ItemCategory.DOOR));
}
public static boolean isDoor(ItemStack stack)
{
return isDoor(stack == null ? null : stack.getType());
}
public static boolean isTool(Material material)
{
return material == null ? false : (contains(material, ItemCategory.TOOL));
@ -1137,4 +1147,56 @@ public class UtilItem
i.setItemMeta(im);
return i;
}
public static double getAttackDamage(Material type)
{
return ItemDamage.get(type);
}
enum ItemDamage
{
IRON_SHOVEL(Material.IRON_SPADE, 3),
IRON_PICKAXE(Material.IRON_PICKAXE, 4),
IRON_AXE(Material.IRON_AXE, 5),
WOODEN_SHOVEL(Material.WOOD_SPADE, 1),
WOODEN_PICKAXE(Material.WOOD_PICKAXE, 2),
WOODEN_AXE(Material.WOOD_AXE, 3),
STONE_SHOVEL(Material.STONE_SPADE, 2),
STONE_PICKAXE(Material.STONE_PICKAXE, 3),
STONE_AXE(Material.STONE_AXE, 4),
DIAMOND_SHOVEL(Material.DIAMOND_SPADE, 4),
DIAMOND_PICKAXE(Material.DIAMOND_PICKAXE, 5),
DIAMOND_AXE(Material.DIAMOND_AXE, 6),
GOLD_SHOVEL(Material.GOLD_SPADE, 1),
GOLD_PICKAXE(Material.GOLD_PICKAXE, 2),
GOLD_AXE(Material.GOLD_AXE, 3),
IRON_SWORD(Material.IRON_SWORD, 6),
WOODEN_SWORD(Material.WOOD_SWORD, 4),
STONE_SWORD(Material.STONE_SWORD, 5),
DIAMOND_SWORD(Material.DIAMOND_SWORD, 7),
GOLDEN_SWORD(Material.GOLD_SWORD, 4);
private double _damage;
private Material _type;
ItemDamage(Material type, double damage)
{
_type = type;
_damage = damage;
}
public static double get(Material type)
{
for (ItemDamage item : values())
{
if (item._type.equals(type))
{
return item._damage;
}
}
return 1;
}
}
}

View File

@ -108,6 +108,11 @@ public class UtilMath
return num < min ? min : (num > max ? max : num);
}
public static float clamp(float num, float min, float max)
{
return num < min ? min : (num > max ? max : num);
}
public static long clamp(long num, long min, long max)
{
return num < min ? min : (num > max ? max : num);
@ -137,4 +142,145 @@ public class UtilMath
return ((double) rand) / 100.d;
}
public static <T> T getLast(List<T> list)
{
return list.isEmpty() ? null : list.get(list.size() - 1);
}
public static <T> T getFirst(List<T> list)
{
return list.isEmpty() ? null : list.get(0);
}
public static <T> T getLast(NautArrayList<T> list)
{
return list.isEmpty() ? null : list.get(list.size() - 1);
}
public static <T> T getFirst(NautArrayList<T> list)
{
return list.isEmpty() ? null : list.get(0);
}
public static <N extends Number> N closest(List<N> values, N value)
{
int closestIndex = -1;
int index = 0;
for (N number : values)
{
if (closestIndex == -1 || (Math.abs(number.doubleValue() - value.doubleValue()) < Math.abs(values.get(closestIndex).doubleValue() - value.doubleValue())))
{
closestIndex = index;
}
index++;
}
return values.get(closestIndex);
}
public static boolean isOdd(int size)
{
return !isEven(size);
}
public static boolean isEven(int size)
{
return size % 2 == 0;
}
public static byte[] getBits(int value)
{
byte[] bits = new byte[32];
String bit = Long.toBinaryString(value);
while (bit.length() < 32)
{
bit = "0" + bit;
}
int index = 0;
for (char c : bit.toCharArray())
{
bits[index] = (byte) (c == '1' ? '1' : '0');
index++;
}
return bits;
}
public static byte[] getBits(long value)
{
byte[] bits = new byte[64];
String bit = Long.toBinaryString(value);
while (bit.length() < 64)
{
bit = "0" + bit;
}
int index = 0;
for (char c : bit.toCharArray())
{
bits[index] = (byte) (c == '1' ? '1' : '0');
index++;
}
return bits;
}
public static byte[] getBits(byte value)
{
byte[] bits = new byte[8];
String bit = Long.toBinaryString(value);
while (bit.length() < 8)
{
bit = "0" + bit;
}
int index = 0;
for (char c : bit.toCharArray())
{
bits[index] = (byte) (c == '1' ? '1' : '0');
index++;
}
return bits;
}
public static byte[] getBits(short value)
{
byte[] bits = new byte[16];
String bit = Long.toBinaryString(value);
while (bit.length() < 16)
{
bit = "0" + bit;
}
int index = 0;
for (char c : bit.toCharArray())
{
bits[index] = (byte) (c == '1' ? '1' : '0');
index++;
}
return bits;
}
public static double getDecimalPoints(double n)
{
return n - ((int) ((int) n));
}
}

View File

@ -0,0 +1,29 @@
package mineplex.core.common.util;
import java.io.File;
import java.io.FileInputStream;
import org.bukkit.inventory.ItemStack;
import com.java.sk89q.jnbt.NBTInputStream;
import com.java.sk89q.jnbt.NamedTag;
public class UtilOfflinePlayer
{
public static ItemStack loadOfflineInventory(File file)
{
try (NBTInputStream stream = new NBTInputStream(new FileInputStream(file)))
{
NamedTag tag = stream.readNamedTag();
System.out.println(tag);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}

View File

@ -27,6 +27,7 @@ import org.bukkit.potion.PotionEffect;
import org.bukkit.util.BlockIterator;
import org.bukkit.util.Vector;
import mineplex.core.common.MinecraftVersion;
import net.minecraft.server.v1_8_R3.EntityPlayer;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PlayerConnection;
@ -341,7 +342,7 @@ public class UtilPlayer
{
if (cur.getName().equalsIgnoreCase(player))
return cur;
if (cur.getName().toLowerCase().contains(player.toLowerCase()))
matchList.add(cur);
}
@ -814,4 +815,12 @@ public class UtilPlayer
{
((CraftPlayer) player).getHandle().setWingsDeployAt(distance);
}
public static MinecraftVersion getVersion(Player player)
{
if (is1_9(player))
return MinecraftVersion.Version1_9;
return MinecraftVersion.Version1_8;
}
}

View File

@ -1,20 +1,38 @@
package mineplex.core.common.util;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Stream;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.scheduler.BukkitRunnable;
import com.google.common.collect.Lists;
import mineplex.core.common.events.PlayerRecieveBroadcastEvent;
public class UtilServer
{
// Quite hacky. would be nice if we could have a "MineplexPlugin" interface
// which would define a getServerName() method and then implement it in
// whatever way needed.
// MineplexPlugin plugin = (MineplexPlugin) plugin.getClass().getDeclaredMethod("getMineplexPlugin").invoke(plugin);
// plugin.getServerName();
private static String _serverName;
public static Player[] getPlayers()
{
return getServer().getOnlinePlayers().toArray(new Player[0]);
@ -52,7 +70,10 @@ public class UtilServer
public static void broadcast(String message)
{
for (Player cur : getPlayers())
UtilPlayer.message(cur, message);
{
if (!UtilServer.CallEvent(new PlayerRecieveBroadcastEvent(cur, message)).isCancelled())
UtilPlayer.message(cur, message);
}
}
public static void broadcast(LinkedList<String> messages)
@ -86,4 +107,116 @@ public class UtilServer
{
return (double)getPlayers().length / (double)UtilServer.getServer().getMaxPlayers();
}
public static void RegisterEvents(Listener listener)
{
getPluginManager().registerEvents(listener, getPlugin());
}
public static void Unregister(Listener listener)
{
HandlerList.unregisterAll(listener);
}
public static Plugin getPlugin()
{
return getPluginManager().getPlugins()[0];
}
public static PluginManager getPluginManager()
{
return getServer().getPluginManager();
}
public static <T extends Event> T CallEvent(T event)
{
getPluginManager().callEvent(event);
return event;
}
public static void repeat(BukkitRunnable runnable, long time)
{
runnable.runTaskTimer(getPlugin(), time, time);
}
public static boolean IsOnline(String name)
{
return !UtilStreams.IsEmpty(getPlayersCollection().stream().filter(player -> player.getName().equals(name)));
}
public static Player GetPlayer(String name)
{
return UtilStreams.GetFirst(getPlayersCollection().stream().filter(player -> player.getName().equals(name)));
}
public static OfflinePlayer GetOffline(String player)
{
return getServer().getOfflinePlayer(player);
}
public static String getServerName()
{
if (_serverName == null)
{
try
{
Class<?> Portal = Class.forName("mineplex.core.portal.Portal");
Object instance = null;
List<Field> stringFields = Lists.newArrayList();
for (Field field : Portal.getDeclaredFields())
{
if (field.getType().equals(Portal))
{
field.setAccessible(true);
instance = field.get(null);
}
if (field.getType().equals(String.class))
{
stringFields.add(field);
}
}
for (Field field : stringFields)
{
field.setAccessible(true);
String value = (String) field.get(instance);
if (stringFields.size() > 1)
{
if (value.contains("-"))
{
_serverName = new String(value);
}
}
else
{
_serverName = new String(value);
}
}
if (_serverName == null)
{
_serverName = "UNKOWN";
System.out.println("ERROR: Could not get server name from Portal. Cause is most likely ambiguous fields in the class. Please revise UtilServer's method of getting the current server name.");
}
}
catch (Exception exception)
{
System.out.println("FATAL ERROR WHILE TRYING TO GET SERVER NAME");
exception.printStackTrace();
}
}
return _serverName;
}
public static Collection<Player> GetPlayers()
{
return Lists.newArrayList(getPlayers());
}
}

View File

@ -53,7 +53,7 @@ public class UtilShapes
return circleblocks;
}
/**
* Gets the block at the exact corners, will return a diagonal.
*

View File

@ -0,0 +1,58 @@
package mineplex.core.common.util;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.stream.Stream;
import org.apache.commons.lang.Validate;
public class UtilStreams
{
public static boolean IsEmpty(Stream<?> stream)
{
return Sum(stream) != 0;
}
public static int Sum(Stream<?> stream)
{
return stream.mapToInt(v -> 1).sum();
}
public static Object[] ToArray(Stream<? extends Object> stream)
{
return stream.toArray();
}
public static <T> T Get(int index, Stream<T> stream)
{
if (Sum(stream) < index + 1)
{
return null;
}
return (T) ToArray(stream)[index];
}
public static <T> T GetFirst(Stream<T> stream)
{
return Get(0, stream);
}
public static <T> T GetLast(Stream<T> stream)
{
return Get(Sum(stream) + 1, stream);
}
public static byte[] ReadBytes(DataInputStream dos, int bytes) throws IOException
{
Validate.isTrue(bytes > 0, "Amount of bytes to read must be > 0");
byte[] read = new byte[bytes];
for (int i = 0; i < bytes; i++)
read[i] = dos.readByte();
return read;
}
}

View File

@ -6,14 +6,14 @@ import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.UUID;
import javax.imageio.ImageIO;
import mineplex.core.common.CurrencyType;
import org.apache.commons.lang.WordUtils;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import mineplex.core.common.CurrencyType;
public class UtilText
{
@ -614,6 +614,11 @@ public class UtilText
public static String repeat(String txt, int times)
{
if (times <= 0)
{
return new String();
}
return new String(new byte[times]).replace("\0", txt);
}
@ -653,12 +658,16 @@ public class UtilText
}
public static String getProgress(String prefix, double amount, String suffix, boolean progressDirectionSwap)
{
return getProgress(prefix, amount, suffix, progressDirectionSwap, 24);
}
public static String getProgress(String prefix, double amount, String suffix, boolean progressDirectionSwap, int bars)
{
if (progressDirectionSwap)
amount = 1 - amount;
//Generate Bar
int bars = 24;
String progressBar = C.cGreen + "";
boolean colorChange = false;
for (int i=0 ; i<bars ; i++)
@ -673,6 +682,20 @@ public class UtilText
}
return(prefix == null ? "" : prefix + ChatColor.RESET + " ") + progressBar + (suffix == null ? "" : ChatColor.RESET + " " + suffix);
}
}
public static String possesive(String possesiveNoun, String noun)
{
if (possesiveNoun == null || noun == null)
{
return "???";
}
if (possesiveNoun.isEmpty() || noun.isEmpty())
{
return "???";
}
return possesiveNoun.endsWith("s") ? possesiveNoun + "' " + noun : possesiveNoun + "'s " + noun;
}
}

View File

@ -1,6 +1,5 @@
package mineplex.core.common.util;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_8_R3.ChatMessage;
@ -28,6 +27,11 @@ public class UtilTextMiddle
public static void display(String text, String subtitle, int fadeInTicks, int stayTicks, int fadeOutTicks, Player... players)
{
if (players.length == 1 && players[0] == null)
{
return;
}
setTimings(fadeInTicks, stayTicks, fadeOutTicks, players);
display(text, subtitle, players);

View File

@ -0,0 +1,80 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.util.Vector;
public class UtilTrig
{
public static List<Vector> GetCirclePoints(Vector origin, int points, double radius)
{
List<Vector> list = new LinkedList<>();
double slice = 2 * Math.PI / points;
for (int point = 0; point < points; point++)
{
double angle = slice * point;
list.add(new Vector(origin.getX() + radius * Math.cos(angle), 0, origin.getZ() + radius * Math.sin(angle)));
}
return list;
}
public static ArrayList<Location> GetSpherePoints(Location loc, double radius, double height, boolean hollow, double addition)
{
ArrayList<Location> circleblocks = new ArrayList<Location>();
double cx = loc.getBlockX();
double cy = loc.getBlockY();
double cz = loc.getBlockZ();
for (double y = cy - radius; y < cy + radius; y += addition)
{
for (double x = cx - radius; x <= cx + radius; x += addition)
{
for (double z = cz - radius; z <= cz + radius; z += addition)
{
double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (cy - y) * (cy - y);
if (dist < radius * radius && !(hollow && dist < (radius - 1) * (radius - 1)))
{
Location l = new Location(loc.getWorld(), x, y, z);
circleblocks.add(l);
}
}
}
}
return circleblocks;
}
public static List<Vector> GetSpherePoints(Vector vector, double radius, double height, boolean hollow, double addition)
{
List<Vector> circleblocks = new ArrayList<>();
double cx = vector.getX();
double cy = vector.getY();
double cz = vector.getZ();
for (double y = cy - radius; y < cy + radius; y += addition)
{
for (double x = cx - radius; x <= cx + radius; x += addition)
{
for (double z = cz - radius; z <= cz + radius; z += addition)
{
double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (cy - y) * (cy - y);
if (dist < radius * radius && !(hollow && dist < (radius - 1) * (radius - 1)))
{
Vector l = new Vector(x, y, z);
circleblocks.add(l);
}
}
}
}
return circleblocks;
}
}

View File

@ -0,0 +1,58 @@
package mineplex.core.common.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
public class UtilWeb
{
public static String doPOST(String url, Map<String, Object> params)
{
try
{
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet())
{
if (postData.length() != 0)
{
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder back = new StringBuilder();
for (int $char; ($char = in.read()) >= 0;)
{
back.append((char) $char);
}
return back.toString();
}
catch (Exception exception)
{
exception.printStackTrace();
return null;
}
}
}

View File

@ -209,4 +209,5 @@ public class UtilWorld
origin.getBlock().getRelative(BlockFace.SOUTH),
origin.getBlock().getRelative(BlockFace.WEST));
}
}

View File

@ -15,7 +15,6 @@ public abstract class MiniClientPlugin<DataType extends Object> extends MiniPlug
private NautHashMap<String, DataType> _clientData = new NautHashMap<String, DataType>();
public MiniClientPlugin(String moduleName, JavaPlugin plugin)
{
super(moduleName, plugin);
@ -41,7 +40,7 @@ public abstract class MiniClientPlugin<DataType extends Object> extends MiniPlug
return _clientData.get(name);
}
}
public void saveData(String name, int accountId) {}
public DataType Get(Player player)

View File

@ -3,34 +3,36 @@ package mineplex.core;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.bukkit.Bukkit;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import mineplex.core.command.CommandCenter;
import mineplex.core.command.ICommand;
import mineplex.core.common.util.F;
import mineplex.core.common.util.NautHashMap;
import mineplex.core.common.util.UtilTime;
import mineplex.core.common.util.UtilTime.TimeUnit;
import mineplex.core.thread.ThreadPool;
public abstract class MiniPlugin implements Listener
{
private static final ExecutorService threadPool = Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("MiniPlugin Async %1$d").build());
protected String _moduleName = "Default";
protected JavaPlugin _plugin;
protected NautHashMap<String, ICommand> _commands;
public MiniPlugin(String moduleName, JavaPlugin plugin)
protected long _initializedTime;
public MiniPlugin(String moduleName, JavaPlugin plugin)
{
_moduleName = moduleName;
_plugin = plugin;
_initializedTime = System.currentTimeMillis();
_commands = new NautHashMap<String, ICommand>();
onEnable();
@ -107,13 +109,13 @@ public abstract class MiniPlugin implements Listener
public void log(String message)
{
System.out.println(F.main(_moduleName, message));
Bukkit.getConsoleSender().sendMessage(F.main(_moduleName, message));
}
public void runAsync(Runnable runnable)
{
// Instead of using
threadPool.execute(runnable);
ThreadPool.ASYNC.execute(runnable);
}
public void runAsync(Runnable runnable, long time)

View File

@ -184,7 +184,7 @@ public class CoreClientManager extends MiniPlugin
if (!LoadClient(Add(event.getName()), event.getUniqueId(), event.getAddress().getHostAddress()))
event.disallow(Result.KICK_OTHER, "There was a problem logging you in.");
}
catch(Exception exception)
catch (Exception exception)
{
event.disallow(Result.KICK_OTHER, "Error retrieving information from web, please retry in a minute.");
exception.printStackTrace();
@ -375,6 +375,7 @@ public class CoreClientManager extends MiniPlugin
runAsync(new Runnable()
{
@Override
public void run()
{
client.setAccountId(_repository.login(_loginProcessors, uuid, client.GetPlayerName()));

View File

@ -60,17 +60,11 @@ public class AccountRepository extends MinecraftRepository
public int login(final List<ILoginProcessor> loginProcessors, final UUID uuid, final String name)
{
// First we try to grab the account id from cache - this saves an extra trip to database
int accountId = -1;
int accountId = PlayerCache.getInstance().getAccountId(uuid);
try (Connection connection = getConnection(); Statement statement = connection.createStatement())
{
int cachedId = PlayerCache.getInstance().getAccountId(uuid);
if (cachedId > 0)
{
accountId = cachedId;
System.out.println("Loaded Account ID From Cache [" + name + " - " + accountId + "]");
}
else
if (accountId <= 0)
{
// Player was not found in cache, we need to grab the account id from database
statement.execute("SELECT id FROM accounts WHERE accounts.uuid = '" + uuid + "' LIMIT 1;");
@ -100,6 +94,10 @@ public class AccountRepository extends MinecraftRepository
accountId = tempList.get(0);
}
}
else
{
System.out.println(name + " Loaded Account ID From Cache [" + name + " - " + accountId + "]");
}
final int finalId = accountId;
final String uuidString = uuid.toString();
@ -109,7 +107,7 @@ public class AccountRepository extends MinecraftRepository
loginString += loginProcessors.parallelStream().map(processor -> processor.getQuery(finalId, uuidString, name)).collect(Collectors.joining());
statement.execute(loginString);
statement.getUpdateCount();
statement.getMoreResults();

View File

@ -33,6 +33,7 @@ import mineplex.core.donation.GiveDonorData;
import mineplex.core.facebook.FacebookManager;
import mineplex.core.hologram.Hologram;
import mineplex.core.hologram.HologramManager;
import mineplex.core.inventory.ClientItem;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.npc.Npc;
import mineplex.core.npc.NpcManager;
@ -474,6 +475,7 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
{
if (timeTillRankBonus(player) > 0)
result.run(false);
getRepository().attemptRankBonus(player, new Callback<Boolean>()
{
@Override
@ -734,31 +736,35 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
if (oldChests > 0)
{
_inventoryManager.addItemToInventory(player, TreasureType.OLD.getItemName(), oldChests);
//_inventoryManager.addItemToInventory(player, TreasureType.OLD.getItemName(), oldChests);
UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(oldChests + " Old Chests")));
_inventoryManager.Get(player).addItem(new ClientItem(_inventoryManager.getItem(TreasureType.OLD.getItemName()), oldChests));
}
if (ancientChests > 0)
{
UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(ancientChests + " Ancient Chests")));
_inventoryManager.addItemToInventory(player, TreasureType.ANCIENT.getItemName(), ancientChests);
//_inventoryManager.addItemToInventory(player, TreasureType.ANCIENT.getItemName(), ancientChests);
_inventoryManager.Get(player).addItem(new ClientItem(_inventoryManager.getItem(TreasureType.ANCIENT.getItemName()), ancientChests));
}
if (mythicalChests > 0)
{
UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(mythicalChests + " Mythical Chests")));
_inventoryManager.addItemToInventory(player, TreasureType.MYTHICAL.getItemName(), mythicalChests);
//_inventoryManager.addItemToInventory(player, TreasureType.MYTHICAL.getItemName(), mythicalChests);
_inventoryManager.Get(player).addItem(new ClientItem(_inventoryManager.getItem(TreasureType.MYTHICAL.getItemName()), mythicalChests));
}
if (gems > 0)
{
UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(gems + " Gems")));
_gemQueue.add(new GiveDonorData(null, player.getName(), "Treasure", player.getUniqueId(), coreClient.getAccountId(), gems));
//_gemQueue.add(new GiveDonorData(null, player.getName(), "Treasure", player.getUniqueId(), coreClient.getAccountId(), gems));
}
if (gold > 0)
{
UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(gold + " Gold")));
/*
_donationManager.rewardGold(new Callback<Boolean>()
{
@Override
@ -773,12 +779,13 @@ public class BonusManager extends MiniClientPlugin<BonusClientData> implements I
}
}
}, "Earned", player.getName(), coreClient.getAccountId(), gold, true);
*/
}
if (coins > 0)
{
UtilPlayer.message(player, F.main("Carl", "Rewarded " + F.elem(coins + " Treasure Shards")));
_coinQueue.add(new GiveDonorData(null, player.getName(), "Treasure", player.getUniqueId(), coreClient.getAccountId(), coins));
//_coinQueue.add(new GiveDonorData(null, player.getName(), "Treasure", player.getUniqueId(), coreClient.getAccountId(), coins));
}
if (tickets > 0)

View File

@ -259,42 +259,48 @@ public class BonusRepository extends MinecraftRepository
public void attemptRankBonus(final Player player, final Callback<Boolean> result)
{
if (!Recharge.Instance.usable(player, "AttemptRankBonus")) {
if (!Recharge.Instance.usable(player, "AttemptRankBonus"))
{
result.run(false);
return;
}
final int accountId = _manager.getClientManager().Get(player).getAccountId();
final int coins = _manager.getRankBonusAmount(player).getCoins();
final int gems = _manager.getRankBonusAmount(player).getGems();
final int mythicalChestChange = _manager.getRankBonusAmount(player).getMythicalChests();
if (!_manager.getRankBonusAmount(player).isGreaterThanZero()) {
if (!_manager.getRankBonusAmount(player).isGreaterThanZero())
{
result.run(false);
return;
}
final JavaPlugin plug = _manager.getPlugin();
Bukkit.getScheduler().runTaskAsynchronously(plug, new Runnable() {
Bukkit.getScheduler().runTaskAsynchronously(plug, new Runnable()
{
@Override
public void run()
{
try (Connection connection = getConnection();
CallableStatement callableStatement = connection.prepareCall("{call check_rank(?, ?, ?, ?, ?)}")) {
CallableStatement callableStatement = connection.prepareCall("{call rankBonus(?, ?, ?, ?, ?, ?)}"))
{
callableStatement.setInt(1, accountId);
callableStatement.setInt(2, coins);
callableStatement.setInt(3, 0);
callableStatement.registerOutParameter(4, java.sql.Types.BOOLEAN);
callableStatement.registerOutParameter(5, java.sql.Types.DATE);
callableStatement.setInt(3, gems);
callableStatement.setInt(4, mythicalChestChange);
callableStatement.registerOutParameter(5, java.sql.Types.BOOLEAN);
callableStatement.registerOutParameter(6, java.sql.Types.DATE);
callableStatement.executeUpdate();
final boolean pass = callableStatement.getBoolean(4);
final boolean pass = callableStatement.getBoolean(5);
final Date date = callableStatement.getDate(5);
Bukkit.getScheduler().runTask(plug, new Runnable() {
final Date date = callableStatement.getDate(6);
Bukkit.getScheduler().runTask(plug, new Runnable()
{
@Override
public void run()
{
@ -311,9 +317,12 @@ public class BonusRepository extends MinecraftRepository
}
}
});
} catch (Exception e) {
}
catch (Exception e)
{
Recharge.Instance.use(player, "AttemptRankBonus", 1000 * 30, false, false);
e.printStackTrace();
System.out.println("Error : " + e.getMessage());
result.run(false);
}
}

View File

@ -7,9 +7,12 @@ import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
@ -18,24 +21,7 @@ import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import mineplex.core.MiniPlugin;
import mineplex.core.chat.command.ChatSlowCommand;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.recharge.Recharge;
import mineplex.core.updater.event.UpdateEvent;
import mineplex.core.updater.UpdateType;
import mineplex.core.account.CoreClientManager;
import mineplex.core.achievement.AchievementManager;
import mineplex.core.chat.command.BroadcastCommand;
import mineplex.core.chat.command.SilenceCommand;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilText;
import mineplex.core.common.util.UtilTime;
import org.apache.commons.lang3.Validate;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -48,11 +34,31 @@ import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import mineplex.core.MiniPlugin;
import mineplex.core.account.CoreClientManager;
import mineplex.core.achievement.AchievementManager;
import mineplex.core.chat.command.BroadcastCommand;
import mineplex.core.chat.command.ChatSlowCommand;
import mineplex.core.chat.command.SilenceCommand;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilText;
import mineplex.core.common.util.UtilTime;
import mineplex.core.incognito.IncognitoManager;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.recharge.Recharge;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class Chat extends MiniPlugin
{
private CoreClientManager _clientManager;
private PreferencesManager _preferences;
private AchievementManager _achievements;
private IncognitoManager _incognitoManager;
private String[] _hackusations = {"hack", "hax", "hacker", "hacking", "cheat", "cheater", "cheating", "forcefield", "flyhack", "flyhacking", "autoclick", "aimbot"};
private String _filterUrl = "https://chat.mineplex.com:8003/content/item/moderate";
@ -63,13 +69,17 @@ public class Chat extends MiniPlugin
private int _chatSlow = 0;
private long _silenced = 0;
private boolean _threeSecondDelay = true;
private List<Function<AsyncPlayerChatEvent, Boolean>> _highPriorityFilters = new ArrayList<>();
private List<Function<AsyncPlayerChatEvent, Boolean>> _lowPriorityFilters = new ArrayList<>();
private HashMap<UUID, MessageData> _playerLastMessage = new HashMap<UUID, MessageData>();
public Chat(JavaPlugin plugin, CoreClientManager clientManager, PreferencesManager preferences, AchievementManager achievements, String serverName)
public Chat(JavaPlugin plugin, IncognitoManager incognitoManager, CoreClientManager clientManager, PreferencesManager preferences, AchievementManager achievements, String serverName)
{
super("Chat", plugin);
_incognitoManager = incognitoManager;
_clientManager = clientManager;
_serverName = serverName;
_preferences = preferences;
@ -299,7 +309,23 @@ public class Chat extends MiniPlugin
return;
Player sender = event.getPlayer();
if (_incognitoManager != null && _incognitoManager.Get(sender).Status)
{
UtilPlayer.message(sender, C.cYellow + "You can not chat while incognito.");
event.setCancelled(true);
return;
}
for (Function<AsyncPlayerChatEvent, Boolean> filter : _highPriorityFilters)
{
if (filter.apply(event).booleanValue())
{
event.setCancelled(true);
return;
}
}
if (SilenceCheck(sender))
{
event.setCancelled(true);
@ -346,12 +372,21 @@ public class Chat extends MiniPlugin
event.setCancelled(true);
}
}
if (!event.isCancelled())
_playerLastMessage.put(sender.getUniqueId(), new MessageData(event.getMessage()));
for (Function<AsyncPlayerChatEvent, Boolean> filter : _lowPriorityFilters)
{
if (filter.apply(event).booleanValue())
{
event.setCancelled(true);
return;
}
}
}
private boolean msgContainsHack(String msg)
private boolean msgContainsHack(String msg)
{
msg = " " + msg.toLowerCase().replaceAll("[^a-z ]", "") + " ";
for (String s : _hackusations) {
@ -596,4 +631,22 @@ public class Chat extends MiniPlugin
{
_threeSecondDelay = b;
}
/**
* If the function returns Boolean.TRUE then the message will be CANCELLED.
*/
public void AddFilter(Function<AsyncPlayerChatEvent, Boolean> restriction, FilterPriority priority)
{
Validate.isTrue(priority != null, "Priority must not be null.");
switch (priority)
{
case HIGH:
_highPriorityFilters.add(restriction);
break;
case LOW:
_lowPriorityFilters.add(restriction);
}
}
}

View File

@ -0,0 +1,7 @@
package mineplex.core.chat;
public enum FilterPriority
{
HIGH,
LOW;
}

View File

@ -82,6 +82,15 @@ public class PetTagPage extends ShopPageBase<CosmeticManager, CosmeticShop>
getShop().openPageForPlayer(getPlayer(), new PetPage(getPlugin(), getShop(), getClientManager(), getDonationManager(), "Pets", getPlayer()));
return;
}
if (_tagName.equalsIgnoreCase("ULTRA"))
{
UtilPlayer.message(getPlayer(), F.main(getPlugin().getName(), ChatColor.RED + _tagName + " is a restricted name."));
playDenySound(getPlayer());
getShop().openPageForPlayer(getPlayer(), new PetPage(getPlugin(), getShop(), getClientManager(), getDonationManager(), "Pets", getPlayer()));
return;
}
PetExtra tag = new PetExtra("Rename " + _pet.GetName() + " to " + _tagName, Material.NAME_TAG, 100);

View File

@ -62,4 +62,14 @@ public class DelayedTask extends MiniClientPlugin<DelayedTaskClient>
{
return new DelayedTaskClient(Bukkit.getPlayer(player));
}
public boolean HasTask(Player player, String task)
{
return Get(player).getStartTime(task) != -1;
}
public boolean HasTask(String player, String task)
{
return HasTask(Bukkit.getPlayer(player), task);
}
}

View File

@ -27,20 +27,20 @@ public class DonationRepository extends MinecraftRepository
private static String CREATE_GEM_TRANSACTION_TABLE = "CREATE TABLE IF NOT EXISTS accountGemTransactions (id INT NOT NULL AUTO_INCREMENT, accountId INT, reason VARCHAR(100), gems INT, PRIMARY KEY (id), FOREIGN KEY (accountId) REFERENCES accounts(id));";
private static String INSERT_COIN_TRANSACTION = "INSERT INTO accountCoinTransactions(accountId, reason, coins) VALUES(?, ?, ?);";
private static String UPDATE_ACCOUNT_COINS = "UPDATE accounts SET coins = coins + ? WHERE id = ?;";
private static String UPDATE_ACCOUNT_GOLD = "UPDATE accounts SET gold = gold + ? WHERE id = ?;";
private static String UPDATE_ACCOUNT_GOLD = "UPDATE accounts SET gold = gold + ? WHERE id = ? && gold >= ?;";
private static String SET_ACCOUNT_GOLD = "UPDATE accounts SET gold = ? WHERE id = ?;";
private static String UPDATE_NULL_ACCOUNT_GEMS_AND_COINS_ = "UPDATE accounts SET gems = ?, coins = ? WHERE id = ? AND gems IS NULL AND coins IS NULL;";
private String _webAddress;
public DonationRepository(JavaPlugin plugin, String webAddress)
{
super(plugin, DBPool.getAccount());
_webAddress = webAddress;
}
public void PurchaseKnownSalesPackage(final Callback<TransactionResponse> callback, String name, final String uuid, final int cost, final int salesPackageId)
public void PurchaseKnownSalesPackage(final Callback<TransactionResponse> callback, String name, final String uuid, final int cost, final int salesPackageId)
{
final PurchaseToken token = new PurchaseToken();
token.AccountName = name;
@ -61,7 +61,7 @@ public class DonationRepository extends MinecraftRepository
});
}
};
handleDatabaseCall(new DatabaseRunnable(new Runnable()
{
public void run()
@ -70,7 +70,7 @@ public class DonationRepository extends MinecraftRepository
}
}), "Error purchasing known sales package in DonationRepository : ");
}
public void PurchaseUnknownSalesPackage(final Callback<TransactionResponse> callback, final String name, final int accountId, final String packageName, final CurrencyType currencyType, final int cost)
{
final UnknownPurchaseToken token = new UnknownPurchaseToken();
@ -96,7 +96,7 @@ public class DonationRepository extends MinecraftRepository
executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", -cost), new ColumnInt("id", accountId));
}
}
Bukkit.getServer().getScheduler().runTask(getPlugin(), new Runnable()
{
@Override
@ -107,7 +107,7 @@ public class DonationRepository extends MinecraftRepository
});
}
};
handleDatabaseCall(new DatabaseRunnable(new Runnable()
{
public void run()
@ -116,18 +116,18 @@ public class DonationRepository extends MinecraftRepository
}
}), "Error purchasing unknown sales package in DonationRepository : ");
}
public void gemReward(final Callback<Boolean> callback, final String giver, String name, final String uuid, final int greenGems)
{
final GemRewardToken token = new GemRewardToken();
token.Source = giver;
token.Name = name;
token.Amount = greenGems;
final Callback<Boolean> extraCallback = new Callback<Boolean>()
{
public void run(final Boolean response)
{
{
Bukkit.getServer().getScheduler().runTask(getPlugin(), new Runnable()
{
@Override
@ -138,7 +138,7 @@ public class DonationRepository extends MinecraftRepository
});
}
};
handleDatabaseCall(new DatabaseRunnable(new Runnable()
{
public void run()
@ -147,14 +147,14 @@ public class DonationRepository extends MinecraftRepository
}
}), "Error updating player gem amount in DonationRepository : ");
}
public void rewardCoins(final Callback<Boolean> callback, final String giver, String name, final int accountId, final int coins)
{
final GemRewardToken token = new GemRewardToken();
token.Source = giver;
token.Name = name;
token.Amount = coins;
final Callback<Boolean> extraCallback = new Callback<Boolean>()
{
public void run(final Boolean response)
@ -164,7 +164,7 @@ public class DonationRepository extends MinecraftRepository
//executeUpdate(UPDATE_ACCOUNT_COINS, new ColumnInt("coins", coins), new ColumnInt("id", accountId));
//executeUpdate(INSERT_COIN_TRANSACTION, new ColumnInt("id", accountId), new ColumnVarChar("reason", 100, "Rewarded by " + giver), new ColumnInt("coins", coins));
}
Bukkit.getServer().getScheduler().runTask(getPlugin(), new Runnable()
{
@Override
@ -175,7 +175,7 @@ public class DonationRepository extends MinecraftRepository
});
}
};
handleDatabaseCall(new DatabaseRunnable(new Runnable()
{
public void run()
@ -184,21 +184,26 @@ public class DonationRepository extends MinecraftRepository
}
}), "Error updating player coin amount in DonationRepository : ");
}
public void rewardGold(final Callback<Boolean> callback, final String giver, final String name, final int accountId, final int gold)
{
{
handleDatabaseCall(new DatabaseRunnable(new Runnable()
{
public void run()
{
boolean success = executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnInt("id", accountId)) > 0;
ColumnInt min = new ColumnInt("gold", gold < 0 ? -gold : 0);
boolean success = executeUpdate(UPDATE_ACCOUNT_GOLD, new ColumnInt("gold", gold), new ColumnInt("id", accountId), min) > 0;
callback.run(success);
}
}), "Error updating player gold amount in DonationRepository : ");
}
public void setGold(final Callback<Boolean> callback, final String giver, final String name, final int accountId, final int gold)
{
{
if (gold < 0)
{
throw new IllegalArgumentException("gold cannot be negative");
}
handleDatabaseCall(new DatabaseRunnable(new Runnable()
{
public void run()
@ -208,7 +213,7 @@ public class DonationRepository extends MinecraftRepository
}
}), "Error updating player gold amount in DonationRepository : ");
}
@Override
protected void initialize()
{
@ -240,12 +245,12 @@ public class DonationRepository extends MinecraftRepository
public Donor retrieveDonorInfo(ResultSet resultSet) throws SQLException
{
Donor donor = new Donor();
while (resultSet.next())
{
donor.setGold(resultSet.getInt(1));
}
return donor;
}
}

View File

@ -0,0 +1,62 @@
package mineplex.core.fallingblock;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.FallingBlock;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.UtilAction;
import mineplex.core.common.util.UtilAlg;
import mineplex.core.common.util.UtilEnt;
public class FallingBlocks extends MiniPlugin
{
public static FallingBlocks Instance;
private static final String METADATA = "FALLING_BLOCK_SPECIAL";
public FallingBlocks(JavaPlugin plugin)
{
super("Falling Blocks", plugin);
Instance = this;
}
public void Spawn(Location location, Material type, byte data, Location center)
{
Vector vec = UtilAlg.getTrajectory(center, location);
if (vec.getY() < 0)
{
vec.setY(vec.getY() * -1);
}
Spawn(location, type, data, vec);
}
public void Spawn(Location location, Material type, byte data, Vector velocity)
{
FallingBlock fall = location.getWorld().spawnFallingBlock(location.add(0.5, 0.5, 0.5), type, data);
fall.setDropItem(false);
UtilAction.velocity(fall, velocity, 0.5 + 0.25 * Math.random(), false, 0, 0.4 + 0.20 * Math.random(), 10, false);
fall.setMetadata(METADATA, new FixedMetadataValue(_plugin, "x"));
UtilEnt.SetMetadata(fall, METADATA, "x");
}
@EventHandler
public void BlockFall(EntityChangeBlockEvent event)
{
if (event.getEntity().hasMetadata(METADATA))
{
event.getEntity().remove();
event.setCancelled(true);
}
}
}

View File

@ -29,6 +29,7 @@ import mineplex.core.friend.command.FriendsDisplay;
import mineplex.core.friend.data.FriendData;
import mineplex.core.friend.data.FriendRepository;
import mineplex.core.friend.data.FriendStatus;
import mineplex.core.incognito.IncognitoManager;
import mineplex.core.portal.Portal;
import mineplex.core.preferences.PreferencesManager;
import mineplex.core.updater.UpdateType;
@ -278,7 +279,6 @@ public class FriendManager extends MiniDbClientPlugin<FriendData>
if (friend.Status == FriendStatusType.Accepted)
{
// Online Friend
if (friend.Online)
{
if (friend.ServerName.contains("Staff") || friend.ServerName.contains("CUST"))

View File

@ -26,14 +26,14 @@ public class FriendsDisplay extends CommandBase<FriendManager>
Plugin.getPreferenceManager().savePreferences(caller);
caller.playSound(caller.getLocation(), Sound.NOTE_PLING, 1, 1.6f);
if (preferences.friendDisplayInventoryUI)
{
new FriendsGUI(Plugin, caller);
Plugin.runAsync(() -> new FriendsGUI(Plugin, caller));
}
else
{
Plugin.showFriends(caller);
Plugin.runAsync(() -> Plugin.showFriends(caller));
}
}
}

View File

@ -32,6 +32,7 @@ import mineplex.core.friend.FriendManager;
import mineplex.core.friend.FriendStatusType;
import mineplex.core.friend.data.FriendData;
import mineplex.core.friend.data.FriendStatus;
import mineplex.core.incognito.IncognitoManager;
import mineplex.core.itemstack.ItemBuilder;
import mineplex.core.itemstack.ItemLayout;
import mineplex.core.shop.item.IButton;
@ -127,7 +128,7 @@ public class FriendsGUI implements Listener
}
FriendStatus friend = friends.get(friendSlot);
ItemBuilder builder = new ItemBuilder(Material.SKULL_ITEM, 1, (short) (friend.Online ? 3 : 0));
builder.setTitle(C.cWhite + C.Bold + friend.Name);
@ -272,7 +273,7 @@ public class FriendsGUI implements Listener
}
FriendStatus friend = friends.get(friendSlot);
ItemBuilder builder = new ItemBuilder(Material.SKULL_ITEM, 1, (short) (friend.Online ? 3 : 0));
builder.setTitle(C.cWhite + C.Bold + friend.Name);

View File

@ -22,11 +22,9 @@ import net.minecraft.server.v1_8_R3.PacketPlayOutEntityMetadata;
import net.minecraft.server.v1_8_R3.PacketPlayOutEntityTeleport;
import net.minecraft.server.v1_8_R3.PacketPlayOutSpawnEntityLiving;
public class Hologram
{
public class Hologram {
public enum HologramTarget
{
public enum HologramTarget {
BLACKLIST, WHITELIST;
}
@ -39,7 +37,8 @@ public class Hologram
private HologramManager _hologramManager;
private String[] _hologramText = new String[0];
/**
* Keeps track of the holograms movements. This fixes offset that occasionally happens when moving a hologram around.
* Keeps track of the holograms movements. This fixes offset that
* occasionally happens when moving a hologram around.
*/
private Vector _lastMovement;
private Location _location;
@ -55,38 +54,41 @@ public class Hologram
private boolean _hideBoundingBox;
private HologramInteraction _interaction;
public Hologram(HologramManager hologramManager, Location location, String... text)
{
private long _maxLifetime = -1;
private long _startTime;
public Hologram(HologramManager hologramManager, Location location, String... text) {
this(hologramManager, location, -1l, text);
}
public Hologram(HologramManager hologramManager, Location location, long maxLifetime, String... text) {
_hologramManager = hologramManager;
_location = location.clone();
_maxLifetime = maxLifetime;
setText(text);
}
public Hologram setInteraction(HologramInteraction interact)
{
public Hologram setInteraction(HologramInteraction interact) {
_interaction = interact;
return this;
}
public HologramInteraction getInteraction()
{
public HologramInteraction getInteraction() {
return _interaction;
}
/**
* Adds the player to the Hologram to be effected by Whitelist or Blacklist
*/
public Hologram addPlayer(Player player)
{
public Hologram addPlayer(Player player) {
return addPlayer(player.getName());
}
/**
* Adds the player to the Hologram to be effected by Whitelist or Blacklist
*/
public Hologram addPlayer(String player)
{
public Hologram addPlayer(String player) {
_playersInList.add(player);
return this;
}
@ -96,8 +98,7 @@ public class Hologram
*
* @return
*/
public Hologram setHideBoundingBox()
{
public Hologram setHideBoundingBox() {
_hideBoundingBox = true;
return this;
}
@ -105,23 +106,19 @@ public class Hologram
/**
* Is there a player entry in the hologram for Whitelist and Blacklist
*/
public boolean containsPlayer(Player player)
{
public boolean containsPlayer(Player player) {
return _playersInList.contains(player.getName());
}
/**
* Is there a player entry in the hologram for Whitelist and Blacklist
*/
public boolean containsPlayer(String player)
{
public boolean containsPlayer(String player) {
return _playersInList.contains(player);
}
protected Packet getDestroyPacket()
{
if (_makeDestroyPackets)
{
protected Packet getDestroyPacket() {
if (_makeDestroyPackets) {
makeDestroyPacket();
_makeDestroyPackets = false;
}
@ -129,8 +126,7 @@ public class Hologram
return _destroy1_8;
}
public Entity getEntityFollowing()
{
public Entity getEntityFollowing() {
return _followEntity;
}
@ -140,27 +136,22 @@ public class Hologram
* @Whitelist = Only people added can see the hologram
* @Blacklist = Anyone but people added can see the hologram
*/
public HologramTarget getHologramTarget()
{
public HologramTarget getHologramTarget() {
return _target;
}
/**
* Get the hologram location
*/
public Location getLocation()
{
public Location getLocation() {
return _location.clone();
}
protected ArrayList<Player> getNearbyPlayers()
{
protected ArrayList<Player> getNearbyPlayers() {
ArrayList<Player> nearbyPlayers = new ArrayList<Player>();
for (Player player : getLocation().getWorld().getPlayers())
{
if (isVisible(player))
{
for (Player player : getLocation().getWorld().getPlayers()) {
if (isVisible(player)) {
nearbyPlayers.add(player);
}
}
@ -168,15 +159,12 @@ public class Hologram
return nearbyPlayers;
}
protected ArrayList<Player> getPlayersTracking()
{
protected ArrayList<Player> getPlayersTracking() {
return _playersTracking;
}
protected Packet[] getSpawnPackets()
{
if (_makeSpawnPackets)
{
protected Packet[] getSpawnPackets() {
if (_makeSpawnPackets) {
makeSpawnPackets();
_makeSpawnPackets = false;
}
@ -187,13 +175,12 @@ public class Hologram
/**
* Get the text in the hologram
*/
public String[] getText()
{
// We reverse it again as the hologram would otherwise display the text from the bottom row to the top row
public String[] getText() {
// We reverse it again as the hologram would otherwise display the text
// from the bottom row to the top row
String[] reversed = new String[_hologramText.length];
for (int i = 0; i < reversed.length; i++)
{
for (int i = 0; i < reversed.length; i++) {
reversed[i] = _hologramText[reversed.length - (i + 1)];
}
@ -203,32 +190,25 @@ public class Hologram
/**
* Get the view distance the hologram is viewable from. Default is 70
*/
public int getViewDistance()
{
public int getViewDistance() {
return _viewDistance;
}
/**
* Is the hologram holograming?
*/
public boolean isInUse()
{
public boolean isInUse() {
return _lastMovement != null;
}
public boolean isRemoveOnEntityDeath()
{
public boolean isRemoveOnEntityDeath() {
return _removeEntityDeath;
}
public boolean isVisible(Player player)
{
if (getLocation().getWorld() == player.getWorld())
{
if ((getHologramTarget() == HologramTarget.WHITELIST) == containsPlayer(player))
{
if (getLocation().distance(player.getLocation()) < getViewDistance())
{
public boolean isVisible(Player player) {
if (getLocation().getWorld() == player.getWorld()) {
if ((getHologramTarget() == HologramTarget.WHITELIST) == containsPlayer(player)) {
if (getLocation().distance(player.getLocation()) < getViewDistance()) {
return true;
}
}
@ -237,53 +217,42 @@ public class Hologram
return false;
}
private void makeDestroyPacket()
{
private void makeDestroyPacket() {
int[] entityIds1_8 = new int[_entityIds.size()];
for (int i = 0; i < _entityIds.size(); i++)
{
for (int i = 0; i < _entityIds.size(); i++) {
entityIds1_8[i] = _entityIds.get(i);
}
_destroy1_8 = new PacketPlayOutEntityDestroy(entityIds1_8);
}
private void makeSpawnPackets()
{
private void makeSpawnPackets() {
_packets1_8 = new Packet[_hologramText.length * 1];
if (_entityIds.size() < _hologramText.length)
{
if (_entityIds.size() < _hologramText.length) {
_makeDestroyPackets = true;
for (int i = _entityIds.size(); i < _hologramText.length; i++)
{
_entityIds.add(UtilEnt.getNewEntityId());
for (int i = _entityIds.size(); i < _hologramText.length; i++) {
_entityIds.add(Integer.valueOf(UtilEnt.getNewEntityId()));
}
}
else
{
} else {
_makeDestroyPackets = true;
while (_entityIds.size() > _hologramText.length)
{
while (_entityIds.size() > _hologramText.length) {
_entityIds.remove(_hologramText.length);
}
}
for (int textRow = 0; textRow < _hologramText.length; textRow++)
{
for (int textRow = 0; textRow < _hologramText.length; textRow++) {
Packet[] packets1_8 = makeSpawnPackets1_8(textRow, _entityIds.get(textRow), _hologramText[textRow]);
for (int i = 0; i < packets1_8.length; i++)
{
for (int i = 0; i < packets1_8.length; i++) {
_packets1_8[textRow + i] = packets1_8[i];
}
}
}
private Packet[] makeSpawnPackets1_8(int textRow, int entityId, String lineOfText)
{
private Packet[] makeSpawnPackets1_8(int textRow, int entityId, String lineOfText) {
PacketPlayOutSpawnEntityLiving packet = new PacketPlayOutSpawnEntityLiving();
DataWatcher watcher = new DataWatcher(null);
@ -300,44 +269,47 @@ public class Hologram
watcher.a(2, lineOfText, EntityArmorStand.META_CUSTOMNAME, lineOfText);
watcher.a(3, (byte) 1, EntityArmorStand.META_CUSTOMNAME_VISIBLE, true);
if (_hideBoundingBox)
{
watcher.a(10, (byte) 16, EntityArmorStand.META_ARMOR_OPTION, (byte) 16); // TODO Uncomment after we can enforce 1.8.3
if (_hideBoundingBox) {
watcher.a(10, (byte) 16, EntityArmorStand.META_ARMOR_OPTION, (byte) 16); // TODO
// Uncomment
// after
// we
// can
// enforce
// 1.8.3
}
// Also correct hologram positioning
return new Packet[]
{
packet
};
return new Packet[] { packet };
}
/**
* Removes the player from the Hologram so they are no longer effected by Whitelist or Blacklist
* Removes the player from the Hologram so they are no longer effected by
* Whitelist or Blacklist
*/
public Hologram removePlayer(Player player)
{
public Hologram removePlayer(Player player) {
return removePlayer(player.getName());
}
/**
* Removes the player from the Hologram so they are no longer effected by Whitelist or Blacklist
* Removes the player from the Hologram so they are no longer effected by
* Whitelist or Blacklist
*/
public Hologram removePlayer(String player)
{
public Hologram removePlayer(String player) {
_playersInList.remove(player);
return this;
}
/**
* If the entity moves, the hologram will update its position to appear relative to the movement.
* If the entity moves, the hologram will update its position to appear
* relative to the movement.
*
* @Please note the hologram updates every tick.
*/
public Hologram setFollowEntity(Entity entityToFollow)
{
public Hologram setFollowEntity(Entity entityToFollow) {
_followEntity = entityToFollow;
relativeToEntity = entityToFollow == null ? null : _location.clone().subtract(entityToFollow.getLocation()).toVector();
relativeToEntity = entityToFollow == null ? null
: _location.clone().subtract(entityToFollow.getLocation()).toVector();
return this;
}
@ -348,8 +320,7 @@ public class Hologram
* @Whitelist = Only people added can see the hologram
* @Blacklist = Anyone but people added can see the hologram
*/
public Hologram setHologramTarget(HologramTarget newTarget)
{
public Hologram setHologramTarget(HologramTarget newTarget) {
_target = newTarget;
return this;
}
@ -357,52 +328,43 @@ public class Hologram
/**
* Sets the hologram to appear at this location
*/
public Hologram setLocation(Location newLocation)
{
public Hologram setLocation(Location newLocation) {
_makeSpawnPackets = true;
Location oldLocation = getLocation();
_location = newLocation.clone();
if (getEntityFollowing() != null)
{
if (getEntityFollowing() != null) {
relativeToEntity = _location.clone().subtract(getEntityFollowing().getLocation()).toVector();
}
if (isInUse())
{
if (isInUse()) {
ArrayList<Player> canSee = getNearbyPlayers();
Iterator<Player> itel = _playersTracking.iterator();
while (itel.hasNext())
{
while (itel.hasNext()) {
Player player = itel.next();
if (!canSee.contains(player))
{
if (!canSee.contains(player)) {
itel.remove();
if (player.getWorld() == getLocation().getWorld())
{
if (player.getWorld() == getLocation().getWorld()) {
UtilPlayer.sendPacket(player, getDestroyPacket());
}
}
}
itel = canSee.iterator();
while (itel.hasNext())
{
while (itel.hasNext()) {
Player player = itel.next();
if (!_playersTracking.contains(player))
{
if (!_playersTracking.contains(player)) {
_playersTracking.add(player);
itel.remove();
UtilPlayer.sendPacket(player, getSpawnPackets());
}
}
if (!canSee.isEmpty())
{
_lastMovement.add(new Vector(newLocation.getX() - oldLocation.getX(), newLocation.getY() - oldLocation.getY(),
newLocation.getZ() - oldLocation.getZ()));
if (!canSee.isEmpty()) {
_lastMovement.add(new Vector(newLocation.getX() - oldLocation.getX(),
newLocation.getY() - oldLocation.getY(), newLocation.getZ() - oldLocation.getZ()));
int x = (int) Math.floor(32 * _lastMovement.getX());
int y = (int) Math.floor(32 * _lastMovement.getY());
@ -412,11 +374,9 @@ public class Hologram
int i = 0;
if (x >= -128 && x <= 127 && y >= -128 && y <= 127 && z >= -128 && z <= 127)
{
if (x >= -128 && x <= 127 && y >= -128 && y <= 127 && z >= -128 && z <= 127) {
_lastMovement.subtract(new Vector(x / 32D, y / 32D, z / 32D));
for (Integer entityId : _entityIds)
{
for (Integer entityId : _entityIds) {
PacketPlayOutEntity.PacketPlayOutRelEntityMove relMove = new PacketPlayOutEntity.PacketPlayOutRelEntityMove();
relMove.a = entityId;
@ -427,16 +387,13 @@ public class Hologram
packets1_8[i] = relMove;
i++;
}
}
else
{
} else {
x = (int) Math.floor(32 * newLocation.getX());
z = (int) Math.floor(32 * newLocation.getZ());
_lastMovement = new Vector(newLocation.getX() - (x / 32D), 0, newLocation.getZ() - (z / 32D));
for (Integer entityId : _entityIds)
{
for (Integer entityId : _entityIds) {
PacketPlayOutEntityTeleport teleportPacket = new PacketPlayOutEntityTeleport();
teleportPacket.a = entityId;
teleportPacket.b = x;
@ -449,10 +406,8 @@ public class Hologram
}
}
for (Player player : canSee)
{
for (Packet packet : packets1_8)
{
for (Player player : canSee) {
for (Packet packet : packets1_8) {
UtilPlayer.sendPacket(player, packet);
}
}
@ -461,48 +416,50 @@ public class Hologram
return this;
}
public Hologram setRemoveOnEntityDeath()
public long getStartTime()
{
return _startTime;
}
public long getMaxLifetime()
{
return _maxLifetime;
}
public Hologram setRemoveOnEntityDeath() {
_removeEntityDeath = true;
return this;
}
public boolean isEntityId(int entityId)
{
public boolean isEntityId(int entityId) {
return _entityIds.contains(entityId);
}
/**
* Set the hologram text
*/
public Hologram setText(String... newLines)
{
public Hologram setText(String... newLines) {
String[] newText = new String[newLines.length];
for (int i = 0; i < newText.length; i++)
{
for (int i = 0; i < newText.length; i++) {
newText[i] = newLines[newText.length - (i + 1)];
}
if (newText.equals(_hologramText))
return this;
if (isInUse())
{
if (isInUse()) {
int[] destroy1_8 = new int[0];
ArrayList<Packet> packets1_8 = new ArrayList<Packet>();
if (_hologramText.length != newText.length)
{
if (_hologramText.length != newText.length) {
_makeDestroyPackets = true;
}
for (int i = 0; i < Math.max(_hologramText.length, newText.length); i++)
{
for (int i = 0; i < Math.max(_hologramText.length, newText.length); i++) {
// If more lines than previously
if (i >= _hologramText.length)
{
if (i >= _hologramText.length) {
// Add entity id and send spawn packets
// You add a entity id because the new hologram needs
int entityId = UtilEnt.getNewEntityId();
@ -511,16 +468,13 @@ public class Hologram
packets1_8.addAll(Arrays.asList(makeSpawnPackets1_8(i, entityId, newText[i])));
}
// If less lines than previously
else if (i >= newText.length)
{
else if (i >= newText.length) {
// Remove entity id and send destroy packets
Integer entityId = _entityIds.remove(newText.length);
destroy1_8 = Arrays.copyOf(destroy1_8, destroy1_8.length + 1);
destroy1_8[destroy1_8.length - 1] = entityId;
}
else if (!newText[i].equals(_hologramText[i]))
{
} else if (!newText[i].equals(_hologramText[i])) {
// Send update metadata packets
Integer entityId = _entityIds.get(i);
@ -533,7 +487,8 @@ public class Hologram
watcher1_8.a(0, (byte) 32, EntityArmorStand.META_ENTITYDATA, (byte) 32);
watcher1_8.a(2, newText[i], EntityArmorStand.META_CUSTOMNAME, newText[i]);
watcher1_8.a(3, (byte) 1, EntityArmorStand.META_CUSTOMNAME_VISIBLE, true);
// watcher1_8.a(10, (byte) 16);// TODO Uncomment after we can enforce 1.8.3
// watcher1_8.a(10, (byte) 16);// TODO Uncomment after we
// can enforce 1.8.3
// Also correct hologram positioning
metadata1_8.b = watcher1_8.c();
@ -541,15 +496,12 @@ public class Hologram
}
}
if (destroy1_8.length > 0)
{
if (destroy1_8.length > 0) {
packets1_8.add(new PacketPlayOutEntityDestroy(destroy1_8));
}
for (Player player : _playersTracking)
{
for (Packet packet : packets1_8)
{
for (Player player : _playersTracking) {
for (Packet packet : packets1_8) {
UtilPlayer.sendPacket(player, packet);
}
}
@ -564,8 +516,7 @@ public class Hologram
/**
* Set the distance the hologram is viewable from. Default is 70
*/
public Hologram setViewDistance(int newDistance)
{
public Hologram setViewDistance(int newDistance) {
_viewDistance = newDistance;
return setLocation(getLocation());
}
@ -573,15 +524,15 @@ public class Hologram
/**
* Start the hologram
*/
public Hologram start()
{
if (!isInUse())
{
public Hologram start() {
if (!isInUse()) {
_startTime = System.currentTimeMillis();
_hologramManager.addHologram(this);
_playersTracking.addAll(getNearbyPlayers());
for (Player player : _playersTracking)
{
for (Player player : _playersTracking) {
UtilPlayer.sendPacket(player, getSpawnPackets());
}
@ -593,14 +544,11 @@ public class Hologram
/**
* Stop the hologram
*/
public Hologram stop()
{
if (isInUse())
{
public Hologram stop() {
if (isInUse()) {
_hologramManager.removeHologram(this);
for (Player player : _playersTracking)
{
for (Player player : _playersTracking) {
UtilPlayer.sendPacket(player, getDestroyPacket());
}

View File

@ -5,6 +5,7 @@ import java.util.Iterator;
import java.util.List;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilTime;
import mineplex.core.packethandler.IPacketHandler;
import mineplex.core.packethandler.PacketHandler;
import mineplex.core.packethandler.PacketInfo;
@ -52,15 +53,20 @@ public class HologramManager implements Listener, IPacketHandler
List<World> worlds = Bukkit.getWorlds();
Iterator<Hologram> itel = _activeHolograms.iterator();
Iterator<Hologram> iterator = _activeHolograms.iterator();
while (itel.hasNext())
while (iterator.hasNext())
{
Hologram hologram = itel.next();
if (!worlds.contains(hologram.getLocation().getWorld()))
Hologram hologram = iterator.next();
if (hologram.getMaxLifetime() != -1 && UtilTime.elapsed(hologram.getStartTime(), hologram.getMaxLifetime()))
{
itel.remove();
iterator.remove();
hologram.stop();
}
else if (!worlds.contains(hologram.getLocation().getWorld()))
{
iterator.remove();
hologram.stop();
}
else
@ -71,7 +77,7 @@ public class HologramManager implements Listener, IPacketHandler
if (hologram.isRemoveOnEntityDeath() && !following.isValid())
{
itel.remove();
iterator.remove();
hologram.stop();
continue;
}

View File

@ -0,0 +1,185 @@
package mineplex.core.incognito;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
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.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import com.google.common.base.Function;
import mineplex.core.MiniDbClientPlugin;
import mineplex.core.account.CoreClientManager;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.incognito.commands.IncognitoToggleCommand;
import mineplex.core.incognito.events.IncognitoHidePlayerEvent;
import mineplex.core.incognito.events.IncognitoStatusChangeEvent;
import mineplex.core.incognito.repository.IncognitoClient;
import mineplex.core.incognito.repository.IncognitoRepository;
import mineplex.core.packethandler.PacketHandler;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class IncognitoManager extends MiniDbClientPlugin<IncognitoClient>
{
private CoreClientManager _clientManager;
private IncognitoRepository _repository;
public IncognitoManager(JavaPlugin plugin, CoreClientManager clientManager, PacketHandler packetHandler)
{
super("Incognito", plugin, clientManager);
_repository = new IncognitoRepository(this);
_clientManager = clientManager;
}
public void addCommands()
{
addCommand(new IncognitoToggleCommand(this));
}
public boolean toggle(Player caller)
{
boolean enabled = !Get(caller).Status;
IncognitoStatusChangeEvent event = UtilServer.CallEvent(new IncognitoStatusChangeEvent(caller, enabled));
if (event.isCancelled())
{
return false;
}
Get(caller).Status = enabled;
if (!enabled)
{
if (event.doShow())
{
for (Player other : UtilServer.getPlayers())
{
other.showPlayer(caller);
}
}
}
else
{
IncognitoHidePlayerEvent customEvent = UtilServer.CallEvent(new IncognitoHidePlayerEvent(caller));
if (!customEvent.isCancelled())
{
UtilServer.getPlayersCollection().forEach(player -> {
player.hidePlayer(caller);
});
}
}
runAsync(() -> _repository.setStatus(_clientManager.getAccountId(caller), enabled));
return enabled;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void Join(PlayerJoinEvent event)
{
Player player = event.getPlayer();
if (Get(event.getPlayer()).Status && !_clientManager.hasRank(event.getPlayer(), Rank.HELPER))
{
Get(event.getPlayer()).Status = false;
runAsync(() -> _repository.setStatus(_clientManager.getAccountId(player), false));
return;
}
if (Get(event.getPlayer()).Status)
{
event.setJoinMessage(null);
informIncognito(player);
}
IncognitoHidePlayerEvent customEvent = null;
if (Get(event.getPlayer()).Status)
{
customEvent = UtilServer.CallEvent(new IncognitoHidePlayerEvent(player));
}
for (Player other : UtilServer.getPlayers())
{
if (customEvent != null && !customEvent.isCancelled() && !_clientManager.hasRank(other, _clientManager.Get(player).GetRank()))
{
other.hidePlayer(player);
}
if (Get(other).Status)
{
IncognitoHidePlayerEvent customEvent2 = UtilServer.CallEvent(new IncognitoHidePlayerEvent(other));
if (!customEvent2.isCancelled() && !_clientManager.hasRank(player, _clientManager.Get(other).GetRank()))
{
player.hidePlayer(other);
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void Quit(PlayerQuitEvent event)
{
if (Get(event.getPlayer()).Status)
{
event.setQuitMessage(null);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void Kick(PlayerKickEvent event)
{
if (Get(event.getPlayer()).Status)
{
event.setLeaveMessage(null);
}
}
private void informIncognito(Player player)
{
UtilPlayer.message(player, " ");
UtilPlayer.message(player, C.cGoldB + "You are currently incognito.");
UtilPlayer.message(player, C.cYellow + "This means you are invisible to all except for those who are " + _clientManager.Get(player).GetRank().getTag(true, false) + C.mBody + "+");
UtilPlayer.message(player, " ");
}
protected IncognitoClient AddPlayer(String player)
{
return new IncognitoClient();
}
public IncognitoRepository getRepository()
{
return _repository;
}
@Override
public String getQuery(int accountId, String uuid, String name)
{
return "SELECT * FROM incognitoStaff WHERE accountId = " + accountId + ";";
}
@Override
public void processLoginResultSet(String playerName, int accountId, ResultSet resultSet) throws SQLException
{
while (resultSet.next())
{
Get(playerName).Status = resultSet.getInt("status") == 1;
}
}
}

View File

@ -0,0 +1,30 @@
package mineplex.core.incognito.commands;
import org.bukkit.entity.Player;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.incognito.IncognitoManager;
public class IncognitoToggleCommand extends CommandBase<IncognitoManager>
{
public IncognitoToggleCommand(IncognitoManager plugin)
{
super(plugin, Rank.HELPER, "incognito", "vanish");
}
@Override
public void Execute(Player caller, String[] args)
{
if (Plugin.toggle(caller))
{
UtilPlayer.message(caller, F.main("Incognito", "You are now incognito. Your status will only change when you run " + F.elem(AliasUsed) + " again."));
}
else
{
UtilPlayer.message(caller, F.main("Incognito", "You are no longer incognito. Your status will only change when you run " + F.elem(AliasUsed) + " again."));
}
}
}

View File

@ -0,0 +1,47 @@
package mineplex.core.incognito.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Called when an Incognito player is getting hidden from all other players.
*/
public class IncognitoHidePlayerEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private Player _player;
private boolean _cancelled;
public IncognitoHidePlayerEvent(Player player)
{
_player = player;
}
public Player getPlayer()
{
return _player;
}
public void setCancelled(boolean cancelled)
{
_cancelled = cancelled;
}
public boolean isCancelled()
{
return _cancelled;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -0,0 +1,64 @@
package mineplex.core.incognito.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
public class IncognitoStatusChangeEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private Player _player;
private boolean _newState;
private boolean _cancelled;
private boolean _show = true;
public IncognitoStatusChangeEvent(Player player, boolean newState)
{
_player = player;
_newState = newState;
}
public boolean getNewState()
{
return _newState;
}
public Player getPlayer()
{
return _player;
}
public void setCancelled(boolean cancelled)
{
_cancelled = cancelled;
}
public boolean isCancelled()
{
return _cancelled;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
public void show(boolean show)
{
_show = show;
}
public boolean doShow()
{
return _show;
}
}

View File

@ -0,0 +1,6 @@
package mineplex.core.incognito.repository;
public class IncognitoClient
{
public boolean Status;
}

View File

@ -0,0 +1,33 @@
package mineplex.core.incognito.repository;
import mineplex.core.database.MinecraftRepository;
import mineplex.core.incognito.IncognitoManager;
import mineplex.serverdata.database.DBPool;
import mineplex.serverdata.database.column.ColumnInt;
public class IncognitoRepository extends MinecraftRepository
{
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS incognitoStaff (accountId INT NOT NULL, status TINYINT(1) DEFAULT '0', PRIMARY KEY (accountId));";
private static final String INSERT_STATUS = "INSERT INTO incognitoStaff (accountId, status) VALUES (?, ?);";
private static final String UPDATE_STATUS = "UPDATE incognitoStaff SET status=? WHERE accountId=?;";
public IncognitoRepository(IncognitoManager incognitoManager)
{
super(incognitoManager.getPlugin(), DBPool.getAccount());
}
public void setStatus(int accountId, boolean status)
{
if (executeUpdate(UPDATE_STATUS, new ColumnInt("status", status ? 1 : 0), new ColumnInt("accountId", accountId)) <= 0)
executeInsert(INSERT_STATUS, null, new ColumnInt("accountId", accountId), new ColumnInt("status", status ? 1 : 0));
}
protected void initialize()
{
executeUpdate(CREATE_TABLE);
}
protected void update()
{
}
}

View File

@ -277,12 +277,9 @@ public class ItemBuilder
ItemBuilder newBuilder = new ItemBuilder(_mat);
newBuilder.setTitle(_title);
for (String lore : _lore)
{
newBuilder.addLore(lore);
}
_lore.forEach(newBuilder::addLore);
for (Map.Entry<Enchantment, Integer> entry : _enchants.entrySet())
{
newBuilder.addEnchantment(entry.getKey(), entry.getValue());

View File

@ -26,7 +26,13 @@ import mineplex.core.friend.FriendManager;
import mineplex.core.friend.data.FriendData;
import mineplex.core.friend.data.FriendStatus;
import mineplex.core.ignore.IgnoreManager;
import mineplex.core.message.commands.*;
import mineplex.core.incognito.IncognitoManager;
import mineplex.core.message.commands.AdminCommand;
import mineplex.core.message.commands.AnnounceCommand;
import mineplex.core.message.commands.MessageAdminCommand;
import mineplex.core.message.commands.MessageCommand;
import mineplex.core.message.commands.ResendAdminCommand;
import mineplex.core.message.commands.ResendCommand;
import mineplex.core.message.redis.AnnouncementHandler;
import mineplex.core.message.redis.MessageHandler;
import mineplex.core.message.redis.RedisMessage;
@ -44,6 +50,8 @@ public class MessageManager extends MiniClientPlugin<ClientMessage>
private CoreClientManager _clientManager;
private FriendManager _friendsManager;
private IgnoreManager _ignoreManager;
private IncognitoManager _incognitoManager;
private HashMap<UUID, BukkitRunnable> _messageTimeouts = new HashMap<UUID, BukkitRunnable>();
private PreferencesManager _preferences;
private Punish _punish;
@ -51,11 +59,12 @@ public class MessageManager extends MiniClientPlugin<ClientMessage>
private ArrayList<String> _randomMessage;
private String _serverName;
public MessageManager(JavaPlugin plugin, CoreClientManager clientManager, PreferencesManager preferences,
public MessageManager(JavaPlugin plugin, IncognitoManager incognitoManager, CoreClientManager clientManager, PreferencesManager preferences,
IgnoreManager ignoreManager, Punish punish, FriendManager friendManager, Chat chat)
{
super("Message", plugin);
_incognitoManager = incognitoManager;
_clientManager = clientManager;
_preferences = preferences;
_ignoreManager = ignoreManager;
@ -85,7 +94,7 @@ public class MessageManager extends MiniClientPlugin<ClientMessage>
addCommand(new AnnounceCommand(this));
//addCommand(new GlobalCommand(this));
addCommand(new AdminCommand(this));
addCommand(new AdminCommand(this, _incognitoManager));
}
@Override
@ -462,10 +471,9 @@ public class MessageManager extends MiniClientPlugin<ClientMessage>
{
FriendData friends = _friendsManager.Get(sender);
FriendStatus friend = null;
if (!adminMessage)
{
for (FriendStatus friendInfo : friends.getFriends())
{
@ -523,6 +531,12 @@ public class MessageManager extends MiniClientPlugin<ClientMessage>
// If this is a message inside the server
if (to != null)
{
if (_incognitoManager.Get(to).Status)
{
UtilPlayer.message(sender, F.main("Online Player Search", F.elem("0") + " matches for [" + F.elem(target) + "]."));
return;
}
if (adminMessage)
{
DoMessageAdmin(sender, to, message);
@ -542,45 +556,63 @@ public class MessageManager extends MiniClientPlugin<ClientMessage>
// If this is a admin message, or the sender isn't muted/ignoring the target
if (adminMessage || canSenderMessageThem(sender, playerTarget))
{
// Construct the command to send to redis
RedisMessage globalMessage = new RedisMessage(_serverName,
sender.getName(),
adminMessage ? null : friend.ServerName,
playerTarget,
message,
// Include the sender's rank if this is a admin message. So we can format the receivers chat.
adminMessage ? F.rank(_clientManager.Get(sender).GetRank()) : null);
final UUID uuid = globalMessage.getUUID();
// A backup for the rare case where the message fails to deliver. Server doesn't respond
BukkitRunnable runnable = new BukkitRunnable()
{
public void run()
runAsync(new Runnable()
{
_messageTimeouts.remove(uuid);
// Inform the player that the message failed to deliver
UtilPlayer.message(
sender,
F.main((adminMessage ? "Admin " : "") + "Message", C.mBody + " Failed to send message to ["
+ C.mElem + playerTarget + C.mBody + "]."));
@Override
public void run()
{
// TODO Newgarbo wrote this stuff inefficiently and for sake of time and thousands of players i'm going to just comment this out
/*
if (IncognitoManager.Instance.getRepository().GetStatus(playerTarget))
{
UtilPlayer.message(sender, F.main("Online Player Search", F.elem("0") + " matches for [" + F.elem(target) + "]."));
return;
}
*/
runSync(new Runnable()
{
public void run()
{
// Construct the command to send to redis
RedisMessage globalMessage = new RedisMessage(_serverName,
sender.getName(),
adminMessage ? null : friend.ServerName,
playerTarget,
message,
// Include the sender's rank if this is a admin message. So we can format the receivers chat.
adminMessage ? F.rank(_clientManager.Get(sender).GetRank()) : null);
final UUID uuid = globalMessage.getUUID();
// A backup for the rare case where the message fails to deliver. Server doesn't respond
BukkitRunnable runnable = new BukkitRunnable()
{
public void run()
{
_messageTimeouts.remove(uuid);
// Inform the player that the message failed to deliver
UtilPlayer.message(
sender,
F.main((adminMessage ? "Admin " : "") + "Message", C.mBody + " Failed to send message to ["
+ C.mElem + playerTarget + C.mBody + "]."));
}
};
// This will activate in 2 seconds
runnable.runTaskLater(getPlugin(), 40);
// The key is the UUID its trading between servers
_messageTimeouts.put(uuid, runnable);
// Time to send the message!
globalMessage.publish();
}
});
}
}
};
// This will activate in 2 seconds
runnable.runTaskLater(getPlugin(), 40);
// The key is the UUID its trading between servers
_messageTimeouts.put(uuid, runnable);
// Time to send the message!
globalMessage.publish();
);
}
}
}

View File

@ -9,14 +9,18 @@ import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.incognito.IncognitoManager;
import mineplex.core.message.MessageManager;
import mineplex.core.visibility.VisibilityManager;
public class AdminCommand extends CommandBase<MessageManager>
{
public AdminCommand(MessageManager plugin)
private IncognitoManager _incognitoManager;
public AdminCommand(MessageManager plugin, IncognitoManager incognitoManager)
{
super(plugin, Rank.ALL, "a","admin");
_incognitoManager = incognitoManager;
}
@Override
@ -51,6 +55,11 @@ public class AdminCommand extends CommandBase<MessageManager>
{
if (Plugin.GetClientManager().Get(to).GetRank().has(Rank.HELPER))
{
if (_incognitoManager.Get(to).Status)
{
continue;
}
if (!to.equals(caller))
UtilPlayer.message(to, F.rank(Plugin.GetClientManager().Get(caller).GetRank()) + " " + caller.getName() + " " + C.cPurple + message);

View File

@ -1,18 +1,15 @@
package mineplex.core.message.commands;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import mineplex.core.command.CommandBase;
import mineplex.core.common.Rank;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilTextMiddle;
import mineplex.core.message.MessageManager;
import mineplex.serverdata.commands.AnnouncementCommand;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class AnnounceCommand extends CommandBase<MessageManager>
{
public AnnounceCommand(MessageManager plugin)

View File

@ -478,6 +478,17 @@ public class NpcManager extends MiniPlugin
}
}
public void addFakeNpc(Npc npc)
{
_npcs.add(npc);
}
public void removeFakeNpc(Npc npc)
{
_npcs.remove(npc);
npc.getEntity().remove();
}
public void loadNpcs() throws SQLException
{
String serverType = getServerName();

View File

@ -87,7 +87,8 @@ public class PacketHandler extends MiniPlugin
return _playerVerifierMap.get(player);
}
public void addPacketHandler(IPacketHandler packetHandler, Class<? extends Packet>... packetsToListen)
@SafeVarargs
public final void addPacketHandler(IPacketHandler packetHandler, Class<? extends Packet>... packetsToListen)
{
if (packetsToListen.length == 0)
{

View File

@ -16,6 +16,8 @@ import org.bukkit.plugin.java.JavaPlugin;
import com.google.common.base.Objects;
import mineplex.core.MiniPlugin;
import mineplex.core.common.MinecraftVersion;
import mineplex.core.common.Pair;
import mineplex.core.common.jsonchat.ClickEvent;
import mineplex.core.common.jsonchat.JsonMessage;
import mineplex.core.common.util.C;
@ -31,7 +33,7 @@ import mineplex.serverdata.commands.ServerCommandManager;
public class ResourcePackManager extends MiniPlugin implements CommandCallback
{
private String _resourcePackUrl;
private Pair<MinecraftVersion, String>[] _resourcePackUrls;
private boolean _resourcePackRequired;
private NautHashMap<String, Boolean> _resourcePackUsers = new NautHashMap<String, Boolean>();
private NautHashMap<String, Long> _resourcePackNoResponse = new NautHashMap<String, Long>();
@ -45,13 +47,32 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback
ServerCommandManager.getInstance().registerCommandType("RedisUnloadResPack", RedisUnloadResPack.class, this);
}
public void setPlayerPack(Player player)
{
MinecraftVersion version = UtilPlayer.getVersion(player);
if (_resourcePackUrls == null || _resourcePackUrls.length == 0)
return;
for (Pair<MinecraftVersion, String> entry : _resourcePackUrls)
{
if (entry.getLeft() == version || entry.getLeft() == MinecraftVersion.ALL)
{
player.setResourcePack(entry.getRight());
return;
}
}
player.setResourcePack(_resourcePackUrls[0].getRight());
}
@EventHandler
public void ResourcePackJoin(PlayerJoinEvent event)
{
Player player = event.getPlayer();
if (_resourcePackUrl == null)
if (_resourcePackUrls == null)
{
return;
}
@ -62,7 +83,8 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback
}
_resourcePackUsers.put(player.getName(), false);
player.setResourcePack(_resourcePackUrl);
setPlayerPack(player);
}
@EventHandler
@ -89,14 +111,15 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback
// Send it again, enforce it!
_resourcePackNoResponse.put(player.getName(), System.currentTimeMillis());
player.setResourcePack(_resourcePackUrl);
setPlayerPack(player);
}
}
@EventHandler
public void onResourcePackStatus(PlayerResourcePackStatusEvent event)
{
if (_resourcePackUrl == null)
if (_resourcePackUrls == null)
{
return;
}
@ -176,19 +199,19 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback
returnHubNoResPack(player);
}
public void setResourcePack(String resourcePack, boolean forceResourcePack)
public void setResourcePack(Pair<MinecraftVersion, String>[] resourcePack, boolean forceResourcePack)
{
if (Objects.equal(resourcePack, _resourcePackUrl) && forceResourcePack == _resourcePackRequired)
if (Objects.equal(resourcePack, _resourcePackUrls) && forceResourcePack == _resourcePackRequired)
{
return;
}
_resourcePackNoResponse.clear();
_resourcePackUsers.clear();
_resourcePackUrl = resourcePack == null || resourcePack.isEmpty() ? null : resourcePack;
_resourcePackUrls = resourcePack == null || (resourcePack.length == 0) ? null : resourcePack;
_resourcePackRequired = forceResourcePack;
if (_resourcePackUrl == null || _resourcePackUrl.isEmpty())
if (_resourcePackUrls == null || _resourcePackUrls.length == 0)
{
_resourcePackRequired = false;
@ -207,7 +230,8 @@ public class ResourcePackManager extends MiniPlugin implements CommandCallback
}
_resourcePackUsers.put(player.getName(), false);
player.setResourcePack(_resourcePackUrl);
setPlayerPack(player);
}
}
}

View File

@ -23,15 +23,15 @@ import mineplex.core.shop.item.IButton;
public abstract class ShopPageBase<PluginType extends MiniPlugin, ShopType extends ShopBase<PluginType>> extends CraftInventoryCustom implements Listener
{
private PluginType _plugin;
private CoreClientManager _clientManager;
private DonationManager _donationManager;
private ShopType _shop;
private Player _player;
private CoreClient _client;
private CurrencyType _currencyType;
private NautHashMap<Integer, IButton> _buttonMap;
private boolean _showCurrency = false;
protected PluginType _plugin;
protected CoreClientManager _clientManager;
protected DonationManager _donationManager;
protected ShopType _shop;
protected Player _player;
protected CoreClient _client;
protected CurrencyType _currencyType;
protected NautHashMap<Integer, IButton> _buttonMap;
protected boolean _showCurrency = false;
private int _currencySlot = 4;

View File

@ -0,0 +1,129 @@
package mineplex.core.slack;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import com.google.gson.JsonObject;
import mineplex.core.thread.ThreadPool;
/**
* An API for sending and handling Slack messages.
*/
public class SlackAPI
{
// Default emoji.
public static final String DEFAULT_ICON = ":mineplex:";
// Singular instance.
private static SlackAPI _instance;
// Don't allow instantiation elsewhere.
private SlackAPI() {}
/**
* Sends a message asynchronously to a Slack channel.
*
* @param team The team which contains the target channel.
* @param channel The target channel for the message.
* @param message The message to be displayed.
* @param customTitle Whether or not to use a custom title for the message.
* If <code>false</code> the default team title is used.
*/
public void sendMessage(SlackTeam team, String channel, SlackMessage message, boolean customTitle)
{
ThreadPool.ASYNC.execute(() ->
{
// Set message title.
if (!customTitle)
{
message.setUsername(team.getTitle());
message.setIcon(DEFAULT_ICON);
}
// Set message channel.
JsonObject msg = message.toJson();
msg.addProperty("channel", channel);
// Run the call.
runWebCall(team, msg);
});
}
/**
* Runs a web call to a specified Slack incoming-hook.
*
* @param team The team to run the call on.
* @param call The call to be run.
*/
private String runWebCall(SlackTeam team, JsonObject call)
{
HttpURLConnection connection = null;
try
{
// Create connection.
URL url = new URL(team.getURL());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Setup payload.
String payload = "payload=" + URLEncoder.encode(call.toString(), "UTF-8");
// Send request.
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes(payload);
dos.flush();
dos.close();
// Receive response.
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
String response = "";
while ((line = rd.readLine()) != null)
{
response += line + "\n";
}
rd.close();
return response.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (connection != null)
{
// Terminate connection.
connection.disconnect();
}
}
return "500 Error";
}
/**
* Gets the singular instance of the Slack API.
*
* @return The {@link SlackAPI} instance.
*/
public static SlackAPI getInstance()
{
if (_instance == null)
{
_instance = new SlackAPI();
}
return _instance;
}
}

View File

@ -0,0 +1,139 @@
package mineplex.core.slack;
import com.google.gson.JsonObject;
/**
* A message to be sent through the {@link SlackAPI}.
*/
public class SlackMessage
{
private String _username;
private String _icon;
private String _content;
/**
* Class constructor.
*
* @param content The content of the message.
*/
public SlackMessage(String content)
{
_icon = SlackAPI.DEFAULT_ICON;
_content = content;
}
/**
* Class constructor.
*
* @param username The username of the message.
* @param content The content of the message.
*/
public SlackMessage(String username, String content)
{
_username = username;
_icon = SlackAPI.DEFAULT_ICON;
_content = content;
}
/**
* Class constructor.
*
* @param username The username of the message.
* @param icon The icon/emoji of the message.
* @param content The content of the message.
*/
public SlackMessage(String username, String icon, String content)
{
_username = username;
_icon = ":" + icon + ":";
_content = content;
}
/**
* Converts the message to JSON format.
*
* @return The {@link SlackMessage} in the form of a {@link JsonObject}.
*/
public JsonObject toJson()
{
JsonObject msg = new JsonObject();
if (_username != null)
{
msg.addProperty("username", _username);
}
if (_icon != null)
{
msg.addProperty("icon_emoji", _icon);
}
if (_content != null)
{
msg.addProperty("text", _content);
}
return msg;
}
/**
* Gets the username that displays as a title.
*
* @return The username in use.
*/
public String getUsername()
{
return _username;
}
/**
* Sets the username that displays as a title.
*
* @param username The username to use.
*/
public void setUsername(String username)
{
_username = username;
}
/**
* Gets the icon that displays with the title.
*
* @return The icon in use.
*/
public String getIcon()
{
return _icon;
}
/**
* Sets the icon that displays with the title.
*
* @param icon The icon to use.
*/
public void setIcon(String icon)
{
_icon = icon;
}
/**
* Gets the content of the message.
*
* @return The content of the message.
*/
public String getContent()
{
return _content;
}
/**
* Sets the content of the message.
*
* @param content The content of the message.
*/
public void setContent(String content)
{
_content = content;
}
}

View File

@ -0,0 +1,79 @@
package mineplex.core.slack;
/**
* An enumeration of Mineplex Slack teams.
*/
public enum SlackTeam
{
// Dev team - mineplex.slack.com
DEVELOPER("Mineplex Dev", "T045RUM7F", "B0VK6GFKN", "6GxwJsDfEpbVnQl8pYuEyq5T"),
// QA team - mineplexqa.slack.com
QA("Mineplex QA", "todo", "todo", "todo"), // TODO: new details
;
private String _title;
private String _id1;
private String _id2;
private String _token;
SlackTeam(String title, String id1, String id2, String token)
{
_title = title;
_id1 = id1;
_id2 = id2;
_token = token;
}
/**
* Gets the title that will be displayed that the top of each
* {@link SlackMessage}.
*
* @return The title of this team.
*/
public String getTitle()
{
return _title;
}
/**
* Gets the first ID of this Slack team.
*
* @return The individual first ID.
*/
public String getId1()
{
return _id1;
}
/**
* Gets the second ID of this Slack team.
*
* @return The individual second ID.
*/
public String getId2()
{
return _id2;
}
/**
* Gets the token key of this Slack team.
*
* @return The individual and <b>secret</b> token.
*/
public String getToken()
{
return _token;
}
/**
* Gets the web hook in the form of a URL.
*
* @return The URL as a string.
*/
public String getURL()
{
return "https://hooks.slack.com/services/" + getId1() + "/" + getId2() + "/" + getToken();
}
}

View File

@ -294,6 +294,8 @@ public class StatsManager extends MiniDbClientPlugin<PlayerStats>
});
}
public int getStatId(String statName)
{
return _stats.get(statName);

View File

@ -118,7 +118,7 @@ public class TaskManager extends MiniDbClientPlugin<TaskClient>
{
public void run(Boolean success)
{
if (!success)
if (!success.booleanValue())
{
System.out.println("Add task FAILED for " + player.getName());

View File

@ -0,0 +1,154 @@
package mineplex.core.texttutorial;
import java.util.HashSet;
import java.util.Iterator;
import org.bukkit.Sound;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.C;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.donation.DonationManager;
import mineplex.core.task.TaskManager;
import mineplex.core.texttutorial.tutorial.Tutorial;
import mineplex.core.texttutorial.tutorial.TutorialData;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class TextTutorialManager extends MiniPlugin
{
private DonationManager _donationManager;
private TaskManager _taskManager;
private HashSet<Tutorial> _tutorials;
public TextTutorialManager(JavaPlugin plugin, DonationManager donationManager, TaskManager taskManager)
{
super("Text Tutorial", plugin);
_donationManager = donationManager;
_taskManager = taskManager;
}
@EventHandler
public void startTutorial(PlayerInteractEntityEvent event)
{
if (isInTutorial(event.getPlayer()))
return;
if (!(event.getRightClicked() instanceof LivingEntity))
return;
LivingEntity ent = (LivingEntity)event.getRightClicked();
String name = ent.getCustomName();
if (name == null)
return;
for (Tutorial tut : _tutorials)
{
if (name.contains(tut.getName()))
{
UtilPlayer.message(event.getPlayer(), F.main("Tutorial", "You started " + F.elem(tut.getName()) + "."));
tut.startTutorial(event.getPlayer());
return;
}
}
}
@EventHandler
public void update(UpdateEvent event)
{
if (event.getType() != UpdateType.TICK)
return;
for (final Tutorial tut : _tutorials)
{
Iterator<TutorialData> iterator = tut.getTutorialDatas().iterator();
while (iterator.hasNext())
{
TutorialData data = iterator.next();
final Player player = data.getPlayer();
//Check if Phase Completed
if (data.tick())
{
//Next Phase
if (data.getPhaseStep() < tut.getPhaseSize())
{
data.setNextPhase(tut.getPhase(data.getPhaseStep()));
}
//End Tutorial
else
{
iterator.remove();
//Inform
UtilPlayer.message(player, F.main("Tutorial", "You completed " + F.elem(tut.getName()) + "."));
//Gems
if (tut.getGemReward() > 0)
{
if (!_taskManager.hasCompletedTask(player, tut.getTaskId()))
{
_taskManager.completedTask(new Callback<Boolean>()
{
public void run(Boolean completed)
{
_donationManager.RewardGems(new Callback<Boolean>()
{
public void run(Boolean completed)
{
if (completed)
{
UtilPlayer.message(player, F.main("Tutorial", "You received " + F.elem(C.cGreen + tut.getGemReward() + " Gems") + "."));
//Sound
player.playSound(player.getLocation(), Sound.LEVEL_UP, 2f, 1.5f);
}
}
}, "Tutorial " + tut.getName(), player.getName(), player.getUniqueId(), tut.getGemReward());
}
}, player, tut.getTaskId());
}
}
}
}
}
}
}
@EventHandler
public void playerQuit(PlayerQuitEvent event)
{
for (Tutorial tut : _tutorials)
tut.stopTutorial(event.getPlayer());
}
@EventHandler
public void cancelInteract(PlayerInteractEvent event)
{
if (isInTutorial(event.getPlayer()))
event.setCancelled(true);
}
public boolean isInTutorial(Player player)
{
for (Tutorial tutorial : _tutorials)
{
if (tutorial.isInTutorial(player))
return true;
}
return false;
}
}

View File

@ -0,0 +1,47 @@
package mineplex.core.texttutorial.tutorial;
import org.bukkit.Location;
public class Phase
{
private Location _location;
private String _header;
private String[] _text;
public Phase(Location location, String header, String[] text)
{
_location = location;
_header = header;
_text = text;
}
public Location getLocation()
{
return _location;
}
public void setLocation(Location location)
{
_location = location;
}
public String getHeader()
{
return _header;
}
public void setHeader(String header)
{
_header = header;
}
public String[] getText()
{
return _text;
}
public void setText(String[] text)
{
_text = text;
}
}

View File

@ -0,0 +1,74 @@
package mineplex.core.texttutorial.tutorial;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import org.bukkit.entity.Player;
public abstract class Tutorial
{
private String _name;
private String _taskId;
private int _gemReward;
private ArrayList<Phase> _phases;
private HashMap<Player, TutorialData> _playerMap;
public Tutorial(String name, String taskId, int gemReward)
{
_name = name;
_taskId = taskId;
_gemReward = gemReward;
}
public String getName()
{
return _name;
}
public String getTaskId()
{
return _taskId;
}
public void startTutorial(Player player)
{
_playerMap.put(player, new TutorialData(player, _phases.get(0)));
}
public void stopTutorial(Player player)
{
_playerMap.remove(player);
}
public boolean isInTutorial(Player player)
{
return _playerMap.containsKey(player);
}
protected void addPhase(Phase phase)
{
_phases.add(phase);
}
public Collection<TutorialData> getTutorialDatas()
{
return _playerMap.values();
}
public Phase getPhase(int phaseIndex)
{
return _phases.get(phaseIndex);
}
public int getPhaseSize()
{
return _phases.size();
}
public int getGemReward()
{
return _gemReward;
}
}

View File

@ -0,0 +1,102 @@
package mineplex.core.texttutorial.tutorial;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilPlayer;
public class TutorialData
{
private Player _player;
private Phase _phase;
private int _phaseStep;
private int _textStep;
private long _sleep;
public TutorialData(Player player, Phase startPhase)
{
_player = player;
_phase = startPhase;
_phaseStep = 0;
_textStep = 0;
_sleep = System.currentTimeMillis() + 3000;
}
public boolean tick()
{
if (!_player.getLocation().equals(_phase.getLocation()))
_player.teleport(_phase.getLocation());
if (System.currentTimeMillis() < _sleep)
return false;
if (_textStep >= _phase.getText().length)
{
// No more text to display, move to next phase
_phaseStep++;
_sleep = System.currentTimeMillis() + 2000;
return true;
}
// Display Text
String text = _phase.getText()[_textStep];
UtilPlayer.message(_player, " ");
UtilPlayer.message(_player, " ");
UtilPlayer.message(_player, " ");
UtilPlayer.message(_player, C.cGreen + C.Strike + C.Bold + "========================================");
UtilPlayer.message(_player, C.cGold + C.Bold + _phase.getHeader());
UtilPlayer.message(_player, " ");
for (int i=0 ; i<=_textStep ; i++)
UtilPlayer.message(_player, " " + _phase.getText()[i]);
for (int i=_textStep ; i<=5 ; i++)
UtilPlayer.message(_player, " ");
UtilPlayer.message(_player, C.cGreen + C.Strike + C.Bold + "========================================");
if (text.length() > 0)
{
_player.playSound(_player.getLocation(), Sound.ORB_PICKUP, 2f, 1.5f);
_sleep = System.currentTimeMillis() + 1000 + (50*text.length());
}
else
{
_sleep = System.currentTimeMillis() + 600;
}
_textStep++;
return false;
}
public void setNextPhase(Phase phase)
{
_phase = phase;
_textStep = 0;
_player.teleport(_phase.getLocation());
}
public Phase getPhase()
{
return _phase;
}
public long getSleep()
{
return _sleep;
}
public int getPhaseStep()
{
return _phaseStep;
}
public Player getPlayer()
{
return _player;
}
}

View File

@ -0,0 +1,19 @@
package mineplex.core.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
/**
* A collection of threads for different uses.
*/
public class ThreadPool
{
// Async Thread
public static ExecutorService ASYNC = Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("MiniPlugin Async %1$d").build()
);
}

View File

@ -53,9 +53,13 @@ public enum UpdateType
*/
SLOWEST(32000),
/**
* ONce every 30 seconds
* Once every 30 seconds
*/
SEC_30(30000),
/**
* Once every 20 seconds
*/
SEC_20(20000),
/**
* Once every 16 seconds
*/
@ -64,6 +68,10 @@ public enum UpdateType
* Once every 8 seconds
*/
SEC_08(8000),
/**
* Once every 5 seconds
*/
SEC_05(5000),
/**
* Once every 4 seconds
*/

View File

@ -44,9 +44,9 @@ public class ClanRepository extends MinecraftRepository
private static String CREATE_CLAN_TERRITORY_TABLE = "CREATE TABLE IF NOT EXISTS clanTerritory (id INT NOT NULL AUTO_INCREMENT, clanId INT, chunk VARCHAR(100), safe BIT(1), PRIMARY KEY (id), FOREIGN KEY (clanId) REFERENCES clans(id));";
private static String CREATE_CLAN_ALLIANCE_TABLE = "CREATE TABLE IF NOT EXISTS clanAlliances (id INT NOT NULL AUTO_INCREMENT, clanId INT, otherClanId INT, trusted BIT(1), PRIMARY KEY (id), FOREIGN KEY (otherClanId) REFERENCES clans(id), FOREIGN KEY (clanId) REFERENCES clans(id), INDEX clanIdIndex (clanId));";
private static String RETRIEVE_CLAN_INFO = "SELECT c.id, c.name, c.description, c.home, c.admin, c.energy, c.kills, c.murder, c.deaths, c.warWins, c.warLosses, c.generator, c.generatorStock, c.dateCreated, c.lastOnline FROM clans AS c WHERE lower(c.name) = ?;";
private static String RETRIEVE_CLAN_INFO = "SELECT c.id, c.name, c.description, c.home, c.admin, c.energy, c.kills, c.murder, c.deaths, c.warWins, c.warLosses, c.generator, c.generatorStock, c.dateCreated, c.lastOnline, c.eloRating FROM clans AS c WHERE lower(c.name) = ?;";
private static String RETRIEVE_PLAYER_CLAN_INFO = "SELECT clans.name, accountClan.clanRole, clanServer.serverName, clans.id FROM accountClan INNER JOIN clans ON clans.id = accountClan.clanId INNER JOIN clanServer ON clans.serverId = clanServer.id WHERE accountClan.accountId = ?;";
private static String RETRIEVE_START_CLAN_INFO = "SELECT c.id, c.name, c.description, c.home, c.admin, c.energy, c.kills, c.murder, c.deaths, c.warWins, c.warLosses, c.generator, c.generatorStock, c.dateCreated, c.lastOnline, ct.chunk, ct.safe FROM clans AS c LEFT JOIN clanTerritory AS ct ON ct.clanId = c.id WHERE c.serverId = ? OR c.admin = 1;";
private static String RETRIEVE_START_CLAN_INFO = "SELECT c.id, c.name, c.description, c.home, c.admin, c.energy, c.kills, c.murder, c.deaths, c.warWins, c.warLosses, c.generator, c.generatorStock, c.dateCreated, c.lastOnline, c.eloRating, ct.chunk, ct.safe FROM clans AS c LEFT JOIN clanTerritory AS ct ON ct.clanId = c.id WHERE c.serverId = ? OR c.admin = 1;";
private static String RETRIEVE_CLAN_MEMBER_INFO = "SELECT c.name, a.name, a.uuid, clanRole FROM accountClan AS ac INNER JOIN accounts AS a ON a.id = ac.accountId INNER JOIN clans AS c on c.id = ac.clanId WHERE c.serverId = ?;";
private static String RETRIEVE_CLAN_MEMBERS = "SELECT c.name, a.name, a.uuid, clanRole FROM accountClan AS ac INNER JOIN accounts AS a ON a.id = ac.accountId INNER JOIN clans AS c on c.id = ac.clanId WHERE lower(c.name) = ?;";
private static String RETRIEVE_CLAN_ALLIANCE_INFO = "SELECT c.name, cOther.name, ca.trusted FROM clanAlliances AS ca INNER JOIN clans AS c ON c.id = ca.clanId INNER JOIN clans as cOther ON cOther.id = ca.otherClanId WHERE c.serverId = ?;";
@ -71,6 +71,7 @@ public class ClanRepository extends MinecraftRepository
private static String ADD_CLAN_WAR = "INSERT INTO clanWar (initiatorId, clanId, score, created, lastUpdated) VALUES (?, ?, ?, ?, ?)";
private static String ADD_CLAN_TERRITORY = "INSERT INTO clanTerritory (clanId, chunk, safe) VALUES (?, ?, ?);";
//Not Sure if UPDATE_CLAN should set eloRating, but I would think it would need to
private static String UPDATE_CLAN = "UPDATE clans SET name = ?, description = ?, home = ?, admin = ?, energy = ?, kills = ?, murder = ?, deaths = ?, warWins = ?, warLosses = ?, lastOnline = ? WHERE id = ?;";
private static String UPDATE_CLAN_MEMBER = "UPDATE accountClan AS AC INNER JOIN accounts ON accounts.id = AC.accountId SET AC.clanRole = ? WHERE AC.clanId = ? AND accounts.name = ?;";
private static String UPDATE_CLAN_ALLIANCE = "UPDATE clanAlliances SET trusted = ? WHERE clanId = ? AND otherClanId = ?;";
@ -200,10 +201,12 @@ public class ClanRepository extends MinecraftRepository
clan.Deaths = resultSet.getInt(9);
clan.WarWins = resultSet.getInt(10);
clan.WarLosses = resultSet.getInt(11);
clan.Generator = resultSet.getString(12);
clan.GeneratorBuyer = resultSet.getString(12);
clan.GeneratorStock = resultSet.getInt(13);
clan.DateCreated = resultSet.getTimestamp(14);
clan.LastOnline = resultSet.getTimestamp(15);
clan.EloRating = resultSet.getInt(16);
}
}
}, new ColumnVarChar("name", 100, clanName.toLowerCase()));
@ -290,15 +293,18 @@ public class ClanRepository extends MinecraftRepository
token.Deaths = resultSet.getInt(9);
token.WarWins = resultSet.getInt(10);
token.WarLosses = resultSet.getInt(11);
token.Generator = resultSet.getString(12);
token.GeneratorBuyer = resultSet.getString(12);
token.GeneratorStock = resultSet.getInt(13);
token.DateCreated = resultSet.getTimestamp(14);
token.LastOnline = resultSet.getTimestamp(15);
token.EloRating = resultSet.getInt(16);
ClanTerritoryToken territoryToken = new ClanTerritoryToken();
territoryToken.ClanName = token.Name;
territoryToken.Chunk = resultSet.getString(16);
territoryToken.Safe = resultSet.getBoolean(17);
territoryToken.Chunk = resultSet.getString(17);
territoryToken.Safe = resultSet.getBoolean(18);
if (!clans.containsKey(token.Name))
{
@ -561,6 +567,11 @@ public class ClanRepository extends MinecraftRepository
// new ColumnInt("clanScore", clanScore), new ColumnInt("otherClanScore", otherClanScore), new ColumnInt("clanKills", clanKills),
// new ColumnInt("otherClanKills", otherClanKills), new ColumnInt("clanId", clanId), new ColumnInt("otherClanId", otherClanId));
// }
public int getServerId()
{
return _serverId;
}
public boolean updateClanGenerator(int clanId, String generator, int generatorStock)
{

View File

@ -17,7 +17,8 @@ public class ClanToken
public int Deaths;
public int WarWins;
public int WarLosses;
public String Generator;
public int EloRating;
public String GeneratorBuyer;
public int GeneratorStock;
public Timestamp DateCreated;
public Timestamp LastOnline;

View File

@ -3,7 +3,7 @@ package mineplex.game.clans.core.repository.tokens;
public class SimpleClanToken
{
private String _clanName;
private String _clanName = "";
public String getClanName() { return _clanName; }
private String _clanRole;
@ -22,4 +22,6 @@ public class SimpleClanToken
_homeServer = homeServer;
_clanId = clanId;
}
public SimpleClanToken() { }
}

View File

@ -7,20 +7,25 @@ import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.CustomTagFix;
import mineplex.core.FoodDupeFix;
import mineplex.core.PacketsInteractionFix;
import mineplex.core.account.CoreClientManager;
import mineplex.core.achievement.AchievementManager;
import mineplex.core.antihack.AntiHack;
import mineplex.core.blockrestore.BlockRestore;
import mineplex.core.chat.Chat;
import mineplex.core.command.CommandCenter;
import mineplex.core.common.MinecraftVersion;
import mineplex.core.common.Pair;
import mineplex.core.common.events.ServerShutdownEvent;
import mineplex.core.delayedtask.DelayedTask;
import mineplex.core.donation.DonationManager;
import mineplex.core.explosion.Explosion;
import mineplex.core.fallingblock.FallingBlocks;
import mineplex.core.friend.FriendManager;
import mineplex.core.give.Give;
import mineplex.core.hologram.HologramManager;
import mineplex.core.ignore.IgnoreManager;
import mineplex.core.incognito.IncognitoManager;
import mineplex.core.inventory.InventoryManager;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.memory.MemoryFix;
@ -53,7 +58,7 @@ import net.minecraft.server.v1_8_R3.MinecraftServer;
public class Clans extends JavaPlugin
{
public static final String VERSION = "1.0";
public static final String VERSION = "Beta 1.0";
private String WEB_CONFIG = "webServer";
// Modules
@ -88,6 +93,8 @@ public class Clans extends JavaPlugin
_donationManager = new DonationManager(this, _clientManager, webServerAddress);
new FallingBlocks(this);
new ServerConfiguration(this, _clientManager);
PreferencesManager preferenceManager = new PreferencesManager(this, _clientManager, _donationManager);
@ -102,8 +109,9 @@ public class Clans extends JavaPlugin
Portal portal = new Portal(this, _clientManager, serverStatusManager.getCurrentServerName());
new FileUpdater(this, portal, serverStatusManager.getCurrentServerName(), serverStatusManager.getRegion());
new ClansBanManager(this, _clientManager, _donationManager);
// ClansBanManager clansBans = new ClansBanManager(this, _clientManager, _donationManager);
PacketHandler packetHandler = new PacketHandler(this);
Punish punish = new Punish(this, webServerAddress, _clientManager);
AntiHack.Initialize(this, punish, portal, preferenceManager, _clientManager);
AntiHack.Instance.setKick(false);
@ -111,27 +119,31 @@ public class Clans extends JavaPlugin
BlockRestore blockRestore = new BlockRestore(this);
IgnoreManager ignoreManager = new IgnoreManager(this, _clientManager, preferenceManager, portal);
IncognitoManager incognito = new IncognitoManager(this, _clientManager, packetHandler);
StatsManager statsManager = new StatsManager(this, _clientManager);
AchievementManager achievementManager = new AchievementManager(statsManager, _clientManager, _donationManager);
Chat chat = new Chat(this, _clientManager, preferenceManager, achievementManager, serverStatusManager.getCurrentServerName());
new MessageManager(this, _clientManager, preferenceManager, ignoreManager, punish, new FriendManager(this, _clientManager, preferenceManager, portal), chat);
Chat chat = new Chat(this, incognito, _clientManager, preferenceManager, achievementManager, serverStatusManager.getCurrentServerName());
new MessageManager(this, incognito, _clientManager, preferenceManager, ignoreManager, punish, new FriendManager(this, _clientManager, preferenceManager, portal), chat);
new MemoryFix(this);
new FoodDupeFix(this);
new Explosion(this, blockRestore);
new FriendManager(this, _clientManager, preferenceManager, portal);
new InventoryManager(this, _clientManager);
ResourcePackManager resourcePackManager = new ResourcePackManager(this, portal);
resourcePackManager.setResourcePack("http://file.mineplex.com/ResClans.zip", true);
resourcePackManager.setResourcePack(new Pair[]
{
Pair.create(MinecraftVersion.Version1_8, "http://phinary.ca/ResClans.zip"),
Pair.create(MinecraftVersion.Version1_9, "http://phinary.ca/ResClans19.zip")
}, true);
// Enable custom-gear related managers
PacketHandler packetHandler = new PacketHandler(this);
new CustomTagFix(this, packetHandler);
GearManager customGear = new GearManager(this, packetHandler, _clientManager, _donationManager);
HologramManager hologram = new HologramManager(this, packetHandler);
_clansManager = new ClansManager(this, serverStatusManager.getCurrentServerName(), packetHandler, punish, _clientManager, _donationManager, preferenceManager, blockRestore, teleport, chat, customGear, hologram, webServerAddress);
_clansManager = new ClansManager(this, /*clansBans,*/ serverStatusManager.getCurrentServerName(), packetHandler, punish, _clientManager, _donationManager, preferenceManager, blockRestore, statsManager, teleport, chat, customGear, hologram, webServerAddress);
new Recipes(this);
new Farming(this);
new BuildingShop(_clansManager, _clientManager, _donationManager);
@ -152,8 +164,6 @@ public class Clans extends JavaPlugin
new Updater(this);
MinecraftServer.getServer().getPropertyManager().setProperty("debug", true);
getServer().setWhitelist(false); // TODO: remove
}
public static String prettifyName(Material material)
@ -179,4 +189,9 @@ public class Clans extends JavaPlugin
getServer().getPluginManager().callEvent(new ServerShutdownEvent(this));
}
public static String version()
{
return VERSION;
}
}

View File

@ -1,27 +1,23 @@
package mineplex.game.clans;
import java.util.ArrayList;
import java.util.List;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.UtilGear;
import mineplex.core.itemstack.ItemStackFactory;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilServer;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.PrepareItemCraftEvent;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.material.SmoothBrick;
import org.bukkit.plugin.java.JavaPlugin;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.C;
import mineplex.core.common.util.F;
import mineplex.core.common.util.UtilGear;
import mineplex.core.common.util.UtilServer;
import mineplex.core.itemstack.ItemStackFactory;
public class Recipes extends MiniPlugin
{
public Recipes(JavaPlugin plugin)
@ -41,7 +37,14 @@ public class Recipes extends MiniPlugin
diamondAxe.setIngredient('M', Material.DIAMOND_BLOCK);
diamondAxe.setIngredient('S', Material.STICK);
UtilServer.getServer().addRecipe(diamondAxe);
ShapedRecipe bricks = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1));
bricks.shape("XX", "XX");
bricks.setIngredient('X', new SmoothBrick(Material.COBBLESTONE));
UtilServer.getServer().addRecipe(bricks);
ItemStack boosterSword = ItemStackFactory.Instance.CreateStack(Material.GOLD_SWORD, (byte) 0, 1, "Booster Sword", false);
ShapedRecipe goldSword = new ShapedRecipe(boosterSword);
goldSword.shape("M","M","S");
@ -141,6 +144,28 @@ public class Recipes extends MiniPlugin
chainBoots2.setIngredient('S', Material.IRON_INGOT);
UtilServer.getServer().addRecipe(chainBoots2);
ShapedRecipe stonebrick = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1));
stonebrick.shape("SS#", "SS#");
stonebrick.setIngredient('S', Material.STONE);
UtilServer.getServer().addRecipe(stonebrick);
stonebrick = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1));
stonebrick.shape("#SS", "#SS");
stonebrick.setIngredient('S', Material.STONE);
UtilServer.getServer().addRecipe(stonebrick);
stonebrick = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1));
stonebrick.shape("###", "SS#", "SS#");
stonebrick.setIngredient('S', Material.STONE);
UtilServer.getServer().addRecipe(stonebrick);
stonebrick = new ShapedRecipe(new ItemStack(Material.SMOOTH_BRICK, 1));
stonebrick.shape("###", "#SS", "#SS");
stonebrick.setIngredient('S', Material.STONE);
UtilServer.getServer().addRecipe(stonebrick);
}
@EventHandler(priority = EventPriority.LOW)

View File

@ -61,7 +61,7 @@ public class ClanEnergyTracker extends MiniPlugin
Triple<Long, Long, String[]> energyBounds = _updateMap.get(type);
if (energyBounds != null && energyRemaining > energyBounds.getLeft() && energyRemaining < energyBounds.getMiddle())
if (energyBounds != null && energyRemaining > energyBounds.getLeft().longValue() && energyRemaining < energyBounds.getMiddle().longValue())
{
_clans.middleTextClan(clan, energyBounds.getRight()[0], energyBounds.getRight()[1], 20, 200, 80);
_clans.sendTipToClan(clan, TipType.ENERGY);

View File

@ -48,6 +48,7 @@ public class ClanInfo
private int _deaths;
private int _warWins;
private int _warLosses;
private int _eloRating;
private boolean _admin = false;
@ -86,6 +87,7 @@ public class ClanInfo
_id = token.Id;
_name = token.Name;
_desc = token.Description;
_eloRating = token.EloRating;
try
{
@ -119,23 +121,6 @@ public class ClanInfo
_bedStatus = BedStatus.DOESNT_EXIST;
}
try
{
if (token.Generator != null && token.Generator.length() > 0)
{
Block block = UtilWorld.strToBlock(token.Generator);
if (block != null)
{
_generator = new TntGenerator(block);
_generator.setStock(token.GeneratorStock);
}
}
}
catch (Exception e)
{
}
_energy = token.Energy;
_admin = token.Admin;
@ -169,6 +154,39 @@ public class ClanInfo
ClanWarData warData = warToken.WarData;
_warOut.put(warData.getClanB(), warData);
}
try
{
if (token.GeneratorBuyer != null && token.GeneratorBuyer.length() > 0)
{
if (token.GeneratorBuyer.contains(","))
{
// Convert to new generator format;
for (ClanMemberToken memberToken : token.Members)
{
ClanRole role = ClanRole.valueOf(memberToken.ClanRole);
if (role.equals(ClanRole.LEADER))
{
token.GeneratorBuyer = memberToken.PlayerUUID.toString();
break;
}
}
System.out.println("Clans> Converted " + _name + "'s generator to the new format.");
}
_generator = new TntGenerator(token.GeneratorBuyer);
_generator.setStock(token.GeneratorStock);
Clans.getClanDataAccess().updateGenerator(this, null);
}
}
catch (Exception e)
{
}
}
public int getClaims()
@ -246,12 +264,17 @@ public class ClanInfo
public boolean isAlly(ClanInfo other)
{
if (other == null)
{
return false;
}
return isAlly(other.getName());
}
public boolean isSelf(String other)
{
return this.getName().equals(other);
return getName().equals(other);
}
public boolean isNeutral(String other)
@ -594,6 +617,16 @@ public class ClanInfo
{
_warLosses += amount;
}
public int getEloRating()
{
return _eloRating;
}
public void addEloRating(int amount)
{
_eloRating += amount;
}
public ClanWarData getWarData(ClanInfo against)
{

View File

@ -219,6 +219,16 @@ public class ClanTips extends MiniPlugin
C.cDAqua + "Clan Home",
C.cAqua + "Your Clan Home is a bed in your Territory which you can teleport to from the Spawn Islands. However, you are unable to teleport to your Clan Home if the bed is broken, blocks have been placed above the bed, or enemies are in your Territory."
}),
MOUNT_CANNON(
new String[] {
C.cDAqua + "Meownon",
C.cAqua + "Congratulations on your new purchase! You are now in possesion, of the one, and only, Meownon 3000.24! " + C.Italics + "we are not responsible for any injuries caused by the meownon, or any related products. stay safe kids."
}),
ENTER_NETHER(
new String[] {
C.cDAqua + "The Nether",
C.cAqua + "Welcome to the Nether. This is a very scary place full of fire and is a place for people to battle to the death! TODO: Write something better about the nether here"
}),
;
// this is only LinkedList because UtilPlayer.message wants it

View File

@ -1,7 +1,12 @@
package mineplex.game.clans.clans;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import mineplex.core.common.Rank;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.F;
@ -10,10 +15,9 @@ import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.common.util.UtilWorld;
import mineplex.game.clans.core.repository.ClanTerritory;
import mineplex.game.clans.core.repository.tokens.ClanToken;
import mineplex.game.clans.core.war.ClanWarData;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import mineplex.serverdata.database.ResultSetCallable;
public class ClansAdmin
{
@ -84,6 +88,9 @@ public class ClansAdmin
else if (args[1].equalsIgnoreCase("wp"))
wp(caller, args);
else if (args[1].equalsIgnoreCase("rename"))
rename(caller, args);
else if (args[1].equalsIgnoreCase("timer"))
resetTime(caller, args);
@ -110,6 +117,7 @@ public class ClansAdmin
UtilPlayer.message(caller, F.help("/c x trust <clan>", "Give Trust to Clan", Rank.CMOD));
UtilPlayer.message(caller, F.help("/c x neutral <clan>", "Set Neutrality", Rank.CMOD));
UtilPlayer.message(caller, F.help("/c x enemy <clan>", "Start Invasion", Rank.CMOD));
UtilPlayer.message(caller, F.help("/c x rename <name>", "Change the name of Mimic", Rank.CMOD));
UtilPlayer.message(caller, F.help("/c x claim", "Claim Territory for Mimic", Rank.CMOD));
UtilPlayer.message(caller, F.help("/c x unclaim (all)", "Unclaim Territory for Mimic", Rank.CMOD));
UtilPlayer.message(caller, F.help("/c x delete", "Delete Mimic Clan", Rank.CMOD));
@ -194,80 +202,80 @@ public class ClansAdmin
public void create(final Player caller, final String[] args)
{
if (args.length < 3)
{
UtilPlayer.message(caller, F.main("Clans Admin", "You did not input a Clan name."));
return;
}
if (args.length < 3)
{
UtilPlayer.message(caller, F.main("Clans Admin", "You did not input a Clan name."));
return;
}
if (!UtilInput.valid(args[2]))
{
UtilPlayer.message(caller, F.main("Clans Admin", "Invalid characters in Clan name."));
return;
}
if (!UtilInput.valid(args[2]))
{
UtilPlayer.message(caller, F.main("Clans Admin", "Invalid characters in Clan name."));
return;
}
if (args[2].length() < Clans.getNameMin())
{
UtilPlayer.message(caller, F.main("Clans Admin", "Clan name too short. Minimum length is " + (Clans.getNameMin()) + "."));
return;
}
if (args[2].length() < Clans.getNameMin())
{
UtilPlayer.message(caller, F.main("Clans Admin", "Clan name too short. Minimum length is " + (Clans.getNameMin()) + "."));
return;
}
if (args[2].length() > Clans.getNameMax())
{
UtilPlayer.message(caller, F.main("Clans Admin", "Clan name too long. Maximum length is " + (Clans.getNameMax()) + "."));
return;
}
if (args[2].length() > Clans.getNameMax())
{
UtilPlayer.message(caller, F.main("Clans Admin", "Clan name too long. Maximum length is " + (Clans.getNameMax()) + "."));
return;
}
if (!ClansBlacklist.isValidClanName(args[2]))
{
UtilPlayer.message(caller, F.main("Clans Admin", "Clan name cannot be a Clan command."));
}
if (!Clans.getBlacklist().allowed(args[2]))
{
UtilPlayer.message(caller, F.main("Clans Admin", "That name is blacklisted, please choose another one."));
}
if (Clans.getClan(args[2]) != null)
if (Clans.getClan(args[2]) != null)
{
UtilPlayer.message(caller, F.main("Clans Admin", F.elem("Clan " + args[2]) + " already exists."));
return;
}
Clans.getClientManager().checkPlayerNameExact(new Callback<Boolean>()
{
public void run(final Boolean nameExists)
{
UtilPlayer.message(caller, F.main("Clans Admin", F.elem("Clan " + args[2]) + " already exists."));
return;
}
Clans.getClientManager().checkPlayerNameExact(new Callback<Boolean>()
{
public void run(final Boolean nameExists)
Bukkit.getServer().getScheduler().runTask(Clans.getPlugin(), new Runnable()
{
Bukkit.getServer().getScheduler().runTask(Clans.getPlugin(), new Runnable()
public void run()
{
public void run()
if (nameExists.booleanValue())
UtilPlayer.message(caller, F.main("Clans Admin", "Clan name cannot be a Player name."));
else
{
if (nameExists)
UtilPlayer.message(caller, F.main("Clans Admin", "Clan name cannot be a Player name."));
else
Clans.getClanDataAccess().create(caller.getName(), args[2], true, new Callback<ClanInfo>()
{
Clans.getClanDataAccess().create(caller.getName(), args[2], true, new Callback<ClanInfo>()
@Override
public void run(ClanInfo data)
{
@Override
public void run(ClanInfo data)
if (data != null)
{
if (data != null)
{
//Inform
UtilServer.broadcast(F.main("Clans Admin", caller.getName() + " formed " + F.elem("Admin Clan " + args[2]) + "."));
//Inform
UtilServer.broadcast(F.main("Clans Admin", caller.getName() + " formed " + F.elem("Admin Clan " + args[2]) + "."));
// Set Mimic
Clans.Get(caller).setMimic(args[2]);
// Set Mimic
Clans.Get(caller).setMimic(args[2]);
// Inform
UtilPlayer.message(caller, F.main("Clans Admin", "You are mimicing Clan " + args[2] + "."));
}
else
{
UtilPlayer.message(caller, F.main("Clans", "There was an error creating a clan! Try again later"));
}
// Inform
UtilPlayer.message(caller, F.main("Clans Admin", "You are mimicing Clan " + args[2] + "."));
}
});
}
else
{
UtilPlayer.message(caller, F.main("Clans", "There was an error creating a clan! Try again later"));
}
}
});
}
});
}
}, args[2]);
}
});
}
}, args[2]);
}
public void delete(final Player caller, String[] args)
@ -480,7 +488,7 @@ public class ClansAdmin
UtilPlayer.message(caller, F.main("Clans Admin", "You demoted " + target + " to " + newRank + " in Mimic Clan."));
clan.inform(F.main("Clans Admin", caller.getName() + " demoted " + target + " to " + newRank + "."), null);
}
public void kick(final Player caller, String[] args)
{
final ClanInfo clan = getMimic(caller, true);
@ -577,6 +585,46 @@ public class ClansAdmin
cB.inform("Clan " + cA.getName() + " has requested alliance with you.", null);
}
}
public void rename(Player caller, String[] args)
{
ClanInfo cA = getMimic(caller, true);
if (cA == null)
return;
if (args.length < 3)
{
UtilPlayer.message(caller, F.main("Clans Admin", "You did not input a new name."));
return;
}
String name = args[2];
final ClanToken clan = new ClanToken();
// Populate simple fields
clan.Id = cA.getId();
clan.Name = cA.getName();
clan.Description = cA.getDesc();
clan.Home = UtilWorld.locToStr(cA.getHome());
clan.Admin = cA.isAdmin();
clan.Energy = cA.getEnergy();
clan.Kills = cA.getKills();
clan.Murder = cA.getMurder();
clan.Deaths = cA.getDeaths();
clan.WarWins = cA.getWarWins();
clan.WarLosses = cA.getWarLosses();
clan.GeneratorBuyer = cA.getGenerator().getBuyer().toString();
clan.GeneratorStock = cA.getGenerator().getStock();
clan.DateCreated = cA.getDateCreated();
clan.LastOnline = cA.getLastOnline();
clan.EloRating = cA.getEloRating();
// clan.Members = cA.getMembers();
}
// public void trust(Player caller, String[] args)
// {

View File

@ -1,75 +0,0 @@
package mineplex.game.clans.clans;
import java.util.Arrays;
import java.util.LinkedList;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.C;
import mineplex.core.common.util.Callback;
import mineplex.core.common.util.UtilMath;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.common.util.UtilServer;
import mineplex.core.task.TaskManager;
import mineplex.core.updater.UpdateType;
import mineplex.core.updater.event.UpdateEvent;
public class ClansAlphaManager extends MiniPlugin
{
private static final LinkedList<LinkedList<String>> ANNOUNCEMENTS = new LinkedList<>(Arrays.asList(new LinkedList<>(Arrays.asList(C.cDAquaB + "Welcome to Clans Alpha", C.cAqua + "Clans is in early Alpha stages so expect there to be bugs/issues. Please report any bugs to staff, we hope you enjoy this early test!"))));
private static final boolean RANDOM_ANNOUNCEMENT = true;
/**
* This is useful if the above boolean (RANDOM_ANNOUNCEMENT) is set to
* false, then the announcement at index SET_ANNOUNCEMENT will be used every
* time.
*/
private static final int SET_ANNOUNCEMENT = 0;
private static final LinkedList<String> FIRST_JOIN_MESSAGES = new LinkedList<>(ANNOUNCEMENTS.getFirst());
private static final UpdateType ANNOUNCEMENT_DELAY = UpdateType.MIN_16;
private TaskManager _taskManager;
public ClansAlphaManager(ClansManager manager, TaskManager taskManager)
{
super("Announcements", manager.getPlugin());
_taskManager = taskManager;
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event)
{
if (!_taskManager.hasCompletedTask(event.getPlayer(), "ClansAlphaJoinMessage"))
{
_taskManager.completedTask(new Callback<Boolean>()
{
public void run(Boolean data)
{
UtilPlayer.message(event.getPlayer(), FIRST_JOIN_MESSAGES);
}
}, event.getPlayer(), "ClansAlphaJoinMessage");
}
}
@EventHandler
public void onUpdate(UpdateEvent event)
{
if (event.getType().equals(ANNOUNCEMENT_DELAY))
{
if (RANDOM_ANNOUNCEMENT)
{
UtilServer.broadcast(UtilMath.randomElement(ANNOUNCEMENTS));
}
else
{
UtilServer.broadcast(ANNOUNCEMENTS.get(SET_ANNOUNCEMENT));
}
}
}
}

View File

@ -0,0 +1,27 @@
package mineplex.game.clans.clans;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent;
import mineplex.core.MiniPlugin;
import mineplex.core.common.util.C;
import mineplex.core.common.util.UtilPlayer;
import mineplex.core.task.TaskManager;
import mineplex.game.clans.Clans;
public class ClansBetaManager extends MiniPlugin
{
public ClansBetaManager(ClansManager manager, TaskManager taskManager)
{
super("Clans Beta", manager.getPlugin());
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(final PlayerJoinEvent event)
{
UtilPlayer.message(event.getPlayer(), C.cDAquaB + "Welcome to Mineplex Clans " + Clans.VERSION);
}
}

View File

@ -1,41 +0,0 @@
package mineplex.game.clans.clans;
import java.util.Arrays;
import java.util.List;
/**
* ClansBlacklist represents the blacklist of all disallowed names for clan creation.
* @author MrTwiggy
*
*/
public class ClansBlacklist
{
// Set of all blacklisted clan names that are NOT valid.
private final static List<String> BLACKLISTED_NAMES = Arrays.asList(new String[]
{
"Youtube", "Owner", "Admin", "Mod", "Trainee", "Twitch",
"Wilderness", "Shops", "Builder", "Spawn", "Clan", "Clans",
"Fields", "Sr.Mod", "Sr. Mod", "Dev", "Jr.Dev", "Jr. Dev", "create",
"join", "leave", "map", "cc", "ac", "invite", "kick", "neutral",
"enemy", "trust", "unclaim", "claim", "delete", "SrMod", "Twitch", "YouTube", "Event",
"Media", "MapLead", "JrDev", "Developer", "Leader", "LT", "Support"
});
/**
* @param clanName - the name of the clan to validate
* @return true, if {@code clanName} is a valid and non-blacklisted clan name, false otherwise.
*/
public static boolean isValidClanName(String clanName)
{
for (String blacklistedName : BLACKLISTED_NAMES)
{
if (blacklistedName.equalsIgnoreCase(clanName))
{
return false;
}
}
return true;
}
}

Some files were not shown because too many files have changed in this diff Show More