List of usage examples for java.lang Class isEnum
public boolean isEnum()
From source file:org.projectforge.database.TableAttribute.java
/** * Creates a property and gets the information from the entity class. The JPA annotations Column, JoinColumn, Entity, Table and ID are * supported./*w ww .j a v a 2 s. c om*/ * @param clazz * @param property */ public TableAttribute(final Class<?> clazz, final String property) { this.property = property; this.name = property; final Method getterMethod = BeanHelper.determineGetter(clazz, property); if (getterMethod == null) { throw new IllegalStateException("Can't determine getter: " + clazz + "." + property); } final Class<?> dType = BeanHelper.determinePropertyType(getterMethod); final boolean primitive = dType.isPrimitive(); if (Boolean.class.isAssignableFrom(dType) == true || Boolean.TYPE.isAssignableFrom(dType) == true) { type = TableAttributeType.BOOLEAN; } else if (Integer.class.isAssignableFrom(dType) == true || Integer.TYPE.isAssignableFrom(dType) == true) { type = TableAttributeType.INT; } else if (String.class.isAssignableFrom(dType) == true || dType.isEnum() == true) { type = TableAttributeType.VARCHAR; } else if (BigDecimal.class.isAssignableFrom(dType) == true) { type = TableAttributeType.DECIMAL; } else if (java.sql.Date.class.isAssignableFrom(dType) == true) { type = TableAttributeType.DATE; } else if (java.util.Date.class.isAssignableFrom(dType) == true) { type = TableAttributeType.TIMESTAMP; } else if (java.util.Locale.class.isAssignableFrom(dType) == true) { type = TableAttributeType.LOCALE; } else { final Entity entity = dType.getAnnotation(Entity.class); final javax.persistence.Table table = dType.getAnnotation(javax.persistence.Table.class); if (entity != null && table != null && StringUtils.isNotEmpty(table.name()) == true) { this.foreignTable = table.name(); final String idProperty = JPAHelper.getIdProperty(dType); if (idProperty == null) { log.info("Id property not found for class '" + dType + "'): " + clazz + "." + property); } this.foreignAttribute = idProperty; final Column column = JPAHelper.getColumnAnnotation(dType, idProperty); if (column != null && StringUtils.isNotEmpty(column.name()) == true) { this.foreignAttribute = column.name(); } } else { log.info( "Unsupported property (@Entity, @Table and @Table.name expected for the destination class '" + dType + "'): " + clazz + "." + property); } type = TableAttributeType.INT; } final Id id = JPAHelper.getIdAnnotation(clazz, property); if (id != null) { this.primaryKey = true; this.nullable = false; } if (primitive == true) { nullable = false; } final Column column = JPAHelper.getColumnAnnotation(clazz, property); if (column != null) { if (isPrimaryKey() == false && primitive == false) { this.nullable = column.nullable(); } if (StringUtils.isNotEmpty(column.name()) == true) { this.name = column.name(); } if (type.isIn(TableAttributeType.VARCHAR, TableAttributeType.CHAR) == true) { this.length = column.length(); } if (type == TableAttributeType.DECIMAL) { this.precision = column.precision(); this.scale = column.scale(); } this.unique = column.unique(); } if (type == TableAttributeType.DECIMAL && this.scale == 0 && this.precision == 0) { throw new UnsupportedOperationException( "Decimal values should have a precision and scale definition: " + clazz + "." + property); } final JoinColumn joinColumn = JPAHelper.getJoinColumnAnnotation(clazz, property); if (joinColumn != null) { if (StringUtils.isNotEmpty(joinColumn.name()) == true) { this.name = joinColumn.name(); } } }
From source file:com.bstek.dorado.config.definition.Definition.java
/** * ?/*from w ww .j a v a 2 s .c o m*/ * * @param object * ? * @param property * ?? * @param value * @see {@link #getProperties()} * @param context * * @throws Exception */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected void setObjectProperty(Object object, String property, Object value, CreationContext context) throws Exception { if (object instanceof Map) { value = DefinitionUtils.getRealValue(value, context); if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { List collection = new ArrayList(); for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } value = collection; } if (value != ConfigUtils.IGNORE_VALUE) { ((Map) object).put(property, value); } } else { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(object, property); if (propertyDescriptor != null) { Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); Class<?> propertyType = propertyDescriptor.getPropertyType(); if (writeMethod != null) { Class<?> oldImpl = context.getDefaultImpl(); try { context.setDefaultImpl(propertyType); value = DefinitionUtils.getRealValue(value, context); } finally { context.setDefaultImpl(oldImpl); } if (!propertyType.equals(String.class) && value instanceof String) { if (propertyType.isEnum()) { value = Enum.valueOf((Class) propertyType, (String) value); } else if (StringUtils.isBlank((String) value)) { value = null; } } else if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { List collection = new ArrayList(); for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } value = collection; } if (value != ConfigUtils.IGNORE_VALUE) { writeMethod.invoke(object, new Object[] { ConvertUtils.convert(value, propertyType) }); } } else if (readMethod != null && Collection.class.isAssignableFrom(propertyType)) { Collection collection = (Collection) readMethod.invoke(object, EMPTY_ARGS); if (collection != null) { if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } } else { collection.addAll((Collection) value); } } } else { throw new NoSuchMethodException( "Property [" + property + "] of [" + object + "] is not writable."); } } else { throw new NoSuchMethodException("Property [" + property + "] not found in [" + object + "]."); } } }
From source file:org.atricore.idbus.kernel.main.databinding.JAXBUtils.java
private static ArrayList<Class> getClassesFromDirectory(String pkg, ClassLoader cl) throws ClassNotFoundException { // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths String pckgname = pkg;//from w ww.jav a 2s . c om ArrayList<File> directories = new ArrayList<File>(); try { String path = pckgname.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = cl.getResources(path); while (resources.hasMoreElements()) { directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8"))); } } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug(pckgname + " does not appear to be a valid package (Unsupported encoding)"); } throw new ClassNotFoundException( pckgname + " might not be a valid package because the encoding is unsupported."); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("IOException was thrown when trying to get all resources for " + pckgname); } throw new ClassNotFoundException( "An IOException error was thrown when trying to get all of the resources for " + pckgname); } ArrayList<Class> classes = new ArrayList<Class>(); // For every directory identified capture all the .class files for (File directory : directories) { if (log.isDebugEnabled()) { log.debug(" Adding JAXB classes from directory: " + directory.getName()); } if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { // we are only interested in .class files if (file.endsWith(".class")) { // removes the .class extension // TODO Java2 Sec String className = pckgname + '.' + file.substring(0, file.length() - 6); try { Class clazz = forName(className, false, getContextClassLoader()); // Don't add any interfaces or JAXWS specific classes. // Only classes that represent data and can be marshalled // by JAXB should be added. if (!clazz.isInterface() && (clazz.isEnum() || getAnnotation(clazz, XmlType.class) != null || ClassUtils.getDefaultPublicConstructor(clazz) != null) && !ClassUtils.isJAXWSClass(clazz) && !isSkipClass(clazz) && !Exception.class.isAssignableFrom(clazz)) { // Ensure that all the referenced classes are loadable too clazz.getDeclaredMethods(); clazz.getDeclaredFields(); if (log.isDebugEnabled()) { log.debug("Adding class: " + file); } classes.add(clazz); // REVIEW: // Support of RPC list (and possibly other scenarios) requires that the array classes should also be present. // This is a hack until we can determine how to get this information. // The arrayName and loadable name are different. Get the loadable // name, load the array class, and add it to our list //className += "[]"; //String loadableName = ClassUtils.getLoadableClassName(className); //Class aClazz = Class.forName(loadableName, false, Thread.currentThread().getContextClassLoader()); } //Catch Throwable as ClassLoader can throw an NoClassDefFoundError that //does not extend Exception } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Tried to load class " + className + " while constructing a JAXBContext. This class will be skipped. Processing Continues."); log.debug(" The reason that class could not be loaded:" + e.toString()); log.trace(JavaUtils.stackToString(e)); } } } } } } return classes; }
From source file:org.force66.beantester.valuegens.ValueGeneratorFactory.java
public ValueGenerator<?> forClass(Class<?> targetClass) { Validate.notNull(targetClass, "Null class not allowed"); ValueGenerator<?> generator = registeredGeneratorMap.get(targetClass); if (generator == null) { for (ValueGenerator<?> gen : STOCK_GENERATORS) { if (gen.canGenerate(targetClass)) { registeredGeneratorMap.put(targetClass, gen); return gen; }//w w w . j a v a2s .c o m } } else { return generator; } if (targetClass.isInterface()) { InterfaceValueGenerator gen = new InterfaceValueGenerator(targetClass); this.registerGenerator(targetClass, gen); return gen; } else if (Modifier.isAbstract(targetClass.getModifiers())) { return null; // generator not possible on abstract classes } else if (targetClass.isEnum()) { return registerGenericGenerator(targetClass, targetClass.getEnumConstants()); } else if (targetClass.isArray()) { ArrayValueGenerator gen = new ArrayValueGenerator(targetClass, this); this.registerGenerator(targetClass, gen); return gen; } else if (Class.class.equals(targetClass)) { return registerGenericGenerator(targetClass, new Object[] { Object.class }); } else { return registerGenericGenerator(targetClass, new Object[] { InstantiationUtils.safeNewInstance(this, targetClass) }); } }
From source file:com.citytechinc.cq.component.touchuidialog.util.TouchUIDialogUtil.java
public static final List<com.citytechinc.cq.component.touchuidialog.widget.selection.options.Option> getOptionsForSelection( Selection selectionAnnotation, Class<?> type, ClassLoader classLoader, ClassPool classPool) throws InvalidComponentFieldException { List<com.citytechinc.cq.component.touchuidialog.widget.selection.options.Option> options = new ArrayList<com.citytechinc.cq.component.touchuidialog.widget.selection.options.Option>(); /*//from w w w.j av a 2 s . c o m * Options specified in the annotation take precedence */ if (selectionAnnotation != null && selectionAnnotation.options().length > 0) { int i = 0; for (com.citytechinc.cq.component.annotations.Option curOptionAnnotation : selectionAnnotation .options()) { if (StringUtils.isEmpty(curOptionAnnotation.value())) { throw new InvalidComponentFieldException( "Selection Options specified in the selectionOptions Annotation property must include a non-empty text and value attribute"); } OptionParameters optionParameters = new OptionParameters(); optionParameters.setText(curOptionAnnotation.text()); optionParameters.setValue(curOptionAnnotation.value()); optionParameters.setSelected(curOptionAnnotation.selected()); optionParameters.setFieldName(OPTION_FIELD_NAME_PREFIX + (i++)); options.add(new com.citytechinc.cq.component.touchuidialog.widget.selection.options.Option( optionParameters)); } } /* * If options were not specified by the annotation then we check to see * if the field is an Enum and if so, the options are pulled from the * Enum definition */ else if (type.isEnum()) { int i = 0; try { for (Object curEnumObject : classLoader.loadClass(type.getName()).getEnumConstants()) { Enum<?> curEnum = (Enum<?>) curEnumObject; options.add(buildSelectionOptionForEnum(curEnum, classPool, OPTION_FIELD_NAME_PREFIX + (i++))); } } catch (Exception e) { throw new InvalidComponentFieldException("Error generating selection from enum", e); } } return options; }
From source file:org.apache.syncope.client.console.panels.BeanPanel.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private FieldPanel buildSinglePanel(final Serializable bean, final Class<?> type, final String fieldName, final String id) { FieldPanel result = null;// ww w.ja v a 2 s . c o m PropertyModel model = new PropertyModel(bean, fieldName); if (ClassUtils.isAssignable(Boolean.class, type)) { result = new AjaxCheckBoxPanel(id, fieldName, model); } else if (ClassUtils.isAssignable(Number.class, type)) { result = new AjaxSpinnerFieldPanel.Builder<>().build(id, fieldName, (Class<Number>) ClassUtils.resolvePrimitiveIfNecessary(type), model); } else if (Date.class.equals(type)) { result = new AjaxDateTimeFieldPanel(id, fieldName, model, SyncopeConstants.DEFAULT_DATE_PATTERN); } else if (type.isEnum()) { result = new AjaxDropDownChoicePanel(id, fieldName, model) .setChoices(Arrays.asList(type.getEnumConstants())); } // treat as String if nothing matched above if (result == null) { result = new AjaxTextFieldPanel(id, fieldName, model); } result.hideLabel(); return result; }
From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java
private static ArrayList<Class> getClassesFromDirectory(String pkg, ClassLoader cl) throws ClassNotFoundException { // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths String pckgname = pkg;/*from w w w .j a v a 2 s.c om*/ ArrayList<File> directories = new ArrayList<File>(); try { String path = pckgname.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = cl.getResources(path); while (resources.hasMoreElements()) { directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8"))); } } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug(pckgname + " does not appear to be a valid package (Unsupported encoding)"); } throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr2", pckgname)); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("IOException was thrown when trying to get all resources for " + pckgname); } throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr3", pckgname)); } ArrayList<Class> classes = new ArrayList<Class>(); // For every directory identified capture all the .class files for (File directory : directories) { if (log.isDebugEnabled()) { log.debug(" Adding JAXB classes from directory: " + directory.getName()); } if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { // we are only interested in .class files if (file.endsWith(".class")) { // removes the .class extension // TODO Java2 Sec String className = pckgname + '.' + file.substring(0, file.length() - 6); try { Class clazz = forName(className, false, getContextClassLoader()); // Don't add any interfaces or JAXWS specific classes. // Only classes that represent data and can be marshalled // by JAXB should be added. if (!clazz.isInterface() && (clazz.isEnum() || getAnnotation(clazz, XmlType.class) != null || ClassUtils.getDefaultPublicConstructor(clazz) != null) && !ClassUtils.isJAXWSClass(clazz) && !isSkipClass(clazz) && !java.lang.Exception.class.isAssignableFrom(clazz)) { // Ensure that all the referenced classes are loadable too clazz.getDeclaredMethods(); clazz.getDeclaredFields(); if (log.isDebugEnabled()) { log.debug("Adding class: " + file); } classes.add(clazz); // REVIEW: // Support of RPC list (and possibly other scenarios) requires that the array classes should also be present. // This is a hack until we can determine how to get this information. // The arrayName and loadable name are different. Get the loadable // name, load the array class, and add it to our list //className += "[]"; //String loadableName = ClassUtils.getLoadableClassName(className); //Class aClazz = Class.forName(loadableName, false, Thread.currentThread().getContextClassLoader()); } //Catch Throwable as ClassLoader can throw an NoClassDefFoundError that //does not extend Exception } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Tried to load class " + className + " while constructing a JAXBContext. This class will be skipped. Processing Continues."); log.debug(" The reason that class could not be loaded:" + e.toString()); log.trace(JavaUtils.stackToString(e)); } } } } } } return classes; }
From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java
public JSONObject describeClass(Class<?> clazz) throws Exception { JSONObject desc = new JSONObject(); desc.put("name", clazz.getName()); if (clazz.isEnum()) { @SuppressWarnings("unchecked") Class<Enum<?>> enumClass = (Class<Enum<?>>) clazz; ArrayList<String> enumNames = Lists.newArrayList(); for (Enum<?> e : enumClass.getEnumConstants()) { enumNames.add(e.name());// w ww . j av a2 s . c o m } desc.put("enum", enumNames); } UI_TYPE ui_type = UI_TYPE.getEnumFor(clazz); if (ui_type != null) { desc.put("uiType", ui_type.getName()); } desc.put("properties", getClassProperties(clazz, 0)); return desc; }
From source file:net.jofm.metadata.PrimitiveFieldMetaData.java
private static Format createFormatter(Field fieldAnnotation, Class<?> fieldType, String fieldName, FormatConfig formatConfig) {//from w w w . j a va 2 s. c o m String defaultFormat = ""; Class<? extends Format> formatterClazz = null; if (Date.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) { defaultFormat = formatConfig.getDateFormat(); formatterClazz = DateFormat.class; } else if (String.class.isAssignableFrom(fieldType)) { formatterClazz = StringFormat.class; } else if (fieldType.equals(BigDecimal.class)) { defaultFormat = formatConfig.getBigDecimalFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) { defaultFormat = formatConfig.getShortFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) { defaultFormat = formatConfig.getIntFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) { defaultFormat = formatConfig.getLongFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) { defaultFormat = formatConfig.getFloatFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) { defaultFormat = formatConfig.getDoubleFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) { defaultFormat = formatConfig.getBooleanFormat(); formatterClazz = BooleanFormat.class; } else if (fieldType.isEnum()) { formatterClazz = EnumFormat.class; } if (fieldAnnotation.formatter() != null && !fieldAnnotation.formatter().equals(DefaultFormat.class)) { formatterClazz = fieldAnnotation.formatter(); } if (formatterClazz == null) { throw new FixedMappingException( "Unable to find formatter for field '" + fieldName + "' of type " + fieldType); } try { Constructor<?> c = formatterClazz .getConstructor(new Class[] { Pad.class, char.class, int.class, String.class }); Pad pad = fieldAnnotation.pad() == Pad.DEFAULT ? formatConfig.getPad() : fieldAnnotation.pad(); char padWith = fieldAnnotation.padWith() == Character.MIN_VALUE ? formatConfig.getPadWith() : fieldAnnotation.padWith(); int length = fieldAnnotation.length(); String format = StringUtils.isEmpty(fieldAnnotation.format()) ? defaultFormat : fieldAnnotation.format(); return (Format) c.newInstance(new Object[] { pad, padWith, length, format }); } catch (Exception e) { throw new FixedMappingException( "Unable to instantiate the formatter " + formatterClazz + " for field '" + fieldName + "'", e); } }
From source file:org.amplafi.flow.flowproperty.FlowPropertyDefinitionImpl.java
/** * @return// w w w . j a v a 2 s . c om */ private boolean isDefaultByClassAvailable() { if (this.autoCreate != null) { return getBoolean(this.autoCreate); } if (!getDataClassDefinition().isCollection()) { Class<?> dataClass = getDataClassDefinition().getDataClass(); if (dataClass.isPrimitive()) { return true; } else if (dataClass.isInterface() || dataClass.isEnum()) { return false; } } return false; }