List of usage examples for java.lang Class getEnumConstants
public T[] getEnumConstants()
From source file:com.heliosphere.demeter.base.resource.bundle.ResourceBundleManager.java
/** * Retrieves a message from a resource bundle from its key. * <p>//from w w w . j a va 2 s . c om * @param key Resource key to retrieve. * @param parameters Parameters to inject while formatting the message. * @return The formatted message. */ @SuppressWarnings("nls") private static final String retrieve(final Enum<? extends IBundle> key, final Object... parameters) { if (!isInitialized) { initialize(); } final Class<? extends IBundle> bundleClass = key.getDeclaringClass(); if (BUNDLES.containsKey(bundleClass)) { try { return MessageFormat.format(BUNDLES.get(bundleClass).getString(((IBundle) key).getKey()), parameters); } catch (MissingResourceException e) { throw new ResourceBundleException(BundleDemeterBase.ResourceBundleInvalidKey, bundleClass.getSimpleName(), key.name(), bundleClass.getEnumConstants()[0].getKey(), getLocale(), e); } } return "Resource bundle key cannot be found [bundle=" + bundleClass.getName() + ", key=" + key.name() + "]"; }
From source file:Season.java
public RandomEnum(Class<E> token) { values = token.getEnumConstants(); }
From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java
private static Set<String> mapValueField(List<APIValueFieldModel> fieldModels, Field fields[], boolean onlyComsumeField) { Set<String> fieldNamesCaptured = new HashSet<>(); for (Field field : fields) { boolean capture = true; if (onlyComsumeField) { ConsumeField consumeField = (ConsumeField) field.getAnnotation(ConsumeField.class); if (consumeField == null) { capture = false;// ww w .j a va 2s . c o m } } if (capture) { APIValueFieldModel fieldModel = new APIValueFieldModel(); fieldModel.setFieldName(field.getName()); fieldNamesCaptured.add(field.getName()); fieldModel.setType(field.getType().getSimpleName()); DataType dataType = (DataType) field.getAnnotation(DataType.class); if (dataType != null) { String typeName = dataType.value().getSimpleName(); if (StringUtils.isNotBlank(dataType.actualClassName())) { typeName = dataType.actualClassName(); } fieldModel.setType(fieldModel.getType() + ": " + typeName); } NotNull requiredParam = (NotNull) field.getAnnotation(NotNull.class); if (requiredParam != null) { fieldModel.setRequired(true); } StringBuilder validation = new StringBuilder(); ParamTypeDescription description = (ParamTypeDescription) field .getAnnotation(ParamTypeDescription.class); if (description != null) { validation.append(description.value()).append("<br>"); } APIDescription aPIDescription = (APIDescription) field.getAnnotation(APIDescription.class); if (aPIDescription != null) { fieldModel.setDescription(aPIDescription.value()); } if ("Date".equals(field.getType().getSimpleName())) { validation.append("Timestamp (milliseconds since UNIX Epoch<br>"); } if ("boolean".equalsIgnoreCase(field.getType().getSimpleName())) { validation.append("T | F"); } ValidationRequirement validationRequirement = (ValidationRequirement) field .getAnnotation(ValidationRequirement.class); if (validationRequirement != null) { validation.append(validationRequirement.value()).append("<br>"); } PK pk = (PK) field.getAnnotation(PK.class); if (pk != null) { if (pk.generated()) { validation.append("Primary Key (Generated)").append("<br>"); } else { validation.append("Primary Key").append("<br>"); } } Min min = (Min) field.getAnnotation(Min.class); if (min != null) { validation.append("Min Value: ").append(min.value()).append("<br>"); } Max max = (Max) field.getAnnotation(Max.class); if (max != null) { validation.append("Max Value: ").append(max.value()).append("<br>"); } Size size = (Size) field.getAnnotation(Size.class); if (size != null) { validation.append("Min Length: ").append(size.min()).append(" Max Length: ").append(size.max()) .append("<br>"); } Pattern pattern = (Pattern) field.getAnnotation(Pattern.class); if (pattern != null) { validation.append("Needs to Match: ").append(pattern.regexp()).append("<br>"); } ValidValueType validValueType = (ValidValueType) field.getAnnotation(ValidValueType.class); if (validValueType != null) { validation.append("Set of valid values: ").append(Arrays.toString(validValueType.value())) .append("<br>"); if (validValueType.lookupClass().length > 0) { validation.append("See Lookup table(s): <br>"); for (Class lookupClass : validValueType.lookupClass()) { validation.append(lookupClass.getSimpleName()); } } if (validValueType.enumClass().length > 0) { validation.append("See Enum List: <br>"); for (Class enumClass : validValueType.enumClass()) { validation.append(enumClass.getSimpleName()); if (enumClass.isEnum()) { validation.append(" (").append(Arrays.toString(enumClass.getEnumConstants())) .append(") "); } } } } fieldModel.setValidation(validation.toString()); fieldModels.add(fieldModel); } } return fieldNamesCaptured; }
From source file:org.openlmis.fulfillment.testutils.DtoGenerator.java
private static Object generateBaseValue(Class<?> propertyType) { if (String.class.isAssignableFrom(propertyType)) { return randomAlphanumeric(10); }//ww w .j a va2 s.c om if (Number.class.isAssignableFrom(propertyType)) { return parseNumber(String.valueOf(RANDOM.nextInt(1000)), (Class<Number>) propertyType); } if (UUID.class.isAssignableFrom(propertyType)) { return randomUUID(); } if (Boolean.class.isAssignableFrom(propertyType) || boolean.class.isAssignableFrom(propertyType)) { return true; } if (LocalDate.class.isAssignableFrom(propertyType)) { return LocalDate.now(); } if (ZonedDateTime.class.isAssignableFrom(propertyType)) { return ZonedDateTime.now(); } if (Enum.class.isAssignableFrom(propertyType)) { int idx = RANDOM.nextInt(propertyType.getEnumConstants().length); return propertyType.getEnumConstants()[idx]; } return null; }
From source file:com.doitnext.jsonschema.generator.SchemaGen.java
private static boolean handleObjectType(Class<?> classz, StringBuilder sb, JsonSchemaProperty propertyDescriptor, Map<String, String> declarations, boolean topLevel, String uriPrefix) {/*from ww w .ja va 2 s .c o m*/ boolean result = false; String prepend = ""; Map<String, Boolean> flags = new HashMap<String, Boolean>(); flags.put("hasTitle", false); flags.put("hasDescription", false); flags.put("hasType", false); flags.put("hasEnum", false); if (classz.isEnum()) { sb.append("\"type\":\"string\","); sb.append("\"enum\":["); for (Enum<?> c : (Enum<?>[]) classz.getEnumConstants()) { sb.append("\""); sb.append(c.toString()); sb.append("\", "); } sb.append("]"); flags.put("hasType", true); flags.put("hasEnum", true); result = true; } if (!flags.get("hasType")) { sb.append(prepend); sb.append("\"type\":\"object\""); prepend = ", "; flags.put("hasType", true); result = true; } if (handlePropertyDescriptor(sb, propertyDescriptor, flags, prepend, result, uriPrefix)) { result = true; } JsonSchemaClass annotation = classz.getAnnotation(JsonSchemaClass.class); if (annotation != null) { if (result == true) prepend = ", "; if (!StringUtils.isEmpty(annotation.id())) { sb.append(prepend); sb.append("\"id\":\"" + annotation.id() + "\""); prepend = ", "; } if (!flags.get("hasTitle") && !StringUtils.isEmpty(annotation.title())) { sb.append(prepend); sb.append("\"title\":\"" + annotation.title() + "\""); prepend = ", "; } if (!flags.get("hasDescription") && !StringUtils.isEmpty(annotation.description())) { sb.append(prepend); sb.append("\"description\":\"" + annotation.description() + "\""); prepend = ", "; } result = true; } sb.append(prepend); sb.append("\"properties\":"); handleProperties(classz, sb, declarations, uriPrefix); prepend = ", "; return result; }
From source file:org.apache.camel.maven.DocumentGeneratorMojo.java
public static List<EndpointInfo> getEndpoints(Class<? extends ApiMethod> apiMethod, ApiMethodHelper<?> helper, Class<?> endpointConfig) { // get list of valid options final Set<String> validOptions = new HashSet<String>(); for (Field field : endpointConfig.getDeclaredFields()) { validOptions.add(field.getName()); }/*from w ww.j a v a 2 s.c o m*/ // create method name map final Map<String, List<ApiMethod>> methodMap = new TreeMap<String, List<ApiMethod>>(); for (ApiMethod method : apiMethod.getEnumConstants()) { String methodName = method.getName(); List<ApiMethod> apiMethods = methodMap.get(methodName); if (apiMethods == null) { apiMethods = new ArrayList<ApiMethod>(); methodMap.put(methodName, apiMethods); } apiMethods.add(method); } // create method name to alias name map final Map<String, Set<String>> aliasMap = new TreeMap<String, Set<String>>(); final Map<String, Set<String>> aliasToMethodMap = helper.getAliases(); for (Map.Entry<String, Set<String>> entry : aliasToMethodMap.entrySet()) { final String alias = entry.getKey(); for (String method : entry.getValue()) { Set<String> aliases = aliasMap.get(method); if (aliases == null) { aliases = new TreeSet<String>(); aliasMap.put(method, aliases); } aliases.add(alias); } } // create options map and return type map final Map<String, Set<String>> optionMap = new TreeMap<String, Set<String>>(); final Map<String, Set<String>> returnType = new TreeMap<String, Set<String>>(); for (Map.Entry<String, List<ApiMethod>> entry : methodMap.entrySet()) { final String name = entry.getKey(); final List<ApiMethod> apiMethods = entry.getValue(); // count the number of times, every valid option shows up across methods // and also collect return types final Map<String, Integer> optionCount = new TreeMap<String, Integer>(); final TreeSet<String> resultTypes = new TreeSet<String>(); returnType.put(name, resultTypes); for (ApiMethod method : apiMethods) { for (String arg : method.getArgNames()) { if (validOptions.contains(arg)) { Integer count = optionCount.get(arg); if (count == null) { count = 1; } else { count += 1; } optionCount.put(arg, count); } } // wrap primitive result types Class<?> resultType = method.getResultType(); if (resultType.isPrimitive()) { resultType = ClassUtils.primitiveToWrapper(resultType); } resultTypes.add(getCanonicalName(resultType)); } // collect method options final TreeSet<String> options = new TreeSet<String>(); optionMap.put(name, options); final Set<String> mandatory = new TreeSet<String>(); // generate optional and mandatory lists for overloaded methods int nMethods = apiMethods.size(); for (ApiMethod method : apiMethods) { final Set<String> optional = new TreeSet<String>(); for (String arg : method.getArgNames()) { if (validOptions.contains(arg)) { final Integer count = optionCount.get(arg); if (count == nMethods) { mandatory.add(arg); } else { optional.add(arg); } } } if (!optional.isEmpty()) { options.add(optional.toString()); } } if (!mandatory.isEmpty()) { // strip [] from mandatory options final String mandatoryOptions = mandatory.toString(); options.add(mandatoryOptions.substring(1, mandatoryOptions.length() - 1)); } } // create endpoint data final List<EndpointInfo> infos = new ArrayList<EndpointInfo>(); for (Map.Entry<String, List<ApiMethod>> methodEntry : methodMap.entrySet()) { final String endpoint = methodEntry.getKey(); // set endpoint name EndpointInfo info = new EndpointInfo(); info.endpoint = endpoint; info.aliases = convertSetToString(aliasMap.get(endpoint)); info.options = convertSetToString(optionMap.get(endpoint)); final Set<String> resultTypes = returnType.get(endpoint); // get rid of void results resultTypes.remove("void"); info.resultTypes = convertSetToString(resultTypes); infos.add(info); } return infos; }
From source file:org.jaxygen.converters.properties.EnumConverter.java
@SuppressWarnings("unchecked") @Override// w ww.ja va2 s . c o m public Object convert(Class type, Object value) { Object rc = null; Object enums[] = type.getEnumConstants(); for (Object o : enums) { if (o.toString().equals(value)) rc = o; } return rc; }
From source file:org.waveprotocol.box.server.util.ClientFlagsUtil.java
/** * Checks parameter for validity.// w ww .j a v a 2 s. co m * * @param name parameter name in CamelCase format * @param value parameter value * @throws IllegalArgumentException if the parameter is invalid */ public static void checkParameter(String name, String value) throws IllegalArgumentException { String shortName = FlagConstants.getShortName(name); if (shortName == null) { throw new IllegalArgumentException(String.format("Unknown parameter: %s!", name)); } Method getter; try { getter = ClientFlags.class.getMethod(name); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(String.format("Unknown method %s() in ClientFlags class!", name)); } Class<?> retType = getter.getReturnType(); boolean correct = true; if (retType.equals(String.class)) { correct = ValueUtils.isEmbracedWith(value, "\""); } else if (retType.equals(int.class)) { try { Integer.parseInt(value); } catch (NumberFormatException e) { correct = false; } } else if (retType.equals(boolean.class)) { correct = value.equals("true") || value.equals("false"); } else if (retType.equals(double.class)) { try { Double.parseDouble(value); } catch (NumberFormatException e) { correct = false; } } else if (retType.isEnum()) { // check enum String enumValues = ValueUtils.stripFrom(Arrays.toString(retType.getEnumConstants()), "[", "]"); correct = false; String upperValue = value.toUpperCase(); for (String enumValue : enumValues.split(",")) { if (upperValue.equals(enumValue.trim())) { correct = true; break; } } } else { throw new IllegalArgumentException( String.format("Unknown parameter type (%s) for parameter %s", retType, name)); } if (!correct) { throw new IllegalArgumentException( String.format("Invalid parameter: name=%s, type=%s, value=%s", name, retType, value)); } }
From source file:org.openmrs.module.htmlwidgets.web.handler.EnumHandler.java
/** * @see CodedHandler#populateOptions(WidgetConfig, CodedWidget) */// ww w . ja v a 2s . c o m @Override public void populateOptions(WidgetConfig config, CodedWidget widget) { Class<?> c = config.getType(); Object[] enums = c.getEnumConstants(); if (enums != null) { for (Object o : enums) { widget.addOption(new Option(o.toString(), o.toString(), null, o), config); } } }
From source file:com.tacitknowledge.noexcuses.EnumTypeHandler.java
@Override @SuppressWarnings("unchecked") public <T> T createInstance(Class<T> type) { T instance = null;//from w w w.j a v a 2 s . com if (type.isEnum()) { Object[] enums = type.getEnumConstants(); if (ArrayUtils.isNotEmpty(enums)) { instance = (T) enums[0]; } } return instance; }