More Txt.

This commit is contained in:
Olof Larsson 2013-04-10 10:45:47 +02:00
parent f6aa6f63ac
commit 262ec248f5
13 changed files with 37 additions and 459 deletions

View File

@ -15,7 +15,6 @@ import com.massivecraft.mcore.xlib.gson.reflect.TypeToken;
import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.util.MiscUtil; import com.massivecraft.factions.util.MiscUtil;
import com.massivecraft.factions.zcore.persist.EntityCollection; import com.massivecraft.factions.zcore.persist.EntityCollection;
import com.massivecraft.factions.zcore.util.TextUtil;
public class FactionColl extends EntityCollection<Faction> public class FactionColl extends EntityCollection<Faction>
{ {
@ -253,7 +252,7 @@ public class FactionColl extends EntityCollection<Faction>
tag2faction.put(ChatColor.stripColor(faction.getTag()), faction); tag2faction.put(ChatColor.stripColor(faction.getTag()), faction);
} }
String tag = TextUtil.getBestStartWithCI(tag2faction.keySet(), searchFor); String tag = Txt.getBestCIStart(tag2faction.keySet(), searchFor);
if (tag == null) return null; if (tag == null) return null;
return tag2faction.get(tag); return tag2faction.get(tag);
} }

View File

@ -1,6 +1,8 @@
package com.massivecraft.factions; package com.massivecraft.factions;
import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible;
import com.massivecraft.mcore.util.PermUtil;
public enum Perm public enum Perm
{ {
@ -89,13 +91,14 @@ public enum Perm
// HAS // HAS
// -------------------------------------------- // // -------------------------------------------- //
public boolean has(CommandSender sender, boolean informSenderIfNot) public boolean has(Permissible permissible, boolean informSenderIfNot)
{ {
return Factions.get().perm.has(sender, this.node, informSenderIfNot); return PermUtil.has(permissible, this.node, informSenderIfNot);
} }
public boolean has(CommandSender sender) public boolean has(Permissible permissible)
{ {
return has(sender, false); return has(permissible, false);
} }
} }

View File

@ -8,7 +8,7 @@ import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Perm; import com.massivecraft.factions.Perm;
import com.massivecraft.factions.TerritoryAccess; import com.massivecraft.factions.TerritoryAccess;
import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.integration.SpoutFeatures;
import com.massivecraft.factions.zcore.util.TextUtil; import com.massivecraft.mcore.util.Txt;
public class CmdAccess extends FCommand public class CmdAccess extends FCommand
@ -88,14 +88,14 @@ public class CmdAccess extends FCommand
target = "Faction \""+targetFaction.getTag()+"\""; target = "Faction \""+targetFaction.getTag()+"\"";
} }
msg("<i>%s has been %s<i> the access list for this territory.", target, TextUtil.parseColor(added ? "<lime>added to" : "<rose>removed from")); msg("<i>%s has been %s<i> the access list for this territory.", target, Txt.parse(added ? "<lime>added to" : "<rose>removed from"));
SpoutFeatures.updateAccessInfoLoc(loc); SpoutFeatures.updateAccessInfoLoc(loc);
showAccessList(territory, locFaction); showAccessList(territory, locFaction);
} }
private void showAccessList(TerritoryAccess territory, Faction locFaction) private void showAccessList(TerritoryAccess territory, Faction locFaction)
{ {
msg("<i>Host faction %s has %s<i> in this territory.", locFaction.getTag(), TextUtil.parseColor(territory.isHostFactionAllowed() ? "<lime>normal access" : "<rose>restricted access")); msg("<i>Host faction %s has %s<i> in this territory.", locFaction.getTag(), Txt.parse(territory.isHostFactionAllowed() ? "<lime>normal access" : "<rose>restricted access"));
String players = territory.fplayerList(); String players = territory.fplayerList();
String factions = territory.factionList(); String factions = territory.factionList();

View File

@ -4,7 +4,7 @@ import com.massivecraft.factions.ConfServer;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayerColl; import com.massivecraft.factions.FPlayerColl;
import com.massivecraft.factions.Perm; import com.massivecraft.factions.Perm;
import com.massivecraft.factions.zcore.util.TextUtil; import com.massivecraft.mcore.util.Txt;
public class CmdDescription extends FCommand public class CmdDescription extends FCommand
{ {
@ -32,7 +32,8 @@ public class CmdDescription extends FCommand
// if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay
if ( ! payForCommand(ConfServer.econCostDesc, "to change faction description", "for changing faction description")) return; if ( ! payForCommand(ConfServer.econCostDesc, "to change faction description", "for changing faction description")) return;
myFaction.setDescription(TextUtil.implode(args, " ").replaceAll("(&([a-f0-9]))", "& $2")); // since "&" color tags seem to work even through plain old FPlayer.sendMessage() for some reason, we need to break those up // TODO: This must be an invalid replace-approach. The call order is wrong somehow?
myFaction.setDescription(Txt.implode(args, " ").replaceAll("(&([a-f0-9]))", "& $2")); // since "&" color tags seem to work even through plain old FPlayer.sendMessage() for some reason, we need to break those up
if ( ! ConfServer.broadcastDescriptionChanges) if ( ! ConfServer.broadcastDescriptionChanges)
{ {

View File

@ -12,7 +12,6 @@ import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Perm; import com.massivecraft.factions.Perm;
import com.massivecraft.factions.Rel; import com.massivecraft.factions.Rel;
import com.massivecraft.factions.zcore.util.TextUtil;
import com.massivecraft.mcore.util.Txt; import com.massivecraft.mcore.util.Txt;
public class CmdShow extends FCommand public class CmdShow extends FCommand
@ -103,11 +102,11 @@ public class CmdShow extends FCommand
} }
else else
{ {
sendMessage(Txt.parse("<a>In Truce with: ") + TextUtil.implode(relationTags.get(Rel.TRUCE), sepparator)); sendMessage(Txt.parse("<a>In Truce with: ") + Txt.implode(relationTags.get(Rel.TRUCE), sepparator));
} }
sendMessage(Txt.parse("<a>Allied to: ") + TextUtil.implode(relationTags.get(Rel.ALLY), sepparator)); sendMessage(Txt.parse("<a>Allied to: ") + Txt.implode(relationTags.get(Rel.ALLY), sepparator));
sendMessage(Txt.parse("<a>Enemies: ") + TextUtil.implode(relationTags.get(Rel.ENEMY), sepparator)); sendMessage(Txt.parse("<a>Enemies: ") + Txt.implode(relationTags.get(Rel.ENEMY), sepparator));
// List the members... // List the members...
List<String> memberOnlineNames = new ArrayList<String>(); List<String> memberOnlineNames = new ArrayList<String>();
@ -160,8 +159,8 @@ public class CmdShow extends FCommand
memberOfflineNames.add(follower.getNameAndTitle(fme)); memberOfflineNames.add(follower.getNameAndTitle(fme));
} }
} }
sendMessage(Txt.parse("<a>Members online: ") + TextUtil.implode(memberOnlineNames, sepparator)); sendMessage(Txt.parse("<a>Members online: ") + Txt.implode(memberOnlineNames, sepparator));
sendMessage(Txt.parse("<a>Members offline: ") + TextUtil.implode(memberOfflineNames, sepparator)); sendMessage(Txt.parse("<a>Members offline: ") + Txt.implode(memberOfflineNames, sepparator));
} }
} }

View File

@ -4,7 +4,7 @@ import com.massivecraft.factions.ConfServer;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Perm; import com.massivecraft.factions.Perm;
import com.massivecraft.factions.integration.SpoutFeatures; import com.massivecraft.factions.integration.SpoutFeatures;
import com.massivecraft.factions.zcore.util.TextUtil; import com.massivecraft.mcore.util.Txt;
public class CmdTitle extends FCommand public class CmdTitle extends FCommand
{ {
@ -31,7 +31,7 @@ public class CmdTitle extends FCommand
if (you == null) return; if (you == null) return;
args.remove(0); args.remove(0);
String title = TextUtil.implode(args, " "); String title = Txt.implode(args, " ");
if ( ! canIAdministerYou(fme, you)) return; if ( ! canIAdministerYou(fme, you)) return;

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.util;
import java.util.Map.Entry; import java.util.Map.Entry;
import com.massivecraft.factions.ConfServer; import com.massivecraft.factions.ConfServer;
import com.massivecraft.factions.zcore.util.TextUtil; import com.massivecraft.mcore.util.Txt;
public class HealthBarUtil public class HealthBarUtil
{ {
@ -22,13 +22,13 @@ public class HealthBarUtil
int emptyCount = (int) ((barLength - solidCount) / ConfServer.spoutHealthBarSolidsPerEmpty); int emptyCount = (int) ((barLength - solidCount) / ConfServer.spoutHealthBarSolidsPerEmpty);
// Create the non-parsed bar // Create the non-parsed bar
String ret = ConfServer.spoutHealthBarLeft + TextUtil.repeat(ConfServer.spoutHealthBarSolid, solidCount) + ConfServer.spoutHealthBarBetween + TextUtil.repeat(ConfServer.spoutHealthBarEmpty, emptyCount) + ConfServer.spoutHealthBarRight; String ret = ConfServer.spoutHealthBarLeft + Txt.repeat(ConfServer.spoutHealthBarSolid, solidCount) + ConfServer.spoutHealthBarBetween + Txt.repeat(ConfServer.spoutHealthBarEmpty, emptyCount) + ConfServer.spoutHealthBarRight;
// Replace color tag // Replace color tag
ret = ret.replace("{c}", color); ret = ret.replace("{c}", color);
// Parse amp color codes // Parse amp color codes
ret = TextUtil.parseColorAmp(ret); ret = Txt.parse(ret);
return ret; return ret;
} }

View File

@ -8,7 +8,7 @@ import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Rel; import com.massivecraft.factions.Rel;
import com.massivecraft.factions.iface.RelationParticipator; import com.massivecraft.factions.iface.RelationParticipator;
import com.massivecraft.factions.zcore.util.TextUtil; import com.massivecraft.mcore.util.Txt;
public class RelationUtil public class RelationUtil
{ {
@ -57,7 +57,7 @@ public class RelationUtil
if (ucfirst) if (ucfirst)
{ {
ret = TextUtil.upperCaseFirst(ret); ret = Txt.upperCaseFirst(ret);
} }
return "" + getColorOfThatToMe(that, me) + ret; return "" + getColorOfThatToMe(that, me) + ret;

View File

@ -9,7 +9,7 @@ import org.bukkit.entity.Player;
import com.massivecraft.factions.zcore.MCommand; import com.massivecraft.factions.zcore.MCommand;
import com.massivecraft.factions.zcore.MPlugin; import com.massivecraft.factions.zcore.MPlugin;
import com.massivecraft.factions.zcore.util.TextUtil; import com.massivecraft.mcore.util.PermUtil;
import com.massivecraft.mcore.util.Txt; import com.massivecraft.mcore.util.Txt;
@ -43,7 +43,7 @@ public abstract class MCommand<T extends MPlugin>
{ {
if (this.helpShort == null) if (this.helpShort == null)
{ {
String pdesc = p.perm.getPermissionDescription(this.permission); String pdesc = PermUtil.getDescription(permission);
if (pdesc != null) if (pdesc != null)
{ {
return pdesc; return pdesc;
@ -182,7 +182,7 @@ public abstract class MCommand<T extends MPlugin>
public boolean validSenderPermissions(CommandSender sender, boolean informSenderIfNot) public boolean validSenderPermissions(CommandSender sender, boolean informSenderIfNot)
{ {
if (this.permission == null) return true; if (this.permission == null) return true;
return p.perm.has(sender, this.permission, informSenderIfNot); return PermUtil.has(sender, this.permission, informSenderIfNot);
} }
public boolean validArgs(List<String> args, CommandSender sender) public boolean validArgs(List<String> args, CommandSender sender)
@ -203,7 +203,7 @@ public abstract class MCommand<T extends MPlugin>
{ {
// Get the to many string slice // Get the to many string slice
List<String> theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size()); List<String> theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size());
msg(Lang.commandToManyArgs, TextUtil.implode(theToMany, " ")); msg(Lang.commandToManyArgs, Txt.implode(theToMany, " "));
sender.sendMessage(this.getUseageTemplate()); sender.sendMessage(this.getUseageTemplate());
} }
return false; return false;
@ -227,11 +227,11 @@ public abstract class MCommand<T extends MPlugin>
for (MCommand<?> mc : commandChain) for (MCommand<?> mc : commandChain)
{ {
ret.append(TextUtil.implode(mc.aliases, ",")); ret.append(Txt.implode(mc.aliases, ","));
ret.append(' '); ret.append(' ');
} }
ret.append(TextUtil.implode(this.aliases, ",")); ret.append(Txt.implode(this.aliases, ","));
List<String> args = new ArrayList<String>(); List<String> args = new ArrayList<String>();
@ -257,7 +257,7 @@ public abstract class MCommand<T extends MPlugin>
if (args.size() > 0) if (args.size() > 0)
{ {
ret.append(Txt.parse("<p> ")); ret.append(Txt.parse("<p> "));
ret.append(TextUtil.implode(args, " ")); ret.append(Txt.implode(args, " "));
} }
if (addShortHelp) if (addShortHelp)

View File

@ -8,7 +8,6 @@ import org.bukkit.plugin.java.JavaPlugin;
import com.massivecraft.factions.zcore.persist.EM; import com.massivecraft.factions.zcore.persist.EM;
import com.massivecraft.factions.zcore.persist.SaveTask; import com.massivecraft.factions.zcore.persist.SaveTask;
import com.massivecraft.factions.zcore.util.PermUtil;
import com.massivecraft.factions.zcore.util.Persist; import com.massivecraft.factions.zcore.util.Persist;
import com.massivecraft.mcore.util.Txt; import com.massivecraft.mcore.util.Txt;
import com.massivecraft.mcore.xlib.gson.Gson; import com.massivecraft.mcore.xlib.gson.Gson;
@ -19,7 +18,6 @@ public abstract class MPlugin extends JavaPlugin
{ {
// Some utils // Some utils
public Persist persist; public Persist persist;
public PermUtil perm;
// Persist related // Persist related
public Gson gson; public Gson gson;
@ -45,7 +43,6 @@ public abstract class MPlugin extends JavaPlugin
this.getDataFolder().mkdirs(); this.getDataFolder().mkdirs();
// Create Utility Instances // Create Utility Instances
this.perm = new PermUtil(this);
this.persist = new Persist(this); this.persist = new Persist(this);
// GSON 2.1 is now embedded in CraftBukkit, used by the auto-updater: https://github.com/Bukkit/CraftBukkit/commit/0ed1d1fdbb1e0bc09a70bc7bfdf40c1de8411665 // GSON 2.1 is now embedded in CraftBukkit, used by the auto-updater: https://github.com/Bukkit/CraftBukkit/commit/0ed1d1fdbb1e0bc09a70bc7bfdf40c1de8411665

View File

@ -7,8 +7,8 @@ import java.util.logging.Level;
import java.util.Map.Entry; import java.util.Map.Entry;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import com.massivecraft.factions.zcore.util.TextUtil;
import com.massivecraft.mcore.util.DiscUtil; import com.massivecraft.mcore.util.DiscUtil;
import com.massivecraft.mcore.util.Txt;
import com.massivecraft.mcore.xlib.gson.Gson; import com.massivecraft.mcore.xlib.gson.Gson;
import com.massivecraft.mcore.xlib.gson.JsonSyntaxException; import com.massivecraft.mcore.xlib.gson.JsonSyntaxException;
@ -100,7 +100,8 @@ public abstract class EntityCollection<E extends Entity>
public E getBestIdMatch(String pattern) public E getBestIdMatch(String pattern)
{ {
String id = TextUtil.getBestStartWithCI(this.id2entity.keySet(), pattern); String id = Txt.getBestCIStart(this.id2entity.keySet(), pattern);
if (id == null) return null; if (id == null) return null;
return this.id2entity.get(id); return this.id2entity.get(id);
} }

View File

@ -1,97 +0,0 @@
package com.massivecraft.factions.zcore.util;
import java.util.*;
import java.util.Map.Entry;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import com.massivecraft.factions.zcore.Lang;
import com.massivecraft.factions.zcore.MPlugin;
import com.massivecraft.mcore.util.Txt;
public class PermUtil {
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 Txt.parse(Lang.permForbidden, getPermissionDescription(perm));
}
/**
* This method hooks into all permission plugins we are supporting
*/
public final void setup()
{
for(Permission permission : p.getDescription().getPermissions())
{
//p.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\"");
this.permissionDescriptions.put(permission.getName(), permission.getDescription());
}
}
public String getPermissionDescription (String perm)
{
String desc = permissionDescriptions.get(perm);
if (desc == null)
{
return Lang.permDoThat;
}
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 == null) return false;
if ( ! (me instanceof Player))
{
return me.hasPermission(perm);
}
return me.hasPermission(perm);
}
public boolean has (CommandSender me, String perm, boolean informSenderIfNot)
{
if (has(me, perm))
{
return true;
}
else if (informSenderIfNot && me != null)
{
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

@ -1,325 +0,0 @@
package com.massivecraft.factions.zcore.util;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.ChatColor;
import org.bukkit.Material;
public class TextUtil
{
public Map<String, String> tags;
public TextUtil()
{
this.tags = new HashMap<String, String>();
}
// -------------------------------------------- //
// Top-level parsing functions.
// -------------------------------------------- //
public String parse(String str, Object... args)
{
return String.format(this.parse(str), args);
}
public String parse(String str)
{
return this.parseTags(parseColor(str));
}
// -------------------------------------------- //
// Tag parsing
// -------------------------------------------- //
public String parseTags(String str)
{
return replaceTags(str, this.tags);
}
public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>");
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();
}
// -------------------------------------------- //
// Color parsing
// -------------------------------------------- //
public static String parseColor(String string)
{
string = parseColorAmp(string);
string = parseColorAcc(string);
string = parseColorTags(string);
return string;
}
public static String parseColorAmp(String string)
{
string = string.replaceAll("(§([a-z0-9]))", "\u00A7$2");
string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2");
string = string.replace("&&", "&");
return string;
}
public static String parseColorAcc(String string)
{
return string.replace("`e", "")
.replace("`r", ChatColor.RED.toString()) .replace("`R", ChatColor.DARK_RED.toString())
.replace("`y", ChatColor.YELLOW.toString()) .replace("`Y", ChatColor.GOLD.toString())
.replace("`g", ChatColor.GREEN.toString()) .replace("`G", ChatColor.DARK_GREEN.toString())
.replace("`a", ChatColor.AQUA.toString()) .replace("`A", ChatColor.DARK_AQUA.toString())
.replace("`b", ChatColor.BLUE.toString()) .replace("`B", ChatColor.DARK_BLUE.toString())
.replace("`p", ChatColor.LIGHT_PURPLE.toString()) .replace("`P", ChatColor.DARK_PURPLE.toString())
.replace("`k", ChatColor.BLACK.toString()) .replace("`s", ChatColor.GRAY.toString())
.replace("`S", ChatColor.DARK_GRAY.toString()) .replace("`w", ChatColor.WHITE.toString());
}
public static String parseColorTags(String string)
{
return string.replace("<empty>", "")
.replace("<black>", "\u00A70")
.replace("<navy>", "\u00A71")
.replace("<green>", "\u00A72")
.replace("<teal>", "\u00A73")
.replace("<red>", "\u00A74")
.replace("<purple>", "\u00A75")
.replace("<gold>", "\u00A76")
.replace("<silver>", "\u00A77")
.replace("<gray>", "\u00A78")
.replace("<blue>", "\u00A79")
.replace("<lime>", "\u00A7a")
.replace("<aqua>", "\u00A7b")
.replace("<rose>", "\u00A7c")
.replace("<pink>", "\u00A7d")
.replace("<yellow>", "\u00A7e")
.replace("<white>", "\u00A7f");
}
// -------------------------------------------- //
// Standard utils like UCFirst, implode and repeat.
// -------------------------------------------- //
public static String upperCaseFirst(String string)
{
return string.substring(0, 1).toUpperCase()+string.substring(1);
}
public static String repeat(String s, int times)
{
if (times <= 0) return "";
else return s + repeat(s, times-1);
}
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 implodeCommaAnd(List<String> list, String comma, String and)
{
if (list.size() == 0) return "";
if (list.size() == 1) return list.get(0);
String lastItem = list.get(list.size()-1);
String nextToLastItem = list.get(list.size()-2);
String merge = nextToLastItem+and+lastItem;
list.set(list.size()-2, merge);
list.remove(list.size()-1);
return implode(list, comma);
}
public static String implodeCommaAnd(List<String> list)
{
return implodeCommaAnd(list, ", ", " and ");
}
// -------------------------------------------- //
// Material name tools
// -------------------------------------------- //
public static String getMaterialName(Material material)
{
return material.toString().replace('_', ' ').toLowerCase();
}
public static String getMaterialName(int materialId)
{
return getMaterialName(Material.getMaterial(materialId));
}
// -------------------------------------------- //
// Paging and chrome-tools like titleize
// -------------------------------------------- //
private final static String titleizeLine = repeat("_", 52);
private final static int titleizeBalance = -1;
public String titleize(String str)
{
String center = ".[ "+ parseTags("<l>") + str + parseTags("<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 parseTags("<a>")+titleizeLine.substring(0, pivot - eatLeft) + center + titleizeLine.substring(pivot + eatRight);
else
return parseTags("<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.parseTags("<i>Sorry. No Pages available."));
return ret;
}
else if (pageZeroBased < 0 || pageHumanBased > pagecount)
{
ret.add(this.parseTags("<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;
}
// -------------------------------------------- //
// Describing Time
// -------------------------------------------- //
/**
* 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 Map<String, Long> unitMillis;
static
{
unitMillis = new LinkedHashMap<String, Long>();
unitMillis.put("years", millisPerYear);
unitMillis.put("months", millisPerMonth);
unitMillis.put("weeks", millisPerWeek);
unitMillis.put("days", millisPerDay);
unitMillis.put("hours", millisPerHour);
unitMillis.put("minutes", millisPerMinute);
unitMillis.put("seconds", millisPerSecond);
}
public static String getTimeDeltaDescriptionRelNow(long millis)
{
String ret = "";
double millisLeft = (double) Math.abs(millis);
List<String> unitCountParts = new ArrayList<String>();
for (Entry<String, Long> entry : unitMillis.entrySet())
{
if (unitCountParts.size() == 3 ) break;
String unitName = entry.getKey();
long unitSize = entry.getValue();
long unitCount = (long) Math.floor(millisLeft / unitSize);
if (unitCount < 1) continue;
millisLeft -= unitSize*unitCount;
unitCountParts.add(unitCount+" "+unitName);
}
if (unitCountParts.size() == 0) return "just now";
ret += implodeCommaAnd(unitCountParts);
ret += " ";
if (millis <= 0)
{
ret += "ago";
}
else
{
ret += "from now";
}
return ret;
}
// -------------------------------------------- //
// String comparison
// -------------------------------------------- //
public static String getBestStartWithCI(Collection<String> candidates, String start)
{
String ret = null;
int best = 0;
start = start.toLowerCase();
int minlength = start.length();
for (String candidate : candidates)
{
if (candidate.length() < minlength) continue;
if ( ! candidate.toLowerCase().startsWith(start)) continue;
// The closer to zero the better
int lendiff = candidate.length() - minlength;
if (lendiff == 0)
{
return candidate;
}
if (lendiff < best || best == 0)
{
best = lendiff;
ret = candidate;
}
}
return ret;
}
}