In progress: Using MassiveCraftCore and Allman indentation style and minor refactoring.

This commit is contained in:
Olof Larsson
2011-10-08 22:03:44 +02:00
parent 61998f459d
commit 0ce9cce9d3
75 changed files with 4605 additions and 2033 deletions

View File

@@ -0,0 +1,51 @@
package com.massivecraft.factions.zcore.util;
import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class ClassLoadHack {
private static URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
public static boolean load(String filename)
{
return load(new File(filename));
}
public static boolean load(File file)
{
try
{
return load(file.toURI().toURL());
}
catch (MalformedURLException e)
{
return false;
}
}
public static boolean load(URL url)
{
// If the file already is loaded we can skip it
for (URL otherUrl : sysloader.getURLs())
{
if (otherUrl.sameFile(url)) return true;
}
try
{
Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{ URL.class });
addURLMethod.setAccessible(true);
addURLMethod.invoke(sysloader, new Object[]{ url });
return true;
}
catch (Exception e)
{
return false;
}
}
}

View File

@@ -0,0 +1,78 @@
package com.massivecraft.factions.zcore.util;
import java.io.*;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
public class DiscUtil
{
public static void write(File file, String content) throws IOException
{
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF8"));
out.write(content);
out.close();
}
public static String read(File file) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String ret = new String(new byte[0], "UTF-8");
String line;
while ((line = in.readLine()) != null)
{
ret += line;
}
in.close();
return ret;
}
public static boolean writeCatch(File file, String content)
{
try
{
write(file, content);
return true;
}
catch (Exception e)
{
return false;
}
}
public static String readCatch(File file)
{
try
{
return read(file);
}
catch (IOException e)
{
return null;
}
}
public static boolean downloadUrl(String urlstring, File file)
{
try
{
URL url = new URL(urlstring);
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream(file);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
public static boolean downloadUrl(String urlstring, String filename)
{
return downloadUrl(urlstring, new File(filename));
}
}

View File

@@ -0,0 +1,50 @@
package com.massivecraft.factions.zcore.util;
import java.io.File;
import com.massivecraft.factions.zcore.MPlugin;
public class LibLoader
{
MPlugin p;
public LibLoader(MPlugin p)
{
this.p = p;
new File("./lib").mkdirs();
}
public boolean require(String filename, String url)
{
if ( ! include(filename, url))
{
p.log("Failed to load the required library "+filename);
p.suicide();
return false;
}
return true;
}
public boolean include (String filename, String url)
{
File file = getFile(filename);
if ( ! file.exists())
{
p.log("Downloading library "+filename);
if ( ! DiscUtil.downloadUrl(url, file))
{
p.log("Failed to download "+filename);
return false;
}
}
return ClassLoadHack.load(file);
}
private static File getFile(String filename)
{
return new File("./lib/"+filename);
}
}

View File

@@ -0,0 +1,128 @@
package com.massivecraft.factions.zcore.util;
import java.util.*;
import java.util.Map.Entry;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin;
import ru.tehkode.permissions.PermissionManager;
import ru.tehkode.permissions.bukkit.PermissionsEx;
import com.massivecraft.factions.zcore.MPlugin;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
public class PermUtil {
public PermissionManager pex = null;
public PermissionHandler perm2or3 = null;
public Map<String, String> permissionDescriptions = new HashMap<String, String>();
protected MPlugin p;
public PermUtil(MPlugin p)
{
this.p = p;
this.setup();
}
public String getForbiddenMessage(String perm)
{
return p.txt.get("perm.forbidden", getPermissionDescription(perm));
}
/**
* This method hooks into all permission plugins we are supporting
*/
public void setup()
{
for(Permission permission : p.getDescription().getPermissions())
{
this.permissionDescriptions.put(permission.getName(), permission.getDescription());
}
if ( Bukkit.getServer().getPluginManager().isPluginEnabled("PermissionsEx"))
{
pex = PermissionsEx.getPermissionManager();
p.log("Will use this plugin for permissions: " + Bukkit.getServer().getPluginManager().getPlugin("PermissionsEx").getDescription().getFullName());
return;
}
if ( Bukkit.getServer().getPluginManager().isPluginEnabled("Permissions"))
{
Plugin permissionsPlugin = Bukkit.getServer().getPluginManager().getPlugin("Permissions");
perm2or3 = ((Permissions) permissionsPlugin).getHandler();
p.log("Will use this plugin for permissions: " + permissionsPlugin.getDescription().getFullName());
return;
}
p.log("No permission plugin detected. Defaulting to native bukkit permissions.");
}
public String getPermissionDescription (String perm)
{
String desc = permissionDescriptions.get(perm);
if (desc == null)
{
return p.txt.get("perm.dothat");
}
return desc;
}
/**
* This method tests if me has a certain permission and returns
* true if me has. Otherwise false
*/
public boolean has (CommandSender me, String perm)
{
if ( ! (me instanceof Player))
{
return me.hasPermission(perm);
}
if (pex != null)
{
return pex.has((Player)me, perm);
}
if (perm2or3 != null)
{
return perm2or3.has((Player)me, perm);
}
return me.hasPermission(perm);
}
public boolean has (CommandSender me, String perm, boolean informSenderIfNot)
{
if (has(me, perm))
{
return true;
}
else if (informSenderIfNot)
{
me.sendMessage(this.getForbiddenMessage(perm));
}
return false;
}
public <T> T pickFirstVal(CommandSender me, Map<String, T> perm2val)
{
if (perm2val == null) return null;
T ret = null;
for ( Entry<String, T> entry : perm2val.entrySet())
{
ret = entry.getValue();
if (has(me, entry.getKey())) break;
}
return ret;
}
}

View File

@@ -0,0 +1,154 @@
package com.massivecraft.factions.zcore.util;
import java.io.File;
import java.lang.reflect.Type;
import java.util.logging.Level;
import com.massivecraft.factions.zcore.MPlugin;
// TODO: Give better name and place to differenciate from the entity-orm-ish system in "com.massivecraft.core.persist".
public class Persist {
private MPlugin p;
public Persist(MPlugin p)
{
this.p = p;
}
// ------------------------------------------------------------ //
// GET NAME - What should we call this type of object?
// ------------------------------------------------------------ //
public static String getName(Class<?> clazz)
{
return clazz.getSimpleName().toLowerCase();
}
public static String getName(Object o)
{
return getName(o.getClass());
}
public static String getName(Type type)
{
return getName(type.getClass());
}
// ------------------------------------------------------------ //
// GET FILE - In which file would we like to store this object?
// ------------------------------------------------------------ //
public File getFile(String name)
{
return new File(p.getDataFolder(), name+".json");
}
public File getFile(Class<?> clazz)
{
return getFile(getName(clazz));
}
public File getFile(Object obj)
{
return getFile(getName(obj));
}
public File getFile(Type type)
{
return getFile(getName(type));
}
// NICE WRAPPERS
public <T> T loadOrSaveDefault(T def, Class<T> clazz)
{
return loadOrSaveDefault(def, clazz, getFile(clazz));
}
public <T> T loadOrSaveDefault(T def, Class<T> clazz, String name)
{
return loadOrSaveDefault(def, clazz, getFile(name));
}
public <T> T loadOrSaveDefault(T def, Class<T> clazz, File file)
{
if ( ! file.exists())
{
p.log("Creating default: "+file);
this.save(def, file);
return def;
}
T loaded = this.load(clazz, file);
if (loaded == null)
{
p.log(Level.WARNING, "Using default as I failed to load: "+file);
return def;
}
return loaded;
}
// SAVE
public boolean save(Object instance)
{
return save(instance, getFile(instance));
}
public boolean save(Object instance, String name)
{
return save(instance, getFile(name));
}
public boolean save(Object instance, File file)
{
return DiscUtil.writeCatch(file, p.gson.toJson(instance));
}
// LOAD BY CLASS
public <T> T load(Class<T> clazz)
{
return load(clazz, getFile(clazz));
}
public <T> T load(Class<T> clazz, String name)
{
return load(clazz, getFile(name));
}
public <T> T load(Class<T> clazz, File file)
{
String content = DiscUtil.readCatch(file);
if (content == null)
{
return null;
}
T instance = p.gson.fromJson(content, clazz);
return instance;
}
// LOAD BY TYPE
public <T> T load(Type typeOfT, String name)
{
return load(typeOfT, getFile(name));
}
public <T> T load(Type typeOfT, File file)
{
String content = DiscUtil.readCatch(file);
if (content == null) {
return null;
}
return p.gson.fromJson(content, typeOfT);
}
}

View File

@@ -0,0 +1,245 @@
package com.massivecraft.factions.zcore.util;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.ChatColor;
import org.bukkit.Material;
public class TextUtil
{
private Map<String, String> tags = new HashMap<String, String>();
private Map<String, String> lang = new HashMap<String, String>();
public TextUtil(Map<String, String> tags, Map<String, String> lang)
{
if (tags != null)
{
this.tags.putAll(tags);
}
if (lang != null)
{
this.lang.putAll(lang);
}
}
// Get is supposed to be the way we reach registered lang
// TODO: Is the parse
public String get(String name)
{
String str = lang.get(name);
if (str == null) str = name;
return this.parse(str);
}
public String get(String name, Object... args)
{
String str = lang.get(name);
if (str == null) str = name;
return this.parse(str, args);
}
// Parse is used to handle non registered text
public String parse(String str, Object... args)
{
return String.format(this.tags(str), args);
}
public String parse(String str)
{
return this.tags(str);
}
public Map<String, String> getTags()
{
return tags;
}
public Map<String, String> getLang()
{
return lang;
}
public String tags(String str)
{
return replaceTags(str, this.tags);
}
public static final transient Pattern patternTag = Pattern.compile("<([^<>]*)>");
public static String replaceTags(String str, Map<String, String> tags)
{
StringBuffer ret = new StringBuffer();
Matcher matcher = patternTag.matcher(str);
while (matcher.find())
{
String tag = matcher.group(1);
String repl = tags.get(tag);
if (repl == null)
{
matcher.appendReplacement(ret, "<"+tag+">");
}
else
{
matcher.appendReplacement(ret, repl);
}
}
matcher.appendTail(ret);
return ret.toString();
}
public static String implode(List<String> list, String glue)
{
StringBuilder ret = new StringBuilder();
for (int i=0; i<list.size(); i++)
{
if (i!=0)
{
ret.append(glue);
}
ret.append(list.get(i));
}
return ret.toString();
}
public static String repeat(String s, int times)
{
if (times <= 0) return "";
else return s + repeat(s, times-1);
}
public static String getMaterialName(Material material)
{
return material.toString().replace('_', ' ').toLowerCase();
}
public static String getMaterialName(int materialId)
{
return getMaterialName(Material.getMaterial(materialId));
}
public static String upperCaseFirst(String string)
{
return string.substring(0, 1).toUpperCase()+string.substring(1);
}
// TODO: Make part of layout configuration.
private final static String titleizeLine = repeat("_", 52);
private final static int titleizeBalance = -1;
public String titleize(String str)
{
String center = ".[ "+ tags("<l>") + str + tags("<a>")+ " ].";
int centerlen = ChatColor.stripColor(center).length();
int pivot = titleizeLine.length() / 2;
int eatLeft = (centerlen / 2) - titleizeBalance;
int eatRight = (centerlen - eatLeft) + titleizeBalance;
if (eatLeft < pivot)
return tags("<a>")+titleizeLine.substring(0, pivot - eatLeft) + center + titleizeLine.substring(pivot + eatRight);
else
return tags("<a>")+center;
}
public ArrayList<String> getPage(List<String> lines, int pageHumanBased, String title)
{
ArrayList<String> ret = new ArrayList<String>();
int pageZeroBased = pageHumanBased - 1;
int pageheight = 9;
int pagecount = (lines.size() / pageheight)+1;
ret.add(this.titleize(title+" "+pageHumanBased+"/"+pagecount));
if (pagecount == 0)
{
ret.add(this.tags("<i>Sorry. No Pages available."));
return ret;
}
else if (pageZeroBased < 0 || pageHumanBased > pagecount)
{
ret.add(this.tags("<i>Invalid page. Must be between 1 and "+pagecount));
return ret;
}
int from = pageZeroBased * pageheight;
int to = from+pageheight;
if (to > lines.size())
{
to = lines.size();
}
ret.addAll(lines.subList(from, to));
return ret;
}
/**
* Using this function you transform a delta in milliseconds
* to a String like "2 weeks from now" or "7 days ago".
*/
public static final long millisPerSecond = 1000;
public static final long millisPerMinute = 60 * millisPerSecond;
public static final long millisPerHour = 60 * millisPerMinute;
public static final long millisPerDay = 24 * millisPerHour;
public static final long millisPerWeek = 7 * millisPerDay;
public static final long millisPerMonth = 31 * millisPerDay;
public static final long millisPerYear = 365 * millisPerDay;
public static String getTimeDeltaDescriptionRelNow(long millis)
{
double absmillis = (double) Math.abs(millis);
String agofromnow = "from now";
String unit;
long num;
if (millis <= 0)
{
agofromnow = "ago";
}
// We use a factor 3 below for a reason... why do you think?
// Answer: it is a way to make our round of error smaller.
if (absmillis < 3 * millisPerSecond)
{
unit = "milliseconds";
num = (long) (absmillis);
}
else if (absmillis < 3 * millisPerMinute)
{
unit = "seconds";
num = (long) (absmillis / millisPerSecond);
}
else if (absmillis < 3 * millisPerHour)
{
unit = "minutes";
num = (long) (absmillis / millisPerMinute);
}
else if (absmillis < 3 * millisPerDay)
{
unit = "hours";
num = (long) (absmillis / millisPerHour);
}
else if (absmillis < 3 * millisPerWeek)
{
unit = "days";
num = (long) (absmillis / millisPerDay);
}
else if (absmillis < 3 * millisPerMonth)
{
unit = "weeks";
num = (long) (absmillis / millisPerWeek);
}
else if (absmillis < 3 * millisPerYear)
{
unit = "months";
num = (long) (absmillis / millisPerMonth);
}
else
{
unit = "years";
num = (long) (absmillis / millisPerYear);
}
return ""+num+" "+unit+" "+agofromnow;
}
}

View File

@@ -0,0 +1,39 @@
package com.massivecraft.factions.zcore.util;
import java.io.File;
import org.bukkit.Bukkit;
public class WorldUtil
{
// Previously We had crappy support for multiworld management.
// This should however be handled by an external plugin!
/*public static boolean load(String name) {
if (isWorldLoaded(name)) {
return true;
}
if ( ! doesWorldExist(name)) {
return false;
}
Environment env = WorldEnv.get(name);
if (env == null) {
P.log(Level.WARNING, "Failed to load world. Environment was unknown.");
return false;
}
P.p.getServer().createWorld(name, env);
return true;
}*/
public static boolean isWorldLoaded(String name)
{
return Bukkit.getServer().getWorld(name) != null;
}
public static boolean doesWorldExist(String name)
{
return new File(name, "level.dat").exists();
}
}