Example usage for java.lang.reflect Field isAnnotationPresent

List of usage examples for java.lang.reflect Field isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect Field isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.madrobot.di.wizard.json.JSONDeserializer.java

/**
 * Deserialize a specific element, recursively.
 * /*from  w  ww . j  av  a  2 s.  c  om*/
 * @param obj
 *            Object whose fields need to be set
 * @param jsonObject
 *            JSON Parser to read data from
 * @param stack
 *            Stack of {@link ClassInfo} - entity type under consideration
 * @throws JSONException
 *             If an exception occurs during parsing
 */
private void deserialize(Object obj, JSONObject jsonObject, Stack<Class<?>> stack) throws JSONException {

    Iterator<?> iterator = jsonObject.keys();
    Class<?> userClass = stack.peek();

    while (iterator.hasNext()) {
        Object jsonKey = iterator.next();

        if (jsonKey instanceof String) {
            String key = (String) jsonKey;
            Object jsonElement = jsonObject.get(key);

            try {

                Field field = getField(userClass, key);
                String fieldName = field.getName();
                Class<?> classType = field.getType();

                if (jsonElement instanceof JSONObject) {
                    if (!Converter.isPseudoPrimitive(classType)) {

                        String setMethodName = getSetMethodName(fieldName, classType);
                        Method setMethod = userClass.getDeclaredMethod(setMethodName, classType);

                        JSONObject fieldObject = (JSONObject) jsonElement;

                        stack.push(classType);
                        Object itemObj = classType.newInstance();
                        deserialize(itemObj, fieldObject, stack);

                        setMethod.invoke(obj, itemObj);
                    } else {
                        Log.e(TAG, "Expecting composite type for " + fieldName);
                    }
                } else if (jsonElement instanceof JSONArray) {
                    if (Converter.isCollectionType(classType)) {
                        if (field.isAnnotationPresent(ItemType.class)) {
                            ItemType itemType = field.getAnnotation(ItemType.class);
                            Class<?> itemValueType = itemType.value();
                            int size = itemType.size();

                            JSONArray fieldArrayObject = (JSONArray) jsonElement;

                            if (size == JSONDeserializer.DEFAULT_ITEM_COLLECTION_SIZE
                                    || size > fieldArrayObject.length()) {
                                size = fieldArrayObject.length();
                            }

                            for (int index = 0; index < size; index++) {
                                Object value = fieldArrayObject.get(index);
                                if (value instanceof JSONObject) {
                                    stack.push(itemValueType);
                                    Object itemObj = itemValueType.newInstance();
                                    deserialize(itemObj, (JSONObject) value, stack);

                                    String addMethodName = getAddMethodName(fieldName);
                                    Method addMethod = userClass.getDeclaredMethod(addMethodName,
                                            itemValueType);
                                    addMethod.invoke(obj, itemObj);
                                }
                            }
                        }
                    } else {
                        Log.e(TAG, "Expecting collection type for " + fieldName);
                    }
                } else if (Converter.isPseudoPrimitive(classType)) {

                    Object value = Converter.convertTo(jsonObject, key, classType, field);

                    String setMethodName = getSetMethodName(fieldName, classType);
                    Method setMethod = userClass.getDeclaredMethod(setMethodName, classType);
                    setMethod.invoke(obj, value);
                } else {
                    Log.e(TAG, "Unknown datatype");
                }

            } catch (NoSuchFieldException e) {
                Log.e(TAG, e.getMessage());
            } catch (NoSuchMethodException e) {
                Log.e(TAG, e.getMessage());
            } catch (IllegalAccessException e) {
                Log.e(TAG, e.getMessage());
            } catch (InvocationTargetException e) {
                Log.e(TAG, e.getMessage());
            } catch (InstantiationException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }
}

From source file:adalid.core.AbstractPersistentEntity.java

private void annotateForeignKey(Field field) {
    _annotatedWithForeignKey = field.isAnnotationPresent(ForeignKey.class);
    if (_annotatedWithForeignKey) {
        ForeignKey annotation = field.getAnnotation(ForeignKey.class);
        _onDeleteAction = annotation.onDelete();
        _onUpdateAction = annotation.onUpdate();
    }/* ww  w  .j  ava  2 s. com*/
}

From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

private String lookupIdFromIndex(String indexedValue, String fieldName, String indexName)
        throws RuntimeException {
    try {//from w w w  .  jav  a2  s.  c  om
        RedissonIndex index = null;
        Field field = cls.getDeclaredField(fieldName);
        if (field.isAnnotationPresent(RedissonIndex.List.class)) {
            RedissonIndex.List list = field.getAnnotation(RedissonIndex.List.class);
            index = Arrays.stream(list.value()).filter(r -> r.name().equals(indexName)).findFirst().get();
        }
        if (field.isAnnotationPresent(RedissonIndex.class)) {
            index = field.getAnnotation(RedissonIndex.class);
            if (!index.name().equals(indexName)) {
                throw new NoSuchElementException("Index not found: " + indexName);
            }
        }
        if (index == null) {
            throw new NoSuchElementException();
        }
        return index.valueResolver().newInstance().lookup(indexedValue, index);
    } catch (NoSuchFieldException | SecurityException | InstantiationException | IllegalAccessException
            | NoSuchElementException e) {
        throw new RuntimeException("Can not find index " + indexName + " for field " + fieldName
                + " under class " + cls.getCanonicalName() + " to resolve value " + indexedValue, e);
    }
}

From source file:com.quangphuong.crawler.dbutil.DBWrapper.java

public Object getEntityByCondition(Object entity) {
    String sql = selectAll.concat(entity.getClass().getSimpleName());
    sql = sql.concat(whereClause);/* w w  w.j ava2  s  . co m*/
    Connection con = null;
    if (this.isDisconnect) {
        con = DBHandler.openConnection();
    }
    Object result = null;
    try {
        Statement statement;
        if (this.isDisconnect) {
            statement = con.createStatement();
        } else {
            statement = connection.createStatement();
        }
        Field[] attributes = entity.getClass().getDeclaredFields();
        int count = 0;
        for (Field attribute : attributes) {
            attribute.setAccessible(true);
            if (attribute.get(entity) != null) {
                String value = attribute.get(entity).toString();

                if (count == 0) {
                    sql = sql.concat(attribute.getName() + "=" + "\'" + value + "\'");
                } else {
                    sql = sql.concat(" AND " + attribute.getName() + "=" + "\'" + value + "\'");
                }
                count++;
            }
        }
        System.out.println(sql);
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            List<Object> listFields = new ArrayList();
            List<Class<?>> listFieldTypes = new ArrayList();
            for (Field attribute : attributes) {
                if (!attribute.isAnnotationPresent(Ignore.class)) {
                    Object obj = resultSet.getObject(attribute.getName());
                    listFields.add(obj);
                    listFieldTypes.add(attribute.getType());
                }
            }
            result = entity.getClass().getConstructor((Class<?>[]) listFieldTypes.toArray(new Class[0]))
                    .newInstance(listFields.toArray());
        }
    } catch (Exception ex) {
        Logger.getLogger(DBWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (this.isDisconnect && con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:adalid.core.EntityAtlas.java

@SuppressWarnings("deprecation")
void initialiseFields(Class<?> clazz) {
    track("initialiseFields", _declaringArtifact, clazz.getSimpleName());
    Class<?> c;//from  ww w. j a  va2s. c  om
    int d, r;
    String name;
    String key;
    String pattern = "there are several fields for operation {0}";
    String message;
    Class<?> type;
    Class<?> decl;
    Class<?> operationClass;
    Field operationField;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = _declaringArtifact.depth();
    int round = _declaringArtifact.round();
    Class<?>[] classes = new Class<?>[] { Property.class, Key.class, Tab.class, View.class, Instance.class,
            NamedValue.class, Expression.class, Transition.class, Operation.class, Trigger.class };
    Class<?> dac = _declaringArtifact.getClass();
    Class<?> top = Entity.class;
    int i = ArrayUtils.indexOf(classes, clazz);
    if (i != ArrayUtils.INDEX_NOT_FOUND) {
        c = classes[i];
        for (Field field : XS1.getFields(dac, top)) {
            field.setAccessible(true);
            logger.trace(field);
            name = field.getName();
            type = field.getType();
            decl = field.getDeclaringClass();
            if (!c.isAssignableFrom(type)) {
                continue;
            }
            if (c.equals(Expression.class) && Property.class.isAssignableFrom(type)) {
                continue;
            }
            // TODO: extension handling
            if (field.isAnnotationPresent(Extension.class) && Entity.class.isAssignableFrom(type)) {
                //                  if (!dac.equals(decl) || !dac.isAssignableFrom(type)) {
                //                      continue;
                //                  }
                continue;
            }
            modifiers = type.getModifiers();
            if (NamedValue.class.isAssignableFrom(type) || Expression.class.isAssignableFrom(type)) {
                restricted = false;
            } else {
                restricted = type.isInterface() || Modifier.isAbstract(modifiers);
            }
            restricted = restricted || !Modifier.isPublic(modifiers);
            if (restricted) {
                continue;
            }
            modifiers = field.getModifiers();
            restricted = Modifier.isPrivate(modifiers);
            if (restricted) {
                continue;
            }
            restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
            if (restricted) {
                continue;
            }
            if (Operation.class.isAssignableFrom(type)) {
                key = type.getSimpleName();
                operationClass = _operationClasses.get(key);
                if (operationClass != null) {
                    operationField = _operationFields.get(key);
                    if (operationField == null) {
                        _operationFields.put(key, field);
                    } else {
                        message = MessageFormat.format(pattern, operationClass.getName());
                        logger.warn(message);
                        TLC.getProject().getParser().increaseWarningCount();
                    }
                }
            }
            String errmsg = "failed to create a new instance of field \"" + field + "\" at "
                    + _declaringArtifact;
            try {
                o = field.get(_declaringArtifact);
                if (o == null) {
                    logger.debug(message(type, name, o, depth, round));
                    o = XS1.initialiseField(_declaringArtifact, field);
                    if (o == null) {
                        logger.debug(message(type, name, o, depth, round));
                        //                          throw new RuntimeException(message(type, name, o, depth, round));
                    } else {
                        logger.debug(message(type, name, o, depth, round));
                        field.set(_declaringArtifact, o);
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new InstantiationRuntimeException(errmsg, ex);
            }
        }
    }
}

From source file:com.impetus.client.cassandra.query.CassQuery.java

/**
 * Builds where Clause./*www.  jav a2 s .com*/
 * 
 * @param kunderaQuery
 *            the kundera query
 * @param metadata
 *            the metadata
 * @param metaModel
 *            the meta model
 * @param translator
 *            the translator
 * @param builder
 *            the builder
 */
private void buildWhereClause(KunderaQuery kunderaQuery, EntityMetadata metadata, MetamodelImpl metaModel,
        CQLTranslator translator, StringBuilder builder) {
    for (Object clause : kunderaQuery.getFilterClauseQueue()) {
        FilterClause filterClause = (FilterClause) clause;
        Field f = (Field) metaModel.entity(metadata.getEntityClazz())
                .getAttribute(metadata.getFieldName(filterClause.getProperty())).getJavaMember();
        String jpaColumnName = getColumnName(metadata, filterClause.getProperty());

        if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
            Field[] fields = metadata.getIdAttribute().getBindableJavaType().getDeclaredFields();
            EmbeddableType compoundKey = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType());
            for (Field field : fields) {
                if (field != null && !Modifier.isStatic(field.getModifiers())
                        && !Modifier.isTransient(field.getModifiers())
                        && !field.isAnnotationPresent(Transient.class)) {
                    Attribute attribute = compoundKey.getAttribute(field.getName());
                    String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
                    Object value = PropertyAccessorHelper.getObject(filterClause.getValue().get(0), field);
                    // TODO
                    translator.buildWhereClause(builder, field.getType(), columnName, value,
                            filterClause.getCondition(), false);
                }
            }
        } else {
            translator.buildWhereClause(builder, f.getType(), jpaColumnName, filterClause.getValue().get(0),
                    filterClause.getCondition(), false);
        }
    }
    builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());
}

From source file:org.apache.tomee.embedded.TomEEEmbeddedApplicationRunner.java

public void composerInject(final Object target) throws IllegalAccessException {
    WebBeansContext webBeansContext = null;
    try {/* ww  w.jav  a  2  s  .co m*/
        webBeansContext = WebBeansContext.currentInstance();
    } catch (final IllegalStateException ise) {
        // no-op
    }
    if (webBeansContext != null) {
        OWBInjector.inject(webBeansContext.getBeanManagerImpl(), target, null);
    }

    Class<?> aClass = target.getClass();
    while (aClass != null && aClass != Object.class) {
        for (final Field f : aClass.getDeclaredFields()) {
            final RandomPort randomPort = f.getAnnotation(RandomPort.class);
            if (randomPort != null) {
                for (final Field field : app.getClass().getDeclaredFields()) {
                    final RandomPort appPort = field.getAnnotation(RandomPort.class);
                    if (field.getType() == f.getType() && appPort != null
                            && appPort.value().equals(randomPort.value())) {
                        if (!field.isAccessible()) {
                            field.setAccessible(true);
                        }
                        if (!f.isAccessible()) {
                            f.setAccessible(true);
                        }

                        final Object value = field.get(app);
                        f.set(target, value);
                        break;
                    }
                }
            } else if (f.isAnnotationPresent(Application.class)) {
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
                f.set(target, app);
            } else if (f.isAnnotationPresent(LifecycleTask.class)) {
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
                final LifecycleTaskAccessor accessor = SystemInstance.get()
                        .getComponent(LifecycleTaskAccessor.class);
                final Class type = f.getType();
                final Object taskByType = accessor.getTaskByType(type);
                f.set(target, taskByType);
            } else if (f.isAnnotationPresent(Args.class)) {
                if (String[].class != f.getType()) {
                    throw new IllegalArgumentException(
                            "@Args can only be used for String[] field, not on " + f.getType());
                }
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
                final TomEEEmbeddedArgs args = SystemInstance.get().getComponent(TomEEEmbeddedArgs.class);
                f.set(target, args == null ? new String[0] : args.getArgs());
            }
        }
        aClass = aClass.getSuperclass();
    }

    SystemInstance.get().fireEvent(new TomEEEmbeddedApplicationRunnerInjection(target));
}

From source file:net.zcarioca.zcommons.config.data.BeanPropertySetterFactory.java

/**
 * Gets a collection of {@link BeanPropertySetter} to configure the bean.
 *
 * @param bean The bean to configure.//from  w ww. ja va 2s .c  om
 * @return Returns a collection of {@link BeanPropertySetter}.
 * @throws ConfigurationException
 */
public Collection<BeanPropertySetter> getPropertySettersForBean(Object bean) throws ConfigurationException {
    List<BeanPropertySetter> setters = new ArrayList<BeanPropertySetter>();
    Map<String, PropertyDescriptor> descriptors = new HashMap<String, PropertyDescriptor>();

    Class<?> beanClass = bean.getClass();

    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
            Method reader = desc.getReadMethod();
            Method writer = desc.getWriteMethod();
            Field field = getField(beanClass, desc);

            if (reader != null) {
                descriptors.put(desc.getDisplayName(), desc);
            }

            if (writer != null) {
                if (writer.isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            writer.getAnnotation(ConfigurableAttribute.class)));
                    descriptors.remove(desc.getDisplayName());
                }
                if (reader != null && reader.isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            reader.getAnnotation(ConfigurableAttribute.class)));
                    descriptors.remove(desc.getDisplayName());
                }
            }
        }
    } catch (Throwable t) {
        throw new ConfigurationException("Could not introspect bean class", t);
    }
    do {
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ConfigurableAttribute.class)) {
                if (descriptors.containsKey(field.getName())
                        && descriptors.get(field.getName()).getWriteMethod() != null) {
                    PropertyDescriptor desc = descriptors.get(field.getName());
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            field.getAnnotation(ConfigurableAttribute.class)));
                } else {
                    setters.add(new FieldBeanPropertySetter(bean, null, field,
                            field.getAnnotation(ConfigurableAttribute.class)));
                }
            } else if (descriptors.containsKey(field.getName())) {
                // the annotation may have been set on the getter, not the field
                PropertyDescriptor desc = descriptors.get(field.getName());
                if (desc.getReadMethod().isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new FieldBeanPropertySetter(bean, desc, field,
                            desc.getReadMethod().getAnnotation(ConfigurableAttribute.class)));
                }
            }
        }
    } while ((beanClass = beanClass.getSuperclass()) != null);
    return setters;
}

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  va2 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/*from  w  ww. j ava  2s .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 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;
}