1
0

refactor: clean source code

This commit is contained in:
labalityowo
2022-07-07 10:09:42 +07:00
parent 49950087f5
commit de68079e8a
16487 changed files with 721393 additions and 227033 deletions

View File

@ -0,0 +1,26 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mineplex</groupId>
<artifactId>mineplex-parent</artifactId>
<version>dev-SNAPSHOT</version>
</parent>
<artifactId>mineplex-core-common-base</artifactId>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.labalityowo</groupId>
<artifactId>spigot</artifactId>
</dependency>
</dependencies>
</project>

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,6 @@
package mineplex.core.common;
public interface GenericRunnable<T>
{
void run(T t);
}

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,56 @@
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);
}
public Material getMaterial()
{
return _material;
}
public byte getData()
{
return _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,50 @@
package mineplex.core.common;
import com.google.common.base.Preconditions;
/**
* Used to declare specific milestone versions
*/
public enum MinecraftVersion
{
Version1_13("1.13", 393),
Version1_9("1.9", 48),
Version1_8("1.8", Integer.MIN_VALUE), //Any player will at minimum be 1.8, we can't handle anything below that
;
private final String _friendlyName;
private final int _minimum;
MinecraftVersion(String friendlyName, int minimum)
{
_friendlyName = friendlyName;
_minimum = minimum;
}
public String friendlyName()
{
return _friendlyName;
}
public boolean atOrAbove(MinecraftVersion other)
{
Preconditions.checkNotNull(other);
return ordinal() <= other.ordinal();
}
public static MinecraftVersion fromInt(int version)
{
MinecraftVersion v = null;
for (MinecraftVersion test : values())
{
if (version >= test._minimum)
{
v = test;
break;
}
}
return v;
}
}

View File

@ -0,0 +1,69 @@
package mineplex.core.common;
import java.io.Serializable;
public class Pair<L, R> implements Serializable {
private static final long serialVersionUID = -7631968541502978704L;
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);
}
private Pair(L left, R right) {
this.setLeft(left);
this.setRight(right);
}
public L getLeft()
{
return left;
}
public void setLeft(L left)
{
this.left = left;
}
public R getRight()
{
return right;
}
public void setRight(R right)
{
this.right = right;
}
@Override
public String toString()
{
return getLeft().toString() + ":" + getRight().toString();
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (left != null ? !left.equals(pair.left) : pair.left != null) return false;
return right != null ? right.equals(pair.right) : pair.right == null;
}
@Override
public int hashCode()
{
int result = left != null ? left.hashCode() : 0;
result = 31 * result + (right != null ? right.hashCode() : 0);
return result;
}
}

View File

@ -0,0 +1,81 @@
package mineplex.core.common;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProcessRunner extends Thread
{
private ProcessBuilder _processBuilder;
private Process _process;
private GenericRunnable<Boolean> _runnable;
boolean _done = false;
Boolean _error = false;
public ProcessRunner(String[] args)
{
super("ProcessRunner " + args);
_processBuilder = new ProcessBuilder(args);
}
public void run()
{
try
{
_process = _processBuilder.start();
_process.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(_process.getInputStream()));
String line = reader.readLine();
while(line != null)
{
if (line.equals("255"))
_error = true;
line=reader.readLine();
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally
{
_done = true;
if (_runnable != null)
_runnable.run(_error);
}
}
public void start(GenericRunnable<Boolean> runnable)
{
super.start();
_runnable = runnable;
}
public int exitValue() throws IllegalStateException
{
if (_process != null)
{
return _process.exitValue();
}
throw new IllegalStateException("Process not started yet");
}
public boolean isDone()
{
return _done;
}
public void abort()
{
if (!isDone())
{
_process.destroy();
}
}
}

View File

@ -0,0 +1,162 @@
package mineplex.core.common;
import java.util.Iterator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.PrimitiveIterator;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import com.google.common.base.Preconditions;
/**
* An Iterator that shuffles and provides integers from a specified range.
* The shuffle strategy is based on the Fisher-Yates shuffle.
*
* @see #nextInts(int)
* @see #nextInt()
*/
public class RangeShuffleIterator implements PrimitiveIterator.OfInt
{
private static final Random random = new Random();
private final IntSet _remaining;
private int _remainingCount;
/**
* Create a RangeShuffleIterator encompassing the specified range (inclusive)
*
* @param start The range lower bound, inclusive
* @param end The range upper bound, inclusive
*/
public RangeShuffleIterator(int start, int end)
{
Preconditions.checkArgument(start <= end);
_remaining = new IntSet(start, end);
_remainingCount = end - start + 1;
}
/**
* Provide a specified number of integers in an int array. If the number
* of elements remaining is fewer than {@code maxAmount}, return all
* remaining elements.
*
* @param maxAmount The number of elements to retrieve
* @return An array containing the retrieved elements
*/
public int[] nextInts(int maxAmount)
{
int[] ret = new int[Math.min(_remainingCount, maxAmount)];
for (int i = 0; i < ret.length; i++)
{
ret[i] = nextInt();
}
return ret;
}
@Override
public int nextInt()
{
if (!hasNext())
{
throw new IllegalStateException("No remaining ranges to iterate");
}
int selectedPosition = random.nextInt(_remainingCount);
Iterator<Map.Entry<Integer, Integer>> it = _remaining.ranges().iterator();
final int selected;
while (true)
{
Map.Entry<Integer, Integer> range = it.next();
int span = range.getValue() - range.getKey();
if (span < selectedPosition)
{
selectedPosition -= span + 1;
}
else
{
selected = range.getKey() + selectedPosition;
break;
}
}
_remaining.remove(selected);
--_remainingCount;
return selected;
}
@Override
public boolean hasNext()
{
return _remainingCount > 0;
}
/**
* A set of integers. The set is seeded by a single range, and the only
* supported operation is int removal.
* <p>
* This implementation only exists for performance reasons.
*/
private static class IntSet
{
/**
* A set of ranges representing the remaining integers in this set
*/
private final NavigableMap<Integer, Integer> ranges = new TreeMap<>();
/**
* Create an IntSet containing all numbers from {@code start} to
* {@code end}, inclusive
*
* @param start The range lower bound, inclusive
* @param end The range upper bound, inclusive
*/
private IntSet(int start, int end)
{
ranges.put(start, end);
}
public Set<Map.Entry<Integer, Integer>> ranges()
{
return ranges.entrySet();
}
/**
* Remove an integer from this IntSet
* @param value The integer to remove
*/
public void remove(int value)
{
Map.Entry<Integer,Integer> range = ranges.floorEntry(value);
if (range == null || range.getValue() < value)
{
return;
}
int lower = range.getKey();
int upper = range.getValue();
if (upper > value)
{
reinsert(value + 1, upper);
}
reinsert(lower, Math.min(upper, value - 1));
}
private void reinsert(int start, int end)
{
if (end < start)
{
ranges.remove(start);
}
else
{
ranges.put(start, end);
}
}
}
}

View File

@ -0,0 +1,54 @@
package mineplex.core.common;
import java.util.Objects;
/**
* Represents an operation that accepts two input arguments and returns no
* result. This is the three-arity specialization of {@link Consumer}.
* Unlike most other functional interfaces, {@code TriConsumer} is expected
* to operate via side-effects.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #accept(Object, Object, Object)}.
*
* @param <T> the type of the first argument to the operation
* @param <U> the type of the second argument to the operation
* @param <V> the type of the third argument to the operation
*
* @see Consumer
*/
@FunctionalInterface
public interface TriConsumer<T, U, V>
{
/**
* Performs this operation on the given arguments.
*
* @param t the first input argument
* @param u the second input argument
* @param v the third input argument
*/
void accept(T t, U u, V v);
/**
* Returns a composed {@code TriConsumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code TriConsumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default TriConsumer<T, U, V> andThen(TriConsumer<? super T, ? super U, ? super V> after)
{
Objects.requireNonNull(after);
return (f, s, t) -> {
accept(f, s, t);
after.accept(f, s, t);
};
}
}

View File

@ -0,0 +1,51 @@
package mineplex.core.common.currency;
import org.bukkit.Material;
/**
* Currency is the base class for all currency types in mineplex:
* - Global currencies, found in {@link GlobalCurrency}, e.g., treasure shards
* - Clans gold, found in the Mineplex.Game.Clans project
*/
public class Currency
{
private final String _plural;
private final String _singular;
private final String _color;
private final Material _displayMaterial;
public Currency(String plural, String singular, String color, Material displayMaterial)
{
this._plural = plural;
this._singular = singular;
this._color = color;
this._displayMaterial = displayMaterial;
}
@Deprecated
public String getPrefix()
{
return _plural;
}
public String getString(int amount, boolean color)
{
return (color ? _color : "") + amount + " " + (amount == 1 ? _singular : _plural);
}
public String getString(int amount)
{
return getString(amount, true);
}
public String getColor()
{
return _color;
}
public Material getDisplayMaterial()
{
return _displayMaterial;
}
}

View File

@ -0,0 +1,17 @@
package mineplex.core.common.currency;
import mineplex.core.common.util.C;
import org.bukkit.Material;
/**
* A GlobalCurrency is one whose state is shared between all Mineplex servers.
* GlobalCurrencies can be retrieved and modified through DonationManager/Donor in Mineplex.Core
*/
public class GlobalCurrency extends Currency {
public static final GlobalCurrency TREASURE_SHARD = new GlobalCurrency("Treasure Shards", "Treasure Shard", C.cAqua, Material.PRISMARINE_SHARD);
public static final GlobalCurrency GEM = new GlobalCurrency("Gems", "Gem", C.cGreen, Material.EMERALD);
public GlobalCurrency(String plural, String singular, String color, Material displayMaterial) {
super(plural, singular, color, displayMaterial);
}
}

View File

@ -0,0 +1,60 @@
package mineplex.core.common.events;
import org.bukkit.entity.Entity;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.util.Vector;
/**
* Called just before UtilAction#velocity changes an entity's velocity.
*/
public class EntityVelocityChangeEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private Entity _ent;
private Vector _vel;
private boolean _cancelled;
public EntityVelocityChangeEvent(Entity entity, Vector velocity)
{
_ent = entity;
_vel = velocity;
}
public Entity getEntity()
{
return _ent;
}
public boolean isCancelled()
{
return _cancelled;
}
public Vector getVelocity()
{
return _vel;
}
public void setVelocity(Vector velocity)
{
_vel = velocity;
}
public void setCancelled(boolean cancelled)
{
_cancelled = cancelled;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -0,0 +1,61 @@
package mineplex.core.common.events;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Called just before UtilPlayer#message sends out a message to the specified Player.
*/
public class PlayerMessageEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private Player _player;
private String _message;
private boolean _cancelled;
public PlayerMessageEvent(Player player, String message)
{
_player = player;
_message = message;
}
public Player getPlayer()
{
return _player;
}
public boolean isCancelled()
{
return _cancelled;
}
public String getMessage()
{
return _message;
}
public String getUnformattedMessage()
{
return ChatColor.stripColor(_message);
}
public void setCancelled(boolean cancelled)
{
_cancelled = cancelled;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

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,33 @@
package mineplex.core.common.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;
public class ServerShutdownEvent extends Event
{
private static final HandlerList handlers = new HandlerList();
private JavaPlugin _plugin;
public ServerShutdownEvent(JavaPlugin plugin)
{
_plugin = plugin;
}
public JavaPlugin getPlugin()
{
return _plugin;
}
public HandlerList getHandlers()
{
return handlers;
}
public static HandlerList getHandlerList()
{
return handlers;
}
}

View File

@ -0,0 +1,117 @@
package mineplex.core.common.util;
import org.bukkit.ChatColor;
public class C
{
public static final String blankLine = ChatColor.RESET + " ";
public static String Scramble = "§k";
public static String Bold = "§l";
public static String Strike = "§m";
public static String BoldStrike = "§l§m";
public static String Line = "§n";
public static String Italics = "§o";
public static String Reset = "§r";
public static String cAqua = "" + ChatColor.AQUA;
public static String cBlack = "" + ChatColor.BLACK;
public static String cBlue = "" + ChatColor.BLUE;
public static String cDAqua = "" + ChatColor.DARK_AQUA;
public static String cDBlue = "" + ChatColor.DARK_BLUE;
public static String cDGray = "" + ChatColor.DARK_GRAY;
public static String cDGreen = "" + ChatColor.DARK_GREEN;
public static String cDPurple = "" + ChatColor.DARK_PURPLE;
public static String cDRed = "" + ChatColor.DARK_RED;
public static String cGold = "" + ChatColor.GOLD;
public static String cGray = "" + ChatColor.GRAY;
public static String cGreen = "" + ChatColor.GREEN;
public static String cPurple = "" + ChatColor.LIGHT_PURPLE;
public static String cRed = "" + ChatColor.RED;
public static String cWhite = "" + ChatColor.WHITE;
public static String cYellow = "" + ChatColor.YELLOW;
public static String cAquaB = "" + ChatColor.AQUA + "" + ChatColor.BOLD;
public static String cBlackB = "" + ChatColor.BLACK + "" + ChatColor.BOLD;
public static String cBlueB = "" + ChatColor.BLUE + "" + ChatColor.BOLD;
public static String cDAquaB = "" + ChatColor.DARK_AQUA + "" + ChatColor.BOLD;
public static String cDBlueB = "" + ChatColor.DARK_BLUE + "" + ChatColor.BOLD;
public static String cDGrayB = "" + ChatColor.DARK_GRAY + "" + ChatColor.BOLD;
public static String cDGreenB = "" + ChatColor.DARK_GREEN + "" + ChatColor.BOLD;
public static String cDPurpleB = "" + ChatColor.DARK_PURPLE + "" + ChatColor.BOLD;
public static String cDRedB = "" + ChatColor.DARK_RED + "" + ChatColor.BOLD;
public static String cGoldB = "" + ChatColor.GOLD + "" + ChatColor.BOLD;
public static String cGrayB = "" + ChatColor.GRAY + "" + ChatColor.BOLD;
public static String cGreenB = "" + ChatColor.GREEN + "" + ChatColor.BOLD;
public static String cPurpleB = "" + ChatColor.LIGHT_PURPLE + "" + ChatColor.BOLD;
public static String cRedB = "" + ChatColor.RED + "" + ChatColor.BOLD;
public static String cWhiteB = "" + ChatColor.WHITE + "" + ChatColor.BOLD;
public static String cYellowB = "" + ChatColor.YELLOW + "" + ChatColor.BOLD;
public static String mHead = "" + ChatColor.BLUE;
public static String mBody = "" + ChatColor.GRAY;
public static String mChat = "" + ChatColor.WHITE;
public static String mElem = "" + ChatColor.YELLOW;
public static String mCount = "" + ChatColor.YELLOW;
public static String mTime = "" + ChatColor.GREEN;
public static String mItem = "" + ChatColor.YELLOW;
public static String mSkill = "" + ChatColor.GREEN;
public static String mLink = "" + ChatColor.GREEN;
public static String mLoot = "" + ChatColor.RED;
public static String mGame = "" + ChatColor.LIGHT_PURPLE;
public static String wField = "" + ChatColor.WHITE;
public static String wFrame = "" + ChatColor.DARK_GRAY;
public static String descHead = "" + ChatColor.DARK_GREEN;
public static String descBody = "" + ChatColor.WHITE;
public static String chatPMHead = "" + ChatColor.DARK_GREEN;
public static String chatPMBody = "" + ChatColor.GREEN;
public static String chatClanHead = "" + ChatColor.DARK_AQUA;
public static String chatClanBody = "" + ChatColor.AQUA;
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;
public static String listValueOff = "" + ChatColor.RED;
public static String consoleHead = "" + ChatColor.RED;
public static String consoleFill = "" + ChatColor.WHITE;
public static String consoleBody = "" + ChatColor.YELLOW;
public static String sysHead = "" + ChatColor.DARK_GRAY;
public static String sysBody = "" + ChatColor.GRAY;
public static String chat = "" + ChatColor.WHITE;
public static String xBorderlands = "" + ChatColor.GOLD;
public static String xWilderness = "" + ChatColor.GRAY;
public static String xMid = "" + ChatColor.WHITE;
public static ChatColor xNone = ChatColor.YELLOW;
public static ChatColor xAdmin = ChatColor.WHITE;
public static ChatColor xSafe = ChatColor.AQUA;
public static ChatColor xNeutral = ChatColor.YELLOW;
public static ChatColor xSelf = ChatColor.AQUA;
public static ChatColor xAlly = ChatColor.GREEN;
public static ChatColor xEnemy = ChatColor.RED;
public static ChatColor xWarWinning = ChatColor.LIGHT_PURPLE;
public static ChatColor xWarLosing = ChatColor.RED;
public static ChatColor xPillage = ChatColor.LIGHT_PURPLE;
public static ChatColor xdNeutral = ChatColor.GOLD;
public static ChatColor xdSelf = ChatColor.DARK_AQUA;
public static ChatColor xdAlly = ChatColor.DARK_GREEN;
public static ChatColor xdEnemy = ChatColor.DARK_RED;
public static ChatColor xdWarWinning = ChatColor.DARK_PURPLE;
public static ChatColor xdWarLosing = ChatColor.DARK_RED;
public static ChatColor xdPillage = ChatColor.DARK_PURPLE;
}

View File

@ -0,0 +1,6 @@
package mineplex.core.common.util;
public interface Callback<T>
{
public void run(T data);
}

View File

@ -0,0 +1,233 @@
package mineplex.core.common.util;
import org.bukkit.ChatColor;
import mineplex.core.common.currency.Currency;
public class F
{
public static String main(String module, String body)
{
return C.mHead + module + "> " + C.mBody + body;
//return C.mBody + body;
}
public static String tute(String sender, String body)
{
return C.cGold + sender + "> " + C.cWhite + body;
}
public static String te(String message)
{
return C.cYellow + message + C.cWhite;
}
public static String game(String elem)
{
return C.mGame + elem + C.mBody;
}
public static String color(String msg, String color)
{
return color + msg + C.mBody;
}
public static String ta(String message)
{
return C.cGreen + message + C.cWhite;
}
public static String ts(String message)
{
return C.cGold + message + C.cWhite;
}
public static String sys(String head, String body)
{
return C.sysHead + head + "> " + C.sysBody + body;
}
public static String elem(Object elem)
{
return C.mElem + elem.toString() + ChatColor.RESET + C.mBody;
}
public static String name(String elem)
{
return C.mElem + elem + C.mBody;
}
public static String count(int elem)
{
return count(String.valueOf(elem));
}
public static String count(String elem)
{
return C.mCount + elem + C.mBody;
}
public static String item(String elem)
{
return C.mItem + elem + C.mBody;
}
public static String link(String elem)
{
return C.mLink + elem + C.mBody;
}
public static String skill(String elem)
{
return C.mSkill + elem + C.mBody;
}
public static String skill(String a, String b)
{
return C.cYellow + " " + C.cGreen + b + C.mBody;
}
public static String time(String elem)
{
return C.mTime + elem + C.mBody;
}
public static String desc(String head, String body)
{
return C.descHead + head + ": " + C.descBody + body;
}
public static String wField(String field, String data)
{
return C.wFrame + "[" + C.wField + field + C.wFrame + "] " + C.mBody + data + " ";
}
public static String help(String cmd, String body, ChatColor displayColor)
{
return displayColor + cmd + " " + C.mBody + body;
}
public static String value(String variable, int value)
{
return value(variable, "" + value);
}
public static String value(String variable, String value)
{
return value(0, variable, value);
}
public static String value(int a, String variable, String value)
{
String indent = "";
while (indent.length() < a)
indent += ChatColor.GRAY + ">";
return indent + C.listTitle + variable + ": " + C.listValue + value;
}
public static String value(String variable, String value, boolean on)
{
return value(0, variable, value, on);
}
public static String value(int a, String variable, String value, boolean on)
{
String indent = "";
while (indent.length() < a)
indent += ChatColor.GRAY + ">";
if (on) return indent + C.listTitle + variable + ": " + C.listValueOn + value;
else return indent + C.listTitle + variable + ": " + C.listValueOff + value;
}
public static String ed(boolean var)
{
if (var)
return C.listValueOn + "Enabled" + C.mBody;
return C.listValueOff + "Disabled" + C.mBody;
}
public static String oo(boolean var)
{
if (var)
return C.listValueOn + "On" + C.mBody;
return C.listValueOff + "Off" + C.mBody;
}
public static String tf(boolean var)
{
if (var)
return C.listValueOn + "True" + C.mBody;
return C.listValueOff + "False" + C.mBody;
}
public static String oo(String variable, boolean value)
{
if (value)
return C.listValueOn + variable + C.mBody;
return C.listValueOff + variable + C.mBody;
}
public static String combine(String[] args, int start, String color, boolean comma)
{
if (args.length == 0)
return "";
String out = "";
for (int i = start ; i<args.length ; i++)
{
if (color != null)
{
String preColor = ChatColor.getLastColors(args[i]);
out += color + args[i] + preColor;
}
else
out += args[i];
if (comma)
out += ", ";
else
out += " ";
}
if (out.length() > 0)
if (comma) out = out.substring(0, out.length() - 2);
else out = out.substring(0, out.length() - 1);
return out;
}
public static String currency(Currency type, int amount)
{
return type.getString(amount) + ChatColor.RESET + C.mBody;
}
public static String vowelAN(String word)
{
return word.toLowerCase().startsWith("a")
|| word.toLowerCase().startsWith("A")
|| word.toLowerCase().startsWith("e")
|| word.toLowerCase().startsWith("E")
|| word.toLowerCase().startsWith("i")
|| word.toLowerCase().startsWith("I")
|| word.toLowerCase().startsWith("o")
|| word.toLowerCase().startsWith("O")
|| word.toLowerCase().startsWith("u")
|| word.toLowerCase().startsWith("U")
? "an" : "a";
}
public static String clansNether(String word)
{
return C.cClansNether + word + C.mBody;
}
public static String greenElem(String text)
{
return C.cGreen + text + ChatColor.RESET + C.mBody;
}
}

View File

@ -0,0 +1,158 @@
package mineplex.core.common.util;
import java.util.ArrayList;
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> 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);
}
public void add(int index, Elem elem)
{
_wrappedArrayList.add(index, elem);
}
public boolean addAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.addAll(elements);
}
public boolean addAll(int index, Collection<? extends Elem> elements)
{
return _wrappedArrayList.addAll(index, elements);
}
public void clear()
{
_wrappedArrayList.clear();
}
public boolean contains(Elem elem)
{
return _wrappedArrayList.contains(elem);
}
public boolean containsAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.containsAll(elements);
}
public Elem get(int index)
{
return _wrappedArrayList.get(index);
}
public boolean equals(Object o)
{
return _wrappedArrayList.equals(o);
}
public int hashCode()
{
return _wrappedArrayList.hashCode();
}
public int indexOf(Elem elem)
{
return _wrappedArrayList.indexOf(elem);
}
public boolean isEmpty()
{
return _wrappedArrayList.isEmpty();
}
public Iterator<Elem> iterator()
{
return _wrappedArrayList.iterator();
}
public int lastIndexOf(Elem elem)
{
return _wrappedArrayList.lastIndexOf(elem);
}
public ListIterator<Elem> listIterator()
{
return _wrappedArrayList.listIterator();
}
public ListIterator<Elem> listIterator(int index)
{
return _wrappedArrayList.listIterator(index);
}
public Elem remove(int index)
{
return _wrappedArrayList.remove(index);
}
public boolean remove(Elem element)
{
return _wrappedArrayList.remove(element);
}
public boolean removeAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.removeAll(elements);
}
public boolean retainAll(Collection<? extends Elem> elements)
{
return _wrappedArrayList.retainAll(elements);
}
public Elem set(int index, Elem element)
{
return _wrappedArrayList.set(index, element);
}
public int size()
{
return _wrappedArrayList.size();
}
public List<Elem> subList(int begin, int end)
{
return _wrappedArrayList.subList(begin, end);
}
public Object[] toArray()
{
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

@ -0,0 +1,80 @@
package mineplex.core.common.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import org.apache.commons.lang.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], values[i]));
}
public boolean containsKey(KeyType key)
{
return _wrappedHashMap.containsKey(key);
}
public boolean containsValue(ValueType key)
{
return _wrappedHashMap.containsValue(key);
}
public Set<Entry<KeyType, ValueType>> entrySet()
{
return _wrappedHashMap.entrySet();
}
public Set<KeyType> keySet()
{
return _wrappedHashMap.keySet();
}
public Collection<ValueType> values()
{
return _wrappedHashMap.values();
}
public ValueType get(KeyType key)
{
return _wrappedHashMap.get(key);
}
public ValueType remove(KeyType key)
{
return _wrappedHashMap.remove(key);
}
public ValueType put(KeyType key, ValueType value)
{
return _wrappedHashMap.put(key, value);
}
public void clear()
{
_wrappedHashMap.clear();
}
public int size()
{
return _wrappedHashMap.size();
}
public boolean isEmpty()
{
return _wrappedHashMap.isEmpty();
}
}

View File

@ -0,0 +1,38 @@
package mineplex.core.common.util;
import java.util.ArrayList;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
public class UtilBlockBase
{
public static ArrayList<Block> getSurrounding(Block block, boolean diagonals)
{
ArrayList<Block> blocks = new ArrayList<Block>();
if (diagonals)
{
for (int x = -1; x <= 1; x++)
for (int z = -1; z <= 1; z++)
for (int y = 1; y >= -1; y--)
{
if (x == 0 && y == 0 && z == 0) continue;
blocks.add(block.getRelative(x, y, z));
}
}
else
{
blocks.add(block.getRelative(BlockFace.UP));
blocks.add(block.getRelative(BlockFace.NORTH));
blocks.add(block.getRelative(BlockFace.SOUTH));
blocks.add(block.getRelative(BlockFace.EAST));
blocks.add(block.getRelative(BlockFace.WEST));
blocks.add(block.getRelative(BlockFace.DOWN));
}
return blocks;
}
}

View File

@ -0,0 +1,284 @@
package mineplex.core.common.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
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(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(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();
}
public static <T> List<T> unboxPresent(Collection<Optional<T>> optionalList)
{
return optionalList.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}
}

View File

@ -0,0 +1,86 @@
package mineplex.core.common.util;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Projectile;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerInteractEvent;
public class UtilEvent
{
public enum ActionType
{
L,
L_AIR,
L_BLOCK,
R,
R_AIR,
R_BLOCK,
ANY
}
public static boolean isAction(PlayerInteractEvent event, ActionType action)
{
if (action == ActionType.L)
return (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK);
if (action == ActionType.L_AIR)
return (event.getAction() == Action.LEFT_CLICK_AIR);
if (action == ActionType.L_BLOCK)
return (event.getAction() == Action.LEFT_CLICK_BLOCK);
if (action == ActionType.R)
return (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK);
if (action == ActionType.R_AIR)
return (event.getAction() == Action.RIGHT_CLICK_AIR);
if (action == ActionType.R_BLOCK)
return (event.getAction() == Action.RIGHT_CLICK_BLOCK);
if (action == ActionType.ANY)
return event.getAction() != Action.PHYSICAL;
return false;
}
public static boolean isBowDamage(EntityDamageEvent event)
{
if (!(event instanceof EntityDamageByEntityEvent))
return false;
EntityDamageByEntityEvent e = (EntityDamageByEntityEvent)event;
return e.getDamager() instanceof Arrow;
}
public static LivingEntity GetDamagerEntity(EntityDamageEvent event, boolean ranged)
{
if (!(event instanceof EntityDamageByEntityEvent))
return null;
EntityDamageByEntityEvent eventEE = (EntityDamageByEntityEvent)event;
//Get Damager
if (eventEE.getDamager() instanceof LivingEntity)
return (LivingEntity)eventEE.getDamager();
if (!ranged)
return null;
if (!(eventEE.getDamager() instanceof Projectile))
return null;
Projectile projectile = (Projectile)eventEE.getDamager();
if (projectile.getShooter() == null)
return null;
if (!(projectile.getShooter() instanceof LivingEntity))
return null;
return (LivingEntity)projectile.getShooter();
}
}

View File

@ -0,0 +1,207 @@
package mineplex.core.common.util;
import java.util.HashSet;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public class UtilGear
{
private static HashSet<Material> _axeSet = new HashSet<Material>();
private static HashSet<Material> _swordSet = new HashSet<Material>();
private static HashSet<Material> _maulSet = new HashSet<Material>();
private static HashSet<Material> pickSet = new HashSet<Material>();
private static HashSet<Material> diamondSet = new HashSet<Material>();
private static HashSet<Material> goldSet = new HashSet<Material>();
private static HashSet<Material> _armorSet = new HashSet<Material>();
public static boolean isArmor(ItemStack item)
{
if (item == null)
return false;
if (_armorSet.isEmpty())
{
_armorSet.add(Material.LEATHER_HELMET);
_armorSet.add(Material.LEATHER_CHESTPLATE);
_armorSet.add(Material.LEATHER_LEGGINGS);
_armorSet.add(Material.LEATHER_BOOTS);
_armorSet.add(Material.GOLD_HELMET);
_armorSet.add(Material.GOLD_CHESTPLATE);
_armorSet.add(Material.GOLD_LEGGINGS);
_armorSet.add(Material.GOLD_BOOTS);
_armorSet.add(Material.CHAINMAIL_HELMET);
_armorSet.add(Material.CHAINMAIL_CHESTPLATE);
_armorSet.add(Material.CHAINMAIL_LEGGINGS);
_armorSet.add(Material.CHAINMAIL_BOOTS);
_armorSet.add(Material.IRON_HELMET);
_armorSet.add(Material.IRON_CHESTPLATE);
_armorSet.add(Material.IRON_LEGGINGS);
_armorSet.add(Material.IRON_BOOTS);
_armorSet.add(Material.DIAMOND_HELMET);
_armorSet.add(Material.DIAMOND_CHESTPLATE);
_armorSet.add(Material.DIAMOND_LEGGINGS);
_armorSet.add(Material.DIAMOND_BOOTS);
}
return _armorSet.contains(item.getType());
}
public static boolean isAxe(ItemStack item)
{
if (item == null)
return false;
if (_axeSet.isEmpty())
{
_axeSet.add(Material.WOOD_AXE);
_axeSet.add(Material.STONE_AXE);
_axeSet.add(Material.IRON_AXE);
_axeSet.add(Material.GOLD_AXE);
_axeSet.add(Material.DIAMOND_AXE);
}
return _axeSet.contains(item.getType());
}
public static boolean isSword(ItemStack item)
{
if (item == null)
return false;
if (_swordSet.isEmpty())
{
_swordSet.add(Material.WOOD_SWORD);
_swordSet.add(Material.STONE_SWORD);
_swordSet.add(Material.IRON_SWORD);
_swordSet.add(Material.GOLD_SWORD);
_swordSet.add(Material.DIAMOND_SWORD);
}
return _swordSet.contains(item.getType());
}
public static boolean isShovel(ItemStack item)
{
if (item == null)
return false;
if (_maulSet.isEmpty())
{
_maulSet.add(Material.WOOD_SPADE);
_maulSet.add(Material.STONE_SPADE);
_maulSet.add(Material.IRON_SPADE);
_maulSet.add(Material.GOLD_SPADE);
_maulSet.add(Material.DIAMOND_SPADE);
}
return _maulSet.contains(item.getType());
}
public static HashSet<Material> scytheSet = new HashSet<Material>();
public static boolean isHoe(ItemStack item)
{
if (item == null)
return false;
if (scytheSet.isEmpty())
{
scytheSet.add(Material.WOOD_HOE);
scytheSet.add(Material.STONE_HOE);
scytheSet.add(Material.IRON_HOE);
scytheSet.add(Material.GOLD_HOE);
scytheSet.add(Material.DIAMOND_HOE);
}
return scytheSet.contains(item.getType());
}
public static boolean isPickaxe(ItemStack item)
{
if (item == null)
return false;
if (pickSet.isEmpty())
{
pickSet.add(Material.WOOD_PICKAXE);
pickSet.add(Material.STONE_PICKAXE);
pickSet.add(Material.IRON_PICKAXE);
pickSet.add(Material.GOLD_PICKAXE);
pickSet.add(Material.DIAMOND_PICKAXE);
}
return pickSet.contains(item.getType());
}
public static boolean isDiamond(ItemStack item)
{
if (item == null)
return false;
if (diamondSet.isEmpty())
{
diamondSet.add(Material.DIAMOND_SWORD);
diamondSet.add(Material.DIAMOND_AXE);
diamondSet.add(Material.DIAMOND_SPADE);
diamondSet.add(Material.DIAMOND_HOE);
}
return diamondSet.contains(item.getType());
}
public static boolean isGold(ItemStack item)
{
if (item == null)
return false;
if (goldSet.isEmpty())
{
goldSet.add(Material.GOLD_SWORD);
goldSet.add(Material.GOLD_AXE);
goldSet.add(Material.GOLD_HELMET);
goldSet.add(Material.GOLD_CHESTPLATE);
goldSet.add(Material.GOLD_LEGGINGS);
goldSet.add(Material.GOLD_BOOTS);
}
return goldSet.contains(item.getType());
}
public static boolean isBow(ItemStack item)
{
if (item == null)
return false;
return item.getType() == Material.BOW;
}
public static boolean isWeapon(ItemStack item)
{
return isAxe(item) || isSword(item);
}
public static boolean isMat(ItemStack item, Material mat)
{
if (item == null)
return false;
return item.getType() == mat;
}
public static boolean isMatAndData(ItemStack item, Material mat, byte data)
{
if (item == null) return false;
return item.getType() == mat && item.getData().getData() == data;
}
public static boolean isRepairable(ItemStack item)
{
return (item.getType().getMaxDurability() > 0);
}
}

View File

@ -0,0 +1,453 @@
package mineplex.core.common.util;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.util.Vector;
public class UtilMath
{
public static final double TAU = Math.PI * 2D;
public static double trim(int degree, double d)
{
StringBuilder format = new StringBuilder("#.#");
for (int i = 1; i < degree; i++)
format.append("#");
DecimalFormatSymbols symb = new DecimalFormatSymbols(Locale.US);
DecimalFormat twoDForm = new DecimalFormat(format.toString(), symb);
return Double.valueOf(twoDForm.format(d));
}
public static Random random = new Random();
public static int r(int i)
{
return random.nextInt(i);
}
public static int rRange(int min, int max)
{
return min + r(1 + max - min);
}
public static double offset2d(Entity a, Entity b)
{
return offset2d(a.getLocation().toVector(), b.getLocation().toVector());
}
public static double offset2d(Location a, Location b)
{
return offset2d(a.toVector(), b.toVector());
}
public static double offset2d(Vector a, Vector b)
{
a.setY(0);
b.setY(0);
return a.subtract(b).length();
}
public static double offset2dSquared(Entity a, Entity b)
{
return offset2dSquared(a.getLocation().toVector(), b.getLocation().toVector());
}
public static double offset2dSquared(Location a, Location b)
{
return offset2dSquared(a.toVector(), b.toVector());
}
public static double offset2dSquared(Vector a, Vector b)
{
a.setY(0);
b.setY(0);
return a.subtract(b).lengthSquared();
}
public static double offset(Entity a, Entity b)
{
return offset(a.getLocation().toVector(), b.getLocation().toVector());
}
public static double offset(Location a, Location b)
{
return offset(a.toVector(), b.toVector());
}
public static double offset(Vector a, Vector b)
{
return a.clone().subtract(b).length();
}
public static double offsetSquared(Entity a, Entity b)
{
return offsetSquared(a.getLocation(), b.getLocation());
}
public static double offsetSquared(Location a, Location b)
{
return offsetSquared(a.toVector(), b.toVector());
}
public static double offsetSquared(Vector a, Vector b)
{
return a.distanceSquared(b);
}
public static double rr(double d, boolean bidirectional)
{
if (bidirectional) return Math.random() * (2 * d) - d;
return Math.random() * d;
}
public static <T> T randomElement(T[] array)
{
if (array.length == 0) return null;
return array[random.nextInt(array.length)];
}
public static <T> T randomElement(List<T> list)
{
if (list.isEmpty()) return null;
return list.get(random.nextInt(list.size()));
}
public static double clamp(double num, double min, double max)
{
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);
}
public static int clamp(int num, int min, int max)
{
return num < min ? min : (num > max ? max : num);
}
public static List<Integer> digits(int i) {
List<Integer> digits = new ArrayList<Integer>();
while(i > 0) {
digits.add(i % 10);
i /= 10;
}
return digits;
}
public static double random(double min, double max)
{
min = Math.abs(min);
int rand = -random.nextInt((int)(min * 100));
rand += random.nextInt((int)(max * 100));
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));
}
public static int getMax(int... ints)
{
if (ints.length < 1)
{
return -1;
}
int max = ints[0];
for (int i = 1; i < ints.length; i++)
{
max = Math.max(max, ints[i]);
}
return max;
}
public static int getMin(int... ints)
{
if (ints.length < 1)
{
return -1;
}
int min = ints[0];
for (int i = 1; i < ints.length; i++)
{
min = Math.min(min, ints[i]);
}
return min;
}
/**
* Creates an array of points, arranged in a circle normal to a vector.
*
* @param center The center of the circle.
* @param normal A vector normal to the circle.
* @param radius The radius of the circle.
* @param points How many points to make up the circle.
*
* @return An array of points of the form <code>double[point #][x=0, y=1, z=3]</code>.
*/
public static double[][] normalCircle(Location center, Vector normal, double radius, int points)
{
return normalCircle(center.toVector(), normal, radius, points);
}
/**
* Creates an array of points, arranged in a circle normal to a vector.
*
* @param center The center of the circle.
* @param normal A vector normal to the circle.
* @param radius The radius of the circle.
* @param points How many points to make up the circle.
*
* @return An array of points of the form <code>double[point #][x=0, y=1, z=3]</code>.
*/
public static double[][] normalCircle(Vector center, Vector normal, double radius, int points)
{
Vector n = normal.clone().normalize();
Vector a = n.clone().add(new Vector(1, 1, 1)).crossProduct(n).normalize();
Vector b = n.getCrossProduct(a).normalize();
double[][] data = new double[points][3];
double interval = TAU / points;
double theta = 0;
for (int i = 0; i < points; i++)
{
data[i][0] = center.getX() + (radius * ((Math.cos(theta) * a.getX()) + (Math.sin(theta) * b.getX())));
data[i][1] = center.getY() + (radius * ((Math.cos(theta) * a.getY()) + (Math.sin(theta) * b.getY())));
data[i][2] = center.getZ() + (radius * ((Math.cos(theta) * a.getZ()) + (Math.sin(theta) * b.getZ())));
theta += interval;
}
return data;
}
/**
* Slightly randomize a location with a standard deviation of one.
*
* @param location The location to randomize.
*
* @return The original location, now gaussian-randomized.
*/
public static Location gauss(Location location)
{
return gauss(location, 1, 1, 1);
}
/**
* Slightly randomize a vector with a standard deviation of one.
*
* @param vector The location to randomize.
*
* @return The randomized vector, now gaussian-randomized.
*/
public static Vector gauss(Vector vector)
{
return gauss(vector, 1, 1, 1);
}
/**
* Slightly randomize a location with a standard deviation of one. <br>
*
* <b>This method only accepts positive values for all of its arguments.</b> <br>
*
* A good parameter set for small offsets is (loc, 10, 10, 10).
*
* @param location The location to randomize.
* @param x A granularity control for the x-axis, higher numbers = less randomness
* @param y A granularity control for the y-axis, higher numbers = less randomness
* @param z A granularity control for the z-axis, higher numbers = less randomness
*
* @return The original location, now gaussian-randomized
*/
public static Location gauss(Location location, double x, double y, double z)
{
return location.clone().add(
x <= 0 ? 0 : (ThreadLocalRandom.current().nextGaussian() / x),
y <= 0 ? 0 : (ThreadLocalRandom.current().nextGaussian() / y),
z <= 0 ? 0 : (ThreadLocalRandom.current().nextGaussian() / z));
}
/**
* Slightly randomize a vector with a standard deviation of one. <br>
*
* <b>This method only accepts positive values for all of its arguments.</b> <br>
*
* A good parameter set for small offsets is (loc, 10, 10, 10).
*
* @param vector The location to randomize.
* @param x A granularity control for the x-axis, higher numbers = less randomness
* @param y A granularity control for the y-axis, higher numbers = less randomness
* @param z A granularity control for the z-axis, higher numbers = less randomness
*
* @return The randomized vector, now gaussian-randomized
*/
public static Vector gauss(Vector vector, double x, double y, double z)
{
return vector.clone().add(new Vector(
x <= 0 ? 0 : (ThreadLocalRandom.current().nextGaussian() / x),
y <= 0 ? 0 : (ThreadLocalRandom.current().nextGaussian() / y),
z <= 0 ? 0 : (ThreadLocalRandom.current().nextGaussian() / z)));
}
}

View File

@ -0,0 +1,100 @@
package mineplex.core.common.util;
import java.util.LinkedList;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import mineplex.core.common.events.PlayerMessageEvent;
import org.bukkit.Bukkit;
public class UtilPlayerBase
{
public static void message(Entity client, LinkedList<String> messageList)
{
message(client, messageList, false);
}
public static void message(Entity client, String message)
{
message(client, message, false);
}
public static void message(Entity client, LinkedList<String> messageList, boolean wiki)
{
for (String curMessage : messageList)
{
message(client, curMessage, wiki);
}
}
public static void message(Entity client, String message, boolean wiki)
{
if (client == null)
return;
if (!(client instanceof Player))
return;
/*
if (wiki)
message = UtilWiki.link(message);
*/
PlayerMessageEvent event = new PlayerMessageEvent((Player) client, message);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled())
return;
((Player) client).sendMessage(message);
}
public static void messageSearchOnlineResult(Player caller, String player, int matchCount)
{
message(caller, F.main("Online Player Search", "" + C.mCount + matchCount + C.mBody + " matches for [" + C.mElem + player + C.mBody + "]."));
}
public static Player searchOnline(Player caller, String player, boolean inform)
{
LinkedList<Player> matchList = new LinkedList<Player>();
for (Player cur : Bukkit.getOnlinePlayers())
{
if (cur.getName().equalsIgnoreCase(player))
return cur;
if (cur.getName().toLowerCase().contains(player.toLowerCase()))
matchList.add(cur);
}
// No / Non-Unique
if (matchList.size() != 1)
{
if (!inform)
return null;
// Inform
messageSearchOnlineResult(caller, player, matchList.size());
if (matchList.size() > 0)
{
String matchString = "";
for (Player cur : matchList)
matchString += F.elem(cur.getName()) + ", ";
if (matchString.length() > 1)
matchString = matchString.substring(0, matchString.length() - 2);
message(caller,
F.main("Online Player Search", "" + C.mBody + "Matches [" + C.mElem + matchString + C.mBody + "]."));
}
return null;
}
return matchList.get(0);
}
}

View File

@ -0,0 +1,249 @@
package mineplex.core.common.util;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
public class UtilTime
{
public static final ZoneId CENTRAL_ZONE = ZoneId.of("America/Chicago"); // This means "CST"
public static final String DATE_FORMAT_NOW = "MM-dd-yyyy HH:mm:ss";
public static final String DATE_FORMAT_DAY = "MM-dd-yyyy";
public static String now()
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
public static String when(long time)
{
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(time);
}
public static String date()
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DAY);
return sdf.format(cal.getTime());
}
public static String date(long date)
{
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DAY);
return sdf.format(date);
}
public static String getDayOfMonthSuffix(final int n)
{
if (n >= 11 && n <= 13) {
return "th";
}
switch (n % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
/**
* Converts a {@link Timestamp} to a {@link LocalDateTime}.
* This method will only work for timestamp's stored using {@link #CENTRAL_ZONE}, if stored using
* another zone please see: {@link #fromTimestamp(Timestamp, ZoneId)}.
*
* @param timestamp the timestamp to convert
* @return the time
*/
public static LocalDateTime fromTimestamp(Timestamp timestamp)
{
return fromTimestamp(timestamp, CENTRAL_ZONE);
}
/**
* Converts a {@link Timestamp} to a {@link LocalDateTime}.
* The zone supplied should be that of which the timezone was stored using.
*
* @param timestamp the timestamp to convert
* @param zoneId the zone of the timestamp
* @return the time
*/
public static LocalDateTime fromTimestamp(Timestamp timestamp, ZoneId zoneId)
{
return LocalDateTime.ofInstant(timestamp.toInstant(), zoneId);
}
/**
* Converts a {@link LocalDateTime} to a {@link Timestamp}.
* Please not that this will convert using the {@link #CENTRAL_ZONE} timezone.
*
* @param localDateTime the time to convert
* @return the timestamp
*/
public static Timestamp toTimestamp(LocalDateTime localDateTime)
{
return toTimestamp(localDateTime, CENTRAL_ZONE);
}
/**
* Converts a {@link LocalDateTime} to a {@link Timestamp}.
*
* @param localDateTime the time to convert
* @param zoneId the zone to use when converting to a timestamp
* @return the timestamp
*/
public static Timestamp toTimestamp(LocalDateTime localDateTime, ZoneId zoneId)
{
return new Timestamp(localDateTime.atZone(zoneId).toInstant().toEpochMilli());
}
public enum TimeUnit
{
FIT(1),
DAYS(86400000),
HOURS(3600000),
MINUTES(60000),
SECONDS(1000),
MILLISECONDS(1);
private long _ms;
TimeUnit(long ms)
{
_ms = ms;
}
public long getMilliseconds()
{
return _ms;
}
public static TimeUnit[] decreasingOrder()
{
return new TimeUnit[]{ DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS };
}
}
/**
* Convert from one TimeUnit to a different one
*/
public static long convert(long time, TimeUnit from, TimeUnit to)
{
long milleseconds = time * from.getMilliseconds();
return milleseconds / to.getMilliseconds();
}
public static String since(long epoch)
{
return "Took " + convertString(System.currentTimeMillis()-epoch, 1, TimeUnit.FIT) + ".";
}
public static double convert(long time, int trim, TimeUnit type)
{
if (type == TimeUnit.FIT)
{
if (time < 60000) type = TimeUnit.SECONDS;
else if (time < 3600000) type = TimeUnit.MINUTES;
else if (time < 86400000) type = TimeUnit.HOURS;
else type = TimeUnit.DAYS;
}
if (type == TimeUnit.DAYS) return UtilMath.trim(trim, (time)/86400000d);
if (type == TimeUnit.HOURS) return UtilMath.trim(trim, (time)/3600000d);
if (type == TimeUnit.MINUTES) return UtilMath.trim(trim, (time)/60000d);
if (type == TimeUnit.SECONDS) return UtilMath.trim(trim, (time)/1000d);
else return UtilMath.trim(trim, time);
}
public static String MakeStr(long time)
{
return convertString(time, 1, TimeUnit.FIT);
}
public static String MakeStr(long time, int trim)
{
return convertString(Math.max(0, time), trim, TimeUnit.FIT);
}
public static String convertColonString(long time)
{
return convertColonString(time, TimeUnit.HOURS, TimeUnit.SECONDS);
}
/**
* Converts a time into a colon separated string, displaying max to min units.
*
* @param time Time in milliseconds
* @param max The max {@link TimeUnit} to display, inclusive
* @param min The min {@link TimeUnit} to display, inclusive
* @return A colon separated string to represent the time
*/
public static String convertColonString(long time, TimeUnit max, TimeUnit min)
{
if (time == -1) return "Permanent";
else if (time == 0) return "0";
StringBuilder sb = new StringBuilder();
long curr = time;
for (TimeUnit unit : TimeUnit.decreasingOrder())
{
if (unit.getMilliseconds() >= min.getMilliseconds() && unit.getMilliseconds() <= max.getMilliseconds())
{
long amt = curr / unit.getMilliseconds();
if (amt < 10 && unit.getMilliseconds() != max.getMilliseconds()) sb.append('0'); // prefix single digit numbers with a 0
sb.append(amt);
if (unit.getMilliseconds() > min.getMilliseconds()) sb.append(':');
curr -= amt * unit.getMilliseconds();
}
}
return sb.toString();
}
public static String convertString(long time, int trim, TimeUnit type)
{
if (time <= -1) return "Permanent";
if (type == TimeUnit.FIT)
{
if (time < 60000) type = TimeUnit.SECONDS;
else if (time < 3600000) type = TimeUnit.MINUTES;
else if (time < 86400000) type = TimeUnit.HOURS;
else type = TimeUnit.DAYS;
}
String text;
double num;
if (trim == 0)
{
if (type == TimeUnit.DAYS) text = (num = UtilMath.trim(trim, time / 86400000d)) + " Day";
else if (type == TimeUnit.HOURS) text = (num = UtilMath.trim(trim, time / 3600000d)) + " Hour";
else if (type == TimeUnit.MINUTES) text = (int) (num = (int) UtilMath.trim(trim, time / 60000d)) + " Minute";
else if (type == TimeUnit.SECONDS) text = (int) (num = (int) UtilMath.trim(trim, time / 1000d)) + " Second";
else text = (int) (num = (int) UtilMath.trim(trim, time)) + " Millisecond";
}
else
{
if (type == TimeUnit.DAYS) text = (num = UtilMath.trim(trim, time / 86400000d)) + " Day";
else if (type == TimeUnit.HOURS) text = (num = UtilMath.trim(trim, time / 3600000d)) + " Hour";
else if (type == TimeUnit.MINUTES) text = (num = UtilMath.trim(trim, time / 60000d)) + " Minute";
else if (type == TimeUnit.SECONDS) text = (num = UtilMath.trim(trim, time / 1000d)) + " Second";
else text = (int) (num = (int) UtilMath.trim(0, time)) + " Millisecond";
}
if (num != 1)
text += "s";
return text;
}
public static boolean elapsed(long from, long required)
{
return System.currentTimeMillis() - from > required;
}
}

View File

@ -0,0 +1,310 @@
package mineplex.core.common.util;
import java.util.Collection;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldBorder;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.util.Vector;
import com.google.common.collect.Lists;
public class UtilWorld
{
public static World getWorld(String world)
{
return Bukkit.getServer().getWorld(world);
}
public static boolean isInChunk(Location location, Chunk chunk)
{
return location.getChunk().getX() == chunk.getX() && location.getChunk().getZ() == chunk.getZ() && chunk.getWorld().equals(location.getChunk().getWorld());
}
public static boolean areChunksEqual(Location first, Location second)
{
return first.getBlockX() >> 4 == second.getBlockX() >> 4 && first.getBlockZ() >> 4 == second.getBlockZ() >> 4;
}
public static String chunkToStr(Chunk chunk)
{
if (chunk == null)
return "";
return chunkToStr(chunk.getWorld().getName(), chunk.getX(), chunk.getZ());
}
public static String chunkToStr(Location location)
{
return chunkToStr(location.getWorld().getName(), location.getBlockX() >> 4, location.getBlockZ() >> 4);
}
public static String chunkToStr(String world, int x, int z)
{
return world + "," + x + "," + z;
}
public static String chunkToStrClean(Chunk chunk)
{
if (chunk == null)
return "";
return "(" + chunk.getX() + "," + chunk.getZ() + ")";
}
public static Chunk strToChunk(String string)
{
try
{
String[] tokens = string.split(",");
return getWorld(tokens[0]).getChunkAt(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2]));
}
catch (Exception e)
{
return null;
}
}
public static String blockToStr(Block block)
{
if (block == null)
return "";
return block.getWorld().getName() + "," +
block.getX() + "," +
block.getY() + "," +
block.getZ();
}
public static String blockToStrClean(Block block)
{
if (block == null)
return "";
return "(" + block.getX() + "," +
block.getY() + "," +
block.getZ() + ")";
}
public static Block strToBlock(String string)
{
if (string.length() == 0)
return null;
String[] parts = string.split(",");
try
{
for (World cur : Bukkit.getServer().getWorlds())
{
if (cur.getName().equalsIgnoreCase(parts[0]))
{
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
return cur.getBlockAt(x, y, z);
}
}
}
catch (Exception e)
{
}
return null;
}
public static String locToStr(Location loc)
{
if (loc == null)
return "";
return loc.getWorld().getName() + "," +
UtilMath.trim(1, loc.getX()) + "," +
UtilMath.trim(1, loc.getY()) + "," +
UtilMath.trim(1, loc.getZ());
}
public static String locToStrClean(Location loc)
{
if (loc == null)
return "Null";
return "(" + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ() + ")";
}
public static String vecToStrClean(Vector loc)
{
if (loc == null)
return "Null";
return "(" + loc.getX() + ", " + loc.getY() + ", " + loc.getZ() + ")";
}
public static Location strToLoc(String string)
{
if (string.length() == 0)
return null;
String[] tokens = string.split(",");
try
{
for (World cur : Bukkit.getServer().getWorlds())
{
if (cur.getName().equalsIgnoreCase(tokens[0]))
{
return new Location(cur, Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]), Double.parseDouble(tokens[3]));
}
}
}
catch (Exception e)
{
return null;
}
return null;
}
public static Location locMerge(Location a, Location b)
{
a.setX(b.getX());
a.setY(b.getY());
a.setZ(b.getZ());
return a;
}
public static String envToStr(Environment env)
{
if (env == Environment.NORMAL) return "Overworld";
if (env == Environment.NETHER) return "Nether";
if (env == Environment.THE_END) return "The End";
return "Unknown";
}
public static World getWorldType(Environment env)
{
for (World cur : Bukkit.getServer().getWorlds())
if (cur.getEnvironment() == env)
return cur;
return null;
}
public static Location averageLocation(Collection<Location> locs)
{
if (locs.isEmpty())
return null;
Vector vec = new Vector(0,0,0);
double count = 0;
World world = null;
for (Location spawn : locs)
{
count++;
vec.add(spawn.toVector());
world = spawn.getWorld();
}
vec.multiply(1d/count);
return vec.toLocation(world);
}
private static List<Block> branch(Location origin)
{
return Lists.newArrayList(origin.getBlock(),
origin.getBlock().getRelative(BlockFace.DOWN),
origin.getBlock().getRelative(BlockFace.UP),
origin.getBlock().getRelative(BlockFace.NORTH),
origin.getBlock().getRelative(BlockFace.EAST),
origin.getBlock().getRelative(BlockFace.SOUTH),
origin.getBlock().getRelative(BlockFace.WEST));
}
/**
* This method will use the World provided by the given Location.<p>
* @return <b>true</b> if the specified location is within the bounds of the
* world's set border, or <b>false</b> if {@link World#getWorldBorder()} returns null.
*/
public static boolean inWorldBorder(Location location)
{
WorldBorder border = location.getWorld().getWorldBorder();
if (border == null)
{
return false;
}
double size = border.getSize() / 2;
double maxX = size;
double maxZ = size;
double minX = -size;
double minZ = -size;
return location.getX() >= minX && location.getX() <= maxX && location.getZ() >= minZ && location.getZ() <= maxZ;
}
/**
* This method will use the World specified by the second argument, and the
* x, y, and z provided by the given Location.<p>
* @return <b>true</b> if the specified location is within the bounds of the
* world's set border, or <b>false</b> if {@link World#getWorldBorder()} returns null.
*/
public static boolean inWorldBorder(World world, Location location)
{
WorldBorder border = world.getWorldBorder();
if (border == null)
{
return false;
}
double size = border.getSize() / 2;
double maxX = size;
double maxZ = size;
double minX = -size;
double minZ = -size;
return location.getX() >= minX && location.getX() <= maxX && location.getZ() >= minZ && location.getZ() <= maxZ;
}
/**
* @return <b>true</b> if the specified bounding box is within the bounds of the
* world's set border, or <b>false</b> if {@link World#getWorldBorder()} returns null.
*/
public static boolean isBoxInWorldBorder(World world, Location min, Location max)
{
WorldBorder border = world.getWorldBorder();
if (border == null)
{
return false;
}
double size = border.getSize() / 2;
double maxX = size;
double maxZ = size;
double minX = -size;
double minZ = -size;
double startX = Math.min(min.getX(), max.getX());
double startZ = Math.min(min.getZ(), max.getZ());
double endX = Math.max(min.getX(), max.getX());
double endZ = Math.max(min.getZ(), max.getZ());
return startX >= minX && startZ <= maxX && endX >= minZ && endZ <= maxZ;
}
}

View File

@ -0,0 +1,268 @@
package mineplex.core.common.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipUtil
{
private static void getFileList(List<String> fileList, String sourceFolder, File node)
{
// add file only
if (node.isFile())
{
fileList.add(generateZipEntry(sourceFolder, node.getAbsoluteFile().toString()));
}
if (node.isDirectory())
{
String[] subNote = node.list();
for (String filename : subNote)
{
getFileList(fileList, sourceFolder, new File(node, filename));
}
}
}
private static String generateZipEntry(String sourceFolder, String file)
{
System.out.println(sourceFolder + " " + file);
return file.substring(sourceFolder.length() + 1, file.length());
}
public static void ZipFolders(String sourceFolder, String zipFilename, List<String> folders, List<String> files)
{
ZipOutputStream zipOutputStream = null;
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
List<String> fileList = new ArrayList<String>();
byte[] buffer = new byte[2048];
try
{
fileOutputStream = new FileOutputStream(zipFilename);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
zipOutputStream = new ZipOutputStream(bufferedOutputStream);
ZipEntry entry;
for (String file : files)
{
fileList.add(generateZipEntry(sourceFolder, new File(file).getAbsoluteFile().toString()));
}
for (String folder : folders)
{
getFileList(fileList, sourceFolder, new File(folder));
}
for (String file : fileList)
{
entry = new ZipEntry(file);
zipOutputStream.putNextEntry(entry);
fileInputStream = new FileInputStream(sourceFolder + File.separator + file);
int len;
while ((len = fileInputStream.read(buffer)) > 0)
{
zipOutputStream.write(buffer, 0, len);
}
fileInputStream.close();
}
zipOutputStream.flush();
zipOutputStream.close();
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
if (fileInputStream != null)
{
try
{
fileInputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (bufferedOutputStream != null)
{
try
{
bufferedOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (zipOutputStream != null)
{
try
{
zipOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (fileOutputStream != null)
{
try
{
fileOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (bufferedOutputStream != null)
{
try
{
bufferedOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
public static void UnzipToDirectory(String zipFilePath, String outputDirectory)
{
FileInputStream fileInputStream = null;
ZipInputStream zipInputStream = null;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
BufferedInputStream bufferedInputStream = null;
try
{
fileInputStream = new FileInputStream(zipFilePath);
bufferedInputStream = new BufferedInputStream(fileInputStream);
zipInputStream = new ZipInputStream(bufferedInputStream);
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null)
{
int size;
byte[] buffer = new byte[2048];
String fileName = outputDirectory + File.separator + entry.getName();
if (fileName.endsWith("/"))
{
new File(fileName).mkdirs();
continue;
}
fileOutputStream = new FileOutputStream(fileName);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream, buffer.length);
while ((size = zipInputStream.read(buffer, 0, buffer.length)) != -1)
{
bufferedOutputStream.write(buffer, 0, size);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
}
zipInputStream.close();
bufferedInputStream.close();
fileInputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
if (fileInputStream != null)
{
try
{
fileInputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (bufferedInputStream != null)
{
try
{
bufferedInputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (zipInputStream != null)
{
try
{
zipInputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (fileOutputStream != null)
{
try
{
fileOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
if (bufferedOutputStream != null)
{
try
{
bufferedOutputStream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
}