List of usage examples for java.lang Class getEnumConstants
public T[] getEnumConstants()
From source file:org.cruxframework.crux.tools.schema.DefaultSchemaGenerator.java
/** * /*from w w w . ja v a 2 s . co m*/ * @param out */ @SuppressWarnings("unchecked") private void generateTypesForEnumerations(PrintStream out) { for (String enumType : enumTypes.keySet()) { out.println("<xs:simpleType name=\"" + enumType + "\">"); out.println("<xs:restriction base=\"xs:string\">"); Class<? extends Enum<?>> enumClass = (Class<? extends Enum<?>>) enumTypes.get(enumType); Enum<?>[] enumConstants = enumClass.getEnumConstants(); for (Enum<?> enumConstant : enumConstants) { out.println("<xs:enumeration value=\"" + enumConstant.toString() + "\" />"); } out.println("</xs:restriction>"); out.println("</xs:simpleType>"); } enumTypes.clear(); }
From source file:com.basistech.rosette.apimodel.ModelTest.java
private Object createObjectForType(Class<?> type, Type genericParameterType) throws IllegalAccessException, InstantiationException, InvocationTargetException { Object o = null;/*from ww w . ja v a 2 s.c om*/ 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:com.expressui.core.view.field.FormField.java
private void initializeFieldDefaults() { if (field == null) { return;/*from ww w.ja v a 2 s. c om*/ } 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.github.gekoh.yagen.ddl.TableConfig.java
private void gatherEnumCheckConstraints(final Map<String, String> attr2colName, final String attrPath, Class type) {/*from w w w . j a v a 2s.c o m*/ // HACK: we are using field annotations, need to skip methods otherwise we would have wrong constraints traverseFieldsAndMethods(type, true, false, new GatherFieldOrMethodInfoAction() { @Override public void gatherInfo(AccessibleObject fOm) { String attributeName = getAttributeName(fOm); String attrPathField = attrPath + "." + attributeName; Class attributeType = getAttributeType(fOm); if (fOm.isAnnotationPresent(Embedded.class)) { addAttributeOverrides(attr2colName, attrPathField, fOm); gatherEnumCheckConstraints(attr2colName, attrPathField, attributeType); } else if (attributeType.isEnum()) { String colName = attr2colName.get(attrPathField); if (colName == null) { if (fOm.isAnnotationPresent(Column.class)) { colName = getIdentifierForReference(fOm.getAnnotation(Column.class).name()); } if (StringUtils.isEmpty(colName)) { colName = getIdentifierForReference(attributeName); } } boolean useName = fOm.isAnnotationPresent(Enumerated.class) && fOm.getAnnotation(Enumerated.class).value() == EnumType.STRING; StringBuilder cons = new StringBuilder(); for (Object e : attributeType.getEnumConstants()) { if (cons.length() > 0) { cons.append(", "); } if (useName) { cons.append("'").append(((Enum) e).name()).append("'"); } else { cons.append(((Enum) e).ordinal()); } } columnNameToEnumCheckConstraints.put(colName, cons.toString()); } } }); Class superClass = getEntitySuperclass(type); if (superClass != null) { gatherEnumCheckConstraints(attr2colName, attrPath, superClass); } }
From source file:org.simplx.args.MainArgs.java
/** * Returns a value selected from an enum class. The argument string names * an element of the enum. The string must match one element name in the * enum. An abbreviation of any unique starting string is accepted by * default. For example, if the enum had elements <tt>MIN</tt>, * <tt>AVG</tt>, and <tt>MAX</tt>, the user could use any of <tt>a</tt>, * <tt>av</tt>, or <tt>avg</tt> to match <tt>AVG</tt>. But <tt>m</tt> would * cause an error since it could match either <tt>MIN</tt> or <tt>MAX</tt>, * whose shortest abbreviations are <tt>mi</tt> and <tt>ma</tt>, * respectively.//from w w w. jav a 2 s .co m * <p/> * The string is compared against the enum element names both with and * without any underscore they may have. For example, if {@code GO_HOME} is * an enum member, the command-line argument to match it can be {@code * GO_HOME}, {@code go_home}, {@code GoHome}, or even {@code gOhOmE}. (If * the enum has two elements whose names differ only by the presence of * underscores, the behavior is undefined.) * <p/> * You can turn off abbreviations, requiring only full enum member names, * using {@link #setAbbreviatedEnums(boolean)}. * * @param option The option. * @param defaultValue The enum value to use if the option is not * specified. * @param enumClass The class of the enum to be parsed. * @param doc Usage documentation for the option (@see {@link * #getString(String,String,String...)} getString}). * @param <T> The type of the enum; derived from {@code * defaultValue}. * * @return The value for the option, or {@code defaultValue}. * * @see #setAbbreviatedEnums(boolean) */ public <T extends Enum<T>> T getEnumValue(String option, T defaultValue, Class<T> enumClass, String... doc) { String typeName = enumClass.getSimpleName(); String str = getArgument(option, typeName, doc); if (str == null) return defaultValue; T[] possibles = enumClass.getEnumConstants(); EnumSet<T> matches = EnumSet.noneOf(enumClass); for (T e : possibles) { String name = e.toString(); if (str.equalsIgnoreCase(name)) return e; String stripped = STRIP_NAME_PATTERN.matcher(name).replaceAll(""); if (str.equalsIgnoreCase(stripped)) return e; if (abbreviatedEnums && (abbreviation(str, name) || abbreviation(str, stripped))) { matches.add(e); } } // No exact match, see if it is an abbreviation if (abbreviatedEnums) { if (matches.size() == 0) { throw new CommandLineException(str + " unknown in " + enumClass.getSimpleName()); } if (matches.size() == 1) return matches.iterator().next(); else if (matches.size() > 1) { String msg = "Ambiguous option \"" + str + "\": Could be " + matches; throw new CommandLineException(msg); } } return defaultValue; }
From source file:org.logic2j.core.impl.DefaultTermAdapter.java
/** * Specific conversion of enums//from ww w .j a v a 2 s. c om * @param theTerm The Prolog term * @param theTargetClass The target Java class * @param message * @param <T> * @return */ protected <T extends Enum> T fromEnum(Object theTerm, Class<T> theTargetClass, String message) { if (theTargetClass == Enum.class) { throw new IllegalArgumentException( message + ": converting to any Enum will require a custom TermAdapter, " + this + " cannot guess your intended Enum class"); } // For converting to Enum, we expect that theTerm will match the name() of the target Enum. // We will allow theTerm to be either the exact atom (eg 'VAL'), or // a struct/1 with any functor and the value, (eg my_enum_type_ignored('VAL')). // The reason is for consistency with the cases when the Prolog will return an enum value of a class that // Java cannot pre-determine. In that case user has to override this method in a dedicated TermAdapter, // and lookup the effective enum from the specified functor. final String effectiveEnumName; if (theTerm instanceof String) { effectiveEnumName = theTerm.toString(); } else if (theTerm instanceof Struct) { Struct s = (Struct) theTerm; if (s.getArity() != 1) { throw new IllegalArgumentException( message + ": if a Struct is passed, arity must be 1, was " + s.getArity()); } effectiveEnumName = s.getArg(0).toString(); } else { throw new IllegalArgumentException( message + ": converting to an Enum requires either an atom or a struct of arity=1"); } final Enum[] enumConstants = theTargetClass.getEnumConstants(); for (Enum c : enumConstants) { if (c.name().equals(effectiveEnumName)) { return (T) c; } } throw new IllegalArgumentException(message + ": no such enum value"); }
From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java
@Override public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type fulltype, ArgumentMatches matches) {// www .jav a 2s. co m Class type = makeRawTypeIfNecessary(fulltype); if (source.isFlag()) return true; ArgumentDefinition defaultDefinition = createDefaultArgumentDefinition(source); ArgumentMatchValue value = getArgumentValue(defaultDefinition, matches); Object result; Tags tags = getArgumentTags(matches); // lets go through the types we support try { if (type.isPrimitive()) { Method valueOf = primitiveToWrapperMap.get(type).getMethod("valueOf", String.class); if (value == null) throw new MissingArgumentValueException(createDefaultArgumentDefinition(source)); result = valueOf.invoke(null, value.asString().trim()); } else if (type.isEnum()) { Object[] vals = type.getEnumConstants(); Object defaultEnumeration = null; // as we look at options, record the default option if it exists for (Object val : vals) { if (String.valueOf(val).equalsIgnoreCase(value == null ? null : value.asString())) return val; try { if (type.getField(val.toString()).isAnnotationPresent(EnumerationArgumentDefault.class)) defaultEnumeration = val; } catch (NoSuchFieldException e) { throw new ReviewedStingException( "parsing " + type.toString() + "doesn't contain the field " + val.toString()); } } // if their argument has no value (null), and there's a default, return that default for the enum value if (defaultEnumeration != null && value == null) result = defaultEnumeration; // if their argument has no value and there's no default, throw a missing argument value exception. // TODO: Clean this up so that null values never make it to this point. To fix this, we'll have to clean up the implementation of -U. else if (value == null) throw new MissingArgumentValueException(createDefaultArgumentDefinition(source)); else throw new UnknownEnumeratedValueException(createDefaultArgumentDefinition(source), value.asString()); } else if (type.equals(File.class)) { result = value == null ? null : value.asFile(); } else { Constructor ctor = type.getConstructor(String.class); result = ctor.newInstance(value == null ? null : value.asString()); } } catch (UserException e) { throw e; } catch (InvocationTargetException e) { throw new UserException.CommandLineException(String.format( "Failed to parse value %s for argument %s. This is most commonly caused by providing an incorrect data type (e.g. a double when an int is required)", value, source.field.getName())); } catch (Exception e) { throw new DynamicClassResolutionException(String.class, e); } // TODO FIXME! // WARNING: Side effect! parsingEngine.addTags(result, tags); return result; }
From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java
@SuppressWarnings("unchecked") public <T> T generateRandom(Class<T> clazz, Map<String, Type> itestGenericMap, ITestContext iTestContext) { Object res;// w w w . j ava 2 s . c o m ITestParamState iTestState = iTestContext.getCurrentParam(); if (null != iTestState && null == iTestState.getNames()) { res = iTestConfig.getITestValueConverter().convert(clazz, iTestState.getValue()); } else if (Void.class == clazz || void.class == clazz) { res = null; } else if (String.class == clazz && (null == iTestState || null == iTestState.getNames())) { res = RandomStringUtils.randomAlphanumeric(20); } else if (Long.class == clazz || long.class == clazz) { res = new Long(random.nextLong()); } else if (Integer.class == clazz || int.class == clazz) { res = new Integer(random.nextInt()); } else if (Boolean.class == clazz || boolean.class == clazz) { res = random.nextBoolean() ? Boolean.TRUE : Boolean.FALSE; } else if (Date.class == clazz) { res = new Date(random.nextLong()); } else if (Double.class == clazz || double.class == clazz) { res = random.nextDouble(); } else if (Float.class == clazz || float.class == clazz) { res = random.nextFloat(); } else if (Character.class == clazz || char.class == clazz) { res = RandomStringUtils.random(1).charAt(0); } else if (clazz.isEnum()) { res = clazz.getEnumConstants()[random.nextInt(clazz.getEnumConstants().length)]; } else if (clazz.isArray()) { int size = random.nextInt(RANDOM_MAX - RANDOM_MIN) + RANDOM_MIN; if (null != iTestState && iTestState.getSizeParam() != null) { size = iTestState.getSizeParam(); } Object array = Array.newInstance(clazz.getComponentType(), size); for (int i = 0; i < size; i++) { iTestContext.enter(array, String.valueOf(i)); ITestParamState elementITestState = iTestState == null ? null : iTestState.getElement(String.valueOf(i)); Object value = generateRandom((Type) clazz.getComponentType(), itestGenericMap, iTestContext); Array.set(array, i, value); iTestContext.leave(value); } res = array; } else { res = newInstance(clazz, iTestContext); fillFields(clazz, res, iTestState, Collections.EMPTY_MAP, iTestContext); } return (T) res; }
From source file:org.richfaces.tests.metamer.ftest.MatrixConfigurator.java
private List<? extends Object> getUseParameter(Class<?> testClass, Class<?> parameterType, Use useAnnotation) { List<Object> result = new LinkedList<Object>(); if (useAnnotation.empty()) { result.addAll(Arrays.asList(new Object[] { null })); }/* w w w.j a v a2 s .c o m*/ if (useAnnotation.ints().length > 0) { if (parameterType == int.class || parameterType == Integer.class) { result.addAll(Arrays.asList(ArrayUtils.toObject(useAnnotation.ints()))); } } if (useAnnotation.decimals().length > 0) { if (parameterType == double.class || parameterType == Double.class) { result.addAll(Arrays.asList(ArrayUtils.toObject(useAnnotation.decimals()))); } } if (useAnnotation.strings().length > 0) { if (parameterType == String.class) { result.addAll(Arrays.asList(useAnnotation.strings())); } } if (useAnnotation.booleans().length > 0) { if (parameterType == boolean.class || parameterType == Boolean.class) { result.addAll(Arrays.asList(ArrayUtils.toObject(useAnnotation.booleans()))); } } if (useAnnotation.enumeration()) { if (!parameterType.isEnum()) { throw new IllegalArgumentException(parameterType + "have to be enumeration"); } result.addAll(Arrays.asList(parameterType.getEnumConstants())); } // tries satisfy parameter from fields if (result.isEmpty()) { Object testInstance = getTestInstance(testClass); for (int i = 0; i < useAnnotation.value().length; i++) { boolean satisfied = false; String namePattern = useAnnotation.value()[i]; namePattern = StringUtils.replace(namePattern, "*", ".+"); namePattern = StringUtils.replace(namePattern, "?", "."); for (Field field : getAllFields(testClass)) { Pattern pattern = Pattern.compile(namePattern); if (pattern.matcher(field.getName()).matches()) { boolean isArray = field.getType().isArray(); Class<?> representedType = field.getType(); if (!parameterType.isAssignableFrom(representedType) && isArray) { representedType = field.getType().getComponentType(); } else { isArray = false; } if (parameterType.isAssignableFrom(representedType)) { Object[] assignments = getDeclaredFieldValues(testInstance, field, isArray); for (Object assignment : assignments) { result.add(assignment); } satisfied = true; } else { throw new IllegalStateException( "cannot satisfy parameter with declared field '" + field.getName() + "'"); } } } if (satisfied) { continue; } throw new IllegalStateException( "cannot find the field satysfying injection point with name pattern: " + useAnnotation.value()[i]); } } if (useAnnotation.useNull()) { if (parameterType.isPrimitive()) { throw new IllegalArgumentException("parameterType is primitive, can't use null value"); } if (result.contains(null)) { result.addAll(null); } } return result; }
From source file:org.openmrs.util.OpenmrsUtil.java
/** * Takes a String (e.g. a user-entered one) and parses it into an object of the specified class * /*from w w w . jav a 2 s . c o m*/ * @param string * @param clazz * @return Object of type <code>clazz</code> with the data from <code>string</code> */ @SuppressWarnings("unchecked") public static Object parse(String string, Class clazz) { try { // If there's a valueOf(String) method, just use that (will cover at // least String, Integer, Double, Boolean) Method valueOfMethod = null; try { valueOfMethod = clazz.getMethod("valueOf", String.class); } catch (NoSuchMethodException ex) { } if (valueOfMethod != null) { return valueOfMethod.invoke(null, string); } else if (clazz.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) clazz.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(string)) { return e; } } throw new IllegalArgumentException(string + " is not a legal value of enum class " + clazz); } else if (String.class.equals(clazz)) { return string; } else if (Location.class.equals(clazz)) { try { Integer.parseInt(string); LocationEditor ed = new LocationEditor(); ed.setAsText(string); return ed.getValue(); } catch (NumberFormatException ex) { return Context.getLocationService().getLocation(string); } } else if (Concept.class.equals(clazz)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(string); return ed.getValue(); } else if (Program.class.equals(clazz)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(string); return ed.getValue(); } else if (ProgramWorkflowState.class.equals(clazz)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(string); return ed.getValue(); } else if (EncounterType.class.equals(clazz)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(string); return ed.getValue(); } else if (Form.class.equals(clazz)) { FormEditor ed = new FormEditor(); ed.setAsText(string); return ed.getValue(); } else if (Drug.class.equals(clazz)) { DrugEditor ed = new DrugEditor(); ed.setAsText(string); return ed.getValue(); } else if (PersonAttributeType.class.equals(clazz)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(string); return ed.getValue(); } else if (Cohort.class.equals(clazz)) { CohortEditor ed = new CohortEditor(); ed.setAsText(string); return ed.getValue(); } else if (Date.class.equals(clazz)) { // TODO: this uses the date format from the current session, // which could cause problems if the user changes it after // searching. CustomDateEditor ed = new CustomDateEditor(Context.getDateFormat(), true, 10); ed.setAsText(string); return ed.getValue(); } else if (Object.class.equals(clazz)) { // TODO: Decide whether this is a hack. Currently setting Object // arguments with a String return string; } else { throw new IllegalArgumentException("Don't know how to handle class: " + clazz); } } catch (Exception ex) { log.error("error converting \"" + string + "\" to " + clazz, ex); throw new IllegalArgumentException(ex); } }