Java Code Examples for org.apache.commons.configuration2.ex.ConversionException

The following examples show how to use org.apache.commons.configuration2.ex.ConversionException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: swagger2markup   Source File: Schema2MarkupProperties.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return a list of Path property values associated with the given key,
 * or {@code defaultValue} if the key cannot be resolved.
 *
 * @param key the property name to resolve
 * @return The list of Path properties
 * @throws IllegalStateException if the value cannot be mapped to an array of strings
 */
public List<Path> getPathList(String key) {
    List<Path> pathList = new ArrayList<>();

    try {
        String[] stringList = configuration.getStringArray(key);

        for (String pathStr : stringList) {
            pathList.add(Paths.get(pathStr));
        }
    } catch (ConversionException ce) {
        throw new IllegalStateException(String.format("requested key [%s] is not convertable to an array", key));
    }

    return pathList;
}
 
Example 2
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the specified object into a Boolean. Internally the
 * {@code org.apache.commons.lang.BooleanUtils} class from the
 * <a href="https://commons.apache.org/lang/">Commons Lang</a>
 * project is used to perform this conversion. This class accepts some more
 * tokens for the boolean value of <b>true</b>, e.g. {@code yes} and
 * {@code on}. Please refer to the documentation of this class for more
 * details.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a boolean
 */
public static Boolean toBoolean(final Object value) throws ConversionException
{
    if (value instanceof Boolean)
    {
        return (Boolean) value;
    }
    else if (value instanceof String)
    {
        final Boolean b = BooleanUtils.toBooleanObject((String) value);
        if (b == null)
        {
            throw new ConversionException("The value " + value + " can't be converted to a Boolean object");
        }
        return b;
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to a Boolean object");
    }
}
 
Example 3
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the specified object into a File.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a File
 * @since 2.3
 */
public static File toFile(final Object value) throws ConversionException
{
    if (value instanceof File)
    {
        return (File) value;
    }
    else if (value instanceof Path)
    {
        return ((Path) value).toFile();
    }
    else if (value instanceof String)
    {
        return new File((String) value);
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to a File");
    }
}
 
Example 4
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the specified object into a Path.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a Path
 * @since 2.3
 */
public static Path toPath(final Object value) throws ConversionException
{
    if (value instanceof File)
    {
        return ((File) value).toPath();
    }
    else if (value instanceof Path)
    {
        return (Path) value;
    }
    else if (value instanceof String)
    {
        return Paths.get((String) value);
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to a Path");
    }
}
 
Example 5
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the specified object into an URI.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to an URI
 */
public static URI toURI(final Object value) throws ConversionException
{
    if (value instanceof URI)
    {
        return (URI) value;
    }
    else if (value instanceof String)
    {
        try
        {
            return new URI((String) value);
        }
        catch (final URISyntaxException e)
        {
            throw new ConversionException("The value " + value + " can't be converted to an URI", e);
        }
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to an URI");
    }
}
 
Example 6
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the specified object into an URL.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to an URL
 */
public static URL toURL(final Object value) throws ConversionException
{
    if (value instanceof URL)
    {
        return (URL) value;
    }
    else if (value instanceof String)
    {
        try
        {
            return new URL((String) value);
        }
        catch (final MalformedURLException e)
        {
            throw new ConversionException("The value " + value + " can't be converted to an URL", e);
        }
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to an URL");
    }
}
 
Example 7
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the specified object into a Pattern.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a Pattern
 */
public static Pattern toPattern(final Object value) throws ConversionException
{
    if (value instanceof Pattern)
    {
        return (Pattern) value;
    }
    else if (value instanceof String)
    {
        try
        {
            return Pattern.compile((String) value);
        }
        catch (final PatternSyntaxException e)
        {
            throw new ConversionException("The value " + value + " can't be converted to a Pattern", e);
        }
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to a Pattern");
    }
}
 
Example 8
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the specified value into an internet address.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a InetAddress
 *
 * @since 1.5
 */
static InetAddress toInetAddress(final Object value) throws ConversionException
{
    if (value instanceof InetAddress)
    {
        return (InetAddress) value;
    }
    else if (value instanceof String)
    {
        try
        {
            return InetAddress.getByName((String) value);
        }
        catch (final UnknownHostException e)
        {
            throw new ConversionException("The value " + value + " can't be converted to a InetAddress", e);
        }
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to a InetAddress");
    }
}
 
Example 9
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the specified value into an email address.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to an email address
 *
 * @since 1.5
 */
static Object toInternetAddress(final Object value) throws ConversionException
{
    if (value.getClass().getName().equals(INTERNET_ADDRESS_CLASSNAME))
    {
        return value;
    }
    else if (value instanceof String)
    {
        try
        {
            final Constructor<?> ctor = Class.forName(INTERNET_ADDRESS_CLASSNAME)
                    .getConstructor(String.class);
            return ctor.newInstance(value);
        }
        catch (final Exception e)
        {
            throw new ConversionException("The value " + value + " can't be converted to a InternetAddress", e);
        }
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to a InternetAddress");
    }
}
 
Example 10
/**
 * Obtains the property value for the specified key and converts it to the
 * given target class.
 *
 * @param <T> the target type of the conversion
 * @param cls the target class
 * @param key the key of the desired property
 * @param defaultValue a default value
 * @return the converted value of this property
 * @throws ConversionException if the conversion cannot be performed
 */
private <T> T getAndConvertProperty(final Class<T> cls, final String key, final T defaultValue)
{
    final Object value = getProperty(key);
    try
    {
        return ObjectUtils.defaultIfNull(
                getConversionHandler().to(value, cls, getInterpolator()),
                defaultValue);
    }
    catch (final ConversionException cex)
    {
        // improve error message
        throw new ConversionException(
                String.format(
                        "Key '%s' cannot be converted to class %s. Value is: '%s'.",
                        key, cls.getName(), String.valueOf(value)), cex.getCause());
    }
}
 
Example 11
/**
 * Tests the exception message triggered by the conversion to BigInteger.
 * This test is related to CONFIGURATION-357.
 */
@Test
public void testGetBigIntegerConversion()
{
    final Configuration config = getConfiguration();
    try
    {
        config.getBigInteger("key1");
        fail("No conversion exception thrown!");
    }
    catch (final ConversionException cex)
    {
        assertTrue("Key not found in exception message: " + cex, cex
                .getMessage().contains("'key1'"));
        assertTrue("Target class not found in exception message: " + cex,
                cex.getMessage().contains(BigInteger.class.getName()));
        assertTrue("Value not found in exception message: " + cex, cex
                .getMessage().contains(config.getString("key1")));
    }
}
 
Example 12
@Test
public void testGetInternetAddress() throws Exception
{
    final Object expected = createInternetAddress("[email protected]");

    // address as string
    assertEquals(expected, conf.get(expected.getClass(), "email.string"));

    // address object
    assertEquals(expected, conf.get(expected.getClass(), "email.object"));

    // interpolated value
    assertEquals(expected, conf.get(expected.getClass(), "email.string.interpolated"));

    conf.setProperty("email.invalid", "[email protected]@org");
    try
    {
        conf.get(expected.getClass(), "email.invalid");
        fail("ConversionException should be thrown for invalid emails");
    }
    catch (final ConversionException e)
    {
        // expected
    }
}
 
Example 13
@Test
void configureShouldThrowOnNonBooleanValueForSupportsVirtualHosting() {
    HierarchicalConfiguration<ImmutableNode> configuration = ldapRepositoryConfiguration(ldapContainer);
    configuration.addProperty(SUPPORTS_VIRTUAL_HOSTING, "bad");

    ReadOnlyUsersLDAPRepository usersLDAPRepository = new ReadOnlyUsersLDAPRepository(new SimpleDomainList());

    assertThatThrownBy(() -> usersLDAPRepository.configure(configuration))
        .isInstanceOf(ConversionException.class);
}
 
Example 14
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts the specified value object to a {@code Character}. This method
 * converts the passed in object to a string. If the string has exactly one
 * character, this character is returned as result. Otherwise, conversion
 * fails.
 *
 * @param value the value to be converted
 * @return the resulting {@code Character} object
 * @throws ConversionException if the conversion is not possible
 */
public static Character toCharacter(final Object value) throws ConversionException
{
    final String strValue = String.valueOf(value);
    if (strValue.length() == 1)
    {
        return Character.valueOf(strValue.charAt(0));
    }
    throw new ConversionException(
            String.format(
                    "The value '%s' cannot be converted to a Character object!",
                    strValue));
}
 
Example 15
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into a Byte.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a byte
 */
public static Byte toByte(final Object value) throws ConversionException
{
    final Number n = toNumber(value, Byte.class);
    if (n instanceof Byte)
    {
        return (Byte) n;
    }
    return n.byteValue();
}
 
Example 16
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into a Short.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a short
 */
public static Short toShort(final Object value) throws ConversionException
{
    final Number n = toNumber(value, Short.class);
    if (n instanceof Short)
    {
        return (Short) n;
    }
    return n.shortValue();
}
 
Example 17
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into an Integer.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to an integer
 */
public static Integer toInteger(final Object value) throws ConversionException
{
    final Number n = toNumber(value, Integer.class);
    if (n instanceof Integer)
    {
        return (Integer) n;
    }
    return n.intValue();
}
 
Example 18
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into a Long.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a Long
 */
public static Long toLong(final Object value) throws ConversionException
{
    final Number n = toNumber(value, Long.class);
    if (n instanceof Long)
    {
        return (Long) n;
    }
    return n.longValue();
}
 
Example 19
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into a Float.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a Float
 */
public static Float toFloat(final Object value) throws ConversionException
{
    final Number n = toNumber(value, Float.class);
    if (n instanceof Float)
    {
        return (Float) n;
    }
    return new Float(n.floatValue());
}
 
Example 20
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into a Double.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a Double
 */
public static Double toDouble(final Object value) throws ConversionException
{
    final Number n = toNumber(value, Double.class);
    if (n instanceof Double)
    {
        return (Double) n;
    }
    return new Double(n.doubleValue());
}
 
Example 21
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into a BigInteger.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a BigInteger
 */
public static BigInteger toBigInteger(final Object value) throws ConversionException
{
    final Number n = toNumber(value, BigInteger.class);
    if (n instanceof BigInteger)
    {
        return (BigInteger) n;
    }
    return BigInteger.valueOf(n.longValue());
}
 
Example 22
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into a BigDecimal.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a BigDecimal
 */
public static BigDecimal toBigDecimal(final Object value) throws ConversionException
{
    final Number n = toNumber(value, BigDecimal.class);
    if (n instanceof BigDecimal)
    {
        return (BigDecimal) n;
    }
    return new BigDecimal(n.doubleValue());
}
 
Example 23
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into a Locale.
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a Locale
 */
public static Locale toLocale(final Object value) throws ConversionException
{
    if (value instanceof Locale)
    {
        return (Locale) value;
    }
    else if (value instanceof String)
    {
        final String[] elements = ((String) value).split("_");
        final int size = elements.length;

        if (size >= 1 && (elements[0].length() == 2 || elements[0].length() == 0))
        {
            final String language = elements[0];
            final String country = size >= 2 ? elements[1] : "";
            final String variant = size >= 3 ? elements[2] : "";

            return new Locale(language, country, variant);
        }
        throw new ConversionException("The value " + value + " can't be converted to a Locale");
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to a Locale");
    }
}
 
Example 24
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert the specified object into a Date.
 *
 * @param value  the value to convert
 * @param format the DateFormat pattern to parse String values
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a Calendar
 */
public static Date toDate(final Object value, final String format) throws ConversionException
{
    if (value instanceof Date)
    {
        return (Date) value;
    }
    else if (value instanceof Calendar)
    {
        return ((Calendar) value).getTime();
    }
    else if (value instanceof String)
    {
        try
        {
            return new SimpleDateFormat(format).parse((String) value);
        }
        catch (final ParseException e)
        {
            throw new ConversionException("The value " + value + " can't be converted to a Date", e);
        }
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to a Date");
    }
}
 
Example 25
/**
 * Tests a failed conversion to character.
 */
@Test(expected = ConversionException.class)
public void testToCharFailed()
{
    PropertyConverter.to(Character.TYPE, "FF",
            new DefaultConversionHandler());
}
 
Example 26
/**
 * Tests that the cause of a conversion exception is kept.
 */
@Test
public void testConversionExceptionCause()
{
    try
    {
        conf.get(Integer.TYPE, "uri.string");
        fail("No conversion exception thrown!");
    }
    catch (final ConversionException cex)
    {
        assertTrue("Wrong cause",
                cex.getCause() instanceof NumberFormatException);
    }
}
 
Example 27
Source Project: commons-configuration   Source File: PropertyConverter.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Convert the specified object into a Color. If the value is a String,
 * the format allowed is (#)?[0-9A-F]{6}([0-9A-F]{2})?. Examples:
 * <ul>
 *   <li>FF0000 (red)</li>
 *   <li>0000FFA0 (semi transparent blue)</li>
 *   <li>#CCCCCC (gray)</li>
 *   <li>#00FF00A0 (semi transparent green)</li>
 * </ul>
 *
 * @param value the value to convert
 * @return the converted value
 * @throws ConversionException thrown if the value cannot be converted to a Color
 */
public static Color toColor(final Object value) throws ConversionException
{
    if (value instanceof Color)
    {
        return (Color) value;
    }
    else if (value instanceof String && !StringUtils.isBlank((String) value))
    {
        String color = ((String) value).trim();

        final int[] components = new int[3];

        // check the size of the string
        final int minlength = components.length * 2;
        if (color.length() < minlength)
        {
            throw new ConversionException("The value " + value + " can't be converted to a Color");
        }

        // remove the leading #
        if (color.startsWith("#"))
        {
            color = color.substring(1);
        }

        try
        {
            // parse the components
            for (int i = 0; i < components.length; i++)
            {
                components[i] = Integer.parseInt(color.substring(2 * i, 2 * i + 2), HEX_RADIX);
            }

            // parse the transparency
            int alpha;
            if (color.length() >= minlength + 2)
            {
                alpha = Integer.parseInt(color.substring(minlength, minlength + 2), HEX_RADIX);
            }
            else
            {
                alpha = Color.black.getAlpha();
            }

            return new Color(components[0], components[1], components[2], alpha);
        }
        catch (final Exception e)
        {
            throw new ConversionException("The value " + value + " can't be converted to a Color", e);
        }
    }
    else
    {
        throw new ConversionException("The value " + value + " can't be converted to a Color");
    }
}
 
Example 28
@Override
public List<Object> getList(final String key, final List<?> defaultValue)
{
    final Object value = getProperty(key);
    List<Object> list;

    if (value instanceof String)
    {
        list = new ArrayList<>(1);
        list.add(interpolate((String) value));
    }
    else if (value instanceof List)
    {
        list = new ArrayList<>();
        final List<?> l = (List<?>) value;

        // add the interpolated elements in the new list
        for (final Object elem : l)
        {
            list.add(interpolate(elem));
        }
    }
    else if (value == null)
    {
        // This is okay because we just return this list to the caller
        @SuppressWarnings("unchecked")
        final
        List<Object> resultList = (List<Object>) defaultValue;
        list = resultList;
    }
    else if (value.getClass().isArray())
    {
        return Arrays.asList((Object[]) value);
    }
    else if (isScalarValue(value))
    {
        return Collections.singletonList((Object) value.toString());
    }
    else
    {
        throw new ConversionException('\'' + key + "' doesn't map to a List object: " + value + ", a "
                + value.getClass().getName());
    }
    return list;
}
 
Example 29
/**
 * Tests a failed conversion.
 */
@Test(expected = ConversionException.class)
public void testToFailedConversion()
{
    handler.to(VAR, Integer.class, null);
}
 
Example 30
/**
 * Tests conversion to numbers when an invalid Hex value is passed in.
 * This should cause an exception.
 */
@Test(expected = ConversionException.class)
public void testToNumberFromInvalidHexString()
{
    PropertyConverter.toNumber("0xNotAHexValue", Integer.class);
}