List of usage examples for java.lang.reflect Field isAccessible
@Deprecated(since = "9") public boolean isAccessible()
From source file:org.kuali.coeus.common.budget.framework.query.QueryList.java
/** calculates the sum of the field in this QueryList. * @param fieldName field of bean whose sum has to be calculated. * @param arg argument for the getter method of field if it takes any argumnt, * else can be null./*from w w w . ja v a 2s . c o m*/ * @param value value for the argument, else can be null. * @return returns sum. */ public double sum(String fieldName, Class arg, Object value) { if (size() == 0) { return 0; } Object current; Field field = null; Method method = null; Class dataClass = get(0).getClass(); double sum = 0; try { field = dataClass.getDeclaredField(fieldName); Class fieldClass = field.getType(); if (!(fieldClass.equals(Integer.class) || fieldClass.equals(Long.class) || fieldClass.equals(Double.class) || fieldClass.equals(Float.class) || fieldClass.equals(BigDecimal.class) || fieldClass.equals(BigInteger.class) || fieldClass.equals(ScaleTwoDecimal.class) || fieldClass.equals(ScaleTwoDecimal.class) || fieldClass.equals(int.class) || fieldClass.equals(long.class) || fieldClass.equals(float.class) || fieldClass.equals(double.class))) { throw new UnsupportedOperationException("Data Type not numeric"); } if (!field.isAccessible()) { throw new NoSuchFieldException(); } } catch (NoSuchFieldException noSuchFieldException) { try { String methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1); if (arg != null) { Class args[] = { arg }; method = dataClass.getMethod(methodName, args); } else { method = dataClass.getMethod(methodName, null); } } catch (NoSuchMethodException noSuchMethodException) { LOG.error(noSuchMethodException.getMessage(), noSuchMethodException); } } for (int index = 0; index < size(); index++) { current = get(index); try { if (field != null && field.isAccessible()) { sum = sum + Double.parseDouble(((Comparable) field.get(current)).toString()); } else { Comparable dataValue; if (value != null) { Object values[] = { value }; dataValue = (Comparable) method.invoke(current, values); } else { dataValue = (Comparable) method.invoke(current, null); } if (dataValue != null) { sum += Double.parseDouble(dataValue.toString()); } } } catch (IllegalAccessException illegalAccessException) { LOG.error(illegalAccessException.getMessage(), illegalAccessException); } catch (InvocationTargetException invocationTargetException) { LOG.error(invocationTargetException.getMessage(), invocationTargetException); } } return sum; }
From source file:org.kuali.kra.budget.calculator.QueryList.java
/** calculates the sum of the field in this QueryList. * @param fieldName field of bean whose sum has to be calculated. * @param arg argument for the getter method of field if it takes any argumnt, * else can be null.//from www . j a va2 s . c o m * @param value value for the argument, else can be null. * @return returns sum. */ public double sum(String fieldName, Class arg, Object value) { if (size() == 0) { return 0; } Object current; Field field = null; Method method = null; Class dataClass = get(0).getClass(); double sum = 0; try { field = dataClass.getDeclaredField(fieldName); Class fieldClass = field.getType(); if (!(fieldClass.equals(Integer.class) || fieldClass.equals(Long.class) || fieldClass.equals(Double.class) || fieldClass.equals(Float.class) || fieldClass.equals(BigDecimal.class) || fieldClass.equals(BigInteger.class) || fieldClass.equals(BudgetDecimal.class) || fieldClass.equals(KualiDecimal.class) || fieldClass.equals(int.class) || fieldClass.equals(long.class) || fieldClass.equals(float.class) || fieldClass.equals(double.class))) { throw new UnsupportedOperationException("Data Type not numeric"); } if (!field.isAccessible()) { throw new NoSuchFieldException(); } } catch (NoSuchFieldException noSuchFieldException) { try { String methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1); if (arg != null) { Class args[] = { arg }; method = dataClass.getMethod(methodName, args); } else { method = dataClass.getMethod(methodName, null); } } catch (NoSuchMethodException noSuchMethodException) { noSuchMethodException.printStackTrace(); } } for (int index = 0; index < size(); index++) { current = get(index); try { if (field != null && field.isAccessible()) { sum = sum + Double.parseDouble(((Comparable) field.get(current)).toString()); } else { Comparable dataValue; if (value != null) { Object values[] = { value }; dataValue = (Comparable) method.invoke(current, values); } else { dataValue = (Comparable) method.invoke(current, null); } if (dataValue != null) { sum += Double.parseDouble(dataValue.toString()); } } } catch (IllegalAccessException illegalAccessException) { illegalAccessException.printStackTrace(); } catch (InvocationTargetException invocationTargetException) { invocationTargetException.printStackTrace(); } } return sum; }
From source file:org.j2free.admin.ReflectionMarshaller.java
/** * /*from w w w. ja v a2s .co m*/ * @param entity * @param includeTransient * @return * @throws IllegalArgumentException */ public List<MarshalledField> marshallOut(Object entity, boolean includeTransient) throws IllegalArgumentException { TreeSet<MarshalledField> fields = new TreeSet<MarshalledField>(); if (entity == null) { for (Map.Entry<Field, Converter> ent : instructions.entrySet()) { fields.add(new MarshalledField(ent.getKey().getName())); } return new LinkedList<MarshalledField>(fields); } log.debug("Marshalling out instance of " + entity.getClass().getSimpleName()); Field field; Converter converter; Object value; Method getter; boolean error = false; for (Map.Entry<Field, Converter> ent : instructions.entrySet()) { error = false; field = ent.getKey(); converter = ent.getValue(); value = null; log.debug("Converting field " + field.getName()); if ((field.isAnnotationPresent(Transient.class) || Modifier.isTransient(field.getModifiers())) && !includeTransient) continue; try { if (!field.isAccessible()) { field.setAccessible(true); } if (field.isAccessible()) { value = convertNull(field.get(entity)); } else { error = true; } } catch (IllegalAccessException iae) { log.error("Unable to access " + entity.getClass().getSimpleName() + "." + field.getName() + " directly.", iae); error = true; } if (error) { error = false; try { getter = converter.getGetter(); if (getter != null) { if (!getter.isAccessible()) { getter.setAccessible(true); } if (getter.isAccessible()) { value = convertNull(getter.invoke(entity)); } else { error = true; } } else { error = true; } } catch (IllegalAccessException iae) { log.error("Error accessing getter for field " + entity.getClass().getSimpleName() + "." + field.getName(), iae); error = true; } catch (InvocationTargetException ite) { log.error("Error invoking getter for field " + entity.getClass().getSimpleName() + "." + field.getName(), ite); error = true; } } if (error) { // if there was an error, then we weren't able to access the field, // so set the value to be displayed to "Inaccessible!" and override // the converter readonly value to make sure the display doesn't let // the user edit an inaccessible field. converter.setReadOnly(true); fields.add(new MarshalledField(field.getName(), "Inaccessible!", converter)); } else { fields.add(new MarshalledField(field.getName(), value, converter)); } } return new LinkedList<MarshalledField>(fields); }
From source file:org.cloudifysource.usm.UniversalServiceManagerBean.java
@Override public void setApplicationContext(final ApplicationContext arg0) throws BeansException { // CHECKSTYLE:ON this.applicationContext = arg0; if (arg0.getClassLoader() instanceof ServiceClassLoader) { // running in GSC this.runningInGSC = true; final ServiceClassLoader scl = (ServiceClassLoader) arg0.getClassLoader(); final URL url = scl.getSlashPath(); logger.fine("The slashpath URL is: " + url); URI uri;//ww w . ja v a2 s .c o m try { uri = url.toURI(); } catch (final URISyntaxException e) { throw new IllegalArgumentException(e); } logger.fine("The slashpath URI is: " + uri); this.puWorkDir = new File(uri); this.puExtDir = new File(this.puWorkDir, "ext"); return; } final ResourceApplicationContext rac = (ResourceApplicationContext) arg0; try { this.runningInGSC = false; final Field resourcesField = rac.getClass().getDeclaredField("resources"); final boolean accessibleBefore = resourcesField.isAccessible(); resourcesField.setAccessible(true); final Resource[] resources = (Resource[]) resourcesField.get(rac); for (final Resource resource : resources) { // find META-INF/spring/pu.xml final File file = resource.getFile(); if (file.getName().equals("pu.xml") && file.getParentFile().getName().equals("spring") && file.getParentFile().getParentFile().getName().equals("META-INF")) { puWorkDir = resource.getFile().getParentFile().getParentFile().getParentFile(); puExtDir = new File(puWorkDir, "ext"); break; } } resourcesField.setAccessible(accessibleBefore); } catch (final Exception e) { throw new IllegalArgumentException("Could not find pu.xml in the ResourceApplicationContext", e); } if (puWorkDir == null) { throw new IllegalArgumentException("Could not find pu.xml in the ResourceApplicationContext"); } }
From source file:dinistiq.Dinistiq.java
/** * Injects all available dependencies into a given bean and records all dependencies. * * @param key key / name/ id of the bean * @param bean bean instance//w w w. j av a2 s . c o m * @param dependencies dependencies map where the dependecies of the bean are recorded with the given key * @throws Exception */ private void injectDependencies(Map<String, Set<Object>> dependencies, String key, Object bean) throws Exception { // Prepare values from properties files Properties beanProperties = getProperties(key); LOG.debug("injectDependencies({}) bean properties {}", key, beanProperties.keySet()); // fill injected fields Class<? extends Object> beanClass = bean.getClass(); String beanClassName = beanClass.getName(); while (beanClass != Object.class) { if (bean instanceof Map) { fillMap(bean, getProperties(key)); LOG.info("injectDependencies() filled map '{}' {}", key, bean); return; // If it's a map we don't need to inject anything beyond some map properties files. } // if for (Field field : beanClass.getDeclaredFields()) { LOG.debug("injectDependencies({}) field {}", key, field.getName()); if (field.getAnnotation(Inject.class) != null) { Named named = field.getAnnotation(Named.class); String name = (named == null) ? null : (StringUtils.isBlank(named.value()) ? field.getName() : named.value()); LOG.info("injectDependencies({}) {} :{} needs injection with name {}", key, field.getName(), field.getGenericType(), name); Object b = getValue(beanProperties, dependencies, key, field.getType(), field.getGenericType(), name); final boolean accessible = field.isAccessible(); try { field.setAccessible(true); field.set(bean, b); } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) { LOG.error("injectDependencies() error setting field " + field.getName() + " :" + field.getType().getName() + " at '" + key + "' :" + beanClassName, e); } finally { field.setAccessible(accessible); } // try/catch } // if } // for beanClass = beanClass.getSuperclass(); } // while // call methods with annotated injections for (Method m : bean.getClass().getMethods()) { if (m.getAnnotation(Inject.class) != null) { LOG.debug("injectDependencies({}) inject parameters on method {}", key, m.getName()); Class<? extends Object>[] parameterTypes = m.getParameterTypes(); Type[] genericParameterTypes = m.getGenericParameterTypes(); Annotation[][] parameterAnnotations = m.getParameterAnnotations(); Object[] parameters = getParameters(beanProperties, dependencies, key, parameterTypes, genericParameterTypes, parameterAnnotations); try { m.invoke(bean, parameters); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { LOG.error("injectDependencies() error injecting for method " + m.getName() + " at '" + key + "' :" + beanClassName, ex); } // try/catch } // if } // for // Fill in manually set values from properties file for (String property : beanProperties.stringPropertyNames()) { String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); LOG.debug("injectDependencies({}) {} -> {}", key, property, methodName); Method m = null; // Have to find it just by name for (Method me : bean.getClass().getMethods()) { if (me.getName().equals(methodName) && (me.getParameterTypes().length > 0)) { m = me; } // if } // for if (m == null) { LOG.warn("injectDependencies({}) no setter method found for property {}", key, property); } else { String propertyName = Introspector.decapitalize(m.getName().substring(3)); Class<?> parameterType = m.getParameterTypes()[0]; Type genericType = m.getGenericParameterTypes()[0]; LOG.debug("injectDependencies({}) writable property found {} :{} {}", key, propertyName, parameterType, genericType); String propertyValue = beanProperties.getProperty(propertyName); // Must definetely be there without additional check boolean isBoolean = (parameterType == Boolean.class) || (m.getParameterTypes()[0] == Boolean.TYPE); boolean isCollection = Collection.class.isAssignableFrom(parameterType); Object[] parameters = new Object[1]; LOG.debug("injectDependencies({}) trying to set value {} (bool {}) (collection {}) '{}'", key, propertyName, isBoolean, isCollection, propertyValue); try { parameters[0] = getReferenceValue(propertyValue); if (isBoolean && (parameters[0] instanceof String)) { parameters[0] = Boolean.valueOf(propertyValue); } // if if ("long".equals(parameterType.getName())) { parameters[0] = new Long(propertyValue); } // if if ("int".equals(parameterType.getName())) { parameters[0] = new Integer(propertyValue); } // if if ("float".equals(parameterType.getName())) { parameters[0] = new Float(propertyValue); } // if if ("double".equals(parameterType.getName())) { parameters[0] = new Double(propertyValue); } // if if (isCollection) { if (!Collection.class.isAssignableFrom(parameters[0].getClass())) { Collection<Object> values = List.class.isAssignableFrom(parameterType) ? new ArrayList<>() : new HashSet<>(); for (String value : propertyValue.split(",")) { values.add(getReferenceValue(value)); } // for parameters[0] = values; } // if if (dependencies != null) { for (Object d : (Collection<?>) parameters[0]) { if (beans.containsValue(d)) { dependencies.get(key).add(d); } // if } // if } // if } else { if ((dependencies != null) && (beans.containsValue(parameters[0]))) { dependencies.get(key).add(parameters[0]); } // if } // if LOG.debug("injectDependencies({}) setting value {} '{}' :{}", key, propertyName, parameters[0], parameters[0].getClass()); m.invoke(bean, parameters); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { LOG.error("injectDependencies() error setting property " + propertyName + " to '" + propertyValue + "' at " + key + " :" + beanClassName, ex); } // try/catch } // if } // for }
From source file:com.evolveum.midpoint.prism.marshaller.BeanUnmarshaller.java
/** * For cases when XSD complex type has a simple content. In that case the resulting class has @XmlValue annotation. *//*from w w w .jav a2s . c o m*/ private <T> T unmarshallPrimitive(PrimitiveXNode<T> prim, Class<T> beanClass, ParsingContext pc) throws SchemaException { if (prim.isEmpty()) { return instantiateWithSubtypeGuess(beanClass, emptySet()); // Special case. Just return empty object } Field valueField = XNodeProcessorUtil.findXmlValueField(beanClass); if (valueField == null) { ParsingMigrator parsingMigrator = prismContext.getParsingMigrator(); if (parsingMigrator != null) { T bean = parsingMigrator.tryParsingPrimitiveAsBean(prim, beanClass, pc); if (bean != null) { return bean; } } throw new SchemaException("Cannot convert primitive value to bean of type " + beanClass); } T instance = instantiate(beanClass); if (!valueField.isAccessible()) { valueField.setAccessible(true); } T value; if (prim.isParsed()) { value = prim.getValue(); } else { Class<?> fieldType = valueField.getType(); QName xsdType = XsdTypeMapper.toXsdType(fieldType); value = prim.getParsedValue(xsdType, (Class<T>) fieldType); } try { valueField.set(instance, value); } catch (IllegalArgumentException | IllegalAccessException e) { throw new SchemaException("Cannot set primitive value to field " + valueField.getName() + " of bean " + beanClass + ": " + e.getMessage(), e); } return instance; }
From source file:org.soyatec.windowsazure.table.internal.CloudTableRest.java
/** * Deserial the xml to object accord to the give model class. * * @param partitionKey/*from w w w.j av a2s.c o m*/ * @param rowKey * @param eTag * @param timestamp * @param values * @return Instance of the given model class. */ private ITableServiceEntity createObjectByModelClass(String partitionKey, String rowKey, String eTag, String timestamp, List<ICloudTableColumn> values) { ITableServiceEntity newInstance = instanceModel(partitionKey, rowKey, eTag, timestamp, values); if (newInstance == null) { return null; } // Copy Field if (values != null && !values.isEmpty()) { for (ICloudTableColumn column : values) { Field field = null; try { field = newInstance.getClass().getDeclaredField(column.getName()); } catch (NoSuchFieldException e) { continue; } if (field == null) { continue; } int modifier = field.getModifiers(); if (Modifier.isPrivate(modifier) && Modifier.isFinal(modifier) && Modifier.isStatic(modifier)) { if (getModelClass() != null) { Logger.debug(MessageFormat.format( "{0} class {1} is a static final field. Can not set data to it.", getModelClass().getClass(), field.getName())); } continue; } boolean accessible = field.isAccessible(); if (!accessible) { field.setAccessible(true); } ETableColumnType type = column.getType(); String value = column.getValue(); if (value == null) { continue; } else { try { if (type == null) { setStringOrObjectField(newInstance, column, field, value); } else if (type.equals(ETableColumnType.TYPE_BINARY)) { field.set(newInstance, Base64.decode(value)); } else if (type.equals(ETableColumnType.TYPE_BOOL)) { field.setBoolean(newInstance, Boolean.parseBoolean(value)); } else if (type.equals(ETableColumnType.TYPE_DATE_TIME)) { field.set(newInstance, Utilities.tryGetDateTimeFromTableEntry(value)); } else if (type.equals(ETableColumnType.TYPE_DOUBLE)) { field.setDouble(newInstance, Double.parseDouble(value)); } else if (type.equals(ETableColumnType.TYPE_GUID)) { Guid guid = new Guid(); try { Field valueField = guid.getClass().getDeclaredField("value"); boolean accessiable = valueField.isAccessible(); if (!accessible) { valueField.setAccessible(true); } valueField.set(guid, value); valueField.setAccessible(accessiable); field.set(newInstance, guid); } catch (NoSuchFieldException e) { Logger.error(e.getMessage(), e); } } else if (type.equals(ETableColumnType.TYPE_INT)) { try { field.setInt(newInstance, Integer.parseInt(value)); } catch (Exception e) { field.setByte(newInstance, Byte.parseByte(value)); } } else if (type.equals(ETableColumnType.TYPE_LONG)) { field.setLong(newInstance, Long.parseLong(value)); } else if (type.equals(ETableColumnType.TYPE_STRING)) { setStringOrObjectField(newInstance, column, field, value); } } catch (Exception e) { Logger.error( MessageFormat.format("{0} class filed {1} set failed.", getModelClass(), value), e); } } // revert aaccessible field.setAccessible(accessible); } } return newInstance; }
From source file:io.milton.config.HttpManagerBuilder.java
private Object createObject(Class c) throws CreationException { log.info("createObject: {}", c.getCanonicalName()); // Look for an @Inject or default constructor Constructor found = null;// w w w. ja va 2s. c om for (Constructor con : c.getConstructors()) { Annotation[][] paramTypes = con.getParameterAnnotations(); if (paramTypes != null && paramTypes.length > 0) { Annotation inject = con.getAnnotation(Inject.class); if (inject != null) { found = con; } } else { found = con; } } if (found == null) { throw new RuntimeException( "Could not find a default or @Inject constructor for class: " + c.getCanonicalName()); } Object args[] = new Object[found.getParameterTypes().length]; int i = 0; for (Class paramType : found.getParameterTypes()) { try { args[i++] = findOrCreateObject(paramType); } catch (CreationException ex) { throw new CreationException(c, ex); } } Object created; try { log.info("Creating: {}", c.getCanonicalName()); created = found.newInstance(args); rootContext.put(created); } catch (InstantiationException ex) { throw new CreationException(c, ex); } catch (IllegalAccessException ex) { throw new CreationException(c, ex); } catch (IllegalArgumentException ex) { throw new CreationException(c, ex); } catch (InvocationTargetException ex) { throw new CreationException(c, ex); } // Now look for @Inject fields for (Field field : c.getDeclaredFields()) { Inject anno = field.getAnnotation(Inject.class); if (anno != null) { boolean acc = field.isAccessible(); try { field.setAccessible(true); field.set(created, findOrCreateObject(field.getType())); } catch (IllegalArgumentException ex) { throw new CreationException(field, c, ex); } catch (IllegalAccessException ex) { throw new CreationException(field, c, ex); } finally { field.setAccessible(acc); // put back the way it was } } } // Finally set any @Inject methods for (Method m : c.getMethods()) { Inject anno = m.getAnnotation(Inject.class); if (anno != null) { Object[] methodArgs = new Object[m.getParameterTypes().length]; int ii = 0; try { for (Class<?> paramType : m.getParameterTypes()) { methodArgs[ii++] = findOrCreateObject(paramType); } m.invoke(created, methodArgs); } catch (CreationException creationException) { throw new CreationException(m, c, creationException); } catch (IllegalAccessException ex) { throw new CreationException(m, c, ex); } catch (IllegalArgumentException ex) { throw new CreationException(m, c, ex); } catch (InvocationTargetException ex) { throw new CreationException(m, c, ex); } } } if (created instanceof InitListener) { if (listeners == null) { listeners = new ArrayList<InitListener>(); } InitListener l = (InitListener) created; l.beforeInit(this); // better late then never!! listeners.add(l); } return created; }
From source file:com.pastekit.twist.gae.GaeMarshaller.java
/** * * Create entity objects that can be persisted into the GAE Datastore, * including its Parent-Child relationships (if necessary). * * @param parent parent of the generated entity or Entities * @param instance to marshall/*w w w . j a va 2 s .c o m*/ * @return */ @Override public IdentityHashMap marshall(Key parent, Object instance) { if (instance == null) { throw new RuntimeException("Object cannot be null"); } Entity e = null; // Its possible that a Entity to be saved without id and just a parent key if (parent != null && hasNoIdField(instance)) { String kind = getKindOf(instance); e = new Entity(kind, parent); } else { Key key = createKeyFrom(parent, instance); // inspect kind and create key e = new Entity(key); } boolean indexed = !AnnotationUtil.isClassAnnotated(GaeObjectStore.unIndexed(), instance); Map<String, Object> props = new LinkedHashMap<String, Object>(); List<Entity> target = null; // Marshall java.util.Map if (instance instanceof Map) { Map map = (Map) instance; if (String.class.getName().equals(MapHelper.getKeyType(map))) { Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String entryKey = entry.getKey(); Object entryVal = entry.getValue(); if (!entryKey.equals(GaeObjectStore.KEY_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.KIND_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.NAMESPACE_RESERVED_PROPERTY)) { if (entryVal instanceof Map) { setProperty(e, entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { setProperty(e, entryKey, createEmbeddedEntityFromList((List) entryVal), indexed); } else { setProperty(e, entryKey, entryVal, indexed); } } } } else { throw new RuntimeException( String.class.getName() + " is the only supported " + Map.class.getName() + " key"); } } else { // Marshall all other object types Field[] fields = instance.getClass().getDeclaredFields(); GeoPt geoPt = null; for (Field field : fields) { if (target == null) { target = new LinkedList<Entity>(); } if ((field.getModifiers() & java.lang.reflect.Modifier.FINAL) == java.lang.reflect.Modifier.FINAL) { // do nothing for a final field // usually static UID fields continue; } String fieldName = field.getName(); if (field.isAnnotationPresent(GaeObjectStore.key())) { // skip continue; } else if (field.isAnnotationPresent(GaeObjectStore.kind())) { continue; } else if (field.isAnnotationPresent(Volatile.class)) { // skip continue; } try { boolean isAccessible = field.isAccessible(); field.setAccessible(true); Class<?> fieldType = field.getType(); Object fieldValue = field.get(instance); if (fieldValue == null) { e.setProperty(fieldName, null); } else if (fieldValue instanceof String) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Number || fieldValue instanceof Long || fieldValue instanceof Integer || fieldValue instanceof Short) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Boolean) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Date) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof User) { // GAE support this type setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof List) { LOG.debug("Processing List valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromList((List) fieldValue), indexed); } else { boolean supported = true; List list = (List) fieldValue; for (Object item : list) { if (!GAE_SUPPORTED_TYPES.contains(item.getClass())) { supported = false; } } if (supported) { setProperty(e, fieldName, fieldValue, indexed); } else { throw new RuntimeException("List should only include GAE supported types " + GAE_SUPPORTED_TYPES + " otherwise annotate the List with @Embedded"); } } } else if (fieldValue instanceof GeoPt) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Map) { LOG.debug("Processing Map valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromMap((Map) fieldValue), indexed); } else if (field.isAnnotationPresent(Flat.class)) { Map<String, Object> flat = (Map) fieldValue; Iterator<Map.Entry<String, Object>> it = flat.entrySet().iterator(); if (!it.hasNext()) { LOG.debug("Iterator is empty"); } while (it.hasNext()) { Object entry = it.next(); try { Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) entry; Object entryKey = mapEntry.getKey(); Object entryVal = mapEntry.getValue(); if (entryVal == null) { setProperty(e, (String) entryKey, null, indexed); } else if (entryVal instanceof Map) { setProperty(e, (String) entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { throw new RuntimeException("List values are not yet supported"); } else if (entryVal instanceof String || entryVal instanceof Number || entryVal instanceof Boolean || entryVal instanceof Date || entryVal instanceof User) { setProperty(e, (String) entryKey, entryVal, indexed); } else { throw new RuntimeException( "Unsupported GAE property type: " + entryVal.getClass().getName()); } if (e == null) { throw new RuntimeException("Entity is null"); } } catch (ClassCastException ex) { // Something is wrong here ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } } else { throw new TwistException("Map type should be annotated with @Embedded or @Flat"); } } else { // For primitives if (fieldType.equals(int.class)) { int i = (Integer) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(boolean.class)) { boolean i = (Boolean) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte i = (Byte) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(short.class)) { short i = (Short) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(long.class)) { long i = (Long) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(float.class)) { float i = (Float) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(double.class)) { double i = (Double) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte b = (byte) fieldValue; Blob blob = new Blob(new byte[b]); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(byte[].class)) { byte[] bytes = (byte[]) fieldValue; Blob blob = new Blob(bytes); setProperty(e, fieldName, blob, indexed); } else { // POJO if (field.isAnnotationPresent(Embedded.class)) { Map<String, Object> map = createMapFrom(fieldValue); EmbeddedEntity ee = createEmbeddedEntityFromMap(map); setProperty(e, fieldName, ee, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.parent())) { // @Parent first before @Child, don't switch. @Child needs parent Key. if (field.getType().equals(Key.class)) { // skip it continue; } else { if (parent != null) { // Case where a Parent entity is marshalled then during the // iteration process, a @Child entity is found Entity _target = new Entity(createKeyFrom(parent, instance)); _target.setPropertiesFrom(e); e = _target; } else { // Case where a Child entity is first marshalled // at this point this child is not yet in the stack // and the Parent entity is not yet also in the stack // so we will create a Key from the "not yet marshalled" parent instance // or is it not? Let's check. Object parentField = field.get(instance); Entity parentEntity = stack.get(parentField); if (parentEntity != null) { Entity _target = new Entity( createKeyFrom(parentEntity.getKey(), instance)); _target.setPropertiesFrom(e); e = _target; } else { Key generatedParentKey = createKeyFrom(null, parentField); Entity _target = new Entity( createKeyFrom(generatedParentKey, instance)); _target.setPropertiesFrom(e); e = _target; marshall(null, parentField); } } } } else if (field.isAnnotationPresent(GaeObjectStore.child())) { Object childField = field.get(instance); marshall(e.getKey(), childField); Entity childEntity = stack.get(childField); Key childEntityKey = childEntity.getKey(); setProperty(e, fieldName, childEntityKey, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.ancestor())) { // already processed above, skip it } else { throw new RuntimeException( "POJO's must be annotated with @Embedded, @Parent or @Child annotations for field " + fieldName); } } } field.setAccessible(isAccessible); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } } stack.put(instance, e); return stack; }
From source file:com.hunchee.twist.gae.GaeMarshaller.java
/** * * Create entity objects that can be persisted into the GAE Datastore, * including its Parent-Child relationships (if necessary). * * @param parent parent of the generated entity or Entities * @param instance to marshall//ww w .jav a 2s .c om * @return */ @Override public IdentityHashMap marshall(Key parent, Object instance) { if (instance == null) { throw new RuntimeException("Object cannot be null"); } Entity e = null; // Its possible that a Entity to be saved without id and just a parent key if (parent != null && hasNoIdField(instance)) { String kind = getKindOf(instance); e = new Entity(kind, parent); } else { Key key = createKeyFrom(parent, instance); // inspect kind and create key e = new Entity(key); } boolean indexed = !AnnotationUtil.isClassAnnotated(GaeObjectStore.unIndexed(), instance); Map<String, Object> props = new LinkedHashMap<String, Object>(); List<Entity> target = null; // Marshall java.util.Map if (instance instanceof Map) { Map map = (Map) instance; if (String.class.getName().equals(MapHelper.getKeyType(map))) { Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String entryKey = entry.getKey(); Object entryVal = entry.getValue(); if (!entryKey.equals(GaeObjectStore.KEY_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.KIND_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.NAMESPACE_RESERVED_PROPERTY)) { if (entryVal instanceof Map) { setProperty(e, entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { setProperty(e, entryKey, createEmbeddedEntityFromList((List) entryVal), indexed); } else { setProperty(e, entryKey, entryVal, indexed); } } } } else { throw new RuntimeException( String.class.getName() + " is the only supported " + Map.class.getName() + " key"); } } else { // Marshall all other object types Field[] fields = instance.getClass().getDeclaredFields(); GeoPt geoPt = null; for (Field field : fields) { if (target == null) { target = new LinkedList<Entity>(); } if ((field.getModifiers() & java.lang.reflect.Modifier.FINAL) == java.lang.reflect.Modifier.FINAL) { // do nothing for a final field // usually static UID fields continue; } String fieldName = field.getName(); if (field.isAnnotationPresent(GaeObjectStore.key())) { // skip continue; } else if (field.isAnnotationPresent(GaeObjectStore.kind())) { continue; } else if (field.isAnnotationPresent(Volatile.class)) { // skip continue; } try { boolean isAccessible = field.isAccessible(); field.setAccessible(true); Class<?> fieldType = field.getType(); Object fieldValue = field.get(instance); if (fieldValue == null) { e.setProperty(fieldName, null); } else if (fieldValue instanceof String) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Number || fieldValue instanceof Long || fieldValue instanceof Integer || fieldValue instanceof Short) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Boolean) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Date) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof User) { // GAE support this type setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Blob) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof List) { LOG.debug("Processing List valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromList((List) fieldValue), indexed); } else { boolean supported = true; List list = (List) fieldValue; for (Object item : list) { if (!GAE_SUPPORTED_TYPES.contains(item.getClass())) { supported = false; } } if (supported) { setProperty(e, fieldName, fieldValue, indexed); } else { throw new RuntimeException("List should only include GAE supported types " + GAE_SUPPORTED_TYPES + " otherwise annotate the List with @Embedded"); } } } else if (fieldValue instanceof GeoPt) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Enum) { String enumValue = fieldValue.toString(); LOG.info("Enum marshalled as \"" + enumValue + "\""); setProperty(e, fieldName, enumValue, indexed); } else if (fieldValue instanceof Map) { LOG.debug("Processing Map valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromMap((Map) fieldValue), indexed); } else if (field.isAnnotationPresent(Flat.class)) { Map<String, Object> flat = (Map) fieldValue; Iterator<Map.Entry<String, Object>> it = flat.entrySet().iterator(); if (!it.hasNext()) { LOG.debug("Iterator is empty"); } while (it.hasNext()) { Object entry = it.next(); try { Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) entry; Object entryKey = mapEntry.getKey(); Object entryVal = mapEntry.getValue(); if (entryVal == null) { setProperty(e, (String) entryKey, null, indexed); } else if (entryVal instanceof Map) { setProperty(e, (String) entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { throw new RuntimeException("List values are not yet supported"); } else if (entryVal instanceof String || entryVal instanceof Number || entryVal instanceof Boolean || entryVal instanceof Date || entryVal instanceof User) { setProperty(e, (String) entryKey, entryVal, indexed); } else { throw new RuntimeException( "Unsupported GAE property type: " + entryVal.getClass().getName()); } if (e == null) { throw new RuntimeException("Entity is null"); } } catch (ClassCastException ex) { // Something is wrong here ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } } else { throw new TwistException("Map type should be annotated with @Embedded or @Flat"); } } else { // For primitives if (fieldType.equals(int.class)) { int i = (Integer) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(boolean.class)) { boolean i = (Boolean) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte i = (Byte) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(short.class)) { short i = (Short) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(long.class)) { long i = (Long) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(float.class)) { float i = (Float) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(double.class)) { double i = (Double) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte b = (byte) fieldValue; Blob blob = new Blob(new byte[b]); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(byte[].class)) { byte[] bytes = (byte[]) fieldValue; Blob blob = new Blob(bytes); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(Enum.class)) { throw new RuntimeException("Enum primitive type not yet implemented"); } else { // POJO if (field.isAnnotationPresent(Embedded.class)) { Map<String, Object> map = createMapFrom(fieldValue); EmbeddedEntity ee = createEmbeddedEntityFromMap(map); setProperty(e, fieldName, ee, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.parent())) { // @Parent first before @Child, don't switch. @Child needs parent Key. if (field.getType().equals(Key.class)) { // skip it continue; } else { if (parent != null) { // Case where a Parent entity is marshalled then during the // iteration process, a @Child entity is found Entity _target = new Entity(createKeyFrom(parent, instance)); _target.setPropertiesFrom(e); e = _target; } else { // Case where a Child entity is first marshalled // at this point this child is not yet in the stack // and the Parent entity is not yet also in the stack // so we will create a Key from the "not yet marshalled" parent instance // or is it not? Let's check. Object parentField = field.get(instance); Entity parentEntity = stack.get(parentField); if (parentEntity != null) { Entity _target = new Entity( createKeyFrom(parentEntity.getKey(), instance)); _target.setPropertiesFrom(e); e = _target; } else { Key generatedParentKey = createKeyFrom(null, parentField); Entity _target = new Entity( createKeyFrom(generatedParentKey, instance)); _target.setPropertiesFrom(e); e = _target; marshall(null, parentField); } } } } else if (field.isAnnotationPresent(GaeObjectStore.child())) { Object childField = field.get(instance); marshall(e.getKey(), childField); Entity childEntity = stack.get(childField); Key childEntityKey = childEntity.getKey(); setProperty(e, fieldName, childEntityKey, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.ancestor())) { // already processed above, skip it } else { throw new RuntimeException( "POJO's must be annotated with @Embedded, @Parent or @Child annotations for field " + fieldName); } } } field.setAccessible(isAccessible); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } } stack.put(instance, e); return stack; }