diff --git a/src/main/java/com/flowpowered/cerealization/CastUtils.java b/src/main/java/com/flowpowered/cerealization/CastUtils.java index b6c3e47..0ba82cd 100644 --- a/src/main/java/com/flowpowered/cerealization/CastUtils.java +++ b/src/main/java/com/flowpowered/cerealization/CastUtils.java @@ -33,265 +33,265 @@ * Class containing generic casting functions. */ public class CastUtils { - private CastUtils() { - } + private CastUtils() { + } - /** - * Casts a value to a float. May return null. - * - * @param o The object to attempt to cast - * @return The object as a float - */ - public static Float castFloat(Object o) { - if (o == null) { - return null; - } + /** + * Casts a value to a float. May return null. + * + * @param o The object to attempt to cast + * @return The object as a float + */ + public static Float castFloat(Object o) { + if (o == null) { + return null; + } - if (o instanceof Number) { - return ((Number) o).floatValue(); - } + if (o instanceof Number) { + return ((Number) o).floatValue(); + } - try { - return Float.valueOf(o.toString()); - } catch (NumberFormatException e) { - return null; - } - } + try { + return Float.valueOf(o.toString()); + } catch (NumberFormatException e) { + return null; + } + } - /** - * Casts a value to a byte. May return null. - * - * @param o The object to attempt to cast - * @return The object as a byte - */ - public static Byte castByte(Object o) { - if (o == null) { - return null; - } + /** + * Casts a value to a byte. May return null. + * + * @param o The object to attempt to cast + * @return The object as a byte + */ + public static Byte castByte(Object o) { + if (o == null) { + return null; + } - if (o instanceof Number) { - return ((Number) o).byteValue(); - } + if (o instanceof Number) { + return ((Number) o).byteValue(); + } - try { - return Byte.valueOf(o.toString()); - } catch (NumberFormatException e) { - return null; - } - } + try { + return Byte.valueOf(o.toString()); + } catch (NumberFormatException e) { + return null; + } + } - /** - * Casts a value to a short. May return null. - * - * @param o The object to attempt to cast - * @return The object as a short - */ - public static Short castShort(Object o) { - if (o == null) { - return null; - } + /** + * Casts a value to a short. May return null. + * + * @param o The object to attempt to cast + * @return The object as a short + */ + public static Short castShort(Object o) { + if (o == null) { + return null; + } - if (o instanceof Number) { - return ((Number) o).shortValue(); - } + if (o instanceof Number) { + return ((Number) o).shortValue(); + } - try { - return Short.valueOf(o.toString()); - } catch (NumberFormatException e) { - return null; - } - } + try { + return Short.valueOf(o.toString()); + } catch (NumberFormatException e) { + return null; + } + } - /** - * Casts a value to an integer. May return null. - * - * @param o The object to attempt to cast - * @return The object as an int - */ - public static Integer castInt(Object o) { - if (o == null) { - return null; - } + /** + * Casts a value to an integer. May return null. + * + * @param o The object to attempt to cast + * @return The object as an int + */ + public static Integer castInt(Object o) { + if (o == null) { + return null; + } - if (o instanceof Number) { - return ((Number) o).intValue(); - } + if (o instanceof Number) { + return ((Number) o).intValue(); + } - try { - return Integer.valueOf(o.toString()); - } catch (NumberFormatException e) { - return null; - } - } + try { + return Integer.valueOf(o.toString()); + } catch (NumberFormatException e) { + return null; + } + } - /** - * Casts a value to a double. May return null. - * - * @param o The object to attempt to cast - * @return The object as a double - */ - public static Double castDouble(Object o) { - if (o == null) { - return null; - } + /** + * Casts a value to a double. May return null. + * + * @param o The object to attempt to cast + * @return The object as a double + */ + public static Double castDouble(Object o) { + if (o == null) { + return null; + } - if (o instanceof Number) { - return ((Number) o).doubleValue(); - } + if (o instanceof Number) { + return ((Number) o).doubleValue(); + } - try { - return Double.valueOf(o.toString()); - } catch (NumberFormatException e) { - return null; - } - } + try { + return Double.valueOf(o.toString()); + } catch (NumberFormatException e) { + return null; + } + } - /** - * Casts a value to a long. May return null. - * - * @param o The object to attempt to cast - * @return The object as a long - */ - public static Long castLong(Object o) { - if (o == null) { - return null; - } + /** + * Casts a value to a long. May return null. + * + * @param o The object to attempt to cast + * @return The object as a long + */ + public static Long castLong(Object o) { + if (o == null) { + return null; + } - if (o instanceof Number) { - return ((Number) o).longValue(); - } + if (o instanceof Number) { + return ((Number) o).longValue(); + } - try { - return Long.valueOf(o.toString()); - } catch (NumberFormatException e) { - return null; - } - } + try { + return Long.valueOf(o.toString()); + } catch (NumberFormatException e) { + return null; + } + } - /** - * Casts a value to a BigInteger. May return null. - * - * @param o The object to attempt to cast - * @return The object as a BigInteger - */ - public static BigInteger castBigInt(Object o) { - if (o == null) { - return null; - } + /** + * Casts a value to a BigInteger. May return null. + * + * @param o The object to attempt to cast + * @return The object as a BigInteger + */ + public static BigInteger castBigInt(Object o) { + if (o == null) { + return null; + } - if (o instanceof BigInteger) { - return (BigInteger) o; - } + if (o instanceof BigInteger) { + return (BigInteger) o; + } - if (o instanceof Number) { - return BigInteger.valueOf(((Number) o).longValue()); - } - try { - return new BigInteger(o.toString()); - } catch (NumberFormatException e) { - return null; - } - } + if (o instanceof Number) { + return BigInteger.valueOf(((Number) o).longValue()); + } + try { + return new BigInteger(o.toString()); + } catch (NumberFormatException e) { + return null; + } + } - /** - * Casts a value to a BigDecimal. May return null. - * - * @param o The object to attempt to cast - * @return The object as a BigDecimal - */ - public static BigDecimal castBigDecimal(Object o) { - if (o == null) { - return null; - } + /** + * Casts a value to a BigDecimal. May return null. + * + * @param o The object to attempt to cast + * @return The object as a BigDecimal + */ + public static BigDecimal castBigDecimal(Object o) { + if (o == null) { + return null; + } - if (o instanceof BigDecimal) { - return (BigDecimal) o; - } + if (o instanceof BigDecimal) { + return (BigDecimal) o; + } - if (o instanceof Number) { - return BigDecimal.valueOf(((Number) o).doubleValue()); - } - try { - return new BigDecimal(o.toString()); - } catch (NumberFormatException e) { - return null; - } - } + if (o instanceof Number) { + return BigDecimal.valueOf(((Number) o).doubleValue()); + } + try { + return new BigDecimal(o.toString()); + } catch (NumberFormatException e) { + return null; + } + } - /** - * Casts a value to a boolean. May return null. - * - * @param o The object to attempt to cast - * @return The object as a boolean - */ - public static Boolean castBoolean(Object o) { - if (o == null) { - return null; - } + /** + * Casts a value to a boolean. May return null. + * + * @param o The object to attempt to cast + * @return The object as a boolean + */ + public static Boolean castBoolean(Object o) { + if (o == null) { + return null; + } - if (o instanceof Boolean) { - return (Boolean) o; - } else if (o instanceof String) { - try { - return Boolean.parseBoolean((String) o); - } catch (IllegalArgumentException e) { - return null; - } - } + if (o instanceof Boolean) { + return (Boolean) o; + } else if (o instanceof String) { + try { + return Boolean.parseBoolean((String) o); + } catch (IllegalArgumentException e) { + return null; + } + } - return null; - } + return null; + } - /** - * Casts a value to a Date. May return null. - * - * @param o The object to attempt to cast - * @return The object as a Date - */ - public static Date castDate(Object o) { - if (o == null) { - return null; - } - if (o instanceof Date) { - return (Date) o; - } - Long l = castLong(o); - if (l != null) { - return new Date(l); - } - String str = String.valueOf(o); - try { - return DateFormat.getDateTimeInstance().parse(str); - } catch (ParseException e) { - } - try { - return DateFormat.getDateInstance().parse(str); - } catch (ParseException e) { - } - try { - return DateFormat.getTimeInstance().parse(str); - } catch (ParseException e) { - } - try { - return DateFormat.getInstance().parse(str); - } catch (ParseException e) { - } - return null; - } + /** + * Casts a value to a Date. May return null. + * + * @param o The object to attempt to cast + * @return The object as a Date + */ + public static Date castDate(Object o) { + if (o == null) { + return null; + } + if (o instanceof Date) { + return (Date) o; + } + Long l = castLong(o); + if (l != null) { + return new Date(l); + } + String str = String.valueOf(o); + try { + return DateFormat.getDateTimeInstance().parse(str); + } catch (ParseException e) { + } + try { + return DateFormat.getDateInstance().parse(str); + } catch (ParseException e) { + } + try { + return DateFormat.getTimeInstance().parse(str); + } catch (ParseException e) { + } + try { + return DateFormat.getInstance().parse(str); + } catch (ParseException e) { + } + return null; + } - /** - * Casts a value to a byte array. May return null. - * - * @param o The object to attempt to cast - * @return The object as a byte array - */ - public static byte[] castBytes(Object o) { - if (o == null) { - return null; - } - if (o instanceof byte[]) { - return (byte[]) o; - } - return null; - } + /** + * Casts a value to a byte array. May return null. + * + * @param o The object to attempt to cast + * @return The object as a byte array + */ + public static byte[] castBytes(Object o) { + if (o == null) { + return null; + } + if (o instanceof byte[]) { + return (byte[]) o; + } + return null; + } } diff --git a/src/main/java/com/flowpowered/cerealization/ReflectionUtils.java b/src/main/java/com/flowpowered/cerealization/ReflectionUtils.java index 9244e20..4b941fa 100644 --- a/src/main/java/com/flowpowered/cerealization/ReflectionUtils.java +++ b/src/main/java/com/flowpowered/cerealization/ReflectionUtils.java @@ -41,506 +41,506 @@ * Various utility methods that deal with reflection */ public class ReflectionUtils { - /** - * Get all the public fields in a class, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all fields in - * @return The public fields in the class - */ - public static List getFieldsRecur(Class clazz) { - return getFieldsRecur(clazz, false); - } - - /** - * Get all the public fields in a class with the specified modifiers, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all fields in - * @param modifiers the modifier mask - * @return The public fields in the class - */ - public static List getFieldsRecur(Class clazz, int modifiers) { - return getFieldsRecur(clazz, modifiers, false); - } - - /** - * Get all the public fields in a class, as well as those in its superclasses. - * - * @param clazz The class to get all fields in - * @param includeObject Whether to include fields in {@link Object} - * @return The public fields in the class - */ - public static List getFieldsRecur(Class clazz, boolean includeObject) { - return getFieldsRecur(clazz, includeObject, (Class[]) null); - } - - /** - * Get all the public fields in a class with the specified modifiers, as well as those in its superclasses. - * - * @param clazz The class to get all fields in - * @param modifiers the modifier mask - * @param includeObject Whether to include fields in {@link Object} - * @return The public fields in the class - */ - public static List getFieldsRecur(Class clazz, int modifiers, boolean includeObject) { - return getFieldsRecur(clazz, modifiers, includeObject, (Class[]) null); - } - - /** - * Get all the public fields in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all fields in - * @param annotations if not null, only include fields with any of these annotations - * @return The public fields in the class - */ - public static List getFieldsRecur(Class clazz, Class... annotations) { - return getFieldsRecur(clazz, 0, false, annotations); - } - - /** - * Get all the public fields in a class with the desired annotation and the specified modifiers, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all fields in - * @param modifiers the modifier mask - * @param annotations if not null, only include fields with any of these annotations - * @return The public fields in the class - */ - public static List getFieldsRecur(Class clazz, int modifiers, Class... annotations) { - return getFieldsRecur(clazz, modifiers, false, annotations); - } - - /** - * Get all the public fields in a class with the desired annotation, as well as those in its superclasses. - * - * @param clazz The class to get all fields in - * @param includeObject Whether to include fields in {@link Object} - * @param annotations if not null, only include fields with any of these annotations - * @return The public fields in the class - */ - public static List getFieldsRecur(Class clazz, boolean includeObject, Class... annotations) { - return getFieldsRecur(clazz, 0, includeObject, annotations); - } - - /** - * Get all the public fields in a class with the specified modifiers (optionally, with the desired annotation), as well as those in its superclasses. - * - * @param clazz The class to get all fields in - * @param modifiers the modifier mask - * @param includeObject Whether to include fields in {@link Object} - * @param annotations if not null, only include fields with any of these annotations - * @return The public fields in the class - * @see Class#getFields() - */ - public static List getFieldsRecur(Class clazz, int modifiers, boolean includeObject, Class... annotations) { - final List fields = new ArrayList(); - while (clazz != null && (includeObject || !Object.class.equals(clazz))) { - for (Field field : clazz.getFields()) { - if (hasModifiers(field, modifiers) && (annotations == null || hasAnyAnnotation(field, annotations))) { - fields.add(field); - } - } - clazz = clazz.getSuperclass(); - } - return fields; - } - - /** - * Get all the fields in a class, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all fields in - * @return The public fields in the class - */ - public static List getDeclaredFieldsRecur(Class clazz) { - return getDeclaredFieldsRecur(clazz, false); - } - - /** - * Get all the fields in a class with the specified modifiers, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all fields in - * @param modifiers the modifier mask - * @return The public fields in the class - */ - public static List getDeclaredFieldsRecur(Class clazz, int modifiers) { - return getDeclaredFieldsRecur(clazz, modifiers, false); - } - - /** - * Get all the fields in a class, as well as those in its superclasses. - * - * @param clazz The class to get all fields in - * @param includeObject Whether to include fields in {@link Object} - * @return The public fields in the class - */ - public static List getDeclaredFieldsRecur(Class clazz, boolean includeObject) { - return getDeclaredFieldsRecur(clazz, 0, includeObject, (Class[]) null); - } - - /** - * Get all the fields with the specified modifiers in a class, as well as those in its superclasses. - * - * @param clazz The class to get all fields in - * @param modifiers the modifier mask - * @param includeObject Whether to include fields in {@link Object} - * @return The public fields in the class - */ - public static List getDeclaredFieldsRecur(Class clazz, int modifiers, boolean includeObject) { - return getDeclaredFieldsRecur(clazz, modifiers, includeObject, (Class[]) null); - } - - /** - * Get all the fields in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all fields in - * @param annotations if not null, only include fields with any of these annotations - * @return The public fields in the class - */ - public static List getDeclaredFieldsRecur(Class clazz, Class... annotations) { - return getDeclaredFieldsRecur(clazz, 0, false, annotations); - } - - /** - * Get all the fields in a class with the desired annotation and the specified modifiers, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all fields in - * @param modifiers the modifier mask - * @param annotations if not null, only include fields with any of these annotations - * @return The public fields in the class - */ - public static List getDeclaredFieldsRecur(Class clazz, int modifiers, Class... annotations) { - return getDeclaredFieldsRecur(clazz, modifiers, false, annotations); - } - - /** - * Get all the fields in a class with the desired annotation, as well as those in its superclasses. - * - * @param clazz The class to get all fields in - * @param includeObject Whether to include fields in {@link Object} - * @return The public fields in the class - */ - public static List getDeclaredFieldsRecur(Class clazz, boolean includeObject, Class... annotations) { - return getDeclaredFieldsRecur(clazz, 0, includeObject, annotations); - } - - /** - * Get all the fields in a class with the specified modifiers (optionally, with the desired annotation), as well as those in its superclasses. - * - * @param clazz The class to get all fields in - * @param modifiers the modifier mask - * @param includeObject Whether to include fields in {@link Object} - * @param annotations if not null, only include fields with any of these annotations - * @return The public fields in the class - * @see Class#getDeclaredFields() - */ - public static List getDeclaredFieldsRecur(Class clazz, int modifiers, boolean includeObject, Class... annotations) { - final List fields = new ArrayList(); - while (clazz != null && (includeObject || !Object.class.equals(clazz))) { - for (Field field : clazz.getDeclaredFields()) { - if (hasModifiers(field, modifiers) && (annotations == null || hasAnyAnnotation(field, annotations))) { - fields.add(field); - } - } - clazz = clazz.getSuperclass(); - } - return fields; - } - - /** - * Attempts to list all the classes in the specified package as determined by the context class loader - * - * @param packageName the package name to search - * @param recursive if the search should include all subdirectories - * @return a list of classes that exist within that package - * @throws ClassNotFoundException if the package had invalid classes, or does not exist - */ - public static List> getClassesForPackage(String packageName, boolean recursive) throws ClassNotFoundException { - ArrayList directories = new ArrayList(); - try { - ClassLoader cld = Thread.currentThread().getContextClassLoader(); - if (cld == null) { - throw new ClassNotFoundException("Can't get class loader."); - } - String path = packageName.replace('.', '/'); - Enumeration resources = cld.getResources(path); - while (resources.hasMoreElements()) { - File file = new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")); - directories.add(file); - if (recursive) { - findDirs(directories, file); - } - } - } catch (NullPointerException ex) { - throw new ClassNotFoundException(packageName + " does not appear to be a valid package (Null pointer exception)", ex); - } catch (UnsupportedEncodingException encex) { - throw new ClassNotFoundException(packageName + " does not appear to be a valid package (Unsupported encoding)", encex); - } catch (IOException ioex) { - throw new ClassNotFoundException("IOException was thrown when trying to get all resources for " + packageName, ioex); - } - - ArrayList> classes = new ArrayList>(); - for (File directory : directories) { - if (directory.exists()) { - String[] files = directory.list(); - for (String file : files) { - if (file.endsWith(".class")) { - try { - String path = directory.getCanonicalPath().replaceAll("/", ".").replaceAll("\\\\", "."); - int start = path.indexOf(packageName); - path = path.substring(start, path.length()); - classes.add(Class.forName(path + '.' + file.substring(0, file.length() - 6))); - } catch (IOException ex) { - throw new ClassNotFoundException("IOException was thrown when trying to get path for " + file); - } - } - } - } else { - throw new ClassNotFoundException(packageName + " (" + directory.getPath() + ") does not appear to be a valid package"); - } - } - return classes; - } - - /** - * Recursively builds a list of all subdirectories - * - * @param dirs list to add to - * @param dir to search - */ - private static void findDirs(List dirs, File dir) { - for (File f : dir.listFiles()) { - if (f.isDirectory()) { - dirs.add(f); - findDirs(dirs, f); - } - } - } - - /** - * Get all the public methods in a class, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all methods in - * @return The public methods in the class - */ - public static List getMethodsRecur(Class clazz) { - return getMethodsRecur(clazz, false); - } - - /** - * Get all the public methods in a class with the specified modifiers, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all methods in - * @param modifiers the modifier mask - * @return The public methods in the class - */ - public static List getMethodsRecur(Class clazz, int modifiers) { - return getMethodsRecur(clazz, modifiers, false); - } - - /** - * Get all the public methods in a class, as well as those in its superclasses. - * - * @param clazz The class to get all methods in - * @param includeObject Whether to include methods in {@link Object} - * @return The public methods in the class - */ - public static List getMethodsRecur(Class clazz, boolean includeObject) { - return getMethodsRecur(clazz, includeObject, (Class[]) null); - } - - /** - * Get all the public methods in a class with the specified modifiers, as well as those in its superclasses. - * - * @param clazz The class to get all methods in - * @param modifiers the modifier mask - * @param includeObject Whether to include methods in {@link Object} - * @return The public methods in the class - */ - public static List getMethodsRecur(Class clazz, int modifiers, boolean includeObject) { - return getMethodsRecur(clazz, modifiers, includeObject, (Class[]) null); - } - - /** - * Get all the public methods in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all methods in - * @param annotations if not null, only include methods with any of these annotations - * @return The public methods in the class - */ - public static List getMethodsRecur(Class clazz, Class... annotations) { - return getMethodsRecur(clazz, false, annotations); - } - - /** - * Get all the public methods in a class with the desired annotation and the specified modifiers, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all methods in - * @param modifiers the modifier mask - * @param annotations if not null, only include methods with any of these annotations - * @return The public methods in the class - */ - public static List getMethodsRecur(Class clazz, int modifiers, Class... annotations) { - return getMethodsRecur(clazz, modifiers, false, annotations); - } - - /** - * Get all the public methods in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all methods in - * @param includeObject Whether to include methods in {@link Object} - * @param annotations if not null, only include methods with any of these annotations - * @return The public methods in the class - */ - public static List getMethodsRecur(Class clazz, boolean includeObject, Class... annotations) { - return getMethodsRecur(clazz, 0, false, annotations); - } - - /** - * Get all the public methods in a class with the specified modifiers (optionally, with the desired annotation), as well as those in its superclasses. - * - * @param clazz The class to get all methods in - * @param modifiers the modifier mask - * @param includeObject Whether to include methods in {@link Object} - * @param annotations if not null, only include methods with any of these annotations - * @return The public methods in the class - * @see Class#getMethods() - */ - public static List getMethodsRecur(Class clazz, int modifiers, boolean includeObject, Class... annotations) { - final List methods = new ArrayList(); - while (clazz != null && (includeObject || !Object.class.equals(clazz))) { - for (Method method : clazz.getMethods()) { - if (hasModifiers(method, modifiers) && (annotations == null || hasAnyAnnotation(method, annotations))) { - methods.add(method); - } - } - clazz = clazz.getSuperclass(); - } - return methods; - } - - /** - * Get all the methods in a class, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all methods in - * @return The public methods in the class - */ - public static List getDeclaredMethodsRecur(Class clazz) { - return getDeclaredMethodsRecur(clazz, false); - } - - /** - * Get all the methods in a class with the specified modifiers, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all methods in - * @param modifiers the modifier mask - * @return The public methods in the class - */ - public static List getDeclaredMethodsRecur(Class clazz, int modifiers) { - return getDeclaredMethodsRecur(clazz, modifiers, false); - } - - /** - * Get all the methods in a class, as well as those in its superclasses. - * - * @param clazz The class to get all methods in - * @param includeObject Whether to include methods in {@link Object} - * @return The public methods in the class - */ - public static List getDeclaredMethodsRecur(Class clazz, boolean includeObject) { - return getDeclaredMethodsRecur(clazz, 0, includeObject, (Class[]) null); - } - - /** - * Get all the methods in a class with the specified modifiers, as well as those in its superclasses. - * - * @param clazz The class to get all methods in - * @param modifiers the modifier mask - * @param includeObject Whether to include methods in {@link Object} - * @return The public methods in the class - */ - public static List getDeclaredMethodsRecur(Class clazz, int modifiers, boolean includeObject) { - return getDeclaredMethodsRecur(clazz, modifiers, includeObject, (Class[]) null); - } - - /** - * Get all the methods in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all methods in - * @param annotations if not null, only include methods with any of these annotations - * @return The public methods in the class - */ - public static List getDeclaredMethodsRecur(Class clazz, Class... annotations) { - return getDeclaredMethodsRecur(clazz, 0, false, annotations); - } - - /** - * Get all the methods in a class with the desired annotation and the specified modifiers, as well as those in its superclasses (excluding {@link Object}). - * - * @param clazz The class to get all methods in - * @param modifiers the modifier mask - * @param annotations if not null, only include methods with any of these annotations - * @return The public methods in the class - */ - public static List getDeclaredMethodsRecur(Class clazz, int modifiers, Class... annotations) { - return getDeclaredMethodsRecur(clazz, modifiers, false, annotations); - } - - /** - * Get all the methods in a class with the desired annotation, as well as those in its superclasses. - * - * @param clazz The class to get all methods in - * @param includeObject Whether to include methods in {@link Object} - * @return The public methods in the class - */ - public static List getDeclaredMethodsRecur(Class clazz, boolean includeObject, Class... annotations) { - return getDeclaredMethodsRecur(clazz, 0, includeObject, annotations); - } - - /** - * Get all the methods in a class with the specified modifiers (optionally, with the desired annotation), as well as those in its superclasses. - * - * @param clazz The class to get all methods in - * @param modifiers the modifier mask - * @param includeObject Whether to include methods in {@link Object} - * @param annotations if not null, only include methods with any of these annotations - * @return The public methods in the class - * @see Class#getDeclaredMethods() - */ - public static List getDeclaredMethodsRecur(Class clazz, int modifiers, boolean includeObject, Class... annotations) { - final List methods = new ArrayList(); - while (clazz != null && (includeObject || !Object.class.equals(clazz))) { - for (Method method : clazz.getDeclaredMethods()) { - if ((annotations == null || hasAnyAnnotation(method, annotations)) && hasModifiers(method, modifiers)) { - methods.add(method); - } - } - clazz = clazz.getSuperclass(); - } - return methods; - } - - /** - * Check if the {@link Member} has all of the specified modifiers. - * - * @param member the Member to check - * @param modifiers the modifier mask - * @return Whether or not the member has all the modifiers. - */ - public static boolean hasModifiers(Member member, int modifiers) { - return (modifiers & member.getModifiers()) == modifiers; - } - - /** - * Check if the {@link AccessibleObject} has any of the specified annotations. - * - * @param object the object to check - * @param annotations the annotations to look for - * @return Whether or not the object has the annotations - */ - public static boolean hasAnyAnnotation(AccessibleObject object, Class... annotations) { - for (Class annotation : annotations) { - if (object.isAnnotationPresent(annotation)) { - return true; - } - } - return false; - } + /** + * Get all the public fields in a class, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all fields in + * @return The public fields in the class + */ + public static List getFieldsRecur(Class clazz) { + return getFieldsRecur(clazz, false); + } + + /** + * Get all the public fields in a class with the specified modifiers, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all fields in + * @param modifiers the modifier mask + * @return The public fields in the class + */ + public static List getFieldsRecur(Class clazz, int modifiers) { + return getFieldsRecur(clazz, modifiers, false); + } + + /** + * Get all the public fields in a class, as well as those in its superclasses. + * + * @param clazz The class to get all fields in + * @param includeObject Whether to include fields in {@link Object} + * @return The public fields in the class + */ + public static List getFieldsRecur(Class clazz, boolean includeObject) { + return getFieldsRecur(clazz, includeObject, (Class[]) null); + } + + /** + * Get all the public fields in a class with the specified modifiers, as well as those in its superclasses. + * + * @param clazz The class to get all fields in + * @param modifiers the modifier mask + * @param includeObject Whether to include fields in {@link Object} + * @return The public fields in the class + */ + public static List getFieldsRecur(Class clazz, int modifiers, boolean includeObject) { + return getFieldsRecur(clazz, modifiers, includeObject, (Class[]) null); + } + + /** + * Get all the public fields in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all fields in + * @param annotations if not null, only include fields with any of these annotations + * @return The public fields in the class + */ + public static List getFieldsRecur(Class clazz, Class... annotations) { + return getFieldsRecur(clazz, 0, false, annotations); + } + + /** + * Get all the public fields in a class with the desired annotation and the specified modifiers, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all fields in + * @param modifiers the modifier mask + * @param annotations if not null, only include fields with any of these annotations + * @return The public fields in the class + */ + public static List getFieldsRecur(Class clazz, int modifiers, Class... annotations) { + return getFieldsRecur(clazz, modifiers, false, annotations); + } + + /** + * Get all the public fields in a class with the desired annotation, as well as those in its superclasses. + * + * @param clazz The class to get all fields in + * @param includeObject Whether to include fields in {@link Object} + * @param annotations if not null, only include fields with any of these annotations + * @return The public fields in the class + */ + public static List getFieldsRecur(Class clazz, boolean includeObject, Class... annotations) { + return getFieldsRecur(clazz, 0, includeObject, annotations); + } + + /** + * Get all the public fields in a class with the specified modifiers (optionally, with the desired annotation), as well as those in its superclasses. + * + * @param clazz The class to get all fields in + * @param modifiers the modifier mask + * @param includeObject Whether to include fields in {@link Object} + * @param annotations if not null, only include fields with any of these annotations + * @return The public fields in the class + * @see Class#getFields() + */ + public static List getFieldsRecur(Class clazz, int modifiers, boolean includeObject, Class... annotations) { + final List fields = new ArrayList(); + while (clazz != null && (includeObject || !Object.class.equals(clazz))) { + for (Field field : clazz.getFields()) { + if (hasModifiers(field, modifiers) && (annotations == null || hasAnyAnnotation(field, annotations))) { + fields.add(field); + } + } + clazz = clazz.getSuperclass(); + } + return fields; + } + + /** + * Get all the fields in a class, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all fields in + * @return The public fields in the class + */ + public static List getDeclaredFieldsRecur(Class clazz) { + return getDeclaredFieldsRecur(clazz, false); + } + + /** + * Get all the fields in a class with the specified modifiers, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all fields in + * @param modifiers the modifier mask + * @return The public fields in the class + */ + public static List getDeclaredFieldsRecur(Class clazz, int modifiers) { + return getDeclaredFieldsRecur(clazz, modifiers, false); + } + + /** + * Get all the fields in a class, as well as those in its superclasses. + * + * @param clazz The class to get all fields in + * @param includeObject Whether to include fields in {@link Object} + * @return The public fields in the class + */ + public static List getDeclaredFieldsRecur(Class clazz, boolean includeObject) { + return getDeclaredFieldsRecur(clazz, 0, includeObject, (Class[]) null); + } + + /** + * Get all the fields with the specified modifiers in a class, as well as those in its superclasses. + * + * @param clazz The class to get all fields in + * @param modifiers the modifier mask + * @param includeObject Whether to include fields in {@link Object} + * @return The public fields in the class + */ + public static List getDeclaredFieldsRecur(Class clazz, int modifiers, boolean includeObject) { + return getDeclaredFieldsRecur(clazz, modifiers, includeObject, (Class[]) null); + } + + /** + * Get all the fields in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all fields in + * @param annotations if not null, only include fields with any of these annotations + * @return The public fields in the class + */ + public static List getDeclaredFieldsRecur(Class clazz, Class... annotations) { + return getDeclaredFieldsRecur(clazz, 0, false, annotations); + } + + /** + * Get all the fields in a class with the desired annotation and the specified modifiers, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all fields in + * @param modifiers the modifier mask + * @param annotations if not null, only include fields with any of these annotations + * @return The public fields in the class + */ + public static List getDeclaredFieldsRecur(Class clazz, int modifiers, Class... annotations) { + return getDeclaredFieldsRecur(clazz, modifiers, false, annotations); + } + + /** + * Get all the fields in a class with the desired annotation, as well as those in its superclasses. + * + * @param clazz The class to get all fields in + * @param includeObject Whether to include fields in {@link Object} + * @return The public fields in the class + */ + public static List getDeclaredFieldsRecur(Class clazz, boolean includeObject, Class... annotations) { + return getDeclaredFieldsRecur(clazz, 0, includeObject, annotations); + } + + /** + * Get all the fields in a class with the specified modifiers (optionally, with the desired annotation), as well as those in its superclasses. + * + * @param clazz The class to get all fields in + * @param modifiers the modifier mask + * @param includeObject Whether to include fields in {@link Object} + * @param annotations if not null, only include fields with any of these annotations + * @return The public fields in the class + * @see Class#getDeclaredFields() + */ + public static List getDeclaredFieldsRecur(Class clazz, int modifiers, boolean includeObject, Class... annotations) { + final List fields = new ArrayList(); + while (clazz != null && (includeObject || !Object.class.equals(clazz))) { + for (Field field : clazz.getDeclaredFields()) { + if (hasModifiers(field, modifiers) && (annotations == null || hasAnyAnnotation(field, annotations))) { + fields.add(field); + } + } + clazz = clazz.getSuperclass(); + } + return fields; + } + + /** + * Attempts to list all the classes in the specified package as determined by the context class loader + * + * @param packageName the package name to search + * @param recursive if the search should include all subdirectories + * @return a list of classes that exist within that package + * @throws ClassNotFoundException if the package had invalid classes, or does not exist + */ + public static List> getClassesForPackage(String packageName, boolean recursive) throws ClassNotFoundException { + ArrayList directories = new ArrayList(); + try { + ClassLoader cld = Thread.currentThread().getContextClassLoader(); + if (cld == null) { + throw new ClassNotFoundException("Can't get class loader."); + } + String path = packageName.replace('.', '/'); + Enumeration resources = cld.getResources(path); + while (resources.hasMoreElements()) { + File file = new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")); + directories.add(file); + if (recursive) { + findDirs(directories, file); + } + } + } catch (NullPointerException ex) { + throw new ClassNotFoundException(packageName + " does not appear to be a valid package (Null pointer exception)", ex); + } catch (UnsupportedEncodingException encex) { + throw new ClassNotFoundException(packageName + " does not appear to be a valid package (Unsupported encoding)", encex); + } catch (IOException ioex) { + throw new ClassNotFoundException("IOException was thrown when trying to get all resources for " + packageName, ioex); + } + + ArrayList> classes = new ArrayList>(); + for (File directory : directories) { + if (directory.exists()) { + String[] files = directory.list(); + for (String file : files) { + if (file.endsWith(".class")) { + try { + String path = directory.getCanonicalPath().replaceAll("/", ".").replaceAll("\\\\", "."); + int start = path.indexOf(packageName); + path = path.substring(start, path.length()); + classes.add(Class.forName(path + '.' + file.substring(0, file.length() - 6))); + } catch (IOException ex) { + throw new ClassNotFoundException("IOException was thrown when trying to get path for " + file); + } + } + } + } else { + throw new ClassNotFoundException(packageName + " (" + directory.getPath() + ") does not appear to be a valid package"); + } + } + return classes; + } + + /** + * Recursively builds a list of all subdirectories + * + * @param dirs list to add to + * @param dir to search + */ + private static void findDirs(List dirs, File dir) { + for (File f : dir.listFiles()) { + if (f.isDirectory()) { + dirs.add(f); + findDirs(dirs, f); + } + } + } + + /** + * Get all the public methods in a class, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all methods in + * @return The public methods in the class + */ + public static List getMethodsRecur(Class clazz) { + return getMethodsRecur(clazz, false); + } + + /** + * Get all the public methods in a class with the specified modifiers, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all methods in + * @param modifiers the modifier mask + * @return The public methods in the class + */ + public static List getMethodsRecur(Class clazz, int modifiers) { + return getMethodsRecur(clazz, modifiers, false); + } + + /** + * Get all the public methods in a class, as well as those in its superclasses. + * + * @param clazz The class to get all methods in + * @param includeObject Whether to include methods in {@link Object} + * @return The public methods in the class + */ + public static List getMethodsRecur(Class clazz, boolean includeObject) { + return getMethodsRecur(clazz, includeObject, (Class[]) null); + } + + /** + * Get all the public methods in a class with the specified modifiers, as well as those in its superclasses. + * + * @param clazz The class to get all methods in + * @param modifiers the modifier mask + * @param includeObject Whether to include methods in {@link Object} + * @return The public methods in the class + */ + public static List getMethodsRecur(Class clazz, int modifiers, boolean includeObject) { + return getMethodsRecur(clazz, modifiers, includeObject, (Class[]) null); + } + + /** + * Get all the public methods in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all methods in + * @param annotations if not null, only include methods with any of these annotations + * @return The public methods in the class + */ + public static List getMethodsRecur(Class clazz, Class... annotations) { + return getMethodsRecur(clazz, false, annotations); + } + + /** + * Get all the public methods in a class with the desired annotation and the specified modifiers, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all methods in + * @param modifiers the modifier mask + * @param annotations if not null, only include methods with any of these annotations + * @return The public methods in the class + */ + public static List getMethodsRecur(Class clazz, int modifiers, Class... annotations) { + return getMethodsRecur(clazz, modifiers, false, annotations); + } + + /** + * Get all the public methods in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all methods in + * @param includeObject Whether to include methods in {@link Object} + * @param annotations if not null, only include methods with any of these annotations + * @return The public methods in the class + */ + public static List getMethodsRecur(Class clazz, boolean includeObject, Class... annotations) { + return getMethodsRecur(clazz, 0, false, annotations); + } + + /** + * Get all the public methods in a class with the specified modifiers (optionally, with the desired annotation), as well as those in its superclasses. + * + * @param clazz The class to get all methods in + * @param modifiers the modifier mask + * @param includeObject Whether to include methods in {@link Object} + * @param annotations if not null, only include methods with any of these annotations + * @return The public methods in the class + * @see Class#getMethods() + */ + public static List getMethodsRecur(Class clazz, int modifiers, boolean includeObject, Class... annotations) { + final List methods = new ArrayList(); + while (clazz != null && (includeObject || !Object.class.equals(clazz))) { + for (Method method : clazz.getMethods()) { + if (hasModifiers(method, modifiers) && (annotations == null || hasAnyAnnotation(method, annotations))) { + methods.add(method); + } + } + clazz = clazz.getSuperclass(); + } + return methods; + } + + /** + * Get all the methods in a class, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all methods in + * @return The public methods in the class + */ + public static List getDeclaredMethodsRecur(Class clazz) { + return getDeclaredMethodsRecur(clazz, false); + } + + /** + * Get all the methods in a class with the specified modifiers, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all methods in + * @param modifiers the modifier mask + * @return The public methods in the class + */ + public static List getDeclaredMethodsRecur(Class clazz, int modifiers) { + return getDeclaredMethodsRecur(clazz, modifiers, false); + } + + /** + * Get all the methods in a class, as well as those in its superclasses. + * + * @param clazz The class to get all methods in + * @param includeObject Whether to include methods in {@link Object} + * @return The public methods in the class + */ + public static List getDeclaredMethodsRecur(Class clazz, boolean includeObject) { + return getDeclaredMethodsRecur(clazz, 0, includeObject, (Class[]) null); + } + + /** + * Get all the methods in a class with the specified modifiers, as well as those in its superclasses. + * + * @param clazz The class to get all methods in + * @param modifiers the modifier mask + * @param includeObject Whether to include methods in {@link Object} + * @return The public methods in the class + */ + public static List getDeclaredMethodsRecur(Class clazz, int modifiers, boolean includeObject) { + return getDeclaredMethodsRecur(clazz, modifiers, includeObject, (Class[]) null); + } + + /** + * Get all the methods in a class with the desired annotation, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all methods in + * @param annotations if not null, only include methods with any of these annotations + * @return The public methods in the class + */ + public static List getDeclaredMethodsRecur(Class clazz, Class... annotations) { + return getDeclaredMethodsRecur(clazz, 0, false, annotations); + } + + /** + * Get all the methods in a class with the desired annotation and the specified modifiers, as well as those in its superclasses (excluding {@link Object}). + * + * @param clazz The class to get all methods in + * @param modifiers the modifier mask + * @param annotations if not null, only include methods with any of these annotations + * @return The public methods in the class + */ + public static List getDeclaredMethodsRecur(Class clazz, int modifiers, Class... annotations) { + return getDeclaredMethodsRecur(clazz, modifiers, false, annotations); + } + + /** + * Get all the methods in a class with the desired annotation, as well as those in its superclasses. + * + * @param clazz The class to get all methods in + * @param includeObject Whether to include methods in {@link Object} + * @return The public methods in the class + */ + public static List getDeclaredMethodsRecur(Class clazz, boolean includeObject, Class... annotations) { + return getDeclaredMethodsRecur(clazz, 0, includeObject, annotations); + } + + /** + * Get all the methods in a class with the specified modifiers (optionally, with the desired annotation), as well as those in its superclasses. + * + * @param clazz The class to get all methods in + * @param modifiers the modifier mask + * @param includeObject Whether to include methods in {@link Object} + * @param annotations if not null, only include methods with any of these annotations + * @return The public methods in the class + * @see Class#getDeclaredMethods() + */ + public static List getDeclaredMethodsRecur(Class clazz, int modifiers, boolean includeObject, Class... annotations) { + final List methods = new ArrayList(); + while (clazz != null && (includeObject || !Object.class.equals(clazz))) { + for (Method method : clazz.getDeclaredMethods()) { + if ((annotations == null || hasAnyAnnotation(method, annotations)) && hasModifiers(method, modifiers)) { + methods.add(method); + } + } + clazz = clazz.getSuperclass(); + } + return methods; + } + + /** + * Check if the {@link Member} has all of the specified modifiers. + * + * @param member the Member to check + * @param modifiers the modifier mask + * @return Whether or not the member has all the modifiers. + */ + public static boolean hasModifiers(Member member, int modifiers) { + return (modifiers & member.getModifiers()) == modifiers; + } + + /** + * Check if the {@link AccessibleObject} has any of the specified annotations. + * + * @param object the object to check + * @param annotations the annotations to look for + * @return Whether or not the object has the annotations + */ + public static boolean hasAnyAnnotation(AccessibleObject object, Class... annotations) { + for (Class annotation : annotations) { + if (object.isAnnotationPresent(annotation)) { + return true; + } + } + return false; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/AbstractConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/AbstractConfiguration.java index f8419e6..d9fe251 100644 --- a/src/main/java/com/flowpowered/cerealization/config/AbstractConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/AbstractConfiguration.java @@ -32,137 +32,137 @@ * A basic implementation of {@link Configuration} using {@link ConfigurationNodeSource} method implementations from {@link AbstractConfigurationNodeSource} */ public abstract class AbstractConfiguration extends AbstractConfigurationNodeSource implements Configuration { - private String pathSeparator; - private Pattern pathSeparatorPattern; - private boolean writesDefaults; - - public AbstractConfiguration() { - super(null); - this.config = this; - setPathSeparator("."); - setWritesDefaults(true); - } - - /** - * Implementations can use this method to provide the necessary data for calls of load. - * - * @return A map with raw configuration data - * @throws ConfigurationException when an error occurs while loading. - */ - protected abstract Map loadToNodes() throws ConfigurationException; - - /** - * Save the data from this configuration. This method is called from {@link #save()} - * - * @param nodes Configuration as a set of nested ConfigurationNodes - * @throws ConfigurationException When an error occurs while saving the given data. - */ - protected abstract void saveFromNodes(Map nodes) throws ConfigurationException; - - @Override - public void load() throws ConfigurationException { - // Kill the existing children - for (ConfigurationNode child : children.values()) { - detachChild(child); - } - children.clear(); - - Map rawValues = loadToNodes(); - // Load the new children - for (Map.Entry entry : rawValues.entrySet()) { - addChild(entry.getValue()); - } - } - - @Override - public void save() throws ConfigurationException { - saveFromNodes(getChildren()); - } - - @Override - public void setNode(ConfigurationNode node) { - String[] path = node.getPathElements(); - if (path == null || path.length == 0) { - throw new IllegalArgumentException("Path must be specified!"); - } else if (path.length == 1) { - addChild(node); - return; - } - // Gather the parents the node already has for later reference - ConfigurationNode parentCollector = node; - ConfigurationNode[] parents = new ConfigurationNode[path.length]; - int index = parents.length - 1; - parents[parents.length - 1] = node; - while (index > 0 && parentCollector.getParent() != null) { - ConfigurationNode parentNode = parentCollector.getParent() instanceof ConfigurationNode ? (ConfigurationNode) parentCollector.getParent() : null; - if (parentNode == null) { - break; - } - parents[--index] = parentNode; - parentCollector = parentNode; - } - - // Try to use existing parents where they are present - ConfigurationNode parent; - if (parents[0] != null) { - parent = parents[0]; - if (!parent.isAttached() || parent.getParent() != this) { - addChild(parents[0]); - } - } else { - parent = getChild(path[0]); - } - - ConfigurationNodeSource oldParent; - for (int i = 1; i < path.length - 1; ++i) { - oldParent = parent; - parent = parents[i] != null ? parents[i] : oldParent.getChild(path[i], true); - - if (i != path.length - 2 && !parent.isAttached()) { - oldParent.addChild(parent); - } - } - parent.addChild(node); - } - - @Override - public String getPathSeparator() { - return pathSeparator; - } - - @Override - public void setPathSeparator(String pathSeparator) { - this.pathSeparator = pathSeparator; - this.pathSeparatorPattern = Pattern.compile(Pattern.quote(pathSeparator)); - } - - @Override - public Pattern getPathSeparatorPattern() { - return pathSeparatorPattern; - } - - @Override - public boolean doesWriteDefaults() { - return writesDefaults; - } - - @Override - public void setWritesDefaults(boolean writesDefaults) { - this.writesDefaults = writesDefaults; - } - - @Override - public String[] splitNodePath(String path) { - return getPathSeparatorPattern().split(path); - } - - @Override - public String[] ensureCorrectPath(String[] rawPath) { - return rawPath; - } - - @Override - public String[] getPathElements() { - return ArrayUtils.EMPTY_STRING_ARRAY; - } + private String pathSeparator; + private Pattern pathSeparatorPattern; + private boolean writesDefaults; + + public AbstractConfiguration() { + super(null); + this.config = this; + setPathSeparator("."); + setWritesDefaults(true); + } + + /** + * Implementations can use this method to provide the necessary data for calls of load. + * + * @return A map with raw configuration data + * @throws ConfigurationException when an error occurs while loading. + */ + protected abstract Map loadToNodes() throws ConfigurationException; + + /** + * Save the data from this configuration. This method is called from {@link #save()} + * + * @param nodes Configuration as a set of nested ConfigurationNodes + * @throws ConfigurationException When an error occurs while saving the given data. + */ + protected abstract void saveFromNodes(Map nodes) throws ConfigurationException; + + @Override + public void load() throws ConfigurationException { + // Kill the existing children + for (ConfigurationNode child : children.values()) { + detachChild(child); + } + children.clear(); + + Map rawValues = loadToNodes(); + // Load the new children + for (Map.Entry entry : rawValues.entrySet()) { + addChild(entry.getValue()); + } + } + + @Override + public void save() throws ConfigurationException { + saveFromNodes(getChildren()); + } + + @Override + public void setNode(ConfigurationNode node) { + String[] path = node.getPathElements(); + if (path == null || path.length == 0) { + throw new IllegalArgumentException("Path must be specified!"); + } else if (path.length == 1) { + addChild(node); + return; + } + // Gather the parents the node already has for later reference + ConfigurationNode parentCollector = node; + ConfigurationNode[] parents = new ConfigurationNode[path.length]; + int index = parents.length - 1; + parents[parents.length - 1] = node; + while (index > 0 && parentCollector.getParent() != null) { + ConfigurationNode parentNode = parentCollector.getParent() instanceof ConfigurationNode ? (ConfigurationNode) parentCollector.getParent() : null; + if (parentNode == null) { + break; + } + parents[--index] = parentNode; + parentCollector = parentNode; + } + + // Try to use existing parents where they are present + ConfigurationNode parent; + if (parents[0] != null) { + parent = parents[0]; + if (!parent.isAttached() || parent.getParent() != this) { + addChild(parents[0]); + } + } else { + parent = getChild(path[0]); + } + + ConfigurationNodeSource oldParent; + for (int i = 1; i < path.length - 1; ++i) { + oldParent = parent; + parent = parents[i] != null ? parents[i] : oldParent.getChild(path[i], true); + + if (i != path.length - 2 && !parent.isAttached()) { + oldParent.addChild(parent); + } + } + parent.addChild(node); + } + + @Override + public String getPathSeparator() { + return pathSeparator; + } + + @Override + public void setPathSeparator(String pathSeparator) { + this.pathSeparator = pathSeparator; + this.pathSeparatorPattern = Pattern.compile(Pattern.quote(pathSeparator)); + } + + @Override + public Pattern getPathSeparatorPattern() { + return pathSeparatorPattern; + } + + @Override + public boolean doesWriteDefaults() { + return writesDefaults; + } + + @Override + public void setWritesDefaults(boolean writesDefaults) { + this.writesDefaults = writesDefaults; + } + + @Override + public String[] splitNodePath(String path) { + return getPathSeparatorPattern().split(path); + } + + @Override + public String[] ensureCorrectPath(String[] rawPath) { + return rawPath; + } + + @Override + public String[] getPathElements() { + return ArrayUtils.EMPTY_STRING_ARRAY; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/AbstractConfigurationNodeSource.java b/src/main/java/com/flowpowered/cerealization/config/AbstractConfigurationNodeSource.java index 91f412d..8eaa41d 100644 --- a/src/main/java/com/flowpowered/cerealization/config/AbstractConfigurationNodeSource.java +++ b/src/main/java/com/flowpowered/cerealization/config/AbstractConfigurationNodeSource.java @@ -37,182 +37,182 @@ * A basic implementation of ConfigurationNodeSource. */ public abstract class AbstractConfigurationNodeSource implements ConfigurationNodeSource { - protected final Map children = new LinkedHashMap(); - protected Configuration config; - - public AbstractConfigurationNodeSource(Configuration config) { - this.config = config; - } - - @Override - public Configuration getConfiguration() { - return config; - } - - @Override - public ConfigurationNode getChild(String name) { - return getChild(name, false); - } - - @Override - public ConfigurationNode getChild(String name, boolean add) { - ConfigurationNode node = children.get(name); - if (node == null) { - node = createConfigurationNode(ArrayUtils.add(getPathElements(), name), null); - node.setParent(this); - if (add) { - addChild(node); - } - } - return node; - } - - @Override - public ConfigurationNode addChild(ConfigurationNode node) { - ConfigurationNode ret = children.put(node.getPathElements()[node.getPathElements().length - 1], node); - node.setAttached(true); - node.setParent(this); - return ret; - } - - @Override - public ConfigurationNode addNode(String name) { - if (name.contains(getConfiguration().getPathSeparator())) { - String[] split = name.split(getConfiguration().getPathSeparator()); - ConfigurationNode newNode = createConfigurationNode(ArrayUtils.add(getPathElements(), split[0]), null); - addChild(newNode); - ArrayUtils.remove(split, 0); - newNode.addNode(StringUtils.join(split, getConfiguration().getPathSeparator())); - return newNode; - } - ConfigurationNode newNode = createConfigurationNode(ArrayUtils.add(getPathElements(), name), null); - addChild(newNode); - return newNode; - } - - @Override - public void addChildren(ConfigurationNode... nodes) { - for (ConfigurationNode child : nodes) { - addChild(child); - } - } - - @Override - public ConfigurationNode removeChild(String key) { - return removeChild(children.get(key)); - } - - /** - * Detach a node from this node source and remove its children If the node's parent isn't this, the method will silently return After this method, the node will have a parent of null, no children, - * and be marked as detached - * - * @param node The node to detach - */ - protected void detachChild(ConfigurationNode node) { - if (node.getParent() != this) { - return; - } - node.setAttached(false); - node.setParent(null); - for (Iterator i = node.children.values().iterator(); i.hasNext(); ) { - node.detachChild(i.next()); - i.remove(); - } - } - - @Override - public ConfigurationNode removeChild(ConfigurationNode node) { - if (node != null) { - if (node.getParent() != this) { - return null; - } - if (children.remove(node.getPathElements()[node.getPathElements().length - 1]) == null) { - return null; - } - detachChild(node); - } - return node; - } - - @Override - public Map getChildren() { - return Collections.unmodifiableMap(children); - } - - @Override - public Map getValues() { - Map ret = new LinkedHashMap(); - for (Map.Entry entry : getChildren().entrySet()) { - ret.put(entry.getKey(), entry.getValue().getValue()); - } - return ret; - } - - @Override - public Set getKeys(boolean deep) { - Set keys = new LinkedHashSet(deep ? children.size() * 2 : children.size()); - for (Map.Entry entry : children.entrySet()) { - keys.add(entry.getKey()); - if (deep) { - for (String key : entry.getValue().getKeys(true)) { - keys.add(entry.getKey() + getConfiguration().getPathSeparator() + key); - } - } - } - return keys; - } - - @Override - public ConfigurationNode getNode(String path) { - if (path.contains(getConfiguration().getPathSeparator())) { - return getNode(getConfiguration().splitNodePath(path)); - } else { - return getChild(path); - } - } - - @Override - public ConfigurationNode getNode(String... path) { - if (path.length == 0) { - throw new IllegalArgumentException("Path must not be empty!"); - } - path = getConfiguration().ensureCorrectPath(path); - ConfigurationNode node = getChild(path[0]); - for (int i = 1; i < path.length && node != null && node.isAttached(); ++i) { - node = node.getChild(path[i]); - } - - return node == null || !node.isAttached() ? createConfigurationNode(path, null) : node; - } - - public ConfigurationNode createConfigurationNode(String[] path, Object value) { - return new ConfigurationNode(getConfiguration(), path, value); - } - - @Override - public boolean hasChildren() { - return children.size() > 0; - } - - @Override - public boolean hasChild(String key) { - return children.containsKey(key); - } - - @Override - public boolean hasNode(String... path) { - if (path.length == 0) { - throw new IllegalArgumentException("Path must not be empty!"); - } - path = getConfiguration().ensureCorrectPath(path); - AbstractConfigurationNodeSource current = this; - for (String key : path) { - ConfigurationNode node = current.children.get(key); - if (node == null) { - return false; - } - current = node; - } - return true; - } + protected final Map children = new LinkedHashMap(); + protected Configuration config; + + public AbstractConfigurationNodeSource(Configuration config) { + this.config = config; + } + + @Override + public Configuration getConfiguration() { + return config; + } + + @Override + public ConfigurationNode getChild(String name) { + return getChild(name, false); + } + + @Override + public ConfigurationNode getChild(String name, boolean add) { + ConfigurationNode node = children.get(name); + if (node == null) { + node = createConfigurationNode(ArrayUtils.add(getPathElements(), name), null); + node.setParent(this); + if (add) { + addChild(node); + } + } + return node; + } + + @Override + public ConfigurationNode addChild(ConfigurationNode node) { + ConfigurationNode ret = children.put(node.getPathElements()[node.getPathElements().length - 1], node); + node.setAttached(true); + node.setParent(this); + return ret; + } + + @Override + public ConfigurationNode addNode(String name) { + if (name.contains(getConfiguration().getPathSeparator())) { + String[] split = name.split(getConfiguration().getPathSeparator()); + ConfigurationNode newNode = createConfigurationNode(ArrayUtils.add(getPathElements(), split[0]), null); + addChild(newNode); + ArrayUtils.remove(split, 0); + newNode.addNode(StringUtils.join(split, getConfiguration().getPathSeparator())); + return newNode; + } + ConfigurationNode newNode = createConfigurationNode(ArrayUtils.add(getPathElements(), name), null); + addChild(newNode); + return newNode; + } + + @Override + public void addChildren(ConfigurationNode... nodes) { + for (ConfigurationNode child : nodes) { + addChild(child); + } + } + + @Override + public ConfigurationNode removeChild(String key) { + return removeChild(children.get(key)); + } + + /** + * Detach a node from this node source and remove its children If the node's parent isn't this, the method will silently return After this method, the node will have a parent of null, no children, + * and be marked as detached + * + * @param node The node to detach + */ + protected void detachChild(ConfigurationNode node) { + if (node.getParent() != this) { + return; + } + node.setAttached(false); + node.setParent(null); + for (Iterator i = node.children.values().iterator(); i.hasNext(); ) { + node.detachChild(i.next()); + i.remove(); + } + } + + @Override + public ConfigurationNode removeChild(ConfigurationNode node) { + if (node != null) { + if (node.getParent() != this) { + return null; + } + if (children.remove(node.getPathElements()[node.getPathElements().length - 1]) == null) { + return null; + } + detachChild(node); + } + return node; + } + + @Override + public Map getChildren() { + return Collections.unmodifiableMap(children); + } + + @Override + public Map getValues() { + Map ret = new LinkedHashMap(); + for (Map.Entry entry : getChildren().entrySet()) { + ret.put(entry.getKey(), entry.getValue().getValue()); + } + return ret; + } + + @Override + public Set getKeys(boolean deep) { + Set keys = new LinkedHashSet(deep ? children.size() * 2 : children.size()); + for (Map.Entry entry : children.entrySet()) { + keys.add(entry.getKey()); + if (deep) { + for (String key : entry.getValue().getKeys(true)) { + keys.add(entry.getKey() + getConfiguration().getPathSeparator() + key); + } + } + } + return keys; + } + + @Override + public ConfigurationNode getNode(String path) { + if (path.contains(getConfiguration().getPathSeparator())) { + return getNode(getConfiguration().splitNodePath(path)); + } else { + return getChild(path); + } + } + + @Override + public ConfigurationNode getNode(String... path) { + if (path.length == 0) { + throw new IllegalArgumentException("Path must not be empty!"); + } + path = getConfiguration().ensureCorrectPath(path); + ConfigurationNode node = getChild(path[0]); + for (int i = 1; i < path.length && node != null && node.isAttached(); ++i) { + node = node.getChild(path[i]); + } + + return node == null || !node.isAttached() ? createConfigurationNode(path, null) : node; + } + + public ConfigurationNode createConfigurationNode(String[] path, Object value) { + return new ConfigurationNode(getConfiguration(), path, value); + } + + @Override + public boolean hasChildren() { + return children.size() > 0; + } + + @Override + public boolean hasChild(String key) { + return children.containsKey(key); + } + + @Override + public boolean hasNode(String... path) { + if (path.length == 0) { + throw new IllegalArgumentException("Path must not be empty!"); + } + path = getConfiguration().ensureCorrectPath(path); + AbstractConfigurationNodeSource current = this; + for (String key : path) { + ConfigurationNode node = current.children.get(key); + if (node == null) { + return false; + } + current = node; + } + return true; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/Configuration.java b/src/main/java/com/flowpowered/cerealization/config/Configuration.java index ea5b722..282225c 100644 --- a/src/main/java/com/flowpowered/cerealization/config/Configuration.java +++ b/src/main/java/com/flowpowered/cerealization/config/Configuration.java @@ -26,74 +26,74 @@ import java.util.regex.Pattern; public interface Configuration extends ConfigurationNodeSource { - /** - * Load the configuration's values - * - * @throws ConfigurationException if an error occurs while loading the configuration - */ - void load() throws ConfigurationException; + /** + * Load the configuration's values + * + * @throws ConfigurationException if an error occurs while loading the configuration + */ + void load() throws ConfigurationException; - /** - * Save the configuration's values - * - * @throws com.flowpowered.cerealization.config.ConfigurationException when an error occurs - */ - void save() throws ConfigurationException; + /** + * Save the configuration's values + * + * @throws com.flowpowered.cerealization.config.ConfigurationException when an error occurs + */ + void save() throws ConfigurationException; - /** - * Adds the given node to the configuration structure This will attempt to use the node's existing parents in the configuration structure where possible - * - * @param node The node to add - */ - void setNode(ConfigurationNode node); + /** + * Adds the given node to the configuration structure This will attempt to use the node's existing parents in the configuration structure where possible + * + * @param node The node to add + */ + void setNode(ConfigurationNode node); - /** - * The path separator to use with {@link #getNode(String)} The path separator splits paths as a literal string, not a regular expression. - * - * @return The configuration's path separator - */ - String getPathSeparator(); + /** + * The path separator to use with {@link #getNode(String)} The path separator splits paths as a literal string, not a regular expression. + * + * @return The configuration's path separator + */ + String getPathSeparator(); - /** - * Sets this configuration's path separator. More information on how the path separator functions in {@link #getPathSeparator()} - * - * @param pathSeparator The path separator - * @see #getPathSeparator() - */ - void setPathSeparator(String pathSeparator); + /** + * Sets this configuration's path separator. More information on how the path separator functions in {@link #getPathSeparator()} + * + * @param pathSeparator The path separator + * @see #getPathSeparator() + */ + void setPathSeparator(String pathSeparator); - Pattern getPathSeparatorPattern(); + Pattern getPathSeparatorPattern(); - /** - * Whether this configuration writes default values (from {@link ConfigurationNode#getValue(Object)} to the configuration structure - * - * @return Whether this configuration writes defaults - */ - boolean doesWriteDefaults(); + /** + * Whether this configuration writes default values (from {@link ConfigurationNode#getValue(Object)} to the configuration structure + * + * @return Whether this configuration writes defaults + */ + boolean doesWriteDefaults(); - /** - * Sets whether this configuration writes defaults - * - * @param writesDefaults Whether this configuration writes defaults - * @see #doesWriteDefaults() for info on what this means - */ - void setWritesDefaults(boolean writesDefaults); + /** + * Sets whether this configuration writes defaults + * + * @param writesDefaults Whether this configuration writes defaults + * @see #doesWriteDefaults() for info on what this means + */ + void setWritesDefaults(boolean writesDefaults); - /** - * Split the provided path into a string array suitable for accessing the correct configuration children. Normally this just splits the path with the {@link #getPathSeparator()}, but can limit how - * deep a child path can go or whether this configuration can even have children. - * - * @param path The path to split - * @return The connectly split path. - */ - String[] splitNodePath(String path); + /** + * Split the provided path into a string array suitable for accessing the correct configuration children. Normally this just splits the path with the {@link #getPathSeparator()}, but can limit how + * deep a child path can go or whether this configuration can even have children. + * + * @param path The path to split + * @return The connectly split path. + */ + String[] splitNodePath(String path); - /** - * Make sure the provided path meets the requirements. A correct implementation of Configuration will impose the same restrictions on this and {@link #splitNodePath(String)}, so invoking this method - * on an array from {@link #splitNodePath(String)} would return the original array. - * - * @param rawPath The raw path of the configuration - * @return The corrected input path - */ - String[] ensureCorrectPath(String[] rawPath); + /** + * Make sure the provided path meets the requirements. A correct implementation of Configuration will impose the same restrictions on this and {@link #splitNodePath(String)}, so invoking this method + * on an array from {@link #splitNodePath(String)} would return the original array. + * + * @param rawPath The raw path of the configuration + * @return The corrected input path + */ + String[] ensureCorrectPath(String[] rawPath); } diff --git a/src/main/java/com/flowpowered/cerealization/config/ConfigurationException.java b/src/main/java/com/flowpowered/cerealization/config/ConfigurationException.java index 3d6a36c..ecb4854 100644 --- a/src/main/java/com/flowpowered/cerealization/config/ConfigurationException.java +++ b/src/main/java/com/flowpowered/cerealization/config/ConfigurationException.java @@ -27,17 +27,17 @@ * Configuration exception. */ public class ConfigurationException extends Exception { - private static final long serialVersionUID = 0L; + private static final long serialVersionUID = 0L; - public ConfigurationException() { - super(); - } + public ConfigurationException() { + super(); + } - public ConfigurationException(String msg) { - super(msg); - } + public ConfigurationException(String msg) { + super(msg); + } - public ConfigurationException(Throwable cause) { - super(cause); - } + public ConfigurationException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/ConfigurationHolder.java b/src/main/java/com/flowpowered/cerealization/config/ConfigurationHolder.java index 7240c05..9cf46f9 100644 --- a/src/main/java/com/flowpowered/cerealization/config/ConfigurationHolder.java +++ b/src/main/java/com/flowpowered/cerealization/config/ConfigurationHolder.java @@ -34,143 +34,143 @@ * This object holds a reference to a ConfigurationNode and provides all the methods to get its value, but using the default provided in the constructor */ public class ConfigurationHolder extends ValueHolderBase implements ConfigurationNodeSource { - private Configuration configuration; - private final String[] path; - private Object def; - - public ConfigurationHolder(Configuration config, Object def, String... path) { - this.path = path; - this.configuration = config; - this.def = def; - } - - public ConfigurationHolder(Object value, String... path) { - this(null, value, path); - } - - private ConfigurationNode getNode() { - if (getConfiguration() == null) { - throw new IllegalStateException("The ConfigurationHolder at path " + ArrayUtils.toString(path) + " is not attached to a Configuration!"); - } - return getConfiguration().getNode(getPathElements()); - } - - @Override - public Configuration getConfiguration() { - return configuration; - } - - public void setConfiguration(Configuration config) { - this.configuration = config; - } - - @Override - public String[] getPathElements() { - return path; - } - - /** - * Gets the default value of this Configuration Holder - * - * @return the default value - */ - public Object getDefaultValue() { - return this.def; - } - - /** - * Sets the default value for this Configuration Holder - * - * @param def value to set to - */ - public void setDefaultValue(Object def) { - this.def = def; - } - - @Override - public Object getValue() { - return getNode().getValue(this.def); - } - - @Override - public Object getValue(Object def) { - return getNode().getValue(this.def); - } - - public Object setValue(Object value) { - return getNode().setValue(value); - } - - @Override - public ConfigurationNode getChild(String name) { - return getNode().getChild(name); - } - - @Override - public ConfigurationNode getChild(String name, boolean add) { - return getNode().getChild(name, add); - } - - @Override - public ConfigurationNode addChild(ConfigurationNode node) { - return getNode().addChild(node); - } - - @Override - public ConfigurationNode addNode(String name) { - return getNode().addNode(name); - } - - @Override - public void addChildren(ConfigurationNode... nodes) { - getNode().addChildren(nodes); - } - - @Override - public ConfigurationNode removeChild(String key) { - return getNode().removeChild(key); - } - - @Override - public ConfigurationNode removeChild(ConfigurationNode node) { - return getNode().removeChild(node); - } - - @Override - public Map getChildren() { - return getNode().getChildren(); - } - - @Override - public Map getValues() { - return getNode().getValues(); - } - - @Override - public Set getKeys(boolean deep) { - return getNode().getKeys(deep); - } - - @Override - public ConfigurationNode getNode(String path) { - return getNode().getNode(path); - } - - @Override - public ConfigurationNode getNode(String... path) { - return getNode().getNode(path); - } - - @Override - public boolean hasChildren() { - return getNode().hasChildren(); - } - - public boolean hasChild(String key) { - return getNode().hasChild(key); - } - - public boolean hasNode(String... path) { - return getNode().hasNode(path); - } + private Configuration configuration; + private final String[] path; + private Object def; + + public ConfigurationHolder(Configuration config, Object def, String... path) { + this.path = path; + this.configuration = config; + this.def = def; + } + + public ConfigurationHolder(Object value, String... path) { + this(null, value, path); + } + + private ConfigurationNode getNode() { + if (getConfiguration() == null) { + throw new IllegalStateException("The ConfigurationHolder at path " + ArrayUtils.toString(path) + " is not attached to a Configuration!"); + } + return getConfiguration().getNode(getPathElements()); + } + + @Override + public Configuration getConfiguration() { + return configuration; + } + + public void setConfiguration(Configuration config) { + this.configuration = config; + } + + @Override + public String[] getPathElements() { + return path; + } + + /** + * Gets the default value of this Configuration Holder + * + * @return the default value + */ + public Object getDefaultValue() { + return this.def; + } + + /** + * Sets the default value for this Configuration Holder + * + * @param def value to set to + */ + public void setDefaultValue(Object def) { + this.def = def; + } + + @Override + public Object getValue() { + return getNode().getValue(this.def); + } + + @Override + public Object getValue(Object def) { + return getNode().getValue(this.def); + } + + public Object setValue(Object value) { + return getNode().setValue(value); + } + + @Override + public ConfigurationNode getChild(String name) { + return getNode().getChild(name); + } + + @Override + public ConfigurationNode getChild(String name, boolean add) { + return getNode().getChild(name, add); + } + + @Override + public ConfigurationNode addChild(ConfigurationNode node) { + return getNode().addChild(node); + } + + @Override + public ConfigurationNode addNode(String name) { + return getNode().addNode(name); + } + + @Override + public void addChildren(ConfigurationNode... nodes) { + getNode().addChildren(nodes); + } + + @Override + public ConfigurationNode removeChild(String key) { + return getNode().removeChild(key); + } + + @Override + public ConfigurationNode removeChild(ConfigurationNode node) { + return getNode().removeChild(node); + } + + @Override + public Map getChildren() { + return getNode().getChildren(); + } + + @Override + public Map getValues() { + return getNode().getValues(); + } + + @Override + public Set getKeys(boolean deep) { + return getNode().getKeys(deep); + } + + @Override + public ConfigurationNode getNode(String path) { + return getNode().getNode(path); + } + + @Override + public ConfigurationNode getNode(String... path) { + return getNode().getNode(path); + } + + @Override + public boolean hasChildren() { + return getNode().hasChildren(); + } + + public boolean hasChild(String key) { + return getNode().hasChild(key); + } + + public boolean hasNode(String... path) { + return getNode().hasNode(path); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/ConfigurationHolderConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/ConfigurationHolderConfiguration.java index 3fd4db4..017ca63 100644 --- a/src/main/java/com/flowpowered/cerealization/config/ConfigurationHolderConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/ConfigurationHolderConfiguration.java @@ -34,31 +34,31 @@ * fields will be automatically associated with the attached configuration and have their default values loaded into the configuration as needed on load */ public abstract class ConfigurationHolderConfiguration extends ConfigurationWrapper { - private final List holders = new ArrayList(); + private final List holders = new ArrayList(); - public ConfigurationHolderConfiguration(Configuration base) { - super(base); - for (Field field : ReflectionUtils.getDeclaredFieldsRecur(getClass())) { - field.setAccessible(true); + public ConfigurationHolderConfiguration(Configuration base) { + super(base); + for (Field field : ReflectionUtils.getDeclaredFieldsRecur(getClass())) { + field.setAccessible(true); - if (ConfigurationHolder.class.isAssignableFrom(field.getType())) { - holders.add(field); - } - } - } + if (ConfigurationHolder.class.isAssignableFrom(field.getType())) { + holders.add(field); + } + } + } - @Override - public void load() throws ConfigurationException { - super.load(); - for (Field field : this.holders) { - try { - ConfigurationHolder holder = (ConfigurationHolder) field.get(this); - if (holder != null) { - holder.setConfiguration(getConfiguration()); - holder.getValue(); // Initialize the ConfigurationHolder's value - } - } catch (IllegalAccessException e) { - } - } - } + @Override + public void load() throws ConfigurationException { + super.load(); + for (Field field : this.holders) { + try { + ConfigurationHolder holder = (ConfigurationHolder) field.get(this); + if (holder != null) { + holder.setConfiguration(getConfiguration()); + holder.getValue(); // Initialize the ConfigurationHolder's value + } + } catch (IllegalAccessException e) { + } + } + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/ConfigurationNode.java b/src/main/java/com/flowpowered/cerealization/config/ConfigurationNode.java index ad61556..5ae1cd6 100644 --- a/src/main/java/com/flowpowered/cerealization/config/ConfigurationNode.java +++ b/src/main/java/com/flowpowered/cerealization/config/ConfigurationNode.java @@ -41,348 +41,348 @@ import com.flowpowered.cerealization.data.ValueHolderBase; public class ConfigurationNode extends AbstractConfigurationNodeSource implements ValueHolder { - private Object value; - private boolean attached; - private WeakReference parent = new WeakReference(null); - private final String[] path; - private final ValueHolderBase valueHolder = new ValueHolderBase(this); - - public ConfigurationNode(Configuration config, String[] path, Object value) { - super(config); - this.path = path; - if (value != null) { - setValue(value); - } - } - - // Delegated methods - - @Override - public boolean getBoolean() { - return valueHolder.getBoolean(); - } - - @Override - public boolean getBoolean(boolean def) { - return valueHolder.getBoolean(def); - } - - @Override - public byte getByte() { - return valueHolder.getByte(); - } - - @Override - public byte getByte(byte def) { - return valueHolder.getByte(def); - } - - @Override - public float getFloat() { - return valueHolder.getFloat(); - } - - @Override - public float getFloat(float def) { - return valueHolder.getFloat(def); - } - - @Override - public short getShort() { - return valueHolder.getShort(); - } - - @Override - public short getShort(short def) { - return valueHolder.getShort(def); - } - - @Override - public int getInt() { - return valueHolder.getInt(); - } - - @Override - public int getInt(int def) { - return valueHolder.getInt(def); - } - - @Override - public long getLong() { - return valueHolder.getLong(); - } - - @Override - public long getLong(long def) { - return valueHolder.getLong(def); - } - - @Override - public double getDouble() { - return valueHolder.getDouble(); - } - - @Override - public double getDouble(double def) { - return valueHolder.getDouble(def); - } - - @Override - public BigInteger getBigInt() { - return valueHolder.getBigInt(); - } - - @Override - public BigInteger getBigInt(BigInteger def) { - return valueHolder.getBigInt(def); - } - - @Override - public BigDecimal getDecimal() { - return valueHolder.getDecimal(); - } - - @Override - public BigDecimal getDecimal(BigDecimal def) { - return valueHolder.getDecimal(def); - } - - @Override - public Date getDate() { - return valueHolder.getDate(); - } - - public Date getDate(Date def) { - return valueHolder.getDate(def); - } - - @Override - public byte[] getBytes() { - return valueHolder.getBytes(); - } - - public byte[] getBytes(byte[] def) { - return valueHolder.getBytes(def); - } - - @Override - public String getString() { - return valueHolder.getString(); - } - - @Override - public String getString(String def) { - return valueHolder.getString(def); - } - - @Override - public T getTypedValue(Class type) { - return valueHolder.getTypedValue(type); - } - - @Override - public T getTypedValue(Class type, T def) { - return valueHolder.getTypedValue(type, def); - } - - @Override - public Object getTypedValue(Type type) { - return valueHolder.getTypedValue(type); - } - - @Override - public Object getTypedValue(Type type, Object def) { - return valueHolder.getTypedValue(type, def); - } - - @Override - public List getList() { - return valueHolder.getList(); - } - - @Override - public List getList(List def) { - return valueHolder.getList(def); - } - - @Override - public List getStringList() { - return valueHolder.getStringList(); - } - - @Override - public List getStringList(List def) { - return valueHolder.getStringList(def); - } - - @Override - public List getIntegerList() { - return valueHolder.getIntegerList(); - } - - @Override - public List getIntegerList(List def) { - return valueHolder.getIntegerList(def); - } - - @Override - public List getDoubleList() { - return valueHolder.getDoubleList(); - } - - @Override - public List getDoubleList(List def) { - return valueHolder.getDoubleList(def); - } - - @Override - public List getBooleanList() { - return valueHolder.getBooleanList(); - } - - @Override - public List getBooleanList(List def) { - return valueHolder.getBooleanList(def); - } - - // Actual value access - - @Override - public Object getValue() { - return getValue(null); - } - - @Override - public Object getValue(Object def) { - if (hasChildren()) { - return getValues(); - } - - if (value != null) { - return value; - } - - if (def != null && getConfiguration().doesWriteDefaults()) { - setValue(def); - } - - return def; - } - - /** - * Sets the configuration's value - * - * @param value The value to set - * @return The previous value of the configuration - */ - public Object setValue(Object value) { - if (value instanceof ValueHolder) { - value = ((ValueHolder) value).getValue(); - } - checkAdded(); - Object old = this.getValue(); - if (value instanceof Map) { - this.value = null; - removeChildren(); - for (Map.Entry entry : ((Map) value).entrySet()) { - addChild(createConfigurationNode(ArrayUtils.add(getPathElements(), entry.getKey().toString()), entry.getValue())); - } - } else { - if (value != null) { - removeChildren(); - } - this.value = value; - } - return old; - } - - /** - * Sets the type and value - * - * @return the previous value - */ - public Object setValue(Type type, Object value) { - return setValue(Serialization.serialize(type, value)); - } - - // Util methods to make sure stuff is connected properly - - /** - * Detach all this node's children, making sure to remove associations both ways - */ - private void removeChildren() { - for (ConfigurationNode node : children.values()) { - detachChild(node); - } - children.clear(); - } - - protected void checkAdded() { - if (!isAttached()) { - getConfiguration().setNode(this); - } - } - - public void remove() { - if (isAttached()) { - getParent().removeChild(this); - } - this.value = null; - } - - /** - * Return whether a ConfigurationNode is attached to any configuration - * - * @return if this node is attached to any configuration - */ - public boolean isAttached() { - return attached; - } - - protected void setAttached(boolean value) { - this.attached = value; - } - - public ConfigurationNodeSource getParent() { - return parent.get(); - } - - protected void setParent(ConfigurationNodeSource parent) { - if (parent == this) { - throw new IllegalArgumentException("Attempted circular inheritance between child" + getPath() + " and parent."); - } - Set visited = new HashSet(); - ConfigurationNodeSource oldParent = getParent(); - while (oldParent != null) { - if (visited.contains(oldParent)) { - throw new IllegalArgumentException("Attempted circular inheritance between child " + getPath() + " and parent " + - (oldParent instanceof ConfigurationNode ? ((ConfigurationNode) oldParent).getPath() : "root") + "."); - } - visited.add(oldParent); - oldParent = oldParent instanceof ConfigurationNode ? ((ConfigurationNode) oldParent).getParent() : null; - } - this.parent = new WeakReference(parent); - } - - @Override - public ConfigurationNode addChild(ConfigurationNode node) { - checkAdded(); - return super.addChild(node); - } - - /** - * @return The path, joined by the {@link AbstractConfiguration#getPathSeparator()} of the attached configuration - * @see #getPathElements - */ - public String getPath() { - return StringUtils.join(getPathElements(), getConfiguration().getPathSeparator()); - } - - /** - * @return the elements of this node's path, unjoined - */ - @Override - public String[] getPathElements() { - return path; - } + private Object value; + private boolean attached; + private WeakReference parent = new WeakReference(null); + private final String[] path; + private final ValueHolderBase valueHolder = new ValueHolderBase(this); + + public ConfigurationNode(Configuration config, String[] path, Object value) { + super(config); + this.path = path; + if (value != null) { + setValue(value); + } + } + + // Delegated methods + + @Override + public boolean getBoolean() { + return valueHolder.getBoolean(); + } + + @Override + public boolean getBoolean(boolean def) { + return valueHolder.getBoolean(def); + } + + @Override + public byte getByte() { + return valueHolder.getByte(); + } + + @Override + public byte getByte(byte def) { + return valueHolder.getByte(def); + } + + @Override + public float getFloat() { + return valueHolder.getFloat(); + } + + @Override + public float getFloat(float def) { + return valueHolder.getFloat(def); + } + + @Override + public short getShort() { + return valueHolder.getShort(); + } + + @Override + public short getShort(short def) { + return valueHolder.getShort(def); + } + + @Override + public int getInt() { + return valueHolder.getInt(); + } + + @Override + public int getInt(int def) { + return valueHolder.getInt(def); + } + + @Override + public long getLong() { + return valueHolder.getLong(); + } + + @Override + public long getLong(long def) { + return valueHolder.getLong(def); + } + + @Override + public double getDouble() { + return valueHolder.getDouble(); + } + + @Override + public double getDouble(double def) { + return valueHolder.getDouble(def); + } + + @Override + public BigInteger getBigInt() { + return valueHolder.getBigInt(); + } + + @Override + public BigInteger getBigInt(BigInteger def) { + return valueHolder.getBigInt(def); + } + + @Override + public BigDecimal getDecimal() { + return valueHolder.getDecimal(); + } + + @Override + public BigDecimal getDecimal(BigDecimal def) { + return valueHolder.getDecimal(def); + } + + @Override + public Date getDate() { + return valueHolder.getDate(); + } + + public Date getDate(Date def) { + return valueHolder.getDate(def); + } + + @Override + public byte[] getBytes() { + return valueHolder.getBytes(); + } + + public byte[] getBytes(byte[] def) { + return valueHolder.getBytes(def); + } + + @Override + public String getString() { + return valueHolder.getString(); + } + + @Override + public String getString(String def) { + return valueHolder.getString(def); + } + + @Override + public T getTypedValue(Class type) { + return valueHolder.getTypedValue(type); + } + + @Override + public T getTypedValue(Class type, T def) { + return valueHolder.getTypedValue(type, def); + } + + @Override + public Object getTypedValue(Type type) { + return valueHolder.getTypedValue(type); + } + + @Override + public Object getTypedValue(Type type, Object def) { + return valueHolder.getTypedValue(type, def); + } + + @Override + public List getList() { + return valueHolder.getList(); + } + + @Override + public List getList(List def) { + return valueHolder.getList(def); + } + + @Override + public List getStringList() { + return valueHolder.getStringList(); + } + + @Override + public List getStringList(List def) { + return valueHolder.getStringList(def); + } + + @Override + public List getIntegerList() { + return valueHolder.getIntegerList(); + } + + @Override + public List getIntegerList(List def) { + return valueHolder.getIntegerList(def); + } + + @Override + public List getDoubleList() { + return valueHolder.getDoubleList(); + } + + @Override + public List getDoubleList(List def) { + return valueHolder.getDoubleList(def); + } + + @Override + public List getBooleanList() { + return valueHolder.getBooleanList(); + } + + @Override + public List getBooleanList(List def) { + return valueHolder.getBooleanList(def); + } + + // Actual value access + + @Override + public Object getValue() { + return getValue(null); + } + + @Override + public Object getValue(Object def) { + if (hasChildren()) { + return getValues(); + } + + if (value != null) { + return value; + } + + if (def != null && getConfiguration().doesWriteDefaults()) { + setValue(def); + } + + return def; + } + + /** + * Sets the configuration's value + * + * @param value The value to set + * @return The previous value of the configuration + */ + public Object setValue(Object value) { + if (value instanceof ValueHolder) { + value = ((ValueHolder) value).getValue(); + } + checkAdded(); + Object old = this.getValue(); + if (value instanceof Map) { + this.value = null; + removeChildren(); + for (Map.Entry entry : ((Map) value).entrySet()) { + addChild(createConfigurationNode(ArrayUtils.add(getPathElements(), entry.getKey().toString()), entry.getValue())); + } + } else { + if (value != null) { + removeChildren(); + } + this.value = value; + } + return old; + } + + /** + * Sets the type and value + * + * @return the previous value + */ + public Object setValue(Type type, Object value) { + return setValue(Serialization.serialize(type, value)); + } + + // Util methods to make sure stuff is connected properly + + /** + * Detach all this node's children, making sure to remove associations both ways + */ + private void removeChildren() { + for (ConfigurationNode node : children.values()) { + detachChild(node); + } + children.clear(); + } + + protected void checkAdded() { + if (!isAttached()) { + getConfiguration().setNode(this); + } + } + + public void remove() { + if (isAttached()) { + getParent().removeChild(this); + } + this.value = null; + } + + /** + * Return whether a ConfigurationNode is attached to any configuration + * + * @return if this node is attached to any configuration + */ + public boolean isAttached() { + return attached; + } + + protected void setAttached(boolean value) { + this.attached = value; + } + + public ConfigurationNodeSource getParent() { + return parent.get(); + } + + protected void setParent(ConfigurationNodeSource parent) { + if (parent == this) { + throw new IllegalArgumentException("Attempted circular inheritance between child" + getPath() + " and parent."); + } + Set visited = new HashSet(); + ConfigurationNodeSource oldParent = getParent(); + while (oldParent != null) { + if (visited.contains(oldParent)) { + throw new IllegalArgumentException("Attempted circular inheritance between child " + getPath() + " and parent " + + (oldParent instanceof ConfigurationNode ? ((ConfigurationNode) oldParent).getPath() : "root") + "."); + } + visited.add(oldParent); + oldParent = oldParent instanceof ConfigurationNode ? ((ConfigurationNode) oldParent).getParent() : null; + } + this.parent = new WeakReference(parent); + } + + @Override + public ConfigurationNode addChild(ConfigurationNode node) { + checkAdded(); + return super.addChild(node); + } + + /** + * @return The path, joined by the {@link AbstractConfiguration#getPathSeparator()} of the attached configuration + * @see #getPathElements + */ + public String getPath() { + return StringUtils.join(getPathElements(), getConfiguration().getPathSeparator()); + } + + /** + * @return the elements of this node's path, unjoined + */ + @Override + public String[] getPathElements() { + return path; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/ConfigurationNodeSource.java b/src/main/java/com/flowpowered/cerealization/config/ConfigurationNodeSource.java index 5da55f6..ea2831b 100644 --- a/src/main/java/com/flowpowered/cerealization/config/ConfigurationNodeSource.java +++ b/src/main/java/com/flowpowered/cerealization/config/ConfigurationNodeSource.java @@ -27,139 +27,139 @@ import java.util.Set; public interface ConfigurationNodeSource { - /** - * Gets a child of the current node. Remember that this returns a DIRECT child, without splitting at the {@link com.flowpowered.cerealization.config.Configuration#getPathSeparator()} - * - * @param name The name of the child - * @return The ConfigurationNode with the child's path. - * @see #getChild(String, boolean) - */ - public ConfigurationNode getChild(String name); - - /** - * Gets a child of the current node. Remember that this returns a DIRECT child, without splitting at the {@link com.flowpowered.cerealization.config.Configuration#getPathSeparator()} - * - * @param name The name of the child - * @param add Whether to store the configuration to the node structure. - * @return The ConfigurationNode with the child's path. - */ - public ConfigurationNode getChild(String name, boolean add); - - /** - * Adds the provided node as a child to this one As with the other methods handling children, this method only works with DIRECT children - * - * @param node The node to add as a child - * @return The previous node at the specified path (can be null) - */ - public ConfigurationNode addChild(ConfigurationNode node); - - /** - * Adds a new node as a child to this one Will overwrite existing - * - * @param name The path to the node to add - * @return The previous node at the specified path (can be null) - */ - public ConfigurationNode addNode(String name); - - /** - * Add the given children. The process for adding children is the same as that for {@link #addChild(ConfigurationNode)} - * - * @param nodes The nodes to add - * @see #addChild(ConfigurationNode) - */ - public void addChildren(ConfigurationNode... nodes); - - /** - * Remove the child at the specified path, if any, from the configuration structure - * - * @param key The name of the child - * @return The child at the key given, if any - */ - public ConfigurationNode removeChild(String key); - - /** - * Remove the specified child from the configuration structure - * - * @param node The node to remove - * @return null if unsuccessful, otherwise the node passed in - */ - public ConfigurationNode removeChild(ConfigurationNode node); - - /** - * Return the children of this node. The returned map is unmodifiable - * - * @return This node's children - */ - public Map getChildren(); - - /** - * Return the raw Object values of this node's children ConfigurationNodes are converted into Maps for the result of this method - * - * @return The node's children values - */ - public Map getValues(); - - /** - * Return the keys in this configuration. If {@code deep} is true, this will also include paths from child nodes, joined by {@link com.flowpowered.cerealization.config.Configuration#getPathSeparator()} Keys - * returned are relative to the current node. - * - * @param deep Whether to also fetch keys in children nodes of this configuration - * @return the keys in this configuration - */ - public Set getKeys(boolean deep); - - /** - * Returns the node at the specified child path, splitting by the configuration's path separator. This can return both direct children and indirect children. - * - * @param path The path to get a node at - * @return The node at the specified path - * @see #getNode(String...) for more information on how this method behaves. (This is also the method called when a path given contains the path separator) - */ - public ConfigurationNode getNode(String path); - - /** - * Get a child node of this node source, going across multiple levels. If there is no node at the specified path a detached configuration node will be returned, which will be attached to {@link - * #getConfiguration()} if its value is set or a child is added. - * - * @param path The path elements to get to the requested node. - * @return The child node. Never null. - */ - public ConfigurationNode getNode(String... path); - - /** - * Returns whether this node source has children. This is the same as running {@code getChildren().size() > 0} - * - * @return whether this node source has children - */ - public boolean hasChildren(); - - /** - * Returns whether the direct child (not checking children of children, etc) at {@code key} exists - * - * @param key The key to check - * @return Whether key is a direct child of this node - */ - public boolean hasChild(String key); - - /** - * Returns whether the node at {@code key} exists - * - * @param path The key to check - * @return Whether key is a direct child of this node - */ - public boolean hasNode(String... path); - - /** - * Returns the configuration this node source is attached to. This may return the same object if this {@link ConfigurationNodeSource} is a Configuration. - * - * @return the attached configuration. - */ - public Configuration getConfiguration(); - - /** - * Returns the elements of the configuration path going to this node source. Can return an empty array if we are at the root of the tree. - * - * @return the elements to here - */ - public String[] getPathElements(); + /** + * Gets a child of the current node. Remember that this returns a DIRECT child, without splitting at the {@link com.flowpowered.cerealization.config.Configuration#getPathSeparator()} + * + * @param name The name of the child + * @return The ConfigurationNode with the child's path. + * @see #getChild(String, boolean) + */ + public ConfigurationNode getChild(String name); + + /** + * Gets a child of the current node. Remember that this returns a DIRECT child, without splitting at the {@link com.flowpowered.cerealization.config.Configuration#getPathSeparator()} + * + * @param name The name of the child + * @param add Whether to store the configuration to the node structure. + * @return The ConfigurationNode with the child's path. + */ + public ConfigurationNode getChild(String name, boolean add); + + /** + * Adds the provided node as a child to this one As with the other methods handling children, this method only works with DIRECT children + * + * @param node The node to add as a child + * @return The previous node at the specified path (can be null) + */ + public ConfigurationNode addChild(ConfigurationNode node); + + /** + * Adds a new node as a child to this one Will overwrite existing + * + * @param name The path to the node to add + * @return The previous node at the specified path (can be null) + */ + public ConfigurationNode addNode(String name); + + /** + * Add the given children. The process for adding children is the same as that for {@link #addChild(ConfigurationNode)} + * + * @param nodes The nodes to add + * @see #addChild(ConfigurationNode) + */ + public void addChildren(ConfigurationNode... nodes); + + /** + * Remove the child at the specified path, if any, from the configuration structure + * + * @param key The name of the child + * @return The child at the key given, if any + */ + public ConfigurationNode removeChild(String key); + + /** + * Remove the specified child from the configuration structure + * + * @param node The node to remove + * @return null if unsuccessful, otherwise the node passed in + */ + public ConfigurationNode removeChild(ConfigurationNode node); + + /** + * Return the children of this node. The returned map is unmodifiable + * + * @return This node's children + */ + public Map getChildren(); + + /** + * Return the raw Object values of this node's children ConfigurationNodes are converted into Maps for the result of this method + * + * @return The node's children values + */ + public Map getValues(); + + /** + * Return the keys in this configuration. If {@code deep} is true, this will also include paths from child nodes, joined by {@link com.flowpowered.cerealization.config.Configuration#getPathSeparator()} Keys + * returned are relative to the current node. + * + * @param deep Whether to also fetch keys in children nodes of this configuration + * @return the keys in this configuration + */ + public Set getKeys(boolean deep); + + /** + * Returns the node at the specified child path, splitting by the configuration's path separator. This can return both direct children and indirect children. + * + * @param path The path to get a node at + * @return The node at the specified path + * @see #getNode(String...) for more information on how this method behaves. (This is also the method called when a path given contains the path separator) + */ + public ConfigurationNode getNode(String path); + + /** + * Get a child node of this node source, going across multiple levels. If there is no node at the specified path a detached configuration node will be returned, which will be attached to {@link + * #getConfiguration()} if its value is set or a child is added. + * + * @param path The path elements to get to the requested node. + * @return The child node. Never null. + */ + public ConfigurationNode getNode(String... path); + + /** + * Returns whether this node source has children. This is the same as running {@code getChildren().size() > 0} + * + * @return whether this node source has children + */ + public boolean hasChildren(); + + /** + * Returns whether the direct child (not checking children of children, etc) at {@code key} exists + * + * @param key The key to check + * @return Whether key is a direct child of this node + */ + public boolean hasChild(String key); + + /** + * Returns whether the node at {@code key} exists + * + * @param path The key to check + * @return Whether key is a direct child of this node + */ + public boolean hasNode(String... path); + + /** + * Returns the configuration this node source is attached to. This may return the same object if this {@link ConfigurationNodeSource} is a Configuration. + * + * @return the attached configuration. + */ + public Configuration getConfiguration(); + + /** + * Returns the elements of the configuration path going to this node source. Can return an empty array if we are at the root of the tree. + * + * @return the elements to here + */ + public String[] getPathElements(); } diff --git a/src/main/java/com/flowpowered/cerealization/config/ConfigurationWrapper.java b/src/main/java/com/flowpowered/cerealization/config/ConfigurationWrapper.java index e8e5e03..38b0311 100644 --- a/src/main/java/com/flowpowered/cerealization/config/ConfigurationWrapper.java +++ b/src/main/java/com/flowpowered/cerealization/config/ConfigurationWrapper.java @@ -31,155 +31,155 @@ * A parent class for implementations of Configuration that wrap other Configurations. */ public abstract class ConfigurationWrapper implements Configuration { - private Configuration config; - - public ConfigurationWrapper() { - this(null); - } - - public ConfigurationWrapper(Configuration config) { - this.config = config; - } - - @Override - public Configuration getConfiguration() { - if (config == null) { - throw new IllegalArgumentException("The Configuration for a " + getClass().getSimpleName() + " is not set!"); - } - return config; - } - - public void setConfiguration(Configuration config) { - this.config = config; - } - - @Override - public void load() throws ConfigurationException { - getConfiguration().load(); - } - - @Override - public void save() throws ConfigurationException { - getConfiguration().save(); - } - - @Override - public void setNode(ConfigurationNode node) { - getConfiguration().setNode(node); - } - - @Override - public String getPathSeparator() { - return getConfiguration().getPathSeparator(); - } - - @Override - public void setPathSeparator(String pathSeparator) { - getConfiguration().setPathSeparator(pathSeparator); - } - - @Override - public Pattern getPathSeparatorPattern() { - return getConfiguration().getPathSeparatorPattern(); - } - - @Override - public boolean doesWriteDefaults() { - return getConfiguration().doesWriteDefaults(); - } - - @Override - public void setWritesDefaults(boolean writesDefaults) { - getConfiguration().setWritesDefaults(writesDefaults); - } - - @Override - public String[] splitNodePath(String path) { - return getConfiguration().splitNodePath(path); - } - - @Override - public String[] ensureCorrectPath(String[] rawPath) { - return getConfiguration().ensureCorrectPath(rawPath); - } - - @Override - public ConfigurationNode getChild(String name) { - return getConfiguration().getChild(name); - } - - @Override - public ConfigurationNode getChild(String name, boolean add) { - return getConfiguration().getChild(name, add); - } - - @Override - public ConfigurationNode addChild(ConfigurationNode node) { - return getConfiguration().addChild(node); - } - - @Override - public ConfigurationNode addNode(String name) { - return getConfiguration().addNode(name); - } - - @Override - public void addChildren(ConfigurationNode... nodes) { - getConfiguration().addChildren(nodes); - } - - @Override - public ConfigurationNode removeChild(String key) { - return getConfiguration().removeChild(key); - } - - @Override - public ConfigurationNode removeChild(ConfigurationNode node) { - return getConfiguration().removeChild(node); - } - - @Override - public Map getChildren() { - return getConfiguration().getChildren(); - } - - @Override - public Map getValues() { - return getConfiguration().getValues(); - } - - @Override - public Set getKeys(boolean deep) { - return getConfiguration().getKeys(deep); - } - - @Override - public ConfigurationNode getNode(String path) { - return getConfiguration().getNode(path); - } - - @Override - public ConfigurationNode getNode(String... path) { - return getConfiguration().getNode(path); - } - - @Override - public boolean hasChildren() { - return getConfiguration().hasChildren(); - } - - @Override - public boolean hasChild(String key) { - return getConfiguration().hasChild(key); - } - - @Override - public boolean hasNode(String... path) { - return getConfiguration().hasNode(path); - } - - @Override - public String[] getPathElements() { - return getConfiguration().getPathElements(); - } + private Configuration config; + + public ConfigurationWrapper() { + this(null); + } + + public ConfigurationWrapper(Configuration config) { + this.config = config; + } + + @Override + public Configuration getConfiguration() { + if (config == null) { + throw new IllegalArgumentException("The Configuration for a " + getClass().getSimpleName() + " is not set!"); + } + return config; + } + + public void setConfiguration(Configuration config) { + this.config = config; + } + + @Override + public void load() throws ConfigurationException { + getConfiguration().load(); + } + + @Override + public void save() throws ConfigurationException { + getConfiguration().save(); + } + + @Override + public void setNode(ConfigurationNode node) { + getConfiguration().setNode(node); + } + + @Override + public String getPathSeparator() { + return getConfiguration().getPathSeparator(); + } + + @Override + public void setPathSeparator(String pathSeparator) { + getConfiguration().setPathSeparator(pathSeparator); + } + + @Override + public Pattern getPathSeparatorPattern() { + return getConfiguration().getPathSeparatorPattern(); + } + + @Override + public boolean doesWriteDefaults() { + return getConfiguration().doesWriteDefaults(); + } + + @Override + public void setWritesDefaults(boolean writesDefaults) { + getConfiguration().setWritesDefaults(writesDefaults); + } + + @Override + public String[] splitNodePath(String path) { + return getConfiguration().splitNodePath(path); + } + + @Override + public String[] ensureCorrectPath(String[] rawPath) { + return getConfiguration().ensureCorrectPath(rawPath); + } + + @Override + public ConfigurationNode getChild(String name) { + return getConfiguration().getChild(name); + } + + @Override + public ConfigurationNode getChild(String name, boolean add) { + return getConfiguration().getChild(name, add); + } + + @Override + public ConfigurationNode addChild(ConfigurationNode node) { + return getConfiguration().addChild(node); + } + + @Override + public ConfigurationNode addNode(String name) { + return getConfiguration().addNode(name); + } + + @Override + public void addChildren(ConfigurationNode... nodes) { + getConfiguration().addChildren(nodes); + } + + @Override + public ConfigurationNode removeChild(String key) { + return getConfiguration().removeChild(key); + } + + @Override + public ConfigurationNode removeChild(ConfigurationNode node) { + return getConfiguration().removeChild(node); + } + + @Override + public Map getChildren() { + return getConfiguration().getChildren(); + } + + @Override + public Map getValues() { + return getConfiguration().getValues(); + } + + @Override + public Set getKeys(boolean deep) { + return getConfiguration().getKeys(deep); + } + + @Override + public ConfigurationNode getNode(String path) { + return getConfiguration().getNode(path); + } + + @Override + public ConfigurationNode getNode(String... path) { + return getConfiguration().getNode(path); + } + + @Override + public boolean hasChildren() { + return getConfiguration().hasChildren(); + } + + @Override + public boolean hasChild(String key) { + return getConfiguration().hasChild(key); + } + + @Override + public boolean hasNode(String... path) { + return getConfiguration().hasNode(path); + } + + @Override + public String[] getPathElements() { + return getConfiguration().getPathElements(); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/FileConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/FileConfiguration.java index 59d69b8..36ebc40 100644 --- a/src/main/java/com/flowpowered/cerealization/config/FileConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/FileConfiguration.java @@ -29,10 +29,10 @@ * Represents a configuration that loads from a file */ public interface FileConfiguration extends Configuration { - /** - * Returns the file that this configuration loads from. - * - * @return The file that this configuration loads from - */ - public File getFile(); + /** + * Returns the file that this configuration loads from. + * + * @return The file that this configuration loads from + */ + public File getFile(); } diff --git a/src/main/java/com/flowpowered/cerealization/config/MapBasedConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/MapBasedConfiguration.java index 792c901..897b5e3 100644 --- a/src/main/java/com/flowpowered/cerealization/config/MapBasedConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/MapBasedConfiguration.java @@ -30,38 +30,38 @@ * A base class for configurations that load their values from a {@link Map} */ public abstract class MapBasedConfiguration extends AbstractConfiguration { - /** - * Implementations can use this method to provide the necessary data for calls of load. - * - * @return A map with raw configuration data - * @throws ConfigurationException when an error occurs while loading. - */ - protected abstract Map loadToMap() throws ConfigurationException; + /** + * Implementations can use this method to provide the necessary data for calls of load. + * + * @return A map with raw configuration data + * @throws ConfigurationException when an error occurs while loading. + */ + protected abstract Map loadToMap() throws ConfigurationException; - /** - * Save the data from this configuration. This method is called from {@link #save()} - * - * @param map Configuration as a set of nested Maps - * @throws ConfigurationException When an error occurs while saving the given data. - */ - protected abstract void saveFromMap(Map map) throws ConfigurationException; + /** + * Save the data from this configuration. This method is called from {@link #save()} + * + * @param map Configuration as a set of nested Maps + * @throws ConfigurationException When an error occurs while saving the given data. + */ + protected abstract void saveFromMap(Map map) throws ConfigurationException; - @Override - protected Map loadToNodes() throws ConfigurationException { - Map items = loadToMap(); - Map children = new LinkedHashMap(); - for (Map.Entry entry : items.entrySet()) { - children.put(entry.getKey().toString(), createConfigurationNode(new String[] {entry.getKey().toString()}, entry.getValue())); - } - return children; - } + @Override + protected Map loadToNodes() throws ConfigurationException { + Map items = loadToMap(); + Map children = new LinkedHashMap(); + for (Map.Entry entry : items.entrySet()) { + children.put(entry.getKey().toString(), createConfigurationNode(new String[] {entry.getKey().toString()}, entry.getValue())); + } + return children; + } - @Override - protected void saveFromNodes(Map nodes) throws ConfigurationException { - Map ret = new LinkedHashMap(); - for (Map.Entry entry : getChildren().entrySet()) { - ret.put(entry.getKey(), entry.getValue().getValue()); - } - saveFromMap(ret); - } + @Override + protected void saveFromNodes(Map nodes) throws ConfigurationException { + Map ret = new LinkedHashMap(); + for (Map.Entry entry : getChildren().entrySet()) { + ret.put(entry.getKey(), entry.getValue().getValue()); + } + saveFromMap(ret); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/MapConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/MapConfiguration.java index 063d66b..d60479d 100644 --- a/src/main/java/com/flowpowered/cerealization/config/MapConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/MapConfiguration.java @@ -30,33 +30,33 @@ * This represents a configuration that loads its values from an in-memory {@link Map} */ public class MapConfiguration extends MapBasedConfiguration { - private Map map; + private Map map; - /** - * Create a new configuration backed by an empty map. Loading a configuration instantiated with this constructor will do nothing. - */ - public MapConfiguration() { - this(null); - } + /** + * Create a new configuration backed by an empty map. Loading a configuration instantiated with this constructor will do nothing. + */ + public MapConfiguration() { + this(null); + } - public MapConfiguration(Map map) { - super(); - this.map = map == null ? new HashMap() : map; - } + public MapConfiguration(Map map) { + super(); + this.map = map == null ? new HashMap() : map; + } - @Override - protected Map loadToMap() { - return map; - } + @Override + protected Map loadToMap() { + return map; + } - @Override - @SuppressWarnings ({"unchecked", "rawtypes"}) - protected void saveFromMap(Map map) { - this.map.clear(); - ((Map) this.map).putAll(map); - } + @Override + @SuppressWarnings ({"unchecked", "rawtypes"}) + protected void saveFromMap(Map map) { + this.map.clear(); + ((Map) this.map).putAll(map); + } - public Map getMap() { - return map; - } + public Map getMap() { + return map; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedConfiguration.java index a40e242..9006d21 100644 --- a/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedConfiguration.java @@ -29,26 +29,26 @@ import com.flowpowered.cerealization.config.ConfigurationWrapper; public abstract class AnnotatedConfiguration extends ConfigurationWrapper { - public AnnotatedConfiguration() { - } + public AnnotatedConfiguration() { + } - public AnnotatedConfiguration(Configuration config) { - super(config); - } + public AnnotatedConfiguration(Configuration config) { + super(config); + } - public abstract void load(ConfigurationNodeSource source) throws ConfigurationException; + public abstract void load(ConfigurationNodeSource source) throws ConfigurationException; - public abstract void save(ConfigurationNodeSource source) throws ConfigurationException; + public abstract void save(ConfigurationNodeSource source) throws ConfigurationException; - @Override - public void load() throws ConfigurationException { - super.load(); - load(this); - } + @Override + public void load() throws ConfigurationException { + super.load(); + load(this); + } - @Override - public void save() throws ConfigurationException { - save(this); - super.save(); - } + @Override + public void save() throws ConfigurationException { + save(this); + super.save(); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedObjectConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedObjectConfiguration.java index 17b160f..c0a12b3 100644 --- a/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedObjectConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedObjectConfiguration.java @@ -77,148 +77,148 @@ * */ public class AnnotatedObjectConfiguration extends AnnotatedConfiguration { - private final Map> objectMembers = new HashMap>(); - private final Map objectPaths = new HashMap(); + private final Map> objectMembers = new HashMap>(); + private final Map objectPaths = new HashMap(); - /** - * Creates a new empty AnnotatedObjectConfiguration wrapper. - */ - public AnnotatedObjectConfiguration() { - } + /** + * Creates a new empty AnnotatedObjectConfiguration wrapper. + */ + public AnnotatedObjectConfiguration() { + } - /** - * Creates a new AnnotatedObjectConfiguration wrapper wrapping the provided configuration. - */ - public AnnotatedObjectConfiguration(Configuration config) { - super(config); - } + /** + * Creates a new AnnotatedObjectConfiguration wrapper wrapping the provided configuration. + */ + public AnnotatedObjectConfiguration(Configuration config) { + super(config); + } - /** - * Adds an object or a class to be saved or loaded by the configuration.

The node path of the object in the configuration is specified as an array (varargs) of strings. Only annotated fields and - * methods will be used.

The individual paths of the fields can be specified with the Setting annotation. If none are specified, the field name is used.

A field named "exa" annotated with - * {@code @Setting({"cd.ef"})} in an object with path "ab" will have its value saved at "ab.cd.ef". If no path is specified in Setting, the path will be "ab.exa".

If the target is a class, only - * static fields and methods will be registered. - * - * @param object The object or class to load or save - * @param path The path at which the object or class should be or is located in the configuration - */ - @SuppressWarnings ("unchecked") - public void add(Object object, String... path) { - if (!objectMembers.containsKey(object)) { - final Set members = new HashSet(); - if (object instanceof Class) { - members.addAll(ReflectionUtils.getDeclaredFieldsRecur((Class) object, Modifier.STATIC, Setting.class)); - members.addAll(ReflectionUtils.getDeclaredMethodsRecur((Class) object, Modifier.STATIC, Load.class, Save.class)); - } else { - members.addAll(ReflectionUtils.getDeclaredFieldsRecur(object.getClass(), Setting.class)); - members.addAll(ReflectionUtils.getDeclaredMethodsRecur(object.getClass(), Load.class, Save.class)); - } - objectMembers.put(object, members); - } - if (!objectPaths.containsKey(object)) { - objectPaths.put(object, path); - } - } + /** + * Adds an object or a class to be saved or loaded by the configuration.

The node path of the object in the configuration is specified as an array (varargs) of strings. Only annotated fields and + * methods will be used.

The individual paths of the fields can be specified with the Setting annotation. If none are specified, the field name is used.

A field named "exa" annotated with + * {@code @Setting({"cd.ef"})} in an object with path "ab" will have its value saved at "ab.cd.ef". If no path is specified in Setting, the path will be "ab.exa".

If the target is a class, only + * static fields and methods will be registered. + * + * @param object The object or class to load or save + * @param path The path at which the object or class should be or is located in the configuration + */ + @SuppressWarnings ("unchecked") + public void add(Object object, String... path) { + if (!objectMembers.containsKey(object)) { + final Set members = new HashSet(); + if (object instanceof Class) { + members.addAll(ReflectionUtils.getDeclaredFieldsRecur((Class) object, Modifier.STATIC, Setting.class)); + members.addAll(ReflectionUtils.getDeclaredMethodsRecur((Class) object, Modifier.STATIC, Load.class, Save.class)); + } else { + members.addAll(ReflectionUtils.getDeclaredFieldsRecur(object.getClass(), Setting.class)); + members.addAll(ReflectionUtils.getDeclaredMethodsRecur(object.getClass(), Load.class, Save.class)); + } + objectMembers.put(object, members); + } + if (!objectPaths.containsKey(object)) { + objectPaths.put(object, path); + } + } - /** - * Removes an object or a class from the configuration. It will not be used during the next save or load invocations. - * - * @param object the object or the class to remove - */ - public void remove(Object object) { - objectMembers.remove(object); - objectPaths.remove(object); - } + /** + * Removes an object or a class from the configuration. It will not be used during the next save or load invocations. + * + * @param object the object or the class to remove + */ + public void remove(Object object) { + objectMembers.remove(object); + objectPaths.remove(object); + } - @Override - public void load(ConfigurationNodeSource source) throws ConfigurationException { - for (Entry> entry : objectMembers.entrySet()) { - final Object object = entry.getKey(); - load(source, object instanceof Class ? null : object, objectPaths.get(object), entry.getValue()); - } - } + @Override + public void load(ConfigurationNodeSource source) throws ConfigurationException { + for (Entry> entry : objectMembers.entrySet()) { + final Object object = entry.getKey(); + load(source, object instanceof Class ? null : object, objectPaths.get(object), entry.getValue()); + } + } - private void load(ConfigurationNodeSource source, Object object, String[] path, Set members) throws ConfigurationException { - final Set methods = new HashSet(); - for (Member member : members) { - if (member instanceof Method) { - final Method method = (Method) member; - if (method.isAnnotationPresent(Load.class)) { - methods.add(method); - } - continue; - } - final Field field = (Field) member; - field.setAccessible(true); - String[] fieldPath = field.getAnnotation(Setting.class).value(); - if (fieldPath.length == 0) { - fieldPath = new String[] {field.getName()}; - } - final ConfigurationNode fieldNode = source.getNode(ArrayUtils.addAll(path, fieldPath)); - final Object value = fieldNode.getTypedValue(field.getGenericType()); - try { - if (value != null) { - field.set(object, value); - } else { - fieldNode.setValue(field.getGenericType(), field.get(object)); - } - } catch (IllegalAccessException ex) { - throw new ConfigurationException(ex); - } - } - invokeMethods(methods, object, source.getNode(path)); - } + private void load(ConfigurationNodeSource source, Object object, String[] path, Set members) throws ConfigurationException { + final Set methods = new HashSet(); + for (Member member : members) { + if (member instanceof Method) { + final Method method = (Method) member; + if (method.isAnnotationPresent(Load.class)) { + methods.add(method); + } + continue; + } + final Field field = (Field) member; + field.setAccessible(true); + String[] fieldPath = field.getAnnotation(Setting.class).value(); + if (fieldPath.length == 0) { + fieldPath = new String[] {field.getName()}; + } + final ConfigurationNode fieldNode = source.getNode(ArrayUtils.addAll(path, fieldPath)); + final Object value = fieldNode.getTypedValue(field.getGenericType()); + try { + if (value != null) { + field.set(object, value); + } else { + fieldNode.setValue(field.getGenericType(), field.get(object)); + } + } catch (IllegalAccessException ex) { + throw new ConfigurationException(ex); + } + } + invokeMethods(methods, object, source.getNode(path)); + } - @Override - public void save(ConfigurationNodeSource source) throws ConfigurationException { - for (Entry> entry : objectMembers.entrySet()) { - final Object object = entry.getKey(); - save(source, object instanceof Class ? null : object, objectPaths.get(object), entry.getValue()); - } - } + @Override + public void save(ConfigurationNodeSource source) throws ConfigurationException { + for (Entry> entry : objectMembers.entrySet()) { + final Object object = entry.getKey(); + save(source, object instanceof Class ? null : object, objectPaths.get(object), entry.getValue()); + } + } - private void save(ConfigurationNodeSource source, Object object, String[] path, Set members) throws ConfigurationException { - final Set methods = new HashSet(); - for (Member member : members) { - if (member instanceof Method) { - final Method method = (Method) member; - if (method.isAnnotationPresent(Save.class)) { - methods.add(method); - } - continue; - } - final Field field = (Field) member; - field.setAccessible(true); - String[] fieldPath = field.getAnnotation(Setting.class).value(); - if (fieldPath.length == 0) { - fieldPath = new String[] {field.getName()}; - } - final ConfigurationNode fieldNode = source.getNode(ArrayUtils.addAll(path, fieldPath)); - try { - fieldNode.setValue(field.getGenericType(), field.get(object)); - } catch (IllegalAccessException ex) { - throw new ConfigurationException(ex); - } - } - invokeMethods(methods, object, source.getNode(path)); - } + private void save(ConfigurationNodeSource source, Object object, String[] path, Set members) throws ConfigurationException { + final Set methods = new HashSet(); + for (Member member : members) { + if (member instanceof Method) { + final Method method = (Method) member; + if (method.isAnnotationPresent(Save.class)) { + methods.add(method); + } + continue; + } + final Field field = (Field) member; + field.setAccessible(true); + String[] fieldPath = field.getAnnotation(Setting.class).value(); + if (fieldPath.length == 0) { + fieldPath = new String[] {field.getName()}; + } + final ConfigurationNode fieldNode = source.getNode(ArrayUtils.addAll(path, fieldPath)); + try { + fieldNode.setValue(field.getGenericType(), field.get(object)); + } catch (IllegalAccessException ex) { + throw new ConfigurationException(ex); + } + } + invokeMethods(methods, object, source.getNode(path)); + } - private void invokeMethods(Set methods, Object target, ConfigurationNode nodeParam) - throws ConfigurationException { - for (Method method : methods) { - method.setAccessible(true); - Class[] parameters = method.getParameterTypes(); - if (parameters.length == 0 - || !ConfigurationNode.class.isAssignableFrom(parameters[0])) { - continue; - } - try { - method.invoke(target, nodeParam); - } catch (IllegalAccessException ex) { - throw new ConfigurationException(ex); - } catch (InvocationTargetException ex) { - throw new ConfigurationException(ex); - } - } - } + private void invokeMethods(Set methods, Object target, ConfigurationNode nodeParam) + throws ConfigurationException { + for (Method method : methods) { + method.setAccessible(true); + Class[] parameters = method.getParameterTypes(); + if (parameters.length == 0 + || !ConfigurationNode.class.isAssignableFrom(parameters[0])) { + continue; + } + try { + method.invoke(target, nodeParam); + } catch (IllegalAccessException ex) { + throw new ConfigurationException(ex); + } catch (InvocationTargetException ex) { + throw new ConfigurationException(ex); + } + } + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedSubclassConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedSubclassConfiguration.java index d1a712f..5be0f94 100644 --- a/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedSubclassConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/annotated/AnnotatedSubclassConfiguration.java @@ -37,63 +37,63 @@ * The base class for annotated configurations Annotated configurations are created by subclassing AnnotatedConfiguration and having fields annotated with "@Setting" */ public abstract class AnnotatedSubclassConfiguration extends AnnotatedConfiguration { - private final Set fields = new HashSet(); - private boolean fieldsCached = false; - private boolean isConfigured; + private final Set fields = new HashSet(); + private boolean fieldsCached = false; + private boolean isConfigured; - public AnnotatedSubclassConfiguration(Configuration baseConfig) { - super(baseConfig); - } + public AnnotatedSubclassConfiguration(Configuration baseConfig) { + super(baseConfig); + } - public boolean isConfigured() { - return isConfigured; - } + public boolean isConfigured() { + return isConfigured; + } - @SuppressWarnings ("unchecked") - private Set getFields() { - if (!fieldsCached) { - fields.addAll(ReflectionUtils.getDeclaredFieldsRecur(getClass(), Setting.class)); - fieldsCached = true; - } - return fields; - } + @SuppressWarnings ("unchecked") + private Set getFields() { + if (!fieldsCached) { + fields.addAll(ReflectionUtils.getDeclaredFieldsRecur(getClass(), Setting.class)); + fieldsCached = true; + } + return fields; + } - @Override - public void load(ConfigurationNodeSource source) throws ConfigurationException { - for (Field field : getFields()) { - field.setAccessible(true); - String[] key = field.getAnnotation(Setting.class).value(); - if (key.length == 0) { - key = new String[] {field.getName()}; - } - ConfigurationNode node = source.getNode(key); - final Object value = node.getTypedValue(field.getGenericType()); - try { - if (value != null) { - field.set(this, value); - } else { - node.setValue(field.getGenericType(), field.get(this)); - } - } catch (IllegalAccessException e) { - throw new ConfigurationException(e); - } - } - isConfigured = true; - } + @Override + public void load(ConfigurationNodeSource source) throws ConfigurationException { + for (Field field : getFields()) { + field.setAccessible(true); + String[] key = field.getAnnotation(Setting.class).value(); + if (key.length == 0) { + key = new String[] {field.getName()}; + } + ConfigurationNode node = source.getNode(key); + final Object value = node.getTypedValue(field.getGenericType()); + try { + if (value != null) { + field.set(this, value); + } else { + node.setValue(field.getGenericType(), field.get(this)); + } + } catch (IllegalAccessException e) { + throw new ConfigurationException(e); + } + } + isConfigured = true; + } - @Override - public void save(ConfigurationNodeSource source) throws ConfigurationException { - for (Field field : getFields()) { - field.setAccessible(true); - String[] key = field.getAnnotation(Setting.class).value(); - if (key.length == 0) { - key = new String[] {field.getName()}; - } - try { - source.getNode(key).setValue(field.getGenericType(), field.get(this)); - } catch (IllegalAccessException e) { - throw new ConfigurationException(e); - } - } - } + @Override + public void save(ConfigurationNodeSource source) throws ConfigurationException { + for (Field field : getFields()) { + field.setAccessible(true); + String[] key = field.getAnnotation(Setting.class).value(); + if (key.length == 0) { + key = new String[] {field.getName()}; + } + try { + source.getNode(key).setValue(field.getGenericType(), field.get(this)); + } catch (IllegalAccessException e) { + throw new ConfigurationException(e); + } + } + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/annotated/Setting.java b/src/main/java/com/flowpowered/cerealization/config/annotated/Setting.java index 94738a8..26fae13 100644 --- a/src/main/java/com/flowpowered/cerealization/config/annotated/Setting.java +++ b/src/main/java/com/flowpowered/cerealization/config/annotated/Setting.java @@ -34,5 +34,5 @@ @Target (ElementType.FIELD) @Retention (RetentionPolicy.RUNTIME) public @interface Setting { - public String[] value() default {}; + public String[] value() default {}; } diff --git a/src/main/java/com/flowpowered/cerealization/config/commented/CommentedConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/commented/CommentedConfiguration.java index 4e4ae63..e0eb375 100644 --- a/src/main/java/com/flowpowered/cerealization/config/commented/CommentedConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/commented/CommentedConfiguration.java @@ -30,11 +30,11 @@ * CommentedConfigurationNodes for convenience.
*/ public interface CommentedConfiguration extends Configuration { - public CommentedConfigurationNode createConfigurationNode(String[] path, Object value); + public CommentedConfigurationNode createConfigurationNode(String[] path, Object value); - @Override - public CommentedConfigurationNode getNode(String... node); + @Override + public CommentedConfigurationNode getNode(String... node); - @Override - public CommentedConfigurationNode getNode(String path); + @Override + public CommentedConfigurationNode getNode(String path); } diff --git a/src/main/java/com/flowpowered/cerealization/config/commented/CommentedConfigurationNode.java b/src/main/java/com/flowpowered/cerealization/config/commented/CommentedConfigurationNode.java index 5e0d4b0..716a37a 100644 --- a/src/main/java/com/flowpowered/cerealization/config/commented/CommentedConfigurationNode.java +++ b/src/main/java/com/flowpowered/cerealization/config/commented/CommentedConfigurationNode.java @@ -30,53 +30,53 @@ * A ConfigurationNode type that also stores comments. These normally exist in {@link CommentedConfiguration}s. */ public class CommentedConfigurationNode extends ConfigurationNode { - public static final String LINE_SEPARATOR; + public static final String LINE_SEPARATOR; - static { - String sep = System.getProperty("line.separator"); - if (sep == null) { - sep = "\n"; - } - LINE_SEPARATOR = sep; - } + static { + String sep = System.getProperty("line.separator"); + if (sep == null) { + sep = "\n"; + } + LINE_SEPARATOR = sep; + } - private String[] comment; + private String[] comment; - public CommentedConfigurationNode(Configuration config, String[] path, Object value) { - super(config, path, value); - } + public CommentedConfigurationNode(Configuration config, String[] path, Object value) { + super(config, path, value); + } - /** - * Returns the comment lines attached to this configuration node Will return null if this node doesn't have a comment - * - * @return The comment for this node - */ - public String[] getComment() { - return comment; - } + /** + * Returns the comment lines attached to this configuration node Will return null if this node doesn't have a comment + * + * @return The comment for this node + */ + public String[] getComment() { + return comment; + } - /** - * Sets the comment that is attached to this configuration node. In this method the comment is provided as one line, containing the line separator character - * - * @param comment The comment to set - */ - public void setComment(String comment) { - checkAdded(); - this.comment = comment.split(LINE_SEPARATOR); - } + /** + * Sets the comment that is attached to this configuration node. In this method the comment is provided as one line, containing the line separator character + * + * @param comment The comment to set + */ + public void setComment(String comment) { + checkAdded(); + this.comment = comment.split(LINE_SEPARATOR); + } - /** - * Sets the comment of the configuration, already split by line - * - * @param comment The comment lines - */ - public void setComment(String... comment) { - checkAdded(); - this.comment = comment; - } + /** + * Sets the comment of the configuration, already split by line + * + * @param comment The comment lines + */ + public void setComment(String... comment) { + checkAdded(); + this.comment = comment; + } - @Override - public CommentedConfigurationNode createConfigurationNode(String[] path, Object value) { - return new CommentedConfigurationNode(getConfiguration(), path, value); - } + @Override + public CommentedConfigurationNode createConfigurationNode(String[] path, Object value) { + return new CommentedConfigurationNode(getConfiguration(), path, value); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/ini/IniConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/ini/IniConfiguration.java index 102fd8a..d3ed99b 100644 --- a/src/main/java/com/flowpowered/cerealization/config/ini/IniConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/ini/IniConfiguration.java @@ -81,322 +81,322 @@ * */ public class IniConfiguration extends AbstractConfiguration implements CommentedConfiguration, FileConfiguration { - public static final char COMMENT_CHAR_SEMICOLON = ';'; - public static final char COMMENT_CHAR_HASH = '#'; - public static final Pattern COMMENT_REGEX = Pattern.compile("[" + COMMENT_CHAR_SEMICOLON + COMMENT_CHAR_HASH + "] ?(.*)"); - public static final Pattern SECTION_REGEX = Pattern.compile("\\[(.*)\\]"); - private char preferredCommentChar = COMMENT_CHAR_HASH; - private final IOFactory factory; - - public IniConfiguration(File file) { - this(new IOFactory.File(file)); - } - - public IniConfiguration(IOFactory factory) { - this.factory = factory; - } - - @Override - protected Map loadToNodes() throws ConfigurationException { - Reader stream = null; - Map nodes = new LinkedHashMap(); - try { - stream = getReader(); - BufferedReader reader = new BufferedReader(stream); - String line; - List comments = new ArrayList(); - List curSection = new ArrayList(); - CommentedConfigurationNode node = null; - Matcher match; - while ((line = reader.readLine()) != null) { - line = line.trim(); - if (line.length() == 0) { - continue; - } - - match = COMMENT_REGEX.matcher(line); - if (match.matches()) { - comments.add(match.group(1)); - continue; - } - match = SECTION_REGEX.matcher(line); - if (match.matches()) { - if (node != null) { - for (ConfigurationNode subNode : readNodeSection(node.getPathElements(), curSection.toArray(new String[curSection.size()]))) { - node.addChild(subNode); - } - } - node = createConfigurationNode(new String[] {match.group(1)}, null); - if (comments.size() > 0) { - node.setComment(comments.toArray(new String[comments.size()])); - comments.clear(); - } - nodes.put(match.group(1), node); - } else { - if (comments.size() > 0) { - for (String comment : comments) { - curSection.add(getPreferredCommentChar() + " " + comment); - } - comments.clear(); - } - curSection.add(line); - } - } - - if (node != null && curSection.size() > 0) { - for (ConfigurationNode subNode : readNodeSection(node.getPathElements(), curSection.toArray(new String[curSection.size()]))) { - node.addChild(subNode); - } - } - } catch (IOException e) { - throw new ConfigurationException(e); - } finally { - if (stream != null) { - try { - stream.close(); - } catch (IOException ignore) { - } - } - } - return nodes; - } - - @Override - protected void saveFromNodes(Map nodes) throws ConfigurationException { - Writer rawWriter = null; - BufferedWriter writer = null; - try { - rawWriter = getWriter(); - writer = new BufferedWriter(rawWriter); - - List childlessNodes = new ArrayList(), sectionNodes = new ArrayList(); - for (ConfigurationNode node : nodes.values()) { - if (node.hasChildren()) { - sectionNodes.add(node); - } else { - childlessNodes.add(node); - } - } - - if (childlessNodes.size() > 0) { - writeNodeSection(writer, childlessNodes); - } - - for (Iterator i = sectionNodes.iterator(); i.hasNext(); ) { - ConfigurationNode node = i.next(); - String[] comment = getComment(node); - if (comment != null) { - for (String line : comment) { - writer.append(getPreferredCommentChar()).append(" ").append(line).append(LINE_SEPARATOR); - } - } - writer.append('[').append(node.getPathElements()[0]).append(']').append(LINE_SEPARATOR); - writeNodeSection(writer, node.getChildren().values()); - if (i.hasNext()) { - writer.append(LINE_SEPARATOR); - } - } - } catch (IOException e) { - throw new ConfigurationException(e); - } finally { - if (writer != null) { - try { - writer.flush(); - } catch (IOException ignore) { - } - } - if (rawWriter != null) { - try { - rawWriter.flush(); - rawWriter.close(); - } catch (IOException ignore) { - } - } - } - } - - /** - * This method reads one section of INI configuration data. - * - * @param parentPath The path of the section containing this data - * @param lines The lines of data to read - * @return The configuration nodes read from the section - * @throws ConfigurationException when an invalid node is specified - */ - protected List readNodeSection(String[] parentPath, String[] lines) throws ConfigurationException { - List nodes = new ArrayList(); - List comment = new ArrayList(); - Matcher match; - for (String line : lines) { - match = COMMENT_REGEX.matcher(line); - if (match.matches()) { - comment.add(match.group(1)); - continue; - } - String[] split = line.split("[=:]", 2); - if (split.length < 2) { - throw new ConfigurationException("Key with no value: " + line); - } - CommentedConfigurationNode node = createConfigurationNode(ArrayUtils.add(parentPath, split[0].trim()), null); - node.setValue(fromStringValue(split[1].trim())); - if (comment.size() > 0) { - node.setComment(comment.toArray(new String[comment.size()])); - } - nodes.add(node); - } - return nodes; - } - - /** - * Writes a single section of nodes to the specified Writer The nodes passed to this method must not have children - * - * @param writer The Writer to write data to - * @param nodes The nodes to write - * @throws ConfigurationException when a node cannot be correctly written - */ - protected void writeNodeSection(Writer writer, Collection nodes) throws ConfigurationException { - try { - for (ConfigurationNode node : nodes) { - if (node.hasChildren()) { - throw new ConfigurationException("Nodes passed to getChildlessNodes must not have children!"); - } - String[] comment = getComment(node); - if (comment != null) { - for (String line : comment) { - writer.append(getPreferredCommentChar()).append(" ").append(line).append(LINE_SEPARATOR); - } - } - writer.append(node.getPathElements()[node.getPathElements().length - 1]).append("=").append(toStringValue(node.getValue())).append(LINE_SEPARATOR); - } - } catch (IOException e) { - throw new ConfigurationException(e); - } - } - - /** - * Returns the comment for a given configuration node, with a safe check to make sure the node is a CommentedConfigurationNode - * - * @param node The node to get a comment from - * @return The node's comment, or null if no comment is present - */ - protected static String[] getComment(ConfigurationNode node) { - String[] comment = null; - if (node instanceof CommentedConfigurationNode) { - comment = ((CommentedConfigurationNode) node).getComment(); - } - return comment; - } - - /** - * Converts a raw String into the correct Object representation for the Configuration node - * - * @param value The string value - * @return The value converted into the correct Object representation - */ - public Object fromStringValue(String value) { - if (value.matches("^([\"']).*\\1$")) { // Quote value - return value.substring(1, value.length() - 1); - } - - String[] objects = value.split(", ?"); - if (objects.length == 1) { - return objects[0]; - } - return new ArrayList(Arrays.asList(objects)); - } - - /** - * Returns the String representation of a configuration value for writing to the file - * - * @return string representation - */ - public String toStringValue(Object value) { - if (value == null) { - return "null"; - } - if (value.getClass().isArray()) { - List toList = new ArrayList(); - final int length = Array.getLength(value); - for (int i = 0; i < length; ++i) { - toList.add(Array.get(value, i)); - } - value = toList; - } - if (value instanceof Collection) { - StringBuilder builder = new StringBuilder(); - for (Object obj : (Collection) value) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append(obj.toString()); - } - return builder.toString(); - } else { - String strValue = value.toString(); - if (strValue.contains(",")) { - strValue = '"' + strValue + '"'; - } - return strValue; - } - } - - @Override - public CommentedConfigurationNode getNode(String path) { - return (CommentedConfigurationNode) super.getNode(path); - } - - @Override - public CommentedConfigurationNode getNode(String... path) { - return (CommentedConfigurationNode) super.getNode(path); - } - - @Override - public String[] splitNodePath(String path) { - return getPathSeparatorPattern().split(path, 2); - } - - @Override - public String[] ensureCorrectPath(String[] rawPath) { - if (rawPath.length <= 2) { - return rawPath; - } - - return new String[] { - rawPath[0], - StringUtils.join(ArrayUtils.subarray(rawPath, 1, rawPath.length), getPathSeparator()) - }; - } - - @Override - public CommentedConfigurationNode createConfigurationNode(String[] path, Object value) { - return new CommentedConfigurationNode(getConfiguration(), path, value); - } - - public IOFactory getIOFactory() { - return factory; - } - - protected Reader getReader() throws IOException { - return factory.createReader(); - } - - protected Writer getWriter() throws IOException { - return factory.createWriter(); - } - - @Override - public File getFile() { - return factory instanceof IOFactory.File ? ((IOFactory.File) factory).getFile() : null; - } - - public char getPreferredCommentChar() { - return preferredCommentChar; - } - - public void setPreferredCommentChar(char commentChar) { - if (commentChar != COMMENT_CHAR_HASH && commentChar != COMMENT_CHAR_SEMICOLON) { - throw new IllegalArgumentException("Invalid comment char: " + commentChar + "!"); - } - this.preferredCommentChar = commentChar; - } + public static final char COMMENT_CHAR_SEMICOLON = ';'; + public static final char COMMENT_CHAR_HASH = '#'; + public static final Pattern COMMENT_REGEX = Pattern.compile("[" + COMMENT_CHAR_SEMICOLON + COMMENT_CHAR_HASH + "] ?(.*)"); + public static final Pattern SECTION_REGEX = Pattern.compile("\\[(.*)\\]"); + private char preferredCommentChar = COMMENT_CHAR_HASH; + private final IOFactory factory; + + public IniConfiguration(File file) { + this(new IOFactory.File(file)); + } + + public IniConfiguration(IOFactory factory) { + this.factory = factory; + } + + @Override + protected Map loadToNodes() throws ConfigurationException { + Reader stream = null; + Map nodes = new LinkedHashMap(); + try { + stream = getReader(); + BufferedReader reader = new BufferedReader(stream); + String line; + List comments = new ArrayList(); + List curSection = new ArrayList(); + CommentedConfigurationNode node = null; + Matcher match; + while ((line = reader.readLine()) != null) { + line = line.trim(); + if (line.length() == 0) { + continue; + } + + match = COMMENT_REGEX.matcher(line); + if (match.matches()) { + comments.add(match.group(1)); + continue; + } + match = SECTION_REGEX.matcher(line); + if (match.matches()) { + if (node != null) { + for (ConfigurationNode subNode : readNodeSection(node.getPathElements(), curSection.toArray(new String[curSection.size()]))) { + node.addChild(subNode); + } + } + node = createConfigurationNode(new String[] {match.group(1)}, null); + if (comments.size() > 0) { + node.setComment(comments.toArray(new String[comments.size()])); + comments.clear(); + } + nodes.put(match.group(1), node); + } else { + if (comments.size() > 0) { + for (String comment : comments) { + curSection.add(getPreferredCommentChar() + " " + comment); + } + comments.clear(); + } + curSection.add(line); + } + } + + if (node != null && curSection.size() > 0) { + for (ConfigurationNode subNode : readNodeSection(node.getPathElements(), curSection.toArray(new String[curSection.size()]))) { + node.addChild(subNode); + } + } + } catch (IOException e) { + throw new ConfigurationException(e); + } finally { + if (stream != null) { + try { + stream.close(); + } catch (IOException ignore) { + } + } + } + return nodes; + } + + @Override + protected void saveFromNodes(Map nodes) throws ConfigurationException { + Writer rawWriter = null; + BufferedWriter writer = null; + try { + rawWriter = getWriter(); + writer = new BufferedWriter(rawWriter); + + List childlessNodes = new ArrayList(), sectionNodes = new ArrayList(); + for (ConfigurationNode node : nodes.values()) { + if (node.hasChildren()) { + sectionNodes.add(node); + } else { + childlessNodes.add(node); + } + } + + if (childlessNodes.size() > 0) { + writeNodeSection(writer, childlessNodes); + } + + for (Iterator i = sectionNodes.iterator(); i.hasNext(); ) { + ConfigurationNode node = i.next(); + String[] comment = getComment(node); + if (comment != null) { + for (String line : comment) { + writer.append(getPreferredCommentChar()).append(" ").append(line).append(LINE_SEPARATOR); + } + } + writer.append('[').append(node.getPathElements()[0]).append(']').append(LINE_SEPARATOR); + writeNodeSection(writer, node.getChildren().values()); + if (i.hasNext()) { + writer.append(LINE_SEPARATOR); + } + } + } catch (IOException e) { + throw new ConfigurationException(e); + } finally { + if (writer != null) { + try { + writer.flush(); + } catch (IOException ignore) { + } + } + if (rawWriter != null) { + try { + rawWriter.flush(); + rawWriter.close(); + } catch (IOException ignore) { + } + } + } + } + + /** + * This method reads one section of INI configuration data. + * + * @param parentPath The path of the section containing this data + * @param lines The lines of data to read + * @return The configuration nodes read from the section + * @throws ConfigurationException when an invalid node is specified + */ + protected List readNodeSection(String[] parentPath, String[] lines) throws ConfigurationException { + List nodes = new ArrayList(); + List comment = new ArrayList(); + Matcher match; + for (String line : lines) { + match = COMMENT_REGEX.matcher(line); + if (match.matches()) { + comment.add(match.group(1)); + continue; + } + String[] split = line.split("[=:]", 2); + if (split.length < 2) { + throw new ConfigurationException("Key with no value: " + line); + } + CommentedConfigurationNode node = createConfigurationNode(ArrayUtils.add(parentPath, split[0].trim()), null); + node.setValue(fromStringValue(split[1].trim())); + if (comment.size() > 0) { + node.setComment(comment.toArray(new String[comment.size()])); + } + nodes.add(node); + } + return nodes; + } + + /** + * Writes a single section of nodes to the specified Writer The nodes passed to this method must not have children + * + * @param writer The Writer to write data to + * @param nodes The nodes to write + * @throws ConfigurationException when a node cannot be correctly written + */ + protected void writeNodeSection(Writer writer, Collection nodes) throws ConfigurationException { + try { + for (ConfigurationNode node : nodes) { + if (node.hasChildren()) { + throw new ConfigurationException("Nodes passed to getChildlessNodes must not have children!"); + } + String[] comment = getComment(node); + if (comment != null) { + for (String line : comment) { + writer.append(getPreferredCommentChar()).append(" ").append(line).append(LINE_SEPARATOR); + } + } + writer.append(node.getPathElements()[node.getPathElements().length - 1]).append("=").append(toStringValue(node.getValue())).append(LINE_SEPARATOR); + } + } catch (IOException e) { + throw new ConfigurationException(e); + } + } + + /** + * Returns the comment for a given configuration node, with a safe check to make sure the node is a CommentedConfigurationNode + * + * @param node The node to get a comment from + * @return The node's comment, or null if no comment is present + */ + protected static String[] getComment(ConfigurationNode node) { + String[] comment = null; + if (node instanceof CommentedConfigurationNode) { + comment = ((CommentedConfigurationNode) node).getComment(); + } + return comment; + } + + /** + * Converts a raw String into the correct Object representation for the Configuration node + * + * @param value The string value + * @return The value converted into the correct Object representation + */ + public Object fromStringValue(String value) { + if (value.matches("^([\"']).*\\1$")) { // Quote value + return value.substring(1, value.length() - 1); + } + + String[] objects = value.split(", ?"); + if (objects.length == 1) { + return objects[0]; + } + return new ArrayList(Arrays.asList(objects)); + } + + /** + * Returns the String representation of a configuration value for writing to the file + * + * @return string representation + */ + public String toStringValue(Object value) { + if (value == null) { + return "null"; + } + if (value.getClass().isArray()) { + List toList = new ArrayList(); + final int length = Array.getLength(value); + for (int i = 0; i < length; ++i) { + toList.add(Array.get(value, i)); + } + value = toList; + } + if (value instanceof Collection) { + StringBuilder builder = new StringBuilder(); + for (Object obj : (Collection) value) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append(obj.toString()); + } + return builder.toString(); + } else { + String strValue = value.toString(); + if (strValue.contains(",")) { + strValue = '"' + strValue + '"'; + } + return strValue; + } + } + + @Override + public CommentedConfigurationNode getNode(String path) { + return (CommentedConfigurationNode) super.getNode(path); + } + + @Override + public CommentedConfigurationNode getNode(String... path) { + return (CommentedConfigurationNode) super.getNode(path); + } + + @Override + public String[] splitNodePath(String path) { + return getPathSeparatorPattern().split(path, 2); + } + + @Override + public String[] ensureCorrectPath(String[] rawPath) { + if (rawPath.length <= 2) { + return rawPath; + } + + return new String[] { + rawPath[0], + StringUtils.join(ArrayUtils.subarray(rawPath, 1, rawPath.length), getPathSeparator()) + }; + } + + @Override + public CommentedConfigurationNode createConfigurationNode(String[] path, Object value) { + return new CommentedConfigurationNode(getConfiguration(), path, value); + } + + public IOFactory getIOFactory() { + return factory; + } + + protected Reader getReader() throws IOException { + return factory.createReader(); + } + + protected Writer getWriter() throws IOException { + return factory.createWriter(); + } + + @Override + public File getFile() { + return factory instanceof IOFactory.File ? ((IOFactory.File) factory).getFile() : null; + } + + public char getPreferredCommentChar() { + return preferredCommentChar; + } + + public void setPreferredCommentChar(char commentChar) { + if (commentChar != COMMENT_CHAR_HASH && commentChar != COMMENT_CHAR_SEMICOLON) { + throw new IllegalArgumentException("Invalid comment char: " + commentChar + "!"); + } + this.preferredCommentChar = commentChar; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/ini/StringLoadingIniConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/ini/StringLoadingIniConfiguration.java index ca2ac8a..1151bd2 100644 --- a/src/main/java/com/flowpowered/cerealization/config/ini/StringLoadingIniConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/ini/StringLoadingIniConfiguration.java @@ -29,20 +29,20 @@ * A subclass of IniConfiguration that loads from a String */ public class StringLoadingIniConfiguration extends IniConfiguration { - public StringLoadingIniConfiguration(String value) { - super(new IOFactory.String(value)); - } + public StringLoadingIniConfiguration(String value) { + super(new IOFactory.String(value)); + } - @Override - public IOFactory.String getIOFactory() { - return (IOFactory.String) super.getIOFactory(); - } + @Override + public IOFactory.String getIOFactory() { + return (IOFactory.String) super.getIOFactory(); + } - public void setValue(String value) { - getIOFactory().setData(value); - } + public void setValue(String value) { + getIOFactory().setData(value); + } - public String getValue() { - return getIOFactory().getBuffer().toString(); - } + public String getValue() { + return getIOFactory().getBuffer().toString(); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/migration/ConfigurationMigrator.java b/src/main/java/com/flowpowered/cerealization/config/migration/ConfigurationMigrator.java index 727d700..32d76a1 100644 --- a/src/main/java/com/flowpowered/cerealization/config/migration/ConfigurationMigrator.java +++ b/src/main/java/com/flowpowered/cerealization/config/migration/ConfigurationMigrator.java @@ -39,67 +39,67 @@ * A simple migrator for configurations that moves values from one key to another. It can also convert values */ public abstract class ConfigurationMigrator { - private final Configuration configuration; + private final Configuration configuration; - protected ConfigurationMigrator(Configuration configuration) { - Validate.notNull(configuration); - this.configuration = configuration; - } + protected ConfigurationMigrator(Configuration configuration) { + Validate.notNull(configuration); + this.configuration = configuration; + } - /** - * Put together a collection of all keys to be migrated and their associated actions. This can be put in a static HashMap, or generated on each invocation - * - * @return The map of configuration keys to their associated actions - */ - protected abstract Map getMigrationActions(); + /** + * Put together a collection of all keys to be migrated and their associated actions. This can be put in a static HashMap, or generated on each invocation + * + * @return The map of configuration keys to their associated actions + */ + protected abstract Map getMigrationActions(); - public Configuration getConfiguration() { - return configuration; - } + public Configuration getConfiguration() { + return configuration; + } - /** - * This method checks whether migration is needed on the {@link Configuration} this instance is constructed with - * - * @return Whether migration is needed - */ - protected abstract boolean shouldMigrate(); + /** + * This method checks whether migration is needed on the {@link Configuration} this instance is constructed with + * + * @return Whether migration is needed + */ + protected abstract boolean shouldMigrate(); - /** - * Perform migration of the configuration this object was constructed with If migration was not necessary ({@link #shouldMigrate()} returned false), the method invocation will be considered - * successful. If {@link #configuration} is a {@link com.flowpowered.cerealization.config.FileConfiguration}, the file the configuration vas previously stored in will be moved to (file name).old as a backup of - * the data before migration - * - * @throws MigrationException if the configuration could not be successfully migrated - */ - public void migrate() throws MigrationException { - if (!shouldMigrate()) { - return; - } + /** + * Perform migration of the configuration this object was constructed with If migration was not necessary ({@link #shouldMigrate()} returned false), the method invocation will be considered + * successful. If {@link #configuration} is a {@link com.flowpowered.cerealization.config.FileConfiguration}, the file the configuration vas previously stored in will be moved to (file name).old as a backup of + * the data before migration + * + * @throws MigrationException if the configuration could not be successfully migrated + */ + public void migrate() throws MigrationException { + if (!shouldMigrate()) { + return; + } - if (configuration instanceof FileConfiguration) { - File oldFile = ((FileConfiguration) configuration).getFile(); - try { - FileUtils.moveFile(oldFile, new File(oldFile.getAbsolutePath() + ".old")); - } catch (IOException e) { - throw new MigrationException(e); - } - } + if (configuration instanceof FileConfiguration) { + File oldFile = ((FileConfiguration) configuration).getFile(); + try { + FileUtils.moveFile(oldFile, new File(oldFile.getAbsolutePath() + ".old")); + } catch (IOException e) { + throw new MigrationException(e); + } + } - for (Map.Entry entry : getMigrationActions().entrySet()) { - final ConfigurationNode existingNode = configuration.getNode(entry.getKey()); - final Object existing = existingNode.getValue(); - existingNode.remove(); - if (existing == null || entry.getValue() == null) { - continue; - } - final String[] newKey = entry.getValue().convertKey(entry.getKey()); - final Object newValue = entry.getValue().convertValue(existing); - configuration.getNode(newKey).setValue(newValue); - } - try { - configuration.save(); - } catch (ConfigurationException e) { - throw new MigrationException(e); - } - } + for (Map.Entry entry : getMigrationActions().entrySet()) { + final ConfigurationNode existingNode = configuration.getNode(entry.getKey()); + final Object existing = existingNode.getValue(); + existingNode.remove(); + if (existing == null || entry.getValue() == null) { + continue; + } + final String[] newKey = entry.getValue().convertKey(entry.getKey()); + final Object newValue = entry.getValue().convertValue(existing); + configuration.getNode(newKey).setValue(newValue); + } + try { + configuration.save(); + } catch (ConfigurationException e) { + throw new MigrationException(e); + } + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/migration/MigrationAction.java b/src/main/java/com/flowpowered/cerealization/config/migration/MigrationAction.java index 897421d..642d37e 100644 --- a/src/main/java/com/flowpowered/cerealization/config/migration/MigrationAction.java +++ b/src/main/java/com/flowpowered/cerealization/config/migration/MigrationAction.java @@ -27,19 +27,19 @@ * Represents the two sides of migrating an existing configuration key: Converting the key and converting the value */ public interface MigrationAction { - /** - * This method converts the old configuration key to its migrated value. - * - * @param key The existing configuration key - * @return The key modified to its new value - */ - public String[] convertKey(String[] key); + /** + * This method converts the old configuration key to its migrated value. + * + * @param key The existing configuration key + * @return The key modified to its new value + */ + public String[] convertKey(String[] key); - /** - * This method converts the old configuration value to its migrated value. - * - * @param value The existing configuration value - * @return The value modified to its new value - */ - public Object convertValue(Object value); + /** + * This method converts the old configuration value to its migrated value. + * + * @param value The existing configuration value + * @return The value modified to its new value + */ + public Object convertValue(Object value); } diff --git a/src/main/java/com/flowpowered/cerealization/config/migration/MigrationException.java b/src/main/java/com/flowpowered/cerealization/config/migration/MigrationException.java index 10b157f..07e3e6d 100644 --- a/src/main/java/com/flowpowered/cerealization/config/migration/MigrationException.java +++ b/src/main/java/com/flowpowered/cerealization/config/migration/MigrationException.java @@ -27,13 +27,13 @@ * This exception is thrown when an error occurs while migrating the config */ public class MigrationException extends Exception { - private static final long serialVersionUID = 3201476285205550742L; + private static final long serialVersionUID = 3201476285205550742L; - public MigrationException(String message) { - super(message); - } + public MigrationException(String message) { + super(message); + } - public MigrationException(Throwable cause) { - super(cause); - } + public MigrationException(Throwable cause) { + super(cause); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/migration/NewJoinedKey.java b/src/main/java/com/flowpowered/cerealization/config/migration/NewJoinedKey.java index 89ec908..a79c3b5 100644 --- a/src/main/java/com/flowpowered/cerealization/config/migration/NewJoinedKey.java +++ b/src/main/java/com/flowpowered/cerealization/config/migration/NewJoinedKey.java @@ -34,22 +34,22 @@ * @see com.flowpowered.cerealization.config.Configuration#getPathSeparator() */ public final class NewJoinedKey implements MigrationAction { - private final String newKeyPattern; - private final Configuration config; + private final String newKeyPattern; + private final Configuration config; - public NewJoinedKey(String newKeyPattern, Configuration config) { - this.newKeyPattern = newKeyPattern; - this.config = config; - } + public NewJoinedKey(String newKeyPattern, Configuration config) { + this.newKeyPattern = newKeyPattern; + this.config = config; + } - @Override - public String[] convertKey(String[] key) { - String oldKey = StringUtils.join(key, config.getPathSeparator()); - return config.getPathSeparatorPattern().split(newKeyPattern.replace("%", oldKey)); - } + @Override + public String[] convertKey(String[] key) { + String oldKey = StringUtils.join(key, config.getPathSeparator()); + return config.getPathSeparatorPattern().split(newKeyPattern.replace("%", oldKey)); + } - @Override - public Object convertValue(Object value) { - return value; - } + @Override + public Object convertValue(Object value) { + return value; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/migration/NewKey.java b/src/main/java/com/flowpowered/cerealization/config/migration/NewKey.java index beb5b0b..26bb3f4 100644 --- a/src/main/java/com/flowpowered/cerealization/config/migration/NewKey.java +++ b/src/main/java/com/flowpowered/cerealization/config/migration/NewKey.java @@ -27,19 +27,19 @@ * This implementation of MigrationAction changes the key of a configuration value to a predefined new key */ public final class NewKey implements MigrationAction { - private final String[] newKey; + private final String[] newKey; - public NewKey(String... key) { - this.newKey = key; - } + public NewKey(String... key) { + this.newKey = key; + } - @Override - public String[] convertKey(String[] key) { - return newKey; - } + @Override + public String[] convertKey(String[] key) { + return newKey; + } - @Override - public Object convertValue(Object value) { - return value; - } + @Override + public Object convertValue(Object value) { + return value; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/BooleanSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/BooleanSerializer.java index 482bfa7..0253fb0 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/BooleanSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/BooleanSerializer.java @@ -24,22 +24,22 @@ package com.flowpowered.cerealization.config.serialization; public class BooleanSerializer extends Serializer { - @Override - public boolean isApplicable(GenericType type) { - return boolean.class.isAssignableFrom(type.getMainType()) || Boolean.class.isAssignableFrom(type.getMainType()); - } + @Override + public boolean isApplicable(GenericType type) { + return boolean.class.isAssignableFrom(type.getMainType()) || Boolean.class.isAssignableFrom(type.getMainType()); + } - @Override - protected int getParametersRequired() { - return 0; - } + @Override + protected int getParametersRequired() { + return 0; + } - @Override - protected Object handleDeserialize(GenericType type, Object value) { - if (value instanceof Boolean) { - return value; - } else { - return Boolean.parseBoolean(value.toString()); - } - } + @Override + protected Object handleDeserialize(GenericType type, Object value) { + if (value instanceof Boolean) { + return value; + } else { + return Boolean.parseBoolean(value.toString()); + } + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/ByteArraySerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/ByteArraySerializer.java index c20b588..d4383b4 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/ByteArraySerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/ByteArraySerializer.java @@ -26,23 +26,23 @@ import com.flowpowered.cerealization.CastUtils; public class ByteArraySerializer extends Serializer { - @Override - public boolean isApplicable(GenericType type) { - if (!type.isArray()) { - return false; - } - Class arrayType = type.getArrayType().getMainType(); - return arrayType == byte.class; - } + @Override + public boolean isApplicable(GenericType type) { + if (!type.isArray()) { + return false; + } + Class arrayType = type.getArrayType().getMainType(); + return arrayType == byte.class; + } - @Override - protected int getParametersRequired() { - return -1; - } + @Override + protected int getParametersRequired() { + return -1; + } - @Override - protected Object handleDeserialize(GenericType type, Object value) { - return CastUtils.castBytes(value); - } + @Override + protected Object handleDeserialize(GenericType type, Object value) { + return CastUtils.castBytes(value); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/ConfigurationBaseSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/ConfigurationBaseSerializer.java index 775aa42..b628eda 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/ConfigurationBaseSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/ConfigurationBaseSerializer.java @@ -34,80 +34,80 @@ import com.flowpowered.cerealization.config.annotated.AnnotatedSubclassConfiguration; public class ConfigurationBaseSerializer extends Serializer { - private static final Map, - Constructor> CACHED_CONSTRUCTORS = - new HashMap, Constructor>(); + private static final Map, + Constructor> CACHED_CONSTRUCTORS = + new HashMap, Constructor>(); - public ConfigurationBaseSerializer() { - setAllowsNullValue(true); - } + public ConfigurationBaseSerializer() { + setAllowsNullValue(true); + } - @Override - public boolean isApplicable(GenericType type) { - return AnnotatedSubclassConfiguration.class.isAssignableFrom(type.getMainType()); - } + @Override + public boolean isApplicable(GenericType type) { + return AnnotatedSubclassConfiguration.class.isAssignableFrom(type.getMainType()); + } - @Override - public boolean isApplicableDeserialize(GenericType type, Object value) { - return super.isApplicableDeserialize(type, value) && (value == null || value instanceof Map); - } + @Override + public boolean isApplicableDeserialize(GenericType type, Object value) { + return super.isApplicableDeserialize(type, value) && (value == null || value instanceof Map); + } - @Override - protected int getParametersRequired() { - return -1; - } + @Override + protected int getParametersRequired() { + return -1; + } - @Override - protected Object handleDeserialize(GenericType type, Object value) { - if (value == null) { - value = new HashMap(); - } + @Override + protected Object handleDeserialize(GenericType type, Object value) { + if (value == null) { + value = new HashMap(); + } - Class configClass = type.getMainType().asSubclass(AnnotatedSubclassConfiguration.class); - Constructor constructor = CACHED_CONSTRUCTORS.get(configClass); - if (constructor == null) { - try { - constructor = configClass.getDeclaredConstructor(Configuration.class); - constructor.setAccessible(true); - } catch (NoSuchMethodException e) { - return null; - } - CACHED_CONSTRUCTORS.put(configClass, constructor); - } - AnnotatedSubclassConfiguration config = null; - MapConfiguration rawConfig = new MapConfiguration((Map) value); + Class configClass = type.getMainType().asSubclass(AnnotatedSubclassConfiguration.class); + Constructor constructor = CACHED_CONSTRUCTORS.get(configClass); + if (constructor == null) { + try { + constructor = configClass.getDeclaredConstructor(Configuration.class); + constructor.setAccessible(true); + } catch (NoSuchMethodException e) { + return null; + } + CACHED_CONSTRUCTORS.put(configClass, constructor); + } + AnnotatedSubclassConfiguration config = null; + MapConfiguration rawConfig = new MapConfiguration((Map) value); - try { - config = constructor.newInstance(rawConfig); - } catch (InstantiationException ignore) { - } catch (IllegalAccessException e) { - e.printStackTrace(); - return null; - } catch (InvocationTargetException e) { - e.getCause().printStackTrace(); - } + try { + config = constructor.newInstance(rawConfig); + } catch (InstantiationException ignore) { + } catch (IllegalAccessException e) { + e.printStackTrace(); + return null; + } catch (InvocationTargetException e) { + e.getCause().printStackTrace(); + } - if (config != null) { - try { - config.load(); - } catch (ConfigurationException e) { - e.printStackTrace(); - return null; - } - } + if (config != null) { + try { + config.load(); + } catch (ConfigurationException e) { + e.printStackTrace(); + return null; + } + } - return config; - } + return config; + } - @Override - protected Object handleSerialize(GenericType type, Object val) { - MapConfiguration config = new MapConfiguration(); - try { - ((AnnotatedSubclassConfiguration) val).save(config); - config.save(); - } catch (ConfigurationException e) { - return null; - } - return config.getMap(); - } + @Override + protected Object handleSerialize(GenericType type, Object val) { + MapConfiguration config = new MapConfiguration(); + try { + ((AnnotatedSubclassConfiguration) val).save(config); + config.save(); + } catch (ConfigurationException e) { + return null; + } + return config.getMap(); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/DateSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/DateSerializer.java index edcaeb7..03aff67 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/DateSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/DateSerializer.java @@ -28,19 +28,19 @@ import com.flowpowered.cerealization.CastUtils; public class DateSerializer extends Serializer { - @Override - public boolean isApplicable(GenericType type) { - return type.getMainType() != null && type.getMainType() == Date.class; - } + @Override + public boolean isApplicable(GenericType type) { + return type.getMainType() != null && type.getMainType() == Date.class; + } - @Override - protected Object handleDeserialize(GenericType type, Object value) { - return CastUtils.castDate(value); - } + @Override + protected Object handleDeserialize(GenericType type, Object value) { + return CastUtils.castDate(value); + } - @Override - protected int getParametersRequired() { - return -1; - } + @Override + protected int getParametersRequired() { + return -1; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/EnumSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/EnumSerializer.java index 7b71ceb..dd463dd 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/EnumSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/EnumSerializer.java @@ -24,28 +24,28 @@ package com.flowpowered.cerealization.config.serialization; public class EnumSerializer extends Serializer { - @Override - public boolean isApplicable(GenericType target) { - return target.getMainType() != null && target.getMainType().isEnum(); - } + @Override + public boolean isApplicable(GenericType target) { + return target.getMainType() != null && target.getMainType().isEnum(); + } - @Override - protected int getParametersRequired() { - return 0; - } + @Override + protected int getParametersRequired() { + return 0; + } - @Override - @SuppressWarnings ("unchecked") - protected Object handleDeserialize(GenericType type, Object value) { - try { - return Enum.valueOf(type.getMainType().asSubclass(Enum.class), String.valueOf(value).toUpperCase()); - } catch (IllegalArgumentException e) { - return null; - } - } + @Override + @SuppressWarnings ("unchecked") + protected Object handleDeserialize(GenericType type, Object value) { + try { + return Enum.valueOf(type.getMainType().asSubclass(Enum.class), String.valueOf(value).toUpperCase()); + } catch (IllegalArgumentException e) { + return null; + } + } - @Override - protected Object handleSerialize(GenericType type, Object value) { - return ((Enum) value).name(); - } + @Override + protected Object handleSerialize(GenericType type, Object value) { + return ((Enum) value).name(); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/GenericType.java b/src/main/java/com/flowpowered/cerealization/config/serialization/GenericType.java index ef0edd7..38122e1 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/GenericType.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/GenericType.java @@ -32,65 +32,65 @@ * A wrapper around {@link Type} to allow easier access to parameterized types. */ public class GenericType { - private final Class mainType; - private final GenericType[] neededGenerics; - private final GenericType arrayType; - private final Type rawType; + private final Class mainType; + private final GenericType[] neededGenerics; + private final GenericType arrayType; + private final Type rawType; - public GenericType(Type rawType) { - if (rawType instanceof ParameterizedType) { - ParameterizedType type = (ParameterizedType) rawType; - mainType = getMainType(type.getRawType()); - neededGenerics = toGenericType(type.getActualTypeArguments()); - arrayType = null; - } else if (rawType instanceof GenericArrayType) { - GenericArrayType type = (GenericArrayType) rawType; - mainType = null; - neededGenerics = new GenericType[0]; - arrayType = new GenericType(type.getGenericComponentType()); - } else { - mainType = getMainType(rawType); - neededGenerics = new GenericType[0]; - arrayType = null; - } - this.rawType = rawType; - } + public GenericType(Type rawType) { + if (rawType instanceof ParameterizedType) { + ParameterizedType type = (ParameterizedType) rawType; + mainType = getMainType(type.getRawType()); + neededGenerics = toGenericType(type.getActualTypeArguments()); + arrayType = null; + } else if (rawType instanceof GenericArrayType) { + GenericArrayType type = (GenericArrayType) rawType; + mainType = null; + neededGenerics = new GenericType[0]; + arrayType = new GenericType(type.getGenericComponentType()); + } else { + mainType = getMainType(rawType); + neededGenerics = new GenericType[0]; + arrayType = null; + } + this.rawType = rawType; + } - public Class getMainType() { - return mainType; - } + public Class getMainType() { + return mainType; + } - public GenericType[] getGenerics() { - return neededGenerics; - } + public GenericType[] getGenerics() { + return neededGenerics; + } - public Type getRawType() { - return rawType; - } + public Type getRawType() { + return rawType; + } - public boolean isArray() { - return arrayType != null; - } + public boolean isArray() { + return arrayType != null; + } - public GenericType getArrayType() { - return arrayType; - } + public GenericType getArrayType() { + return arrayType; + } - private static Class getMainType(Type type) { - if (type instanceof Class) { - return (Class) type; - } else if (type instanceof WildcardType) { - return (Class) ((WildcardType) type).getUpperBounds()[0]; - } else { - throw new IllegalArgumentException("Unknown main class type: " + type.getClass()); - } - } + private static Class getMainType(Type type) { + if (type instanceof Class) { + return (Class) type; + } else if (type instanceof WildcardType) { + return (Class) ((WildcardType) type).getUpperBounds()[0]; + } else { + throw new IllegalArgumentException("Unknown main class type: " + type.getClass()); + } + } - public static GenericType[] toGenericType(Type[] types) { - GenericType[] genericTypes = new GenericType[types.length]; - for (int i = 0; i < types.length; ++i) { - genericTypes[i] = new GenericType(types[i]); - } - return genericTypes; - } + public static GenericType[] toGenericType(Type[] types) { + GenericType[] genericTypes = new GenericType[types.length]; + for (int i = 0; i < types.length; ++i) { + genericTypes[i] = new GenericType(types[i]); + } + return genericTypes; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/ListSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/ListSerializer.java index 905433d..0da973e 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/ListSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/ListSerializer.java @@ -28,38 +28,38 @@ import java.util.List; public class ListSerializer extends Serializer { - @Override - public boolean isApplicable(GenericType type) { - return List.class.equals(type.getMainType()); - } + @Override + public boolean isApplicable(GenericType type) { + return List.class.equals(type.getMainType()); + } - @Override - public boolean isApplicableDeserialize(GenericType type, Object value) { - return super.isApplicableDeserialize(type, value) && value instanceof Collection; - } + @Override + public boolean isApplicableDeserialize(GenericType type, Object value) { + return super.isApplicableDeserialize(type, value) && value instanceof Collection; + } - @Override - public int getParametersRequired() { - return 1; - } + @Override + public int getParametersRequired() { + return 1; + } - @Override - protected Object handleDeserialize(GenericType type, Object value) { - List values = new ArrayList(); - Collection raw = (Collection) value; - for (Object obj : raw) { - values.add(Serialization.deserialize(type.getGenerics()[0], obj)); - } - return values; - } + @Override + protected Object handleDeserialize(GenericType type, Object value) { + List values = new ArrayList(); + Collection raw = (Collection) value; + for (Object obj : raw) { + values.add(Serialization.deserialize(type.getGenerics()[0], obj)); + } + return values; + } - @Override - protected Object handleSerialize(GenericType type, Object value) { - List values = new ArrayList(); - Collection raw = (Collection) value; - for (Object obj : raw) { - values.add(Serialization.serialize(type.getGenerics()[0], obj)); - } - return values; - } + @Override + protected Object handleSerialize(GenericType type, Object value) { + List values = new ArrayList(); + Collection raw = (Collection) value; + for (Object obj : raw) { + values.add(Serialization.serialize(type.getGenerics()[0], obj)); + } + return values; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/MapSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/MapSerializer.java index 601c39a..2e2936f 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/MapSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/MapSerializer.java @@ -27,40 +27,40 @@ import java.util.Map; public class MapSerializer extends Serializer { - @Override - public boolean isApplicable(GenericType type) { - return Map.class.equals(type.getMainType()); - } + @Override + public boolean isApplicable(GenericType type) { + return Map.class.equals(type.getMainType()); + } - @Override - protected int getParametersRequired() { - return 2; - } + @Override + protected int getParametersRequired() { + return 2; + } - @Override - public boolean isApplicableDeserialize(GenericType type, Object value) { - return super.isApplicableDeserialize(type, value) && value instanceof Map; - } + @Override + public boolean isApplicableDeserialize(GenericType type, Object value) { + return super.isApplicableDeserialize(type, value) && value instanceof Map; + } - @Override - protected Object handleDeserialize(GenericType type, Object value) { - Map raw = (Map) value; - Map values = new HashMap(); - for (Map.Entry entry : raw.entrySet()) { - values.put(Serialization.deserialize(type.getGenerics()[0], entry.getKey()), - Serialization.deserialize(type.getGenerics()[1], entry.getValue())); - } - return values; - } + @Override + protected Object handleDeserialize(GenericType type, Object value) { + Map raw = (Map) value; + Map values = new HashMap(); + for (Map.Entry entry : raw.entrySet()) { + values.put(Serialization.deserialize(type.getGenerics()[0], entry.getKey()), + Serialization.deserialize(type.getGenerics()[1], entry.getValue())); + } + return values; + } - @Override - protected Object handleSerialize(GenericType type, Object value) { - Map raw = (Map) value; - Map values = new HashMap(); - for (Map.Entry entry : raw.entrySet()) { - values.put(Serialization.serialize(type.getGenerics()[0], entry.getKey()), - Serialization.serialize(type.getGenerics()[1], entry.getValue())); - } - return values; - } + @Override + protected Object handleSerialize(GenericType type, Object value) { + Map raw = (Map) value; + Map values = new HashMap(); + for (Map.Entry entry : raw.entrySet()) { + values.put(Serialization.serialize(type.getGenerics()[0], entry.getKey()), + Serialization.serialize(type.getGenerics()[1], entry.getValue())); + } + return values; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/NumberSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/NumberSerializer.java index a3ea2be..25c7515 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/NumberSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/NumberSerializer.java @@ -29,74 +29,74 @@ import com.flowpowered.cerealization.CastUtils; public class NumberSerializer extends Serializer { - @Override - public boolean isApplicable(GenericType type) { - Class target = type.getMainType(); - return target != null && (target.isPrimitive() || Number.class.isAssignableFrom(target)) && !boolean.class.isAssignableFrom(target); - } + @Override + public boolean isApplicable(GenericType type) { + Class target = type.getMainType(); + return target != null && (target.isPrimitive() || Number.class.isAssignableFrom(target)) && !boolean.class.isAssignableFrom(target); + } - @Override - public int getParametersRequired() { - return 0; - } + @Override + public int getParametersRequired() { + return 0; + } - @Override - protected Object handleDeserialize(GenericType type, Object rawVal) { - Class target = type.getMainType(); - // Wrapper classes are evil! - if (target.equals(Number.class) && rawVal instanceof Number) { - return rawVal; - } else if (target.equals(int.class) || target.equals(Integer.class)) { - if (rawVal instanceof Number) { - return ((Number) rawVal).intValue(); - } else { - return Integer.parseInt(String.valueOf(rawVal)); - } - } else if (target.equals(byte.class) || target.equals(Byte.class)) { - if (rawVal instanceof Number) { - return ((Number) rawVal).byteValue(); - } else { - return Byte.parseByte(String.valueOf(rawVal)); - } - } else if (target.equals(long.class) || target.equals(Long.class)) { - if (rawVal instanceof Number) { - return ((Number) rawVal).longValue(); - } else { - return Long.parseLong(String.valueOf(rawVal)); - } - } else if (target.equals(double.class) || target.equals(Double.class)) { - if (rawVal instanceof Number) { - return ((Number) rawVal).doubleValue(); - } else { - return Double.parseDouble(String.valueOf(rawVal)); - } - } else if (target.equals(float.class) || target.equals(Float.class)) { - if (rawVal instanceof Number) { - return ((Number) rawVal).floatValue(); - } else { - return Float.parseFloat(String.valueOf(rawVal)); - } - } else if (target.equals(short.class) || target.equals(Short.class)) { - if (rawVal instanceof Number) { - return ((Number) rawVal).shortValue(); - } else { - return Short.parseShort(String.valueOf(rawVal)); - } - } else if (target.equals(BigInteger.class)) { - final BigInteger val = CastUtils.castBigInt(rawVal); - if (val != null) { - return val; - } else { - return new BigInteger(String.valueOf(rawVal)); - } - } else if (target.equals(BigDecimal.class)) { - final BigDecimal val = CastUtils.castBigDecimal(rawVal); - if (val != null) { - return val; - } else { - return new BigDecimal(String.valueOf(rawVal)); - } - } - return null; - } + @Override + protected Object handleDeserialize(GenericType type, Object rawVal) { + Class target = type.getMainType(); + // Wrapper classes are evil! + if (target.equals(Number.class) && rawVal instanceof Number) { + return rawVal; + } else if (target.equals(int.class) || target.equals(Integer.class)) { + if (rawVal instanceof Number) { + return ((Number) rawVal).intValue(); + } else { + return Integer.parseInt(String.valueOf(rawVal)); + } + } else if (target.equals(byte.class) || target.equals(Byte.class)) { + if (rawVal instanceof Number) { + return ((Number) rawVal).byteValue(); + } else { + return Byte.parseByte(String.valueOf(rawVal)); + } + } else if (target.equals(long.class) || target.equals(Long.class)) { + if (rawVal instanceof Number) { + return ((Number) rawVal).longValue(); + } else { + return Long.parseLong(String.valueOf(rawVal)); + } + } else if (target.equals(double.class) || target.equals(Double.class)) { + if (rawVal instanceof Number) { + return ((Number) rawVal).doubleValue(); + } else { + return Double.parseDouble(String.valueOf(rawVal)); + } + } else if (target.equals(float.class) || target.equals(Float.class)) { + if (rawVal instanceof Number) { + return ((Number) rawVal).floatValue(); + } else { + return Float.parseFloat(String.valueOf(rawVal)); + } + } else if (target.equals(short.class) || target.equals(Short.class)) { + if (rawVal instanceof Number) { + return ((Number) rawVal).shortValue(); + } else { + return Short.parseShort(String.valueOf(rawVal)); + } + } else if (target.equals(BigInteger.class)) { + final BigInteger val = CastUtils.castBigInt(rawVal); + if (val != null) { + return val; + } else { + return new BigInteger(String.valueOf(rawVal)); + } + } else if (target.equals(BigDecimal.class)) { + final BigDecimal val = CastUtils.castBigDecimal(rawVal); + if (val != null) { + return val; + } else { + return new BigDecimal(String.valueOf(rawVal)); + } + } + return null; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/SameSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/SameSerializer.java index c99497d..016232a 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/SameSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/SameSerializer.java @@ -24,28 +24,28 @@ package com.flowpowered.cerealization.config.serialization; public class SameSerializer extends Serializer { - @Override - public boolean isApplicable(GenericType type) { - return type.getMainType() != null; - } + @Override + public boolean isApplicable(GenericType type) { + return type.getMainType() != null; + } - @Override - public boolean isApplicableDeserialize(GenericType type, Object value) { - return super.isApplicableDeserialize(type, value) && type.getMainType().isInstance(value); - } + @Override + public boolean isApplicableDeserialize(GenericType type, Object value) { + return super.isApplicableDeserialize(type, value) && type.getMainType().isInstance(value); + } - @Override - public boolean isApplicableSerialize(GenericType type, Object val) { - return false; - } + @Override + public boolean isApplicableSerialize(GenericType type, Object val) { + return false; + } - @Override - public int getParametersRequired() { - return 0; - } + @Override + public int getParametersRequired() { + return 0; + } - @Override - protected Object handleDeserialize(GenericType type, Object value) { - return value; - } + @Override + protected Object handleDeserialize(GenericType type, Object value) { + return value; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/Serialization.java b/src/main/java/com/flowpowered/cerealization/config/serialization/Serialization.java index bf30ffd..b10d5a0 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/Serialization.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/Serialization.java @@ -31,57 +31,57 @@ import java.util.Map; public class Serialization { - private static final Map CACHED_SERIALIZERS = new HashMap(); - private static final List SERIALIZERS = new ArrayList( - Arrays.asList(new SameSerializer(), - new StringSerializer(), - new BooleanSerializer(), - new NumberSerializer(), - new EnumSerializer(), - new DateSerializer(), - new ByteArraySerializer(), - new ConfigurationBaseSerializer(), - new SetSerializer(), - new ListSerializer(), - new MapSerializer() - )); + private static final Map CACHED_SERIALIZERS = new HashMap(); + private static final List SERIALIZERS = new ArrayList( + Arrays.asList(new SameSerializer(), + new StringSerializer(), + new BooleanSerializer(), + new NumberSerializer(), + new EnumSerializer(), + new DateSerializer(), + new ByteArraySerializer(), + new ConfigurationBaseSerializer(), + new SetSerializer(), + new ListSerializer(), + new MapSerializer() + )); - public static Object deserialize(Type target, Object value) { - return deserialize(new GenericType(target), value); - } + public static Object deserialize(Type target, Object value) { + return deserialize(new GenericType(target), value); + } - public static Object deserialize(GenericType type, Object value) { - Object ret; - for (Serializer serializer : SERIALIZERS) { - if ((ret = serializer.deserialize(type, value)) != null) { - CACHED_SERIALIZERS.put(type.getRawType(), serializer); - return ret; - } - } - return null; - } + public static Object deserialize(GenericType type, Object value) { + Object ret; + for (Serializer serializer : SERIALIZERS) { + if ((ret = serializer.deserialize(type, value)) != null) { + CACHED_SERIALIZERS.put(type.getRawType(), serializer); + return ret; + } + } + return null; + } - public static Object serialize(Type type, Object obj) { - return serialize(new GenericType(type), obj); - } + public static Object serialize(Type type, Object obj) { + return serialize(new GenericType(type), obj); + } - public static Object serialize(GenericType type, Object obj) { - Serializer serializer = CACHED_SERIALIZERS.get(type.getRawType()); - if (serializer != null && serializer.isApplicableSerialize(type, obj)) { - return serializer.serialize(type, obj); - } else { - Object ret; - for (Serializer ser : SERIALIZERS) { - if ((ret = ser.serialize(type, obj)) != null) { - CACHED_SERIALIZERS.put(type.getRawType(), ser); - return ret; - } - } - } - return obj; - } + public static Object serialize(GenericType type, Object obj) { + Serializer serializer = CACHED_SERIALIZERS.get(type.getRawType()); + if (serializer != null && serializer.isApplicableSerialize(type, obj)) { + return serializer.serialize(type, obj); + } else { + Object ret; + for (Serializer ser : SERIALIZERS) { + if ((ret = ser.serialize(type, obj)) != null) { + CACHED_SERIALIZERS.put(type.getRawType(), ser); + return ret; + } + } + } + return obj; + } - public static void registerSerializer(Serializer serializer) { - SERIALIZERS.add(serializer); - } + public static void registerSerializer(Serializer serializer) { + SERIALIZERS.add(serializer); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/Serializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/Serializer.java index 0126328..3e408f2 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/Serializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/Serializer.java @@ -29,64 +29,64 @@ * Handles serializing and deserializing objects for use in annotated configurations. */ public abstract class Serializer { - private boolean allowsNullValue; + private boolean allowsNullValue; - public Object deserialize(GenericType type, Object value) { - if (value == null && !allowsNullValue()) { - return null; - } + public Object deserialize(GenericType type, Object value) { + if (value == null && !allowsNullValue()) { + return null; + } - if (isApplicableDeserialize(type, value) && (getParametersRequired() == -1 - || type.getGenerics().length == getParametersRequired())) { - return handleDeserialize(type, value); - } else { - return null; - } - } + if (isApplicableDeserialize(type, value) && (getParametersRequired() == -1 + || type.getGenerics().length == getParametersRequired())) { + return handleDeserialize(type, value); + } else { + return null; + } + } - public Object serialize(GenericType type, Object value) { - if (value == null && !allowsNullValue()) { - return null; - } + public Object serialize(GenericType type, Object value) { + if (value == null && !allowsNullValue()) { + return null; + } - if (isApplicableSerialize(type, value) && (getParametersRequired() == -1 - || type.getGenerics().length == getParametersRequired())) { - return handleSerialize(type, value); - } else { - return null; - } - } + if (isApplicableSerialize(type, value) && (getParametersRequired() == -1 + || type.getGenerics().length == getParametersRequired())) { + return handleSerialize(type, value); + } else { + return null; + } + } - protected abstract Object handleDeserialize(GenericType type, Object value); + protected abstract Object handleDeserialize(GenericType type, Object value); - protected Object handleSerialize(GenericType type, Object value) { - return value; - } + protected Object handleSerialize(GenericType type, Object value) { + return value; + } - public boolean isApplicableDeserialize(GenericType type, Object value) { - return isApplicable(type); - } + public boolean isApplicableDeserialize(GenericType type, Object value) { + return isApplicable(type); + } - public abstract boolean isApplicable(GenericType type); + public abstract boolean isApplicable(GenericType type); - public boolean isApplicableSerialize(GenericType type, Object value) { - return isApplicable(type); - } + public boolean isApplicableSerialize(GenericType type, Object value) { + return isApplicable(type); + } - protected abstract int getParametersRequired(); + protected abstract int getParametersRequired(); - public boolean allowsNullValue() { - return allowsNullValue; - } + public boolean allowsNullValue() { + return allowsNullValue; + } - protected void setAllowsNullValue(boolean allowsNullValue) { - this.allowsNullValue = allowsNullValue; - } + protected void setAllowsNullValue(boolean allowsNullValue) { + this.allowsNullValue = allowsNullValue; + } - public static class NeededGenericsComparator implements Comparator { - @Override - public int compare(Serializer a, Serializer b) { - return Integer.valueOf(a.getParametersRequired()).compareTo(b.getParametersRequired()); - } - } + public static class NeededGenericsComparator implements Comparator { + @Override + public int compare(Serializer a, Serializer b) { + return Integer.valueOf(a.getParametersRequired()).compareTo(b.getParametersRequired()); + } + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/SetSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/SetSerializer.java index 7f9cc02..d70b065 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/SetSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/SetSerializer.java @@ -30,38 +30,38 @@ import java.util.Set; public class SetSerializer extends Serializer { - @Override - public boolean isApplicable(GenericType type) { - return Set.class.equals(type.getMainType()); - } + @Override + public boolean isApplicable(GenericType type) { + return Set.class.equals(type.getMainType()); + } - @Override - public boolean isApplicableDeserialize(GenericType type, Object value) { - return super.isApplicableDeserialize(type, value) && value instanceof Collection; - } + @Override + public boolean isApplicableDeserialize(GenericType type, Object value) { + return super.isApplicableDeserialize(type, value) && value instanceof Collection; + } - @Override - public int getParametersRequired() { - return 1; - } + @Override + public int getParametersRequired() { + return 1; + } - @Override - protected Object handleDeserialize(GenericType type, Object value) { - Set values = new HashSet(); - Collection raw = (Collection) value; - for (Object obj : raw) { - values.add(Serialization.deserialize(type.getGenerics()[0], obj)); - } - return values; - } + @Override + protected Object handleDeserialize(GenericType type, Object value) { + Set values = new HashSet(); + Collection raw = (Collection) value; + for (Object obj : raw) { + values.add(Serialization.deserialize(type.getGenerics()[0], obj)); + } + return values; + } - @Override - protected Object handleSerialize(GenericType type, Object value) { - List values = new ArrayList(); - Collection raw = (Collection) value; - for (Object obj : raw) { - values.add(Serialization.serialize(type.getGenerics()[0], obj)); - } - return values; - } + @Override + protected Object handleSerialize(GenericType type, Object value) { + List values = new ArrayList(); + Collection raw = (Collection) value; + for (Object obj : raw) { + values.add(Serialization.serialize(type.getGenerics()[0], obj)); + } + return values; + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/serialization/StringSerializer.java b/src/main/java/com/flowpowered/cerealization/config/serialization/StringSerializer.java index 9cb63d0..2c077a7 100644 --- a/src/main/java/com/flowpowered/cerealization/config/serialization/StringSerializer.java +++ b/src/main/java/com/flowpowered/cerealization/config/serialization/StringSerializer.java @@ -24,18 +24,18 @@ package com.flowpowered.cerealization.config.serialization; public class StringSerializer extends Serializer { - @Override - public boolean isApplicable(GenericType type) { - return String.class.isAssignableFrom(type.getMainType()); - } + @Override + public boolean isApplicable(GenericType type) { + return String.class.isAssignableFrom(type.getMainType()); + } - @Override - public int getParametersRequired() { - return 0; - } + @Override + public int getParametersRequired() { + return 0; + } - @Override - protected Object handleDeserialize(GenericType type, Object value) { - return value.toString(); - } + @Override + protected Object handleDeserialize(GenericType type, Object value) { + return value.toString(); + } } diff --git a/src/main/java/com/flowpowered/cerealization/config/yaml/EmptyNullRepresenter.java b/src/main/java/com/flowpowered/cerealization/config/yaml/EmptyNullRepresenter.java index 44e4f16..273195e 100644 --- a/src/main/java/com/flowpowered/cerealization/config/yaml/EmptyNullRepresenter.java +++ b/src/main/java/com/flowpowered/cerealization/config/yaml/EmptyNullRepresenter.java @@ -52,39 +52,39 @@ * A custom representer that represents null values as empty text instead of {@code null} */ public class EmptyNullRepresenter extends Representer { - public EmptyNullRepresenter() { - super(); - nullRepresenter = new EmptyRepresentNull(); - } + public EmptyNullRepresenter() { + super(); + nullRepresenter = new EmptyRepresentNull(); + } - protected class EmptyRepresentNull implements Represent { - @Override - public Node representData(Object data) { - return representScalar(Tag.NULL, ""); // Changed "null" to "" so as to avoid writing nulls - } - } + protected class EmptyRepresentNull implements Represent { + @Override + public Node representData(Object data) { + return representScalar(Tag.NULL, ""); // Changed "null" to "" so as to avoid writing nulls + } + } - // Code borrowed from snakeyaml (http://code.google.com/p/snakeyaml/source/browse/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBeanTest.java) - @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) { - NodeTuple tuple = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); - Node valueNode = tuple.getValueNode(); - if (valueNode instanceof CollectionNode) { - // Removed null check - if (Tag.SEQ.equals(valueNode.getTag())) { - SequenceNode seq = (SequenceNode) valueNode; - if (seq.getValue().isEmpty()) { - return null; // skip empty lists - } - } - if (Tag.MAP.equals(valueNode.getTag())) { - MappingNode seq = (MappingNode) valueNode; - if (seq.getValue().isEmpty()) { - return null; // skip empty maps - } - } - } - return tuple; - } - // End of borrowed code + // Code borrowed from snakeyaml (http://code.google.com/p/snakeyaml/source/browse/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBeanTest.java) + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) { + NodeTuple tuple = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + Node valueNode = tuple.getValueNode(); + if (valueNode instanceof CollectionNode) { + // Removed null check + if (Tag.SEQ.equals(valueNode.getTag())) { + SequenceNode seq = (SequenceNode) valueNode; + if (seq.getValue().isEmpty()) { + return null; // skip empty lists + } + } + if (Tag.MAP.equals(valueNode.getTag())) { + MappingNode seq = (MappingNode) valueNode; + if (seq.getValue().isEmpty()) { + return null; // skip empty maps + } + } + } + return tuple; + } + // End of borrowed code } diff --git a/src/main/java/com/flowpowered/cerealization/config/yaml/YamlConfiguration.java b/src/main/java/com/flowpowered/cerealization/config/yaml/YamlConfiguration.java index 100bf05..5acb58a 100644 --- a/src/main/java/com/flowpowered/cerealization/config/yaml/YamlConfiguration.java +++ b/src/main/java/com/flowpowered/cerealization/config/yaml/YamlConfiguration.java @@ -53,191 +53,191 @@ * A configuration that loads from a YAML file */ public class YamlConfiguration extends MapBasedConfiguration implements FileConfiguration { - public static final String LINE_BREAK = DumperOptions.LineBreak.getPlatformLineBreak().getString(); - public static final char COMMENT_CHAR = '#'; - public static final Pattern COMMENT_REGEX = Pattern.compile(COMMENT_CHAR + " ?(.*)"); - private final IOFactory factory; - private final Yaml yaml; - private String[] header = null; - - public YamlConfiguration(java.io.File file) { - this(new IOFactory.File(file)); - } - - public YamlConfiguration(InputStream stream) { - this(new IOFactory.Stream(stream, null)); - } - - public YamlConfiguration(Reader reader) { - this(new IOFactory.Direct(reader, null)); - } - - public YamlConfiguration(String string) { - this(new IOFactory.String(string)); - } - - public YamlConfiguration() { - this((IOFactory) null); - } - - public YamlConfiguration(IOFactory factory) { - this.factory = factory; - DumperOptions options = new DumperOptions(); - - options.setIndent(4); - options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); - - yaml = new Yaml(new SafeConstructor(), new EmptyNullRepresenter(), options); - } - - @Override - protected Map loadToMap() throws ConfigurationException { - // Allow the usage of temporary empty YamlConfiguration objects. - if (factory == null) { - return Collections.emptyMap(); - } - BufferedReader in = null; - try { - in = new BufferedReader(getReader()); - List header = new ArrayList(); - boolean inHeader = true; - String str; - StringBuilder buffer = new StringBuilder(10000); - while ((str = in.readLine()) != null) { - if (inHeader) { - if (str.trim().startsWith("#")) { - header.add(str); - } else { - inHeader = false; - } - } - buffer.append(str.replaceAll("\t", " ")); - buffer.append(LINE_BREAK); - } - - if (header.size() > 0) { - setHeader(header.toArray(new String[header.size()])); - } - - Object val = yaml.load(new StringReader(buffer.toString())); - if (val instanceof Map) { - return (Map) val; - } - } catch (YAMLException e) { - throw new ConfigurationException(e); - } catch (FileNotFoundException ignore) { - } catch (IOException e) { - throw new ConfigurationException(e); - } finally { - try { - if (in != null) { - in.close(); - } - } catch (IOException ignore) { - } - } - return Collections.emptyMap(); - } - - @Override - protected void saveFromMap(Map map) throws ConfigurationException { - // Allow the usage of YamlConfiguration objects not created from a File. - if (factory == null) { - return; - } - BufferedWriter writer = null; - - try { - writer = new BufferedWriter(getWriter()); - if (getHeader() != null) { - for (String line : getHeader()) { - writer.append(COMMENT_CHAR).append(" ").append(line).append(LINE_BREAK); - } - - writer.append(LINE_BREAK); - } - - yaml.dump(map, writer); - } catch (YAMLException e) { - throw new ConfigurationException(e); - } catch (IOException e) { - throw new ConfigurationException(e); - } finally { - try { - if (writer != null) { - writer.flush(); - writer.close(); - } - } catch (IOException ignore) { - } - } - } - - public String getYamlString() throws ConfigurationException { - StringWriter writer = null; - - try { - writer = new StringWriter(); - if (getHeader() != null) { - for (String line : getHeader()) { - writer.append(COMMENT_CHAR).append(" ").append(line).append(LINE_BREAK); - } - - writer.append(LINE_BREAK); - } - - yaml.dump(getChildren(), writer); - return writer.toString(); - } catch (YAMLException e) { - throw new ConfigurationException(e); - } finally { - try { - if (writer != null) { - writer.flush(); - writer.close(); - } - } catch (IOException ignore) { - } - } - } - - public void setHeader(String... headerLines) { - if (headerLines.length == 1) { - headerLines = headerLines[0].split(LINE_BREAK); - } - String[] header = new String[headerLines.length]; - - for (int i = 0; i < headerLines.length; ++i) { - String line = headerLines[i]; - line = line.trim(); - Matcher matcher = COMMENT_REGEX.matcher(line); - if (matcher.find()) { - line = matcher.group(1).trim(); - } - header[i] = line; - } - - this.header = header; - } - - public String[] getHeader() { - return header; - } - - @Override - public java.io.File getFile() { - return factory instanceof IOFactory.File ? ((IOFactory.File) factory).getFile() : null; - } - - public IOFactory getIOFactory() { - return factory; - } - - protected Reader getReader() throws IOException { - return factory == null ? null : factory.createReader(); - } - - protected Writer getWriter() throws IOException { - return factory == null ? null : factory.createWriter(); - } + public static final String LINE_BREAK = DumperOptions.LineBreak.getPlatformLineBreak().getString(); + public static final char COMMENT_CHAR = '#'; + public static final Pattern COMMENT_REGEX = Pattern.compile(COMMENT_CHAR + " ?(.*)"); + private final IOFactory factory; + private final Yaml yaml; + private String[] header = null; + + public YamlConfiguration(java.io.File file) { + this(new IOFactory.File(file)); + } + + public YamlConfiguration(InputStream stream) { + this(new IOFactory.Stream(stream, null)); + } + + public YamlConfiguration(Reader reader) { + this(new IOFactory.Direct(reader, null)); + } + + public YamlConfiguration(String string) { + this(new IOFactory.String(string)); + } + + public YamlConfiguration() { + this((IOFactory) null); + } + + public YamlConfiguration(IOFactory factory) { + this.factory = factory; + DumperOptions options = new DumperOptions(); + + options.setIndent(4); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + + yaml = new Yaml(new SafeConstructor(), new EmptyNullRepresenter(), options); + } + + @Override + protected Map loadToMap() throws ConfigurationException { + // Allow the usage of temporary empty YamlConfiguration objects. + if (factory == null) { + return Collections.emptyMap(); + } + BufferedReader in = null; + try { + in = new BufferedReader(getReader()); + List header = new ArrayList(); + boolean inHeader = true; + String str; + StringBuilder buffer = new StringBuilder(10000); + while ((str = in.readLine()) != null) { + if (inHeader) { + if (str.trim().startsWith("#")) { + header.add(str); + } else { + inHeader = false; + } + } + buffer.append(str.replaceAll("\t", " ")); + buffer.append(LINE_BREAK); + } + + if (header.size() > 0) { + setHeader(header.toArray(new String[header.size()])); + } + + Object val = yaml.load(new StringReader(buffer.toString())); + if (val instanceof Map) { + return (Map) val; + } + } catch (YAMLException e) { + throw new ConfigurationException(e); + } catch (FileNotFoundException ignore) { + } catch (IOException e) { + throw new ConfigurationException(e); + } finally { + try { + if (in != null) { + in.close(); + } + } catch (IOException ignore) { + } + } + return Collections.emptyMap(); + } + + @Override + protected void saveFromMap(Map map) throws ConfigurationException { + // Allow the usage of YamlConfiguration objects not created from a File. + if (factory == null) { + return; + } + BufferedWriter writer = null; + + try { + writer = new BufferedWriter(getWriter()); + if (getHeader() != null) { + for (String line : getHeader()) { + writer.append(COMMENT_CHAR).append(" ").append(line).append(LINE_BREAK); + } + + writer.append(LINE_BREAK); + } + + yaml.dump(map, writer); + } catch (YAMLException e) { + throw new ConfigurationException(e); + } catch (IOException e) { + throw new ConfigurationException(e); + } finally { + try { + if (writer != null) { + writer.flush(); + writer.close(); + } + } catch (IOException ignore) { + } + } + } + + public String getYamlString() throws ConfigurationException { + StringWriter writer = null; + + try { + writer = new StringWriter(); + if (getHeader() != null) { + for (String line : getHeader()) { + writer.append(COMMENT_CHAR).append(" ").append(line).append(LINE_BREAK); + } + + writer.append(LINE_BREAK); + } + + yaml.dump(getChildren(), writer); + return writer.toString(); + } catch (YAMLException e) { + throw new ConfigurationException(e); + } finally { + try { + if (writer != null) { + writer.flush(); + writer.close(); + } + } catch (IOException ignore) { + } + } + } + + public void setHeader(String... headerLines) { + if (headerLines.length == 1) { + headerLines = headerLines[0].split(LINE_BREAK); + } + String[] header = new String[headerLines.length]; + + for (int i = 0; i < headerLines.length; ++i) { + String line = headerLines[i]; + line = line.trim(); + Matcher matcher = COMMENT_REGEX.matcher(line); + if (matcher.find()) { + line = matcher.group(1).trim(); + } + header[i] = line; + } + + this.header = header; + } + + public String[] getHeader() { + return header; + } + + @Override + public java.io.File getFile() { + return factory instanceof IOFactory.File ? ((IOFactory.File) factory).getFile() : null; + } + + public IOFactory getIOFactory() { + return factory; + } + + protected Reader getReader() throws IOException { + return factory == null ? null : factory.createReader(); + } + + protected Writer getWriter() throws IOException { + return factory == null ? null : factory.createWriter(); + } } diff --git a/src/main/java/com/flowpowered/cerealization/data/IOFactory.java b/src/main/java/com/flowpowered/cerealization/data/IOFactory.java index 1fc4fb9..1110367 100644 --- a/src/main/java/com/flowpowered/cerealization/data/IOFactory.java +++ b/src/main/java/com/flowpowered/cerealization/data/IOFactory.java @@ -40,122 +40,122 @@ * A factory for creating IO objects from a source */ public interface IOFactory { - public static final Charset UTF_8_CHARSET = Charset.forName("UTF-8"); - - public Reader createReader() throws IOException; - - public Writer createWriter() throws IOException; - - /** - * This factory should only be used when you know where a config is going to be read from or written to. - */ - public static class Direct implements IOFactory { - private final Reader reader; - private final Writer writer; - - public Direct(Reader reader, Writer writer) { - this.reader = reader; - this.writer = writer; - } - - public Reader createReader() throws IOException { - return reader; - } - - public Writer createWriter() throws IOException { - return writer; - } - } - - public static class File implements IOFactory { - private final java.io.File file; - - public File(java.io.File file) { - this.file = file; - } - - public java.io.File getFile() { - return file; - } - - private void createFile() throws IOException { - if (file != null && !file.exists()) { - if (file.getParentFile() != null) { - file.getParentFile().mkdirs(); - } - file.createNewFile(); - } - } - - public Reader createReader() throws IOException { - createFile(); - return new InputStreamReader(new FileInputStream(file), UTF_8_CHARSET); - } - - public Writer createWriter() throws IOException { - createFile(); - return new OutputStreamWriter(new FileOutputStream(file), UTF_8_CHARSET); - } - } - - public static class Stream implements IOFactory { - private final InputStream input; - private final OutputStream output; - - /** - * An IO factory that creates Readers from existing streams. Either of the parameters may be null, but not both. - * - * @param input The input stream - * @param output The output stream. - */ - public Stream(InputStream input, OutputStream output) { - this.input = input; - this.output = output; - } - - public Reader createReader() throws IOException { - return new InputStreamReader(input, UTF_8_CHARSET); - } - - public Writer createWriter() throws IOException { - return new OutputStreamWriter(output, UTF_8_CHARSET); - } - } - - public static class String implements IOFactory { - private StringBuffer buffer; - - public String(StringBuilder buffer) { - this.buffer = new StringBuffer(buffer); - } - - public String(StringBuffer buffer) { - this.buffer = buffer; - } - - public String(java.lang.String s) { - this.buffer = new StringBuffer(s == null ? "" : s); - } - - public String() { - } - - public void setData(java.lang.String value) { - this.buffer = new StringBuffer(value); - } - - public StringBuffer getBuffer() { - return buffer; - } - - public Reader createReader() throws IOException { - return buffer == null ? new StringReader("") : new StringReader(buffer.toString()); - } - - public Writer createWriter() throws IOException { - StringWriter w = new StringWriter(); - this.buffer = w.getBuffer(); - return w; - } - } + public static final Charset UTF_8_CHARSET = Charset.forName("UTF-8"); + + public Reader createReader() throws IOException; + + public Writer createWriter() throws IOException; + + /** + * This factory should only be used when you know where a config is going to be read from or written to. + */ + public static class Direct implements IOFactory { + private final Reader reader; + private final Writer writer; + + public Direct(Reader reader, Writer writer) { + this.reader = reader; + this.writer = writer; + } + + public Reader createReader() throws IOException { + return reader; + } + + public Writer createWriter() throws IOException { + return writer; + } + } + + public static class File implements IOFactory { + private final java.io.File file; + + public File(java.io.File file) { + this.file = file; + } + + public java.io.File getFile() { + return file; + } + + private void createFile() throws IOException { + if (file != null && !file.exists()) { + if (file.getParentFile() != null) { + file.getParentFile().mkdirs(); + } + file.createNewFile(); + } + } + + public Reader createReader() throws IOException { + createFile(); + return new InputStreamReader(new FileInputStream(file), UTF_8_CHARSET); + } + + public Writer createWriter() throws IOException { + createFile(); + return new OutputStreamWriter(new FileOutputStream(file), UTF_8_CHARSET); + } + } + + public static class Stream implements IOFactory { + private final InputStream input; + private final OutputStream output; + + /** + * An IO factory that creates Readers from existing streams. Either of the parameters may be null, but not both. + * + * @param input The input stream + * @param output The output stream. + */ + public Stream(InputStream input, OutputStream output) { + this.input = input; + this.output = output; + } + + public Reader createReader() throws IOException { + return new InputStreamReader(input, UTF_8_CHARSET); + } + + public Writer createWriter() throws IOException { + return new OutputStreamWriter(output, UTF_8_CHARSET); + } + } + + public static class String implements IOFactory { + private StringBuffer buffer; + + public String(StringBuilder buffer) { + this.buffer = new StringBuffer(buffer); + } + + public String(StringBuffer buffer) { + this.buffer = buffer; + } + + public String(java.lang.String s) { + this.buffer = new StringBuffer(s == null ? "" : s); + } + + public String() { + } + + public void setData(java.lang.String value) { + this.buffer = new StringBuffer(value); + } + + public StringBuffer getBuffer() { + return buffer; + } + + public Reader createReader() throws IOException { + return buffer == null ? new StringReader("") : new StringReader(buffer.toString()); + } + + public Writer createWriter() throws IOException { + StringWriter w = new StringWriter(); + this.buffer = w.getBuffer(); + return w; + } + } } diff --git a/src/main/java/com/flowpowered/cerealization/data/ValueHolder.java b/src/main/java/com/flowpowered/cerealization/data/ValueHolder.java index ff87261..17bc567 100644 --- a/src/main/java/com/flowpowered/cerealization/data/ValueHolder.java +++ b/src/main/java/com/flowpowered/cerealization/data/ValueHolder.java @@ -30,343 +30,343 @@ import java.util.List; public interface ValueHolder { - /** - * Return this node's value as a boolean - * - * @return the boolean value - * @see #getBoolean(boolean) - * @see #getValue() - */ - public boolean getBoolean(); - - /** - * Return this node's value as a boolean - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a boolean - * @return the boolean value - * @see #getValue(Object) - */ - public boolean getBoolean(boolean def); - - /** - * Return this node's value as a byte - * - * @return the byte value - * @see #getByte(byte) - * @see #getValue() - */ - public byte getByte(); - - /** - * Return this value as a byte - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a byte - * @return the byte value - * @see #getValue(Object) - */ - public byte getByte(byte def); - - /** - * Return this node's value as a float - * - * @return the float value - * @see #getFloat(float) - * @see #getValue() - */ - public float getFloat(); - - /** - * Return this value as a float - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a float - * @return the float value - * @see #getValue(Object) - */ - public float getFloat(float def); - - /** - * Return this node's value as a short - * - * @return the short value - * @see #getShort(short) - * @see #getValue() - */ - public short getShort(); - - /** - * Return this value as a short - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a short - * @return the short value - * @see #getValue(Object) - */ - public short getShort(short def); - - /** - * Return this node's value as an integer - * - * @return the integer value - * @see #getInt(int) - * @see #getValue() - */ - public int getInt(); - - /** - * Return this value as an integer - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't an integer - * @return the integer value - * @see #getValue(Object) - */ - public int getInt(int def); - - /** - * Return this node's value as a long - * - * @return the long value - * @see #getLong(long) - * @see #getValue() - */ - public long getLong(); - - /** - * Return this node's value as a long - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a long - * @return the long value - * @see #getValue(Object) - */ - public long getLong(long def); - - /** - * Return this node's value as a double - * - * @return the double value - * @see #getDouble(double) - * @see #getValue() - */ - public double getDouble(); - - /** - * Return this node's value as a double - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a double - * @return the double value - * @see #getValue(Object) - */ - public double getDouble(double def); - - /** - * Return this node's value as a BigInteger - * - * @return the BigInteger value - * @see #getBigInt(BigInteger) - * @see #getValue() - */ - public BigInteger getBigInt(); - - /** - * Return this node's value as a BigInteger - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a BigInteger - * @return the BigInteger value - * @see #getValue() - */ - public BigInteger getBigInt(BigInteger def); - - /** - * Return this node's value as a BigDecimal - * - * @return the BigDecimal value - * @see #getDecimal(BigDecimal) - * @see #getValue() - */ - public BigDecimal getDecimal(); - - /** - * Return this node's value as a BigDecimal - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a BigDecimal - * @return the BigDecimal value - * @see #getValue() - */ - public BigDecimal getDecimal(BigDecimal def); - - /** - * Return this node's value as a Date - * - * @return the Date value - * @see #getDate(Date) - * @see #getValue(Object) - */ - public Date getDate(); - - /** - * Return this node's value as a Date - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a Date - * @return the Date value - * @see #getValue(Object) - */ - public Date getDate(Date def); - - /** - * Return this node's value as a String - * - * @return the String value - * @see #getString(String) - * @see #getValue() - */ - public String getString(); - - /** - * Return this node's value as a String - * - * @param def The default value, returned if this node doesn't have a set value - * @return the String value - * @see #getValue(Object) - */ - public String getString(String def); - - /** - * Return this node's value as a byte array - * - * @return the byte array value - * @see #getBytes(byte[]) - * @see #getValue() - */ - public byte[] getBytes(); - - /** - * Return this node's value as a byte array - * - * @param def The default value, returned if this node doesn't have a set value - * @return the byte array value - * @see #getValue() - */ - public byte[] getBytes(byte[] def); - - /** - * Return this node's value - * - * @return the value - * @see #getValue(Object) - */ - public Object getValue(); - - /** - * Return this node's value - * - * @param def The default value, returned if this node doesn't have a set value - * @return the value - */ - public abstract Object getValue(Object def); - - /** - * Return this node's value as the given type - * - * @param The type to get as - * @param type The type to get as and check for - * @return the value as the give type, or null if the value is not present or not of the given type - * @see #getTypedValue(Class, Object) - * @see #getValue() - */ - public T getTypedValue(Class type); - - /** - * Return this node's value as the given type - * - * @param The type to get as - * @param type The type to get as and check for - * @param def The value to use as default - * @return the value as the give type, or {@code def} if the value is not present or not of the given type - * @see #getValue(Object) - */ - public T getTypedValue(Class type, T def); - - /** - * Return this node's value as the given type - * - * @param type The type to get as and check for - * @return the value as the give type, or null if the value is not present or not of the given type - * @see #getTypedValue(Class, Object) - * @see #getValue() - */ - public Object getTypedValue(Type type); - - /** - * Return this node's value as the given type - * - * @param type The type to get as and check for - * @param def The value to use as default - * @return the value as the give type, or {@code def} if the value is not present or not of the given type - * @see #getValue(Object) - */ - public Object getTypedValue(Type type, Object def); - - /** - * Return this node's value as a list - * - * @return the list value - * @see #getList(java.util.List) - * @see #getValue() - */ - public List getList(); - - /** - * Return this node's value as a list - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a boolean. If this is null it will act as an empty list. - * @return the List value - * @see #getValue(Object) - */ - public abstract List getList(List def); - - /** - * Return this node's value as a string list. Note that this will not necessarily return the same collection that is in this configuration's value. This means that changes to the return value of this - * method might not affect the configuration, so after changes the value of this node should be set to this list. - * - * @return the string list value - * @see #getStringList(java.util.List) - * @see #getValue() - */ - public List getStringList(); - - /** - * Return this node's value as a string list. Note that this will not necessarily return the same collection that is in this configuration's value. This means that changes to the return value of this - * method might not affect the configuration, so after changes the value of this node should be set to this list. - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a boolean. If this is null it will act as an empty list. - * @return the string list value - * @see #getValue(Object) - */ - public abstract List getStringList(List def); - - /** - * Return this node's value as an integer list. Note that this will not necessarily return the same collection that is in this configuration's value. This means that changes to the return value of - * this method might not affect the configuration, so after changes the value of this node should be set to this list. - * - * @return the integer list value - * @see #getStringList(java.util.List) - * @see #getValue() - */ - public List getIntegerList(); - - /** - * Return this node's value as a string list. Note that this will not necessarily return the same collection that is in this value. This means that changes to the return value of this method might - * not affect the value, so after changes the value of this node should be set to this list. - * - * @param def The default value, returned if this node doesn't have a set value or the value isn't a boolean. If this is null it will act as an empty list. - * @return the string list value - * @see #getValue(Object) - */ - public abstract List getIntegerList(List def); - - public List getDoubleList(); - - public abstract List getDoubleList(List def); - - public List getBooleanList(); - - public abstract List getBooleanList(List def); + /** + * Return this node's value as a boolean + * + * @return the boolean value + * @see #getBoolean(boolean) + * @see #getValue() + */ + public boolean getBoolean(); + + /** + * Return this node's value as a boolean + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a boolean + * @return the boolean value + * @see #getValue(Object) + */ + public boolean getBoolean(boolean def); + + /** + * Return this node's value as a byte + * + * @return the byte value + * @see #getByte(byte) + * @see #getValue() + */ + public byte getByte(); + + /** + * Return this value as a byte + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a byte + * @return the byte value + * @see #getValue(Object) + */ + public byte getByte(byte def); + + /** + * Return this node's value as a float + * + * @return the float value + * @see #getFloat(float) + * @see #getValue() + */ + public float getFloat(); + + /** + * Return this value as a float + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a float + * @return the float value + * @see #getValue(Object) + */ + public float getFloat(float def); + + /** + * Return this node's value as a short + * + * @return the short value + * @see #getShort(short) + * @see #getValue() + */ + public short getShort(); + + /** + * Return this value as a short + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a short + * @return the short value + * @see #getValue(Object) + */ + public short getShort(short def); + + /** + * Return this node's value as an integer + * + * @return the integer value + * @see #getInt(int) + * @see #getValue() + */ + public int getInt(); + + /** + * Return this value as an integer + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't an integer + * @return the integer value + * @see #getValue(Object) + */ + public int getInt(int def); + + /** + * Return this node's value as a long + * + * @return the long value + * @see #getLong(long) + * @see #getValue() + */ + public long getLong(); + + /** + * Return this node's value as a long + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a long + * @return the long value + * @see #getValue(Object) + */ + public long getLong(long def); + + /** + * Return this node's value as a double + * + * @return the double value + * @see #getDouble(double) + * @see #getValue() + */ + public double getDouble(); + + /** + * Return this node's value as a double + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a double + * @return the double value + * @see #getValue(Object) + */ + public double getDouble(double def); + + /** + * Return this node's value as a BigInteger + * + * @return the BigInteger value + * @see #getBigInt(BigInteger) + * @see #getValue() + */ + public BigInteger getBigInt(); + + /** + * Return this node's value as a BigInteger + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a BigInteger + * @return the BigInteger value + * @see #getValue() + */ + public BigInteger getBigInt(BigInteger def); + + /** + * Return this node's value as a BigDecimal + * + * @return the BigDecimal value + * @see #getDecimal(BigDecimal) + * @see #getValue() + */ + public BigDecimal getDecimal(); + + /** + * Return this node's value as a BigDecimal + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a BigDecimal + * @return the BigDecimal value + * @see #getValue() + */ + public BigDecimal getDecimal(BigDecimal def); + + /** + * Return this node's value as a Date + * + * @return the Date value + * @see #getDate(Date) + * @see #getValue(Object) + */ + public Date getDate(); + + /** + * Return this node's value as a Date + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a Date + * @return the Date value + * @see #getValue(Object) + */ + public Date getDate(Date def); + + /** + * Return this node's value as a String + * + * @return the String value + * @see #getString(String) + * @see #getValue() + */ + public String getString(); + + /** + * Return this node's value as a String + * + * @param def The default value, returned if this node doesn't have a set value + * @return the String value + * @see #getValue(Object) + */ + public String getString(String def); + + /** + * Return this node's value as a byte array + * + * @return the byte array value + * @see #getBytes(byte[]) + * @see #getValue() + */ + public byte[] getBytes(); + + /** + * Return this node's value as a byte array + * + * @param def The default value, returned if this node doesn't have a set value + * @return the byte array value + * @see #getValue() + */ + public byte[] getBytes(byte[] def); + + /** + * Return this node's value + * + * @return the value + * @see #getValue(Object) + */ + public Object getValue(); + + /** + * Return this node's value + * + * @param def The default value, returned if this node doesn't have a set value + * @return the value + */ + public abstract Object getValue(Object def); + + /** + * Return this node's value as the given type + * + * @param The type to get as + * @param type The type to get as and check for + * @return the value as the give type, or null if the value is not present or not of the given type + * @see #getTypedValue(Class, Object) + * @see #getValue() + */ + public T getTypedValue(Class type); + + /** + * Return this node's value as the given type + * + * @param The type to get as + * @param type The type to get as and check for + * @param def The value to use as default + * @return the value as the give type, or {@code def} if the value is not present or not of the given type + * @see #getValue(Object) + */ + public T getTypedValue(Class type, T def); + + /** + * Return this node's value as the given type + * + * @param type The type to get as and check for + * @return the value as the give type, or null if the value is not present or not of the given type + * @see #getTypedValue(Class, Object) + * @see #getValue() + */ + public Object getTypedValue(Type type); + + /** + * Return this node's value as the given type + * + * @param type The type to get as and check for + * @param def The value to use as default + * @return the value as the give type, or {@code def} if the value is not present or not of the given type + * @see #getValue(Object) + */ + public Object getTypedValue(Type type, Object def); + + /** + * Return this node's value as a list + * + * @return the list value + * @see #getList(java.util.List) + * @see #getValue() + */ + public List getList(); + + /** + * Return this node's value as a list + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a boolean. If this is null it will act as an empty list. + * @return the List value + * @see #getValue(Object) + */ + public abstract List getList(List def); + + /** + * Return this node's value as a string list. Note that this will not necessarily return the same collection that is in this configuration's value. This means that changes to the return value of this + * method might not affect the configuration, so after changes the value of this node should be set to this list. + * + * @return the string list value + * @see #getStringList(java.util.List) + * @see #getValue() + */ + public List getStringList(); + + /** + * Return this node's value as a string list. Note that this will not necessarily return the same collection that is in this configuration's value. This means that changes to the return value of this + * method might not affect the configuration, so after changes the value of this node should be set to this list. + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a boolean. If this is null it will act as an empty list. + * @return the string list value + * @see #getValue(Object) + */ + public abstract List getStringList(List def); + + /** + * Return this node's value as an integer list. Note that this will not necessarily return the same collection that is in this configuration's value. This means that changes to the return value of + * this method might not affect the configuration, so after changes the value of this node should be set to this list. + * + * @return the integer list value + * @see #getStringList(java.util.List) + * @see #getValue() + */ + public List getIntegerList(); + + /** + * Return this node's value as a string list. Note that this will not necessarily return the same collection that is in this value. This means that changes to the return value of this method might + * not affect the value, so after changes the value of this node should be set to this list. + * + * @param def The default value, returned if this node doesn't have a set value or the value isn't a boolean. If this is null it will act as an empty list. + * @return the string list value + * @see #getValue(Object) + */ + public abstract List getIntegerList(List def); + + public List getDoubleList(); + + public abstract List getDoubleList(List def); + + public List getBooleanList(); + + public abstract List getBooleanList(List def); } diff --git a/src/main/java/com/flowpowered/cerealization/data/ValueHolderBase.java b/src/main/java/com/flowpowered/cerealization/data/ValueHolderBase.java index 4e08c46..9419927 100644 --- a/src/main/java/com/flowpowered/cerealization/data/ValueHolderBase.java +++ b/src/main/java/com/flowpowered/cerealization/data/ValueHolderBase.java @@ -36,291 +36,291 @@ import com.flowpowered.cerealization.config.serialization.Serialization; public class ValueHolderBase implements ValueHolder { - private final ValueHolder actualValue; - - public ValueHolderBase() { - this(null); - } - - public ValueHolderBase(ValueHolder actualValue) { - this.actualValue = actualValue; - } - - @Override - public boolean getBoolean() { - return getBoolean(false); - } - - @Override - public boolean getBoolean(boolean def) { - final Boolean val = CastUtils.castBoolean(getValue(def)); - return val == null ? def : val; - } - - @Override - public byte getByte() { - return getByte((byte) 0); - } - - @Override - public byte getByte(byte def) { - final Byte val = CastUtils.castByte(getValue(def)); - return val == null ? def : val; - } - - @Override - public float getFloat() { - return getFloat(0f); - } - - @Override - public float getFloat(float def) { - final Float val = CastUtils.castFloat(getValue(def)); - return val == null ? def : val; - } - - @Override - public short getShort() { - return getShort((short) 0); - } - - @Override - public short getShort(short def) { - final Short val = CastUtils.castShort(getValue(def)); - return val == null ? def : val; - } - - @Override - public int getInt() { - return getInt(0); - } - - @Override - public int getInt(int def) { - final Integer val = CastUtils.castInt(getValue(def)); - return val == null ? def : val; - } - - @Override - public long getLong() { - return getLong(0); - } - - @Override - public long getLong(long def) { - final Long val = CastUtils.castLong(getValue(def)); - return val == null ? def : val; - } - - @Override - public double getDouble() { - return getDouble(0); - } - - @Override - public double getDouble(double def) { - final Double val = CastUtils.castDouble(getValue(def)); - return val == null ? def : val; - } - - @Override - public BigInteger getBigInt() { - return getBigInt(null); - } - - @Override - public BigInteger getBigInt(BigInteger def) { - final BigInteger val = CastUtils.castBigInt(getValue(def)); - return val == null ? def : val; - } - - @Override - public BigDecimal getDecimal() { - return getDecimal(null); - } - - @Override - public BigDecimal getDecimal(BigDecimal def) { - final BigDecimal val = CastUtils.castBigDecimal(getValue(def)); - return val == null ? def : val; - } - - @Override - public Date getDate() { - return getDate(null); - } - - @Override - public Date getDate(Date def) { - final Date val = CastUtils.castDate(getValue(def)); - return val == null ? def : val; - } - - @Override - public byte[] getBytes() { - return getBytes(null); - } - - @Override - public byte[] getBytes(byte[] def) { - final Object val = getValue(def); - if (val == null) { - return def; - } - final byte[] bytes = CastUtils.castBytes(val); - return bytes == null ? val.toString().getBytes() : bytes; - } - - @Override - public String getString() { - return getString(null); - } - - @Override - public String getString(String def) { - final Object val = getValue(def); - return val == null ? def : val.toString(); - } - - @Override - public Object getValue() { - if (actualValue == null) { - throw new UnsupportedOperationException("ValueHolderBase must have a reference to another ValueHolder or override getValue"); - } - return actualValue.getValue(); - } - - @Override - public Object getValue(Object def) { - if (actualValue == null) { - throw new UnsupportedOperationException("ValueHolderBase must have a reference to another ValueHolder or override getValue"); - } - return actualValue.getValue(def); - } - - @Override - public T getTypedValue(Class type) { - return getTypedValue(type, null); - } - - @Override - public T getTypedValue(Class type, T def) { - final Object val = Serialization.deserialize(type, getValue()); - return type.isInstance(val) ? type.cast(val) : def; - } - - @Override - public Object getTypedValue(Type type) { - return getTypedValue(type, null); - } - - @Override - public Object getTypedValue(Type type, Object def) { - Object val = Serialization.deserialize(type, getValue()); - if (val == null) { - val = def; - } - return val; - } - - @Override - public List getList() { - return getList(null); - } - - @Override - public List getList(List def) { - Object val = getValue(); - if (val instanceof List) { - return (List) val; - } else if (val instanceof Collection) { - return new ArrayList((Collection) val); - } else { - return def == null ? Collections.emptyList() : def; - } - } - - @Override - public List getStringList() { - return getStringList(null); - } - - @Override - public List getStringList(List def) { - List val = getList(def); - List ret = new ArrayList(); - for (Object item : val) { - ret.add(item == null ? null : item.toString()); - } - return ret; - } - - @Override - public List getIntegerList() { - return getIntegerList(null); - } - - @Override - public List getIntegerList(List def) { - List val = getList(def); - List ret = new ArrayList(); - for (Object item : val) { - Integer asInt = CastUtils.castInt(item); - if (asInt == null) { - return def == null ? Collections.emptyList() : def; - } - ret.add(asInt); - } - return ret; - } - - @Override - public List getDoubleList() { - return getDoubleList(null); - } - - @Override - public List getDoubleList(List def) { - List val = getList(def); - List ret = new ArrayList(); - for (Object item : val) { - Double asDouble = CastUtils.castDouble(item); - if (asDouble == null) { - return def == null ? Collections.emptyList() : def; - } - ret.add(asDouble); - } - return ret; - } - - @Override - public List getBooleanList() { - return getBooleanList(null); - } - - @Override - public List getBooleanList(List def) { - List val = getList(def); - List ret = new ArrayList(); - for (Object item : val) { - Boolean asBoolean = CastUtils.castBoolean(item); - if (asBoolean == null) { - return def == null ? Collections.emptyList() : def; - } - ret.add(asBoolean); - } - return ret; - } - - public static class NullHolder extends ValueHolderBase { - @Override - public Object getValue() { - return null; - } - - @Override - public Object getValue(Object def) { - return def; - } - } + private final ValueHolder actualValue; + + public ValueHolderBase() { + this(null); + } + + public ValueHolderBase(ValueHolder actualValue) { + this.actualValue = actualValue; + } + + @Override + public boolean getBoolean() { + return getBoolean(false); + } + + @Override + public boolean getBoolean(boolean def) { + final Boolean val = CastUtils.castBoolean(getValue(def)); + return val == null ? def : val; + } + + @Override + public byte getByte() { + return getByte((byte) 0); + } + + @Override + public byte getByte(byte def) { + final Byte val = CastUtils.castByte(getValue(def)); + return val == null ? def : val; + } + + @Override + public float getFloat() { + return getFloat(0f); + } + + @Override + public float getFloat(float def) { + final Float val = CastUtils.castFloat(getValue(def)); + return val == null ? def : val; + } + + @Override + public short getShort() { + return getShort((short) 0); + } + + @Override + public short getShort(short def) { + final Short val = CastUtils.castShort(getValue(def)); + return val == null ? def : val; + } + + @Override + public int getInt() { + return getInt(0); + } + + @Override + public int getInt(int def) { + final Integer val = CastUtils.castInt(getValue(def)); + return val == null ? def : val; + } + + @Override + public long getLong() { + return getLong(0); + } + + @Override + public long getLong(long def) { + final Long val = CastUtils.castLong(getValue(def)); + return val == null ? def : val; + } + + @Override + public double getDouble() { + return getDouble(0); + } + + @Override + public double getDouble(double def) { + final Double val = CastUtils.castDouble(getValue(def)); + return val == null ? def : val; + } + + @Override + public BigInteger getBigInt() { + return getBigInt(null); + } + + @Override + public BigInteger getBigInt(BigInteger def) { + final BigInteger val = CastUtils.castBigInt(getValue(def)); + return val == null ? def : val; + } + + @Override + public BigDecimal getDecimal() { + return getDecimal(null); + } + + @Override + public BigDecimal getDecimal(BigDecimal def) { + final BigDecimal val = CastUtils.castBigDecimal(getValue(def)); + return val == null ? def : val; + } + + @Override + public Date getDate() { + return getDate(null); + } + + @Override + public Date getDate(Date def) { + final Date val = CastUtils.castDate(getValue(def)); + return val == null ? def : val; + } + + @Override + public byte[] getBytes() { + return getBytes(null); + } + + @Override + public byte[] getBytes(byte[] def) { + final Object val = getValue(def); + if (val == null) { + return def; + } + final byte[] bytes = CastUtils.castBytes(val); + return bytes == null ? val.toString().getBytes() : bytes; + } + + @Override + public String getString() { + return getString(null); + } + + @Override + public String getString(String def) { + final Object val = getValue(def); + return val == null ? def : val.toString(); + } + + @Override + public Object getValue() { + if (actualValue == null) { + throw new UnsupportedOperationException("ValueHolderBase must have a reference to another ValueHolder or override getValue"); + } + return actualValue.getValue(); + } + + @Override + public Object getValue(Object def) { + if (actualValue == null) { + throw new UnsupportedOperationException("ValueHolderBase must have a reference to another ValueHolder or override getValue"); + } + return actualValue.getValue(def); + } + + @Override + public T getTypedValue(Class type) { + return getTypedValue(type, null); + } + + @Override + public T getTypedValue(Class type, T def) { + final Object val = Serialization.deserialize(type, getValue()); + return type.isInstance(val) ? type.cast(val) : def; + } + + @Override + public Object getTypedValue(Type type) { + return getTypedValue(type, null); + } + + @Override + public Object getTypedValue(Type type, Object def) { + Object val = Serialization.deserialize(type, getValue()); + if (val == null) { + val = def; + } + return val; + } + + @Override + public List getList() { + return getList(null); + } + + @Override + public List getList(List def) { + Object val = getValue(); + if (val instanceof List) { + return (List) val; + } else if (val instanceof Collection) { + return new ArrayList((Collection) val); + } else { + return def == null ? Collections.emptyList() : def; + } + } + + @Override + public List getStringList() { + return getStringList(null); + } + + @Override + public List getStringList(List def) { + List val = getList(def); + List ret = new ArrayList(); + for (Object item : val) { + ret.add(item == null ? null : item.toString()); + } + return ret; + } + + @Override + public List getIntegerList() { + return getIntegerList(null); + } + + @Override + public List getIntegerList(List def) { + List val = getList(def); + List ret = new ArrayList(); + for (Object item : val) { + Integer asInt = CastUtils.castInt(item); + if (asInt == null) { + return def == null ? Collections.emptyList() : def; + } + ret.add(asInt); + } + return ret; + } + + @Override + public List getDoubleList() { + return getDoubleList(null); + } + + @Override + public List getDoubleList(List def) { + List val = getList(def); + List ret = new ArrayList(); + for (Object item : val) { + Double asDouble = CastUtils.castDouble(item); + if (asDouble == null) { + return def == null ? Collections.emptyList() : def; + } + ret.add(asDouble); + } + return ret; + } + + @Override + public List getBooleanList() { + return getBooleanList(null); + } + + @Override + public List getBooleanList(List def) { + List val = getList(def); + List ret = new ArrayList(); + for (Object item : val) { + Boolean asBoolean = CastUtils.castBoolean(item); + if (asBoolean == null) { + return def == null ? Collections.emptyList() : def; + } + ret.add(asBoolean); + } + return ret; + } + + public static class NullHolder extends ValueHolderBase { + @Override + public Object getValue() { + return null; + } + + @Override + public Object getValue(Object def) { + return def; + } + } } diff --git a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationHolderConfigurationTest.java b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationHolderConfigurationTest.java index 0248db3..90fe0f4 100644 --- a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationHolderConfigurationTest.java +++ b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationHolderConfigurationTest.java @@ -34,30 +34,30 @@ import static org.junit.Assert.assertEquals; public class ConfigurationHolderConfigurationTest { - private static class TestConfig extends ConfigurationHolderConfiguration { - public static final int TEST_ONE_VALUE = 42; - public static final ConfigurationHolder TEST_ONE = new ConfigurationHolder(TEST_ONE_VALUE, "test", "one"); - public static final String TEST_TWO_VALUE = "richard"; - public static final ConfigurationHolder TEST_TWO = new ConfigurationHolder(TEST_TWO_VALUE, "test", "two"); + private static class TestConfig extends ConfigurationHolderConfiguration { + public static final int TEST_ONE_VALUE = 42; + public static final ConfigurationHolder TEST_ONE = new ConfigurationHolder(TEST_ONE_VALUE, "test", "one"); + public static final String TEST_TWO_VALUE = "richard"; + public static final ConfigurationHolder TEST_TWO = new ConfigurationHolder(TEST_TWO_VALUE, "test", "two"); - public TestConfig(Configuration base) { - super(base); - } - } + public TestConfig(Configuration base) { + super(base); + } + } - @Test - public void testConfigSet() throws ConfigurationException { - TestConfig testConfig = new TestConfig(new MapConfiguration()); - testConfig.load(); - assertEquals(testConfig.getConfiguration(), TestConfig.TEST_ONE.getConfiguration()); - assertEquals(testConfig.getConfiguration(), TestConfig.TEST_TWO.getConfiguration()); - } + @Test + public void testConfigSet() throws ConfigurationException { + TestConfig testConfig = new TestConfig(new MapConfiguration()); + testConfig.load(); + assertEquals(testConfig.getConfiguration(), TestConfig.TEST_ONE.getConfiguration()); + assertEquals(testConfig.getConfiguration(), TestConfig.TEST_TWO.getConfiguration()); + } - @Test - public void testSetDefaultValues() throws ConfigurationException { - TestConfig testConfig = new TestConfig(new MapConfiguration()); - testConfig.load(); - assertEquals(TestConfig.TEST_ONE_VALUE, testConfig.getConfiguration().getNode(TestConfig.TEST_ONE.getPathElements()).getValue()); - assertEquals(TestConfig.TEST_TWO_VALUE, testConfig.getConfiguration().getNode(TestConfig.TEST_TWO.getPathElements()).getValue()); - } + @Test + public void testSetDefaultValues() throws ConfigurationException { + TestConfig testConfig = new TestConfig(new MapConfiguration()); + testConfig.load(); + assertEquals(TestConfig.TEST_ONE_VALUE, testConfig.getConfiguration().getNode(TestConfig.TEST_ONE.getPathElements()).getValue()); + assertEquals(TestConfig.TEST_TWO_VALUE, testConfig.getConfiguration().getNode(TestConfig.TEST_TWO.getPathElements()).getValue()); + } } diff --git a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationHolderTest.java b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationHolderTest.java index 7cdc0f9..42b09dc 100644 --- a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationHolderTest.java +++ b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationHolderTest.java @@ -32,26 +32,26 @@ import static org.junit.Assert.assertEquals; public class ConfigurationHolderTest { - @Test - public void testGetWithDefaultValue() { - Configuration config = new MapConfiguration(); - ConfigurationHolder subject = new ConfigurationHolder(config, (Object) "hello", "unknown", "path"); - assertEquals("hello", subject.getString()); - } + @Test + public void testGetWithDefaultValue() { + Configuration config = new MapConfiguration(); + ConfigurationHolder subject = new ConfigurationHolder(config, (Object) "hello", "unknown", "path"); + assertEquals("hello", subject.getString()); + } - @Test - public void testGetExistingValue() { - Configuration config = new MapConfiguration(); - config.getNode("path", "with", "value").setValue("valuehere"); - ConfigurationHolder subject = new ConfigurationHolder(config, (Object) null, "path", "with", "value"); - assertEquals("valuehere", subject.getValue()); - } + @Test + public void testGetExistingValue() { + Configuration config = new MapConfiguration(); + config.getNode("path", "with", "value").setValue("valuehere"); + ConfigurationHolder subject = new ConfigurationHolder(config, (Object) null, "path", "with", "value"); + assertEquals("valuehere", subject.getValue()); + } - @Test - public void testGettingNewValueWritesToConfig() { - Configuration config = new MapConfiguration(); - ConfigurationHolder subject = new ConfigurationHolder(config, (Object) "hello", "unknown", "path"); - subject.getValue(); - assertEquals("hello", config.getNode("unknown", "path").getString()); - } + @Test + public void testGettingNewValueWritesToConfig() { + Configuration config = new MapConfiguration(); + ConfigurationHolder subject = new ConfigurationHolder(config, (Object) "hello", "unknown", "path"); + subject.getValue(); + assertEquals("hello", config.getNode("unknown", "path").getString()); + } } diff --git a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationMigratorTest.java b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationMigratorTest.java index 1ba64f0..d330474 100644 --- a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationMigratorTest.java +++ b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationMigratorTest.java @@ -47,69 +47,69 @@ import static org.junit.Assert.assertTrue; public class ConfigurationMigratorTest { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); + @Rule + public TemporaryFolder folder = new TemporaryFolder(); - private class TestConfigurationMigrator extends ConfigurationMigrator { - private final Map migrationActions; + private class TestConfigurationMigrator extends ConfigurationMigrator { + private final Map migrationActions; - protected TestConfigurationMigrator(Configuration configuration, Map migrationActions) { - super(configuration); - this.migrationActions = migrationActions; - } + protected TestConfigurationMigrator(Configuration configuration, Map migrationActions) { + super(configuration); + this.migrationActions = migrationActions; + } - @Override - protected Map getMigrationActions() { - return migrationActions; - } + @Override + protected Map getMigrationActions() { + return migrationActions; + } - @Override - protected boolean shouldMigrate() { - return true; // Always migrate so we can test easily - } - } + @Override + protected boolean shouldMigrate() { + return true; // Always migrate so we can test easily + } + } - @Test - public void testNewJoinedKeyMigrationAction() { - ConfigurationMigrator migrator = new TestConfigurationMigrator(new MapConfiguration(), Collections.emptyMap()); - NewJoinedKey action = new NewJoinedKey("now.before.%", migrator.getConfiguration()); - assertArrayEquals(new String[] {"now", "before", "input", "key"}, action.convertKey(new String[] {"input", "key"})); - } + @Test + public void testNewJoinedKeyMigrationAction() { + ConfigurationMigrator migrator = new TestConfigurationMigrator(new MapConfiguration(), Collections.emptyMap()); + NewJoinedKey action = new NewJoinedKey("now.before.%", migrator.getConfiguration()); + assertArrayEquals(new String[] {"now", "before", "input", "key"}, action.convertKey(new String[] {"input", "key"})); + } - @Test - public void testConfigurationFileMoved() throws IOException, ConfigurationException, MigrationException { - File testFile = folder.newFile("test.ini"); - IniConfiguration testConfig = new IniConfiguration(testFile); - testConfig.getNode("test", "node").setValue("node-value"); - testConfig.getNode("test", "node2").setValue("node2-value"); - testConfig.getNode("test2", "node").setValue("node-value"); - testConfig.getNode("test2", "node2").setValue("node2-value"); - testConfig.save(); - ConfigurationMigrator migrator = new TestConfigurationMigrator(testConfig, Collections.emptyMap()); - migrator.migrate(); - assertTrue(new File(testFile.getAbsolutePath() + ".old").isFile()); - } + @Test + public void testConfigurationFileMoved() throws IOException, ConfigurationException, MigrationException { + File testFile = folder.newFile("test.ini"); + IniConfiguration testConfig = new IniConfiguration(testFile); + testConfig.getNode("test", "node").setValue("node-value"); + testConfig.getNode("test", "node2").setValue("node2-value"); + testConfig.getNode("test2", "node").setValue("node-value"); + testConfig.getNode("test2", "node2").setValue("node2-value"); + testConfig.save(); + ConfigurationMigrator migrator = new TestConfigurationMigrator(testConfig, Collections.emptyMap()); + migrator.migrate(); + assertTrue(new File(testFile.getAbsolutePath() + ".old").isFile()); + } - //@Test(expected = MigrationException.class) - @Test - public void testErrorOnOldFileExisting() throws IOException, ConfigurationException, MigrationException { - File testNewFile = folder.newFile("testOldFileExisting.ini"); - IniConfiguration config = new IniConfiguration(testNewFile); - config.getNode("test", "node").setValue("test value"); - config.save(); + //@Test(expected = MigrationException.class) + @Test + public void testErrorOnOldFileExisting() throws IOException, ConfigurationException, MigrationException { + File testNewFile = folder.newFile("testOldFileExisting.ini"); + IniConfiguration config = new IniConfiguration(testNewFile); + config.getNode("test", "node").setValue("test value"); + config.save(); - ConfigurationMigrator migrator = new TestConfigurationMigrator(config, Collections.emptyMap()); - migrator.migrate(); - } + ConfigurationMigrator migrator = new TestConfigurationMigrator(config, Collections.emptyMap()); + migrator.migrate(); + } - @Test - public void testConfigurationKeyMove() throws MigrationException { - Configuration testConfig = new MapConfiguration(); - ConfigurationMigrator testMigrator = new TestConfigurationMigrator(testConfig, Collections.singletonMap(new String[] {"test", "key"}, new NewKey("test2", "key2"))); - final Object obj = new Object(); - testConfig.getNode("test", "key").setValue(obj); - testMigrator.migrate(); + @Test + public void testConfigurationKeyMove() throws MigrationException { + Configuration testConfig = new MapConfiguration(); + ConfigurationMigrator testMigrator = new TestConfigurationMigrator(testConfig, Collections.singletonMap(new String[] {"test", "key"}, new NewKey("test2", "key2"))); + final Object obj = new Object(); + testConfig.getNode("test", "key").setValue(obj); + testMigrator.migrate(); - assertEquals(obj, testConfig.getNode("test2", "key2").getValue()); - } + assertEquals(obj, testConfig.getNode("test2", "key2").getValue()); + } } diff --git a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationNodeTest.java b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationNodeTest.java index 859e955..4e8a681 100644 --- a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationNodeTest.java +++ b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationNodeTest.java @@ -39,49 +39,49 @@ import static org.junit.Assert.assertFalse; public class ConfigurationNodeTest { - private Configuration base; + private Configuration base; - @Before - public void setUp() { - base = new MapConfiguration(); - } + @Before + public void setUp() { + base = new MapConfiguration(); + } - @Test - public void testGetPath() { - ConfigurationNode config = new ConfigurationNode(base, new String[] {"a", "b", "c"}, null); - assertEquals("a.b.c", config.getPath()); - } + @Test + public void testGetPath() { + ConfigurationNode config = new ConfigurationNode(base, new String[] {"a", "b", "c"}, null); + assertEquals("a.b.c", config.getPath()); + } - @Test - public void testGetKeys() { - ConfigurationNode parent = base.getChild("a"); - parent.getChild("a1", true).setValue("b1"); - parent.getChild("a2", true).setValue("b2"); - parent.getChild("a3", true).setValue("b3"); - parent.getChild("a3").getChild("c3", true); - assertEquals(new HashSet(Arrays.asList("a1", "a2", "a3")), parent.getKeys(false)); - assertEquals(new HashSet(Arrays.asList("a")), base.getKeys(false)); - assertEquals(new HashSet(Arrays.asList("a", "a.a1", "a.a2", "a.a3", "a.a3.c3")), base.getKeys(true)); - } + @Test + public void testGetKeys() { + ConfigurationNode parent = base.getChild("a"); + parent.getChild("a1", true).setValue("b1"); + parent.getChild("a2", true).setValue("b2"); + parent.getChild("a3", true).setValue("b3"); + parent.getChild("a3").getChild("c3", true); + assertEquals(new HashSet(Arrays.asList("a1", "a2", "a3")), parent.getKeys(false)); + assertEquals(new HashSet(Arrays.asList("a")), base.getKeys(false)); + assertEquals(new HashSet(Arrays.asList("a", "a.a1", "a.a2", "a.a3", "a.a3.c3")), base.getKeys(true)); + } - @Test - public void testGetValues() { - ConfigurationNode parent = base.getChild("a"); - Map vals = new HashMap(); - for (int i = 1; i <= 3; ++i) { - parent.getChild("a" + i).setValue("b" + i); - vals.put("a" + i, "b" + i); - } - assertEquals(vals, parent.getValues()); - } + @Test + public void testGetValues() { + ConfigurationNode parent = base.getChild("a"); + Map vals = new HashMap(); + for (int i = 1; i <= 3; ++i) { + parent.getChild("a" + i).setValue("b" + i); + vals.put("a" + i, "b" + i); + } + assertEquals(vals, parent.getValues()); + } - @Test - public void testRemove() { - ConfigurationNode toRemove = base.getNode("to-remove"); - toRemove.setValue("test"); - assertEquals(toRemove, base.getNode("to-remove")); - toRemove.remove(); - assertFalse(base.getChildren().containsKey("to-remove")); - assertEquals(null, base.getNode("to-remove").getValue()); - } + @Test + public void testRemove() { + ConfigurationNode toRemove = base.getNode("to-remove"); + toRemove.setValue("test"); + assertEquals(toRemove, base.getNode("to-remove")); + toRemove.remove(); + assertFalse(base.getChildren().containsKey("to-remove")); + assertEquals(null, base.getNode("to-remove").getValue()); + } } diff --git a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationTest.java b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationTest.java index 27721de..08dd011 100644 --- a/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationTest.java +++ b/src/test/java/com/flowpowered/cerealization/util/config/ConfigurationTest.java @@ -38,73 +38,73 @@ import static org.junit.Assert.assertTrue; public class ConfigurationTest { - private MapConfiguration config; + private MapConfiguration config; - @Before - public void setUp() throws ConfigurationException { - config = createConfiguration(); - config.load(); - } + @Before + public void setUp() throws ConfigurationException { + config = createConfiguration(); + config.load(); + } - public Map getConfigMap() { - Map newData = new HashMap(); - newData.put("string-type", "someString"); - newData.put("int-type", 45); - Map testNested = new HashMap(); - testNested.put("bar", "baz"); - newData.put("foo", testNested); - return newData; - } + public Map getConfigMap() { + Map newData = new HashMap(); + newData.put("string-type", "someString"); + newData.put("int-type", 45); + Map testNested = new HashMap(); + testNested.put("bar", "baz"); + newData.put("foo", testNested); + return newData; + } - public MapConfiguration createConfiguration() { - return new MapConfiguration(getConfigMap()); - } + public MapConfiguration createConfiguration() { + return new MapConfiguration(getConfigMap()); + } - @Test - public void testLoadSave() throws ConfigurationException { - config.load(); - config.save(); - assertEquals(getConfigMap(), config.getMap()); - } + @Test + public void testLoadSave() throws ConfigurationException { + config.load(); + config.save(); + assertEquals(getConfigMap(), config.getMap()); + } - @Test - public void testGetNode() { - ConfigurationNode node = config.getNode("string-type"); - assertEquals("someString", node.getValue()); - node = config.getNode("foo.bar"); - assertEquals("baz", node.getValue()); - } + @Test + public void testGetNode() { + ConfigurationNode node = config.getNode("string-type"); + assertEquals("someString", node.getValue()); + node = config.getNode("foo.bar"); + assertEquals("baz", node.getValue()); + } - @Test - public void testGetNewNode() { - ConfigurationNode node = config.getNode("unknown.node"); - assertTrue(node != null); - assertEquals(null, node.getValue()); - assertFalse(node.isAttached()); - assertEquals(null, node.getParent()); - } + @Test + public void testGetNewNode() { + ConfigurationNode node = config.getNode("unknown.node"); + assertTrue(node != null); + assertEquals(null, node.getValue()); + assertFalse(node.isAttached()); + assertEquals(null, node.getParent()); + } - private static final String TEST_PATH = "another.unknown.node"; - private static final String TEST_VALUE = "Never gonna give you up!"; + private static final String TEST_PATH = "another.unknown.node"; + private static final String TEST_VALUE = "Never gonna give you up!"; - @Test - public void testSetNewNode() { - ConfigurationNode node = config.getNode(TEST_PATH); - assertEquals(null, node.getValue()); - node.setValue(TEST_VALUE); - assertEquals(TEST_VALUE, node.getString()); - assertEquals(node, config.getNode(TEST_PATH)); - assertEquals(TEST_VALUE, config.getNode(TEST_PATH).getString()); - } + @Test + public void testSetNewNode() { + ConfigurationNode node = config.getNode(TEST_PATH); + assertEquals(null, node.getValue()); + node.setValue(TEST_VALUE); + assertEquals(TEST_VALUE, node.getString()); + assertEquals(node, config.getNode(TEST_PATH)); + assertEquals(TEST_VALUE, config.getNode(TEST_PATH).getString()); + } - @Test - public void testPathSeparator() { - String actualValue = config.getNode("foo", "bar").getString(); - String value = config.getNode("foo.bar").getString(); - assertEquals(actualValue, value); - config.setPathSeparator("/"); - value = config.getNode("foo/bar").getString(); - assertEquals(actualValue, value); - config.setPathSeparator("."); - } + @Test + public void testPathSeparator() { + String actualValue = config.getNode("foo", "bar").getString(); + String value = config.getNode("foo.bar").getString(); + assertEquals(actualValue, value); + config.setPathSeparator("/"); + value = config.getNode("foo/bar").getString(); + assertEquals(actualValue, value); + config.setPathSeparator("."); + } } diff --git a/src/test/java/com/flowpowered/cerealization/util/config/IniConfigurationTest.java b/src/test/java/com/flowpowered/cerealization/util/config/IniConfigurationTest.java index 1ce52cc..cb14dd2 100644 --- a/src/test/java/com/flowpowered/cerealization/util/config/IniConfigurationTest.java +++ b/src/test/java/com/flowpowered/cerealization/util/config/IniConfigurationTest.java @@ -38,42 +38,42 @@ import static com.flowpowered.cerealization.config.commented.CommentedConfigurationNode.LINE_SEPARATOR; public class IniConfigurationTest { - @Test - public void testBasicLoading() throws ConfigurationException { - StringLoadingIniConfiguration subject = new StringLoadingIniConfiguration("[section]" + LINE_SEPARATOR + "node = value" + LINE_SEPARATOR); - subject.load(); - ConfigurationNode sectionNode = subject.getNode("section"); - assertNotNull(sectionNode); - assertTrue(sectionNode.isAttached()); - assertTrue(sectionNode.hasChildren()); - assertEquals("value", subject.getNode("section.node").getString()); - } + @Test + public void testBasicLoading() throws ConfigurationException { + StringLoadingIniConfiguration subject = new StringLoadingIniConfiguration("[section]" + LINE_SEPARATOR + "node = value" + LINE_SEPARATOR); + subject.load(); + ConfigurationNode sectionNode = subject.getNode("section"); + assertNotNull(sectionNode); + assertTrue(sectionNode.isAttached()); + assertTrue(sectionNode.hasChildren()); + assertEquals("value", subject.getNode("section.node").getString()); + } - @Test - public void testBasicSaving() throws ConfigurationException { - StringLoadingIniConfiguration subject = new StringLoadingIniConfiguration(null); - subject.getNode("section.node").setValue("value"); - subject.save(); - assertEquals("[section]" + LINE_SEPARATOR + "node=value" + LINE_SEPARATOR, subject.getValue()); - } + @Test + public void testBasicSaving() throws ConfigurationException { + StringLoadingIniConfiguration subject = new StringLoadingIniConfiguration(null); + subject.getNode("section.node").setValue("value"); + subject.save(); + assertEquals("[section]" + LINE_SEPARATOR + "node=value" + LINE_SEPARATOR, subject.getValue()); + } - @Test - public void testCommentLoading() throws ConfigurationException { - StringLoadingIniConfiguration subject = new StringLoadingIniConfiguration("# This is the first section!" + LINE_SEPARATOR + "[section]" + LINE_SEPARATOR + "# This is a node!" + LINE_SEPARATOR + "# With a multiline comment!" + LINE_SEPARATOR + "node=value" + LINE_SEPARATOR); - subject.load(); - ConfigurationNode node = subject.getNode("section"); - assertArrayEquals(new String[] {"This is the first section!"}, ((CommentedConfigurationNode) node).getComment()); - node = subject.getNode("section.node"); - assertArrayEquals(new String[] {"This is a node!", "With a multiline comment!"}, ((CommentedConfigurationNode) node).getComment()); - } + @Test + public void testCommentLoading() throws ConfigurationException { + StringLoadingIniConfiguration subject = new StringLoadingIniConfiguration("# This is the first section!" + LINE_SEPARATOR + "[section]" + LINE_SEPARATOR + "# This is a node!" + LINE_SEPARATOR + "# With a multiline comment!" + LINE_SEPARATOR + "node=value" + LINE_SEPARATOR); + subject.load(); + ConfigurationNode node = subject.getNode("section"); + assertArrayEquals(new String[] {"This is the first section!"}, ((CommentedConfigurationNode) node).getComment()); + node = subject.getNode("section.node"); + assertArrayEquals(new String[] {"This is a node!", "With a multiline comment!"}, ((CommentedConfigurationNode) node).getComment()); + } - @Test - public void testCommentSaving() throws ConfigurationException { - StringLoadingIniConfiguration subject = new StringLoadingIniConfiguration(null); - subject.getNode("section").setComment("Hello", "World"); - subject.getNode("section", "node").setValue("value"); - subject.getNode("section", "node").setComment("Node Comment"); - subject.save(); - assertEquals("# Hello" + LINE_SEPARATOR + "# World" + LINE_SEPARATOR + "[section]" + LINE_SEPARATOR + "# Node Comment" + LINE_SEPARATOR + "node=value" + LINE_SEPARATOR, subject.getValue()); - } + @Test + public void testCommentSaving() throws ConfigurationException { + StringLoadingIniConfiguration subject = new StringLoadingIniConfiguration(null); + subject.getNode("section").setComment("Hello", "World"); + subject.getNode("section", "node").setValue("value"); + subject.getNode("section", "node").setComment("Node Comment"); + subject.save(); + assertEquals("# Hello" + LINE_SEPARATOR + "# World" + LINE_SEPARATOR + "[section]" + LINE_SEPARATOR + "# Node Comment" + LINE_SEPARATOR + "node=value" + LINE_SEPARATOR, subject.getValue()); + } } diff --git a/src/test/java/com/flowpowered/cerealization/util/config/annotated/AnnotatedConfigurationTest.java b/src/test/java/com/flowpowered/cerealization/util/config/annotated/AnnotatedConfigurationTest.java index 424fbe2..55a6647 100644 --- a/src/test/java/com/flowpowered/cerealization/util/config/annotated/AnnotatedConfigurationTest.java +++ b/src/test/java/com/flowpowered/cerealization/util/config/annotated/AnnotatedConfigurationTest.java @@ -48,191 +48,191 @@ * Tests for AnnotatedConfiguration */ public class AnnotatedConfigurationTest { - public static enum TestEnum { - ONE, - TWO, - } - - // Constants for easier accurate results - private static final String BOOLEAN_KEY = "boolean-setting"; - private static final boolean BOOLEAN_VALUE = true; - private static final String BOOLEAN_AUTO_KEY = "bool"; - private static final boolean BOOLEAN_AUTO_KEY_VALUE = false; - private static final String INT_KEY = "int-setting"; - private static final int INT_VALUE = 42; - private static final String[] NESTED_STRING_KEY = new String[] {"nested", "key"}; - private static final String NESTED_STRING_VALUE = "cute asian cadvahns"; - private static final String[] MAP_STRING_STRING_KEY = new String[] {"map", "string-string"}; - private static final Map MAP_STRING_STRING_VALUE = createMapStringString(); - private static final String SET_INTEGER_KEY = "int-set"; - private static final Set SET_INTEGER_VALUE = new HashSet(Arrays.asList(1, 2, 3, 4, 5)); - private static final String SET_ENUM_KEY = "enum-set"; - private static final Set SET_ENUM_VALUE = new HashSet(Arrays.asList(TestEnum.values())); - private static final String[] NESTED_MAP_KEY = new String[] {"map", "nested"}; - private static final Map> NESTED_MAP_VALUE = createNestedMap(); - private static final String ENUM_KEY = "enum"; - private static final TestEnum ENUM_VALUE = TestEnum.TWO; - private static final String CONFIG_BASE_KEY = "configbase"; - private static final String DEFAULT_KEY = "dead"; - private static final String DEFAULT_VALUE = "parrot"; - - private static class LocalConfiguration extends AnnotatedSubclassConfiguration { - @Setting (BOOLEAN_KEY) - public boolean booleanSetting; - @Setting - public boolean bool; - @Setting (INT_KEY) - public int intSetting; - @Setting ({"nested", "key"}) - public String nestedStringSetting; - @Setting ({"map", "string-string"}) - public Map mapStringStringSetting; - @Setting (SET_INTEGER_KEY) - public Set setIntegerSetting; - @Setting (SET_ENUM_KEY) - public Set setEnumSetting; - @Setting ({"map", "nested"}) - public Map> nestedMapSetting; - @Setting (ENUM_KEY) - public TestEnum enumSetting; - @Setting (CONFIG_BASE_KEY) - public SubConfiguration subConfigSetting; - @Setting (DEFAULT_KEY) - public String defaultSetting = DEFAULT_VALUE; - - public LocalConfiguration(Configuration baseConfig) { - super(baseConfig); - } - } - - public static class SubConfiguration extends AnnotatedSubclassConfiguration { - public SubConfiguration(Configuration baseConfig) { - super(baseConfig); - } - - @Setting ("a") - public String aSetting; - @Setting ("b") - public String bSetting; - } - - private static Map createMapStringString() { - Map result = new HashMap(); - result.put("hello", "world"); - result.put("command", "book"); - return result; - } - - private static Map> createNestedMap() { - Map> result = new HashMap>(); - result.put("one", (Map) createMapStringString()); - Map two = new HashMap(); - two.put("something", "else"); - two.put("andnowforsomething", "completelydifferent"); - result.put("two", two); - return result; - } - - // The real tests! - protected Configuration config; - protected LocalConfiguration annotatedConfig; - - @Before - public void setUp() throws ConfigurationException { - config = new MapConfiguration(); - config.getNode(BOOLEAN_KEY).setValue(BOOLEAN_VALUE); - config.getNode(BOOLEAN_AUTO_KEY).setValue(BOOLEAN_AUTO_KEY_VALUE); - config.getNode(INT_KEY).setValue(INT_VALUE); - config.getNode(NESTED_STRING_KEY).setValue(NESTED_STRING_VALUE); - config.getNode(MAP_STRING_STRING_KEY).setValue(MAP_STRING_STRING_VALUE); - List sortedIntList = new ArrayList(SET_INTEGER_VALUE); - Collections.sort(sortedIntList); - config.getNode(SET_INTEGER_KEY).setValue(sortedIntList); - - List enumNames = new ArrayList(SET_ENUM_VALUE.size()); - for (TestEnum val : SET_ENUM_VALUE) { - enumNames.add(val.name()); - } - Collections.sort(enumNames); - config.getNode(SET_ENUM_KEY).setValue(enumNames); - config.getNode(NESTED_MAP_KEY).setValue(NESTED_MAP_VALUE); - config.getNode(ENUM_KEY).setValue(ENUM_VALUE.name()); - config.save(); - annotatedConfig = new LocalConfiguration(config); - annotatedConfig.load(); - } - - @Test - @SuppressWarnings ({"unchecked", "rawtypes"}) - public void testSaving() throws ConfigurationException { - MapConfiguration saveConfig = new MapConfiguration(); - annotatedConfig.save(saveConfig); - Map values = config.getValues(); - SubConfiguration subConfig = new SubConfiguration(new MapConfiguration()); - subConfig.save(); - Map saveValues = saveConfig.getValues(); - Collections.sort((List) saveValues.get(SET_ENUM_KEY)); - Collections.sort((List) saveValues.get(SET_INTEGER_KEY)); - values.put(CONFIG_BASE_KEY, subConfig.getValues()); - assertEquals(values, saveValues); - } - - @Test - public void testBooleanValue() { - assertEquals(BOOLEAN_VALUE, annotatedConfig.booleanSetting); - } - - @Test - public void testAutoKeyBooleanValue() { - assertEquals(BOOLEAN_AUTO_KEY_VALUE, annotatedConfig.bool); - } - - @Test - public void testIntValue() { - assertEquals(INT_VALUE, annotatedConfig.intSetting); - } - - @Test - public void testNestedStringValue() { - assertEquals(NESTED_STRING_VALUE, annotatedConfig.nestedStringSetting); - } - - @Test - public void testMapStringStringValue() { - assertEquals(MAP_STRING_STRING_VALUE, annotatedConfig.mapStringStringSetting); - } - - @Test - public void testSetIntegerValue() { - assertEquals(SET_INTEGER_VALUE, annotatedConfig.setIntegerSetting); - } - - @Test - public void testNestedMapValue() { - assertEquals(NESTED_MAP_VALUE, annotatedConfig.nestedMapSetting); - } - - @Test - public void testEnumValue() { - assertEquals(ENUM_VALUE, annotatedConfig.enumSetting); - } - - @Test - public void testDefaultValue() { - assertEquals(DEFAULT_VALUE, annotatedConfig.defaultSetting); - } - - @Test - public void testSetEnumValue() { - assertEquals(SET_ENUM_VALUE, annotatedConfig.setEnumSetting); - } - - @Test - public void testAnnotatedConfigurationValue() throws ConfigurationException { - assertNotNull(annotatedConfig.subConfigSetting); - SubConfiguration second = new SubConfiguration(new MapConfiguration()); - second.load(); - annotatedConfig.save(); - assertEquals(second.getValues(), annotatedConfig.getNode(CONFIG_BASE_KEY).getValues()); - } + public static enum TestEnum { + ONE, + TWO, + } + + // Constants for easier accurate results + private static final String BOOLEAN_KEY = "boolean-setting"; + private static final boolean BOOLEAN_VALUE = true; + private static final String BOOLEAN_AUTO_KEY = "bool"; + private static final boolean BOOLEAN_AUTO_KEY_VALUE = false; + private static final String INT_KEY = "int-setting"; + private static final int INT_VALUE = 42; + private static final String[] NESTED_STRING_KEY = new String[] {"nested", "key"}; + private static final String NESTED_STRING_VALUE = "cute asian cadvahns"; + private static final String[] MAP_STRING_STRING_KEY = new String[] {"map", "string-string"}; + private static final Map MAP_STRING_STRING_VALUE = createMapStringString(); + private static final String SET_INTEGER_KEY = "int-set"; + private static final Set SET_INTEGER_VALUE = new HashSet(Arrays.asList(1, 2, 3, 4, 5)); + private static final String SET_ENUM_KEY = "enum-set"; + private static final Set SET_ENUM_VALUE = new HashSet(Arrays.asList(TestEnum.values())); + private static final String[] NESTED_MAP_KEY = new String[] {"map", "nested"}; + private static final Map> NESTED_MAP_VALUE = createNestedMap(); + private static final String ENUM_KEY = "enum"; + private static final TestEnum ENUM_VALUE = TestEnum.TWO; + private static final String CONFIG_BASE_KEY = "configbase"; + private static final String DEFAULT_KEY = "dead"; + private static final String DEFAULT_VALUE = "parrot"; + + private static class LocalConfiguration extends AnnotatedSubclassConfiguration { + @Setting (BOOLEAN_KEY) + public boolean booleanSetting; + @Setting + public boolean bool; + @Setting (INT_KEY) + public int intSetting; + @Setting ({"nested", "key"}) + public String nestedStringSetting; + @Setting ({"map", "string-string"}) + public Map mapStringStringSetting; + @Setting (SET_INTEGER_KEY) + public Set setIntegerSetting; + @Setting (SET_ENUM_KEY) + public Set setEnumSetting; + @Setting ({"map", "nested"}) + public Map> nestedMapSetting; + @Setting (ENUM_KEY) + public TestEnum enumSetting; + @Setting (CONFIG_BASE_KEY) + public SubConfiguration subConfigSetting; + @Setting (DEFAULT_KEY) + public String defaultSetting = DEFAULT_VALUE; + + public LocalConfiguration(Configuration baseConfig) { + super(baseConfig); + } + } + + public static class SubConfiguration extends AnnotatedSubclassConfiguration { + public SubConfiguration(Configuration baseConfig) { + super(baseConfig); + } + + @Setting ("a") + public String aSetting; + @Setting ("b") + public String bSetting; + } + + private static Map createMapStringString() { + Map result = new HashMap(); + result.put("hello", "world"); + result.put("command", "book"); + return result; + } + + private static Map> createNestedMap() { + Map> result = new HashMap>(); + result.put("one", (Map) createMapStringString()); + Map two = new HashMap(); + two.put("something", "else"); + two.put("andnowforsomething", "completelydifferent"); + result.put("two", two); + return result; + } + + // The real tests! + protected Configuration config; + protected LocalConfiguration annotatedConfig; + + @Before + public void setUp() throws ConfigurationException { + config = new MapConfiguration(); + config.getNode(BOOLEAN_KEY).setValue(BOOLEAN_VALUE); + config.getNode(BOOLEAN_AUTO_KEY).setValue(BOOLEAN_AUTO_KEY_VALUE); + config.getNode(INT_KEY).setValue(INT_VALUE); + config.getNode(NESTED_STRING_KEY).setValue(NESTED_STRING_VALUE); + config.getNode(MAP_STRING_STRING_KEY).setValue(MAP_STRING_STRING_VALUE); + List sortedIntList = new ArrayList(SET_INTEGER_VALUE); + Collections.sort(sortedIntList); + config.getNode(SET_INTEGER_KEY).setValue(sortedIntList); + + List enumNames = new ArrayList(SET_ENUM_VALUE.size()); + for (TestEnum val : SET_ENUM_VALUE) { + enumNames.add(val.name()); + } + Collections.sort(enumNames); + config.getNode(SET_ENUM_KEY).setValue(enumNames); + config.getNode(NESTED_MAP_KEY).setValue(NESTED_MAP_VALUE); + config.getNode(ENUM_KEY).setValue(ENUM_VALUE.name()); + config.save(); + annotatedConfig = new LocalConfiguration(config); + annotatedConfig.load(); + } + + @Test + @SuppressWarnings ({"unchecked", "rawtypes"}) + public void testSaving() throws ConfigurationException { + MapConfiguration saveConfig = new MapConfiguration(); + annotatedConfig.save(saveConfig); + Map values = config.getValues(); + SubConfiguration subConfig = new SubConfiguration(new MapConfiguration()); + subConfig.save(); + Map saveValues = saveConfig.getValues(); + Collections.sort((List) saveValues.get(SET_ENUM_KEY)); + Collections.sort((List) saveValues.get(SET_INTEGER_KEY)); + values.put(CONFIG_BASE_KEY, subConfig.getValues()); + assertEquals(values, saveValues); + } + + @Test + public void testBooleanValue() { + assertEquals(BOOLEAN_VALUE, annotatedConfig.booleanSetting); + } + + @Test + public void testAutoKeyBooleanValue() { + assertEquals(BOOLEAN_AUTO_KEY_VALUE, annotatedConfig.bool); + } + + @Test + public void testIntValue() { + assertEquals(INT_VALUE, annotatedConfig.intSetting); + } + + @Test + public void testNestedStringValue() { + assertEquals(NESTED_STRING_VALUE, annotatedConfig.nestedStringSetting); + } + + @Test + public void testMapStringStringValue() { + assertEquals(MAP_STRING_STRING_VALUE, annotatedConfig.mapStringStringSetting); + } + + @Test + public void testSetIntegerValue() { + assertEquals(SET_INTEGER_VALUE, annotatedConfig.setIntegerSetting); + } + + @Test + public void testNestedMapValue() { + assertEquals(NESTED_MAP_VALUE, annotatedConfig.nestedMapSetting); + } + + @Test + public void testEnumValue() { + assertEquals(ENUM_VALUE, annotatedConfig.enumSetting); + } + + @Test + public void testDefaultValue() { + assertEquals(DEFAULT_VALUE, annotatedConfig.defaultSetting); + } + + @Test + public void testSetEnumValue() { + assertEquals(SET_ENUM_VALUE, annotatedConfig.setEnumSetting); + } + + @Test + public void testAnnotatedConfigurationValue() throws ConfigurationException { + assertNotNull(annotatedConfig.subConfigSetting); + SubConfiguration second = new SubConfiguration(new MapConfiguration()); + second.load(); + annotatedConfig.save(); + assertEquals(second.getValues(), annotatedConfig.getNode(CONFIG_BASE_KEY).getValues()); + } } diff --git a/src/test/java/com/flowpowered/cerealization/util/config/annotated/AnnotatedObjectConfigurationTest.java b/src/test/java/com/flowpowered/cerealization/util/config/annotated/AnnotatedObjectConfigurationTest.java index 72eac2a..8fec2dc 100644 --- a/src/test/java/com/flowpowered/cerealization/util/config/annotated/AnnotatedObjectConfigurationTest.java +++ b/src/test/java/com/flowpowered/cerealization/util/config/annotated/AnnotatedObjectConfigurationTest.java @@ -35,132 +35,132 @@ import com.flowpowered.cerealization.config.annotated.Setting; public class AnnotatedObjectConfigurationTest { - // Save settings - private static final String SAVE_TEST_OBJECT_STRING = "save test"; - private static final int SAVE_TEST_OBJECT_INT = 1234; - private static final String SAVE_TEST_CONFIG_OBJECT_STRING = "save object test"; - private static final int SAVE_TEST_CONFIG_OBJECT_INT = 5678; - private static final double SAVE_TEST_SPECIAL_NODE = 4356.2; - // Load settings - private static final String LOAD_TEST_OBJECT_STRING = "load test"; - private static final int LOAD_TEST_OBJECT_INT = 91234; - private static final String LOAD_TEST_CONFIG_OBJECT_STRING = "load object test"; - private static final int LOAD_TEST_CONFIG_OBJECT_INT = 95678; - private static final double LOAD_TEST_SPECIAL_NODE = 94356.2; - - @Test - public void testSave() throws ConfigurationException { - final AnnotatedObjectConfiguration annotated = new AnnotatedObjectConfiguration(new MapConfiguration()); - annotated.add(new TestObject(), "object"); - annotated.save(); - Assert.assertEquals(SAVE_TEST_OBJECT_STRING, annotated.getNode("object", "string").getString()); - Assert.assertEquals(SAVE_TEST_OBJECT_INT, annotated.getNode("object", "integer").getInt()); - Assert.assertEquals(SAVE_TEST_CONFIG_OBJECT_STRING, annotated.getNode("object", "config-object", "obj-string").getString()); - Assert.assertEquals(SAVE_TEST_CONFIG_OBJECT_INT, annotated.getNode("object", "config-object", "obj-integer").getInt()); - Assert.assertEquals(SAVE_TEST_SPECIAL_NODE, annotated.getNode("object", "special", "node").getDouble(), 0); - } - - @Test - public void testLoad() throws ConfigurationException { - final MapConfiguration map = new MapConfiguration(); - map.getNode("object", "string").setValue(LOAD_TEST_OBJECT_STRING); - map.getNode("object", "integer").setValue(LOAD_TEST_OBJECT_INT); - map.getNode("object", "config-object", "obj-string").setValue(LOAD_TEST_CONFIG_OBJECT_STRING); - map.getNode("object", "config-object", "obj-integer").setValue(LOAD_TEST_CONFIG_OBJECT_INT); - map.getNode("object", "special", "node").setValue(LOAD_TEST_SPECIAL_NODE); - final TestObject object = new TestObject(); - final AnnotatedObjectConfiguration annotated = new AnnotatedObjectConfiguration(map); - annotated.add(object, "object"); - annotated.load(map); - Assert.assertEquals(LOAD_TEST_OBJECT_STRING, object.string); - Assert.assertEquals(LOAD_TEST_OBJECT_INT, object.integer); - Assert.assertEquals(LOAD_TEST_CONFIG_OBJECT_STRING, object.configObject.string); - Assert.assertEquals(LOAD_TEST_CONFIG_OBJECT_INT, object.configObject.integer); - Assert.assertEquals(LOAD_TEST_SPECIAL_NODE, object.special, 0); - } - - @Test - public void testClass() throws ConfigurationException { - { - final AnnotatedObjectConfiguration annotated = new AnnotatedObjectConfiguration(new MapConfiguration()); - annotated.add(TestClass.class, "object"); - annotated.save(); - - Assert.assertEquals(SAVE_TEST_OBJECT_STRING, annotated.getNode("object", "string").getString()); - Assert.assertEquals(SAVE_TEST_OBJECT_INT, annotated.getNode("object", "integer").getInt()); - Assert.assertEquals(SAVE_TEST_CONFIG_OBJECT_STRING, annotated.getNode("object", "config-object", "obj-string").getString()); - Assert.assertEquals(SAVE_TEST_CONFIG_OBJECT_INT, annotated.getNode("object", "config-object", "obj-integer").getInt()); - Assert.assertEquals(SAVE_TEST_SPECIAL_NODE, annotated.getNode("object", "special", "node").getDouble(), 0); - } - - { - final MapConfiguration map = new MapConfiguration(); - map.getNode("object", "string").setValue(LOAD_TEST_OBJECT_STRING); - map.getNode("object", "integer").setValue(LOAD_TEST_OBJECT_INT); - map.getNode("object", "config-object", "obj-string").setValue(LOAD_TEST_CONFIG_OBJECT_STRING); - map.getNode("object", "config-object", "obj-integer").setValue(LOAD_TEST_CONFIG_OBJECT_INT); - map.getNode("object", "special", "node").setValue(LOAD_TEST_SPECIAL_NODE); - - final AnnotatedObjectConfiguration annotated = new AnnotatedObjectConfiguration(map); - annotated.add(TestClass.class, "object"); - annotated.load(map); - - Assert.assertEquals(LOAD_TEST_OBJECT_STRING, TestClass.string); - Assert.assertEquals(LOAD_TEST_OBJECT_INT, TestClass.integer); - Assert.assertEquals(LOAD_TEST_CONFIG_OBJECT_STRING, TestClass.configObject.string); - Assert.assertEquals(LOAD_TEST_CONFIG_OBJECT_INT, TestClass.configObject.integer); - Assert.assertEquals(LOAD_TEST_SPECIAL_NODE, TestClass.special, 0); - } - } - - private final static class TestClass { - @Setting - private static String string = SAVE_TEST_OBJECT_STRING; - @Setting - private static int integer = SAVE_TEST_OBJECT_INT; - private static final TestConfigObject configObject = new TestConfigObject(); - @Setting ({"special", "node"}) - private static double special = SAVE_TEST_SPECIAL_NODE; - - @Load - private static void load(ConfigurationNode node) { - configObject.string = node.getNode("config-object", "obj-string").getString(); - configObject.integer = node.getNode("config-object", "obj-integer").getInt(); - } - - @Save - private static void save(ConfigurationNode node) { - final ConfigurationNode objectNode = node.getNode("config-object"); - objectNode.getNode("obj-string").setValue(configObject.string); - objectNode.getNode("obj-integer").setValue(configObject.integer); - } - } - - private static class TestObject { - @Setting - private String string = SAVE_TEST_OBJECT_STRING; - @Setting - private int integer = SAVE_TEST_OBJECT_INT; - private final TestConfigObject configObject = new TestConfigObject(); - @Setting ({"special", "node"}) - private double special = SAVE_TEST_SPECIAL_NODE; - - @Load - private void load(ConfigurationNode node) { - configObject.string = node.getNode("config-object", "obj-string").getString(); - configObject.integer = node.getNode("config-object", "obj-integer").getInt(); - } - - @Save - private void save(ConfigurationNode node) { - final ConfigurationNode objectNode = node.getNode("config-object"); - objectNode.getNode("obj-string").setValue(configObject.string); - objectNode.getNode("obj-integer").setValue(configObject.integer); - } - } - - private static class TestConfigObject { - private String string = SAVE_TEST_CONFIG_OBJECT_STRING; - private int integer = SAVE_TEST_CONFIG_OBJECT_INT; - } + // Save settings + private static final String SAVE_TEST_OBJECT_STRING = "save test"; + private static final int SAVE_TEST_OBJECT_INT = 1234; + private static final String SAVE_TEST_CONFIG_OBJECT_STRING = "save object test"; + private static final int SAVE_TEST_CONFIG_OBJECT_INT = 5678; + private static final double SAVE_TEST_SPECIAL_NODE = 4356.2; + // Load settings + private static final String LOAD_TEST_OBJECT_STRING = "load test"; + private static final int LOAD_TEST_OBJECT_INT = 91234; + private static final String LOAD_TEST_CONFIG_OBJECT_STRING = "load object test"; + private static final int LOAD_TEST_CONFIG_OBJECT_INT = 95678; + private static final double LOAD_TEST_SPECIAL_NODE = 94356.2; + + @Test + public void testSave() throws ConfigurationException { + final AnnotatedObjectConfiguration annotated = new AnnotatedObjectConfiguration(new MapConfiguration()); + annotated.add(new TestObject(), "object"); + annotated.save(); + Assert.assertEquals(SAVE_TEST_OBJECT_STRING, annotated.getNode("object", "string").getString()); + Assert.assertEquals(SAVE_TEST_OBJECT_INT, annotated.getNode("object", "integer").getInt()); + Assert.assertEquals(SAVE_TEST_CONFIG_OBJECT_STRING, annotated.getNode("object", "config-object", "obj-string").getString()); + Assert.assertEquals(SAVE_TEST_CONFIG_OBJECT_INT, annotated.getNode("object", "config-object", "obj-integer").getInt()); + Assert.assertEquals(SAVE_TEST_SPECIAL_NODE, annotated.getNode("object", "special", "node").getDouble(), 0); + } + + @Test + public void testLoad() throws ConfigurationException { + final MapConfiguration map = new MapConfiguration(); + map.getNode("object", "string").setValue(LOAD_TEST_OBJECT_STRING); + map.getNode("object", "integer").setValue(LOAD_TEST_OBJECT_INT); + map.getNode("object", "config-object", "obj-string").setValue(LOAD_TEST_CONFIG_OBJECT_STRING); + map.getNode("object", "config-object", "obj-integer").setValue(LOAD_TEST_CONFIG_OBJECT_INT); + map.getNode("object", "special", "node").setValue(LOAD_TEST_SPECIAL_NODE); + final TestObject object = new TestObject(); + final AnnotatedObjectConfiguration annotated = new AnnotatedObjectConfiguration(map); + annotated.add(object, "object"); + annotated.load(map); + Assert.assertEquals(LOAD_TEST_OBJECT_STRING, object.string); + Assert.assertEquals(LOAD_TEST_OBJECT_INT, object.integer); + Assert.assertEquals(LOAD_TEST_CONFIG_OBJECT_STRING, object.configObject.string); + Assert.assertEquals(LOAD_TEST_CONFIG_OBJECT_INT, object.configObject.integer); + Assert.assertEquals(LOAD_TEST_SPECIAL_NODE, object.special, 0); + } + + @Test + public void testClass() throws ConfigurationException { + { + final AnnotatedObjectConfiguration annotated = new AnnotatedObjectConfiguration(new MapConfiguration()); + annotated.add(TestClass.class, "object"); + annotated.save(); + + Assert.assertEquals(SAVE_TEST_OBJECT_STRING, annotated.getNode("object", "string").getString()); + Assert.assertEquals(SAVE_TEST_OBJECT_INT, annotated.getNode("object", "integer").getInt()); + Assert.assertEquals(SAVE_TEST_CONFIG_OBJECT_STRING, annotated.getNode("object", "config-object", "obj-string").getString()); + Assert.assertEquals(SAVE_TEST_CONFIG_OBJECT_INT, annotated.getNode("object", "config-object", "obj-integer").getInt()); + Assert.assertEquals(SAVE_TEST_SPECIAL_NODE, annotated.getNode("object", "special", "node").getDouble(), 0); + } + + { + final MapConfiguration map = new MapConfiguration(); + map.getNode("object", "string").setValue(LOAD_TEST_OBJECT_STRING); + map.getNode("object", "integer").setValue(LOAD_TEST_OBJECT_INT); + map.getNode("object", "config-object", "obj-string").setValue(LOAD_TEST_CONFIG_OBJECT_STRING); + map.getNode("object", "config-object", "obj-integer").setValue(LOAD_TEST_CONFIG_OBJECT_INT); + map.getNode("object", "special", "node").setValue(LOAD_TEST_SPECIAL_NODE); + + final AnnotatedObjectConfiguration annotated = new AnnotatedObjectConfiguration(map); + annotated.add(TestClass.class, "object"); + annotated.load(map); + + Assert.assertEquals(LOAD_TEST_OBJECT_STRING, TestClass.string); + Assert.assertEquals(LOAD_TEST_OBJECT_INT, TestClass.integer); + Assert.assertEquals(LOAD_TEST_CONFIG_OBJECT_STRING, TestClass.configObject.string); + Assert.assertEquals(LOAD_TEST_CONFIG_OBJECT_INT, TestClass.configObject.integer); + Assert.assertEquals(LOAD_TEST_SPECIAL_NODE, TestClass.special, 0); + } + } + + private final static class TestClass { + @Setting + private static String string = SAVE_TEST_OBJECT_STRING; + @Setting + private static int integer = SAVE_TEST_OBJECT_INT; + private static final TestConfigObject configObject = new TestConfigObject(); + @Setting ({"special", "node"}) + private static double special = SAVE_TEST_SPECIAL_NODE; + + @Load + private static void load(ConfigurationNode node) { + configObject.string = node.getNode("config-object", "obj-string").getString(); + configObject.integer = node.getNode("config-object", "obj-integer").getInt(); + } + + @Save + private static void save(ConfigurationNode node) { + final ConfigurationNode objectNode = node.getNode("config-object"); + objectNode.getNode("obj-string").setValue(configObject.string); + objectNode.getNode("obj-integer").setValue(configObject.integer); + } + } + + private static class TestObject { + @Setting + private String string = SAVE_TEST_OBJECT_STRING; + @Setting + private int integer = SAVE_TEST_OBJECT_INT; + private final TestConfigObject configObject = new TestConfigObject(); + @Setting ({"special", "node"}) + private double special = SAVE_TEST_SPECIAL_NODE; + + @Load + private void load(ConfigurationNode node) { + configObject.string = node.getNode("config-object", "obj-string").getString(); + configObject.integer = node.getNode("config-object", "obj-integer").getInt(); + } + + @Save + private void save(ConfigurationNode node) { + final ConfigurationNode objectNode = node.getNode("config-object"); + objectNode.getNode("obj-string").setValue(configObject.string); + objectNode.getNode("obj-integer").setValue(configObject.integer); + } + } + + private static class TestConfigObject { + private String string = SAVE_TEST_CONFIG_OBJECT_STRING; + private int integer = SAVE_TEST_CONFIG_OBJECT_INT; + } }