List of usage examples for java.lang Enum valueOf
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
From source file:com.cinchapi.concourse.config.PreferencesHandler.java
/** * Get the enum value associated with the given key. If the key doesn't map * to an existing object or the mapped value is not a valid enum, the * defaultValue is returned//from www. j av a 2 s .c o m * * @param key * @param defaultValue * @return the associated enum if key is found, defaultValue * otherwise */ @SuppressWarnings("unchecked") public <T extends Enum<T>> T getEnum(String key, T defaultValue) { String value = getString(key, null); if (value != null) { try { defaultValue = (T) Enum.valueOf(defaultValue.getClass(), value); } catch (IllegalArgumentException e) { // ignore } } return defaultValue; }
From source file:com.tongbanjie.tarzan.rpc.protocol.RpcCommand.java
public CustomHeader decodeCustomHeader(Class<? extends CustomHeader> classHeader) throws RpcCommandException { CustomHeader objectHeader;//from w ww. ja v a 2 s. c om try { objectHeader = classHeader.newInstance(); } catch (InstantiationException e) { return null; } catch (IllegalAccessException e) { return null; } if (MapUtils.isNotEmpty(this.customFields)) { Field[] fields = getClazzFields(classHeader); for (Field field : fields) { String fieldName = field.getName(); Class clazz = field.getType(); if (Modifier.isStatic(field.getModifiers()) || fieldName.startsWith("this")) { continue; } String value = this.customFields.get(fieldName); if (value == null) { continue; } field.setAccessible(true); Object valueParsed; if (clazz.isEnum()) { valueParsed = Enum.valueOf(clazz, value); } else { String type = getCanonicalName(clazz); try { valueParsed = ClassUtils.parseSimpleValue(type, value); } catch (ParseException e) { throw new RpcCommandException("Encode the header failed, the custom field <" + fieldName + "> type <" + getCanonicalName(clazz) + "> parse error:" + e.getMessage()); } } if (valueParsed == null) { throw new RpcCommandException("Encode the header failed, the custom field <" + fieldName + "> type <" + getCanonicalName(clazz) + "> is not supported."); } try { field.set(objectHeader, valueParsed); } catch (IllegalAccessException e) { throw new RpcCommandException( "Encode the header failed, set the value of field < " + fieldName + "> error.", e); } } objectHeader.checkFields(); } return objectHeader; }
From source file:org.mutabilitydetector.cli.CommandLineOptions.java
private void extractReportMode(CommandLine line) { if (line.hasOption("r") || line.hasOption("report")) { String mode = line.getOptionValue("report"); this.reportMode = Enum.valueOf(ReportMode.class, mode.toUpperCase()); } else {//from ww w.j av a 2s .c om this.reportMode = ReportMode.ALL; } }
From source file:cz.cuni.mff.d3s.tools.perfdoc.server.measuring.MeasureRequest.java
/** * Normalize incoming values. The normalizing includes converting to proper * types (e.g. integers will be saved as integers, enums like enums) and * shortening numeric types (e.g. integer value sent in format "0 to 0", * will be converted to integer with value 0). * * @param valuesList the List containing values to normalize. * @param rangeValue the number of the rangeValue. valueList[item] will be * left as it was./*from w w w . j a va2 s . co m*/ */ private Object[] normalize(List<Object> valuesList, int rangeValue) throws ClassNotFoundException, IOException { Object[] normalizedValues = valuesList.toArray(); for (int i = 0; i < valuesList.size(); i++) { //rangeValue shall stay in the incoming format if (i != rangeValue) { Object item = valuesList.get(i); String parameter = getArgName(workload, i); //if it is a number, it must be on it converted if (parameter.equals("int") || parameter.equals("float") || parameter.equals("double")) { if (((String) item).contains(" to ")) { String[] chunks = ((String) item).split(" to "); if (chunks.length == 2 && (chunks[0].equals(chunks[1]))) { switch (parameter) { case "int": normalizedValues[i] = Integer.parseInt(chunks[0]); break; case "float": normalizedValues[i] = Float.parseFloat(chunks[0]); break; case "double": normalizedValues[i] = Double.parseDouble(chunks[0]); break; } } } else { switch (parameter) { case "int": normalizedValues[i] = Integer.parseInt((String) item); break; case "float": normalizedValues[i] = Float.parseFloat((String) item); break; case "double": normalizedValues[i] = Double.parseDouble((String) item); break; } } } else if (!parameter.equals("java.lang.String") && !parameter.equals("String")) { //enum //enum can be of any type, therefore Enum<?>, however this format is not accepted by valueof @SuppressWarnings({ "unchecked", "rawtypes" }) Object pom = Enum.valueOf((Class<? extends Enum>) new ClassParser(parameter).getLoadedClass(), (String) item); normalizedValues[i] = pom; } } } return normalizedValues; }
From source file:io.stallion.users.OAuthEndpoints.java
@POST @Path("/authorize-to-json") @MinRole(Role.CONTACT)//from ww w.j a v a 2s . c om public Map<String, Object> authorize(@BodyParam("grantType") String grantTypeString, @BodyParam("clientId") String fullClientId, @BodyParam("redirectUri") String redirectUri, @BodyParam("scopes") String scopesString, @BodyParam("state") String state) { GrantType grantType = Enum.valueOf(GrantType.class, grantTypeString.toUpperCase()); state = or(state, ""); boolean scoped = true; Set<String> scopes = null; if (scopesString == null) { scoped = false; scopes = set(); } else { scopes = set(or(scopesString, "").split(",")); } OAuthApproval approval = OAuthApprovalController.instance().checkGrantApprovalForUser(grantType, getUser(), fullClientId, scopes, scoped, redirectUri); Map<String, Object> data = map(val("state", state), val("redirect_uri", redirectUri)); if (grantType.equals(GrantType.CODE)) { data.put("code", approval.getCode()); } else if (grantType.equals(GrantType.TOKEN)) { data.put("access_token", approval.getAccessToken()); } return data; }
From source file:com.baidu.bjf.remoting.protobuf.IDLProxyObject.java
/** * @param value/* w w w . ja v a 2 s . c o m*/ * @param object * @param f * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException */ private void setField(Object value, Object object, Field f) { f.setAccessible(true); Object valueToSet = value; try { // check if field type is enum if (Enum.class.isAssignableFrom(f.getType())) { Enum v = Enum.valueOf((Class<Enum>) f.getType(), String.valueOf(value)); { valueToSet = v; } } if (f.getType().getName().equals("java.util.List")) { // Method[] ms = object.getClass().getMethods(); Method method = MethodUtils.findMethod(object.getClass(), "add" + StringUtils.capitalize(f.getName()), new Class[] { value.getClass() }); method.invoke(object, value); } else { f.set(object, valueToSet); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:org.eclipse.smarthome.config.core.internal.ConfigMapper.java
private static Object objectConvert(Object value, Class<?> type) { Object result = value;//from www . j av a 2 s . c o m // Handle the conversion case of BigDecimal to Float,Double,Long,Integer and the respective // primitive types String typeName = type.getSimpleName(); if (value instanceof BigDecimal && !type.equals(BigDecimal.class)) { BigDecimal bdValue = (BigDecimal) value; if (type.equals(Float.class) || typeName.equals("float")) { result = bdValue.floatValue(); } else if (type.equals(Double.class) || typeName.equals("double")) { result = bdValue.doubleValue(); } else if (type.equals(Long.class) || typeName.equals("long")) { result = bdValue.longValue(); } else if (type.equals(Integer.class) || typeName.equals("int")) { result = bdValue.intValue(); } } else // Handle the conversion case of String to Float,Double,Long,Integer,BigDecimal,Boolean and the respective // primitive types if (value instanceof String && !type.equals(String.class)) { String bdValue = (String) value; if (type.equals(Float.class) || typeName.equals("float")) { result = Float.valueOf(bdValue); } else if (type.equals(Double.class) || typeName.equals("double")) { result = Double.valueOf(bdValue); } else if (type.equals(Long.class) || typeName.equals("long")) { result = Long.valueOf(bdValue); } else if (type.equals(BigDecimal.class)) { result = new BigDecimal(bdValue); } else if (type.equals(Integer.class) || typeName.equals("int")) { result = Integer.valueOf(bdValue); } else if (type.equals(Boolean.class) || typeName.equals("boolean")) { result = Boolean.valueOf(bdValue); } else if (type.isEnum()) { @SuppressWarnings({ "rawtypes", "unchecked" }) final Class<? extends Enum> enumType = (Class<? extends Enum>) type; @SuppressWarnings({ "unchecked" }) final Enum<?> enumvalue = Enum.valueOf(enumType, value.toString()); result = enumvalue; } else if (Collection.class.isAssignableFrom(type)) { result = Collections.singletonList(value); } } return result; }
From source file:com.haulmont.cuba.security.entity.EntityLogAttr.java
public String getLocValue(String value) { if (Strings.isNullOrEmpty(value)) return value; String entityName = getLogItem().getEntity(); com.haulmont.chile.core.model.MetaClass metaClass = getClassFromEntityName(entityName); if (metaClass != null) { com.haulmont.chile.core.model.MetaProperty property = metaClass.getProperty(name); if (property != null && property.getRange().isEnum()) { try { Enum caller = Enum.valueOf((Class<Enum>) property.getJavaType(), value); Messages messages = AppBeans.get(Messages.NAME); return messages.getMessage(caller); } catch (IllegalArgumentException ignored) { }/* w w w . j a va2 s .c o m*/ } } if (!StringUtils.isBlank(messagesPack)) { Messages messages = AppBeans.get(Messages.NAME); return messages.getMessage(messagesPack, value); } else { return value; } }
From source file:org.openmrs.module.webservices.rest.web.ConversionUtil.java
/** * Converts the given object to the given type * /*from w ww .j av a 2s .com*/ * @param object * @param toType a simple class or generic type * @return * @throws ConversionException * @should convert strings to locales * @should convert strings to enum values * @should convert to an array * @should convert to a class */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Object convert(Object object, Type toType) throws ConversionException { if (object == null) return object; Class<?> toClass = toType instanceof Class ? ((Class<?>) toType) : (Class<?>) (((ParameterizedType) toType).getRawType()); // if we're trying to convert _to_ a collection, handle it as a special case if (Collection.class.isAssignableFrom(toClass) || toClass.isArray()) { if (!(object instanceof Collection)) throw new ConversionException("Can only convert a Collection to a Collection/Array. Not " + object.getClass() + " to " + toType, null); if (toClass.isArray()) { Class<?> targetElementType = toClass.getComponentType(); Collection input = (Collection) object; Object ret = Array.newInstance(targetElementType, input.size()); int i = 0; for (Object element : (Collection) object) { Array.set(ret, i, convert(element, targetElementType)); ++i; } return ret; } Collection ret = null; if (SortedSet.class.isAssignableFrom(toClass)) { ret = new TreeSet(); } else if (Set.class.isAssignableFrom(toClass)) { ret = new HashSet(); } else if (List.class.isAssignableFrom(toClass)) { ret = new ArrayList(); } else { throw new ConversionException("Don't know how to handle collection class: " + toClass, null); } if (toType instanceof ParameterizedType) { // if we have generic type information for the target collection, we can use it to do conversion ParameterizedType toParameterizedType = (ParameterizedType) toType; Type targetElementType = toParameterizedType.getActualTypeArguments()[0]; for (Object element : (Collection) object) ret.add(convert(element, targetElementType)); } else { // otherwise we must just add all items in a non-type-safe manner ret.addAll((Collection) object); } return ret; } // otherwise we're converting _to_ a non-collection type if (toClass.isAssignableFrom(object.getClass())) return object; // Numbers with a decimal are always assumed to be Double, so convert to Float, if necessary if (toClass.isAssignableFrom(Float.class) && object instanceof Double) { return new Float((Double) object); } if (object instanceof String) { String string = (String) object; Converter<?> converter = getConverter(toClass); if (converter != null) return converter.getByUniqueId(string); if (toClass.isAssignableFrom(Date.class)) { ParseException pex = null; String[] supportedFormats = { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS", "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd" }; for (int i = 0; i < supportedFormats.length; i++) { try { Date date = new SimpleDateFormat(supportedFormats[i]).parse(string); return date; } catch (ParseException ex) { pex = ex; } } throw new ConversionException( "Error converting date - correct format (ISO8601 Long): yyyy-MM-dd'T'HH:mm:ss.SSSZ", pex); } else if (toClass.isAssignableFrom(Locale.class)) { return LocaleUtility.fromSpecification(object.toString()); } else if (toClass.isEnum()) { return Enum.valueOf((Class<? extends Enum>) toClass, object.toString()); } else if (toClass.isAssignableFrom(Class.class)) { try { return Context.loadClass((String) object); } catch (ClassNotFoundException e) { throw new ConversionException("Could not convert from " + object.getClass() + " to " + toType, e); } } // look for a static valueOf(String) method (e.g. Double, Integer, Boolean) try { Method method = toClass.getMethod("valueOf", String.class); if (Modifier.isStatic(method.getModifiers()) && toClass.isAssignableFrom(method.getReturnType())) { return method.invoke(null, string); } } catch (Exception ex) { } } else if (object instanceof Map) { return convertMap((Map<String, ?>) object, toClass); } if (toClass.isAssignableFrom(Double.class) && object instanceof Number) { return ((Number) object).doubleValue(); } else if (toClass.isAssignableFrom(Integer.class) && object instanceof Number) { return ((Number) object).intValue(); } throw new ConversionException("Don't know how to convert from " + object.getClass() + " to " + toType, null); }