use one mcore only

This commit is contained in:
Olof Larsson
2013-02-22 08:27:28 +01:00
parent 022e05ceaa
commit 06bf6f2946
422 changed files with 1476 additions and 1476 deletions

View File

@@ -0,0 +1,46 @@
package com.massivecraft.mcore;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.massivecraft.mcore.cmd.CmdMcore;
import com.massivecraft.mcore.usys.cmd.CmdUsys;
import com.massivecraft.mcore.util.MUtil;
public class Conf extends SimpleConfig
{
// -------------------------------------------- //
// CONTENT
// -------------------------------------------- //
public static String dburi = "gson://./mstore";
public static String serverid = UUID.randomUUID().toString();
public static Map<String, List<String>> cmdaliases = MUtil.map(
CmdUsys.USYS, MUtil.list(CmdUsys.USYS),
CmdMcore.MCORE, MUtil.list(CmdMcore.MCORE)
);
public static int tpdelay = 10;
public static List<String> getCmdAliases(String name)
{
List<String> ret = cmdaliases.get(name);
if (ret == null)
{
ret = MUtil.list(name);
cmdaliases.put(name, ret);
i.save();
}
return ret;
}
// -------------------------------------------- //
// META
// -------------------------------------------- //
public static transient Conf i = new Conf();
private Conf()
{
super(MCore.p, new File("plugins/mcore/conf.json"));
}
}

View File

@@ -0,0 +1,254 @@
package com.massivecraft.mcore;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import com.massivecraft.mcore.event.MCoreAfterPlayerRespawnEvent;
import com.massivecraft.mcore.event.MCoreAfterPlayerTeleportEvent;
import com.massivecraft.mcore.event.MCorePlayerLeaveEvent;
import com.massivecraft.mcore.event.MCoreSenderRegisterEvent;
import com.massivecraft.mcore.event.MCoreSenderUnregisterEvent;
import com.massivecraft.mcore.mixin.Mixin;
import com.massivecraft.mcore.store.Coll;
import com.massivecraft.mcore.store.SenderColl;
import com.massivecraft.mcore.util.SenderUtil;
import com.massivecraft.mcore.util.SmokeUtil;
public class InternalListener implements Listener
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static InternalListener i = new InternalListener();
public static InternalListener get() { return i; }
// -------------------------------------------- //
// REGISTER
// -------------------------------------------- //
public void setup()
{
MCorePlayerLeaveEvent.player2event.clear();
Bukkit.getPluginManager().registerEvents(this, MCore.get());
}
// -------------------------------------------- //
// CHAT TAB COMPLETE
// -------------------------------------------- //
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void chatTabComplete(PlayerChatTabCompleteEvent event)
{
// So the player is watching ...
Player watcher = event.getPlayer();
// Get the lowercased token
String tokenlc = event.getLastToken().toLowerCase();
// Create a case insensitive set to check for already added stuff
Set<String> current = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
current.addAll(event.getTabCompletions());
// Add ids of all online senders that match and isn't added yet.
for (String senderId : Mixin.getOnlineSenderIds())
{
if (!senderId.toLowerCase().startsWith(tokenlc)) continue;
if (current.contains(senderId)) continue;
if (!Mixin.isVisible(watcher, senderId)) continue;
event.getTabCompletions().add(senderId);
}
}
// -------------------------------------------- //
// EXPLOSION FX
// -------------------------------------------- //
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void explosionFx(EntityDamageByBlockEvent event)
{
// If an entity is taking damage from a block explosion ...
DamageCause cause = event.getCause();
if (cause != DamageCause.BLOCK_EXPLOSION) return;
// ... and that explosion is a fake ...
if (SmokeUtil.fakeExplosion == false) return;
// ... then cancel the event and the damage.
event.setCancelled(true);
}
// -------------------------------------------- //
// PLAYER AND SENDER REFERENCES
// -------------------------------------------- //
@EventHandler(priority = EventPriority.LOWEST)
public void senderReferencesLoginLowest(PlayerLoginEvent event)
{
String id = SenderUtil.getSenderId(event.getPlayer());
CommandSender sender = event.getPlayer();
SenderColl.setSenderRefferences(id, sender);
}
@EventHandler(priority = EventPriority.MONITOR)
public void senderReferencesLoginMonitor(PlayerLoginEvent event)
{
if (event.getResult() == Result.ALLOWED) return;
String id = SenderUtil.getSenderId(event.getPlayer());
CommandSender sender = null;
SenderColl.setSenderRefferences(id, sender);
}
@EventHandler(priority = EventPriority.MONITOR)
public void senderReferencesQuitMonitor(PlayerQuitEvent event)
{
String id = SenderUtil.getSenderId(event.getPlayer());
CommandSender sender = null;
SenderColl.setSenderRefferences(id, sender);
}
@EventHandler(priority = EventPriority.MONITOR)
public void senderReferencesRegisterMonitor(MCoreSenderRegisterEvent event)
{
String id = SenderUtil.getSenderId(event.getSender());
CommandSender sender = event.getSender();
SenderColl.setSenderRefferences(id, sender);
}
@EventHandler(priority = EventPriority.MONITOR)
public void senderReferencesUnregisterMonitor(MCoreSenderUnregisterEvent event)
{
String id = SenderUtil.getSenderId(event.getSender());
CommandSender sender = null;
SenderColl.setSenderRefferences(id, sender);
}
// -------------------------------------------- //
// AFTER EVENTS
// -------------------------------------------- //
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void after(PlayerTeleportEvent event)
{
Bukkit.getScheduler().scheduleSyncDelayedTask(MCore.get(), new MCoreAfterPlayerTeleportEvent(event), 0);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void after(PlayerRespawnEvent event)
{
Bukkit.getScheduler().scheduleSyncDelayedTask(MCore.get(), new MCoreAfterPlayerRespawnEvent(event, event.getPlayer().getLocation()), 0);
}
// -------------------------------------------- //
// EVENT TOOL: causedByKick
// -------------------------------------------- //
public static Map<String,String> kickedPlayerReasons = new HashMap<String,String>();
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void causedByKick(PlayerKickEvent event)
{
final String name = event.getPlayer().getName();
kickedPlayerReasons.put(name, event.getReason());
}
@EventHandler(priority = EventPriority.MONITOR)
public void causedByKick(PlayerQuitEvent event)
{
// We do the schedule in order for the set to be correct through out the whole MONITOR priority state.
final String name = event.getPlayer().getName();
Bukkit.getScheduler().scheduleSyncDelayedTask(MCore.p, new Runnable()
{
@Override
public void run()
{
kickedPlayerReasons.remove(name);
}
});
}
// -------------------------------------------- //
// PLAYER LEAVE EVENT
// -------------------------------------------- //
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void leaveEventKickCall(PlayerKickEvent event)
{
new MCorePlayerLeaveEvent(event.getPlayer(), true, "kick", event.getReason()).run();
}
@EventHandler(priority = EventPriority.MONITOR)
public void leaveEventQuitCall(PlayerQuitEvent event)
{
new MCorePlayerLeaveEvent(event.getPlayer(), false, "quit", null).run();
}
@EventHandler(priority = EventPriority.MONITOR)
public void leaveEventQuitClear(PlayerQuitEvent event)
{
// We do the schedule in order for the set to be correct through out the whole MONITOR priority state.
final String name = event.getPlayer().getName();
Bukkit.getScheduler().scheduleSyncDelayedTask(MCore.p, new Runnable()
{
@Override
public void run()
{
MCorePlayerLeaveEvent.player2event.remove(name);
}
});
}
// -------------------------------------------- //
// SYNC PLAYER ON LOGON AND LEAVE
// -------------------------------------------- //
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void syncOnPlayerLogin(PlayerLoginEvent event)
{
MCore.get().log("LOWEST syncOnPlayerLogin", event.getPlayer().getName());
this.syncAllForPlayer(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void syncOnPlayerLeave(MCorePlayerLeaveEvent event)
{
MCore.get().log("MONITOR syncOnPlayerLeave", event.getPlayer().getName());
this.syncAllForPlayer(event.getPlayer());
}
public void syncAllForPlayer(Player player)
{
String playerName = player.getName();
for (Coll<?, ?> coll : Coll.instances)
{
if (!(coll instanceof SenderColl)) continue;
SenderColl<?> pcoll = (SenderColl<?>)coll;
pcoll.syncId(playerName);
}
}
}

View File

@@ -0,0 +1,12 @@
package com.massivecraft.mcore;
public class Lang
{
public static final String permForbidden = "<b>You don't have permission to %s.";
public static final String permDoThat = "do that";
public static final String commandSenderMustBePlayer = "<b>This command can only be used by ingame players.";
public static final String commandToFewArgs = "<b>To few arguments. <i>Use like this:";
public static final String commandToManyArgs = "<b>Strange arguments %s<b>.";
public static final String commandToManyArgs2 = "<i>Use the command like this:";
}

View File

@@ -0,0 +1,182 @@
package com.massivecraft.mcore;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.massivecraft.mcore.adapter.InventoryAdapter;
import com.massivecraft.mcore.adapter.ItemStackAdapter;
import com.massivecraft.mcore.adapter.MongoURIAdapter;
import com.massivecraft.mcore.adapter.PSAdapter;
import com.massivecraft.mcore.cmd.CmdMcore;
import com.massivecraft.mcore.mixin.ScheduledTeleportListener;
import com.massivecraft.mcore.mixin.SenderIdMixinDefault;
import com.massivecraft.mcore.store.Coll;
import com.massivecraft.mcore.store.Db;
import com.massivecraft.mcore.store.MStore;
import com.massivecraft.mcore.usys.AspectColl;
import com.massivecraft.mcore.usys.MultiverseColl;
import com.massivecraft.mcore.usys.cmd.CmdUsys;
import com.massivecraft.mcore.util.PlayerUtil;
import com.massivecraft.mcore.util.TimeDiffUtil;
import com.massivecraft.mcore.util.TimeUnit;
import com.massivecraft.mcore.xlib.gson.Gson;
import com.massivecraft.mcore.xlib.gson.GsonBuilder;
import com.massivecraft.mcore.xlib.mongodb.MongoURI;
public class MCore extends MPlugin
{
// -------------------------------------------- //
// COMMON CONSTANTS
// -------------------------------------------- //
public final static String INSTANCE = "instance";
public final static String DEFAULT = "default";
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
public static MCore p;
public static MCore get() { return p; }
public MCore() { p = this; }
// -------------------------------------------- //
// STATIC
// -------------------------------------------- //
public static Random random = new Random();
public static Gson gson = getMCoreGsonBuilder().create();
public static GsonBuilder getMCoreGsonBuilder()
{
return new GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.excludeFieldsWithModifiers(Modifier.TRANSIENT)
.registerTypeAdapter(MongoURI.class, MongoURIAdapter.get())
.registerTypeAdapter(ItemStack.class, ItemStackAdapter.get())
.registerTypeAdapter(Inventory.class, InventoryAdapter.get())
.registerTypeAdapter(PS.class, new PSAdapter());
}
public static String getServerId() { return Conf.serverid; }
private static Db<?> db;
public static Db<?> getDb() { return db; }
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
// Commands
public CmdUsys cmdUsys;
public CmdMcore cmdMcore;
private Runnable collTickTask = new Runnable()
{
public void run()
{
for (Coll<?, ?> coll : Coll.instances)
{
coll.onTick();
}
}
};
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public void onEnable()
{
// This is safe since all plugins using Persist should bukkit-depend this plugin.
// Note this one must be before preEnable. dooh.
Coll.instances.clear();
if ( ! preEnable()) return;
Conf.i.load();
// Setup the default database
db = MStore.getDb(Conf.dburi);
// Setup PlayerUtil and it's events
new PlayerUtil(this);
SenderIdMixinDefault.get().setup();
// Register events
InternalListener.get().setup();
ScheduledTeleportListener.get().setup();
// Schedule the collection ticker.
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, this.collTickTask, 1, 1);
// Init internal collections
MultiverseColl.i.init();
AspectColl.i.init();
// Register commands
this.cmdUsys = new CmdUsys();
this.cmdUsys.register(this, true);
this.cmdMcore = new CmdMcore();
this.cmdMcore.register(this, true);
/*
test("");
test("+1day");
test("1day");
test("1 day");
test("-1day");
test("1week4d");
test("+1week-4d");
test("day");
test("1month");
test("1months");
test("1months2ms");
*/
this.postEnable();
}
public void test(String diffString)
{
log("===========================");
log("Testing Diff String \""+diffString+"\":");
try
{
Map<TimeUnit, Long> unitcounts = TimeDiffUtil.unitcounts(diffString);
for (Entry<TimeUnit, Long> entry : unitcounts.entrySet())
{
System.out.println(entry.getValue()+": "+entry.getKey());
}
System.out.println("---");
long millis = TimeDiffUtil.millis(unitcounts);
log("millis: "+millis);
String verboose = ChatColor.stripColor(TimeDiffUtil.formatedVerboose(unitcounts));
String minimal = ChatColor.stripColor(TimeDiffUtil.formatedMinimal(unitcounts));
log("verboose: "+verboose);
log("minimal: "+minimal);
long millisRec = TimeDiffUtil.millis(minimal);
log("millisRec: "+millisRec);
log("matches: "+(millis == millisRec));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,116 @@
package com.massivecraft.mcore;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import com.massivecraft.mcore.integration.Integration;
import com.massivecraft.mcore.integration.IntegrationFeatures;
import com.massivecraft.mcore.store.Coll;
import com.massivecraft.mcore.util.Txt;
import com.massivecraft.mcore.xlib.gson.Gson;
import com.massivecraft.mcore.xlib.gson.GsonBuilder;
public abstract class MPlugin extends JavaPlugin implements Listener
{
// Gson
public Gson gson;
// -------------------------------------------- //
// ENABLE
// -------------------------------------------- //
private long timeEnableStart;
public boolean preEnable()
{
timeEnableStart = System.currentTimeMillis();
this.logPrefixColored = Txt.parse("<teal>[<aqua>%s %s<teal>] <i>", this.getDescription().getName(), this.getDescription().getVersion());
this.logPrefixPlain = ChatColor.stripColor(this.logPrefixColored);
log("=== ENABLE START ===");
// Create Gson
this.gson = this.getGsonBuilder().create();
return true;
}
public void postEnable()
{
log(Txt.parse("=== ENABLE <g>COMPLETE <i>(Took <h>"+(System.currentTimeMillis()-timeEnableStart)+"ms<i>) ==="));
}
// -------------------------------------------- //
// DISABLE
// -------------------------------------------- //
public void onDisable()
{
// Collection shutdowns.
for (Coll<?, ?> coll : Coll.instances)
{
if (coll.getMplugin() != this) continue;
coll.examineThread().interrupt();
coll.syncAll(); // TODO: Save outwards only? We may want to avoid loads at this stage...
Coll.instances.remove(coll);
}
log("Disabled");
}
// -------------------------------------------- //
// GSON
// -------------------------------------------- //
public GsonBuilder getGsonBuilder()
{
return MCore.getMCoreGsonBuilder();
}
// -------------------------------------------- //
// CONVENIENCE
// -------------------------------------------- //
public void suicide()
{
log(Txt.parse("<b>Now I suicide!"));
Bukkit.getPluginManager().disablePlugin(this);
}
public void integrate(IntegrationFeatures... features)
{
for (IntegrationFeatures f : features)
{
new Integration(this, f);
}
}
// -------------------------------------------- //
// LOGGING
// -------------------------------------------- //
private String logPrefixColored = null;
private String logPrefixPlain = null;
public void log(Object... msg)
{
log(Level.INFO, msg);
}
public void log(Level level, Object... msg)
{
String imploded = Txt.implode(msg, " ");
ConsoleCommandSender sender = Bukkit.getConsoleSender();
if (level == Level.INFO && sender != null)
{
Bukkit.getConsoleSender().sendMessage(this.logPrefixColored + imploded);
}
else
{
Logger.getLogger("Minecraft").log(level, this.logPrefixPlain + imploded);
}
}
}

View File

@@ -0,0 +1,711 @@
package com.massivecraft.mcore;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import com.massivecraft.mcore.mixin.Mixin;
import com.massivecraft.mcore.mixin.TeleportMixinDefault;
import com.massivecraft.mcore.mixin.TeleporterException;
import com.massivecraft.mcore.usys.Aspect;
import com.massivecraft.mcore.usys.Multiverse;
import com.massivecraft.mcore.util.MUtil;
import com.massivecraft.mcore.util.Txt;
import com.massivecraft.mcore.xlib.gson.annotations.SerializedName;
/**
* PS stands for PhysicalState.
* This class stores data related to just that.
* When coding plugins you may find yourself wanting to store a player location.
* Another time you may want to store the player location but without the worldName info.
* Another time you may want to store pitch and yaw only.
* This class is supposed to be usable in all those cases.
* Hopefully this class will save you from implementing special classes for all those combinations.
*/
@EqualsAndHashCode
public class PS implements Cloneable, Serializable
{
// -------------------------------------------- //
// CONSTANTS
// -------------------------------------------- //
private static final transient long serialVersionUID = 1L;
public static final transient String UNKNOWN_WORLD_NAME = "?";
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
// Field: worldName
@SerializedName("w")
@Getter @Setter protected String worldName = null;
// FakeField: world
public World getWorld()
{
if (this.worldName == null) return null;
return Bukkit.getWorld(this.worldName);
}
public void setWorld(World val)
{
this.worldName = val.getName();
}
// ---------------------
// Field: blockX
@SerializedName("bx")
@Getter @Setter protected Integer blockX = null;
public Integer calcBlockX()
{
return calcBlock(this.locationX, this.blockX, this.chunkX);
}
// Field: blockY
@SerializedName("by")
@Getter @Setter protected Integer blockY = null;
public Integer calcBlockY()
{
return calcBlock(this.locationY, this.blockY, null);
}
// Field: blockZ
@SerializedName("bz")
@Getter @Setter protected Integer blockZ = null;
public Integer calcBlockZ()
{
return calcBlock(this.locationZ, this.blockZ, this.chunkZ);
}
protected static synchronized Integer calcBlock(Double location, Integer block, Integer chunk)
{
if (block != null) return block;
if (location != null) return (int) Math.floor(location);
if (chunk != null) return chunk * 16;
return null;
}
// ---------------------
// Field: locationX
@SerializedName("lx")
@Getter @Setter protected Double locationX = null;
public Double calcLocationX()
{
return calcLocation(this.locationX, this.blockX, this.chunkX);
}
// Field: locationY
@SerializedName("ly")
@Getter @Setter protected Double locationY = null;
public Double calcLocationY()
{
return calcLocation(this.locationY, this.blockY, null);
}
// Field: locationZ
@SerializedName("lz")
@Getter @Setter protected Double locationZ = null;
public Double calcLocationZ()
{
return calcLocation(this.locationZ, this.blockZ, this.chunkZ);
}
protected static synchronized Double calcLocation(Double location, Integer block, Integer chunk)
{
if (location != null) return location;
if (block != null) return (double) block;
if (chunk != null) return chunk * 16D;
return null;
}
// ---------------------
// Field: chunkX
@SerializedName("cx")
@Getter @Setter protected Integer chunkX = null;
public Integer calcChunkX()
{
return calcChunk(this.locationX, this.blockX, this.chunkX);
}
// Field: chunkZ
@SerializedName("xz")
@Getter @Setter protected Integer chunkZ = null;
public Integer calcChunkZ()
{
return calcChunk(this.locationZ, this.blockZ, this.chunkZ);
}
protected static synchronized Integer calcChunk(Double location, Integer block, Integer chunk)
{
if (chunk != null) return chunk;
if (location != null) return location.intValue() >> 4;
if (block != null) return block >> 4;
return null;
}
// ---------------------
// Field: pitch
@SerializedName("p")
@Getter @Setter protected Float pitch = null;
/*public void setPitch(Float val)
{
if (val == null)
{
this.pitch = null;
}
else
{
this.pitch = (val + 360F) % 360F;
}
}*/
// Field: yaw
@SerializedName("y")
@Getter @Setter protected Float yaw = null;
// ---------------------
// Field: velocityX
@SerializedName("vx")
@Getter @Setter protected Double velocityX = null;
public Double calcVelocityX()
{
return calcVelocity(this.locationX, this.blockX, this.chunkX, this.velocityX);
}
// Field: velocityY
@SerializedName("vy")
@Getter @Setter protected Double velocityY = null;
public Double calcVelocityY()
{
return calcVelocity(this.locationY, this.blockY, 0, this.velocityY);
}
// Field: velocityZ
@SerializedName("vz")
@Getter @Setter protected Double velocityZ = null;
public Double calcVelocityZ()
{
return calcVelocity(this.locationZ, this.blockZ, this.chunkZ, this.velocityZ);
}
protected static synchronized Double calcVelocity(Double location, Integer block, Integer chunk, Double velocity)
{
if (velocity != null) return velocity;
if (location != null) return location;
if (block != null) return (double) block;
if (chunk != null) return chunk * 16D;
return null;
}
//----------------------------------------------//
// GET / CALC
//----------------------------------------------//
public synchronized Location getLocation()
{
return this.innerLocation(this.getLocationX(), this.getLocationY(), this.getLocationZ());
}
public synchronized Location calcLocation()
{
return this.innerLocation(this.calcLocationX(), this.calcLocationY(), this.calcLocationZ());
}
protected synchronized Location innerLocation(Double x, Double y, Double z)
{
World world = this.getWorld();
if (world == null) return null;
if (x == null) return null;
if (y == null) return null;
if (z == null) return null;
Float pitch = this.getPitch();
if (pitch == null) pitch = 0F;
Float yaw = this.getYaw();
if (yaw == null) yaw = 0F;
return new Location(world, x, y, z, yaw, pitch);
}
public synchronized Block getBlock()
{
return this.innerBlock(this.getBlockX(), this.getBlockY(), this.getBlockZ());
}
public synchronized Block calcBlock()
{
return this.innerBlock(this.calcBlockX(), this.calcBlockY(), this.calcBlockZ());
}
protected synchronized Block innerBlock(Integer x, Integer y, Integer z)
{
World world = this.getWorld();
if (world == null) return null;
if (x == null) return null;
if (y == null) return null;
if (z == null) return null;
return world.getBlockAt(x, y, z);
}
public synchronized Chunk getChunk()
{
return this.innerChunk(this.getChunkX(), this.getChunkZ());
}
public synchronized Chunk calcChunk()
{
return this.innerChunk(this.calcChunkX(), this.calcChunkZ());
}
protected synchronized Chunk innerChunk(Integer x, Integer z)
{
World world = this.getWorld();
if (world == null) return null;
if (x == null) return null;
if (z == null) return null;
return world.getChunkAt(x, z);
}
public synchronized Vector getVelocity()
{
return this.innerVelocity(this.getVelocityX(), this.getVelocityY(), this.getVelocityZ());
}
public synchronized Vector calcVelocity()
{
return this.innerVelocity(this.calcVelocityX(), this.calcVelocityY(), this.calcVelocityZ());
}
protected synchronized Vector innerVelocity(Double x, Double y, Double z)
{
if (x == null) return null;
if (y == null) return null;
if (z == null) return null;
return new Vector(x, y, z);
}
//----------------------------------------------//
// SET
//----------------------------------------------//
public synchronized void setDefault()
{
this.worldName = null;
this.blockX = null;
this.blockY = null;
this.blockZ = null;
this.locationX = null;
this.locationY = null;
this.locationZ = null;
this.chunkX = null;
this.chunkZ = null;
this.pitch = null;
this.yaw = null;
this.velocityX = null;
this.velocityY = null;
this.velocityZ = null;
}
public synchronized void setPSTransparent(PS ps)
{
if (ps.worldName != null) this.worldName = ps.worldName;
if (ps.blockX != null) this.blockX = ps.blockX;
if (ps.blockY != null) this.blockY = ps.blockY;
if (ps.blockZ != null) this.blockZ = ps.blockZ;
if (ps.locationX != null) this.locationX = ps.locationX;
if (ps.locationY != null) this.locationY = ps.locationY;
if (ps.locationZ != null) this.locationZ = ps.locationZ;
if (ps.chunkX != null) this.chunkX = ps.chunkX;
if (ps.chunkZ != null) this.chunkZ = ps.chunkZ;
if (ps.pitch != null) this.pitch = ps.pitch;
if (ps.yaw != null) this.yaw = ps.yaw;
if (ps.velocityX != null) this.velocityX = ps.velocityX;
if (ps.velocityY != null) this.velocityY = ps.velocityY;
if (ps.velocityZ != null) this.velocityZ = ps.velocityZ;
}
public synchronized void setPS(PS ps)
{
this.worldName = ps.worldName;
this.blockX = ps.blockX;
this.blockY = ps.blockY;
this.blockZ = ps.blockZ;
this.locationX = ps.locationX;
this.locationY = ps.locationY;
this.locationZ = ps.locationZ;
this.chunkX = ps.chunkX;
this.chunkZ = ps.chunkZ;
this.pitch = ps.pitch;
this.yaw = ps.yaw;
this.velocityX = ps.velocityX;
this.velocityY = ps.velocityY;
this.velocityZ = ps.velocityZ;
}
// ---------------------
public synchronized void setLocation(Location location)
{
this.setDefault();
this.setLocationTransparent(location);
}
public synchronized void setLocationTransparent(Location location)
{
this.worldName = location.getWorld().getName();
this.locationX = location.getX();
this.locationY = location.getY();
this.locationZ = location.getZ();
this.setPitch(location.getPitch());
this.yaw = location.getYaw();
}
// ---------------------
public synchronized void setVelocity(Vector vector)
{
this.setDefault();
this.setVelocityTransparent(vector);
}
public synchronized void setVelocityTransparent(Vector vector)
{
this.velocityX = vector.getX();
this.velocityY = vector.getY();
this.velocityZ = vector.getZ();
}
// ---------------------
public synchronized void setEntity(Entity entity)
{
this.setDefault();
this.setEntityTransparent(entity);
}
public synchronized void setEntityTransparent(Entity entity)
{
this.setLocationTransparent(entity.getLocation());
this.setVelocityTransparent(entity.getVelocity());
}
// ---------------------
public synchronized void setBlock(Block block)
{
this.setDefault();
this.setBlockTransparent(block);
}
public synchronized void setBlockTransparent(Block block)
{
this.worldName = block.getWorld().getName();
this.blockX = block.getX();
this.blockY = block.getY();
this.blockZ = block.getZ();
}
// ---------------------
public synchronized void setChunk(Chunk chunk)
{
this.setDefault();
this.setChunkTransparent(chunk);
}
public synchronized void setChunkTransparent(Chunk chunk)
{
this.worldName = chunk.getWorld().getName();
this.chunkX = chunk.getX();
this.chunkZ = chunk.getZ();
}
// ---------------------
public synchronized void setOldString(String str)
{
this.setDefault();
this.setOldStringTransparent(str);
}
public synchronized void setOldStringTransparent(String str)
{
String[] parts = str.split("\\|");
if (parts.length == 4)
{
this.worldName = parts[0];
this.blockX = Integer.parseInt(parts[1]);
this.blockY = Integer.parseInt(parts[2]);
this.blockZ = Integer.parseInt(parts[3]);
}
else if (parts.length == 6)
{
this.worldName = parts[0];
this.locationX = Double.parseDouble(parts[1]);
this.locationY = Double.parseDouble(parts[2]);
this.locationZ = Double.parseDouble(parts[3]);
this.pitch = Float.parseFloat(parts[4]);
this.yaw = Float.parseFloat(parts[5]);
}
}
//----------------------------------------------//
// WRITERS
//----------------------------------------------//
public synchronized void write(Entity entity) throws TeleporterException
{
if (entity instanceof Player)
{
Mixin.teleport((Player)entity, this);
}
else
{
TeleportMixinDefault.teleportEntity(entity, this);
}
}
//----------------------------------------------//
// CONSTRUCTORS
//----------------------------------------------//
public PS()
{
}
public PS(PS ps)
{
this.setPS(ps);
}
public PS(Location location)
{
this.setLocationTransparent(location);
}
public PS(Vector velocity)
{
this.setVelocityTransparent(velocity);
}
public PS(Entity entity)
{
this.setEntityTransparent(entity);
}
public PS(Block block)
{
this.setBlockTransparent(block);
}
public PS(Chunk chunk)
{
this.setChunkTransparent(chunk);
}
public PS(String oldString)
{
this.setOldStringTransparent(oldString);
}
//----------------------------------------------//
// TO STRING
//----------------------------------------------//
@Override
public synchronized String toString()
{
return this.getClass().getSimpleName()+MCore.gson.toJson(this);
}
protected final transient static DecimalFormat twoDForm = new DecimalFormat("#.##");
public List<String> getDesc()
{
// ret.add("<h>World <a>"+this.worldName);
return this.getDesc("<k>%s <v>%s");
}
public List<String> getDesc(String format)
{
List<String> ret = new ArrayList<String>();
if (this.worldName != null) ret.add(Txt.parse(format, "World", this.worldName));
if (this.blockX != null) ret.add(Txt.parse(format, "Block X", this.blockX));
if (this.blockY != null) ret.add(Txt.parse(format, "Block Y", this.blockY));
if (this.blockZ != null) ret.add(Txt.parse(format, "Block Z", this.blockZ));
if (this.locationX != null) ret.add(Txt.parse(format, "Location X", twoDForm.format(this.locationX)));
if (this.locationY != null) ret.add(Txt.parse(format, "Location Y", twoDForm.format(this.locationY)));
if (this.locationZ != null) ret.add(Txt.parse(format, "Location Z", twoDForm.format(this.locationZ)));
if (this.chunkX != null) ret.add(Txt.parse(format, "Chunk X", this.chunkX));
if (this.chunkZ != null) ret.add(Txt.parse(format, "Chunk Z", this.chunkZ));
if (this.pitch != null) ret.add(Txt.parse(format, "Pitch", twoDForm.format(this.pitch)));
if (this.yaw != null) ret.add(Txt.parse(format, "Yaw", twoDForm.format(this.yaw)));
if (this.velocityX != null) ret.add(Txt.parse(format, "Velocity X", twoDForm.format(this.velocityX)));
if (this.velocityY != null) ret.add(Txt.parse(format, "Velocity Y", twoDForm.format(this.velocityY)));
if (this.velocityZ != null) ret.add(Txt.parse(format, "Velocity Z", twoDForm.format(this.velocityZ)));
return ret;
}
public String getShortDesc()
{
return this.getShortDesc("<k>%s <v>%s ");
}
public String getShortDesc(String format)
{
List<String> ret = new ArrayList<String>();
if (this.worldName != null) ret.add(Txt.parse(format, "w", this.worldName));
if (this.blockX != null) ret.add(Txt.parse(format, "bx", this.blockX));
if (this.blockY != null) ret.add(Txt.parse(format, "by", this.blockY));
if (this.blockZ != null) ret.add(Txt.parse(format, "bz", this.blockZ));
if (this.locationX != null) ret.add(Txt.parse(format, "lx", twoDForm.format(this.locationX)));
if (this.locationY != null) ret.add(Txt.parse(format, "ly", twoDForm.format(this.locationY)));
if (this.locationZ != null) ret.add(Txt.parse(format, "lz", twoDForm.format(this.locationZ)));
if (this.chunkX != null) ret.add(Txt.parse(format, "cx", this.chunkX));
if (this.chunkZ != null) ret.add(Txt.parse(format, "cz", this.chunkZ));
if (this.pitch != null) ret.add(Txt.parse(format, "p", twoDForm.format(this.pitch)));
if (this.yaw != null) ret.add(Txt.parse(format, "y", twoDForm.format(this.yaw)));
if (this.velocityX != null) ret.add(Txt.parse(format, "vx", twoDForm.format(this.velocityX)));
if (this.velocityY != null) ret.add(Txt.parse(format, "vy", twoDForm.format(this.velocityY)));
if (this.velocityZ != null) ret.add(Txt.parse(format, "vz", twoDForm.format(this.velocityZ)));
return Txt.implode(ret, "").trim();
}
//----------------------------------------------//
// CLONE
//----------------------------------------------//
@Override
public PS clone()
{
return new PS(this);
}
//----------------------------------------------//
// STATIC COMPARISON TOOLS
//----------------------------------------------//
public static Double locationDistanceSquared(PS one, PS two)
{
if (one == null) return null;
if (two == null) return null;
String w1 = one.getWorldName();
String w2 = two.getWorldName();
if (!MUtil.equals(w1, w2)) return null;
Double x1 = one.calcLocationX();
if (x1 == null) return null;
Double y1 = one.calcLocationY();
if (y1 == null) return null;
Double z1 = one.calcLocationZ();
if (z1 == null) return null;
Double x2 = two.calcLocationX();
if (x2 == null) return null;
Double y2 = two.calcLocationY();
if (y2 == null) return null;
Double z2 = two.calcLocationZ();
if (z2 == null) return null;
return Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2) + Math.pow(z1 - z2, 2);
}
public static Double locationDistance(PS one, PS two)
{
Double ret = locationDistanceSquared(one, two);
if (ret == null) return null;
return Math.sqrt(ret);
}
public static boolean inSameWorld(PS one, PS two)
{
if (one == null) return false;
if (two == null) return false;
String w1 = one.getWorldName();
String w2 = two.getWorldName();
if (w1 == null) return false;
if (w2 == null) return false;
return w1.equalsIgnoreCase(w2);
}
public static boolean inSameUniverse(PS one, PS two, Multiverse multiverse)
{
if (one == null) return false;
if (two == null) return false;
String w1 = one.getWorldName();
String w2 = two.getWorldName();
if (w1 == null) return false;
if (w2 == null) return false;
String m1 = multiverse.getUniverseForWorldName(w1);
String m2 = multiverse.getUniverseForWorldName(w2);
return m1.equalsIgnoreCase(m2);
}
public static boolean inSameUniverse(PS one, PS two, Aspect aspect)
{
return inSameUniverse(one, two, aspect.multiverse());
}
}

View File

@@ -0,0 +1,44 @@
package com.massivecraft.mcore;
import org.bukkit.permissions.Permissible;
import com.massivecraft.mcore.util.PermUtil;
public enum Permission
{
CMD_USYS("cmd.usys"),
CMD_USYS_MULTIVERSE("cmd.usys.multiverse"),
CMD_USYS_MULTIVERSE_LIST("cmd.usys.multiverse.list"),
CMD_USYS_MULTIVERSE_SHOW("cmd.usys.multiverse.show"),
CMD_USYS_MULTIVERSE_NEW("cmd.usys.multiverse.new"),
CMD_USYS_MULTIVERSE_DEL("cmd.usys.multiverse.del"),
CMD_USYS_UNIVERSE("cmd.usys.universe"),
CMD_USYS_UNIVERSE_NEW("cmd.usys.universe.new"),
CMD_USYS_UNIVERSE_DEL("cmd.usys.universe.del"),
CMD_USYS_UNIVERSE_CLEAR("cmd.usys.universe.clear"),
CMD_USYS_WORLD("cmd.usys.world"),
CMD_USYS_ASPECT("cmd.usys.aspect"),
CMD_USYS_ASPECT_LIST("cmd.usys.aspect.list"),
CMD_USYS_ASPECT_SHOW("cmd.usys.aspect.show"),
CMD_USYS_ASPECT_USE("cmd.usys.aspect.use"),
CMD_MCORE("cmd.mcore"),
NOTPDELAY("notpdelay"),
;
public final String node;
Permission(final String permissionNode)
{
this.node = "mcore."+permissionNode;
}
public boolean has(Permissible permissible, boolean informSenderIfNot)
{
return PermUtil.has(permissible, this.node, informSenderIfNot);
}
public boolean has(Permissible permissible)
{
return has(permissible, false);
}
}

View File

@@ -0,0 +1,6 @@
package com.massivecraft.mcore;
public interface Predictate<T>
{
public boolean apply(T type);
}

View File

@@ -0,0 +1,6 @@
package com.massivecraft.mcore;
public interface Prioritized
{
public int getPriority();
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore;
import java.util.Comparator;
public class PriorityComparator implements Comparator<Prioritized>
{
@Override
public int compare(Prioritized one, Prioritized two)
{
if (one == null && two == null) return 0;
if (two == null) return 1;
if (one == null) return -1;
return Integer.valueOf(one.getPriority()).compareTo(two.getPriority());
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static PriorityComparator i = new PriorityComparator();
public static PriorityComparator get() { return i; }
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore;
import java.util.Comparator;
public class ReversePriorityComparator implements Comparator<Prioritized>
{
@Override
public int compare(Prioritized one, Prioritized two)
{
if (one == null && two == null) return 0;
if (two == null) return -1;
if (one == null) return 1;
return Integer.valueOf(two.getPriority()).compareTo(one.getPriority());
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ReversePriorityComparator i = new ReversePriorityComparator();
public static ReversePriorityComparator get() { return i; }
}

View File

@@ -0,0 +1,81 @@
package com.massivecraft.mcore;
import java.io.File;
import com.massivecraft.mcore.store.accessor.Accessor;
import com.massivecraft.mcore.util.DiscUtil;
public class SimpleConfig
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
protected transient MPlugin mplugin;
protected MPlugin getMplugin() { return this.mplugin; }
protected transient File file;
protected File getFile() { return this.file; }
public SimpleConfig(MPlugin mplugin, File file)
{
this.mplugin = mplugin;
this.file = file;
}
public SimpleConfig(MPlugin mplugin, String confname)
{
this(mplugin, new File(mplugin.getDataFolder(), confname+".json"));
}
public SimpleConfig(MPlugin mplugin)
{
this(mplugin, "conf");
}
// -------------------------------------------- //
// IO
// -------------------------------------------- //
protected static boolean contentRequestsDefaults(String content)
{
if (content == null) return false;
char c = content.charAt(0);
return c == 'd' || c == 'D';
}
public void load()
{
if (this.getFile().isFile())
{
String content = DiscUtil.readCatch(this.getFile());
Object toShallowLoad = null;
if (contentRequestsDefaults(content))
{
try
{
toShallowLoad = this.getClass().newInstance();
}
catch (Exception e)
{
e.printStackTrace();
return;
}
}
else
{
toShallowLoad = this.getMplugin().gson.fromJson(content, this.getClass());
}
Accessor.get(this.getClass()).copy(toShallowLoad, this);
}
save();
}
public void save()
{
String content = DiscUtil.readCatch(this.getFile());
if (contentRequestsDefaults(content)) return;
content = this.getMplugin().gson.toJson(this);
DiscUtil.writeCatch(file, content);
}
}

View File

@@ -0,0 +1,145 @@
package com.massivecraft.mcore.adapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.FireworkEffect.Type;
import com.massivecraft.mcore.util.MUtil;
import com.massivecraft.mcore.xlib.gson.JsonArray;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonObject;
import com.massivecraft.mcore.xlib.gson.JsonPrimitive;
public class FireworkEffectAdapter
{
// -------------------------------------------- //
// FIELD CONSTANTS
// -------------------------------------------- //
public static final String FLICKER = "flicker";
public static final String TRAIL = "trail";
public static final String COLORS = "colors";
public static final String FADE_COLORS = "fade-colors";
public static final String TYPE = "type";
public static final boolean FLICKER_DEFAULT = false;
public static final boolean TRAIL_DEFAULT = false;
public static final List<Color> COLORS_DEFAULT = Collections.unmodifiableList(MUtil.list(Color.GREEN));
public static final List<Color> FADE_COLORS_DEFAULT = Collections.unmodifiableList(new ArrayList<Color>());
public static final Type TYPE_DEFAULT = Type.BALL_LARGE;
// -------------------------------------------- //
// TO JSON
// -------------------------------------------- //
public static JsonObject toJson(FireworkEffect fireworkEffect)
{
if (fireworkEffect == null) return null;
JsonObject ret = new JsonObject();
ret.addProperty(FLICKER, fireworkEffect.hasFlicker());
ret.addProperty(TRAIL, fireworkEffect.hasTrail());
ret.add(COLORS, fromColorCollection(fireworkEffect.getColors()));
ret.add(FADE_COLORS, fromColorCollection(fireworkEffect.getFadeColors()));
ret.addProperty(TYPE, fireworkEffect.getType().name());
return ret;
}
// -------------------------------------------- //
// FROM JSON
// -------------------------------------------- //
public static FireworkEffect fromJson(JsonElement jsonElement)
{
if (jsonElement == null) return null;
if ( ! jsonElement.isJsonObject()) return null;
JsonObject json = jsonElement.getAsJsonObject();
boolean flicker = FLICKER_DEFAULT;
boolean trail = TRAIL_DEFAULT;
List<Color> colors = COLORS_DEFAULT;
List<Color> fadeColors = FADE_COLORS_DEFAULT;
Type type = TYPE_DEFAULT;
JsonElement element;
element = json.get(FLICKER);
if (element != null)
{
flicker = element.getAsBoolean();
}
element = json.get(TRAIL);
if (element != null)
{
trail = element.getAsBoolean();
}
element = json.get(COLORS);
if (element != null)
{
colors = toColorCollection(element);
}
element = json.get(FADE_COLORS);
if (element != null)
{
fadeColors = toColorCollection(element);
}
element = json.get(TYPE);
if (element != null)
{
type = Type.valueOf(element.getAsString());
}
FireworkEffect ret = FireworkEffect.builder()
.flicker(flicker)
.trail(trail)
.withColor(colors)
.withFade(fadeColors)
.with(type)
.build();
return ret;
}
// -------------------------------------------- //
// MINI UTILS
// -------------------------------------------- //
public static JsonArray fromColorCollection(Collection<Color> colors)
{
JsonArray ret = new JsonArray();
for (Color color : colors)
{
ret.add(new JsonPrimitive(color.asRGB()));
}
return ret;
}
public static List<Color> toColorCollection(JsonElement json)
{
JsonArray array = json.getAsJsonArray();
List<Color> ret = new ArrayList<Color>();
Iterator<JsonElement> iter = array.iterator();
while (iter.hasNext())
{
JsonElement element = iter.next();
ret.add(Color.fromRGB(element.getAsInt()));
}
return ret;
}
}

View File

@@ -0,0 +1,113 @@
package com.massivecraft.mcore.adapter;
import java.lang.reflect.Type;
import org.bukkit.craftbukkit.v1_4_R1.inventory.CraftInventoryCustom;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.massivecraft.mcore.MCore;
import com.massivecraft.mcore.xlib.gson.JsonDeserializationContext;
import com.massivecraft.mcore.xlib.gson.JsonDeserializer;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonObject;
import com.massivecraft.mcore.xlib.gson.JsonParseException;
import com.massivecraft.mcore.xlib.gson.JsonPrimitive;
import com.massivecraft.mcore.xlib.gson.JsonSerializationContext;
import com.massivecraft.mcore.xlib.gson.JsonSerializer;
public class InventoryAdapter implements JsonDeserializer<Inventory>, JsonSerializer<Inventory>
{
// -------------------------------------------- //
// FIELD NAME CONSTANTS
// -------------------------------------------- //
public static final String SIZE = "size";
// -------------------------------------------- //
// IMPLEMENTATION
// -------------------------------------------- //
@Override
public JsonElement serialize(Inventory src, Type typeOfSrc, JsonSerializationContext context)
{
return toJson(src);
}
@Override
public Inventory deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
return fromJson(json);
}
// -------------------------------------------- //
// JSON
// -------------------------------------------- //
public static JsonElement toJson(Inventory src)
{
JsonObject jsonInventory = new JsonObject();
ItemStack[] itemStacks = src.getContents();
jsonInventory.add(SIZE, new JsonPrimitive(itemStacks.length));
for (int i = 0; i < itemStacks.length; i++)
{
ItemStack itemStack = itemStacks[i];
JsonElement jsonItemStack = MCore.gson.toJsonTree(itemStack, ItemStack.class);
if (jsonItemStack == null) continue;
jsonInventory.add(String.valueOf(i), jsonItemStack);
}
return jsonInventory;
}
public static Inventory fromJson(JsonElement json)
{
if ( ! json.isJsonObject()) return null;
JsonObject jsonInventory = json.getAsJsonObject();
if ( ! jsonInventory.has(SIZE)) return null;
int size = jsonInventory.get(SIZE).getAsInt();
ItemStack[] itemStacks = new ItemStack[size];
for (int i = 0; i < size; i++)
{
// Fetch the jsonItemStack or mark it as empty and continue
String stackIdx = String.valueOf(i);
JsonElement jsonItemStack = jsonInventory.get(stackIdx);
ItemStack itemStack = MCore.gson.fromJson(jsonItemStack, ItemStack.class);
itemStacks[i] = itemStack;
}
Inventory ret = new CraftInventoryCustom(null, size, "items");
ret.setContents(itemStacks);
return ret;
}
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
// This utility is nice to have in many cases :)
public static boolean isInventoryEmpty(Inventory inv)
{
if (inv == null) return true;
for (ItemStack stack : inv.getContents())
{
if (stack == null) continue;
if (stack.getAmount() == 0) continue;
if (stack.getTypeId() == 0) continue;
return false;
}
return true;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
public static InventoryAdapter i = new InventoryAdapter();
public static InventoryAdapter get() { return i; }
}

View File

@@ -0,0 +1,66 @@
package com.massivecraft.mcore.adapter;
import java.lang.reflect.Type;
import org.bukkit.inventory.ItemStack;
import com.massivecraft.mcore.xlib.gson.JsonDeserializationContext;
import com.massivecraft.mcore.xlib.gson.JsonDeserializer;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonObject;
import com.massivecraft.mcore.xlib.gson.JsonParseException;
import com.massivecraft.mcore.xlib.gson.JsonSerializationContext;
import com.massivecraft.mcore.xlib.gson.JsonSerializer;
public class ItemStackAdapter implements JsonDeserializer<ItemStack>, JsonSerializer<ItemStack>
{
// -------------------------------------------- //
// IMPLEMENTATION
// -------------------------------------------- //
@Override
public JsonElement serialize(ItemStack itemStack, Type typeOfSrc, JsonSerializationContext context)
{
// We always use the latest version when we serialize.
return ItemStackAdapterV2.erialize(itemStack);
}
@Override
public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
// We need to decide what version to use when we deserialize.
JsonDeserializer<ItemStack> deserializer = pickItemStackDeserializer(json);
return deserializer.deserialize(json, typeOfT, context);
}
// -------------------------------------------- //
// PICK ITEM STACK ADAPTER
// -------------------------------------------- //
protected static JsonDeserializer<ItemStack> pickItemStackDeserializer(JsonElement jsonElement)
{
JsonDeserializer<ItemStack> ret = ItemStackAdapterV2.get();
// Check for "nothing"
if (jsonElement == null) return ret;
// Must be a JsonObject
if (jsonElement.isJsonObject() == false) return ret;
JsonObject json = jsonElement.getAsJsonObject();
// Is it V1?
if (json.has(ItemStackAdapterV1.TYPE))
{
ret = ItemStackAdapterV1.get();
}
return ret;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
public static ItemStackAdapter i = new ItemStackAdapter();
public static ItemStackAdapter get() { return i; }
}

View File

@@ -0,0 +1,214 @@
package com.massivecraft.mcore.adapter;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Map.Entry;
import net.minecraft.server.v1_4_R1.NBTBase;
import net.minecraft.server.v1_4_R1.NBTTagCompound;
import org.bukkit.craftbukkit.v1_4_R1.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import com.massivecraft.mcore.xlib.gson.JsonDeserializationContext;
import com.massivecraft.mcore.xlib.gson.JsonDeserializer;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonObject;
import com.massivecraft.mcore.xlib.gson.JsonParseException;
import com.massivecraft.mcore.xlib.gson.JsonSerializationContext;
import com.massivecraft.mcore.xlib.gson.JsonSerializer;
// TODO: This adapter is deprecated as of 2012-12-20. It should be removed in some time.
public class ItemStackAdapterV1 implements JsonDeserializer<ItemStack>, JsonSerializer<ItemStack>
{
// -------------------------------------------- //
// FIELD NAME CONSTANTS
// -------------------------------------------- //
public static final String TYPE = "type";
public static final String AMOUNT = "amount";
public static final String DAMAGE = "damage";
public static final String ENCHANTMENTS = "enchantments";
public static final String TAG = "tag";
// -------------------------------------------- //
// IMPLEMENTATION
// -------------------------------------------- //
@Override
public JsonElement serialize(ItemStack itemStack, Type typeOfSrc, JsonSerializationContext context)
{
return toJson(itemStack);
}
@Override
public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
return fromJson(json);
}
// -------------------------------------------- //
// JSON
// -------------------------------------------- //
public static JsonObject toJson(ItemStack stack)
{
// Check for "nothing"
if (stack == null || stack.getTypeId() == 0 || stack.getAmount() == 0)
{
return null;
}
JsonObject jsonItemStack = new JsonObject();
// Add type id
jsonItemStack.addProperty(TYPE, stack.getTypeId());
// Add amount
if (stack.getAmount() != 1)
{
jsonItemStack.addProperty(AMOUNT, stack.getAmount());
}
// Add damage
if (stack.getDurability() != 0) // Durability is a weird name since it is the amount of damage.
{
jsonItemStack.addProperty(DAMAGE, stack.getDurability());
}
// Add enchantments
if (stack.getEnchantments().size() > 0)
{
JsonObject jsonEnchantments = new JsonObject();
for (Entry<Enchantment, Integer> entry : stack.getEnchantments().entrySet())
{
jsonEnchantments.addProperty(String.valueOf(entry.getKey().getId()), entry.getValue());
}
jsonItemStack.add(ItemStackAdapterV1.ENCHANTMENTS, jsonEnchantments);
}
// Add the tag if there is one
JsonObject tag = getEnchFreeGsonTagFromItemStack(stack);
if (tag != null)
{
jsonItemStack.add(TAG, tag);
}
return jsonItemStack;
}
// Used by method toJson
public static JsonObject getEnchFreeGsonTagFromItemStack(ItemStack stack)
{
if (!(stack instanceof CraftItemStack)) return null;
CraftItemStack craftItemStack = (CraftItemStack)stack;
NBTTagCompound nbt = getHandle(craftItemStack).tag;
if (nbt == null) return null;
JsonObject gsonbt = (JsonObject) NbtGsonConverter.nbtToGsonVal(nbt);
gsonbt.remove("ench");
if (gsonbt.entrySet().size() == 0) return null;
return gsonbt;
}
public static ItemStack fromJson(JsonElement json)
{
// Check for "nothing"
if (json == null || ! json.isJsonObject()) return null;
JsonObject jsonItemStack = json.getAsJsonObject();
// Populate values
int type = 0;
int amount = 1;
short damage = 0;
if (jsonItemStack.has(TYPE))
{
type = jsonItemStack.get(TYPE).getAsInt();
}
if (jsonItemStack.has(AMOUNT))
{
amount = jsonItemStack.get(AMOUNT).getAsInt();
}
if (jsonItemStack.has(DAMAGE))
{
damage = jsonItemStack.get(DAMAGE).getAsShort();
}
// Create Non enchanted stack
ItemStack stack = new ItemStack(type, amount, damage);
// Add tag
if (jsonItemStack.has(TAG))
{
JsonObject jsonbt = jsonItemStack.get(TAG).getAsJsonObject();
CraftItemStack craftItemStack = CraftItemStack.asCraftCopy(stack);
stack = craftItemStack;
NBTBase nbt = NbtGsonConverter.gsonValToNbt(jsonbt, null, NBType.COMPOUND, NBType.UNKNOWN);
getHandle(craftItemStack).tag = (NBTTagCompound) nbt;
}
// Add enchantments if there are any
if (jsonItemStack.has(ENCHANTMENTS))
{
JsonObject jsonEnchantments = jsonItemStack.get(ENCHANTMENTS).getAsJsonObject();
for (Entry<String, JsonElement> enchantmentEntry: jsonEnchantments.entrySet())
{
int enchantmentId = Integer.valueOf(enchantmentEntry.getKey());
Integer enchantmentLevel = Integer.valueOf(enchantmentEntry.getValue().getAsString());
stack.addUnsafeEnchantment(Enchantment.getById(enchantmentId), enchantmentLevel);
}
}
return stack;
}
// -------------------------------------------- //
// GET HANDLE
// -------------------------------------------- //
public static Field fieldCraftItemStackDotHandle = null;
static
{
try
{
fieldCraftItemStackDotHandle = CraftItemStack.class.getDeclaredField("handle");
fieldCraftItemStackDotHandle.setAccessible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static net.minecraft.server.v1_4_R1.ItemStack getHandle(CraftItemStack craftItemStack)
{
try
{
return (net.minecraft.server.v1_4_R1.ItemStack) fieldCraftItemStackDotHandle.get(craftItemStack);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
public static ItemStackAdapterV1 i = new ItemStackAdapterV1();
public static ItemStackAdapterV1 get() { return i; }
}

View File

@@ -0,0 +1,744 @@
package com.massivecraft.mcore.adapter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.FireworkEffectMeta;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.MapMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.inventory.meta.Repairable;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.potion.PotionEffect;
import com.massivecraft.mcore.xlib.gson.JsonArray;
import com.massivecraft.mcore.xlib.gson.JsonDeserializationContext;
import com.massivecraft.mcore.xlib.gson.JsonDeserializer;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonObject;
import com.massivecraft.mcore.xlib.gson.JsonParseException;
import com.massivecraft.mcore.xlib.gson.JsonPrimitive;
import com.massivecraft.mcore.xlib.gson.JsonSerializationContext;
import com.massivecraft.mcore.xlib.gson.JsonSerializer;
/**
* This is a GSON serializer/deserializer for the Bukkit ItemStack. Why not use
* the built in Bukkit serializer/deserializer? I would have loved to do that :)
* but sadly that one is YAML centric and cannot be used with json in a good
* way. This serializer requires manual updating to work but produces clean
* json. See the file itemstackformat.txt for more info.
*/
public class ItemStackAdapterV2 implements JsonDeserializer<ItemStack>, JsonSerializer<ItemStack>
{
// -------------------------------------------- //
// FIELD NAME CONSTANTS
// -------------------------------------------- //
public static final String ID = "id";
public static final String COUNT = "count";
public static final String DAMAGE = "damage";
public static final String NAME = "name";
public static final String LORE = "lore";
public static final String ENCHANTS = "enchants";
public static final String REPAIRCOST = "repaircost";
public static final String BOOK_TITLE = "title";
public static final String BOOK_AUTHOR = "author";
public static final String BOOK_PAGES = "pages";
public static final String LEATHER_ARMOR_COLOR = "color";
public static final String MAP_SCALING = "scaling";
public static final String SKULL_OWNER = "skull";
// We renamed "effects" to "potion-effects".
public static final String POTION_EFFECTS_OLD = "effects";
public static final String POTION_EFFECTS = "potion-effects";
public static final String FIREWORK_EFFECT = "firework-effect";
public static final String FIREWORK_EFFECTS = "firework-effects";
public static final String FIREWORK_FLIGHT = "firework-flight";
public static final String STORED_ENCHANTS = "stored-enchants";
// -------------------------------------------- //
// OTHER CONSTANTS
// -------------------------------------------- //
public static final int DEFAULT_ID;
public static final int DEFAULT_COUNT;
public static final int DEFAULT_DAMAGE;
static
{
ItemStack stack = createItemStack();
DEFAULT_ID = stack.getTypeId();
DEFAULT_COUNT = stack.getAmount();
DEFAULT_DAMAGE = stack.getDurability();
}
// -------------------------------------------- //
// GSON INTERFACE IMPLEMENTATION
// -------------------------------------------- //
@Override
public JsonElement serialize(ItemStack src, Type typeOfSrc, JsonSerializationContext context)
{
return erialize(src);
}
@Override
public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
return erialize(json);
}
// -------------------------------------------- //
// WRITE
// -------------------------------------------- //
public static JsonObject erialize(ItemStack stack)
{
// Check for "nothing"
if (stack == null) return null;
if (stack.getTypeId() == 0) return null;
if (stack.getAmount() == 0) return null;
// Create a new JsonObject
JsonObject json = new JsonObject();
// Transfer data from stack to json
transferAll(stack, json, true);
return json;
}
public static ItemStack erialize(JsonElement jsonElement)
{
// Check for "nothing"
if (jsonElement == null) return null;
// Must be a JsonObject
if (jsonElement.isJsonObject() == false) return null;
JsonObject json = jsonElement.getAsJsonObject();
// Create a new ItemStack
ItemStack stack = createItemStack();
// Transfer data from json to stack
transferAll(stack, json, false);
return stack;
}
// -------------------------------------------- //
// NOARG STACK CONSTRUCTOR
// -------------------------------------------- //
public static ItemStack createItemStack()
{
return new ItemStack(0);
}
// -------------------------------------------- //
// ALL
// -------------------------------------------- //
public static void transferAll(ItemStack stack, JsonObject json, boolean stack2json)
{
transferBasic(stack, json, stack2json);
ItemMeta meta = stack.getItemMeta();
transferMeta(meta, json, stack2json);
if (stack2json == false)
{
stack.setItemMeta(meta);
}
}
// -------------------------------------------- //
// BASIC
// -------------------------------------------- //
public static void transferBasic(ItemStack stack, JsonObject json, boolean stack2json)
{
transferId(stack, json, stack2json);
transferCount(stack, json, stack2json);
transferDamage(stack, json, stack2json);
}
// -------------------------------------------- //
// BASIC: ID
// -------------------------------------------- //
public static void transferId(ItemStack stack, JsonObject json,
boolean stack2json)
{
if (stack2json)
{
int id = stack.getTypeId();
if (id == DEFAULT_ID) return;
json.addProperty(ID, id);
}
else
{
JsonElement element = json.get(ID);
if (element == null) return;
stack.setTypeId(element.getAsInt());
}
}
// -------------------------------------------- //
// BASIC: COUNT
// -------------------------------------------- //
public static void transferCount(ItemStack stack, JsonObject json, boolean stack2json)
{
if (stack2json)
{
int count = stack.getAmount();
if (count == DEFAULT_COUNT) return;
json.addProperty(COUNT, count);
}
else
{
JsonElement element = json.get(COUNT);
if (element == null) return;
stack.setAmount(element.getAsInt());
}
}
// -------------------------------------------- //
// BASIC: DAMAGE
// -------------------------------------------- //
public static void transferDamage(ItemStack stack, JsonObject json, boolean stack2json)
{
// Durability is a weird name since it is the amount of damage.
if (stack2json)
{
int damage = stack.getDurability();
if (damage == DEFAULT_DAMAGE) return;
json.addProperty(DAMAGE, damage);
}
else
{
JsonElement element = json.get(DAMAGE);
if (element == null) return;
stack.setDurability(element.getAsShort());
}
}
// -------------------------------------------- //
// META
// -------------------------------------------- //
public static void transferMeta(ItemMeta meta, JsonObject json, boolean meta2json)
{
transferUnspecificMeta(meta, json, meta2json);
transferSpecificMeta(meta, json, meta2json);
}
// -------------------------------------------- //
// UNSPECIFIC META
// -------------------------------------------- //
public static void transferUnspecificMeta(ItemMeta meta, JsonObject json, boolean meta2json)
{
transferName(meta, json, meta2json);
transferLore(meta, json, meta2json);
transferEnchants(meta, json, meta2json);
transferRepaircost(meta, json, meta2json);
}
// -------------------------------------------- //
// UNSPECIFIC META: NAME
// -------------------------------------------- //
public static void transferName(ItemMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasDisplayName()) return;
json.addProperty(NAME, meta.getDisplayName());
}
else
{
JsonElement element = json.get(NAME);
if (element == null) return;
meta.setDisplayName(element.getAsString());
}
}
// -------------------------------------------- //
// UNSPECIFIC META: LORE
// -------------------------------------------- //
public static void transferLore(ItemMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasLore()) return;
json.add(LORE, convertStringList(meta.getLore()));
}
else
{
JsonElement element = json.get(LORE);
if (element == null) return;
meta.setLore(convertStringList(element));
}
}
// -------------------------------------------- //
// UNSPECIFIC META: ENCHANTS
// -------------------------------------------- //
public static void transferEnchants(ItemMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasEnchants()) return;
json.add(ENCHANTS, convertEnchantLevelMap(meta.getEnchants()));
}
else
{
JsonElement element = json.get(ENCHANTS);
if (element == null) return;
for (Entry<Enchantment, Integer> entry : convertEnchantLevelMap(element).entrySet())
{
meta.addEnchant(entry.getKey(), entry.getValue(), true);
}
}
}
// -------------------------------------------- //
// UNSPECIFIC META: REPAIRCOST
// -------------------------------------------- //
public static void transferRepaircost(ItemMeta meta, JsonObject json, boolean meta2json)
{
if (!(meta instanceof Repairable)) return;
Repairable repairable = (Repairable) meta;
if (meta2json)
{
if (!repairable.hasRepairCost()) return;
json.addProperty(REPAIRCOST, repairable.getRepairCost());
}
else
{
JsonElement element = json.get(REPAIRCOST);
if (element == null) return;
repairable.setRepairCost(element.getAsInt());
}
}
// -------------------------------------------- //
// SPECIFIC META
// -------------------------------------------- //
public static void transferSpecificMeta(ItemMeta meta, JsonObject json, boolean meta2json)
{
if (meta instanceof BookMeta)
{
transferBookMeta((BookMeta) meta, json, meta2json);
}
else if (meta instanceof LeatherArmorMeta)
{
transferLeatherArmorMeta((LeatherArmorMeta) meta, json, meta2json);
}
else if (meta instanceof MapMeta)
{
transferMapMeta((MapMeta) meta, json, meta2json);
}
else if (meta instanceof PotionMeta)
{
transferPotionMeta((PotionMeta) meta, json, meta2json);
}
else if (meta instanceof SkullMeta)
{
transferSkullMeta((SkullMeta) meta, json, meta2json);
}
else if (meta instanceof FireworkEffectMeta)
{
transferFireworkEffectMeta((FireworkEffectMeta) meta, json, meta2json);
}
else if (meta instanceof FireworkMeta)
{
transferFireworkMeta((FireworkMeta) meta, json, meta2json);
}
else if (meta instanceof EnchantmentStorageMeta)
{
transferEnchantmentStorageMeta((EnchantmentStorageMeta) meta, json, meta2json);
}
}
// -------------------------------------------- //
// SPECIFIC META: BOOK
// -------------------------------------------- //
public static void transferBookMeta(BookMeta meta, JsonObject json, boolean meta2json)
{
transferTitle(meta, json, meta2json);
transferAuthor(meta, json, meta2json);
transferPages(meta, json, meta2json);
}
public static void transferTitle(BookMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasTitle()) return;
json.addProperty(BOOK_TITLE, meta.getTitle());
}
else
{
JsonElement element = json.get(BOOK_TITLE);
if (element == null) return;
meta.setTitle(element.getAsString());
}
}
public static void transferAuthor(BookMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasTitle()) return;
json.addProperty(BOOK_AUTHOR, meta.getAuthor());
}
else
{
JsonElement element = json.get(BOOK_AUTHOR);
if (element == null) return;
meta.setAuthor(element.getAsString());
}
}
public static void transferPages(BookMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasTitle()) return;
json.add(BOOK_PAGES, convertStringList(meta.getPages()));
}
else
{
JsonElement element = json.get(BOOK_PAGES);
if (element == null) return;
meta.setPages(convertStringList(element));
}
}
// -------------------------------------------- //
// SPECIFIC META: LEATHER ARMOR
// -------------------------------------------- //
public static void transferLeatherArmorMeta(LeatherArmorMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
Color color = meta.getColor();
if (Bukkit.getItemFactory().getDefaultLeatherColor().equals(color)) return;
json.addProperty(LEATHER_ARMOR_COLOR, color.asRGB());
}
else
{
JsonElement element = json.get(LEATHER_ARMOR_COLOR);
if (element == null) return;
meta.setColor(Color.fromRGB(element.getAsInt()));
}
}
// -------------------------------------------- //
// SPECIFIC META: MAP
// -------------------------------------------- //
public static void transferMapMeta(MapMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.isScaling()) return;
json.addProperty(MAP_SCALING, true);
}
else
{
JsonElement element = json.get(MAP_SCALING);
if (element == null) return;
meta.setScaling(element.getAsBoolean());
}
}
// -------------------------------------------- //
// SPECIFIC META: POTION
// -------------------------------------------- //
public static void transferPotionMeta(PotionMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasCustomEffects()) return;
json.add(POTION_EFFECTS, convertPotionEffectList(meta.getCustomEffects()));
}
else
{
JsonElement element = json.get(POTION_EFFECTS);
if (element == null) element = json.get(POTION_EFFECTS_OLD);
if (element == null) return;
meta.clearCustomEffects();
for (PotionEffect pe : convertPotionEffectList(element))
{
meta.addCustomEffect(pe, false);
}
}
}
// -------------------------------------------- //
// SPECIFIC META: SKULL
// -------------------------------------------- //
public static void transferSkullMeta(SkullMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasOwner()) return;
json.addProperty(SKULL_OWNER, meta.getOwner());
}
else
{
JsonElement element = json.get(SKULL_OWNER);
if (element == null) return;
meta.setOwner(element.getAsString());
}
}
// -------------------------------------------- //
// SPECIFIC META: FIREWORK EFFECT
// -------------------------------------------- //
public static void transferFireworkEffectMeta(FireworkEffectMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasEffect()) return;
json.add(FIREWORK_EFFECT, FireworkEffectAdapter.toJson(meta.getEffect()));
}
else
{
JsonElement element = json.get(FIREWORK_EFFECT);
if (element == null) return;
meta.setEffect(FireworkEffectAdapter.fromJson(element));
}
}
// -------------------------------------------- //
// SPECIFIC META: FIREWORK
// -------------------------------------------- //
public static void transferFireworkMeta(FireworkMeta meta, JsonObject json, boolean meta2json)
{
transferFireworkMetaEffects(meta, json, meta2json);
transferFireworkMetaPower(meta, json, meta2json);
}
public static void transferFireworkMetaEffects(FireworkMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasEffects()) return;
json.add(FIREWORK_EFFECTS, convertFireworkEffectList(meta.getEffects()));
}
else
{
JsonElement element = json.get(FIREWORK_EFFECTS);
if (element == null) return;
meta.clearEffects();
meta.addEffects(convertFireworkEffectList(element));
}
}
public static void transferFireworkMetaPower(FireworkMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
json.addProperty(FIREWORK_FLIGHT, meta.getPower());
}
else
{
JsonElement element = json.get(FIREWORK_FLIGHT);
if (element == null) return;
meta.setPower(element.getAsInt());
}
}
// -------------------------------------------- //
// SPECIFIC META: ENCHANTMENT STORAGE
// -------------------------------------------- //
public static void transferEnchantmentStorageMeta(EnchantmentStorageMeta meta, JsonObject json, boolean meta2json)
{
if (meta2json)
{
if (!meta.hasStoredEnchants()) return;
json.add(STORED_ENCHANTS, convertEnchantLevelMap(meta.getStoredEnchants()));
}
else
{
JsonElement element = json.get(STORED_ENCHANTS);
if (element == null) return;
// TODO: Add a pull request to get rid of this entry set loop!
// TODO: A set, clear, remove all system is missing
for (Entry<Enchantment, Integer> entry : convertEnchantLevelMap(element).entrySet())
{
meta.addStoredEnchant(entry.getKey(), entry.getValue(), true);
}
}
}
// -------------------------------------------- //
// MINI UTILS
// -------------------------------------------- //
// String List
public static JsonArray convertStringList(Collection<String> strings)
{
JsonArray ret = new JsonArray();
for (String string : strings)
{
ret.add(new JsonPrimitive(string));
}
return ret;
}
public static List<String> convertStringList(JsonElement jsonElement)
{
JsonArray array = jsonElement.getAsJsonArray();
List<String> ret = new ArrayList<String>();
Iterator<JsonElement> iter = array.iterator();
while (iter.hasNext())
{
JsonElement element = iter.next();
ret.add(element.getAsString());
}
return ret;
}
// PotionEffect List
public static JsonArray convertPotionEffectList(Collection<PotionEffect> potionEffects)
{
JsonArray ret = new JsonArray();
for (PotionEffect e : potionEffects)
{
ret.add(PotionEffectAdapter.toJson(e));
}
return ret;
}
public static List<PotionEffect> convertPotionEffectList(JsonElement jsonElement)
{
if (jsonElement == null) return null;
if ( ! jsonElement.isJsonArray()) return null;
JsonArray array = jsonElement.getAsJsonArray();
List<PotionEffect> ret = new ArrayList<PotionEffect>();
Iterator<JsonElement> iter = array.iterator();
while(iter.hasNext())
{
PotionEffect e = PotionEffectAdapter.fromJson(iter.next());
if (e == null) continue;
ret.add(e);
}
return ret;
}
// FireworkEffect List
public static JsonArray convertFireworkEffectList(Collection<FireworkEffect> fireworkEffects)
{
JsonArray ret = new JsonArray();
for (FireworkEffect fe : fireworkEffects)
{
ret.add(FireworkEffectAdapter.toJson(fe));
}
return ret;
}
public static List<FireworkEffect> convertFireworkEffectList(JsonElement jsonElement)
{
if (jsonElement == null) return null;
if ( ! jsonElement.isJsonArray()) return null;
JsonArray array = jsonElement.getAsJsonArray();
List<FireworkEffect> ret = new ArrayList<FireworkEffect>();
Iterator<JsonElement> iter = array.iterator();
while(iter.hasNext())
{
FireworkEffect fe = FireworkEffectAdapter.fromJson(iter.next());
if (fe == null) continue;
ret.add(fe);
}
return ret;
}
// EnchantLevelMap
public static JsonObject convertEnchantLevelMap(Map<Enchantment, Integer> enchantLevelMap)
{
JsonObject ret = new JsonObject();
for (Entry<Enchantment, Integer> entry : enchantLevelMap.entrySet())
{
ret.addProperty(String.valueOf(entry.getKey().getId()), entry.getValue());
}
return ret;
}
public static Map<Enchantment, Integer> convertEnchantLevelMap(JsonElement jsonElement)
{
JsonObject json = jsonElement.getAsJsonObject();
Map<Enchantment, Integer> ret = new HashMap<Enchantment, Integer>();
for (Entry<String, JsonElement> entry : json.entrySet())
{
int id = Integer.valueOf(entry.getKey());
Enchantment ench = Enchantment.getById(id);
int lvl = entry.getValue().getAsInt();
ret.put(ench, lvl);
}
return ret;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
public static ItemStackAdapterV2 i = new ItemStackAdapterV2();
public static ItemStackAdapterV2 get() { return i; }
}

View File

@@ -0,0 +1,52 @@
package com.massivecraft.mcore.adapter;
import java.lang.reflect.Type;
import com.massivecraft.mcore.xlib.gson.JsonDeserializationContext;
import com.massivecraft.mcore.xlib.gson.JsonDeserializer;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonParseException;
import com.massivecraft.mcore.xlib.gson.JsonPrimitive;
import com.massivecraft.mcore.xlib.gson.JsonSerializationContext;
import com.massivecraft.mcore.xlib.gson.JsonSerializer;
import com.massivecraft.mcore.xlib.mongodb.MongoURI;
public class MongoURIAdapter implements JsonDeserializer<MongoURI>, JsonSerializer<MongoURI>
{
// -------------------------------------------- //
// IMPLEMENTATION
// -------------------------------------------- //
@Override
public JsonElement serialize(MongoURI mongoURI, Type typeOfSrc, JsonSerializationContext context)
{
return serialize(mongoURI);
}
@Override
public MongoURI deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
return deserialize(json);
}
// -------------------------------------------- //
// STATIC LOGIC
// -------------------------------------------- //
public static JsonElement serialize(MongoURI mongoURI)
{
return new JsonPrimitive(mongoURI.toString());
}
public static MongoURI deserialize(JsonElement json)
{
return new MongoURI(json.getAsString());
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
protected static MongoURIAdapter i = new MongoURIAdapter();
public static MongoURIAdapter get() { return i; }
}

View File

@@ -0,0 +1,93 @@
package com.massivecraft.mcore.adapter;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.server.v1_4_R1.NBTBase;
import lombok.Getter;
public enum NBType
{
// -------------------------------------------- //
// VALUES
// -------------------------------------------- //
END(0, "end"),
BYTE(1, "byte"),
SHORT(2, "short"),
INT(3, "int"),
LONG(4, "long"),
FLOAT(5, "float"),
DOUBLE(6, "double"),
BYTEARRAY(7, "bytearray"),
STRING(8, "string"),
LIST(9, "list"),
COMPOUND(10, "compound"),
INTARRAY(11, "intarray"),
UNKNOWN(-1, "unknown"),
;
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
@Getter final byte id;
@Getter final String name;
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
private NBType(int id, String name)
{
this.id = (byte)id;
this.name = name;
}
// -------------------------------------------- //
// STATIC UTILS
// -------------------------------------------- //
protected final static transient Map<String, NBType> tagnameToEnum = new HashMap<String, NBType>();
protected final static transient Map<Byte, NBType> byteToEnum = new HashMap<Byte, NBType>();
static
{
for (NBType value : values())
{
tagnameToEnum.put(value.getName(), value);
byteToEnum.put(value.getId(), value);
}
}
public static NBType getByName(String name)
{
NBType ret = tagnameToEnum.get(name);
if (ret == null)
{
ret = UNKNOWN;
}
return ret;
}
public static NBType getById(byte id)
{
NBType ret = byteToEnum.get(id);
if (ret == null)
{
ret = UNKNOWN;
}
return ret;
}
public static NBType getByTag(NBTBase tag)
{
NBType ret = byteToEnum.get(tag.getTypeId());
if (ret == null)
{
ret = UNKNOWN;
}
return ret;
}
}

View File

@@ -0,0 +1,333 @@
package com.massivecraft.mcore.adapter;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map.Entry;
import net.minecraft.server.v1_4_R1.NBTBase;
import net.minecraft.server.v1_4_R1.NBTTagByte;
import net.minecraft.server.v1_4_R1.NBTTagByteArray;
import net.minecraft.server.v1_4_R1.NBTTagCompound;
import net.minecraft.server.v1_4_R1.NBTTagDouble;
import net.minecraft.server.v1_4_R1.NBTTagEnd;
import net.minecraft.server.v1_4_R1.NBTTagFloat;
import net.minecraft.server.v1_4_R1.NBTTagInt;
import net.minecraft.server.v1_4_R1.NBTTagIntArray;
import net.minecraft.server.v1_4_R1.NBTTagList;
import net.minecraft.server.v1_4_R1.NBTTagLong;
import net.minecraft.server.v1_4_R1.NBTTagShort;
import net.minecraft.server.v1_4_R1.NBTTagString;
import com.massivecraft.mcore.xlib.gson.JsonArray;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonObject;
import com.massivecraft.mcore.xlib.gson.JsonPrimitive;
//TODO: This converter is deprecated as of 2012-12-20. It should be removed in some time.
public class NbtGsonConverter
{
// -------------------------------------------- //
// CONSTANTS
// -------------------------------------------- //
public final static String TYPE = "type";
public final static String ELEMTYPE = "elemtype";
public final static String VAL = "val";
public final static String NAME = "name";
// -------------------------------------------- //
// GSON TO NBT
// -------------------------------------------- //
public static NBTBase gsonToNbt(JsonElement jsonElement)
{
return gsonToNbt(jsonElement, null);
}
public static NBTBase gsonToNbt(JsonElement jsonElement, String name)
{
// Verify and cast the jsonElement into a jsonObject.
// We could have used jsonObject as parameter type but this method signature is more flexible.
if (!jsonElement.isJsonObject())
{
// must be a json object
return null;
}
JsonObject jsonObject = jsonElement.getAsJsonObject();
// Use the internal name if there is one
JsonElement nameElement = jsonObject.get(NAME);
if (nameElement != null)
{
name = nameElement.getAsString();
}
// Fetch the type-info
JsonElement typeElement = jsonObject.get(TYPE);
if (typeElement == null)
{
// must have a type
return null;
}
NBType type = NBType.getByName(typeElement.getAsString());
// Fetch the elemtype-info (used by NBTTagList only)
NBType elemtype = NBType.UNKNOWN;
if (type == NBType.LIST)
{
JsonElement elemtypeElement = jsonObject.get(ELEMTYPE);
if (elemtypeElement != null)
{
elemtype = NBType.getByName(elemtypeElement.getAsString());
}
}
// Fetch the value field
JsonElement val = jsonObject.get(VAL);
// Convert the value based on the info we gathered
return gsonValToNbt(val, name, type, elemtype);
}
public static NBTBase gsonValToNbt(JsonElement val, String name, NBType type, NBType elemtype)
{
NBTBase ret = null;
switch (type)
{
case END:
ret = new NBTTagEnd();
break;
case BYTE:
ret = new NBTTagByte(name, val.getAsByte());
break;
case SHORT:
ret = new NBTTagShort(name, val.getAsShort());
break;
case INT:
ret = new NBTTagInt(name, val.getAsInt());
break;
case LONG:
ret = new NBTTagLong(name, val.getAsLong());
break;
case FLOAT:
ret = new NBTTagFloat(name, val.getAsFloat());
break;
case DOUBLE:
ret = new NBTTagDouble(name, val.getAsDouble());
break;
case BYTEARRAY:
JsonArray jsonBytes = val.getAsJsonArray();
int jsonBytesSize = jsonBytes.size();
byte[] byteArray = new byte[jsonBytesSize];
for (int index = 0 ; index < jsonBytesSize ; index++)
{
byte b = jsonBytes.get(index).getAsByte();
byteArray[index] = b;
}
ret = new NBTTagByteArray(name, byteArray);
break;
case INTARRAY:
JsonArray jsonInts = val.getAsJsonArray();
int jsonIntsSize = jsonInts.size();
int[] intArray = new int[jsonIntsSize];
for (int index = 0 ; index < jsonIntsSize ; index++)
{
int i = jsonInts.get(index).getAsInt();
intArray[index] = i;
}
ret = new NBTTagIntArray(name, intArray);
break;
case STRING:
ret = new NBTTagString(name, val.getAsString());
break;
case LIST:
NBTTagList nbtlist = new NBTTagList(name);
if (!val.isJsonArray())
{
// must be an array
return null;
}
Iterator<JsonElement> iter = val.getAsJsonArray().iterator();
while (iter.hasNext())
{
nbtlist.add(gsonValToNbt(iter.next(), null, elemtype, NBType.UNKNOWN));
}
ret = nbtlist;
break;
case COMPOUND:
NBTTagCompound compound = new NBTTagCompound(name);
if (!val.isJsonObject())
{
// must be an object
return null;
}
JsonObject jsonCompound = val.getAsJsonObject();
for(Entry<String, JsonElement> entry : jsonCompound.entrySet())
{
String childName = entry.getKey();
JsonElement childJson = entry.getValue();
NBTBase child = gsonToNbt(childJson, childName);
if (child == null) continue;
compound.set(childName, child);
}
ret = compound;
break;
}
return ret;
}
// -------------------------------------------- //
// NBT TO GSON
// -------------------------------------------- //
public static JsonObject nbtToGson(NBTBase nbt, boolean includeName)
{
JsonObject ret = new JsonObject();
String name = nbt.getName();
if (includeName && name != null)
{
ret.addProperty(NAME, name);
}
NBType type = NBType.getById(nbt.getTypeId());
ret.addProperty(TYPE, type.getName());
if (type == NBType.LIST)
{
NBType elemtype = NBType.UNKNOWN;
NBTTagList nbtl = (NBTTagList)nbt;
if (nbtl.size() > 0)
{
elemtype = NBType.getByTag(nbtl.get(0));
}
ret.addProperty(ELEMTYPE, elemtype.getName());
}
JsonElement val = nbtToGsonVal(nbt);
if (val == null)
{
return null;
}
ret.add(VAL, val);
return ret;
}
public static JsonElement nbtToGsonVal(NBTBase nbt)
{
JsonElement val = null;
NBType type = NBType.getByTag(nbt);
switch (type)
{
case END:
// this should never happen
break;
case BYTE:
val = new JsonPrimitive(((NBTTagByte) nbt).data);
break;
case SHORT:
val = new JsonPrimitive(((NBTTagShort) nbt).data);
break;
case INT:
val = new JsonPrimitive(((NBTTagInt) nbt).data);
break;
case LONG:
val = new JsonPrimitive(((NBTTagLong) nbt).data);
break;
case FLOAT:
val = new JsonPrimitive(((NBTTagFloat) nbt).data);
break;
case DOUBLE:
val = new JsonPrimitive(((NBTTagDouble) nbt).data);
break;
case BYTEARRAY:
JsonArray jsonBytes = new JsonArray();
for (byte elem : ((NBTTagByteArray) nbt).data)
{
jsonBytes.add(new JsonPrimitive(elem));
}
val = jsonBytes;
break;
case INTARRAY:
JsonArray jsonInts = new JsonArray();
for (int elem : ((NBTTagIntArray) nbt).data)
{
jsonInts.add(new JsonPrimitive(elem));
}
val = jsonInts;
break;
case STRING:
val = new JsonPrimitive(((NBTTagString) nbt).data);
break;
case LIST:
NBTTagList nbtlist = (NBTTagList)nbt;
int size = nbtlist.size();
if (size <= 0)
{
// NBTTagList may not be empty
return null;
}
JsonArray jsonElems = new JsonArray();
for (int i = 0 ; i < size ; i++)
{
jsonElems.add(nbtToGsonVal(nbtlist.get(i)));
}
val = jsonElems;
break;
case COMPOUND:
JsonObject jsonObject = new JsonObject();
for (NBTBase child : getCompoundChildren((NBTTagCompound)nbt))
{
jsonObject.add(child.getName(), nbtToGson(child, false));
}
val = jsonObject;
break;
}
return val;
}
// -------------------------------------------- //
// UTILS
// -------------------------------------------- //
@SuppressWarnings("unchecked")
public static Collection<NBTBase> getCompoundChildren(NBTTagCompound compound)
{
return (Collection<NBTBase>)compound.c();
}
}

View File

@@ -0,0 +1,51 @@
package com.massivecraft.mcore.adapter;
import java.lang.reflect.Type;
import com.massivecraft.mcore.PS;
import com.massivecraft.mcore.xlib.gson.Gson;
import com.massivecraft.mcore.xlib.gson.JsonDeserializationContext;
import com.massivecraft.mcore.xlib.gson.JsonDeserializer;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonParseException;
import com.massivecraft.mcore.xlib.gson.JsonPrimitive;
import com.massivecraft.mcore.xlib.mongodb.MongoURI;
public class PSAdapter implements JsonDeserializer<PS>
{
// -------------------------------------------- //
// IMPLEMENTATION
// -------------------------------------------- //
@Override
public PS deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
if (json.isJsonPrimitive())
{
return new PS(json.getAsString());
}
return new Gson().fromJson(json, typeOfT);
}
// -------------------------------------------- //
// STATIC LOGIC
// -------------------------------------------- //
public static JsonElement serialize(MongoURI mongoURI)
{
return new JsonPrimitive(mongoURI.toString());
}
public static MongoURI deserialize(JsonElement json)
{
return new MongoURI(json.getAsString());
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
public static PSAdapter i = new PSAdapter();
public static PSAdapter get() { return i; }
}

View File

@@ -0,0 +1,73 @@
package com.massivecraft.mcore.adapter;
import java.lang.reflect.Type;
import com.massivecraft.mcore.xlib.gson.JsonDeserializationContext;
import com.massivecraft.mcore.xlib.gson.JsonDeserializer;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonNull;
import com.massivecraft.mcore.xlib.gson.JsonObject;
import com.massivecraft.mcore.xlib.gson.JsonParseException;
import com.massivecraft.mcore.xlib.gson.JsonPrimitive;
import com.massivecraft.mcore.xlib.gson.JsonSerializationContext;
import com.massivecraft.mcore.xlib.gson.JsonSerializer;
public class PolymorphicAdapter<T> implements JsonDeserializer<T>, JsonSerializer<T>
{
public static final String TYPE = "type";
public static final String VALUE = "value";
@Override
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context)
{
if (src == null)
{
return JsonNull.INSTANCE;
}
JsonObject ret = new JsonObject();
String type = src.getClass().getCanonicalName();
ret.addProperty(TYPE, type);
JsonElement value = context.serialize(src);
ret.add(VALUE, value);
return ret;
}
@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
if (!json.isJsonObject())
{
throw new JsonParseException("A polymorph must be an object.");
}
JsonObject jsonObject = json.getAsJsonObject();
if (!jsonObject.has(TYPE))
{
throw new JsonParseException("A polymorph must be have a \""+TYPE+"\" field.");
}
if (!jsonObject.has(VALUE))
{
throw new JsonParseException("A polymorph must be have a \"+VALUE+\" field.");
}
String type = ((JsonPrimitive)jsonObject.get(TYPE)).getAsString();
Class<?> typeClass = null;
try
{
typeClass = Class.forName(type);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
throw new JsonParseException(e.getMessage());
}
return context.deserialize(jsonObject.get(VALUE), typeClass);
}
}

View File

@@ -0,0 +1,78 @@
package com.massivecraft.mcore.adapter;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import com.massivecraft.mcore.xlib.gson.JsonElement;
import com.massivecraft.mcore.xlib.gson.JsonObject;
public class PotionEffectAdapter
{
// -------------------------------------------- //
// FIELD CONSTANTS
// -------------------------------------------- //
public static final String POTION_EFFECT_ID = "id";
public static final String POTION_DURATION = "duration";
public static final String POTION_AMPLIFIER = "amplifier";
public static final String POTION_AMBIENT = "ambient";
public static final int POTION_DURATION_DEFAULT = 20*3*60;
public static final int POTION_AMPLIFIER_DEFAULT = 0;
public static final boolean POTION_AMBIENT_DEFAULT = false;
// -------------------------------------------- //
// TO JSON
// -------------------------------------------- //
public static JsonObject toJson(PotionEffect potionEffect)
{
if (potionEffect == null) return null;
JsonObject ret = new JsonObject();
ret.addProperty(POTION_EFFECT_ID, potionEffect.getType().getId());
ret.addProperty(POTION_DURATION, potionEffect.getDuration());
ret.addProperty(POTION_AMPLIFIER, potionEffect.getAmplifier());
ret.addProperty(POTION_AMBIENT, potionEffect.isAmbient());
return ret;
}
// -------------------------------------------- //
// FROM JSON
// -------------------------------------------- //
public static PotionEffect fromJson(JsonElement jsonElement)
{
if (jsonElement == null) return null;
if ( ! jsonElement.isJsonObject()) return null;
JsonObject json = jsonElement.getAsJsonObject();
PotionEffectType pet = PotionEffectType.getById(json.get(POTION_EFFECT_ID).getAsInt());
int duration = POTION_DURATION_DEFAULT;
JsonElement durationElement = json.get(POTION_DURATION);
if (durationElement != null)
{
duration = durationElement.getAsInt();
}
int amplifier = POTION_AMPLIFIER_DEFAULT;
JsonElement amplifierElement = json.get(POTION_AMPLIFIER);
if (amplifierElement != null)
{
amplifier = amplifierElement.getAsInt();
}
boolean ambient = POTION_AMBIENT_DEFAULT;
JsonElement ambientElement = json.get(POTION_AMBIENT);
if (ambientElement != null)
{
ambient = ambientElement.getAsBoolean();
}
return new PotionEffect(pet, duration, amplifier, ambient);
}
}

View File

@@ -0,0 +1,56 @@
package com.massivecraft.mcore.cmd;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.MPlugin;
import com.massivecraft.mcore.mixin.Mixin;
import com.massivecraft.mcore.util.Txt;
public class BukkitGlueCommand extends Command
{
public final MCommand mcommand;
public final MPlugin mplugin;
public BukkitGlueCommand(String name, MCommand mcommand, MPlugin mplugin)
{
super(name, mcommand.getDesc(), mcommand.getUseageTemplate(), new ArrayList<String>());
this.mcommand = mcommand;
this.mplugin = mplugin;
}
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args)
{
if ( ! mplugin.isEnabled()) return false;
this.mcommand.execute(sender, Txt.tokenizeArguments(Txt.implode(args, " ")));
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException
{
List<String> superRet = super.tabComplete(sender, alias, args);
if (args.length == 0) return superRet;
Set<String> ret = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
ret.addAll(superRet);
String tokenlc = args[args.length - 1].toLowerCase();
// Add ids of all online senders that match and isn't added yet.
for (String senderId : Mixin.getOnlineSenderIds())
{
if (!senderId.toLowerCase().startsWith(tokenlc)) continue;
if (!Mixin.isVisible(sender, senderId)) continue;
ret.add(senderId);
}
return new ArrayList<String>(ret);
}
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.cmd;
import com.massivecraft.mcore.Conf;
import com.massivecraft.mcore.MCore;
import com.massivecraft.mcore.Permission;
import com.massivecraft.mcore.cmd.req.ReqHasPerm;
public class CmdMcore extends MCommand
{
public final static String MCORE = "mcore";
public CmdMcore()
{
this.addAliases(Conf.getCmdAliases(MCORE));
this.addRequirements(ReqHasPerm.get(Permission.CMD_MCORE.node));
}
@Override
public void perform()
{
this.msg("<i>You are running %s", MCore.p.getDescription().getFullName());
this.msg("<i>The id of this server is \"<h>%s<i>\".", Conf.serverid);
}
}

View File

@@ -0,0 +1,53 @@
package com.massivecraft.mcore.cmd;
import java.util.ArrayList;
import com.massivecraft.mcore.cmd.MCommand;
import com.massivecraft.mcore.cmd.arg.ARInteger;
import com.massivecraft.mcore.util.Txt;
public class HelpCommand extends MCommand
{
private HelpCommand()
{
super();
this.addAliases("?", "h", "help");
this.setDesc("");
this.addOptionalArg("page","1");
}
@Override
public void perform()
{
if (this.commandChain.size() == 0) return;
MCommand parentCommand = this.commandChain.get(this.commandChain.size()-1);
ArrayList<String> lines = new ArrayList<String>();
for (String helpline : parentCommand.getHelp())
{
lines.add(Txt.parse("<a>#<i> "+helpline));
}
for(MCommand subCommand : parentCommand.getSubCommands())
{
if (subCommand.visibleTo(sender))
{
lines.add(subCommand.getUseageTemplate(this.commandChain, true, true));
}
}
Integer pagenumber = this.arg(0, ARInteger.get(), 1);
if (pagenumber == null) return;
sendMessage(Txt.getPage(lines, pagenumber, "Help for command \""+parentCommand.getAliases().get(0)+"\"", sender));
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static HelpCommand i = new HelpCommand();
public static HelpCommand getInstance() { return i; }
public static HelpCommand get() { return i; }
}

View File

@@ -0,0 +1,485 @@
package com.massivecraft.mcore.cmd;
import java.util.*;
import java.util.Map.Entry;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.entity.Player;
import com.massivecraft.mcore.Lang;
import com.massivecraft.mcore.MCore;
import com.massivecraft.mcore.MPlugin;
import com.massivecraft.mcore.cmd.arg.ArgReader;
import com.massivecraft.mcore.cmd.arg.ArgResult;
import com.massivecraft.mcore.cmd.req.IReq;
import com.massivecraft.mcore.cmd.req.ReqHasPerm;
import com.massivecraft.mcore.mixin.Mixin;
import com.massivecraft.mcore.util.BukkitCommandUtil;
import com.massivecraft.mcore.util.PermUtil;
import com.massivecraft.mcore.util.Txt;
public abstract class MCommand
{
// -------------------------------------------- //
// COMMAND BEHAVIOR
// -------------------------------------------- //
// FIELD: subCommands
// The sub-commands to this command
@Getter @Setter protected List<MCommand> subCommands;
public void addSubCommand(MCommand subCommand)
{
subCommand.commandChain.addAll(this.commandChain);
subCommand.commandChain.add(this);
this.subCommands.add(subCommand);
}
// FIELD: aliases
// The different names this commands will react to
@Getter @Setter protected List<String> aliases;
public void addAliases(String... aliases) { this.aliases.addAll(Arrays.asList(aliases)); }
public void addAliases(List<String> aliases) { this.aliases.addAll(aliases); }
// FIELD: requiredArgs
// These args must always be sent
@Getter @Setter protected List<String> requiredArgs;
public void addRequiredArg(String arg) { this.requiredArgs.add(arg); }
// FIELD: optionalArgs
// These args are optional
@Getter @Setter protected Map<String, String> optionalArgs;
public void addOptionalArg(String arg, String def) { this.optionalArgs.put(arg, def); }
// FIELD: errorOnToManyArgs
// Should an error be thrown if "to many" args are sent.
protected boolean errorOnToManyArgs;
public boolean getErrorOnToManyArgs() { return this.errorOnToManyArgs; }
public void setErrorOnToManyArgs(boolean val) { this.errorOnToManyArgs = val; }
// FIELD: requirements
// All these requirements must be met for the command to be executable;
@Getter @Setter protected List<IReq> requirements;
public void addRequirements(IReq... requirements) { this.requirements.addAll(Arrays.asList(requirements)); }
// FIELD: desc
// This field may be left blank and will in such case be loaded from the permissions node instead.
// Thus make sure the permissions node description is an action description like "eat hamburgers" or "do admin stuff".
@Setter protected String desc = null;
public String getDesc()
{
if (this.desc != null) return this.desc;
String perm = this.getDescPermission();
if (perm != null)
{
String pdesc = PermUtil.getPermissionDescription(this.getDescPermission());
if (pdesc != null)
{
return pdesc;
}
}
return "*info unavailable*";
}
// FIELD: descPermission
// This permission node IS NOT TESTED AT ALL. It is rather used in the method above.
@Setter protected String descPermission;
public String getDescPermission()
{
if (this.descPermission != null) return this.descPermission;
// Otherwise we try to find one.
for (IReq req : this.requirements)
{
if ( ! (req instanceof ReqHasPerm)) continue;
return ((ReqHasPerm)req).getPerm();
}
return null;
}
// FIELD: help
// This is a multi-line help text for the command.
protected List<String> help = new ArrayList<String>();
public void setHelp(List<String> val) { this.help = val; }
public void setHelp(String... val) { this.help = Arrays.asList(val); }
public List<String> getHelp() { return this.help; }
// FIELD: visibilityMode
@Getter @Setter protected VisibilityMode visibilityMode;
// -------------------------------------------- //
// EXECUTION INFO
// -------------------------------------------- //
// FIELD: args
// Will contain the arguments, or and empty list if there are none.
@Getter @Setter protected List<String> args;
// FIELD: commandChain
// The command chain used to execute this command
@Getter @Setter protected List<MCommand> commandChain = new ArrayList<MCommand>();
// FIELDS: sender, me, senderIsConsole
public CommandSender sender;
public Player me;
public boolean senderIsConsole;
// -------------------------------------------- //
// BUKKIT INTEGRATION
// -------------------------------------------- //
public boolean register()
{
return register(MCore.p, false);
}
public boolean register(MPlugin mplugin)
{
return this.register(mplugin, false);
}
public boolean register(boolean override)
{
return this.register(MCore.p, override);
}
public boolean register(MPlugin mplugin, boolean override)
{
boolean ret = false;
SimpleCommandMap scm = BukkitCommandUtil.getBukkitCommandMap();
for (String alias : this.getAliases())
{
BukkitGlueCommand bgc = new BukkitGlueCommand(alias, this, mplugin);
if (override)
{
// Our commands are more important than your commands :P
Map<String, Command> knownCommands = BukkitCommandUtil.getKnownCommandsFromSimpleCommandMap(scm);
String lowerLabel = bgc.getName().trim().toLowerCase();
knownCommands.remove(lowerLabel);
}
if (scm.register(MCore.p.getDescription().getName(), bgc))
{
ret = true;
}
}
return ret;
}
// -------------------------------------------- //
// CONSTRUCTORS AND EXECUTOR
// -------------------------------------------- //
public MCommand()
{
this.descPermission = null;
this.subCommands = new ArrayList<MCommand>();
this.aliases = new ArrayList<String>();
this.requiredArgs = new ArrayList<String>();
this.optionalArgs = new LinkedHashMap<String, String>();
this.requirements = new ArrayList<IReq>();
this.errorOnToManyArgs = true;
this.desc = null;
this.visibilityMode = VisibilityMode.VISIBLE;
}
// The commandChain is a list of the parent command chain used to get to this command.
public void execute(CommandSender sender, List<String> args, List<MCommand> commandChain)
{
// Set the execution-time specific variables
this.sender = sender;
this.senderIsConsole = true;
this.me = null;
if (sender instanceof Player)
{
this.me = (Player) sender;
this.senderIsConsole = false;
}
this.fixSenderVars();
this.args = args;
this.commandChain = commandChain;
// Is there a matching sub command?
if (args.size() > 0 )
{
for (MCommand subCommand: this.subCommands)
{
if (subCommand.aliases.contains(args.get(0)))
{
args.remove(0);
commandChain.add(this);
subCommand.execute(sender, args, commandChain);
return;
}
}
}
if ( ! validCall(this.sender, this.args)) return;
perform();
}
public void fixSenderVars() {};
public void execute(CommandSender sender, List<String> args)
{
execute(sender, args, new ArrayList<MCommand>());
}
// This is where the command action is performed.
public abstract void perform();
// -------------------------------------------- //
// CALL VALIDATION
// -------------------------------------------- //
/**
* In this method we validate that all prerequisites to perform this command has been met.
*/
public boolean validCall(CommandSender sender, List<String> args)
{
if ( ! this.requirementsAreMet(sender, true))
{
return false;
}
if ( ! this.validArgs(args, sender))
{
return false;
}
return true;
}
public boolean visibleTo(CommandSender sender)
{
if (this.getVisibilityMode() == VisibilityMode.VISIBLE) return true;
if (this.getVisibilityMode() == VisibilityMode.INVISIBLE) return false;
return this.requirementsAreMet(sender, false);
}
public boolean requirementsAreMet(CommandSender sender, boolean informSenderIfNot)
{
for (IReq req : this.getRequirements())
{
if ( ! req.test(sender, this))
{
if (informSenderIfNot)
{
this.msg(req.createErrorMessage(sender, this));
}
return false;
}
}
return true;
}
public boolean validArgs(List<String> args, CommandSender sender)
{
if (args.size() < this.requiredArgs.size())
{
if (sender != null)
{
msg(Lang.commandToFewArgs);
sender.sendMessage(this.getUseageTemplate());
}
return false;
}
if (args.size() > this.requiredArgs.size() + this.optionalArgs.size() && this.errorOnToManyArgs)
{
if (sender != null)
{
// Get the to many string slice
List<String> theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size());
msg(Lang.commandToManyArgs, Txt.implodeCommaAndDot(theToMany, Txt.parse("<aqua>%s"), Txt.parse("<b>, "), Txt.parse("<b> and "), ""));
msg(Lang.commandToManyArgs2);
sender.sendMessage(this.getUseageTemplate());
}
return false;
}
return true;
}
public boolean validArgs(List<String> args)
{
return this.validArgs(args, null);
}
// -------------------------------------------- //
// HELP AND USAGE INFORMATION
// -------------------------------------------- //
public String getUseageTemplate(List<MCommand> commandChain, boolean addDesc, boolean onlyFirstAlias)
{
StringBuilder ret = new StringBuilder();
ret.append(Txt.parse("<c>"));
ret.append('/');
boolean first = true;
for (MCommand mc : commandChain)
{
if (first && onlyFirstAlias)
{
ret.append(mc.aliases.get(0));
}
else
{
ret.append(Txt.implode(mc.aliases, ","));
}
ret.append(' ');
first = false;
}
ret.append(Txt.implode(this.aliases, ","));
List<String> args = new ArrayList<String>();
for (String requiredArg : this.requiredArgs)
{
args.add("<"+requiredArg+">");
}
for (Entry<String, String> optionalArg : this.optionalArgs.entrySet())
{
String val = optionalArg.getValue();
if (val == null)
{
val = "";
}
else
{
val = "="+val;
}
args.add("["+optionalArg.getKey()+val+"]");
}
if (args.size() > 0)
{
ret.append(Txt.parse("<p>"));
ret.append(' ');
ret.append(Txt.implode(args, " "));
}
if (addDesc)
{
ret.append(' ');
ret.append(Txt.parse("<i>"));
ret.append(this.getDesc());
}
return ret.toString();
}
public String getUseageTemplate(List<MCommand> commandChain, boolean addDesc)
{
return getUseageTemplate(commandChain, addDesc, false);
}
public String getUseageTemplate(boolean addDesc)
{
return getUseageTemplate(this.commandChain, addDesc);
}
public String getUseageTemplate()
{
return getUseageTemplate(false);
}
// -------------------------------------------- //
// MESSAGE SENDING HELPERS
// -------------------------------------------- //
// CONVENIENCE SEND MESSAGE
public boolean sendMessage(String message)
{
return Mixin.message(this.sender, message);
}
public boolean sendMessage(String... messages)
{
return Mixin.message(this.sender, messages);
}
public boolean sendMessage(Collection<String> messages)
{
return Mixin.message(this.sender, messages);
}
// CONVENIENCE MSG
public boolean msg(String msg)
{
return Mixin.msg(this.sender, msg);
}
public boolean msg(String msg, Object... args)
{
return Mixin.msg(this.sender, msg, args);
}
public boolean msg(Collection<String> msgs)
{
return Mixin.msg(this.sender, msgs);
}
// -------------------------------------------- //
// ARGUMENT READERS
// -------------------------------------------- //
public String argConcatFrom(int idx)
{
if ( ! this.argIsSet(idx)) return null;
int from = idx;
int to = args.size();
if (to <= from) return "";
return Txt.implode(this.args.subList(from, to), " ");
}
public boolean argIsSet(int idx)
{
if (this.args.size() < idx+1)
{
return false;
}
return true;
}
public String arg(int idx)
{
if ( ! this.argIsSet(idx)) return null;
return this.args.get(idx);
}
public <T> T arg(int idx, ArgReader<T> ar)
{
return this.arg(idx, ar, null);
}
public <T> T arg(int idx, ArgReader<T> argReader, T defaultNotSet)
{
String str = this.arg(idx);
if (str == null) return defaultNotSet;
ArgResult<T> result = argReader.read(str, this.sender);
if (result.hasErrors()) this.msg(result.getErrors());
return result.getResult();
}
}

View File

@@ -0,0 +1,9 @@
package com.massivecraft.mcore.cmd;
public enum VisibilityMode
{
VISIBLE, // Visible commands are visible to anyone. Even those who don't have permission to use it or is of invalid sender type.
SECRET, // Secret commands are visible only to those who can use the command. These commands are usually some kind of admin commands.
INVISIBLE, // Invisible commands are invisible to everyone, even those who can use the command.
;
}

View File

@@ -0,0 +1,26 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.command.CommandSender;
public abstract class ARAbstractPrimitive<T> implements ArgReader<T>
{
public abstract String typename();
public abstract T convert(String arg) throws Exception;
@Override
public ArgResult<T> read(String arg, CommandSender sender)
{
ArgResult<T> result = new ArgResult<T>();
try
{
result.setResult(this.convert(arg));
}
catch (Exception e)
{
result.getErrors().add("<b>Invalid "+this.typename()+" \"<h>"+arg+"\"<b>.");
}
return result;
}
}

View File

@@ -0,0 +1,40 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.Collection;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.Txt;
public abstract class ARAbstractSelect<T> implements ArgReader<T>
{
public abstract String typename();
public abstract T select(String str, CommandSender sender);
public abstract Collection<String> altNames(CommandSender sender);
public boolean canList(CommandSender sender) { return true; }
@Override
public ArgResult<T> read(String arg, CommandSender sender)
{
ArgResult<T> result = new ArgResult<T>(this.select(arg, sender));
if (!result.hasResult())
{
result.getErrors().add("<b>No "+this.typename()+" matches \"<h>"+arg+"<b>\".");
if (this.canList(sender))
{
Collection<String> names = this.altNames(sender);
if (names.size() == 0)
{
result.getErrors().add("<i>Note: There is no "+this.typename()+" available.");
}
else
{
result.getErrors().add("<i>Use "+Txt.implodeCommaAndDot(names, "<h>%s", "<i>, ", " <i>or ", "<i>."));
}
}
}
return result;
}
}

View File

@@ -0,0 +1,44 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.Collection;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.Permission;
import com.massivecraft.mcore.usys.Aspect;
import com.massivecraft.mcore.usys.AspectColl;
public class ARAspect extends ARAbstractSelect<Aspect>
{
@Override
public String typename()
{
return "aspect";
}
@Override
public Aspect select(String arg, CommandSender sender)
{
return AspectColl.i.get(arg);
}
@Override
public boolean canList(CommandSender sender)
{
return Permission.CMD_USYS_ASPECT_LIST.has(sender, false);
}
@Override
public Collection<String> altNames(CommandSender sender)
{
return AspectColl.i.getIds();
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARAspect i = new ARAspect();
public static ARAspect get() { return i; }
}

View File

@@ -0,0 +1,29 @@
package com.massivecraft.mcore.cmd.arg;
public class ARBoolean extends ARAbstractPrimitive<Boolean>
{
@Override
public String typename()
{
return "boolean";
}
@Override
public Boolean convert(String arg) throws Exception
{
arg = arg.toLowerCase();
if (arg.startsWith("y") || arg.startsWith("t") || arg.startsWith("on") || arg.startsWith("+") || arg.startsWith("1"))
{
return true;
}
return false;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARBoolean i = new ARBoolean();
public static ARBoolean get() { return i; }
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.cmd.arg;
public class ARByte extends ARAbstractPrimitive<Byte>
{
@Override
public String typename()
{
return "byte";
}
@Override
public Byte convert(String arg) throws Exception
{
return Byte.parseByte(arg);
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARByte i = new ARByte();
public static ARByte get() { return i; }
}

View File

@@ -0,0 +1,72 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
public class ARChatColor extends ARAbstractSelect<ChatColor>
{
@Override
public String typename()
{
return "chat color";
}
@Override
public ChatColor select(String arg, CommandSender sender)
{
ChatColor ret = null;
arg = getToCompare(arg);
for (ChatColor cc : ChatColor.values())
{
String ccstr = getToCompare(cc.name());
if ( ! ccstr.equals(arg)) continue;
ret = cc;
break;
}
return ret;
}
@Override
public Collection<String> altNames(CommandSender sender)
{
List<String> ret = new ArrayList<String>();
for (ChatColor cc : ChatColor.values())
{
ret.add(cc.toString()+getToCompare(cc.name()));
}
return ret;
}
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
// "DARK_RED" --> "darkred"
// "DARK RED" --> "darkred"
public static String getToCompare(String str)
{
str = str.toLowerCase();
str = str.replace("_", "");
str = str.replace(" ", "");
return str;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARChatColor i = new ARChatColor();
public static ARChatColor get() { return i; }
}

View File

@@ -0,0 +1,30 @@
package com.massivecraft.mcore.cmd.arg;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ARDate extends ARAbstractPrimitive<Date>
{
protected static DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
@Override
public String typename()
{
return "YYYY-MM-DD date";
}
@Override
public Date convert(String arg) throws Exception
{
return df.parse(arg);
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARDate i = new ARDate();
public static ARDate get() { return i; }
}

View File

@@ -0,0 +1,58 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.Collection;
import org.bukkit.Difficulty;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.MUtil;
public class ARDifficulty extends ARAbstractSelect<Difficulty>
{
@Override
public String typename()
{
return "difficulty";
}
@Override
public Difficulty select(String arg, CommandSender sender)
{
Difficulty ret = null;
arg = arg.toLowerCase();
if (arg.startsWith("p"))
{
ret = Difficulty.PEACEFUL;
}
else if (arg.startsWith("e"))
{
ret = Difficulty.EASY;
}
else if (arg.startsWith("n"))
{
ret = Difficulty.NORMAL;
}
else if (arg.startsWith("h"))
{
ret = Difficulty.HARD;
}
return ret;
}
@Override
public Collection<String> altNames(CommandSender sender)
{
return MUtil.list("peaceful", "easy", "normal", "hard");
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARDifficulty i = new ARDifficulty();
public static ARDifficulty get() { return i; }
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.cmd.arg;
public class ARDouble extends ARAbstractPrimitive<Double>
{
@Override
public String typename()
{
return "double";
}
@Override
public Double convert(String arg) throws Exception
{
return Double.parseDouble(arg);
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARDouble i = new ARDouble();
public static ARDouble get() { return i; }
}

View File

@@ -0,0 +1,60 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.Collection;
import org.bukkit.World.Environment;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.MUtil;
public class AREnvironment extends ARAbstractSelect<Environment>
{
@Override
public String typename()
{
return "environment";
}
@Override
public Environment select(String arg, CommandSender sender)
{
Environment ret = null;
// "THE_END" --> "end"
arg = arg.toLowerCase();
arg = arg.replace("_", "");
arg = arg.replace("the", "");
if (arg.startsWith("no") || arg.startsWith("d"))
{
// "normal" or "default"
ret = Environment.NORMAL;
}
else if (arg.startsWith("ne"))
{
// "nether"
ret = Environment.NETHER;
}
else if (arg.startsWith("e"))
{
// "end"
ret = Environment.THE_END;
}
return ret;
}
@Override
public Collection<String> altNames(CommandSender sender)
{
return MUtil.list("normal", "end", "nether");
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static AREnvironment i = new AREnvironment();
public static AREnvironment get() { return i; }
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.cmd.arg;
public class ARFloat extends ARAbstractPrimitive<Float>
{
@Override
public String typename()
{
return "integer";
}
@Override
public Float convert(String arg) throws Exception
{
return Float.parseFloat(arg);
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARFloat i = new ARFloat();
public static ARFloat get() { return i; }
}

View File

@@ -0,0 +1,54 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.Collection;
import org.bukkit.GameMode;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.MUtil;
public class ARGameMode extends ARAbstractSelect<GameMode>
{
@Override
public String typename()
{
return "game mode";
}
@Override
public GameMode select(String arg, CommandSender sender)
{
GameMode ret = null;
arg = arg.toLowerCase();
if (arg.startsWith("s"))
{
ret = GameMode.SURVIVAL;
}
else if (arg.startsWith("c"))
{
ret = GameMode.CREATIVE;
}
else if (arg.startsWith("a"))
{
ret = GameMode.ADVENTURE;
}
return ret;
}
@Override
public Collection<String> altNames(CommandSender sender)
{
return MUtil.list("survival", "creative", "adventure");
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARGameMode i = new ARGameMode();
public static ARGameMode get() { return i; }
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.cmd.arg;
public class ARInteger extends ARAbstractPrimitive<Integer>
{
@Override
public String typename()
{
return "integer";
}
@Override
public Integer convert(String arg) throws Exception
{
return Integer.parseInt(arg);
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARInteger i = new ARInteger();
public static ARInteger get() { return i; }
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.cmd.arg;
public class ARLong extends ARAbstractPrimitive<Long>
{
@Override
public String typename()
{
return "long";
}
@Override
public Long convert(String arg) throws Exception
{
return Long.parseLong(arg);
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARLong i = new ARLong();
public static ARLong get() { return i; }
}

View File

@@ -0,0 +1,27 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
public class ARMaterial implements ArgReader<Material>
{
@Override
public ArgResult<Material> read(String arg, CommandSender sender)
{
ArgResult<Material> result = new ArgResult<Material>(Material.matchMaterial(arg));
if (!result.hasResult())
{
result.getErrors().add("<b>No material matches <h>"+arg+"<b>.");
result.getErrors().add("<i>Suggestion: <aqua>http://www.minecraftwiki.net/wiki/Data_values");
}
return result;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARMaterial i = new ARMaterial();
public static ARMaterial get() { return i; }
}

View File

@@ -0,0 +1,36 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.TimeDiffUtil;
import com.massivecraft.mcore.util.Txt;
public class ARMillisDiff implements ArgReader<Long>
{
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public ArgResult<Long> read(String arg, CommandSender sender)
{
ArgResult<Long> ret = new ArgResult<Long>();
try
{
ret.setResult(TimeDiffUtil.millis(arg));
}
catch (Exception e)
{
ret.setErrors(Txt.parse("<b>")+e.getMessage());
}
return ret;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARMillisDiff i = new ARMillisDiff();
public static ARMillisDiff get() { return i; }
}

View File

@@ -0,0 +1,44 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.Collection;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.Permission;
import com.massivecraft.mcore.usys.Multiverse;
import com.massivecraft.mcore.usys.MultiverseColl;
public class ARMultiverse extends ARAbstractSelect<Multiverse>
{
@Override
public String typename()
{
return "multiverse";
}
@Override
public Multiverse select(String arg, CommandSender sender)
{
return MultiverseColl.i.get(arg);
}
@Override
public boolean canList(CommandSender sender)
{
return Permission.CMD_USYS_MULTIVERSE_LIST.has(sender, false);
}
@Override
public Collection<String> altNames(CommandSender sender)
{
return MultiverseColl.i.getIds();
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARMultiverse i = new ARMultiverse();
public static ARMultiverse get() { return i; }
}

View File

@@ -0,0 +1,46 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.entity.Player;
import com.massivecraft.mcore.store.SenderIdSource;
import com.massivecraft.mcore.store.SenderIdSourceMixinAllSenderIds;
import com.massivecraft.mcore.util.SenderUtil;
public class ARPlayer extends ARSenderIdAbstractPredsource<Player>
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static final ARPlayer full = getFull(SenderIdSourceMixinAllSenderIds.get());
public static ARPlayer getFull() { return full; }
private static final ARPlayer start = getStart(SenderIdSourceMixinAllSenderIds.get());
public static ARPlayer getStart() { return start; }
public static ARPlayer getFull(SenderIdSource source)
{
return new ARPlayer(source, "player", ArgPredictateStringEqualsLC.get());
}
public static ARPlayer getStart(SenderIdSource source)
{
return new ARPlayer(source, "player", ArgPredictateStringStartsLC.get());
}
private ARPlayer(SenderIdSource source, String typename, ArgPredictate<String> argPredictate)
{
super(source, typename, argPredictate);
}
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public Player getResultForSenderId(String senderId)
{
return SenderUtil.getPlayer(senderId);
}
}

View File

@@ -0,0 +1,46 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.store.SenderIdSource;
import com.massivecraft.mcore.store.SenderIdSourceMixinAllSenderIds;
import com.massivecraft.mcore.util.SenderUtil;
public class ARSender extends ARSenderIdAbstractPredsource<CommandSender>
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static final ARSender full = getFull(SenderIdSourceMixinAllSenderIds.get());
public static ARSender getFull() { return full; }
private static final ARSender start = getStart(SenderIdSourceMixinAllSenderIds.get());
public static ARSender getStart() { return start; }
public static ARSender getFull(SenderIdSource source)
{
return new ARSender(source, "sender", ArgPredictateStringEqualsLC.get());
}
public static ARSender getStart(SenderIdSource source)
{
return new ARSender(source, "sender", ArgPredictateStringStartsLC.get());
}
private ARSender(SenderIdSource source, String typename, ArgPredictate<String> argPredictate)
{
super(source, typename, argPredictate);
}
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public CommandSender getResultForSenderId(String senderId)
{
return SenderUtil.getSender(senderId);
}
}

View File

@@ -0,0 +1,63 @@
package com.massivecraft.mcore.cmd.arg;
import com.massivecraft.mcore.store.SenderColl;
import com.massivecraft.mcore.store.SenderEntity;
import com.massivecraft.mcore.store.SenderIdSource;
public class ARSenderEntity<T extends SenderEntity<T>> extends ARSenderIdAbstractPredsource<T>
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
private final SenderColl<T> coll;
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
public static <T extends SenderEntity<T>> ARSenderEntity<T> getFullAny(SenderColl<T> coll) { return getFullAny(coll, coll.isCreative() ? coll.getMixinedIdSource() : coll); }
public static <T extends SenderEntity<T>> ARSenderEntity<T> getStartAny(SenderColl<T> coll) { return getStartAny(coll, coll.isCreative() ? coll.getMixinedIdSource() : coll); }
public static <T extends SenderEntity<T>> ARSenderEntity<T> getFullOnline(SenderColl<T> coll) { return getFullOnline(coll, coll.isCreative() ? coll.getMixinedIdSource() : coll); }
public static <T extends SenderEntity<T>> ARSenderEntity<T> getStartOnline(SenderColl<T> coll) { return getStartOnline(coll, coll.isCreative() ? coll.getMixinedIdSource() : coll); }
public static <T extends SenderEntity<T>> ARSenderEntity<T> getFullOnline(SenderColl<T> coll, SenderIdSource source)
{
return new ARSenderEntity<T>(coll, source, "player", new ArgPredictateAnd<String>(ArgPredictateStringEqualsLC.get(), ArgPredictateStringIsOnlineSenderId.get()));
}
public static <T extends SenderEntity<T>> ARSenderEntity<T> getStartOnline(SenderColl<T> coll, SenderIdSource source)
{
return new ARSenderEntity<T>(coll, source, "player", new ArgPredictateAnd<String>(ArgPredictateStringStartsLC.get(), ArgPredictateStringIsOnlineSenderId.get()));
}
public static <T extends SenderEntity<T>> ARSenderEntity<T> getFullAny(SenderColl<T> coll, SenderIdSource source)
{
return new ARSenderEntity<T>(coll, source, "player", ArgPredictateStringEqualsLC.get());
}
public static <T extends SenderEntity<T>> ARSenderEntity<T> getStartAny(SenderColl<T> coll, SenderIdSource source)
{
return new ARSenderEntity<T>(coll, source, "player", ArgPredictateStringStartsLC.get());
}
private ARSenderEntity(SenderColl<T> coll, SenderIdSource source, String typename, ArgPredictate<String> argPredictate)
{
super(source, typename, argPredictate);
this.coll = coll;
}
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public T getResultForSenderId(String senderId)
{
return this.coll.get(senderId);
}
}

View File

@@ -0,0 +1,43 @@
package com.massivecraft.mcore.cmd.arg;
import com.massivecraft.mcore.store.SenderIdSource;
import com.massivecraft.mcore.store.SenderIdSourceMixinAllSenderIds;
public class ARSenderId extends ARSenderIdAbstractPredsource<String>
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static final ARSenderId full = getFull(SenderIdSourceMixinAllSenderIds.get());
public static ARSenderId getFull() { return full; }
private static final ARSenderId start = getStart(SenderIdSourceMixinAllSenderIds.get());
public static ARSenderId getStart() { return start; }
public static ARSenderId getFull(SenderIdSource source)
{
return new ARSenderId(source, "player", ArgPredictateStringEqualsLC.get());
}
public static ARSenderId getStart(SenderIdSource source)
{
return new ARSenderId(source, "player", ArgPredictateStringStartsLC.get());
}
private ARSenderId(SenderIdSource source, String typename, ArgPredictate<String> argPredictate)
{
super(source, typename, argPredictate);
}
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public String getResultForSenderId(String senderId)
{
return senderId;
}
}

View File

@@ -0,0 +1,75 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.Collection;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.mixin.Mixin;
import com.massivecraft.mcore.util.Txt;
public abstract class ARSenderIdAbstract<T> implements ArgReader<T>
{
// -------------------------------------------- //
// ABSTRACT
// -------------------------------------------- //
public final static int MAX_COUNT = 10;
// -------------------------------------------- //
// ABSTRACT
// -------------------------------------------- //
public abstract String getTypename();
public abstract T getResultForSenderId(String senderId);
public abstract Collection<String> getSenderIdsFor(String arg, CommandSender sender);
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public ArgResult<T> read(String arg, CommandSender sender)
{
ArgResult<T> ret = new ArgResult<T>();
Collection<String> senderIds = this.getSenderIdsFor(arg, sender);
if (senderIds.size() == 0)
{
// No alternatives found
ret.setErrors("<b>No "+this.getTypename()+" matches \"<h>"+arg+"<b>\".");
}
else if (senderIds.size() == 1)
{
// Only one alternative found
String senderId = senderIds.iterator().next();
ret.setResult(this.getResultForSenderId(senderId));
}
else if (senderIds.contains(arg))
{
// Exact match
String senderId = Mixin.tryFix(arg);
ret.setResult(this.getResultForSenderId(senderId));
}
else
{
// Ambigious!
ret.getErrors().add("<b>Online "+this.getTypename()+" matching \"<h>"+arg+"<b>\" is ambigious.");
if (senderIds.size() >= MAX_COUNT)
{
// To many to list
ret.getErrors().add("<b>More than "+MAX_COUNT+" possible alternatives.");
}
else
{
// List the alternatives
ret.getErrors().add("<b>Did you mean "+Txt.implodeCommaAndDot(senderIds, "<h>%s", "<b>, ", " <b>or ", "<b>?"));
}
}
return ret;
}
}

View File

@@ -0,0 +1,80 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.Collection;
import java.util.TreeSet;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.store.SenderIdSource;
public abstract class ARSenderIdAbstractPredsource<T> extends ARSenderIdAbstract<T>
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
private final SenderIdSource source;
private final String typename;
private final ArgPredictate<String> argPredictate;
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public ARSenderIdAbstractPredsource(SenderIdSource source, String typename, ArgPredictate<String> argPredictate)
{
this.source = source;
this.typename = typename;
this.argPredictate = argPredictate;
}
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public String getTypename()
{
return this.typename;
}
@Override
public Collection<String> getSenderIdsFor(String arg, CommandSender sender)
{
arg = arg.toLowerCase();
TreeSet<String> ret = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
for (Collection<String> coll : this.source.getSenderIdCollections())
{
for (String senderId : coll)
{
if (this.isSenderIdOk(senderId, arg, sender))
{
ret.add(senderId);
if (ret.size() >= MAX_COUNT)
{
return ret;
}
}
}
}
return ret;
}
protected boolean isSenderIdOk(String senderId, String arg, CommandSender sender)
{
// If the predictate applies ...
if (!this.argPredictate.apply(senderId, arg, sender)) return false;
// ... and the result is non null ...
T result = this.getResultForSenderId(senderId);
if (result == null) return false;
// ... then the senderId is ok.
return true;
}
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.cmd.arg;
public class ARString extends ARAbstractPrimitive<String>
{
@Override
public String typename()
{
return "string";
}
@Override
public String convert(String arg) throws Exception
{
return arg;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARString i = new ARString();
public static ARString get() { return i; }
}

View File

@@ -0,0 +1,52 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.ArrayList;
import java.util.Collection;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.usys.Multiverse;
import com.massivecraft.mcore.util.Txt;
public class ARUniverse implements ArgReader<String>
{
// -------------------------------------------- //
// IMPLEMENTATION
// -------------------------------------------- //
@Override
public ArgResult<String> read(String arg, CommandSender sender)
{
ArgResult<String> result = new ArgResult<String>();
if (multiverse.containsUniverse(arg))
{
result.setResult(arg);
}
else
{
result.getErrors().add("<b>No universe \"<h>"+arg+"<b>\" exists in multiverse <h>"+this.multiverse.getId()+"<b>.");
Collection<String> names = new ArrayList<String>(multiverse.getUniverses());
result.getErrors().add("<i>Use "+Txt.implodeCommaAndDot(names, "<h>%s", "<i>, ", " <i>or ", "<i>."));
}
return result;
}
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
protected Multiverse multiverse;
public Multiverse multiverse() { return this.multiverse; }
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public ARUniverse(Multiverse multiverse)
{
this.multiverse = multiverse;
}
}

View File

@@ -0,0 +1,44 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
public class ARWorld implements ArgReader<World>
{
@Override
public ArgResult<World> read(String arg, CommandSender sender)
{
ArgResult<World> ret = new ArgResult<World>();
ArgResult<String> inner = ARWorldId.get().read(arg, sender);
if (inner.hasErrors())
{
ret.setErrors(inner.getErrors());
return ret;
}
String worldId = inner.getResult();
World world = Bukkit.getWorld(worldId);
if (world == null)
{
ret.setErrors("<b>The world could not be found.");
}
else
{
ret.setResult(world);
}
return ret;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARWorld i = new ARWorld();
public static ARWorld get() { return i; }
}

View File

@@ -0,0 +1,60 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.mixin.Mixin;
public class ARWorldId extends ARAbstractSelect<String>
{
@Override
public String typename()
{
return "world";
}
@Override
public String select(String arg, CommandSender sender)
{
List<String> visibleWorldIds = Mixin.getVisibleWorldIds(sender);
for (String worldId : visibleWorldIds)
{
if (!Mixin.canSee(sender, worldId)) continue;
if (arg.equalsIgnoreCase(worldId)) return worldId;
}
for (String worldId : visibleWorldIds)
{
if (!Mixin.canSee(sender, worldId)) continue;
for (String worldAlias : Mixin.getWorldAliases(worldId))
{
if (arg.equalsIgnoreCase(worldAlias)) return worldId;
}
}
return null;
}
@Override
public List<String> altNames(CommandSender sender)
{
List<String> ret = new ArrayList<String>();
for (String worldId : Mixin.getWorldIds())
{
if (!Mixin.canSee(sender, worldId)) continue;
ret.add(Mixin.getWorldDisplayName(worldId));
}
return ret;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARWorldId i = new ARWorldId();
public static ARWorldId get() { return i; }
}

View File

@@ -0,0 +1,70 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.Collection;
import org.bukkit.WorldType;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.MUtil;
public class ARWorldType extends ARAbstractSelect<WorldType>
{
@Override
public String typename()
{
return "world type";
}
@Override
public WorldType select(String arg, CommandSender sender)
{
WorldType ret = null;
// "DEFAULT_1_1" --> "11"
// "LARGE_BIOMES" --> "large"
// "Default" --> ""
arg = arg.toLowerCase();
arg = arg.replace("_", "");
arg = arg.replace(".", "");
arg = arg.replace("normal", "");
arg = arg.replace("default", "");
arg = arg.replace("large", "");
if (arg.equals(""))
{
// "normal" or "default"
ret = WorldType.NORMAL;
}
else if (arg.startsWith("flat"))
{
// "flat"
ret = WorldType.FLAT;
}
else if (arg.contains("11"))
{
// "VERSION_1_1"
ret = WorldType.VERSION_1_1;
}
else if (arg.contains("large"))
{
// "LARGE_BIOMES"
ret = WorldType.LARGE_BIOMES;
}
return ret;
}
@Override
public Collection<String> altNames(CommandSender sender)
{
return MUtil.list("normal", "flat", "1.1", "largebiomes");
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
private static ARWorldType i = new ARWorldType();
public static ARWorldType get() { return i; }
}

View File

@@ -0,0 +1,8 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.command.CommandSender;
public interface ArgPredictate<T>
{
public boolean apply(T type, String arg, CommandSender sender);
}

View File

@@ -0,0 +1,31 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.command.CommandSender;
public class ArgPredictateAnd<T> implements ArgPredictate<T>
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
private final ArgPredictate<T> one;
private final ArgPredictate<T> two;
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public ArgPredictateAnd(ArgPredictate<T> one, ArgPredictate<T>two)
{
this.one = one;
this.two = two;
}
@Override
public boolean apply(T type, String arg, CommandSender sender)
{
if (!this.one.apply(type, arg, sender)) return false;
return this.two.apply(type, arg, sender);
}
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.command.CommandSender;
public class ArgPredictateStringEqualsLC implements ArgPredictate<String>
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static ArgPredictateStringEqualsLC i = new ArgPredictateStringEqualsLC();
public static ArgPredictateStringEqualsLC get() { return i; }
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public boolean apply(String string, String arg, CommandSender sender)
{
return string.toLowerCase().equals(arg);
}
}

View File

@@ -0,0 +1,26 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.mixin.Mixin;
public class ArgPredictateStringIsOnlineSenderId implements ArgPredictate<String>
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static ArgPredictateStringIsOnlineSenderId i = new ArgPredictateStringIsOnlineSenderId();
public static ArgPredictateStringIsOnlineSenderId get() { return i; }
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public boolean apply(String string, String arg, CommandSender sender)
{
return Mixin.isOnline(string);
}
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.command.CommandSender;
public class ArgPredictateStringStartsLC implements ArgPredictate<String>
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static ArgPredictateStringStartsLC i = new ArgPredictateStringStartsLC();
public static ArgPredictateStringStartsLC get() { return i; }
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public boolean apply(String string, String arg, CommandSender sender)
{
return string.toLowerCase().startsWith(arg);
}
}

View File

@@ -0,0 +1,8 @@
package com.massivecraft.mcore.cmd.arg;
import org.bukkit.command.CommandSender;
public interface ArgReader<T>
{
public ArgResult<T> read(String arg, CommandSender sender);
}

View File

@@ -0,0 +1,75 @@
package com.massivecraft.mcore.cmd.arg;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
public class ArgResult<T>
{
// -------------------------------------------- //
// FIELD: RESULT
// -------------------------------------------- //
@Getter @Setter protected T result = null;
public boolean hasResult()
{
return this.getResult() != null;
}
// -------------------------------------------- //
// FIELD: ERRORS
// -------------------------------------------- //
@Getter protected List<String> errors = new ArrayList<String>();
public void setErrors(List<String> val)
{
if (val == null)
{
this.errors = new ArrayList<String>();
}
else
{
this.errors = val;
}
}
public void setErrors(String... val)
{
this.setErrors(Arrays.asList(val));
}
public boolean hasErrors()
{
return this.errors.size() > 0;
}
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public ArgResult()
{
}
public ArgResult(T result)
{
this.setResult(result);
}
public ArgResult(T result, List<String> errors)
{
this.setResult(result);
this.setErrors(errors);
}
public ArgResult(T result, String... errors)
{
this.setResult(result);
this.setErrors(errors);
}
}

View File

@@ -0,0 +1,14 @@
package com.massivecraft.mcore.cmd.req;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.cmd.MCommand;
public interface IReq
{
// This just tests wether the requirement is met or not.
public boolean test(CommandSender sender, MCommand command);
// This just composes the error message and does NOT test the requirement at all.
public String createErrorMessage(CommandSender sender, MCommand command);
}

View File

@@ -0,0 +1,37 @@
package com.massivecraft.mcore.cmd.req;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.cmd.MCommand;
import com.massivecraft.mcore.util.PermUtil;
public class ReqHasPerm implements IReq
{
@Getter @Setter private String perm;
public ReqHasPerm(String perm)
{
this.perm = perm;
}
@Override
public boolean test(CommandSender sender, MCommand command)
{
return sender.hasPermission(this.perm);
}
@Override
public String createErrorMessage(CommandSender sender, MCommand command)
{
return PermUtil.getForbiddenMessage(this.perm);
}
public static ReqHasPerm get(String perm)
{
return new ReqHasPerm(perm);
}
}

View File

@@ -0,0 +1,30 @@
package com.massivecraft.mcore.cmd.req;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.massivecraft.mcore.Lang;
import com.massivecraft.mcore.cmd.MCommand;
public class ReqIsPlayer implements IReq
{
@Override
public boolean test(CommandSender sender, MCommand command)
{
return sender instanceof Player;
}
@Override
public String createErrorMessage(CommandSender sender, MCommand command)
{
return Lang.commandSenderMustBePlayer;
}
// -------------------------------------------- //
// INSTANCE
// -------------------------------------------- //
public static ReqIsPlayer i = new ReqIsPlayer();
public static ReqIsPlayer get() { return i; }
}

View File

@@ -0,0 +1,51 @@
package com.massivecraft.mcore.event;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerRespawnEvent;
public class MCoreAfterPlayerRespawnEvent extends Event implements Runnable
{
// -------------------------------------------- //
// REQUIRED EVENT CODE
// -------------------------------------------- //
private static final HandlerList handlers = new HandlerList();
@Override public HandlerList getHandlers() { return handlers; }
public static HandlerList getHandlerList() { return handlers; }
// -------------------------------------------- //
// FIELD
// -------------------------------------------- //
@Getter protected final Location deathLocation;
@Getter protected final PlayerRespawnEvent bukkitEvent;
public Location getRespawnLocation() { return this.bukkitEvent.getRespawnLocation(); }
public Player getPlayer() { return this.bukkitEvent.getPlayer(); }
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public MCoreAfterPlayerRespawnEvent(PlayerRespawnEvent bukkitEvent, Location deathLocation)
{
this.bukkitEvent = bukkitEvent;
this.deathLocation = deathLocation;
}
// -------------------------------------------- //
// HANDY RUN SHORTCUT
// -------------------------------------------- //
@Override
public void run()
{
Bukkit.getPluginManager().callEvent(this);
}
}

View File

@@ -0,0 +1,59 @@
package com.massivecraft.mcore.event;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
public class MCoreAfterPlayerTeleportEvent extends Event implements Runnable
{
// -------------------------------------------- //
// REQUIRED EVENT CODE
// -------------------------------------------- //
private static final HandlerList handlers = new HandlerList();
@Override public HandlerList getHandlers() { return handlers; }
public static HandlerList getHandlerList() { return handlers; }
// -------------------------------------------- //
// FIELD
// -------------------------------------------- //
@Getter protected final PlayerTeleportEvent bukkitEvent;
public Location getFrom() { return this.bukkitEvent.getFrom(); }
public Location getTo() { return this.bukkitEvent.getTo(); }
public Player getPlayer() { return this.bukkitEvent.getPlayer(); }
public TeleportCause getCause() { return this.bukkitEvent.getCause(); }
public boolean isCrossWorlds()
{
World worldFrom = this.getFrom().getWorld();
World worldTo = this.getTo().getWorld();
return ! worldFrom.equals(worldTo);
}
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public MCoreAfterPlayerTeleportEvent(PlayerTeleportEvent bukkitEvent)
{
this.bukkitEvent = bukkitEvent;
}
// -------------------------------------------- //
// HANDY RUN SHORTCUT
// -------------------------------------------- //
@Override
public void run()
{
Bukkit.getPluginManager().callEvent(this);
}
}

View File

@@ -0,0 +1,18 @@
package com.massivecraft.mcore.event;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;
public abstract class MCoreEvent extends Event implements Runnable
{
// -------------------------------------------- //
// RUN
// -------------------------------------------- //
@Override
public void run()
{
Bukkit.getPluginManager().callEvent(this);
}
}

View File

@@ -0,0 +1,85 @@
package com.massivecraft.mcore.event;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* The MCorePlayerLeaveEvent is a non-cancellable event.
* It is run at the MONITOR of either PlayerKickEvent or PlayerQuitEvent.
* It is also guaranteed to run before the MCore "store" module syncs
* all entities related to the player that is leaving the server.
*
* Use this even if you want to update a player entity as
* that player leaves. Automatic syncing will be guaranteed and the
* event will run pre disconnect if possible due to the internal usage if the PlayerKickedEvent.
*/
public class MCorePlayerLeaveEvent extends Event implements Runnable
{
// -------------------------------------------- //
// REQUIRED EVENT CODE
// -------------------------------------------- //
private static final HandlerList handlers = new HandlerList();
@Override public HandlerList getHandlers() { return handlers; }
public static HandlerList getHandlerList() { return handlers; }
// -------------------------------------------- //
// FIELD
// -------------------------------------------- //
@Getter protected final Player player;
@Getter protected final boolean preDisconnect;
public boolean isPostDisconnect() { return !this.isPreDisconnect(); }
@Getter protected final String caller;
public boolean isQuit() { return "quit".equals(caller); }
public boolean isKick() { return "kick".equals(caller); }
@Getter protected final String message;
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public MCorePlayerLeaveEvent(Player player, boolean preDisconnect, String caller, String message)
{
this.player = player;
this.preDisconnect = preDisconnect;
this.caller = caller;
this.message = message;
}
// -------------------------------------------- //
// HANDY RUN SHORTCUT
// -------------------------------------------- //
@Override
public void run()
{
// Someone may already have issued a player leave event for this disconnect.
// We ignore that since we want one leave event called per disconnect only.
boolean doit = !player2event.containsKey(this.player.getName());
//MCore.p.log("MCorePlayerLeaveEvent", "caller:", caller, "doit:", doit, "player:", player.getDisplayName(), "preDisconnect:", preDisconnect, "message:", message);
if (doit)
{
//MCore.p.log("MCorePlayerLeaveEvent", caller, player.getDisplayName(), preDisconnect, message);
player2event.put(this.player.getName(), this);
Bukkit.getPluginManager().callEvent(this);
}
}
// -------------------------------------------- //
// STORING THE ACTIVE PLAYER EVENT
// -------------------------------------------- //
public static Map<String,MCorePlayerLeaveEvent> player2event = new HashMap<String,MCorePlayerLeaveEvent>();
}

View File

@@ -0,0 +1,23 @@
package com.massivecraft.mcore.event;
import org.bukkit.command.CommandSender;
public abstract class MCoreSenderEvent extends MCoreEvent
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
private final CommandSender sender;
public CommandSender getSender() { return this.sender; }
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public MCoreSenderEvent(CommandSender sender)
{
this.sender = sender;
}
}

View File

@@ -0,0 +1,25 @@
package com.massivecraft.mcore.event;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
public class MCoreSenderRegisterEvent extends MCoreSenderEvent
{
// -------------------------------------------- //
// REQUIRED EVENT CODE
// -------------------------------------------- //
private static final HandlerList handlers = new HandlerList();
@Override public HandlerList getHandlers() { return handlers; }
public static HandlerList getHandlerList() { return handlers; }
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public MCoreSenderRegisterEvent(CommandSender sender)
{
super(sender);
}
}

View File

@@ -0,0 +1,25 @@
package com.massivecraft.mcore.event;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
public class MCoreSenderUnregisterEvent extends MCoreSenderEvent
{
// -------------------------------------------- //
// REQUIRED EVENT CODE
// -------------------------------------------- //
private static final HandlerList handlers = new HandlerList();
@Override public HandlerList getHandlers() { return handlers; }
public static HandlerList getHandlerList() { return handlers; }
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public MCoreSenderUnregisterEvent(CommandSender sender)
{
super(sender);
}
}

View File

@@ -0,0 +1,121 @@
package com.massivecraft.mcore.integration;
import java.util.Collection;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.plugin.Plugin;
import com.massivecraft.mcore.MPlugin;
import com.massivecraft.mcore.util.Txt;
public class Integration implements Listener
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
protected MPlugin ourPlugin;
protected IntegrationFeatures features;
@Getter protected boolean active = false;
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public Integration(MPlugin ourPlugin, IntegrationFeatures features)
{
this.ourPlugin = ourPlugin;
this.features = features;
Bukkit.getServer().getPluginManager().registerEvents(this, this.ourPlugin);
this.tick();
}
// -------------------------------------------- //
// LOGIC
// -------------------------------------------- //
public void tick()
{
String namelist = Txt.implodeCommaAndDot(this.features.getTargetPluginNames(), "<h>%s", "<i>, ", " <i>and ", "<i>.");
if (isPluginsEnabled(this.features.getTargetPluginNames()))
{
if (!this.active)
{
try
{
this.features.activate();
this.active = true;
this.ourPlugin.log(Txt.parse("<g>Activated <i>integration with "+namelist));
}
catch (Exception e)
{
this.ourPlugin.log(Txt.parse("<b>Failed to activate <i>integration with "+namelist));
e.printStackTrace();
}
}
}
else
{
if (this.active)
{
try
{
this.active = false;
this.features.deactivate();
this.ourPlugin.log(Txt.parse("<g>Deactivated <i>integration with "+namelist));
}
catch (Exception e)
{
this.ourPlugin.log(Txt.parse("<b>Failed to deactivate <i>integration with "+namelist));
e.printStackTrace();
}
}
}
}
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
public static boolean isPluginEnabled(String pluginName)
{
Plugin plugin = Bukkit.getPluginManager().getPlugin(pluginName);
if (plugin == null) return false;
return plugin.isEnabled();
}
public static boolean isPluginsEnabled(Collection<String> pluginNames)
{
for (String pluginName : pluginNames)
{
if (!isPluginEnabled(pluginName)) return false;
}
return true;
}
// -------------------------------------------- //
// EVENT LISTENERS
// -------------------------------------------- //
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginDisable(PluginDisableEvent event)
{
this.tick();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginEnable(PluginEnableEvent event)
{
this.tick();
}
}

View File

@@ -0,0 +1,10 @@
package com.massivecraft.mcore.integration;
import java.util.List;
public interface IntegrationFeatures
{
public List<String> getTargetPluginNames();
public void activate();
public void deactivate();
}

View File

@@ -0,0 +1,45 @@
package com.massivecraft.mcore.integration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class IntegrationFeaturesAbstract implements IntegrationFeatures
{
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
private List<String> targetPluginNames;
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public IntegrationFeaturesAbstract(String... targetPluginNames)
{
this.targetPluginNames = new ArrayList<String>(Arrays.asList(targetPluginNames));
}
// -------------------------------------------- //
// OVERRIDES
// -------------------------------------------- //
@Override
public List<String> getTargetPluginNames()
{
return this.targetPluginNames;
}
@Override
public void activate()
{
}
@Override
public void deactivate()
{
}
}

View File

@@ -0,0 +1,11 @@
package com.massivecraft.mcore.mixin;
import org.bukkit.command.CommandSender;
public interface DisplayNameMixin
{
public String getDisplayName(String senderId);
public void setDisplayName(String senderId, String displayName);
public String getDisplayName(CommandSender sender);
public void setDisplayName(CommandSender sender, String displayName);
}

View File

@@ -0,0 +1,20 @@
package com.massivecraft.mcore.mixin;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.SenderUtil;
public abstract class DisplayNameMixinAbstract implements DisplayNameMixin
{
@Override
public String getDisplayName(CommandSender sender)
{
return this.getDisplayName(SenderUtil.getSenderId(sender));
}
@Override
public void setDisplayName(CommandSender sender, String displayName)
{
this.setDisplayName(SenderUtil.getSenderId(sender), displayName);
}
}

View File

@@ -0,0 +1,81 @@
package com.massivecraft.mcore.mixin;
import java.util.Map;
import java.util.TreeMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class DisplayNameMixinDefault extends DisplayNameMixinAbstract
{
public final static ChatColor DEFAULT_COLOR = ChatColor.WHITE;
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static DisplayNameMixinDefault i = new DisplayNameMixinDefault();
public static DisplayNameMixinDefault get() { return i; }
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
protected Map<String, String> idToDisplayName = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public String getDisplayName(String senderId)
{
if (senderId == null) return null;
// Try Our Map
String ret = this.idToDisplayName.get(senderId);
// Try Bukkit
if (ret == null)
{
Player player = Bukkit.getPlayerExact(senderId);
if (player != null)
{
ret = player.getDisplayName();
}
}
// Try Fixed Id
if (ret == null)
{
ret = Mixin.tryFix(senderId);
}
// Ensure Colored
if (ChatColor.stripColor(ret).equals(ret))
{
ret = DEFAULT_COLOR.toString()+ret;
}
return ret;
}
@Override
public void setDisplayName(String senderId, String displayName)
{
if (displayName == null)
{
this.idToDisplayName.remove(senderId);
}
else
{
this.idToDisplayName.put(senderId, displayName);
}
Player player = Bukkit.getPlayerExact(senderId);
if (player == null) return;
player.setDisplayName(this.getDisplayName(senderId));
}
}

View File

@@ -0,0 +1,12 @@
package com.massivecraft.mcore.mixin;
import org.bukkit.command.CommandSender;
public interface KickMixin
{
public boolean kick(CommandSender sender);
public boolean kick(String senderId);
public boolean kick(CommandSender sender, String message);
public boolean kick(String senderId, String message);
}

View File

@@ -0,0 +1,18 @@
package com.massivecraft.mcore.mixin;
import org.bukkit.command.CommandSender;
public abstract class KickMixinAbstract implements KickMixin
{
@Override
public boolean kick(CommandSender sender)
{
return this.kick(sender, null);
}
@Override
public boolean kick(String senderId)
{
return this.kick(senderId, null);
}
}

View File

@@ -0,0 +1,39 @@
package com.massivecraft.mcore.mixin;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.massivecraft.mcore.util.SenderUtil;
public class KickMixinDefault extends KickMixinAbstract
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static KickMixinDefault i = new KickMixinDefault();
public static KickMixinDefault get() { return i; }
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public boolean kick(CommandSender sender, String message)
{
Player player = SenderUtil.getAsPlayer(sender);
if (player == null) return false;
player.kickPlayer(message);
return true;
}
@Override
public boolean kick(String senderId, String message)
{
Player player = SenderUtil.getPlayer(senderId);
if (player == null) return false;
player.kickPlayer(message);
return true;
}
}

View File

@@ -0,0 +1,11 @@
package com.massivecraft.mcore.mixin;
import org.bukkit.command.CommandSender;
public interface ListNameMixin
{
public String getListName(String senderId);
public void setListName(String senderId, String listName);
public String getListName(CommandSender sender);
public void setListName(CommandSender sender, String listName);
}

View File

@@ -0,0 +1,20 @@
package com.massivecraft.mcore.mixin;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.SenderUtil;
public abstract class ListNameMixinAbstract implements ListNameMixin
{
@Override
public String getListName(CommandSender sender)
{
return this.getListName(SenderUtil.getSenderId(sender));
}
@Override
public void setListName(CommandSender sender, String listName)
{
this.setListName(SenderUtil.getSenderId(sender), listName);
}
}

View File

@@ -0,0 +1,81 @@
package com.massivecraft.mcore.mixin;
import java.util.Map;
import java.util.TreeMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
public class ListNameMixinDefault extends ListNameMixinAbstract
{
public final static ChatColor DEFAULT_COLOR = ChatColor.WHITE;
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static ListNameMixinDefault i = new ListNameMixinDefault();
public static ListNameMixinDefault get() { return i; }
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
protected Map<String, String> idToListName = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public String getListName(String senderId)
{
if (senderId == null) return null;
// Try Our Map
String ret = this.idToListName.get(senderId);
// Try Bukkit
if (ret == null)
{
Player player = Bukkit.getPlayerExact(senderId);
if (player != null)
{
ret = player.getPlayerListName();
}
}
// Try Fixed Id
if (ret == null)
{
ret = Mixin.tryFix(senderId);
}
// Ensure Colored
if (ChatColor.stripColor(ret).equals(ret))
{
ret = DEFAULT_COLOR.toString()+ret;
}
return ret;
}
@Override
public void setListName(String senderId, String listName)
{
if (listName == null)
{
this.idToListName.remove(senderId);
}
else
{
this.idToListName.put(senderId, listName);
}
Player player = Bukkit.getPlayerExact(senderId);
if (player == null) return;
player.setPlayerListName(this.getListName(senderId));
}
}

View File

@@ -0,0 +1,24 @@
package com.massivecraft.mcore.mixin;
import java.util.Collection;
import org.bukkit.command.CommandSender;
public interface MessageMixin
{
public boolean message(CommandSender sender, String message);
public boolean message(CommandSender sender, Collection<String> messages);
public boolean message(CommandSender sender, String... messages);
public boolean message(String senderId, String message);
public boolean message(String senderId, Collection<String> messages);
public boolean message(String senderId, String... messages);
public boolean msg(CommandSender sender, String msg);
public boolean msg(CommandSender sender, String msg, Object... args);
public boolean msg(CommandSender sender, Collection<String> msgs);
public boolean msg(String senderId, String msg);
public boolean msg(String senderId, String msg, Object... args);
public boolean msg(String senderId, Collection<String> msgs);
}

View File

@@ -0,0 +1,76 @@
package com.massivecraft.mcore.mixin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.Txt;
public abstract class MessageMixinAbstract implements MessageMixin
{
@Override
public boolean message(CommandSender sender, String... messages)
{
Collection<String> coll = new ArrayList<String>(Arrays.asList(messages));
return this.message(sender, coll);
}
@Override
public boolean message(String senderId, String... messages)
{
Collection<String> coll = new ArrayList<String>(Arrays.asList(messages));
return this.message(senderId, coll);
}
@Override
public boolean msg(CommandSender sender, String msg)
{
return this.message(sender, Txt.parse(msg));
}
@Override
public boolean msg(CommandSender sender, String msg, Object... args)
{
return this.message(sender, Txt.parse(msg, args));
}
@Override
public boolean msg(CommandSender sender, Collection<String> msgs)
{
List<String> messages = new ArrayList<String>();
for (String msg : msgs)
{
String message = Txt.parse(msg);
messages.add(message);
}
return this.message(sender, messages);
}
@Override
public boolean msg(String senderId, String msg)
{
return this.message(senderId, Txt.parse(msg));
}
@Override
public boolean msg(String senderId, String msg, Object... args)
{
return this.message(senderId, Txt.parse(msg, args));
}
@Override
public boolean msg(String senderId, Collection<String> msgs)
{
List<String> messages = new ArrayList<String>();
for (String msg : msgs)
{
String message = Txt.parse(msg);
messages.add(message);
}
return this.message(senderId, messages);
}
}

View File

@@ -0,0 +1,55 @@
package com.massivecraft.mcore.mixin;
import java.util.Collection;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.SenderUtil;
public class MessageMixinDefault extends MessageMixinAbstract
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static MessageMixinDefault i = new MessageMixinDefault();
public static MessageMixinDefault get() { return i; }
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public boolean message(CommandSender sender, String message)
{
if (sender == null) return false;
if (message == null) return false;
sender.sendMessage(message);
return true;
}
@Override
public boolean message(CommandSender sender, Collection<String> messages)
{
if (sender == null) return false;
if (messages == null) return false;
for (String message : messages)
{
sender.sendMessage(message);
}
return true;
}
@Override
public boolean message(String senderId, String message)
{
return this.message(SenderUtil.getSender(senderId), message);
}
@Override
public boolean message(String senderId, Collection<String> messages)
{
return this.message(SenderUtil.getSender(senderId), messages);
}
}

View File

@@ -0,0 +1,422 @@
package com.massivecraft.mcore.mixin;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permissible;
import com.massivecraft.mcore.PS;
public class Mixin
{
// -------------------------------------------- //
// GET/SET MIXINS
// -------------------------------------------- //
private static WorldMixin worldMixin = WorldMixinDefault.get();
public static WorldMixin getWorldMixin() { return worldMixin; }
public static void setWorldMixin(WorldMixin val) { worldMixin = val; }
private static DisplayNameMixin displayNameMixin = DisplayNameMixinDefault.get();
public static DisplayNameMixin getDisplayNameMixin() { return displayNameMixin; }
public static void setDisplayNameMixin(DisplayNameMixin val) { displayNameMixin = val; }
private static ListNameMixin listNameMixin = ListNameMixinDefault.get();
public static ListNameMixin getListNameMixin() { return listNameMixin; }
public static void setListNameMixin(ListNameMixin val) { listNameMixin = val; }
private static SenderPsMixin senderPsMixin = SenderPsMixinDefault.get();
public static SenderPsMixin getSenderPsMixin() { return senderPsMixin; }
public static void setSenderPsMixin(SenderPsMixin val) { senderPsMixin = val; }
private static PlayedMixin playedMixin = PlayedMixinDefault.get();
public static PlayedMixin getPlayedMixin() { return playedMixin; }
public static void setPlayedMixin(PlayedMixin val) { playedMixin = val; }
private static VisibilityMixin visibilityMixin = VisibilityMixinDefault.get();
public static VisibilityMixin getVisibilityMixin() { return visibilityMixin; }
public static void setVisibilityMixin(VisibilityMixin val) { visibilityMixin = val; }
private static SenderIdMixin senderIdMixin = SenderIdMixinDefault.get();
public static SenderIdMixin getSenderIdMixin() { return senderIdMixin; }
public static void setSenderIdMixin(SenderIdMixin val) { senderIdMixin = val; }
private static TeleportMixin teleportMixin = TeleportMixinDefault.get();
public static TeleportMixin getTeleportMixin() { return teleportMixin; }
public static void setTeleportMixin(TeleportMixin val) { teleportMixin = val; }
private static MessageMixin messageMixin = MessageMixinDefault.get();
public static MessageMixin getMessageMixin() { return messageMixin; }
public static void setMessageMixin(MessageMixin val) { messageMixin = val; }
private static KickMixin kickMixin = KickMixinDefault.get();
public static KickMixin getKickMixin() { return kickMixin; }
public static void setKickMixin(KickMixin val) { kickMixin = val; }
// -------------------------------------------- //
// STATIC EXPOSE: WORLD
// -------------------------------------------- //
public static boolean canSee(Permissible permissible, String worldId)
{
return getWorldMixin().canSee(permissible, worldId);
}
public static List<String> getWorldIds()
{
return getWorldMixin().getWorldIds();
}
public static List<String> getVisibleWorldIds(Permissible permissible)
{
return getWorldMixin().getVisibleWorldIds(permissible);
}
public static ChatColor getWorldColor(String worldId)
{
return getWorldMixin().getWorldColor(worldId);
}
public static List<String> getWorldAliases(String worldId)
{
return getWorldAliases(worldId);
}
public static String getWorldAliasOrId(String worldId)
{
return getWorldMixin().getWorldAliasOrId(worldId);
}
public static String getWorldDisplayName(String worldId)
{
return getWorldMixin().getWorldDisplayName(worldId);
}
public static PS getWorldSpawnPs(String worldId)
{
return getWorldMixin().getWorldSpawnPs(worldId);
}
public static void setWorldSpawnPs(String worldId, PS spawnPs)
{
getWorldMixin().setWorldSpawnPs(worldId, spawnPs);
}
public static boolean trySetWorldSpawnWp(CommandSender sender, String worldId, PS spawnPs, boolean verbooseChange, boolean verbooseSame)
{
return getWorldMixin().trySetWorldSpawnWp(sender, worldId, spawnPs, verbooseChange, verbooseSame);
}
// -------------------------------------------- //
// STATIC EXPOSE: DISPLAY NAME
// -------------------------------------------- //
public static String getDisplayName(String senderId)
{
return getDisplayNameMixin().getDisplayName(senderId);
}
public static void setDisplayName(String senderId, String displayName)
{
getDisplayNameMixin().setDisplayName(senderId, displayName);
}
public static String getDisplayName(CommandSender sender)
{
return getDisplayNameMixin().getDisplayName(sender);
}
public static void setDisplayName(CommandSender sender, String displayName)
{
getDisplayNameMixin().setDisplayName(sender, displayName);
}
// -------------------------------------------- //
// STATIC EXPOSE: LIST NAME
// -------------------------------------------- //
public static String getListName(String senderId)
{
return getListNameMixin().getListName(senderId);
}
public static void setListName(String senderId, String listName)
{
getListNameMixin().setListName(senderId, listName);
}
public static String getListName(CommandSender sender)
{
return getListNameMixin().getListName(sender);
}
public static void setListName(CommandSender sender, String listName)
{
getListNameMixin().setListName(sender, listName);
}
// -------------------------------------------- //
// STATIC EXPOSE: SENDER PS
// -------------------------------------------- //
public static PS getSenderPs(String senderId)
{
return getSenderPsMixin().getSenderPs(senderId);
}
public static void setSenderPs(String senderId, PS ps)
{
getSenderPsMixin().setSenderPs(senderId, ps);
}
// -------------------------------------------- //
// STATIC EXPOSE: PLAYED
// -------------------------------------------- //
public static boolean isOnline(String senderId)
{
return getPlayedMixin().isOnline(senderId);
}
public static boolean isOffline(String senderId)
{
return getPlayedMixin().isOffline(senderId);
}
public static Long getLastPlayed(String senderId)
{
return getPlayedMixin().getLastPlayed(senderId);
}
public static Long getFirstPlayed(String senderId)
{
return getPlayedMixin().getFirstPlayed(senderId);
}
public static boolean hasPlayedBefore(String senderId)
{
return getPlayedMixin().hasPlayedBefore(senderId);
}
// -------------------------------------------- //
// STATIC EXPOSE: VISIBILITY
// -------------------------------------------- //
public static boolean isVisible(String watcherId, String watcheeId)
{
return getVisibilityMixin().isVisible(watcherId, watcheeId);
}
public static boolean isVisible(CommandSender watcher, String watcheeId)
{
return getVisibilityMixin().isVisible(watcher, watcheeId);
}
public static boolean isVisible(String watcherId, CommandSender watchee)
{
return getVisibilityMixin().isVisible(watcherId, watchee);
}
public static boolean isVisible(CommandSender watcher, CommandSender watchee)
{
return getVisibilityMixin().isVisible(watcher, watchee);
}
public static void setVisible(String watcherId, String watcheeId, boolean visible)
{
getVisibilityMixin().setVisible(watcherId, watcheeId, visible);
}
public static void setVisible(CommandSender watcher, String watcheeId, boolean visible)
{
getVisibilityMixin().setVisible(watcher, watcheeId, visible);
}
public static void setVisible(String watcherId, CommandSender watchee, boolean visible)
{
getVisibilityMixin().setVisible(watcherId, watchee, visible);
}
public static void setVisible(CommandSender watcher, CommandSender watchee, boolean visible)
{
getVisibilityMixin().setVisible(watcher, watchee, visible);
}
// -------------------------------------------- //
// STATIC EXPOSE: SENDER ID
// -------------------------------------------- //
public static String reqFix(String senderId)
{
return getSenderIdMixin().reqFix(senderId);
}
public static String tryFix(String senderId)
{
return getSenderIdMixin().tryFix(senderId);
}
public static boolean canFix(String senderId)
{
return getSenderIdMixin().canFix(senderId);
}
public static Set<String> getAllSenderIds()
{
return getSenderIdMixin().getAllSenderIds();
}
public static Set<String> getOnlineSenderIds()
{
return getSenderIdMixin().getOnlineSenderIds();
}
public static Set<String> getOfflineSenderIds()
{
return getSenderIdMixin().getOfflineSenderIds();
}
public static Set<String> getAllPlayerIds()
{
return getSenderIdMixin().getAllPlayerIds();
}
public static Set<String> getOnlinePlayerIds()
{
return getSenderIdMixin().getOnlinePlayerIds();
}
public static Set<String> getOfflinePlayerIds()
{
return getSenderIdMixin().getOfflinePlayerIds();
}
// -------------------------------------------- //
// STATIC EXPOSE: TELEPORTER
// -------------------------------------------- //
public static void teleport(Player teleportee, PS destinationPs) throws TeleporterException
{
getTeleportMixin().teleport(teleportee, destinationPs);
}
public static void teleport(Player teleportee, PS destinationPs, String destinationDesc) throws TeleporterException
{
getTeleportMixin().teleport(teleportee, destinationPs, destinationDesc);
}
public static void teleport(Player teleportee, PS destinationPs, String destinationDesc, Permissible delayPermissible) throws TeleporterException
{
getTeleportMixin().teleport(teleportee, destinationPs, destinationDesc, delayPermissible);
}
public static void teleport(Player teleportee, PS destinationPs, String destinationDesc, Permissible delayPermissible, CommandSender otherSender, String otherPerm) throws TeleporterException
{
getTeleportMixin().teleport(teleportee, destinationPs, destinationDesc, delayPermissible, otherSender, otherPerm);
}
public static void teleport(Player teleportee, PS destinationPs, String destinationDesc, CommandSender otherSender, String otherPerm) throws TeleporterException
{
getTeleportMixin().teleport(teleportee, destinationPs, destinationDesc, otherSender, otherPerm);
}
public static void teleport(Player teleportee, PS destinationPs, String destinationDesc, int delaySeconds, CommandSender otherSender, String otherPerm) throws TeleporterException
{
getTeleportMixin().teleport(teleportee, destinationPs, destinationDesc, delaySeconds, otherSender, otherPerm);
}
public static void teleport(Player teleportee, PS destinationPs, String destinationDesc, int delaySeconds) throws TeleporterException
{
getTeleportMixin().teleport(teleportee, destinationPs, destinationDesc, delaySeconds);
}
public static void teleport(String teleporteeId, PS destinationPs) throws TeleporterException
{
getTeleportMixin().teleport(teleporteeId, destinationPs);
}
public static void teleport(String teleporteeId, PS destinationPs, String destinationDesc) throws TeleporterException
{
getTeleportMixin().teleport(teleporteeId, destinationPs, destinationDesc);
}
public static void teleport(String teleporteeId, PS destinationPs, String destinationDesc, Permissible delayPermissible) throws TeleporterException
{
getTeleportMixin().teleport(teleporteeId, destinationPs, destinationDesc, delayPermissible);
}
public static void teleport(String teleporteeId, PS destinationPs, String destinationDesc, Permissible delayPermissible, CommandSender otherSender, String otherPerm) throws TeleporterException
{
getTeleportMixin().teleport(teleporteeId, destinationPs, destinationDesc, delayPermissible, otherSender, otherPerm);
}
public static void teleport(String teleporteeId, PS destinationPs, String destinationDesc, CommandSender otherSender, String otherPerm) throws TeleporterException
{
getTeleportMixin().teleport(teleporteeId, destinationPs, destinationDesc, otherSender, otherPerm);
}
public static void teleport(String teleporteeId, PS destinationPs, String destinationDesc, int delaySeconds, CommandSender otherSender, String otherPerm) throws TeleporterException
{
getTeleportMixin().teleport(teleporteeId, destinationPs, destinationDesc, delaySeconds, otherSender, otherPerm);
}
public static void teleport(String teleporteeId, PS destinationPs, String destinationDesc, int delaySeconds) throws TeleporterException
{
getTeleportMixin().teleport(teleporteeId, destinationPs, destinationDesc, delaySeconds);
}
// -------------------------------------------- //
// STATIC EXPOSE: MESSAGE
// -------------------------------------------- //
public static boolean message(CommandSender sender, String message)
{
return getMessageMixin().message(sender, message);
}
public static boolean message(CommandSender sender, Collection<String> messages)
{
return getMessageMixin().message(sender, messages);
}
public static boolean message(CommandSender sender, String... messages)
{
return getMessageMixin().message(sender, messages);
}
public static boolean message(String senderId, String message)
{
return getMessageMixin().message(senderId, message);
}
public static boolean message(String senderId, Collection<String> messages)
{
return getMessageMixin().message(senderId, messages);
}
public static boolean message(String senderId, String... messages)
{
return getMessageMixin().message(senderId, messages);
}
public static boolean msg(CommandSender sender, String msg)
{
return getMessageMixin().msg(sender, msg);
}
public static boolean msg(CommandSender sender, String msg, Object... args)
{
return getMessageMixin().msg(sender, msg, args);
}
public static boolean msg(CommandSender sender, Collection<String> msgs)
{
return getMessageMixin().msg(sender, msgs);
}
public static boolean msg(String senderId, String msg)
{
return getMessageMixin().msg(senderId, msg);
}
public static boolean msg(String senderId, String msg, Object... args)
{
return getMessageMixin().msg(senderId, msg, args);
}
public static boolean msg(String senderId, Collection<String> msgs)
{
return getMessageMixin().msg(senderId, msgs);
}
// -------------------------------------------- //
// STATIC EXPOSE: KICK
// -------------------------------------------- //
public static boolean kick(CommandSender sender)
{
return getKickMixin().kick(sender);
}
public static boolean kick(String senderId)
{
return getKickMixin().kick(senderId);
}
public static boolean kick(CommandSender sender, String message)
{
return getKickMixin().kick(sender, message);
}
public static boolean kick(String senderId, String message)
{
return getKickMixin().kick(senderId, message);
}
}

View File

@@ -0,0 +1,10 @@
package com.massivecraft.mcore.mixin;
public interface PlayedMixin
{
public boolean isOnline(String senderId);
public boolean isOffline(String senderId);
public Long getFirstPlayed(String senderId);
public Long getLastPlayed(String senderId);
public boolean hasPlayedBefore(String senderId);
}

View File

@@ -0,0 +1,19 @@
package com.massivecraft.mcore.mixin;
public abstract class PlayedMixinAbstract implements PlayedMixin
{
@Override
public boolean isOffline(String senderId)
{
return !this.isOnline(senderId);
}
@Override
public boolean hasPlayedBefore(String senderId)
{
Long firstPlayed = this.getFirstPlayed(senderId);
return firstPlayed != null && firstPlayed != 0;
}
}

View File

@@ -0,0 +1,56 @@
package com.massivecraft.mcore.mixin;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import com.massivecraft.mcore.util.MUtil;
import com.massivecraft.mcore.util.SenderUtil;
public class PlayedMixinDefault extends PlayedMixinAbstract
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static PlayedMixinDefault i = new PlayedMixinDefault();
public static PlayedMixinDefault get() { return i; }
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public boolean isOnline(String senderId)
{
if (senderId == null) return false;
CommandSender sender = SenderUtil.getSender(senderId);
return sender != null;
}
@Override
public Long getFirstPlayed(String senderId)
{
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(senderId);
Long ret = offlinePlayer.getFirstPlayed();
if (ret == 0) ret = null;
return ret;
}
@Override
public Long getLastPlayed(String senderId)
{
if (this.isOnline(senderId)) return System.currentTimeMillis();
String playerNameCC = Mixin.reqFix(senderId);
if (playerNameCC == null) return null;
File playerFile = new File(MUtil.getPlayerDirectory(), playerNameCC+".dat");
long lastModified = playerFile.lastModified();
if (lastModified == 0) return null;
return lastModified;
}
}

View File

@@ -0,0 +1,118 @@
package com.massivecraft.mcore.mixin;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.massivecraft.mcore.MCore;
import com.massivecraft.mcore.PS;
public class ScheduledTeleport implements Runnable
{
// -------------------------------------------- //
// CONSTANTS
// -------------------------------------------- //
public final static transient int NON_SCHEDULED_TASK_ID = -1;
// -------------------------------------------- //
// STATIC INDEX
// -------------------------------------------- //
public static Map<Player, ScheduledTeleport> teleporteeToScheduledTeleport = new ConcurrentHashMap<Player, ScheduledTeleport>();
public static void schedule(ScheduledTeleport scheduledTeleport)
{
if (isScheduled(scheduledTeleport)) return;
Bukkit.getScheduler().scheduleSyncDelayedTask(MCore.get(), scheduledTeleport, scheduledTeleport.getDelaySeconds()*20);
}
public static boolean isScheduled(ScheduledTeleport scheduledTeleport)
{
return teleporteeToScheduledTeleport.containsKey(scheduledTeleport.getTeleportee());
}
// -------------------------------------------- //
// FIELDS & RAW-DATA ACCESS
// -------------------------------------------- //
private final Player teleportee;
public Player getTeleportee() { return this.teleportee; }
private final PS destinationPs;
public PS getDestinationPs() { return this.destinationPs; }
private final String destinationDesc;
public String getDestinationDesc() { return this.destinationDesc; }
private final int delaySeconds;
public int getDelaySeconds() { return this.delaySeconds; }
private int taskId;
public int getTaskId() { return this.taskId; }
// -------------------------------------------- //
// CONSTRUCT
// -------------------------------------------- //
public ScheduledTeleport(Player teleportee, PS destinationPs, String destinationDesc, int delaySeconds)
{
this.teleportee = teleportee;
this.destinationPs = destinationPs;
this.destinationDesc = destinationDesc;
this.delaySeconds = delaySeconds;
this.taskId = NON_SCHEDULED_TASK_ID;
}
// -------------------------------------------- //
// SCHEDULING
// -------------------------------------------- //
public boolean isScheduled()
{
return this.taskId != NON_SCHEDULED_TASK_ID;
}
public ScheduledTeleport schedule()
{
ScheduledTeleport old = teleporteeToScheduledTeleport.get(this.getTeleportee());
if (old != null) old.unschedule();
teleporteeToScheduledTeleport.put(this.getTeleportee(), this);
this.taskId = Bukkit.getScheduler().scheduleSyncDelayedTask(MCore.get(), this, this.getDelaySeconds()*20);
return old;
}
public boolean unschedule()
{
Bukkit.getScheduler().cancelTask(this.getTaskId());
this.taskId = NON_SCHEDULED_TASK_ID;
return teleporteeToScheduledTeleport.remove(this.getTeleportee()) != null;
}
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public void run()
{
this.unschedule();
if (!teleportee.isOnline()) return;
try
{
Mixin.teleport(this.teleportee, this.destinationPs, this.destinationDesc);
}
catch (TeleporterException e)
{
this.teleportee.sendMessage(e.getMessage());
}
}
}

View File

@@ -0,0 +1,51 @@
package com.massivecraft.mcore.mixin;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import com.massivecraft.mcore.MCore;
import com.massivecraft.mcore.util.MUtil;
public class ScheduledTeleportListener implements Listener
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static ScheduledTeleportListener i = new ScheduledTeleportListener();
public static ScheduledTeleportListener get() { return i; }
// -------------------------------------------- //
// SETUP
// -------------------------------------------- //
public void setup()
{
Bukkit.getPluginManager().registerEvents(this, MCore.get());
}
// -------------------------------------------- //
// LISTENER
// -------------------------------------------- //
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerMoved(PlayerMoveEvent event)
{
// If the player moved from one block to another ...
if (MUtil.isSameBlock(event.getFrom(), event.getTo())) return;
// ... and there is a ScheduledTeleport ...
ScheduledTeleport scheduledTeleport = ScheduledTeleport.teleporteeToScheduledTeleport.get(event.getPlayer());
if (scheduledTeleport == null) return;
// ... unschedule it ...
scheduledTeleport.unschedule();
// ... and inform the teleportee.
Mixin.msg(scheduledTeleport.getTeleportee(), "<rose>Cancelled <i>teleport to <h>"+scheduledTeleport.getDestinationDesc()+"<i>.");
}
}

View File

@@ -0,0 +1,22 @@
package com.massivecraft.mcore.mixin;
import java.util.Set;
public interface SenderIdMixin
{
// Q: What do you mean "fix" a senderId?
// A: A senderId is case insensitive. However a certain caseing may be the best looking one. Player do for example have an optimal caseing.
public String reqFix(String senderId);
public String tryFix(String senderId);
public boolean canFix(String senderId);
// These may be unmodifiable. Don't expect them to be changeable.
public Set<String> getAllSenderIds();
public Set<String> getOnlineSenderIds();
public Set<String> getOfflineSenderIds();
public Set<String> getAllPlayerIds();
public Set<String> getOnlinePlayerIds();
public Set<String> getOfflinePlayerIds();
}

View File

@@ -0,0 +1,18 @@
package com.massivecraft.mcore.mixin;
public abstract class SenderIdMixinAbstract implements SenderIdMixin
{
@Override
public String tryFix(String senderId)
{
String ret = this.reqFix(senderId);
if (ret != null) return ret;
return senderId;
}
@Override
public boolean canFix(String senderId)
{
return this.reqFix(senderId) != null;
}
}

View File

@@ -0,0 +1,232 @@
package com.massivecraft.mcore.mixin;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import com.massivecraft.mcore.MCore;
import com.massivecraft.mcore.event.MCorePlayerLeaveEvent;
import com.massivecraft.mcore.event.MCoreSenderRegisterEvent;
import com.massivecraft.mcore.event.MCoreSenderUnregisterEvent;
import com.massivecraft.mcore.util.MUtil;
import com.massivecraft.mcore.util.SenderUtil;
import com.massivecraft.mcore.util.Txt;
public class SenderIdMixinDefault extends SenderIdMixinAbstract implements Listener
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static SenderIdMixinDefault i = new SenderIdMixinDefault();
public static SenderIdMixinDefault get() { return i; }
// -------------------------------------------- //
// SETUP
// -------------------------------------------- //
public void setup()
{
long start = System.currentTimeMillis();
// Create new empty sets
this.allSenderIds = new ConcurrentSkipListMap<String, String>(String.CASE_INSENSITIVE_ORDER);
this.onlineSenderIds = new ConcurrentSkipListSet<String>(String.CASE_INSENSITIVE_ORDER);
this.offlineSenderIds = new ConcurrentSkipListSet<String>(String.CASE_INSENSITIVE_ORDER);
this.allPlayerIds = new ConcurrentSkipListSet<String>(String.CASE_INSENSITIVE_ORDER);
this.onlinePlayerIds = new ConcurrentSkipListSet<String>(String.CASE_INSENSITIVE_ORDER);
this.offlinePlayerIds = new ConcurrentSkipListSet<String>(String.CASE_INSENSITIVE_ORDER);
// Add online players
for (Player player : Bukkit.getOnlinePlayers())
{
String id = player.getName();
this.allSenderIds.put(id, id);
this.allPlayerIds.add(id);
this.onlineSenderIds.add(id);
this.onlinePlayerIds.add(id);
}
// Add offline players
for (String id : MUtil.getPlayerDirectoryNames())
{
// Check if this player was added already since it's online
if (this.onlinePlayerIds.contains(id)) continue;
this.allSenderIds.put(id, id);
this.allPlayerIds.add(id);
this.offlineSenderIds.add(id);
this.offlinePlayerIds.add(id);
}
// Add command senders
for (String id : SenderUtil.getIdToSender().keySet())
{
this.allSenderIds.put(id, id);
this.onlineSenderIds.add(id);
}
Bukkit.getServer().getPluginManager().registerEvents(this, MCore.p);
long end = System.currentTimeMillis();
MCore.get().log(Txt.parse("<i>Setup of SenderIdMixinDefault took <h>%d<i>ms.", end-start));
}
// -------------------------------------------- //
// FIELDS
// -------------------------------------------- //
// The first field is a map since we use it for the "try" methods.
protected Map<String, String> allSenderIds;
protected Set<String> onlineSenderIds;
protected Set<String> offlineSenderIds;
protected Set<String> allPlayerIds;
protected Set<String> onlinePlayerIds;
protected Set<String> offlinePlayerIds;
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
protected void onOnlineChanged(CommandSender sender, boolean isOnline)
{
boolean isPlayer = SenderUtil.isPlayer(sender);
String id = SenderUtil.getSenderId(sender);
this.allSenderIds.put(id, id);
if (isPlayer)
{
this.allPlayerIds.add(id);
}
if (isOnline)
{
this.onlineSenderIds.add(id);
this.offlineSenderIds.remove(id);
if (isPlayer)
{
this.onlinePlayerIds.add(id);
this.offlinePlayerIds.remove(id);
}
}
else
{
this.offlineSenderIds.add(id);
this.onlineSenderIds.remove(id);
if (isPlayer)
{
this.offlinePlayerIds.add(id);
this.onlinePlayerIds.remove(id);
}
}
}
// -------------------------------------------- //
// LISTENER
// -------------------------------------------- //
// We don't care if it's cancelled or not.
// We just wan't to make sure this id is known of and can be "fixed" asap.
// Online or not? We just use the mixin to get the actuall value.
@EventHandler(priority = EventPriority.LOWEST)
public void playerLoginLowest(PlayerLoginEvent event)
{
boolean isOnline = Mixin.isOnline(SenderUtil.getSenderId(event.getPlayer()));
this.onOnlineChanged(event.getPlayer(), isOnline);
}
// Can't be cancelled
@EventHandler(priority = EventPriority.LOWEST)
public void playerJoinLowest(PlayerJoinEvent event)
{
this.onOnlineChanged(event.getPlayer(), true);
}
// Can't be cancelled
@EventHandler(priority = EventPriority.LOWEST)
public void senderRegisterLowest(MCoreSenderRegisterEvent event)
{
this.onOnlineChanged(event.getSender(), true);
}
// Can't be cancelled
@EventHandler(priority = EventPriority.MONITOR)
public void playerLeaveMonitor(MCorePlayerLeaveEvent event)
{
this.onOnlineChanged(event.getPlayer(), false);
}
// Can't be cancelled
@EventHandler(priority = EventPriority.MONITOR)
public void senderUnregisterLowest(MCoreSenderUnregisterEvent event)
{
this.onOnlineChanged(event.getSender(), false);
}
// -------------------------------------------- //
// OVERRIDE: FIX
// -------------------------------------------- //
@Override
public String reqFix(String senderId)
{
return this.allSenderIds.get(senderId);
}
// -------------------------------------------- //
// OVERRIDE: SETS
// -------------------------------------------- //
@Override
public Set<String> getAllSenderIds()
{
return Collections.unmodifiableSet(this.allSenderIds.keySet());
}
@Override
public Set<String> getOnlineSenderIds()
{
return Collections.unmodifiableSet(this.onlineSenderIds);
}
@Override
public Set<String> getOfflineSenderIds()
{
return Collections.unmodifiableSet(this.offlineSenderIds);
}
@Override
public Set<String> getAllPlayerIds()
{
return Collections.unmodifiableSet(this.allPlayerIds);
}
@Override
public Set<String> getOnlinePlayerIds()
{
return Collections.unmodifiableSet(this.onlinePlayerIds);
}
@Override
public Set<String> getOfflinePlayerIds()
{
return Collections.unmodifiableSet(this.offlinePlayerIds);
}
}

View File

@@ -0,0 +1,9 @@
package com.massivecraft.mcore.mixin;
import com.massivecraft.mcore.PS;
public interface SenderPsMixin
{
public PS getSenderPs(String senderId);
public void setSenderPs(String senderId, PS ps);
}

View File

@@ -0,0 +1,6 @@
package com.massivecraft.mcore.mixin;
public abstract class SenderPsMixinAbstract implements SenderPsMixin
{
}

View File

@@ -0,0 +1,34 @@
package com.massivecraft.mcore.mixin;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.massivecraft.mcore.PS;
public class SenderPsMixinDefault extends SenderPsMixinAbstract
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static SenderPsMixinDefault i = new SenderPsMixinDefault();
public static SenderPsMixinDefault get() { return i; }
// -------------------------------------------- //
// OVERRIDE
// -------------------------------------------- //
@Override
public PS getSenderPs(String senderId)
{
Player player = Bukkit.getPlayerExact(senderId);
if (player == null) return null;
return new PS(player.getLocation());
}
@Override
public void setSenderPs(String senderId, PS ps)
{
// Bukkit does not support setting the physical state for offline players for now.
}
}

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