List of usage examples for java.lang Class getEnumConstants
public T[] getEnumConstants()
From source file:org.openmrs.util.ReportingcompatibilityUtil.java
/** * Uses reflection to translate a PatientSearch into a PatientFilter *///from w w w . j a va2s. c o m @SuppressWarnings("unchecked") public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history, EvaluationContext evalContext) { if (search.isSavedSearchReference()) { PatientSearch ps = ((PatientSearchReportObject) Context.getService(ReportObjectService.class) .getReportObject(search.getSavedSearchId())).getPatientSearch(); return toPatientFilter(ps, history, evalContext); } else if (search.isSavedFilterReference()) { return Context.getService(ReportObjectService.class).getPatientFilterById(search.getSavedFilterId()); } else if (search.isSavedCohortReference()) { Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId()); // to prevent lazy loading exceptions, cache the member ids here if (c != null) { c.getMemberIds().size(); } return new CohortFilter(c); } else if (search.isComposition()) { if (history == null && search.requiresHistory()) { throw new IllegalArgumentException("You can't evaluate this search without a history"); } else { return search.cloneCompositionAsFilter(history, evalContext); } } else { Class clz = search.getFilterClass(); if (clz == null) { throw new IllegalArgumentException( "search must be saved, composition, or must have a class specified"); } log.debug("About to instantiate " + clz); PatientFilter pf = null; try { pf = (PatientFilter) clz.newInstance(); } catch (Exception ex) { log.error("Couldn't instantiate a " + search.getFilterClass(), ex); return null; } Class[] stringSingleton = { String.class }; if (search.getArguments() != null) { for (SearchArgument sa : search.getArguments()) { if (log.isDebugEnabled()) { log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue()); } PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(sa.getName(), clz); } catch (IntrospectionException ex) { log.error("Error while examining property " + sa.getName(), ex); continue; } Class<?> realPropertyType = pd.getPropertyType(); // instantiate the value of the search argument String valueAsString = sa.getValue(); String testForExpression = search.getArgumentValue(sa.getName()); if (testForExpression != null) { log.debug("Setting " + sa.getName() + " to: " + testForExpression); if (evalContext != null && EvaluationContext.isExpression(testForExpression)) { Object evaluated = evalContext.evaluateExpression(testForExpression); if (evaluated != null) { if (evaluated instanceof Date) { valueAsString = Context.getDateFormat().format((Date) evaluated); } else { valueAsString = evaluated.toString(); } } log.debug("Evaluated " + sa.getName() + " to: " + valueAsString); } } Object value = null; Class<?> valueClass = sa.getPropertyClass(); try { // If there's a valueOf(String) method, just use that // (will cover at least String, Integer, Double, // Boolean) Method valueOfMethod = null; try { valueOfMethod = valueClass.getMethod("valueOf", stringSingleton); } catch (NoSuchMethodException ex) { } if (valueOfMethod != null) { Object[] holder = { valueAsString }; value = valueOfMethod.invoke(pf, holder); } else if (realPropertyType.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(valueAsString)) { value = e; break; } } } else if (String.class.equals(valueClass)) { value = valueAsString; } else if (Location.class.equals(valueClass)) { LocationEditor ed = new LocationEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Concept.class.equals(valueClass)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Program.class.equals(valueClass)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (ProgramWorkflowState.class.equals(valueClass)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (EncounterType.class.equals(valueClass)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Form.class.equals(valueClass)) { FormEditor ed = new FormEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Drug.class.equals(valueClass)) { DrugEditor ed = new DrugEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (PersonAttributeType.class.equals(valueClass)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Cohort.class.equals(valueClass)) { CohortEditor ed = new CohortEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Date.class.equals(valueClass)) { // TODO: this uses the date format from the current // session, which could cause problems if the user // changes it after searching. DateFormat df = Context.getDateFormat(); // new // SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), // Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(valueAsString); value = ed.getValue(); } else if (LogicCriteria.class.equals(valueClass)) { value = Context.getLogicService().parseString(valueAsString); } else { // TODO: Decide whether this is a hack. Currently // setting Object arguments with a String value = valueAsString; } } catch (Exception ex) { log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex); continue; } if (value != null) { if (realPropertyType.isAssignableFrom(valueClass)) { log.debug("setting value of " + sa.getName() + " to " + value); try { pd.getWriteMethod().invoke(pf, value); } catch (Exception ex) { log.error("Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex); continue; } } else if (Collection.class.isAssignableFrom(realPropertyType)) { log.debug(sa.getName() + " is a Collection property"); // if realPropertyType is a collection, add this // value to it (possibly after instantiating) try { Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null); if (collection == null) { // we need to instantiate this collection. // I'm going with the following rules, which // should be rethought: // SortedSet -> TreeSet // Set -> HashSet // Otherwise -> ArrayList if (SortedSet.class.isAssignableFrom(realPropertyType)) { collection = new TreeSet(); log.debug("instantiated a TreeSet"); pd.getWriteMethod().invoke(pf, collection); } else if (Set.class.isAssignableFrom(realPropertyType)) { collection = new HashSet(); log.debug("instantiated a HashSet"); pd.getWriteMethod().invoke(pf, collection); } else { collection = new ArrayList(); log.debug("instantiated an ArrayList"); pd.getWriteMethod().invoke(pf, collection); } } collection.add(value); } catch (Exception ex) { log.error("Error instantiating collection for property " + sa.getName() + " whose class is " + realPropertyType, ex); continue; } } else { log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType + " but is given as " + valueClass); } } } } log.debug("Returning " + pf); return pf; } }
From source file:org.eobjects.analyzer.util.convert.StandardTypeConverter.java
@Override public Object fromString(Class<?> type, String str) { if (ReflectionUtils.isString(type)) { return str; }// w w w . ja v a 2s. com 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 (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)) { return new File(str.replace('\\', File.separatorChar)); } 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:com.amazonaws.hal.client.ConversionUtil.java
private static Object convertFromString(Class<?> clazz, String value) { if (String.class.isAssignableFrom(clazz)) { return value; } else if (int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)) { return new Integer(value); } else if (long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)) { return new Long(value); } else if (short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)) { return new Short(value); } else if (double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)) { return new Double(value); } else if (float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) { return new Float(value); } else if (boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) { return Boolean.valueOf(value); } else if (char.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)) { return value.charAt(0); } else if (byte.class.isAssignableFrom(clazz) || Byte.class.isAssignableFrom(clazz)) { return new Byte(value); } else if (BigDecimal.class.isAssignableFrom(clazz)) { return new BigDecimal(value); } else if (BigInteger.class.isAssignableFrom(clazz)) { return new BigInteger(value); } else if (Date.class.isAssignableFrom(clazz)) { try {/*w w w. j a v a2 s .c o m*/ return new Date(Long.parseLong(value)); } catch (NumberFormatException e) { try { return DatatypeConverter.parseDateTime(value).getTime(); } catch (IllegalArgumentException e1) { throw new RuntimeException("Unexpected date format: " + value + ". We currently parse xsd:datetime and milliseconds."); } } } else if (clazz.isEnum()) { try { //noinspection unchecked return Enum.valueOf((Class<Enum>) clazz, value); } catch (IllegalArgumentException e) { log.error(String.format( "'%s' is not a recognized enum value for %s. Returning default of %s instead.", value, clazz.getName(), clazz.getEnumConstants()[0])); return clazz.getEnumConstants()[0]; } } else { throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName()); } }
From source file:com.evolveum.midpoint.gui.api.util.WebComponentUtil.java
@NotNull public static <T extends Enum> IModel<List<T>> createReadonlyValueModelFromEnum(@NotNull Class<T> type, @NotNull Predicate<T> filter) { return new ReadOnlyValueModel<>( Arrays.stream(type.getEnumConstants()).filter(filter).collect(Collectors.toList())); }
From source file:com.amazonaws.hal.client.ConversionUtil.java
private static Object convertFromNumber(Class<?> clazz, Number value) { if (String.class.isAssignableFrom(clazz)) { return value.toString(); } else if (int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)) { return value.intValue(); } else if (long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)) { return value.longValue(); } else if (short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)) { return value.shortValue(); } else if (double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)) { return value.doubleValue(); } else if (float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) { return value.floatValue(); } else if (boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) { return Boolean.valueOf(value.toString()); } else if (char.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)) { if (value.longValue() <= 255) { return (char) value.longValue(); } else {//from ww w .ja v a 2 s . co m throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName()); } } else if (byte.class.isAssignableFrom(clazz) || Byte.class.isAssignableFrom(clazz)) { return value.byteValue(); } else if (BigDecimal.class.isAssignableFrom(clazz)) { return new BigDecimal(value.toString()); } else if (BigInteger.class.isAssignableFrom(clazz)) { // Necessary because BigInteger(long) is a private method and we need to convert the Number to a long to // prevent the constructor from throwing a NumberFormatException Example: BigInteger(1.2) return new BigInteger(String.valueOf(value.longValue())); } else if (Date.class.isAssignableFrom(clazz)) { return new Date(value.longValue()); } else if (clazz.isEnum()) { try { //noinspection unchecked return Enum.valueOf((Class<Enum>) clazz, value.toString()); } catch (IllegalArgumentException e) { log.error(String.format( "'%s' is not a recognized enum value for %s. Returning default of %s instead.", value, clazz.getName(), clazz.getEnumConstants()[0])); return clazz.getEnumConstants()[0]; } } else { throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName()); } }
From source file:com.evolveum.midpoint.gui.api.util.WebComponentUtil.java
public static <T extends Enum> IModel<List<T>> createReadonlyModelFromEnum(final Class<T> type) { return new AbstractReadOnlyModel<List<T>>() { @Override/*from w ww . j a v a 2 s. c o m*/ public List<T> getObject() { List<T> list = new ArrayList<>(); Collections.addAll(list, type.getEnumConstants()); return list; } }; }
From source file:org.datacleaner.util.convert.StandardTypeConverter.java
@Override public Object fromString(Class<?> type, String str) { if (ReflectionUtils.isString(type)) { return str; }/*w w w .j a v a 2 s . co 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.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 ww.j a va 2 s . c om*/ */ 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:cx.fbn.nevernote.Global.java
public static <E extends Enum<E>> E fromOrdinal(Class<E> enumClass, int ordinal) { E[] enumArray = enumClass.getEnumConstants(); return enumArray[ordinal]; }
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//w ww . j a v a 2 s . com */ 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; }