Changed to TranslationAPI

This commit is contained in:
Sauilitired 2014-11-08 22:47:45 +01:00
parent b15ccdc789
commit 0a6f2aa357
19 changed files with 927 additions and 108 deletions

View File

@ -21,6 +21,8 @@
package com.intellectualcrafters.plot;
import com.intellectualsites.translation.*;
import com.intellectualsites.translation.bukkit.BukkitTranslation;
import org.bukkit.ChatColor;
/**
@ -231,8 +233,30 @@ public enum C {
* Info
*/
PLOT_INFO_UNCLAIMED("&cPlot &6%s&c is not yet claimed"),
PLOT_INFO("&6ID&7: &a%id%&7\n&6Alias&7: &a%alias%\n&6Owner&7: &a%owner%\n&6Helpers&7: &a%helpers%\n&6Trusted&7: &a%trusted%\n&Denied&7: &a%denied%\n&6Denied&7: &a%denied%\n&6Flags&7: &a%flags%\n&6Biome&7: &a%biome%\n&6Rating&7: &a%rating%&7/&a10\n&6Can build&7: &a%build%"),
/*PLOT_INFO("" +
"&6ID&7: &a%id%&7\n" +
"&6Alias&7: &a%alias%\n" +
"&6Owner&7: &a%owner%\n" +
"&6Helpers&7: &a%helpers%\n" +
"&6Trusted&7: &a%trusted%\n" +
"&6Denied&7: &a%denied%\n" +
"&6Flags&7: &a%flags%\n" +
"&6Biome&7: &a%biome%\n" +
"&6Rating&7: &a%rating%&7/&a10\n" +
"&6Can build&7: &a%build%"
),*/
PLOT_INFO(
"&cID: &6%id%&c, " +
"&cAlias: &6%alias%&c, " +
"&cOwner: &6%owner%&c, " +
"&cBiome: &6%biome%&c, " +
"&cCan Build: &6%build%&c, " +
"&cRating: &6%rating%&c/&610&c, " +
"&cHelpers:&6%helpers%&c, " +
"&cTrusted:&6%trusted%&c, " +
"&cDenied:&6%denied%&c, " +
"&cFlags: &6%flags%"
),
PLOT_INFO_HELPERS("&6Helpers&7: %helpers%"),
PLOT_INFO_TRUSTED("&6Trusted&7: %trusted%"),
PLOT_INFO_DENIED("&6Denied&7: %denied%"),
@ -377,20 +401,11 @@ public enum C {
*/
C(final String d) {
this.d = d;
if (PlotMain.translations == null) {
this.s = d;
} else {
this.s = PlotMain.translations.getString(this.toString());
}
if (this.s == null) {
this.s = "";
}
}
public static class Potato {
}
/**
* Get the default string
*
@ -407,6 +422,8 @@ public enum C {
* @return translated if exists else default
*/
public String s() {
return manager.getTranslated(toString(), TranslationLanguage.englishAmerican).getTranslated().replaceAll("&-", "\n").replaceAll("\\n", "\n");
/*
if (PlotMain.translations != null) {
final String t = PlotMain.translations.getString(this.toString());
if (t != null) {
@ -416,7 +433,7 @@ public enum C {
if (this.s.length() < 1) {
return "";
}
return this.s.replace("\\n", "\n");
return this.s.replace("\\n", "\n");*/
}
/**
@ -426,4 +443,26 @@ public enum C {
return ChatColor.translateAlternateColorCodes('&', this.s());
}
private static TranslationManager manager;
private static TranslationFile defaultFile;
public static void setupTranslations() {
if (manager == null) {
manager = new TranslationManager();
}
if (defaultFile == null) {
defaultFile = new YamlTranslationFile(BukkitTranslation.getParent(PlotMain.getPlugin(PlotMain.class)), TranslationLanguage.englishAmerican, "PlotSquared", manager)
.read();
}
// register everything in this class
for (C c : values()) {
manager.addTranslationObject(
new TranslationObject(c.toString(), c.d, "", "")
);
}
}
public static void saveTranslations() {
manager.saveAll(defaultFile).saveFile(defaultFile);
}
}

View File

@ -1,3 +1,24 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot;
import org.bukkit.ChatColor;

View File

@ -1,17 +1,30 @@
/*
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
*
* >> File = PlayerFunctions.java >> Generated by: Citymonstret at 2014-08-09
* 01:43
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.entity.Player;
import org.bukkit.util.ChatPaginator;
import java.util.*;
@ -228,7 +241,15 @@ public class PlayerFunctions {
* @param plr
* @param msg Was used to wrap the chat client length (Packets out--)
*/
public static void sendMessageWrapped(final Player plr, final String msg) {
public static void sendMessageWrapped(final Player plr, String msg) {
if (msg.length() > ChatPaginator.AVERAGE_CHAT_PAGE_WIDTH) {
String[] ss = ChatPaginator.wordWrap(msg, ChatPaginator.AVERAGE_CHAT_PAGE_WIDTH);
StringBuilder b = new StringBuilder();
for (String p : ss) {
b.append(p).append("\n ");
}
msg = b.toString();
}
plr.sendMessage(msg);
}

View File

@ -1,3 +1,24 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot;
import org.bukkit.generator.ChunkGenerator;

View File

@ -83,15 +83,6 @@ public class PlotMain extends JavaPlugin {
*/
public static YamlConfiguration storage;
public static int storage_ver = 1;
/**
* translations.properties
*/
public static File translationsFile;
/**
* Contains all translations
*/
public static YamlConfiguration translations;
public static int translations_ver = 1;
/**
* MySQL Object
*/
@ -581,6 +572,7 @@ public class PlotMain extends JavaPlugin {
return;
}
C.setupTranslations();
// Setup configurations
configs();
@ -875,7 +867,7 @@ public class PlotMain extends JavaPlugin {
}
public static void reloadTranslations() throws IOException {
translations = YamlConfiguration.loadConfiguration(translationsFile);
C.setupTranslations();
}
public static long getLastPlayed(final UUID uuid) {
@ -926,25 +918,9 @@ public class PlotMain extends JavaPlugin {
Logger.add(LogLevel.DANGER, "Failed to save storage.yml");
System.out.println("Failed to save storage.yml");
}
try {
translationsFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "translations.yml");
if (!translationsFile.exists()) {
if (!translationsFile.createNewFile()) {
sendConsoleSenderMessage("Could not create the translations file, please create \"translations.yml\" manually.");
}
}
translations = YamlConfiguration.loadConfiguration(translationsFile);
setupTranslations();
}
catch (final Exception err_trans) {
Logger.add(LogLevel.DANGER, "Failed to save translations.yml");
System.out.println("Failed to save translations.yml");
}
try {
config.save(configFile);
storage.save(storageFile);
translations.save(translationsFile);
}
catch (final IOException e) {
Logger.add(LogLevel.DANGER, "Configuration file saving failed");
@ -1270,24 +1246,12 @@ public class PlotMain extends JavaPlugin {
}
}
/**
* SETUP: translations.properties
*/
public static void setupTranslations() {
translations.set("version", translations_ver);
for (final C c : C.values()) {
if (!translations.contains(c.toString())) {
translations.set(c.toString(), c.s());
}
}
}
/**
* On unload
*/
@Override
public void onDisable() {
C.saveTranslations();
Logger.add(LogLevel.GENERAL, "Logger disabled");
try {
Logger.write();

View File

@ -1,3 +1,24 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot;
/**

View File

@ -1,10 +1,23 @@
/*
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
*
* >> File = RUtils.java >> Generated by: Citymonstret at 2014-08-09 01:44
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot;

View File

@ -1,10 +1,23 @@
/*
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
*
* >> File = Settings.java >> Generated by: Citymonstret at 2014-08-09 01:44
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot;
@ -19,27 +32,27 @@ public class Settings {
public static boolean MOB_CAP_ENABLED = false;
public static int MOB_CAP = 20;
public static boolean TITLES = true;
public static boolean TITLES = true;
/**
* Schematic Save Path
*/
public static String SCHEMATIC_SAVE_PATH = "/var/www/schematics";
public static String SCHEMATIC_SAVE_PATH = "/var/www/schematics";
/**
* Max allowed plots
*/
public static int MAX_PLOTS = 20;
public static int MAX_PLOTS = 20;
/**
* WorldGuard region on claimed plots
*/
public static boolean WORLDGUARD = false;
public static boolean WORLDGUARD = false;
/**
* metrics
*/
public static boolean METRICS = true;
public static boolean METRICS = true;
/**
* plot specific resource pack
*/
public static String PLOT_SPECIFIC_RESOURCE_PACK = "";
public static String PLOT_SPECIFIC_RESOURCE_PACK = "";
/**
* Kill road mobs?
*/
@ -47,7 +60,7 @@ public class Settings {
/**
* Default kill road mobs: true
*/
public static boolean KILL_ROAD_MOBS_DEFAULT = true;
public static boolean KILL_ROAD_MOBS_DEFAULT = true;
/**
* mob pathfinding?
*/
@ -55,31 +68,31 @@ public class Settings {
/**
* Default mob pathfinding: true
*/
public static boolean MOB_PATHFINDING_DEFAULT = true;
public static boolean MOB_PATHFINDING_DEFAULT = true;
/**
* Delete plots on ban?
*/
public static boolean DELETE_PLOTS_ON_BAN = false;
public static boolean DELETE_PLOTS_ON_BAN = false;
/**
* Verbose?
*/
public static boolean DEBUG = true;
public static boolean DEBUG = true;
/**
* Auto clear enabled
*/
public static boolean AUTO_CLEAR = false;
public static boolean AUTO_CLEAR = false;
/**
* Days until a plot gets cleared
*/
public static int AUTO_CLEAR_DAYS = 365;
public static int AUTO_CLEAR_DAYS = 365;
/**
* API Location
*/
public static String API_URL = "http://www.intellectualsites.com/minecraft.php";
public static String API_URL = "http://www.intellectualsites.com/minecraft.php";
/**
* Use the custom API
*/
public static boolean CUSTOM_API = true;
public static boolean CUSTOM_API = true;
/**
* Database settings
@ -90,7 +103,7 @@ public class Settings {
/**
* MongoDB enabled?
*/
public static boolean USE_MONGO = false; /*
public static boolean USE_MONGO = false; /*
* TODO: Implement Mongo
* @Brandon
*/
@ -101,34 +114,34 @@ public class Settings {
/**
* MySQL Enabled?
*/
public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */
public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */
/**
* SQLite Database name
*/
public static String SQLITE_DB = "storage";
public static String SQLITE_DB = "storage";
/**
* MySQL Host name
*/
public static String HOST_NAME = "localhost";
public static String HOST_NAME = "localhost";
/**
* MySQL Port
*/
public static String PORT = "3306";
public static String PORT = "3306";
/**
* MySQL DB
*/
public static String DATABASE = "plot_db";
public static String DATABASE = "plot_db";
/**
* MySQL User
*/
public static String USER = "root";
public static String USER = "root";
/**
* MySQL Password
*/
public static String PASSWORD = "password";
public static String PASSWORD = "password";
/**
* MySQL Prefix
*/
public static String PREFIX = "";
public static String PREFIX = "";
}
}

View File

@ -114,14 +114,6 @@ public class PlotAPI {
return PlotMain.config;
}
/**
* @return translation configuration
* @see com.intellectualcrafters.plot.PlotMain#translations
*/
public YamlConfiguration getTranslations() {
return PlotMain.translations;
}
/**
* @return storage configuration
* @see com.intellectualcrafters.plot.PlotMain#storage

View File

@ -67,7 +67,7 @@ public class Debug extends SubCommand {
//PlotHelper.getWorldFolderSize() + "MB"));
for (final String worldname : PlotMain.getPlotWorlds()) {
final World world = Bukkit.getWorld(worldname);
information.append(getLine(line, "World: " + world + " size", PlotHelper.getWorldFolderSize(world)));
information.append(getLine(line, "World: " + world.getName() + " size", PlotHelper.getWorldFolderSize(world)));
information.append(getLine(line, " - Entities", PlotHelper.getEntities(world)));
information.append(getLine(line, " - Loaded Tile Entities", PlotHelper.getTileEntities(world)));
information.append(getLine(line, " - Loaded Chunks", PlotHelper.getLoadedChunks(world)));

View File

@ -0,0 +1,19 @@
package com.intellectualsites.translation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Translation annotation
*
* @author Citymonstret
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Translation {
String description() default "";
String creationDescription() default "";
}

View File

@ -0,0 +1,31 @@
package com.intellectualsites.translation;
/**
* Asset
*
* @author Citymonstret
*/
public class TranslationAsset {
private TranslationObject trans;
private String translated;
private TranslationLanguage lang;
public TranslationAsset(TranslationObject trans, String translated, TranslationLanguage lang) {
this.trans = trans;
this.translated = translated;
this.lang = lang;
}
public TranslationObject getObject() {
return trans;
}
public String getTranslated() {
return translated.replace("\n", "&-");
}
public TranslationLanguage getLang() {
return lang;
}
}

View File

@ -0,0 +1,37 @@
package com.intellectualsites.translation;
/**
* Abstract TranslationFile
*
* @author Citymonstret
*/
public abstract class TranslationFile {
/**
* A method used to get the language of the file
*
* @return language
*/
public abstract TranslationLanguage getLanguage();
/**
* Save the file
*/
public abstract void saveFile();
/**
* Read from the file
*
* @return instance
*/
public abstract TranslationFile read();
/**
* Add a value
*
* @param key name
* @param value value
*/
public abstract void add(String key, String value);
}

View File

@ -0,0 +1,50 @@
package com.intellectualsites.translation;
public class TranslationLanguage {
private String countryCode;
private String languageCode;
private String friendlyName;
public TranslationLanguage(String friendlyName, String countryCode, String languageCode) {
this.friendlyName = friendlyName;
this.countryCode = countryCode;
this.languageCode = languageCode;
}
public String getName() {
return friendlyName;
}
public String getCountryCode() {
return countryCode;
}
public String getLanguageCode() {
return languageCode;
}
@Override
public String toString() {
/* en_US */
return languageCode.toLowerCase() + "_" + countryCode.toUpperCase();
}
public static final TranslationLanguage englishAmerican
= (new TranslationLanguage("American English", "us", "en"));
public static final TranslationLanguage englishBritish
= (new TranslationLanguage("British English", "gb", "en"));
public static final TranslationLanguage swedishSwedish
= (new TranslationLanguage("Swedish", "sv", "se"));
public static final TranslationLanguage russianRussian
= (new TranslationLanguage("Russian", "ru", "ru"));
public static TranslationLanguage[] values() {
return new TranslationLanguage[]{
englishAmerican,
englishBritish,
swedishSwedish
};
}
}

View File

@ -0,0 +1,198 @@
package com.intellectualsites.translation;
import java.io.PrintStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;
/**
* Translation Manager Main class
*
* @author Citymonstret
*/
public class TranslationManager {
/**
* The instance
*/
private TranslationManager instance;
/**
* Constructor
*/
public TranslationManager() {
this(new TranslationObject[]{});
}
/**
* Don't use this!
*
* @return this
*/
public TranslationManager instance() {
return this;
}
/**
* Objects
*/
private LinkedList<TranslationObject> translationObjects;
/**
* The translations
*/
private LinkedHashMap<String, TranslationAsset> translatedObjects;
/**
* Get the translation objects
*
* @return objects
*/
public List<TranslationObject> translations() {
return translationObjects;
}
/**
* Constructor
*
* @param translationObjects pre-init
*/
public TranslationManager(TranslationObject[] translationObjects) {
this.translationObjects
= new LinkedList<TranslationObject>(Arrays.asList(translationObjects));
this.translatedObjects
= new LinkedHashMap<String, TranslationAsset>();
instance = this;
}
/**
* Add an object
*
* @param t object
* @return instance
*/
public TranslationManager addTranslationObject(TranslationObject t) {
translationObjects.add(t);
return instance();
}
/**
* Remove an object
*
* @param t object
* @return instance
*/
public TranslationManager removeTranslationObject(TranslationObject t) {
translationObjects.remove(t);
return instance();
}
public String getDescription(String key) {
for (TranslationObject o : translations()) {
if (o.getKey().equals(key) && !o.getDescription().equals("")) {
return "# " + o.getDescription();
}
}
return "";
}
public TranslationManager addTranslation(TranslationObject t, TranslationAsset a) {
return addTranslation(t.getKey(), a);
}
public TranslationManager addTranslation(String key, TranslationAsset a) {
String eKey = key + "." + a.getLang().toString();
eKey = eKey.toLowerCase();
if (translatedObjects.containsKey(eKey))
translatedObjects.remove(eKey);
translatedObjects.put(eKey, a);
return instance();
}
public TranslationAsset getTranslated(String key, String language) {
String eKey = key + "." + language;
eKey = eKey.toLowerCase();
if (!translatedObjects.containsKey(eKey))
return new TranslationAsset(getDefault(key), getDefault(key).getKey(), TranslationLanguage.englishAmerican);
return translatedObjects.get(key);
}
public TranslationAsset getTranslated(String key, TranslationLanguage language) {
String eKey = key + "." + language.toString();
eKey = eKey.toLowerCase();
if (!translatedObjects.containsKey(eKey)) {
return new TranslationAsset(getDefault(key), getDefault(key).getDefaultValue(), TranslationLanguage.englishAmerican);
}
return translatedObjects.get(eKey);
}
public TranslationAsset getTranslated(TranslationObject t, TranslationLanguage l) {
return getTranslated(t.getKey(), l);
}
public String getTranslation(String key, TranslationLanguage l) {
return getTranslated(key, l).getTranslated();
}
public TranslationObject getDefault(String key) {
for (TranslationObject o : translations())
if (o.getKey().equals(key.toLowerCase()))
return o;
return null;
}
public TranslationManager saveAll(TranslationFile file) {
for (TranslationObject object : translations()) {
TranslationAsset o = getTranslated(object.getKey(), file.getLanguage());
file.add(object.getKey(), o.getTranslated());
}
return instance();
}
public static List<TranslationObject> transformEnum(Object[] os) {
List<TranslationObject> eList = new ArrayList<TranslationObject>();
for (Object o : os) {
eList.add(
new TranslationObject(o.toString(), o.toString().toLowerCase().replace("_", " "), "", "")
);
}
return eList;
}
public static void scan(Class c, TranslationManager manager) throws IllegalAccessException {
Field[] fields = c.getDeclaredFields();
Annotation annotation;
for (Field field : fields) {
if (field.getType() != String.class || (annotation = field.getAnnotation(Translation.class)) == null)
continue;
Translation t = (Translation) annotation;
String key = field.getName();
// Make sure we can get the value
field.setAccessible(true);
String defaultValue = (String) field.get(c);
manager.addTranslationObject(
new TranslationObject(
key,
defaultValue,
t.description(),
t.creationDescription()
)
);
}
}
public TranslationManager debug(PrintStream out) {
for (TranslationObject object : translations()) {
out.println(object.getKey() + ":");
for (TranslationLanguage language : TranslationLanguage.values()) {
out.println(language.toString() + ": " + getTranslated(object.getKey(), language).getTranslated());
}
}
return instance();
}
public TranslationManager saveFile(TranslationFile file) {
file.saveFile();
return instance();
}
}

View File

@ -0,0 +1,55 @@
package com.intellectualsites.translation;
import com.sun.istack.internal.NotNull;
public class TranslationObject {
// can include a suffix | not null
private String key;
//The default ("no-translation" value) | not null
private String defaultValue;
// ... "Join message" ... | can be null
private String description;
// Like a plugin name for example | can be null
private String creationDescription;
public TranslationObject(@NotNull String key, @NotNull String defaultValue, String description, String creationDescription) {
if (description == null) {
description = "";
}
if (creationDescription == null) {
creationDescription = "";
}
for (char c : key.toCharArray()) {
if (!Character.isDigit(c) && !Character.isAlphabetic(c) && c != '_' && c != '&' && c != '§' && c != ':') {
throw new RuntimeException(
String.format("Translation: '%s' is invalid (Character: '%s') - Only alphanumeric + (\\, _, &, §, :) charcters are allowed",
key, c + ""
)
);
}
}
this.key = key.toLowerCase();
this.defaultValue = defaultValue.replace("\n", "&-");
;
this.description = description;
this.creationDescription = creationDescription;
}
public String getKey() {
return key;
}
public String getDefaultValue() {
return defaultValue;
}
public String getDescription() {
return description;
}
public String getCreationDescription() {
return creationDescription;
}
}

View File

@ -0,0 +1,216 @@
package com.intellectualsites.translation;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The YAML implementation of TranslationFile
* Relies heavily on SnakeYAML
*
* @author Citymonstret
*/
public class YamlTranslationFile extends TranslationFile {
private File path;
private TranslationLanguage language;
private String name;
private File file;
private HashMap<String, String> map;
private String[] header;
private boolean fancyHead = false;
private YamlTranslationFile instance;
private TranslationManager manager;
/**
* Reload
*/
public void reload() {
this.map = new HashMap<String, String>();
this.read();
}
/**
* Constructor
*
* @param path save path
* @param language translation language
* @param name project name
*/
public YamlTranslationFile(File path, TranslationLanguage language, String name, TranslationManager manager) {
this.path = path;
this.language = language;
this.name = name;
this.manager = manager;
if (!path.exists()) {
if (!path.mkdirs()) {
throw new RuntimeException("Could not create: " + path.getAbsolutePath());
}
}
this.file = new File(path + File.separator + name + "." + language.toString() + ".yml");
if (!file.exists()) {
try {
if (!file.createNewFile()) {
throw new RuntimeException("Could not create: " + file.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
instance = this;
this.instance = this;
}
/**
* Set the header
*
* @param header Comment header
* @return instance
*/
public YamlTranslationFile header(String... header) {
this.header = header;
this.fancyHead = false;
return instance;
}
/**
* Set a fancy header
*
* @param header Comment header
* @return instance
*/
public YamlTranslationFile fancyHeader(String... header) {
final String line = "################################################################################################";
final int lineLength = line.length();
List<String> strings = new ArrayList<String>();
strings.add(line + "\n");
for (String s : header) {
s = "# " + s;
while (s.length() < lineLength - 1) {
s = s + " ";
}
s = s + "#\n";
strings.add(s);
}
strings.add(line + "\n");
this.header = strings.toArray(new String[strings.size()]);
this.fancyHead = true;
return instance;
}
/**
* Add a translation
*
* @param key translation name
* @param value translation value
*/
public void add(String key, String value) {
if (map.containsKey(key))
return;
map.put(
key, value
);
}
/**
* Get the translation language
*
* @return language
*/
@Override
public TranslationLanguage getLanguage() {
return language;
}
/**
* Save the file
*/
@Override
public void saveFile() {
try {
FileWriter writer = new FileWriter(file);
//String s = getYaml().dump(map);
if (header != null && !fancyHead) {
for (String head : header) {
writer.write("# " + head + "\n");
}
} else if (header != null && fancyHead) {
for (String head : header) {
writer.write(head);
}
}
int length = map.size();
int current = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
String var = entry.getKey();
String val = entry.getValue();
String des = manager.getDescription(var);
if (des.equals(""))
writer.write(var + ": \"" + val + "\"" + (current < length - 1 ? "\n" : ""));
else
writer.write(des + "\n" + var + ": \"" + val + "\"" + (current < length - 1 ? "\n" : ""));
++current;
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* YAML Object
*/
private Yaml yaml;
/**
* Get the YAML object
*
* @return yaml object with correct settings
*/
public Yaml getYaml() {
if (yaml == null) {
DumperOptions options = new DumperOptions();
options.setAllowUnicode(true);
options.setPrettyFlow(true);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED);
yaml = new Yaml(options);
yaml.setName(name + "." + language.toString());
}
return yaml;
}
/**
* Read the file
*
* @return instance
*/
@Override
public YamlTranslationFile read() {
try {
map = (HashMap<String, String>) getYaml().load(new FileReader(file));
} catch (Exception e) {
e.printStackTrace();
}
if (map == null) {
map = new HashMap<String, String>();
System.out.println("Was null...");
}
for (Map.Entry<String, String> objects : map.entrySet()) {
String key = objects.getKey();
String val = objects.getValue();
manager.addTranslation(
key,
new TranslationAsset(null, val, language)
);
}
return instance;
}
}

View File

@ -0,0 +1,59 @@
package com.intellectualsites.translation.bukkit;
import com.intellectualsites.translation.TranslationAsset;
import com.intellectualsites.translation.TranslationLanguage;
import com.intellectualsites.translation.TranslationManager;
import com.intellectualsites.translation.TranslationObject;
import org.bukkit.Material;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
/**
* @author Citymonstret
*/
public class BukkitTranslation {
/**
* Get the converted string
*
* @param asset asset
* @return converted asset
*/
public static String convert(TranslationAsset asset) {
// In some cases newline can screw stuff up, so I added a new character thing
// &- = new line
return asset.getTranslated().replace("&-", "\n").replace('&', '§');
}
/**
* Get the universal parent based on the plugin data folder
*
* @param plugin to check
* @return parent folder
*/
public static File getParent(JavaPlugin plugin) {
return new File(plugin.getDataFolder() + File.separator + "translations");
}
/**
* The default translation language
*
* @return default translation language
*/
public TranslationLanguage getDefaultLanguage() {
return TranslationLanguage.englishAmerican;
}
/**
* Add material names to the translation list
* Will default to a somewhat friendly name
*/
public static void addMaterials(TranslationManager manager) {
for (Material material : Material.values()) {
manager.addTranslationObject(
new TranslationObject(material.name(), material.name().replace("_", " ").toLowerCase(), "Material." + material.toString(), "")
);
}
}
}

View File

@ -0,0 +1,49 @@
package com.intellectualsites.translation.bukkit;
import com.intellectualsites.translation.*;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Level;
public class TranslationPlugin extends JavaPlugin {
@Translation(description = "Printed when the translator is fully loaded")
private static final String TRANSLATOR_LOADED = "The translator has been loaded";
@Translation(description = "Printed when the translator has been disabled")
private static final String TRANSLATOR_DISABLED = "The translator has been disabled";
private static TranslationManager manager;
private TranslationFile english;
@Override
public void onEnable() {
// Create a new manager
manager = new TranslationManager();
// Scan this file for all @Translations
try {
TranslationManager.scan(TranslationPlugin.class, manager);
} catch (Exception e) {
e.printStackTrace();
}
// Now let's create some default files :D
english =
new YamlTranslationFile(
BukkitTranslation.getParent(this),
TranslationLanguage.englishAmerican,
getName(),
manager
).read().header("Example file", "@author Citymonstret");
// That created the file, read it, and made a default header
getLogger().log(Level.INFO, BukkitTranslation.convert(manager.getTranslated("translator_loaded", TranslationLanguage.englishAmerican)));
}
@Override
public void onDisable() {
// Add all translations and save the file
manager.saveAll(english).saveFile(english);
getLogger().log(Level.INFO, BukkitTranslation.convert(manager.getTranslated("translator_disabled", TranslationLanguage.englishAmerican)));
}
}