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:gov.nih.nci.system.web.struts.action.UpdateAction.java
public Object convertValue(Class klass, Object value) throws Exception { String fieldType = klass.getName(); Object convertedValue = null; try {/* w w w . j a v a2s . c om*/ if (fieldType.equals("java.lang.Long")) { convertedValue = new Long((String) value); } else if (fieldType.equals("java.lang.Integer")) { convertedValue = new Integer((String) value); } else if (fieldType.equals("java.lang.String")) { convertedValue = value; } else if (fieldType.equals("java.lang.Float")) { convertedValue = new Float((String) value); } else if (fieldType.equals("java.lang.Double")) { convertedValue = new Double((String) value); } else if (fieldType.equals("java.lang.Boolean")) { convertedValue = new Boolean((String) value); } else if (fieldType.equals("java.util.Date")) { SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy"); convertedValue = format.parse((String) value); } else if (fieldType.equals("java.net.URI")) { convertedValue = new URI((String) value); } else if (fieldType.equals("java.lang.Character")) { convertedValue = new Character(((String) value).charAt(0)); } else if (klass.isEnum()) { Class enumKlass = Class.forName(fieldType); convertedValue = Enum.valueOf(enumKlass, (String) value); } else { throw new Exception("type mismatch - " + fieldType); } } catch (NumberFormatException e) { e.printStackTrace(); throw new Exception(e.getMessage()); } catch (Exception ex) { log.error("ERROR : " + ex.getMessage()); throw ex; } return convertedValue; }
From source file:net.sourceforge.vulcan.spring.SpringPluginManager.java
@Override @SuppressWarnings("unchecked") public Enum<?> createEnum(String id, String className, String enumName) throws ClassNotFoundException, PluginNotFoundException { final PluginState state = findPluginState(id); @SuppressWarnings("rawtypes") Class c = state.classLoader.loadClass(className); return Enum.valueOf(c, enumName); }
From source file:com.bstek.dorado.data.JsonUtils.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static Object internalToJavaEntity(ObjectNode objectNode, EntityDataType dataType, Class<?> targetType, boolean proxy, JsonConvertContext context) throws Exception { if (objectNode == null || objectNode.isNull()) { return null; }/*from ww w . j a va 2 s .c om*/ Class<?> creationType = null; if (dataType != null && !(dataType instanceof CustomEntityDataType)) { creationType = dataType.getCreationType(); if (creationType == null) { creationType = dataType.getMatchType(); } } if (creationType == null) { creationType = Record.class; } Object result; if (EnhanceableEntity.class.isAssignableFrom(creationType)) { EnhanceableEntity ee = (EnhanceableEntity) creationType.newInstance(); ee.setEntityEnhancer(new EnhanceableMapEntityEnhancer(dataType)); result = ee; } else { MethodInterceptor[] mis = getMethodInterceptorFactory().createInterceptors(dataType, creationType, null); result = ProxyBeanUtils.createBean(creationType, mis); } EntityWrapper entity = EntityWrapper.create(result); if (proxy) { entity.setStateLocked(true); } Iterator<Entry<String, JsonNode>> fields = objectNode.getFields(); while (fields.hasNext()) { Entry<String, JsonNode> field = fields.next(); String property = field.getKey(); if (property.charAt(0) == SYSTEM_PROPERTY_PREFIX) { continue; } Object value = null; JsonNode jsonNode = field.getValue(); if (jsonNode != null && !jsonNode.isNull()) { Class<?> type = null; PropertyDef propertyDef = null; DataType propertyDataType = null; type = entity.getPropertyType(property); if (dataType != null) { propertyDef = dataType.getPropertyDef(property); if (propertyDef != null) { propertyDataType = propertyDef.getDataType(); } } if (jsonNode instanceof ContainerNode) { value = toJavaObject(jsonNode, propertyDataType, type, proxy, context); } else if (jsonNode instanceof ValueNode) { value = toJavaValue((ValueNode) jsonNode, propertyDataType, null); } else { throw new IllegalArgumentException("Value type mismatch. expect [JSON Value]."); } if (type != null) { if (!type.isInstance(value)) { if (value instanceof String && type.isEnum()) { if (StringUtils.isNotBlank((String) value)) { value = Enum.valueOf((Class<? extends Enum>) type, (String) value); } } else { propertyDataType = getDataTypeManager().getDataType(type); if (propertyDataType != null) { value = propertyDataType.fromObject(value); } } } } else { if (value instanceof String) { // ? String str = (String) value; if (str.length() == DEFAULT_DATE_PATTERN_LEN && DEFAULT_DATE_PATTERN.matcher(str).matches()) { value = DateUtils.parse(com.bstek.dorado.core.Constants.ISO_DATETIME_FORMAT1, str); } } } } entity.set(property, value); } if (proxy) { entity.setStateLocked(false); int state = JsonUtils.getInt(objectNode, STATE_PROPERTY); if (state > 0) { entity.setState(EntityState.fromInt(state)); } int entityId = JsonUtils.getInt(objectNode, ENTITY_ID_PROPERTY); if (entityId > 0) { entity.setEntityId(entityId); } ObjectNode jsonOldValues = (ObjectNode) objectNode.get(OLD_DATA_PROPERTY); if (jsonOldValues != null) { Map<String, Object> oldValues = entity.getOldValues(true); Iterator<Entry<String, JsonNode>> oldFields = jsonOldValues.getFields(); while (oldFields.hasNext()) { Entry<String, JsonNode> entry = oldFields.next(); String property = entry.getKey(); PropertyDef propertyDef = null; DataType propertyDataType = null; Object value; if (dataType != null) { propertyDef = dataType.getPropertyDef(property); if (propertyDef != null) { propertyDataType = propertyDef.getDataType(); } } if (dataType != null) { propertyDef = dataType.getPropertyDef(property); if (propertyDef != null) { propertyDataType = propertyDef.getDataType(); } } JsonNode jsonNode = entry.getValue(); if (jsonNode instanceof ContainerNode) { Class<?> type = entity.getPropertyType(property); value = toJavaObject(jsonNode, propertyDataType, type, proxy, context); } else if (jsonNode instanceof ValueNode) { value = toJavaValue((ValueNode) jsonNode, propertyDataType, null); } else { throw new IllegalArgumentException("Value type mismatch. expect [JSON Value]."); } oldValues.put(property, value); } } } if (targetType != null && !targetType.isInstance(result)) { throw new IllegalArgumentException("Java type mismatch. expect [" + targetType + "]."); } if (context != null && context.getEntityCollection() != null) { context.getEntityCollection().add(result); } return result; }
From source file:com.haulmont.cuba.core.sys.SecurityImpl.java
@SuppressWarnings("unused") protected Object parseValue(Class<?> clazz, String string) { try {/*from www . j a v a2 s.com*/ if (Entity.class.isAssignableFrom(clazz)) { Object entity = metadata.create(clazz); if (entity instanceof BaseIntegerIdEntity) { ((BaseIntegerIdEntity) entity).setId(Integer.valueOf(string)); } else if (entity instanceof BaseLongIdEntity) { ((BaseLongIdEntity) entity).setId(Long.valueOf(string)); } else if (entity instanceof BaseStringIdEntity) { ((BaseStringIdEntity) entity).setId(string); } else if (entity instanceof BaseIdentityIdEntity) { ((BaseIdentityIdEntity) entity).setId(IdProxy.of(Long.valueOf(string))); } else if (entity instanceof BaseIntIdentityIdEntity) { ((BaseIntIdentityIdEntity) entity).setId(IdProxy.of(Integer.valueOf(string))); } else if (entity instanceof HasUuid) { ((HasUuid) entity).setUuid(UUID.fromString(string)); } return entity; } else if (EnumClass.class.isAssignableFrom(clazz)) { //noinspection unchecked Enum parsedEnum = Enum.valueOf((Class<Enum>) clazz, string); return parsedEnum; } else { Datatype datatype = Datatypes.get(clazz); return datatype != null ? datatype.parse(string) : string; } } catch (ParseException | IllegalArgumentException e) { log.error("Could not parse a value in constraint. Class [{}], value [{}].", clazz, string, e); throw new RowLevelSecurityException(format( "Could not parse a value in constraint. Class [%s], value [%s]. " + "See the log for details.", clazz, string), null); } }
From source file:com.haulmont.cuba.gui.components.filter.Param.java
protected Object parseSingleValue(String text) { Object value;/*from w w w . j av a 2 s . c o m*/ switch (type) { case ENTITY: value = loadEntity(text); break; case ENUM: value = Enum.valueOf(javaClass, text); break; case RUNTIME_ENUM: case DATATYPE: case UNARY: Datatype datatype = Datatypes.getNN(javaClass); //hardcode for compatibility with old datatypes if (datatype.getJavaClass().equals(Date.class)) { try { value = datatype.parse(text); } catch (ParseException e) { try { value = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(text); } catch (ParseException exception) { throw new RuntimeException("Can not parse date from string " + text, e); } } } else { try { value = datatype.parse(text); } catch (ParseException e) { throw new RuntimeException("Parse exception for string " + text, e); } } break; default: throw new IllegalStateException("Param type unknown"); } return value; }
From source file:com.l2jfree.config.L2Properties.java
public <T extends Enum<T>> T getEnum(String name, Class<T> enumClass, String deflt) { String val = getProperty(name, deflt); if (val == null) throw new IllegalArgumentException( "Enum value of type " + enumClass.getName() + " required, but not specified"); try {// w w w.j a v a2s .c o m return Enum.valueOf(enumClass, String.valueOf(val)); } catch (Exception e) { throw new IllegalArgumentException( "Enum value of type " + enumClass.getName() + "required, but found: " + val); } }
From source file:org.olap4j.test.TestContext.java
/** * Factory method for the {@link Tester} * object which determines which driver to test. * * @param testContext Test context/*from w ww .j a v a 2 s. c o m*/ * @param testProperties Properties that define the properties of the tester * @return a new Tester */ private static Tester createTester(TestContext testContext, Properties testProperties) { String helperClassName = testProperties.getProperty(Property.HELPER_CLASS_NAME.path); if (helperClassName == null) { helperClassName = "org.olap4j.XmlaTester"; if (!testProperties.containsKey(TestContext.Property.XMLA_CATALOG_URL.path)) { testProperties.setProperty(TestContext.Property.XMLA_CATALOG_URL.path, "dummy_xmla_catalog_url"); } } Tester tester; try { Class<?> clazz = Class.forName(helperClassName); final Constructor<?> constructor = clazz.getConstructor(TestContext.class); tester = (Tester) constructor.newInstance(testContext); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } // Apply a wrapper, if the "org.olap4j.test.wrapper" property is // specified. String wrapperName = testProperties.getProperty(Property.WRAPPER.path); Wrapper wrapper; if (wrapperName == null || wrapperName.equals("")) { wrapper = Wrapper.NONE; } else { try { wrapper = Enum.valueOf(Wrapper.class, wrapperName); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unknown wrapper value '" + wrapperName + "'"); } } switch (wrapper) { case NONE: break; case DBCP: final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(tester.getDriverClassName()); dataSource.setUrl(tester.getURL()); // need access to underlying connection so that we can call // olap4j-specific methods dataSource.setAccessToUnderlyingConnectionAllowed(true); tester = new DelegatingTester(tester) { public Connection createConnection() throws SQLException { return dataSource.getConnection(); } public Wrapper getWrapper() { return Wrapper.DBCP; } }; break; } return tester; }
From source file:org.openehr.build.RMObjectBuilder.java
/** * Construct an instance of RM class of given name and values. <p/> If the * input is a string, and the required attribute is some other types * (integer, double etc), it will be converted into right type. if there is * any error during conversion, AttributeFormatException will be thrown. * /* ww w .j a va2 s .c o m*/ * @param rmClassName * @param valueMap * @return created instance * @throws RMObjectBuildingException */ public RMObject construct(String rmClassName, Map<String, Object> valueMap) throws RMObjectBuildingException { Class rmClass = retrieveRMType(rmClassName); // replace underscore separated names with camel case Map<String, Object> filteredMap = new HashMap<String, Object>(); for (String name : valueMap.keySet()) { filteredMap.put(toCamelCase(name), valueMap.get(name)); } Constructor constructor = fullConstructor(rmClass); Map<String, Class> typeMap = attributeType(rmClass); Map<String, Integer> indexMap = attributeIndex(rmClass); Map<String, Attribute> attributeMap = attributeMap(rmClass); Object[] valueArray = new Object[indexMap.size()]; for (String name : typeMap.keySet()) { Object value = filteredMap.get(name); if (!typeMap.containsKey(name) || !attributeMap.containsKey(name)) { throw new RMObjectBuildingException("unknown attribute " + name); } Class type = typeMap.get(name); Integer index = indexMap.get(name); Attribute attribute = attributeMap.get(name); if (index == null || type == null) { throw new RMObjectBuildingException("unknown attribute \"" + name + "\""); } // system supplied value if (attribute.system()) { SystemValue sysvalue = SystemValue.fromId(name); if (sysvalue == null) { throw new RMObjectBuildingException("unknonw system value" + "\"" + name + "\""); } value = systemValues.get(sysvalue); if (value == null) { throw new AttributeMissingException("missing value for " + "system attribute \"" + name + "\" in class: " + rmClass + ", with valueMap: " + valueMap); } } // check required attributes if (value == null && attribute.required()) { log.info(attribute); throw new AttributeMissingException("missing value for " + "required attribute \"" + name + "\" of type " + type + " while constructing " + rmClass + " with valueMap: " + valueMap); } // enum else if (type.isEnum() && !value.getClass().isEnum()) { // OG added if (type.equals(ProportionKind.class)) value = ProportionKind.fromValue(Integer.parseInt(value.toString())); else value = Enum.valueOf(type, value.toString()); } // in case of null, create a default value else if (value == null) { value = defaultValue(type); } // in case of string value, convert to right type if necessary else if (value instanceof String) { String str = (String) value; try { // for DvCount if (type.equals(int.class)) { value = Integer.parseInt(str); // for DvQuantity } else if (type.equals(double.class)) { value = Double.parseDouble(str); // for DvProportion.precision } else if (type.equals(Integer.class)) { value = new Integer(str); } } catch (NumberFormatException e) { throw new AttributeFormatException( "wrong format of " + "attribute " + name + ", expect " + type); } // deal with mismatch between array and list } else if (type.isAssignableFrom(List.class) && value.getClass().isArray()) { Object[] array = (Object[]) value; List list = new ArrayList(); for (Object o : array) { list.add(o); } value = list; // deal with mismatch between array and set } else if (type.isAssignableFrom(Set.class) && value.getClass().isArray()) { Object[] array = (Object[]) value; Set set = new HashSet(); for (Object o : array) { set.add(o); } value = set; } // check type else if (value != null && !type.isPrimitive()) { try { type.cast(value); } catch (ClassCastException e) { throw new RMObjectBuildingException("Failed to construct: " + rmClassName + ", value for attribute '" + name + "' has wrong type, expected \"" + type + "\", but got \"" + value.getClass() + "\""); } } valueArray[index] = value; } Object ret = null; try { // OG added hack if (rmClassName.equalsIgnoreCase("DVCOUNT")) { log.debug("Fixing DVCOUNT..."); for (int i = 0; i < valueArray.length; i++) { Object value = valueArray[i]; if (value != null && value.getClass().equals(Float.class)) valueArray[i] = Double.parseDouble(value.toString()); else if (value != null && value.getClass().equals(Long.class)) valueArray[i] = Integer.parseInt(value.toString()); } } ret = constructor.newInstance(valueArray); } catch (Exception e) { if (log.isDebugEnabled()) { e.printStackTrace(); } log.debug("failed in constructor.newInstance()", e); if (stringParsingTypes.contains(rmClassName)) { throw new AttributeFormatException("wrong format for type " + rmClassName); } throw new RMObjectBuildingException("failed to create new instance of " + rmClassName + " with valueMap: " + toString(valueMap) + ", cause: " + e.getMessage()); } return (RMObject) ret; }
From source file:org.apache.hadoop.hbase.util.FanOutOneBlockAsyncDFSOutputHelper.java
private static PipelineAckStatusGetter createPipelineAckStatusGetter() { try {// w w w .j a v a 2 s . c o m final Method getFlagListMethod = PipelineAckProto.class.getMethod("getFlagList"); @SuppressWarnings("rawtypes") Class<? extends Enum> ecnClass; try { ecnClass = Class.forName("org.apache.hadoop.hdfs.protocol.datatransfer.PipelineAck$ECN") .asSubclass(Enum.class); } catch (ClassNotFoundException e) { throw new Error(e); } @SuppressWarnings("unchecked") final Enum<?> disabledECN = Enum.valueOf(ecnClass, "DISABLED"); final Method getReplyMethod = PipelineAckProto.class.getMethod("getReply", int.class); final Method combineHeaderMethod = PipelineAck.class.getMethod("combineHeader", ecnClass, Status.class); final Method getStatusFromHeaderMethod = PipelineAck.class.getMethod("getStatusFromHeader", int.class); return new PipelineAckStatusGetter() { @Override public Status get(PipelineAckProto ack) { try { @SuppressWarnings("unchecked") List<Integer> flagList = (List<Integer>) getFlagListMethod.invoke(ack); Integer headerFlag; if (flagList.isEmpty()) { Status reply = (Status) getReplyMethod.invoke(ack, 0); headerFlag = (Integer) combineHeaderMethod.invoke(null, disabledECN, reply); } else { headerFlag = flagList.get(0); } return (Status) getStatusFromHeaderMethod.invoke(null, headerFlag); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } }; } catch (NoSuchMethodException e) { LOG.warn("Can not get expected methods, should be hadoop 2.6-", e); } try { final Method getStatusMethod = PipelineAckProto.class.getMethod("getStatus", int.class); return new PipelineAckStatusGetter() { @Override public Status get(PipelineAckProto ack) { try { return (Status) getStatusMethod.invoke(ack, 0); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } }; } catch (NoSuchMethodException e) { throw new Error(e); } }