List of usage examples for java.lang Class isEnum
public boolean isEnum()
From source file:com.evolveum.midpoint.prism.parser.PrismBeanConverter.java
public <T> XNode marshall(T bean, SerializationContext ctx) throws SchemaException { if (bean == null) { return null; }/* w w w. jav a 2 s . c o m*/ if (bean instanceof SchemaDefinitionType) { return marshalSchemaDefinition((SchemaDefinitionType) bean); } else if (bean instanceof ProtectedDataType<?>) { MapXNode xProtected = marshalProtectedDataType((ProtectedDataType<?>) bean); return xProtected; } else if (bean instanceof ItemPathType) { return marshalItemPathType((ItemPathType) bean); } else if (bean instanceof RawType) { return marshalRawValue((RawType) bean); } else if (bean instanceof XmlAsStringType) { return marshalXmlAsStringType((XmlAsStringType) bean); } else if (prismContext != null && prismContext.getSchemaRegistry().determineDefinitionFromClass(bean.getClass()) != null) { return prismContext.getXnodeProcessor().serializeObject(((Objectable) bean).asPrismObject(), false, ctx) .getSubnode(); } // Note: SearchFilterType is treated below Class<? extends Object> beanClass = bean.getClass(); if (beanClass == String.class) { return createPrimitiveXNode((String) bean, DOMUtil.XSD_STRING, false); } //check for enums if (beanClass.isEnum()) { String enumValue = inspector.findEnumFieldValue(beanClass, bean.toString()); if (StringUtils.isEmpty(enumValue)) { enumValue = bean.toString(); } QName fieldTypeName = inspector.findFieldTypeName(null, beanClass, DEFAULT_PLACEHOLDER); return createPrimitiveXNode(enumValue, fieldTypeName, false); } MapXNode xmap; if (bean instanceof SearchFilterType) { // this hack is here because of c:ConditionalSearchFilterType - it is analogous to situation when unmarshalling this type (TODO: rework this in a nicer way) xmap = marshalSearchFilterType((SearchFilterType) bean); if (SearchFilterType.class.equals(bean.getClass())) { return xmap; // nothing more to serialize; otherwise we continue, because in that case we deal with a subclass of SearchFilterType } } else { xmap = new MapXNode(); } XmlType xmlType = beanClass.getAnnotation(XmlType.class); if (xmlType == null) { throw new IllegalArgumentException( "Cannot marshall " + beanClass + " it does not have @XmlType annotation"); } String namespace = inspector.determineNamespace(beanClass); if (namespace == null) { throw new IllegalArgumentException("Cannot determine namespace of " + beanClass); } List<String> propOrder = inspector.getPropOrder(beanClass); for (String fieldName : propOrder) { QName elementName = inspector.findFieldElementQName(fieldName, beanClass, namespace); Method getter = inspector.findPropertyGetter(beanClass, fieldName); if (getter == null) { throw new IllegalStateException("No getter for field " + fieldName + " in " + beanClass); } Object getterResult; try { getterResult = getter.invoke(bean); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new SystemException( "Cannot invoke method for field " + fieldName + " in " + beanClass + ": " + e.getMessage(), e); } if (getterResult == null) { continue; } Field field = inspector.findPropertyField(beanClass, fieldName); boolean isAttribute = inspector.isAttribute(field, getter); if (getterResult instanceof Collection<?>) { Collection col = (Collection) getterResult; if (col.isEmpty()) { continue; } Iterator i = col.iterator(); if (i == null) { // huh?!? .. but it really happens throw new IllegalArgumentException( "Iterator of collection returned from " + getter + " is null"); } Object getterResultValue = i.next(); if (getterResultValue == null) { continue; } ListXNode xlist = new ListXNode(); // elementName will be determined from the first item on the list // TODO make sure it will be correct with respect to other items as well! if (getterResultValue instanceof JAXBElement && ((JAXBElement) getterResultValue).getName() != null) { elementName = ((JAXBElement) getterResultValue).getName(); } for (Object element : col) { if (element == null) { continue; } QName fieldTypeName = inspector.findFieldTypeName(field, element.getClass(), namespace); Object elementToMarshall = element; if (element instanceof JAXBElement) { elementToMarshall = ((JAXBElement) element).getValue(); } XNode marshalled = marshallValue(elementToMarshall, fieldTypeName, isAttribute, ctx); // Brutal hack - made here just to make scripts (bulk actions) functional while not breaking anything else // Fix it in 3.1. [med] if (fieldTypeName == null && element instanceof JAXBElement && marshalled != null) { QName typeName = inspector.determineTypeForClass(elementToMarshall.getClass()); if (typeName != null && !getSchemaRegistry().hasImplicitTypeDefinition(elementName, typeName)) { marshalled.setExplicitTypeDeclaration(true); marshalled.setTypeQName(typeName); } } else { // end of hack setExplicitTypeDeclarationIfNeeded(getter, getterResultValue, marshalled, fieldTypeName); } xlist.add(marshalled); } xmap.put(elementName, xlist); } else { QName fieldTypeName = inspector.findFieldTypeName(field, getterResult.getClass(), namespace); Object valueToMarshall = null; if (getterResult instanceof JAXBElement) { valueToMarshall = ((JAXBElement) getterResult).getValue(); elementName = ((JAXBElement) getterResult).getName(); } else { valueToMarshall = getterResult; } XNode marshelled = marshallValue(valueToMarshall, fieldTypeName, isAttribute, ctx); if (!getter.getReturnType().equals(valueToMarshall.getClass()) && getter.getReturnType().isAssignableFrom(valueToMarshall.getClass())) { if (prismContext != null) { PrismObjectDefinition def = prismContext.getSchemaRegistry() .determineDefinitionFromClass(valueToMarshall.getClass()); if (def != null) { QName type = def.getTypeName(); marshelled.setTypeQName(type); marshelled.setExplicitTypeDeclaration(true); } } } xmap.put(elementName, marshelled); // setExplicitTypeDeclarationIfNeeded(getter, valueToMarshall, xmap, fieldTypeName); } } return xmap; }
From source file:org.soybeanMilk.core.bean.DefaultGenericConverter.java
@SuppressWarnings("unchecked") protected Object convertStringToType(String str, Type type) throws ConvertException { Object result = null;/*from w w w . j a v a 2s.co m*/ if (str == null || str.length() == 0) { if (SbmUtils.isPrimitive(type)) throw new GenericConvertException("can not convert " + SbmUtils.toString(str) + " to primitive type " + SbmUtils.toString(type)); else return null; } else if (SbmUtils.isClassType(type)) { @SuppressWarnings("rawtypes") Class clazz = SbmUtils.narrowToClass(type); if (clazz.isEnum()) result = Enum.valueOf(clazz, str); else result = converterNotFoundThrow(str.getClass(), type); } else if (type instanceof TypeVariable<?>) { result = convertObjectToType(str, reify(type)); } else if (type instanceof WildcardType) { result = convertObjectToType(str, reify(type)); } else if (type instanceof ParameterizedType) { result = converterNotFoundThrow(str.getClass(), type); } else if (type instanceof GenericArrayType) { result = converterNotFoundThrow(str.getClass(), type); } else result = converterNotFoundThrow(str.getClass(), type); return result; }
From source file:org.datacleaner.util.convert.StandardTypeConverter.java
@Override public Object fromString(Class<?> type, String str) { if (ReflectionUtils.isString(type)) { return str; }/*from w ww . j av a 2 s .c o m*/ if (ReflectionUtils.isBoolean(type)) { return Boolean.valueOf(str); } if (ReflectionUtils.isCharacter(type)) { return Character.valueOf(str.charAt(0)); } if (ReflectionUtils.isInteger(type)) { return Integer.valueOf(str); } if (ReflectionUtils.isLong(type)) { return Long.valueOf(str); } if (ReflectionUtils.isByte(type)) { return Byte.valueOf(str); } if (ReflectionUtils.isShort(type)) { return Short.valueOf(str); } if (ReflectionUtils.isDouble(type)) { return Double.valueOf(str); } if (ReflectionUtils.isFloat(type)) { return Float.valueOf(str); } if (ReflectionUtils.is(type, Class.class)) { try { return Class.forName(str); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Class not found: " + str, e); } } if (ReflectionUtils.is(type, EnumerationValue.class)) { return new EnumerationValue(str); } if (type.isEnum()) { try { Object[] enumConstants = type.getEnumConstants(); // first look for enum constant matches Method nameMethod = Enum.class.getMethod("name"); for (Object e : enumConstants) { String name = (String) nameMethod.invoke(e); if (name.equals(str)) { return e; } } // check for aliased enums for (Object e : enumConstants) { String name = (String) nameMethod.invoke(e); Field field = type.getField(name); Alias alias = ReflectionUtils.getAnnotation(field, Alias.class); if (alias != null) { String[] aliasValues = alias.value(); for (String aliasValue : aliasValues) { if (aliasValue.equals(str)) { return e; } } } } } catch (Exception e) { throw new IllegalStateException("Unexpected error occurred while examining enum", e); } throw new IllegalArgumentException("No such enum '" + str + "' in enum class: " + type.getName()); } if (ReflectionUtils.isDate(type)) { return toDate(str); } if (ReflectionUtils.is(type, File.class)) { final FileResolver fileResolver = new FileResolver(_configuration); return fileResolver.toFile(str); } if (ReflectionUtils.is(type, Calendar.class)) { Date date = toDate(str); Calendar c = Calendar.getInstance(); c.setTime(date); return c; } if (ReflectionUtils.is(type, Pattern.class)) { try { return Pattern.compile(str); } catch (PatternSyntaxException e) { throw new IllegalArgumentException("Invalid regular expression syntax in '" + str + "'.", e); } } if (ReflectionUtils.is(type, java.sql.Date.class)) { Date date = toDate(str); return new java.sql.Date(date.getTime()); } if (ReflectionUtils.isNumber(type)) { return ConvertToNumberTransformer.transformValue(str); } if (ReflectionUtils.is(type, Serializable.class)) { logger.warn("fromString(...): No built-in handling of type: {}, using deserialization", type.getName()); byte[] bytes = (byte[]) _parentConverter.fromString(byte[].class, str); ChangeAwareObjectInputStream objectInputStream = null; try { objectInputStream = new ChangeAwareObjectInputStream(new ByteArrayInputStream(bytes)); objectInputStream.addClassLoader(type.getClassLoader()); Object obj = objectInputStream.readObject(); return obj; } catch (Exception e) { throw new IllegalStateException("Could not deserialize to " + type + ".", e); } finally { FileHelper.safeClose(objectInputStream); } } throw new IllegalArgumentException("Could not convert to type: " + type.getName()); }
From source file:org.itest.impl.ITestValueConverterImpl.java
@Override public <T> T convert(Class<T> clazz, String value) { Object res;//w ww . j av a 2 s . c o m if (null == value) { res = null; } else if (String.class == clazz || Object.class == clazz) { res = StringEscapeUtils.unescapeJava(value); } else if (Integer.class == clazz || int.class == clazz) { res = Integer.valueOf(value); } else if (Long.class == clazz || long.class == clazz) { res = Long.valueOf(value); } else if (Double.class == clazz || double.class == clazz) { res = Double.valueOf(value); } else if (Float.class == clazz || float.class == clazz) { res = Float.valueOf(value); } else if (Boolean.class == clazz || boolean.class == clazz) { res = Boolean.valueOf(value); } else if (Character.class == clazz || char.class == clazz) { value = StringEscapeUtils.unescapeJava(value); if (value.length() > 1) { throw new ITestInitializationException( "Character expected, found (" + value + ") " + value.length() + " characters.", null); } res = value.charAt(0); } else if (Date.class == clazz || Time.class == clazz || Timestamp.class == clazz || java.sql.Date.class == clazz) { Long milis = Long.valueOf(value); try { res = clazz.getConstructor(long.class).newInstance(milis); } catch (Exception e) { throw new ITestException("", e); } } else if (clazz.isEnum()) { res = Enum.valueOf((Class<Enum>) clazz, value); } else if (Class.class == clazz) { try { res = ClassUtils.getClass(getClass().getClassLoader(), value); } catch (ClassNotFoundException e) { throw new ITestInitializationException(value, e); } } else { throw new ITestInitializationException(clazz.getName() + "(" + value + ")", null); } return (T) res; }
From source file:org.efaps.esjp.common.uiform.Field_Base.java
/** * @param _parameter Parameter as passed from the eFaps API * @return Return containing Html Snipplet * @throws EFapsException on error//from w w w . j a v a 2 s . c o m */ public Return getLabel4Enum(final Parameter _parameter) throws EFapsException { final Return ret = new Return(); final String enumName = getProperty(_parameter, "Enum"); if (enumName != null) { try { final Class<?> enumClazz = Class.forName(enumName); if (enumClazz.isEnum()) { final Object[] consts = enumClazz.getEnumConstants(); final Integer ordinal; final Object uiObject = _parameter.get(ParameterValues.UIOBJECT); if (uiObject instanceof IUIValue && ((IUIValue) uiObject).getObject() != null) { ordinal = (Integer) ((IUIValue) uiObject).getObject(); final String label = DBProperties.getProperty(enumName + "." + consts[ordinal].toString()); ret.put(ReturnValues.VALUES, label); } } } catch (final ClassNotFoundException e) { LOG.error("ClassNotFoundException", e); } } return ret; }
From source file:org.efaps.esjp.common.uiform.Field_Base.java
/** * @param _parameter Parameter as passed from the eFaps API * @return Return containing Html Snipplet * @throws EFapsException on error/*ww w . ja v a2s . c om*/ */ public Return getOptionList4Enum(final Parameter _parameter) throws EFapsException { final List<DropDownPosition> values = new ArrayList<>(); final String enumName = getProperty(_parameter, "Enum"); if (enumName != null) { final boolean orderByOrdinal = "true".equalsIgnoreCase(getProperty(_parameter, "OrderByOrdinal")); try { final Class<?> enumClazz = Class.forName(enumName); if (enumClazz.isEnum()) { final Object[] consts = enumClazz.getEnumConstants(); Integer selected = -1; final Object uiObject = _parameter.get(ParameterValues.UIOBJECT); if (uiObject instanceof IUIValue && ((IUIValue) uiObject).getObject() != null) { selected = (Integer) ((IUIValue) uiObject).getObject(); } else if (containsProperty(_parameter, "DefaultValue")) { final String defaultValue = getProperty(_parameter, "DefaultValue"); for (final Object con : consts) { if (((Enum<?>) con).name().equals(defaultValue)) { selected = ((Enum<?>) con).ordinal(); break; } } } if (org.efaps.admin.ui.field.Field.Display.EDITABLE .equals(((IUIValue) uiObject).getDisplay())) { for (final Object con : consts) { final Enum<?> enumVal = (Enum<?>) con; final Integer ordinal = enumVal.ordinal(); final String label = DBProperties.getProperty(enumName + "." + enumVal.name()); final DropDownPosition pos = new DropDownPosition(ordinal, label, orderByOrdinal ? ordinal : label); values.add(pos); pos.setSelected(ordinal == selected); } Collections.sort(values, new Comparator<DropDownPosition>() { @SuppressWarnings("unchecked") @Override public int compare(final DropDownPosition _o1, final DropDownPosition _o2) { return _o1.getOrderValue().compareTo(_o2.getOrderValue()); } }); } } } catch (final ClassNotFoundException e) { LOG.error("ClassNotFoundException", e); } } final Return ret = new Return(); ret.put(ReturnValues.VALUES, values); return ret; }
From source file:com.expressui.core.view.field.FormField.java
private void initializeFieldDefaults() { if (field == null) { return;//w ww . j a v a 2 s. c o m } field.setInvalidAllowed(true); if (field instanceof AbstractField) { initAbstractFieldDefaults((AbstractField) field); } if (field instanceof AbstractTextField) { initTextFieldDefaults((AbstractTextField) field); initWidthAndMaxLengthDefaults((AbstractTextField) field); } if (field instanceof RichTextArea) { initRichTextFieldDefaults((RichTextArea) field); } if (field instanceof DateField) { initDateFieldDefaults((DateField) field); } if (field instanceof AbstractSelect) { initAbstractSelectDefaults((AbstractSelect) field); if (field instanceof Select) { initSelectDefaults((Select) field); } if (field instanceof ListSelect) { initListSelectDefaults((ListSelect) field); } Class valueType = getPropertyType(); if (getBeanPropertyType().isCollectionType()) { valueType = getBeanPropertyType().getCollectionValueType(); } List referenceEntities = null; if (Currency.class.isAssignableFrom(valueType)) { referenceEntities = CurrencyUtil.getAvailableCurrencies(); ((AbstractSelect) field).setItemCaptionPropertyId("currencyCode"); } else if (valueType.isEnum()) { Object[] enumConstants = valueType.getEnumConstants(); referenceEntities = Arrays.asList(enumConstants); } else if (ReferenceEntity.class.isAssignableFrom(valueType)) { EntityDao propertyDao = SpringApplicationContext .getBeanByTypeAndGenericArgumentType(EntityDao.class, valueType); if (propertyDao != null) { referenceEntities = propertyDao.findAll(); } else { referenceEntities = referenceEntityDao.findAll(valueType); } } if (referenceEntities != null) { setSelectItems(referenceEntities); } } if (getFormFieldSet().isEntityForm()) { if (getBeanPropertyType().isValidatable()) { initializeIsRequired(); initializeValidators(); } // Change listener causes erratic behavior for RichTextArea if (!(field instanceof RichTextArea)) { field.addListener(new FieldValueChangeListener()); } } setOriginallyReadOnly(field.isReadOnly()); isVisible = field.isVisible(); }
From source file:com.basistech.rosette.apimodel.ModelTest.java
private Object createObjectForType(Class<?> type, Type genericParameterType) throws IllegalAccessException, InstantiationException, InvocationTargetException { Object o = null;/* w w w .ja v a2s . co m*/ Class firstComponentType = type.isArray() ? type.getComponentType() : type; String typeName = firstComponentType.getSimpleName(); Class parameterArgClass = null; Type[] parameterArgTypes = null; if (genericParameterType != null) { if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; parameterArgTypes = aType.getActualTypeArguments(); for (Type parameterArgType : parameterArgTypes) { if (parameterArgType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) parameterArgType; if (isListString(parameterizedType)) { List<List<String>> rv = Lists.newArrayList(); rv.add(Lists.newArrayList("string")); return rv; } } else { parameterArgClass = (Class) parameterArgType; if ("Map".equals(typeName)) { break; } } } } } if (firstComponentType.isEnum()) { return firstComponentType.getEnumConstants()[0]; } switch (typeName) { case "byte": { if (type.isArray()) { o = "somebytes".getBytes(); } else { o = (byte) '8'; } break; } case "String": case "CharSequence": { o = "foo"; break; } case "long": case "Long": { o = (long) 123456789; break; } case "Double": case "double": { o = 1.0; break; } case "int": case "Integer": { o = 98761234; break; } case "boolean": case "Boolean": { o = false; break; } case "Collection": case "List": { if (parameterArgClass != null) { Object o1 = createObjectForType(parameterArgClass, null); List<Object> list = new ArrayList<>(); list.add(o1); o = list; } break; } case "Object": if (inputStreams) { o = new ByteArrayInputStream(new byte[0]); } else { o = "foo"; } break; case "EnumSet": break; case "Set": { if (parameterArgClass != null) { Object o1 = createObjectForType(parameterArgClass, null); Set<Object> set = new HashSet<>(); set.add(o1); o = set; } break; } case "Map": { if (parameterArgTypes != null && parameterArgTypes.length == 2) { Class keyClass = (Class) parameterArgTypes[0]; Object keyObject = createObject(keyClass); if (keyObject != null) { HashMap<Object, Object> map = new HashMap<>(); map.put(keyObject, null); o = map; } } break; } default: if (parameterArgClass != null) { Constructor[] ctors = parameterArgClass.getDeclaredConstructors(); o = createObject(ctors[0]); } else { Constructor[] ctors = firstComponentType.getDeclaredConstructors(); o = createObject(ctors[0]); } } return o; }
From source file:gov.nih.nci.system.web.struts.action.CreateAction.java
public Object convertValue(Class klass, Object value) throws NumberFormatException, Exception { String fieldType = klass.getName(); if (value == null) return null; Object convertedValue = null; try {//w w w . ja va2 s .c om if (fieldType.equals("java.lang.Long")) { convertedValue = new Long((String) value); } else if (fieldType.equals("java.lang.Integer")) { convertedValue = new Integer((String) value); } else if (fieldType.equals("java.lang.String")) { convertedValue = value; } else if (fieldType.equals("java.lang.Float")) { convertedValue = new Float((String) value); } else if (fieldType.equals("java.lang.Double")) { convertedValue = new Double((String) value); } else if (fieldType.equals("java.lang.Boolean")) { convertedValue = new Boolean((String) value); } else if (fieldType.equals("java.util.Date")) { SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy"); convertedValue = format.parse((String) value); } else if (fieldType.equals("java.net.URI")) { convertedValue = new URI((String) value); } else if (fieldType.equals("java.lang.Character")) { convertedValue = new Character(((String) value).charAt(0)); } else if (klass.isEnum()) { Class enumKlass = Class.forName(fieldType); convertedValue = Enum.valueOf(enumKlass, (String) value); } else { throw new Exception("type mismatch - " + fieldType); } } catch (NumberFormatException e) { e.printStackTrace(); log.error("ERROR : " + e.getMessage()); throw e; } catch (Exception ex) { ex.printStackTrace(); log.error("ERROR : " + ex.getMessage()); throw ex; } return convertedValue; }
From source file:com.expressui.core.view.field.FormField.java
private Field generateField() { Class propertyType = getPropertyType(); if (propertyType == null) { return null; }//from ww w . j av a 2s. co m if (Date.class.isAssignableFrom(propertyType)) { return new DateField(); } if (boolean.class.isAssignableFrom(propertyType) || Boolean.class.isAssignableFrom(propertyType)) { return new CheckBox(); } if (ReferenceEntity.class.isAssignableFrom(propertyType)) { return new Select(); } if (Currency.class.isAssignableFrom(propertyType)) { return new Select(); } if (propertyType.isEnum()) { return new Select(); } if (Collection.class.isAssignableFrom(propertyType)) { return new ListSelect(); } if (getBeanPropertyType().hasAnnotation(Lob.class)) { return new RichTextArea(); } return new TextField(); }