Browse Source

Dépôt des sources

boozaa 4 years ago
commit
b654ec33c6
25 changed files with 3312 additions and 0 deletions
  1. 215 0
      .gitignore
  2. 96 0
      dependency-reduced-pom.xml
  3. BIN
      lib/commons-lang-2.3.jar
  4. BIN
      lib/guava-10.0.1.jar
  5. BIN
      lib/snakeyaml-1.9.jar
  6. 118 0
      pom.xml
  7. 82 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/Configuration.java
  8. 93 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationFile.java
  9. 81 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationOptions.java
  10. 608 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationSection.java
  11. 35 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationSerializable.java
  12. 258 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationSerialization.java
  13. 40 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/InvalidConfigurationException.java
  14. 79 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/MemoryConfiguration.java
  15. 27 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/MemoryConfigurationOptions.java
  16. 748 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/MemorySection.java
  17. 193 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/file/FileConfiguration.java
  18. 110 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/file/FileConfigurationOptions.java
  19. 23 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/serialization/DelegateDeserialization.java
  20. 35 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/serialization/SerializableAs.java
  21. 213 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/serialization/YamlConfiguration.java
  22. 71 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/serialization/YamlConfigurationOptions.java
  23. 49 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/serialization/YamlConstructor.java
  24. 38 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/serialization/YamlRepresenter.java
  25. 100 0
      src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/utils/NumberConversions.java

+ 215 - 0
.gitignore

@ -0,0 +1,215 @@
1
#################
2
## Eclipse
3
#################
4

													
5
*.pydevproject
6
.project
7
.metadata
8
bin/
9
tmp/
10
*.tmp
11
*.bak
12
*.swp
13
*~.nib
14
local.properties
15
.classpath
16
.settings/
17
.loadpath
18

													
19
# External tool builders
20
.externalToolBuilders/
21

													
22
# Locally stored "Eclipse launch configurations"
23
*.launch
24

													
25
# CDT-specific
26
.cproject
27

													
28
# PDT-specific
29
.buildpath
30

													
31

													
32
#################
33
## Visual Studio
34
#################
35

													
36
## Ignore Visual Studio temporary files, build results, and
37
## files generated by popular Visual Studio add-ons.
38

													
39
# User-specific files
40
*.suo
41
*.user
42
*.sln.docstates
43

													
44
# Build results
45

													
46
[Dd]ebug/
47
[Rr]elease/
48
x64/
49
build/
50
[Bb]in/
51
[Oo]bj/
52

													
53
# MSTest test Results
54
[Tt]est[Rr]esult*/
55
[Bb]uild[Ll]og.*
56

													
57
*_i.c
58
*_p.c
59
*.ilk
60
*.meta
61
*.obj
62
*.pch
63
*.pdb
64
*.pgc
65
*.pgd
66
*.rsp
67
*.sbr
68
*.tlb
69
*.tli
70
*.tlh
71
*.tmp
72
*.tmp_proj
73
*.log
74
*.vspscc
75
*.vssscc
76
.builds
77
*.pidb
78
*.log
79
*.scc
80

													
81
# Visual C++ cache files
82
ipch/
83
*.aps
84
*.ncb
85
*.opensdf
86
*.sdf
87
*.cachefile
88

													
89
# Visual Studio profiler
90
*.psess
91
*.vsp
92
*.vspx
93

													
94
# Guidance Automation Toolkit
95
*.gpState
96

													
97
# ReSharper is a .NET coding add-in
98
_ReSharper*/
99
*.[Rr]e[Ss]harper
100

													
101
# TeamCity is a build add-in
102
_TeamCity*
103

													
104
# DotCover is a Code Coverage Tool
105
*.dotCover
106

													
107
# NCrunch
108
*.ncrunch*
109
.*crunch*.local.xml
110

													
111
# Installshield output folder
112
[Ee]xpress/
113

													
114
# DocProject is a documentation generator add-in
115
DocProject/buildhelp/
116
DocProject/Help/*.HxT
117
DocProject/Help/*.HxC
118
DocProject/Help/*.hhc
119
DocProject/Help/*.hhk
120
DocProject/Help/*.hhp
121
DocProject/Help/Html2
122
DocProject/Help/html
123

													
124
# Click-Once directory
125
publish/
126

													
127
# Publish Web Output
128
*.Publish.xml
129
*.pubxml
130

													
131
# NuGet Packages Directory
132
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
133
#packages/
134

													
135
# Windows Azure Build Output
136
csx
137
*.build.csdef
138

													
139
# Windows Store app package directory
140
AppPackages/
141

													
142
# Others
143
sql/
144
*.Cache
145
ClientBin/
146
[Ss]tyle[Cc]op.*
147
~$*
148
*~
149
*.dbmdl
150
*.[Pp]ublish.xml
151
*.pfx
152
*.publishsettings
153

													
154
# RIA/Silverlight projects
155
Generated_Code/
156

													
157
# Backup & report files from converting an old project file to a newer
158
# Visual Studio version. Backup files are not needed, because we have git ;-)
159
_UpgradeReport_Files/
160
Backup*/
161
UpgradeLog*.XML
162
UpgradeLog*.htm
163

													
164
# SQL Server files
165
App_Data/*.mdf
166
App_Data/*.ldf
167

													
168
#############
169
## Windows detritus
170
#############
171

													
172
# Windows image file caches
173
Thumbs.db
174
ehthumbs.db
175

													
176
# Folder config file
177
Desktop.ini
178

													
179
# Recycle Bin used on file shares
180
$RECYCLE.BIN/
181

													
182
# Mac crap
183
.DS_Store
184

													
185

													
186
#############
187
## Python
188
#############
189

													
190
*.py[co]
191

													
192
# Packages
193
*.egg
194
*.egg-info
195
dist/
196
build/
197
eggs/
198
parts/
199
var/
200
sdist/
201
develop-eggs/
202
.installed.cfg
203

													
204
# Installer logs
205
pip-log.txt
206

													
207
# Unit test / coverage reports
208
.coverage
209
.tox
210

													
211
#Translations
212
*.mo
213

													
214
#Mr Developer
215
.mr.developer.cfg

+ 96 - 0
dependency-reduced-pom.xml

@ -0,0 +1,96 @@
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3
  <modelVersion>4.0.0</modelVersion>
4
  <groupId>org.shortrip.boozaa.libs</groupId>
5
  <artifactId>YAMLConfiguration</artifactId>
6
  <name>YAMLConfiguration</name>
7
  <version>1.0</version>
8
  <build>
9
    <resources>
10
      <resource>
11
        <directory>src/main/resources</directory>
12
      </resource>
13
    </resources>
14
    <plugins>
15
      <plugin>
16
        <artifactId>maven-compiler-plugin</artifactId>
17
        <version>2.0.2</version>
18
        <configuration>
19
          <source>1.5</source>
20
          <target>1.5</target>
21
        </configuration>
22
      </plugin>
23
      <plugin>
24
        <artifactId>maven-dependency-plugin</artifactId>
25
        <executions>
26
          <execution>
27
            <phase>install</phase>
28
            <goals>
29
              <goal>copy-dependencies</goal>
30
            </goals>
31
            <configuration>
32
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
33
            </configuration>
34
          </execution>
35
        </executions>
36
      </plugin>
37
      <plugin>
38
        <artifactId>maven-shade-plugin</artifactId>
39
        <executions>
40
          <execution>
41
            <phase>package</phase>
42
            <goals>
43
              <goal>shade</goal>
44
            </goals>
45
            <configuration>
46
              <relocations>
47
                <relocation>
48
                  <pattern>org.apache.commons</pattern>
49
                  <shadedPattern>org.shortrip.boozaa.libs.commons</shadedPattern>
50
                </relocation>
51
                <relocation>
52
                  <pattern>com.google.common</pattern>
53
                  <shadedPattern>org.shortrip.boozaa.libs.commons</shadedPattern>
54
                </relocation>
55
                <relocation>
56
                  <pattern>org.yaml.snakeyaml</pattern>
57
                  <shadedPattern>org.shortrip.boozaa.libs.snakeyaml</shadedPattern>
58
                </relocation>
59
                <relocation>
60
                  <pattern>javax</pattern>
61
                  <shadedPattern>org.shortrip.boozaa.libs.javax</shadedPattern>
62
                </relocation>
63
              </relocations>
64
            </configuration>
65
          </execution>
66
        </executions>
67
        <configuration>
68
          <finalName>${project.artifactId}-${project.version}</finalName>
69
        </configuration>
70
      </plugin>
71
    </plugins>
72
  </build>
73
  <repositories>
74
    <repository>
75
      <snapshots>
76
        <enabled>false</enabled>
77
      </snapshots>
78
      <id>central</id>
79
      <name>Maven Repository Switchboard</name>
80
      <url>http://repo1.maven.org/maven2</url>
81
    </repository>
82
    <repository>
83
      <id>google-releases</id>
84
      <name>Google Releases</name>
85
      <url>https://oss.sonatype.org/content/repositories/google-releases</url>
86
    </repository>
87
    <repository>
88
      <id>shortrip-repo</id>
89
      <url>http://shortrip.org/maven</url>
90
    </repository>
91
  </repositories>
92
  <properties>
93
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
94
  </properties>
95
</project>
96

													

BIN
lib/commons-lang-2.3.jar


BIN
lib/guava-10.0.1.jar


BIN
lib/snakeyaml-1.9.jar


+ 118 - 0
pom.xml

@ -0,0 +1,118 @@
1
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2
    <modelVersion>4.0.0</modelVersion>
3
    <groupId>org.shortrip.boozaa.libs</groupId>
4
    <artifactId>YAMLConfiguration</artifactId>
5
    <version>1.0</version>
6
    <name>YAMLConfiguration</name>
7
    <repositories>
8
        <repository>
9
            <id>central</id>
10
            <name>Maven Repository Switchboard</name>
11
            <layout>default</layout>
12
            <url>http://repo1.maven.org/maven2</url>
13
            <snapshots>
14
                <enabled>false</enabled>
15
            </snapshots>
16
        </repository>
17
        <repository>
18
            <id>google-releases</id>
19
            <name>Google Releases</name>
20
            <url>https://oss.sonatype.org/content/repositories/google-releases</url>
21
        </repository>
22
        <repository>
23
            <id>shortrip-repo</id>
24
            <url>http://shortrip.org/maven</url>
25
        </repository>
26
    </repositories>
27
    <properties>
28
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
29
    </properties>
30
    <build>
31
        <plugins>
32
            <plugin>
33
                <groupId>org.apache.maven.plugins</groupId>
34
                <artifactId>maven-compiler-plugin</artifactId>
35
                <version>2.0.2</version>
36
                <configuration>
37
                    <source>1.5</source>
38
                    <target>1.5</target>
39
                </configuration>
40
            </plugin>
41
            <plugin>
42
            	<artifactId>maven-dependency-plugin</artifactId>
43
            	<executions>
44
                	<execution>
45
                    	<phase>install</phase>
46
                        <goals>
47
                        	<goal>copy-dependencies</goal>
48
                        </goals>
49
                        <configuration>
50
                        	<outputDirectory>${project.build.directory}/lib</outputDirectory>
51
                        </configuration>
52
                	</execution>
53
            	</executions>
54
            </plugin>
55
            <plugin>
56
                <groupId>org.apache.maven.plugins</groupId>
57
                <artifactId>maven-shade-plugin</artifactId>
58
                <executions>
59
                  <execution>
60
                    <phase>package</phase>
61
                    <goals>
62
                      <goal>shade</goal>
63
                    </goals>
64
                    <configuration>
65
                        <relocations>
66
                            <relocation>
67
                                <pattern>org.apache.commons</pattern>
68
                                <shadedPattern>org.shortrip.boozaa.libs.commons</shadedPattern>
69
                            </relocation>
70
                            <relocation>
71
                                <pattern>com.google.common</pattern>
72
                                <shadedPattern>org.shortrip.boozaa.libs.commons</shadedPattern>
73
                            </relocation>
74
                            <relocation>
75
                                <pattern>org.yaml.snakeyaml</pattern>
76
                                <shadedPattern>org.shortrip.boozaa.libs.snakeyaml</shadedPattern>
77
                            </relocation>
78
                            <relocation>
79
                                <pattern>javax</pattern>
80
                                <shadedPattern>org.shortrip.boozaa.libs.javax</shadedPattern>
81
                            </relocation>
82
                        </relocations>
83
                    </configuration>
84
                  </execution>
85
                </executions>
86
                <configuration>
87
                  <finalName>${project.artifactId}-${project.version}</finalName>                  
88
                </configuration>
89
            </plugin>
90
        </plugins>
91
        <resources>
92
            <resource>
93
                <directory>src/main/resources</directory>
94
            </resource>
95
        </resources>
96
    </build>
97
    <dependencies>
98
        <dependency>
99
            <groupId>org.yaml</groupId>
100
            <artifactId>snakeyaml</artifactId>
101
            <version>1.9</version>
102
            <type>jar</type>
103
            <scope>compile</scope>
104
        </dependency>
105
        <dependency>
106
            <groupId>com.google.guava</groupId>
107
            <artifactId>guava</artifactId>
108
            <version>10.0.1</version>
109
            <type>jar</type>
110
            <scope>compile</scope>
111
        </dependency>
112
        <dependency>
113
            <groupId>commons-lang</groupId>
114
            <artifactId>commons-lang</artifactId>
115
            <version>2.3</version>
116
        </dependency>
117
    </dependencies>
118
</project>

+ 82 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/Configuration.java

@ -0,0 +1,82 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3
import java.util.Map;
4

													
5
/**
6
 * Represents a source of configurable options and settings
7
 */
8
public interface Configuration extends ConfigurationSection {
9
    /**
10
     * Sets the default value of the given path as provided.
11
     * <p />
12
     * If no source {@link Configuration} was provided as a default collection,
13
     * then a new {@link MemoryConfiguration} will be created to hold the new default
14
     * value.
15
     * <p />
16
     * If value is null, the value will be removed from the default Configuration source.
17
     *
18
     * @param path Path of the value to set.
19
     * @param value Value to set the default to.
20
     * @throws IllegalArgumentException Thrown if path is null.
21
     */
22
    public void addDefault(String path, Object value);
23

													
24
    /**
25
     * Sets the default values of the given paths as provided.
26
     * <p />
27
     * If no source {@link Configuration} was provided as a default collection,
28
     * then a new {@link MemoryConfiguration} will be created to hold the new default
29
     * values.
30
     *
31
     * @param defaults A map of Path->Values to add to defaults.
32
     * @throws IllegalArgumentException Thrown if defaults is null.
33
     */
34
    public void addDefaults(Map<String, Object> defaults);
35

													
36
    /**
37
     * Sets the default values of the given paths as provided.
38
     * <p />
39
     * If no source {@link Configuration} was provided as a default collection,
40
     * then a new {@link MemoryConfiguration} will be created to hold the new default
41
     * value.
42
     * <p />
43
     * This method will not hold a reference to the specified Configuration, nor will it
44
     * automatically update if that Configuration ever changes. If you require this,
45
     * you should set the default source with {@link #setDefaults(org.bukkit.configuration.Configuration)}.
46
     *
47
     * @param defaults A configuration holding a list of defaults to copy.
48
     * @throws IllegalArgumentException Thrown if defaults is null or this.
49
     */
50
    public void addDefaults(Configuration defaults);
51

													
52
    /**
53
     * Sets the source of all default values for this {@link Configuration}.
54
     * <p />
55
     * If a previous source was set, or previous default values were defined, then they will
56
     * not be copied to the new source.
57
     *
58
     * @param defaults New source of default values for this configuration.
59
     * @throws IllegalArgumentException Thrown if defaults is null or this.
60
     */
61
    public void setDefaults(Configuration defaults);
62

													
63
    /**
64
     * Gets the source {@link Configuration} for this configuration.
65
     * <p />
66
     * If no configuration source was set, but default values were added, then a
67
     * {@link MemoryConfiguration} will be returned. If no source was set and no
68
     * defaults were set, then this method will return null.
69
     *
70
     * @return Configuration source for default values, or null if none exist.
71
     */
72
    public Configuration getDefaults();
73

													
74
    /**
75
     * Gets the {@link ConfigurationOptions} for this {@link Configuration}.
76
     * <p />
77
     * All setters through this method are chainable.
78
     *
79
     * @return Options for this configuration
80
     */
81
    public ConfigurationOptions options();
82
}

+ 93 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationFile.java

@ -0,0 +1,93 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3
import java.io.File;
4
import java.io.FileNotFoundException;
5
import java.util.ArrayList;
6
import java.util.HashSet;
7
import java.util.List;
8
import java.util.Set;
9
import org.shortrip.boozaa.libs.yamlconfiguration.serialization.YamlConfiguration;
10

													
11

													
12
public class ConfigurationFile extends YamlConfiguration {
13

													
14
private File source;
15
	
16
	
17
	
18
	public ConfigurationFile(String pluginName) {
19
		this( new File("plugins" + File.separator + pluginName + File.separator + "config.yml") );
20
	}
21
	public ConfigurationFile(File source) {
22
		this.source = source;
23
	}
24

													
25
	
26
	
27
	@SuppressWarnings("unchecked")
28
	public <T> T parse(String path, T def) {
29
		T rval = (T) this.get(path, def);
30
		this.set(path, rval);
31
		return rval;
32
	}
33
	
34
	public boolean exists() {
35
		return this.source.exists();
36
	}
37
	
38
	public void init() {
39
		this.load();
40
		this.save();
41
	}
42

													
43
	public void load() {
44
		try {
45
			this.load(this.source);
46
		} catch (FileNotFoundException ex) {
47
			System.out.println("File '" + this.source + "' was not found");
48
		} catch (Exception ex) {
49
			System.out.println("Error while loading file '" + this.source + "':");
50
			ex.printStackTrace();
51
		}
52
	}
53
	public void save() {
54
		try {
55
			//boolean regen = !this.exists();
56
			this.save(this.source);
57
			//if (regen) System.out.println("[BooKnowInactivePlayer] File '" + this.source + "' has been regenerated");
58
		} catch (Exception ex) {
59
			System.out.println("Error while saving to file '" + this.source + "':");
60
			ex.printStackTrace();
61
		}
62
	}
63
	
64
	public <T> List<T> getListOf(String path) {
65
		return this.getListOf(path, new ArrayList<T>());
66
	}
67
	
68
	@SuppressWarnings({ "unchecked", "rawtypes" })
69
	public <T> List<T> getListOf(String path, List<T> def) {
70
		List list = this.getList(path, null);
71
		if (list == null) {
72
			return def;
73
		} else {
74
			List<T> rval = new ArrayList<T>();
75
			for (Object object : this.getList(path)) {
76
				try {
77
					rval.add((T) object);
78
				} catch (Throwable t) {}
79
			}
80
			return rval;
81
		}
82
	}
83
	
84
	public Set<String> getKeys(String path) {
85
		try {
86
			return this.getConfigurationSection(path).getKeys(false);
87
		} catch (Exception ex) {
88
			return new HashSet<String>();
89
		}
90
	}
91
	
92
	
93
}

+ 81 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationOptions.java

@ -0,0 +1,81 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3
/**
4
 * Various settings for controlling the input and output of a {@link Configuration}
5
 */
6
public class ConfigurationOptions {
7
    private char pathSeparator = '.';
8
    private boolean copyDefaults = false;
9
    private final Configuration configuration;
10

													
11
    protected ConfigurationOptions(Configuration configuration) {
12
        this.configuration = configuration;
13
    }
14

													
15
    /**
16
     * Returns the {@link Configuration} that this object is responsible for.
17
     *
18
     * @return Parent configuration
19
     */
20
    public Configuration configuration() {
21
        return configuration;
22
    }
23

													
24
    /**
25
     * Gets the char that will be used to separate {@link ConfigurationSection}s
26
     * <p />
27
     * This value does not affect how the {@link Configuration} is stored, only in
28
     * how you access the data. The default value is '.'.
29
     *
30
     * @return Path separator
31
     */
32
    public char pathSeparator() {
33
        return pathSeparator;
34
    }
35

													
36
    /**
37
     * Sets the char that will be used to separate {@link ConfigurationSection}s
38
     * <p />
39
     * This value does not affect how the {@link Configuration} is stored, only in
40
     * how you access the data. The default value is '.'.
41
     *
42
     * @param value Path separator
43
     * @return This object, for chaining
44
     */
45
    public ConfigurationOptions pathSeparator(char value) {
46
        this.pathSeparator = value;
47
        return this;
48
    }
49

													
50
    /**
51
     * Checks if the {@link Configuration} should copy values from its default {@link Configuration} directly.
52
     * <p />
53
     * If this is true, all values in the default Configuration will be directly copied,
54
     * making it impossible to distinguish between values that were set and values that
55
     * are provided by default. As a result, {@link ConfigurationSection#contains(java.lang.String)} will always
56
     * return the same value as {@link ConfigurationSection#isSet(java.lang.String)}.
57
     * The default value is false.
58
     *
59
     * @return Whether or not defaults are directly copied
60
     */
61
    public boolean copyDefaults() {
62
        return copyDefaults;
63
    }
64

													
65
    /**
66
     * Sets if the {@link Configuration} should copy values from its default {@link Configuration} directly.
67
     * <p />
68
     * If this is true, all values in the default Configuration will be directly copied,
69
     * making it impossible to distinguish between values that were set and values that
70
     * are provided by default. As a result, {@link ConfigurationSection#contains(java.lang.String)} will always
71
     * return the same value as {@link ConfigurationSection#isSet(java.lang.String)}.
72
     * The default value is false.
73
     *
74
     * @param value Whether or not defaults are directly copied
75
     * @return This object, for chaining
76
     */
77
    public ConfigurationOptions copyDefaults(boolean value) {
78
        this.copyDefaults = value;
79
        return this;
80
    }
81
}

+ 608 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationSection.java

@ -0,0 +1,608 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3
import java.util.Map;
4
import java.util.Set;
5
import java.util.List;
6

													
7

													
8
/**
9
 * Represents a section of a {@link Configuration}
10
 */
11
public interface ConfigurationSection {
12
    /**
13
     * Gets a set containing all keys in this section.
14
     * <p />
15
     * If deep is set to true, then this will contain all the keys within any child
16
     * {@link ConfigurationSection}s (and their children, etc). These will be in a
17
     * valid path notation for you to use.
18
     * <p />
19
     * If deep is set to false, then this will contain only the keys of any direct children,
20
     * and not their own children.
21
     *
22
     * @param deep Whether or not to get a deep list, as opposed to a shallow list.
23
     * @return Set of keys contained within this ConfigurationSection.
24
     */
25
    public Set<String> getKeys(boolean deep);
26

													
27
    /**
28
     * Gets a Map containing all keys and their values for this section.
29
     * <p />
30
     * If deep is set to true, then this will contain all the keys and values within
31
     * any child {@link ConfigurationSection}s (and their children, etc). These
32
     * keys will be in a valid path notation for you to use.
33
     * <p />
34
     * If deep is set to false, then this will contain only the keys and values of any
35
     * direct children, and not their own children.
36
     *
37
     * @param deep Whether or not to get a deep list, as opposed to a shallow list.
38
     * @return Map of keys and values of this section.
39
     */
40
    public Map<String, Object> getValues(boolean deep);
41

													
42
    /**
43
     * Checks if this {@link ConfigurationSection} contains the given path.
44
     * <p />
45
     * If the value for the requested path does not exist but a default value has
46
     * been specified, this will return true.
47
     *
48
     * @param path Path to check for existence.
49
     * @return True if this section contains the requested path, either via default or being set.
50
     * @throws IllegalArgumentException Thrown when path is null.
51
     */
52
    public boolean contains(String path);
53

													
54
    /**
55
     * Checks if this {@link ConfigurationSection} has a value set for the given path.
56
     * <p />
57
     * If the value for the requested path does not exist but a default value has
58
     * been specified, this will still return false.
59
     *
60
     * @param path Path to check for existence.
61
     * @return True if this section contains the requested path, regardless of having a default.
62
     * @throws IllegalArgumentException Thrown when path is null.
63
     */
64
    public boolean isSet(String path);
65

													
66
    /**
67
     * Gets the path of this {@link ConfigurationSection} from its root {@link Configuration}
68
     * <p />
69
     * For any {@link Configuration} themselves, this will return an empty string.
70
     * <p />
71
     * If the section is no longer contained within its root for any reason, such as
72
     * being replaced with a different value, this may return null.
73
     * <p />
74
     * To retrieve the single name of this section, that is, the final part of the path
75
     * returned by this method, you may use {@link #getName()}.
76
     *
77
     * @return Path of this section relative to its root
78
     */
79
    public String getCurrentPath();
80

													
81
    /**
82
     * Gets the name of this individual {@link ConfigurationSection}, in the path.
83
     * <p />
84
     * This will always be the final part of {@link #getCurrentPath()}, unless the
85
     * section is orphaned.
86
     *
87
     * @return Name of this section
88
     */
89
    public String getName();
90

													
91
    /**
92
     * Gets the root {@link Configuration} that contains this {@link ConfigurationSection}
93
     * <p />
94
     * For any {@link Configuration} themselves, this will return its own object.
95
     * <p />
96
     * If the section is no longer contained within its root for any reason, such as
97
     * being replaced with a different value, this may return null.
98
     *
99
     * @return Root configuration containing this section.
100
     */
101
    public Configuration getRoot();
102

													
103
    /**
104
     * Gets the parent {@link ConfigurationSection} that directly contains this
105
     * {@link ConfigurationSection}.
106
     * <p />
107
     * For any {@link Configuration} themselves, this will return null.
108
     * <p />
109
     * If the section is no longer contained within its parent for any reason, such as
110
     * being replaced with a different value, this may return null.
111
     *
112
     * @return Parent section containing this section.
113
     */
114
    public ConfigurationSection getParent();
115

													
116
    /**
117
     * Gets the requested Object by path.
118
     * <p />
119
     * If the Object does not exist but a default value has been specified, this
120
     * will return the default value. If the Object does not exist and no default
121
     * value was specified, this will return null.
122
     *
123
     * @param path Path of the Object to get.
124
     * @return Requested Object.
125
     */
126
    public Object get(String path);
127

													
128
    /**
129
     * Gets the requested Object by path, returning a default value if not found.
130
     * <p />
131
     * If the Object does not exist then the specified default value will returned
132
     * regardless of if a default has been identified in the root {@link Configuration}.
133
     *
134
     * @param path Path of the Object to get.
135
     * @param def The default value to return if the path is not found.
136
     * @return Requested Object.
137
     */
138
    public Object get(String path, Object def);
139

													
140
    /**
141
     * Sets the specified path to the given value.
142
     * <p />
143
     * If value is null, the entry will be removed. Any existing entry will be
144
     * replaced, regardless of what the new value is.
145
     * <p />
146
     * Some implementations may have limitations on what you may store. See their
147
     * individual javadocs for details. No implementations should allow you to store
148
     * {@link Configuration}s or {@link ConfigurationSection}s, please use
149
     * {@link #createSection(java.lang.String)} for that.
150
     *
151
     * @param path Path of the object to set.
152
     * @param value New value to set the path to.
153
     */
154
    public void set(String path, Object value);
155

													
156
    /**
157
     * Creates an empty {@link ConfigurationSection} at the specified path.
158
     * <p />
159
     * Any value that was previously set at this path will be overwritten. If the
160
     * previous value was itself a {@link ConfigurationSection}, it will be orphaned.
161
     *
162
     * @param path Path to create the section at.
163
     * @return Newly created section
164
     */
165
    public ConfigurationSection createSection(String path);
166

													
167
    /**
168
     * Creates a {@link ConfigurationSection} at the specified path, with specified values.
169
     * <p />
170
     * Any value that was previously set at this path will be overwritten. If the
171
     * previous value was itself a {@link ConfigurationSection}, it will be orphaned.
172
     *
173
     * @param path Path to create the section at.
174
     * @param map The values to used.
175
     * @return Newly created section
176
     */
177
    public ConfigurationSection createSection(String path, Map<?, ?> map);
178

													
179
    // Primitives
180
    /**
181
     * Gets the requested String by path.
182
     * <p />
183
     * If the String does not exist but a default value has been specified, this
184
     * will return the default value. If the String does not exist and no default
185
     * value was specified, this will return null.
186
     *
187
     * @param path Path of the String to get.
188
     * @return Requested String.
189
     */
190
    public String getString(String path);
191

													
192
    /**
193
     * Gets the requested String by path, returning a default value if not found.
194
     * <p />
195
     * If the String does not exist then the specified default value will returned
196
     * regardless of if a default has been identified in the root {@link Configuration}.
197
     *
198
     * @param path Path of the String to get.
199
     * @param def The default value to return if the path is not found or is not a String.
200
     * @return Requested String.
201
     */
202
    public String getString(String path, String def);
203

													
204
    /**
205
     * Checks if the specified path is a String.
206
     * <p />
207
     * If the path exists but is not a String, this will return false. If the path does not
208
     * exist, this will return false. If the path does not exist but a default value
209
     * has been specified, this will check if that default value is a String and return
210
     * appropriately.
211
     *
212
     * @param path Path of the String to check.
213
     * @return Whether or not the specified path is a String.
214
     */
215
    public boolean isString(String path);
216

													
217
    /**
218
     * Gets the requested int by path.
219
     * <p />
220
     * If the int does not exist but a default value has been specified, this
221
     * will return the default value. If the int does not exist and no default
222
     * value was specified, this will return 0.
223
     *
224
     * @param path Path of the int to get.
225
     * @return Requested int.
226
     */
227
    public int getInt(String path);
228

													
229
    /**
230
     * Gets the requested int by path, returning a default value if not found.
231
     * <p />
232
     * If the int does not exist then the specified default value will returned
233
     * regardless of if a default has been identified in the root {@link Configuration}.
234
     *
235
     * @param path Path of the int to get.
236
     * @param def The default value to return if the path is not found or is not an int.
237
     * @return Requested int.
238
     */
239
    public int getInt(String path, int def);
240

													
241
    /**
242
     * Checks if the specified path is an int.
243
     * <p />
244
     * If the path exists but is not a int, this will return false. If the path does not
245
     * exist, this will return false. If the path does not exist but a default value
246
     * has been specified, this will check if that default value is a int and return
247
     * appropriately.
248
     *
249
     * @param path Path of the int to check.
250
     * @return Whether or not the specified path is an int.
251
     */
252
    public boolean isInt(String path);
253

													
254
    /**
255
     * Gets the requested boolean by path.
256
     * <p />
257
     * If the boolean does not exist but a default value has been specified, this
258
     * will return the default value. If the boolean does not exist and no default
259
     * value was specified, this will return false.
260
     *
261
     * @param path Path of the boolean to get.
262
     * @return Requested boolean.
263
     */
264
    public boolean getBoolean(String path);
265

													
266
    /**
267
     * Gets the requested boolean by path, returning a default value if not found.
268
     * <p />
269
     * If the boolean does not exist then the specified default value will returned
270
     * regardless of if a default has been identified in the root {@link Configuration}.
271
     *
272
     * @param path Path of the boolean to get.
273
     * @param def The default value to return if the path is not found or is not a boolean.
274
     * @return Requested boolean.
275
     */
276
    public boolean getBoolean(String path, boolean def);
277

													
278
    /**
279
     * Checks if the specified path is a boolean.
280
     * <p />
281
     * If the path exists but is not a boolean, this will return false. If the path does not
282
     * exist, this will return false. If the path does not exist but a default value
283
     * has been specified, this will check if that default value is a boolean and return
284
     * appropriately.
285
     *
286
     * @param path Path of the boolean to check.
287
     * @return Whether or not the specified path is a boolean.
288
     */
289
    public boolean isBoolean(String path);
290

													
291
    /**
292
     * Gets the requested double by path.
293
     * <p />
294
     * If the double does not exist but a default value has been specified, this
295
     * will return the default value. If the double does not exist and no default
296
     * value was specified, this will return null.
297
     *
298
     * @param path Path of the double to get.
299
     * @return Requested double.
300
     */
301
    public double getDouble(String path);
302

													
303
    /**
304
     * Gets the requested double by path, returning a default value if not found.
305
     * <p />
306
     * If the double does not exist then the specified default value will returned
307
     * regardless of if a default has been identified in the root {@link Configuration}.
308
     *
309
     * @param path Path of the double to get.
310
     * @param def The default value to return if the path is not found or is not a double.
311
     * @return Requested double.
312
     */
313
    public double getDouble(String path, double def);
314

													
315
    /**
316
     * Checks if the specified path is a double.
317
     * <p />
318
     * If the path exists but is not a double, this will return false. If the path does not
319
     * exist, this will return false. If the path does not exist but a default value
320
     * has been specified, this will check if that default value is a double and return
321
     * appropriately.
322
     *
323
     * @param path Path of the double to check.
324
     * @return Whether or not the specified path is a double.
325
     */
326
    public boolean isDouble(String path);
327

													
328
    /**
329
     * Gets the requested long by path.
330
     * <p />
331
     * If the long does not exist but a default value has been specified, this
332
     * will return the default value. If the long does not exist and no default
333
     * value was specified, this will return null.
334
     *
335
     * @param path Path of the long to get.
336
     * @return Requested long.
337
     */
338
    public long getLong(String path);
339

													
340
    /**
341
     * Gets the requested long by path, returning a default value if not found.
342
     * <p />
343
     * If the long does not exist then the specified default value will returned
344
     * regardless of if a default has been identified in the root {@link Configuration}.
345
     *
346
     * @param path Path of the long to get.
347
     * @param def The default value to return if the path is not found or is not a long.
348
     * @return Requested long.
349
     */
350
    public long getLong(String path, long def);
351

													
352
    /**
353
     * Checks if the specified path is a long.
354
     * <p />
355
     * If the path exists but is not a long, this will return false. If the path does not
356
     * exist, this will return false. If the path does not exist but a default value
357
     * has been specified, this will check if that default value is a long and return
358
     * appropriately.
359
     *
360
     * @param path Path of the long to check.
361
     * @return Whether or not the specified path is a long.
362
     */
363
    public boolean isLong(String path);
364

													
365
    // Java
366
    /**
367
     * Gets the requested List by path.
368
     * <p />
369
     * If the List does not exist but a default value has been specified, this
370
     * will return the default value. If the List does not exist and no default
371
     * value was specified, this will return null.
372
     *
373
     * @param path Path of the List to get.
374
     * @return Requested List.
375
     */
376
    public List<?> getList(String path);
377

													
378
    /**
379
     * Gets the requested List by path, returning a default value if not found.
380
     * <p />
381
     * If the List does not exist then the specified default value will returned
382
     * regardless of if a default has been identified in the root {@link Configuration}.
383
     *
384
     * @param path Path of the List to get.
385
     * @param def The default value to return if the path is not found or is not a List.
386
     * @return Requested List.
387
     */
388
    public List<?> getList(String path, List<?> def);
389

													
390
    /**
391
     * Checks if the specified path is a List.
392
     * <p />
393
     * If the path exists but is not a List, this will return false. If the path does not
394
     * exist, this will return false. If the path does not exist but a default value
395
     * has been specified, this will check if that default value is a List and return
396
     * appropriately.
397
     *
398
     * @param path Path of the List to check.
399
     * @return Whether or not the specified path is a List.
400
     */
401
    public boolean isList(String path);
402

													
403
    /**
404
     * Gets the requested List of String by path.
405
     * <p />
406
     * If the List does not exist but a default value has been specified, this
407
     * will return the default value. If the List does not exist and no default
408
     * value was specified, this will return null.
409
     * <p />
410
     * This method will attempt to cast any values into a String if possible, but may
411
     * miss any values out if they are not compatible.
412
     *
413
     * @param path Path of the List to get.
414
     * @return Requested List of String.
415
     */
416
    public List<String> getStringList(String path);
417

													
418
    /**
419
     * Gets the requested List of Integer by path.
420
     * <p />
421
     * If the List does not exist but a default value has been specified, this
422
     * will return the default value. If the List does not exist and no default
423
     * value was specified, this will return null.
424
     * <p />
425
     * This method will attempt to cast any values into a Integer if possible, but may
426
     * miss any values out if they are not compatible.
427
     *
428
     * @param path Path of the List to get.
429
     * @return Requested List of Integer.
430
     */
431
    public List<Integer> getIntegerList(String path);
432

													
433
    /**
434
     * Gets the requested List of Boolean by path.
435
     * <p />
436
     * If the List does not exist but a default value has been specified, this
437
     * will return the default value. If the List does not exist and no default
438
     * value was specified, this will return null.
439
     * <p />
440
     * This method will attempt to cast any values into a Boolean if possible, but may
441
     * miss any values out if they are not compatible.
442
     *
443
     * @param path Path of the List to get.
444
     * @return Requested List of Boolean.
445
     */
446
    public List<Boolean> getBooleanList(String path);
447

													
448
    /**
449
     * Gets the requested List of Double by path.
450
     * <p />
451
     * If the List does not exist but a default value has been specified, this
452
     * will return the default value. If the List does not exist and no default
453
     * value was specified, this will return null.
454
     * <p />
455
     * This method will attempt to cast any values into a Double if possible, but may
456
     * miss any values out if they are not compatible.
457
     *
458
     * @param path Path of the List to get.
459
     * @return Requested List of Double.
460
     */
461
    public List<Double> getDoubleList(String path);
462

													
463
    /**
464
     * Gets the requested List of Float by path.
465
     * <p />
466
     * If the List does not exist but a default value has been specified, this
467
     * will return the default value. If the List does not exist and no default
468
     * value was specified, this will return null.
469
     * <p />
470
     * This method will attempt to cast any values into a Float if possible, but may
471
     * miss any values out if they are not compatible.
472
     *
473
     * @param path Path of the List to get.
474
     * @return Requested List of Float.
475
     */
476
    public List<Float> getFloatList(String path);
477

													
478
    /**
479
     * Gets the requested List of Long by path.
480
     * <p />
481
     * If the List does not exist but a default value has been specified, this
482
     * will return the default value. If the List does not exist and no default
483
     * value was specified, this will return null.
484
     * <p />
485
     * This method will attempt to cast any values into a Long if possible, but may
486
     * miss any values out if they are not compatible.
487
     *
488
     * @param path Path of the List to get.
489
     * @return Requested List of Long.
490
     */
491
    public List<Long> getLongList(String path);
492

													
493
    /**
494
     * Gets the requested List of Byte by path.
495
     * <p />
496
     * If the List does not exist but a default value has been specified, this
497
     * will return the default value. If the List does not exist and no default
498
     * value was specified, this will return null.
499
     * <p />
500
     * This method will attempt to cast any values into a Byte if possible, but may
501
     * miss any values out if they are not compatible.
502
     *
503
     * @param path Path of the List to get.
504
     * @return Requested List of Byte.
505
     */
506
    public List<Byte> getByteList(String path);
507

													
508
    /**
509
     * Gets the requested List of Character by path.
510
     * <p />
511
     * If the List does not exist but a default value has been specified, this
512
     * will return the default value. If the List does not exist and no default
513
     * value was specified, this will return null.
514
     * <p />
515
     * This method will attempt to cast any values into a Character if possible, but may
516
     * miss any values out if they are not compatible.
517
     *
518
     * @param path Path of the List to get.
519
     * @return Requested List of Character.
520
     */
521
    public List<Character> getCharacterList(String path);
522

													
523
    /**
524
     * Gets the requested List of Short by path.
525
     * <p />
526
     * If the List does not exist but a default value has been specified, this
527
     * will return the default value. If the List does not exist and no default
528
     * value was specified, this will return null.
529
     * <p />
530
     * This method will attempt to cast any values into a Short if possible, but may
531
     * miss any values out if they are not compatible.
532
     *
533
     * @param path Path of the List to get.
534
     * @return Requested List of Short.
535
     */
536
    public List<Short> getShortList(String path);
537

													
538
    /**
539
     * Gets the requested List of Maps by path.
540
     * <p />
541
     * If the List does not exist but a default value has been specified, this
542
     * will return the default value. If the List does not exist and no default
543
     * value was specified, this will return null.
544
     * <p />
545
     * This method will attempt to cast any values into a Map if possible, but may
546
     * miss any values out if they are not compatible.
547
     *
548
     * @param path Path of the List to get.
549
     * @return Requested List of Maps.
550
     */
551
    public List<Map<?, ?>> getMapList(String path);
552
    
553

													
554
    /**
555
     * Gets the requested ConfigurationSection by path.
556
     * <p />
557
     * If the ConfigurationSection does not exist but a default value has been specified, this
558
     * will return the default value. If the ConfigurationSection does not exist and no default
559
     * value was specified, this will return null.
560
     *
561
     * @param path Path of the ConfigurationSection to get.
562
     * @return Requested ConfigurationSection.
563
     */
564
    public ConfigurationSection getConfigurationSection(String path);
565

													
566
    /**
567
     * Checks if the specified path is a ConfigurationSection.
568
     * <p />
569
     * If the path exists but is not a ConfigurationSection, this will return false. If the path does not
570
     * exist, this will return false. If the path does not exist but a default value
571
     * has been specified, this will check if that default value is a ConfigurationSection and return
572
     * appropriately.
573
     *
574
     * @param path Path of the ConfigurationSection to check.
575
     * @return Whether or not the specified path is a ConfigurationSection.
576
     */
577
    public boolean isConfigurationSection(String path);
578

													
579
    /**
580
     * Gets the equivalent {@link ConfigurationSection} from the default {@link Configuration} defined in {@link #getRoot()}.
581
     * <p />
582
     * If the root contains no defaults, or the defaults doesn't contain a value
583
     * for this path, or the value at this path is not a {@link ConfigurationSection} then
584
     * this will return null.
585
     *
586
     * @return Equivalent section in root configuration
587
     */
588
    public ConfigurationSection getDefaultSection();
589

													
590
    /**
591
     * Sets the default value in the root at the given path as provided.
592
     * <p />
593
     * If no source {@link Configuration} was provided as a default collection,
594
     * then a new {@link MemoryConfiguration} will be created to hold the new default
595
     * value.
596
     * <p />
597
     * If value is null, the value will be removed from the default Configuration source.
598
     * <p />
599
     * If the value as returned by {@link #getDefaultSection()} is null,
600
     * then this will create a new section at the path, replacing anything that
601
     * may have existed there previously.
602
     *
603
     * @param path Path of the value to set.
604
     * @param value Value to set the default to.
605
     * @throws IllegalArgumentException Thrown if path is null.
606
     */
607
    public void addDefault(String path, Object value);
608
}

+ 35 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationSerializable.java

@ -0,0 +1,35 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3
import java.util.Map;
4

													
5
import org.shortrip.boozaa.libs.yamlconfiguration.serialization.DelegateDeserialization;
6
import org.shortrip.boozaa.libs.yamlconfiguration.serialization.SerializableAs;
7

													
8
/**
9
 * Represents an object that may be serialized.
10
 * <p />
11
 * These objects MUST implement one of the following, in addition to the methods
12
 * as defined by this interface:
13
 * <ul>
14
 * <li>A static method "deserialize" that accepts a single {@link Map}&lt;{@link String}, {@link Object}>
15
 * and returns the class.</li>
16
 * <li>A static method "valueOf" that accepts a single {@link Map}&lt;{@link String}, {@link Object}>
17
 * and returns the class.</li>
18
 * <li>A constructor that accepts a single {@link Map}&lt;{@link String}, {@link Object}>.</li>
19
 * </ul>
20
 * In addition to implementing this interface, you must register the class with
21
 * {@link ConfigurationSerialization#registerClass(Class)}.
22
 * @see DelegateDeserialization
23
 * @see SerializableAs
24
 */
25
public interface ConfigurationSerializable {
26
    /**
27
     * Creates a Map representation of this class.
28
     * <p />
29
     * This class must provide a method to restore this class, as defined in the
30
     * {@link ConfigurationSerializable} interface javadocs.
31
     *
32
     * @return Map containing the current state of this class
33
     */
34
    public Map<String, Object> serialize();
35
}

+ 258 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/ConfigurationSerialization.java

@ -0,0 +1,258 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3
import java.lang.reflect.Constructor;
4
import java.lang.reflect.InvocationTargetException;
5
import java.lang.reflect.Method;
6
import java.lang.reflect.Modifier;
7
import java.util.HashMap;
8
import java.util.Map;
9
import java.util.logging.Level;
10
import java.util.logging.Logger;
11
import org.apache.commons.lang.Validate;
12
import org.shortrip.boozaa.libs.yamlconfiguration.serialization.DelegateDeserialization;
13
import org.shortrip.boozaa.libs.yamlconfiguration.serialization.SerializableAs;
14

													
15
/**
16
 * Utility class for storing and retrieving classes for {@link Configuration}.
17
 */
18
public class ConfigurationSerialization {
19
    public static final String SERIALIZED_TYPE_KEY = "==";
20
    private final Class<? extends ConfigurationSerializable> clazz;
21
    private static Map<String, Class<? extends ConfigurationSerializable>> aliases = new HashMap<String, Class<? extends ConfigurationSerializable>>();
22

													
23

													
24
    protected ConfigurationSerialization(Class<? extends ConfigurationSerializable> clazz) {
25
        this.clazz = clazz;
26
    }
27

													
28
    protected Method getMethod(String name, boolean isStatic) {
29
        try {
30
            Method method = clazz.getDeclaredMethod(name, Map.class);
31

													
32
            if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) {
33
                return null;
34
            }
35
            if (Modifier.isStatic(method.getModifiers()) != isStatic) {
36
                return null;
37
            }
38

													
39
            return method;
40
        } catch (NoSuchMethodException ex) {
41
            return null;
42
        } catch (SecurityException ex) {
43
            return null;
44
        }
45
    }
46

													
47
    protected Constructor<? extends ConfigurationSerializable> getConstructor() {
48
        try {
49
            return clazz.getConstructor(Map.class);
50
        } catch (NoSuchMethodException ex) {
51
            return null;
52
        } catch (SecurityException ex) {
53
            return null;
54
        }
55
    }
56

													
57
    protected ConfigurationSerializable deserializeViaMethod(Method method, Map<String, Object> args) {
58
        try {
59
            ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);
60

													
61
            if (result == null) {
62
                Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null");
63
            } else {
64
                return result;
65
            }
66
        } catch (Throwable ex) {
67
            Logger.getLogger(ConfigurationSerialization.class.getName()).log(
68
                    Level.SEVERE,
69
                    "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
70
                    ex instanceof InvocationTargetException ? ex.getCause() : ex);
71
        }
72

													
73
        return null;
74
    }
75

													
76
    protected ConfigurationSerializable deserializeViaCtor(Constructor<? extends ConfigurationSerializable> ctor, Map<String, Object> args) {
77
        try {
78
            return ctor.newInstance(args);
79
        } catch (Throwable ex) {
80
            Logger.getLogger(ConfigurationSerialization.class.getName()).log(
81
                    Level.SEVERE,
82
                    "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization",
83
                    ex instanceof InvocationTargetException ? ex.getCause() : ex);
84
        }
85

													
86
        return null;
87
    }
88

													
89
    public ConfigurationSerializable deserialize(Map<String, Object> args) {
90
        Validate.notNull(args, "Args must not be null");
91

													
92
        ConfigurationSerializable result = null;
93
        Method method = null;
94

													
95
        if (result == null) {
96
            method = getMethod("deserialize", true);
97

													
98
            if (method != null) {
99
                result = deserializeViaMethod(method, args);
100
            }
101
        }
102

													
103
        if (result == null) {
104
            method = getMethod("valueOf", true);
105

													
106
            if (method != null) {
107
                result = deserializeViaMethod(method, args);
108
            }
109
        }
110

													
111
        if (result == null) {
112
            Constructor<? extends ConfigurationSerializable> constructor = getConstructor();
113

													
114
            if (constructor != null) {
115
                result = deserializeViaCtor(constructor, args);
116
            }
117
        }
118

													
119
        return result;
120
    }
121

													
122
    /**
123
     * Attempts to deserialize the given arguments into a new instance of the given class.
124
     * <p />
125
     * The class must implement {@link ConfigurationSerializable}, including the extra methods
126
     * as specified in the javadoc of ConfigurationSerializable.
127
     * <p />
128
     * If a new instance could not be made, an example being the class not fully implementing
129
     * the interface, null will be returned.
130
     *
131
     * @param args Arguments for deserialization
132
     * @param clazz Class to deserialize into
133
     * @return New instance of the specified class
134
     */
135
    public static ConfigurationSerializable deserializeObject(Map<String, Object> args, Class<? extends ConfigurationSerializable> clazz) {
136
        return new ConfigurationSerialization(clazz).deserialize(args);
137
    }
138

													
139
    /**
140
     * Attempts to deserialize the given arguments into a new instance of the given class.
141
     * <p />
142
     * The class must implement {@link ConfigurationSerializable}, including the extra methods
143
     * as specified in the javadoc of ConfigurationSerializable.
144
     * <p />
145
     * If a new instance could not be made, an example being the class not fully implementing
146
     * the interface, null will be returned.
147
     *
148
     * @param args Arguments for deserialization
149
     * @return New instance of the specified class
150
     */
151
    public static ConfigurationSerializable deserializeObject(Map<String, Object> args) {
152
        Class<? extends ConfigurationSerializable> clazz = null;
153

													
154
        if (args.containsKey(SERIALIZED_TYPE_KEY)) {
155
            try {
156
                String alias = (String) args.get(SERIALIZED_TYPE_KEY);
157

													
158
                if (alias == null) {
159
                    throw new IllegalArgumentException("Cannot have null alias");
160
                }
161
                clazz = getClassByAlias(alias);
162
                if (clazz == null) {
163
                    throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')");
164
                }
165
            } catch (ClassCastException ex) {
166
                ex.fillInStackTrace();
167
                throw ex;
168
            }
169
        } else {
170
            throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')");
171
        }
172

													
173
        return new ConfigurationSerialization(clazz).deserialize(args);
174
    }
175

													
176
    /**
177
     * Registers the given {@link ConfigurationSerializable} class by its alias
178
     *
179
     * @param clazz Class to register
180
     */
181
    public static void registerClass(Class<? extends ConfigurationSerializable> clazz) {
182
        DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
183

													
184
        if (delegate == null) {
185
            registerClass(clazz, getAlias(clazz));
186
            registerClass(clazz, clazz.getName());
187
        }
188
    }
189

													
190
    /**
191
     * Registers the given alias to the specified {@link ConfigurationSerializable} class
192
     *
193
     * @param clazz Class to register
194
     * @param alias Alias to register as
195
     * @see SerializableAs
196
     */
197
    public static void registerClass(Class<? extends ConfigurationSerializable> clazz, String alias) {
198
        aliases.put(alias, clazz);
199
    }
200

													
201
    /**
202
     * Unregisters the specified alias to a {@link ConfigurationSerializable}
203
     *
204
     * @param alias Alias to unregister
205
     */
206
    public static void unregisterClass(String alias) {
207
        aliases.remove(alias);
208
    }
209

													
210
    /**
211
     * Unregisters any aliases for the specified {@link ConfigurationSerializable} class
212
     *
213
     * @param clazz Class to unregister
214
     */
215
    public static void unregisterClass(Class<? extends ConfigurationSerializable> clazz) {
216
        while (aliases.values().remove(clazz)) {
217
            ;
218
        }
219
    }
220

													
221
    /**
222
     * Attempts to get a registered {@link ConfigurationSerializable} class by its alias
223
     *
224
     * @param alias Alias of the serializable
225
     * @return Registered class, or null if not found
226
     */
227
    public static Class<? extends ConfigurationSerializable> getClassByAlias(String alias) {
228
        return aliases.get(alias);
229
    }
230

													
231
    /**
232
     * Gets the correct alias for the given {@link ConfigurationSerializable} class
233
     *
234
     * @param clazz Class to get alias for
235
     * @return Alias to use for the class
236
     */
237
    public static String getAlias(Class<? extends ConfigurationSerializable> clazz) {
238
        DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
239

													
240
        if (delegate != null) {
241
            if ((delegate.value() == null) || (delegate.value() == clazz)) {
242
                delegate = null;
243
            } else {
244
                return getAlias(delegate.value());
245
            }
246
        }
247

													
248
        if (delegate == null) {
249
            SerializableAs alias = clazz.getAnnotation(SerializableAs.class);
250

													
251
            if ((alias != null) && (alias.value() != null)) {
252
                return alias.value();
253
            }
254
        }
255

													
256
        return clazz.getName();
257
    }
258
}

+ 40 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/InvalidConfigurationException.java

@ -0,0 +1,40 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3
/**
4
 * Exception thrown when attempting to load an invalid {@link Configuration}
5
 */
6
@SuppressWarnings("serial")
7
public class InvalidConfigurationException extends Exception {
8
    /**
9
     * Creates a new instance of InvalidConfigurationException without a message or cause.
10
     */
11
    public InvalidConfigurationException() {}
12

													
13
    /**
14
     * Constructs an instance of InvalidConfigurationException with the specified message.
15
     *
16
     * @param msg The details of the exception.
17
     */
18
    public InvalidConfigurationException(String msg) {
19
        super(msg);
20
    }
21

													
22
    /**
23
     * Constructs an instance of InvalidConfigurationException with the specified cause.
24
     *
25
     * @param cause The cause of the exception.
26
     */
27
    public InvalidConfigurationException(Throwable cause) {
28
        super(cause);
29
    }
30

													
31
    /**
32
     * Constructs an instance of InvalidConfigurationException with the specified message and cause.
33
     *
34
     * @param cause The cause of the exception.
35
     * @param msg The details of the exception.
36
     */
37
    public InvalidConfigurationException(String msg, Throwable cause) {
38
        super(msg, cause);
39
    }
40
}

+ 79 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/MemoryConfiguration.java

@ -0,0 +1,79 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3
import java.util.Map;
4

													
5
import org.apache.commons.lang.Validate;
6

													
7
/**
8
 * This is a {@link Configuration} implementation that does not save or load
9
 * from any source, and stores all values in memory only.
10
 * This is useful for temporary Configurations for providing defaults.
11
 */
12
public class MemoryConfiguration extends MemorySection implements Configuration {
13
    protected Configuration defaults;
14
    protected MemoryConfigurationOptions options;
15

													
16
    /**
17
     * Creates an empty {@link MemoryConfiguration} with no default values.
18
     */
19
    public MemoryConfiguration() {}
20

													
21
    /**
22
     * Creates an empty {@link MemoryConfiguration} using the specified {@link Configuration}
23
     * as a source for all default values.
24
     *
25
     * @param defaults Default value provider
26
     * @throws IllegalArgumentException Thrown if defaults is null
27
     */
28
    public MemoryConfiguration(Configuration defaults) {
29
        this.defaults = defaults;
30
    }
31

													
32
    @Override
33
    public void addDefault(String path, Object value) {
34
        Validate.notNull(path, "Path may not be null");
35

													
36
        if (defaults == null) {
37
            defaults = new MemoryConfiguration();
38
        }
39

													
40
        defaults.set(path, value);
41
    }
42

													
43
    public void addDefaults(Map<String, Object> defaults) {
44
        Validate.notNull(defaults, "Defaults may not be null");
45

													
46
        for (Map.Entry<String, Object> entry : defaults.entrySet()) {
47
            addDefault(entry.getKey(), entry.getValue());
48
        }
49
    }
50

													
51
    public void addDefaults(Configuration defaults) {
52
        Validate.notNull(defaults, "Defaults may not be null");
53

													
54
        addDefaults(defaults.getValues(true));
55
    }
56

													
57
    public void setDefaults(Configuration defaults) {
58
        Validate.notNull(defaults, "Defaults may not be null");
59

													
60
        this.defaults = defaults;
61
    }
62

													
63
    public Configuration getDefaults() {
64
        return defaults;
65
    }
66

													
67
    @Override
68
    public ConfigurationSection getParent() {
69
        return null;
70
    }
71

													
72
    public MemoryConfigurationOptions options() {
73
        if (options == null) {
74
            options = new MemoryConfigurationOptions(this);
75
        }
76

													
77
        return options;
78
    }
79
}

+ 27 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/MemoryConfigurationOptions.java

@ -0,0 +1,27 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3
/**
4
 * Various settings for controlling the input and output of a {@link MemoryConfiguration}
5
 */
6
public class MemoryConfigurationOptions extends ConfigurationOptions {
7
    protected MemoryConfigurationOptions(MemoryConfiguration configuration) {
8
        super(configuration);
9
    }
10

													
11
    @Override
12
    public MemoryConfiguration configuration() {
13
        return (MemoryConfiguration) super.configuration();
14
    }
15

													
16
    @Override
17
    public MemoryConfigurationOptions copyDefaults(boolean value) {
18
        super.copyDefaults(value);
19
        return this;
20
    }
21

													
22
    @Override
23
    public MemoryConfigurationOptions pathSeparator(char value) {
24
        super.pathSeparator(value);
25
        return this;
26
    }
27
}

+ 748 - 0
src/main/java/org/shortrip/boozaa/libs/yamlconfiguration/MemorySection.java

</
@ -0,0 +1,748 @@
1
package org.shortrip.boozaa.libs.yamlconfiguration;
2

													
3

													
4
import java.util.ArrayList;
5
import java.util.LinkedHashMap;
6
import java.util.LinkedHashSet;
7
import java.util.List;
8
import java.util.Map;
9
import java.util.Set;
10
import org.apache.commons.lang.Validate;
11
import org.shortrip.boozaa.libs.yamlconfiguration.utils.NumberConversions;
12

													
13

													
14
/**
15
 * A type of {@link ConfigurationSection} that is stored in memory.
16
 */
17
public class MemorySection implements ConfigurationSection {
18
    protected final Map<String, Object> map = new LinkedHashMap<String, Object>();
19
    private final Configuration root;
20
    private final ConfigurationSection parent;
21
    private final String path;
22
    private final String fullPath;
23

													
24
    /**
25
     * Creates an empty MemorySection for use as a root {@link Configuration} section.
26
     * <p />
27
     * Note that calling this without being yourself a {@link Configuration} will throw an
28
     * exception!
29
     *
30
     * @throws IllegalStateException Thrown if this is not a {@link Configuration} root.
31
     */
32
    protected MemorySection() {
33
        if (!(this instanceof Configuration)) {
34
            throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration");
35
        }
36

													
37
        this.path = "";
38
        this.fullPath = "";
39
        this.parent = null;
40
        this.root = (Configuration) this;
41
    }
42

													
43
    /**
44
     * Creates an empty MemorySection with the specified parent and path.
45
     *
46
     * @param parent Parent section that contains this own section.
47
     * @param path Path that you may access this section from via the root {@link Configuration}.
48
     * @throws IllegalArgumentException Thrown is parent or path is null, or if parent contains no root Configuration.
49
     */
50
    protected MemorySection(ConfigurationSection parent, String path) {
51
        Validate.notNull(parent, "Parent cannot be null");
52
        Validate.notNull(path, "Path cannot be null");
53

													
54
        this.path = path;
55
        this.parent = parent;
56
        this.root = parent.getRoot();
57

													
58
        Validate.notNull(root, "Path cannot be orphaned");
59

													
60
        this.fullPath = createPath(parent, path);
61
    }
62

													
63
    public Set<String> getKeys(boolean deep) {
64
        Set<String> result = new LinkedHashSet<String>();
65

													
66
        Configuration root = getRoot();
67
        if (root != null && root.options().copyDefaults()) {
68
            ConfigurationSection defaults = getDefaultSection();
69

													
70
            if (defaults != null) {
71
                result.addAll(defaults.getKeys(deep));
72
            }
73
        }
74

													
75
        mapChildrenKeys(result, this, deep);
76

													
77
        return result;
78
    }
79

													
80
    public Map<String, Object> getValues(boolean deep) {
81
        Map<String, Object> result = new LinkedHashMap<String, Object>();
82

													
83
        Configuration root = getRoot();
84
        if (root != null && root.options().copyDefaults()) {
85
            ConfigurationSection defaults = getDefaultSection();
86

													
87
            if (defaults != null) {
88
                result.putAll(defaults.getValues(deep));
89
            }
90
        }
91

													
92
        mapChildrenValues(result, this, deep);
93

													
94
        return result;
95
    }
96

													
97
    public boolean contains(String path) {
98
        return get(path) != null;
99
    }
100

													
101
    public boolean isSet(String path) {
102
        Configuration root = getRoot();
103
        if (root == null) {
104
            return false;
105
        }
106
        if (root.options().copyDefaults()) {
107
            return contains(path);
108
        }
109
        return get(path, null) != null;
110
    }
111

													
112
    public String getCurrentPath() {
113
        return fullPath;
114
    }
115

													
116
    public String getName() {
117
        return path;
118
    }
119

													
120
    public Configuration getRoot() {
121
        return root;
122
    }
123

													
124
    public ConfigurationSection getParent() {
125
        return parent;
126
    }
127

													
128
    public void addDefault(String path, Object value) {
129
        Validate.notNull(path, "Path cannot be null");
130

													
131
        Configuration root = getRoot();
132
        if (root == null) {
133
            throw new IllegalStateException("Cannot add default without root");
134
        }
135
        if (root == this) {
136
            throw new UnsupportedOperationException("Unsupported addDefault(String, Object) implementation");
137
        }
138
        root.addDefault(createPath(this, path), value);
139
    }
140

													
141
    public ConfigurationSection getDefaultSection() {
142
        Configuration root = getRoot();
143
        Configuration defaults = root == null ? null : root.getDefaults();
144

													
145
        if (defaults != null) {
146
            if (defaults.isConfigurationSection(getCurrentPath())) {
147
                return defaults.getConfigurationSection(getCurrentPath());
148
            }
149
        }
150

													
151
        return null;
152
    }
153

													
154
    public void set(String path, Object value) {
155
        Validate.notEmpty(path, "Cannot set to an empty path");
156

													
157
        Configuration root = getRoot();
158
        if (root == null) {
159
            throw new IllegalStateException("Cannot use section without a root");
160
        }
161

													
162
        final char separator = root.options().pathSeparator();
163
        // i1 is the leading (higher) index
164
        // i2 is the trailing (lower) index
165
        int i1 = -1, i2;
166
        ConfigurationSection section = this;
167
        while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
168
            String node = path.substring(i2, i1);
169
            ConfigurationSection subSection = section.getConfigurationSection(node);
170
            if (subSection == null) {
171
                section = section.createSection(node);
172
            } else {
173
                section = subSection;
174
            }
175
        }
176

													
177
        String key = path.substring(i2);
178
        if (section == this) {
179
            if (value == null) {
180
                map.remove(key);
181
            } else {
182
                map.put(key, value);
183
            }
184
        } else {
185
            section.set(key, value);
186
        }
187
    }
188

													
189
    public Object get(String path) {
190
        return get(path, getDefault(path));
191
    }
192

													
193
    public Object get(String path, Object def) {
194
        Validate.notNull(path, "Path cannot be null");
195

													
196
        if (path.length() == 0) {
197
            return this;
198
        }
199

													
200
        Configuration root = getRoot();
201
        if (root == null) {
202
            throw new IllegalStateException("Cannot access section without a root");
203
        }
204

													
205
        final char separator = root.options().pathSeparator();
206
        // i1 is the leading (higher) index
207
        // i2 is the trailing (lower) index
208
        int i1 = -1, i2;
209
        ConfigurationSection section = this;
210
        while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
211
            section = section.getConfigurationSection(path.substring(i2, i1));
212
            if (section == null) {
213
                return def;
214
            }
215
        }
216

													
217
        String key = path.substring(i2);
218
        if (section == this) {
219
            Object result = map.get(key);
220
            return (result == null) ? def : result;
221
        }
222
        return section.get(key, def);
223
    }
224

													
225
    public ConfigurationSection createSection(String path) {
226
        Validate.notEmpty(path, "Cannot create section at empty path");
227
        Configuration root = getRoot();
228
        if (root == null) {
229
            throw new IllegalStateException("Cannot create section without a root");
230
        }
231

													
232
        final char separator = root.options().pathSeparator();
233
        // i1 is the leading (higher) index
234
        // i2 is the trailing (lower) index
235
        int i1 = -1, i2;
236
        ConfigurationSection section = this;
237
        while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
238
            String node = path.substring(i2, i1);
239
            ConfigurationSection subSection = section.getConfigurationSection(node);
240
            if (subSection == null) {
241
                section = section.createSection(node);
242
            } else {
243
                section = subSection;
244
            }
245
        }
246

													
247
        String key = path.substring(i2);
248
        if (section == this) {
249
            ConfigurationSection result = new MemorySection(this, key);
250
            map.put(key, result);
251
            return result;
252
        }
253
        return section.createSection(key);
254
    }
255

													
256
    public ConfigurationSection createSection(String path, Map<?, ?> map) {
257
        ConfigurationSection section = createSection(path);
258

													
259
        for (Map.Entry<?, ?> entry : map.entrySet()) {
260
            if (entry.getValue() instanceof Map) {
261
                section.createSection(entry.getKey().toString(), (Map<?, ?>) entry.getValue());
262
            } else {
263
                section.set(entry.getKey().toString(), entry.getValue());
264
            }
265
        }
266

													
267
        return section;
268
    }
269

													
270
    // Primitives
271
    public String getString(String path) {
272
        Object def = getDefault(path);
273
        return getString(path, def != null ? def.toString() : null);
274
    }
275

													
276
    public String getString(String path, String def) {
277
        Object val = get(path, def);
278
        return (val != null) ? val.toString() : def;
279
    }
280

													
281
    public boolean isString(String path) {
282
        Object val = get(path);
283
        return val instanceof String;
284
    }
285

													
286
    public int getInt(String path) {
287
        Object def = getDefault(path);
288
        return getInt(path, (def instanceof Number) ? NumberConversions.toInt(def) : 0);
289
    }
290

													
291
    public int getInt(String path, int def) {
292
        Object val = get(path, def);
293
        return (val instanceof Number) ? NumberConversions.toInt(val) : def;
294
    }
295

													
296
    public boolean isInt(String path) {
297
        Object val = get(path);
298
        return val instanceof Integer;
299
    }
300

													
301
    public boolean getBoolean(String path) {
302
        Object def = getDefault(path);
303
        return getBoolean(path, (def instanceof Boolean) ? (Boolean) def : false);
304
    }
305

													
306
    public boolean getBoolean(String path, boolean def) {
307
        Object val = get(path, def);
308
        return (val instanceof Boolean) ? (Boolean) val : def;
309
    }
310

													
311
    public boolean isBoolean(String path) {
312
        Object val = get(path);
313
        return val instanceof Boolean;
314
    }
315

													
316
    public double getDouble(String path) {
317
        Object def = getDefault(path);
318
        return getDouble(path, (def instanceof Number) ? NumberConversions.toDouble(def) : 0);
319
    }
320

													
321
    public double getDouble(String path, double def) {
322
        Object val = get(path, def);
323
        return (val instanceof Number) ? NumberConversions.toDouble(val) : def;
324
    }
325

													
326
    public boolean isDouble(String path) {
327
        Object val = get(path);
328
        return val instanceof Double;
329
    }
330

													
331
    public long getLong(String path) {
332
        Object def = getDefault(path);
333
        return getLong(path, (def instanceof Number) ? NumberConversions.toLong(def) : 0);
334
    }
335

													
336
    public long getLong(String path, long def) {
337
        Object val = get(path, def);
338
        return (val instanceof Number) ? NumberConversions.toLong(val) : def;
339
    }
340

													
341
    public boolean isLong(String path) {
342
        Object val = get(path);
343
        return val instanceof Long;
344
    }
345

													
346
    // Java
347
    public List<?> getList(String path) {
348
        Object def = getDefault(path);
349
        return getList(path, (def instanceof List) ? (List<?>) def : null);
350
    }
351

													
352
    public List<?> getList(String path, List<?> def) {
353
        Object val = get(path, def);
354
        return (List<?>) ((val instanceof List) ? val : def);
355
    }
356

													
357
    public boolean isList(String path) {
358
        Object val = get(path);
359
        return val instanceof List;
360
    }
361

													
362
    public List<String> getStringList(String path) {
363
        List<?> list = getList(path);
364

													
365
        if (list == null) {
366
            return new ArrayList<String>(0);
367
        }
368

													
369
        List<String> result = new ArrayList<String>();
370

													
371
        for (Object object : list) {
372
            if ((object instanceof String) || (isPrimitiveWrapper(object))) {
373
                result.add(String.valueOf(object));