Example usage for org.apache.commons.beanutils BeanMap getType

List of usage examples for org.apache.commons.beanutils BeanMap getType

Introduction

In this page you can find the example usage for org.apache.commons.beanutils BeanMap getType.

Prototype

public Class getType(String name) 

Source Link

Document

Returns the type of the property with the given name.

Usage

From source file:br.com.ingenieux.mojo.aws.AbstractAWSMojo.java

protected void displayResults(Object result, int level) {
    if (null == result) {
        return;/*  www .  j a va  2 s .c  om*/
    }

    String prefix = StringUtils.repeat(" ", level * 2) + " * ";

    if (Collection.class.isAssignableFrom(result.getClass())) {
        @SuppressWarnings("unchecked")
        Collection<Object> coll = Collection.class.cast(result);

        for (Object o : coll) {
            displayResults(o, 1 + level);
        }

        return;
    } else if ("java.lang".equals(result.getClass().getPackage().getName())) {
        getLog().info(prefix + CredentialsUtil.redact("" + result) + " [class: "
                + result.getClass().getSimpleName() + "]");

        return;
    }

    BeanMap beanMap = new BeanMap(result);

    for (Iterator<?> itProperty = beanMap.keyIterator(); itProperty.hasNext();) {
        String propertyName = "" + itProperty.next();
        Object propertyValue = beanMap.get(propertyName);

        if ("class".equals(propertyName)) {
            continue;
        }

        if (null == propertyValue) {
            continue;
        }

        Class<?> propertyClass = null;

        try {
            propertyClass = beanMap.getType(propertyName);
        } catch (Exception e) {
            getLog().warn("Failure on property " + propertyName, e);
        }

        if (null == propertyClass) {
            getLog().info(prefix + propertyName + ": " + CredentialsUtil.redact("" + propertyValue));
        } else {
            getLog().info(prefix + propertyName + ": " + CredentialsUtil.redact("" + propertyValue)
                    + " [class: " + propertyClass.getSimpleName() + "]");
        }
    }
}

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

private T mapResults(T instance, List results, ArrayList<String> pList)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException {
    pList.parallelStream().forEach(e -> {
        Object o = instance;//  ww w. ja  v a 2s .c  o m
        for (String fieldName : e.split("\\.")) {
            BeanMap m = new BeanMap(o);
            Class type = m.getType(fieldName);
            if (isRedisEntity(type)) {
                o = m.get(fieldName);
            } else {
                Object value;
                Object result = results.get(pList.indexOf(e));
                if (result == null) {
                    value = null;
                } else if (String.class.isAssignableFrom(type)) {
                    value = result.toString();
                } else if (type.isEnum()) {
                    try {
                        value = type.getMethod("valueOf", String.class).invoke(null,
                                results.get(pList.indexOf(e)));
                    } catch (NoSuchMethodException | SecurityException | IllegalAccessException
                            | IllegalArgumentException | InvocationTargetException ex) {
                        throw new IllegalArgumentException(ex);
                    }
                } else if (result.getClass().isAssignableFrom(type)) {
                    value = type.cast(result);
                } else {
                    try {
                        value = type.getConstructor(result.getClass()).newInstance(result);
                    } catch (NoSuchMethodException | SecurityException | InstantiationException
                            | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException ex) {
                        throw new IllegalArgumentException(ex);
                    }
                }
                m.put(fieldName, value);
            }
        }
    });
    return instance;
}

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

private T prepareInstanceAndFetchList(String id, RBatch redissonBatch, ArrayList<String> pList, String parent,
        Boolean deepFetch) throws InstantiationException, IllegalAccessException {
    BeanMap pMap = new BeanMap(cls.newInstance());
    try {//from   ww w  .  j  a  v  a  2s .c  o  m
        pMap.keySet().forEach(e -> {
            if ("class".equals(e)) {
                return;
            }
            Class type = pMap.getType(e.toString());
            String fieldName = (parent == null ? "" : parent.concat(".")).concat(e.toString());
            if (isRedisEntity(type)) {
                if (deepFetch) {
                    try {
                        RedisRepositoryImpl innerRepo = (RedisRepositoryImpl) factory.instance(type);
                        pMap.put(e.toString(), innerRepo.prepareInstanceAndFetchList(id, redissonBatch, pList,
                                fieldName, deepFetch));
                    } catch (InstantiationException | IllegalAccessException | RepositoryException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            } else {
                if ("id".equals(e)) {
                    redissonBatch.getMap(getStorageKey(), StringCodec.INSTANCE).getAsync(id);
                } else {
                    redissonBatch.getMap(getStorageKey(e.toString())).getAsync(id);
                }
                pList.add(fieldName);
            }
        });
    } catch (RuntimeException ex) {
        throw new InstantiationException();
    }
    return (T) pMap.getBean();
}

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

private void prepareEnsureUnique(String id, JsonObject instance, RBatch redissonBatch, ArrayList<String> pList,
        String parent) throws RepositoryException {
    try {/*from  w ww.j a  va 2 s.  co m*/
        BeanMap pMap = new BeanMap(cls.newInstance());
        pMap.keySet().forEach(e -> {
            if ("class".equals(e) || instance.getValue(e.toString()) == null) {
                return;
            }
            Class type = pMap.getType(e.toString());
            String fieldName = (parent == null ? "" : parent.concat(".")).concat(e.toString());
            if (isRedisEntity(type)) {
                try {
                    RedisRepositoryImpl innerRepo = (RedisRepositoryImpl) factory.instance(type);
                    innerRepo.prepareEnsureUnique(id, instance.getJsonObject(e.toString()), redissonBatch,
                            pList, fieldName);
                } catch (RepositoryException ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                try {
                    if (cls.getDeclaredField(e.toString()).isAnnotationPresent(RedissonUnique.class)) {
                        redissonBatch.getMap(getUniqueKey(e.toString()))
                                .putIfAbsentAsync(instance.getValue(e.toString()), id);
                        pList.add(fieldName);
                    }
                } catch (NoSuchFieldException | SecurityException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
    } catch (InstantiationException | IllegalAccessException | RuntimeException ex) {
        throw new RepositoryException(ex);
    }
}

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

private void prepareUndoUnique(String id, JsonObject instance, RBatch redissonBatch, ArrayList<String> pList,
        String parent) throws RepositoryException {
    try {//from   w  ww.j  a  va 2  s. c  om
        BeanMap pMap = new BeanMap(cls.newInstance());
        pMap.keySet().forEach(e -> {
            if ("class".equals(e) || instance.getValue(e.toString()) == null) {
                return;
            }
            Class type = pMap.getType(e.toString());
            String fieldName = (parent == null ? "" : parent.concat(".")).concat(e.toString());
            if (isRedisEntity(type)) {
                try {
                    RedisRepositoryImpl innerRepo = (RedisRepositoryImpl) factory.instance(type);
                    innerRepo.prepareUndoUnique(id, instance.getJsonObject(e.toString()), redissonBatch, pList,
                            fieldName);
                } catch (RepositoryException ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                try {
                    if (cls.getDeclaredField(e.toString()).isAnnotationPresent(RedissonUnique.class)
                            && pList.contains(fieldName)) {
                        redissonBatch.getMap(getUniqueKey(e.toString()))
                                .removeAsync(instance.getValue(e.toString()), id);
                    }
                } catch (NoSuchFieldException | SecurityException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
    } catch (InstantiationException | IllegalAccessException | RuntimeException ex) {
        throw new RepositoryException(ex);
    }
}

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

private void prepareEnsuerIndex(String id, T r, JsonObject instance, Boolean isNew, RBatch redissonBatch,
        ArrayList<String> pList, String parent) throws RepositoryException {
    try {/*from  w ww  . j a v  a 2 s  .  co m*/
        BeanMap pMap = new BeanMap(r == null ? cls.newInstance() : r);
        pMap.keySet().forEach(e -> {
            if ("class".equals(e) || instance.getValue(e.toString()) == null) {
                return;
            }
            Class type = pMap.getType(e.toString());
            String fieldName = (parent == null ? "" : parent.concat(".")).concat(e.toString());
            if (isRedisEntity(type)) {
                try {
                    RedisRepositoryImpl innerRepo = (RedisRepositoryImpl) factory.instance(type);
                    innerRepo.prepareEnsuerIndex(id, pMap.get(e), instance.getJsonObject(e.toString()), isNew,
                            redissonBatch, pList, fieldName);
                } catch (RepositoryException ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                try {
                    if (cls.getDeclaredField(e.toString()).isAnnotationPresent(RedissonIndex.class)) {
                        RedissonIndex index = cls.getDeclaredField(e.toString())
                                .getAnnotation(RedissonIndex.class);
                        if (index.indexOnSave()) {
                            prepareEnsuerIndex(id, r, instance, redissonBatch, index, e.toString(),
                                    pMap.get(e));
                        }
                    } else if (cls.getDeclaredField(e.toString())
                            .isAnnotationPresent(RedissonIndex.List.class)) {
                        RedissonIndex.List indexList = cls.getDeclaredField(e.toString())
                                .getAnnotation(RedissonIndex.List.class);
                        Arrays.stream(indexList.value()).filter(f -> f.indexOnSave())
                                .forEach(index -> prepareEnsuerIndex(id, r, instance, redissonBatch, index,
                                        e.toString(), pMap.get(e)));
                    }
                    if (cls.getDeclaredField(e.toString()).isAnnotationPresent(RedissonCounter.class)) {
                        RedissonCounter counter = cls.getDeclaredField(e.toString())
                                .getAnnotation(RedissonCounter.class);
                        prepareEnsuerCounter(id, r, instance, isNew, redissonBatch, counter, e.toString(),
                                pMap.get(e));
                    } else if (cls.getDeclaredField(e.toString())
                            .isAnnotationPresent(RedissonCounter.List.class)) {
                        RedissonCounter.List counterList = cls.getDeclaredField(e.toString())
                                .getAnnotation(RedissonCounter.List.class);
                        Arrays.stream(counterList.value()).forEach(index -> prepareEnsuerCounter(id, r,
                                instance, isNew, redissonBatch, index, e.toString(), pMap.get(e)));
                    }
                } catch (NoSuchFieldException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
    } catch (InstantiationException | IllegalAccessException | RuntimeException ex) {
        throw new RepositoryException(ex);
    }
}

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

private void persistBlocking(String id, JsonObject data, RBatch redissonBatch,
        Handler<AsyncResult<Boolean>> resultHandler) {
    RBatch batch = redissonBatch == null ? redissonWrite.createBatch() : redissonBatch;
    AtomicBoolean failed = new AtomicBoolean(false);
    try {/*w w  w .  j a v a2s  .co m*/
        BeanMap pMap = new BeanMap(cls.newInstance());
        //remove the indexes;
        if (isRedisEntity()) {
            AtomicBoolean finished = new AtomicBoolean(false);
            AtomicBoolean hasNested = new AtomicBoolean(false);
            AtomicLong stack = new AtomicLong();
            pMap.forEach((k, v) -> {
                if ("class".equals(k)) {
                    return;
                }
                Class<?> type = pMap.getType((String) k);
                if (!isRedisEntity(type)) {
                    //recreate the indexes;
                    if ("id".equals(k)) {
                        batch.getMap(getStorageKey(), StringCodec.INSTANCE).fastPutAsync(id, id);
                    } else {
                        batch.getMap(getStorageKey((String) k)).fastPutAsync(id, data.getValue((String) k));
                    }
                } else {
                    hasNested.set(true);
                    stack.incrementAndGet();
                    RedisRepositoryImpl<?> innerRepo;
                    try {
                        innerRepo = (RedisRepositoryImpl) factory.instance(type);
                    } catch (RepositoryException e) {
                        throw new RuntimeException(e);
                    }
                    JsonObject value = data.getJsonObject((String) k);
                    final boolean newOne = !value.containsKey("id") || value.getString("id") == null
                            || "null".equals(value.getString("id"));
                    final String ID = newOne ? id : value.getString("id");
                    innerRepo.persist(ID, value, batch, c -> {//making the nested entity shares the same id as the parent when its 1:1 relation. This makes fetch a lot faster since it doesn't not need to resolve the reference when fetching 1:1 nested objects.
                        if (c.succeeded()) {
                            long s = stack.decrementAndGet();
                            if (newOne) {
                                batch.getMap(getStorageKey((String) k)).fastPutAsync(id, ID);//different to the update, create needs to add the reference field to batch
                            }
                            if (s == 0 && finished.get() && !failed.get()) { //finished iterating and no outstanding processes. 
                                if (redissonBatch == null) {//if it's not inside a nested process.
                                    finishPersist(id, data, batch, resultHandler);
                                } else {//if it is inside a nested process.
                                    resultHandler.handle(Future.succeededFuture(true));
                                }
                            }
                            //else wait for others to complete
                        } else {
                            boolean firstToFail = failed.compareAndSet(false, true);
                            if (firstToFail) {
                                resultHandler.handle(Future.failedFuture(c.cause()));
                            }
                        }
                    });
                }
            });
            batch.getAtomicLongAsync(getCounterKey()).incrementAndGetAsync();
            finished.set(true);
            if (!hasNested.get()) {//does not have nested RedissonEntity within
                if (redissonBatch == null) {//if it's not inside a nested process.
                    finishPersist(id, data, batch, resultHandler);
                } else {//if it is inside a nested process.
                    resultHandler.handle(Future.succeededFuture(true));
                }
            }
        } else {//not a RedissonEntity class, persist as json string.
            //recreate the indexes;
            batch.<String, String>getMap(getStorageKey(), StringCodec.INSTANCE).fastPutAsync(id,
                    Json.encode(data));
            batch.getAtomicLongAsync(getCounterKey()).incrementAndGetAsync();
            if (redissonBatch == null) {//if it's not inside a nested process.
                finishPersist(id, data, batch, resultHandler);
            } else {//if it is inside a nested process.
                resultHandler.handle(Future.succeededFuture(true));
            }
        }
    } catch (InstantiationException | IllegalAccessException | RuntimeException ex) {
        failed.set(true);
        resultHandler.handle(Future.failedFuture(ex));
    }
}

From source file:org.ms123.common.data.JdoLayerImpl.java

public void populate(SessionContext sessionContext, Map from, Object to, Map hintsMap) {
    PersistenceManager pm = sessionContext.getPM();
    if (hintsMap == null) {
        hintsMap = new HashMap();
    }//from www.jav a2 s .c o m
    Map<String, String> expressions = (Map) hintsMap.get("__expressions");
    if (expressions == null)
        expressions = new HashMap();
    BeanMap beanMap = new BeanMap(to);
    String entityName = m_inflector.getEntityName(to.getClass().getSimpleName());
    debug("populate.from:" + from + ",to:" + to + ",BeanMap:" + beanMap + "/hintsMap:" + hintsMap
            + "/entityName:" + entityName);
    if (from == null) {
        return;
    }
    Map permittedFields = sessionContext.getPermittedFields(entityName, "write");
    Iterator<String> it = from.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        Object oldValue = beanMap.get(key);
        boolean permitted = m_permissionService.hasAdminRole() || "team".equals(entityName)
                || sessionContext.isFieldPermitted(key, entityName, "write");
        if (!key.startsWith("_") && !permitted) {
            debug("---->populate:field(" + key + ") no write permission");
            continue;
        } else {
            debug("++++>populate:field(" + key + ") write permitted");
        }
        String datatype = null;
        String edittype = null;
        if (!key.startsWith("_")) {
            Map config = (Map) permittedFields.get(key);
            if (config != null) {
                datatype = (String) config.get("datatype");
                edittype = (String) config.get("edittype");
            }
        }

        if (key.equals(STATE_FIELD) && !m_permissionService.hasAdminRole()) {
            continue;
        }
        if ("auto".equals(edittype))
            continue;
        String mode = null;
        Map hm = (Map) hintsMap.get(key);
        if (hm != null) {
            Object m = hm.get("mode");
            if (m != null && m instanceof String) {
                mode = (String) m;
            }
            if (mode == null) {
                m = hm.get("useit");
                if (m != null && m instanceof String) {
                    mode = (String) m;
                }
            }
        }
        if (mode == null) {
            mode = "replace";
        }
        Class clazz = beanMap.getType(key);
        debug("\ttype:" + clazz + "(" + key + "=" + from.get(key) + ")");
        if ("_ignore_".equals(from.get(key))) {
            continue;
        }
        if (clazz == null) {
            debug("\t--- Warning property not found:" + key);
        } else if (clazz.equals(java.util.Date.class)) {
            String value = Utils.getString(from.get(key), beanMap.get(key), mode);
            debug("\tDate found:" + key + "=>" + value);
            Date date = null;
            if (value != null) {
                try {
                    Long val = Long.valueOf(value);
                    date = (Date) ConvertUtils.convert(val, Date.class);
                    debug("\tdate1:" + date);
                } catch (Exception e) {
                    try {
                        DateTime dt = new DateTime(value);
                        date = new Date(dt.getMillis());
                        debug("\tdate2:" + date);
                    } catch (Exception e1) {
                        try {
                            int space = value.indexOf(" ");
                            if (space != -1) {
                                value = value.substring(0, space) + "T" + value.substring(space + 1);
                                DateTime dt = new DateTime(value);
                                date = new Date(dt.getMillis());
                            }
                            debug("\tdate3:" + date);
                        } catch (Exception e2) {
                            debug("\terror setting date:" + e);
                        }
                    }
                }
            }
            debug("\tsetting date:" + date);
            beanMap.put(key, date);
        } else if (clazz.equals(java.util.Map.class)) {
            info("!!!!!!!!!!!!!!!!!!!Map not implemented");
        } else if (clazz.equals(java.util.List.class) || clazz.equals(java.util.Set.class)) {
            boolean isList = clazz.equals(java.util.List.class);
            boolean isSimple = false;
            if (datatype != null && datatype.startsWith("list_")) {
                isSimple = true;
            }
            try {
                Class type = TypeUtils.getTypeForField(to, key);
                debug("type:" + type + " fill with: " + from.get(key) + ",list:" + beanMap.get(key) + "/mode:"
                        + mode);
                Collection valList = isList ? new ArrayList() : new HashSet();
                Object fromVal = from.get(key);
                if (fromVal instanceof String && ((String) fromVal).length() > 0) {
                    info("FromVal is StringSchrott, ignore");
                    continue;
                }
                if (from.get(key) instanceof Collection) {
                    valList = (Collection) from.get(key);
                }
                if (valList == null) {
                    valList = isList ? new ArrayList() : new HashSet();
                }
                Collection toList = (Collection) PropertyUtils.getProperty(to, key);
                debug("toList:" + toList);
                debug("valList:" + valList);
                if (toList == null) {
                    toList = isList ? new ArrayList() : new HashSet();
                    PropertyUtils.setProperty(to, key, toList);
                }
                if ("replace".equals(mode)) {
                    boolean isEqual = false;
                    if (isSimple) {
                        isEqual = Utils.isCollectionEqual(toList, valList);
                        if (!isEqual) {
                            toList.clear();
                        }
                        debug("\tisEqual:" + isEqual);
                    } else {
                        List deleteList = new ArrayList();
                        String namespace = sessionContext.getStoreDesc().getNamespace();
                        for (Object o : toList) {
                            if (type.getName().endsWith(".Team")) {
                                int status = m_teamService.getTeamStatus(namespace, new BeanMap(o), null,
                                        sessionContext.getUserName());
                                debug("populate.replace.teamStatus:" + status + "/"
                                        + new HashMap(new BeanMap(o)));
                                if (status != -1) {
                                    pm.deletePersistent(o);
                                    deleteList.add(o);
                                }
                            } else {
                                pm.deletePersistent(o);
                                deleteList.add(o);
                            }
                        }
                        for (Object o : deleteList) {
                            toList.remove(o);
                        }
                    }
                    debug("populate.replace.toList:" + toList + "/" + type.getName());
                    if (isSimple) {
                        if (!isEqual) {
                            for (Object o : valList) {
                                toList.add(o);
                            }
                        }
                    } else {
                        for (Object o : valList) {
                            Map valMap = (Map) o;
                            Object n = type.newInstance();
                            if (type.getName().endsWith(".Team")) {
                                valMap.remove("id");
                                Object desc = valMap.get("description");
                                Object name = valMap.get("name");
                                Object dis = valMap.get("disabled");
                                String teamid = (String) valMap.get("teamid");
                                Object ti = Utils.getTeamintern(sessionContext, teamid);
                                if (desc == null) {
                                    valMap.put("description", PropertyUtils.getProperty(ti, "description"));
                                }
                                if (name == null) {
                                    valMap.put("name", PropertyUtils.getProperty(ti, "name"));
                                }
                                if (dis == null) {
                                    valMap.put("disabled", false);
                                }
                                pm.makePersistent(n);
                                populate(sessionContext, valMap, n, null);
                                PropertyUtils.setProperty(n, "teamintern", ti);
                            } else {
                                pm.makePersistent(n);
                                populate(sessionContext, valMap, n, null);
                            }
                            debug("populated.add:" + new HashMap(new BeanMap(n)));
                            toList.add(n);
                        }
                    }
                } else if ("remove".equals(mode)) {
                    if (isSimple) {
                        for (Object o : valList) {
                            if (toList.contains(o)) {
                                toList.remove(o);
                            }
                        }
                    } else {
                        for (Object ol : valList) {
                            Map map = (Map) ol;
                            Object o = Utils.listContainsId(toList, map, "teamid");
                            if (o != null) {
                                toList.remove(o);
                                pm.deletePersistent(o);
                            }
                        }
                    }
                } else if ("add".equals(mode)) {
                    if (isSimple) {
                        for (Object o : valList) {
                            toList.add(o);
                        }
                    } else {
                        for (Object ol : valList) {
                            Map map = (Map) ol;
                            Object o = Utils.listContainsId(toList, map, "teamid");
                            if (o != null) {
                                populate(sessionContext, map, o, null);
                            } else {
                                o = type.newInstance();
                                if (type.getName().endsWith(".Team")) {
                                    Object desc = map.get("description");
                                    Object name = map.get("name");
                                    Object dis = map.get("disabled");
                                    String teamid = (String) map.get("teamid");
                                    Object ti = Utils.getTeamintern(sessionContext, teamid);
                                    if (desc == null) {
                                        map.put("description", PropertyUtils.getProperty(ti, "description"));
                                    }
                                    if (name == null) {
                                        map.put("name", PropertyUtils.getProperty(ti, "name"));
                                    }
                                    if (dis == null) {
                                        map.put("disabled", false);
                                    }

                                    pm.makePersistent(o);
                                    populate(sessionContext, map, o, null);
                                    PropertyUtils.setProperty(o, "teamintern", ti);
                                } else {
                                    pm.makePersistent(o);
                                    populate(sessionContext, map, o, null);
                                }
                                toList.add(o);
                            }
                        }
                    }
                } else if ("assign".equals(mode)) {
                    if (!isSimple) {
                        for (Object ol : valList) {
                            Map map = (Map) ol;
                            Object o = Utils.listContainsId(toList, map);
                            if (o != null) {
                                debug("id:" + map + " already assigned");
                            } else {
                                Object id = map.get("id");
                                Boolean assign = Utils.getBoolean(map.get("assign"));
                                Object obj = pm.getObjectById(type, id);
                                if (assign) {
                                    toList.add(obj);
                                } else {
                                    toList.remove(obj);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                debug("populate.list.failed:" + key + "=>" + from.get(key) + ";" + e);
            }
        } else if (clazz.equals(java.lang.Boolean.class)) {
            try {
                beanMap.put(key, ConvertUtils.convert(from.get(key), Boolean.class));
            } catch (Exception e) {
                debug("populate.boolean.failed:" + key + "=>" + from.get(key) + ";" + e);
            }
        } else if (clazz.equals(java.lang.Double.class)) {
            String value = Utils.getString(from.get(key), beanMap.get(key), mode);
            try {
                beanMap.put(key, Double.valueOf(value));
            } catch (Exception e) {
                debug("populate.double.failed:" + key + "=>" + value + ";" + e);
            }
        } else if (clazz.equals(java.lang.Long.class)) {
            try {
                beanMap.put(key, ConvertUtils.convert(from.get(key), Long.class));
            } catch (Exception e) {
                debug("populate.long.failed:" + key + "=>" + from.get(key) + ";" + e);
            }
        } else if (clazz.equals(java.lang.Integer.class)) {
            debug("Integer:" + ConvertUtils.convert(from.get(key), Integer.class));
            try {
                beanMap.put(key, ConvertUtils.convert(from.get(key), Integer.class));
            } catch (Exception e) {
                debug("populate.integer.failed:" + key + "=>" + from.get(key) + ";" + e);
            }
        } else if ("binary".equals(datatype) || clazz.equals(byte[].class)) {
            InputStream is = null;
            InputStream is2 = null;

            try {
                if (from.get(key) instanceof FileItem) {
                    FileItem fi = (FileItem) from.get(key);
                    String name = fi.getName();
                    byte[] bytes = IOUtils.toByteArray(fi.getInputStream());
                    if (bytes != null) {
                        debug("bytes:" + bytes.length);
                    }
                    beanMap.put(key, bytes);
                    is = fi.getInputStream();
                    is2 = fi.getInputStream();
                } else if (from.get(key) instanceof Map) {
                    Map map = (Map) from.get(key);
                    String storeLocation = (String) map.get("storeLocation");
                    is = new FileInputStream(new File(storeLocation));
                    is2 = new FileInputStream(new File(storeLocation));
                    byte[] bytes = IOUtils.toByteArray(is);
                    if (bytes != null) {
                        debug("bytes2:" + bytes.length);
                    }
                    is.close();
                    beanMap.put(key, bytes);
                    is = new FileInputStream(new File(storeLocation));
                } else if (from.get(key) instanceof String) {
                    String value = (String) from.get(key);
                    if ("ignore".equals(value)) {
                        debug("ignore:");
                        return;
                    }
                    if (value.startsWith("data:")) {
                        int ind = value.indexOf(";base64,");
                        byte b[] = Base64.decode(value.substring(ind + 8));
                        beanMap.put(key, b);
                        is = new ByteArrayInputStream(b);
                        is2 = new ByteArrayInputStream(b);
                    } else {
                        byte b[] = value.getBytes();
                        beanMap.put(key, b);
                        is = new ByteArrayInputStream(b);
                        is2 = new ByteArrayInputStream(b);
                    }
                } else {
                    debug("populate.byte[].no a FileItem:" + key + "=>" + from.get(key));
                    continue;
                }
                Tika tika = new Tika();
                TikaInputStream stream = TikaInputStream.get(is);
                TikaInputStream stream2 = TikaInputStream.get(is2);
                String text = tika.parseToString(is);
                debug("Text:" + text);
                try {
                    beanMap.put("text", text);
                } catch (Exception e) {
                    beanMap.put("text", text.getBytes());
                }
                //@@@MS Hardcoded 
                try {
                    Detector detector = new DefaultDetector();
                    MediaType mime = detector.detect(stream2, new Metadata());
                    debug("Mime:" + mime.getType() + "|" + mime.getSubtype() + "|" + mime.toString());
                    beanMap.put("type", mime.toString());
                    from.put("type", mime.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
                debug("populate.byte[].failed:" + key + "=>" + from.get(key) + ";" + e);
            } finally {
                try {
                    is.close();
                    is2.close();
                } catch (Exception e) {
                }
            }
        } else {
            boolean ok = false;
            try {
                Class type = TypeUtils.getTypeForField(to, key);
                if (type != null) {
                    Object o = type.newInstance();
                    boolean hasAnn = type.isAnnotationPresent(PersistenceCapable.class);
                    debug("hasAnnotation:" + hasAnn);
                    if (o instanceof javax.jdo.spi.PersistenceCapable || hasAnn) {
                        Object id = null;
                        try {
                            Object _id = from.get(key);
                            if (_id != null) {
                                if (_id instanceof Map) {
                                    id = ((Map) _id).get("id");
                                } else {
                                    String s = String.valueOf(_id);
                                    if (s.indexOf("/") >= 0) {
                                        _id = Utils.extractId(s);
                                    }
                                    Class idClass = PropertyUtils.getPropertyType(o, "id");
                                    id = (idClass.equals(Long.class)) ? Long.valueOf(_id + "") : _id;
                                }
                            }
                        } catch (Exception e) {
                        }
                        if (id != null && !"".equals(id) && !"null".equals(id)) {
                            debug("\tId2:" + id);
                            Object relatedObject = pm.getObjectById(type, id);
                            List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to, null);
                            if (candidates.size() == 1) {
                                Collection l = candidates.get(0);
                                debug("list.contains:" + l.contains(to));
                                if (!l.contains(to)) {
                                    l.add(to);
                                }
                            }
                            beanMap.put(key, relatedObject);
                        } else {
                            Object relatedObject = beanMap.get(key);
                            debug("\trelatedObject:" + relatedObject);
                            if (relatedObject != null) {
                                List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to,
                                        null);
                                if (candidates.size() == 1) {
                                    Collection l = candidates.get(0);
                                    debug("list.contains:" + l.contains(to));
                                    if (l.contains(to)) {
                                        l.remove(to);
                                    }
                                }
                            }
                            beanMap.put(key, null);
                        }
                        ok = true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!ok) {
                String value = Utils.getString(from.get(key), beanMap.get(key), mode);
                // debug("populate:" + key + "=>" + value); 
                // debug("String:" + ConvertUtils.convert(from.get(key), String.class)); 
                try {
                    beanMap.put(key, value);
                } catch (Exception e) {
                    debug("populate.failed:" + key + "=>" + value + ";" + e);
                }
            }
        }
        String expression = expressions.get(key);
        if (!isEmpty(expression)) {
            beanMap.put(key, oldValue);
            Map scriptCache = (Map) sessionContext.getProperty("scriptCache");
            if (scriptCache == null) {
                scriptCache = new HashMap();
                sessionContext.setProperty("scriptCache", scriptCache);
            }
            Object result = Utils.eval(expression, beanMap, scriptCache);
            try {
                if ("string".equals(datatype) && !(result instanceof String)) {
                    beanMap.put(key, ConvertUtils.convert(result, String.class));
                } else {
                    beanMap.put(key, result);
                }
            } catch (Exception e) {
                info("Cannot set value for(" + key + "):" + result + "/" + e.getMessage());
            }
        }
    }
}

From source file:org.ms123.common.data.JdoLayerImpl.java

private void getBinary(SessionContext sessionContext, Object obj, boolean hasTeamSecurity, Map permittedFields,
        HttpServletResponse resp) throws Exception {
    Map<String, Object> map = new HashMap();
    BeanMap beanMap = new BeanMap(obj);
    if (beanMap.getType("_team_list") != null) {
        Set<Object> _teams = (Set<Object>) beanMap.get("_team_list");
        if (hasTeamSecurity && !m_teamService.checkTeams(sessionContext.getStoreDesc().getNamespace(),
                sessionContext.getUserName(), sessionContext.getUserProperties(), _teams)) {
            info("getPropertyMap.notAllowed:" + _teams);
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }/*from  w w  w.  j ava2 s  .c  o m*/
    }
    if (PropertyUtils.isReadable(obj, "content")) {
        byte[] c = (byte[]) PropertyUtils.getProperty(obj, "content");
        if (PropertyUtils.isReadable(obj, "type")) {
            String t = (String) PropertyUtils.getProperty(obj, "type");
            resp.setContentType(t);
        }
        if (PropertyUtils.isReadable(obj, "filename")) {
            String t = (String) PropertyUtils.getProperty(obj, "filename");
            resp.addHeader("Content-Disposition", "inline;filename=" + t);
        }
        if (c != null) {
            debug("getBinary:length:" + c.length);
            IOUtils.write(c, resp.getOutputStream());
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getOutputStream().close();
    }
}

From source file:org.ms123.common.data.JdoLayerImpl.java

private Map<String, Object> getPropertyMap(SessionContext sessionContext, Object obj, boolean hasTeamSecurity,
        Map permittedFields, List<String> fieldsArray) throws Exception {
    Map<String, Object> map = new HashMap();
    BeanMap beanMap = new BeanMap(obj);
    if (beanMap.getType("_team_list") != null) {
        Set<Object> _teams = (Set<Object>) beanMap.get("_team_list");
        debug("getPropertyMap.hasTeamSecurity:" + hasTeamSecurity);
        if (hasTeamSecurity && !m_teamService.checkTeams(sessionContext.getStoreDesc().getNamespace(),
                sessionContext.getUserName(), sessionContext.getUserProperties(), _teams)) {
            debug("getPropertyMap.notAllowed:" + _teams);
            return null;
        }//from www.  j  a v  a 2  s.com
    }
    map.put("id", beanMap.get("id"));
    if (fieldsArray != null) {
        for (String field : fieldsArray) {
            if (beanMap.getType(field) == null) {
                m_logger.error("getPropertyMap.property_not_found:" + field);
                continue;
            }
            Map cm = (Map) permittedFields.get(field);
            if (cm == null) {
                continue;
            }
            try {
                Class type = beanMap.getType(field);
                Object value = beanMap.get(field);
                map.put(field, prepareValue(sessionContext, beanMap, value, (String) cm.get("datatype")));
            } catch (Exception e) {
                m_logger.error("getPropertyMap.field:" + field + "," + e);
                e.printStackTrace();
            }
        }
    } else {
        Iterator itk = beanMap.keyIterator();
        while (itk.hasNext()) {
            String field = (String) itk.next();
            Map cm = (Map) permittedFields.get(field);
            if (cm == null) {
                continue;
            }

            if (STATE_FIELD.equals(cm.get("id")) && !m_permissionService.hasAdminRole()) {
                continue;
            }
            try {
                Class type = beanMap.getType(field);
                debug("Type:" + type + "/" + cm.get("datatype") + "/field:" + field);
                Object value = beanMap.get(field);
                if ("binary".equals(cm.get("datatype"))) {
                    continue;
                }
                if ("fulltext".equals(cm.get("datatype"))) {
                    continue;
                }
                if ("set".equals(cm.get("datatype"))) {
                    continue;
                }
                if (type.equals(java.util.List.class) || type.equals(java.util.Set.class)) {
                    continue;
                }
                map.put(field, prepareValue(sessionContext, beanMap, value, (String) cm.get("datatype")));
            } catch (Exception e) {
                m_logger.error("getPropertyMap.field:" + field + "," + e);
                e.printStackTrace();
            }
        }
    }
    return map;
}