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:io.fabric8.forge.rest.dto.UICommands.java
public static void populateController(Map<String, Object> requestedInputs, CommandController controller, ConverterFactory converterFactory) { Map<String, InputComponent<?, ?>> inputs = controller.getInputs(); Set<String> inputKeys = new HashSet<>(inputs.keySet()); if (requestedInputs != null) { inputKeys.retainAll(requestedInputs.keySet()); Set<Map.Entry<String, InputComponent<?, ?>>> entries = inputs.entrySet(); for (Map.Entry<String, InputComponent<?, ?>> entry : entries) { String key = entry.getKey(); InputComponent<?, ?> component = entry.getValue(); Object value = requestedInputs.get(key); String textValue = null; if (value instanceof String || value instanceof Number || value instanceof Date) { textValue = value.toString(); }// w ww.j a v a 2s . c om /* String textValue = requestedInputs.get(key); Object value = textValue; */ if (component != null && textValue != null) { Converter<String, ?> valueConverter = component.getValueConverter(); if (valueConverter != null) { value = valueConverter.convert(textValue); } else { Class<?> valueType = component.getValueType(); if (valueType.isEnum()) { Class<? extends Enum> enumType = (Class<? extends Enum>) valueType; value = Enum.valueOf(enumType, textValue); } } InputComponents.setValueFor(converterFactory, component, value); } else { controller.setValueFor(key, value); } Object actual = controller.getValueFor(key); } } }
From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputHelper.java
private static PipelineAckStatusGetter createPipelineAckStatusGetter27() throws NoSuchMethodException { final Method getFlagListMethod = PipelineAckProto.class.getMethod("getFlagList"); @SuppressWarnings("rawtypes") Class<? extends Enum> ecnClass; try {/*ww w .j a v a 2s . c o m*/ ecnClass = Class.forName("org.apache.hadoop.hdfs.protocol.datatransfer.PipelineAck$ECN") .asSubclass(Enum.class); } catch (ClassNotFoundException e) { final String msg = "Couldn't properly initialize the PipelineAck.ECN class. Please " + "update your WAL Provider to not make use of the 'asyncfs' provider. See " + "HBASE-16110 for more information."; LOG.error(msg, e); throw new Error(msg, 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); } } }; }
From source file:com.google.gwt.resources.rg.GssResourceGenerator.java
public static GssOptions getGssOptions(PropertyOracle propertyOracle, TreeLogger logger) throws UnableToCompleteException { boolean gssEnabled; boolean gssDefaultInUiBinder; AutoConversionMode conversionMode;/* w w w. j a va 2s . co m*/ try { ConfigurationProperty enableGssProp = propertyOracle.getConfigurationProperty(KEY_ENABLE_GSS); String enableGss = enableGssProp.getValues().get(0); gssEnabled = Boolean.parseBoolean(enableGss); } catch (BadPropertyValueException ex) { logger.log(Type.ERROR, "Unable to determine if GSS need to be used"); throw new UnableToCompleteException(); } try { conversionMode = Enum.valueOf(AutoConversionMode.class, propertyOracle .getConfigurationProperty(KEY_CONVERSION_MODE).getValues().get(0).toUpperCase(Locale.ROOT)); } catch (BadPropertyValueException ex) { logger.log(Type.ERROR, "Unable to conversion mode for GSS"); throw new UnableToCompleteException(); } try { ConfigurationProperty uiBinderGssDefaultProp = propertyOracle .getConfigurationProperty(KEY_GSS_DEFAULT_IN_UIBINDER); String uiBinderGssDefaultValue = uiBinderGssDefaultProp.getValues().get(0); gssDefaultInUiBinder = Boolean.parseBoolean(uiBinderGssDefaultValue); } catch (BadPropertyValueException ex) { logger.log(Type.ERROR, "Unable to determine default for GSS in UiBinder"); throw new UnableToCompleteException(); } return new GssOptions(gssEnabled, conversionMode, gssDefaultInUiBinder); }
From source file:com.alliander.osgp.acceptancetests.adhocmanagement.GetStatusSteps.java
@DomainStep("the get status oslp message from the device contains (.*), (.*), (.*), (.*), (.*), (.*), and (.*)") public void givenAnOslpResponse(final String preferredLinkType, final String actualLinkType, final String lightType, final String eventNotifications, final String index, final Boolean on, final String dimValue) { LOGGER.info("GIVEN: the get status oslp message from the device contains {}, {}, {}, {}, {}, {}, and {}.", new Object[] { preferredLinkType, actualLinkType, lightType, eventNotifications, index, on, dimValue });/* w w w.j a v a 2s .c o m*/ // final OslpUtils oslpUtils = new OslpUtils(); // LightValue final Oslp.LightValue.Builder lightValueBuilder = Oslp.LightValue.newBuilder(); if (StringUtils.isNotBlank(index)) { lightValueBuilder.setIndex(OslpUtils.integerToByteString(Integer.parseInt(index))); } lightValueBuilder.setOn(on); if (StringUtils.isNotBlank(dimValue)) { lightValueBuilder.setDimValue(OslpUtils.integerToByteString(Integer.parseInt(dimValue))); } // EventNotificationMask int mask = 0; if (StringUtils.isNotBlank(eventNotifications)) { for (final String event : eventNotifications.split(",")) { mask += (Enum.valueOf(EventNotificationType.class, event)).getValue(); } } final com.alliander.osgp.oslp.Oslp.GetStatusResponse getStatusResponse = com.alliander.osgp.oslp.Oslp.GetStatusResponse .newBuilder().setStatus(Status.OK) .setPreferredLinktype(StringUtils.isBlank(preferredLinkType) ? Oslp.LinkType.LINK_NOT_SET : Enum.valueOf(Oslp.LinkType.class, preferredLinkType)) .setActualLinktype(StringUtils.isBlank(actualLinkType) ? Oslp.LinkType.LINK_NOT_SET : Enum.valueOf(Oslp.LinkType.class, actualLinkType)) .setLightType(StringUtils.isBlank(lightType) ? Oslp.LightType.LT_NOT_SET : Enum.valueOf(Oslp.LightType.class, lightType)) .setEventNotificationMask(mask).addValue(lightValueBuilder).build(); this.oslpResponse = OslpTestUtils.createOslpEnvelopeBuilder().withDeviceId(Base64.decodeBase64(DEVICE_UID)) .withPayloadMessage(Message.newBuilder().setGetStatusResponse(getStatusResponse).build()).build(); this.oslpChannelHandler = OslpTestUtils.createOslpChannelHandlerWithResponse(this.oslpResponse, this.channelMock, this.device.getNetworkAddress()); this.oslpChannelHandler.setDeviceRegistrationService(this.deviceRegistrationService); this.oslpDeviceService.setOslpChannelHandler(this.oslpChannelHandler); }
From source file:cn.afterturn.easypoi.excel.imports.CellValueService.java
/** * ??/* w w w .j av a 2s . com*/ * * @param classFullName * @param result * @param entity * @param clazz * @return */ private Object getValueByType(String classFullName, Object result, ExcelImportEntity entity, Class clazz) { try { //,null,?? if (result == null || StringUtils.isBlank(result.toString())) { return null; } if ("class java.util.Date".equals(classFullName) && result instanceof String) { return DateUtils.parseDate(result.toString(), entity.getFormat()); } if ("class java.lang.Boolean".equals(classFullName) || "boolean".equals(classFullName)) { return Boolean.valueOf(String.valueOf(result)); } if ("class java.lang.Double".equals(classFullName) || "double".equals(classFullName)) { return Double.valueOf(String.valueOf(result)); } if ("class java.lang.Long".equals(classFullName) || "long".equals(classFullName)) { try { return Long.valueOf(String.valueOf(result)); } catch (Exception e) { //?,double,??Int return Double.valueOf(String.valueOf(result)).longValue(); } } if ("class java.lang.Float".equals(classFullName) || "float".equals(classFullName)) { return Float.valueOf(String.valueOf(result)); } if ("class java.lang.Integer".equals(classFullName) || "int".equals(classFullName)) { try { return Integer.valueOf(String.valueOf(result)); } catch (Exception e) { //?,double,??Int return Double.valueOf(String.valueOf(result)).intValue(); } } if ("class java.math.BigDecimal".equals(classFullName)) { return new BigDecimal(String.valueOf(result)); } if ("class java.lang.String".equals(classFullName)) { //String ,Excel????String,Double, if (result instanceof String) { return result; } // double if (result instanceof Double) { return PoiPublicUtil.doubleToString((Double) result); } return String.valueOf(result); } if (clazz != null && clazz.isEnum()) { if (StringUtils.isNotEmpty(entity.getEnumImportMethod())) { return PoiReflectorUtil.fromCache(clazz).execEnumStaticMethod(entity.getEnumImportMethod(), result); } else { return Enum.valueOf(clazz, result.toString()); } } return result; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR); } }
From source file:com.dotweblabs.twirl.gae.GaeUnmarshaller.java
private void doUnmarshall(Object destination, Transaction transaction, Entity entity) { // Preconditions.checkNotNull(destination, "Destination object cannot be null"); // Preconditions.checkNotNull(entity, "Source entity cannot be null"); assert validator.validate(destination) == true; Map<String, Object> props = entity.getProperties(); Key key = entity.getKey();//from ww w .j a va 2 s. com String name = entity.getKey().getName(); if (destination instanceof PrimitiveWrapper) { PrimitiveWrapper wrapper = (PrimitiveWrapper) destination; Object wrapped = wrapper.getValue(); if (wrapped.getClass().isPrimitive() || wrapped.getClass().equals(String.class) || wrapped.getClass().equals(Integer.class) || wrapped.getClass().equals(Long.class) || wrapped.getClass().equals(Double.class) || wrapped.getClass().equals(Float.class) || wrapped.getClass().equals(Boolean.class)) { if (entity.getProperties().size() > 1) { LOG.warn( "Unmarshalling entity with multiple properties into primitive type will be serialized"); // TODO: Implement XStream serializer throw new RuntimeException( "Serializing multiple properties into primitives not yet implemented"); } else if (entity.getProperties().size() == 1) { String entityKey = entity.getProperties().keySet().iterator().next(); wrapper.setValue(entity.getProperty(entityKey)); } } return; } else if (destination instanceof Map) { Iterator<Map.Entry<String, Object>> it = entity.getProperties().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String entryKey = entry.getKey(); Object entryVal = entry.getValue(); if (entryVal instanceof EmbeddedEntity) { EmbeddedEntity ee = (EmbeddedEntity) entryVal; Object mapOrList = GaeMarshaller.getMapOrList(ee); ((Map) destination).put(entryKey, mapOrList); } else { ((Map) destination).put(entryKey, entryVal); } } ((Map) destination).put(Entity.KEY_RESERVED_PROPERTY, key.getName()); return; } AnnotatedField parentKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.parent(), destination); if (parentKeyField != null) { if (parentKeyField.getFieldType().equals(Key.class)) { parentKeyField.setFieldValue(entity.getParent()); } else { // throw new RuntimeException("Only GAE Key can be used as @Ancestor"); } } AnnotatedField ancestorKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.ancestor(), destination); if (ancestorKeyField != null) { if (ancestorKeyField.getFieldType().equals(Key.class)) { ancestorKeyField.setFieldValue(getAncestor(entity)); } else { throw new RuntimeException("Only GAE Key can be used as @Ancestor"); } } AnnotatedField idField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.key(), destination); if (idField != null) { if (idField.getFieldType().equals(String.class)) { idField.setFieldValue(key.getName()); } else if (idField.getFieldType().equals(Long.class)) { idField.setFieldValue(key.getId()); } else if (idField.getFieldType().equals(long.class)) { idField.setFieldValue(key.getId()); } else { throw new RuntimeException("Invalid key was retrieved with type " + idField.getFieldType()); } } AnnotatedField objectIdField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.objectId(), destination); if (objectIdField != null) { if (objectIdField.getFieldType().equals(String.class)) { String objectId = KeyFactory.keyToString(key); objectIdField.setFieldValue(objectId); } else { throw new RuntimeException( "Invalid ObjectId key was retrieved with type " + objectIdField.getFieldType()); } } AnnotatedField kindField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.kind(), destination); if (kindField != null) { if (kindField.getFieldType().equals(String.class)) { kindField.setFieldValue(entity.getKind()); } else { throw new RuntimeException("Invalid @Kind field is found for " + destination.getClass().getName()); } } AnnotatedField flatField = AnnotationUtil.getFieldWithAnnotation(Flat.class, destination); if (flatField != null) { if (flatField.getFieldType().equals(Map.class)) { Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator(); Map map = new LinkedHashMap(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String fieldName = entry.getKey(); Object fieldValue = entry.getValue(); // TODO: How about when by change a Map key would be the same with the POJO field name // TODO: Fix this or do not allow that to happen! boolean ok = true; Field[] fields = destination.getClass().getDeclaredFields(); for (Field field : list(fields)) { if (field.getName().equals(fieldName)) { ok = false; } } if (ok) { if (fieldValue instanceof EmbeddedEntity) { Map m = getMapFromEmbeddedEntity((EmbeddedEntity) fieldValue); fieldValue = m; } map.put(fieldName, fieldValue); } } Field field = flatField.getField(); setFieldValue(field, destination, map); } else { throw new RuntimeException("Only java.util.Map should be used for @Flat fields"); } } Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator(); Class<?> clazz = destination.getClass(); List<Field> fields = list(clazz.getDeclaredFields()); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String fieldName = entry.getKey(); Object fieldValue = entry.getValue(); try { for (Field field : fields) { if (field.getName().equals(fieldName)) { if (fieldValue == null) { setFieldValue(field, destination, fieldValue); } else if (fieldValue instanceof Key) { // child try { Entity e = store.getDatastoreService() .get((com.google.appengine.api.datastore.Key) fieldValue); AnnotatedField annotatedField = AnnotationUtil .getFieldWithAnnotation(GaeObjectStore.child(), destination); Object childInstance = store.createInstance(annotatedField.getFieldType()); unmarshall(childInstance, e); setFieldValue(field, destination, childInstance); } catch (EntityNotFoundException e) { fieldValue = null; } } else if (fieldValue instanceof String || fieldValue instanceof Boolean || fieldValue instanceof Number || fieldValue instanceof Blob) { if (field.getName().equals(fieldName)) { if (field.getType().isEnum()) { setFieldValue(field, destination, Enum.valueOf((Class<Enum>) field.getType(), (String) fieldValue)); } if (field.getType().equals(String.class)) { setFieldValue(field, destination, String.valueOf(fieldValue)); } else if (field.getType().equals(Boolean.class)) { setFieldValue(field, destination, (Boolean) fieldValue); } else if (field.getType().equals(Long.class)) { setFieldValue(field, destination, (Long) fieldValue); } else if (field.getType().equals(Integer.class)) { if (fieldValue.getClass().equals(Long.class)) { Long value = (Long) fieldValue; setFieldValue(field, destination, value.intValue()); } else { setFieldValue(field, destination, (Integer) fieldValue); } } else if (field.getType().equals(int.class)) { if (fieldValue.getClass().equals(Long.class) || fieldValue.getClass().equals(long.class)) { Long value = (Long) fieldValue; setFieldValue(field, destination, value.intValue()); } else { setFieldValue(field, destination, ((Integer) fieldValue).intValue()); } } else if (field.getType().equals(long.class)) { if (fieldValue.getClass().equals(Integer.class) || fieldValue.getClass().equals(int.class)) { Integer value = (Integer) fieldValue; setFieldValue(field, destination, value.longValue()); } else { setFieldValue(field, destination, ((Long) fieldValue).longValue()); } } else if (field.getType().equals(boolean.class)) { setFieldValue(field, destination, ((Boolean) fieldValue).booleanValue()); } else if (field.getType().equals(byte.class)) { if (fieldValue.getClass().equals(Blob.class)) { // TODO: Need to have a second look with this code Blob blob = (Blob) fieldValue; setFieldValue(field, destination, blob.getBytes()[0]); } } else if (field.getType().equals(byte[].class)) { if (fieldValue.getClass().equals(Blob.class)) { Blob blob = (Blob) fieldValue; setFieldValue(field, destination, blob.getBytes()); } } else if (field.getType().equals(Date.class)) { if (fieldValue.getClass().equals(String.class)) { Date date = DateUtil.parseDate((String) fieldValue); setFieldValue(field, destination, date); } else if (fieldValue.getClass().equals(Long.class)) { Date date = new Date((Long) fieldValue); setFieldValue(field, destination, date); } else if (fieldValue.getClass().equals(Date.class)) { setFieldValue(field, destination, fieldValue); } else { throw new RuntimeException( "Unable to unmarshall " + fieldValue.getClass().getName() + " to " + field.getType().getName()); } } else if (field.getType().equals(Blob.class)) { if (fieldValue.getClass().equals(Blob.class)) { Blob blob = (Blob) fieldValue; setFieldValue(field, destination, blob); } } } } else if (fieldValue instanceof Blob) { setFieldValue(field, destination, fieldValue); } else if (fieldValue instanceof Text) { Text textField = (Text) fieldValue; setFieldValue(field, destination, textField.getValue()); } else if (fieldValue instanceof Date) { setFieldValue(field, destination, fieldValue); } else if (fieldValue instanceof User) { setFieldValue(field, destination, fieldValue); } else if (fieldValue instanceof EmbeddedEntity) { // List or Java primitive types and standard types, Map or POJO's Class<?> fieldValueType = fieldValue.getClass(); EmbeddedEntity ee = (EmbeddedEntity) fieldValue; Map<String, Object> map = ee.getProperties(); store.createInstance(fieldValueType); if (field.getType().equals(List.class) || field.getType().equals(Map.class)) { Object mapOrList = getMapOrList((EmbeddedEntity) fieldValue); setFieldValue(field, destination, mapOrList); } else { // Must be a POJO Map<String, Object> getMap = getMapFromEmbeddedEntity((EmbeddedEntity) fieldValue); Object pojo = Maps.fromMap(getMap, field.getType()); setFieldValue(field, destination, pojo); } } else if (fieldValue instanceof GeoPt) { setFieldValue(field, destination, fieldValue); } else if (fieldValue instanceof List) { setFieldValue(field, destination, fieldValue); } else if (fieldValue.getClass().isPrimitive()) { throw new RuntimeException("Not yet implemented"); } } } } catch (ClassCastException e) { if (fieldName != null && fieldValue != null) { LOG.error("Exception while unmarshalling GAE Entity field name=" + fieldName + " type=" + fieldValue.getClass().getName() + " value=" + fieldValue); } throw e; } } AnnotatedField aliasField = AnnotationUtil.getFieldWithAnnotation(Alias.class, destination); if (aliasField != null) { Alias alias = aliasField.getField().getAnnotation(Alias.class); String fieldName = alias.field(); Object value = props.get(fieldName); String actualField = aliasField.getFieldName(); Object actualValue = props.get(actualField); if (value != null) { setFieldValue(aliasField.getField(), destination, value); } else { setFieldValue(aliasField.getField(), destination, actualValue); } } }
From source file:net.ceos.project.poi.annotated.core.CGen.java
/** * Import the CSV file into the object.// w w w . j ava2 s . c om * * @param object * the object * @param fT * the field type * @param field * the field * @param xlsAnnotation * the {@link XlsElement} annotation * @param values * the array with the content at one line * @param idx * the index of the field * @return true if the field has been updated, otherwise false * @throws WorkbookException */ @SuppressWarnings({ "unchecked", "rawtypes" }) private boolean toObject(final Object object, final Class<?> fT, final Field field, final XlsElement xlsAnnotation, final String[] values, final int idx) throws WorkbookException { /* flag which define if the cell was updated or not */ boolean isUpdated; /* set enabled the accessible object */ field.setAccessible(true); switch (fT.getName()) { case CellHandler.OBJECT_DATE: CsvHandler.dateReader(object, field, xlsAnnotation, values, idx); isUpdated = true; break; case CellHandler.OBJECT_LOCALDATE: CsvHandler.localDateReader(object, field, xlsAnnotation, values, idx); isUpdated = true; break; case CellHandler.OBJECT_LOCALDATETIME: CsvHandler.localDateTimeReader(object, field, xlsAnnotation, values, idx); isUpdated = true; break; case CellHandler.OBJECT_STRING: CsvHandler.stringReader(object, field, values, idx); isUpdated = true; break; case CellHandler.OBJECT_SHORT: /* falls through */ case CellHandler.PRIMITIVE_SHORT: CsvHandler.shortReader(object, field, values, idx); isUpdated = true; break; case CellHandler.OBJECT_INTEGER: /* falls through */ case CellHandler.PRIMITIVE_INTEGER: CsvHandler.integerReader(object, field, values, idx); isUpdated = true; break; case CellHandler.OBJECT_LONG: /* falls through */ case CellHandler.PRIMITIVE_LONG: CsvHandler.longReader(object, field, values, idx); isUpdated = true; break; case CellHandler.OBJECT_DOUBLE: /* falls through */ case CellHandler.PRIMITIVE_DOUBLE: CsvHandler.doubleReader(object, field, xlsAnnotation, values, idx); isUpdated = true; break; case CellHandler.OBJECT_BIGDECIMAL: CsvHandler.bigDecimalReader(object, field, values, idx); isUpdated = true; break; case CellHandler.OBJECT_FLOAT: /* falls through */ case CellHandler.PRIMITIVE_FLOAT: CsvHandler.floatReader(object, field, values, idx); isUpdated = true; break; case CellHandler.OBJECT_BOOLEAN: /* falls through */ case CellHandler.PRIMITIVE_BOOLEAN: CsvHandler.booleanReader(object, field, xlsAnnotation, values, idx); isUpdated = true; break; default: isUpdated = false; break; } if (!isUpdated && fT.isEnum()) { try { field.set(object, Enum.valueOf((Class<Enum>) fT, values[idx])); } catch (IllegalArgumentException | IllegalAccessException e) { throw new WorkbookException(e.getMessage(), e); } isUpdated = true; } /* set disabled the accessible object */ field.setAccessible(false); return isUpdated; }
From source file:org.apache.tajo.catalog.store.HCatalogStore.java
private TajoDataTypes.Type getDataType(final String typeStr) { try {//from w w w . j a va 2 s. c o m return Enum.valueOf(TajoDataTypes.Type.class, typeStr); } catch (IllegalArgumentException iae) { LOG.error("Cannot find a matched type against from '" + typeStr + "'"); return null; } }
From source file:org.datanucleus.store.hbase.fieldmanager.FetchFieldManager.java
public Object fetchObjectField(int fieldNumber) { ClassLoaderResolver clr = ec.getClassLoaderResolver(); AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumber); if (mmd.getType() == UUID.class) { String familyName = HBaseUtils.getFamilyName(cmd, fieldNumber); String columnName = HBaseUtils.getQualifierName(cmd, fieldNumber); byte[] bytes = result.getValue(familyName.getBytes(), columnName.getBytes()); return fetchUUIDInternal(mmd, bytes); }/*from w w w.j ava 2 s. c o m*/ int relationType = mmd.getRelationType(clr); if (mmd.isEmbedded() && Relation.isRelationSingleValued(relationType)) { // Persistable object embedded into table of this object Class embcls = mmd.getType(); AbstractClassMetaData embcmd = ec.getMetaDataManager().getMetaDataForClass(embcls, clr); if (embcmd != null) { String tableName = HBaseUtils.getTableName(cmd); // Check for null value (currently need all columns to return null) // TODO Cater for null (use embmd.getNullIndicatorColumn/Value) EmbeddedMetaData embmd = mmd.getEmbeddedMetaData(); AbstractMemberMetaData[] embmmds = embmd.getMemberMetaData(); boolean isNull = true; for (int i = 0; i < embmmds.length; i++) { String familyName = HBaseUtils.getFamilyName(mmd, i, tableName); String columnName = HBaseUtils.getQualifierName(mmd, i); if (result.getValue(familyName.getBytes(), columnName.getBytes()) != null) { isNull = false; break; } } if (isNull) { return null; } ObjectProvider embSM = ec.newObjectProviderForEmbedded(mmd, embcmd, sm, fieldNumber); FieldManager ffm = new FetchEmbeddedFieldManager(embSM, result, mmd, tableName); embSM.replaceFields(embcmd.getAllMemberPositions(), ffm); return embSM.getObject(); } throw new NucleusUserException( "Field " + mmd.getFullFieldName() + " marked as embedded but no such metadata"); } String familyName = HBaseUtils.getFamilyName(cmd, fieldNumber); String columnName = HBaseUtils.getQualifierName(cmd, fieldNumber); Object value = readObjectField(familyName, columnName, result, fieldNumber, mmd); if (value == null) { return null; } if (Relation.isRelationSingleValued(relationType)) { if (mmd.isSerialized()) { return value; } else { // The stored value was the identity return ec.findObject(value, true, true, null); } } else if (Relation.isRelationMultiValued(relationType)) { if (mmd.hasCollection()) { if (mmd.isSerialized()) { return value; } Collection<Object> coll; try { Class instanceType = SCOUtils.getContainerInstanceType(mmd.getType(), mmd.getOrderMetaData() != null); coll = (Collection<Object>) instanceType.newInstance(); } catch (Exception e) { throw new NucleusDataStoreException(e.getMessage(), e); } Collection collIds = (Collection) value; Iterator idIter = collIds.iterator(); while (idIter.hasNext()) { Object elementId = idIter.next(); coll.add(ec.findObject(elementId, true, true, null)); } if (sm != null) { return sm.wrapSCOField(fieldNumber, coll, false, false, true); } return coll; } else if (mmd.hasMap()) { if (mmd.isSerialized()) { return value; } Map map; try { Class instanceType = SCOUtils.getContainerInstanceType(mmd.getType(), false); map = (Map) instanceType.newInstance(); } catch (Exception e) { throw new NucleusDataStoreException(e.getMessage(), e); } Map mapIds = (Map) value; Iterator<Map.Entry> mapIdIter = mapIds.entrySet().iterator(); while (mapIdIter.hasNext()) { Map.Entry entry = mapIdIter.next(); Object mapKey = entry.getKey(); Object mapValue = entry.getValue(); if (mmd.getMap().getKeyClassMetaData(clr, ec.getMetaDataManager()) != null) { // Map key must be an "id" mapKey = ec.findObject(mapKey, true, true, null); } if (mmd.getMap().getValueClassMetaData(clr, ec.getMetaDataManager()) != null) { // Map value must be an "id" mapValue = ec.findObject(mapValue, true, true, null); } map.put(mapKey, mapValue); } if (sm != null) { return sm.wrapSCOField(fieldNumber, map, false, false, true); } return map; } else if (mmd.hasArray()) { if (mmd.isSerialized()) { return value; } Collection arrIds = (Collection) value; Object array = Array.newInstance(mmd.getType().getComponentType(), arrIds.size()); Iterator idIter = arrIds.iterator(); int i = 0; while (idIter.hasNext()) { Object elementId = idIter.next(); Array.set(array, i, ec.findObject(elementId, true, true, null)); } return array; } throw new NucleusUserException("No container that isnt collection/map/array"); } else { Object returnValue = value; if (!mmd.isSerialized()) { if (Enum.class.isAssignableFrom(mmd.getType())) { // Persisted as a String, so convert back // TODO Retrieve as number when requested return Enum.valueOf(mmd.getType(), (String) value); } ObjectStringConverter strConv = ec.getNucleusContext().getTypeManager() .getStringConverter(mmd.getType()); if (strConv != null) { // Persisted as a String, so convert back String strValue = (String) value; returnValue = strConv.toObject(strValue); } } if (sm != null) { return sm.wrapSCOField(fieldNumber, returnValue, false, false, true); } return returnValue; } }
From source file:org.apache.olingo.ext.proxy.utils.CoreUtils.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static Enum<?> enumValueToObject(final ClientEnumValue value, final Class<?> reference) { final Namespace namespace = reference.getAnnotation(Namespace.class); final EnumType enumType = reference.getAnnotation(EnumType.class); if (value.getTypeName().equals(namespace.value() + "." + enumType.name())) { return Enum.valueOf((Class<Enum>) reference, value.getValue()); }/*from w ww. j ava 2s . c om*/ return null; }