joda-convert-1.8.1/0000775000175000017500000000000012603461407013451 5ustar ebourgebourgjoda-convert-1.8.1/.travis.yml0000664000175000017500000000046712603461407015571 0ustar ebourgebourg# This file enables the Travis continuous integration system, which # automatically builds and tests joda-convert for each GitHub commit or # pull request on three separate JDKs. # # For more information, see https://travis-ci.org sudo: false language: java jdk: - oraclejdk8 - oraclejdk7 - openjdk6 joda-convert-1.8.1/README.md0000664000175000017500000000442212603461407014732 0ustar ebourgebourgJoda-Convert ------------ Joda-Convert provides a small set of classes to aid conversion between Objects and Strings. It is not intended to tackle the wider problem of Object to Object transformation. ```java // conversion to String String str = StringConvert.INSTANCE.convertToString(foo); // conversion from String Foo bar = StringConvert.INSTANCE.convertFromString(Foo.class, str); ``` Joda-Convert supports two mechanisms of extending the list of supported conversions. The first is to write your own converter implementing an interface. The second is to use annotations. The ability of Joda-Convert to use annotations to define the conversion methods is a key difference from other projects. For example, most value classes, like Currency or TimeZone, already have methods to convert to and from a standard format String. Consider a Distance class: ```java public class Distance { @FromString public static Distance parse(String str) { ... } @ToString public String getStandardOutput() { ... } } ``` As shown, the two methods may have any name. They must simply fulfil the required method signatures for conversion. The FromString annotation may also be applied to a constructor. When Joda-Convert is asked to convert between an object and a String, if there is no registered converter then the annotations are checked. If they are found, then the methods are called by reflection. Joda-Convert is licensed under the business-friendly [Apache 2.0 licence](http://www.joda.org/joda-convert/license.html). ### Documentation Various documentation is available: * The [home page](http://www.joda.org/joda-convert/) * The helpful [user guide](http://www.joda.org/joda-convert/userguide.html) * The [Javadoc](http://www.joda.org/joda-convert/apidocs/index.html) * The change notes for the [releases](http://www.joda.org/joda-convert/changes-report.html) ### Releases [Release 1.8.1](http://www.joda.org/joda-convert/download.html) is the current latest release. This release is considered stable and worthy of the 1.x tag. It depends on Java SE 6 or later. Available in the [Maven Central repository](http://search.maven.org/#artifactdetails|org.joda|joda-convert|1.8.1|jar) ### Support Please use GitHub issues and Pull Requests for support. joda-convert-1.8.1/src/0000775000175000017500000000000012603461407014240 5ustar ebourgebourgjoda-convert-1.8.1/src/main/0000775000175000017500000000000012603461407015164 5ustar ebourgebourgjoda-convert-1.8.1/src/main/checkstyle/0000775000175000017500000000000012603461407017322 5ustar ebourgebourgjoda-convert-1.8.1/src/main/checkstyle/checkstyle.xml0000664000175000017500000001351612603461407022210 0ustar ebourgebourg joda-convert-1.8.1/src/main/java/0000775000175000017500000000000012603461407016105 5ustar ebourgebourgjoda-convert-1.8.1/src/main/java/org/0000775000175000017500000000000012603461407016674 5ustar ebourgebourgjoda-convert-1.8.1/src/main/java/org/joda/0000775000175000017500000000000012603461407017611 5ustar ebourgebourgjoda-convert-1.8.1/src/main/java/org/joda/convert/0000775000175000017500000000000012603461407021271 5ustar ebourgebourgjoda-convert-1.8.1/src/main/java/org/joda/convert/RenameHandler.java0000664000175000017500000001660312603461407024647 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * A general purpose utility for registering renames. *

* This handles type and enum constant renames. * For example, use as follows: *

 *  RenameHandler.INSTANCE.renamedType("org.joda.OldName", NewName.class);
 *  RenameHandler.INSTANCE.renamedEnum("CORRECT", Status.VALID);
 *  RenameHandler.INSTANCE.renamedEnum("INCORRECT", Status.INVALID);
 * 
* The recommended usage is to edit the static singleton before using other classes. * Editing a static is acceptable because renames are driven by bytecode which is static. *

* This class is thread-safe with concurrent caches. * * @since 1.6 */ public final class RenameHandler { /** * A mutable global instance. * This is a singleton instance which is mutated. */ public static final RenameHandler INSTANCE = new RenameHandler(); /** * The type renames. */ private final ConcurrentHashMap> typeRenames = new ConcurrentHashMap>(16, 0.75f, 2); /** * The enum renames. */ private final ConcurrentHashMap, Map>> enumRenames = new ConcurrentHashMap, Map>>(16, 0.75f, 2); //----------------------------------------------------------------------- /** * Creates an instance. *

* This is not normally used as the preferred option is to edit the singleton. * * @return a new instance, not null */ public static RenameHandler create() { return new RenameHandler(); } //----------------------------------------------------------------------- /** * Restricted constructor. */ private RenameHandler() { } //----------------------------------------------------------------------- /** * Register the fact that a type was renamed. * * @param oldName the old name of the type including the package name, not null * @param currentValue the current type, not null */ public void renamedType(String oldName, Class currentValue) { if (oldName == null) { throw new IllegalArgumentException("oldName must not be null"); } if (currentValue == null) { throw new IllegalArgumentException("currentValue must not be null"); } typeRenames.put(oldName, currentValue); } /** * Gets the map of renamed types. *

* An empty map is returned if there are no renames. * * @return a copy of the set of enum types with renames, not null */ public Map> getTypeRenames() { return new HashMap>(typeRenames); } /** * Lookup a type from a name, handling renames. * * @param name the name of the type to lookup, not null * @return the type, not null * @throws ClassNotFoundException if the name is not a valid type */ public Class lookupType(String name) throws ClassNotFoundException { if (name == null) { throw new IllegalArgumentException("name must not be null"); } Class type = typeRenames.get(name); if (type == null) { type = loadType(name); } return type; } /** * Loads a type avoiding nulls * * @param fullName the full class name * @return the loaded class * @throws ClassNotFoundException if the class is not found */ Class loadType(String fullName) throws ClassNotFoundException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); return loader != null ? loader.loadClass(fullName) : Class.forName(fullName); } //----------------------------------------------------------------------- /** * Register the fact that an enum constant was renamed. * * @param oldName the old name of the enum constant, not null * @param currentValue the current enum constant, not null */ public void renamedEnum(String oldName, Enum currentValue) { if (oldName == null) { throw new IllegalArgumentException("oldName must not be null"); } if (currentValue == null) { throw new IllegalArgumentException("currentValue must not be null"); } Class enumType = currentValue.getDeclaringClass(); Map> perClass = enumRenames.get(enumType); if (perClass == null) { enumRenames.putIfAbsent(enumType, new ConcurrentHashMap>(16, 0.75f, 2)); perClass = enumRenames.get(enumType); } perClass.put(oldName, currentValue); } /** * Gets the set of enum types that have renames. *

* An empty set is returned if there are no renames. * * @return a copy of the set of enum types with renames, not null */ public Set> getEnumTypesWithRenames() { return new HashSet>(enumRenames.keySet()); } /** * Gets the map of renamed for an enum type. *

* An empty map is returned if there are no renames. * * @param type the enum type, not null * @return a copy of the set of enum renames, not null */ public Map> getEnumRenames(Class type) { if (type == null) { throw new IllegalArgumentException("type must not be null"); } Map> map = enumRenames.get(type); if (map == null) { return new HashMap>(); } return new HashMap>(map); } /** * Lookup an enum from a name, handling renames. * * @param the type of the desired enum * @param type the enum type, not null * @param name the name of the enum to lookup, not null * @return the enum value, not null * @throws IllegalArgumentException if the name is not a valid enum constant */ public > T lookupEnum(Class type, String name) { if (type == null) { throw new IllegalArgumentException("type must not be null"); } if (name == null) { throw new IllegalArgumentException("name must not be null"); } Map> map = getEnumRenames(type); Enum value = map.get(name); if (value != null) { return type.cast(value); } return Enum.valueOf(type, name); } //----------------------------------------------------------------------- @Override public String toString() { return "RenamedTypes" + typeRenames + ",RenamedEnumConstants" + enumRenames; } } joda-convert-1.8.1/src/main/java/org/joda/convert/FromStringConverter.java0000664000175000017500000000240112603461407026113 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Interface defining conversion from a {@code String}. *

* FromStringConverter is an interface and must be implemented with care. * Implementations must be immutable and thread-safe. * * @param the type of the converter */ public interface FromStringConverter { /** * Converts the specified object from a {@code String}. * @param cls the class to convert to, not null * @param str the string to convert, not null * @return the converted object, may be null but generally not */ T convertFromString(Class cls, String str); } joda-convert-1.8.1/src/main/java/org/joda/convert/TypedStringConverter.java0000664000175000017500000000261412603461407026303 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Interface defining conversion to and from a {@code String} together with the type. *

* TypedStringConverter is an interface and must be implemented with care. * Implementations must be immutable and thread-safe. * * @param the type of the converter * @since 1.7 */ public interface TypedStringConverter extends StringConverter { /** * Gets the effective type that the converter works on. *

* For example, if a class declares the {@code FromString} and {@code ToString} * then the effective type of the converter is that class. If a subclass is * queried for a converter, then the effective type is that of the superclass. * * @return the effective type */ Class getEffectiveType(); } joda-convert-1.8.1/src/main/java/org/joda/convert/JDKStringConverter.java0000664000175000017500000004124712603461407025633 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.UnknownHostException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Currency; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * Conversion between JDK classes and a {@code String}. */ enum JDKStringConverter implements TypedStringConverter { /** * String converter. */ STRING(String.class) { @Override public Object convertFromString(Class cls, String str) { return str; } }, /** * CharSequence converter. */ CHAR_SEQUENCE(CharSequence.class) { @Override public Object convertFromString(Class cls, String str) { return str; } }, /** * StringBuffer converter. */ STRING_BUFFER(StringBuffer.class) { @Override public Object convertFromString(Class cls, String str) { return new StringBuffer(str); } }, /** * StringBuilder converter. */ STRING_BUILDER(StringBuilder.class) { @Override public Object convertFromString(Class cls, String str) { return new StringBuilder(str); } }, /** * Long converter. */ LONG(Long.class) { @Override public Object convertFromString(Class cls, String str) { return new Long(str); } }, /** * Integer converter. */ INTEGER(Integer.class) { @Override public Object convertFromString(Class cls, String str) { return new Integer(str); } }, /** * Short converter. */ SHORT (Short.class) { @Override public Object convertFromString(Class cls, String str) { return new Short(str); } }, /** * Byte converter. */ BYTE(Byte.class) { @Override public Object convertFromString(Class cls, String str) { return new Byte(str); } }, /** * String converter. */ BYTE_ARRAY(byte[].class) { @Override public String convertToString(Object object) { return printBase64Binary((byte[]) object); } @Override public Object convertFromString(Class cls, String str) { return parseBase64Binary(str); } }, /** * Character converter. */ CHARACTER(Character.class) { @Override public Object convertFromString(Class cls, String str) { if (str.length() != 1) { throw new IllegalArgumentException("Character value must be a string length 1"); } return new Character(str.charAt(0)); } }, /** * String converter. */ CHAR_ARRAY(char[].class) { @Override public String convertToString(Object object) { return new String((char[]) object); } @Override public Object convertFromString(Class cls, String str) { return str.toCharArray(); } }, /** * Boolean converter. */ BOOLEAN(Boolean.class) { @Override public Object convertFromString(Class cls, String str) { if ("true".equalsIgnoreCase(str)) { return Boolean.TRUE; } if ("false".equalsIgnoreCase(str)) { return Boolean.FALSE; } throw new IllegalArgumentException("Boolean value must be 'true' or 'false', case insensitive"); } }, /** * Double converter. */ DOUBLE(Double.class) { @Override public Object convertFromString(Class cls, String str) { return new Double(str); } }, /** * Float converter. */ FLOAT(Float.class) { @Override public Object convertFromString(Class cls, String str) { return new Float(str); } }, /** * BigInteger converter. */ BIG_INTEGER(BigInteger.class) { @Override public Object convertFromString(Class cls, String str) { return new BigInteger(str); } }, /** * BigDecimal converter. */ BIG_DECIMAL(BigDecimal.class) { @Override public Object convertFromString(Class cls, String str) { return new BigDecimal(str); } }, /** * AtomicLong converter. */ ATOMIC_LONG(AtomicLong.class) { @Override public Object convertFromString(Class cls, String str) { long val = Long.parseLong(str); return new AtomicLong(val); } }, /** * AtomicLong converter. */ ATOMIC_INTEGER(AtomicInteger.class) { @Override public Object convertFromString(Class cls, String str) { int val = Integer.parseInt(str); return new AtomicInteger(val); } }, /** * AtomicBoolean converter. */ ATOMIC_BOOLEAN(AtomicBoolean.class) { @Override public Object convertFromString(Class cls, String str) { if ("true".equalsIgnoreCase(str)) { return new AtomicBoolean(true); } if ("false".equalsIgnoreCase(str)) { return new AtomicBoolean(false); } throw new IllegalArgumentException("Boolean value must be 'true' or 'false', case insensitive"); } }, /** * Locale converter. */ LOCALE(Locale.class) { @Override public Object convertFromString(Class cls, String str) { String[] split = str.split("_", 3); switch (split.length) { case 1: return new Locale(split[0]); case 2: return new Locale(split[0], split[1]); case 3: return new Locale(split[0], split[1], split[2]); } throw new IllegalArgumentException("Unable to parse Locale: " + str); } }, /** * Class converter. */ CLASS(Class.class) { @Override public String convertToString(Object object) { return ((Class) object).getName(); } @Override public Object convertFromString(Class cls, String str) { try { return RenameHandler.INSTANCE.lookupType(str); } catch (ClassNotFoundException ex) { throw new RuntimeException("Unable to create type: " + str, ex); } } }, /** * Package converter. */ PACKAGE(Package.class) { @Override public String convertToString(Object object) { return ((Package) object).getName(); } @Override public Object convertFromString(Class cls, String str) { return Package.getPackage(str); } }, /** * Currency converter. */ CURRENCY(Currency.class) { @Override public Object convertFromString(Class cls, String str) { return Currency.getInstance(str); } }, /** * TimeZone converter. */ TIME_ZONE(TimeZone.class) { @Override public String convertToString(Object object) { return ((TimeZone) object).getID(); } @Override public Object convertFromString(Class cls, String str) { return TimeZone.getTimeZone(str); } }, /** * UUID converter. */ UUID(UUID.class) { @Override public Object convertFromString(Class cls, String str) { return java.util.UUID.fromString(str); } }, /** * URL converter. */ URL(URL.class) { @Override public Object convertFromString(Class cls, String str) { try { return new URL(str); } catch (MalformedURLException ex) { throw new RuntimeException(ex.getMessage(), ex); } } }, /** * URI converter. */ URI(URI.class) { @Override public Object convertFromString(Class cls, String str) { return java.net.URI.create(str); } }, /** * InetAddress converter. */ INET_ADDRESS(InetAddress.class) { @Override public String convertToString(Object object) { return ((InetAddress) object).getHostAddress(); } @Override public Object convertFromString(Class cls, String str) { try { return InetAddress.getByName(str); } catch (UnknownHostException ex) { throw new RuntimeException(ex); } } }, /** * File converter. */ FILE(File.class) { @Override public Object convertFromString(Class cls, String str) { return new File(str); } }, /** * Date converter. */ DATE(Date.class) { @Override public String convertToString(Object object) { SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); String str = f.format(object); return str.substring(0, 26) + ":" + str.substring(26); } @Override public Object convertFromString(Class cls, String str) { if (str.length() != 29) { throw new IllegalArgumentException("Unable to parse date: " + str); } str = str.substring(0, 26) + str.substring(27); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); try { return f.parseObject(str); } catch (ParseException ex) { throw new RuntimeException(ex); } } }, /** * Calendar converter. */ CALENDAR(Calendar.class) { @Override public String convertToString(Object object) { if (object instanceof GregorianCalendar == false) { throw new RuntimeException("Unable to convert calendar as it is not a GregorianCalendar"); } GregorianCalendar cal = (GregorianCalendar) object; SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); f.setCalendar(cal); String str = f.format(cal.getTime()); return str.substring(0, 26) + ":" + str.substring(26) + "[" + cal.getTimeZone().getID() + "]"; } @Override public Object convertFromString(Class cls, String str) { if (str.length() < 31 || str.charAt(26) != ':' || str.charAt(29) != '[' || str.charAt(str.length() - 1) != ']') { throw new IllegalArgumentException("Unable to parse date: " + str); } TimeZone zone = TimeZone.getTimeZone(str.substring(30, str.length() - 1)); str = str.substring(0, 26) + str.substring(27, 29); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); GregorianCalendar cal = new GregorianCalendar(zone); cal.setTimeInMillis(0); f.setCalendar(cal); try { f.parseObject(str); return f.getCalendar(); } catch (ParseException ex) { throw new RuntimeException(ex); } } }, ; /** The type. */ private Class type; /** * Creates an enum. * @param type the type, not null */ JDKStringConverter(Class type) { this.type = type; } /** * Gets the type of the converter. * @return the type, not null */ Class getType() { return type; } /** * Gets the type of the converter. * @return the type, not null */ @Override public Class getEffectiveType() { return type; } //----------------------------------------------------------------------- @Override public String convertToString(Object object) { return object.toString(); } //----------------------------------------------------------------------- private static String base64Str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; private static char[] base64Array = base64Str.toCharArray(); private static final int MASK_8BIT = 0xff; private static final int MASK_6BIT = 0x3f; private static String printBase64Binary(byte[] array) { int len = array.length; char[] buf = new char[((len + 2) / 3) * 4]; int pos = 0; for (int i = 0; i < len; i += 3) { int remaining = len - i; if (remaining >= 3) { int bits = (array[i] & MASK_8BIT) << 16 | (array[i + 1] & MASK_8BIT) << 8 | (array[i + 2] & MASK_8BIT); buf[pos++] = base64Array[(bits >>> 18) & MASK_6BIT]; buf[pos++] = base64Array[(bits >>> 12) & MASK_6BIT]; buf[pos++] = base64Array[(bits >>> 6) & MASK_6BIT]; buf[pos++] = base64Array[bits & MASK_6BIT]; } else if (remaining == 2) { int bits = (array[i] & MASK_8BIT) << 16 | (array[i + 1] & MASK_8BIT) << 8; buf[pos++] = base64Array[(bits >>> 18) & MASK_6BIT]; buf[pos++] = base64Array[(bits >>> 12) & MASK_6BIT]; buf[pos++] = base64Array[(bits >>> 6) & MASK_6BIT]; buf[pos++] = '='; } else { int bits = (array[i] & MASK_8BIT) << 16; buf[pos++] = base64Array[(bits >>> 18) & MASK_6BIT]; buf[pos++] = base64Array[(bits >>> 12) & MASK_6BIT]; buf[pos++] = '='; buf[pos++] = '='; } } return new String(buf); } private static byte[] parseBase64Binary(String str) { // strict parser, must have length divisble by 4 if (str.length() % 4 != 0) { throw new IllegalArgumentException("Invalid Base64 string"); } // base64Str has 65 characters, with '=' at the end which is masked away int parsedLen = (str.length() * 3) / 4; byte[] decoded = new byte[parsedLen]; char[] inChars = str.toCharArray(); int pos = 0; for (int i = 0; i < inChars.length; ) { int bits = (base64Str.indexOf(inChars[i++]) & MASK_6BIT) << 18 | (base64Str.indexOf(inChars[i++]) & MASK_6BIT) << 12 | (base64Str.indexOf(inChars[i++]) & MASK_6BIT) << 6 | (base64Str.indexOf(inChars[i++]) & MASK_6BIT); decoded[pos++] = (byte) ((bits >>> 16) & MASK_8BIT); decoded[pos++] = (byte) ((bits >>> 8) & MASK_8BIT); decoded[pos++] = (byte) (bits & MASK_8BIT); } // fixup avoiding Arrays.copyRange if (str.endsWith("==")) { byte[] result = new byte[parsedLen - 2]; System.arraycopy(decoded, 0, result, 0, parsedLen - 2); return result; } else if (str.endsWith("=")) { byte[] result = new byte[parsedLen - 1]; System.arraycopy(decoded, 0, result, 0, parsedLen - 1); return result; } return decoded; } } joda-convert-1.8.1/src/main/java/org/joda/convert/TypeTokenStringConverter.java0000664000175000017500000000304312603461407027135 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import com.google.common.reflect.TypeToken; /** * Parse the string format of Guava TypeToken. *

* This is loaded by reflection only when Guava is on the classpath. * It relies on internal methods in Guava that could change in any release. *

* This parser is incomplete, but handles common cases. * It does not handle union types or multi-dimensional arrays. */ final class TypeTokenStringConverter extends AbstractTypeStringConverter implements TypedStringConverter> { public TypeTokenStringConverter() { } @Override public String convertToString(TypeToken object) { return object.toString(); } @Override public TypeToken convertFromString(Class> cls, String str) { return TypeToken.of(parse(str)); } @Override public Class getEffectiveType() { return TypeToken.class; } } joda-convert-1.8.1/src/main/java/org/joda/convert/EnumStringConverterFactory.java0000664000175000017500000000531512603461407027453 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Factory for {@code StringConverter} looking up enums. *

* This class is immutable and thread-safe. * * @since 1.7 */ final class EnumStringConverterFactory implements StringConverterFactory { /** * Singleton instance. */ static final StringConverterFactory INSTANCE = new EnumStringConverterFactory(); /** * Restricted constructor. */ private EnumStringConverterFactory() { } //----------------------------------------------------------------------- /** * Finds a converter by type. * * @param cls the type to lookup, not null * @return the converter, null if not found * @throws RuntimeException (or subclass) if source code is invalid */ @Override public StringConverter findConverter(Class cls) { Class sup = cls.getSuperclass(); if (sup == Enum.class) { return new EnumStringConverter(cls); } else if (sup != null && sup.getSuperclass() == Enum.class) { return new EnumStringConverter(sup); } return null; } //----------------------------------------------------------------------- @Override public String toString() { return getClass().getSimpleName(); } //----------------------------------------------------------------------- final class EnumStringConverter implements TypedStringConverter> { private final Class effectiveType; EnumStringConverter(Class effectiveType) { this.effectiveType = effectiveType; } @Override public String convertToString(Enum en) { return en.name(); // avoid toString() as that can be overridden } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Enum convertFromString(Class> cls, String str) { return RenameHandler.INSTANCE.lookupEnum((Class) cls, str); } @Override public Class getEffectiveType() { return effectiveType; } } } joda-convert-1.8.1/src/main/java/org/joda/convert/TypeStringConverter.java0000664000175000017500000000303512603461407026135 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.reflect.Type; import com.google.common.reflect.TypeToken; /** * Parse the string format of Type via Guava TypeToken. *

* This is loaded by reflection only when Guava is on the classpath. * It relies on internal methods in Guava that could change in any release. *

* This parser is incomplete, but handles common cases. * It does not handle union types or multi-dimensional arrays. */ final class TypeStringConverter extends AbstractTypeStringConverter implements TypedStringConverter { public TypeStringConverter() { } @Override public String convertToString(Type object) { return TypeToken.of(object).toString(); } @Override public Type convertFromString(Class cls, String str) { return parse(str); } @Override public Class getEffectiveType() { return Type.class; } } joda-convert-1.8.1/src/main/java/org/joda/convert/ToString.java0000664000175000017500000000265012603461407023710 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used to mark a method as being suitable for converting an * object to a standard format {@code String}. *

* This annotation should be applied to one method on a class. * The method must not be static. It must take no parameters and return a {@code String}. * The string format must be able to be parsed by the matching @FromString on * the same class. The format should be human readable and an industry standard * where possible, for example ISO-8601 for dates and times. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ToString { } joda-convert-1.8.1/src/main/java/org/joda/convert/StringConverter.java0000664000175000017500000000177012603461407025277 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Interface defining conversion to and from a {@code String}. *

* StringConverter is an interface and must be implemented with care. * Implementations must be immutable and thread-safe. * * @param the type of the converter */ public interface StringConverter extends ToStringConverter, FromStringConverter { } joda-convert-1.8.1/src/main/java/org/joda/convert/AbstractTypeStringConverter.java0000664000175000017500000001476612603461407027636 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import com.google.common.collect.ImmutableMap; /** * Parse the string format of Guava TypeToken. *

* This is loaded by reflection only when Guava is on the classpath. * It relies on internal methods in Guava that could change in any release. *

* This parser is incomplete, but handles common cases. * It does not handle union types or multi-dimensional arrays. */ abstract class AbstractTypeStringConverter { // extends private static final String EXTENDS = "? extends "; // super private static final String SUPER = "? super "; // primitive types private static final ImmutableMap> PRIMITIVES = ImmutableMap.>builder() .put("byte", byte.class) .put("short", short.class) .put("int", int.class) .put("long", long.class) .put("boolean", boolean.class) .put("char", char.class) .put("float", float.class) .put("double", double.class) .build(); private static final Method NEW_PARAM_TYPE; private static final Method EXTENDS_TYPE; private static final Method SUPER_TYPE; static { try { Class typesClass = RenameHandler.INSTANCE.loadType("com.google.common.reflect.Types"); Method newParam = typesClass.getDeclaredMethod("newParameterizedType", Class.class, Type[].class); newParam.setAccessible(true); NEW_PARAM_TYPE = newParam; Method extendsType = typesClass.getDeclaredMethod("subtypeOf", Type.class); extendsType.setAccessible(true); EXTENDS_TYPE = extendsType; Method superType = typesClass.getDeclaredMethod("supertypeOf", Type.class); superType.setAccessible(true); SUPER_TYPE = superType; } catch (Exception ex) { throw new RuntimeException(ex); } } //----------------------------------------------------------------------- // constructor AbstractTypeStringConverter() { } //----------------------------------------------------------------------- /** * Parses the TypeToken string format. * * @param str the string * @return the token */ static Type parse(String str) { try { return doParse(str); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } } // parse an element private static Type doParse(String str) throws Exception { Class token = PRIMITIVES.get(str); if (token != null) { return token; } int first = str.indexOf('<'); if (first < 0) { return RenameHandler.INSTANCE.loadType(str); } int last = str.lastIndexOf('>'); String baseStr = str.substring(0, first); Class base = RenameHandler.INSTANCE.loadType(baseStr); String argsStr = str.substring(first + 1, last); List splitArgs = split(argsStr); List types = new ArrayList(); for (String splitArg : splitArgs) { Type argType; if (splitArg.startsWith(EXTENDS)) { String remainder = splitArg.substring(EXTENDS.length()); argType = wildExtendsType(doParse(remainder)); } else if (splitArg.startsWith(SUPER)) { String remainder = splitArg.substring(SUPER.length()); argType = wildSuperType(doParse(remainder)); } else if (splitArg.equals("?")) { argType = wildExtendsType(Object.class); } else if (splitArg.endsWith("[]")) { String componentStr = splitArg.substring(0, splitArg.length() - 2); Class componentCls = RenameHandler.INSTANCE.loadType(componentStr); argType = Array.newInstance(componentCls, 0).getClass(); } else if (splitArg.startsWith("[L") && splitArg.endsWith(";")) { String componentStr = splitArg.substring(2, splitArg.length() - 1); Class componentCls = RenameHandler.INSTANCE.loadType(componentStr); argType = Array.newInstance(componentCls, 0).getClass(); } else { argType = doParse(splitArg); } types.add(argType); } return newParameterizedType(base, types.toArray(new Type[types.size()])); } // split by comma, handling nested generified types private static List split(String str) { List result = new ArrayList(); int genericCount = 0; int startPos = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ',' && genericCount == 0) { result.add(str.substring(startPos, i).trim()); startPos = i + 1; } else if (str.charAt(i) == '<') { genericCount++; } else if (str.charAt(i) == '>') { genericCount--; } } result.add(str.substring(startPos).trim()); return result; } // create a type representing "? extends X" private static Type wildExtendsType(Type bound) throws Exception { return (Type) EXTENDS_TYPE.invoke(null, bound); } // create a type representing "? super X" private static Type wildSuperType(Type bound) throws Exception { return (Type) SUPER_TYPE.invoke(null, bound); } // create a type representing "base" private static ParameterizedType newParameterizedType(final Class base, Type... args) throws Exception { return (ParameterizedType) NEW_PARAM_TYPE.invoke(null, base, args); } } joda-convert-1.8.1/src/main/java/org/joda/convert/MethodConstructorStringConverter.java0000664000175000017500000000702212603461407030702 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * Conversion to and from a string using a toString method and a fromString constructor. *

* The toString method must meet the following signature:
* {@code String anyName()} on Class T. *

* The fromString constructor must take a single {@code String} parameter. *

* MethodConstructorStringConverter is thread-safe and immutable. * * @param the type of the converter */ final class MethodConstructorStringConverter extends ReflectionStringConverter { /** Conversion from a string. */ private final Constructor fromString; /** * Creates an instance using a method and a constructor. * @param cls the class this converts for, not null * @param toString the toString method, not null * @param fromString the fromString method, not null * @throws RuntimeException (or subclass) if the method signatures are invalid */ MethodConstructorStringConverter(Class cls, Method toString, Constructor fromString) { super(cls, toString); if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers()) || cls.isLocalClass() || cls.isMemberClass()) { throw new IllegalArgumentException("FromString constructor must be on an instantiable class: " + fromString); } if (fromString.getDeclaringClass() != cls) { throw new IllegalStateException("FromString constructor must be defined on specified class: " + fromString); } this.fromString = fromString; } //----------------------------------------------------------------------- /** * Converts the {@code String} to an object. * @param cls the class to convert to, not null * @param str the string to convert, not null * @return the converted object, may be null but generally not */ @Override public T convertFromString(Class cls, String str) { try { return fromString.newInstance(str); } catch (IllegalAccessException ex) { throw new IllegalStateException("Constructor is not accessible: " + fromString); } catch (InstantiationException ex) { throw new IllegalStateException("Constructor is not valid: " + fromString); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new RuntimeException(ex.getMessage(), ex.getCause()); } } //------------------------------------------------------------------------- @Override public Class getEffectiveType() { return fromString.getDeclaringClass(); } } joda-convert-1.8.1/src/main/java/org/joda/convert/TypedAdapter.java0000664000175000017500000000344612603461407024531 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Adapts {@code StringConverter} to {@code TypedStringConverter}. * * @param the type of the converter * @since 1.7 */ final class TypedAdapter implements TypedStringConverter { private final StringConverter conv; private final Class effectiveType; static TypedStringConverter adapt(final Class cls, StringConverter converter) { if (converter instanceof TypedStringConverter) { return (TypedStringConverter) converter; } else { return new TypedAdapter(converter, cls); } } private TypedAdapter(StringConverter conv, Class effectiveType) { this.conv = conv; this.effectiveType = effectiveType; } @Override public String convertToString(T object) { return conv.convertToString(object); } @Override public T convertFromString(Class cls, String str) { return conv.convertFromString(cls, str); } @Override public Class getEffectiveType() { return effectiveType; } @Override public String toString() { return "TypedAdapter:" + conv.toString(); } } joda-convert-1.8.1/src/main/java/org/joda/convert/MethodsStringConverter.java0000664000175000017500000000754612603461407026632 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * Conversion to and from a string using two methods. *

* The toString method must meet the following signature:
* {@code String anyName()} on Class T. *

* The fromString method must meet the following signature:
* {@code static T anyName(String)} on any class. *

* MethodsStringConverter is thread-safe and immutable. * * @param the type of the converter */ final class MethodsStringConverter extends ReflectionStringConverter { /** Conversion from a string. */ private final Method fromString; /** Effective type. */ private final Class effectiveType; /** * Creates an instance using two methods. * @param cls the class this converts for, not null * @param toString the toString method, not null * @param fromString the fromString method, not null * @throws RuntimeException (or subclass) if the method signatures are invalid */ MethodsStringConverter(Class cls, Method toString, Method fromString, Class effectiveType) { super(cls, toString); if (Modifier.isStatic(fromString.getModifiers()) == false) { throw new IllegalStateException("FromString method must be static: " + fromString); } if (fromString.getParameterTypes().length != 1) { throw new IllegalStateException("FromString method must have one parameter: " + fromString); } Class param = fromString.getParameterTypes()[0]; if (param != String.class && param != CharSequence.class) { throw new IllegalStateException("FromString method must take a String or CharSequence: " + fromString); } if (fromString.getReturnType().isAssignableFrom(cls) == false && cls.isAssignableFrom(fromString.getReturnType()) == false) { throw new IllegalStateException("FromString method must return specified class or a supertype: " + fromString); } this.fromString = fromString; this.effectiveType = effectiveType; } //----------------------------------------------------------------------- /** * Converts the {@code String} to an object. * @param cls the class to convert to, not null * @param str the string to convert, not null * @return the converted object, may be null but generally not */ @Override public T convertFromString(Class cls, String str) { try { return cls.cast(fromString.invoke(null, str)); } catch (IllegalAccessException ex) { throw new IllegalStateException("Method is not accessible: " + fromString); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new RuntimeException(ex.getMessage(), ex.getCause()); } } //------------------------------------------------------------------------- @Override public Class getEffectiveType() { return effectiveType; } } joda-convert-1.8.1/src/main/java/org/joda/convert/StringConvert.java0000664000175000017500000010006312603461407024743 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import org.joda.convert.factory.BooleanArrayStringConverterFactory; import org.joda.convert.factory.BooleanObjectArrayStringConverterFactory; import org.joda.convert.factory.ByteObjectArrayStringConverterFactory; import org.joda.convert.factory.CharObjectArrayStringConverterFactory; import org.joda.convert.factory.NumericArrayStringConverterFactory; import org.joda.convert.factory.NumericObjectArrayStringConverterFactory; /** * Manager for conversion to and from a {@code String}, acting as the main client interface. *

* Support is provided for conversions based on the {@link StringConverter} interface * or the {@link ToString} and {@link FromString} annotations. *

* StringConvert is thread-safe with concurrent caches. */ public final class StringConvert { /** * An immutable global instance. *

* This instance cannot be added to using {@link #register}, however annotated classes * are picked up. To register your own converters, simply create an instance of this class. */ public static final StringConvert INSTANCE = new StringConvert(); /** * The cached null object. */ private static final TypedStringConverter CACHED_NULL = new TypedStringConverter() { @Override public String convertToString(Object object) { return null; } @Override public Object convertFromString(Class cls, String str) { return null; } @Override public Class getEffectiveType() { return null; } }; /** * The list of factories. */ private final CopyOnWriteArrayList factories = new CopyOnWriteArrayList(); /** * The cache of converters. */ private final ConcurrentMap, TypedStringConverter> registered = new ConcurrentHashMap, TypedStringConverter>(); //----------------------------------------------------------------------- /** * Creates a new conversion manager including the extended standard set of converters. *

* The returned converter is a new instance that includes additional converters: *

    *
  • JDK converters *
  • {@link NumericArrayStringConverterFactory} *
  • {@link NumericObjectArrayStringConverterFactory} *
  • {@link CharObjectArrayStringConverterFactory} *
  • {@link ByteObjectArrayStringConverterFactory} *
  • {@link BooleanArrayStringConverterFactory} *
  • {@link BooleanObjectArrayStringConverterFactory} *
*

* The convert instance is mutable in a thread-safe manner. * Converters may be altered at any time, including the JDK converters. * It is strongly recommended to only alter the converters before performing * actual conversions. * * @return the new converter, not null * @since 1.5 */ public static StringConvert create() { return new StringConvert(true, NumericArrayStringConverterFactory.INSTANCE, NumericObjectArrayStringConverterFactory.INSTANCE, CharObjectArrayStringConverterFactory.INSTANCE, ByteObjectArrayStringConverterFactory.INSTANCE, BooleanArrayStringConverterFactory.INSTANCE, BooleanObjectArrayStringConverterFactory.INSTANCE); } //----------------------------------------------------------------------- /** * Creates a new conversion manager including the JDK converters. *

* The convert instance is mutable in a thread-safe manner. * Converters may be altered at any time, including the JDK converters. * It is strongly recommended to only alter the converters before performing * actual conversions. */ public StringConvert() { this(true); } /** * Creates a new conversion manager. *

* The convert instance is mutable in a thread-safe manner. * Converters may be altered at any time, including the JDK converters. * It is strongly recommended to only alter the converters before performing * actual conversions. *

* If specified, the factories will be queried in the order specified. * * @param includeJdkConverters true to include the JDK converters * @param factories optional array of factories to use, not null */ public StringConvert(boolean includeJdkConverters, StringConverterFactory... factories) { if (factories == null) { throw new IllegalArgumentException("StringConverterFactory array must not be null"); } for (int i = 0; i < factories.length; i++) { if (factories[i] == null) { throw new IllegalArgumentException("StringConverterFactory array must not contain a null element"); } } if (includeJdkConverters) { for (JDKStringConverter conv : JDKStringConverter.values()) { registered.put(conv.getType(), conv); } registered.put(Boolean.TYPE, JDKStringConverter.BOOLEAN); registered.put(Byte.TYPE, JDKStringConverter.BYTE); registered.put(Short.TYPE, JDKStringConverter.SHORT); registered.put(Integer.TYPE, JDKStringConverter.INTEGER); registered.put(Long.TYPE, JDKStringConverter.LONG); registered.put(Float.TYPE, JDKStringConverter.FLOAT); registered.put(Double.TYPE, JDKStringConverter.DOUBLE); registered.put(Character.TYPE, JDKStringConverter.CHARACTER); // Guava tryRegisterGuava(); // JDK 1.8 classes tryRegister("java.time.Instant", "parse"); tryRegister("java.time.Duration", "parse"); tryRegister("java.time.LocalDate", "parse"); tryRegister("java.time.LocalTime", "parse"); tryRegister("java.time.LocalDateTime", "parse"); tryRegister("java.time.OffsetTime", "parse"); tryRegister("java.time.OffsetDateTime", "parse"); tryRegister("java.time.ZonedDateTime", "parse"); tryRegister("java.time.Year", "parse"); tryRegister("java.time.YearMonth", "parse"); tryRegister("java.time.MonthDay", "parse"); tryRegister("java.time.Period", "parse"); tryRegister("java.time.ZoneOffset", "of"); tryRegister("java.time.ZoneId", "of"); // ThreeTen backport classes tryRegister("org.threeten.bp.Instant", "parse"); tryRegister("org.threeten.bp.Duration", "parse"); tryRegister("org.threeten.bp.LocalDate", "parse"); tryRegister("org.threeten.bp.LocalTime", "parse"); tryRegister("org.threeten.bp.LocalDateTime", "parse"); tryRegister("org.threeten.bp.OffsetTime", "parse"); tryRegister("org.threeten.bp.OffsetDateTime", "parse"); tryRegister("org.threeten.bp.ZonedDateTime", "parse"); tryRegister("org.threeten.bp.Year", "parse"); tryRegister("org.threeten.bp.YearMonth", "parse"); tryRegister("org.threeten.bp.MonthDay", "parse"); tryRegister("org.threeten.bp.Period", "parse"); tryRegister("org.threeten.bp.ZoneOffset", "of"); tryRegister("org.threeten.bp.ZoneId", "of"); // Old ThreeTen/JSR-310 classes v0.6.3 and beyond tryRegister("javax.time.Instant", "parse"); tryRegister("javax.time.Duration", "parse"); tryRegister("javax.time.calendar.LocalDate", "parse"); tryRegister("javax.time.calendar.LocalTime", "parse"); tryRegister("javax.time.calendar.LocalDateTime", "parse"); tryRegister("javax.time.calendar.OffsetDate", "parse"); tryRegister("javax.time.calendar.OffsetTime", "parse"); tryRegister("javax.time.calendar.OffsetDateTime", "parse"); tryRegister("javax.time.calendar.ZonedDateTime", "parse"); tryRegister("javax.time.calendar.Year", "parse"); tryRegister("javax.time.calendar.YearMonth", "parse"); tryRegister("javax.time.calendar.MonthDay", "parse"); tryRegister("javax.time.calendar.Period", "parse"); tryRegister("javax.time.calendar.ZoneOffset", "of"); tryRegister("javax.time.calendar.ZoneId", "of"); tryRegister("javax.time.calendar.TimeZone", "of"); } if (factories.length > 0) { this.factories.addAll(Arrays.asList(factories)); } this.factories.add(AnnotationStringConverterFactory.INSTANCE); if (includeJdkConverters) { this.factories.add(EnumStringConverterFactory.INSTANCE); } } /** * Tries to register the Guava converters class. * * @param className the class name, not null */ private void tryRegisterGuava() { try { RenameHandler.INSTANCE.loadType("com.google.common.reflect.Types"); @SuppressWarnings("unchecked") Class cls = (Class>) RenameHandler.INSTANCE .loadType("org.joda.convert.TypeTokenStringConverter"); TypedStringConverter conv = (TypedStringConverter) cls.newInstance(); registered.put(conv.getEffectiveType(), conv); @SuppressWarnings("unchecked") Class cls2 = (Class>) RenameHandler.INSTANCE .loadType("org.joda.convert.TypeStringConverter"); TypedStringConverter conv2 = (TypedStringConverter) cls2.newInstance(); registered.put(conv2.getEffectiveType(), conv2); } catch (Throwable ex) { // ignore } } /** * Tries to register a class using the standard toString/parse pattern. * * @param className the class name, not null */ private void tryRegister(String className, String fromStringMethodName) { try { Class cls = RenameHandler.INSTANCE.lookupType(className); registerMethods(cls, "toString", fromStringMethodName); } catch (Throwable ex) { // ignore } } //----------------------------------------------------------------------- /** * Converts the specified object to a {@code String}. *

* This uses {@link #findConverter} to provide the converter. * * @param object the object to convert, null returns null * @return the converted string, may be null * @throws RuntimeException (or subclass) if unable to convert */ public String convertToString(Object object) { if (object == null) { return null; } Class cls = object.getClass(); StringConverter conv = findConverterNoGenerics(cls); return conv.convertToString(object); } /** * Converts the specified object to a {@code String}. *

* This uses {@link #findConverter} to provide the converter. * The class can be provided to select a more specific converter. * * @param cls the class to convert from, not null * @param object the object to convert, null returns null * @return the converted string, may be null * @throws RuntimeException (or subclass) if unable to convert */ public String convertToString(Class cls, Object object) { if (object == null) { return null; } StringConverter conv = findConverterNoGenerics(cls); return conv.convertToString(object); } /** * Converts the specified object from a {@code String}. *

* This uses {@link #findConverter} to provide the converter. * * @param the type to convert to * @param cls the class to convert to, not null * @param str the string to convert, null returns null * @return the converted object, may be null * @throws RuntimeException (or subclass) if unable to convert */ public T convertFromString(Class cls, String str) { if (str == null) { return null; } StringConverter conv = findConverter(cls); return conv.convertFromString(cls, str); } //----------------------------------------------------------------------- /** * Checks if a suitable converter exists for the type. *

* This performs the same checks as the {@code findConverter} methods. * Calling this before {@code findConverter} will cache the converter. *

* Note that all exceptions, including developer errors are caught and hidden. * * @param cls the class to find a converter for, null returns false * @return true if convertible * @since 1.5 */ public boolean isConvertible(final Class cls) { try { return cls != null && findConverterQuiet(cls) != null; } catch (RuntimeException ex) { return false; } } /** * Finds a suitable converter for the type. *

* This returns an instance of {@code StringConverter} for the specified class. * This is designed for user code where the {@code Class} object generics is known. *

* The search algorithm first searches the registered converters in the * class hierarchy and immediate parent interfaces. * It then searches for {@code ToString} and {@code FromString} annotations on the * specified class, class hierarchy or immediate parent interfaces. * Finally, it handles {@code Enum} instances. * * @param the type of the converter * @param cls the class to find a converter for, not null * @return the converter, not null * @throws RuntimeException (or subclass) if no converter found */ public StringConverter findConverter(final Class cls) { return findTypedConverter(cls); } /** * Finds a suitable converter for the type with open generics. *

* This returns an instance of {@code StringConverter} for the specified class. * This is designed for framework usage where the {@code Class} object generics are unknown'?'. * The returned type is declared with {@code Object} instead of '?' to * allow the {@link ToStringConverter} to be invoked. *

* The search algorithm first searches the registered converters in the * class hierarchy and immediate parent interfaces. * It then searches for {@code ToString} and {@code FromString} annotations on the * specified class, class hierarchy or immediate parent interfaces. * Finally, it handles {@code Enum} instances. * * @param cls the class to find a converter for, not null * @return the converter, using {@code Object} to avoid generics, not null * @throws RuntimeException (or subclass) if no converter found * @since 1.5 */ public StringConverter findConverterNoGenerics(final Class cls) { return findTypedConverterNoGenerics(cls); } /** * Finds a suitable converter for the type. *

* This returns an instance of {@code TypedStringConverter} for the specified class. * This is designed for user code where the {@code Class} object generics is known. *

* The search algorithm first searches the registered converters in the * class hierarchy and immediate parent interfaces. * It then searches for {@code ToString} and {@code FromString} annotations on the * specified class, class hierarchy or immediate parent interfaces. * Finally, it handles {@code Enum} instances. *

* The returned converter may be queried for the effective type of the conversion. * This can be used to find the best type to send in a serialized form. *

* NOTE: Changing the method return type of {@link #findConverter(Class)} * would be source compatible but not binary compatible. As this is a low-level * library, binary compatibility is important, hence the addition of this method. * * @param the type of the converter * @param cls the class to find a converter for, not null * @return the converter, not null * @throws RuntimeException (or subclass) if no converter found * @since 1.7 */ public TypedStringConverter findTypedConverter(final Class cls) { TypedStringConverter conv = findConverterQuiet(cls); if (conv == null) { throw new IllegalStateException("No registered converter found: " + cls); } return conv; } /** * Finds a suitable converter for the type with open generics. *

* This returns an instance of {@code TypedStringConverter} for the specified class. * This is designed for framework usage where the {@code Class} object generics are unknown'?'. * The returned type is declared with {@code Object} instead of '?' to * allow the {@link ToStringConverter} to be invoked. *

* The search algorithm first searches the registered converters in the * class hierarchy and immediate parent interfaces. * It then searches for {@code ToString} and {@code FromString} annotations on the * specified class, class hierarchy or immediate parent interfaces. * Finally, it handles {@code Enum} instances. *

* The returned converter may be queried for the effective type of the conversion. * This can be used to find the best type to send in a serialized form. *

* NOTE: Changing the method return type of {@link #findConverterNoGenerics(Class)} * would be source compatible but not binary compatible. As this is a low-level * library, binary compatibility is important, hence the addition of this method. * * @param cls the class to find a converter for, not null * @return the converter, using {@code Object} to avoid generics, not null * @throws RuntimeException (or subclass) if no converter found * @since 1.7 */ @SuppressWarnings("unchecked") public TypedStringConverter findTypedConverterNoGenerics(final Class cls) { TypedStringConverter conv = (TypedStringConverter) findConverterQuiet(cls); if (conv == null) { throw new IllegalStateException("No registered converter found: " + cls); } return conv; } /** * Finds a converter searching registered and annotated. * * @param the type of the converter * @param cls the class to find a method for, not null * @return the converter, null if no converter * @throws RuntimeException if invalid */ @SuppressWarnings("unchecked") private TypedStringConverter findConverterQuiet(final Class cls) { if (cls == null) { throw new IllegalArgumentException("Class must not be null"); } TypedStringConverter conv = (TypedStringConverter) registered.get(cls); if (conv == CACHED_NULL) { return null; } if (conv == null) { try { conv = findAnyConverter(cls); } catch (RuntimeException ex) { registered.putIfAbsent(cls, CACHED_NULL); throw ex; } if (conv == null) { registered.putIfAbsent(cls, CACHED_NULL); return null; } registered.putIfAbsent(cls, conv); } return conv; } /** * Finds a converter searching registered and annotated. * * @param the type of the converter * @param cls the class to find a method for, not null * @return the converter, not null * @throws RuntimeException if invalid */ @SuppressWarnings("unchecked") private TypedStringConverter findAnyConverter(final Class cls) { TypedStringConverter conv = null; // check for registered on superclass Class loopCls = cls.getSuperclass(); while (loopCls != null && conv == null) { conv = (TypedStringConverter) registered.get(loopCls); if (conv != null && conv != CACHED_NULL) { return conv; } loopCls = loopCls.getSuperclass(); } // check for registered on interfaces for (Class loopIfc : cls.getInterfaces()) { conv = (TypedStringConverter) registered.get(loopIfc); if (conv != null && conv != CACHED_NULL) { return conv; } } // check factories for (StringConverterFactory factory : factories) { StringConverter factoryConv = (StringConverter) factory.findConverter(cls); if (factoryConv != null) { return TypedAdapter.adapt(cls, factoryConv); } } return null; } //----------------------------------------------------------------------- /** * Registers a converter factory. *

* This will be registered ahead of all existing factories. *

* No new factories may be registered for the global singleton. * * @param factory the converter factory, not null * @throws IllegalStateException if trying to alter the global singleton * @since 1.5 */ public void registerFactory(final StringConverterFactory factory) { if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } if (this == INSTANCE) { throw new IllegalStateException("Global singleton cannot be extended"); } factories.add(0, factory); } //----------------------------------------------------------------------- /** * Registers a converter for a specific type. *

* The converter will be used for subclasses unless overidden. *

* No new converters may be registered for the global singleton. * * @param the type of the converter * @param cls the class to register a converter for, not null * @param converter the String converter, not null * @throws IllegalArgumentException if the class or converter are null * @throws IllegalStateException if trying to alter the global singleton */ public void register(final Class cls, StringConverter converter) { if (cls == null) { throw new IllegalArgumentException("Class must not be null"); } if (converter == null) { throw new IllegalArgumentException("StringConverter must not be null"); } if (this == INSTANCE) { throw new IllegalStateException("Global singleton cannot be extended"); } registered.put(cls, TypedAdapter.adapt(cls, converter)); } /** * Registers a converter for a specific type using two separate converters. *

* This method registers a converter for the specified class. * It is primarily intended for use with JDK 1.8 method references or lambdas: *

     *  sc.register(Distance.class, Distance::toString, Distance::parse);
     * 
* The converter will be used for subclasses unless overidden. *

* No new converters may be registered for the global singleton. * * @param the type of the converter * @param cls the class to register a converter for, not null * @param toString the to String converter, typically a method reference, not null * @param fromString the from String converter, typically a method reference, not null * @throws IllegalArgumentException if the class or converter are null * @throws IllegalStateException if trying to alter the global singleton * @since 1.3 */ public void register(final Class cls, final ToStringConverter toString, final FromStringConverter fromString) { if (fromString == null || toString == null) { throw new IllegalArgumentException("Converters must not be null"); } register(cls, new TypedStringConverter() { @Override public String convertToString(T object) { return toString.convertToString(object); } @Override public T convertFromString(Class cls, String str) { return fromString.convertFromString(cls, str); } @Override public Class getEffectiveType() { return cls; } }); } /** * Registers a converter for a specific type by method names. *

* This method allows the converter to be used when the target class cannot have annotations added. * The two method names must obey the same rules as defined by the annotations * {@link ToString} and {@link FromString}. * The converter will be used for subclasses unless overidden. *

* No new converters may be registered for the global singleton. *

* For example, {@code convert.registerMethods(Distance.class, "toString", "parse");} * * @param the type of the converter * @param cls the class to register a converter for, not null * @param toStringMethodName the name of the method converting to a string, not null * @param fromStringMethodName the name of the method converting from a string, not null * @throws IllegalArgumentException if the class or method name are null or invalid * @throws IllegalStateException if trying to alter the global singleton */ public void registerMethods(final Class cls, String toStringMethodName, String fromStringMethodName) { if (cls == null) { throw new IllegalArgumentException("Class must not be null"); } if (toStringMethodName == null || fromStringMethodName == null) { throw new IllegalArgumentException("Method names must not be null"); } if (this == INSTANCE) { throw new IllegalStateException("Global singleton cannot be extended"); } Method toString = findToStringMethod(cls, toStringMethodName); Method fromString = findFromStringMethod(cls, fromStringMethodName); MethodsStringConverter converter = new MethodsStringConverter(cls, toString, fromString, cls); registered.putIfAbsent(cls, converter); } /** * Registers a converter for a specific type by method and constructor. *

* This method allows the converter to be used when the target class cannot have annotations added. * The two method name and constructor must obey the same rules as defined by the annotations * {@link ToString} and {@link FromString}. * The converter will be used for subclasses unless overidden. *

* No new converters may be registered for the global singleton. *

* For example, {@code convert.registerMethodConstructor(Distance.class, "toString");} * * @param the type of the converter * @param cls the class to register a converter for, not null * @param toStringMethodName the name of the method converting to a string, not null * @throws IllegalArgumentException if the class or method name are null or invalid * @throws IllegalStateException if trying to alter the global singleton */ public void registerMethodConstructor(final Class cls, String toStringMethodName) { if (cls == null) { throw new IllegalArgumentException("Class must not be null"); } if (toStringMethodName == null) { throw new IllegalArgumentException("Method name must not be null"); } if (this == INSTANCE) { throw new IllegalStateException("Global singleton cannot be extended"); } Method toString = findToStringMethod(cls, toStringMethodName); Constructor fromString = findFromStringConstructorByType(cls); MethodConstructorStringConverter converter = new MethodConstructorStringConverter(cls, toString, fromString); registered.putIfAbsent(cls, converter); } /** * Finds the conversion method. * * @param cls the class to find a method for, not null * @param methodName the name of the method to find, not null * @return the method to call, null means use {@code toString} */ private Method findToStringMethod(Class cls, String methodName) { Method m; try { m = cls.getMethod(methodName); } catch (NoSuchMethodException ex) { throw new IllegalArgumentException(ex); } if (Modifier.isStatic(m.getModifiers())) { throw new IllegalArgumentException("Method must not be static: " + methodName); } return m; } /** * Finds the conversion method. * * @param cls the class to find a method for, not null * @param methodName the name of the method to find, not null * @return the method to call, null means use {@code toString} */ private Method findFromStringMethod(Class cls, String methodName) { Method m; try { m = cls.getMethod(methodName, String.class); } catch (NoSuchMethodException ex) { try { m = cls.getMethod(methodName, CharSequence.class); } catch (NoSuchMethodException ex2) { throw new IllegalArgumentException("Method not found", ex2); } } if (Modifier.isStatic(m.getModifiers()) == false) { throw new IllegalArgumentException("Method must be static: " + methodName); } return m; } /** * Finds the conversion method. * * @param the type of the converter * @param cls the class to find a method for, not null * @return the method to call, null means use {@code toString} */ private Constructor findFromStringConstructorByType(Class cls) { try { return cls.getDeclaredConstructor(String.class); } catch (NoSuchMethodException ex) { try { return cls.getDeclaredConstructor(CharSequence.class); } catch (NoSuchMethodException ex2) { throw new IllegalArgumentException("Constructor not found", ex2); } } } //----------------------------------------------------------------------- /** * Returns a simple string representation of the object. * * @return the string representation, never null */ @Override public String toString() { return getClass().getSimpleName(); } } joda-convert-1.8.1/src/main/java/org/joda/convert/FromString.java0000664000175000017500000000275212603461407024234 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used to mark a method or constructor as being suitable for converting * an object from a {@code String}. *

* When applying to a method, this annotation should be applied once per class. * The method must be static and have one {@code String} parameter with a * return type of the type that the method is implemented on. * For example, {@link Integer#parseInt(String)}. *

* When applying to a constructor, this annotation should be applied to the constructor * that takes one {@code String} parameter. */ @Target({ElementType.METHOD, ElementType.CONSTRUCTOR }) @Retention(RetentionPolicy.RUNTIME) public @interface FromString { } joda-convert-1.8.1/src/main/java/org/joda/convert/factory/0000775000175000017500000000000012603461407022740 5ustar ebourgebourgjoda-convert-1.8.1/src/main/java/org/joda/convert/factory/ByteObjectArrayStringConverterFactory.java0000664000175000017500000001000612603461407033240 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.factory; import org.joda.convert.StringConverter; import org.joda.convert.StringConverterFactory; import org.joda.convert.TypedStringConverter; /** * Factory for {@code StringConverter} providing support for Byte object array * as a sequence of two letter hex codes for each byte plus '--' for null. *

* This is intended as a human readable format, not a compact format. *

* To use, simply register the instance with a {@code StringConvert} instance. *

* This class is immutable and thread-safe. * * @since 1.5 */ public final class ByteObjectArrayStringConverterFactory implements StringConverterFactory { /** * Singleton instance. */ public static final StringConverterFactory INSTANCE = new ByteObjectArrayStringConverterFactory(); /** * Restricted constructor. */ private ByteObjectArrayStringConverterFactory() { } //----------------------------------------------------------------------- /** * Finds a converter by type. * * @param cls the type to lookup, not null * @return the converter, null if not found * @throws RuntimeException (or subclass) if source code is invalid */ @Override public StringConverter findConverter(Class cls) { if (cls == Byte[].class) { return ByteArrayStringConverter.INSTANCE; } return null; } //----------------------------------------------------------------------- @Override public String toString() { return getClass().getSimpleName(); } //----------------------------------------------------------------------- enum ByteArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(Byte[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length); for (int i = 0; i < array.length; i++) { if (array[i] == null) { buf.append('-').append('-'); } else { int b = array[i].byteValue(); buf.append(HEX.charAt((b & 0xF0) >>> 4)).append(HEX.charAt(b & 0x0F)); } } return buf.toString(); } @Override public Byte[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } if (str.length() % 2 == 1) { throw new IllegalArgumentException("Invalid Byte[] string"); } Byte[] array = new Byte[str.length() / 2]; for (int i = 0; i < array.length; i++) { String in = str.substring(i * 2, i * 2 + 2); if (in.equals("--")) { array[i] = null; } else { array[i] = (byte) Integer.parseInt(in, 16); } } return array; } @Override public Class getEffectiveType() { return Byte[].class; } }; private static final Byte[] EMPTY = new Byte[0]; private static final String HEX = "0123456789ABCDEF"; } } ././@LongLink0000644000000000000000000000015000000000000011577 Lustar rootrootjoda-convert-1.8.1/src/main/java/org/joda/convert/factory/BooleanObjectArrayStringConverterFactory.javajoda-convert-1.8.1/src/main/java/org/joda/convert/factory/BooleanObjectArrayStringConverterFactory.j0000664000175000017500000000753312603461407033237 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.factory; import org.joda.convert.StringConverter; import org.joda.convert.StringConverterFactory; import org.joda.convert.TypedStringConverter; /** * Factory for {@code StringConverter} providing support for Boolean object array * as a sequence of 'T', 'F' and '-' for null. *

* This is intended as a human readable format, not a compact format. *

* To use, simply register the instance with a {@code StringConvert} instance. *

* This class is immutable and thread-safe. * * @since 1.5 */ public final class BooleanObjectArrayStringConverterFactory implements StringConverterFactory { /** * Singleton instance. */ public static final StringConverterFactory INSTANCE = new BooleanObjectArrayStringConverterFactory(); /** * Restricted constructor. */ private BooleanObjectArrayStringConverterFactory() { } //----------------------------------------------------------------------- /** * Finds a converter by type. * * @param cls the type to lookup, not null * @return the converter, null if not found * @throws RuntimeException (or subclass) if source code is invalid */ @Override public StringConverter findConverter(Class cls) { if (cls == Boolean[].class) { return BooleanArrayStringConverter.INSTANCE; } return null; } //----------------------------------------------------------------------- @Override public String toString() { return getClass().getSimpleName(); } //----------------------------------------------------------------------- enum BooleanArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(Boolean[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length); for (int i = 0; i < array.length; i++) { buf.append(array[i] == null ? '-' : (array[i].booleanValue() ? 'T' : 'F')); } return buf.toString(); } @Override public Boolean[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } Boolean[] array = new Boolean[str.length()]; for (int i = 0; i < array.length; i++) { char ch = str.charAt(i); if (ch == 'T') { array[i] = Boolean.TRUE; } else if (ch == 'F') { array[i] = Boolean.FALSE; } else if (ch == '-') { array[i] = null; } else { throw new IllegalArgumentException("Invalid Boolean[] string, must consist only of 'T', 'F' and '-'"); } } return array; } @Override public Class getEffectiveType() { return Boolean[].class; } }; private static final Boolean[] EMPTY = new Boolean[0]; } } ././@LongLink0000644000000000000000000000015000000000000011577 Lustar rootrootjoda-convert-1.8.1/src/main/java/org/joda/convert/factory/NumericObjectArrayStringConverterFactory.javajoda-convert-1.8.1/src/main/java/org/joda/convert/factory/NumericObjectArrayStringConverterFactory.j0000664000175000017500000002360012603461407033253 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.factory; import java.util.regex.Pattern; import org.joda.convert.StringConverter; import org.joda.convert.StringConverterFactory; import org.joda.convert.TypedStringConverter; /** * Factory for {@code StringConverter} providing support for numeric object arrays * as a comma separated list, using '-' for null. *

* To use, simply register the instance with a {@code StringConvert} instance. *

* This class is immutable and thread-safe. * * @since 1.5 */ public final class NumericObjectArrayStringConverterFactory implements StringConverterFactory { /** * Singleton instance. */ public static final StringConverterFactory INSTANCE = new NumericObjectArrayStringConverterFactory(); /** * Delimiter to find. */ static final Pattern DELIMITER = Pattern.compile("[,]"); /** * Restricted constructor. */ private NumericObjectArrayStringConverterFactory() { } //----------------------------------------------------------------------- /** * Finds a converter by type. * * @param cls the type to lookup, not null * @return the converter, null if not found * @throws RuntimeException (or subclass) if source code is invalid */ @Override public StringConverter findConverter(Class cls) { if (cls.isArray()) { if (cls == Long[].class) { return LongArrayStringConverter.INSTANCE; } if (cls == Integer[].class) { return IntArrayStringConverter.INSTANCE; } if (cls == Short[].class) { return ShortArrayStringConverter.INSTANCE; } if (cls == Double[].class) { return DoubleArrayStringConverter.INSTANCE; } if (cls == Float[].class) { return FloatArrayStringConverter.INSTANCE; } } return null; } //----------------------------------------------------------------------- @Override public String toString() { return getClass().getSimpleName(); } //----------------------------------------------------------------------- enum LongArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(Long[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 8); buf.append(array[0] != null ? array[0] : "-"); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i] != null ? array[i] : "-"); } return buf.toString(); } @Override public Long[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); Long[] array = new Long[split.length]; for (int i = 0; i < split.length; i++) { if (split[i].equals("-") == false) { array[i] = Long.parseLong(split[i]); } } return array; } @Override public Class getEffectiveType() { return Long[].class; } }; private static final Long[] EMPTY = new Long[0]; } //----------------------------------------------------------------------- enum IntArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(Integer[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 6); buf.append(array[0] != null ? array[0] : "-"); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i] != null ? array[i] : "-"); } return buf.toString(); } @Override public Integer[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); Integer[] array = new Integer[split.length]; for (int i = 0; i < split.length; i++) { if (split[i].equals("-") == false) { array[i] = Integer.parseInt(split[i]); } } return array; } @Override public Class getEffectiveType() { return Integer[].class; } }; private static final Integer[] EMPTY = new Integer[0]; } //----------------------------------------------------------------------- enum ShortArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(Short[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 3); buf.append(array[0] != null ? array[0] : "-"); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i] != null ? array[i] : "-"); } return buf.toString(); } @Override public Short[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); Short[] array = new Short[split.length]; for (int i = 0; i < split.length; i++) { if (split[i].equals("-") == false) { array[i] = Short.parseShort(split[i]); } } return array; } @Override public Class getEffectiveType() { return Short[].class; } }; private static final Short[] EMPTY = new Short[0]; } //----------------------------------------------------------------------- enum DoubleArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(Double[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 8); buf.append(array[0] != null ? array[0] : "-"); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i] != null ? array[i] : "-"); } return buf.toString(); } @Override public Double[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); Double[] array = new Double[split.length]; for (int i = 0; i < split.length; i++) { if (split[i].equals("-") == false) { array[i] = Double.parseDouble(split[i]); } } return array; } @Override public Class getEffectiveType() { return Double[].class; } }; private static final Double[] EMPTY = new Double[0]; } //----------------------------------------------------------------------- enum FloatArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(Float[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 8); buf.append(array[0] != null ? array[0] : "-"); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i] != null ? array[i] : "-"); } return buf.toString(); } @Override public Float[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); Float[] array = new Float[split.length]; for (int i = 0; i < split.length; i++) { if (split[i].equals("-") == false) { array[i] = Float.parseFloat(split[i]); } } return array; } @Override public Class getEffectiveType() { return Float[].class; } }; private static final Float[] EMPTY = new Float[0]; } } joda-convert-1.8.1/src/main/java/org/joda/convert/factory/BooleanArrayStringConverterFactory.java0000664000175000017500000000725212603461407032576 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.factory; import org.joda.convert.StringConverter; import org.joda.convert.StringConverterFactory; import org.joda.convert.TypedStringConverter; /** * Factory for {@code StringConverter} providing support for primitive boolean array * as a sequence of 'T' and 'F'. *

* This is intended as a human readable format, not a compact format. *

* To use, simply register the instance with a {@code StringConvert} instance. *

* This class is immutable and thread-safe. * * @since 1.5 */ public final class BooleanArrayStringConverterFactory implements StringConverterFactory { /** * Singleton instance. */ public static final StringConverterFactory INSTANCE = new BooleanArrayStringConverterFactory(); /** * Restricted constructor. */ private BooleanArrayStringConverterFactory() { } //----------------------------------------------------------------------- /** * Finds a converter by type. * * @param cls the type to lookup, not null * @return the converter, null if not found * @throws RuntimeException (or subclass) if source code is invalid */ @Override public StringConverter findConverter(Class cls) { if (cls == boolean[].class) { return BooleanArrayStringConverter.INSTANCE; } return null; } //----------------------------------------------------------------------- @Override public String toString() { return getClass().getSimpleName(); } //----------------------------------------------------------------------- enum BooleanArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(boolean[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length); for (int i = 0; i < array.length; i++) { buf.append(array[i] ? 'T' : 'F'); } return buf.toString(); } @Override public boolean[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } boolean[] array = new boolean[str.length()]; for (int i = 0; i < array.length; i++) { char ch = str.charAt(i); if (ch == 'T') { array[i] = true; } else if (ch == 'F') { array[i] = false; } else { throw new IllegalArgumentException("Invalid boolean[] string, must consist only of 'T' and 'F'"); } } return array; } @Override public Class getEffectiveType() { return boolean[].class; } }; private static final boolean[] EMPTY = new boolean[0]; } } joda-convert-1.8.1/src/main/java/org/joda/convert/factory/CharObjectArrayStringConverterFactory.java0000664000175000017500000001113312603461407033214 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.factory; import java.util.Arrays; import java.util.regex.Pattern; import org.joda.convert.StringConverter; import org.joda.convert.StringConverterFactory; import org.joda.convert.TypedStringConverter; /** * Factory for {@code StringConverter} providing support for Character object arrays * as a string, using backslash as an escape. *

* Double backslash is a backslash. * One backslash followed by a dash is null. *

* To use, simply register the instance with a {@code StringConvert} instance. *

* This class is immutable and thread-safe. * * @since 1.5 */ public final class CharObjectArrayStringConverterFactory implements StringConverterFactory { /** * Singleton instance. */ public static final StringConverterFactory INSTANCE = new CharObjectArrayStringConverterFactory(); /** * Delimiter to find. */ static final Pattern DELIMITER = Pattern.compile("[,]"); /** * Restricted constructor. */ private CharObjectArrayStringConverterFactory() { } //----------------------------------------------------------------------- /** * Finds a converter by type. * * @param cls the type to lookup, not null * @return the converter, null if not found * @throws RuntimeException (or subclass) if source code is invalid */ @Override public StringConverter findConverter(Class cls) { if (cls == Character[].class) { return CharecterArrayStringConverter.INSTANCE; } return null; } //----------------------------------------------------------------------- @Override public String toString() { return getClass().getSimpleName(); } //----------------------------------------------------------------------- enum CharecterArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(Character[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 8); for (int i = 0; i < array.length; i++) { if (array[i] == null) { buf.append("\\-"); } else { char ch = array[i].charValue(); if (ch == '\\') { buf.append("\\\\"); } else { buf.append(ch); } } } return buf.toString(); } @Override public Character[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } Character[] array = new Character[str.length()]; int arrayPos = 0; int pos; while ((pos = str.indexOf('\\')) >= 0) { for (int i = 0; i < pos; i++) { array[arrayPos++] = str.charAt(i); } if (str.charAt(pos + 1) == '\\') { array[arrayPos++] = '\\'; } else if (str.charAt(pos + 1) == '-') { array[arrayPos++] = null; } else { throw new IllegalArgumentException("Invalid Character[] string, incorrect escape"); } str = str.substring(pos + 2); } for (int i = 0; i < str.length(); i++) { array[arrayPos++] = str.charAt(i); } return Arrays.copyOf(array, arrayPos); } @Override public Class getEffectiveType() { return Character[].class; } }; private static final Character[] EMPTY = new Character[0]; } } joda-convert-1.8.1/src/main/java/org/joda/convert/factory/NumericArrayStringConverterFactory.java0000664000175000017500000002227412603461407032622 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.factory; import java.util.regex.Pattern; import org.joda.convert.StringConverter; import org.joda.convert.StringConverterFactory; import org.joda.convert.TypedStringConverter; /** * Factory for {@code StringConverter} providing support for primitive arrays * as a comma separated list. *

* To use, simply register the instance with a {@code StringConvert} instance. *

* This class is immutable and thread-safe. * * @since 1.5 */ public final class NumericArrayStringConverterFactory implements StringConverterFactory { /** * Singleton instance. */ public static final StringConverterFactory INSTANCE = new NumericArrayStringConverterFactory(); /** * Delimiter to find. */ static final Pattern DELIMITER = Pattern.compile("[,]"); /** * Restricted constructor. */ private NumericArrayStringConverterFactory() { } //----------------------------------------------------------------------- /** * Finds a converter by type. * * @param cls the type to lookup, not null * @return the converter, null if not found * @throws RuntimeException (or subclass) if source code is invalid */ @Override public StringConverter findConverter(Class cls) { if (cls.isArray() && cls.getComponentType().isPrimitive()) { if (cls == long[].class) { return LongArrayStringConverter.INSTANCE; } if (cls == int[].class) { return IntArrayStringConverter.INSTANCE; } if (cls == short[].class) { return ShortArrayStringConverter.INSTANCE; } if (cls == double[].class) { return DoubleArrayStringConverter.INSTANCE; } if (cls == float[].class) { return FloatArrayStringConverter.INSTANCE; } } return null; } //----------------------------------------------------------------------- @Override public String toString() { return getClass().getSimpleName(); } //----------------------------------------------------------------------- enum LongArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(long[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 8); buf.append(array[0]); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i]); } return buf.toString(); } @Override public long[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); long[] array = new long[split.length]; for (int i = 0; i < split.length; i++) { array[i] = Long.parseLong(split[i]); } return array; } @Override public Class getEffectiveType() { return long[].class; } }; private static final long[] EMPTY = new long[0]; } //----------------------------------------------------------------------- enum IntArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(int[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 6); buf.append(array[0]); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i]); } return buf.toString(); } @Override public int[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); int[] array = new int[split.length]; for (int i = 0; i < split.length; i++) { array[i] = Integer.parseInt(split[i]); } return array; } @Override public Class getEffectiveType() { return int[].class; } }; private static final int[] EMPTY = new int[0]; } //----------------------------------------------------------------------- enum ShortArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(short[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 3); buf.append(array[0]); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i]); } return buf.toString(); } @Override public short[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); short[] array = new short[split.length]; for (int i = 0; i < split.length; i++) { array[i] = Short.parseShort(split[i]); } return array; } @Override public Class getEffectiveType() { return short[].class; } }; private static final short[] EMPTY = new short[0]; } //----------------------------------------------------------------------- enum DoubleArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(double[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 8); buf.append(array[0]); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i]); } return buf.toString(); } @Override public double[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); double[] array = new double[split.length]; for (int i = 0; i < split.length; i++) { array[i] = Double.parseDouble(split[i]); } return array; } @Override public Class getEffectiveType() { return double[].class; } }; private static final double[] EMPTY = new double[0]; } //----------------------------------------------------------------------- enum FloatArrayStringConverter implements TypedStringConverter { INSTANCE { @Override public String convertToString(float[] array) { if (array.length == 0) { return ""; } StringBuilder buf = new StringBuilder(array.length * 8); buf.append(array[0]); for (int i = 1; i < array.length; i++) { buf.append(',').append(array[i]); } return buf.toString(); } @Override public float[] convertFromString(Class cls, String str) { if (str.length() == 0) { return EMPTY; } String[] split = DELIMITER.split(str); float[] array = new float[split.length]; for (int i = 0; i < split.length; i++) { array[i] = Float.parseFloat(split[i]); } return array; } @Override public Class getEffectiveType() { return float[].class; } }; private static final float[] EMPTY = new float[0]; } } joda-convert-1.8.1/src/main/java/org/joda/convert/AnnotationStringConverterFactory.java0000664000175000017500000002235312603461407030662 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** * Factory for {@code StringConverter} looking up annotations. *

* This class is immutable and thread-safe. * * @since 1.5 */ final class AnnotationStringConverterFactory implements StringConverterFactory { /** * Singleton instance. */ static final StringConverterFactory INSTANCE = new AnnotationStringConverterFactory(); /** * Restricted constructor. */ private AnnotationStringConverterFactory() { } //----------------------------------------------------------------------- /** * Finds a converter by type. * * @param cls the type to lookup, not null * @return the converter, null if not found * @throws RuntimeException (or subclass) if source code is invalid */ @Override public StringConverter findConverter(Class cls) { return findAnnotatedConverter(cls); // capture generics } /** * Finds a converter searching annotated. * * @param the type of the converter * @param cls the class to find a method for, not null * @return the converter, not null * @throws RuntimeException if none found */ private StringConverter findAnnotatedConverter(final Class cls) { Method toString = findToStringMethod(cls); // checks superclasses if (toString == null) { return null; } MethodConstructorStringConverter con = findFromStringConstructor(cls, toString); MethodsStringConverter mth = findFromStringMethod(cls, toString, con == null); // optionally checks superclasses if (con == null && mth == null) { throw new IllegalStateException("Class annotated with @ToString but not with @FromString: " + cls.getName()); } if (con != null && mth != null) { throw new IllegalStateException("Both method and constructor are annotated with @FromString: " + cls.getName()); } return (con != null ? con : mth); } /** * Finds the conversion method. * * @param cls the class to find a method for, not null * @return the method to call, null means use {@code toString} * @throws RuntimeException if invalid */ private Method findToStringMethod(Class cls) { Method matched = null; // find in superclass hierarchy Class loopCls = cls; while (loopCls != null && matched == null) { Method[] methods = loopCls.getDeclaredMethods(); for (Method method : methods) { ToString toString = method.getAnnotation(ToString.class); if (toString != null) { if (matched != null) { throw new IllegalStateException("Two methods are annotated with @ToString: " + cls.getName()); } matched = method; } } loopCls = loopCls.getSuperclass(); } // find in immediate parent interfaces if (matched == null) { for (Class loopIfc : eliminateEnumSubclass(cls).getInterfaces()) { Method[] methods = loopIfc.getDeclaredMethods(); for (Method method : methods) { ToString toString = method.getAnnotation(ToString.class); if (toString != null) { if (matched != null) { throw new IllegalStateException("Two methods are annotated with @ToString on interfaces: " + cls.getName()); } matched = method; } } } } return matched; } /** * Finds the conversion method. * * @param the type of the converter * @param cls the class to find a method for, not null * @param toString the toString method, not null * @return the method to call, null means none found * @throws RuntimeException if invalid */ private MethodConstructorStringConverter findFromStringConstructor(Class cls, Method toString) { Constructor con; try { con = cls.getDeclaredConstructor(String.class); } catch (NoSuchMethodException ex) { try { con = cls.getDeclaredConstructor(CharSequence.class); } catch (NoSuchMethodException ex2) { return null; } } FromString fromString = con.getAnnotation(FromString.class); if (fromString == null) { return null; } return new MethodConstructorStringConverter(cls, toString, con); } /** * Finds the conversion method. * * @param cls the class to find a method for, not null * @param toString the toString method, not null * @param searchSuperclasses whether to search superclasses * @return the method to call, null means not found * @throws RuntimeException if invalid */ private MethodsStringConverter findFromStringMethod(Class cls, Method toString, boolean searchSuperclasses) { // find in superclass hierarchy Class loopCls = cls; while (loopCls != null) { Method fromString = findFromString(loopCls); if (fromString != null) { return new MethodsStringConverter(cls, toString, fromString, loopCls); } if (searchSuperclasses == false) { break; } loopCls = loopCls.getSuperclass(); } // find in immediate parent interfaces MethodsStringConverter matched = null; if (searchSuperclasses) { for (Class loopIfc : eliminateEnumSubclass(cls).getInterfaces()) { Method fromString = findFromString(loopIfc); if (fromString != null) { if (matched != null) { throw new IllegalStateException("Two different interfaces are annotated with " + "@FromString or @FromStringFactory: " + cls.getName()); } matched = new MethodsStringConverter(cls, toString, fromString, loopIfc); } } } return matched; } /** * Finds the conversion method. * * @param cls the class to find a method for, not null * @param matched the matched method, may be null * @return the method to call, null means not found * @throws RuntimeException if invalid */ private Method findFromString(Class cls) { // find in declared methods Method[] methods = cls.getDeclaredMethods(); Method matched = null; for (Method method : methods) { FromString fromString = method.getAnnotation(FromString.class); if (fromString != null) { if (matched != null) { throw new IllegalStateException("Two methods are annotated with @FromString: " + cls.getName()); } matched = method; } } // check for factory FromStringFactory factory = cls.getAnnotation(FromStringFactory.class); if (factory != null) { if (matched != null) { throw new IllegalStateException("Class annotated with @FromString and @FromStringFactory: " + cls.getName()); } Method[] factoryMethods = factory.factory().getDeclaredMethods(); for (Method method : factoryMethods) { // handle factory containing multiple FromString for different types if (cls.isAssignableFrom(method.getReturnType())) { FromString fromString = method.getAnnotation(FromString.class); if (fromString != null) { if (matched != null) { throw new IllegalStateException("Two methods are annotated with @FromString on the factory: " + factory.factory().getName()); } matched = method; } } } } return matched; } // eliminates enum subclass as they are pesky private Class eliminateEnumSubclass(Class cls) { Class sup = cls.getSuperclass(); if (sup != null && sup.getSuperclass() == Enum.class) { return sup; } return cls; } //----------------------------------------------------------------------- @Override public String toString() { return getClass().getSimpleName(); } } joda-convert-1.8.1/src/main/java/org/joda/convert/StringConverterFactory.java0000664000175000017500000000222412603461407026622 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Factory for {@code StringConverter} that allows converters to be * created dynamically or easily initialised. *

* Implementations must be immutable and thread-safe. * * @since 1.5 */ public interface StringConverterFactory { /** * Finds a converter by type. * * @param cls the type to lookup, not null * @return the converter, null if not found * @throws RuntimeException (or subclass) if source code is invalid */ StringConverter findConverter(Class cls); } joda-convert-1.8.1/src/main/java/org/joda/convert/FromStringFactory.java0000664000175000017500000000334312603461407025561 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used on a type to indicate that another class, the factory, * provides the 'from string' method. *

* This annotation is applied at the type level, typically to an interface. * It indicates the class which contains the relevant {@code FromString} * annotation, which follows the normal rules. *

* For example, the interface {@code Foo} could be annotated to define its * associated factory as being {@code FooFactory}. The {@code FooFactory} * class would then be expected to provide a method returning {@code Foo} * with a single {@code String} parameter, annotated with {@code FromString}. * * @since 1.4 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface FromStringFactory { /** * The factory class containing the static method. * The static method must have a return type of the type that declares * the factory annotation. */ Class factory(); } joda-convert-1.8.1/src/main/java/org/joda/convert/ToStringConverter.java0000664000175000017500000000225712603461407025603 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Interface defining conversion to a {@code String}. *

* ToStringConverter is an interface and must be implemented with care. * Implementations must be immutable and thread-safe. * * @param the type of the converter */ public interface ToStringConverter { /** * Converts the specified object to a {@code String}. * @param object the object to convert, not null * @return the converted string, may be null but generally not */ String convertToString(T object); } joda-convert-1.8.1/src/main/java/org/joda/convert/ReflectionStringConverter.java0000664000175000017500000000577412603461407027322 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Conversion to and from a string using reflection. *

* The toString method must meet the following signature:
* {@code String anyName()} on Class T. *

* ReflectionStringConverter is abstract, but all known implementations are thread-safe and immutable. * * @param the type of the converter */ abstract class ReflectionStringConverter implements TypedStringConverter { /** The converted class. */ private final Class cls; /** Conversion to a string. */ private final Method toString; /** * Creates an instance using two methods. * @param cls the class this converts for, not null * @param toString the toString method, not null * @throws RuntimeException (or subclass) if the method signatures are invalid */ ReflectionStringConverter(Class cls, Method toString) { if (toString.getParameterTypes().length != 0) { throw new IllegalStateException("ToString method must have no parameters: " + toString); } if (toString.getReturnType() != String.class) { throw new IllegalStateException("ToString method must return a String: " + toString); } this.cls = cls; this.toString = toString; } //----------------------------------------------------------------------- /** * Converts the object to a {@code String}. * @param object the object to convert, not null * @return the converted string, may be null but generally not */ @Override public String convertToString(T object) { try { return (String) toString.invoke(object); } catch (IllegalAccessException ex) { throw new IllegalStateException("Method is not accessible: " + toString); } catch (InvocationTargetException ex) { if (ex.getCause() instanceof RuntimeException) { throw (RuntimeException) ex.getCause(); } throw new RuntimeException(ex.getMessage(), ex.getCause()); } } //----------------------------------------------------------------------- @Override public String toString() { return "RefectionStringConverter[" + cls.getSimpleName() + "]"; } } joda-convert-1.8.1/src/main/assembly/0000775000175000017500000000000012603461407017003 5ustar ebourgebourgjoda-convert-1.8.1/src/main/assembly/dist.xml0000664000175000017500000000154112603461407020471 0ustar ebourgebourg dist tar.gz zip ${artifactId}-${version} checkstyle.xml LICENSE.txt NOTICE.txt pom.xml RELEASE-NOTES.txt src target *.jar joda-convert-1.8.1/src/site/0000775000175000017500000000000012603461407015204 5ustar ebourgebourgjoda-convert-1.8.1/src/site/resources/0000775000175000017500000000000012603461407017216 5ustar ebourgebourgjoda-convert-1.8.1/src/site/resources/download.html0000664000175000017500000000023312603461407021711 0ustar ebourgebourg OpenGamma joda-convert-1.8.1/src/site/resources/css/0000775000175000017500000000000012603461407020006 5ustar ebourgebourgjoda-convert-1.8.1/src/site/resources/css/site.css0000664000175000017500000000165712603461407021475 0ustar ebourgebourg/* Fix broken definition that causes hyperlinks to break */ h1[id]:before, h2[id]:before, h3[id]:before, h4[id]:before, h5[id]:before, h6[id]:before, a[name]:before { height:0px; margin:0px; } /* Blacker text */ body { color: #222; } code, pre { color: #444; } .dropdown-menu>li>a { color: #666; } /* Sidebar had too much padding at the top */ .well { padding-top: 6px; padding-bottom: 36px; } /* Font Awesome icons by CSS as markdown class is stripped */ h2 i { display: inline-block; font: normal normal normal 14px/1 FontAwesome; font-size: inherit; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } h2#About i:before { content: "\f015"; } h2#Features i:before { content: "\f0d0"; } h2#Documentation i:before { content: "\f02d"; } h2#Releases i:before { content: "\f02c"; } h2#Why_Joda_Convert i:before { content: "\f19c"; } joda-convert-1.8.1/src/site/markdown/0000775000175000017500000000000012603461407017026 5ustar ebourgebourgjoda-convert-1.8.1/src/site/markdown/userguide.md0000664000175000017500000001575512603461407021361 0ustar ebourgebourg## User guide Joda-Convert is intended for one simple task - Converting objects to and from strings. This is a common problem, particularly when communicating over textual protocols like XML or JSON. ## Basic usage Using Joda-Convert is easy at the simplest level. The main access is via the class `StringConvert`. The easiest way to use the conversion is via the global constant: ``` // conversion to a String TimeZone zone = ... String str = StringConvert.INSTANCE.convertToString(zone); // conversion from a String TimeZone zone = StringConvert.INSTANCE.convertFromString(TimeZone.class, str); ``` In both cases, if the input is `null` then the output will also be `null`. The global constant is quick and easy to use, but is shared between all users in the `ClassLoader`. It also cannot be extended. The alternative approach is to instantiate your own instance of `StringConvert`. This would normally be stored in your own static variable, or made available as needed by dependency injection. This may be updated by registering your own converters. ## Converters Each instance of `StringConvert`, including the global singleton, includes a standard set of JDK-based converters. These cover all the standard JDK types for which conversion to and from a string is sensible. The set also includes JSR-310 types, but these are optional and loaded by reflection. The system will run without any dependency. The JDK conversions are generally obvious. The types are as follows: * String * CharSequence * StringBuffer * StringBuilder * long and Long * int and Integer * short and Short * char and Character * byte and Byte * double and Double * float and Float * boolean and Boolean - 'true' or 'false' * byte[] - using Base-64 encoding * char[] * BigInteger * BigDecimal * AtomicLong * AtomicInteger * AtomicBoolean - 'true' or 'false' * Locale - separated by underscores, en_GB_VARIANT * Class - using the class name, using the rename handler * Package - using the package name * Currency - using the three letter code * TimeZone - using the ID * UUID - using the toString() form * URL - using the toString() form * URI - using the toString() form * InetAddress - using the host address * File - using the toString() form * Date - yyyy-MM-dd'T'HH:mm:ss.SSSZ * Calendar - yyyy-MM-dd'T'HH:mm:ss.SSSZ, Gregorian only * Instant * Duration * LocalDate * LocalTime * LocalDateTime * OffsetTime * OffsetDateTime * ZonedDateTime * Year * YearMonth * MonthDay * Period * ZoneOffset * ZoneId * Enum subclasses - using name(), annotations can override Note that the JSR-310 date types are supported in three different package namespaces - 'java.time', 'javax.time' and 'org.threeten.bp'. Each `StringConvert` instance, other than the global singleton, may have additional converters registered manually. Each converter implements the `StringConverter` interface, which is self explanatory. Converters may also be manually added by method name. This is equivalent to using annotations, but suitable when you don't own the code to add them. See `StringConvert.registerMethods` and `StringConvert.registerMethodConstructor`. ## Factories In addition to manual registration of individual converters, each instance of `StringConvert` has a list of factories to use. The `StringConverterFactory` interface defines the factory. This allows either bulk registration or dynamic lookup of converters. A factory is provided to allow numeric arrays to be converted to/from a comma separated list. A separate factory handles numeric object arrays. Another factory is provided to allow boolean arrays to be converted to/from a string such as 'TTFFT'. Again, a separate factory handles boolean object arrays. Primitive byte and char arrays are handled by default, but the primitive object arrays are handled via their own factories. These extra factories must be manually registered, unless the `StringConvert.create()` static method is used, which defines an "extended" converter with the factories included. ## Annotation based conversion If there is no registered converter for a type, then a search by annotation is performed. This will search for the `ToString` and `FromString` annotation on the type. These annotations will indicate which method should be called to perform the conversion. ``` public class Distance { @FromString public static Distance parse(String str) { ... } @ToString public String getStandardOutput() { ... } } ``` To be valid, the class must contain one `ToString` annotation and one `FromString` annotation. The `ToString` annotation must be an instance method taking no parameters and returning a String. The `FromString` annotation must be either a static method or a constructor taking a String parameter and returning the correct type. If the annotations are not found on the target class, then superclasses are searched, followed by immediate parent interfaces. Sometimes, you want to provide to/from string conversions for interfaces. In Java SE 8 this can be done using static methods on interfaces. However in earlier versions, a separate "factory" class is necessary. This can also be annotated: ``` @FromStringFactory(factory = DistanceFactory.class) public interface Distance { @ToString String standardFormat(); } public class Metres implements Distance { @Override public String standardFormat() { ... } } public class DistanceFactory { @FromString public static Distance parseDistance(String str) { ... } } ``` The `FromStringFactory` annotation points at the factory class that will provide the factory method. Although intended for use with interfaces, it can also be used on the target class or any superclass. Note that only the immediate parent interfaces of a class will be searched. The effective type of the converter in use is the type that declares the `FromString` or `FromStringFactory` annotation. This can be used by serialization systems to determine the best type of the value to send. One use case is to declare annotations on a public superclass and have all the subclasses be package scoped. Using the effective type, the package scoped subclasses remain out of the serialized form and off the public API. ## Rename handler Most large bodies of code will end up renaming classes and enum constants at some point. The `RenameHandler` class provides a convenient central place to track this. If the `RenameHandler` is setup with details of a rename, then an old class name or enum constant can be read in and will be automatically converted. ## Rationale The concept is that other open source libraries, as well as your application code, will implement these two annotations. For open source projects, a key point is that adding the annotations is a compile-time only event. The Joda-Convert jar file is not needed by your users unless they want to use conversion. If they don't want to use Joda-Convert then the annotations are effectively ignored. Joda-Time v2.0 and Joda-Money contain these annotations. In both cases, the dependency is optional at runtime for users of the projects. (Note that Scala does not honour the optional behaviour.) joda-convert-1.8.1/src/site/markdown/index.md0000664000175000017500000000616112603461407020463 0ustar ebourgebourg## About **Joda-Convert** tackles the problem of round-trip Object to String conversion. A common problem in serialization, particularly when working with textual formats like JSON, is that of converting simple objects to and from strings. Joda-Convert addresses this without getting caught up in the wider problem of Object to Object transformation. Joda-Convert is licensed under the business-friendly [Apache 2.0 licence](license.html). ## Features A selection of key features: * Round-trip Object to String * Conversions defined by annotations or by implementing a simple interface * Very simple to use * No dependencies ## Documentation Various documentation is available: * The helpful [user guide](userguide.html) * The [Javadoc](apidocs/index.html) * The [change notes](changes-report.html) for each release * The [GitHub](https://github.com/JodaOrg/joda-convert) source repository --- ## Why Joda Convert? Joda-Convert is a small, highly-focussed library, tackling a problem that the JDK should solve - providing round-trip conversion between Objects and Strings. ``` // conversion to String String str = StringConvert.INSTANCE.convertToString(foo); // conversion from String Foo bar = StringConvert.INSTANCE.convertFromString(Foo.class, str); ``` Joda-Convert supports two mechanisms of extending the list of supported conversions. The first is to write your own converter implementing an interface. The second is to use annotations. The ability of Joda-Convert to use annotations to define the conversion methods is a key difference from other projects. For example, most value classes, like `Currency` or `TimeZone`, already have methods to convert to and from a standard format String. Consider a `Distance` class: ``` public class Distance { @FromString public static Distance parse(String str) { ... } @ToString public String getStandardOutput() { ... } } ``` As shown, the two methods may have any name. They must simply fulfil the required method signatures for conversion. The FromString annotation may also be applied to a constructor. When Joda-Convert is asked to convert between an object and a String, if there is no registered converter then the annotations are checked. If they are found, then the methods are called by reflection. --- ## Releases [Release 1.8.1](download.html) is the current latest release. This release is considered stable and worthy of the 1.x tag. Joda-Convert requires Java SE 6 or later and has [no dependencies](dependencies.html). Available in [Maven Central](http://search.maven.org/#artifactdetails%7Corg.joda%7Cjoda-convert%7C1.8.1%7Cjar). ```xml org.joda joda-convert 1.8.1 ``` --- ### Support Support on bugs, library usage or enhancement requests is available on a best efforts basis. To suggest enhancements or contribute, please [fork the source code](https://github.com/JodaOrg/joda-convert) on GitHub and send a Pull Request. Alternatively, use GitHub [issues](https://github.com/JodaOrg/joda-convert/issues). joda-convert-1.8.1/src/site/site.xml0000664000175000017500000000614312603461407016676 0ustar ebourgebourg UA-1425975-4 lt.velykis.maven.skins reflow-maven-skin 1.1.1 false true github false bootswatch-cosmo Joda-Convert index.html Documentation|Releases|Development|Joda Documentation Releases Development Reports false false false 3 1 Home false false false false

joda-convert-1.8.1/src/test/0000775000175000017500000000000012603461407015217 5ustar ebourgebourgjoda-convert-1.8.1/src/test/java/0000775000175000017500000000000012603461407016140 5ustar ebourgebourgjoda-convert-1.8.1/src/test/java/org/0000775000175000017500000000000012603461407016727 5ustar ebourgebourgjoda-convert-1.8.1/src/test/java/org/joda/0000775000175000017500000000000012603461407017644 5ustar ebourgebourgjoda-convert-1.8.1/src/test/java/org/joda/convert/0000775000175000017500000000000012603461407021324 5ustar ebourgebourgjoda-convert-1.8.1/src/test/java/org/joda/convert/TestGuavaTypeTokenStringConverter.java0000664000175000017500000001501512603461407031016 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import org.junit.Test; import com.google.common.reflect.TypeToken; /** * Test GuavaStringConverters. */ @SuppressWarnings("serial") public class TestGuavaTypeTokenStringConverter { @Test public void test_simpleClass_String() { TypeToken token = TypeToken.of(String.class); doTest(token, "java.lang.String"); } @Test public void test_simpleClass_Integer() { TypeToken token = TypeToken.of(Integer.class); doTest(token, "java.lang.Integer"); } @Test public void test_simpleClass_rawList() { TypeToken token = TypeToken.of(List.class); doTest(token, "java.util.List"); } //----------------------------------------------------------------------- @Test public void test_primitive_int() { TypeToken token = TypeToken.of(Integer.TYPE); doTest(token, "int"); } @Test public void test_primitive_char() { TypeToken token = TypeToken.of(Character.TYPE); doTest(token, "char"); } //----------------------------------------------------------------------- @Test public void test_oneParam() { TypeToken token = new TypeToken>() {}; doTest(token, "java.util.List"); } @Test public void test_oneWild() { TypeToken token = new TypeToken>() {}; doTest(token, "java.util.List"); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void test_oneArray() { TypeToken token = new TypeToken>() {}; // two different output formats to parse TypeTokenStringConverter test = new TypeTokenStringConverter(); String asStr = test.convertToString(token); Object reverse1 = test.convertFromString((Class) TypeToken.class, "java.util.List"); Object reverse2 = test.convertFromString((Class) TypeToken.class, "java.util.List<[Ljava.lang.String;>"); assertEquals(reverse1, reverse2); String expected = (asStr.equals("java.util.List") ? "java.util.List" : "java.util.List<[Ljava.lang.String;>"); doTest(token, expected); } @Test public void test_oneExtends() { TypeToken token = new TypeToken>() {}; doTest(token, "java.util.List"); } @Test public void test_oneSuper() { TypeToken token = new TypeToken>() {}; doTest(token, "java.util.List"); } @Test public void test_twoParams() { TypeToken token = new TypeToken>() {}; doTest(token, "java.util.Map"); } @Test public void test_twoParamsExtends() { TypeToken token = new TypeToken>() {}; doTest(token, "java.util.Map"); } @Test public void test_twoParamsSuper() { TypeToken token = new TypeToken>() {}; doTest(token, "java.util.Map"); } //----------------------------------------------------------------------- @Test public void test_twoParamNested() { TypeToken token = new TypeToken>>() {}; doTest(token, "java.util.Map>"); } @Test public void test_twoParamNestedExtends() { TypeToken token = new TypeToken>>() {}; doTest(token, "java.util.Map>"); } @Test public void test_twoParamComplex() { TypeToken token = new TypeToken>>() {}; doTest(token, "java.util.Map>"); } @Test public void test_twoParamComplexExtends() { TypeToken token = new TypeToken>>>() {}; doTest(token, "java.util.Map>>"); } //----------------------------------------------------------------------- @SuppressWarnings({ "unchecked", "rawtypes" }) public void doTest(TypeToken obj, String str) { TypeTokenStringConverter test = new TypeTokenStringConverter(); assertEquals(TypeToken.class, test.getEffectiveType()); assertEquals(str, test.convertToString(obj)); assertEquals(obj, test.convertFromString((Class) TypeToken.class, str)); TypedStringConverter test2 = StringConvert.INSTANCE.findTypedConverterNoGenerics(TypeToken.class); assertEquals(TypeToken.class, test2.getEffectiveType()); assertEquals(str, test2.convertToString(obj)); assertEquals(obj, test2.convertFromString(TypeToken.class, str)); TypeStringConverter test3 = new TypeStringConverter(); assertEquals(Type.class, test3.getEffectiveType()); assertEquals(str, test3.convertToString(obj.getType())); assertEquals(obj.getType(), test3.convertFromString(Type.class, str)); TypedStringConverter test4 = StringConvert.INSTANCE.findTypedConverterNoGenerics(Type.class); assertEquals(Type.class, test4.getEffectiveType()); assertEquals(str, test4.convertToString(obj.getType())); assertEquals(obj.getType(), test4.convertFromString(Type.class, str)); } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceToStringInvalidParameters.java0000664000175000017500000000242612603461407030752 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceToStringInvalidParameters { /** Amount. */ final int amount; public DistanceToStringInvalidParameters(int amount) { this.amount = amount; } @FromString public DistanceToStringInvalidParameters(String amount) { amount = amount.substring(0, amount.length() - 1); this.amount = Integer.parseInt(amount); } @ToString public Object print(int num) { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceNoAnnotationsCharSequence.java0000664000175000017500000000255312603461407030730 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceNoAnnotationsCharSequence { /** Amount. */ final int amount; public static DistanceNoAnnotationsCharSequence parse(CharSequence amount) { return new DistanceNoAnnotationsCharSequence(amount); } public DistanceNoAnnotationsCharSequence(int amount) { this.amount = amount; } public DistanceNoAnnotationsCharSequence(CharSequence amount) { String amt = amount.toString().substring(0, amount.length() - 1); this.amount = Integer.parseInt(amt); } public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/TestStringConvert.java0000664000175000017500000010163512603461407025644 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.RoundingMode; import java.text.ParseException; import org.joda.convert.test1.Test1Class; import org.joda.convert.test2.Test2Class; import org.joda.convert.test2.Test2Interface; import org.joda.convert.test3.Test3Class; import org.joda.convert.test3.Test3SuperClass; import org.joda.convert.test4.Test4Class; import org.joda.convert.test4.Test4Interface; import org.junit.Test; /** * Test StringConvert. */ public class TestStringConvert { @Test public void test_constructor() { StringConvert test = new StringConvert(); TypedStringConverter conv = test.findTypedConverter(Integer.class); assertEquals(true, conv instanceof JDKStringConverter); assertEquals(Integer.class, conv.getEffectiveType()); } @Test public void test_constructor_true() { StringConvert test = new StringConvert(true); StringConverter conv = test.findConverter(Integer.class); assertEquals(true, conv instanceof JDKStringConverter); } @Test(expected=IllegalStateException.class) public void test_constructor_false() { StringConvert test = new StringConvert(false); StringConverter conv = test.findConverter(Integer.class); assertEquals(null, conv); } //----------------------------------------------------------------------- @Test public void test_isConvertible() { assertTrue(StringConvert.INSTANCE.isConvertible(Integer.class)); assertTrue(StringConvert.INSTANCE.isConvertible(String.class)); assertFalse(StringConvert.INSTANCE.isConvertible(Object.class)); } //----------------------------------------------------------------------- @Test public void test_convertToString() { Integer i = 6; assertEquals("6", StringConvert.INSTANCE.convertToString(i)); } @Test public void test_convertToString_primitive() { int i = 6; assertEquals("6", StringConvert.INSTANCE.convertToString(i)); } @Test public void test_convertToString_inherit() { assertEquals("CEILING", StringConvert.INSTANCE.convertToString(RoundingMode.CEILING)); } @Test public void test_convertToString_null() { assertEquals(null, StringConvert.INSTANCE.convertToString(null)); } //----------------------------------------------------------------------- @Test public void test_convertToString_withType() { Integer i = 6; assertEquals("6", StringConvert.INSTANCE.convertToString(Integer.class, i)); } @Test public void test_convertToString_withType_noGenerics() { Integer i = 6; Class cls = Integer.class; assertEquals("6", StringConvert.INSTANCE.convertToString(cls, i)); } @Test public void test_convertToString_withType_primitive1() { int i = 6; assertEquals("6", StringConvert.INSTANCE.convertToString(Integer.class, i)); } @Test public void test_convertToString_withType_primitive2() { int i = 6; assertEquals("6", StringConvert.INSTANCE.convertToString(Integer.TYPE, i)); } @Test public void test_convertToString_withType_inherit1() { assertEquals("CEILING", StringConvert.INSTANCE.convertToString(RoundingMode.class, RoundingMode.CEILING)); } @Test public void test_convertToString_withType_null() { assertEquals(null, StringConvert.INSTANCE.convertToString(Integer.class, null)); } @Test(expected = IllegalArgumentException.class) public void test_convertToString_withType_nullClass() { assertEquals(null, StringConvert.INSTANCE.convertToString(null, "6")); } //----------------------------------------------------------------------- @Test public void test_convertFromString() { assertEquals(Integer.valueOf(6), StringConvert.INSTANCE.convertFromString(Integer.class, "6")); } @Test public void test_convertFromString_primitiveInt() { assertEquals(Integer.valueOf(6), StringConvert.INSTANCE.convertFromString(Integer.TYPE, "6")); } @Test public void test_convertFromString_primitiveBoolean() { assertEquals(Boolean.TRUE, StringConvert.INSTANCE.convertFromString(Boolean.TYPE, "true")); } @Test public void test_convertFromString_inherit() { assertEquals(RoundingMode.CEILING, StringConvert.INSTANCE.convertFromString(RoundingMode.class, "CEILING")); } @Test public void test_convertFromString_null() { assertEquals(null, StringConvert.INSTANCE.convertFromString(Integer.class, null)); } @Test(expected = IllegalArgumentException.class) public void test_convertFromString_nullClass() { assertEquals(null, StringConvert.INSTANCE.convertFromString(null, "6")); } //----------------------------------------------------------------------- @Test public void test_findConverter() { Class cls = Integer.class; StringConverter conv = StringConvert.INSTANCE.findConverter(cls); assertEquals(Integer.valueOf(12), conv.convertFromString(cls, "12")); assertEquals("12", conv.convertToString(12)); } @Test(expected=IllegalArgumentException.class) public void test_findConverter_null() { StringConvert.INSTANCE.findConverter(null); } @Test(expected=IllegalStateException.class) public void test_findConverter_Object() { StringConvert.INSTANCE.findConverter(Object.class); } //----------------------------------------------------------------------- @Test public void test_findConverterNoGenerics() { Class cls = Integer.class; StringConverter conv = StringConvert.INSTANCE.findConverterNoGenerics(cls); assertEquals(Integer.valueOf(12), conv.convertFromString(cls, "12")); assertEquals("12", conv.convertToString(12)); } @Test(expected=IllegalArgumentException.class) public void test_findConverterNoGenerics_null() { StringConvert.INSTANCE.findConverterNoGenerics(null); } @Test(expected=IllegalStateException.class) public void test_findConverterNoGenerics_Object() { StringConvert.INSTANCE.findConverterNoGenerics(Object.class); } //----------------------------------------------------------------------- @Test public void test_convert_annotationMethodMethod() { StringConvert test = new StringConvert(); DistanceMethodMethod d = new DistanceMethodMethod(25); assertEquals("25m", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceMethodMethod.class, "25m").amount); TypedStringConverter conv = test.findTypedConverter(DistanceMethodMethod.class); assertEquals(true, conv instanceof MethodsStringConverter); assertSame(conv, test.findConverter(DistanceMethodMethod.class)); assertEquals(DistanceMethodMethod.class, conv.getEffectiveType()); assertEquals(true, conv.toString().startsWith("RefectionStringConverter")); } @Test public void test_convert_annotationMethodMethodCharSequence() { StringConvert test = new StringConvert(); DistanceMethodMethodCharSequence d = new DistanceMethodMethodCharSequence(25); assertEquals("25m", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceMethodMethodCharSequence.class, "25m").amount); TypedStringConverter conv = test.findTypedConverter(DistanceMethodMethodCharSequence.class); assertEquals(true, conv instanceof MethodsStringConverter); assertSame(conv, test.findConverter(DistanceMethodMethodCharSequence.class)); assertEquals(DistanceMethodMethodCharSequence.class, conv.getEffectiveType()); assertEquals(true, conv.toString().startsWith("RefectionStringConverter")); } @Test public void test_convert_annotationMethodConstructor() { StringConvert test = new StringConvert(); DistanceMethodConstructor d = new DistanceMethodConstructor(25); assertEquals("25m", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceMethodConstructor.class, "25m").amount); TypedStringConverter conv = test.findTypedConverter(DistanceMethodConstructor.class); assertEquals(true, conv instanceof MethodConstructorStringConverter); assertSame(conv, test.findConverter(DistanceMethodConstructor.class)); assertEquals(DistanceMethodConstructor.class, conv.getEffectiveType()); assertEquals(true, conv.toString().startsWith("RefectionStringConverter")); } @Test public void test_convert_annotationMethodConstructorCharSequence() { StringConvert test = new StringConvert(); DistanceMethodConstructorCharSequence d = new DistanceMethodConstructorCharSequence(25); assertEquals("25m", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceMethodConstructorCharSequence.class, "25m").amount); TypedStringConverter conv = test.findTypedConverter(DistanceMethodConstructorCharSequence.class); assertEquals(true, conv instanceof MethodConstructorStringConverter); assertSame(conv, test.findConverter(DistanceMethodConstructorCharSequence.class)); assertEquals(DistanceMethodConstructorCharSequence.class, conv.getEffectiveType()); assertEquals(true, conv.toString().startsWith("RefectionStringConverter")); } @Test public void test_convert_annotationSubMethodMethod() { StringConvert test = new StringConvert(); SubMethodMethod d = new SubMethodMethod(25); assertEquals("25m", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(SubMethodMethod.class, "25m").amount); TypedStringConverter conv = test.findTypedConverter(SubMethodMethod.class); assertEquals(true, conv instanceof MethodsStringConverter); assertEquals(SubMethodMethod.class, conv.getEffectiveType()); assertSame(conv, test.findConverter(SubMethodMethod.class)); } @Test public void test_convert_annotationSubMethodConstructor() { StringConvert test = new StringConvert(); SubMethodConstructor d = new SubMethodConstructor("25m"); assertEquals("25m", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(SubMethodConstructor.class, "25m").amount); TypedStringConverter conv = test.findTypedConverter(SubMethodConstructor.class); assertEquals(true, conv instanceof MethodConstructorStringConverter); assertEquals(SubMethodConstructor.class, conv.getEffectiveType()); assertSame(conv, test.findConverter(SubMethodConstructor.class)); } @Test public void test_convert_annotationSuperFactorySuper() { StringConvert test = new StringConvert(); SuperFactorySuper d = new SuperFactorySuper(25); assertEquals("25m", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(SuperFactorySuper.class, "25m").amount); TypedStringConverter conv = test.findTypedConverter(SuperFactorySuper.class); assertEquals(true, conv instanceof MethodsStringConverter); assertEquals(SuperFactorySuper.class, conv.getEffectiveType()); assertSame(conv, test.findConverter(SuperFactorySuper.class)); } @Test public void test_convert_annotationSuperFactorySubViaSuper() { StringConvert test = new StringConvert(); SuperFactorySub d = new SuperFactorySub(8); assertEquals("8m", test.convertToString(d)); SuperFactorySuper fromStr = test.convertFromString(SuperFactorySuper.class, "8m"); assertEquals(d.amount, fromStr.amount); assertEquals(true, fromStr instanceof SuperFactorySub); TypedStringConverter conv = test.findTypedConverter(SuperFactorySub.class); assertEquals(true, conv instanceof MethodsStringConverter); assertEquals(SuperFactorySuper.class, conv.getEffectiveType()); assertSame(conv, test.findConverter(SuperFactorySub.class)); } @Test public void test_convert_annotationSuperFactorySubViaSub1() { StringConvert test = new StringConvert(); SuperFactorySub d = new SuperFactorySub(25); assertEquals("25m", test.convertToString(d)); } // TODO problem is fwks, that just request a converter based on the type of the object @Test(expected = ClassCastException.class) public void test_convert_annotationSuperFactorySubViaSub2() { StringConvert test = new StringConvert(); test.convertFromString(SuperFactorySub.class, "25m"); } @Test public void test_convert_annotationToStringInvokeException() { StringConvert test = new StringConvert(); DistanceToStringException d = new DistanceToStringException(25); StringConverter conv = test.findConverter(DistanceToStringException.class); try { conv.convertToString(d); fail(); } catch (RuntimeException ex) { assertEquals(ParseException.class, ex.getCause().getClass()); } } @Test public void test_convert_annotationFromStringInvokeException() { StringConvert test = new StringConvert(); StringConverter conv = test.findConverter(DistanceFromStringException.class); try { conv.convertFromString(DistanceFromStringException.class, "25m"); fail(); } catch (RuntimeException ex) { assertEquals(ParseException.class, ex.getCause().getClass()); } } //----------------------------------------------------------------------- @Test public void test_convert_annotationFactoryMethod() { StringConvert test = new StringConvert(); DistanceWithFactory d = new DistanceWithFactory(25); assertEquals("25m", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceWithFactory.class, "25m").amount); TypedStringConverter conv = test.findTypedConverter(DistanceWithFactory.class); assertEquals(true, conv instanceof MethodsStringConverter); assertEquals(DistanceWithFactory.class, conv.getEffectiveType()); assertSame(conv, test.findConverter(DistanceWithFactory.class)); assertEquals(true, conv.toString().startsWith("RefectionStringConverter")); } @Test public void test_convert_annotation_ToStringOnInterface() { StringConvert test = new StringConvert(); Test1Class d = new Test1Class(25); assertEquals("25g", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(Test1Class.class, "25g").amount); TypedStringConverter conv = test.findTypedConverter(Test1Class.class); assertEquals(true, conv instanceof MethodsStringConverter); assertEquals(Test1Class.class, conv.getEffectiveType()); assertSame(conv, test.findConverter(Test1Class.class)); assertEquals(true, conv.toString().startsWith("RefectionStringConverter")); } @Test public void test_convert_annotation_FactoryAndToStringOnInterface() { StringConvert test = new StringConvert(); Test2Class d = new Test2Class(25); assertEquals("25g", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(Test2Class.class, "25g").amount); TypedStringConverter conv = test.findTypedConverter(Test2Class.class); assertEquals(true, conv instanceof MethodsStringConverter); assertEquals(Test2Interface.class, conv.getEffectiveType()); assertSame(conv, test.findConverter(Test2Class.class)); assertEquals(true, conv.toString().startsWith("RefectionStringConverter")); } @Test public void test_convert_annotation_FactoryAndToStringOnInterface_usingInterface() { StringConvert test = new StringConvert(); Test2Class d = new Test2Class(25); assertEquals("25g", test.convertToString(d)); assertEquals("25g", test.convertFromString(Test2Interface.class, "25g").print()); TypedStringConverter conv = test.findTypedConverter(Test2Interface.class); assertEquals(true, conv instanceof MethodsStringConverter); assertEquals(Test2Interface.class, conv.getEffectiveType()); assertSame(conv, test.findConverter(Test2Interface.class)); assertEquals(true, conv.toString().startsWith("RefectionStringConverter")); } @Test public void test_convert_annotation_ToStringFromStringOnSuperClassBeatsInterface() { StringConvert test = new StringConvert(); Test3Class d = new Test3Class(25); assertEquals("25g", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(Test3Class.class, "25g").amount); TypedStringConverter conv = test.findTypedConverter(Test3Class.class); assertEquals(true, conv instanceof MethodsStringConverter); assertSame(conv, test.findConverter(Test3Class.class)); assertEquals(Test3SuperClass.class, conv.getEffectiveType()); assertEquals(true, conv.toString().startsWith("RefectionStringConverter")); } @Test(expected=IllegalStateException.class) public void test_convert_annotation_FromStringFactoryClashingMethods_fromClass() { StringConvert test = new StringConvert(); test.findConverter(Test4Class.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotation_FromStringFactoryClashingMethods_fromInterface() { StringConvert test = new StringConvert(); test.findConverter(Test4Interface.class); } //----------------------------------------------------------------------- @Test(expected=IllegalStateException.class) public void test_convert_annotationNoMethods() { StringConvert test = new StringConvert(); test.findConverter(DistanceNoAnnotations.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedMethodAndConstructor() { StringConvert test = new StringConvert(); test.findConverter(DistanceMethodAndConstructorAnnotations.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedTwoToString() { StringConvert test = new StringConvert(); test.findConverter(DistanceTwoToStringAnnotations.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedToStringInvalidReturnType() { StringConvert test = new StringConvert(); test.findConverter(DistanceToStringInvalidReturnType.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedToStringInvalidParameters() { StringConvert test = new StringConvert(); test.findConverter(DistanceToStringInvalidParameters.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedFromStringInvalidReturnType() { StringConvert test = new StringConvert(); test.findConverter(DistanceFromStringInvalidReturnType.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedFromStringInvalidParameter() { StringConvert test = new StringConvert(); test.findConverter(DistanceFromStringInvalidParameter.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedFromStringInvalidParameterCount() { StringConvert test = new StringConvert(); test.findConverter(DistanceFromStringInvalidParameterCount.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedFromStringConstructorInvalidParameter() { StringConvert test = new StringConvert(); test.findConverter(DistanceFromStringConstructorInvalidParameter.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedFromStringConstructorInvalidParameterCount() { StringConvert test = new StringConvert(); test.findConverter(DistanceFromStringConstructorInvalidParameterCount.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedToStringNoFromString() { StringConvert test = new StringConvert(); test.findConverter(DistanceToStringNoFromString.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedFromStringNoToString() { StringConvert test = new StringConvert(); test.findConverter(DistanceFromStringNoToString.class); } @Test(expected=IllegalStateException.class) public void test_convert_annotatedTwoFromStringMethod() { StringConvert test = new StringConvert(); test.findConverter(DistanceTwoFromStringMethodAnnotations.class); } //----------------------------------------------------------------------- @Test public void test_convert_Enum_overrideDefaultWithConverter() { StringConvert test = new StringConvert(); test.register(Validity.class, ValidityStringConverter.INSTANCE); assertEquals("VALID", test.convertToString(Validity.class, Validity.VALID)); assertEquals("INVALID", test.convertToString(Validity.class, Validity.INVALID)); assertEquals(Validity.VALID, test.convertFromString(Validity.class, "VALID")); assertEquals(Validity.INVALID, test.convertFromString(Validity.class, "INVALID")); assertEquals(Validity.VALID, test.convertFromString(Validity.class, "OK")); } //----------------------------------------------------------------------- @Test(expected=IllegalArgumentException.class) public void test_register_classNotNull() { StringConvert.INSTANCE.register(null, MockIntegerStringConverter.INSTANCE); } @Test(expected=IllegalArgumentException.class) public void test_register_converterNotNull() { StringConvert.INSTANCE.register(Integer.class, null); } @Test(expected=IllegalStateException.class) public void test_register_notOnShared() { StringConvert.INSTANCE.register(Integer.class, MockIntegerStringConverter.INSTANCE); } @Test public void test_register_classAlreadyRegistered() { new StringConvert().register(Integer.class, MockIntegerStringConverter.INSTANCE); } public void test_register_distance() { StringConvert test = new StringConvert(); test.register(DistanceMethodMethod.class, MockDistanceStringConverter.INSTANCE); assertSame(MockDistanceStringConverter.INSTANCE, test.findConverter(DistanceMethodMethod.class)); } //------------------------------------------------------------------------- ToStringConverter DISTANCE_TO_STRING_CONVERTER = new ToStringConverter() { @Override public String convertToString(DistanceNoAnnotations object) { return object.toString(); } }; FromStringConverter DISTANCE_FROM_STRING_CONVERTER = new FromStringConverter() { @Override public DistanceNoAnnotations convertFromString(Class cls, String str) { return DistanceNoAnnotations.parse(str); } }; @Test public void test_register_FunctionalInterfaces() { StringConvert test = new StringConvert(); test.register(DistanceNoAnnotations.class, DISTANCE_TO_STRING_CONVERTER, DISTANCE_FROM_STRING_CONVERTER); DistanceNoAnnotations d = new DistanceNoAnnotations(25); assertEquals("Distance[25m]", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceNoAnnotations.class, "25m").amount); StringConverter conv = test.findConverter(DistanceNoAnnotations.class); assertEquals(true, conv.getClass().getName().contains("$")); assertSame(conv, test.findConverter(DistanceNoAnnotations.class)); } @Test(expected=IllegalArgumentException.class) public void test_register_FunctionalInterfaces_nullClass() { StringConvert test = new StringConvert(); test.register(null, DISTANCE_TO_STRING_CONVERTER, DISTANCE_FROM_STRING_CONVERTER); } @Test(expected=IllegalArgumentException.class) public void test_register_FunctionalInterfaces_nullToString() { StringConvert test = new StringConvert(); test.register(DistanceNoAnnotations.class, null, DISTANCE_FROM_STRING_CONVERTER); } @Test(expected=IllegalArgumentException.class) public void test_register_FunctionalInterfaces_nullFromString() { StringConvert test = new StringConvert(); test.register(DistanceNoAnnotations.class, DISTANCE_TO_STRING_CONVERTER, null); } @Test(expected = IllegalStateException.class) public void test_registerFactory_cannotChangeSingleton() { StringConvert.INSTANCE.register( DistanceNoAnnotations.class, DISTANCE_TO_STRING_CONVERTER, DISTANCE_FROM_STRING_CONVERTER); } //------------------------------------------------------------------------- @Test public void test_registerMethods() { StringConvert test = new StringConvert(); test.registerMethods(DistanceNoAnnotations.class, "toString", "parse"); DistanceNoAnnotations d = new DistanceNoAnnotations(25); assertEquals("Distance[25m]", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceNoAnnotations.class, "25m").amount); StringConverter conv = test.findConverter(DistanceNoAnnotations.class); assertEquals(true, conv instanceof MethodsStringConverter); assertSame(conv, test.findConverter(DistanceNoAnnotations.class)); } @Test public void test_registerMethodsCharSequence() { StringConvert test = new StringConvert(); test.registerMethods(DistanceNoAnnotationsCharSequence.class, "toString", "parse"); DistanceNoAnnotationsCharSequence d = new DistanceNoAnnotationsCharSequence(25); assertEquals("Distance[25m]", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceNoAnnotationsCharSequence.class, "25m").amount); StringConverter conv = test.findConverter(DistanceNoAnnotationsCharSequence.class); assertEquals(true, conv instanceof MethodsStringConverter); assertSame(conv, test.findConverter(DistanceNoAnnotationsCharSequence.class)); } @Test(expected=IllegalArgumentException.class) public void test_registerMethods_nullClass() { StringConvert test = new StringConvert(); test.registerMethods(null, "toString", "parse"); } @Test(expected=IllegalArgumentException.class) public void test_registerMethods_nullToString() { StringConvert test = new StringConvert(); test.registerMethods(DistanceNoAnnotations.class, null, "parse"); } @Test(expected=IllegalArgumentException.class) public void test_registerMethods_nullFromString() { StringConvert test = new StringConvert(); test.registerMethods(DistanceNoAnnotations.class, "toString", null); } @Test(expected=IllegalArgumentException.class) public void test_registerMethods_noSuchToStringMethod() { StringConvert test = new StringConvert(); test.registerMethods(DistanceNoAnnotations.class, "rubbishName", "parse"); } @Test(expected=IllegalArgumentException.class) public void test_registerMethods_invalidToStringMethod() { StringConvert test = new StringConvert(); test.registerMethods(Thread.class, "currentThread", "toString"); } @Test(expected=IllegalArgumentException.class) public void test_registerMethods_noSuchFromStringMethod() { StringConvert test = new StringConvert(); test.registerMethods(DistanceNoAnnotations.class, "toString", "rubbishName"); } @Test(expected = IllegalStateException.class) public void ttest_registerMethods_cannotChangeSingleton() { StringConvert.INSTANCE.registerMethods(DistanceNoAnnotationsCharSequence.class, "toString", "parse"); } @Test public void test_registerMethods_classAlreadyRegistered() { StringConvert test = new StringConvert(); test.registerMethods(DistanceNoAnnotations.class, "toString", "parse"); test.registerMethods(DistanceNoAnnotations.class, "toString", "parse"); } //------------------------------------------------------------------------- @Test public void test_registerMethodConstructorCharSequence() { StringConvert test = new StringConvert(); test.registerMethodConstructor(DistanceNoAnnotationsCharSequence.class, "toString"); DistanceNoAnnotationsCharSequence d = new DistanceNoAnnotationsCharSequence(25); assertEquals("Distance[25m]", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceNoAnnotationsCharSequence.class, "25m").amount); StringConverter conv = test.findConverter(DistanceNoAnnotationsCharSequence.class); assertEquals(true, conv instanceof MethodConstructorStringConverter); assertSame(conv, test.findConverter(DistanceNoAnnotationsCharSequence.class)); } @Test public void test_registerMethodConstructor() { StringConvert test = new StringConvert(); test.registerMethodConstructor(DistanceNoAnnotations.class, "toString"); DistanceNoAnnotations d = new DistanceNoAnnotations(25); assertEquals("Distance[25m]", test.convertToString(d)); assertEquals(d.amount, test.convertFromString(DistanceNoAnnotations.class, "25m").amount); StringConverter conv = test.findConverter(DistanceNoAnnotations.class); assertEquals(true, conv instanceof MethodConstructorStringConverter); assertSame(conv, test.findConverter(DistanceNoAnnotations.class)); } @Test(expected=IllegalArgumentException.class) public void test_registerMethodConstructor_nullClass() { StringConvert test = new StringConvert(); test.registerMethodConstructor(null, "toString"); } @Test(expected=IllegalArgumentException.class) public void test_registerMethodConstructor_nullToString() { StringConvert test = new StringConvert(); test.registerMethodConstructor(DistanceNoAnnotations.class, null); } @Test(expected=IllegalArgumentException.class) public void test_registerMethodConstructor_noSuchConstructor() { StringConvert test = new StringConvert(); test.registerMethodConstructor(Enum.class, "toString"); } @Test(expected = IllegalStateException.class) public void ttest_registerMethodConstructor_cannotChangeSingleton() { StringConvert.INSTANCE.registerMethodConstructor(DistanceNoAnnotationsCharSequence.class, "toString"); } @Test public void test_registerMethodConstructor_classAlreadyRegistered() { StringConvert test = new StringConvert(); test.registerMethodConstructor(DistanceNoAnnotations.class, "toString"); test.registerMethodConstructor(DistanceNoAnnotations.class, "toString"); } //----------------------------------------------------------------------- @Test public void test_convert_toString() { assertEquals("StringConvert", new StringConvert().toString()); } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceToStringNoFromString.java0000664000175000017500000000235712603461407027732 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceToStringNoFromString { /** Amount. */ final int amount; public DistanceToStringNoFromString(int amount) { this.amount = amount; } public DistanceToStringNoFromString(String amount) { amount = amount.substring(0, amount.length() - 1); this.amount = Integer.parseInt(amount); } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/Status.java0000664000175000017500000000134312603461407023453 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Mock enum used to test renames. */ public enum Status { VALID, INVALID; } joda-convert-1.8.1/src/test/java/org/joda/convert/MockDistanceStringConverter.java0000664000175000017500000000321512603461407027613 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Conversion between an {@code DistanceMethodMethod} and a {@code String}. */ public enum MockDistanceStringConverter implements StringConverter { /** Singleton instance. */ INSTANCE; /** * Converts the {@code DistanceMethodMethod} to a {@code String}. * @param object the object to convert, not null * @return the converted string, may be null but generally not */ @Override public String convertToString(DistanceMethodMethod object) { return object.print(); } /** * Converts the {@code String} to an {@code DistanceMethodMethod}. * @param cls the class to convert to, not null * @param str the string to convert, not null * @return the converted integer, may be null but generally not */ @Override public DistanceMethodMethod convertFromString(Class cls, String str) { return DistanceMethodMethod.parse(str); } } joda-convert-1.8.1/src/test/java/org/joda/convert/TestNumericObjectArrayStringConverterFactory.java0000664000175000017500000001202312603461407033164 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.joda.convert.factory.NumericObjectArrayStringConverterFactory; import org.junit.Test; /** * Test NumericObjectArrayStringConverterFactory. */ public class TestNumericObjectArrayStringConverterFactory { @Test public void test_LongArray() { doTest(new Long[0], ""); doTest(new Long[] {5L}, "5"); doTest(new Long[] {null}, "-"); doTest(new Long[] {-1234L, null, 56789L, null, null, 5L}, "-1234,-,56789,-,-,5"); doTest(new Long[] {12345678912345L, 12345678912345L}, "12345678912345,12345678912345"); } private void doTest(Long[] array, String str) { StringConvert test = new StringConvert(true, NumericObjectArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(Long[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(Long[].class, str))); } //----------------------------------------------------------------------- @Test public void test_IntegerArray() { doTest(new Integer[0], ""); doTest(new Integer[] {5}, "5"); doTest(new Integer[] {null}, "-"); doTest(new Integer[] {-1234, null, 56789, null, null, 5}, "-1234,-,56789,-,-,5"); } private void doTest(Integer[] array, String str) { StringConvert test = new StringConvert(true, NumericObjectArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(Integer[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(Integer[].class, str))); } //----------------------------------------------------------------------- @Test public void test_ShortArray() { doTest(new Short[0], ""); doTest(new Short[] {5}, "5"); doTest(new Short[] {null}, "-"); doTest(new Short[] {-1234, null, 5678, null, null, 5}, "-1234,-,5678,-,-,5"); } private void doTest(Short[] array, String str) { StringConvert test = new StringConvert(true, NumericObjectArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(Short[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(Short[].class, str))); } //----------------------------------------------------------------------- @Test public void test_DoubleArray() { doTest(new Double[0], ""); doTest(new Double[] {5d}, "5.0"); doTest(new Double[] {null}, "-"); doTest(new Double[] {5.123456789d}, "5.123456789"); doTest(new Double[] {-1234d, null, 5678d, null, null, 5d}, "-1234.0,-,5678.0,-,-,5.0"); doTest(new Double[] {Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, -0.0d, +0.0d, 0d}, "NaN,-Infinity,Infinity,-0.0,0.0,0.0"); doTest(new Double[] {0.0000006d, 6000000000d}, "6.0E-7,6.0E9"); } private void doTest(Double[] array, String str) { StringConvert test = new StringConvert(true, NumericObjectArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(Double[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(Double[].class, str))); } //----------------------------------------------------------------------- @Test public void test_FloatArray() { doTest(new Float[0], ""); doTest(new Float[] {5f}, "5.0"); doTest(new Float[] {null}, "-"); doTest(new Float[] {5.1234f}, "5.1234"); doTest(new Float[] {-1234f, null, 5678f, null, null, 5f}, "-1234.0,-,5678.0,-,-,5.0"); doTest(new Float[] {Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, -0.0f, +0.0f, 0f}, "NaN,-Infinity,Infinity,-0.0,0.0,0.0"); doTest(new Float[] {0.0000006f, 6000000000f}, "6.0E-7,6.0E9"); } private void doTest(Float[] array, String str) { StringConvert test = new StringConvert(true, NumericObjectArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(Float[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(Float[].class, str))); } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceMethodConstructor.java0000664000175000017500000000241112603461407027326 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with annotated constructor and method. */ public class DistanceMethodConstructor { /** Amount. */ final int amount; public DistanceMethodConstructor(int amount) { this.amount = amount; } @FromString public DistanceMethodConstructor(String amount) { amount = amount.substring(0, amount.length() - 1); this.amount = Integer.parseInt(amount); } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceFromStringException.java0000664000175000017500000000241012603461407027610 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.text.ParseException; /** * Example class with annotated methods. */ public class DistanceFromStringException { /** Amount. */ final int amount; @FromString public static DistanceFromStringException parse(String amount) throws ParseException { throw new ParseException("Test", 2); } public DistanceFromStringException(int amount) { this.amount = amount; } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/test3/0000775000175000017500000000000012603461407022366 5ustar ebourgebourgjoda-convert-1.8.1/src/test/java/org/joda/convert/test3/Test3Factory.java0000664000175000017500000000160412603461407025564 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test3; import org.joda.convert.FromString; /** * Example class with annotated methods. */ public class Test3Factory { @FromString public static Test3Interface parse(String amount) { throw new UnsupportedOperationException(); } } joda-convert-1.8.1/src/test/java/org/joda/convert/test3/Test3SuperClass.java0000664000175000017500000000204712603461407026243 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test3; import org.joda.convert.FromString; import org.joda.convert.ToString; /** * Example class with annotated methods. */ public abstract class Test3SuperClass { @FromString public static Test3SuperClass parse(String amount) { amount = amount.substring(0, amount.length() - 1); return new Test3Class(Integer.parseInt(amount)); } @ToString public abstract String print(); } joda-convert-1.8.1/src/test/java/org/joda/convert/test3/Test3Class.java0000664000175000017500000000206312603461407025222 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test3; /** * Example class with annotated methods. */ public class Test3Class extends Test3SuperClass implements Test3Interface { /** Amount. */ public final int amount; public Test3Class(int amount) { this.amount = amount; } @Override public String print() { return amount + "g"; } @Override public String toString() { return "Weight[" + amount + "g]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/test3/Test3Interface.java0000664000175000017500000000163212603461407026056 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test3; import org.joda.convert.FromStringFactory; import org.joda.convert.ToString; /** * Example interface with annotated methods. */ @FromStringFactory(factory = Test3Factory.class) public interface Test3Interface { @ToString @Override String toString(); } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceToStringInvalidReturnType.java0000664000175000017500000000241712603461407030770 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceToStringInvalidReturnType { /** Amount. */ final int amount; public DistanceToStringInvalidReturnType(int amount) { this.amount = amount; } @FromString public DistanceToStringInvalidReturnType(String amount) { amount = amount.substring(0, amount.length() - 1); this.amount = Integer.parseInt(amount); } @ToString public Object print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/test1/0000775000175000017500000000000012603461407022364 5ustar ebourgebourgjoda-convert-1.8.1/src/test/java/org/joda/convert/test1/Test1Class.java0000664000175000017500000000237712603461407025226 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test1; import org.joda.convert.FromString; /** * Example class with annotated methods. */ public class Test1Class implements Test1Interface { /** Amount. */ public final int amount; @FromString public static Test1Class parse(String amount) { amount = amount.substring(0, amount.length() - 1); return new Test1Class(Integer.parseInt(amount)); } public Test1Class(int amount) { this.amount = amount; } @Override public String print() { return amount + "g"; } @Override public String toString() { return "Weight[" + amount + "g]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/test1/Test1Interface.java0000664000175000017500000000145512603461407026055 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test1; import org.joda.convert.ToString; /** * Example interface with annotated methods. */ public interface Test1Interface { @ToString String print(); } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceMethodMethodCharSequence.java0000664000175000017500000000243712603461407030520 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with annotated methods. */ public class DistanceMethodMethodCharSequence { /** Amount. */ final int amount; @FromString public static DistanceMethodMethodCharSequence parse(CharSequence amount) { String amt = amount.toString().substring(0, amount.length() - 1); return new DistanceMethodMethodCharSequence(Integer.parseInt(amt)); } public DistanceMethodMethodCharSequence(int amount) { this.amount = amount; } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceMethodAndConstructorAnnotations.java0000664000175000017500000000304012603461407032166 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceMethodAndConstructorAnnotations { /** Amount. */ final int amount; @FromString public static DistanceMethodAndConstructorAnnotations parse(String amount) { amount = amount.substring(0, amount.length() - 1); return new DistanceMethodAndConstructorAnnotations(Integer.parseInt(amount)); } public DistanceMethodAndConstructorAnnotations(int amount) { this.amount = amount; } @FromString public DistanceMethodAndConstructorAnnotations(String amount) { amount = amount.substring(0, amount.length() - 1); this.amount = Integer.parseInt(amount); } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceMethodMethod.java0000664000175000017500000000241312603461407026223 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with annotated methods. */ public class DistanceMethodMethod { /** Amount. */ final int amount; @FromString public static DistanceMethodMethod parse(String amount) { amount = amount.substring(0, amount.length() - 1); return new DistanceMethodMethod(Integer.parseInt(amount)); } public DistanceMethodMethod(int amount) { this.amount = amount; } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/TestNumericArrayStringConverterFactory.java0000664000175000017500000001113512603461407032040 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.joda.convert.factory.NumericArrayStringConverterFactory; import org.junit.Test; /** * Test NumericArrayStringConverterFactory. */ public class TestNumericArrayStringConverterFactory { @Test public void test_longArray() { doTest(new long[0], ""); doTest(new long[] {5}, "5"); doTest(new long[] {-1234, 56789}, "-1234,56789"); doTest(new long[] {12345678912345L, 12345678912345L}, "12345678912345,12345678912345"); } private void doTest(long[] array, String str) { StringConvert test = new StringConvert(true, NumericArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(long[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(long[].class, str))); } //----------------------------------------------------------------------- @Test public void test_intArray() { doTest(new int[0], ""); doTest(new int[] {5}, "5"); doTest(new int[] {-1234, 56789}, "-1234,56789"); } private void doTest(int[] array, String str) { StringConvert test = new StringConvert(true, NumericArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(int[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(int[].class, str))); } //----------------------------------------------------------------------- @Test public void test_shortArray() { doTest(new short[0], ""); doTest(new short[] {5}, "5"); doTest(new short[] {-1234, 5678}, "-1234,5678"); } private void doTest(short[] array, String str) { StringConvert test = new StringConvert(true, NumericArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(short[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(short[].class, str))); } //----------------------------------------------------------------------- @Test public void test_doubleArray() { doTest(new double[0], ""); doTest(new double[] {5d}, "5.0"); doTest(new double[] {5.123456789d}, "5.123456789"); doTest(new double[] {-1234d, 5678d}, "-1234.0,5678.0"); doTest(new double[] {Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, -0.0d, +0.0d, 0d}, "NaN,-Infinity,Infinity,-0.0,0.0,0.0"); doTest(new double[] {0.0000006d, 6000000000d}, "6.0E-7,6.0E9"); } private void doTest(double[] array, String str) { StringConvert test = new StringConvert(true, NumericArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(double[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(double[].class, str))); } //----------------------------------------------------------------------- @Test public void test_floatArray() { doTest(new float[0], ""); doTest(new float[] {5f}, "5.0"); doTest(new float[] {5.1234f}, "5.1234"); doTest(new float[] {-1234f, 5678f}, "-1234.0,5678.0"); doTest(new float[] {Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, -0.0f, +0.0f, 0f}, "NaN,-Infinity,Infinity,-0.0,0.0,0.0"); doTest(new float[] {0.0000006f, 6000000000f}, "6.0E-7,6.0E9"); } private void doTest(float[] array, String str) { StringConvert test = new StringConvert(true, NumericArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(float[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(float[].class, str))); } } joda-convert-1.8.1/src/test/java/org/joda/convert/SubNoAnnotations.java0000664000175000017500000000153312603461407025435 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with annotated methods. */ public class SubNoAnnotations extends DistanceMethodMethod { public SubNoAnnotations(int amount) { super(amount); } } joda-convert-1.8.1/src/test/java/org/joda/convert/TestBooleanArrayStringConverterFactory.java0000664000175000017500000000307512603461407032021 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.joda.convert.factory.BooleanArrayStringConverterFactory; import org.junit.Test; /** * Test BooleanArrayStringConverterFactory. */ public class TestBooleanArrayStringConverterFactory { @Test public void test_longArray() { doTest(new boolean[0], ""); doTest(new boolean[] {true}, "T"); doTest(new boolean[] {false}, "F"); doTest(new boolean[] {true, true, false, true, false, false}, "TTFTFF"); } private void doTest(boolean[] array, String str) { StringConvert test = new StringConvert(true, BooleanArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(boolean[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(boolean[].class, str))); } } joda-convert-1.8.1/src/test/java/org/joda/convert/test4/0000775000175000017500000000000012603461407022367 5ustar ebourgebourgjoda-convert-1.8.1/src/test/java/org/joda/convert/test4/Test4Interface.java0000664000175000017500000000161112603461407026055 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test4; import org.joda.convert.FromStringFactory; import org.joda.convert.ToString; /** * Example interface with annotated methods. */ @FromStringFactory(factory = Test4Factory.class) public interface Test4Interface { @ToString String print(); } joda-convert-1.8.1/src/test/java/org/joda/convert/test4/Test4Class.java0000664000175000017500000000203312603461407025221 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test4; /** * Example class with annotated methods. */ public class Test4Class implements Test4Interface { /** Amount. */ public final int amount; public Test4Class(int amount) { this.amount = amount; } @Override public String print() { return amount + "g"; } @Override public String toString() { return "Weight[" + amount + "g]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/test4/Test4Factory.java0000664000175000017500000000222212603461407025563 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test4; import org.joda.convert.FromString; /** * Example class with annotated methods. */ public class Test4Factory { @FromString public static Test4Interface parseInterface(String amount) { amount = amount.substring(0, amount.length() - 1); return new Test4Class(Integer.parseInt(amount)); } @FromString public static Test4Class parseClass(String amount) { amount = amount.substring(0, amount.length() - 1); return new Test4Class(Integer.parseInt(amount)); } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceWithFactoryFactory.java0000664000175000017500000000164112603461407027437 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example factory. */ public class DistanceWithFactoryFactory { @FromString public static DistanceWithFactory parse(String amount) { amount = amount.substring(0, amount.length() - 1); return new DistanceWithFactory(Integer.parseInt(amount)); } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceFromStringInvalidParameter.java0000664000175000017500000000231012603461407031100 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceFromStringInvalidParameter { /** Amount. */ final int amount; @FromString public static DistanceFromStringInvalidParameter parse(Object amount) { return null; } public DistanceFromStringInvalidParameter(int amount) { this.amount = amount; } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/MockIntegerStringConverter.java0000664000175000017500000000304512603461407027457 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Conversion between an {@code Integer} and a {@code String}. */ public enum MockIntegerStringConverter implements StringConverter { /** Singleton instance. */ INSTANCE; /** * Converts the {@code Integer} to a {@code String}. * @param object the object to convert, not null * @return the converted string, may be null but generally not */ @Override public String convertToString(Integer object) { return object.toString(); } /** * Converts the {@code String} to an {@code Integer}. * @param cls the class to convert to, not null * @param str the string to convert, not null * @return the converted integer, may be null but generally not */ @Override public Integer convertFromString(Class cls, String str) { return new Integer(str); } } joda-convert-1.8.1/src/test/java/org/joda/convert/TestJDKStringConverters.java0000664000175000017500000004501712603461407026710 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.net.InetAddress; import java.net.URI; import java.net.URL; import java.util.Arrays; import java.util.Calendar; import java.util.Currency; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.junit.Test; /** * Test JDKStringConverters. */ public class TestJDKStringConverters { @Test public void test_String() { JDKStringConverter test = JDKStringConverter.STRING; doTest(test, String.class, "Hello", "Hello"); } @Test public void test_StringBuffer() { JDKStringConverter test = JDKStringConverter.STRING_BUFFER; Object obj = new StringBuffer("Hello"); assertEquals(StringBuffer.class, test.getType()); assertEquals("Hello", test.convertToString(obj)); StringBuffer back = (StringBuffer) test.convertFromString(StringBuffer.class, "Hello"); assertEquals("Hello", back.toString()); } @Test public void test_StringBuilder() { JDKStringConverter test = JDKStringConverter.STRING_BUILDER; Object obj = new StringBuilder("Hello"); assertEquals(StringBuilder.class, test.getType()); assertEquals("Hello", test.convertToString(obj)); StringBuilder back = (StringBuilder) test.convertFromString(StringBuilder.class, "Hello"); assertEquals("Hello", back.toString()); } @Test public void test_CharSequence() { JDKStringConverter test = JDKStringConverter.CHAR_SEQUENCE; doTest(test, CharSequence.class, "Hello", "Hello"); doTest(test, CharSequence.class, new StringBuffer("Hello"), "Hello", "Hello"); doTest(test, CharSequence.class, new StringBuilder("Hello"), "Hello", "Hello"); } @Test public void test_Long() { JDKStringConverter test = JDKStringConverter.LONG; doTest(test, Long.class, Long.valueOf(12L), "12"); } @Test public void test_Int() { JDKStringConverter test = JDKStringConverter.INTEGER; doTest(test, Integer.class, Integer.valueOf(12), "12"); } @Test public void test_Short() { JDKStringConverter test = JDKStringConverter.SHORT; doTest(test, Short.class, Short.valueOf((byte) 12), "12"); } @Test public void test_Character() { JDKStringConverter test = JDKStringConverter.CHARACTER; doTest(test, Character.class, Character.valueOf('a'), "a"); doTest(test, Character.class, Character.valueOf('z'), "z"); } @Test(expected=IllegalArgumentException.class) public void test_Character_fail() { JDKStringConverter.CHARACTER.convertFromString(Character.class, "RUBBISH"); } @Test public void test_charArray() { JDKStringConverter test = JDKStringConverter.CHAR_ARRAY; char[] array = new char[] {'M', 'a', 'p'}; String str = "Map"; assertEquals(char[].class, test.getType()); assertEquals(str, test.convertToString(array)); assertTrue(Arrays.equals(array, (char[]) test.convertFromString(char[].class, str))); } @Test public void test_Byte() { JDKStringConverter test = JDKStringConverter.BYTE; doTest(test, Byte.class, Byte.valueOf((byte) 12), "12"); } @Test public void test_byteArray1() { JDKStringConverter test = JDKStringConverter.BYTE_ARRAY; byte[] array = new byte[] {77, 97, 112}; String str = "TWFw"; assertEquals(byte[].class, test.getType()); assertEquals(str, test.convertToString(array)); assertTrue(Arrays.equals(array, (byte[]) test.convertFromString(byte[].class, str))); } @Test public void test_byteArray2() { JDKStringConverter test = JDKStringConverter.BYTE_ARRAY; byte[] array = new byte[] {77, 97}; String str = "TWE="; assertEquals(byte[].class, test.getType()); assertEquals(str, test.convertToString(array)); assertTrue(Arrays.equals(array, (byte[]) test.convertFromString(byte[].class, str))); } @Test public void test_byteArray3() { JDKStringConverter test = JDKStringConverter.BYTE_ARRAY; byte[] array = new byte[] {77}; String str = "TQ=="; assertEquals(byte[].class, test.getType()); assertEquals(str, test.convertToString(array)); assertTrue(Arrays.equals(array, (byte[]) test.convertFromString(byte[].class, str))); } @Test public void test_byteArray4() { JDKStringConverter test = JDKStringConverter.BYTE_ARRAY; byte[] array = new byte[] {73, 97, 112, 77}; String str = "SWFwTQ=="; assertEquals(byte[].class, test.getType()); assertEquals(str, test.convertToString(array)); assertTrue(Arrays.equals(array, (byte[]) test.convertFromString(byte[].class, str))); } @Test public void test_Boolean() { JDKStringConverter test = JDKStringConverter.BOOLEAN; doTest(test, Boolean.class, Boolean.TRUE, "true"); doTest(test, Boolean.class, Boolean.FALSE, "false"); } @Test(expected=IllegalArgumentException.class) public void test_Boolean_fail() { JDKStringConverter.BOOLEAN.convertFromString(Boolean.class, "RUBBISH"); } @Test public void test_Double() { JDKStringConverter test = JDKStringConverter.DOUBLE; doTest(test, Double.class, Double.valueOf(12.4d), "12.4"); } @Test public void test_Float() { JDKStringConverter test = JDKStringConverter.FLOAT; doTest(test, Float.class, Float.valueOf(12.2f), "12.2"); } @Test public void test_BigInteger() { JDKStringConverter test = JDKStringConverter.BIG_INTEGER; doTest(test, BigInteger.class, BigInteger.valueOf(12L), "12"); } @Test public void test_BigDecimal() { JDKStringConverter test = JDKStringConverter.BIG_DECIMAL; doTest(test, BigDecimal.class, BigDecimal.valueOf(12.23d), "12.23"); } @Test public void test_AtomicLong() { JDKStringConverter test = JDKStringConverter.ATOMIC_LONG; AtomicLong obj = new AtomicLong(12); assertEquals(AtomicLong.class, test.getType()); assertEquals("12", test.convertToString(obj)); AtomicLong back = (AtomicLong) test.convertFromString(AtomicLong.class, "12"); assertEquals(12, back.get()); } @Test public void test_AtomicInteger() { JDKStringConverter test = JDKStringConverter.ATOMIC_INTEGER; AtomicInteger obj = new AtomicInteger(12); assertEquals(AtomicInteger.class, test.getType()); assertEquals("12", test.convertToString(obj)); AtomicInteger back = (AtomicInteger) test.convertFromString(AtomicInteger.class, "12"); assertEquals(12, back.get()); } @Test public void test_AtomicBoolean_true() { JDKStringConverter test = JDKStringConverter.ATOMIC_BOOLEAN; AtomicBoolean obj = new AtomicBoolean(true); assertEquals(AtomicBoolean.class, test.getType()); assertEquals("true", test.convertToString(obj)); AtomicBoolean back = (AtomicBoolean) test.convertFromString(AtomicBoolean.class, "true"); assertEquals(true, back.get()); } @Test public void test_AtomicBoolean_false() { JDKStringConverter test = JDKStringConverter.ATOMIC_BOOLEAN; AtomicBoolean obj = new AtomicBoolean(false); assertEquals(AtomicBoolean.class, test.getType()); assertEquals("false", test.convertToString(obj)); AtomicBoolean back = (AtomicBoolean) test.convertFromString(AtomicBoolean.class, "false"); assertEquals(false, back.get()); } @Test(expected=IllegalArgumentException.class) public void test_AtomicBoolean_fail() { JDKStringConverter.ATOMIC_BOOLEAN.convertFromString(AtomicBoolean.class, "RUBBISH"); } @Test public void test_Locale() { JDKStringConverter test = JDKStringConverter.LOCALE; doTest(test, Locale.class, new Locale("en"), "en"); doTest(test, Locale.class, new Locale("en", "GB"), "en_GB"); doTest(test, Locale.class, new Locale("en", "GB", "VARIANT_B"), "en_GB_VARIANT_B"); } @Test public void test_Class() { JDKStringConverter test = JDKStringConverter.CLASS; doTest(test, Class.class, Locale.class, "java.util.Locale"); doTest(test, Class.class, FromString.class, "org.joda.convert.FromString"); } @Test(expected=RuntimeException.class) public void test_Class_fail() { JDKStringConverter.CLASS.convertFromString(Class.class, "RUBBISH"); } @Test public void test_Class_withRename() { try { JDKStringConverter.CLASS.convertFromString(Class.class, "org.foo.StringConvert"); fail(); } catch (RuntimeException ex) { // expected } RenameHandler.INSTANCE.renamedType("org.foo.StringConvert", StringConvert.class); assertEquals(StringConvert.class, JDKStringConverter.CLASS.convertFromString(Class.class, "org.foo.StringConvert")); } @Test public void test_Package() { JDKStringConverter test = JDKStringConverter.PACKAGE; doTest(test, Package.class, Locale.class.getPackage(), "java.util"); doTest(test, Package.class, FromString.class.getPackage(), "org.joda.convert"); } @Test public void test_Currency() { JDKStringConverter test = JDKStringConverter.CURRENCY; doTest(test, Currency.class, Currency.getInstance("GBP"), "GBP"); doTest(test, Currency.class, Currency.getInstance("USD"), "USD"); } @Test public void test_TimeZone() { JDKStringConverter test = JDKStringConverter.TIME_ZONE; doTest(test, TimeZone.class, TimeZone.getTimeZone("Europe/London"), "Europe/London"); doTest(test, TimeZone.class, TimeZone.getTimeZone("America/New_York"), "America/New_York"); } @Test public void test_UUID() { JDKStringConverter test = JDKStringConverter.UUID; UUID uuid = UUID.randomUUID(); doTest(test, UUID.class, uuid, uuid.toString()); } @Test public void test_URL() throws Exception { JDKStringConverter test = JDKStringConverter.URL; doTest(test, URL.class, new URL("http://localhost:8080/my/test"), "http://localhost:8080/my/test"); doTest(test, URL.class, new URL(null, "ftp:world"), "ftp:world"); } @Test(expected=RuntimeException.class) public void test_URL_invalidFormat() { JDKStringConverter.URL.convertFromString(URL.class, "RUBBISH:RUBBISH"); } @Test public void test_URI() { JDKStringConverter test = JDKStringConverter.URI; doTest(test, URI.class, URI.create("http://localhost:8080/my/test"), "http://localhost:8080/my/test"); doTest(test, URI.class, URI.create("/my/test"), "/my/test"); doTest(test, URI.class, URI.create("/my/../test"), "/my/../test"); doTest(test, URI.class, URI.create("urn:hello"), "urn:hello"); } @Test public void test_InetAddress() throws Exception { JDKStringConverter test = JDKStringConverter.INET_ADDRESS; doTest(test, InetAddress.class, InetAddress.getByName("1.2.3.4"), "1.2.3.4"); InetAddress obj = InetAddress.getByName("2001:0db8:85a3:0000:0000:8a2e:0370:7334"); String str = test.convertToString(obj); assertTrue(str.equals("2001:db8:85a3:0:0:8a2e:370:7334") || str.equals("2001:db8:85a3::8a2e:370:7334")); assertEquals(obj, test.convertFromString(InetAddress.class, str)); assertEquals(obj, test.convertFromString(InetAddress.class, "2001:db8:85a3:0:0:8a2e:370:7334")); assertEquals(obj, test.convertFromString(InetAddress.class, "2001:db8:85a3::8a2e:370:7334")); } // @Test(expected=RuntimeException.class) // public void test_InetAddress_invalidFormat() { // JDKStringConverter.INET_ADDRESS.convertFromString(InetAddress.class, "RUBBISH"); // } @Test public void test_File() { JDKStringConverter test = JDKStringConverter.FILE; File file = new File("/path/to/file"); doTest(test, File.class, file, file.toString()); } @SuppressWarnings("deprecation") @Test public void test_Date() { TimeZone zone = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("Europe/Paris")); JDKStringConverter test = JDKStringConverter.DATE; doTest(test, Date.class, new Date(2010 - 1900, 9 - 1, 3, 12, 34, 5), "2010-09-03T12:34:05.000+02:00"); doTest(test, Date.class, new Date(2011 - 1900, 1 - 1, 4, 12, 34, 5), "2011-01-04T12:34:05.000+01:00"); } finally { TimeZone.setDefault(zone); } } @Test(expected=RuntimeException.class) public void test_Date_invalidLength() { JDKStringConverter.DATE.convertFromString(Date.class, "2010-09-03"); } @Test(expected=RuntimeException.class) public void test_Date_invalidFormat() { JDKStringConverter.DATE.convertFromString(Date.class, "2010-09-03XXX:34:05.000+02:00"); } @Test public void test_Calendar() { JDKStringConverter test = JDKStringConverter.CALENDAR; GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris")); cal.set(2010, 9 - 1, 3, 12, 34, 5); cal.set(Calendar.MILLISECOND, 0); doTest(test, Calendar.class, cal, "2010-09-03T12:34:05.000+02:00[Europe/Paris]"); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris")); cal2.set(2011, 1 - 1, 4, 12, 34, 5); cal2.set(Calendar.MILLISECOND, 0); doTest(test, Calendar.class, cal2, "2011-01-04T12:34:05.000+01:00[Europe/Paris]"); } @Test(expected=RuntimeException.class) public void test_Calendar_invalidLength() { JDKStringConverter.CALENDAR.convertFromString(GregorianCalendar.class, "2010-09-03"); } @Test(expected=RuntimeException.class) public void test_Calendar_invalidFormat() { JDKStringConverter.CALENDAR.convertFromString(GregorianCalendar.class, "2010-09-03XXX:34:05.000+02:00[Europe/London]"); } @Test(expected=RuntimeException.class) public void test_Calendar_notGregorian() { JDKStringConverter.CALENDAR.convertToString(new Calendar() { private static final long serialVersionUID = 1L; @Override public void roll(int field, boolean up) { } @Override public int getMinimum(int field) { return 0; } @Override public int getMaximum(int field) { return 0; } @Override public int getLeastMaximum(int field) { return 0; } @Override public int getGreatestMinimum(int field) { return 0; } @Override protected void computeTime() { } @Override protected void computeFields() { } @Override public void add(int field, int amount) { } }); } @Test public void test_Enum() { TypedStringConverter test = StringConvert.create().findTypedConverter(RoundingMode.class); assertEquals(RoundingMode.class, test.getEffectiveType()); assertEquals("CEILING", test.convertToString(RoundingMode.CEILING)); assertEquals(RoundingMode.CEILING, test.convertFromString(RoundingMode.class, "CEILING")); } @Test(expected=RuntimeException.class) public void test_Enum_invalidConstant() { TypedStringConverter test = StringConvert.create().findTypedConverter(RoundingMode.class); test.convertFromString(RoundingMode.class, "RUBBISH"); } @Test public void test_Enum_withRename() { TypedStringConverter test = StringConvert.create().findTypedConverter(Status.class); assertEquals("VALID", test.convertToString(Status.VALID)); assertEquals("INVALID", test.convertToString(Status.INVALID)); assertEquals(Status.VALID, test.convertFromString(Status.class, "VALID")); assertEquals(Status.INVALID, test.convertFromString(Status.class, "INVALID")); try { test.convertFromString(Status.class, "OK"); fail(); } catch (RuntimeException ex) { // expected } RenameHandler.INSTANCE.renamedEnum("OK", Status.VALID); assertEquals(Status.VALID, test.convertFromString(Status.class, "OK")); assertEquals(Status.VALID, test.convertFromString(Status.class, "VALID")); assertEquals(Status.INVALID, test.convertFromString(Status.class, "INVALID")); } //----------------------------------------------------------------------- public void doTest(JDKStringConverter test, Class cls, Object obj, String str) { doTest(test, cls, obj, str, obj); } public void doTest(JDKStringConverter test, Class cls, Object obj, String str, Object objFromStr) { assertEquals(cls, test.getType()); assertEquals(str, test.convertToString(obj)); assertEquals(objFromStr, test.convertFromString(cls, str)); } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceFromStringInvalidReturnType.java0000664000175000017500000000225712603461407031313 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceFromStringInvalidReturnType { /** Amount. */ final int amount; @FromString public static Integer parse(String amount) { return null; } public DistanceFromStringInvalidReturnType(int amount) { this.amount = amount; } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceFromStringInvalidParameterCount.java0000664000175000017500000000234212603461407032116 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceFromStringInvalidParameterCount { /** Amount. */ final int amount; @FromString public static DistanceFromStringInvalidParameterCount parse(String amount, int value) { return null; } public DistanceFromStringInvalidParameterCount(int amount) { this.amount = amount; } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/test2/0000775000175000017500000000000012603461407022365 5ustar ebourgebourgjoda-convert-1.8.1/src/test/java/org/joda/convert/test2/Test2Class.java0000664000175000017500000000203312603461407025215 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test2; /** * Example class with annotated methods. */ public class Test2Class implements Test2Interface { /** Amount. */ public final int amount; public Test2Class(int amount) { this.amount = amount; } @Override public String print() { return amount + "g"; } @Override public String toString() { return "Weight[" + amount + "g]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/test2/Test2Interface.java0000664000175000017500000000161112603461407026051 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test2; import org.joda.convert.FromStringFactory; import org.joda.convert.ToString; /** * Example interface with annotated methods. */ @FromStringFactory(factory = Test2Factory.class) public interface Test2Interface { @ToString String print(); } joda-convert-1.8.1/src/test/java/org/joda/convert/test2/Test2Factory.java0000664000175000017500000000170112603461407025560 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert.test2; import org.joda.convert.FromString; /** * Example class with annotated methods. */ public class Test2Factory { @FromString public static Test2Class parse(String amount) { amount = amount.substring(0, amount.length() - 1); return new Test2Class(Integer.parseInt(amount)); } } joda-convert-1.8.1/src/test/java/org/joda/convert/TestByteObjectArrayStringConverterFactory.java0000664000175000017500000000317012603461407032470 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.joda.convert.factory.ByteObjectArrayStringConverterFactory; import org.junit.Test; /** * Test ByteObjectArrayStringConverterFactory. */ public class TestByteObjectArrayStringConverterFactory { @Test public void test_ByteArray() { doTest(new Byte[0], ""); doTest(new Byte[] {(byte) 0}, "00"); doTest(new Byte[] {null}, "--"); doTest(new Byte[] {(byte) 0, (byte) 1, null, null, (byte) 15, (byte) 16, (byte) 127, (byte) -128, (byte) -1}, "0001----0F107F80FF"); } private void doTest(Byte[] array, String str) { StringConvert test = new StringConvert(true, ByteObjectArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(Byte[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(Byte[].class, str))); } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceWithFactory.java0000664000175000017500000000176512603461407026116 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ @FromStringFactory(factory = DistanceWithFactoryFactory.class) public class DistanceWithFactory { /** Amount. */ final int amount; public DistanceWithFactory(int amount) { this.amount = amount; } @ToString @Override public String toString() { return amount + "m"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceMethodConstructorCharSequence.java0000664000175000017500000000242112603461407031616 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with annotated constructor and method. */ public class DistanceMethodConstructorCharSequence { /** Amount. */ final int amount; public DistanceMethodConstructorCharSequence(int amount) { this.amount = amount; } @FromString public DistanceMethodConstructorCharSequence(CharSequence amount) { String amt = amount.toString().substring(0, amount.length() - 1); this.amount = Integer.parseInt(amt); } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/Validity.java0000664000175000017500000000134112603461407023753 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Mock enum with a converter. */ public enum Validity { VALID, INVALID; } ././@LongLink0000644000000000000000000000015200000000000011601 Lustar rootrootjoda-convert-1.8.1/src/test/java/org/joda/convert/DistanceFromStringConstructorInvalidParameterCount.javajoda-convert-1.8.1/src/test/java/org/joda/convert/DistanceFromStringConstructorInvalidParameterCount0000664000175000017500000000237212603461407033447 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceFromStringConstructorInvalidParameterCount { /** Amount. */ final int amount; @FromString public DistanceFromStringConstructorInvalidParameterCount(String amount, int value) { this.amount = 0; } public DistanceFromStringConstructorInvalidParameterCount(int amount) { this.amount = amount; } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceFromStringNoToString.java0000664000175000017500000000236112603461407027725 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceFromStringNoToString { /** Amount. */ final int amount; public DistanceFromStringNoToString(int amount) { this.amount = amount; } @FromString public DistanceFromStringNoToString(String amount) { amount = amount.substring(0, amount.length() - 1); this.amount = Integer.parseInt(amount); } public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceToStringException.java0000664000175000017500000000255112603461407027275 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import java.text.ParseException; /** * Example class with annotated methods. */ public class DistanceToStringException { /** Amount. */ final int amount; @FromString public static DistanceToStringException parse(String amount) { amount = amount.substring(0, amount.length() - 1); return new DistanceToStringException(Integer.parseInt(amount)); } public DistanceToStringException(int amount) { this.amount = amount; } @ToString public String print() throws ParseException { throw new ParseException("Test", 2); } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/SubMethodConstructor.java0000664000175000017500000000157412603461407026336 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with annotated methods. */ public class SubMethodConstructor extends DistanceMethodConstructor { @FromString public SubMethodConstructor(String amount) { super(amount); } } joda-convert-1.8.1/src/test/java/org/joda/convert/TestBooleanObjectArrayStringConverterFactory.java0000664000175000017500000000322512603461407033145 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.joda.convert.factory.BooleanObjectArrayStringConverterFactory; import org.junit.Test; /** * Test BooleanObjectArrayStringConverterFactory. */ public class TestBooleanObjectArrayStringConverterFactory { @Test public void test_longArray() { doTest(new Boolean[0], ""); doTest(new Boolean[] {true}, "T"); doTest(new Boolean[] {false}, "F"); doTest(new Boolean[] {null}, "-"); doTest(new Boolean[] {true, true, false, null, true, false, null, null, false}, "TTF-TF--F"); } private void doTest(Boolean[] array, String str) { StringConvert test = new StringConvert(true, BooleanObjectArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(Boolean[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(Boolean[].class, str))); } } joda-convert-1.8.1/src/test/java/org/joda/convert/TestCharObjectArrayStringConverterFactory.java0000664000175000017500000000340012603461407032436 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.joda.convert.factory.CharObjectArrayStringConverterFactory; import org.junit.Test; /** * Test CharObjectArrayStringConverterFactory. */ public class TestCharObjectArrayStringConverterFactory { @Test public void test_CharacterArray() { doTest(new Character[0], ""); doTest(new Character[] {'T'}, "T"); doTest(new Character[] {'-'}, "-"); doTest(new Character[] {null}, "\\-"); doTest(new Character[] {'J', '-', 'T'}, "J-T"); doTest(new Character[] {'\\', '\\', null}, "\\\\\\\\\\-"); doTest(new Character[] {'-', 'H', 'e', null, null, 'o'}, "-He\\-\\-o"); } private void doTest(Character[] array, String str) { StringConvert test = new StringConvert(true, CharObjectArrayStringConverterFactory.INSTANCE); assertEquals(str, test.convertToString(array)); assertEquals(str, test.convertToString(Character[].class, array)); assertTrue(Arrays.equals(array, test.convertFromString(Character[].class, str))); } } joda-convert-1.8.1/src/test/java/org/joda/convert/SuperFactorySuper.java0000664000175000017500000000254112603461407025636 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class which matches the case where a superclass acts as the sole factory. */ public class SuperFactorySuper { /** Amount. */ final int amount; @FromString public static SuperFactorySuper parse(String amount) { amount = amount.substring(0, amount.length() - 1); int i = Integer.parseInt(amount); return i > 10 ? new SuperFactorySuper(i) : new SuperFactorySub(i); } public SuperFactorySuper(int amount) { this.amount = amount; } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceTwoFromStringMethodAnnotations.java0000664000175000017500000000341012603461407032003 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceTwoFromStringMethodAnnotations { /** Amount. */ final int amount; public DistanceTwoFromStringMethodAnnotations(int amount) { this.amount = amount; } @FromString public static DistanceTwoFromStringMethodAnnotations parse(String amount) { amount = amount.substring(0, amount.length() - 1); return new DistanceTwoFromStringMethodAnnotations(Integer.parseInt(amount)); } @FromString public static DistanceTwoFromStringMethodAnnotations parse2(String amount) { amount = amount.substring(0, amount.length() - 1); return new DistanceTwoFromStringMethodAnnotations(Integer.parseInt(amount)); } public DistanceTwoFromStringMethodAnnotations(String amount) { amount = amount.substring(0, amount.length() - 1); this.amount = Integer.parseInt(amount); } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/ValidityStringConverter.java0000664000175000017500000000315312603461407027035 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Conversion between an {@code Validity} and a {@code String}. */ public enum ValidityStringConverter implements StringConverter { /** Singleton instance. */ INSTANCE; /** * Converts the {@code Validity} to a {@code String}. * @param object the object to convert, not null * @return the converted string, may be null but generally not */ @Override public String convertToString(Validity object) { return object.name(); } /** * Converts the {@code String} to an {@code Validity}. * @param cls the class to convert to, not null * @param str the string to convert, not null * @return the converted integer, may be null but generally not */ @Override public Validity convertFromString(Class cls, String str) { // handle renamed constant if (str.equals("OK")) { return Validity.VALID; } return Validity.valueOf(str); } } joda-convert-1.8.1/src/test/java/org/joda/convert/SubMethodMethod.java0000664000175000017500000000205012603461407025217 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with annotated methods. */ public class SubMethodMethod extends DistanceMethodMethod { @FromString public static SubMethodMethod parse(String amount) { amount = amount.substring(0, amount.length() - 1); return new SubMethodMethod(Integer.parseInt(amount)); } public SubMethodMethod(int amount) { super(amount); } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceFromStringConstructorInvalidParameter.java0000664000175000017500000000234012603461407033351 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceFromStringConstructorInvalidParameter { /** Amount. */ final int amount; @FromString public DistanceFromStringConstructorInvalidParameter(Object amount) { this.amount = 0; } public DistanceFromStringConstructorInvalidParameter(int amount) { this.amount = amount; } @ToString public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceNoAnnotations.java0000664000175000017500000000250712603461407026440 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceNoAnnotations { /** Amount. */ final int amount; public static DistanceNoAnnotations parse(String amount) { return new DistanceNoAnnotations(amount); } public DistanceNoAnnotations(int amount) { this.amount = amount; } public DistanceNoAnnotations(String amount) { amount = amount.substring(0, amount.length() - 1); this.amount = Integer.parseInt(amount); } public String print() { return amount + "m"; } @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/TestStringConverterFactory.java0000664000175000017500000000450112603461407027515 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * Test StringConvert factory. */ public class TestStringConverterFactory { @Test public void test_constructor() { StringConvert test = new StringConvert(true, new Factory1()); assertEquals(DistanceMethodMethod.class, test.findTypedConverter(DistanceMethodMethod.class).getEffectiveType()); } @Test(expected = IllegalArgumentException.class) public void test_constructor_null() { new StringConvert(true, (StringConverterFactory[]) null); } @Test(expected = IllegalArgumentException.class) public void test_constructor_nullInArray() { new StringConvert(true, new StringConverterFactory[] {null}); } @Test public void test_registerFactory() { StringConvert test = new StringConvert(); test.registerFactory(new Factory1()); assertEquals(DistanceMethodMethod.class, test.findTypedConverter(DistanceMethodMethod.class).getEffectiveType()); } @Test(expected = IllegalArgumentException.class) public void test_registerFactory_null() { StringConvert test = new StringConvert(); test.registerFactory(null); } @Test(expected = IllegalStateException.class) public void test_registerFactory_cannotChangeSingleton() { StringConvert.INSTANCE.registerFactory(new Factory1()); } static class Factory1 implements StringConverterFactory { @Override public StringConverter findConverter(Class cls) { if (cls == DistanceMethodMethod.class) { return MockDistanceStringConverter.INSTANCE; } return null; } } } joda-convert-1.8.1/src/test/java/org/joda/convert/DistanceTwoToStringAnnotations.java0000664000175000017500000000242512603461407030326 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class with no annotations. */ public class DistanceTwoToStringAnnotations { /** Amount. */ final int amount; public DistanceTwoToStringAnnotations(int amount) { this.amount = amount; } @FromString public DistanceTwoToStringAnnotations(String amount) { amount = amount.substring(0, amount.length() - 1); this.amount = Integer.parseInt(amount); } @ToString public String print() { return amount + "m"; } @ToString @Override public String toString() { return "Distance[" + amount + "m]"; } } joda-convert-1.8.1/src/test/java/org/joda/convert/SuperFactorySub.java0000664000175000017500000000160212603461407025266 0ustar ebourgebourg/* * Copyright 2010-present Stephen Colebourne * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joda.convert; /** * Example class which matches the case where a superclass acts as the sole factory. */ public class SuperFactorySub extends SuperFactorySuper { public SuperFactorySub(int amount) { super(amount); } } joda-convert-1.8.1/src/changes/0000775000175000017500000000000012603461407015650 5ustar ebourgebourgjoda-convert-1.8.1/src/changes/changes.xml0000664000175000017500000001270112603461407020003 0ustar ebourgebourg Java convert - Changes Stephen Colebourne More lenient test of InetAddress format. Fixes #13. Make Guava dependency optional again. Add test run to ensure this Fixes #14. Avoid use of java.xml.DatatypeConverter which may help Android. Fixes #7. Add support for Guava TypeToken and java.lang.reflect.Type. Most string formats of TypeToken are handled, but not all (eg. union types, mult-dimensional arrays). The Guava dependency is completely optional, loaded by reflection. Avoid possible null pointer exception when loading a class. Add ability to extract the effective type. Useful when serializing data to avoid exposing private subclasses. The effective type is the class defining the FromString. Fixes #8. Add support for renaming types and enum constants. Fixes #6. Add support for all primitive object arrays. Add support for boolean[]. Add support for numeric primitive arrays. Add support for char[] and byte[]. Add StringConverterFactory for more flexible initialization. Weaken generics to better support framework-level access. Add isConvertible() method. Validate the @FromString is a static method. Change to use Maven plugin for OSGi, changing some published info. Home page at GitHub. Add support for FromString using a factory. Issue #5. Change to use m2e Maven Eclipse. Fix OSGI manifest. Add register method designed for JDK 1.8 method references or lambdas. Change to requiring JDK 1.6. Add alternate package locations for JSR-310 classes. Add support for CharSequence based fromString methods. Add support for JSR-310 by reflection, avoiding a dependency. Allow registration of conversions by method name. Allow toString conversion to specify the desired type. Allow conversion of primitive types. Allow conversion of primitive types Enable superclass factories. Lots of tests and fixes. Initial checkin. joda-convert-1.8.1/.gitignore0000664000175000017500000000014112603461407015435 0ustar ebourgebourg/bin/ /target/ *.log /tests/ .checkstyle .classpath .project /.settings/ /nbproject/ .idea *.iml joda-convert-1.8.1/pom.xml0000664000175000017500000005343612603461407015001 0ustar ebourgebourg 4.0.0 org.joda joda-convert jar Joda-Convert 1.8.1 Library to convert Objects to and from String http://www.joda.org/joda-convert/ GitHub https://github.com/JodaOrg/joda-convert/issues 2010 jodastephen Stephen Colebourne Project Lead 0 https://github.com/jodastephen Chris Kent https://github.com/cjkent Raman Gupta https://github.com/rocketraman Apache 2 http://www.apache.org/licenses/LICENSE-2.0.txt repo scm:git:https://github.com/JodaOrg/joda-convert.git scm:git:git@github.com:JodaOrg/joda-convert.git https://github.com/JodaOrg/joda-convert Joda.org http://www.joda.org src/main/resources META-INF ${project.basedir} LICENSE.txt NOTICE.txt org.apache.maven.plugins maven-checkstyle-plugin run-checkstyle process-sources checkstyle org.apache.maven.plugins maven-surefire-plugin default-test test test no-guava test test com.google.guava:guava **/TestBooleanArrayStringConverterFactory.java **/TestBooleanObjectArrayStringConverterFactory.java **/TestByteObjectArrayStringConverterFactory.java **/TestCharObjectArrayStringConverterFactory.java **/TestJDKStringConverters.java **/TestNumericArrayStringConverterFactory.java **/TestNumericObjectArrayStringConverterFactory.java **/TestStringConvert.java **/TestStringConverterFactory.java usedefaultlisteners false org.apache.maven.plugins maven-jar-plugin ${project.build.outputDirectory}/META-INF/MANIFEST.MF true true org.apache.felix maven-bundle-plugin 2.4.0 bundle-manifest process-classes manifest org.apache.maven.plugins maven-javadoc-plugin attach-javadocs package jar org.apache.maven.plugins maven-source-plugin attach-sources package jar-no-fork org.apache.maven.plugins maven-assembly-plugin false src/main/assembly/dist.xml gnu make-assembly deploy single org.apache.maven.plugins maven-site-plugin true lt.velykis.maven.skins reflow-velocity-tools 1.1.1 org.apache.velocity velocity 1.7 com.github.github site-maven-plugin 0.12 github-site site site-deploy Create website for ${project.artifactId} v${project.version} ${project.artifactId} true github JodaOrg jodaorg.github.io refs/heads/master org.apache.maven.plugins maven-assembly-plugin ${maven-assembly-plugin.version} org.apache.maven.plugins maven-checkstyle-plugin ${maven-checkstyle-plugin.version} org.apache.maven.plugins maven-changes-plugin ${maven-changes-plugin.version} org.apache.maven.plugins maven-clean-plugin ${maven-clean-plugin.version} org.apache.maven.plugins maven-compiler-plugin ${maven-compiler-plugin.version} org.apache.maven.plugins maven-deploy-plugin ${maven-deploy-plugin.version} org.apache.maven.plugins maven-dependency-plugin ${maven-dependency-plugin.version} org.apache.maven.plugins maven-gpg-plugin ${maven-gpg-plugin.version} org.apache.maven.plugins maven-install-plugin ${maven-install-plugin.version} org.apache.maven.plugins maven-jar-plugin ${maven-jar-plugin.version} org.apache.maven.plugins maven-javadoc-plugin ${maven-javadoc-plugin.version} org.apache.maven.plugins maven-jxr-plugin ${maven-jxr-plugin.version} org.apache.maven.plugins maven-plugin-plugin ${maven-plugin-plugin.version} org.apache.maven.plugins maven-pmd-plugin ${maven-pmd-plugin.version} org.apache.maven.plugins maven-project-info-reports-plugin ${maven-project-info-reports-plugin.version} org.apache.maven.plugins maven-repository-plugin ${maven-repository-plugin.version} org.apache.maven.plugins maven-resources-plugin ${maven-resources-plugin.version} org.apache.maven.plugins maven-site-plugin ${maven-site-plugin.version} org.apache.maven.plugins maven-source-plugin ${maven-source-plugin.version} org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} org.apache.maven.plugins maven-surefire-report-plugin ${maven-surefire-report-plugin.version} org.apache.maven.plugins maven-toolchains-plugin ${maven-toolchains-plugin.version} org.eclipse.m2e lifecycle-mapping 1.0.0 org.apache.felix maven-bundle-plugin [2.4.0,) manifest 3.0.4 com.google.guava guava 18.0 true junit junit 4.11 test org.apache.maven.plugins maven-project-info-reports-plugin ${maven-project-info-plugin.version} dependencies dependency-info issue-tracking license project-team scm summary org.apache.maven.plugins maven-checkstyle-plugin ${maven-checkstyle-plugin.version} false false false org.apache.maven.plugins maven-javadoc-plugin ${maven-javadoc-plugin.version} javadoc org.apache.maven.plugins maven-surefire-report-plugin ${maven-surefire-report-plugin.version} true org.apache.maven.plugins maven-changes-plugin ${maven-changes-plugin.version} changes-report sonatype-joda-staging Sonatype OSS staging repository http://oss.sonatype.org/service/local/staging/deploy/maven2/ default false sonatype-joda-snapshot Sonatype OSS snapshot repository http://oss.sonatype.org/content/repositories/joda-snapshots default http://oss.sonatype.org/content/repositories/joda-releases java8 1.8 -Xdoclint:none repo-sign-artifacts oss.repo true org.apache.maven.plugins maven-toolchains-plugin validate toolchain 1.6 sun org.apache.maven.plugins maven-gpg-plugin sign-artifacts verify sign 2.5.5 2.11 2.11 2.6.1 3.3 2.8.2 2.10 1.6 2.5.2 2.6 2.10.3 2.5 3.4 3.5 2.8 2.4 2.7 3.4 2.4 2.18.1 2.18.1 1.1 1.6 1.6 1.6 true true true true false true ${project.basedir}/src/main/checkstyle/checkstyle.xml UTF-8 UTF-8 joda-convert-1.8.1/LICENSE.txt0000664000175000017500000002645012603461407015303 0ustar ebourgebourg Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. joda-convert-1.8.1/NOTICE.txt0000664000175000017500000000047412603461407015200 0ustar ebourgebourg============================================================================= = NOTICE file corresponding to section 4d of the Apache License Version 2.0 = ============================================================================= This product includes software developed by Joda.org (http://www.joda.org/). joda-convert-1.8.1/RELEASE-NOTES.txt0000664000175000017500000000107612603461407016164 0ustar ebourgebourg Joda-Convert ================================================ Joda-Convert is a small library providing conversion to and from String. The release runs on JDK 6 or later. See http://www.joda.org/joda-convert/changes-report.html for changes Joda-Convert is licensed under the business-friendly Apache License Version 2. This is the same license as all of Apache, plus other open source projects such as Spring. Feedback -------- Feedback is best received using GitHub issues and Pull Requests. https://github.com/JodaOrg/joda-convert/ The Joda team