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

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

Introduction

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

Prototype

public Object put(Object name, Object value) throws IllegalArgumentException, ClassCastException 

Source Link

Document

Sets the bean property with the given name to the given value.

Usage

From source file:de.iteratec.iteraplan.businesslogic.exchange.common.vbb.impl.util.VisualVariableHelper.java

/**
 * Sets the value of a given visual variable to a beanMap. If no such variable exists or the variable is null, then no value is set.
 * @param target the beanMap to which the variable should be set.
 * @param source the instance holding the values of the visual variables.
 * @param vv the visual variable to set to the beanMap.
 *//*from   w ww .j a  va2 s.com*/
@SuppressWarnings("unchecked")
public static void setVisualVariableValue(BeanMap target, EObject source, EAttribute vv) {
    if (source.eIsSet(vv) && source.eGet(vv) != null && target.containsKey(vv.getName())) {
        Object value = source.eGet(vv);
        //TODO handle multivalued attributes here
        if (vv.getEAttributeType() instanceof EEnum) {
            Class<Enum<?>> enumType = (Class<Enum<?>>) ((EEnum) vv.getEAttributeType()).getInstanceClass();
            for (Enum<?> ec : enumType.getEnumConstants()) {
                if (ec.name().equals(((EEnumLiteral) value).getName())) {
                    value = ec;
                }
            }
        }
        target.put(vv.getName(), value);
    }
}

From source file:com.googlecode.commons.swing.value.GenericValueGetterSetter.java

public void setValue(Component component, Object value) {
    BeanMap map = new BeanMap(component);
    map.put(setterName, value);
}

From source file:com.enonic.cms.business.core.security.userstore.connector.remote.plugin.RemoteUserStoreFactory.java

public RemoteUserStorePlugin create(String type, Properties props) {
    RemoteUserStorePlugin userStorePlugin = createInstance(type);
    if (props != null) {
        BeanMap bean = new BeanMap(userStorePlugin);
        for (Object key : props.keySet()) {
            String strKey = key.toString();
            String strValue = props.getProperty(strKey);

            // Preventing this property to be set as false if it blank (since it will be confusing for the user)
            if ("readUserSyncAttributeAsBinary".equals(strKey) && StringUtils.isBlank(strValue)) {
                continue;
            }//from   w  ww  . j  a  v a 2  s.  c  o m

            try {
                bean.put(strKey, strValue);
            } catch (Exception e) {
                LOG.warn("Failed to set property [" + strKey + "] with value [" + strValue + "].");
            }
        }
    }
    return userStorePlugin;
}

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 {// w  w w.  j a  v  a2s .com
        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 T mapResults(T instance, List results, ArrayList<String> pList)
        throws InstantiationException, IllegalAccessException, IllegalArgumentException {
    pList.parallelStream().forEach(e -> {
        Object o = instance;/*  ww w . j a  v a 2 s.  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:org.beanfuse.model.EntityUtils.java

/**
 * ().<br>/*from  w  ww .j a  v a  2s. c  o m*/
 * 
 * <pre>
 *  hibernate????.
 *  (Entity)???id??.
 *  ?
 * &lt;code&gt;
 * Component
 * &lt;/code&gt;
 *  ?
 *  ?????????.
 *  // evict collection
 *  if (value instanceof Collection) {
 *    if (((Collection) value).isEmpty())
 *    map.put(attr, null);
 *  }
 * </pre>
 * 
 * @see ValidEntityPredicate
 * @param entity
 */
public static void evictEmptyProperty(Object entity) {
    if (null == entity) {
        return;
    }
    boolean isEntity = false;
    if (entity instanceof Entity) {
        isEntity = true;
    }
    BeanMap map = new BeanMap(entity);
    List attList = new ArrayList();
    attList.addAll(map.keySet());
    attList.remove("class");
    for (Iterator iter = attList.iterator(); iter.hasNext();) {
        String attr = (String) iter.next();
        if (!PropertyUtils.isWriteable(entity, attr)) {
            continue;
        }
        Object value = map.get(attr);
        if (null == value) {
            continue;
        } else {
            // evict invalid entity key
            if (isEntity && attr.equals(((Entity) entity).key())) {
                if (!ValidEntityKeyPredicate.getInstance().evaluate(value)) {
                    map.put(attr, null);
                }
            }
            // evict invalid entity
            if (value instanceof Entity && !ValidEntityPredicate.getInstance().evaluate(value)) {
                map.put(attr, null);
            } else if (value instanceof Component) {
                // evict component recursively
                evictEmptyProperty(value);
            }
        }
    }
}

From source file:org.dcm4chee.archive.patient.PatientSelectorFactory.java

private static PatientSelector createSelector(PatientSelectorConfig conf) {

    try {//w w  w  .j  a  v a 2s.co  m
        Object selectorObject = Class.forName(conf.getPatientSelectorClassName()).newInstance();
        BeanMap map = new BeanMap(selectorObject);

        for (String key : conf.getPatientSelectorProperties().keySet())
            map.put(key, conf.getPatientSelectorProperties().get(key));

        return (PatientSelector) map.getBean();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        throw new IllegalArgumentException("conf=" + conf, e);
    }
}

From source file:org.eclipse.dawnsci.doe.DOEUtils.java

/**
 * Changes a value on the given bean using reflection
 * /*from   w  w  w. ja  v  a 2 s  . c  om*/
 * @param bean
 * @param fieldName
 * @param value
 * @throws Exception
 */
public static void setBeanValue(final Object bean, final String fieldName, final Object value)
        throws Exception {
    final String setterName = getSetterName(fieldName);
    try {
        final Method method;
        if (value != null) {
            method = bean.getClass().getMethod(setterName, value.getClass());
        } else {
            method = bean.getClass().getMethod(setterName, Object.class);
        }
        method.invoke(bean, value);
    } catch (NoSuchMethodException ne) {
        // Happens when UI and bean types are not the same, for instance Text editing a double field,
        // or label showing a double field.
        final BeanMap properties = new BeanMap(bean);
        properties.put(fieldName, value);
    }
}

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   ww  w. j a v a  2s . 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.MultiOperations.java

public static void populate(SessionContext sessionContext, Map sourceMap, Object destinationObj, Map hintsMap) {
    PersistenceManager pm = sessionContext.getPM();
    if (hintsMap == null) {
        hintsMap = new HashMap();
    }//from   w w w. j a v  a 2s  .  c  o  m
    boolean noUpdate = Utils.getBoolean(hintsMap, "noUpdate", false);
    BeanMap destinationMap = new BeanMap(destinationObj);
    String entityName = m_inflector.getEntityName(destinationObj.getClass().getSimpleName());
    debug("populate.sourceMap:" + sourceMap + ",destinationObj:" + destinationObj + ",destinationMap:"
            + destinationMap + "/hintsMap:" + hintsMap + "/entityName:" + entityName);
    if (sourceMap == null) {
        return;
    }
    debug("populate(" + entityName + ") is a persistObject:" + javax.jdo.JDOHelper.isPersistent(destinationObj)
            + "/" + javax.jdo.JDOHelper.isNew(destinationObj));
    if (sourceMap.get("id") != null) {
        debug("populate(" + entityName + ") has id:" + sourceMap.get("id"));
        return;
    }
    Map permittedFields = sessionContext.getPermittedFields(entityName, "write");
    Iterator<String> it = sourceMap.keySet().iterator();
    while (it.hasNext()) {
        String propertyName = it.next();
        boolean permitted = sessionContext.getPermissionService().hasAdminRole() || "team".equals(entityName)
                || sessionContext.isFieldPermitted(propertyName, entityName, "write");
        if (!propertyName.startsWith("_") && !permitted) {
            debug("---->populate:field(" + propertyName + ") no write permission");
            continue;
        } else {
            debug("++++>populate:field(" + propertyName + ") write permitted");
        }
        String datatype = null;
        String edittype = null;
        if (!propertyName.startsWith("_")) {
            Map config = (Map) permittedFields.get(propertyName);
            if (config != null) {
                datatype = (String) config.get("datatype");
                edittype = (String) config.get("edittype");
            }
        }
        if (propertyName.equals(STATE_FIELD) && !sessionContext.getPermissionService().hasAdminRole()) {
            continue;
        }
        if ("auto".equals(edittype))
            continue;

        String mode = null;
        Map hm = (Map) hintsMap.get(propertyName);
        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 propertyClass = destinationMap.getType(propertyName);
        debug("\ttype:" + propertyClass + "(" + propertyName + "=" + sourceMap.get(propertyName) + ")");
        if ("_ignore_".equals(sourceMap.get(propertyName))) {
            continue;
        }
        if (propertyClass == null) {
            debug("\t--- Warning property not found:" + propertyName);
        } else if (propertyClass.equals(java.util.Date.class)) {
            String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode);
            debug("\tDate found:" + propertyName + "=>" + 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);
            destinationMap.put(propertyName, date);
        } else if (propertyClass.equals(java.util.Map.class)) {
            info("!!!!!!!!!!!!!!!!!!!Map not implemented");
        } else if (propertyClass.equals(java.util.List.class) || propertyClass.equals(java.util.Set.class)) {
            boolean isList = propertyClass.equals(java.util.List.class);
            boolean isSimple = false;
            if (datatype != null && datatype.startsWith("list_")) {
                isSimple = true;
            }
            try {
                Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName);
                debug("propertyType:" + propertyType + " fill with: " + sourceMap.get(propertyName) + ",list:"
                        + destinationMap.get(propertyName) + "/mode:" + mode);
                Collection sourceList = isList ? new ArrayList() : new HashSet();

                Object fromVal = sourceMap.get(propertyName);
                if (fromVal instanceof String && ((String) fromVal).length() > 0) {
                    info("FromVal is StringSchrott, ignore");
                    continue;
                }

                if (sourceMap.get(propertyName) instanceof Collection) {
                    sourceList = (Collection) sourceMap.get(propertyName);
                }
                if (sourceList == null) {
                    sourceList = isList ? new ArrayList() : new HashSet();
                }
                Collection destinationList = (Collection) PropertyUtils.getProperty(destinationObj,
                        propertyName);
                debug("destinationList:" + destinationList);
                debug("sourceList:" + sourceList);
                if (destinationList == null) {
                    destinationList = isList ? new ArrayList() : new HashSet();
                    PropertyUtils.setProperty(destinationObj, propertyName, destinationList);
                }
                if ("replace".equals(mode)) {
                    boolean isEqual = false;
                    if (isSimple) {
                        isEqual = Utils.isCollectionEqual(destinationList, sourceList);
                        if (!isEqual) {
                            destinationList.clear();
                        }
                        debug("\tisEqual:" + isEqual);
                    } else {
                        List deleteList = new ArrayList();
                        String namespace = sessionContext.getStoreDesc().getNamespace();
                        for (Object o : destinationList) {
                            if (propertyType.getName().endsWith(".Team")) {
                                int status = sessionContext.getTeamService().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) {
                            destinationList.remove(o);
                        }
                    }
                    debug("populate.replace.destinationList:" + destinationList + "/" + propertyType.getName());
                    if (isSimple) {
                        if (!isEqual) {
                            for (Object o : sourceList) {
                                destinationList.add(o);
                            }
                        }
                    } else {
                        for (Object o : sourceList) {
                            Map childSourceMap = (Map) o;
                            Object childDestinationObj = propertyType.newInstance();
                            if (propertyType.getName().endsWith(".Team")) {
                                childSourceMap.remove("id");
                                Object desc = childSourceMap.get("description");
                                Object name = childSourceMap.get("name");
                                Object dis = childSourceMap.get("disabled");
                                String teamid = (String) childSourceMap.get("teamid");
                                Object ti = Utils.getTeamintern(sessionContext, teamid);
                                if (desc == null) {
                                    childSourceMap.put("description",
                                            PropertyUtils.getProperty(ti, "description"));
                                }
                                if (name == null) {
                                    childSourceMap.put("name", PropertyUtils.getProperty(ti, "name"));
                                }
                                if (dis == null) {
                                    childSourceMap.put("disabled", false);
                                }
                                pm.makePersistent(childDestinationObj);
                                populate(sessionContext, childSourceMap, childDestinationObj, hintsMap);
                                PropertyUtils.setProperty(childDestinationObj, "teamintern", ti);
                            } else {
                                pm.makePersistent(childDestinationObj);
                                populate(sessionContext, childSourceMap, childDestinationObj, hintsMap);
                            }
                            debug("populated.add:" + new HashMap(new BeanMap(childDestinationObj)));
                            destinationList.add(childDestinationObj);
                        }
                    }
                } else if ("remove".equals(mode)) {
                    if (isSimple) {
                        for (Object o : sourceList) {
                            if (destinationList.contains(o)) {
                                destinationList.remove(o);
                            }
                        }
                    } else {
                        for (Object ol : sourceList) {
                            Map childSourceMap = (Map) ol;
                            Object o = Utils.listContainsId(destinationList, childSourceMap, "teamid");
                            if (o != null) {
                                destinationList.remove(o);
                                pm.deletePersistent(o);
                            }
                        }
                    }
                } else if ("add".equals(mode)) {
                    if (isSimple) {
                        for (Object o : sourceList) {
                            destinationList.add(o);
                        }
                    } else {
                        for (Object ol : sourceList) {
                            Map childSourceMap = (Map) ol;
                            Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap,
                                    "teamid");
                            if (childDestinationObj != null) {
                                populate(sessionContext, childSourceMap, childDestinationObj, hintsMap);
                            } else {
                                childDestinationObj = propertyType.newInstance();
                                if (propertyType.getName().endsWith(".Team")) {
                                    Object desc = childSourceMap.get("description");
                                    Object name = childSourceMap.get("name");
                                    Object dis = childSourceMap.get("disabled");
                                    String teamid = (String) childSourceMap.get("teamid");
                                    Object ti = Utils.getTeamintern(sessionContext, teamid);
                                    if (desc == null) {
                                        childSourceMap.put("description",
                                                PropertyUtils.getProperty(ti, "description"));
                                    }
                                    if (name == null) {
                                        childSourceMap.put("name", PropertyUtils.getProperty(ti, "name"));
                                    }
                                    if (dis == null) {
                                        childSourceMap.put("disabled", false);
                                    }
                                    pm.makePersistent(childDestinationObj);
                                    populate(sessionContext, childSourceMap, childDestinationObj, hintsMap);
                                    PropertyUtils.setProperty(childDestinationObj, "teamintern", ti);
                                } else {
                                    pm.makePersistent(childDestinationObj);
                                    populate(sessionContext, childSourceMap, childDestinationObj, hintsMap);
                                }
                                destinationList.add(childDestinationObj);
                            }
                        }
                    }
                } else if ("assign".equals(mode)) {
                    if (!isSimple) {
                        for (Object ol : sourceList) {
                            Map childSourceMap = (Map) ol;
                            Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap);
                            if (childDestinationObj != null) {
                                debug("id:" + childSourceMap + " already assigned");
                            } else {
                                Object id = childSourceMap.get("id");
                                Boolean assign = Utils.getBoolean(childSourceMap.get("assign"));
                                Object obj = pm.getObjectById(propertyType, id);
                                if (assign) {
                                    destinationList.add(obj);
                                } else {
                                    destinationList.remove(obj);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                debug("populate.list.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e);
            }
        } else if (propertyClass.equals(java.lang.Boolean.class)) {
            try {
                destinationMap.put(propertyName,
                        ConvertUtils.convert(sourceMap.get(propertyName), Boolean.class));
            } catch (Exception e) {
                debug("populate.boolean.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e);
            }
        } else if (propertyClass.equals(java.lang.Double.class)) {
            String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode);
            try {
                destinationMap.put(propertyName, Double.valueOf(value));
            } catch (Exception e) {
                debug("populate.double.failed:" + propertyName + "=>" + value + ";" + e);
            }
        } else if (propertyClass.equals(java.lang.Long.class)) {
            try {
                destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Long.class));
            } catch (Exception e) {
                debug("populate.long.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e);
            }
        } else if (propertyClass.equals(java.lang.Integer.class)) {
            debug("Integer:" + ConvertUtils.convert(sourceMap.get(propertyName), Integer.class));
            try {
                destinationMap.put(propertyName,
                        ConvertUtils.convert(sourceMap.get(propertyName), Integer.class));
            } catch (Exception e) {
                debug("populate.integer.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e);
            }
        } else if ("binary".equals(datatype) || propertyClass.equals(byte[].class)) {
            InputStream is = null;
            InputStream is2 = null;
            try {
                if (sourceMap.get(propertyName) instanceof FileItem) {
                    FileItem fi = (FileItem) sourceMap.get(propertyName);
                    String name = fi.getName();
                    byte[] bytes = IOUtils.toByteArray(fi.getInputStream());
                    if (bytes != null) {
                        debug("bytes:" + bytes.length);
                    }
                    destinationMap.put(propertyName, bytes);
                    is = fi.getInputStream();
                    is2 = fi.getInputStream();
                } else if (sourceMap.get(propertyName) instanceof Map) {
                    Map map = (Map) sourceMap.get(propertyName);
                    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();
                    destinationMap.put(propertyName, bytes);
                    is = new FileInputStream(new File(storeLocation));
                } else if (sourceMap.get(propertyName) instanceof String) {
                    String value = (String) sourceMap.get(propertyName);
                    if (value.startsWith("data:")) {
                        int ind = value.indexOf(";base64,");
                        byte b[] = Base64.decode(value.substring(ind + 8));
                        destinationMap.put(propertyName, b);
                        is = new ByteArrayInputStream(b);
                        is2 = new ByteArrayInputStream(b);
                    } else {
                    }
                } else {
                    debug("populate.byte[].no a FileItem:" + propertyName + "=>" + sourceMap.get(propertyName));
                    continue;
                }
                Tika tika = new Tika();
                TikaInputStream stream = TikaInputStream.get(is);
                TikaInputStream stream2 = TikaInputStream.get(is2);
                String text = tika.parseToString(is);
                debug("Text:" + text);
                try {
                    destinationMap.put("text", text);
                } catch (Exception e) {
                    destinationMap.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());
                    destinationMap.put("type", mime.toString());
                    sourceMap.put("type", mime.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
                debug("populate.byte[].failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e);
            } finally {
                try {
                    is.close();
                    is2.close();
                } catch (Exception e) {
                }
            }
        } else {
            boolean ok = false;
            try {
                Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName);
                debug("propertyType:" + propertyType + "/" + propertyName);
                if (propertyType != null) {
                    boolean hasAnn = propertyType.isAnnotationPresent(PersistenceCapable.class);
                    debug("hasAnnotation:" + hasAnn);
                    if (propertyType.newInstance() instanceof javax.jdo.spi.PersistenceCapable || hasAnn) {
                        handleRelatedTo(sessionContext, sourceMap, propertyName, destinationMap, destinationObj,
                                propertyType);
                        Object obj = sourceMap.get(propertyName);
                        if (obj != null && obj instanceof Map) {
                            Map childSourceMap = (Map) obj;
                            Object childDestinationObj = destinationMap.get(propertyName);
                            if (childDestinationObj == null) {
                                childDestinationObj = propertyType.newInstance();
                                destinationMap.put(propertyName, childDestinationObj);
                            }
                            populate(sessionContext, childSourceMap, childDestinationObj, hintsMap);
                        } else {
                            if (obj == null) {
                                destinationMap.put(propertyName, null);
                            }
                        }
                        ok = true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!ok) {
                String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName),
                        mode);
                try {
                    if (noUpdate) {
                        if (Utils.isEmptyObj(destinationMap.get(propertyName))) {
                            destinationMap.put(propertyName, value);
                        }
                    } else {
                        destinationMap.put(propertyName, value);
                    }
                } catch (Exception e) {
                    debug("populate.failed:" + propertyName + "=>" + value + ";" + e);
                }
            }
        }
    }
}