diff --git a/src/main/java/fr/eyzox/bsc/config/Config.java b/src/main/java/fr/eyzox/bsc/config/Config.java index 17d492e..9b55255 100644 --- a/src/main/java/fr/eyzox/bsc/config/Config.java +++ b/src/main/java/fr/eyzox/bsc/config/Config.java @@ -6,28 +6,29 @@ public class Config { - private final Map groups = new LinkedHashMap(); - - public Config() {} - - public void addOptionGroup(final ConfigOptionGroup optionGroup) { - this.groups.put(optionGroup.getName(), optionGroup); - } - - public void removeOptionGroup(final ConfigOptionGroup optionGroup) { - this.removeOptionGroup(optionGroup.getName()); - } - - public void removeOptionGroup(final String optionGroupeName) { - this.groups.remove(optionGroupeName); - } - - public ConfigOptionGroup getOptionGroup(final String name) { - return groups.get(name); - } - - public Collection getOptionGroups() { - return groups.values(); - } - + private final Map groups = new LinkedHashMap(); + + public Config() { + } + + public void addOptionGroup(final ConfigOptionGroup optionGroup) { + this.groups.put(optionGroup.getName(), optionGroup); + } + + public void removeOptionGroup(final ConfigOptionGroup optionGroup) { + this.removeOptionGroup(optionGroup.getName()); + } + + public void removeOptionGroup(final String optionGroupeName) { + this.groups.remove(optionGroupeName); + } + + public ConfigOptionGroup getOptionGroup(final String name) { + return groups.get(name); + } + + public Collection getOptionGroups() { + return groups.values(); + } + } diff --git a/src/main/java/fr/eyzox/bsc/config/ConfigOptionGroup.java b/src/main/java/fr/eyzox/bsc/config/ConfigOptionGroup.java index 792b883..7ff5eb2 100644 --- a/src/main/java/fr/eyzox/bsc/config/ConfigOptionGroup.java +++ b/src/main/java/fr/eyzox/bsc/config/ConfigOptionGroup.java @@ -1,42 +1,42 @@ package fr.eyzox.bsc.config; +import fr.eyzox.bsc.config.option.IConfigOption; + import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; -import fr.eyzox.bsc.config.option.IConfigOption; - public class ConfigOptionGroup { - private final String name; - private final Map options = new LinkedHashMap(); - - public ConfigOptionGroup(final String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void addOption(final IConfigOption option) { - this.options.put(option.getName(), option); - } - - public void removeOption(final String optionName) { - this.options.remove(optionName); - } - - public void removeOption(final IConfigOption option) { - this.removeOption(option.getName()); - } - - public IConfigOption getOption(final String name) { - return options.get(name); - } - - public Collection getOptions() { - return options.values(); - } - + private final String name; + private final Map options = new LinkedHashMap(); + + public ConfigOptionGroup(final String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void addOption(final IConfigOption option) { + this.options.put(option.getName(), option); + } + + public void removeOption(final String optionName) { + this.options.remove(optionName); + } + + public void removeOption(final IConfigOption option) { + this.removeOption(option.getName()); + } + + public IConfigOption getOption(final String name) { + return options.get(name); + } + + public Collection getOptions() { + return options.values(); + } + } diff --git a/src/main/java/fr/eyzox/bsc/config/IConfigListener.java b/src/main/java/fr/eyzox/bsc/config/IConfigListener.java index 6895c3c..c106865 100644 --- a/src/main/java/fr/eyzox/bsc/config/IConfigListener.java +++ b/src/main/java/fr/eyzox/bsc/config/IConfigListener.java @@ -1,5 +1,5 @@ package fr.eyzox.bsc.config; public interface IConfigListener { - public void onChange(final Config config); + public void onChange(final Config config); } diff --git a/src/main/java/fr/eyzox/bsc/config/IConfigProvider.java b/src/main/java/fr/eyzox/bsc/config/IConfigProvider.java index d7ce3dd..187b34c 100644 --- a/src/main/java/fr/eyzox/bsc/config/IConfigProvider.java +++ b/src/main/java/fr/eyzox/bsc/config/IConfigProvider.java @@ -1,10 +1,15 @@ package fr.eyzox.bsc.config; public interface IConfigProvider { - public Config getConfig(); - public void addConfigListener(final IConfigListener listener); - public void removeConfigListener(final IConfigListener listener); - public void fireConfigChanged(); - public void loadConfig(); - public void unloadConfig(); + public Config getConfig(); + + public void addConfigListener(final IConfigListener listener); + + public void removeConfigListener(final IConfigListener listener); + + public void fireConfigChanged(); + + public void loadConfig(); + + public void unloadConfig(); } diff --git a/src/main/java/fr/eyzox/bsc/config/loader/AbstractFileConfigLoader.java b/src/main/java/fr/eyzox/bsc/config/loader/AbstractFileConfigLoader.java index a044035..b28c91f 100644 --- a/src/main/java/fr/eyzox/bsc/config/loader/AbstractFileConfigLoader.java +++ b/src/main/java/fr/eyzox/bsc/config/loader/AbstractFileConfigLoader.java @@ -1,86 +1,81 @@ package fr.eyzox.bsc.config.loader; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.file.AccessDeniedException; -import java.nio.file.NoSuchFileException; - import fr.eyzox.bsc.config.Config; import fr.eyzox.bsc.exception.InvalidValueException; +import java.io.*; +import java.nio.file.AccessDeniedException; +import java.nio.file.NoSuchFileException; + public abstract class AbstractFileConfigLoader implements IConfigLoader { - private final File file; - private final IErrorManager errorManager = new FileErrorManager(); - - public AbstractFileConfigLoader(final File file) { - this.file = file; - } - - @Override - public void load(Config config) throws NoSuchFileException, FileNotFoundException, AccessDeniedException, IOException, InvalidValueException{ - if(!file.exists()) { - throw new NoSuchFileException(file.getAbsolutePath()); - } - - if(!file.isFile()) { - throw new FileNotFoundException(file.getAbsolutePath() + "is not a file"); - } - - if(!file.canRead()) { - throw new AccessDeniedException(file.getAbsolutePath() + "must allow reading"); - } - errorManager.getErrors().clear(); - } - - @Override - public void save(Config config) throws FileNotFoundException, AccessDeniedException, IOException { - if(file.exists()) { - if(!file.isFile()) { - throw new FileNotFoundException(file.getAbsolutePath() + " is not a file"); - } - - if(!file.canWrite()) { - throw new AccessDeniedException(file.getAbsolutePath()+" must allow writing"); - } - }else if(!file.getParentFile().canWrite()){ - throw new AccessDeniedException(file.getParentFile().getAbsolutePath()+" must allow writing"); - } - } - - public File getFile() { - return file; - } - - @Override - public IErrorManager getErrorManager() { - return errorManager; - } - - protected class FileErrorManager extends ErrorManager { - @Override - public void output(PrintWriter out) throws IOException { - super.output(out); - out.println(); - out.println("-------- ORIGINAL FILE --------"); - out.println(); - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(file)); - String s = null; - while((s=in.readLine())!=null) { - out.println(s); - } - }finally { - if(in != null) { - in.close(); - } - } - } - } + private final File file; + private final IErrorManager errorManager = new FileErrorManager(); + + public AbstractFileConfigLoader(final File file) { + this.file = file; + } + + @Override + public void load(Config config) throws NoSuchFileException, FileNotFoundException, AccessDeniedException, IOException, InvalidValueException { + if (!file.exists()) { + throw new NoSuchFileException(file.getAbsolutePath()); + } + + if (!file.isFile()) { + throw new FileNotFoundException(file.getAbsolutePath() + "is not a file"); + } + + if (!file.canRead()) { + throw new AccessDeniedException(file.getAbsolutePath() + "must allow reading"); + } + errorManager.getErrors().clear(); + } + + @Override + public void save(Config config) throws FileNotFoundException, AccessDeniedException, IOException { + if (file.exists()) { + if (!file.isFile()) { + throw new FileNotFoundException(file.getAbsolutePath() + " is not a file"); + } + + if (!file.canWrite()) { + throw new AccessDeniedException(file.getAbsolutePath() + " must allow writing"); + } + } else if (!file.getParentFile().canWrite()) { + throw new AccessDeniedException(file.getParentFile().getAbsolutePath() + " must allow writing"); + } + } + + public File getFile() { + return file; + } + + @Override + public IErrorManager getErrorManager() { + return errorManager; + } + + protected class FileErrorManager extends ErrorManager { + @Override + public void output(PrintWriter out) throws IOException { + super.output(out); + out.println(); + out.println("-------- ORIGINAL FILE --------"); + out.println(); + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(file)); + String s = null; + while ((s = in.readLine()) != null) { + out.println(s); + } + } finally { + if (in != null) { + in.close(); + } + } + } + } } diff --git a/src/main/java/fr/eyzox/bsc/config/loader/ErrorManager.java b/src/main/java/fr/eyzox/bsc/config/loader/ErrorManager.java index dbd262c..4936089 100644 --- a/src/main/java/fr/eyzox/bsc/config/loader/ErrorManager.java +++ b/src/main/java/fr/eyzox/bsc/config/loader/ErrorManager.java @@ -1,39 +1,40 @@ package fr.eyzox.bsc.config.loader; +import fr.eyzox.bsc.exception.ConfigException; + import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.LinkedList; import java.util.List; -import fr.eyzox.bsc.exception.ConfigException; +public class ErrorManager implements IErrorManager { + + private final List errors = new LinkedList(); + + public ErrorManager() { + } + + @Override + public void error(ConfigException exception) { + errors.add(exception); + } + + @Override + public boolean hasErrors() { + return !errors.isEmpty(); + } + + @Override + public void output(final PrintWriter out) throws IOException { + for (final ConfigException e : errors) { + out.println(e.getMessage()); + } + } -public class ErrorManager implements IErrorManager{ - - private final List errors = new LinkedList(); - - public ErrorManager() {} - - @Override - public void error(ConfigException exception) { - errors.add(exception); - } - - @Override - public boolean hasErrors() { - return !errors.isEmpty(); - } - - @Override - public void output(final PrintWriter out) throws IOException{ - for(final ConfigException e : errors) { - out.println(e.getMessage()); - } - } - - @Override - public Collection getErrors() { - return errors; - } + @Override + public Collection getErrors() { + return errors; + } } diff --git a/src/main/java/fr/eyzox/bsc/config/loader/IConfigLoader.java b/src/main/java/fr/eyzox/bsc/config/loader/IConfigLoader.java index 32f6063..9465e89 100644 --- a/src/main/java/fr/eyzox/bsc/config/loader/IConfigLoader.java +++ b/src/main/java/fr/eyzox/bsc/config/loader/IConfigLoader.java @@ -3,7 +3,9 @@ import fr.eyzox.bsc.config.Config; public interface IConfigLoader { - public void load(final Config config) throws Exception; - public void save(final Config config) throws Exception; - public IErrorManager getErrorManager(); + public void load(final Config config) throws Exception; + + public void save(final Config config) throws Exception; + + public IErrorManager getErrorManager(); } diff --git a/src/main/java/fr/eyzox/bsc/config/loader/IErrorManager.java b/src/main/java/fr/eyzox/bsc/config/loader/IErrorManager.java index 374f0d5..1883f8f 100644 --- a/src/main/java/fr/eyzox/bsc/config/loader/IErrorManager.java +++ b/src/main/java/fr/eyzox/bsc/config/loader/IErrorManager.java @@ -1,14 +1,17 @@ package fr.eyzox.bsc.config.loader; +import fr.eyzox.bsc.exception.ConfigException; + import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; -import fr.eyzox.bsc.exception.ConfigException; - public interface IErrorManager { - public void error(ConfigException exception); - public boolean hasErrors(); - public void output(final PrintWriter out) throws IOException; - public Collection getErrors(); + public void error(ConfigException exception); + + public boolean hasErrors(); + + public void output(final PrintWriter out) throws IOException; + + public Collection getErrors(); } diff --git a/src/main/java/fr/eyzox/bsc/config/loader/JSONConfigLoader.java b/src/main/java/fr/eyzox/bsc/config/loader/JSONConfigLoader.java index b853975..adbaafb 100644 --- a/src/main/java/fr/eyzox/bsc/config/loader/JSONConfigLoader.java +++ b/src/main/java/fr/eyzox/bsc/config/loader/JSONConfigLoader.java @@ -1,23 +1,8 @@ package fr.eyzox.bsc.config.loader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.nio.file.AccessDeniedException; -import java.nio.file.NoSuchFileException; -import java.util.LinkedList; -import java.util.List; - import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; - import fr.eyzox.bsc.config.Config; import fr.eyzox.bsc.config.ConfigOptionGroup; import fr.eyzox.bsc.config.option.ConfigOption; @@ -27,182 +12,188 @@ import fr.eyzox.bsc.exception.FormatException; import fr.eyzox.bsc.exception.InvalidValueException; +import java.io.*; +import java.nio.file.AccessDeniedException; +import java.nio.file.NoSuchFileException; +import java.util.LinkedList; +import java.util.List; + public class JSONConfigLoader extends AbstractFileConfigLoader { - public JSONConfigLoader(File file) { - super(file); - } - - @Override - public void load(Config config) throws NoSuchFileException, FileNotFoundException, AccessDeniedException, IOException, InvalidValueException { - super.load(config); - InputStream input = null; - try { - input = new FileInputStream(getFile()); - this.readJsonStream(input, config); - }finally { - if(input != null) { - input.close(); - } - } - - } - - @Override - public void save(Config config) throws FileNotFoundException, AccessDeniedException, IOException { - super.save(config); - OutputStream output = null; - try { - output = new FileOutputStream(getFile()); - this.writeJsonStream(output, config); - }finally { - if(output != null) { - output.close(); - } - } - } - - private void readJsonStream(final InputStream in, final Config config) throws IOException, InvalidValueException { - final JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); - - reader.beginObject(); - while (reader.hasNext()) { - - final String groupOptionName = reader.nextName(); - final ConfigOptionGroup optionGroup = config.getOptionGroup(groupOptionName); - - if(optionGroup != null) { - - if(reader.peek() != JsonToken.BEGIN_OBJECT) { - getErrorManager().error(new ConfigException(optionGroup.getName() + " : " + new FormatException(reader.peek().name(), JsonToken.BEGIN_OBJECT.name()).getMessage())); - reader.skipValue(); - } - - //Move to groupOption {...} - reader.beginObject(); - - while(reader.hasNext()) { - final String optionName = reader.nextName(); - final IConfigOption option = optionGroup.getOption(optionName); - - if(option != null) { - try { - if(option instanceof ConfigOption) { - readConfigOption(reader, (ConfigOption)option); - }else if(option instanceof ConfigOptionList) { - readConfigOptionList(reader, (ConfigOptionList)option); - }else { - //ERROR : Unknow type (this should never happens) - throw new RuntimeException("Unknown config option type !"); - } - }catch(ConfigException e) { - getErrorManager().error(e); - } - }else { - //warn : Unhandled Option (User has added an option in his configFile that doesn't exist) - getErrorManager().error(new ConfigException(optionName+" is not a valid option name")); - reader.skipValue(); - } - } - //Exit groupOption{...} - reader.endObject(); - }else { - //Unhandled OptionGroup (User has added an optionGroup in his configFile that doesn't exist) - getErrorManager().error(new ConfigException(groupOptionName+" is not a valid option group name")); - reader.skipValue(); - } - } - - reader.endObject(); - reader.close(); - } - - private String getOptionValue(final JsonReader reader, final IConfigOption option) throws IOException, FormatException { - final JsonToken token = reader.peek(); - switch (token) { - case BOOLEAN: - return Boolean.toString(reader.nextBoolean()); - case NUMBER: - return Integer.toString(reader.nextInt()); - case STRING: - return reader.nextString(); - default: - reader.skipValue(); - throw new FormatException(token.name(), " or or "); - } - } - - private void readConfigOption(final JsonReader reader, final ConfigOption configOption) throws IOException, ConfigException { - String value = null; - try { - value = getOptionValue(reader, configOption); - }catch(FormatException e) { - throw new ConfigException(configOption.getName()+" : "+e.getMessage()); - } - configOption.setValue(value); - } - - private void readConfigOptionList(final JsonReader reader, final ConfigOptionList configOptionList) throws IOException, InvalidValueException { - - final JsonToken token = reader.peek(); - - if(token != JsonToken.BEGIN_ARRAY) { - reader.skipValue(); - throw new ConfigException(configOptionList.getName()+" : "+new FormatException(token.name(), "").getMessage()); - } - - reader.beginArray(); - - final List values = new LinkedList(); - while(reader.hasNext()) { - String value = null; - try { - value = getOptionValue(reader, configOptionList); - values.add(value); - }catch(FormatException e) { - getErrorManager().error(new ConfigException(configOptionList.getName()+" : "+e.getMessage())); - } - - } - - reader.endArray(); - - configOptionList.setValues(values); - - } - - private void writeJsonStream(final OutputStream out, final Config config) throws IOException { - JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8")); - writer.setIndent(" "); - writer.beginObject(); - for(final ConfigOptionGroup group : config.getOptionGroups()){ - writer.name(group.getName()); - writer.beginObject(); - for(final IConfigOption option : group.getOptions()) { - if(option instanceof ConfigOption) { - writeConfigOption(writer, (ConfigOption) option); - }else if(option instanceof ConfigOptionList) { - writeConfigOptionList(writer, (ConfigOptionList) option); - } - } - writer.endObject(); - } - writer.endObject(); - writer.close(); - } - - private void writeConfigOption(final JsonWriter writer, final ConfigOption option) throws IOException { - writer.name(option.getName()); - writer.value(option.getValue()); - } - - private void writeConfigOptionList(final JsonWriter writer, final ConfigOptionList option) throws IOException { - writer.name(option.getName()); - writer.beginArray(); - for(final String value : option.getValues()) { - writer.value(value); - } - writer.endArray(); - } + public JSONConfigLoader(File file) { + super(file); + } + + @Override + public void load(Config config) throws NoSuchFileException, FileNotFoundException, AccessDeniedException, IOException, InvalidValueException { + super.load(config); + InputStream input = null; + try { + input = new FileInputStream(getFile()); + this.readJsonStream(input, config); + } finally { + if (input != null) { + input.close(); + } + } + + } + + @Override + public void save(Config config) throws FileNotFoundException, AccessDeniedException, IOException { + super.save(config); + OutputStream output = null; + try { + output = new FileOutputStream(getFile()); + this.writeJsonStream(output, config); + } finally { + if (output != null) { + output.close(); + } + } + } + + private void readJsonStream(final InputStream in, final Config config) throws IOException, InvalidValueException { + final JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); + + reader.beginObject(); + while (reader.hasNext()) { + + final String groupOptionName = reader.nextName(); + final ConfigOptionGroup optionGroup = config.getOptionGroup(groupOptionName); + + if (optionGroup != null) { + + if (reader.peek() != JsonToken.BEGIN_OBJECT) { + getErrorManager().error(new ConfigException(optionGroup.getName() + " : " + new FormatException(reader.peek().name(), JsonToken.BEGIN_OBJECT.name()).getMessage())); + reader.skipValue(); + } + + //Move to groupOption {...} + reader.beginObject(); + + while (reader.hasNext()) { + final String optionName = reader.nextName(); + final IConfigOption option = optionGroup.getOption(optionName); + + if (option != null) { + try { + if (option instanceof ConfigOption) { + readConfigOption(reader, (ConfigOption) option); + } else if (option instanceof ConfigOptionList) { + readConfigOptionList(reader, (ConfigOptionList) option); + } else { + //ERROR : Unknow type (this should never happens) + throw new RuntimeException("Unknown config option type !"); + } + } catch (ConfigException e) { + getErrorManager().error(e); + } + } else { + //warn : Unhandled Option (User has added an option in his configFile that doesn't exist) + getErrorManager().error(new ConfigException(optionName + " is not a valid option name")); + reader.skipValue(); + } + } + //Exit groupOption{...} + reader.endObject(); + } else { + //Unhandled OptionGroup (User has added an optionGroup in his configFile that doesn't exist) + getErrorManager().error(new ConfigException(groupOptionName + " is not a valid option group name")); + reader.skipValue(); + } + } + + reader.endObject(); + reader.close(); + } + + private String getOptionValue(final JsonReader reader, final IConfigOption option) throws IOException, FormatException { + final JsonToken token = reader.peek(); + switch (token) { + case BOOLEAN: + return Boolean.toString(reader.nextBoolean()); + case NUMBER: + return Integer.toString(reader.nextInt()); + case STRING: + return reader.nextString(); + default: + reader.skipValue(); + throw new FormatException(token.name(), " or or "); + } + } + + private void readConfigOption(final JsonReader reader, final ConfigOption configOption) throws IOException, ConfigException { + String value = null; + try { + value = getOptionValue(reader, configOption); + } catch (FormatException e) { + throw new ConfigException(configOption.getName() + " : " + e.getMessage()); + } + configOption.setValue(value); + } + + private void readConfigOptionList(final JsonReader reader, final ConfigOptionList configOptionList) throws IOException, InvalidValueException { + + final JsonToken token = reader.peek(); + + if (token != JsonToken.BEGIN_ARRAY) { + reader.skipValue(); + throw new ConfigException(configOptionList.getName() + " : " + new FormatException(token.name(), "").getMessage()); + } + + reader.beginArray(); + + final List values = new LinkedList(); + while (reader.hasNext()) { + String value = null; + try { + value = getOptionValue(reader, configOptionList); + values.add(value); + } catch (FormatException e) { + getErrorManager().error(new ConfigException(configOptionList.getName() + " : " + e.getMessage())); + } + + } + + reader.endArray(); + + configOptionList.setValues(values); + + } + + private void writeJsonStream(final OutputStream out, final Config config) throws IOException { + JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8")); + writer.setIndent(" "); + writer.beginObject(); + for (final ConfigOptionGroup group : config.getOptionGroups()) { + writer.name(group.getName()); + writer.beginObject(); + for (final IConfigOption option : group.getOptions()) { + if (option instanceof ConfigOption) { + writeConfigOption(writer, (ConfigOption) option); + } else if (option instanceof ConfigOptionList) { + writeConfigOptionList(writer, (ConfigOptionList) option); + } + } + writer.endObject(); + } + writer.endObject(); + writer.close(); + } + + private void writeConfigOption(final JsonWriter writer, final ConfigOption option) throws IOException { + writer.name(option.getName()); + writer.value(option.getValue()); + } + + private void writeConfigOptionList(final JsonWriter writer, final ConfigOptionList option) throws IOException { + writer.name(option.getName()); + writer.beginArray(); + for (final String value : option.getValues()) { + writer.value(value); + } + writer.endArray(); + } } diff --git a/src/main/java/fr/eyzox/bsc/config/option/AbstractConfigOption.java b/src/main/java/fr/eyzox/bsc/config/option/AbstractConfigOption.java index cca9fa6..c751228 100644 --- a/src/main/java/fr/eyzox/bsc/config/option/AbstractConfigOption.java +++ b/src/main/java/fr/eyzox/bsc/config/option/AbstractConfigOption.java @@ -2,41 +2,41 @@ import fr.eyzox.bsc.config.option.validator.IValidator; -public abstract class AbstractConfigOption implements IConfigOption{ - - private final String name; - private String description; - private IValidator validator; - - public AbstractConfigOption(final String name) { - this(name, null, ""); - } - - public AbstractConfigOption(final String name, final IValidator validator, final String description) { - this.name = name; - this.validator = validator; - this.description = description; - } - - public String getName() { - return this.name; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - if(description == null) return; - this.description = description; - } - - public IValidator getValidator() { - return validator; - } - - public void setValidator(IValidator validator) { - this.validator = validator; - } +public abstract class AbstractConfigOption implements IConfigOption { + + private final String name; + private String description; + private IValidator validator; + + public AbstractConfigOption(final String name) { + this(name, null, ""); + } + + public AbstractConfigOption(final String name, final IValidator validator, final String description) { + this.name = name; + this.validator = validator; + this.description = description; + } + + public String getName() { + return this.name; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + if (description == null) return; + this.description = description; + } + + public IValidator getValidator() { + return validator; + } + + public void setValidator(IValidator validator) { + this.validator = validator; + } } diff --git a/src/main/java/fr/eyzox/bsc/config/option/ConfigOption.java b/src/main/java/fr/eyzox/bsc/config/option/ConfigOption.java index bfd2cd5..8be35c0 100644 --- a/src/main/java/fr/eyzox/bsc/config/option/ConfigOption.java +++ b/src/main/java/fr/eyzox/bsc/config/option/ConfigOption.java @@ -3,33 +3,33 @@ import fr.eyzox.bsc.config.option.validator.IValidator; import fr.eyzox.bsc.exception.InvalidValueException; -public class ConfigOption extends AbstractConfigOption{ - - private String value; - - public ConfigOption(final String name) { - super(name); - } - - public ConfigOption(final String name, final IValidator validator, final String description, final String defaultValue) { - super(name, validator, description); - this.value = defaultValue; - } - - public String getValue() { - return this.value; - } - - public void setValue(final String newValue) throws InvalidValueException{ - try { - if(getValidator() == null || getValidator().isValid(newValue) ) { - this.value = newValue; - }else { - throw new InvalidValueException(newValue); - } - }catch(final InvalidValueException e) { - e.setConfigOption(this); - throw e; - } - } +public class ConfigOption extends AbstractConfigOption { + + private String value; + + public ConfigOption(final String name) { + super(name); + } + + public ConfigOption(final String name, final IValidator validator, final String description, final String defaultValue) { + super(name, validator, description); + this.value = defaultValue; + } + + public String getValue() { + return this.value; + } + + public void setValue(final String newValue) throws InvalidValueException { + try { + if (getValidator() == null || getValidator().isValid(newValue)) { + this.value = newValue; + } else { + throw new InvalidValueException(newValue); + } + } catch (final InvalidValueException e) { + e.setConfigOption(this); + throw e; + } + } } diff --git a/src/main/java/fr/eyzox/bsc/config/option/ConfigOptionList.java b/src/main/java/fr/eyzox/bsc/config/option/ConfigOptionList.java index 4cf7c3e..0ad4f3e 100644 --- a/src/main/java/fr/eyzox/bsc/config/option/ConfigOptionList.java +++ b/src/main/java/fr/eyzox/bsc/config/option/ConfigOptionList.java @@ -1,51 +1,50 @@ package fr.eyzox.bsc.config.option; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - import fr.eyzox.bsc.config.option.validator.IValidator; import fr.eyzox.bsc.exception.InvalidValueException; import fr.eyzox.bsc.exception.MultiInvalidValueException; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + public class ConfigOptionList extends AbstractConfigOption { - private final List values = new LinkedList(); - - public ConfigOptionList(final String name) { - super(name); - } - - public ConfigOptionList(final String name, final IValidator validator, final String description) { - super(name, validator, description); - } - - public List getValues() { - return Collections.unmodifiableList(values); - } - - public void setValues(final List values) throws InvalidValueException{ - this.values.clear(); - if(getValidator() != null) { - final MultiInvalidValueException exceptions = new MultiInvalidValueException(values.toString()); - for(final String value : values) { - try { - if(!getValidator().isValid(value)) { - exceptions.exception(new InvalidValueException(value)); - } - }catch(final InvalidValueException e) { - exceptions.exception(e); - } - } - if(!exceptions.getExceptions().isEmpty()) { - exceptions.setConfigOption(this); - throw exceptions; - } - } - - this.values.addAll(values); - } - - + private final List values = new LinkedList(); + + public ConfigOptionList(final String name) { + super(name); + } + + public ConfigOptionList(final String name, final IValidator validator, final String description) { + super(name, validator, description); + } + + public List getValues() { + return Collections.unmodifiableList(values); + } + + public void setValues(final List values) throws InvalidValueException { + this.values.clear(); + if (getValidator() != null) { + final MultiInvalidValueException exceptions = new MultiInvalidValueException(values.toString()); + for (final String value : values) { + try { + if (!getValidator().isValid(value)) { + exceptions.exception(new InvalidValueException(value)); + } + } catch (final InvalidValueException e) { + exceptions.exception(e); + } + } + if (!exceptions.getExceptions().isEmpty()) { + exceptions.setConfigOption(this); + throw exceptions; + } + } + + this.values.addAll(values); + } + } diff --git a/src/main/java/fr/eyzox/bsc/config/option/IConfigOption.java b/src/main/java/fr/eyzox/bsc/config/option/IConfigOption.java index 913311e..bcc87d4 100644 --- a/src/main/java/fr/eyzox/bsc/config/option/IConfigOption.java +++ b/src/main/java/fr/eyzox/bsc/config/option/IConfigOption.java @@ -1,6 +1,7 @@ package fr.eyzox.bsc.config.option; public interface IConfigOption { - public String getName(); - public String getDescription(); + public String getName(); + + public String getDescription(); } diff --git a/src/main/java/fr/eyzox/bsc/config/option/validator/BooleanValidator.java b/src/main/java/fr/eyzox/bsc/config/option/validator/BooleanValidator.java index 9bd15b6..49007ce 100644 --- a/src/main/java/fr/eyzox/bsc/config/option/validator/BooleanValidator.java +++ b/src/main/java/fr/eyzox/bsc/config/option/validator/BooleanValidator.java @@ -4,20 +4,22 @@ public class BooleanValidator implements IValidator { - private static final BooleanValidator INSTANCE = new BooleanValidator(); - private BooleanValidator() {} - - @Override - public boolean isValid(String value) throws InvalidValueException { - if(value.equalsIgnoreCase("TRUE") || value.equalsIgnoreCase("FALSE")) { - return true; - }else { - throw new InvalidValueException(value, ""); - } - } - - public static BooleanValidator getInstance() { - return INSTANCE; - } + private static final BooleanValidator INSTANCE = new BooleanValidator(); + + private BooleanValidator() { + } + + public static BooleanValidator getInstance() { + return INSTANCE; + } + + @Override + public boolean isValid(String value) throws InvalidValueException { + if (value.equalsIgnoreCase("TRUE") || value.equalsIgnoreCase("FALSE")) { + return true; + } else { + throw new InvalidValueException(value, ""); + } + } } diff --git a/src/main/java/fr/eyzox/bsc/config/option/validator/IValidator.java b/src/main/java/fr/eyzox/bsc/config/option/validator/IValidator.java index 4ea38bf..eba2b4a 100644 --- a/src/main/java/fr/eyzox/bsc/config/option/validator/IValidator.java +++ b/src/main/java/fr/eyzox/bsc/config/option/validator/IValidator.java @@ -3,5 +3,5 @@ import fr.eyzox.bsc.exception.InvalidValueException; public interface IValidator { - public boolean isValid(final String value) throws InvalidValueException; + public boolean isValid(final String value) throws InvalidValueException; } diff --git a/src/main/java/fr/eyzox/bsc/config/option/validator/IntValidator.java b/src/main/java/fr/eyzox/bsc/config/option/validator/IntValidator.java index 173940e..2fd5a58 100644 --- a/src/main/java/fr/eyzox/bsc/config/option/validator/IntValidator.java +++ b/src/main/java/fr/eyzox/bsc/config/option/validator/IntValidator.java @@ -4,32 +4,32 @@ public class IntValidator implements IValidator { - private final int minValue, maxValue; - - public IntValidator(final int minValue, final int maxValue) { - this.minValue = minValue; - this.maxValue = maxValue; - } - - public IntValidator() { - this(Integer.MIN_VALUE, Integer.MAX_VALUE); - } - - @Override - public boolean isValid(String value) throws InvalidValueException{ - int intValue = 0; - - try { - intValue = Integer.parseInt(value); - }catch(NumberFormatException e) { - throw new InvalidValueException(value, "", e); - } - - if(intValue >= minValue && intValue <= maxValue) { - return true; - }else { - throw new InvalidValueException(value, "INTEGER between ["+minValue+", "+maxValue+"]"); - } - } + private final int minValue, maxValue; + + public IntValidator(final int minValue, final int maxValue) { + this.minValue = minValue; + this.maxValue = maxValue; + } + + public IntValidator() { + this(Integer.MIN_VALUE, Integer.MAX_VALUE); + } + + @Override + public boolean isValid(String value) throws InvalidValueException { + int intValue = 0; + + try { + intValue = Integer.parseInt(value); + } catch (NumberFormatException e) { + throw new InvalidValueException(value, "", e); + } + + if (intValue >= minValue && intValue <= maxValue) { + return true; + } else { + throw new InvalidValueException(value, "INTEGER between [" + minValue + ", " + maxValue + "]"); + } + } } diff --git a/src/main/java/fr/eyzox/bsc/exception/ConfigException.java b/src/main/java/fr/eyzox/bsc/exception/ConfigException.java index 1feae4f..f6a6ad5 100644 --- a/src/main/java/fr/eyzox/bsc/exception/ConfigException.java +++ b/src/main/java/fr/eyzox/bsc/exception/ConfigException.java @@ -2,26 +2,25 @@ public class ConfigException extends RuntimeException { - public ConfigException() { - super(); - } - - public ConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - - public ConfigException(String message, Throwable cause) { - super(message, cause); - } - - public ConfigException(String message) { - super(message); - } - - public ConfigException(Throwable cause) { - super(cause); - } - - + public ConfigException() { + super(); + } + + public ConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public ConfigException(String message, Throwable cause) { + super(message, cause); + } + + public ConfigException(String message) { + super(message); + } + + public ConfigException(Throwable cause) { + super(cause); + } + } diff --git a/src/main/java/fr/eyzox/bsc/exception/FormatException.java b/src/main/java/fr/eyzox/bsc/exception/FormatException.java index 432c572..43d6e0c 100644 --- a/src/main/java/fr/eyzox/bsc/exception/FormatException.java +++ b/src/main/java/fr/eyzox/bsc/exception/FormatException.java @@ -1,13 +1,13 @@ package fr.eyzox.bsc.exception; public class FormatException extends ConfigException { - - public FormatException(final String type, final String expected) { - this(type, expected, null); - } - - public FormatException(final String type, final String expected, final Throwable cause) { - super(new StringBuilder("Invalid data type : \"").append(type).append("\" expected : \"").append(expected).append("\"").toString(), cause); - } + + public FormatException(final String type, final String expected) { + this(type, expected, null); + } + + public FormatException(final String type, final String expected, final Throwable cause) { + super(new StringBuilder("Invalid data type : \"").append(type).append("\" expected : \"").append(expected).append("\"").toString(), cause); + } } diff --git a/src/main/java/fr/eyzox/bsc/exception/InvalidValueException.java b/src/main/java/fr/eyzox/bsc/exception/InvalidValueException.java index 5520354..6257316 100644 --- a/src/main/java/fr/eyzox/bsc/exception/InvalidValueException.java +++ b/src/main/java/fr/eyzox/bsc/exception/InvalidValueException.java @@ -4,54 +4,54 @@ public class InvalidValueException extends ConfigException { - private IConfigOption configOption; - private final String expected; - private final String value; - - public InvalidValueException(final String value) { - this(value, null, null); - } - - public InvalidValueException(final String newValue, final String expected) { - this(newValue, expected, null); - } - - public InvalidValueException(final String value, final String expected, final Throwable cause) { - super(cause); - this.expected = expected; - this.value = value; - } - - public IConfigOption getConfigOption() { - return configOption; - } - - public void setConfigOption(IConfigOption configOption) { - this.configOption = configOption; - } - - public String getExpected() { - return expected; - } - - public String getValue() { - return value; - } - - @Override - public String getMessage() { - final StringBuilder s = new StringBuilder(); - if(getConfigOption() != null) { - s.append(getConfigOption().getName()); - s.append(" : "); - } - s.append("Unvalid value : "); - s.append(getValue()); - if(getExpected() != null) { - s.append(" expected : "); - s.append(getExpected()); - } - return s.toString(); - } - + private final String expected; + private final String value; + private IConfigOption configOption; + + public InvalidValueException(final String value) { + this(value, null, null); + } + + public InvalidValueException(final String newValue, final String expected) { + this(newValue, expected, null); + } + + public InvalidValueException(final String value, final String expected, final Throwable cause) { + super(cause); + this.expected = expected; + this.value = value; + } + + public IConfigOption getConfigOption() { + return configOption; + } + + public void setConfigOption(IConfigOption configOption) { + this.configOption = configOption; + } + + public String getExpected() { + return expected; + } + + public String getValue() { + return value; + } + + @Override + public String getMessage() { + final StringBuilder s = new StringBuilder(); + if (getConfigOption() != null) { + s.append(getConfigOption().getName()); + s.append(" : "); + } + s.append("Unvalid value : "); + s.append(getValue()); + if (getExpected() != null) { + s.append(" expected : "); + s.append(getExpected()); + } + return s.toString(); + } + } diff --git a/src/main/java/fr/eyzox/bsc/exception/MultiInvalidValueException.java b/src/main/java/fr/eyzox/bsc/exception/MultiInvalidValueException.java index 8da0ef5..fcb5164 100644 --- a/src/main/java/fr/eyzox/bsc/exception/MultiInvalidValueException.java +++ b/src/main/java/fr/eyzox/bsc/exception/MultiInvalidValueException.java @@ -5,28 +5,28 @@ public class MultiInvalidValueException extends InvalidValueException { - private final Collection exceptions = new LinkedList(); - - public MultiInvalidValueException(String value) { - super(value); - } - - public void exception(final InvalidValueException exception) { - exceptions.add(exception); - } - - @Override - public String getMessage() { - final StringBuilder s = new StringBuilder(super.getMessage()); - for(final InvalidValueException e : exceptions) { - s.append("\t"); - s.append(e.getMessage()); - } - return s.toString(); - } - - public Collection getExceptions() { - return exceptions; - } + private final Collection exceptions = new LinkedList(); + + public MultiInvalidValueException(String value) { + super(value); + } + + public void exception(final InvalidValueException exception) { + exceptions.add(exception); + } + + @Override + public String getMessage() { + final StringBuilder s = new StringBuilder(super.getMessage()); + for (final InvalidValueException e : exceptions) { + s.append("\t"); + s.append(e.getMessage()); + } + return s.toString(); + } + + public Collection getExceptions() { + return exceptions; + } } diff --git a/src/main/java/fr/eyzox/dependencygraph/DataKeyProvider.java b/src/main/java/fr/eyzox/dependencygraph/DataKeyProvider.java index e7ef813..2d7d446 100644 --- a/src/main/java/fr/eyzox/dependencygraph/DataKeyProvider.java +++ b/src/main/java/fr/eyzox/dependencygraph/DataKeyProvider.java @@ -1,17 +1,19 @@ package fr.eyzox.dependencygraph; -import java.util.Collection; -import java.util.Map; - import fr.eyzox.dependencygraph.exceptions.DuplicateKeyException; import fr.eyzox.dependencygraph.interfaces.IData; +import java.util.Collection; +import java.util.Map; + public abstract class DataKeyProvider { - DataKeyProvider() { - } - - protected abstract > void buildIndex(final Map.Node> index, final DependencyGraph.Node theNode) throws DuplicateKeyException; - protected abstract > void removeFromIndex(final Map.Node> index, final DependencyGraph.Node theNode); - protected abstract void removeKeyFrom(final Collection c); + DataKeyProvider() { + } + + protected abstract > void buildIndex(final Map.Node> index, final DependencyGraph.Node theNode) throws DuplicateKeyException; + + protected abstract > void removeFromIndex(final Map.Node> index, final DependencyGraph.Node theNode); + + protected abstract void removeKeyFrom(final Collection c); } diff --git a/src/main/java/fr/eyzox/dependencygraph/DependencyGraph.java b/src/main/java/fr/eyzox/dependencygraph/DependencyGraph.java index 34e8ef0..a97c663 100644 --- a/src/main/java/fr/eyzox/dependencygraph/DependencyGraph.java +++ b/src/main/java/fr/eyzox/dependencygraph/DependencyGraph.java @@ -1,109 +1,101 @@ package fr.eyzox.dependencygraph; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - import fr.eyzox.dependencygraph.exceptions.DuplicateKeyException; import fr.eyzox.dependencygraph.interfaces.IData; import fr.eyzox.dependencygraph.interfaces.IDependencyProvider; -public class DependencyGraph>{ - - protected final Map index; - protected final Set nodes; - - protected final List availables = new ArrayList(); - private final List unmodifiableAvailable = Collections.unmodifiableList(availables); - - public DependencyGraph(final Collection c, final IDependencyProvider dependencyProvider) throws DuplicateKeyException{ - //Building index and nodes set - this.index = new HashMap(c.size()); - this.nodes = new HashSet.Node>(); - for(final DATA data : c) { - final Node node = new Node(data); - nodes.add(node); - node.keyProvider.buildIndex(index, node); - } - - for(DependencyGraph.Node node : nodes) { - node.type = dependencyProvider.provideDependency(node.data); - node.type.build(this, node); - } - - - - } - - public DATA poll(final int nextIndex) { - - final DependencyGraph.Node node = availables.remove(nextIndex); - - node.keyProvider.removeFromIndex(index, node); - - for(final DependencyGraph.Node next : node.requiredBySet) { - next.type.onElementPolled(this, node, next); - } - - return node.data; - } - - public boolean hasNext() { - return !availables.isEmpty(); - } - - public List.Node> getAvailables() { - return unmodifiableAvailable; - } - - protected void buildEdge(final DependencyGraph.Node node, final KEY dependency) { - final Node requiredNode = index.get(dependency); - if(requiredNode == null) { - throw new RuntimeException("Unable to build edge : the dependency "+dependency+" is not indexed"); - } - requiredNode.requiredBySet.add(node); - } - - public class Node { - private final DATA data; - private final DataKeyProvider keyProvider; - private DependencyType type; - private Set requiredBySet = new HashSet(); - - protected Node(final DATA data) { - this.data = data; - this.keyProvider = data.getDataKeyProvider(); - - if(this.keyProvider == null) { - throw new NullPointerException(); - } - } - - public DATA getData() { - return data; - } - - public DataKeyProvider getKeyProvider() { - return keyProvider; - } - - public DependencyType getType() { - return type; - } - - public Set getRequiredBySet() { - return requiredBySet; - } - - @Override - public String toString() { - return new StringBuilder("{data=").append(data.toString()).append(", type=").append(type.toString()).append(", requiredBy=").append(requiredBySet.toString()).append("}").toString(); - } - } - +import java.util.*; + +public class DependencyGraph> { + + protected final Map index; + protected final Set nodes; + + protected final List availables = new ArrayList(); + private final List unmodifiableAvailable = Collections.unmodifiableList(availables); + + public DependencyGraph(final Collection c, final IDependencyProvider dependencyProvider) throws DuplicateKeyException { + //Building index and nodes set + this.index = new HashMap(c.size()); + this.nodes = new HashSet.Node>(); + for (final DATA data : c) { + final Node node = new Node(data); + nodes.add(node); + node.keyProvider.buildIndex(index, node); + } + + for (DependencyGraph.Node node : nodes) { + node.type = dependencyProvider.provideDependency(node.data); + node.type.build(this, node); + } + + + } + + public DATA poll(final int nextIndex) { + + final DependencyGraph.Node node = availables.remove(nextIndex); + + node.keyProvider.removeFromIndex(index, node); + + for (final DependencyGraph.Node next : node.requiredBySet) { + next.type.onElementPolled(this, node, next); + } + + return node.data; + } + + public boolean hasNext() { + return !availables.isEmpty(); + } + + public List.Node> getAvailables() { + return unmodifiableAvailable; + } + + protected void buildEdge(final DependencyGraph.Node node, final KEY dependency) { + final Node requiredNode = index.get(dependency); + if (requiredNode == null) { + throw new RuntimeException("Unable to build edge : the dependency " + dependency + " is not indexed"); + } + requiredNode.requiredBySet.add(node); + } + + public class Node { + private final DATA data; + private final DataKeyProvider keyProvider; + private DependencyType type; + private Set requiredBySet = new HashSet(); + + protected Node(final DATA data) { + this.data = data; + this.keyProvider = data.getDataKeyProvider(); + + if (this.keyProvider == null) { + throw new NullPointerException(); + } + } + + public DATA getData() { + return data; + } + + public DataKeyProvider getKeyProvider() { + return keyProvider; + } + + public DependencyType getType() { + return type; + } + + public Set getRequiredBySet() { + return requiredBySet; + } + + @Override + public String toString() { + return new StringBuilder("{data=").append(data.toString()).append(", type=").append(type.toString()).append(", requiredBy=").append(requiredBySet.toString()).append("}").toString(); + } + } + } diff --git a/src/main/java/fr/eyzox/dependencygraph/DependencyType.java b/src/main/java/fr/eyzox/dependencygraph/DependencyType.java index 498865a..8746624 100644 --- a/src/main/java/fr/eyzox/dependencygraph/DependencyType.java +++ b/src/main/java/fr/eyzox/dependencygraph/DependencyType.java @@ -3,9 +3,11 @@ import fr.eyzox.dependencygraph.interfaces.IData; public abstract class DependencyType> { - - DependencyType() {} - - protected abstract void build(final DependencyGraph graph, final DependencyGraph.Node theNode); - protected abstract void onElementPolled(final DependencyGraph graph, final DependencyGraph.Node polledNode, final DependencyGraph.Node theNode); + + DependencyType() { + } + + protected abstract void build(final DependencyGraph graph, final DependencyGraph.Node theNode); + + protected abstract void onElementPolled(final DependencyGraph graph, final DependencyGraph.Node polledNode, final DependencyGraph.Node theNode); } diff --git a/src/main/java/fr/eyzox/dependencygraph/MultipleDataKeyProvider.java b/src/main/java/fr/eyzox/dependencygraph/MultipleDataKeyProvider.java index 82a4d19..2e424d9 100644 --- a/src/main/java/fr/eyzox/dependencygraph/MultipleDataKeyProvider.java +++ b/src/main/java/fr/eyzox/dependencygraph/MultipleDataKeyProvider.java @@ -1,42 +1,42 @@ package fr.eyzox.dependencygraph; +import fr.eyzox.dependencygraph.exceptions.DuplicateKeyException; +import fr.eyzox.dependencygraph.interfaces.IData; + import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; -import fr.eyzox.dependencygraph.exceptions.DuplicateKeyException; -import fr.eyzox.dependencygraph.interfaces.IData; - public final class MultipleDataKeyProvider extends DataKeyProvider { - private final Set keys; - - public MultipleDataKeyProvider(final Collection keys) { - this.keys = new HashSet(keys); - } - - @Override - protected > void buildIndex(Map.Node> index, DependencyGraph.Node theNode) throws DuplicateKeyException { - for(final K key : keys) { - final DependencyGraph.Node oldValue = index.put(key, theNode); - if(oldValue != null) { - throw new DuplicateKeyException(index, oldValue, theNode); - } - } - } - - @Override - protected > void removeFromIndex(Map.Node> index, DependencyGraph.Node theNode) { - for(K key : keys) { - index.remove(key); - } - } - - @Override - protected void removeKeyFrom(Collection c) { - c.removeAll(keys); - } + private final Set keys; + + public MultipleDataKeyProvider(final Collection keys) { + this.keys = new HashSet(keys); + } + + @Override + protected > void buildIndex(Map.Node> index, DependencyGraph.Node theNode) throws DuplicateKeyException { + for (final K key : keys) { + final DependencyGraph.Node oldValue = index.put(key, theNode); + if (oldValue != null) { + throw new DuplicateKeyException(index, oldValue, theNode); + } + } + } + + @Override + protected > void removeFromIndex(Map.Node> index, DependencyGraph.Node theNode) { + for (K key : keys) { + index.remove(key); + } + } + + @Override + protected void removeKeyFrom(Collection c) { + c.removeAll(keys); + } } diff --git a/src/main/java/fr/eyzox/dependencygraph/MultipleDependency.java b/src/main/java/fr/eyzox/dependencygraph/MultipleDependency.java index 9f87d20..5a6bc3f 100644 --- a/src/main/java/fr/eyzox/dependencygraph/MultipleDependency.java +++ b/src/main/java/fr/eyzox/dependencygraph/MultipleDependency.java @@ -1,55 +1,55 @@ package fr.eyzox.dependencygraph; +import fr.eyzox.dependencygraph.interfaces.IData; +import fr.eyzox.dependencygraph.interfaces.IDependencyUpdater; + import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import fr.eyzox.dependencygraph.interfaces.IData; -import fr.eyzox.dependencygraph.interfaces.IDependencyUpdater; - public final class MultipleDependency> extends DependencyType { - - private final Set dependencies; - private final IDependencyUpdater dependencyUpdater; - - private final Set uneditableDependencies; - - public MultipleDependency(final Collection c, final IDependencyUpdater dependencyUpdater) { - this.dependencies = new HashSet(c); - this.dependencyUpdater = dependencyUpdater; - - this.uneditableDependencies = Collections.unmodifiableSet(dependencies); - } - - @Override - protected void build(final DependencyGraph graph, final DependencyGraph.Node theNode) { - boolean flag = false; - for(final KEY dependency : dependencies) { - if(graph.index.containsKey(dependency)) { - graph.buildEdge(theNode, dependency); - flag = true; - } - } - - if(!flag) { - graph.availables.add(theNode); - } - } - - @Override - protected void onElementPolled(final DependencyGraph graph, final DependencyGraph.Node polledNode, final DependencyGraph.Node theNode){ - polledNode.getKeyProvider().removeKeyFrom(dependencies); - - if(dependencyUpdater.isAvailable(uneditableDependencies)) { - //Delete this node now available from other dependencies - for(final KEY dependency : dependencies) { - DependencyGraph.Node dependencyNode = graph.index.get(dependency); - if(dependencyNode != null) { - dependencyNode.getRequiredBySet().remove(polledNode); - } - } - graph.availables.add(theNode); - } - } + + private final Set dependencies; + private final IDependencyUpdater dependencyUpdater; + + private final Set uneditableDependencies; + + public MultipleDependency(final Collection c, final IDependencyUpdater dependencyUpdater) { + this.dependencies = new HashSet(c); + this.dependencyUpdater = dependencyUpdater; + + this.uneditableDependencies = Collections.unmodifiableSet(dependencies); + } + + @Override + protected void build(final DependencyGraph graph, final DependencyGraph.Node theNode) { + boolean flag = false; + for (final KEY dependency : dependencies) { + if (graph.index.containsKey(dependency)) { + graph.buildEdge(theNode, dependency); + flag = true; + } + } + + if (!flag) { + graph.availables.add(theNode); + } + } + + @Override + protected void onElementPolled(final DependencyGraph graph, final DependencyGraph.Node polledNode, final DependencyGraph.Node theNode) { + polledNode.getKeyProvider().removeKeyFrom(dependencies); + + if (dependencyUpdater.isAvailable(uneditableDependencies)) { + //Delete this node now available from other dependencies + for (final KEY dependency : dependencies) { + DependencyGraph.Node dependencyNode = graph.index.get(dependency); + if (dependencyNode != null) { + dependencyNode.getRequiredBySet().remove(polledNode); + } + } + graph.availables.add(theNode); + } + } } \ No newline at end of file diff --git a/src/main/java/fr/eyzox/dependencygraph/NoDependency.java b/src/main/java/fr/eyzox/dependencygraph/NoDependency.java index 37c6692..2309ce5 100644 --- a/src/main/java/fr/eyzox/dependencygraph/NoDependency.java +++ b/src/main/java/fr/eyzox/dependencygraph/NoDependency.java @@ -3,13 +3,13 @@ import fr.eyzox.dependencygraph.interfaces.IData; public final class NoDependency> extends DependencyType { - - @Override - protected void build(final DependencyGraph graph, final DependencyGraph.Node theNode) { - graph.availables.add(theNode); - } - - @Override - protected void onElementPolled(final DependencyGraph graph, final DependencyGraph.Node polledNode, final DependencyGraph.Node theNode){ - } + + @Override + protected void build(final DependencyGraph graph, final DependencyGraph.Node theNode) { + graph.availables.add(theNode); + } + + @Override + protected void onElementPolled(final DependencyGraph graph, final DependencyGraph.Node polledNode, final DependencyGraph.Node theNode) { + } } diff --git a/src/main/java/fr/eyzox/dependencygraph/RandomDependencyGraph.java b/src/main/java/fr/eyzox/dependencygraph/RandomDependencyGraph.java index 6891ba9..9ffcb02 100644 --- a/src/main/java/fr/eyzox/dependencygraph/RandomDependencyGraph.java +++ b/src/main/java/fr/eyzox/dependencygraph/RandomDependencyGraph.java @@ -1,26 +1,26 @@ package fr.eyzox.dependencygraph; +import fr.eyzox.dependencygraph.interfaces.IData; +import fr.eyzox.dependencygraph.interfaces.IDependencyProvider; + import java.util.Collection; import java.util.Random; -import fr.eyzox.dependencygraph.interfaces.IData; -import fr.eyzox.dependencygraph.interfaces.IDependencyProvider; +public class RandomDependencyGraph> extends DependencyGraph { + + private Random rdn; + + public RandomDependencyGraph(final Collection data, final IDependencyProvider dependencyProvider, final Random rdn) { + super(data, dependencyProvider); + this.rdn = rdn; + } + + public RandomDependencyGraph(final Collection data, final IDependencyProvider dependencyProvider) { + this(data, dependencyProvider, new Random()); + } -public class RandomDependencyGraph> extends DependencyGraph { - - private Random rdn; - - public RandomDependencyGraph(final Collection data, final IDependencyProvider dependencyProvider, final Random rdn) { - super(data, dependencyProvider); - this.rdn = rdn; - } - - public RandomDependencyGraph(final Collection data, final IDependencyProvider dependencyProvider) { - this(data, dependencyProvider, new Random()); - } - - public DATA poll() { - return poll(rdn.nextInt(this.getAvailables().size())); - } + public DATA poll() { + return poll(rdn.nextInt(this.getAvailables().size())); + } } diff --git a/src/main/java/fr/eyzox/dependencygraph/SingleDataKeyProvider.java b/src/main/java/fr/eyzox/dependencygraph/SingleDataKeyProvider.java index d007fe1..2b261a1 100644 --- a/src/main/java/fr/eyzox/dependencygraph/SingleDataKeyProvider.java +++ b/src/main/java/fr/eyzox/dependencygraph/SingleDataKeyProvider.java @@ -1,40 +1,37 @@ package fr.eyzox.dependencygraph; -import java.util.Collection; -import java.util.Map; - import fr.eyzox.dependencygraph.exceptions.DuplicateKeyException; import fr.eyzox.dependencygraph.interfaces.IData; +import java.util.Collection; +import java.util.Map; + public final class SingleDataKeyProvider extends DataKeyProvider { - private final K key; - - public SingleDataKeyProvider(final K key) { - this.key = key; - } - - @Override - protected > void buildIndex(final Map.Node> index, final DependencyGraph.Node theNode) throws DuplicateKeyException{ - final DependencyGraph.Node oldValue = index.put(key, theNode); - if(oldValue != null) { - throw new DuplicateKeyException(index, oldValue, theNode); - } - - } - - @Override - protected > void removeFromIndex(Map.Node> index, DependencyGraph.Node theNode) { - index.remove(key); - } - - @Override - protected void removeKeyFrom(Collection c) { - c.remove(key); - } - - - - - + private final K key; + + public SingleDataKeyProvider(final K key) { + this.key = key; + } + + @Override + protected > void buildIndex(final Map.Node> index, final DependencyGraph.Node theNode) throws DuplicateKeyException { + final DependencyGraph.Node oldValue = index.put(key, theNode); + if (oldValue != null) { + throw new DuplicateKeyException(index, oldValue, theNode); + } + + } + + @Override + protected > void removeFromIndex(Map.Node> index, DependencyGraph.Node theNode) { + index.remove(key); + } + + @Override + protected void removeKeyFrom(Collection c) { + c.remove(key); + } + + } diff --git a/src/main/java/fr/eyzox/dependencygraph/SingleDependency.java b/src/main/java/fr/eyzox/dependencygraph/SingleDependency.java index 9a12358..ab8b240 100644 --- a/src/main/java/fr/eyzox/dependencygraph/SingleDependency.java +++ b/src/main/java/fr/eyzox/dependencygraph/SingleDependency.java @@ -3,22 +3,22 @@ import fr.eyzox.dependencygraph.interfaces.IData; public final class SingleDependency> extends DependencyType { - - private final KEY dependency; - - public SingleDependency(final KEY dependency) { - this.dependency = dependency; - } - - protected void build(final DependencyGraph graph, final DependencyGraph.Node theNode) { - if(graph.index.containsKey(dependency)){ - graph.buildEdge(theNode, dependency); - }else { - graph.availables.add(theNode); - } - } - - protected void onElementPolled(final DependencyGraph graph, final DependencyGraph.Node polledNode, final DependencyGraph.Node theNode){ - graph.availables.add(theNode); - } + + private final KEY dependency; + + public SingleDependency(final KEY dependency) { + this.dependency = dependency; + } + + protected void build(final DependencyGraph graph, final DependencyGraph.Node theNode) { + if (graph.index.containsKey(dependency)) { + graph.buildEdge(theNode, dependency); + } else { + graph.availables.add(theNode); + } + } + + protected void onElementPolled(final DependencyGraph graph, final DependencyGraph.Node polledNode, final DependencyGraph.Node theNode) { + graph.availables.add(theNode); + } } diff --git a/src/main/java/fr/eyzox/dependencygraph/exceptions/DependencyGraphException.java b/src/main/java/fr/eyzox/dependencygraph/exceptions/DependencyGraphException.java index 15039e9..0672f35 100644 --- a/src/main/java/fr/eyzox/dependencygraph/exceptions/DependencyGraphException.java +++ b/src/main/java/fr/eyzox/dependencygraph/exceptions/DependencyGraphException.java @@ -2,29 +2,29 @@ public class DependencyGraphException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = -4337395305520296735L; - - public DependencyGraphException() { - super(); - } - - protected DependencyGraphException(String arg0, Throwable arg1, boolean arg2, boolean arg3) { - super(arg0, arg1, arg2, arg3); - } - - public DependencyGraphException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - public DependencyGraphException(String arg0) { - super(arg0); - } - - public DependencyGraphException(Throwable arg0) { - super(arg0); - } + /** + * + */ + private static final long serialVersionUID = -4337395305520296735L; + + public DependencyGraphException() { + super(); + } + + protected DependencyGraphException(String arg0, Throwable arg1, boolean arg2, boolean arg3) { + super(arg0, arg1, arg2, arg3); + } + + public DependencyGraphException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + public DependencyGraphException(String arg0) { + super(arg0); + } + + public DependencyGraphException(Throwable arg0) { + super(arg0); + } } diff --git a/src/main/java/fr/eyzox/dependencygraph/exceptions/DuplicateKeyException.java b/src/main/java/fr/eyzox/dependencygraph/exceptions/DuplicateKeyException.java index dd130fa..6d70f9e 100644 --- a/src/main/java/fr/eyzox/dependencygraph/exceptions/DuplicateKeyException.java +++ b/src/main/java/fr/eyzox/dependencygraph/exceptions/DuplicateKeyException.java @@ -1,45 +1,45 @@ package fr.eyzox.dependencygraph.exceptions; -import java.util.Map; - import fr.eyzox.dependencygraph.DataKeyProvider; import fr.eyzox.dependencygraph.DependencyGraph; import fr.eyzox.dependencygraph.interfaces.IData; +import java.util.Map; + /** * Throws when many {@link DataKeyProvider} have the same key * Index contains the new value - * @author EyZox * + * @author EyZox */ public class DuplicateKeyException extends DependencyGraphException { - /** - * - */ - private static final long serialVersionUID = -1859970829143171467L; - private final Map index; - private final DependencyGraph.Node oldValue, newValue; - - public > DuplicateKeyException(final Map.Node> index, final DependencyGraph.Node oldValue, final DependencyGraph.Node newValue) { - super("Some DependencyData have the same key"); - this.index = index; - this.oldValue = oldValue; - this.newValue = newValue; - } - - public > Map.Node> getIndex() { - return (Map.Node>) index; - } - - @SuppressWarnings("unchecked") - public > DependencyGraph.Node getOldValue() { - return (DependencyGraph.Node) oldValue; - } - - @SuppressWarnings("unchecked") - public > DependencyGraph.Node getNewValue() { - return (DependencyGraph.Node) newValue; - } - + /** + * + */ + private static final long serialVersionUID = -1859970829143171467L; + private final Map index; + private final DependencyGraph.Node oldValue, newValue; + + public > DuplicateKeyException(final Map.Node> index, final DependencyGraph.Node oldValue, final DependencyGraph.Node newValue) { + super("Some DependencyData have the same key"); + this.index = index; + this.oldValue = oldValue; + this.newValue = newValue; + } + + public > Map.Node> getIndex() { + return (Map.Node>) index; + } + + @SuppressWarnings("unchecked") + public > DependencyGraph.Node getOldValue() { + return (DependencyGraph.Node) oldValue; + } + + @SuppressWarnings("unchecked") + public > DependencyGraph.Node getNewValue() { + return (DependencyGraph.Node) newValue; + } + } diff --git a/src/main/java/fr/eyzox/dependencygraph/interfaces/IData.java b/src/main/java/fr/eyzox/dependencygraph/interfaces/IData.java index 6d75334..9f06eff 100644 --- a/src/main/java/fr/eyzox/dependencygraph/interfaces/IData.java +++ b/src/main/java/fr/eyzox/dependencygraph/interfaces/IData.java @@ -3,5 +3,5 @@ import fr.eyzox.dependencygraph.DataKeyProvider; public interface IData { - public DataKeyProvider getDataKeyProvider(); + public DataKeyProvider getDataKeyProvider(); } diff --git a/src/main/java/fr/eyzox/dependencygraph/interfaces/IDependencyProvider.java b/src/main/java/fr/eyzox/dependencygraph/interfaces/IDependencyProvider.java index fa65871..36a5229 100644 --- a/src/main/java/fr/eyzox/dependencygraph/interfaces/IDependencyProvider.java +++ b/src/main/java/fr/eyzox/dependencygraph/interfaces/IDependencyProvider.java @@ -3,5 +3,5 @@ import fr.eyzox.dependencygraph.DependencyType; public interface IDependencyProvider> { - public DependencyType provideDependency(final DATA data); + public DependencyType provideDependency(final DATA data); } diff --git a/src/main/java/fr/eyzox/dependencygraph/interfaces/IDependencyUpdater.java b/src/main/java/fr/eyzox/dependencygraph/interfaces/IDependencyUpdater.java index 8696229..f308332 100644 --- a/src/main/java/fr/eyzox/dependencygraph/interfaces/IDependencyUpdater.java +++ b/src/main/java/fr/eyzox/dependencygraph/interfaces/IDependencyUpdater.java @@ -3,7 +3,7 @@ import java.util.Set; public interface IDependencyUpdater { - - public boolean isAvailable(final Set dependenciesLeft); - + + public boolean isAvailable(final Set dependenciesLeft); + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/ForgeCreeperHeal.java b/src/main/java/fr/eyzox/forgecreeperheal/ForgeCreeperHeal.java index fb86af4..354775e 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/ForgeCreeperHeal.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/ForgeCreeperHeal.java @@ -1,10 +1,6 @@ package fr.eyzox.forgecreeperheal; -import java.util.Map; - -import org.apache.logging.log4j.Logger; - import fr.eyzox.bsc.config.IConfigProvider; import fr.eyzox.forgecreeperheal.builder.blockdata.IBlockDataBuilder; import fr.eyzox.forgecreeperheal.builder.dependency.IDependencyBuilder; @@ -30,106 +26,106 @@ import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; +import org.apache.logging.log4j.Logger; + +import java.util.Map; @Mod( - modid = ForgeCreeperHeal.MODID, - name = ForgeCreeperHeal.MODNAME, - version = ForgeCreeperHeal.VERSION, - acceptableRemoteVersions = "*" - ) -public class ForgeCreeperHeal -{ - + modid = ForgeCreeperHeal.MODID, + name = ForgeCreeperHeal.MODNAME, + version = ForgeCreeperHeal.VERSION, + acceptableRemoteVersions = "*" +) +public class ForgeCreeperHeal { + public static final String MODID = "forgecreeperheal"; public static final String VERSION = "2.1.1"; - public static final String MODNAME = "Forge Creeper Heal "+VERSION; - - @SidedProxy(clientSide = "fr.eyzox.forgecreeperheal.proxy.ClientProxy", serverSide = "fr.eyzox.forgecreeperheal.proxy.CommonProxy") - private static CommonProxy proxy; - + public static final String MODNAME = "Forge Creeper Heal " + VERSION; @Instance(ForgeCreeperHeal.MODID) - public static ForgeCreeperHeal instance; - - @EventHandler - public void onPreInit(FMLPreInitializationEvent event) { - proxy.onPreInit(event); - } - - @EventHandler - public void onInit(FMLInitializationEvent event) { - proxy.onInit(event); - } - - @EventHandler - public void serverAboutToStart(FMLServerAboutToStartEvent event) { - proxy.serverAboutToStart(event); - } - - @EventHandler - public void serverStarting(FMLServerStartingEvent event) { - proxy.serverStarting(event); - } + public static ForgeCreeperHeal instance; + @SidedProxy(clientSide = "fr.eyzox.forgecreeperheal.proxy.ClientProxy", serverSide = "fr.eyzox.forgecreeperheal.proxy.CommonProxy") + private static CommonProxy proxy; - public static ForgeCreeperHeal getInstance() { - return instance; + public static ForgeCreeperHeal getInstance() { + return instance; } - + public static Logger getLogger() { - return proxy.getLogger(); + return proxy.getLogger(); } - + public static IConfigProvider getConfigProvider() { - return proxy.getConfigProvider(); + return proxy.getConfigProvider(); } - + public static FastConfig getConfig() { - return proxy.getConfig(); - } - - /* - public static SimpleNetworkWrapper getChannel() { - return proxy.getChannel(); + return proxy.getConfig(); } - */ - + public static CommonProxy getProxy() { - return proxy; + return proxy; } - + public static HealerManager getHealerManager(final WorldServer world) throws ForgeCreeperHealException { - Map healerManagers = proxy.getHealerManagers(); - if(healerManagers == null) { - throw new ForgeCreeperHealException("HealerManagers are not loaded yet"); - } - return healerManagers.get(world); + Map healerManagers = proxy.getHealerManagers(); + if (healerManagers == null) { + throw new ForgeCreeperHealException("HealerManagers are not loaded yet"); + } + return healerManagers.get(world); } - + public static TickTimelineFactory getHealerFactory() { - return proxy.getHealerFactory(); + return proxy.getHealerFactory(); } - + public static DefaultFactory getBlockDataFactory() { - return proxy.getBlockDataFactory(); + return proxy.getBlockDataFactory(); } + /* + public static SimpleNetworkWrapper getChannel() { + return proxy.getChannel(); + } + */ + public static DefaultFactory getDependencyFactory() { - return proxy.getDependencyFactory(); + return proxy.getDependencyFactory(); } - public void registerReflection() { - // For ChunkTransform - ReflectionManager.getInstance().registerField(Chunk.class, "precipitationHeightMap", "field_76638_b"); - ReflectionManager.getInstance().registerMethod(Chunk.class, "relightBlock", "func_76615_h", new Class[]{int.class, int.class, int.class}); - ReflectionManager.getInstance().registerMethod(Chunk.class, "propagateSkylightOcclusion", "func_76595_e", new Class[]{int.class, int.class}); - - // For WorldTransform - ReflectionManager.getInstance().registerMethod(World.class, "isValid", "func_175701_a", new Class[]{BlockPos.class}); - - // For ExplosionEventHandler - ReflectionManager.getInstance().registerField(Explosion.class, "exploder", "field_77283_e"); - - // For I86n - ReflectionManager.getInstance().registerField(EntityPlayerMP.class, "language", "field_71148_cg"); - - } + @EventHandler + public void onPreInit(FMLPreInitializationEvent event) { + proxy.onPreInit(event); + } + + @EventHandler + public void onInit(FMLInitializationEvent event) { + proxy.onInit(event); + } + + @EventHandler + public void serverAboutToStart(FMLServerAboutToStartEvent event) { + proxy.serverAboutToStart(event); + } + + @EventHandler + public void serverStarting(FMLServerStartingEvent event) { + proxy.serverStarting(event); + } + + public void registerReflection() { + // For ChunkTransform + ReflectionManager.getInstance().registerField(Chunk.class, "precipitationHeightMap", "field_76638_b"); + ReflectionManager.getInstance().registerMethod(Chunk.class, "relightBlock", "func_76615_h", new Class[]{int.class, int.class, int.class}); + ReflectionManager.getInstance().registerMethod(Chunk.class, "propagateSkylightOcclusion", "func_76595_e", new Class[]{int.class, int.class}); + + // For WorldTransform + ReflectionManager.getInstance().registerMethod(World.class, "isValid", "func_175701_a", new Class[]{BlockPos.class}); + + // For ExplosionEventHandler + ReflectionManager.getInstance().registerField(Explosion.class, "exploder", "field_77283_e"); + + // For I86n + ReflectionManager.getInstance().registerField(EntityPlayerMP.class, "language", "field_71148_cg"); + + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/BlockData.java b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/BlockData.java index 919aa3a..68ba130 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/BlockData.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/BlockData.java @@ -6,11 +6,7 @@ import fr.eyzox.forgecreeperheal.builder.blockdata.IBlockDataBuilder; import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealerSerialException; import fr.eyzox.forgecreeperheal.factory.Factory; -import fr.eyzox.forgecreeperheal.healer.IChunked; -import fr.eyzox.forgecreeperheal.healer.IHealable; -import fr.eyzox.forgecreeperheal.healer.IRemovable; -import fr.eyzox.forgecreeperheal.healer.WorldHealer; -import fr.eyzox.forgecreeperheal.healer.WorldRemover; +import fr.eyzox.forgecreeperheal.healer.*; import fr.eyzox.forgecreeperheal.serial.ISerialWrapper; import fr.eyzox.forgecreeperheal.serial.ISerialWrapperProvider; import net.minecraft.block.Block; @@ -22,166 +18,169 @@ import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.common.util.INBTSerializable; -public class BlockData implements fr.eyzox.dependencygraph.interfaces.IData, ISerialWrapperProvider, IChunked, IHealable, IRemovable, INBTSerializable{ - - protected static final String TAG_POS = "pos"; - protected static final String TAG_STATE = "state"; - - protected static final String TAG_IBLOCKSTATE_BLOCK = "block"; - protected static final String TAG_IBLOCKSTATE_METADATA = "meta"; - - protected static final String TAG_TILE_ENTITY = "tileEntity"; - - private BlockPos pos; - private IBlockState state; - private NBTTagCompound tileEntity; - - public BlockData(final BlockPos pos, final IBlockState state) { - this.pos = pos; - this.state = state; - } - - public BlockData(final NBTTagCompound tag) { - this.deserializeNBT(tag); - } - - public final BlockPos getPos() { - return pos; - } - - public final IBlockState getState() { - return state; - } - - public void setTileEntity(TileEntity tileEntity) { - NBTTagCompound tag = tileEntity.serializeNBT(); - if(ForgeCreeperHeal.getConfig().isDropItems() && tileEntity instanceof IInventory) { - TileEntity clone = this.state.getBlock().createTileEntity(tileEntity.getWorld(), this.state); - clone.readFromNBT(tag); - ((IInventory)clone).clear(); - tag = clone.serializeNBT(); - } - this.tileEntity = tag; - } - - public final NBTTagCompound getTileEntity() { - return tileEntity; - } - - public boolean isMultiple() { - return false; - } - - public static boolean hasTileEntity(final NBTTagCompound tag) { - return tag.hasKey(TAG_TILE_ENTITY, NBT.TAG_COMPOUND); - } - - @Override - public void heal(WorldHealer worldHealer) { - worldHealer.heal(pos, state, tileEntity); - } - - @Override - public void remove(final WorldRemover remover) { - remover.remove(pos); - } - - @Override - public DataKeyProvider getDataKeyProvider() { - return new SingleDataKeyProvider(pos); - } - - @Override - public final int getChunkX() { - return pos.getX() >> 4; - } - - @Override - public final int getChunkZ() { - return pos.getZ() >> 4; - } - - @Override - public NBTTagCompound serializeNBT() { - final NBTTagCompound tag = new NBTTagCompound(); - tag.setLong(TAG_POS, this.pos.toLong()); - tag.setTag(TAG_STATE, iBlockStateToNBT(this.state)); - - if(tileEntity != null) { - tag.setTag(TAG_TILE_ENTITY, tileEntity); - } - - return tag; - } - - @Override - public void deserializeNBT(NBTTagCompound tag) { - this.pos = BlockPos.fromLong(tag.getLong(TAG_POS)); - this.state = iBlockStateFromNBT(tag.getCompoundTag(TAG_STATE)); - - final NBTTagCompound tileEntityTag = tag.getCompoundTag(TAG_TILE_ENTITY); - this.tileEntity = tileEntityTag.hasNoTags() ? null : tileEntityTag; - } - - @Override - public final BlockDataSerialWrapper getSerialWrapper() { - return BlockDataSerialWrapper.getInstance(); - } - - private NBTTagCompound iBlockStateToNBT(final IBlockState blockstate) { - final NBTTagCompound tag = new NBTTagCompound(); - tag.setString(TAG_IBLOCKSTATE_BLOCK, blockstate.getBlock().getRegistryName().toString()); - final int metadata = blockstate.getBlock().getMetaFromState(blockstate); - if(metadata != 0) { - tag.setInteger(TAG_IBLOCKSTATE_METADATA, metadata); - } - return tag; - } - - @SuppressWarnings("deprecation") // "Mojang appears to be using @Deprecated as a mark of vanilla MC methods that should be used by internals and subclasses of Block" (Mojang bad practices ... deal with it) - private IBlockState iBlockStateFromNBT(final NBTTagCompound tag) { - final Block block = Block.getBlockFromName((tag.getString(TAG_IBLOCKSTATE_BLOCK))); - final IBlockState state = block.getStateFromMeta(tag.getInteger(TAG_IBLOCKSTATE_METADATA)); - return state; - } - - public static class BlockDataSerialWrapper implements ISerialWrapper{ - - private static final BlockDataSerialWrapper INSTANCE = new BlockDataSerialWrapper(); - - public static BlockDataSerialWrapper getInstance() { return INSTANCE;} - - private BlockDataSerialWrapper() {} - - @Override - public BlockData unserialize(NBTTagCompound tag) throws ForgeCreeperHealerSerialException{ - final Factory factory = ForgeCreeperHeal.getBlockDataFactory(); - final String blockName = getBlockName(tag); - - if(blockName.isEmpty()) { - throw new ForgeCreeperHealerSerialException("Missing Block's name"); - } - - return factory.getData(blockName).create(tag); - } - - @Override - public NBTTagCompound serialize(BlockData data) { - return data.serializeNBT(); - } - - private String getBlockName(NBTTagCompound blockDataTag) { - final NBTTagCompound blockStateTag = blockDataTag.getCompoundTag((BlockData.TAG_STATE)); - return blockStateTag.getString(BlockData.TAG_IBLOCKSTATE_BLOCK); - } - - } - - @Override - public String toString() { - return "BlockData [pos=" + pos + ", state=" + state + ", tileEntity=" + tileEntity + "]"; - } - - - +public class BlockData implements fr.eyzox.dependencygraph.interfaces.IData, ISerialWrapperProvider, IChunked, IHealable, IRemovable, INBTSerializable { + + protected static final String TAG_POS = "pos"; + protected static final String TAG_STATE = "state"; + + protected static final String TAG_IBLOCKSTATE_BLOCK = "block"; + protected static final String TAG_IBLOCKSTATE_METADATA = "meta"; + + protected static final String TAG_TILE_ENTITY = "tileEntity"; + + private BlockPos pos; + private IBlockState state; + private NBTTagCompound tileEntity; + + public BlockData(final BlockPos pos, final IBlockState state) { + this.pos = pos; + this.state = state; + } + + public BlockData(final NBTTagCompound tag) { + this.deserializeNBT(tag); + } + + public static boolean hasTileEntity(final NBTTagCompound tag) { + return tag.hasKey(TAG_TILE_ENTITY, NBT.TAG_COMPOUND); + } + + public final BlockPos getPos() { + return pos; + } + + public final IBlockState getState() { + return state; + } + + public final NBTTagCompound getTileEntity() { + return tileEntity; + } + + public void setTileEntity(TileEntity tileEntity) { + NBTTagCompound tag = tileEntity.serializeNBT(); + if (ForgeCreeperHeal.getConfig().isDropItems() && tileEntity instanceof IInventory) { + TileEntity clone = this.state.getBlock().createTileEntity(tileEntity.getWorld(), this.state); + clone.readFromNBT(tag); + ((IInventory) clone).clear(); + tag = clone.serializeNBT(); + } + this.tileEntity = tag; + } + + public boolean isMultiple() { + return false; + } + + @Override + public void heal(WorldHealer worldHealer) { + worldHealer.heal(pos, state, tileEntity); + } + + @Override + public void remove(final WorldRemover remover) { + remover.remove(pos); + } + + @Override + public DataKeyProvider getDataKeyProvider() { + return new SingleDataKeyProvider(pos); + } + + @Override + public final int getChunkX() { + return pos.getX() >> 4; + } + + @Override + public final int getChunkZ() { + return pos.getZ() >> 4; + } + + @Override + public NBTTagCompound serializeNBT() { + final NBTTagCompound tag = new NBTTagCompound(); + tag.setLong(TAG_POS, this.pos.toLong()); + tag.setTag(TAG_STATE, iBlockStateToNBT(this.state)); + + if (tileEntity != null) { + tag.setTag(TAG_TILE_ENTITY, tileEntity); + } + + return tag; + } + + @Override + public void deserializeNBT(NBTTagCompound tag) { + this.pos = BlockPos.fromLong(tag.getLong(TAG_POS)); + this.state = iBlockStateFromNBT(tag.getCompoundTag(TAG_STATE)); + + final NBTTagCompound tileEntityTag = tag.getCompoundTag(TAG_TILE_ENTITY); + this.tileEntity = tileEntityTag.hasNoTags() ? null : tileEntityTag; + } + + @Override + public final BlockDataSerialWrapper getSerialWrapper() { + return BlockDataSerialWrapper.getInstance(); + } + + private NBTTagCompound iBlockStateToNBT(final IBlockState blockstate) { + final NBTTagCompound tag = new NBTTagCompound(); + tag.setString(TAG_IBLOCKSTATE_BLOCK, blockstate.getBlock().getRegistryName().toString()); + final int metadata = blockstate.getBlock().getMetaFromState(blockstate); + if (metadata != 0) { + tag.setInteger(TAG_IBLOCKSTATE_METADATA, metadata); + } + return tag; + } + + @SuppressWarnings("deprecation") + // "Mojang appears to be using @Deprecated as a mark of vanilla MC methods that should be used by internals and subclasses of Block" (Mojang bad practices ... deal with it) + private IBlockState iBlockStateFromNBT(final NBTTagCompound tag) { + final Block block = Block.getBlockFromName((tag.getString(TAG_IBLOCKSTATE_BLOCK))); + final IBlockState state = block.getStateFromMeta(tag.getInteger(TAG_IBLOCKSTATE_METADATA)); + return state; + } + + @Override + public String toString() { + return "BlockData [pos=" + pos + ", state=" + state + ", tileEntity=" + tileEntity + "]"; + } + + public static class BlockDataSerialWrapper implements ISerialWrapper { + + private static final BlockDataSerialWrapper INSTANCE = new BlockDataSerialWrapper(); + + private BlockDataSerialWrapper() { + } + + public static BlockDataSerialWrapper getInstance() { + return INSTANCE; + } + + @Override + public BlockData unserialize(NBTTagCompound tag) throws ForgeCreeperHealerSerialException { + final Factory factory = ForgeCreeperHeal.getBlockDataFactory(); + final String blockName = getBlockName(tag); + + if (blockName.isEmpty()) { + throw new ForgeCreeperHealerSerialException("Missing Block's name"); + } + + return factory.getData(blockName).create(tag); + } + + @Override + public NBTTagCompound serialize(BlockData data) { + return data.serializeNBT(); + } + + private String getBlockName(NBTTagCompound blockDataTag) { + final NBTTagCompound blockStateTag = blockDataTag.getCompoundTag((BlockData.TAG_STATE)); + return blockStateTag.getString(BlockData.TAG_IBLOCKSTATE_BLOCK); + } + + } + + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/MultiBlockData.java b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/MultiBlockData.java index d03966e..2276e40 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/MultiBlockData.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/MultiBlockData.java @@ -1,12 +1,5 @@ package fr.eyzox.forgecreeperheal.blockdata; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - import fr.eyzox.dependencygraph.DataKeyProvider; import fr.eyzox.dependencygraph.MultipleDataKeyProvider; import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; @@ -22,110 +15,112 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.Constants.NBT; +import java.util.*; + public class MultiBlockData extends BlockData { - private static final String TAG_OTHERS = "others"; - - private Collection others; - - private Set allBlockPos; - - public MultiBlockData(final BlockPos pos, final IBlockState state, final Collection others) { - super(pos, state); - - this.allBlockPos = new HashSet(1+others.size()); - this.allBlockPos.add(this.getPos()); - for(final BlockData other : others) { - - if(other.isMultiple()) { - throw new ForgeCreeperHealException("MultiBlockData is not recursive"); - } - - final boolean added = allBlockPos.add(other.getPos()); - if(!added) { - throw new ForgeCreeperHealException("Duplicate BlockPos in MultiBlockData"); - } - } - - this.others = new ArrayList(others); - } - - public MultiBlockData(final NBTTagCompound tag) { - super(tag); - } - - @Override - public DataKeyProvider getDataKeyProvider() { - return new MultipleDataKeyProvider(allBlockPos); - } - - private Map buildOldStateMap(final World world) { - final Map oldStateMap = new HashMap(allBlockPos.size()); - for(final BlockPos pos : allBlockPos) { - oldStateMap.put(pos, world.getBlockState(pos)); - } - return oldStateMap; - } - - @Override - public void heal(WorldHealer worldHealer) { - super.heal(worldHealer); - for(BlockData other : others) { - other.heal(worldHealer); - } - - } - - @Override - public void remove(final WorldRemover remover) { - super.remove(remover); - for(final BlockData other : others) { - other.remove(remover); - } - } - - @Override - public boolean isMultiple() { - return true; - } - - public static boolean isMultiple(final NBTTagCompound tag) { - return tag.hasKey(TAG_OTHERS, NBT.TAG_LIST); - } - - @Override - public NBTTagCompound serializeNBT() { - final NBTTagCompound tag = super.serializeNBT(); - - final NBTTagList wrapperListTag = new NBTTagList(); - for(BlockData other : others){ - wrapperListTag.appendTag(SerialUtils.serializeWrappedData(other.getSerialWrapper(), other)); - } - - tag.setTag(TAG_OTHERS, wrapperListTag); - return tag; - } - - @Override - public void deserializeNBT(NBTTagCompound tag) { - super.deserializeNBT(tag); - - final NBTTagList wrapperListTag = tag.getTagList(TAG_OTHERS, NBT.TAG_COMPOUND); - this.others = new ArrayList(wrapperListTag.tagCount()); - - for(int i = 0; i others; + + private Set allBlockPos; + + public MultiBlockData(final BlockPos pos, final IBlockState state, final Collection others) { + super(pos, state); + + this.allBlockPos = new HashSet(1 + others.size()); + this.allBlockPos.add(this.getPos()); + for (final BlockData other : others) { + + if (other.isMultiple()) { + throw new ForgeCreeperHealException("MultiBlockData is not recursive"); + } + + final boolean added = allBlockPos.add(other.getPos()); + if (!added) { + throw new ForgeCreeperHealException("Duplicate BlockPos in MultiBlockData"); + } + } + + this.others = new ArrayList(others); + } + + public MultiBlockData(final NBTTagCompound tag) { + super(tag); + } + + public static boolean isMultiple(final NBTTagCompound tag) { + return tag.hasKey(TAG_OTHERS, NBT.TAG_LIST); + } + + @Override + public DataKeyProvider getDataKeyProvider() { + return new MultipleDataKeyProvider(allBlockPos); + } + + private Map buildOldStateMap(final World world) { + final Map oldStateMap = new HashMap(allBlockPos.size()); + for (final BlockPos pos : allBlockPos) { + oldStateMap.put(pos, world.getBlockState(pos)); + } + return oldStateMap; + } + + @Override + public void heal(WorldHealer worldHealer) { + super.heal(worldHealer); + for (BlockData other : others) { + other.heal(worldHealer); + } + + } + + @Override + public void remove(final WorldRemover remover) { + super.remove(remover); + for (final BlockData other : others) { + other.remove(remover); + } + } + + @Override + public boolean isMultiple() { + return true; + } + + @Override + public NBTTagCompound serializeNBT() { + final NBTTagCompound tag = super.serializeNBT(); + + final NBTTagList wrapperListTag = new NBTTagList(); + for (BlockData other : others) { + wrapperListTag.appendTag(SerialUtils.serializeWrappedData(other.getSerialWrapper(), other)); + } + + tag.setTag(TAG_OTHERS, wrapperListTag); + return tag; + } + + @Override + public void deserializeNBT(NBTTagCompound tag) { + super.deserializeNBT(tag); + + final NBTTagList wrapperListTag = tag.getTagList(TAG_OTHERS, NBT.TAG_COMPOUND); + this.others = new ArrayList(wrapperListTag.tagCount()); + + for (int i = 0; i < wrapperListTag.tagCount(); i++) { + + BlockData data = null; + try { + data = SerialUtils.unserializeWrappedData(wrapperListTag.getCompoundTagAt(i)); + } catch (ForgeCreeperHealerSerialException e) { + ForgeCreeperHeal.getLogger().error("Error while unserialize MultiBlockData: " + e.getMessage()); + } + + if (data != null) { + others.add(data); + } + + } + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/BedMultiSelector.java b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/BedMultiSelector.java index c6fae1b..86111bf 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/BedMultiSelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/BedMultiSelector.java @@ -8,9 +8,9 @@ public class BedMultiSelector implements IMultiSelector { - @Override - public BlockPos[] getBlockPos(World w, BlockPos pos, IBlockState state) { - return new BlockPos[]{pos.offset(((EnumFacing) state.getValue(BlockBed.FACING)).getOpposite())}; - } + @Override + public BlockPos[] getBlockPos(World w, BlockPos pos, IBlockState state) { + return new BlockPos[]{pos.offset(((EnumFacing) state.getValue(BlockBed.FACING)).getOpposite())}; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/FacingMultiSelector.java b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/FacingMultiSelector.java index 1dad320..6194cc5 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/FacingMultiSelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/FacingMultiSelector.java @@ -7,17 +7,17 @@ public class FacingMultiSelector implements IMultiSelector { - public static final IMultiSelector FACING_UP = new FacingMultiSelector(EnumFacing.UP); - - private final EnumFacing facing; - - public FacingMultiSelector(final EnumFacing facing) { - this.facing = facing; - } - - @Override - public BlockPos[] getBlockPos(World w, BlockPos pos, IBlockState state) { - return new BlockPos[]{pos.offset(facing)}; - } + public static final IMultiSelector FACING_UP = new FacingMultiSelector(EnumFacing.UP); + + private final EnumFacing facing; + + public FacingMultiSelector(final EnumFacing facing) { + this.facing = facing; + } + + @Override + public BlockPos[] getBlockPos(World w, BlockPos pos, IBlockState state) { + return new BlockPos[]{pos.offset(facing)}; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/IMultiSelector.java b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/IMultiSelector.java index e8204b7..5c9b55f 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/IMultiSelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/IMultiSelector.java @@ -5,5 +5,5 @@ import net.minecraft.world.World; public interface IMultiSelector { - public BlockPos[] getBlockPos(World w, BlockPos pos, IBlockState state); + public BlockPos[] getBlockPos(World w, BlockPos pos, IBlockState state); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/PistonMultiSelector.java b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/PistonMultiSelector.java index 1f2fbb1..7e4e4d7 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/PistonMultiSelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/blockdata/multi/selector/PistonMultiSelector.java @@ -8,9 +8,9 @@ public class PistonMultiSelector implements IMultiSelector { - @Override - public BlockPos[] getBlockPos(World w, BlockPos pos, IBlockState state) { - return new BlockPos[]{pos.offset((EnumFacing) state.getValue(BlockPistonBase.FACING))}; - } + @Override + public BlockPos[] getBlockPos(World w, BlockPos pos, IBlockState state) { + return new BlockPos[]{pos.offset((EnumFacing) state.getValue(BlockPistonBase.FACING))}; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/AbstractFactoryBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/AbstractFactoryBuilder.java index 8c94d5c..fffb80d 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/AbstractFactoryBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/AbstractFactoryBuilder.java @@ -5,15 +5,15 @@ public abstract class AbstractFactoryBuilder implements IData { - private final Class clazz; - - public AbstractFactoryBuilder(final Class clazz) { - this.clazz = clazz; - } - - @Override - public boolean accept(Block block) { - return this.clazz.isAssignableFrom(block.getClass()); - } + private final Class clazz; + + public AbstractFactoryBuilder(final Class clazz) { + this.clazz = clazz; + } + + @Override + public boolean accept(Block block) { + return this.clazz.isAssignableFrom(block.getClass()); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/BedBlockDataBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/BedBlockDataBuilder.java index 4f4f910..93ad63e 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/BedBlockDataBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/BedBlockDataBuilder.java @@ -9,16 +9,16 @@ public class BedBlockDataBuilder extends MultiBlockDataBuilder { - public BedBlockDataBuilder() { - super(BlockBed.class, new BedMultiSelector()); - } - - @Override - public BlockData create(World w, BlockPos pos, IBlockState state) { - if(state.getValue(BlockBed.PART) == BlockBed.EnumPartType.HEAD) { - return super.create(w, pos, state); - } - return null; - } + public BedBlockDataBuilder() { + super(BlockBed.class, new BedMultiSelector()); + } + + @Override + public BlockData create(World w, BlockPos pos, IBlockState state) { + if (state.getValue(BlockBed.PART) == BlockBed.EnumPartType.HEAD) { + return super.create(w, pos, state); + } + return null; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/DefaultBlockDataBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/DefaultBlockDataBuilder.java index e6f4690..7512495 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/DefaultBlockDataBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/DefaultBlockDataBuilder.java @@ -9,21 +9,22 @@ public class DefaultBlockDataBuilder implements IBlockDataBuilder { - public DefaultBlockDataBuilder() {} + public DefaultBlockDataBuilder() { + } - @Override - public BlockData create(World world, BlockPos pos, IBlockState state) { - if(state.getBlock().isAir(state, world, pos)) return null; - return new BlockData(pos, state); - } + @Override + public BlockData create(World world, BlockPos pos, IBlockState state) { + if (state.getBlock().isAir(state, world, pos)) return null; + return new BlockData(pos, state); + } - @Override - public BlockData create(NBTTagCompound tag) { - return new BlockData(tag); - } - - @Override - public boolean accept(Block block) { - return true; - } + @Override + public BlockData create(NBTTagCompound tag) { + return new BlockData(tag); + } + + @Override + public boolean accept(Block block) { + return true; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/DoorBlockDataBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/DoorBlockDataBuilder.java index f7700bc..3c096d4 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/DoorBlockDataBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/DoorBlockDataBuilder.java @@ -7,18 +7,18 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -public class DoorBlockDataBuilder extends MultiBlockDataBuilder{ +public class DoorBlockDataBuilder extends MultiBlockDataBuilder { - public DoorBlockDataBuilder() { - super(BlockDoor.class, FacingMultiSelector.FACING_UP); - } + public DoorBlockDataBuilder() { + super(BlockDoor.class, FacingMultiSelector.FACING_UP); + } - @Override - public BlockData create(World w, BlockPos pos, IBlockState state) { - if(state.getValue(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.LOWER) { - return super.create(w, pos, state); - } - return null; - } + @Override + public BlockData create(World w, BlockPos pos, IBlockState state) { + if (state.getValue(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.LOWER) { + return super.create(w, pos, state); + } + return null; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/IBlockDataBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/IBlockDataBuilder.java index bf36f56..0de478e 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/IBlockDataBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/IBlockDataBuilder.java @@ -9,6 +9,7 @@ import net.minecraft.world.World; public interface IBlockDataBuilder extends IData { - public BlockData create(final World w, final BlockPos pos, final IBlockState state); - public BlockData create(final NBTTagCompound tag); + public BlockData create(final World w, final BlockPos pos, final IBlockState state); + + public BlockData create(final NBTTagCompound tag); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/MultiBlockDataBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/MultiBlockDataBuilder.java index c61b021..c99dd9d 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/MultiBlockDataBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/MultiBlockDataBuilder.java @@ -1,7 +1,5 @@ package fr.eyzox.forgecreeperheal.builder.blockdata; -import java.util.ArrayList; - import fr.eyzox.forgecreeperheal.blockdata.BlockData; import fr.eyzox.forgecreeperheal.blockdata.MultiBlockData; import fr.eyzox.forgecreeperheal.blockdata.multi.selector.IMultiSelector; @@ -13,46 +11,48 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import java.util.ArrayList; + public class MultiBlockDataBuilder extends AbstractFactoryBuilder implements IBlockDataBuilder { - private final IMultiSelector sel; - - public MultiBlockDataBuilder(Class clazz, final IMultiSelector sel) { - super(clazz); - this.sel = sel; - } - - @Override - public BlockData create(World w, BlockPos pos, IBlockState state) { - - final BlockPos[] otherPosArray = sel.getBlockPos(w,pos,state); - - final ArrayList otherList = new ArrayList(otherPosArray.length); - - for(final BlockPos otherPos : otherPosArray) { - final IBlockState otherState = w.getBlockState(otherPos); - BlockData other = new BlockData(otherPos, otherState); - //TODO Rework MultiBlockData : make it recursive - if(otherState.getBlock().hasTileEntity(otherState)) { - TileEntity te = w.getTileEntity(otherPos); - if(te != null) { - other.setTileEntity(te); - } - } - otherList.add(other); - } - - return new MultiBlockData(pos, state, otherList); - - } - - @Override - public BlockData create(NBTTagCompound tag) { - return new MultiBlockData(tag); - } - - public IMultiSelector getMultiSelector() { - return sel; - } + private final IMultiSelector sel; + + public MultiBlockDataBuilder(Class clazz, final IMultiSelector sel) { + super(clazz); + this.sel = sel; + } + + @Override + public BlockData create(World w, BlockPos pos, IBlockState state) { + + final BlockPos[] otherPosArray = sel.getBlockPos(w, pos, state); + + final ArrayList otherList = new ArrayList(otherPosArray.length); + + for (final BlockPos otherPos : otherPosArray) { + final IBlockState otherState = w.getBlockState(otherPos); + BlockData other = new BlockData(otherPos, otherState); + //TODO Rework MultiBlockData : make it recursive + if (otherState.getBlock().hasTileEntity(otherState)) { + TileEntity te = w.getTileEntity(otherPos); + if (te != null) { + other.setTileEntity(te); + } + } + otherList.add(other); + } + + return new MultiBlockData(pos, state, otherList); + + } + + @Override + public BlockData create(NBTTagCompound tag) { + return new MultiBlockData(tag); + } + + public IMultiSelector getMultiSelector() { + return sel; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/PistonBlockDataBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/PistonBlockDataBuilder.java index 1b6cbf4..7883659 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/PistonBlockDataBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/blockdata/PistonBlockDataBuilder.java @@ -14,34 +14,33 @@ public class PistonBlockDataBuilder extends MultiBlockDataBuilder { - public PistonBlockDataBuilder() { - super(null, new PistonMultiSelector()); - } - - @Override - public boolean accept(Block block) { - return BlockPistonBase.class.isAssignableFrom(block.getClass()) || BlockPistonExtension.class.isAssignableFrom(block.getClass()) || BlockPistonMoving.class.isAssignableFrom(block.getClass()); - } - - @Override - public BlockData create(World w, BlockPos pos, IBlockState state) { - if(BlockPistonBase.class.isAssignableFrom(state.getBlock().getClass())) { - if( ((Boolean)state.getValue(BlockPistonBase.EXTENDED)).booleanValue() ) { - return super.create(w, pos, state); - } - return new BlockData(pos, state); - } - return null; - } - - @Override - public BlockData create(NBTTagCompound tag) { - if(MultiBlockData.isMultiple(tag)) { - return new MultiBlockData(tag); - } - return new BlockData(tag); - } - + public PistonBlockDataBuilder() { + super(null, new PistonMultiSelector()); + } + + @Override + public boolean accept(Block block) { + return BlockPistonBase.class.isAssignableFrom(block.getClass()) || BlockPistonExtension.class.isAssignableFrom(block.getClass()) || BlockPistonMoving.class.isAssignableFrom(block.getClass()); + } + + @Override + public BlockData create(World w, BlockPos pos, IBlockState state) { + if (BlockPistonBase.class.isAssignableFrom(state.getBlock().getClass())) { + if (((Boolean) state.getValue(BlockPistonBase.EXTENDED)).booleanValue()) { + return super.create(w, pos, state); + } + return new BlockData(pos, state); + } + return null; + } + + @Override + public BlockData create(NBTTagCompound tag) { + if (MultiBlockData.isMultiple(tag)) { + return new MultiBlockData(tag); + } + return new BlockData(tag); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/AbstractFacingDependencyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/AbstractFacingDependencyBuilder.java index 8abbda9..769f3d5 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/AbstractFacingDependencyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/AbstractFacingDependencyBuilder.java @@ -9,25 +9,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; -public abstract class AbstractFacingDependencyBuilder extends AbstractFactoryBuilder implements IDependencyBuilder{ - - private final IPropertySelector facingProperty; - - public AbstractFacingDependencyBuilder(Class clazz, final IPropertySelector facingProperty) { - super(clazz); - this.facingProperty = facingProperty; - } - - @Override - public DependencyType getDependencies(BlockData data) { - final EnumFacing facing = getEnumFacing(data); - return new SingleDependency(FacingDependencyUtils.getBlockPos(data.getPos(), facing)); - } - - public IPropertySelector getFacingProperty() { - return facingProperty; - } - - protected abstract EnumFacing getEnumFacing(final BlockData data); +public abstract class AbstractFacingDependencyBuilder extends AbstractFactoryBuilder implements IDependencyBuilder { + + private final IPropertySelector facingProperty; + + public AbstractFacingDependencyBuilder(Class clazz, final IPropertySelector facingProperty) { + super(clazz); + this.facingProperty = facingProperty; + } + + @Override + public DependencyType getDependencies(BlockData data) { + final EnumFacing facing = getEnumFacing(data); + return new SingleDependency(FacingDependencyUtils.getBlockPos(data.getPos(), facing)); + } + + public IPropertySelector getFacingProperty() { + return facingProperty; + } + + protected abstract EnumFacing getEnumFacing(final BlockData data); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/AbstractGenericDependencyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/AbstractGenericDependencyBuilder.java index ff8c8e2..bf6b9b0 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/AbstractGenericDependencyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/AbstractGenericDependencyBuilder.java @@ -1,34 +1,34 @@ package fr.eyzox.forgecreeperheal.builder.dependency; +import net.minecraft.block.Block; + import java.util.LinkedList; import java.util.List; -import net.minecraft.block.Block; +public abstract class AbstractGenericDependencyBuilder implements IDependencyBuilder { + + private final List> registeredClasses = new LinkedList>(); + + @Override + public boolean accept(Block in) { + for (final Class clazz : registeredClasses) { + if (clazz.isAssignableFrom(in.getClass())) { + return true; + } + } + return false; + } + + public List> getRegisteredClasses() { + return registeredClasses; + } + + public void register(final Class clazz) { + this.registeredClasses.add(clazz); + } -public abstract class AbstractGenericDependencyBuilder implements IDependencyBuilder{ - - private final List> registeredClasses = new LinkedList>(); - - @Override - public boolean accept(Block in) { - for(final Class clazz : registeredClasses) { - if(clazz.isAssignableFrom(in.getClass())) { - return true; - } - } - return false; - } - - public List> getRegisteredClasses() { - return registeredClasses; - } - - public void register(final Class clazz) { - this.registeredClasses.add(clazz); - } - - public boolean unregister(final Class clazz) { - return this.registeredClasses.remove(clazz); - } + public boolean unregister(final Class clazz) { + return this.registeredClasses.remove(clazz); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/FacingDependencyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/FacingDependencyBuilder.java index 7702f90..846eb86 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/FacingDependencyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/FacingDependencyBuilder.java @@ -5,15 +5,15 @@ import net.minecraft.block.Block; import net.minecraft.util.EnumFacing; -public class FacingDependencyBuilder extends AbstractFacingDependencyBuilder{ +public class FacingDependencyBuilder extends AbstractFacingDependencyBuilder { - public FacingDependencyBuilder(Class clazz, final IPropertySelector facingProperty) { - super(clazz, facingProperty); - } + public FacingDependencyBuilder(Class clazz, final IPropertySelector facingProperty) { + super(clazz, facingProperty); + } - @Override - protected EnumFacing getEnumFacing(BlockData data) { - return (EnumFacing) data.getState().getValue(getFacingProperty().getPropertyDirection()); - } + @Override + protected EnumFacing getEnumFacing(BlockData data) { + return (EnumFacing) data.getState().getValue(getFacingProperty().getPropertyDirection()); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/FacingDependencyUtils.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/FacingDependencyUtils.java index cf8f9bc..bd5b3a1 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/FacingDependencyUtils.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/FacingDependencyUtils.java @@ -5,10 +5,11 @@ public class FacingDependencyUtils { - private FacingDependencyUtils() {} - - public static BlockPos getBlockPos(final BlockPos pos, final EnumFacing facing) { - return pos.offset(facing); - } + private FacingDependencyUtils() { + } + + public static BlockPos getBlockPos(final BlockPos pos, final EnumFacing facing) { + return pos.offset(facing); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/IDependencyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/IDependencyBuilder.java index 0b212d5..286d838 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/IDependencyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/IDependencyBuilder.java @@ -6,6 +6,6 @@ import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; -public interface IDependencyBuilder extends IData{ - public DependencyType getDependencies(final BlockData data); +public interface IDependencyBuilder extends IData { + public DependencyType getDependencies(final BlockData data); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/LeverDependencyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/LeverDependencyBuilder.java index c6e3630..7f69c6e 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/LeverDependencyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/LeverDependencyBuilder.java @@ -8,19 +8,18 @@ import net.minecraft.block.BlockLever.EnumOrientation; import net.minecraft.util.math.BlockPos; -public class LeverDependencyBuilder implements IDependencyBuilder{ +public class LeverDependencyBuilder implements IDependencyBuilder { - @Override - public boolean accept(Block in) { - return BlockLever.class.isAssignableFrom(in.getClass()); - } + @Override + public boolean accept(Block in) { + return BlockLever.class.isAssignableFrom(in.getClass()); + } - @Override - public DependencyType getDependencies(BlockData data) { - final EnumOrientation orientation = (EnumOrientation)data.getState().getValue(BlockLever.FACING); - return new SingleDependency(FacingDependencyUtils.getBlockPos(data.getPos(), orientation.getFacing().getOpposite())); - } + @Override + public DependencyType getDependencies(BlockData data) { + final EnumOrientation orientation = (EnumOrientation) data.getState().getValue(BlockLever.FACING); + return new SingleDependency(FacingDependencyUtils.getBlockPos(data.getPos(), orientation.getFacing().getOpposite())); + } - } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/NoDependencyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/NoDependencyBuilder.java index 740f242..8b02732 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/NoDependencyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/NoDependencyBuilder.java @@ -6,20 +6,21 @@ import net.minecraft.block.Block; import net.minecraft.util.math.BlockPos; -public class NoDependencyBuilder implements IDependencyBuilder{ +public class NoDependencyBuilder implements IDependencyBuilder { - private final NoDependency noDependency = new NoDependency(); - - public NoDependencyBuilder() {} + private final NoDependency noDependency = new NoDependency(); - @Override - public boolean accept(Block in) { - return true; - } + public NoDependencyBuilder() { + } - @Override - public DependencyType getDependencies(BlockData data) { - return noDependency; - } + @Override + public boolean accept(Block in) { + return true; + } + + @Override + public DependencyType getDependencies(BlockData data) { + return noDependency; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/OppositeFacingDependencyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/OppositeFacingDependencyBuilder.java index 736dea4..3701423 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/OppositeFacingDependencyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/OppositeFacingDependencyBuilder.java @@ -5,15 +5,15 @@ import net.minecraft.block.Block; import net.minecraft.util.EnumFacing; -public class OppositeFacingDependencyBuilder extends FacingDependencyBuilder{ +public class OppositeFacingDependencyBuilder extends FacingDependencyBuilder { - public OppositeFacingDependencyBuilder(Class clazz, final IPropertySelector facingProperty) { - super(clazz, facingProperty); - } + public OppositeFacingDependencyBuilder(Class clazz, final IPropertySelector facingProperty) { + super(clazz, facingProperty); + } - @Override - protected EnumFacing getEnumFacing(BlockData data) { - return super.getEnumFacing(data).getOpposite(); - } + @Override + protected EnumFacing getEnumFacing(BlockData data) { + return super.getEnumFacing(data).getOpposite(); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/SupportByBottomDependencyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/SupportByBottomDependencyBuilder.java index 619f784..2f3f607 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/SupportByBottomDependencyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/SupportByBottomDependencyBuilder.java @@ -8,16 +8,18 @@ public class SupportByBottomDependencyBuilder extends AbstractGenericDependencyBuilder { - private final static SupportByBottomDependencyBuilder INSTANCE = new SupportByBottomDependencyBuilder(); - private SupportByBottomDependencyBuilder() {} + private final static SupportByBottomDependencyBuilder INSTANCE = new SupportByBottomDependencyBuilder(); - @Override - public DependencyType getDependencies(BlockData data) { - return new SingleDependency(FacingDependencyUtils.getBlockPos(data.getPos(), EnumFacing.DOWN)); - } - - public static SupportByBottomDependencyBuilder getInstance() { - return INSTANCE; - } + private SupportByBottomDependencyBuilder() { + } + + public static SupportByBottomDependencyBuilder getInstance() { + return INSTANCE; + } + + @Override + public DependencyType getDependencies(BlockData data) { + return new SingleDependency(FacingDependencyUtils.getBlockPos(data.getPos(), EnumFacing.DOWN)); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/VineDependencyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/VineDependencyBuilder.java index b67e916..e2bb567 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/VineDependencyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/VineDependencyBuilder.java @@ -1,8 +1,5 @@ package fr.eyzox.forgecreeperheal.builder.dependency; -import java.util.ArrayList; -import java.util.List; - import fr.eyzox.dependencygraph.DependencyType; import fr.eyzox.dependencygraph.MultipleDependency; import fr.eyzox.forgecreeperheal.blockdata.BlockData; @@ -12,26 +9,29 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; -public class VineDependencyBuilder implements IDependencyBuilder{ +import java.util.ArrayList; +import java.util.List; + +public class VineDependencyBuilder implements IDependencyBuilder { + + @Override + public boolean accept(Block in) { + return BlockVine.class.isAssignableFrom(in.getClass()); + } - @Override - public boolean accept(Block in) { - return BlockVine.class.isAssignableFrom(in.getClass()); - } + @Override + public DependencyType getDependencies(BlockData data) { + final List dependencies = new ArrayList(2); + for (EnumFacing facing : EnumFacing.HORIZONTALS) { + if (((Boolean) data.getState().getValue(BlockVine.getPropertyFor(facing))).booleanValue()) { + dependencies.add(FacingDependencyUtils.getBlockPos(data.getPos(), facing)); + break; + } + } + if (((Boolean) data.getState().getValue(BlockVine.UP)).booleanValue()) { + dependencies.add(FacingDependencyUtils.getBlockPos(data.getPos(), EnumFacing.UP)); + } - @Override - public DependencyType getDependencies(BlockData data) { - final List dependencies = new ArrayList(2); - for(EnumFacing facing : EnumFacing.HORIZONTALS) { - if(((Boolean)data.getState().getValue(BlockVine.getPropertyFor(facing))).booleanValue()) { - dependencies.add(FacingDependencyUtils.getBlockPos(data.getPos(), facing)); - break; - } - } - if(((Boolean)data.getState().getValue(BlockVine.UP)).booleanValue()) { - dependencies.add(FacingDependencyUtils.getBlockPos(data.getPos(), EnumFacing.UP)); - } - - return new MultipleDependency(dependencies, new FullOrDependency(dependencies.size())); - } + return new MultipleDependency(dependencies, new FullOrDependency(dependencies.size())); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/BannerHangingPropertySelector.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/BannerHangingPropertySelector.java index bdc6f4e..e069ac3 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/BannerHangingPropertySelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/BannerHangingPropertySelector.java @@ -5,9 +5,9 @@ public class BannerHangingPropertySelector implements IPropertySelector { - @Override - public PropertyDirection getPropertyDirection() { - return BlockBannerHanging.FACING; - } + @Override + public PropertyDirection getPropertyDirection() { + return BlockBannerHanging.FACING; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/ButtonPropertySelector.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/ButtonPropertySelector.java index a46ad5d..f939bd9 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/ButtonPropertySelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/ButtonPropertySelector.java @@ -5,9 +5,9 @@ public class ButtonPropertySelector implements IPropertySelector { - @Override - public PropertyDirection getPropertyDirection() { - return BlockButton.FACING; - } + @Override + public PropertyDirection getPropertyDirection() { + return BlockButton.FACING; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/CocoaPropertySelector.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/CocoaPropertySelector.java index cec6917..2589bdc 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/CocoaPropertySelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/CocoaPropertySelector.java @@ -5,9 +5,9 @@ public class CocoaPropertySelector implements IPropertySelector { - @Override - public PropertyDirection getPropertyDirection() { - return BlockCocoa.FACING; - } + @Override + public PropertyDirection getPropertyDirection() { + return BlockCocoa.FACING; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/IPropertySelector.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/IPropertySelector.java index 159c75b..833badc 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/IPropertySelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/IPropertySelector.java @@ -4,6 +4,6 @@ public interface IPropertySelector { - PropertyDirection getPropertyDirection(); - + PropertyDirection getPropertyDirection(); + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/LadderPropertySelector.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/LadderPropertySelector.java index c5b3c09..a6548c4 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/LadderPropertySelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/LadderPropertySelector.java @@ -5,9 +5,9 @@ public class LadderPropertySelector implements IPropertySelector { - @Override - public PropertyDirection getPropertyDirection() { - return BlockLadder.FACING; - } + @Override + public PropertyDirection getPropertyDirection() { + return BlockLadder.FACING; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TorchPropertySelector.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TorchPropertySelector.java index 90b89af..6f28fde 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TorchPropertySelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TorchPropertySelector.java @@ -5,9 +5,9 @@ public class TorchPropertySelector implements IPropertySelector { - @Override - public PropertyDirection getPropertyDirection() { - return BlockTorch.FACING; - } + @Override + public PropertyDirection getPropertyDirection() { + return BlockTorch.FACING; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TrapDoorPropertySelector.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TrapDoorPropertySelector.java index 71f4634..10f780a 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TrapDoorPropertySelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TrapDoorPropertySelector.java @@ -5,9 +5,9 @@ public class TrapDoorPropertySelector implements IPropertySelector { - @Override - public PropertyDirection getPropertyDirection() { - return BlockTrapDoor.FACING; - } + @Override + public PropertyDirection getPropertyDirection() { + return BlockTrapDoor.FACING; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TripWireHookPropertySelector.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TripWireHookPropertySelector.java index efddf78..511efe2 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TripWireHookPropertySelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/TripWireHookPropertySelector.java @@ -5,9 +5,9 @@ public class TripWireHookPropertySelector implements IPropertySelector { - @Override - public PropertyDirection getPropertyDirection() { - return BlockTripWireHook.FACING; - } + @Override + public PropertyDirection getPropertyDirection() { + return BlockTripWireHook.FACING; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/WallSignPropertySelector.java b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/WallSignPropertySelector.java index 35d2dd2..1fafb02 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/WallSignPropertySelector.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/builder/dependency/property/WallSignPropertySelector.java @@ -5,9 +5,9 @@ public class WallSignPropertySelector implements IPropertySelector { - @Override - public PropertyDirection getPropertyDirection() { - return BlockWallSign.FACING; - } + @Override + public PropertyDirection getPropertyDirection() { + return BlockWallSign.FACING; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/commands/ConfigCommand.java b/src/main/java/fr/eyzox/forgecreeperheal/commands/ConfigCommand.java index 95d3d53..7e4dd5b 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/commands/ConfigCommand.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/commands/ConfigCommand.java @@ -7,72 +7,72 @@ import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextFormatting; -public class ConfigCommand extends ForgeCreeperHealCommands{ +public class ConfigCommand extends ForgeCreeperHealCommands { - @Override - protected String getFCHCommandName() { - return "config"; - } - - @Override - protected String getFCHUsage() { - return "[-r] [-s] [:]"; - } + @Override + protected String getFCHCommandName() { + return "config"; + } - @Override - protected String getHelp() { - return "fch.command.config.help"; - } + @Override + protected String getFCHUsage() { + return "[-r] [-s] [:]"; + } - @Override - protected void _execute(MinecraftServer server, ICommandSender sender, String[] args) throws ForgeCreeperHealCommandException { - if(args.length < 1) { - throw new ForgeCreeperHealCommandException(sender, "fch.command.exception.missingparams", new Object[]{getCommandUsage(sender)}); - } - - int shift = 0; - - boolean reload = false, save = false; - while(shift < args.length && args[shift].startsWith("-")) { - for(int i=1; i getCommandAliases() { - final List aliases = new LinkedList(); - aliases.add(buildCommandName(BASE_ALIAS)); - return aliases; - } - - protected abstract String getFCHCommandName(); - - protected abstract String getFCHUsage(); - - protected abstract String getHelp(); - - protected abstract void _execute(MinecraftServer server, ICommandSender sender, String[] args) throws ForgeCreeperHealCommandException; - - private String buildCommandName(String prefix) { - return getFCHCommandName() != null ? (prefix+'-'+getFCHCommandName()) : prefix; - } - - @Override - public final void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { - if(args.length > 0 && "?".equals(args[0])) { - - final ITextComponent head = buildChatMessage(sender, buildTranslationMessage(sender, "fch.command.generic.help.head", new Object[]{buildCommandName(BASE_ALIAS)})); - head.getStyle().setColor(TextFormatting.DARK_GREEN); - sender.sendMessage(head); - - final ITextComponent usage = buildTranslationMessage(sender, "fch.command.generic.help.usage",new Object[]{getCommandUsage(sender)}); - usage.getStyle().setColor(TextFormatting.GRAY); - sender.sendMessage(usage); - - final String rawHelp = buildTranslationMessage(sender, getHelp()).getFormattedText(); - final String[] helps = rawHelp.split("\\\\n"); - for(int i=0; i getCommandAliases() { + final List aliases = new LinkedList(); + aliases.add(buildCommandName(BASE_ALIAS)); + return aliases; + } + + protected abstract String getFCHCommandName(); + + protected abstract String getFCHUsage(); + + protected abstract String getHelp(); + + protected abstract void _execute(MinecraftServer server, ICommandSender sender, String[] args) throws ForgeCreeperHealCommandException; + + private String buildCommandName(String prefix) { + return getFCHCommandName() != null ? (prefix + '-' + getFCHCommandName()) : prefix; + } + + @Override + public final void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { + if (args.length > 0 && "?".equals(args[0])) { + + final ITextComponent head = buildChatMessage(sender, buildTranslationMessage(sender, "fch.command.generic.help.head", new Object[]{buildCommandName(BASE_ALIAS)})); + head.getStyle().setColor(TextFormatting.DARK_GREEN); + sender.sendMessage(head); + + final ITextComponent usage = buildTranslationMessage(sender, "fch.command.generic.help.usage", new Object[]{getCommandUsage(sender)}); + usage.getStyle().setColor(TextFormatting.GRAY); + sender.sendMessage(usage); + + final String rawHelp = buildTranslationMessage(sender, getHelp()).getFormattedText(); + final String[] helps = rawHelp.split("\\\\n"); + for (int i = 0; i < helps.length; i++) { + sender.sendMessage(new TextComponentString(helps[i])); + } + } else { + _execute(server, sender, args); + } + + } + + protected static enum MessageType { + SUCCESS(TextFormatting.GREEN), ERROR(TextFormatting.RED); + + private TextFormatting color; + + private MessageType(TextFormatting color) { + this.color = color; + } + + public TextFormatting getColor() { + return color; + } + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/commands/HealCommand.java b/src/main/java/fr/eyzox/forgecreeperheal/commands/HealCommand.java index 2770706..5ad9cc8 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/commands/HealCommand.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/commands/HealCommand.java @@ -11,64 +11,64 @@ public class HealCommand extends ForgeCreeperHealCommands { - @Override - protected String getFCHCommandName() { - return "heal"; - } - - @Override - protected String getFCHUsage() { - return "[|all]"; - } + @Override + protected String getFCHCommandName() { + return "heal"; + } - @Override - protected String getHelp() { - return "fch.command.heal.help"; - } + @Override + protected String getFCHUsage() { + return "[|all]"; + } - @Override - protected void _execute(MinecraftServer server, ICommandSender sender, String[] args) throws ForgeCreeperHealCommandException { - if(args.length > 0 && "all".equalsIgnoreCase(args[0])) { - final WorldServer[] worlds = DimensionManager.getWorlds(); - for(WorldServer world : worlds) { - ForgeCreeperHeal.getHealerManager(world).heal(); - } - - final ITextComponent healAllMsg = buildChatMessage(sender, buildTranslationMessage(sender, "fch.command.heal.action.allworld"), MessageType.SUCCESS); - sender.sendMessage(healAllMsg); - }else { - WorldServer world = null; - final String rawDimId = args.length > 0 ? args[0] : null; - if(rawDimId == null) { - world = (WorldServer) sender.getEntityWorld(); - }else { - try { - world = DimensionManager.getWorld(parseInt(rawDimId)); - }catch(NumberInvalidException e) { - throw new ForgeCreeperHealCommandException(sender, "fch.command.heal.exception.invaliddimensionid", null, e); - } - } - - if(world == null) { - if(rawDimId == null) { - throw new ForgeCreeperHealCommandException(sender, "fch.command.heal.exception.noentityworld", new Object[]{sender}); - } - throw new ForgeCreeperHealCommandException(sender, "fch.command.heal.exception.nodimensionid", new Object[]{rawDimId}); - }else { - ForgeCreeperHeal.getHealerManager(world).heal(); - final ITextComponent healedMsg = buildChatMessage(sender, buildTranslationMessage(sender, "fch.command.heal.action.world", new Object[]{world.getWorldInfo().getWorldName(), world.provider.getDimension()}), MessageType.SUCCESS); - sender.sendMessage(healedMsg); - } - } - } + @Override + protected String getHelp() { + return "fch.command.heal.help"; + } - @Override - public String getName() { - return null; - } + @Override + protected void _execute(MinecraftServer server, ICommandSender sender, String[] args) throws ForgeCreeperHealCommandException { + if (args.length > 0 && "all".equalsIgnoreCase(args[0])) { + final WorldServer[] worlds = DimensionManager.getWorlds(); + for (WorldServer world : worlds) { + ForgeCreeperHeal.getHealerManager(world).heal(); + } - @Override - public String getUsage(ICommandSender sender) { - return null; - } + final ITextComponent healAllMsg = buildChatMessage(sender, buildTranslationMessage(sender, "fch.command.heal.action.allworld"), MessageType.SUCCESS); + sender.sendMessage(healAllMsg); + } else { + WorldServer world = null; + final String rawDimId = args.length > 0 ? args[0] : null; + if (rawDimId == null) { + world = (WorldServer) sender.getEntityWorld(); + } else { + try { + world = DimensionManager.getWorld(parseInt(rawDimId)); + } catch (NumberInvalidException e) { + throw new ForgeCreeperHealCommandException(sender, "fch.command.heal.exception.invaliddimensionid", null, e); + } + } + + if (world == null) { + if (rawDimId == null) { + throw new ForgeCreeperHealCommandException(sender, "fch.command.heal.exception.noentityworld", new Object[]{sender}); + } + throw new ForgeCreeperHealCommandException(sender, "fch.command.heal.exception.nodimensionid", new Object[]{rawDimId}); + } else { + ForgeCreeperHeal.getHealerManager(world).heal(); + final ITextComponent healedMsg = buildChatMessage(sender, buildTranslationMessage(sender, "fch.command.heal.action.world", new Object[]{world.getWorldInfo().getWorldName(), world.provider.getDimension()}), MessageType.SUCCESS); + sender.sendMessage(healedMsg); + } + } + } + + @Override + public String getName() { + return null; + } + + @Override + public String getUsage(ICommandSender sender) { + return null; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/commands/HelpCommand.java b/src/main/java/fr/eyzox/forgecreeperheal/commands/HelpCommand.java index 5f95e4c..13bce48 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/commands/HelpCommand.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/commands/HelpCommand.java @@ -1,8 +1,5 @@ package fr.eyzox.forgecreeperheal.commands; -import java.util.Iterator; -import java.util.List; - import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealCommandException; import net.minecraft.command.CommandException; import net.minecraft.command.CommandHelp; @@ -10,61 +7,64 @@ import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; +import java.util.Iterator; +import java.util.List; + public class HelpCommand extends ForgeCreeperHealCommands { - @Override - public String getName() { - return null; - } + private final static WrappedVanillaHelpCommand wrap = new WrappedVanillaHelpCommand(); + + @Override + public String getName() { + return null; + } + + @Override + public String getUsage(ICommandSender sender) { + return null; + } + + @Override + protected String getFCHCommandName() { + return "help"; + } - @Override - public String getUsage(ICommandSender sender) { - return null; - } + @Override + protected String getHelp() { + return "fch.command.help.help"; + } - private static final class WrappedVanillaHelpCommand extends CommandHelp { - @Override - protected List getSortedPossibleCommands(ICommandSender sender, MinecraftServer server) { - final List possibleCommands = super.getSortedPossibleCommands(sender, server); - for(Iterator it = possibleCommands.iterator(); it.hasNext();) { - ICommand c = it.next(); - if(!(c instanceof ForgeCreeperHealCommands)) { - it.remove(); - } - } - return possibleCommands; - } - } - - private final static WrappedVanillaHelpCommand wrap = new WrappedVanillaHelpCommand(); - - @Override - protected String getFCHCommandName() { - return "help"; - } + @Override + public int getRequiredPermissionLevel() { + return wrap.getRequiredPermissionLevel(); + } - @Override - protected String getHelp() { - return "fch.command.help.help"; - } - - @Override - public int getRequiredPermissionLevel() { - return wrap.getRequiredPermissionLevel(); - } + @Override + protected void _execute(MinecraftServer server, ICommandSender sender, String[] args) throws ForgeCreeperHealCommandException { + try { + wrap.execute(server, sender, args); + } catch (CommandException e) { + throw new ForgeCreeperHealCommandException(sender, e); + } + } - @Override - protected void _execute(MinecraftServer server, ICommandSender sender, String[] args) throws ForgeCreeperHealCommandException { - try { - wrap.execute(server, sender, args); - } catch (CommandException e) { - throw new ForgeCreeperHealCommandException(sender, e); - } - } + @Override + protected String getFCHUsage() { + return ""; + } - @Override - protected String getFCHUsage() { - return ""; - } + private static final class WrappedVanillaHelpCommand extends CommandHelp { + @Override + protected List getSortedPossibleCommands(ICommandSender sender, MinecraftServer server) { + final List possibleCommands = super.getSortedPossibleCommands(sender, server); + for (Iterator it = possibleCommands.iterator(); it.hasNext(); ) { + ICommand c = it.next(); + if (!(c instanceof ForgeCreeperHealCommands)) { + it.remove(); + } + } + return possibleCommands; + } + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/commands/VersionCommand.java b/src/main/java/fr/eyzox/forgecreeperheal/commands/VersionCommand.java index 3f19a9b..6f32c12 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/commands/VersionCommand.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/commands/VersionCommand.java @@ -7,33 +7,33 @@ public class VersionCommand extends ForgeCreeperHealCommands { - @Override - public void _execute(MinecraftServer server, ICommandSender sender, String[] args) { - sender.sendMessage(new TextComponentString(ForgeCreeperHeal.MODNAME)); - } - - @Override - protected String getFCHCommandName() { - return null; - } - - @Override - protected String getHelp() { - return "fch.command.version.help"; - } - - @Override - protected String getFCHUsage() { - return ""; - } - - @Override - public String getName() { - return null; - } - - @Override - public String getUsage(ICommandSender sender) { - return null; - } + @Override + public void _execute(MinecraftServer server, ICommandSender sender, String[] args) { + sender.sendMessage(new TextComponentString(ForgeCreeperHeal.MODNAME)); + } + + @Override + protected String getFCHCommandName() { + return null; + } + + @Override + protected String getHelp() { + return "fch.command.version.help"; + } + + @Override + protected String getFCHUsage() { + return ""; + } + + @Override + public String getName() { + return null; + } + + @Override + public String getUsage(ICommandSender sender) { + return null; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/config/ConfigProvider.java b/src/main/java/fr/eyzox/forgecreeperheal/config/ConfigProvider.java index 4f2f0d6..ed6aae5 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/config/ConfigProvider.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/config/ConfigProvider.java @@ -1,14 +1,5 @@ package fr.eyzox.forgecreeperheal.config; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.file.NoSuchFileException; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - import fr.eyzox.bsc.config.Config; import fr.eyzox.bsc.config.ConfigOptionGroup; import fr.eyzox.bsc.config.IConfigListener; @@ -24,290 +15,300 @@ import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; import net.minecraft.init.Blocks; -public class ConfigProvider implements IConfigProvider{ - - public static final String GROUP_HEALING_TIME = "healing time"; - public static final String GROUP_OVERRIDE = "override"; - public static final String GROUP_CONTAINERS = "containers"; - public static final String GROUP_FILTERS = "filters"; - - public static final String OPTION_MIN_TICK_BEFORE_HEAL = "minTickStart"; - public static final String OPTION_MAX_TICK_BEFORE_HEAL = "maxTickStart"; - public static final String OPTION_MIN_TICK = "minTick"; - public static final String OPTION_MAX_TICK = "maxTick"; - public static final String OPTION_OVERRIDE_BLOCK = "overrideBlock"; - public static final String OPTION_OVERRIDE_FUILD = "overrideFluid"; - public static final String OPTION_DROP_IF_COLLISION = "dropIfCollision"; - public static final String OPTION_DROP_ITEMS = "dropItems"; - public static final String OPTION_REMOVE_EXCEPTION = "removeException"; - public static final String OPTION_HEAL_EXCEPTION = "healException"; - public static final String OPTION_SOURCE_EXCEPTION = "sourceException"; - - private final List listeners = new LinkedList(); - - private IConfigLoader configLoader; - private File errorFile; - - private Config config; - - public ConfigProvider() { - this(null); - } - - public ConfigProvider(final IConfigLoader loader) { - this(loader, null); - } - - public ConfigProvider (final IConfigLoader loader, final File errorFile) { - this.configLoader = loader; - this.errorFile = errorFile; - } - - @Override - public synchronized Config getConfig() throws ConfigException{ - if(config == null) { - throw new ConfigException("Config is not loaded"); - } - return config; - } - - @Override - public synchronized void addConfigListener(IConfigListener listener) { - this.listeners.add(listener); - } - - @Override - public synchronized void removeConfigListener(IConfigListener listener) { - this.listeners.remove(listener); - } - - @Override - public synchronized void loadConfig() { - config = loadDefaultConfig(); - if(configLoader != null) { - try { - this.configLoader.load(config); - }catch(final NoSuchFileException e) { - ForgeCreeperHeal.getLogger().info("Config File doesn't exist at "+e.getFile()+" : creating a new one"); - }catch (Exception e2) { - e2.printStackTrace(); - ForgeCreeperHeal.getLogger().error("Unable to load config : "+e2.getMessage()); - } - } - - if(configLoader.getErrorManager().hasErrors()) { - FileWriter out = null; - try { - out = new FileWriter(errorFile); - PrintWriter pw = new PrintWriter(out); - configLoader.getErrorManager().output(pw); - ForgeCreeperHeal.getLogger().warn("Errors occurs during loading config, more information in "+errorFile.getAbsolutePath()); - }catch(IOException e) { - ForgeCreeperHeal.getLogger().error("Errors occurs during loading config, unable to write into "+errorFile.getAbsolutePath()+" : "+e.getMessage()); - for(ConfigException error : configLoader.getErrorManager().getErrors()) { - ForgeCreeperHeal.getLogger().info(error.getMessage()); - } - }finally { - if(out != null) { - try { - out.close(); - } catch (IOException e) {} - } - } - } - - } - - @Override - public synchronized void unloadConfig() { - config = null; - } - - @Override - public synchronized void fireConfigChanged() throws ConfigException{ - final Config config = this.getConfig(); - for(IConfigListener listener : listeners) { - listener.onChange(config); - } - } - - public synchronized IConfigLoader getConfigLoader() { - return configLoader; - } - - public synchronized void setConfigLoader(IConfigLoader configLoader) { - this.configLoader = configLoader; - } - - public synchronized File getErrorFile() { - return errorFile; - } - - public synchronized void setErrorFile(File errorFile) { - this.errorFile = errorFile; - } - - private Config loadDefaultConfig() { - - final IntValidator positiveIntValidator = new IntValidator(0, Integer.MAX_VALUE); - - //## ConfigOptions - - final ConfigOption minTickBeforeStartHeal = new ConfigOption(OPTION_MIN_TICK_BEFORE_HEAL); - final ConfigOption maxTickBeforeStartHeal = new ConfigOption(OPTION_MAX_TICK_BEFORE_HEAL); - final ConfigOption minTickBetweenEachHeal = new ConfigOption(OPTION_MIN_TICK); - final ConfigOption maxTickBetweenEachHeal = new ConfigOption(OPTION_MAX_TICK); - - final ConfigOption overrideBlock = new ConfigOption(OPTION_OVERRIDE_BLOCK); - final ConfigOption overrideFluid = new ConfigOption(OPTION_OVERRIDE_FUILD); - final ConfigOption dropIfAlreadyBlock = new ConfigOption(OPTION_DROP_IF_COLLISION); - - final ConfigOption dropItemsFromContainers = new ConfigOption(OPTION_DROP_ITEMS); - - final ConfigOptionList removeException = new ConfigOptionList(OPTION_REMOVE_EXCEPTION); - final ConfigOptionList healException = new ConfigOptionList(OPTION_HEAL_EXCEPTION); - final ConfigOptionList fromEntityException = new ConfigOptionList(OPTION_SOURCE_EXCEPTION); - - //## Default value - - //6000 ticks = 360 seconds = 5 mins = 1/2 minecraft day - //12000 ticks = 720 seconds = 10 mins = 1 minecraft day - minTickBeforeStartHeal.setValue("6000"); - maxTickBeforeStartHeal.setValue("12000"); - //200 ticks = 10 seconds - minTickBetweenEachHeal.setValue("0"); - maxTickBetweenEachHeal.setValue("200"); - - overrideBlock.setValue("false"); - overrideFluid.setValue("true"); - dropIfAlreadyBlock.setValue("true"); - - dropItemsFromContainers.setValue("false"); - - final List removeExceptionValues = new ArrayList(1); - removeExceptionValues.add(Blocks.TNT.getRegistryName().toString()); - removeException.setValues(removeExceptionValues); - final List healExceptionValues = new ArrayList(1); - healExceptionValues.add(Blocks.TNT.getRegistryName().toString()); - healException.setValues(healExceptionValues); - final List fromEntityExceptionValues = new ArrayList(); - fromEntityException.setValues(fromEntityExceptionValues); - - //## Validator - - minTickBeforeStartHeal.setValidator(new IValidator() { - @Override - public boolean isValid(String value) throws InvalidValueException { - if(positiveIntValidator.isValid(value)) { - if(Integer.parseInt(value) <= Integer.parseInt(maxTickBeforeStartHeal.getValue())) { - return true; - }else { - throw new InvalidValueException(value, String.format("INTEGER <= %s [%s]", maxTickBeforeStartHeal.getName(), maxTickBeforeStartHeal.getValue())); - } - }else { - return false; - } - } - }); - - maxTickBeforeStartHeal.setValidator(new IValidator() { - @Override - public boolean isValid(String value) throws InvalidValueException { - if(positiveIntValidator.isValid(value)) { - if(Integer.parseInt(minTickBeforeStartHeal.getValue()) <= Integer.parseInt(value)) { - return true; - }else { - throw new InvalidValueException(value, String.format("INTEGER >= %s [%s]", minTickBeforeStartHeal.getName(), minTickBeforeStartHeal.getValue())); - } - }else { - return false; - } - } - }); - - minTickBetweenEachHeal.setValidator(new IValidator() { - @Override - public boolean isValid(String value) throws InvalidValueException { - if(positiveIntValidator.isValid(value)) { - if(Integer.parseInt(value) <= Integer.parseInt(maxTickBetweenEachHeal.getValue())) { - return true; - }else { - throw new InvalidValueException(value, String.format("INTEGER <= %s [%s]", maxTickBetweenEachHeal.getName(), maxTickBetweenEachHeal.getValue())); - } - }else { - return false; - } - } - }); - - maxTickBetweenEachHeal.setValidator(new IValidator() { - @Override - public boolean isValid(String value) throws InvalidValueException { - if(positiveIntValidator.isValid(value)) { - if(Integer.parseInt(minTickBetweenEachHeal.getValue()) <= Integer.parseInt(value)) { - return true; - }else { - throw new InvalidValueException(value, String.format("INTEGER >= %s [%s]", minTickBetweenEachHeal.getName(), minTickBetweenEachHeal.getValue())); - } - }else { - return false; - } - } - }); - - - overrideBlock.setValidator(BooleanValidator.getInstance()); - overrideFluid.setValidator(BooleanValidator.getInstance()); - dropIfAlreadyBlock.setValidator(BooleanValidator.getInstance()); - - dropItemsFromContainers.setValidator(BooleanValidator.getInstance()); - - //## Descriptions - - minTickBeforeStartHeal.setDescription("Minimum ticks before starting heal (Only affect new explosions)"); - maxTickBeforeStartHeal.setDescription("Maximum ticks before starting heal (Only affect new explosions)"); - minTickBetweenEachHeal.setDescription("Minimum ticks between each heal (Only affect new explosions)"); - maxTickBetweenEachHeal.setDescription("Maximum ticks between each heal (Only affect new explosions)"); - - overrideBlock.setDescription("When a block is healed, if a replacement block has been placed meanwhile, this block is overrided by the healed block"); - overrideFluid.setDescription("When a block is healed, if a fluid filled the block position meanwhile, this fluid is overrided at this position by the healed block"); - dropIfAlreadyBlock.setDescription("If "+overrideBlock.getName()+" then the replacement block is dropped, else the block about to be heal is dropped"); - - dropItemsFromContainers.setDescription("Drops all items from a container when it blows up, else items are restored with the container when healed (Only affect new explosions)"); - - removeException.setDescription("These blocks will be not removed after a handled explosion and will be affected by the explosion"); - healException.setDescription("These blocks will be not healed"); - fromEntityException.setDescription("Forge Creeper Heal does not handle explosion triggered by entity from these entities"); - - //## ConfigOptionGroups - - final ConfigOptionGroup healingTimeGroup = new ConfigOptionGroup(GROUP_HEALING_TIME); - healingTimeGroup.addOption(minTickBeforeStartHeal); - healingTimeGroup.addOption(maxTickBeforeStartHeal); - healingTimeGroup.addOption(minTickBetweenEachHeal); - healingTimeGroup.addOption(maxTickBetweenEachHeal); - - final ConfigOptionGroup overrideGroup = new ConfigOptionGroup(GROUP_OVERRIDE); - overrideGroup.addOption(overrideBlock); - overrideGroup.addOption(overrideFluid); - overrideGroup.addOption(dropIfAlreadyBlock); - - final ConfigOptionGroup containerGroup = new ConfigOptionGroup(GROUP_CONTAINERS); - containerGroup.addOption(dropItemsFromContainers); - - final ConfigOptionGroup filtersGroup = new ConfigOptionGroup(GROUP_FILTERS); - filtersGroup.addOption(removeException); - filtersGroup.addOption(healException); - filtersGroup.addOption(fromEntityException); - - //## Config - - final Config config = new Config(); - config.addOptionGroup(healingTimeGroup); - config.addOptionGroup(overrideGroup); - config.addOptionGroup(containerGroup); - config.addOptionGroup(filtersGroup); - return config; - } +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.NoSuchFileException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class ConfigProvider implements IConfigProvider { + + public static final String GROUP_HEALING_TIME = "healing time"; + public static final String GROUP_OVERRIDE = "override"; + public static final String GROUP_CONTAINERS = "containers"; + public static final String GROUP_FILTERS = "filters"; + + public static final String OPTION_MIN_TICK_BEFORE_HEAL = "minTickStart"; + public static final String OPTION_MAX_TICK_BEFORE_HEAL = "maxTickStart"; + public static final String OPTION_MIN_TICK = "minTick"; + public static final String OPTION_MAX_TICK = "maxTick"; + public static final String OPTION_OVERRIDE_BLOCK = "overrideBlock"; + public static final String OPTION_OVERRIDE_FUILD = "overrideFluid"; + public static final String OPTION_DROP_IF_COLLISION = "dropIfCollision"; + public static final String OPTION_DROP_ITEMS = "dropItems"; + public static final String OPTION_REMOVE_EXCEPTION = "removeException"; + public static final String OPTION_HEAL_EXCEPTION = "healException"; + public static final String OPTION_SOURCE_EXCEPTION = "sourceException"; + + private final List listeners = new LinkedList(); + + private IConfigLoader configLoader; + private File errorFile; + + private Config config; + + public ConfigProvider() { + this(null); + } + + public ConfigProvider(final IConfigLoader loader) { + this(loader, null); + } + + public ConfigProvider(final IConfigLoader loader, final File errorFile) { + this.configLoader = loader; + this.errorFile = errorFile; + } + + @Override + public synchronized Config getConfig() throws ConfigException { + if (config == null) { + throw new ConfigException("Config is not loaded"); + } + return config; + } + + @Override + public synchronized void addConfigListener(IConfigListener listener) { + this.listeners.add(listener); + } + + @Override + public synchronized void removeConfigListener(IConfigListener listener) { + this.listeners.remove(listener); + } + + @Override + public synchronized void loadConfig() { + config = loadDefaultConfig(); + if (configLoader != null) { + try { + this.configLoader.load(config); + } catch (final NoSuchFileException e) { + ForgeCreeperHeal.getLogger().info("Config File doesn't exist at " + e.getFile() + " : creating a new one"); + } catch (Exception e2) { + e2.printStackTrace(); + ForgeCreeperHeal.getLogger().error("Unable to load config : " + e2.getMessage()); + } + } + + if (configLoader.getErrorManager().hasErrors()) { + FileWriter out = null; + try { + out = new FileWriter(errorFile); + PrintWriter pw = new PrintWriter(out); + configLoader.getErrorManager().output(pw); + ForgeCreeperHeal.getLogger().warn("Errors occurs during loading config, more information in " + errorFile.getAbsolutePath()); + } catch (IOException e) { + ForgeCreeperHeal.getLogger().error("Errors occurs during loading config, unable to write into " + errorFile.getAbsolutePath() + " : " + e.getMessage()); + for (ConfigException error : configLoader.getErrorManager().getErrors()) { + ForgeCreeperHeal.getLogger().info(error.getMessage()); + } + } finally { + if (out != null) { + try { + out.close(); + } catch (IOException e) { + } + } + } + } + + } + + @Override + public synchronized void unloadConfig() { + config = null; + } + + @Override + public synchronized void fireConfigChanged() throws ConfigException { + final Config config = this.getConfig(); + for (IConfigListener listener : listeners) { + listener.onChange(config); + } + } + + public synchronized IConfigLoader getConfigLoader() { + return configLoader; + } + + public synchronized void setConfigLoader(IConfigLoader configLoader) { + this.configLoader = configLoader; + } + + public synchronized File getErrorFile() { + return errorFile; + } + + public synchronized void setErrorFile(File errorFile) { + this.errorFile = errorFile; + } + + private Config loadDefaultConfig() { + + final IntValidator positiveIntValidator = new IntValidator(0, Integer.MAX_VALUE); + + //## ConfigOptions + + final ConfigOption minTickBeforeStartHeal = new ConfigOption(OPTION_MIN_TICK_BEFORE_HEAL); + final ConfigOption maxTickBeforeStartHeal = new ConfigOption(OPTION_MAX_TICK_BEFORE_HEAL); + final ConfigOption minTickBetweenEachHeal = new ConfigOption(OPTION_MIN_TICK); + final ConfigOption maxTickBetweenEachHeal = new ConfigOption(OPTION_MAX_TICK); + + final ConfigOption overrideBlock = new ConfigOption(OPTION_OVERRIDE_BLOCK); + final ConfigOption overrideFluid = new ConfigOption(OPTION_OVERRIDE_FUILD); + final ConfigOption dropIfAlreadyBlock = new ConfigOption(OPTION_DROP_IF_COLLISION); + + final ConfigOption dropItemsFromContainers = new ConfigOption(OPTION_DROP_ITEMS); + + final ConfigOptionList removeException = new ConfigOptionList(OPTION_REMOVE_EXCEPTION); + final ConfigOptionList healException = new ConfigOptionList(OPTION_HEAL_EXCEPTION); + final ConfigOptionList fromEntityException = new ConfigOptionList(OPTION_SOURCE_EXCEPTION); + + //## Default value + + //6000 ticks = 360 seconds = 5 mins = 1/2 minecraft day + //12000 ticks = 720 seconds = 10 mins = 1 minecraft day + minTickBeforeStartHeal.setValue("6000"); + maxTickBeforeStartHeal.setValue("12000"); + //200 ticks = 10 seconds + minTickBetweenEachHeal.setValue("0"); + maxTickBetweenEachHeal.setValue("200"); + + overrideBlock.setValue("false"); + overrideFluid.setValue("true"); + dropIfAlreadyBlock.setValue("true"); + + dropItemsFromContainers.setValue("false"); + + final List removeExceptionValues = new ArrayList(1); + removeExceptionValues.add(Blocks.TNT.getRegistryName().toString()); + removeException.setValues(removeExceptionValues); + final List healExceptionValues = new ArrayList(1); + healExceptionValues.add(Blocks.TNT.getRegistryName().toString()); + healException.setValues(healExceptionValues); + final List fromEntityExceptionValues = new ArrayList(); + fromEntityException.setValues(fromEntityExceptionValues); + + //## Validator + + minTickBeforeStartHeal.setValidator(new IValidator() { + @Override + public boolean isValid(String value) throws InvalidValueException { + if (positiveIntValidator.isValid(value)) { + if (Integer.parseInt(value) <= Integer.parseInt(maxTickBeforeStartHeal.getValue())) { + return true; + } else { + throw new InvalidValueException(value, String.format("INTEGER <= %s [%s]", maxTickBeforeStartHeal.getName(), maxTickBeforeStartHeal.getValue())); + } + } else { + return false; + } + } + }); + + maxTickBeforeStartHeal.setValidator(new IValidator() { + @Override + public boolean isValid(String value) throws InvalidValueException { + if (positiveIntValidator.isValid(value)) { + if (Integer.parseInt(minTickBeforeStartHeal.getValue()) <= Integer.parseInt(value)) { + return true; + } else { + throw new InvalidValueException(value, String.format("INTEGER >= %s [%s]", minTickBeforeStartHeal.getName(), minTickBeforeStartHeal.getValue())); + } + } else { + return false; + } + } + }); + + minTickBetweenEachHeal.setValidator(new IValidator() { + @Override + public boolean isValid(String value) throws InvalidValueException { + if (positiveIntValidator.isValid(value)) { + if (Integer.parseInt(value) <= Integer.parseInt(maxTickBetweenEachHeal.getValue())) { + return true; + } else { + throw new InvalidValueException(value, String.format("INTEGER <= %s [%s]", maxTickBetweenEachHeal.getName(), maxTickBetweenEachHeal.getValue())); + } + } else { + return false; + } + } + }); + + maxTickBetweenEachHeal.setValidator(new IValidator() { + @Override + public boolean isValid(String value) throws InvalidValueException { + if (positiveIntValidator.isValid(value)) { + if (Integer.parseInt(minTickBetweenEachHeal.getValue()) <= Integer.parseInt(value)) { + return true; + } else { + throw new InvalidValueException(value, String.format("INTEGER >= %s [%s]", minTickBetweenEachHeal.getName(), minTickBetweenEachHeal.getValue())); + } + } else { + return false; + } + } + }); + + + overrideBlock.setValidator(BooleanValidator.getInstance()); + overrideFluid.setValidator(BooleanValidator.getInstance()); + dropIfAlreadyBlock.setValidator(BooleanValidator.getInstance()); + + dropItemsFromContainers.setValidator(BooleanValidator.getInstance()); + + //## Descriptions + + minTickBeforeStartHeal.setDescription("Minimum ticks before starting heal (Only affect new explosions)"); + maxTickBeforeStartHeal.setDescription("Maximum ticks before starting heal (Only affect new explosions)"); + minTickBetweenEachHeal.setDescription("Minimum ticks between each heal (Only affect new explosions)"); + maxTickBetweenEachHeal.setDescription("Maximum ticks between each heal (Only affect new explosions)"); + + overrideBlock.setDescription("When a block is healed, if a replacement block has been placed meanwhile, this block is overrided by the healed block"); + overrideFluid.setDescription("When a block is healed, if a fluid filled the block position meanwhile, this fluid is overrided at this position by the healed block"); + dropIfAlreadyBlock.setDescription("If " + overrideBlock.getName() + " then the replacement block is dropped, else the block about to be heal is dropped"); + + dropItemsFromContainers.setDescription("Drops all items from a container when it blows up, else items are restored with the container when healed (Only affect new explosions)"); + + removeException.setDescription("These blocks will be not removed after a handled explosion and will be affected by the explosion"); + healException.setDescription("These blocks will be not healed"); + fromEntityException.setDescription("Forge Creeper Heal does not handle explosion triggered by entity from these entities"); + + //## ConfigOptionGroups + + final ConfigOptionGroup healingTimeGroup = new ConfigOptionGroup(GROUP_HEALING_TIME); + healingTimeGroup.addOption(minTickBeforeStartHeal); + healingTimeGroup.addOption(maxTickBeforeStartHeal); + healingTimeGroup.addOption(minTickBetweenEachHeal); + healingTimeGroup.addOption(maxTickBetweenEachHeal); + + final ConfigOptionGroup overrideGroup = new ConfigOptionGroup(GROUP_OVERRIDE); + overrideGroup.addOption(overrideBlock); + overrideGroup.addOption(overrideFluid); + overrideGroup.addOption(dropIfAlreadyBlock); + + final ConfigOptionGroup containerGroup = new ConfigOptionGroup(GROUP_CONTAINERS); + containerGroup.addOption(dropItemsFromContainers); + + final ConfigOptionGroup filtersGroup = new ConfigOptionGroup(GROUP_FILTERS); + filtersGroup.addOption(removeException); + filtersGroup.addOption(healException); + filtersGroup.addOption(fromEntityException); + + //## Config + + final Config config = new Config(); + config.addOptionGroup(healingTimeGroup); + config.addOptionGroup(overrideGroup); + config.addOptionGroup(containerGroup); + config.addOptionGroup(filtersGroup); + return config; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/config/FastConfig.java b/src/main/java/fr/eyzox/forgecreeperheal/config/FastConfig.java index d7dcdb6..c478392 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/config/FastConfig.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/config/FastConfig.java @@ -1,107 +1,104 @@ package fr.eyzox.forgecreeperheal.config; -import java.util.HashSet; -import java.util.Set; - import fr.eyzox.bsc.config.Config; import fr.eyzox.bsc.config.ConfigOptionGroup; import fr.eyzox.bsc.config.IConfigListener; import fr.eyzox.bsc.config.option.ConfigOption; import fr.eyzox.bsc.config.option.ConfigOptionList; +import java.util.HashSet; +import java.util.Set; + public class FastConfig implements IConfigListener { - private int minTickStart, maxTickStart; - private int minTick, maxTick; - - private boolean overrideBlock, overrideFluid; - private boolean dropIfCollision; - - private boolean dropItems; - - private final Set removeException = new HashSet(); - private final Set healException = new HashSet(); - private final Set sourceException = new HashSet(); - - public FastConfig() {} - - @Override - public void onChange(Config config) { - - removeException.clear(); - healException.clear(); - sourceException.clear(); - - ConfigOptionGroup group = config.getOptionGroup(ConfigProvider.GROUP_HEALING_TIME); - - this.minTickStart = Integer.parseInt(((ConfigOption)group.getOption(ConfigProvider.OPTION_MIN_TICK_BEFORE_HEAL)).getValue()); - this.maxTickStart = Integer.parseInt(((ConfigOption)group.getOption(ConfigProvider.OPTION_MAX_TICK_BEFORE_HEAL)).getValue()); - - this.minTick = Integer.parseInt(((ConfigOption)group.getOption(ConfigProvider.OPTION_MIN_TICK)).getValue()); - this.maxTick = Integer.parseInt(((ConfigOption)group.getOption(ConfigProvider.OPTION_MAX_TICK)).getValue()); - - group = config.getOptionGroup(ConfigProvider.GROUP_OVERRIDE); - - this.overrideBlock = Boolean.parseBoolean(((ConfigOption)group.getOption(ConfigProvider.OPTION_OVERRIDE_BLOCK)).getValue()); - this.overrideFluid = Boolean.parseBoolean(((ConfigOption)group.getOption(ConfigProvider.OPTION_OVERRIDE_FUILD)).getValue()); - this.dropIfCollision = Boolean.parseBoolean(((ConfigOption)group.getOption(ConfigProvider.OPTION_DROP_IF_COLLISION)).getValue()); - - group = config.getOptionGroup(ConfigProvider.GROUP_CONTAINERS); - - this.dropItems = Boolean.parseBoolean(((ConfigOption)group.getOption(ConfigProvider.OPTION_DROP_ITEMS)).getValue()); - - group = config.getOptionGroup(ConfigProvider.GROUP_FILTERS); - - this.removeException.addAll(((ConfigOptionList)group.getOption(ConfigProvider.OPTION_REMOVE_EXCEPTION)).getValues()); - this.healException.addAll(((ConfigOptionList)group.getOption(ConfigProvider.OPTION_HEAL_EXCEPTION)).getValues()); - this.sourceException.addAll(((ConfigOptionList)group.getOption(ConfigProvider.OPTION_SOURCE_EXCEPTION)).getValues()); - - } - - public int getMinTickStart() { - return minTickStart; - } - - public int getMaxTickStart() { - return maxTickStart; - } - - public int getMinTick() { - return minTick; - } - - public int getMaxTick() { - return maxTick; - } - - public boolean isOverrideBlock() { - return overrideBlock; - } - - public boolean isOverrideFluid() { - return overrideFluid; - } - - public boolean isDropIfCollision() { - return dropIfCollision; - } - - public boolean isDropItems() { - return dropItems; - } - - public Set getRemoveException() { - return removeException; - } - - public Set getHealException() { - return healException; - } - - public Set getSourceException() { - return sourceException; - } - - + private final Set removeException = new HashSet(); + private final Set healException = new HashSet(); + private final Set sourceException = new HashSet(); + private int minTickStart, maxTickStart; + private int minTick, maxTick; + private boolean overrideBlock, overrideFluid; + private boolean dropIfCollision; + private boolean dropItems; + + public FastConfig() { + } + + @Override + public void onChange(Config config) { + + removeException.clear(); + healException.clear(); + sourceException.clear(); + + ConfigOptionGroup group = config.getOptionGroup(ConfigProvider.GROUP_HEALING_TIME); + + this.minTickStart = Integer.parseInt(((ConfigOption) group.getOption(ConfigProvider.OPTION_MIN_TICK_BEFORE_HEAL)).getValue()); + this.maxTickStart = Integer.parseInt(((ConfigOption) group.getOption(ConfigProvider.OPTION_MAX_TICK_BEFORE_HEAL)).getValue()); + + this.minTick = Integer.parseInt(((ConfigOption) group.getOption(ConfigProvider.OPTION_MIN_TICK)).getValue()); + this.maxTick = Integer.parseInt(((ConfigOption) group.getOption(ConfigProvider.OPTION_MAX_TICK)).getValue()); + + group = config.getOptionGroup(ConfigProvider.GROUP_OVERRIDE); + + this.overrideBlock = Boolean.parseBoolean(((ConfigOption) group.getOption(ConfigProvider.OPTION_OVERRIDE_BLOCK)).getValue()); + this.overrideFluid = Boolean.parseBoolean(((ConfigOption) group.getOption(ConfigProvider.OPTION_OVERRIDE_FUILD)).getValue()); + this.dropIfCollision = Boolean.parseBoolean(((ConfigOption) group.getOption(ConfigProvider.OPTION_DROP_IF_COLLISION)).getValue()); + + group = config.getOptionGroup(ConfigProvider.GROUP_CONTAINERS); + + this.dropItems = Boolean.parseBoolean(((ConfigOption) group.getOption(ConfigProvider.OPTION_DROP_ITEMS)).getValue()); + + group = config.getOptionGroup(ConfigProvider.GROUP_FILTERS); + + this.removeException.addAll(((ConfigOptionList) group.getOption(ConfigProvider.OPTION_REMOVE_EXCEPTION)).getValues()); + this.healException.addAll(((ConfigOptionList) group.getOption(ConfigProvider.OPTION_HEAL_EXCEPTION)).getValues()); + this.sourceException.addAll(((ConfigOptionList) group.getOption(ConfigProvider.OPTION_SOURCE_EXCEPTION)).getValues()); + + } + + public int getMinTickStart() { + return minTickStart; + } + + public int getMaxTickStart() { + return maxTickStart; + } + + public int getMinTick() { + return minTick; + } + + public int getMaxTick() { + return maxTick; + } + + public boolean isOverrideBlock() { + return overrideBlock; + } + + public boolean isOverrideFluid() { + return overrideFluid; + } + + public boolean isDropIfCollision() { + return dropIfCollision; + } + + public boolean isDropItems() { + return dropItems; + } + + public Set getRemoveException() { + return removeException; + } + + public Set getHealException() { + return healException; + } + + public Set getSourceException() { + return sourceException; + } + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealCommandException.java b/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealCommandException.java index 418f594..d5ca0e7 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealCommandException.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealCommandException.java @@ -7,15 +7,15 @@ public class ForgeCreeperHealCommandException extends CommandException { - public ForgeCreeperHealCommandException(ICommandSender sender, String message, Object[] objects) { - this(sender, message, objects, null); - } - - public ForgeCreeperHealCommandException(ICommandSender sender, CommandException cause) { - this(sender, null, null, cause); - } + public ForgeCreeperHealCommandException(ICommandSender sender, String message, Object[] objects) { + this(sender, message, objects, null); + } - public ForgeCreeperHealCommandException(ICommandSender sender, String message, Object[] objects, CommandException cause) { - super(ForgeCreeperHealCommands.buildChatMessage(sender, new TextComponentString("")).getText()+ForgeCreeperHealCommands.buildTranslationMessage(sender, message, objects).getText()+(cause == null ? "" : (" : "+net.minecraft.util.text.translation.I18n.translateToLocalFormatted(cause.getMessage(), cause.getErrorObjects()))), new Object[]{}); - } + public ForgeCreeperHealCommandException(ICommandSender sender, CommandException cause) { + this(sender, null, null, cause); + } + + public ForgeCreeperHealCommandException(ICommandSender sender, String message, Object[] objects, CommandException cause) { + super(ForgeCreeperHealCommands.buildChatMessage(sender, new TextComponentString("")).getText() + ForgeCreeperHealCommands.buildTranslationMessage(sender, message, objects).getText() + (cause == null ? "" : (" : " + net.minecraft.util.text.translation.I18n.translateToLocalFormatted(cause.getMessage(), cause.getErrorObjects()))), new Object[]{}); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealException.java b/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealException.java index 46512e0..c909337 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealException.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealException.java @@ -2,24 +2,24 @@ public class ForgeCreeperHealException extends RuntimeException { - public ForgeCreeperHealException() { - } + public ForgeCreeperHealException() { + } - public ForgeCreeperHealException(String message) { - super(message); - } + public ForgeCreeperHealException(String message) { + super(message); + } - public ForgeCreeperHealException(Throwable cause) { - super(cause); - } + public ForgeCreeperHealException(Throwable cause) { + super(cause); + } - public ForgeCreeperHealException(String message, Throwable cause) { - super(message, cause); - } + public ForgeCreeperHealException(String message, Throwable cause) { + super(message, cause); + } - public ForgeCreeperHealException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public ForgeCreeperHealException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealReflectionException.java b/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealReflectionException.java index e2dbae4..b95987c 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealReflectionException.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealReflectionException.java @@ -2,25 +2,25 @@ public class ForgeCreeperHealReflectionException extends ForgeCreeperHealException { - public ForgeCreeperHealReflectionException() { - super(); - } + public ForgeCreeperHealReflectionException() { + super(); + } - public ForgeCreeperHealReflectionException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public ForgeCreeperHealReflectionException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } - public ForgeCreeperHealReflectionException(String message, Throwable cause) { - super(message, cause); - } + public ForgeCreeperHealReflectionException(String message, Throwable cause) { + super(message, cause); + } - public ForgeCreeperHealReflectionException(String message) { - super(message); - } + public ForgeCreeperHealReflectionException(String message) { + super(message); + } - public ForgeCreeperHealReflectionException(Throwable cause) { - super(cause); - } + public ForgeCreeperHealReflectionException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealerSerialException.java b/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealerSerialException.java index b94448c..bb3f660 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealerSerialException.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/exception/ForgeCreeperHealerSerialException.java @@ -2,25 +2,25 @@ public class ForgeCreeperHealerSerialException extends ForgeCreeperHealException { - public ForgeCreeperHealerSerialException() { - super(); - } + public ForgeCreeperHealerSerialException() { + super(); + } - public ForgeCreeperHealerSerialException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public ForgeCreeperHealerSerialException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } - public ForgeCreeperHealerSerialException(String message, Throwable cause) { - super(message, cause); - } + public ForgeCreeperHealerSerialException(String message, Throwable cause) { + super(message, cause); + } - public ForgeCreeperHealerSerialException(String message) { - super(message); - } + public ForgeCreeperHealerSerialException(String message) { + super(message); + } - public ForgeCreeperHealerSerialException(Throwable cause) { - super(cause); - } + public ForgeCreeperHealerSerialException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/factory/DefaultFactory.java b/src/main/java/fr/eyzox/forgecreeperheal/factory/DefaultFactory.java index f91a378..c81ffc8 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/factory/DefaultFactory.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/factory/DefaultFactory.java @@ -4,25 +4,25 @@ public class DefaultFactory> extends Factory { - private final DATA _default; - - public DefaultFactory(final IKeyBuilder keyBuilder, final DATA _default) { - super(keyBuilder); - this._default = _default; - } - - @Override - public DATA getData(String key) { - DATA data = super.getData(key); - if(data == null && _default.accept(keyBuilder.convertToKey(key))) { - data = _default; - customCache.put(key, data); - } - return data; - } - - public DATA getDefault() { - return _default; - } + private final DATA _default; + + public DefaultFactory(final IKeyBuilder keyBuilder, final DATA _default) { + super(keyBuilder); + this._default = _default; + } + + @Override + public DATA getData(String key) { + DATA data = super.getData(key); + if (data == null && _default.accept(keyBuilder.convertToKey(key))) { + data = _default; + customCache.put(key, data); + } + return data; + } + + public DATA getDefault() { + return _default; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/factory/Factory.java b/src/main/java/fr/eyzox/forgecreeperheal/factory/Factory.java index fb76ef5..e1c56a0 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/factory/Factory.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/factory/Factory.java @@ -1,52 +1,52 @@ package fr.eyzox.forgecreeperheal.factory; +import fr.eyzox.forgecreeperheal.factory.keybuilder.IKeyBuilder; + import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -import fr.eyzox.forgecreeperheal.factory.keybuilder.IKeyBuilder; - public class Factory> { - protected final List custom = new LinkedList(); - protected final Map customCache = new HashMap(); - - protected final IKeyBuilder keyBuilder; - - public Factory(final IKeyBuilder keyBuilder) { - this.keyBuilder = keyBuilder; - } - - public List getCustomHandlers() { - return custom; - } - - public DATA getData(final KEY key) { - return this.getData(keyBuilder.convertToString(key)); - } - - public DATA getData(final String key) { - DATA data = customCache.get(key); - if(data == null) { - for(DATA dataFromCustom : custom) { - if(dataFromCustom.accept(keyBuilder.convertToKey(key))) { - data = dataFromCustom; - break; - } - } - - if(data != null){ - customCache.put(key, data); - } - - } - - return data; - } - - public void clearCache() { - customCache.clear(); - } + protected final List custom = new LinkedList(); + protected final Map customCache = new HashMap(); + + protected final IKeyBuilder keyBuilder; + + public Factory(final IKeyBuilder keyBuilder) { + this.keyBuilder = keyBuilder; + } + + public List getCustomHandlers() { + return custom; + } + + public DATA getData(final KEY key) { + return this.getData(keyBuilder.convertToString(key)); + } + + public DATA getData(final String key) { + DATA data = customCache.get(key); + if (data == null) { + for (DATA dataFromCustom : custom) { + if (dataFromCustom.accept(keyBuilder.convertToKey(key))) { + data = dataFromCustom; + break; + } + } + + if (data != null) { + customCache.put(key, data); + } + + } + + return data; + } + + public void clearCache() { + customCache.clear(); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/factory/IData.java b/src/main/java/fr/eyzox/forgecreeperheal/factory/IData.java index f6ed920..125be37 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/factory/IData.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/factory/IData.java @@ -1,5 +1,5 @@ package fr.eyzox.forgecreeperheal.factory; public interface IData { - public boolean accept(INPUT in); + public boolean accept(INPUT in); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/factory/keybuilder/BlockKeyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/factory/keybuilder/BlockKeyBuilder.java index 7e5c1b9..236fe67 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/factory/keybuilder/BlockKeyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/factory/keybuilder/BlockKeyBuilder.java @@ -4,23 +4,23 @@ public class BlockKeyBuilder implements IKeyBuilder { - private static final BlockKeyBuilder INSTANCE = new BlockKeyBuilder(); - - private BlockKeyBuilder() { - } - - @Override - public String convertToString(Block key) { - return key.getRegistryName().toString(); - } - - @Override - public Block convertToKey(String keyStr) { - return Block.getBlockFromName(keyStr); - } - - public static BlockKeyBuilder getInstance() { - return INSTANCE; - } + private static final BlockKeyBuilder INSTANCE = new BlockKeyBuilder(); + + private BlockKeyBuilder() { + } + + public static BlockKeyBuilder getInstance() { + return INSTANCE; + } + + @Override + public String convertToString(Block key) { + return key.getRegistryName().toString(); + } + + @Override + public Block convertToKey(String keyStr) { + return Block.getBlockFromName(keyStr); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/factory/keybuilder/IKeyBuilder.java b/src/main/java/fr/eyzox/forgecreeperheal/factory/keybuilder/IKeyBuilder.java index 430a63a..cf2bc56 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/factory/keybuilder/IKeyBuilder.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/factory/keybuilder/IKeyBuilder.java @@ -1,6 +1,7 @@ package fr.eyzox.forgecreeperheal.factory.keybuilder; public interface IKeyBuilder { - public String convertToString(final KEY key); - public KEY convertToKey(final String keyStr); + public String convertToString(final KEY key); + + public KEY convertToKey(final String keyStr); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/handler/ChunkEventHandler.java b/src/main/java/fr/eyzox/forgecreeperheal/handler/ChunkEventHandler.java index ef1efce..90d30e9 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/handler/ChunkEventHandler.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/handler/ChunkEventHandler.java @@ -11,69 +11,69 @@ import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -public class ChunkEventHandler implements IEventHandler{ - - private static final String FCH_TAG = "FCHTAG"; - private static final String HEALER_TAG = "HEALER"; - - @SubscribeEvent - public void onChunkDataLoad(final ChunkDataEvent.Load event) { - if(event.getWorld().isRemote) return; - - final NBTTagCompound FCHTag = event.getData().getCompoundTag(FCH_TAG); - if(!FCHTag.hasNoTags()) { - final NBTTagCompound healerTag = FCHTag.getCompoundTag(HEALER_TAG); - if(!healerTag.hasNoTags()) { - - final Healer healer = new Healer(event.getChunk()); - healer.deserializeNBT(healerTag); - - healer.setLoaded(true); - - ForgeCreeperHeal.getHealerManager((WorldServer) event.getWorld()).getLoadedHealers().put(ChunkPos.asLong(event.getChunk().xPosition, event.getChunk().zPosition), healer); - } - } - } - - - @SubscribeEvent - public void onChunkDataSave(final ChunkDataEvent.Save event) { - if(event.getWorld().isRemote) return; - - final HealerManager manager = ForgeCreeperHeal.getHealerManager((WorldServer) event.getWorld()); - - final Healer healer = manager.getLoadedHealers().get(ChunkPos.asLong(event.getChunk().xPosition, event.getChunk().zPosition)); - - if(healer != null) { - - final NBTTagCompound healerTag = healer.serializeNBT(); - - final NBTTagCompound FCHTag = event.getData().getCompoundTag(FCH_TAG); - FCHTag.setTag(HEALER_TAG, healerTag); - event.getData().setTag(FCH_TAG, FCHTag); - - //If chunk is unloaded, unhandle its healer - if(!healer.isLoaded()) { - manager.getLoadedHealers().remove(ChunkPos.asLong(event.getChunk().xPosition, event.getChunk().zPosition)); - } - } - } - - @SubscribeEvent - public void onChunkUnload(ChunkEvent.Unload event) { - if(event.getWorld().isRemote) return; - final HealerManager manager = ForgeCreeperHeal.getHealerManager((WorldServer)event.getWorld()); - - final Healer healer = manager.getLoadedHealers().get(ChunkPos.asLong(event.getChunk().xPosition, event.getChunk().zPosition)); - if(healer != null) { - healer.setLoaded(false); - } - - } - - @Override - public void register() { - MinecraftForge.EVENT_BUS.register(this); - } +public class ChunkEventHandler implements IEventHandler { + + private static final String FCH_TAG = "FCHTAG"; + private static final String HEALER_TAG = "HEALER"; + + @SubscribeEvent + public void onChunkDataLoad(final ChunkDataEvent.Load event) { + if (event.getWorld().isRemote) return; + + final NBTTagCompound FCHTag = event.getData().getCompoundTag(FCH_TAG); + if (!FCHTag.hasNoTags()) { + final NBTTagCompound healerTag = FCHTag.getCompoundTag(HEALER_TAG); + if (!healerTag.hasNoTags()) { + + final Healer healer = new Healer(event.getChunk()); + healer.deserializeNBT(healerTag); + + healer.setLoaded(true); + + ForgeCreeperHeal.getHealerManager((WorldServer) event.getWorld()).getLoadedHealers().put(ChunkPos.asLong(event.getChunk().xPosition, event.getChunk().zPosition), healer); + } + } + } + + + @SubscribeEvent + public void onChunkDataSave(final ChunkDataEvent.Save event) { + if (event.getWorld().isRemote) return; + + final HealerManager manager = ForgeCreeperHeal.getHealerManager((WorldServer) event.getWorld()); + + final Healer healer = manager.getLoadedHealers().get(ChunkPos.asLong(event.getChunk().xPosition, event.getChunk().zPosition)); + + if (healer != null) { + + final NBTTagCompound healerTag = healer.serializeNBT(); + + final NBTTagCompound FCHTag = event.getData().getCompoundTag(FCH_TAG); + FCHTag.setTag(HEALER_TAG, healerTag); + event.getData().setTag(FCH_TAG, FCHTag); + + //If chunk is unloaded, unhandle its healer + if (!healer.isLoaded()) { + manager.getLoadedHealers().remove(ChunkPos.asLong(event.getChunk().xPosition, event.getChunk().zPosition)); + } + } + } + + @SubscribeEvent + public void onChunkUnload(ChunkEvent.Unload event) { + if (event.getWorld().isRemote) return; + final HealerManager manager = ForgeCreeperHeal.getHealerManager((WorldServer) event.getWorld()); + + final Healer healer = manager.getLoadedHealers().get(ChunkPos.asLong(event.getChunk().xPosition, event.getChunk().zPosition)); + if (healer != null) { + healer.setLoaded(false); + } + + } + + @Override + public void register() { + MinecraftForge.EVENT_BUS.register(this); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/handler/ExplosionEventHandler.java b/src/main/java/fr/eyzox/forgecreeperheal/handler/ExplosionEventHandler.java index e49a395..dc8b82d 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/handler/ExplosionEventHandler.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/handler/ExplosionEventHandler.java @@ -1,12 +1,5 @@ package fr.eyzox.forgecreeperheal.handler; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.Map; -import java.util.Map.Entry; - import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; import fr.eyzox.forgecreeperheal.blockdata.BlockData; import fr.eyzox.forgecreeperheal.builder.blockdata.IBlockDataBuilder; @@ -32,97 +25,103 @@ import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -public class ExplosionEventHandler implements IEventHandler{ - - private static final Field EXPLODER = ReflectionManager.getInstance().getField(Explosion.class, "exploder"); - - - @SubscribeEvent(priority=EventPriority.LOWEST) - public void onDetonate(ExplosionEvent.Detonate event) { - - if(event.getWorld().isRemote) - return; - - final WorldServer world = (WorldServer) event.getWorld(); - - //TODO FromPlayer exception config - - - //Entity Filter : Retrieve which entity make this explosion - Entity exploder = (Entity) ReflectionHelper.get(ExplosionEventHandler.EXPLODER, event.getExplosion()); - //TODO maybe better config - if(exploder == null || ForgeCreeperHeal.getConfig().getSourceException().contains(exploder.getClass().getName())) - return; - - //All filters applied, now begins the real stuff :P - - final Collection affectedBlockData = this.buildBlockDataCollection(world, event.getAffectedBlocks()); - - final Collection toHeal = new ArrayList(affectedBlockData.size()); - for(final BlockData data : affectedBlockData) { - if(!ForgeCreeperHeal.getConfig().getHealException().contains(data.getState().getBlock().getRegistryName().toString())) { - toHeal.add(data); - } - } - - //Process TileEntity - for(final BlockData data : toHeal) { - if(data.getState().getBlock().hasTileEntity(data.getState())) { - TileEntity te = world.getTileEntity(data.getPos()); - if(te != null) { - data.setTileEntity(te); - } - } - } - - final Map>> addToTimeline = ForgeCreeperHeal.getHealerFactory().create(world, new CustomRandomScheduler(toHeal, BlockDataDependencyProvider.getInstance())); - - - final HealerManager manager = ForgeCreeperHeal.getHealerManager((WorldServer) event.getWorld()); - for(final Entry>> entry : addToTimeline.entrySet()) { - Healer healer = manager.load(entry.getKey()); - if(healer == null) { - healer = new Healer(event.getWorld().getChunkFromChunkCoords(entry.getKey().chunkXPos, entry.getKey().chunkZPos)); - } - healer.getTimeline().add(entry.getValue()); - manager.hook(healer); - } - - //Remove future healed block from world to destroy drop appearing after the explosion and avoid item duplication - final WorldRemover remover = new WorldRemover(world); - for(BlockData block : affectedBlockData) { - if(!ForgeCreeperHeal.getConfig().getRemoveException().contains(block.getState().getBlock().getRegistryName().toString())) { - block.remove(remover); - } - } - remover.update(3); - - - - } - - private Collection buildBlockDataCollection(WorldServer world, Collection affectedBlocks) { - - final DefaultFactory blockDataFactory = ForgeCreeperHeal.getBlockDataFactory(); - - final Collection healables = new LinkedList(); - for(final BlockPos pos : affectedBlocks) { - final IBlockState blockstate = world.getBlockState(pos); - - final IBlockDataBuilder builder = blockDataFactory.getData(blockstate.getBlock()); - final BlockData data = builder.create(world, pos, blockstate); - - if(data != null) { - healables.add(data); - } - - } - return healables; - } - - @Override - public void register() { - MinecraftForge.EVENT_BUS.register(this); - } +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.Map; +import java.util.Map.Entry; + +public class ExplosionEventHandler implements IEventHandler { + + private static final Field EXPLODER = ReflectionManager.getInstance().getField(Explosion.class, "exploder"); + + + @SubscribeEvent(priority = EventPriority.LOWEST) + public void onDetonate(ExplosionEvent.Detonate event) { + + if (event.getWorld().isRemote) + return; + + final WorldServer world = (WorldServer) event.getWorld(); + + //TODO FromPlayer exception config + + + //Entity Filter : Retrieve which entity make this explosion + Entity exploder = (Entity) ReflectionHelper.get(ExplosionEventHandler.EXPLODER, event.getExplosion()); + //TODO maybe better config + if (exploder == null || ForgeCreeperHeal.getConfig().getSourceException().contains(exploder.getClass().getName())) + return; + + //All filters applied, now begins the real stuff :P + + final Collection affectedBlockData = this.buildBlockDataCollection(world, event.getAffectedBlocks()); + + final Collection toHeal = new ArrayList(affectedBlockData.size()); + for (final BlockData data : affectedBlockData) { + if (!ForgeCreeperHeal.getConfig().getHealException().contains(data.getState().getBlock().getRegistryName().toString())) { + toHeal.add(data); + } + } + + //Process TileEntity + for (final BlockData data : toHeal) { + if (data.getState().getBlock().hasTileEntity(data.getState())) { + TileEntity te = world.getTileEntity(data.getPos()); + if (te != null) { + data.setTileEntity(te); + } + } + } + + final Map>> addToTimeline = ForgeCreeperHeal.getHealerFactory().create(world, new CustomRandomScheduler(toHeal, BlockDataDependencyProvider.getInstance())); + + + final HealerManager manager = ForgeCreeperHeal.getHealerManager((WorldServer) event.getWorld()); + for (final Entry>> entry : addToTimeline.entrySet()) { + Healer healer = manager.load(entry.getKey()); + if (healer == null) { + healer = new Healer(event.getWorld().getChunkFromChunkCoords(entry.getKey().chunkXPos, entry.getKey().chunkZPos)); + } + healer.getTimeline().add(entry.getValue()); + manager.hook(healer); + } + + //Remove future healed block from world to destroy drop appearing after the explosion and avoid item duplication + final WorldRemover remover = new WorldRemover(world); + for (BlockData block : affectedBlockData) { + if (!ForgeCreeperHeal.getConfig().getRemoveException().contains(block.getState().getBlock().getRegistryName().toString())) { + block.remove(remover); + } + } + remover.update(3); + + + } + + private Collection buildBlockDataCollection(WorldServer world, Collection affectedBlocks) { + + final DefaultFactory blockDataFactory = ForgeCreeperHeal.getBlockDataFactory(); + + final Collection healables = new LinkedList(); + for (final BlockPos pos : affectedBlocks) { + final IBlockState blockstate = world.getBlockState(pos); + + final IBlockDataBuilder builder = blockDataFactory.getData(blockstate.getBlock()); + final BlockData data = builder.create(world, pos, blockstate); + + if (data != null) { + healables.add(data); + } + + } + return healables; + } + + @Override + public void register() { + MinecraftForge.EVENT_BUS.register(this); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/handler/IEventHandler.java b/src/main/java/fr/eyzox/forgecreeperheal/handler/IEventHandler.java index 9d499b5..d7ff5c3 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/handler/IEventHandler.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/handler/IEventHandler.java @@ -1,5 +1,5 @@ package fr.eyzox.forgecreeperheal.handler; public interface IEventHandler { - public void register(); + public void register(); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/handler/PlayerConnectionHandler.java b/src/main/java/fr/eyzox/forgecreeperheal/handler/PlayerConnectionHandler.java index bd633cc..cc64045 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/handler/PlayerConnectionHandler.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/handler/PlayerConnectionHandler.java @@ -6,19 +6,19 @@ import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedOutEvent; -public class PlayerConnectionHandler implements IEventHandler{ +public class PlayerConnectionHandler implements IEventHandler { - @SubscribeEvent - public void onPlayerLeave(PlayerLoggedOutEvent evt) { - if(evt.player instanceof EntityPlayerMP) { - I18n.getInstance().onPlayerLeave((EntityPlayerMP) evt.player); - } - } - - @Override - public void register() { - MinecraftForge.EVENT_BUS.register(this); - } + @SubscribeEvent + public void onPlayerLeave(PlayerLoggedOutEvent evt) { + if (evt.player instanceof EntityPlayerMP) { + I18n.getInstance().onPlayerLeave((EntityPlayerMP) evt.player); + } + } + + @Override + public void register() { + MinecraftForge.EVENT_BUS.register(this); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/handler/WorldEventHandler.java b/src/main/java/fr/eyzox/forgecreeperheal/handler/WorldEventHandler.java index ee9e168..b473961 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/handler/WorldEventHandler.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/handler/WorldEventHandler.java @@ -8,31 +8,31 @@ import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; -public class WorldEventHandler implements IEventHandler{ +public class WorldEventHandler implements IEventHandler { - @SubscribeEvent - public void onWorldLoad(WorldEvent.Load event) { - if(event.getWorld().isRemote) return; + @SubscribeEvent + public void onWorldLoad(WorldEvent.Load event) { + if (event.getWorld().isRemote) return; - final WorldServer world = (WorldServer) event.getWorld(); - ForgeCreeperHeal.getProxy().getHealerManagers().put(world, new HealerManager(world)); + final WorldServer world = (WorldServer) event.getWorld(); + ForgeCreeperHeal.getProxy().getHealerManagers().put(world, new HealerManager(world)); - } + } - @SubscribeEvent - public void onWorldUnload(WorldEvent.Unload event) { - if(event.getWorld().isRemote) return; - ForgeCreeperHeal.getProxy().getHealerManagers().remove((WorldServer) event.getWorld()); - } + @SubscribeEvent + public void onWorldUnload(WorldEvent.Unload event) { + if (event.getWorld().isRemote) return; + ForgeCreeperHeal.getProxy().getHealerManagers().remove((WorldServer) event.getWorld()); + } - @SubscribeEvent - public void onWorldTick(TickEvent.WorldTickEvent event) { - if(event.world.isRemote || event.phase != TickEvent.Phase.START) return; - ForgeCreeperHeal.getHealerManager((WorldServer) event.world).tick(); - } + @SubscribeEvent + public void onWorldTick(TickEvent.WorldTickEvent event) { + if (event.world.isRemote || event.phase != TickEvent.Phase.START) return; + ForgeCreeperHeal.getHealerManager((WorldServer) event.world).tick(); + } - @Override - public void register() { - MinecraftForge.EVENT_BUS.register(this); - } + @Override + public void register() { + MinecraftForge.EVENT_BUS.register(this); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/healer/Healer.java b/src/main/java/fr/eyzox/forgecreeperheal/healer/Healer.java index 40476d8..c5d980c 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/healer/Healer.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/healer/Healer.java @@ -8,65 +8,65 @@ import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.util.INBTSerializable; -public class Healer implements INBTSerializable{ - - private final static String TAG_TIMELINE = "TIMELINE"; - - private final Chunk chunk; - private boolean loaded; - - private TickTimeline timeline; - - public Healer(final Chunk chunk) { - this.chunk = chunk; - this.timeline = new TickTimeline(); - } - - public Healer(final Chunk chunk, final NBTTagCompound tag) { - this.chunk = chunk; - this.deserializeNBT(tag); - } - - public Chunk getChunk() { - return chunk; - } - - public TickTimeline getTimeline() { - return timeline; - } - - public boolean isLoaded() { - return loaded; - } - - public void setLoaded(boolean loaded) { - this.loaded = loaded; - } - - @Override - public String toString() { - return new StringBuilder().append("{[").append(chunk.xPosition).append(", ").append(chunk.zPosition).append("], ").append(timeline.toString()).append(']').toString(); - } - - @Override - public NBTTagCompound serializeNBT() { - - if(timeline == null) { - throw new ForgeCreeperHealException("Unable to serialize : TickTimeline cannot be null"); - } - - final TimelineSerializer timelineSerializer = TimelineSerializer.getInstance(); - - final NBTTagCompound tag = new NBTTagCompound(); - tag.setTag(TAG_TIMELINE, timelineSerializer.serializeNBT(timeline)); - - return tag; - } - - @Override - public void deserializeNBT(NBTTagCompound tag) { - final TimelineSerializer timelineSerializer = TimelineSerializer.getInstance(); - this.timeline = timelineSerializer.deserializeNBT(tag.getCompoundTag(TAG_TIMELINE)); - } - +public class Healer implements INBTSerializable { + + private final static String TAG_TIMELINE = "TIMELINE"; + + private final Chunk chunk; + private boolean loaded; + + private TickTimeline timeline; + + public Healer(final Chunk chunk) { + this.chunk = chunk; + this.timeline = new TickTimeline(); + } + + public Healer(final Chunk chunk, final NBTTagCompound tag) { + this.chunk = chunk; + this.deserializeNBT(tag); + } + + public Chunk getChunk() { + return chunk; + } + + public TickTimeline getTimeline() { + return timeline; + } + + public boolean isLoaded() { + return loaded; + } + + public void setLoaded(boolean loaded) { + this.loaded = loaded; + } + + @Override + public String toString() { + return new StringBuilder().append("{[").append(chunk.xPosition).append(", ").append(chunk.zPosition).append("], ").append(timeline.toString()).append(']').toString(); + } + + @Override + public NBTTagCompound serializeNBT() { + + if (timeline == null) { + throw new ForgeCreeperHealException("Unable to serialize : TickTimeline cannot be null"); + } + + final TimelineSerializer timelineSerializer = TimelineSerializer.getInstance(); + + final NBTTagCompound tag = new NBTTagCompound(); + tag.setTag(TAG_TIMELINE, timelineSerializer.serializeNBT(timeline)); + + return tag; + } + + @Override + public void deserializeNBT(NBTTagCompound tag) { + final TimelineSerializer timelineSerializer = TimelineSerializer.getInstance(); + this.timeline = timelineSerializer.deserializeNBT(tag.getCompoundTag(TAG_TIMELINE)); + } + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/healer/HealerManager.java b/src/main/java/fr/eyzox/forgecreeperheal/healer/HealerManager.java index c816057..068f9d1 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/healer/HealerManager.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/healer/HealerManager.java @@ -1,8 +1,5 @@ package fr.eyzox.forgecreeperheal.healer; -import java.util.Collection; -import java.util.LinkedList; - import fr.eyzox.forgecreeperheal.blockdata.BlockData; import fr.eyzox.forgecreeperheal.handler.WorldEventHandler; import fr.eyzox.ticktimeline.Node; @@ -11,128 +8,134 @@ import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; +import java.util.Collection; +import java.util.LinkedList; + public class HealerManager { - - private final WorldServer world; - private final Long2ObjectOpenHashMap loadedHealers = new Long2ObjectOpenHashMap(); - private final WorldHealerData worldHealerData; - private final WorldHealer worldHealer; - - public HealerManager(final WorldServer world) { - this.world = world; - this.worldHealerData = WorldHealerData.load(world); - this.worldHealer = new WorldHealer(world); - } - - /** - * Loads and puts a new healer for a chunk - * @param chunkKey - * @param timeline - */ - public void hook(final Healer healer) { - final Chunk chunk = world.getChunkFromChunkCoords(healer.getChunk().xPosition, healer.getChunk().zPosition); - final ChunkPos chunkKey = chunk.getPos(); // UNSURE - - healer.setLoaded(true); - - this.loadedHealers.put(ChunkPos.asLong(chunkKey.chunkXPos, chunkKey.chunkZPos), healer); - chunk.setChunkModified(); - this.worldHealerData.handleChunk(chunkKey); - } - - /** - * Loads and removes the healer for a chunk - * @param chunkKey - */ - public void unhook(final ChunkPos chunkKey) { - final Chunk chunk = world.getChunkFromChunkCoords(chunkKey.chunkXPos, chunkKey.chunkZPos); - this.loadedHealers.remove(ChunkPos.asLong(chunk.xPosition, chunk.zPosition)); - chunk.setChunkModified(); - this.worldHealerData.unhandleChunk(chunkKey); - } - - /** - * Loads and gets the healer for a chunk - * @param chunk - * @return - */ - public Healer load(final ChunkPos chunkKey) { - final Chunk chunk = world.getChunkFromChunkCoords(chunkKey.chunkXPos, chunkKey.chunkZPos); - return loadedHealers.get(ChunkPos.asLong(chunk.xPosition, chunk.zPosition)); - } - - /** - * Heals all healer from the world - */ - public void heal() { - healLoaded(); - for(final ChunkPos chunk : this.worldHealerData.getChunksWithHealer()) { - world.getChunkProvider().loadChunk(chunk.chunkXPos, chunk.chunkZPos); - } - healLoaded(); - } - - /** - * Called by {@link WorldEventHandler#onWorldTick(net.minecraftforge.fml.common.gameevent.TickEvent.WorldTickEvent)} - */ - public void tick() { - if(this.loadedHealers.isEmpty()) { - return; - } - - final LinkedList emptyHealers = new LinkedList(); - synchronized(worldHealer) { - for(final Healer healer : loadedHealers.values()) { - - final Collection healables = healer.getTimeline().tick(); - if(healables != null) { - for(BlockData data : healables) { - data.heal(worldHealer); - } - - if(healer.getTimeline().isEmpty()) { - emptyHealers.add(healer); - } - } - - healer.getChunk().setChunkModified(); - - } - worldHealer.update(3); - } - - if(!emptyHealers.isEmpty()) { - for(final Healer emptyHealer : emptyHealers) { - this.unhook(emptyHealer.getChunk().getPos()); // UNSURE - } - } - } - - /** - * Heals only loaded healers - */ - private void healLoaded() { - synchronized (worldHealer) { - for(final Healer healer : loadedHealers.values()) { - for(final Node> node : healer.getTimeline().getTimeline()) { - for(BlockData data : node.getData()) { - data.heal(worldHealer); - } - } - this.worldHealerData.unhandleChunk(healer.getChunk().getPos()); // UNSURE - } - worldHealer.update(3); - } - this.loadedHealers.clear(); - this.loadedHealers.trim(); - } - - public WorldServer getWorld() { - return world; - } - - public Long2ObjectOpenHashMap getLoadedHealers() { - return loadedHealers; - } + + private final WorldServer world; + private final Long2ObjectOpenHashMap loadedHealers = new Long2ObjectOpenHashMap(); + private final WorldHealerData worldHealerData; + private final WorldHealer worldHealer; + + public HealerManager(final WorldServer world) { + this.world = world; + this.worldHealerData = WorldHealerData.load(world); + this.worldHealer = new WorldHealer(world); + } + + /** + * Loads and puts a new healer for a chunk + * + * @param chunkKey + * @param timeline + */ + public void hook(final Healer healer) { + final Chunk chunk = world.getChunkFromChunkCoords(healer.getChunk().xPosition, healer.getChunk().zPosition); + final ChunkPos chunkKey = chunk.getPos(); // UNSURE + + healer.setLoaded(true); + + this.loadedHealers.put(ChunkPos.asLong(chunkKey.chunkXPos, chunkKey.chunkZPos), healer); + chunk.setChunkModified(); + this.worldHealerData.handleChunk(chunkKey); + } + + /** + * Loads and removes the healer for a chunk + * + * @param chunkKey + */ + public void unhook(final ChunkPos chunkKey) { + final Chunk chunk = world.getChunkFromChunkCoords(chunkKey.chunkXPos, chunkKey.chunkZPos); + this.loadedHealers.remove(ChunkPos.asLong(chunk.xPosition, chunk.zPosition)); + chunk.setChunkModified(); + this.worldHealerData.unhandleChunk(chunkKey); + } + + /** + * Loads and gets the healer for a chunk + * + * @param chunk + * @return + */ + public Healer load(final ChunkPos chunkKey) { + final Chunk chunk = world.getChunkFromChunkCoords(chunkKey.chunkXPos, chunkKey.chunkZPos); + return loadedHealers.get(ChunkPos.asLong(chunk.xPosition, chunk.zPosition)); + } + + /** + * Heals all healer from the world + */ + public void heal() { + healLoaded(); + for (final ChunkPos chunk : this.worldHealerData.getChunksWithHealer()) { + world.getChunkProvider().loadChunk(chunk.chunkXPos, chunk.chunkZPos); + } + healLoaded(); + } + + /** + * Called by {@link WorldEventHandler#onWorldTick(net.minecraftforge.fml.common.gameevent.TickEvent.WorldTickEvent)} + */ + public void tick() { + if (this.loadedHealers.isEmpty()) { + return; + } + + final LinkedList emptyHealers = new LinkedList(); + synchronized (worldHealer) { + for (final Healer healer : loadedHealers.values()) { + + final Collection healables = healer.getTimeline().tick(); + if (healables != null) { + for (BlockData data : healables) { + data.heal(worldHealer); + } + + if (healer.getTimeline().isEmpty()) { + emptyHealers.add(healer); + } + } + + healer.getChunk().setChunkModified(); + + } + worldHealer.update(3); + } + + if (!emptyHealers.isEmpty()) { + for (final Healer emptyHealer : emptyHealers) { + this.unhook(emptyHealer.getChunk().getPos()); // UNSURE + } + } + } + + /** + * Heals only loaded healers + */ + private void healLoaded() { + synchronized (worldHealer) { + for (final Healer healer : loadedHealers.values()) { + for (final Node> node : healer.getTimeline().getTimeline()) { + for (BlockData data : node.getData()) { + data.heal(worldHealer); + } + } + this.worldHealerData.unhandleChunk(healer.getChunk().getPos()); // UNSURE + } + worldHealer.update(3); + } + this.loadedHealers.clear(); + this.loadedHealers.trim(); + } + + public WorldServer getWorld() { + return world; + } + + public Long2ObjectOpenHashMap getLoadedHealers() { + return loadedHealers; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/healer/HealerUtils.java b/src/main/java/fr/eyzox/forgecreeperheal/healer/HealerUtils.java index 66b1109..f98f600 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/healer/HealerUtils.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/healer/HealerUtils.java @@ -7,10 +7,10 @@ public class HealerUtils { - private HealerUtils() { - } - - public static void spawnItemStack(World worldIn, BlockPos pos, ItemStack stack) { - InventoryHelper.spawnItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), stack); - } + private HealerUtils() { + } + + public static void spawnItemStack(World worldIn, BlockPos pos, ItemStack stack) { + InventoryHelper.spawnItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), stack); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/healer/IChunked.java b/src/main/java/fr/eyzox/forgecreeperheal/healer/IChunked.java index a8cd421..008d4e0 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/healer/IChunked.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/healer/IChunked.java @@ -1,6 +1,7 @@ package fr.eyzox.forgecreeperheal.healer; public interface IChunked { - public int getChunkX(); - public int getChunkZ(); + public int getChunkX(); + + public int getChunkZ(); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/healer/IHealable.java b/src/main/java/fr/eyzox/forgecreeperheal/healer/IHealable.java index eb043d7..9c6bf81 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/healer/IHealable.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/healer/IHealable.java @@ -1,5 +1,5 @@ package fr.eyzox.forgecreeperheal.healer; public interface IHealable { - void heal(WorldHealer worldHealer); + void heal(WorldHealer worldHealer); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/healer/IRemovable.java b/src/main/java/fr/eyzox/forgecreeperheal/healer/IRemovable.java index c047ccb..8bf83e1 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/healer/IRemovable.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/healer/IRemovable.java @@ -1,5 +1,5 @@ package fr.eyzox.forgecreeperheal.healer; public interface IRemovable { - public void remove(final WorldRemover remover); + public void remove(final WorldRemover remover); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldHealer.java b/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldHealer.java index 335f490..bfe9662 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldHealer.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldHealer.java @@ -1,9 +1,5 @@ package fr.eyzox.forgecreeperheal.healer; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; import net.minecraft.block.state.IBlockState; import net.minecraft.inventory.IInventory; @@ -15,77 +11,81 @@ import net.minecraft.world.World; import net.minecraftforge.fluids.FluidRegistry; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + public class WorldHealer { - private final World world; - private final Map toUpdate = new LinkedHashMap(); - - public WorldHealer(final World w) { - this.world = w; - } - - public void heal(BlockPos pos, IBlockState newState, NBTTagCompound tileEntity) { - final IBlockState currentBlockState = world.getBlockState(pos); - final boolean isAir = currentBlockState.getBlock().isAir(currentBlockState, world, pos); - - //If current block = air or overriding - if(ForgeCreeperHeal.getConfig().isOverrideBlock() || isAir || (ForgeCreeperHeal.getConfig().isOverrideFluid() && FluidRegistry.lookupFluidForBlock(currentBlockState.getBlock()) != null)) { - - //IF overriding a block : Drop current block & if this block's TileEntity is an IInventory, drop all Items contained - if(ForgeCreeperHeal.getConfig().isDropIfCollision() && !isAir) { - HealerUtils.spawnItemStack(world, pos, new ItemStack(currentBlockState.getBlock())); - TileEntity te = world.getTileEntity(pos); - if(te instanceof IInventory) { - InventoryHelper.dropInventoryItems(world, pos, (IInventory) te); - } - } - - //Restore Block, then its TileEntity - world.setBlockState(pos, newState, 0); - this.markForUpdate(pos, currentBlockState); - if(tileEntity != null) { - TileEntity te = world.getTileEntity(pos); - if(te != null) { - te.readFromNBT(tileEntity); - world.setTileEntity(pos, te); - }else { - ForgeCreeperHeal.getLogger().warn(String.format("Unable to restore a TileEntity \"%s\" because restored blockstate \"%s\", doesn't have TileEntity", tileEntity, newState)); - } - } - - } - // (( If current block != air and no overriding )) & drop if collision - else if(ForgeCreeperHeal.getConfig().isDropIfCollision()){ - //Drop the block which should have been restored & if its TileEntity = IInventory, drop items contained - HealerUtils.spawnItemStack(world, pos, new ItemStack(newState.getBlock())); - if(tileEntity != null) { - TileEntity te = newState.getBlock().createTileEntity(world, newState); - if(te instanceof IInventory) { - te.readFromNBT(tileEntity); - InventoryHelper.dropInventoryItems(world, pos, (IInventory) te); - } - } - - } - } - - public void markForUpdate(BlockPos pos, IBlockState oldState) { - toUpdate.put(pos, oldState); - } - - public void update(int flags) { - if(toUpdate.isEmpty()) return; - - for(Entry entry : toUpdate.entrySet()) { - final BlockPos pos = entry.getKey(); - world.markAndNotifyBlock(pos,world.getChunkFromBlockCoords(pos), entry.getValue(), world.getBlockState(pos), flags); - } - - toUpdate.clear(); - } - - public World getWorld() { - return world; - } + private final World world; + private final Map toUpdate = new LinkedHashMap(); + + public WorldHealer(final World w) { + this.world = w; + } + + public void heal(BlockPos pos, IBlockState newState, NBTTagCompound tileEntity) { + final IBlockState currentBlockState = world.getBlockState(pos); + final boolean isAir = currentBlockState.getBlock().isAir(currentBlockState, world, pos); + + //If current block = air or overriding + if (ForgeCreeperHeal.getConfig().isOverrideBlock() || isAir || (ForgeCreeperHeal.getConfig().isOverrideFluid() && FluidRegistry.lookupFluidForBlock(currentBlockState.getBlock()) != null)) { + + //IF overriding a block : Drop current block & if this block's TileEntity is an IInventory, drop all Items contained + if (ForgeCreeperHeal.getConfig().isDropIfCollision() && !isAir) { + HealerUtils.spawnItemStack(world, pos, new ItemStack(currentBlockState.getBlock())); + TileEntity te = world.getTileEntity(pos); + if (te instanceof IInventory) { + InventoryHelper.dropInventoryItems(world, pos, (IInventory) te); + } + } + + //Restore Block, then its TileEntity + world.setBlockState(pos, newState, 0); + this.markForUpdate(pos, currentBlockState); + if (tileEntity != null) { + TileEntity te = world.getTileEntity(pos); + if (te != null) { + te.readFromNBT(tileEntity); + world.setTileEntity(pos, te); + } else { + ForgeCreeperHeal.getLogger().warn(String.format("Unable to restore a TileEntity \"%s\" because restored blockstate \"%s\", doesn't have TileEntity", tileEntity, newState)); + } + } + + } + // (( If current block != air and no overriding )) & drop if collision + else if (ForgeCreeperHeal.getConfig().isDropIfCollision()) { + //Drop the block which should have been restored & if its TileEntity = IInventory, drop items contained + HealerUtils.spawnItemStack(world, pos, new ItemStack(newState.getBlock())); + if (tileEntity != null) { + TileEntity te = newState.getBlock().createTileEntity(world, newState); + if (te instanceof IInventory) { + te.readFromNBT(tileEntity); + InventoryHelper.dropInventoryItems(world, pos, (IInventory) te); + } + } + + } + } + + public void markForUpdate(BlockPos pos, IBlockState oldState) { + toUpdate.put(pos, oldState); + } + + public void update(int flags) { + if (toUpdate.isEmpty()) return; + + for (Entry entry : toUpdate.entrySet()) { + final BlockPos pos = entry.getKey(); + world.markAndNotifyBlock(pos, world.getChunkFromBlockCoords(pos), entry.getValue(), world.getBlockState(pos), flags); + } + + toUpdate.clear(); + } + + public World getWorld() { + return world; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldHealerData.java b/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldHealerData.java index 9aee1a1..6d58c23 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldHealerData.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldHealerData.java @@ -1,8 +1,5 @@ package fr.eyzox.forgecreeperheal.healer; -import java.util.HashSet; -import java.util.Set; - import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagIntArray; @@ -13,68 +10,71 @@ import net.minecraft.world.storage.MapStorage; import net.minecraftforge.common.util.Constants.NBT; +import java.util.HashSet; +import java.util.Set; + public class WorldHealerData extends WorldSavedData { - public static final String KEY = ForgeCreeperHeal.MODID+":WHD"; - - private final static String CHUNKS_WITH_HEALER_TAG = "chunks"; - - private final Set chunksWithHealer = new HashSet(); - - public WorldHealerData(String name) { - super(name); - } - - public void handleChunk(final ChunkPos chunk) { - if(this.chunksWithHealer.add(chunk)) { - this.markDirty(); - } - } - - public void unhandleChunk(final ChunkPos chunk) { - if(this.chunksWithHealer.remove(chunk)) { - this.markDirty(); - } - } - - public Set getChunksWithHealer() { - return chunksWithHealer; - } - - @Override - public void readFromNBT(NBTTagCompound nbt) { - NBTTagList chunksTagList = nbt.getTagList(CHUNKS_WITH_HEALER_TAG, NBT.TAG_INT_ARRAY); - for(int i = 0 ; i < chunksTagList.tagCount(); i++) { - final int[] array = chunksTagList.getIntArrayAt(i); - if(array.length >= 2) { - chunksWithHealer.add(new ChunkPos(array[0], array[1])); - }else { - ForgeCreeperHeal.getLogger().error("Ignoring a chunk with healer (array length < 2)"); - } - } - - - } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - NBTTagList chunksTagList = new NBTTagList(); - for(final ChunkPos chunk : chunksWithHealer) { - chunksTagList.appendTag(new NBTTagIntArray(new int[]{chunk.chunkXPos, chunk.chunkZPos})); - } - nbt.setTag(CHUNKS_WITH_HEALER_TAG, chunksTagList); - return nbt; - - } - - public static WorldHealerData load(WorldServer w) { - MapStorage storage = w.getPerWorldStorage(); - WorldHealerData result = (WorldHealerData)storage.getOrLoadData(WorldHealerData.class, KEY); - if(result == null) { - result = new WorldHealerData(KEY); - storage.setData(KEY, result); - } - return result; - } + public static final String KEY = ForgeCreeperHeal.MODID + ":WHD"; + + private final static String CHUNKS_WITH_HEALER_TAG = "chunks"; + + private final Set chunksWithHealer = new HashSet(); + + public WorldHealerData(String name) { + super(name); + } + + public static WorldHealerData load(WorldServer w) { + MapStorage storage = w.getPerWorldStorage(); + WorldHealerData result = (WorldHealerData) storage.getOrLoadData(WorldHealerData.class, KEY); + if (result == null) { + result = new WorldHealerData(KEY); + storage.setData(KEY, result); + } + return result; + } + + public void handleChunk(final ChunkPos chunk) { + if (this.chunksWithHealer.add(chunk)) { + this.markDirty(); + } + } + + public void unhandleChunk(final ChunkPos chunk) { + if (this.chunksWithHealer.remove(chunk)) { + this.markDirty(); + } + } + + public Set getChunksWithHealer() { + return chunksWithHealer; + } + + @Override + public void readFromNBT(NBTTagCompound nbt) { + NBTTagList chunksTagList = nbt.getTagList(CHUNKS_WITH_HEALER_TAG, NBT.TAG_INT_ARRAY); + for (int i = 0; i < chunksTagList.tagCount(); i++) { + final int[] array = chunksTagList.getIntArrayAt(i); + if (array.length >= 2) { + chunksWithHealer.add(new ChunkPos(array[0], array[1])); + } else { + ForgeCreeperHeal.getLogger().error("Ignoring a chunk with healer (array length < 2)"); + } + } + + + } + + @Override + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + NBTTagList chunksTagList = new NBTTagList(); + for (final ChunkPos chunk : chunksWithHealer) { + chunksTagList.appendTag(new NBTTagIntArray(new int[]{chunk.chunkXPos, chunk.chunkZPos})); + } + nbt.setTag(CHUNKS_WITH_HEALER_TAG, chunksTagList); + return nbt; + + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldRemover.java b/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldRemover.java index 66e04a8..30d8615 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldRemover.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/healer/WorldRemover.java @@ -1,9 +1,5 @@ package fr.eyzox.forgecreeperheal.healer; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; import fr.eyzox.forgecreeperheal.reflection.transform.WorldTransform; import net.minecraft.block.state.IBlockState; @@ -14,44 +10,48 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + public class WorldRemover { - private final World world; - private final WorldTransform worldTransform; - private final Map oldStates = new HashMap(); - - public WorldRemover(final World world) { - this.world = world; - this.worldTransform = new WorldTransform(world); - } - - public void remove(final BlockPos pos) { - - IBlockState oldState = world.getBlockState(pos); - - if(oldState.getBlock().hasTileEntity(oldState)) { - TileEntity te = world.getTileEntity(pos); - if(te != null) { - this.onTileEntityRemoved(te); - } - } - - this.oldStates.put(pos, oldState); - this.worldTransform.removeSilentBlockState(pos, 0); - world.removeTileEntity(pos); - } - - public void update(final int flags) { - for(final Entry entry : oldStates.entrySet()) { - this.world.markAndNotifyBlock(entry.getKey(), world.getChunkFromBlockCoords(entry.getKey()), entry.getValue(), Blocks.AIR.getDefaultState(), flags); - } - oldStates.clear(); - } - - private void onTileEntityRemoved(TileEntity tileEntity) { - if(ForgeCreeperHeal.getConfig().isDropItems() && tileEntity instanceof IInventory) { - InventoryHelper.dropInventoryItems(tileEntity.getWorld(), tileEntity.getPos(), (IInventory) tileEntity); - } - } - + private final World world; + private final WorldTransform worldTransform; + private final Map oldStates = new HashMap(); + + public WorldRemover(final World world) { + this.world = world; + this.worldTransform = new WorldTransform(world); + } + + public void remove(final BlockPos pos) { + + IBlockState oldState = world.getBlockState(pos); + + if (oldState.getBlock().hasTileEntity(oldState)) { + TileEntity te = world.getTileEntity(pos); + if (te != null) { + this.onTileEntityRemoved(te); + } + } + + this.oldStates.put(pos, oldState); + this.worldTransform.removeSilentBlockState(pos, 0); + world.removeTileEntity(pos); + } + + public void update(final int flags) { + for (final Entry entry : oldStates.entrySet()) { + this.world.markAndNotifyBlock(entry.getKey(), world.getChunkFromBlockCoords(entry.getKey()), entry.getValue(), Blocks.AIR.getDefaultState(), flags); + } + oldStates.clear(); + } + + private void onTileEntityRemoved(TileEntity tileEntity) { + if (ForgeCreeperHeal.getConfig().isDropItems() && tileEntity instanceof IInventory) { + InventoryHelper.dropInventoryItems(tileEntity.getWorld(), tileEntity.getPos(), (IInventory) tileEntity); + } + } + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/i18n/I18n.java b/src/main/java/fr/eyzox/forgecreeperheal/i18n/I18n.java index 01acf5b..eb83a4e 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/i18n/I18n.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/i18n/I18n.java @@ -1,59 +1,60 @@ package fr.eyzox.forgecreeperheal.i18n; -import java.lang.reflect.Field; - import fr.eyzox.forgecreeperheal.reflection.ReflectionHelper; import fr.eyzox.forgecreeperheal.reflection.ReflectionManager; import net.minecraft.entity.player.EntityPlayerMP; +import java.lang.reflect.Field; + public final class I18n { - - private final static Field PLAYER_LOCALE = ReflectionManager.getInstance().getField(EntityPlayerMP.class, "language"); - - private static final I18n INSTANCE = new I18n(); - - private final static String DEFAULT_LOCALE = "en_US"; - - private final LocaleMap localeMap = new LocaleMap(); - private LanguageMap defaultLanguage= LanguageMap.getFromLocale(DEFAULT_LOCALE); - - - private I18n() { - } - - public synchronized String translate(String key, Object[] o) { - return this.translate((EntityPlayerMP)null, key, o); - } - - public synchronized String translate(EntityPlayerMP player, String key, Object[] o) { - LanguageMap dico = defaultLanguage; - String playerLocale = (String) ReflectionHelper.get(PLAYER_LOCALE, player); - if(!defaultLanguage.getLocale().equals(playerLocale)) { - LanguageMap sharedDico = localeMap.getLocalFor(player, playerLocale); - if(sharedDico != null) { - dico = sharedDico; - } - } - - return dico == null ? key : dico.translate(key, o); - } - - public synchronized void onPlayerLeave(EntityPlayerMP player) { - final String playerLocale = (String) ReflectionHelper.get(PLAYER_LOCALE, player); - if(!defaultLanguage.getLocale().equals(playerLocale)) { - localeMap.onPlayerLeave(player); - } - - } - - public synchronized void setDefaultLocale(String locale) { - this.defaultLanguage = localeMap.remove(locale); - if(defaultLanguage == null) { - defaultLanguage = LanguageMap.getFromLocale(locale); - } - } - - - public static final I18n getInstance() { return INSTANCE;} - + + private final static Field PLAYER_LOCALE = ReflectionManager.getInstance().getField(EntityPlayerMP.class, "language"); + + private static final I18n INSTANCE = new I18n(); + + private final static String DEFAULT_LOCALE = "en_US"; + + private final LocaleMap localeMap = new LocaleMap(); + private LanguageMap defaultLanguage = LanguageMap.getFromLocale(DEFAULT_LOCALE); + + + private I18n() { + } + + public static final I18n getInstance() { + return INSTANCE; + } + + public synchronized String translate(String key, Object[] o) { + return this.translate((EntityPlayerMP) null, key, o); + } + + public synchronized String translate(EntityPlayerMP player, String key, Object[] o) { + LanguageMap dico = defaultLanguage; + String playerLocale = (String) ReflectionHelper.get(PLAYER_LOCALE, player); + if (!defaultLanguage.getLocale().equals(playerLocale)) { + LanguageMap sharedDico = localeMap.getLocalFor(player, playerLocale); + if (sharedDico != null) { + dico = sharedDico; + } + } + + return dico == null ? key : dico.translate(key, o); + } + + public synchronized void onPlayerLeave(EntityPlayerMP player) { + final String playerLocale = (String) ReflectionHelper.get(PLAYER_LOCALE, player); + if (!defaultLanguage.getLocale().equals(playerLocale)) { + localeMap.onPlayerLeave(player); + } + + } + + public synchronized void setDefaultLocale(String locale) { + this.defaultLanguage = localeMap.remove(locale); + if (defaultLanguage == null) { + defaultLanguage = LanguageMap.getFromLocale(locale); + } + } + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/i18n/LanguageMap.java b/src/main/java/fr/eyzox/forgecreeperheal/i18n/LanguageMap.java index add9116..2dee426 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/i18n/LanguageMap.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/i18n/LanguageMap.java @@ -1,51 +1,54 @@ package fr.eyzox.forgecreeperheal.i18n; +import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; +import net.minecraft.entity.player.EntityPlayerMP; + import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.Map; import java.util.Set; -import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; -import net.minecraft.entity.player.EntityPlayerMP; - class LanguageMap { - - private final String locale; - private final Map dico; - private final Set usedBy = new HashSet(); - - private LanguageMap(InputStream is, String locale) { - this.dico = net.minecraft.util.text.translation.LanguageMap.parseLangFile(is); - this.locale = locale; - } - - public String translate(String key, Object[] o) { - final String translated = dico.get(key); - return translated == null ? key : (o == null ? translated : String.format(translated, o)); - } - - public String getLocale() { - return locale; - } - - protected Set getUsedBy() { - return usedBy; - } - - public static LanguageMap getFromLocale(String locale) { - InputStream is = null; - LanguageMap dico = null; - try { - is = net.minecraft.util.text.translation.LanguageMap.class.getResourceAsStream("/assets/"+ForgeCreeperHeal.MODID+"/lang/"+locale+".lang"); - if(is != null) { - dico = new LanguageMap(is, locale); - } - }finally { - if(is != null) { - try {is.close();} catch (IOException e1) {} - } - } - return dico; - } + + private final String locale; + private final Map dico; + private final Set usedBy = new HashSet(); + + private LanguageMap(InputStream is, String locale) { + this.dico = net.minecraft.util.text.translation.LanguageMap.parseLangFile(is); + this.locale = locale; + } + + public static LanguageMap getFromLocale(String locale) { + InputStream is = null; + LanguageMap dico = null; + try { + is = net.minecraft.util.text.translation.LanguageMap.class.getResourceAsStream("/assets/" + ForgeCreeperHeal.MODID + "/lang/" + locale + ".lang"); + if (is != null) { + dico = new LanguageMap(is, locale); + } + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException e1) { + } + } + } + return dico; + } + + public String translate(String key, Object[] o) { + final String translated = dico.get(key); + return translated == null ? key : (o == null ? translated : String.format(translated, o)); + } + + public String getLocale() { + return locale; + } + + protected Set getUsedBy() { + return usedBy; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/i18n/LocaleMap.java b/src/main/java/fr/eyzox/forgecreeperheal/i18n/LocaleMap.java index c35f5ae..481bf20 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/i18n/LocaleMap.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/i18n/LocaleMap.java @@ -1,71 +1,71 @@ package fr.eyzox.forgecreeperheal.i18n; +import net.minecraft.entity.player.EntityPlayerMP; + import java.util.HashMap; import java.util.Map; -import net.minecraft.entity.player.EntityPlayerMP; - class LocaleMap { - - private final Map cachedLocales = new HashMap(); - private final Map cachedPlayerLocales = new HashMap(); - - protected LocaleMap() { - } - - public synchronized LanguageMap getLocalFor(EntityPlayerMP player, String locale) { - LanguageMap playerLocale = cachedPlayerLocales.get(player); - if(playerLocale != null) { - if(locale.equals(playerLocale.getLocale())) { - return playerLocale; - } - unregister(player, playerLocale); - } - - playerLocale = cachedLocales.get(locale); - if(playerLocale == null) { - playerLocale = LanguageMap.getFromLocale(locale); - if(playerLocale != null) { - cachedLocales.put(locale, playerLocale); - } - } - - if(playerLocale != null) { - register(player, playerLocale); - } - - return playerLocale; - } - - public void onPlayerLeave(EntityPlayerMP player) { - LanguageMap playerLocale = cachedPlayerLocales.get(player); - if(playerLocale != null) { - unregister(player, playerLocale); - } - } - - private void unregister(EntityPlayerMP player, LanguageMap playerLocale) { - playerLocale.getUsedBy().remove(player); - if(playerLocale.getUsedBy().isEmpty()) { - cachedLocales.remove(playerLocale.getLocale()); - } - } - - private void register(EntityPlayerMP player, LanguageMap playerLocale) { - playerLocale.getUsedBy().add(player); - cachedPlayerLocales.put(player, playerLocale); - } - - protected LanguageMap remove(String locale) { - LanguageMap dico = cachedLocales.get(locale); - if(dico != null) { - for(EntityPlayerMP player : dico.getUsedBy()) { - cachedPlayerLocales.remove(player); - } - dico.getUsedBy().clear(); - } - return dico; - } - + private final Map cachedLocales = new HashMap(); + private final Map cachedPlayerLocales = new HashMap(); + + protected LocaleMap() { + } + + public synchronized LanguageMap getLocalFor(EntityPlayerMP player, String locale) { + LanguageMap playerLocale = cachedPlayerLocales.get(player); + if (playerLocale != null) { + if (locale.equals(playerLocale.getLocale())) { + return playerLocale; + } + unregister(player, playerLocale); + } + + playerLocale = cachedLocales.get(locale); + if (playerLocale == null) { + playerLocale = LanguageMap.getFromLocale(locale); + if (playerLocale != null) { + cachedLocales.put(locale, playerLocale); + } + } + + if (playerLocale != null) { + register(player, playerLocale); + } + + return playerLocale; + + } + + public void onPlayerLeave(EntityPlayerMP player) { + LanguageMap playerLocale = cachedPlayerLocales.get(player); + if (playerLocale != null) { + unregister(player, playerLocale); + } + } + + private void unregister(EntityPlayerMP player, LanguageMap playerLocale) { + playerLocale.getUsedBy().remove(player); + if (playerLocale.getUsedBy().isEmpty()) { + cachedLocales.remove(playerLocale.getLocale()); + } + } + + private void register(EntityPlayerMP player, LanguageMap playerLocale) { + playerLocale.getUsedBy().add(player); + cachedPlayerLocales.put(player, playerLocale); + } + + protected LanguageMap remove(String locale) { + LanguageMap dico = cachedLocales.get(locale); + if (dico != null) { + for (EntityPlayerMP player : dico.getUsedBy()) { + cachedPlayerLocales.remove(player); + } + dico.getUsedBy().clear(); + } + return dico; + } + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/i18n/TextComponentTranslationServer.java b/src/main/java/fr/eyzox/forgecreeperheal/i18n/TextComponentTranslationServer.java index fe967df..a9e343a 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/i18n/TextComponentTranslationServer.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/i18n/TextComponentTranslationServer.java @@ -5,12 +5,12 @@ public class TextComponentTranslationServer extends TextComponentString { - public TextComponentTranslationServer(EntityPlayerMP player, String key) { - this(player, key, null); - } - - public TextComponentTranslationServer(EntityPlayerMP player, String key, Object[] o) { - super(I18n.getInstance().translate(player, key, o)); - } + public TextComponentTranslationServer(EntityPlayerMP player, String key) { + this(player, key, null); + } + + public TextComponentTranslationServer(EntityPlayerMP player, String key, Object[] o) { + super(I18n.getInstance().translate(player, key, o)); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/proxy/ClientProxy.java b/src/main/java/fr/eyzox/forgecreeperheal/proxy/ClientProxy.java index 38a5eb1..3513ac3 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/proxy/ClientProxy.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/proxy/ClientProxy.java @@ -4,18 +4,18 @@ public class ClientProxy extends CommonProxy { - //private ProfilerRenderEventHandler profilerRenderEventHandler; - - @Override - public void onInit(FMLInitializationEvent event) { - super.onInit(event); - //profilerRenderEventHandler = new ProfilerRenderEventHandler(); - //MinecraftForge.EVENT_BUS.register(new PlayerModDataHandler()); - //MinecraftForge.EVENT_BUS.register(profilerRenderEventHandler); - } + //private ProfilerRenderEventHandler profilerRenderEventHandler; + + @Override + public void onInit(FMLInitializationEvent event) { + super.onInit(event); + //profilerRenderEventHandler = new ProfilerRenderEventHandler(); + //MinecraftForge.EVENT_BUS.register(new PlayerModDataHandler()); + //MinecraftForge.EVENT_BUS.register(profilerRenderEventHandler); + } /* - public ProfilerRenderEventHandler getProfilerRenderEventHandler() { + public ProfilerRenderEventHandler getProfilerRenderEventHandler() { return profilerRenderEventHandler; } */ diff --git a/src/main/java/fr/eyzox/forgecreeperheal/proxy/CommonProxy.java b/src/main/java/fr/eyzox/forgecreeperheal/proxy/CommonProxy.java index 9ac4306..e757b3b 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/proxy/CommonProxy.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/proxy/CommonProxy.java @@ -1,35 +1,11 @@ package fr.eyzox.forgecreeperheal.proxy; -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -import org.apache.logging.log4j.Logger; - import fr.eyzox.bsc.config.IConfigProvider; import fr.eyzox.bsc.config.loader.JSONConfigLoader; import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; -import fr.eyzox.forgecreeperheal.builder.blockdata.BedBlockDataBuilder; -import fr.eyzox.forgecreeperheal.builder.blockdata.DefaultBlockDataBuilder; -import fr.eyzox.forgecreeperheal.builder.blockdata.DoorBlockDataBuilder; -import fr.eyzox.forgecreeperheal.builder.blockdata.IBlockDataBuilder; -import fr.eyzox.forgecreeperheal.builder.blockdata.PistonBlockDataBuilder; -import fr.eyzox.forgecreeperheal.builder.dependency.AbstractGenericDependencyBuilder; -import fr.eyzox.forgecreeperheal.builder.dependency.FacingDependencyBuilder; -import fr.eyzox.forgecreeperheal.builder.dependency.IDependencyBuilder; -import fr.eyzox.forgecreeperheal.builder.dependency.LeverDependencyBuilder; -import fr.eyzox.forgecreeperheal.builder.dependency.NoDependencyBuilder; -import fr.eyzox.forgecreeperheal.builder.dependency.OppositeFacingDependencyBuilder; -import fr.eyzox.forgecreeperheal.builder.dependency.SupportByBottomDependencyBuilder; -import fr.eyzox.forgecreeperheal.builder.dependency.VineDependencyBuilder; -import fr.eyzox.forgecreeperheal.builder.dependency.property.BannerHangingPropertySelector; -import fr.eyzox.forgecreeperheal.builder.dependency.property.ButtonPropertySelector; -import fr.eyzox.forgecreeperheal.builder.dependency.property.CocoaPropertySelector; -import fr.eyzox.forgecreeperheal.builder.dependency.property.LadderPropertySelector; -import fr.eyzox.forgecreeperheal.builder.dependency.property.TorchPropertySelector; -import fr.eyzox.forgecreeperheal.builder.dependency.property.TrapDoorPropertySelector; -import fr.eyzox.forgecreeperheal.builder.dependency.property.TripWireHookPropertySelector; -import fr.eyzox.forgecreeperheal.builder.dependency.property.WallSignPropertySelector; +import fr.eyzox.forgecreeperheal.builder.blockdata.*; +import fr.eyzox.forgecreeperheal.builder.dependency.*; +import fr.eyzox.forgecreeperheal.builder.dependency.property.*; import fr.eyzox.forgecreeperheal.commands.ForgeCreeperHealCommands; import fr.eyzox.forgecreeperheal.config.ConfigProvider; import fr.eyzox.forgecreeperheal.config.FastConfig; @@ -41,205 +17,183 @@ import fr.eyzox.forgecreeperheal.handler.WorldEventHandler; import fr.eyzox.forgecreeperheal.healer.HealerManager; import fr.eyzox.forgecreeperheal.scheduler.TickTimelineFactory; -import net.minecraft.block.Block; +import net.minecraft.block.*; import net.minecraft.block.BlockBanner.BlockBannerHanging; import net.minecraft.block.BlockBanner.BlockBannerStanding; -import net.minecraft.block.BlockBasePressurePlate; -import net.minecraft.block.BlockButton; -import net.minecraft.block.BlockCactus; -import net.minecraft.block.BlockCake; -import net.minecraft.block.BlockCarpet; -import net.minecraft.block.BlockCocoa; -import net.minecraft.block.BlockCrops; -import net.minecraft.block.BlockDoor; -import net.minecraft.block.BlockDragonEgg; -import net.minecraft.block.BlockFalling; -import net.minecraft.block.BlockFlowerPot; -import net.minecraft.block.BlockGrass; -import net.minecraft.block.BlockLadder; -import net.minecraft.block.BlockRailBase; -import net.minecraft.block.BlockRedstoneDiode; -import net.minecraft.block.BlockRedstoneWire; -import net.minecraft.block.BlockReed; -import net.minecraft.block.BlockSnow; -import net.minecraft.block.BlockStandingSign; -import net.minecraft.block.BlockTallGrass; -import net.minecraft.block.BlockTorch; -import net.minecraft.block.BlockTrapDoor; -import net.minecraft.block.BlockTripWire; -import net.minecraft.block.BlockTripWireHook; -import net.minecraft.block.BlockWallSign; import net.minecraft.world.WorldServer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; +import org.apache.logging.log4j.Logger; -public class CommonProxy { - - private Logger logger; - - private ConfigProvider configProvider; - private FastConfig config; - //private SimpleNetworkWrapper channel; - - private TickTimelineFactory healerFactory; - private Map healerManagers; +import java.io.File; +import java.util.HashMap; +import java.util.Map; - private DefaultFactory blockDataFactory; - private DefaultFactory dependencyFactory; +public class CommonProxy { - private ChunkEventHandler chunkEventHandler; - private ExplosionEventHandler explosionEventHandler; - private WorldEventHandler worldTickEventHandler; - private PlayerConnectionHandler playerConnectionHandler; + private Logger logger; + private ConfigProvider configProvider; + private FastConfig config; + //private SimpleNetworkWrapper channel; + private TickTimelineFactory healerFactory; + private Map healerManagers; - public void onPreInit(FMLPreInitializationEvent event) { - this.logger = event.getModLog(); - - ForgeCreeperHeal.getInstance().registerReflection(); - - this.configProvider = new ConfigProvider(new JSONConfigLoader(event.getSuggestedConfigurationFile()), new File(ForgeCreeperHeal.MODID+"-config-error.log")); + private DefaultFactory blockDataFactory; + private DefaultFactory dependencyFactory; - this.healerFactory = new TickTimelineFactory(); - this.blockDataFactory = loadBlockDataFactory(); - this.dependencyFactory = loadDependencyFactory(); - - this.config = new FastConfig(); - this.configProvider.addConfigListener(config); - this.loadConfig(); + private ChunkEventHandler chunkEventHandler; + private ExplosionEventHandler explosionEventHandler; + private WorldEventHandler worldTickEventHandler; + private PlayerConnectionHandler playerConnectionHandler; - } - public void onInit(FMLInitializationEvent event) - { - this.chunkEventHandler = new ChunkEventHandler(); - this.chunkEventHandler.register(); + public void onPreInit(FMLPreInitializationEvent event) { + this.logger = event.getModLog(); - this.explosionEventHandler = new ExplosionEventHandler(); - this.explosionEventHandler.register(); + ForgeCreeperHeal.getInstance().registerReflection(); - this.worldTickEventHandler = new WorldEventHandler(); - this.worldTickEventHandler.register(); - - this.playerConnectionHandler = new PlayerConnectionHandler(); - this.playerConnectionHandler.register(); + this.configProvider = new ConfigProvider(new JSONConfigLoader(event.getSuggestedConfigurationFile()), new File(ForgeCreeperHeal.MODID + "-config-error.log")); - //channel = NetworkRegistry.INSTANCE.newSimpleChannel(ForgeCreeperHeal.MODID+":"+"ch0"); - //channel.registerMessage(ModDataMessage.Handler.class, ModDataMessage.class, 0, Side.SERVER); - //channel.registerMessage(ProfilerInfoMessage.Handler.class, ProfilerInfoMessage.class, 1, Side.CLIENT); - } + this.healerFactory = new TickTimelineFactory(); + this.blockDataFactory = loadBlockDataFactory(); + this.dependencyFactory = loadDependencyFactory(); - public void serverAboutToStart(FMLServerAboutToStartEvent event) { - this.healerManagers = new HashMap(); - } + this.config = new FastConfig(); + this.configProvider.addConfigListener(config); + this.loadConfig(); - public void serverStarting(FMLServerStartingEvent event) { - ForgeCreeperHealCommands.register(); - } + } - public Logger getLogger() { - return logger; - } + public void onInit(FMLInitializationEvent event) { + this.chunkEventHandler = new ChunkEventHandler(); + this.chunkEventHandler.register(); - public IConfigProvider getConfigProvider() { - return configProvider; - } + this.explosionEventHandler = new ExplosionEventHandler(); + this.explosionEventHandler.register(); - public FastConfig getConfig() { - return this.config; - } + this.worldTickEventHandler = new WorldEventHandler(); + this.worldTickEventHandler.register(); - /* - public SimpleNetworkWrapper getChannel() { - return channel; - } - */ + this.playerConnectionHandler = new PlayerConnectionHandler(); + this.playerConnectionHandler.register(); - public Map getHealerManagers(){ - return healerManagers; - } + //channel = NetworkRegistry.INSTANCE.newSimpleChannel(ForgeCreeperHeal.MODID+":"+"ch0"); + //channel.registerMessage(ModDataMessage.Handler.class, ModDataMessage.class, 0, Side.SERVER); + //channel.registerMessage(ProfilerInfoMessage.Handler.class, ProfilerInfoMessage.class, 1, Side.CLIENT); + } - public TickTimelineFactory getHealerFactory() { - return healerFactory; - } + public void serverAboutToStart(FMLServerAboutToStartEvent event) { + this.healerManagers = new HashMap(); + } - public DefaultFactory getBlockDataFactory() { - return blockDataFactory; - } + public void serverStarting(FMLServerStartingEvent event) { + ForgeCreeperHealCommands.register(); + } - public DefaultFactory getDependencyFactory() { - return dependencyFactory; - } + public Logger getLogger() { + return logger; + } - public ChunkEventHandler getChunkEventHandler() { - return chunkEventHandler; - } + public IConfigProvider getConfigProvider() { + return configProvider; + } - public void loadConfig() { - this.configProvider.loadConfig(); - - //Save config to have a clean config file (add new options or suppress old options / mistake from user) - try { - this.configProvider.getConfigLoader().save(this.configProvider.getConfig()); - } catch (Exception e) { - e.printStackTrace(); - ForgeCreeperHeal.getLogger().error("Unable to save config : "+e.getMessage()); - } - - //Notify listener to update - this.configProvider.fireConfigChanged(); - //Unload config to free some RAM - this.configProvider.unloadConfig(); - } + public FastConfig getConfig() { + return this.config; + } - private DefaultFactory loadBlockDataFactory() { - final DefaultFactory blockDataFactory = new DefaultFactory(BlockKeyBuilder.getInstance(), new DefaultBlockDataBuilder()); - blockDataFactory.getCustomHandlers().add(new DoorBlockDataBuilder()); - blockDataFactory.getCustomHandlers().add(new BedBlockDataBuilder()); - blockDataFactory.getCustomHandlers().add(new PistonBlockDataBuilder()); - return blockDataFactory; + /* + public SimpleNetworkWrapper getChannel() { + return channel; } + */ - private DefaultFactory loadDependencyFactory() { - final DefaultFactory dependencyFactory = new DefaultFactory(BlockKeyBuilder.getInstance(), new NoDependencyBuilder()); - dependencyFactory.getCustomHandlers().add(new VineDependencyBuilder()); - dependencyFactory.getCustomHandlers().add(new LeverDependencyBuilder()); - dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockTorch.class, new TorchPropertySelector())); - dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockLadder.class, new LadderPropertySelector())); - dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockWallSign.class, new WallSignPropertySelector())); - dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockTrapDoor.class, new TrapDoorPropertySelector())); - dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockButton.class, new ButtonPropertySelector())); - dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockBannerHanging.class, new BannerHangingPropertySelector())); - dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockTripWireHook.class, new TripWireHookPropertySelector())); - dependencyFactory.getCustomHandlers().add(new FacingDependencyBuilder(BlockCocoa.class, new CocoaPropertySelector())); - - final AbstractGenericDependencyBuilder supportByBottomDependencyBuilder = SupportByBottomDependencyBuilder.getInstance(); - supportByBottomDependencyBuilder.register(BlockFalling.class); - supportByBottomDependencyBuilder.register(BlockDoor.class); - supportByBottomDependencyBuilder.register(BlockBasePressurePlate.class); - supportByBottomDependencyBuilder.register(BlockBannerStanding.class); - supportByBottomDependencyBuilder.register(BlockRedstoneDiode.class); - supportByBottomDependencyBuilder.register(BlockRedstoneWire.class); - supportByBottomDependencyBuilder.register(BlockStandingSign.class); - supportByBottomDependencyBuilder.register(BlockCrops.class); - supportByBottomDependencyBuilder.register(BlockCactus.class); - supportByBottomDependencyBuilder.register(BlockRailBase.class); - supportByBottomDependencyBuilder.register(BlockReed.class); - supportByBottomDependencyBuilder.register(BlockSnow.class); - supportByBottomDependencyBuilder.register(BlockTripWire.class); - supportByBottomDependencyBuilder.register(BlockCake.class); - supportByBottomDependencyBuilder.register(BlockCarpet.class); - supportByBottomDependencyBuilder.register(BlockDragonEgg.class); - supportByBottomDependencyBuilder.register(BlockFlowerPot.class); - supportByBottomDependencyBuilder.register(BlockGrass.class); - supportByBottomDependencyBuilder.register(BlockTallGrass.class); - - dependencyFactory.getCustomHandlers().add(supportByBottomDependencyBuilder); - - return dependencyFactory; - } + public Map getHealerManagers() { + return healerManagers; + } + + public TickTimelineFactory getHealerFactory() { + return healerFactory; + } + + public DefaultFactory getBlockDataFactory() { + return blockDataFactory; + } + + public DefaultFactory getDependencyFactory() { + return dependencyFactory; + } + + public ChunkEventHandler getChunkEventHandler() { + return chunkEventHandler; + } + + public void loadConfig() { + this.configProvider.loadConfig(); + + //Save config to have a clean config file (add new options or suppress old options / mistake from user) + try { + this.configProvider.getConfigLoader().save(this.configProvider.getConfig()); + } catch (Exception e) { + e.printStackTrace(); + ForgeCreeperHeal.getLogger().error("Unable to save config : " + e.getMessage()); + } + + //Notify listener to update + this.configProvider.fireConfigChanged(); + //Unload config to free some RAM + this.configProvider.unloadConfig(); + } + + private DefaultFactory loadBlockDataFactory() { + final DefaultFactory blockDataFactory = new DefaultFactory(BlockKeyBuilder.getInstance(), new DefaultBlockDataBuilder()); + blockDataFactory.getCustomHandlers().add(new DoorBlockDataBuilder()); + blockDataFactory.getCustomHandlers().add(new BedBlockDataBuilder()); + blockDataFactory.getCustomHandlers().add(new PistonBlockDataBuilder()); + return blockDataFactory; + } + + private DefaultFactory loadDependencyFactory() { + final DefaultFactory dependencyFactory = new DefaultFactory(BlockKeyBuilder.getInstance(), new NoDependencyBuilder()); + dependencyFactory.getCustomHandlers().add(new VineDependencyBuilder()); + dependencyFactory.getCustomHandlers().add(new LeverDependencyBuilder()); + dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockTorch.class, new TorchPropertySelector())); + dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockLadder.class, new LadderPropertySelector())); + dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockWallSign.class, new WallSignPropertySelector())); + dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockTrapDoor.class, new TrapDoorPropertySelector())); + dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockButton.class, new ButtonPropertySelector())); + dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockBannerHanging.class, new BannerHangingPropertySelector())); + dependencyFactory.getCustomHandlers().add(new OppositeFacingDependencyBuilder(BlockTripWireHook.class, new TripWireHookPropertySelector())); + dependencyFactory.getCustomHandlers().add(new FacingDependencyBuilder(BlockCocoa.class, new CocoaPropertySelector())); + + final AbstractGenericDependencyBuilder supportByBottomDependencyBuilder = SupportByBottomDependencyBuilder.getInstance(); + supportByBottomDependencyBuilder.register(BlockFalling.class); + supportByBottomDependencyBuilder.register(BlockDoor.class); + supportByBottomDependencyBuilder.register(BlockBasePressurePlate.class); + supportByBottomDependencyBuilder.register(BlockBannerStanding.class); + supportByBottomDependencyBuilder.register(BlockRedstoneDiode.class); + supportByBottomDependencyBuilder.register(BlockRedstoneWire.class); + supportByBottomDependencyBuilder.register(BlockStandingSign.class); + supportByBottomDependencyBuilder.register(BlockCrops.class); + supportByBottomDependencyBuilder.register(BlockCactus.class); + supportByBottomDependencyBuilder.register(BlockRailBase.class); + supportByBottomDependencyBuilder.register(BlockReed.class); + supportByBottomDependencyBuilder.register(BlockSnow.class); + supportByBottomDependencyBuilder.register(BlockTripWire.class); + supportByBottomDependencyBuilder.register(BlockCake.class); + supportByBottomDependencyBuilder.register(BlockCarpet.class); + supportByBottomDependencyBuilder.register(BlockDragonEgg.class); + supportByBottomDependencyBuilder.register(BlockFlowerPot.class); + supportByBottomDependencyBuilder.register(BlockGrass.class); + supportByBottomDependencyBuilder.register(BlockTallGrass.class); + + dependencyFactory.getCustomHandlers().add(supportByBottomDependencyBuilder); + + return dependencyFactory; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionClass.java b/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionClass.java index e1acb0c..6a11a3d 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionClass.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionClass.java @@ -1,125 +1,124 @@ package fr.eyzox.forgecreeperheal.reflection; +import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; +import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealException; +import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealReflectionException; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; -import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealException; -import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealReflectionException; - class ReflectionClass { - - private static class MethodKey { - - private final static Class[] NO_METHOD_TYPE = new Class[0]; - - private final String name; - private final Class[] methodTypes; - - private MethodKey(String name, Class[] methodTypes) { - this.name = name; - this.methodTypes = methodTypes == null ? NO_METHOD_TYPE : methodTypes; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(methodTypes); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - MethodKey other = (MethodKey) obj; - if (!Arrays.equals(methodTypes, other.methodTypes)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(name); - sb.append('('); - for(int i=0; i clazz; - private final Map fields = new HashMap(); - private final Map methods = new HashMap(); - - protected ReflectionClass(Class clazz) { - this.clazz = clazz; - } - - public Class getClazz() { - return clazz; - } - - public synchronized Field getField(String name) { - final Field f = fields.get(name); - if(f == null) { - final ForgeCreeperHealException e = new ForgeCreeperHealReflectionException(String.format("The %s.%s field is not registered",clazz.getName(), name)); - ForgeCreeperHeal.getLogger().error(e.getMessage()); - throw e; - } - return f; - } - - public synchronized Method getMethod(String name, Class[] methodTypes) { - final MethodKey key = new MethodKey(name, methodTypes); - final Method m = methods.get(key); - if(m == null) { - final ForgeCreeperHealException e = new ForgeCreeperHealReflectionException(String.format("The %s.%s method is not registered",clazz.getName(), key.toString())); - ForgeCreeperHeal.getLogger().error(e.getMessage()); - throw e; - } - return m; - } - - protected synchronized void registerField(String name, String obfName) { - fields.put(name, net.minecraftforge.fml.relauncher.ReflectionHelper.findField(this.clazz, obfName, name)); - } - - protected synchronized void registerMethod(String name, String obfName, Class[] methodTypes) { - final MethodKey key = new MethodKey(name, methodTypes); - methods.put(key, ReflectionHelper.findMethod(this.clazz, new String[]{obfName, name}, methodTypes)); - } - - protected synchronized void unregisterField(String name) { - fields.remove(name); - } - - protected synchronized void unregisterMethod(String name, Class[] methodTypes) { - final MethodKey key = new MethodKey(name, methodTypes); - methods.remove(key); - } - - protected synchronized boolean isEmpty() { - return fields.isEmpty() && methods.isEmpty(); - } + + private final Class clazz; + private final Map fields = new HashMap(); + private final Map methods = new HashMap(); + protected ReflectionClass(Class clazz) { + this.clazz = clazz; + } + + public Class getClazz() { + return clazz; + } + + public synchronized Field getField(String name) { + final Field f = fields.get(name); + if (f == null) { + final ForgeCreeperHealException e = new ForgeCreeperHealReflectionException(String.format("The %s.%s field is not registered", clazz.getName(), name)); + ForgeCreeperHeal.getLogger().error(e.getMessage()); + throw e; + } + return f; + } + + public synchronized Method getMethod(String name, Class[] methodTypes) { + final MethodKey key = new MethodKey(name, methodTypes); + final Method m = methods.get(key); + if (m == null) { + final ForgeCreeperHealException e = new ForgeCreeperHealReflectionException(String.format("The %s.%s method is not registered", clazz.getName(), key.toString())); + ForgeCreeperHeal.getLogger().error(e.getMessage()); + throw e; + } + return m; + } + + protected synchronized void registerField(String name, String obfName) { + fields.put(name, net.minecraftforge.fml.relauncher.ReflectionHelper.findField(this.clazz, obfName, name)); + } + + protected synchronized void registerMethod(String name, String obfName, Class[] methodTypes) { + final MethodKey key = new MethodKey(name, methodTypes); + methods.put(key, ReflectionHelper.findMethod(this.clazz, new String[]{obfName, name}, methodTypes)); + } + + protected synchronized void unregisterField(String name) { + fields.remove(name); + } + + protected synchronized void unregisterMethod(String name, Class[] methodTypes) { + final MethodKey key = new MethodKey(name, methodTypes); + methods.remove(key); + } + + protected synchronized boolean isEmpty() { + return fields.isEmpty() && methods.isEmpty(); + } + + private static class MethodKey { + + private final static Class[] NO_METHOD_TYPE = new Class[0]; + + private final String name; + private final Class[] methodTypes; + + private MethodKey(String name, Class[] methodTypes) { + this.name = name; + this.methodTypes = methodTypes == null ? NO_METHOD_TYPE : methodTypes; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Arrays.hashCode(methodTypes); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + MethodKey other = (MethodKey) obj; + if (!Arrays.equals(methodTypes, other.methodTypes)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(name); + sb.append('('); + for (int i = 0; i < methodTypes.length; i++) { + sb.append(methodTypes[i].getName()); + if (i < methodTypes.length - 1) { + sb.append(", "); + } + } + sb.append(')'); + return sb.toString(); + } + + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionHelper.java b/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionHelper.java index 8df77cb..048e32b 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionHelper.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionHelper.java @@ -1,45 +1,45 @@ package fr.eyzox.forgecreeperheal.reflection; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealReflectionException; import net.minecraftforge.fml.relauncher.ReflectionHelper.UnableToFindMethodException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + public class ReflectionHelper { - - public static Object get(Field f, Object obj) { - try { - return f.get(obj); - } catch (ReflectiveOperationException e) { - throw new ForgeCreeperHealReflectionException(e); - } - } - - public static Object call(Object fromObject, Method method, Object... params) { - try { - return method.invoke(fromObject, params); - } catch (ReflectiveOperationException e) { - ForgeCreeperHeal.getLogger().error("Unable to call method "+method == null ? null : method.getName()); - throw new ForgeCreeperHealReflectionException(e); - } - } - - /** - * Replacement for net.minecraftforge.fml.relauncher.ReflectionHelper.findMethod(Class, E, String[], Class[]) - * @see https://github.com/MinecraftForge/MinecraftForge/issues/3676 - */ - @Deprecated - protected static Method findMethod(Class clazz, String[] methodNames, Class... methodTypes){ + + public static Object get(Field f, Object obj) { + try { + return f.get(obj); + } catch (ReflectiveOperationException e) { + throw new ForgeCreeperHealReflectionException(e); + } + } + + public static Object call(Object fromObject, Method method, Object... params) { + try { + return method.invoke(fromObject, params); + } catch (ReflectiveOperationException e) { + ForgeCreeperHeal.getLogger().error("Unable to call method " + method == null ? null : method.getName()); + throw new ForgeCreeperHealReflectionException(e); + } + } + + /** + * Replacement for net.minecraftforge.fml.relauncher.ReflectionHelper.findMethod(Class, E, String[], Class[]) + * + * @see https://github.com/MinecraftForge/MinecraftForge/issues/3676 + */ + @Deprecated + protected static Method findMethod(Class clazz, String[] methodNames, Class... methodTypes) { Exception failed = null; - for (String methodName : methodNames){ - try{ + for (String methodName : methodNames) { + try { Method m = clazz.getDeclaredMethod(methodName, methodTypes); m.setAccessible(true); return m; - } - catch (Exception e){ + } catch (Exception e) { failed = e; } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionManager.java b/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionManager.java index add1c8c..87393d7 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionManager.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/reflection/ReflectionManager.java @@ -1,86 +1,86 @@ package fr.eyzox.forgecreeperheal.reflection; +import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; +import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealException; +import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealReflectionException; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; -import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; -import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealException; -import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealReflectionException; - public class ReflectionManager { - private final static String MSG_UNREC_CLASS = "The %s class is not registered"; - - private final static ReflectionManager INSTANCE = new ReflectionManager(); - - private final Map, ReflectionClass> reflectClasses = new HashMap, ReflectionClass>(); - - private ReflectionManager() { - } - - public synchronized void registerField(Class clazz, String name, String obfName) { - getOrPut(clazz).registerField(name, obfName); - } - - public synchronized void registerMethod(Class clazz, String name, String obfName, Class[] methodTypes) { - getOrPut(clazz).registerMethod(name, obfName, methodTypes); - } - - public synchronized void unregisterField(Class clazz, String name) { - ReflectionClass rClass = reflectClasses.get(clazz); - if(rClass != null) { - rClass.unregisterField(name); - if(rClass.isEmpty()) { - reflectClasses.remove(rClass.getClazz()); - } - } - } - - public synchronized void unregisterMethod(Class clazz, String name, Class[] methodTypes) { - ReflectionClass rClass = reflectClasses.get(clazz); - if(rClass != null) { - rClass.unregisterMethod(name, methodTypes); - if(rClass.isEmpty()) { - reflectClasses.remove(rClass.getClazz()); - } - } - } - - public synchronized Field getField(Class clazz, String name) { - ReflectionClass rClass = reflectClasses.get(clazz); - if(rClass == null) { - throwUnrecClass(clazz); - } - return rClass.getField(name); - } - - public synchronized Method getMethod(Class clazz, String name, Class[] methodTypes) { - ReflectionClass rClass = reflectClasses.get(clazz); - if(rClass == null) { - throwUnrecClass(clazz); - } - return rClass.getMethod(name, methodTypes); - } - - private ReflectionClass getOrPut(Class clazz) { - ReflectionClass rClass = reflectClasses.get(clazz); - if(rClass == null) { - rClass = new ReflectionClass(clazz); - reflectClasses.put(rClass.getClazz(), rClass); - } - return rClass; - } - - private void throwUnrecClass(Class clazz) { - final ForgeCreeperHealException e = new ForgeCreeperHealReflectionException(String.format(MSG_UNREC_CLASS,clazz.getName())); - ForgeCreeperHeal.getLogger().error(e.getMessage()); - throw e; - } - - public static ReflectionManager getInstance() { - return INSTANCE; - } - + private final static String MSG_UNREC_CLASS = "The %s class is not registered"; + + private final static ReflectionManager INSTANCE = new ReflectionManager(); + + private final Map, ReflectionClass> reflectClasses = new HashMap, ReflectionClass>(); + + private ReflectionManager() { + } + + public static ReflectionManager getInstance() { + return INSTANCE; + } + + public synchronized void registerField(Class clazz, String name, String obfName) { + getOrPut(clazz).registerField(name, obfName); + } + + public synchronized void registerMethod(Class clazz, String name, String obfName, Class[] methodTypes) { + getOrPut(clazz).registerMethod(name, obfName, methodTypes); + } + + public synchronized void unregisterField(Class clazz, String name) { + ReflectionClass rClass = reflectClasses.get(clazz); + if (rClass != null) { + rClass.unregisterField(name); + if (rClass.isEmpty()) { + reflectClasses.remove(rClass.getClazz()); + } + } + } + + public synchronized void unregisterMethod(Class clazz, String name, Class[] methodTypes) { + ReflectionClass rClass = reflectClasses.get(clazz); + if (rClass != null) { + rClass.unregisterMethod(name, methodTypes); + if (rClass.isEmpty()) { + reflectClasses.remove(rClass.getClazz()); + } + } + } + + public synchronized Field getField(Class clazz, String name) { + ReflectionClass rClass = reflectClasses.get(clazz); + if (rClass == null) { + throwUnrecClass(clazz); + } + return rClass.getField(name); + } + + public synchronized Method getMethod(Class clazz, String name, Class[] methodTypes) { + ReflectionClass rClass = reflectClasses.get(clazz); + if (rClass == null) { + throwUnrecClass(clazz); + } + return rClass.getMethod(name, methodTypes); + } + + private ReflectionClass getOrPut(Class clazz) { + ReflectionClass rClass = reflectClasses.get(clazz); + if (rClass == null) { + rClass = new ReflectionClass(clazz); + reflectClasses.put(rClass.getClazz(), rClass); + } + return rClass; + } + + private void throwUnrecClass(Class clazz) { + final ForgeCreeperHealException e = new ForgeCreeperHealReflectionException(String.format(MSG_UNREC_CLASS, clazz.getName())); + ForgeCreeperHeal.getLogger().error(e.getMessage()); + throw e; + } + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/reflection/transform/ChunkTransform.java b/src/main/java/fr/eyzox/forgecreeperheal/reflection/transform/ChunkTransform.java index 0c4e6c9..b78cd1e 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/reflection/transform/ChunkTransform.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/reflection/transform/ChunkTransform.java @@ -1,10 +1,5 @@ package fr.eyzox.forgecreeperheal.reflection.transform; -import static net.minecraft.world.chunk.Chunk.NULL_BLOCK_STORAGE; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - import fr.eyzox.forgecreeperheal.reflection.ReflectionHelper; import fr.eyzox.forgecreeperheal.reflection.ReflectionManager; import net.minecraft.block.Block; @@ -17,96 +12,94 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import static net.minecraft.world.chunk.Chunk.NULL_BLOCK_STORAGE; + public class ChunkTransform { - - private final static Field FIELD_PRECIPITATION_HEIGHT_MAP = ReflectionManager.getInstance().getField(Chunk.class, "precipitationHeightMap"); - private final static Method METHOD_RELIGHT_BLOCK = ReflectionManager.getInstance().getMethod(Chunk.class, "relightBlock", new Class[]{int.class,int.class,int.class}); - private final static Method METHOD_PROPAGATE_SKYLIGHT_OCCLUSION = ReflectionManager.getInstance().getMethod(Chunk.class, "propagateSkylightOcclusion", new Class[]{int.class,int.class}); - - private final Chunk chunk; - - private final int[] precipitationHeightMap; - private final int[] heightMap; - private final World worldObj; - private final ExtendedBlockStorage[] storageArrays; - - - public ChunkTransform(final Chunk chunk) { - this.chunk = chunk; - this.precipitationHeightMap = (int[]) ReflectionHelper.get(FIELD_PRECIPITATION_HEIGHT_MAP, this.chunk); - this.heightMap = this.chunk.getHeightMap(); - this.worldObj = this.chunk.getWorld(); - this.storageArrays = this.chunk.getBlockStorageArray(); - } - - private IBlockState getBlockState(BlockPos pos) { - return this.chunk.getBlockState(pos); - } - - private TileEntity getTileEntity(BlockPos pos, Chunk.EnumCreateEntityType p_177424_2_) { - return this.chunk.getTileEntity(pos, p_177424_2_); - } - - private void generateSkylightMap() { - this.chunk.generateSkylightMap(); - } - - private void relightBlock(int x, int y, int z) { - ReflectionHelper.call(this.chunk, METHOD_RELIGHT_BLOCK, x, y, z); - } - - private int getLightFor(EnumSkyBlock p_177413_1_, BlockPos pos){ - return this.chunk.getLightFor(p_177413_1_, pos); - } - - private void propagateSkylightOcclusion(int x, int z){ - ReflectionHelper.call(this.chunk, METHOD_PROPAGATE_SKYLIGHT_OCCLUSION, x, z); - } - - private void _isModified(boolean v) { - this.chunk.setModified(true); - } - - /** - * - * From {@link net.minecraft.world.chunk.Chunk#setBlockState(BlockPos, IBlockState)} - * Edition : Don't call {@link Block#breakBlock(net.minecraft.world.World, BlockPos, IBlockState)} - * - * @param pos - * @param state - * @return - */ - public IBlockState setBlockState(BlockPos pos, IBlockState state) { - - int i = pos.getX() & 15; + + private final static Field FIELD_PRECIPITATION_HEIGHT_MAP = ReflectionManager.getInstance().getField(Chunk.class, "precipitationHeightMap"); + private final static Method METHOD_RELIGHT_BLOCK = ReflectionManager.getInstance().getMethod(Chunk.class, "relightBlock", new Class[]{int.class, int.class, int.class}); + private final static Method METHOD_PROPAGATE_SKYLIGHT_OCCLUSION = ReflectionManager.getInstance().getMethod(Chunk.class, "propagateSkylightOcclusion", new Class[]{int.class, int.class}); + + private final Chunk chunk; + + private final int[] precipitationHeightMap; + private final int[] heightMap; + private final World worldObj; + private final ExtendedBlockStorage[] storageArrays; + + + public ChunkTransform(final Chunk chunk) { + this.chunk = chunk; + this.precipitationHeightMap = (int[]) ReflectionHelper.get(FIELD_PRECIPITATION_HEIGHT_MAP, this.chunk); + this.heightMap = this.chunk.getHeightMap(); + this.worldObj = this.chunk.getWorld(); + this.storageArrays = this.chunk.getBlockStorageArray(); + } + + private IBlockState getBlockState(BlockPos pos) { + return this.chunk.getBlockState(pos); + } + + private TileEntity getTileEntity(BlockPos pos, Chunk.EnumCreateEntityType p_177424_2_) { + return this.chunk.getTileEntity(pos, p_177424_2_); + } + + private void generateSkylightMap() { + this.chunk.generateSkylightMap(); + } + + private void relightBlock(int x, int y, int z) { + ReflectionHelper.call(this.chunk, METHOD_RELIGHT_BLOCK, x, y, z); + } + + private int getLightFor(EnumSkyBlock p_177413_1_, BlockPos pos) { + return this.chunk.getLightFor(p_177413_1_, pos); + } + + private void propagateSkylightOcclusion(int x, int z) { + ReflectionHelper.call(this.chunk, METHOD_PROPAGATE_SKYLIGHT_OCCLUSION, x, z); + } + + private void _isModified(boolean v) { + this.chunk.setModified(true); + } + + /** + * From {@link net.minecraft.world.chunk.Chunk#setBlockState(BlockPos, IBlockState)} + * Edition : Don't call {@link Block#breakBlock(net.minecraft.world.World, BlockPos, IBlockState)} + * + * @param pos + * @param state + * @return + */ + public IBlockState setBlockState(BlockPos pos, IBlockState state) { + + int i = pos.getX() & 15; int j = pos.getY(); int k = pos.getZ() & 15; int l = k << 4 | i; - if (j >= this.precipitationHeightMap[l] - 1) - { + if (j >= this.precipitationHeightMap[l] - 1) { this.precipitationHeightMap[l] = -999; } int i1 = this.heightMap[l]; IBlockState iblockstate = this.getBlockState(pos); - if (iblockstate == state) - { + if (iblockstate == state) { return null; - } - else - { + } else { Block block = state.getBlock(); Block block1 = iblockstate.getBlock(); int k1 = iblockstate.getLightOpacity(this.worldObj, pos); // Relocate old light value lookup here, so that it is called before TE is removed. ExtendedBlockStorage extendedblockstorage = this.storageArrays[j >> 4]; boolean flag = false; - if (extendedblockstorage == NULL_BLOCK_STORAGE) - { - if (block == Blocks.AIR) - { + if (extendedblockstorage == NULL_BLOCK_STORAGE) { + if (block == Blocks.AIR) { return null; } @@ -118,73 +111,56 @@ public IBlockState setBlockState(BlockPos pos, IBlockState state) { //if (block1 != block) { - if (!this.worldObj.isRemote) - { - /* ====== REMOVED =========== + if (!this.worldObj.isRemote) { + /* ====== REMOVED =========== if (block1 != block) //Only fire block breaks when the block changes. block1.breakBlock(this.worldObj, pos, iblockstate); ============================= */ TileEntity te = this.getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK); - if (te != null && te.shouldRefresh(this.worldObj, pos, iblockstate, state)) this.worldObj.removeTileEntity(pos); - } - else if (block1.hasTileEntity(iblockstate)) - { + if (te != null && te.shouldRefresh(this.worldObj, pos, iblockstate, state)) + this.worldObj.removeTileEntity(pos); + } else if (block1.hasTileEntity(iblockstate)) { TileEntity te = this.getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK); if (te != null && te.shouldRefresh(this.worldObj, pos, iblockstate, state)) - this.worldObj.removeTileEntity(pos); + this.worldObj.removeTileEntity(pos); } } - if (extendedblockstorage.get(i, j & 15, k).getBlock() != block) - { + if (extendedblockstorage.get(i, j & 15, k).getBlock() != block) { return null; - } - else - { - if (flag) - { + } else { + if (flag) { this.generateSkylightMap(); - } - else - { + } else { int j1 = state.getLightOpacity(this.worldObj, pos); - if (j1 > 0) - { - if (j >= i1) - { + if (j1 > 0) { + if (j >= i1) { this.relightBlock(i, j + 1, k); } - } - else if (j == i1 - 1) - { + } else if (j == i1 - 1) { this.relightBlock(i, j, k); } - if (j1 != k1 && (j1 < k1 || this.getLightFor(EnumSkyBlock.SKY, pos) > 0 || this.getLightFor(EnumSkyBlock.BLOCK, pos) > 0)) - { + if (j1 != k1 && (j1 < k1 || this.getLightFor(EnumSkyBlock.SKY, pos) > 0 || this.getLightFor(EnumSkyBlock.BLOCK, pos) > 0)) { this.propagateSkylightOcclusion(i, k); } } // If capturing blocks, only run block physics for TE's. Non-TE's are handled in ForgeHooks.onPlaceItemIntoWorld - if (!this.worldObj.isRemote && block1 != block && (!this.worldObj.captureBlockSnapshots || block.hasTileEntity(state))) - { + if (!this.worldObj.isRemote && block1 != block && (!this.worldObj.captureBlockSnapshots || block.hasTileEntity(state))) { block.onBlockAdded(this.worldObj, pos, state); } - if (block.hasTileEntity(state)) - { + if (block.hasTileEntity(state)) { TileEntity tileentity1 = this.getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK); - if (tileentity1 == null) - { + if (tileentity1 == null) { tileentity1 = block.createTileEntity(this.worldObj, state); this.worldObj.setTileEntity(pos, tileentity1); } - if (tileentity1 != null) - { + if (tileentity1 != null) { tileentity1.updateContainingBlockInfo(); } } @@ -192,7 +168,7 @@ else if (j == i1 - 1) this._isModified(true); return iblockstate; } - + } - } + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/reflection/transform/WorldTransform.java b/src/main/java/fr/eyzox/forgecreeperheal/reflection/transform/WorldTransform.java index f15250e..e378375 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/reflection/transform/WorldTransform.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/reflection/transform/WorldTransform.java @@ -1,9 +1,5 @@ package fr.eyzox.forgecreeperheal.reflection.transform; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - import fr.eyzox.forgecreeperheal.reflection.ReflectionHelper; import fr.eyzox.forgecreeperheal.reflection.ReflectionManager; import net.minecraft.block.Block; @@ -15,69 +11,64 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.storage.WorldInfo; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + public class WorldTransform { - private static Method isValidMethod = ReflectionManager.getInstance().getMethod(World.class, "isValid", new Class[]{BlockPos.class}); - - private final World world; - - private Map cachedChunkTransform = new HashMap(); - - - private final boolean isRemote; - private final WorldInfo worldInfo; - - - public WorldTransform(World world) { - this.world = world; - this.isRemote = this.world.isRemote; - this.worldInfo = this.world.getWorldInfo(); - } - - public void removeSilentBlockState(BlockPos pos, int flags) { - - final IBlockState newState = Blocks.AIR.getDefaultState(); - - this.setBlockState(pos, newState, flags); - } - - private boolean isValid(BlockPos pos) { - return ((Boolean)ReflectionHelper.call(world, isValidMethod, pos)).booleanValue(); - } - - private Chunk getChunkFromBlockCoords(BlockPos pos) { - return this.world.getChunkFromBlockCoords(pos); - } - - private IBlockState getBlockState(BlockPos pos) { - return this.world.getBlockState(pos); - } - - /** - * From {@link World#setBlockState(BlockPos, IBlockState, int)} - * Don't call {@link Chunk#setBlockState(BlockPos, IBlockState)} but call {@link ChunkTransform#setBlockState(BlockPos, IBlockState)} - * - * @param pos - * @param newState - * @param flags - */ - private boolean setBlockState(BlockPos pos, IBlockState newState, int flags) { - if (!this.isValid(pos)) - { + private static Method isValidMethod = ReflectionManager.getInstance().getMethod(World.class, "isValid", new Class[]{BlockPos.class}); + + private final World world; + private final boolean isRemote; + private final WorldInfo worldInfo; + private Map cachedChunkTransform = new HashMap(); + + + public WorldTransform(World world) { + this.world = world; + this.isRemote = this.world.isRemote; + this.worldInfo = this.world.getWorldInfo(); + } + + public void removeSilentBlockState(BlockPos pos, int flags) { + + final IBlockState newState = Blocks.AIR.getDefaultState(); + + this.setBlockState(pos, newState, flags); + } + + private boolean isValid(BlockPos pos) { + return ((Boolean) ReflectionHelper.call(world, isValidMethod, pos)).booleanValue(); + } + + private Chunk getChunkFromBlockCoords(BlockPos pos) { + return this.world.getChunkFromBlockCoords(pos); + } + + private IBlockState getBlockState(BlockPos pos) { + return this.world.getBlockState(pos); + } + + /** + * From {@link World#setBlockState(BlockPos, IBlockState, int)} + * Don't call {@link Chunk#setBlockState(BlockPos, IBlockState)} but call {@link ChunkTransform#setBlockState(BlockPos, IBlockState)} + * + * @param pos + * @param newState + * @param flags + */ + private boolean setBlockState(BlockPos pos, IBlockState newState, int flags) { + if (!this.isValid(pos)) { return false; - } - else if (!this.isRemote && this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) - { + } else if (!this.isRemote && this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { return false; - } - else - { + } else { Chunk chunk = this.getChunkFromBlockCoords(pos); Block block = newState.getBlock(); net.minecraftforge.common.util.BlockSnapshot blockSnapshot = null; - if (this.world.captureBlockSnapshots && !this.isRemote) - { + if (this.world.captureBlockSnapshots && !this.isRemote) { blockSnapshot = net.minecraftforge.common.util.BlockSnapshot.getBlockSnapshot(this.world, pos, flags); this.world.capturedBlockSnapshots.add(blockSnapshot); } @@ -91,23 +82,19 @@ else if (!this.isRemote && this.worldInfo.getTerrainType() == WorldType.DEBUG_WO /* ======== ADDED =============== */ ChunkTransform chunkTransform = this.cachedChunkTransform.get(chunk); - if(chunkTransform == null) { - chunkTransform = new ChunkTransform(chunk); - this.cachedChunkTransform.put(chunk, chunkTransform); + if (chunkTransform == null) { + chunkTransform = new ChunkTransform(chunk); + this.cachedChunkTransform.put(chunk, chunkTransform); } - + IBlockState iblockstate = chunkTransform.setBlockState(pos, newState); /* =============================== */ - - if (iblockstate == null) - { + + if (iblockstate == null) { if (blockSnapshot != null) this.world.capturedBlockSnapshots.remove(blockSnapshot); return false; - } - else - { - if (newState.getLightOpacity(this.world, pos) != oldOpacity || newState.getLightValue(this.world, pos) != oldLight) - { + } else { + if (newState.getLightOpacity(this.world, pos) != oldOpacity || newState.getLightValue(this.world, pos) != oldLight) { this.world.theProfiler.startSection("checkLight"); this.world.checkLight(pos); this.world.theProfiler.endSection(); @@ -120,6 +107,6 @@ else if (!this.isRemote && this.worldInfo.getTerrainType() == WorldType.DEBUG_WO return true; } } - } - + } + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/TickTimelineFactory.java b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/TickTimelineFactory.java index f78eea0..8e6bd32 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/TickTimelineFactory.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/TickTimelineFactory.java @@ -1,11 +1,5 @@ package fr.eyzox.forgecreeperheal.scheduler; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import java.util.Map.Entry; - import fr.eyzox.dependencygraph.interfaces.IData; import fr.eyzox.forgecreeperheal.healer.IChunked; import fr.eyzox.forgecreeperheal.healer.IHealable; @@ -17,78 +11,86 @@ import net.minecraft.util.math.ChunkPos; import net.minecraft.world.WorldServer; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.Map.Entry; + public class TickTimelineFactory { - - private ITickProvider tickProvider = new TickProvider(); - - public TickTimelineFactory() {} - - /** - * Create healers - * @param world - The world the healer must be created - * @param healables - The block to be heal (no specified order) - */ - public > Map>> create(final WorldServer world, final IScheduler scheduler) { - - final ChunkDataProvider> dispatchedTimelines = this.scheduleHealables(scheduler); - - final Map>> result = new HashMap>>(dispatchedTimelines.size()); - for(final Entry> entry : dispatchedTimelines.entrySet()) { - result.put(entry.getKey(), entry.getValue().timeline); - } - - return result; - } - - private > ChunkDataProvider> scheduleHealables(final IScheduler scheduler) { - - final ChunkDataProvider> dispatchedTimelines = new ChunkDataProvider>(); - - int globalTickCounter = 0; - - while(scheduler.hasNext()) { - final T healable = scheduler.next(); - - final int chunkX = healable.getChunkX(); - final int chunkZ = healable.getChunkZ(); - - //Retrieve or create DispatchedTimeline for a chunk - DispatchedTimeline dispatchedTimeline = dispatchedTimelines.get(ChunkPos.asLong(chunkX, chunkZ)); - if(dispatchedTimeline == null) { - dispatchedTimeline = new DispatchedTimeline(); - dispatchedTimelines.put(new ChunkPos(chunkX, chunkZ), dispatchedTimeline); - } - - //Generate tick - final int providedTick = tickProvider.getNextTick(); - globalTickCounter += providedTick; - final int tick = globalTickCounter - dispatchedTimeline.tickCounter; - dispatchedTimeline.tickCounter += tick; - - //Create TickContainer - final Node container = new Node(tick, healable); - - dispatchedTimeline.timeline.add(container); - } - - //Set minimal tick before heal - final int minTickBeforeHeal = tickProvider.getStartTick(); - for(final DispatchedTimeline timeline : dispatchedTimelines.values()) { - final Node firstNode = timeline.timeline.getFirst(); - firstNode.setTick(minTickBeforeHeal + firstNode.getTick()); - } - - return dispatchedTimelines; - } - - private static class DispatchedTimeline { - LinkedList> timeline = new LinkedList>(); - int tickCounter; - - @Override - public String toString() { - return timeline.toString(); - } - } - + + private ITickProvider tickProvider = new TickProvider(); + + public TickTimelineFactory() { + } + + /** + * Create healers + * + * @param world - The world the healer must be created + * @param healables - The block to be heal (no specified order) + */ + public > Map>> create(final WorldServer world, final IScheduler scheduler) { + + final ChunkDataProvider> dispatchedTimelines = this.scheduleHealables(scheduler); + + final Map>> result = new HashMap>>(dispatchedTimelines.size()); + for (final Entry> entry : dispatchedTimelines.entrySet()) { + result.put(entry.getKey(), entry.getValue().timeline); + } + + return result; + } + + private > ChunkDataProvider> scheduleHealables(final IScheduler scheduler) { + + final ChunkDataProvider> dispatchedTimelines = new ChunkDataProvider>(); + + int globalTickCounter = 0; + + while (scheduler.hasNext()) { + final T healable = scheduler.next(); + + final int chunkX = healable.getChunkX(); + final int chunkZ = healable.getChunkZ(); + + //Retrieve or create DispatchedTimeline for a chunk + DispatchedTimeline dispatchedTimeline = dispatchedTimelines.get(ChunkPos.asLong(chunkX, chunkZ)); + if (dispatchedTimeline == null) { + dispatchedTimeline = new DispatchedTimeline(); + dispatchedTimelines.put(new ChunkPos(chunkX, chunkZ), dispatchedTimeline); + } + + //Generate tick + final int providedTick = tickProvider.getNextTick(); + globalTickCounter += providedTick; + final int tick = globalTickCounter - dispatchedTimeline.tickCounter; + dispatchedTimeline.tickCounter += tick; + + //Create TickContainer + final Node container = new Node(tick, healable); + + dispatchedTimeline.timeline.add(container); + } + + //Set minimal tick before heal + final int minTickBeforeHeal = tickProvider.getStartTick(); + for (final DispatchedTimeline timeline : dispatchedTimelines.values()) { + final Node firstNode = timeline.timeline.getFirst(); + firstNode.setTick(minTickBeforeHeal + firstNode.getTick()); + } + + return dispatchedTimelines; + } + + private static class DispatchedTimeline { + LinkedList> timeline = new LinkedList>(); + int tickCounter; + + @Override + public String toString() { + return timeline.toString(); + } + } + } \ No newline at end of file diff --git a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/custom/CustomRandomScheduler.java b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/custom/CustomRandomScheduler.java index 2f09ba8..a37e6c5 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/custom/CustomRandomScheduler.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/custom/CustomRandomScheduler.java @@ -1,29 +1,28 @@ package fr.eyzox.forgecreeperheal.scheduler.custom; -import java.util.Collection; - import fr.eyzox.dependencygraph.RandomDependencyGraph; import fr.eyzox.dependencygraph.interfaces.IData; import fr.eyzox.dependencygraph.interfaces.IDependencyProvider; -public class CustomRandomScheduler> implements IScheduler{ - - private final RandomDependencyGraph graph; - - public CustomRandomScheduler(Collection c, final IDependencyProvider provider) { - graph = new RandomDependencyGraph(c, provider); - } - - @Override - public boolean hasNext() { - return graph.hasNext(); - } - - @Override - public D next() { - return graph.poll(); - } - - - +import java.util.Collection; + +public class CustomRandomScheduler> implements IScheduler { + + private final RandomDependencyGraph graph; + + public CustomRandomScheduler(Collection c, final IDependencyProvider provider) { + graph = new RandomDependencyGraph(c, provider); + } + + @Override + public boolean hasNext() { + return graph.hasNext(); + } + + @Override + public D next() { + return graph.poll(); + } + + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/custom/IScheduler.java b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/custom/IScheduler.java index 7d87e55..9b51b9f 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/custom/IScheduler.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/custom/IScheduler.java @@ -1,6 +1,7 @@ package fr.eyzox.forgecreeperheal.scheduler.custom; public interface IScheduler { - boolean hasNext(); - T next(); + boolean hasNext(); + + T next(); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/provider/BlockDataDependencyProvider.java b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/provider/BlockDataDependencyProvider.java index 5a10811..ae5b3e3 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/provider/BlockDataDependencyProvider.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/provider/BlockDataDependencyProvider.java @@ -8,18 +8,18 @@ public class BlockDataDependencyProvider implements IDependencyProvider { - private final static BlockDataDependencyProvider INSTANCE = new BlockDataDependencyProvider(); - - private BlockDataDependencyProvider() { - } - - public static BlockDataDependencyProvider getInstance() { - return INSTANCE; - } - - @Override - public DependencyType provideDependency(BlockData data) { - return ForgeCreeperHeal.getDependencyFactory().getData(data.getState().getBlock()).getDependencies(data); - } - + private final static BlockDataDependencyProvider INSTANCE = new BlockDataDependencyProvider(); + + private BlockDataDependencyProvider() { + } + + public static BlockDataDependencyProvider getInstance() { + return INSTANCE; + } + + @Override + public DependencyType provideDependency(BlockData data) { + return ForgeCreeperHeal.getDependencyFactory().getData(data.getState().getBlock()).getDependencies(data); + } + } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/updater/FullAndDependency.java b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/updater/FullAndDependency.java index a7a603c..9fb81f9 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/updater/FullAndDependency.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/updater/FullAndDependency.java @@ -1,15 +1,15 @@ package fr.eyzox.forgecreeperheal.scheduler.graph.dependency.updater; -import java.util.Set; - import fr.eyzox.dependencygraph.interfaces.IDependencyUpdater; import net.minecraft.util.math.BlockPos; +import java.util.Set; + public class FullAndDependency implements IDependencyUpdater { - - @Override - public boolean isAvailable(Set dependenciesLeft) { - return dependenciesLeft.isEmpty(); - } + + @Override + public boolean isAvailable(Set dependenciesLeft) { + return dependenciesLeft.isEmpty(); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/updater/FullOrDependency.java b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/updater/FullOrDependency.java index a4c4d6c..baec6c7 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/updater/FullOrDependency.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/graph/dependency/updater/FullOrDependency.java @@ -1,21 +1,21 @@ package fr.eyzox.forgecreeperheal.scheduler.graph.dependency.updater; -import java.util.Set; - import fr.eyzox.dependencygraph.interfaces.IDependencyUpdater; import net.minecraft.util.math.BlockPos; +import java.util.Set; + public class FullOrDependency implements IDependencyUpdater { - private final int dependencyNumber; - - public FullOrDependency(final int dependencyNumber) { - this.dependencyNumber = dependencyNumber; - } - - @Override - public boolean isAvailable(Set dependenciesLeft) { - return dependenciesLeft.size() < dependencyNumber; - } + private final int dependencyNumber; + + public FullOrDependency(final int dependencyNumber) { + this.dependencyNumber = dependencyNumber; + } + + @Override + public boolean isAvailable(Set dependenciesLeft) { + return dependenciesLeft.size() < dependencyNumber; + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/tick/ITickProvider.java b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/tick/ITickProvider.java index d69768f..15178ef 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/tick/ITickProvider.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/tick/ITickProvider.java @@ -1,6 +1,7 @@ package fr.eyzox.forgecreeperheal.scheduler.tick; public interface ITickProvider { - public int getNextTick(); - public int getStartTick(); + public int getNextTick(); + + public int getStartTick(); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/tick/TickProvider.java b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/tick/TickProvider.java index f3a5f54..d34d081 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/scheduler/tick/TickProvider.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/scheduler/tick/TickProvider.java @@ -1,28 +1,29 @@ package fr.eyzox.forgecreeperheal.scheduler.tick; -import java.util.Random; - import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; +import java.util.Random; + public class TickProvider implements ITickProvider { - private Random rdn = new Random(); - - public TickProvider() {} - - @Override - public int getNextTick() { - return random(ForgeCreeperHeal.getConfig().getMinTick(), ForgeCreeperHeal.getConfig().getMaxTick()); - } - - @Override - public int getStartTick() { - return random(ForgeCreeperHeal.getConfig().getMinTickStart(), ForgeCreeperHeal.getConfig().getMaxTickStart()); - } - - private int random(int min, int max) { - max = max-min; - return min + (max > 0 ? rdn.nextInt(max) : 0); - } + private Random rdn = new Random(); + + public TickProvider() { + } + + @Override + public int getNextTick() { + return random(ForgeCreeperHeal.getConfig().getMinTick(), ForgeCreeperHeal.getConfig().getMaxTick()); + } + + @Override + public int getStartTick() { + return random(ForgeCreeperHeal.getConfig().getMinTickStart(), ForgeCreeperHeal.getConfig().getMaxTickStart()); + } + + private int random(int min, int max) { + max = max - min; + return min + (max > 0 ? rdn.nextInt(max) : 0); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/serial/ISerialWrapper.java b/src/main/java/fr/eyzox/forgecreeperheal/serial/ISerialWrapper.java index 630a141..6959b30 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/serial/ISerialWrapper.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/serial/ISerialWrapper.java @@ -3,6 +3,7 @@ import net.minecraft.nbt.NBTTagCompound; public interface ISerialWrapper { - public DATA unserialize(final NBTTagCompound tag); - public NBTTagCompound serialize(final DATA data); + public DATA unserialize(final NBTTagCompound tag); + + public NBTTagCompound serialize(final DATA data); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/serial/ISerialWrapperProvider.java b/src/main/java/fr/eyzox/forgecreeperheal/serial/ISerialWrapperProvider.java index 871d594..48e9424 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/serial/ISerialWrapperProvider.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/serial/ISerialWrapperProvider.java @@ -1,5 +1,5 @@ package fr.eyzox.forgecreeperheal.serial; public interface ISerialWrapperProvider { - public ISerialWrapper getSerialWrapper(); + public ISerialWrapper getSerialWrapper(); } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/serial/SerialUtils.java b/src/main/java/fr/eyzox/forgecreeperheal/serial/SerialUtils.java index 62acc41..39bfb89 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/serial/SerialUtils.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/serial/SerialUtils.java @@ -1,48 +1,49 @@ package fr.eyzox.forgecreeperheal.serial; -import java.lang.reflect.Method; - import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealerSerialException; import net.minecraft.nbt.NBTTagCompound; +import java.lang.reflect.Method; + public class SerialUtils { - private static final String TAG_WRAPPER = "wrapper"; - private static final String TAG_WRAPPER_DATA = "data"; - - private SerialUtils() {} - - public static NBTTagCompound serializeWrappedData(ISerialWrapper wrapper, T data) throws ForgeCreeperHealerSerialException { - final NBTTagCompound tag = new NBTTagCompound(); - tag.setString(TAG_WRAPPER, wrapper.getClass().getName()); - tag.setTag(TAG_WRAPPER_DATA, wrapper.serialize(data)); - return tag; - } - - public static T unserializeWrappedData(final NBTTagCompound tag) throws ForgeCreeperHealerSerialException { - final String wrapperClassName = tag.getString(TAG_WRAPPER); - - if(wrapperClassName.isEmpty()) { - throw new ForgeCreeperHealerSerialException("Missing SerialWrapper's class name"); - } - - ISerialWrapper wrapper = null; - try { - Class> clazz = (Class>) Class.forName(wrapperClassName); - Method getIntance = clazz.getMethod("getInstance", null); - wrapper = (ISerialWrapper) getIntance.invoke(null, null); - }catch(ReflectiveOperationException e) { - throw new ForgeCreeperHealerSerialException(e); - }catch(ClassCastException e2) { - throw new ForgeCreeperHealerSerialException(e2); - } - - NBTTagCompound data = tag.getCompoundTag(TAG_WRAPPER_DATA); - - if(data.hasNoTags()) { - throw new ForgeCreeperHealerSerialException("Missing wrapper's data"); - } - - return wrapper.unserialize(data); - } + private static final String TAG_WRAPPER = "wrapper"; + private static final String TAG_WRAPPER_DATA = "data"; + + private SerialUtils() { + } + + public static NBTTagCompound serializeWrappedData(ISerialWrapper wrapper, T data) throws ForgeCreeperHealerSerialException { + final NBTTagCompound tag = new NBTTagCompound(); + tag.setString(TAG_WRAPPER, wrapper.getClass().getName()); + tag.setTag(TAG_WRAPPER_DATA, wrapper.serialize(data)); + return tag; + } + + public static T unserializeWrappedData(final NBTTagCompound tag) throws ForgeCreeperHealerSerialException { + final String wrapperClassName = tag.getString(TAG_WRAPPER); + + if (wrapperClassName.isEmpty()) { + throw new ForgeCreeperHealerSerialException("Missing SerialWrapper's class name"); + } + + ISerialWrapper wrapper = null; + try { + Class> clazz = (Class>) Class.forName(wrapperClassName); + Method getIntance = clazz.getMethod("getInstance", null); + wrapper = (ISerialWrapper) getIntance.invoke(null, null); + } catch (ReflectiveOperationException e) { + throw new ForgeCreeperHealerSerialException(e); + } catch (ClassCastException e2) { + throw new ForgeCreeperHealerSerialException(e2); + } + + NBTTagCompound data = tag.getCompoundTag(TAG_WRAPPER_DATA); + + if (data.hasNoTags()) { + throw new ForgeCreeperHealerSerialException("Missing wrapper's data"); + } + + return wrapper.unserialize(data); + } } diff --git a/src/main/java/fr/eyzox/forgecreeperheal/serial/TimelineSerializer.java b/src/main/java/fr/eyzox/forgecreeperheal/serial/TimelineSerializer.java index 9f804d0..ee8805e 100644 --- a/src/main/java/fr/eyzox/forgecreeperheal/serial/TimelineSerializer.java +++ b/src/main/java/fr/eyzox/forgecreeperheal/serial/TimelineSerializer.java @@ -1,8 +1,5 @@ package fr.eyzox.forgecreeperheal.serial; -import java.util.Collection; -import java.util.LinkedList; - import fr.eyzox.forgecreeperheal.ForgeCreeperHeal; import fr.eyzox.forgecreeperheal.exception.ForgeCreeperHealerSerialException; import fr.eyzox.ticktimeline.Node; @@ -11,73 +8,78 @@ import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.Constants.NBT; +import java.util.Collection; +import java.util.LinkedList; + public class TimelineSerializer { - private static final String TAG_NODES = "nodes"; - - private static final String TAG_NODE_CONTENTS = "contents"; - private static final String TAG_NODE_TICK = "tick"; - - private static final TimelineSerializer INSTANCE = new TimelineSerializer(); - - public static TimelineSerializer getInstance() { return INSTANCE;} - - private TimelineSerializer() { - } - - public > NBTTagCompound serializeNBT(final TickTimeline timeline) { - final NBTTagCompound tag = new NBTTagCompound(); - - final NBTTagList nodeListTag = new NBTTagList(); - - for(final Node> node : timeline.getTimeline()){ - final NBTTagCompound nodeTag = this.serializeNode(node); - nodeListTag.appendTag(nodeTag); - } - tag.setTag(TAG_NODES, nodeListTag); - - return tag; - - } - - public > TickTimeline deserializeNBT(final NBTTagCompound tag) { - final TickTimeline timeline = new TickTimeline(); - - final NBTTagList nodeListTag = tag.getTagList(TAG_NODES, NBT.TAG_COMPOUND); - for(int i=0; i> node = unserializeNode(nodeTag); - timeline.getTimeline().add(node); - } - return timeline; - } - - private > NBTTagCompound serializeNode(final Node> node) { - final NBTTagCompound nodeTag = new NBTTagCompound(); - nodeTag.setInteger(TAG_NODE_TICK, node.getTick()); - - final NBTTagList contentListTag = new NBTTagList(); - for(final T nodeData : node.getData()) { - contentListTag.appendTag(SerialUtils.serializeWrappedData(nodeData.getSerialWrapper(), nodeData)); - } - nodeTag.setTag(TAG_NODE_CONTENTS, contentListTag); - return nodeTag; - } - - private > Node> unserializeNode(final NBTTagCompound tag) { - final Node> node = new Node>(tag.getInteger(TAG_NODE_TICK), new LinkedList()); - - final NBTTagList contentListTag = tag.getTagList(TAG_NODE_CONTENTS, NBT.TAG_COMPOUND); - for(int i = 0; i> NBTTagCompound serializeNBT(final TickTimeline timeline) { + final NBTTagCompound tag = new NBTTagCompound(); + + final NBTTagList nodeListTag = new NBTTagList(); + + for (final Node> node : timeline.getTimeline()) { + final NBTTagCompound nodeTag = this.serializeNode(node); + nodeListTag.appendTag(nodeTag); + } + tag.setTag(TAG_NODES, nodeListTag); + + return tag; + + } + + public > TickTimeline deserializeNBT(final NBTTagCompound tag) { + final TickTimeline timeline = new TickTimeline(); + + final NBTTagList nodeListTag = tag.getTagList(TAG_NODES, NBT.TAG_COMPOUND); + for (int i = 0; i < nodeListTag.tagCount(); i++) { + final NBTTagCompound nodeTag = nodeListTag.getCompoundTagAt(i); + final Node> node = unserializeNode(nodeTag); + timeline.getTimeline().add(node); + } + return timeline; + } + + private > NBTTagCompound serializeNode(final Node> node) { + final NBTTagCompound nodeTag = new NBTTagCompound(); + nodeTag.setInteger(TAG_NODE_TICK, node.getTick()); + + final NBTTagList contentListTag = new NBTTagList(); + for (final T nodeData : node.getData()) { + contentListTag.appendTag(SerialUtils.serializeWrappedData(nodeData.getSerialWrapper(), nodeData)); + } + nodeTag.setTag(TAG_NODE_CONTENTS, contentListTag); + return nodeTag; + } + + private > Node> unserializeNode(final NBTTagCompound tag) { + final Node> node = new Node>(tag.getInteger(TAG_NODE_TICK), new LinkedList()); + + final NBTTagList contentListTag = tag.getTagList(TAG_NODE_CONTENTS, NBT.TAG_COMPOUND); + for (int i = 0; i < contentListTag.tagCount(); i++) { + try { + final T data = SerialUtils.unserializeWrappedData(contentListTag.getCompoundTagAt(i)); + node.getData().add(data); + } catch (ForgeCreeperHealerSerialException e) { + ForgeCreeperHeal.getLogger().error("Error while unserialize data : " + e.getMessage()); + } + } + + return node; + } + } diff --git a/src/main/java/fr/eyzox/minecraft/util/ChunkDataProvider.java b/src/main/java/fr/eyzox/minecraft/util/ChunkDataProvider.java index ba73ba3..a914b83 100644 --- a/src/main/java/fr/eyzox/minecraft/util/ChunkDataProvider.java +++ b/src/main/java/fr/eyzox/minecraft/util/ChunkDataProvider.java @@ -1,117 +1,117 @@ package fr.eyzox.minecraft.util; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.chunk.Chunk; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + + +public class ChunkDataProvider extends ConcurrentHashMap { + private static final String NULL_KEY = "Null key is not allowed"; + private static final String CLASS_KEYS = "Key should be a " + ChunkPos.class.getCanonicalName(); + + private Long2ObjectOpenHashMap map = new Long2ObjectOpenHashMap(); + + @Override + public void clear() { + super.clear(); + map.clear(); + map.trim(); + } + + @Override + public Object clone() throws CloneNotSupportedException { + final ChunkDataProvider clone = (ChunkDataProvider) super.clone(); + final Long2ObjectOpenHashMap map = new Long2ObjectOpenHashMap(); + for (final Map.Entry entry : this.entrySet()) { + map.put(this.getMapKey(entry.getKey()), entry.getValue()); + } + clone.map = map; + return clone; + } + + @Override + public E put(ChunkPos key, E value) { + if (key == null) { + throw new NullPointerException(NULL_KEY); + } + map.put(this.getMapKey(key), value); + return super.put(key, value); + } + + public E put(Chunk chunk, E value) { + if (chunk == null) { + throw new NullPointerException(NULL_KEY); + } + return this.put(chunk.getPos(), value); + } + + @Override + public E remove(Object key) { + if (key == null) { + throw new NullPointerException(NULL_KEY); + } + + if (key instanceof ChunkPos) { + return this.remove((ChunkPos) key); + } + + if (key instanceof Chunk) { + return this.remove((Chunk) key); + } + + throw new ClassCastException(CLASS_KEYS); + + } + + public E remove(ChunkPos chunk) { + if (chunk == null) { + throw new NullPointerException(NULL_KEY); + } + map.remove(this.getMapKey((ChunkPos) chunk)); + return super.remove(chunk); + } + + public E remove(Chunk chunk) { + if (chunk == null) { + throw new NullPointerException(NULL_KEY); + } + + if (map.remove(this.getMapKey(chunk)) != null) { + return super.remove(chunk.getPos()); + } else { + return null; + } + } + + public boolean containsKey(final long key) { + return map.containsKey(key); + } + + public boolean containsKey(final Chunk chunk) { + return containsKey(this.getMapKey(chunk)); + } + + public E get(final long key) { + return map.get(key); + } + + public E get(final Chunk chunk) { + return this.get(this.getMapKey(chunk)); + } + + public Long2ObjectMap getLong2ObjectMap() { + return map; + } + + private long getMapKey(final ChunkPos chunk) { + return ChunkPos.asLong(chunk.chunkXPos, chunk.chunkZPos); + } -public class ChunkDataProvider extends ConcurrentHashMap{ - private static final String NULL_KEY = "Null key is not allowed"; - private static final String CLASS_KEYS = "Key should be a "+ChunkPos.class.getCanonicalName(); - - private Long2ObjectOpenHashMap map = new Long2ObjectOpenHashMap(); - - @Override - public void clear() { - super.clear(); - map.clear(); - map.trim(); - } - - @Override - public Object clone() throws CloneNotSupportedException { - final ChunkDataProvider clone = (ChunkDataProvider) super.clone(); - final Long2ObjectOpenHashMap map = new Long2ObjectOpenHashMap(); - for(final Map.Entry entry : this.entrySet()) { - map.put(this.getMapKey(entry.getKey()), entry.getValue()); - } - clone.map = map; - return clone; - } - - @Override - public E put(ChunkPos key, E value) { - if(key == null) { - throw new NullPointerException(NULL_KEY); - } - map.put(this.getMapKey(key), value); - return super.put(key, value); - } - - public E put(Chunk chunk, E value) { - if(chunk == null) { - throw new NullPointerException(NULL_KEY); - } - return this.put(chunk.getPos(), value); - } - - @Override - public E remove(Object key) { - if(key == null) { - throw new NullPointerException(NULL_KEY); - } - - if(key instanceof ChunkPos) { - return this.remove((ChunkPos)key); - } - - if(key instanceof Chunk) { - return this.remove((Chunk)key); - } - - throw new ClassCastException(CLASS_KEYS); - - } - - public E remove(ChunkPos chunk) { - if(chunk == null) { - throw new NullPointerException(NULL_KEY); - } - map.remove(this.getMapKey((ChunkPos)chunk)); - return super.remove(chunk); - } - - public E remove(Chunk chunk) { - if(chunk == null) { - throw new NullPointerException(NULL_KEY); - } - - if(map.remove(this.getMapKey(chunk)) != null) { - return super.remove(chunk.getPos()); - }else { - return null; - } - } - - public boolean containsKey(final long key) { - return map.containsKey(key); - } - - public boolean containsKey(final Chunk chunk) { - return containsKey(this.getMapKey(chunk)); - } - - public E get(final long key) { - return map.get(key); - } - - public E get(final Chunk chunk) { - return this.get(this.getMapKey(chunk)); - } - - public Long2ObjectMap getLong2ObjectMap() { - return map; - } - - private long getMapKey(final ChunkPos chunk) { - return ChunkPos.asLong(chunk.chunkXPos, chunk.chunkZPos); - } - - private long getMapKey(final Chunk chunk) { - return ChunkPos.asLong(chunk.xPosition, chunk.zPosition); - } + private long getMapKey(final Chunk chunk) { + return ChunkPos.asLong(chunk.xPosition, chunk.zPosition); + } } diff --git a/src/main/java/fr/eyzox/ticktimeline/Node.java b/src/main/java/fr/eyzox/ticktimeline/Node.java index a5eb39a..faa8aa7 100644 --- a/src/main/java/fr/eyzox/ticktimeline/Node.java +++ b/src/main/java/fr/eyzox/ticktimeline/Node.java @@ -1,59 +1,61 @@ package fr.eyzox.ticktimeline; public class Node { - - private int tick; - private final W data; - - public Node(W data) { - this(0, data); - } - - public Node(int tick, W data) { - this.tick = tick; - this.data = data; - } - - public int getTick() { - return tick; - } - public void setTick(final int tick) { - this.tick = tick < 1 ? 0 : tick; - } - public W getData() { - return data; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result + tick; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Node other = (Node) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (tick != other.tick) - return false; - return true; - } - - @Override - public String toString() { - return new StringBuilder("[tick=").append(tick).append(", data=").append(data).append("]").toString(); - } + + private final W data; + private int tick; + + public Node(W data) { + this(0, data); + } + + public Node(int tick, W data) { + this.tick = tick; + this.data = data; + } + + public int getTick() { + return tick; + } + + public void setTick(final int tick) { + this.tick = tick < 1 ? 0 : tick; + } + + public W getData() { + return data; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + tick; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Node other = (Node) obj; + if (data == null) { + if (other.data != null) + return false; + } else if (!data.equals(other.data)) + return false; + if (tick != other.tick) + return false; + return true; + } + + @Override + public String toString() { + return new StringBuilder("[tick=").append(tick).append(", data=").append(data).append("]").toString(); + } } diff --git a/src/main/java/fr/eyzox/ticktimeline/TickTimeline.java b/src/main/java/fr/eyzox/ticktimeline/TickTimeline.java index f423e03..a634c37 100644 --- a/src/main/java/fr/eyzox/ticktimeline/TickTimeline.java +++ b/src/main/java/fr/eyzox/ticktimeline/TickTimeline.java @@ -7,114 +7,112 @@ public class TickTimeline { - private final List>> timeline; - - public TickTimeline() { - this(new LinkedList>>()); - } - - public TickTimeline(List>> timeline) { - this.timeline = timeline; - } - - public void add(final Node data) { - this.add(timeline.listIterator(), data); - } - - /** - * - * @param dataCollection MUST BE SORTED - * - * Example : - * We'll use letters for data. - * Input : {(1,A), (1,B), (3,C), (2,D)} - * Output : - * A -> 1 tick - * B -> 2 ticks (A ticks + B ticks) - * C -> 5 ticks (A ticks + B ticks + C ticks) - * D -> 7 ticks (A ticks + B ticks + C ticks + D ticks) - * - */ - public void add(final Collection> dataCollection) { - final ListIterator>> timelineIterator = timeline.listIterator(); - for(final Node data : dataCollection) { - this.add(timelineIterator, data); - } - } - - protected void add(final ListIterator>> timelineIterator, final Node toAdd) { - - int tick = toAdd.getTick() < 1 ? 0 : toAdd.getTick(); - final DATA data = toAdd.getData(); - - //Find Node - Node> container = null; - - if(tick == 0 && timelineIterator.hasPrevious()) { - container = timelineIterator.previous(); - timelineIterator.next(); - }else { - - while(container == null && timelineIterator.hasNext()){ - Node> current = timelineIterator.next(); - - int diff = tick - current.getTick(); - - if(diff > 0) { - tick = diff; - }else if(diff == 0) { - container = current; - }else { - container = new Node>(tick, new LinkedList()); - timelineIterator.set(container); - current.setTick(current.getTick()-tick); - timelineIterator.add(current); - } - } - - if(container == null) { - container = new Node>(tick, new LinkedList()); - timelineIterator.add(container); - //timelineIterator.next(); - } - - } - - container.getData().add(data); - } - - public List>> getTimeline() { - return timeline; - } - - public Collection tick() { - if(timeline.isEmpty()) { - return null; - } - - final Node> container = timeline.get(0); - if(container.getTick() > 1) { - container.setTick(container.getTick()-1); - return null; - } - - timeline.remove(0); - return container.getData(); - } - - public boolean isEmpty() { - return timeline.isEmpty(); - } - - @Override - public String toString() { - final StringBuilder s = new StringBuilder(); - s.append("{"); - for(final Node> node : this.timeline) { - s.append(node.toString()); - } - s.append("}"); - return s.toString(); - } + private final List>> timeline; + + public TickTimeline() { + this(new LinkedList>>()); + } + + public TickTimeline(List>> timeline) { + this.timeline = timeline; + } + + public void add(final Node data) { + this.add(timeline.listIterator(), data); + } + + /** + * @param dataCollection MUST BE SORTED + *

+ * Example : + * We'll use letters for data. + * Input : {(1,A), (1,B), (3,C), (2,D)} + * Output : + * A -> 1 tick + * B -> 2 ticks (A ticks + B ticks) + * C -> 5 ticks (A ticks + B ticks + C ticks) + * D -> 7 ticks (A ticks + B ticks + C ticks + D ticks) + */ + public void add(final Collection> dataCollection) { + final ListIterator>> timelineIterator = timeline.listIterator(); + for (final Node data : dataCollection) { + this.add(timelineIterator, data); + } + } + + protected void add(final ListIterator>> timelineIterator, final Node toAdd) { + + int tick = toAdd.getTick() < 1 ? 0 : toAdd.getTick(); + final DATA data = toAdd.getData(); + + //Find Node + Node> container = null; + + if (tick == 0 && timelineIterator.hasPrevious()) { + container = timelineIterator.previous(); + timelineIterator.next(); + } else { + + while (container == null && timelineIterator.hasNext()) { + Node> current = timelineIterator.next(); + + int diff = tick - current.getTick(); + + if (diff > 0) { + tick = diff; + } else if (diff == 0) { + container = current; + } else { + container = new Node>(tick, new LinkedList()); + timelineIterator.set(container); + current.setTick(current.getTick() - tick); + timelineIterator.add(current); + } + } + + if (container == null) { + container = new Node>(tick, new LinkedList()); + timelineIterator.add(container); + //timelineIterator.next(); + } + + } + + container.getData().add(data); + } + + public List>> getTimeline() { + return timeline; + } + + public Collection tick() { + if (timeline.isEmpty()) { + return null; + } + + final Node> container = timeline.get(0); + if (container.getTick() > 1) { + container.setTick(container.getTick() - 1); + return null; + } + + timeline.remove(0); + return container.getData(); + } + + public boolean isEmpty() { + return timeline.isEmpty(); + } + + @Override + public String toString() { + final StringBuilder s = new StringBuilder(); + s.append("{"); + for (final Node> node : this.timeline) { + s.append(node.toString()); + } + s.append("}"); + return s.toString(); + } }