Example usage for java.lang Class isEnum

List of usage examples for java.lang Class isEnum

Introduction

In this page you can find the example usage for java.lang Class isEnum.

Prototype

public boolean isEnum() 

Source Link

Document

Returns true if and only if this class was declared as an enum in the source code.

Usage

From source file:org.apache.syncope.console.pages.ReportletConfModalPage.java

private ListView<String> buildPropView() {
    LoadableDetachableModel<List<String>> propViewModel = new LoadableDetachableModel<List<String>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override//from  www .ja  v  a  2  s.  c  o  m
        protected List<String> load() {
            List<String> result = new ArrayList<String>();
            if (ReportletConfModalPage.this.reportletConf != null) {
                for (Field field : ReportletConfModalPage.this.reportletConf.getClass().getDeclaredFields()) {
                    if (!ArrayUtils.contains(EXCLUDE_PROPERTIES, field.getName())) {
                        result.add(field.getName());
                    }
                }
            }

            return result;
        }
    };

    propView = new ListView<String>("propView", propViewModel) {

        private static final long serialVersionUID = 9101744072914090143L;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        protected void populateItem(final ListItem<String> item) {
            final String fieldName = item.getModelObject();

            Label label = new Label("key", fieldName);
            item.add(label);

            Field field = null;
            try {
                field = ReportletConfModalPage.this.reportletConf.getClass().getDeclaredField(fieldName);
            } catch (Exception e) {
                LOG.error("Could not find field {} in class {}", fieldName,
                        ReportletConfModalPage.this.reportletConf.getClass(), e);
            }
            if (field == null) {
                return;
            }

            FormAttributeField annotation = field.getAnnotation(FormAttributeField.class);

            BeanWrapper wrapper = PropertyAccessorFactory
                    .forBeanPropertyAccess(ReportletConfModalPage.this.reportletConf);

            Panel panel;

            if (String.class.equals(field.getType()) && annotation != null && annotation.userSearch()) {
                panel = new UserSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (String.class.equals(field.getType()) && annotation != null && annotation.roleSearch()) {
                panel = new RoleSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (List.class.equals(field.getType())) {
                Class<?> listItemType = String.class;
                if (field.getGenericType() instanceof ParameterizedType) {
                    listItemType = (Class<?>) ((ParameterizedType) field.getGenericType())
                            .getActualTypeArguments()[0];
                }

                if (listItemType.equals(String.class) && annotation != null) {
                    List<String> choices;
                    switch (annotation.schema()) {
                    case UserSchema:
                        choices = schemaRestClient.getSchemaNames(AttributableType.USER);
                        break;

                    case UserDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.USER);
                        break;

                    case UserVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.USER);
                        break;

                    case RoleSchema:
                        choices = schemaRestClient.getSchemaNames(AttributableType.ROLE);
                        break;

                    case RoleDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.ROLE);
                        break;

                    case RoleVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.ROLE);
                        break;

                    case MembershipSchema:
                        choices = schemaRestClient.getSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    default:
                        choices = Collections.emptyList();
                    }

                    panel = new AjaxPalettePanel("value",
                            new PropertyModel<List<String>>(ReportletConfModalPage.this.reportletConf,
                                    fieldName),
                            new ListModel<String>(choices), true);
                } else if (listItemType.isEnum()) {
                    panel = new CheckBoxMultipleChoiceFieldPanel("value",
                            new PropertyModel(ReportletConfModalPage.this.reportletConf, fieldName),
                            new ListModel(Arrays.asList(listItemType.getEnumConstants())));
                } else {
                    if (((List) wrapper.getPropertyValue(fieldName)).isEmpty()) {
                        ((List) wrapper.getPropertyValue(fieldName)).add(null);
                    }

                    panel = new MultiFieldPanel("value",
                            new PropertyModel<List>(ReportletConfModalPage.this.reportletConf, fieldName),
                            buildSinglePanel(field.getType(), fieldName, "panel"));
                }
            } else {
                panel = buildSinglePanel(field.getType(), fieldName, "value");
            }

            item.add(panel);
        }
    };

    return propView;
}

From source file:org.apache.syncope.client.console.pages.ReportletConfModalPage.java

private ListView<String> buildPropView() {
    LoadableDetachableModel<List<String>> propViewModel = new LoadableDetachableModel<List<String>>() {

        private static final long serialVersionUID = 5275935387613157437L;

        @Override//from  w ww.j  av  a  2 s. c om
        protected List<String> load() {
            List<String> result = new ArrayList<String>();
            if (ReportletConfModalPage.this.reportletConf != null) {
                for (Field field : ReportletConfModalPage.this.reportletConf.getClass().getDeclaredFields()) {
                    if (!ArrayUtils.contains(EXCLUDE_PROPERTIES, field.getName())) {
                        result.add(field.getName());
                    }
                }
            }

            return result;
        }
    };

    propView = new ListView<String>("propView", propViewModel) {

        private static final long serialVersionUID = 9101744072914090143L;

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        protected void populateItem(final ListItem<String> item) {
            final String fieldName = item.getModelObject();

            Label label = new Label("key", fieldName);
            item.add(label);

            Field field = null;
            try {
                field = ReportletConfModalPage.this.reportletConf.getClass().getDeclaredField(fieldName);
            } catch (Exception e) {
                LOG.error("Could not find field {} in class {}", fieldName,
                        ReportletConfModalPage.this.reportletConf.getClass(), e);
            }
            if (field == null) {
                return;
            }

            FormAttributeField annotation = field.getAnnotation(FormAttributeField.class);

            BeanWrapper wrapper = PropertyAccessorFactory
                    .forBeanPropertyAccess(ReportletConfModalPage.this.reportletConf);

            Panel panel;

            if (String.class.equals(field.getType()) && annotation != null && annotation.userSearch()) {
                panel = new UserSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (String.class.equals(field.getType()) && annotation != null && annotation.groupSearch()) {
                panel = new GroupSearchPanel.Builder("value").fiql((String) wrapper.getPropertyValue(fieldName))
                        .required(false).build();
                // This is needed in order to manually update this.reportletConf with search panel selections
                panel.setDefaultModel(new Model<String>(fieldName));
            } else if (List.class.equals(field.getType())) {
                Class<?> listItemType = String.class;
                if (field.getGenericType() instanceof ParameterizedType) {
                    listItemType = (Class<?>) ((ParameterizedType) field.getGenericType())
                            .getActualTypeArguments()[0];
                }

                if (listItemType.equals(String.class) && annotation != null) {
                    List<String> choices;
                    switch (annotation.schema()) {
                    case UserPlainSchema:
                        choices = schemaRestClient.getPlainSchemaNames(AttributableType.USER);
                        break;

                    case UserDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.USER);
                        break;

                    case UserVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.USER);
                        break;

                    case GroupPlainSchema:
                        choices = schemaRestClient.getPlainSchemaNames(AttributableType.GROUP);
                        break;

                    case GroupDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.GROUP);
                        break;

                    case GroupVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.GROUP);
                        break;

                    case MembershipPlainSchema:
                        choices = schemaRestClient.getPlainSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipDerivedSchema:
                        choices = schemaRestClient.getDerSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    case MembershipVirtualSchema:
                        choices = schemaRestClient.getVirSchemaNames(AttributableType.MEMBERSHIP);
                        break;

                    default:
                        choices = Collections.emptyList();
                    }

                    panel = new AjaxPalettePanel("value",
                            new PropertyModel<List<String>>(ReportletConfModalPage.this.reportletConf,
                                    fieldName),
                            new ListModel<String>(choices), true);
                } else if (listItemType.isEnum()) {
                    panel = new CheckBoxMultipleChoiceFieldPanel("value",
                            new PropertyModel(ReportletConfModalPage.this.reportletConf, fieldName),
                            new ListModel(Arrays.asList(listItemType.getEnumConstants())));
                } else {
                    if (((List) wrapper.getPropertyValue(fieldName)).isEmpty()) {
                        ((List) wrapper.getPropertyValue(fieldName)).add(null);
                    }

                    panel = new MultiFieldPanel("value",
                            new PropertyModel<List>(ReportletConfModalPage.this.reportletConf, fieldName),
                            buildSinglePanel(field.getType(), fieldName, "panel"));
                }
            } else {
                panel = buildSinglePanel(field.getType(), fieldName, "value");
            }

            item.add(panel);
        }
    };

    return propView;
}

From source file:org.apache.sqoop.SqoopOptions.java

@SuppressWarnings("unchecked")
/**//  w ww .  ja  va2s. com
 * Given a set of properties, load this into the current SqoopOptions
 * instance.
 */
public void loadProperties(Properties props) {

    try {
        Field[] fields = SqoopOptions.class.getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(StoredAsProperty.class)) {
                Class typ = f.getType();
                StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
                String propName = storedAs.value();

                if (typ.equals(int.class)) {
                    f.setInt(this, getIntProperty(props, propName, f.getInt(this)));
                } else if (typ.equals(boolean.class)) {
                    f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this)));
                } else if (typ.equals(long.class)) {
                    f.setLong(this, getLongProperty(props, propName, f.getLong(this)));
                } else if (typ.equals(String.class)) {
                    f.set(this, props.getProperty(propName, (String) f.get(this)));
                } else if (typ.equals(Integer.class)) {
                    String value = props.getProperty(propName,
                            f.get(this) == null ? "null" : f.get(this).toString());
                    f.set(this, value.equals("null") ? null : new Integer(value));
                } else if (typ.isEnum()) {
                    f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString())));
                } else {
                    throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ);
                }
            }
        }
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Illegal access to field in property setter", iae);
    }

    // Now load properties that were stored with special types, or require
    // additional logic to set.

    if (getBooleanProperty(props, "db.require.password", false)) {
        // The user's password was stripped out from the metastore.
        // Require that the user enter it now.
        setPasswordFromConsole();
    } else {
        this.password = props.getProperty("db.password", this.password);
    }

    if (this.jarDirIsAuto) {
        // We memoized a user-specific nonce dir for compilation to the data
        // store.  Disregard that setting and create a new nonce dir.
        String localUsername = System.getProperty("user.name", "unknown");
        this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile");
    }

    String colListStr = props.getProperty("db.column.list", null);
    if (null != colListStr) {
        this.columns = listToArray(colListStr);
    }

    this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters);
    this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters);

    this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs);

    this.connectionParams = getPropertiesAsNetstedProperties(props, "db.connect.params");

    // Loading user mapping
    this.mapColumnHive = getPropertiesAsNetstedProperties(props, "map.column.hive");
    this.mapColumnJava = getPropertiesAsNetstedProperties(props, "map.column.java");

    // Delimiters were previously memoized; don't let the tool override
    // them with defaults.
    this.areDelimsManuallySet = true;

    // If we loaded true verbose flag, we need to apply it
    if (this.verbose) {
        LoggingUtils.setDebugLevel();
    }

    // Custom configuration options
    this.invalidIdentifierPrefix = props.getProperty("invalid.identifier.prefix", "_");
}

From source file:net.arnx.jsonic.JSON.java

/**
 * Converts Map, List, Number, String, Boolean or null to other Java Objects after parsing. 
 * //from  w ww  .  ja  v a  2  s.c  o  m
 * @param context current context.
 * @param value null or the instance of Map, List, Number, String or Boolean.
 * @param cls class for converting
 * @param type generics type for converting. type equals to c if not generics.
 * @return a converted object
 * @throws Exception if conversion failed.
 */
protected <T> T postparse(Context context, Object value, Class<? extends T> cls, Type type) throws Exception {
    Converter c = null;

    if (value == null) {
        if (!cls.isPrimitive()) {
            c = NullConverter.INSTANCE;
        }
    } else {
        JSONHint hint = context.getHint();
        if (hint == null) {
            // no handle
        } else if (hint.serialized() && hint != context.skipHint) {
            c = FormatConverter.INSTANCE;
        } else if (Serializable.class.equals(hint.type())) {
            c = SerializableConverter.INSTANCE;
        } else if (String.class.equals(hint.type())) {
            c = StringSerializableConverter.INSTANCE;
        }
    }

    if (c == null) {
        if (value != null && cls.equals(type) && cls.isAssignableFrom(value.getClass())) {
            c = PlainConverter.INSTANCE;
        } else {
            c = CONVERT_MAP.get(cls);
        }
    }

    if (c == null && context.memberCache != null) {
        c = (Converter) context.memberCache.get(cls);
    }

    if (c == null) {
        if (Properties.class.isAssignableFrom(cls)) {
            c = PropertiesConverter.INSTANCE;
        } else if (Map.class.isAssignableFrom(cls)) {
            c = MapConverter.INSTANCE;
        } else if (Collection.class.isAssignableFrom(cls)) {
            c = CollectionConverter.INSTANCE;
        } else if (cls.isArray()) {
            c = ArrayConverter.INSTANCE;
        } else if (cls.isEnum()) {
            c = EnumConverter.INSTANCE;
        } else if (Date.class.isAssignableFrom(cls)) {
            c = DateConverter.INSTANCE;
        } else if (Calendar.class.isAssignableFrom(cls)) {
            c = CalendarConverter.INSTANCE;
        } else if (CharSequence.class.isAssignableFrom(cls)) {
            c = CharSequenceConverter.INSTANCE;
        } else if (Appendable.class.isAssignableFrom(cls)) {
            c = AppendableConverter.INSTANCE;
        } else if (cls.equals(ClassUtil.findClass("java.net.InetAddress"))) {
            c = InetAddressConverter.INSTANCE;
        } else if (java.sql.Array.class.isAssignableFrom(cls) || Struct.class.isAssignableFrom(cls)) {
            c = NullConverter.INSTANCE;
        } else {
            c = new ObjectConverter(cls);
        }

        if (context.memberCache == null) {
            context.memberCache = new HashMap<Class<?>, Object>();
        }
        context.memberCache.put(cls, c);
    }

    if (c != null) {
        @SuppressWarnings("unchecked")
        T ret = (T) c.convert(context, value, cls, type);
        return ret;
    } else {
        throw new UnsupportedOperationException();
    }
}

From source file:org.openmrs.module.webservices.rest.web.ConversionUtil.java

/**
 * Converts the given object to the given type
 * /*w w w .  ja va 2s.com*/
 * @param object
 * @param toType a simple class or generic type
 * @return
 * @throws ConversionException
 * @should convert strings to locales
 * @should convert strings to enum values
 * @should convert to an array
 * @should convert to a class
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object convert(Object object, Type toType) throws ConversionException {
    if (object == null)
        return object;

    Class<?> toClass = toType instanceof Class ? ((Class<?>) toType)
            : (Class<?>) (((ParameterizedType) toType).getRawType());

    // if we're trying to convert _to_ a collection, handle it as a special case
    if (Collection.class.isAssignableFrom(toClass) || toClass.isArray()) {
        if (!(object instanceof Collection))
            throw new ConversionException("Can only convert a Collection to a Collection/Array. Not "
                    + object.getClass() + " to " + toType, null);

        if (toClass.isArray()) {
            Class<?> targetElementType = toClass.getComponentType();
            Collection input = (Collection) object;
            Object ret = Array.newInstance(targetElementType, input.size());

            int i = 0;
            for (Object element : (Collection) object) {
                Array.set(ret, i, convert(element, targetElementType));
                ++i;
            }
            return ret;
        }

        Collection ret = null;
        if (SortedSet.class.isAssignableFrom(toClass)) {
            ret = new TreeSet();
        } else if (Set.class.isAssignableFrom(toClass)) {
            ret = new HashSet();
        } else if (List.class.isAssignableFrom(toClass)) {
            ret = new ArrayList();
        } else {
            throw new ConversionException("Don't know how to handle collection class: " + toClass, null);
        }

        if (toType instanceof ParameterizedType) {
            // if we have generic type information for the target collection, we can use it to do conversion
            ParameterizedType toParameterizedType = (ParameterizedType) toType;
            Type targetElementType = toParameterizedType.getActualTypeArguments()[0];
            for (Object element : (Collection) object)
                ret.add(convert(element, targetElementType));
        } else {
            // otherwise we must just add all items in a non-type-safe manner
            ret.addAll((Collection) object);
        }
        return ret;
    }

    // otherwise we're converting _to_ a non-collection type

    if (toClass.isAssignableFrom(object.getClass()))
        return object;

    // Numbers with a decimal are always assumed to be Double, so convert to Float, if necessary
    if (toClass.isAssignableFrom(Float.class) && object instanceof Double) {
        return new Float((Double) object);
    }

    if (object instanceof String) {
        String string = (String) object;
        Converter<?> converter = getConverter(toClass);
        if (converter != null)
            return converter.getByUniqueId(string);

        if (toClass.isAssignableFrom(Date.class)) {
            ParseException pex = null;
            String[] supportedFormats = { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS",
                    "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd" };
            for (int i = 0; i < supportedFormats.length; i++) {
                try {
                    Date date = new SimpleDateFormat(supportedFormats[i]).parse(string);
                    return date;
                } catch (ParseException ex) {
                    pex = ex;
                }
            }
            throw new ConversionException(
                    "Error converting date - correct format (ISO8601 Long): yyyy-MM-dd'T'HH:mm:ss.SSSZ", pex);
        } else if (toClass.isAssignableFrom(Locale.class)) {
            return LocaleUtility.fromSpecification(object.toString());
        } else if (toClass.isEnum()) {
            return Enum.valueOf((Class<? extends Enum>) toClass, object.toString());
        } else if (toClass.isAssignableFrom(Class.class)) {
            try {
                return Context.loadClass((String) object);
            } catch (ClassNotFoundException e) {
                throw new ConversionException("Could not convert from " + object.getClass() + " to " + toType,
                        e);
            }
        }
        // look for a static valueOf(String) method (e.g. Double, Integer, Boolean)
        try {
            Method method = toClass.getMethod("valueOf", String.class);
            if (Modifier.isStatic(method.getModifiers()) && toClass.isAssignableFrom(method.getReturnType())) {
                return method.invoke(null, string);
            }
        } catch (Exception ex) {
        }
    } else if (object instanceof Map) {
        return convertMap((Map<String, ?>) object, toClass);
    }
    if (toClass.isAssignableFrom(Double.class) && object instanceof Number) {
        return ((Number) object).doubleValue();
    } else if (toClass.isAssignableFrom(Integer.class) && object instanceof Number) {
        return ((Number) object).intValue();
    }
    throw new ConversionException("Don't know how to convert from " + object.getClass() + " to " + toType,
            null);
}

From source file:io.github.benas.jpopulator.impl.DefaultRandomizer.java

/**
 * Generate a random value for the given type.
 *
 * @param type the type for which a random value will be generated
 * @return a random value for the given type or null if the type is not supported
 *//*from   w ww  . j ava2 s . c o  m*/
public static Object getRandomValue(final Class type) {

    /*
     * String and Character types
     */
    if (type.equals(String.class)) {
        return RandomStringUtils.randomAlphabetic(ConstantsUtil.DEFAULT_STRING_LENGTH);
    }
    if (type.equals(Character.TYPE) || type.equals(Character.class)) {
        return RandomStringUtils.randomAlphabetic(1).charAt(0);
    }

    /*
     * Boolean type
     */
    if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
        return ConstantsUtil.RANDOM.nextBoolean();
    }

    /*
     * Numeric types
     */
    if (type.equals(Byte.TYPE) || type.equals(Byte.class)) {
        return (byte) (ConstantsUtil.RANDOM.nextInt());
    }
    if (type.equals(Short.TYPE) || type.equals(Short.class)) {
        return (short) (ConstantsUtil.RANDOM.nextInt());
    }
    if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
        return ConstantsUtil.RANDOM.nextInt();
    }
    if (type.equals(Long.TYPE) || type.equals(Long.class)) {
        return ConstantsUtil.RANDOM.nextLong();
    }
    if (type.equals(Double.TYPE) || type.equals(Double.class)) {
        return ConstantsUtil.RANDOM.nextDouble();
    }
    if (type.equals(Float.TYPE) || type.equals(Float.class)) {
        return ConstantsUtil.RANDOM.nextFloat();
    }
    if (type.equals(BigInteger.class)) {
        return new BigInteger(
                Math.abs(ConstantsUtil.RANDOM.nextInt(ConstantsUtil.DEFAULT_BIG_INTEGER_NUM_BITS_LENGTH)),
                ConstantsUtil.RANDOM);
    }
    if (type.equals(BigDecimal.class)) {
        return new BigDecimal(ConstantsUtil.RANDOM.nextDouble());
    }
    if (type.equals(AtomicLong.class)) {
        return new AtomicLong(ConstantsUtil.RANDOM.nextLong());
    }
    if (type.equals(AtomicInteger.class)) {
        return new AtomicInteger(ConstantsUtil.RANDOM.nextInt());
    }

    /*
     * Date and time types
     */
    if (type.equals(java.util.Date.class)) {
        return ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue();
    }
    if (type.equals(java.sql.Date.class)) {
        return new java.sql.Date(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(java.sql.Time.class)) {
        return new java.sql.Time(ConstantsUtil.RANDOM.nextLong());
    }
    if (type.equals(java.sql.Timestamp.class)) {
        return new java.sql.Timestamp(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(Calendar.class)) {
        return Calendar.getInstance();
    }
    if (type.equals(org.joda.time.DateTime.class)) {
        return new org.joda.time.DateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.LocalDate.class)) {
        return new org.joda.time.LocalDate(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.LocalTime.class)) {
        return new org.joda.time.LocalTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.LocalDateTime.class)) {
        return new org.joda.time.LocalDateTime(ConstantsUtil.DATE_RANGE_RANDOMIZER.getRandomValue().getTime());
    }
    if (type.equals(org.joda.time.Duration.class)) {
        return new org.joda.time.Duration(Math.abs(ConstantsUtil.RANDOM.nextLong()));
    }
    if (type.equals(org.joda.time.Period.class)) {
        return new org.joda.time.Period(Math.abs(ConstantsUtil.RANDOM.nextInt()));
    }
    if (type.equals(org.joda.time.Interval.class)) {
        long startDate = Math.abs(ConstantsUtil.RANDOM.nextInt());
        long endDate = startDate + Math.abs(ConstantsUtil.RANDOM.nextInt());
        return new org.joda.time.Interval(startDate, endDate);
    }

    /*
     * Enum type
     */
    if (type.isEnum() && type.getEnumConstants().length > 0) {
        Object[] enumConstants = type.getEnumConstants();
        return enumConstants[ConstantsUtil.RANDOM.nextInt(enumConstants.length)];
    }

    /*
     * Return null for any unsupported type
     */
    return null;

}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.AbstractGrailsDomainBinder.java

protected void bindCollectionWithJoinTable(GrailsDomainClassProperty property, Mappings mappings,
        Collection collection, PropertyConfig config, String sessionFactoryBeanName) {

    NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName);

    SimpleValue element;/*from  ww  w .ja  v  a 2 s . com*/
    if (property.isBasicCollectionType()) {
        element = new SimpleValue(mappings, collection.getCollectionTable());
    } else {
        // for a normal unidirectional one-to-many we use a join column
        element = new ManyToOne(mappings, collection.getCollectionTable());
        bindUnidirectionalOneToManyInverseValues(property, (ManyToOne) element);
    }
    collection.setInverse(false);

    String columnName;

    final boolean hasJoinColumnMapping = hasJoinColumnMapping(config);
    if (property.isBasicCollectionType()) {
        final Class<?> referencedType = property.getReferencedPropertyType();
        String className = referencedType.getName();
        final boolean isEnum = referencedType.isEnum();
        if (hasJoinColumnMapping) {
            columnName = config.getJoinTable().getColumn().getName();
        } else {
            columnName = isEnum ? namingStrategy.propertyToColumnName(className)
                    : addUnderscore(namingStrategy.propertyToColumnName(property.getName()),
                            namingStrategy.propertyToColumnName(className));
        }

        if (isEnum) {
            bindEnumType(property, referencedType, element, columnName);
        } else {

            String typeName = getTypeName(property, config, getMapping(property.getDomainClass()));
            if (typeName == null) {
                Type type = mappings.getTypeResolver().basic(className);
                if (type != null) {
                    typeName = type.getName();
                }
            }
            if (typeName == null) {
                String domainName = property.getDomainClass().getName();
                throw new MappingException("Missing type or column for column[" + columnName + "] on domain["
                        + domainName + "] referencing[" + className + "]");
            }

            bindSimpleValue(typeName, element, true, columnName, mappings);
            if (hasJoinColumnMapping) {
                bindColumnConfigToColumn(getColumnForSimpleValue(element), config.getJoinTable().getColumn());
            }
        }
    } else {
        final GrailsDomainClass domainClass = property.getReferencedDomainClass();

        Mapping m = getMapping(domainClass.getClazz());
        if (hasCompositeIdentifier(m)) {
            CompositeIdentity ci = (CompositeIdentity) m.getIdentity();
            bindCompositeIdentifierToManyToOne(property, element, ci, domainClass, EMPTY_PATH,
                    sessionFactoryBeanName);
        } else {
            if (hasJoinColumnMapping) {
                columnName = config.getJoinTable().getColumn().getName();
            } else {
                columnName = namingStrategy.propertyToColumnName(domainClass.getPropertyName())
                        + FOREIGN_KEY_SUFFIX;
            }

            bindSimpleValue("long", element, true, columnName, mappings);
        }
    }

    collection.setElement(element);

    bindCollectionForPropertyConfig(collection, config);
}

From source file:net.ceos.project.poi.annotated.core.CGen.java

/**
 * Export the object to the CSV file./*from  w ww . j a  v a  2s .co m*/
 * 
 * @param object
 *            the object
 * @param fT
 *            the field type
 * @param field
 *            the field
 * @param element
 *            the {@link XlsElement} annotation
 * @param idx
 *            the index of the field
 * @return true if the field has been updated, otherwise false
 * @throws WorkbookException
 */
private boolean toCsv(final CConfigCriteria configCriteria, final Object object, final Class<?> fT,
        final Field field, final XlsElement element, final int idx) throws WorkbookException {
    /* flag which define if the cell was updated or not */
    boolean isUpdated;

    /* reading mask */
    String tM = element.transformMask();
    String fM = element.formatMask();

    switch (fT.getName()) {
    case CellHandler.OBJECT_DATE:
        isUpdated = CsvHandler.dateWriter(configCriteria, object, field, idx, tM, fM);
        break;

    case CellHandler.OBJECT_LOCALDATE:
        isUpdated = CsvHandler.localDateWriter(configCriteria, object, field, idx, tM, fM);
        break;

    case CellHandler.OBJECT_LOCALDATETIME:
        isUpdated = CsvHandler.localDateTimeWriter(configCriteria, object, field, idx, tM, fM);
        break;

    case CellHandler.OBJECT_STRING:
        isUpdated = CsvHandler.stringWriter(configCriteria, object, field, idx);
        break;

    case CellHandler.OBJECT_SHORT:
        /* falls through */
    case CellHandler.PRIMITIVE_SHORT:
        isUpdated = CsvHandler.shortWriter(configCriteria, object, field, idx);
        break;

    case CellHandler.OBJECT_INTEGER:
        /* falls through */
    case CellHandler.PRIMITIVE_INTEGER:
        isUpdated = CsvHandler.integerWriter(configCriteria, object, field, idx);
        break;

    case CellHandler.OBJECT_LONG:
        /* falls through */
    case CellHandler.PRIMITIVE_LONG:
        isUpdated = CsvHandler.longWriter(configCriteria, object, field, idx);
        break;

    case CellHandler.OBJECT_DOUBLE:
        /* falls through */
    case CellHandler.PRIMITIVE_DOUBLE:
        isUpdated = CsvHandler.doubleWriter(configCriteria, object, field, idx, tM, fM);
        break;

    case CellHandler.OBJECT_BIGDECIMAL:
        isUpdated = CsvHandler.bigDecimalWriter(configCriteria, object, field, idx);
        break;

    case CellHandler.OBJECT_FLOAT:
        /* falls through */
    case CellHandler.PRIMITIVE_FLOAT:
        isUpdated = CsvHandler.floatWriter(configCriteria, object, field, idx);
        break;

    case CellHandler.OBJECT_BOOLEAN:
        /* falls through */
    case CellHandler.PRIMITIVE_BOOLEAN:
        isUpdated = CsvHandler.booleanWriter(configCriteria, object, field, idx);
        break;

    default:
        isUpdated = false;
        break;
    }

    if (!isUpdated && fT.isEnum()) {
        configCriteria.getContent().put(idx, CsvHandler.toEnum(object, field));
        isUpdated = true;
    }
    return isUpdated;
}

From source file:org.grails.orm.hibernate.cfg.GrailsDomainBinder.java

protected void bindCollectionWithJoinTable(ToMany property, InFlightMetadataCollector mappings,
        Collection collection, PropertyConfig config, String sessionFactoryBeanName) {

    NamingStrategy namingStrategy = getNamingStrategy(sessionFactoryBeanName);

    SimpleValue element;//w w  w .j  a  va 2  s. c  o m
    final boolean isBasicCollectionType = property instanceof Basic;
    if (isBasicCollectionType) {
        element = new SimpleValue(mappings, collection.getCollectionTable());
    } else {
        // for a normal unidirectional one-to-many we use a join column
        element = new ManyToOne(mappings, collection.getCollectionTable());
        bindUnidirectionalOneToManyInverseValues(property, (ManyToOne) element);
    }
    collection.setInverse(false);

    String columnName;

    final boolean hasJoinColumnMapping = hasJoinColumnMapping(config);
    if (isBasicCollectionType) {
        final Class<?> referencedType = ((Basic) property).getComponentType();
        String className = referencedType.getName();
        final boolean isEnum = referencedType.isEnum();
        if (hasJoinColumnMapping) {
            columnName = config.getJoinTable().getColumn().getName();
        } else {
            columnName = isEnum ? namingStrategy.propertyToColumnName(className)
                    : addUnderscore(namingStrategy.propertyToColumnName(property.getName()),
                            namingStrategy.propertyToColumnName(className));
        }

        if (isEnum) {
            bindEnumType(property, referencedType, element, columnName);
        } else {

            String typeName = getTypeName(property, config, getMapping(property.getOwner()));
            if (typeName == null) {
                Type type = mappings.getTypeResolver().basic(className);
                if (type != null) {
                    typeName = type.getName();
                }
            }
            if (typeName == null) {
                String domainName = property.getOwner().getName();
                throw new MappingException("Missing type or column for column[" + columnName + "] on domain["
                        + domainName + "] referencing[" + className + "]");
            }

            bindSimpleValue(typeName, element, true, columnName, mappings);
            if (hasJoinColumnMapping) {
                bindColumnConfigToColumn(property, getColumnForSimpleValue(element),
                        config.getJoinTable().getColumn());
            }
        }
    } else {
        final PersistentEntity domainClass = property.getAssociatedEntity();

        Mapping m = getMapping(domainClass);
        if (hasCompositeIdentifier(m)) {
            CompositeIdentity ci = (CompositeIdentity) m.getIdentity();
            bindCompositeIdentifierToManyToOne(property, element, ci, domainClass, EMPTY_PATH,
                    sessionFactoryBeanName);
        } else {
            if (hasJoinColumnMapping) {
                columnName = config.getJoinTable().getColumn().getName();
            } else {
                columnName = namingStrategy.propertyToColumnName(NameUtils.decapitalize(domainClass.getName()))
                        + FOREIGN_KEY_SUFFIX;
            }

            bindSimpleValue("long", element, true, columnName, mappings);
        }
    }

    collection.setElement(element);

    bindCollectionForPropertyConfig(collection, config);
}

From source file:net.ceos.project.poi.annotated.core.CGen.java

/**
 * Import the CSV file into the object./*www  .  ja v  a 2s  .com*/
 * 
 * @param object
 *            the object
 * @param fT
 *            the field type
 * @param field
 *            the field
 * @param xlsAnnotation
 *            the {@link XlsElement} annotation
 * @param values
 *            the array with the content at one line
 * @param idx
 *            the index of the field
 * @return true if the field has been updated, otherwise false
 * @throws WorkbookException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private boolean toObject(final Object object, final Class<?> fT, final Field field,
        final XlsElement xlsAnnotation, final String[] values, final int idx) throws WorkbookException {
    /* flag which define if the cell was updated or not */
    boolean isUpdated;
    /* set enabled the accessible object */
    field.setAccessible(true);

    switch (fT.getName()) {
    case CellHandler.OBJECT_DATE:
        CsvHandler.dateReader(object, field, xlsAnnotation, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_LOCALDATE:
        CsvHandler.localDateReader(object, field, xlsAnnotation, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_LOCALDATETIME:
        CsvHandler.localDateTimeReader(object, field, xlsAnnotation, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_STRING:
        CsvHandler.stringReader(object, field, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_SHORT:
        /* falls through */
    case CellHandler.PRIMITIVE_SHORT:
        CsvHandler.shortReader(object, field, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_INTEGER:
        /* falls through */
    case CellHandler.PRIMITIVE_INTEGER:
        CsvHandler.integerReader(object, field, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_LONG:
        /* falls through */
    case CellHandler.PRIMITIVE_LONG:
        CsvHandler.longReader(object, field, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_DOUBLE:
        /* falls through */
    case CellHandler.PRIMITIVE_DOUBLE:
        CsvHandler.doubleReader(object, field, xlsAnnotation, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_BIGDECIMAL:
        CsvHandler.bigDecimalReader(object, field, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_FLOAT:
        /* falls through */
    case CellHandler.PRIMITIVE_FLOAT:
        CsvHandler.floatReader(object, field, values, idx);
        isUpdated = true;
        break;

    case CellHandler.OBJECT_BOOLEAN:
        /* falls through */
    case CellHandler.PRIMITIVE_BOOLEAN:
        CsvHandler.booleanReader(object, field, xlsAnnotation, values, idx);
        isUpdated = true;
        break;

    default:
        isUpdated = false;
        break;
    }

    if (!isUpdated && fT.isEnum()) {
        try {
            field.set(object, Enum.valueOf((Class<Enum>) fT, values[idx]));
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new WorkbookException(e.getMessage(), e);
        }
        isUpdated = true;
    }
    /* set disabled the accessible object */
    field.setAccessible(false);

    return isUpdated;
}