Cleaning up exception and error management.

* NEW: Added the PluginLogger class to standardize console logging.
* NEW: URLs are parsed before starting any downloading task, and an error
  is shown to the user if the parsing failed.
* BUG: Exceptions are now catched at the highest possible level, so that
  appropriate error messages/logs can be generated.
* OPT: Standardized code formatting a bit.
This commit is contained in:
ProkopyL 2015-02-15 13:19:05 +01:00
parent e19d8b5f39
commit d541aede3f
19 changed files with 1168 additions and 1177 deletions

View File

@ -10,20 +10,18 @@ import javax.imageio.ImageIO;
public class DownloadImageThread implements Callable<BufferedImage>
{
private final String stringUrl;
private final URL imageURL;
private BufferedImage imgSrc;
DownloadImageThread(String u)
DownloadImageThread(URL imageURL)
{
stringUrl = u;
this.imageURL = imageURL;
}
@Override
public BufferedImage call() throws IOException
{
URL url = new URL(stringUrl);
imgSrc = ImageIO.read(url);
imgSrc = ImageIO.read(imageURL);
if(imgSrc == null) throw new IOException("URL does not points to a valid image.");

View File

@ -10,9 +10,6 @@ import java.util.logging.Level;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
@ -21,158 +18,182 @@ import fr.moribus.imageonmap.map.SingleMap;
public final class ImageOnMap extends JavaPlugin
{
private boolean dossierCree;
static private ImageOnMap plugin;
public ImageOnMap()
{
plugin = this;
}
static public ImageOnMap getPlugin()
{
return plugin;
}
private boolean dossierCree;
private FileConfiguration customConfig = null;
private File customConfigFile = null;
/* liste contenant les maps ne pouvant être placé dans l'inventaire du joueur. Je le fous ici afin que ce soit
accessible de partout dans le plugin. */
private HashMap<String, ArrayList<ItemStack>> cache = new HashMap<String, ArrayList<ItemStack>>();
// Index des maps chargées sur le serveur
public ArrayList<Short> mapChargee = new ArrayList<Short>();
@Override
public void onEnable()
{
// On crée si besoin le dossier les images seront stockées
dossierCree = ImgUtility.CreeRepImg(this);
// On ajoute si besoin les params par défaut du plugin
ImgUtility.CreeSectionConfig(this);
if(getConfig().get("map_path") == null)
getConfig().set("map_path", getServer().getWorlds().get(0).getName());
else if(getConfig().get("map_path") != getServer().getWorlds().get(0).getName())
getConfig().set("map_path", getServer().getWorlds().get(0).getName());
if(getConfig().getBoolean("import-maps"))
ImgUtility.ImporterConfig(this);
if(this.getConfig().getBoolean("collect-data"))
{
try
{
MetricsLite metrics = new MetricsLite(this);
metrics.start();
getLogger().info("Metrics launched for ImageOnMap");
} catch (IOException e)
{
// Failed to submit the stats :-(
}
}
if(dossierCree)
{
getCommand("tomap").setExecutor(new ImageRenduCommande(this));
getCommand("maptool").setExecutor(new MapToolCommand(this));
getServer().getPluginManager().registerEvents(new SendMapOnFrameEvent(this), this);
getServer().getPluginManager().registerEvents(new SendMapOnInvEvent(this), this);
this.saveDefaultConfig();
//ChargerMap();
}
else
{
getLogger().info("[ImageOnMap] An error occured ! Unable to create Image folder. Plugin will NOT work !");
this.setEnabled(false);
}
}
@Override
public void onDisable()
{
getLogger().info("Stopping ImageOnMap");
}
public void ChargerMap()
{
Set<String> cle = getCustomConfig().getKeys(false);
int nbMap = 0, nbErr = 0;
for (String s: cle)
{
if(getCustomConfig().getStringList(s).size() >= 3)
{
ImageMap map;
try
{
map = new SingleMap(Short.valueOf(getCustomConfig().getStringList(s).get(0)));
if(map.load())
nbMap++;
else
nbErr++;
}
catch (NumberFormatException e)
{
e.printStackTrace();
nbErr++;
}
catch (Exception e)
{
nbErr++;
}
}
}
getLogger().info(nbMap +" maps was loaded");
if(nbErr != 0)
getLogger().info(nbErr +" maps can't be loaded");
}
/* Méthodes pour charger / recharger / sauvegarder
* le fichier conf des maps (map.yml).
* Je les ai juste copié depuis un tuto du wiki Bukkit.
*/
@SuppressWarnings("deprecation")
public void reloadCustomConfig()
@Override
public void onEnable()
{
if (customConfigFile == null)
// On crée si besoin le dossier les images seront stockées
dossierCree = ImgUtility.CreeRepImg(this);
// On ajoute si besoin les params par défaut du plugin
ImgUtility.CreeSectionConfig(this);
if (getConfig().get("map_path") == null)
{
customConfigFile = new File(getDataFolder(), "map.yml");
getConfig().set("map_path", getServer().getWorlds().get(0).getName());
}
else if (getConfig().get("map_path") != getServer().getWorlds().get(0).getName())
{
getConfig().set("map_path", getServer().getWorlds().get(0).getName());
}
if (getConfig().getBoolean("import-maps"))
{
ImgUtility.ImporterConfig(this);
}
if (this.getConfig().getBoolean("collect-data"))
{
try
{
MetricsLite metrics = new MetricsLite(this);
metrics.start();
getLogger().info("Metrics launched for ImageOnMap");
}
catch (IOException e)
{
PluginLogger.LogError("Failed to start Plugin metrics", e);
}
}
if (dossierCree)
{
getCommand("tomap").setExecutor(new ImageRenduCommande(this));
getCommand("maptool").setExecutor(new MapToolCommand(this));
getServer().getPluginManager().registerEvents(new SendMapOnFrameEvent(this), this);
getServer().getPluginManager().registerEvents(new SendMapOnInvEvent(this), this);
this.saveDefaultConfig();
//ChargerMap();
}
else
{
getLogger().info("[ImageOnMap] An error occured ! Unable to create Image folder. Plugin will NOT work !");
this.setEnabled(false);
}
}
@Override
public void onDisable()
{
getLogger().info("Stopping ImageOnMap");
}
public void ChargerMap()
{
Set<String> cle = getCustomConfig().getKeys(false);
int nbMap = 0, nbErr = 0;
for (String s : cle)
{
if (getCustomConfig().getStringList(s).size() >= 3)
{
ImageMap map;
String stringID = getCustomConfig().getStringList(s).get(0);
try
{
map = new SingleMap(Short.valueOf(stringID));
map.load();
nbMap++;
}
catch (NumberFormatException e)
{
PluginLogger.LogWarning("Could not parse map ID from config", e);
nbErr++;
}
catch (IOException e)
{
PluginLogger.LogError("Could not load map ID " + stringID, e);
nbErr++;
}
}
}
PluginLogger.LogInfo(nbMap + " maps successfuly loaded.");
if (nbErr != 0)
PluginLogger.LogWarning(nbErr + " couldn't be loaded.");
}
/* Méthodes pour charger / recharger / sauvegarder
* le fichier conf des maps (map.yml).
* Je les ai juste copié depuis un tuto du wiki Bukkit.
*/
@SuppressWarnings("deprecation")
public void reloadCustomConfig()
{
if (customConfigFile == null)
{
customConfigFile = new File(getDataFolder(), "map.yml");
}
customConfig = YamlConfiguration.loadConfiguration(customConfigFile);
// Look for defaults in the jar
InputStream defConfigStream = this.getResource("map.yml");
if (defConfigStream != null)
if (defConfigStream != null)
{
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
customConfig.setDefaults(defConfig);
}
}
public FileConfiguration getCustomConfig()
public FileConfiguration getCustomConfig()
{
if (customConfig == null)
if (customConfig == null)
{
reloadCustomConfig();
}
return customConfig;
}
public void saveCustomConfig()
public void saveCustomConfig()
{
if (customConfig == null || customConfigFile == null) {
if (customConfig == null || customConfigFile == null)
{
return;
}
try {
try
{
getCustomConfig().save(customConfigFile);
} catch (IOException ex) {
}
catch (IOException ex)
{
getLogger().log(Level.SEVERE, "Could not save config to " + customConfigFile, ex);
}
}
public ArrayList<ItemStack> getRemainingMaps(String j)
{
return cache.get(j);
return cache.get(j);
}
public void setRemainingMaps(String j, ArrayList<ItemStack> remaining)
{
cache.put(j, remaining);
cache.put(j, remaining);
}
public void removeRemaingMaps(String j)
{
cache.remove(j);
cache.remove(j);
}
}

View File

@ -6,7 +6,6 @@ import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.HashMap;
import javax.imageio.ImageIO;

View File

@ -7,77 +7,75 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import fr.moribus.imageonmap.map.MapType;
import java.net.MalformedURLException;
import java.net.URL;
public class ImageRenduCommande implements CommandExecutor
{
Player joueur;
boolean renderName, imgSvg;
ImageOnMap plugin;
boolean resize, rename;
MapType type;
public ImageRenduCommande(ImageOnMap p)
{
plugin = p;
}
@Override
public boolean onCommand(CommandSender sender, Command arg1, String arg2,
String[] arg3)
{
// On vérifie si celui qui exécute la commande est bien un joueur
if (!ImgUtility.VerifierIdentite(sender))
return false;
joueur = (Player) sender;
resize = false;
rename = true;
if(joueur.hasPermission("imageonmap.userender"))
{
}
else
{
joueur.sendMessage("You are not allowed to use this command ( " + arg1.getName() + " )!");
return false;
}
if (arg3.length < 1)
{
joueur.sendMessage(ChatColor.RED + "You must enter image url.");
return false;
}
if(!arg3[0].startsWith("http"))
{
joueur.sendMessage("You must enter a valid URL.");
return true;
}
else if(arg3[0].startsWith("https"))
{
joueur.sendMessage("WARNING: you have entered a secure HTTP link, ImageOnMap can't guarantee " +
"that the image is downloadable");
}
if(arg3.length >= 2)
{
try
{
type = Enum.valueOf(MapType.class, arg3[1]);
}
catch(IllegalArgumentException ex)
{
joueur.sendMessage("Specified map type doesn't exist");
}
}
TacheTraitementMap tache = new TacheTraitementNouvelleMap(joueur, arg3[0], type, resize, rename);
tache.runTaskTimer(plugin, 0, 5);
return true;
}
Player joueur;
boolean renderName, imgSvg;
ImageOnMap plugin;
boolean resize, rename;
MapType type;
}
public ImageRenduCommande(ImageOnMap p)
{
plugin = p;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
// On vérifie si celui qui exécute la commande est bien un joueur
if (!ImgUtility.VerifierIdentite(sender))
{
return false;
}
joueur = (Player) sender;
resize = false;
rename = true;
if (!joueur.hasPermission("imageonmap.userender"))
{
joueur.sendMessage("You are not allowed to use this command ( " + cmd.getName() + " )!");
return false;
}
if (args.length < 1)
{
joueur.sendMessage(ChatColor.RED + "You must enter image url.");
return false;
}
URL url;
try
{
url = new URL(args[0]);
}
catch (MalformedURLException ex)
{
joueur.sendMessage("§cInvalid URL.");
return false;
}
if (args.length >= 2)
{
try
{
type = Enum.valueOf(MapType.class, args[1]);
}
catch (IllegalArgumentException ex)
{
joueur.sendMessage("Specified map type doesn't exist");
}
}
TacheTraitementMap tache = new TacheTraitementNouvelleMap(joueur, url, type, resize, rename);
tache.runTaskTimer(plugin, 0, 5);
return true;
}
}

View File

@ -15,243 +15,246 @@ import org.bukkit.map.MapView;
import fr.moribus.imageonmap.map.ImageMap;
import fr.moribus.imageonmap.map.PosterMap;
import fr.moribus.imageonmap.map.SingleMap;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class MapToolCommand implements CommandExecutor
{
short id;
ImageOnMap plugin;
MapView map;
Player joueur;
Inventory inv;
MapToolCommand(ImageOnMap p)
{
plugin = p;
}
short id;
ImageOnMap plugin;
MapView map;
Player joueur;
Inventory inv;
@Override
public boolean onCommand(CommandSender sender, Command command, String arg2, String[] arg3)
{
if(!ImgUtility.VerifierIdentite(sender))
return false;
String nomCmd = arg2;
joueur = (Player) sender;
inv = joueur.getInventory();
if(arg3.length < 1)
{
joueur.sendMessage("Map tools usage:" +
"\n/"+ ChatColor.GOLD + nomCmd+ ChatColor.RESET+ " get [id]: get the map corresponding to this id" +
"\n/"+ ChatColor.GOLD + nomCmd+ ChatColor.RESET+ " delete [id]: remove the map corresponding to this id" +
"\n/"+ ChatColor.GOLD + nomCmd+ ChatColor.RESET+ " list: show all ids of maps in your possession");
return true;
}
if(arg3[0].equalsIgnoreCase("get"))
{
try
{
id = Short.parseShort(arg3[1]);
}
catch(NumberFormatException err)
{
joueur.sendMessage("you must enter a number !");
return true;
}
SingleMap smap;
try
{
smap = new SingleMap(id);
if(!smap.load())
{
if(joueur.isOp())
joueur.sendMessage(ChatColor.RED+ "Can't retrieve the map ! Check if map"+ id+ " exists in your maps.yml or if the dat file in the world folder exists");
else
joueur.sendMessage(ChatColor.RED+ "ERROR: This map doesn't exists");
return true;
}
else
{
if(inv.firstEmpty() == -1)
{
joueur.sendMessage("Your inventory is full, you can't take the map !");
return true;
}
smap.give(joueur.getInventory());
joueur.sendMessage("Map "+ ChatColor.ITALIC+ id+ ChatColor.RESET+ " was added in your inventory.");
}
}
catch (Exception e)
{
joueur.sendMessage(ChatColor.RED+ "ERROR while loading maps");
}
return true;
}
else if(arg3[0].equalsIgnoreCase("set"))
{
ImageMap smap;
try
{
if(arg3[1].startsWith("poster"))
{
smap = new PosterMap(arg3[1]);
}
else
{
id = Short.parseShort(arg3[1]);
smap = new SingleMap(id);
}
}
catch(NumberFormatException err)
{
joueur.sendMessage("you must enter a number !");
return true;
} catch (Exception e)
{
e.printStackTrace();
joueur.sendMessage(ChatColor.RED+ "ERROR while loading maps");
return true;
}
if(!arg3[2].startsWith("http"))
{
joueur.sendMessage("You must enter a valid URL.");
return true;
}
else if(arg3[2].startsWith("https"))
{
joueur.sendMessage("WARNING: you have entered a secure HTTP link, ImageOnMap can't guarantee " +
"that the image is downloadable");
return true;
}
TacheTraitementMajMap tache = new TacheTraitementMajMap(smap, arg3[2], joueur);
tache.runTaskTimer(plugin, 0, 5);
return true;
}
else if(arg3[0].equalsIgnoreCase("delete"))
{
if(!joueur.hasPermission("imageonmap.usermmap"))
{
joueur.sendMessage("You are not allowed to delete map !");
return true;
}
if(arg3.length == 2 && arg3[1].startsWith("poster"))
{
SavedPoster poster = new SavedPoster(plugin, arg3[1]);
boolean suppr = poster.Remove();
if(!suppr)
joueur.sendMessage("Unable to remove the entire poster, check the server log for more information");
return true;
}
if(arg3.length <= 1)
{
if(joueur.getItemInHand().getType() == Material.MAP)
{
id = joueur.getItemInHand().getDurability();
}
else
{
joueur.sendMessage(ChatColor.RED+ "You must hold a map or enter an id");
}
}
else
{
try
{
id = Short.parseShort(arg3[1]);
}
catch(NumberFormatException err)
{
joueur.sendMessage("you must enter a number !");
return true;
}
}
boolean success = ImgUtility.RemoveMap(plugin, id);
if(success)
{
joueur.sendMessage("Map#"+ id+ " was deleted");
return true;
}
else
{
joueur.sendMessage(ChatColor.RED+ "Can't delete delete Map#"+ id+ ": check the server log");
return true;
}
}
else if(arg3[0].equalsIgnoreCase("list"))
{
String msg = "", msg2 = "";
int compteur = 0;
ArrayList<String> liste = new ArrayList<String>();
liste = ImgUtility.getListMapByPlayer(plugin, joueur.getName());
for (; compteur < liste.size(); compteur++)
{
msg += liste.get(compteur)+ " ";
}
SavedPoster tmp = new SavedPoster(plugin);
ArrayList<String> listePoster = tmp.getListMapByPlayer(plugin, joueur.getName());
for (int i= 0; i< listePoster.size(); i++)
{
msg2 += listePoster.get(i)+ " ";
}
joueur.sendMessage(msg+
"\nYou have rendered "+ ChatColor.DARK_PURPLE+ (compteur + 1)+ ChatColor.RESET+ " pictures");
joueur.sendMessage("Your posters: \n"+ msg2);
}
else if(arg3[0].equalsIgnoreCase("getrest"))
{
if(plugin.getRemainingMaps(joueur.getName()) == null)
{
joueur.sendMessage("All maps have already be placed in your inventory");
return true;
}
ArrayList<ItemStack> reste = plugin.getRemainingMaps(joueur.getName());
ArrayList<ItemStack> restant = new ArrayList<ItemStack>();
for(int i = 0; i < reste.size(); i++)
{
ImgUtility.AddMap(reste.get(i), inv, restant);
}
if(restant.isEmpty())
{
plugin.removeRemaingMaps(joueur.getName());
joueur.sendMessage("All maps have been placed in your inventory");
}
else
{
plugin.setRemainingMaps(joueur.getName(), restant);
joueur.sendMessage(restant.size()+ " maps can't be placed in your inventory. Please run "+ ChatColor.GOLD+ "/maptool getrest again");
}
}
return true;
}
public MapToolCommand(ImageOnMap p)
{
plugin = p;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
if (!ImgUtility.VerifierIdentite(sender))
{
return false;
}
joueur = (Player) sender;
inv = joueur.getInventory();
if (args.length < 1)
{
joueur.sendMessage("Map tools usage:"
+ "\n/" + ChatColor.GOLD + label + ChatColor.RESET + " get [id]: get the map corresponding to this id"
+ "\n/" + ChatColor.GOLD + label + ChatColor.RESET + " delete [id]: remove the map corresponding to this id"
+ "\n/" + ChatColor.GOLD + label + ChatColor.RESET + " list: show all ids of maps in your possession");
return true;
}
if (args[0].equalsIgnoreCase("get"))
{
try
{
id = Short.parseShort(args[1]);
}
catch (NumberFormatException err)
{
joueur.sendMessage("you must enter a number !");
return true;
}
SingleMap smap;
try
{
smap = new SingleMap(id);
smap.load();
if (inv.firstEmpty() == -1)
{
joueur.sendMessage("Your inventory is full, you can't take the map !");
return true;
}
smap.give(joueur.getInventory());
joueur.sendMessage("Map " + ChatColor.ITALIC + id + ChatColor.RESET + " was added in your inventory.");
}
catch (IllegalArgumentException ex)
{
joueur.sendMessage(ChatColor.RED + "Invalid argument : " + ex.getMessage());
}
catch(IOException ex)
{
joueur.sendMessage(ChatColor.RED + "Unable to load the map. Check server console for details.");
PluginLogger.LogError("Could not load the map", ex);
}
return true;
}
else if (args[0].equalsIgnoreCase("set"))
{
ImageMap smap;
try
{
if (args[1].startsWith("poster"))
{
smap = new PosterMap(args[1]);
}
else
{
id = Short.parseShort(args[1]);
smap = new SingleMap(id);
}
}
catch (NumberFormatException err)
{
joueur.sendMessage("you must enter a number !");
return true;
}
catch (Exception e)
{
e.printStackTrace();
joueur.sendMessage(ChatColor.RED + "ERROR while loading maps");
return true;
}
if(args.length < 3)
{
joueur.sendMessage("§cYou must enter a valid URL.");
return true;
}
URL url;
try
{
url = new URL(args[2]);
}
catch (MalformedURLException ex)
{
joueur.sendMessage("§Invalid URL.");
return true;
}
TacheTraitementMajMap tache = new TacheTraitementMajMap(smap, url, joueur);
tache.runTaskTimer(plugin, 0, 5);
return true;
}
else if (args[0].equalsIgnoreCase("delete"))
{
if (!joueur.hasPermission("imageonmap.usermmap"))
{
joueur.sendMessage("You are not allowed to delete map !");
return true;
}
if (args.length == 2 && args[1].startsWith("poster"))
{
SavedPoster poster = new SavedPoster(plugin, args[1]);
try
{
poster.Remove();
}
catch (IOException ex)
{
joueur.sendMessage("Unable to remove the entire poster, check the server log for more information");
PluginLogger.LogError("Unable to remove the entire poster", ex);
}
return true;
}
if (args.length <= 1)
{
if (joueur.getItemInHand().getType() == Material.MAP)
{
id = joueur.getItemInHand().getDurability();
}
else
{
joueur.sendMessage(ChatColor.RED + "You must hold a map or enter an id");
}
}
else
{
try
{
id = Short.parseShort(args[1]);
}
catch (NumberFormatException err)
{
joueur.sendMessage("you must enter a number !");
return true;
}
}
boolean success = ImgUtility.RemoveMap(plugin, id);
if (success)
{
joueur.sendMessage("Map#" + id + " was deleted");
return true;
}
else
{
joueur.sendMessage(ChatColor.RED + "Can't delete delete Map#" + id + ": check the server log");
return true;
}
}
else if (args[0].equalsIgnoreCase("list"))
{
String msg = "", msg2 = "";
int compteur = 0;
ArrayList<String> liste = new ArrayList<String>();
liste = ImgUtility.getListMapByPlayer(plugin, joueur.getName());
for (; compteur < liste.size(); compteur++)
{
msg += liste.get(compteur) + " ";
}
SavedPoster tmp = new SavedPoster(plugin);
ArrayList<String> listePoster = tmp.getListMapByPlayer(plugin, joueur.getName());
for (int i = 0; i < listePoster.size(); i++)
{
msg2 += listePoster.get(i) + " ";
}
joueur.sendMessage(msg
+ "\nYou have rendered " + ChatColor.DARK_PURPLE + (compteur + 1) + ChatColor.RESET + " pictures");
joueur.sendMessage("Your posters: \n" + msg2);
}
else if (args[0].equalsIgnoreCase("getrest"))
{
if (plugin.getRemainingMaps(joueur.getName()) == null)
{
joueur.sendMessage("All maps have already be placed in your inventory");
return true;
}
ArrayList<ItemStack> reste = plugin.getRemainingMaps(joueur.getName());
ArrayList<ItemStack> restant = new ArrayList<ItemStack>();
for (int i = 0; i < reste.size(); i++)
{
ImgUtility.AddMap(reste.get(i), inv, restant);
}
if (restant.isEmpty())
{
plugin.removeRemaingMaps(joueur.getName());
joueur.sendMessage("All maps have been placed in your inventory");
}
else
{
plugin.setRemainingMaps(joueur.getName(), restant);
joueur.sendMessage(restant.size() + " maps can't be placed in your inventory. Please run " + ChatColor.GOLD + "/maptool getrest again");
}
}
return true;
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright (C) 2014 ProkopyL
*
* 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 2
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package fr.moribus.imageonmap;
import java.util.logging.Level;
import java.util.logging.Logger;
abstract public class PluginLogger
{
static private Logger getLogger()
{
return ImageOnMap.getPlugin().getLogger();
}
static public void LogInfo(String message)
{
getLogger().log(Level.INFO, message);
}
static public void LogWarning(String message)
{
getLogger().log(Level.WARNING, message);
}
static public void LogWarning(String message, Throwable ex)
{
getLogger().log(Level.WARNING, message, ex);
}
static public void LogError(String message, Throwable ex)
{
getLogger().log(Level.SEVERE, message, ex);
}
}

View File

@ -4,100 +4,112 @@ import java.awt.image.BufferedImage;
import java.util.HashMap;
/* Class which represents a picture cut into several parts */
public class Poster
public class Poster
{
private BufferedImage src;
private BufferedImage[] ImgDecoupe;
private HashMap<Integer, String> NumeroMap;
private int nbPartie;
private int nbColonne;
public Poster(BufferedImage img)
{
src = img;
NumeroMap = new HashMap<Integer, String>();
DecoupeImg();
}
public BufferedImage[] getPoster()
{
return ImgDecoupe;
}
public int getNbColonne()
{
return nbColonne;
}
private void DecoupeImg()
{
int ligne, colonne;
int x = 0, y = 0;
int index = 0;
int resteX = src.getWidth() % 128;
int resteY = src.getHeight() % 128;
if(src.getWidth() / 128 <= 0)
ligne = 1;
else if(src.getWidth() % 128 != 0)
ligne = src.getWidth() / 128 + 1;
else
ligne = src.getWidth() / 128;
if(src.getHeight() <= 0)
colonne = 1;
else if(src.getHeight() % 128 != 0)
colonne = src.getHeight() / 128 + 1;
else
colonne = src.getHeight() / 128;
nbColonne = colonne;
nbPartie = ligne * colonne;
ImgDecoupe = new BufferedImage[nbPartie];
for(int lig = 0; lig < ligne; lig++)
{
y = 0;
if(lig == ligne - 1 && resteX != 0 )
{
for(int col = 0; col < colonne; col++)
{
if(col == colonne - 1 && resteY != 0)
{
ImgDecoupe[index] = src.getSubimage(x, y, resteX, resteY);
}
else
{
ImgDecoupe[index] = src.getSubimage(x, y, resteX, 128);
y += 128;
}
NumeroMap.put(index, "column "+ (lig + 1) +", row "+ (col + 1));
index++;
}
}
else
{
for(int col = 0; col < colonne; col++)
{
if(col == colonne - 1 && resteY != 0)
{
ImgDecoupe[index] = src.getSubimage(x, y, 128, resteY);
}
else
{
ImgDecoupe[index] = src.getSubimage(x, y, 128, 128);
y += 128;
}
NumeroMap.put(index, "column "+ (lig +1) +", row "+ (col + 1));
index++;
}
x += 128;
}
}
}
private BufferedImage src;
private BufferedImage[] ImgDecoupe;
private HashMap<Integer, String> NumeroMap;
private int nbPartie;
private int nbColonne;
public Poster(BufferedImage img)
{
src = img;
NumeroMap = new HashMap<Integer, String>();
DecoupeImg();
}
public BufferedImage[] getPoster()
{
return ImgDecoupe;
}
public int getNbColonne()
{
return nbColonne;
}
private void DecoupeImg()
{
int ligne, colonne;
int x = 0, y = 0;
int index = 0;
int resteX = src.getWidth() % 128;
int resteY = src.getHeight() % 128;
if (src.getWidth() / 128 <= 0)
{
ligne = 1;
}
else if (src.getWidth() % 128 != 0)
{
ligne = src.getWidth() / 128 + 1;
}
else
{
ligne = src.getWidth() / 128;
}
if (src.getHeight() <= 0)
{
colonne = 1;
}
else if (src.getHeight() % 128 != 0)
{
colonne = src.getHeight() / 128 + 1;
}
else
{
colonne = src.getHeight() / 128;
}
nbColonne = colonne;
nbPartie = ligne * colonne;
ImgDecoupe = new BufferedImage[nbPartie];
for (int lig = 0; lig < ligne; lig++)
{
y = 0;
if (lig == ligne - 1 && resteX != 0)
{
for (int col = 0; col < colonne; col++)
{
if (col == colonne - 1 && resteY != 0)
{
ImgDecoupe[index] = src.getSubimage(x, y, resteX, resteY);
}
else
{
ImgDecoupe[index] = src.getSubimage(x, y, resteX, 128);
y += 128;
}
NumeroMap.put(index, "column " + (lig + 1) + ", row " + (col + 1));
index++;
}
}
else
{
for (int col = 0; col < colonne; col++)
{
if (col == colonne - 1 && resteY != 0)
{
ImgDecoupe[index] = src.getSubimage(x, y, 128, resteY);
}
else
{
ImgDecoupe[index] = src.getSubimage(x, y, 128, 128);
y += 128;
}
NumeroMap.put(index, "column " + (lig + 1) + ", row " + (col + 1));
index++;
}
x += 128;
}
}
}
}

View File

@ -12,100 +12,94 @@ import org.bukkit.Bukkit;
import org.bukkit.map.MapPalette;
import org.bukkit.map.MapView;
public class SavedMap
public class SavedMap
{
ImageOnMap plugin;
String nomImg, nomJoueur, nomMonde;
short idMap;
BufferedImage image;
boolean loaded = false;
SavedMap(ImageOnMap plug, String nomJ, short id, BufferedImage img, String nomM)
{
plugin = plug;
nomJoueur = nomJ;
idMap = id;
image = img;
nomImg = "map" + id;
nomMonde = nomM;
loaded = true;
}
SavedMap(ImageOnMap plug, short id)
{
idMap = id;
plugin = plug;
Set<String> cle = plugin.getCustomConfig().getKeys(false);
for (String s: cle)
{
if(plugin.getCustomConfig().getStringList(s).size() >= 3 && Short.valueOf(plugin.getCustomConfig().getStringList(s).get(0)) == id)
{
ImageOnMap plugin;
String nomImg, nomJoueur, nomMonde;
short idMap;
BufferedImage image;
boolean loaded = false;
SavedMap(ImageOnMap plug, String nomJ, short id, BufferedImage img, String nomM)
{
plugin = plug;
nomJoueur = nomJ;
idMap = id;
image = img;
nomImg = "map" + id;
nomMonde = nomM;
loaded = true;
}
SavedMap(ImageOnMap plug, short id) throws IOException
{
idMap = id;
plugin = plug;
Set<String> cle = plugin.getCustomConfig().getKeys(false);
for (String s : cle)
{
if (plugin.getCustomConfig().getStringList(s).size() >= 3 && Short.valueOf(plugin.getCustomConfig().getStringList(s).get(0)) == id)
{
//System.out.println(tmp);
//MapView carte = Bukkit.getMap(Short.parseShort(plugin.getConfig().getStringList(s).get(0)));
nomImg = plugin.getCustomConfig().getStringList(s).get(1);
nomJoueur = plugin.getCustomConfig().getStringList(s).get(2);
try {
image = ImageIO.read(new File("./plugins/ImageOnMap/Image/"+ nomImg + ".png"));
loaded = true;
//System.out.println("Chargement de l'image fini");
} catch (IOException e) {
System.out.println("Image "+ nomImg +".png doesn't exists in Image directory.");
}
break;
}
}
if(!loaded)
{
//plugin.getLogger().info("No map was loaded");
}
}
Boolean SaveMap()
{
if(!loaded)
{
plugin.getLogger().info("Cannot save the map !");
return false;
}
plugin.getLogger().info("Saving map " + idMap);
// Enregistrement de l'image sur le disque dur
try
{
File outputfile = new File("./plugins/ImageOnMap/Image/"+ nomImg + ".png");
ImageIO.write(MapPalette.resizeImage(image), "png", outputfile);
} catch (IOException e)
{
e.printStackTrace();
return false;
//MapView carte = Bukkit.getMap(Short.parseShort(plugin.getConfig().getStringList(s).get(0)));
nomImg = plugin.getCustomConfig().getStringList(s).get(1);
nomJoueur = plugin.getCustomConfig().getStringList(s).get(2);
image = ImageIO.read(new File("./plugins/ImageOnMap/Image/" + nomImg + ".png"));
loaded = true;
break;
}
}
// Enregistrement de la map dans la config
ArrayList<String> liste = new ArrayList<String>();
liste.add(String.valueOf(idMap));
liste.add(nomImg);
liste.add(nomJoueur);
liste.add(nomMonde);
plugin.getCustomConfig().set(nomImg, liste);
plugin.saveCustomConfig();
if(!plugin.mapChargee.contains(idMap))
plugin.mapChargee.add(idMap);
return true;
}
@SuppressWarnings("deprecation")
Boolean LoadMap()
{
MapView carte = Bukkit.getMap(idMap);
if(carte != null && loaded)
{
ImageRendererThread.SupprRendu(carte);
carte.addRenderer(new Rendu(image));
if(!plugin.mapChargee.contains(idMap))
plugin.mapChargee.add(idMap);
return true;
}
else
return false;
}
if (!loaded)
{
//plugin.getLogger().info("No map was loaded");
}
}
public void saveMap() throws IOException
{
if (!loaded)
{
PluginLogger.LogWarning("Tried to save a map that wasn't loaded. ID:" + idMap);
return;
}
plugin.getLogger().info("Saving map " + idMap);
// Enregistrement de l'image sur le disque dur
File outputfile = new File("./plugins/ImageOnMap/Image/" + nomImg + ".png");
ImageIO.write(MapPalette.resizeImage(image), "png", outputfile);
// Enregistrement de la map dans la config
ArrayList<String> liste = new ArrayList<String>();
liste.add(String.valueOf(idMap));
liste.add(nomImg);
liste.add(nomJoueur);
liste.add(nomMonde);
plugin.getCustomConfig().set(nomImg, liste);
plugin.saveCustomConfig();
if (!plugin.mapChargee.contains(idMap))
{
plugin.mapChargee.add(idMap);
}
}
@SuppressWarnings("deprecation")
Boolean LoadMap()
{
MapView carte = Bukkit.getMap(idMap);
if (carte != null && loaded)
{
ImageRendererThread.SupprRendu(carte);
carte.addRenderer(new Rendu(image));
if (!plugin.mapChargee.contains(idMap))
{
plugin.mapChargee.add(idMap);
}
return true;
}
else
{
return false;
}
}
}

View File

@ -5,162 +5,151 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.logging.Level;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class SavedPoster
public class SavedPoster
{
ImageOnMap plugin;
short[] ids;
ImageOnMap plugin;
short[] ids;
private FileConfiguration customConfig = null;
private File customConfigFile = null;
String PosName, nomJoueur;
SavedPoster(ImageOnMap p, short[] i, String nom)
{
ids = i;
plugin = p;
nomJoueur = nom;
PosName = "";
}
SavedPoster(ImageOnMap p, short[] i, String nom, String n)
{
ids = i;
plugin = p;
nomJoueur = nom;
PosName = n;
}
SavedPoster(ImageOnMap p, String id)
{
plugin = p;
PosName = id;
ArrayList<String> liste = (ArrayList<String>) getCustomConfig().getStringList(PosName);
if(!liste.isEmpty() || liste != null)
{
nomJoueur = liste.get(0);
ids = new short[liste.size() - 1];
for(int i= 0; i< ids.length; i++)
{
ids[i] = Short.parseShort(liste.get(i+1));
}
}
}
SavedPoster(ImageOnMap p)
{
plugin = p;
}
String Save()
{
int increment = increment();
ArrayList<String> liste = new ArrayList<String>();
liste.add(nomJoueur);
for(int i= 0; i< ids.length; i++)
{
liste.add(String.valueOf(ids[i]));
}
PosName = "poster"+ increment;
getCustomConfig().set(PosName, liste);
saveCustomConfig();
return PosName;
}
boolean Remove()
{
if(!PosName.isEmpty())
{
for(int i= 0; i< ids.length; i++)
{
ImgUtility.RemoveMap(plugin, ids[i]);
}
getCustomConfig().set(PosName, null);
saveCustomConfig();
return true;
}
else
return false;
}
int increment()
{
int i;
if(getCustomConfig().get("IdCount") != null)
i = getCustomConfig().getInt("IdCount");
else
i = 0;
i++;
this.getCustomConfig().set("IdCount", i);
return i;
}
String getId()
{
return PosName;
}
ArrayList<String> getListMapByPlayer(ImageOnMap plugin, String pseudo)
{
ArrayList<String> listeMap = new ArrayList<String>();
Set<String> cle = getCustomConfig().getKeys(false);
for (String s: cle)
{
if(getCustomConfig().getStringList(s).size() > 1 && pseudo.equalsIgnoreCase(getCustomConfig().getStringList(s).get(0)))
{
listeMap.add(s);
}
}
return listeMap;
}
/* Méthodes pour charger / recharger / sauvegarder
* le fichier conf des Posters (poster.yml).
* Je les ai juste copié depuis un tuto du wiki Bukkit...
*/
@SuppressWarnings("deprecation")
public void reloadCustomConfig()
String posterName, playerName;
public SavedPoster(ImageOnMap plugin, short[] ids, String playerName, String posterName)
{
if (customConfigFile == null)
this.ids = ids;
this.plugin = plugin;
this.playerName = playerName;
this.posterName = posterName;
}
public SavedPoster(ImageOnMap plugin, short[] ids, String playerName)
{
this(plugin, ids, playerName, null);
}
public SavedPoster(ImageOnMap plugin)
{
this(plugin, null, null, null);
}
public SavedPoster(ImageOnMap p, String id)
{
plugin = p;
posterName = id;
ArrayList<String> liste = (ArrayList<String>) getCustomConfig().getStringList(posterName);
if (!liste.isEmpty() || liste != null)
{
customConfigFile = new File(plugin.getDataFolder(), "poster.yml");
playerName = liste.get(0);
ids = new short[liste.size() - 1];
for (int i = 0; i < ids.length; i++)
{
ids[i] = Short.parseShort(liste.get(i + 1));
}
}
}
public String Save() throws IOException
{
int increment = increment();
ArrayList<String> liste = new ArrayList<String>();
liste.add(playerName);
for (int i = 0; i < ids.length; i++)
{
liste.add(String.valueOf(ids[i]));
}
posterName = "poster" + increment;
getCustomConfig().set(posterName, liste);
saveCustomConfig();
return posterName;
}
public void Remove() throws IOException
{
if (posterName == null || posterName.isEmpty()) return;
for (int i = 0; i < ids.length; i++)
{
ImgUtility.RemoveMap(plugin, ids[i]);
}
getCustomConfig().set(posterName, null);
saveCustomConfig();
}
int increment()
{
int i;
if (getCustomConfig().get("IdCount") != null)
{
i = getCustomConfig().getInt("IdCount");
}
else
{
i = 0;
}
i++;
this.getCustomConfig().set("IdCount", i);
return i;
}
String getId()
{
return posterName;
}
ArrayList<String> getListMapByPlayer(ImageOnMap plugin, String pseudo)
{
ArrayList<String> listeMap = new ArrayList<String>();
Set<String> cle = getCustomConfig().getKeys(false);
for (String s : cle)
{
if (getCustomConfig().getStringList(s).size() > 1 && pseudo.equalsIgnoreCase(getCustomConfig().getStringList(s).get(0)))
{
listeMap.add(s);
}
}
return listeMap;
}
/* Méthodes pour charger / recharger / sauvegarder
* le fichier conf des Posters (poster.yml).
* Je les ai juste copié depuis un tuto du wiki Bukkit...
*/
@SuppressWarnings("deprecation")
public void reloadCustomConfig()
{
if (customConfigFile == null)
{
customConfigFile = new File(plugin.getDataFolder(), "poster.yml");
}
customConfig = YamlConfiguration.loadConfiguration(customConfigFile);
// Look for defaults in the jar
InputStream defConfigStream = plugin.getResource("poster.yml");
if (defConfigStream != null)
if (defConfigStream != null)
{
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
customConfig.setDefaults(defConfig);
}
}
public FileConfiguration getCustomConfig()
public FileConfiguration getCustomConfig()
{
if (customConfig == null)
if (customConfig == null)
{
reloadCustomConfig();
}
return customConfig;
}
public void saveCustomConfig()
public void saveCustomConfig() throws IOException
{
if (customConfig == null || customConfigFile == null) {
if (customConfig == null || customConfigFile == null)
{
return;
}
try {
getCustomConfig().save(customConfigFile);
} catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + customConfigFile, ex);
}
getCustomConfig().save(customConfigFile);
}
}

View File

@ -15,45 +15,44 @@ import fr.moribus.imageonmap.map.SingleMap;
public class SendMapOnFrameEvent implements Listener
{
ImageOnMap plugin;
Chunk chunk;
Entity[] entites;
ItemFrame frame;
SendMapOnFrameEvent(ImageOnMap plug)
{
plugin = plug;
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event)
{
chunk = event.getChunk();
entites = chunk.getEntities().clone();
for(int i = 0; i < entites.length; i++)
{
Entity entite = entites[i];
if(entite instanceof ItemFrame)
{
ArrayList<Short> ListeId = plugin.mapChargee;
frame = (ItemFrame) entite;
ItemStack stack = frame.getItem();
if(stack.getType() == Material.MAP && !ListeId.contains(stack.getDurability()))
{
try
{
new SingleMap(stack.getDurability()).load();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
ImageOnMap plugin;
Chunk chunk;
Entity[] entites;
ItemFrame frame;
SendMapOnFrameEvent(ImageOnMap plug)
{
plugin = plug;
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event)
{
chunk = event.getChunk();
entites = chunk.getEntities().clone();
for (int i = 0; i < entites.length; i++)
{
Entity entite = entites[i];
if (entite instanceof ItemFrame)
{
ArrayList<Short> ListeId = plugin.mapChargee;
frame = (ItemFrame) entite;
ItemStack stack = frame.getItem();
if (stack.getType() == Material.MAP && !ListeId.contains(stack.getDurability()))
{
try
{
new SingleMap(stack.getDurability()).load();
}
catch (Exception e)
{
PluginLogger.LogWarning("Could not send frame map", e);
}
}
}
}
}
}

View File

@ -12,54 +12,48 @@ import org.bukkit.inventory.ItemStack;
import fr.moribus.imageonmap.map.SingleMap;
public class SendMapOnInvEvent implements Listener
{
ImageOnMap plugin;
ImageOnMap plugin;
SendMapOnInvEvent(ImageOnMap p)
{
plugin = p;
}
SendMapOnInvEvent(ImageOnMap p)
{
plugin = p;
}
@EventHandler
public void onPlayerInv(PlayerItemHeldEvent event)
{
Player joueur = event.getPlayer();
int slot = event.getNewSlot();
ItemStack stack = joueur.getInventory().getItem(slot);
@EventHandler
public void onPlayerInv(PlayerItemHeldEvent event)
{
Player joueur = event.getPlayer();
int slot = event.getNewSlot();
ItemStack stack = joueur.getInventory().getItem(slot);
if(stack != null && stack.getType() == Material.MAP)
{
ArrayList<Short> listeId = plugin.mapChargee;
Set<String> cle = plugin.getCustomConfig().getKeys(false);
for (String s: cle)
{
if(!listeId.contains(stack.getDurability()))
{
if(plugin.getCustomConfig().getStringList(s).get(0).equals(String.valueOf(stack.getDurability())))
{
try
{
new SingleMap(stack.getDurability()).load();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
if (stack != null && stack.getType() == Material.MAP)
{
ArrayList<Short> listeId = plugin.mapChargee;
Set<String> cle = plugin.getCustomConfig().getKeys(false);
for (String s : cle)
{
if (!listeId.contains(stack.getDurability()))
{
if (plugin.getCustomConfig().getStringList(s).get(0).equals(String.valueOf(stack.getDurability())))
{
try
{
new SingleMap(stack.getDurability()).load();
}
catch (Exception e)
{
PluginLogger.LogWarning("Could not send inventory map.", e);
}
}
}
}
}
}
}

View File

@ -5,20 +5,22 @@ import java.awt.image.BufferedImage;
import org.bukkit.entity.Player;
import fr.moribus.imageonmap.map.ImageMap;
import java.io.IOException;
import java.net.URL;
public class TacheTraitementMajMap extends TacheTraitementMap
{
private ImageMap m;
public TacheTraitementMajMap(ImageMap m, String u, Player joueur)
public TacheTraitementMajMap(ImageMap m, URL url, Player joueur)
{
super(u);
super(url);
setJoueur(joueur);
this.m = m;
}
@Override
public void traiterMap(BufferedImage img)
public void traiterMap(BufferedImage img) throws IOException
{
m.setImage(img);
m.save();

View File

@ -1,6 +1,8 @@
package fr.moribus.imageonmap;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -15,7 +17,6 @@ import org.bukkit.scheduler.BukkitRunnable;
public abstract class TacheTraitementMap extends BukkitRunnable
{
private Player joueur;
private DownloadImageThread renduImg;
private PlayerInventory inv;
@ -26,17 +27,17 @@ public abstract class TacheTraitementMap extends BukkitRunnable
private Future<BufferedImage> futurDlImg;
private int compteurExec;
protected TacheTraitementMap(String u)
protected TacheTraitementMap(URL url)
{
renduImg = new DownloadImageThread(u);
renduImg = new DownloadImageThread(url);
dlImg = Executors.newSingleThreadExecutor();
futurDlImg = dlImg.submit(renduImg);
plugin = (ImageOnMap) Bukkit.getPluginManager().getPlugin("ImageOnMap");
}
public TacheTraitementMap(Player j, String u, boolean rs, boolean rn)
public TacheTraitementMap(Player j, URL url, boolean rs, boolean rn)
{
this(u);
this(url);
joueur = j;
inv = joueur.getInventory();
resized = rs;
@ -83,15 +84,22 @@ public abstract class TacheTraitementMap extends BukkitRunnable
traiterMap(dlimg);
joueur.sendMessage("Image successfuly downloaded !");
}
catch (InterruptedException e)
catch (InterruptedException ex)
{
joueur.sendMessage(ChatColor.RED + "ERROR: download task has been interrupted. Make sure your URL is valid.");
joueur.sendMessage(ChatColor.RED + "Download task has been interrupted unexpectedly. Check server console for details.");
PluginLogger.LogError("Download task has been interrupted", ex);
}
catch (ExecutionException e)
catch (ExecutionException ex)
{
joueur.sendMessage(ChatColor.RED + "Download failed : " + e.getMessage());
joueur.sendMessage(ChatColor.RED + "Download failed : " + ex.getMessage());
joueur.sendMessage(ChatColor.RED + "Please check your URL");
}
catch(IOException ex)
{
joueur.sendMessage(ChatColor.RED + "Failed to process the image. Check server console for details.");
PluginLogger.LogError("Image processing failed", ex);
}
}
else
{
@ -100,7 +108,7 @@ public abstract class TacheTraitementMap extends BukkitRunnable
}
}
public abstract void traiterMap(BufferedImage img);
public abstract void traiterMap(BufferedImage img) throws IOException;
protected Player getJoueur()
{

View File

@ -8,19 +8,21 @@ import fr.moribus.imageonmap.map.ImageMap;
import fr.moribus.imageonmap.map.MapType;
import fr.moribus.imageonmap.map.PosterMap;
import fr.moribus.imageonmap.map.SingleMap;
import java.io.IOException;
import java.net.URL;
public class TacheTraitementNouvelleMap extends TacheTraitementMap
{
private MapType type;
private final MapType type;
public TacheTraitementNouvelleMap(Player j, String u, MapType type, boolean rs, boolean rn)
public TacheTraitementNouvelleMap(Player player, URL url, MapType type, boolean rs, boolean rn)
{
super(j, u, rs, rn);
super(player, url, rs, rn);
this.type = type;
}
@Override
public void traiterMap(BufferedImage img)
public void traiterMap(BufferedImage img) throws IOException
{
ImageMap m;

View File

@ -1,16 +1,17 @@
package fr.moribus.imageonmap.map;
import java.awt.image.BufferedImage;
import java.io.IOException;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public interface ImageMap
{
public boolean load();
public boolean save();
public void load() throws IOException;
public void save() throws IOException;
public void give(Inventory inv);
public boolean isNamed();
public void setImage(BufferedImage image);
public void send(Player joueur);
}
}

View File

@ -6,7 +6,6 @@ import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.imageio.ImageIO;
@ -16,94 +15,75 @@ import fr.moribus.imageonmap.ImageOnMap;
public class MapData
{
private short id;
private String joueur;
private String monde;
private String nom;
private BufferedImage image;
public Image getImage()
{
return image;
}
public void setImage(BufferedImage image)
{
this.image = image;
}
private final short id;
private String playerName;
private String worldName;
private String name;
private BufferedImage image;
public MapData(short id, String playerName, BufferedImage image, String worldName, String name)
{
this.id = id;
this.playerName = playerName;
this.image = image;
this.worldName = worldName;
this.name = name;
}
public MapData(short id)
{
this(id, null, null, null, null);
}
public MapData(short id, String joueur, BufferedImage image, String monde)
{
this.id = id;
this.joueur = joueur;
this.monde = monde;
this.image = image;
}
public MapData(short id, String joueur, Image image, String monde, String nom)
{
this.id = id;
this.joueur = joueur;
this.monde = monde;
this.setNom(nom);
}
public MapData(short id) throws Exception
{
this.id = id;
}
public boolean save()
{
boolean ok = true;
String nomImg = "map"+ id;
ImageOnMap plugin = (ImageOnMap)Bukkit.getPluginManager().getPlugin("ImageOnMap");
try
{
File outputfile = new File("./plugins/ImageOnMap/Image/"+ nomImg + ".png");
ImageIO.write(image, "png", outputfile);
// Enregistrement de la map dans la config
ArrayList<String> liste = new ArrayList<String>();
liste.add(String.valueOf(id));
liste.add(nomImg);
liste.add(joueur);
liste.add(monde);
plugin.getCustomConfig().set(nomImg, liste);
plugin.saveCustomConfig();
}
catch (IOException e)
{
e.printStackTrace();
ok = false;
}
return ok;
}
public void load() throws IOException
{
ImageOnMap plugin = (ImageOnMap)Bukkit.getPluginManager().getPlugin("ImageOnMap");
List<String> svg = plugin.getCustomConfig().getStringList("map"+id);
String nomImg = svg.get(1);
joueur = svg.get(2);
try
{
image = ImageIO.read(new File("./plugins/ImageOnMap/Image/"+ nomImg + ".png"));
}
catch (IOException e)
{
plugin.getLogger().log(Level.WARNING, "Image "+ nomImg +".png doesn't exists in Image directory.");
throw e;
}
}
public MapData(short id, String playerName, BufferedImage image, String worldName)
{
this(id, playerName, image, worldName, null);
}
public String getNom() {
return nom;
}
public Image getImage()
{
return image;
}
public void setNom(String nom) {
this.nom = nom;
}
public void setImage(BufferedImage image)
{
this.image = image;
}
public void save() throws IOException
{
String nomImg = "map" + id;
ImageOnMap plugin = (ImageOnMap) Bukkit.getPluginManager().getPlugin("ImageOnMap");
File outputfile = new File("./plugins/ImageOnMap/Image/" + nomImg + ".png");
ImageIO.write(image, "png", outputfile);
// Enregistrement de la map dans la config
ArrayList<String> liste = new ArrayList<String>();
liste.add(String.valueOf(id));
liste.add(nomImg);
liste.add(playerName);
liste.add(worldName);
plugin.getCustomConfig().set(nomImg, liste);
plugin.saveCustomConfig();
}
public void load() throws IOException
{
ImageOnMap plugin = (ImageOnMap) Bukkit.getPluginManager().getPlugin("ImageOnMap");
List<String> svg = plugin.getCustomConfig().getStringList("map" + id);
String nomImg = svg.get(1);
playerName = svg.get(2);
image = ImageIO.read(new File("./plugins/ImageOnMap/Image/" + nomImg + ".png"));
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}

View File

@ -5,7 +5,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
@ -61,20 +60,12 @@ public class PosterData
{
nomPoster = id;
setJoueur(svg.get(0));
try
{
short[] ids = new short[svg.size()-1];
for(int i = 0; i < ids.length; i++)
{
ids[i] = Short.parseShort(svg.get(i+1));
}
setIdMaps(ids);
}
catch(NumberFormatException e)
{
throw e;
}
short[] ids = new short[svg.size()-1];
for(int i = 0; i < ids.length; i++)
{
ids[i] = Short.parseShort(svg.get(i+1));
}
setIdMaps(ids);
}
else
{
@ -83,7 +74,7 @@ public class PosterData
}
public void save()
public void save() throws IOException
{
ArrayList<String> liste = new ArrayList<String>();
liste.add(joueur);
@ -139,17 +130,13 @@ public class PosterData
return customConfig;
}
public void saveCustomConfig()
public void saveCustomConfig() throws IOException
{
ImageOnMap plugin = (ImageOnMap)Bukkit.getPluginManager().getPlugin("ImageOnMap");
if (customConfig == null || customConfigFile == null) {
return;
}
try {
getCustomConfig().save(customConfigFile);
} catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + customConfigFile, ex);
}
getCustomConfig().save(customConfigFile);
}
}

View File

@ -1,134 +1,104 @@
package fr.moribus.imageonmap.map;
import java.awt.Image;
import java.awt.image.BufferedImage;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import fr.moribus.imageonmap.Poster;
import java.io.IOException;
public class PosterMap implements ImageMap
{
private SingleMap[] posterMap;
private PosterData data;
public PosterMap(BufferedImage img, Player joueur)
{
Poster poster = new Poster(img);
BufferedImage[] imgs = poster.getPoster();
posterMap = new SingleMap[imgs.length];
short[] idsMap = new short[posterMap.length];
for(int i = 0; i < posterMap.length; i++)
{
SingleMap map = new SingleMap(imgs[i], joueur);
posterMap[i] = map;
idsMap[i] = map.getId();
}
data = new PosterData(joueur.getName(), idsMap);
}
public PosterMap(String id) throws Exception
{
data = new PosterData(id);
short[] ids = data.getIdMaps();
posterMap = new SingleMap[ids.length];
for(int i = 0; i < ids.length; i++)
{
SingleMap map = new SingleMap(ids[i]);
posterMap[i] = map;
}
}
@Override
public boolean load()
{
boolean ok;
int i = 0;
do
{
ok = posterMap[i].load();
i++;
}
while(ok && i < posterMap.length);
return ok;
}
private SingleMap[] posterMap;
private PosterData data;
@Override
public boolean save()
{
boolean ok;
int i = 0;
do
{
ok = posterMap[i].save();
i++;
}
while(ok && i < posterMap.length);
data.save();
return ok;
}
public PosterMap(BufferedImage img, Player joueur)
{
Poster poster = new Poster(img);
BufferedImage[] imgs = poster.getPoster();
posterMap = new SingleMap[imgs.length];
@Override
public void give(Inventory inv)
{
int i = 0;
do
{
posterMap[i].give(inv);
i++;
}
while(i < posterMap.length);
}
short[] idsMap = new short[posterMap.length];
for (int i = 0; i < posterMap.length; i++)
{
SingleMap map = new SingleMap(imgs[i], joueur);
posterMap[i] = map;
idsMap[i] = map.getId();
}
@Override
public boolean isNamed()
{
boolean ok;
int i = 0;
do
{
ok = posterMap[i].isNamed();
i++;
}
while(ok && i < posterMap.length);
return ok;
}
data = new PosterData(joueur.getName(), idsMap);
}
@Override
public void setImage(BufferedImage image)
{
Poster poster = new Poster(image);
BufferedImage[] imgs = poster.getPoster();
int i = 0;
do
{
posterMap[i].setImage(imgs[i]);
i++;
}
while(i < imgs.length);
}
public PosterMap(String id) throws Exception
{
data = new PosterData(id);
@Override
public void send(Player joueur)
{
int i = 0;
do
{
posterMap[i].send(joueur);
i++;
}
while(i < posterMap.length);
}
short[] ids = data.getIdMaps();
posterMap = new SingleMap[ids.length];
for (int i = 0; i < ids.length; i++)
{
SingleMap map = new SingleMap(ids[i]);
posterMap[i] = map;
}
}
@Override
public void load()
{
for(SingleMap map : posterMap)
{
map.load();
}
}
@Override
public void save() throws IOException
{
for(SingleMap map : posterMap)
{
map.save();
}
}
@Override
public void give(Inventory inv)
{
for(SingleMap map : posterMap)
{
map.give(inv);
}
}
@Override
public boolean isNamed()
{
for(SingleMap map : posterMap)
{
if(!map.isNamed()) return false;
}
return true;
}
@Override
public void setImage(BufferedImage image)
{
Poster poster = new Poster(image);
BufferedImage[] imgs = poster.getPoster();
for(int i = 0; i < posterMap.length; i++)
{
posterMap[i].setImage(imgs[i]);
}
}
@Override
public void send(Player player)
{
for(SingleMap map : posterMap)
{
map.send(player);
}
}
}

View File

@ -1,7 +1,6 @@
package fr.moribus.imageonmap.map;
import fr.moribus.imageonmap.ImgUtility;
import java.awt.Image;
import org.bukkit.Bukkit;
import org.bukkit.Material;
@ -13,116 +12,101 @@ import org.bukkit.map.MapView;
import fr.moribus.imageonmap.Rendu;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class SingleMap implements ImageMap
{
private MapData data;
private MapView map;
private boolean named;
public final int LARGEUR = 128;
public final int HAUTEUR = 128;
@SuppressWarnings("deprecation")
public SingleMap(BufferedImage img, Player joueur)
{
map = Bukkit.createMap(joueur.getWorld());
this.named = false;
data = new MapData(map.getId(), joueur.getName(), ImgUtility.scaleImage(img, LARGEUR, HAUTEUR), joueur.getWorld().getName());
}
@SuppressWarnings("deprecation")
public SingleMap(Image img, Player joueur, String name)
{
map = Bukkit.createMap(joueur.getWorld());
data = new MapData(map.getId(), joueur.getName(), ImgUtility.scaleImage(img, LARGEUR, HAUTEUR), joueur.getWorld().getName(), name);
}
@SuppressWarnings("deprecation")
public SingleMap(short id) throws Exception
{
try
{
data = new MapData(id);
data.load();
map = Bukkit.getMap(id);
}
catch (Exception e)
{
throw e;
}
}
private final MapData data;
private final MapView map;
@Override
public boolean save()
{
return data.save();
}
public final int LARGEUR = 128;
public final int HAUTEUR = 128;
@SuppressWarnings("deprecation")
@Override
public void give(Inventory inv)
{
ItemStack itemMap = new ItemStack(Material.MAP, 1, map.getId());
if(isNamed())
{
ItemMeta meta = itemMap.getItemMeta();
meta.setDisplayName(data.getNom());
itemMap.setItemMeta(meta);
}
inv.addItem(itemMap);
}
public SingleMap(BufferedImage img, Player player)
{
this(img, player, null);
}
@Override
public boolean load()
{
if(map != null)
{
SingleMap.SupprRendu(map);
map.addRenderer(new Rendu(data.getImage()));
return true;
}
else
return false;
}
public SingleMap(BufferedImage img, Player player, String imageName)
{
map = Bukkit.createMap(player.getWorld());
@Override
public boolean isNamed()
{
return named;
}
@SuppressWarnings("deprecation")
public short getId()
{
return map.getId();
}
data = new MapData(map.getId(), player.getName(), ImgUtility.scaleImage(img, LARGEUR, HAUTEUR), player.getWorld().getName(), imageName);
}
@Override
public void setImage(BufferedImage image)
{
data.setImage(image);
load();
}
@SuppressWarnings("deprecation")
public SingleMap(short id) throws IOException, IllegalArgumentException
{
data = new MapData(id);
data.load();
map = Bukkit.getMap(id);
if(map == null)
throw new IllegalArgumentException("Map ID '"+id+"' doesn't exist");
}
@Override
public void send(Player joueur)
{
joueur.sendMap(map);
}
@Override
public void save() throws IOException
{
data.save();
}
public static void SupprRendu(MapView map)
{
if (map.getRenderers().size() > 0)
{
int i = 0, t = map.getRenderers().size();
while (i < t)
{
map.removeRenderer(map.getRenderers().get(i));
i++;
}
}
}
@SuppressWarnings("deprecation")
@Override
public void give(Inventory inv)
{
ItemStack itemMap = new ItemStack(Material.MAP, 1, map.getId());
if (isNamed())
{
ItemMeta meta = itemMap.getItemMeta();
meta.setDisplayName(data.getName());
itemMap.setItemMeta(meta);
}
inv.addItem(itemMap);
}
@Override
public void load()
{
SingleMap.SupprRendu(map);
map.addRenderer(new Rendu(data.getImage()));
}
@Override
public boolean isNamed()
{
return data.getName() != null;
}
@SuppressWarnings("deprecation")
public short getId()
{
return map.getId();
}
@Override
public void setImage(BufferedImage image)
{
data.setImage(image);
load();
}
@Override
public void send(Player joueur)
{
joueur.sendMap(map);
}
public static void SupprRendu(MapView map)
{
if (map.getRenderers().size() > 0)
{
int i = 0, t = map.getRenderers().size();
while (i < t)
{
map.removeRenderer(map.getRenderers().get(i));
i++;
}
}
}
}