001package org.andromda.andromdapp;
002
003import org.andromda.core.common.ClassUtils;
004import org.andromda.core.common.Converter;
005import org.apache.commons.lang.BooleanUtils;
006import org.apache.commons.lang.ObjectUtils;
007import org.apache.commons.lang.StringUtils;
008
009/**
010 * Some utilities for dealing with the AndroMDApp generator.
011 *
012 * @author Chad Brandon
013 */
014public class AndroMDAppUtils
015{
016    /**
017     * The delimiter for separating patterns.
018     */
019    private static final String COMMA = ",";
020
021    /**
022     * Converts a comma delimited string to an array of Strings.
023     *
024     * @param string to convert.
025     * @return the resulting array or null if the string was null.
026     */
027    public static String[] stringToArray(final String string)
028    {
029        return string == null ? null : string.split(COMMA);
030    }
031
032    /**
033     * Attempts to convert the given <code>value</code> to the given
034     * <code>type</code> (if the type is specified), otherwise does nothing and
035     * returns the value unchanged.
036     *
037     * @param value the value to convert.
038     * @param type the type to convert it to.
039     * @return the converted, or unconverted depending on whether it needed
040     *         to be converted.
041     */
042    public static Object convert(
043        final Object value,
044        final String type)
045    {
046        Object object = value;
047        if (StringUtils.isNotBlank(type))
048        {
049            try
050            {
051                final Class typeClass = ClassUtils.getClassLoader().loadClass(type);
052
053                // - handle booleans differently, since we want to be able to
054                // convert 'yes/no', 'on/off', etc
055                // to boolean values
056                if (typeClass == Boolean.class)
057                {
058                    object = BooleanUtils.toBooleanObject(ObjectUtils.toString(value));
059                }
060                else
061                {
062                    object = Converter.convert(
063                            value,
064                            typeClass);
065                }
066            }
067            catch (final ClassNotFoundException exception)
068            {
069                // - ignore
070            }
071        }
072        return object;
073    }
074}