Example usage for org.apache.commons.beanutils PropertyUtils describe

List of usage examples for org.apache.commons.beanutils PropertyUtils describe

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils describe.

Prototype

public static Map describe(Object bean)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Return the entire set of properties for which the specified bean provides a read method.

For more details see PropertyUtilsBean.

Usage

From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java

/**
 * Converts "normal" java types to JSON stuff.
 *
 * @param       obj                 the object to convert.
 *//*from w  w w.j  av a 2 s  . c  o m*/

public Object fromJava(Object obj)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (obj == null) {
        return JSONObject.NULL;
    }
    if (obj instanceof String) {
        return obj;
    }
    if (obj instanceof Date) {
        return obj;
    }
    if (obj instanceof Integer || obj instanceof Double || obj instanceof Boolean) {
        return obj;
    }
    if (obj instanceof Float) {
        return new Double(((Float) obj).doubleValue());
    }
    // FIXME: find a better way to handle longs
    if (obj instanceof Long) {
        return new Double(((Long) obj).doubleValue());
    }
    if (obj instanceof Object[]) {
        Object[] objectArray = (Object[]) obj;
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < objectArray.length; ++i) {
            jsonArray.put(fromJava(objectArray[i]));
        }
        return jsonArray;
    }
    Class componentType = obj.getClass().getComponentType();
    if (componentType == Integer.TYPE) {
        JSONArray jsonArray = new JSONArray();
        int[] intArray = (int[]) obj;
        for (int i = 0; i < intArray.length; ++i) {
            jsonArray.put(intArray[i]);
        }
        return jsonArray;
    }
    if (componentType == Float.TYPE) {
        JSONArray jsonArray = new JSONArray();
        float[] floatArray = (float[]) obj;
        for (int i = 0; i < floatArray.length; ++i) {
            jsonArray.put((double) (floatArray[i]));
        }
        return jsonArray;
    }
    // FIXME: find a better way to handle longs
    if (componentType == Long.TYPE) {
        JSONArray jsonArray = new JSONArray();
        long[] longArray = (long[]) obj;
        for (int i = 0; i < longArray.length; ++i) {
            jsonArray.put((double) (longArray[i]));
        }
        return jsonArray;
    }
    if (componentType == Double.TYPE) {
        JSONArray jsonArray = new JSONArray();
        double[] doubleArray = (double[]) obj;
        for (int i = 0; i < doubleArray.length; ++i) {
            jsonArray.put(doubleArray[i]);
        }
        return jsonArray;
    }
    if (componentType == Boolean.TYPE) {
        JSONArray jsonArray = new JSONArray();
        boolean[] booleanArray = (boolean[]) obj;
        for (int i = 0; i < booleanArray.length; ++i) {
            jsonArray.put(booleanArray[i]);
        }
        return jsonArray;
    }
    if (obj instanceof Map) {
        Map map = (Map) obj;
        Iterator keyIterator = map.keySet().iterator();
        JSONObject jsonObject = new JSONObject();
        Object key;
        while (keyIterator.hasNext()) {
            key = keyIterator.next();
            jsonObject.put((key == null ? null : key.toString()), fromJava(map.get(key)));
        }
        return jsonObject;
    }
    if (obj instanceof Set) {
        Set set = (Set) obj;
        Iterator iterator = set.iterator();
        JSONObject jsonObject = new JSONObject();
        Object key;
        while (iterator.hasNext()) {
            key = iterator.next();
            jsonObject.put((key == null ? null : key.toString()), true);
        }
        return jsonObject;
    }
    return fromJava(filter(obj, PropertyUtils.describe(obj)));
}

From source file:com.gewara.util.XSSFilter.java

/**
 * //ww  w  . j a v a2s. com
 * @param entity
 * @param attrs
 * @return
 */
public static <T extends BaseObject> T filterObjAttrs(T entity, String... attrs) {
    if (ArrayUtils.isEmpty(attrs))
        return entity;
    XSSFilter filter = new XSSFilter();
    try {
        Map result = PropertyUtils.describe(entity);
        for (Object key : result.keySet()) {
            if (result.get(key) instanceof String && ArrayUtils.contains(attrs, String.valueOf(key))) {
                String cleanString = filter.filter(String.valueOf(result.get(key)));
                result.put(key, cleanString);
            }
        }
        BeanUtil.copyProperties(entity, result);
    } catch (Exception ex) {
    }
    return entity;
}

From source file:fr.duminy.jbackup.core.ConfigurationManagerTest.java

private static Map describe(BackupConfiguration config) {
    Map properties;//  w w w . ja v a2 s .c  o m
    try {
        properties = PropertyUtils.describe(config);
    } catch (Exception e) {
        LOG.error("unable to extract properties from configuration", e);
        properties = Collections.EMPTY_MAP;
    }

    properties.remove("class");
    properties.put("archiveFactory", config.getArchiveFactory().getClass().getName());
    List<BackupConfiguration.Source> sources = (List<BackupConfiguration.Source>) properties.remove("sources");
    properties.put("sources.size", sources.size());
    for (int i = 0; i < sources.size(); i++) {
        Map sourceProperties = null;
        try {
            sourceProperties = PropertyUtils.describe(sources.get(i));
        } catch (Exception e) {
            LOG.error("unable to extract source #" + i, e);
        }
        sourceProperties.remove("class");
        properties.put("sources[" + i + "]", sourceProperties);
    }
    return properties;
}

From source file:com.complexible.pinto.RDFMapper.java

@SuppressWarnings("unchecked")
private <T> ResourceBuilder write(final T theValue) {
    // before we do anything, do we have a custom codec for this?
    RDFCodec aCodec = mCodecs.get(theValue.getClass());
    if (aCodec != null) {
        final Value aResult = aCodec.writeValue(theValue);

        if (aResult instanceof ResourceBuilder) {
            return (ResourceBuilder) aResult;
        } else {/*from w w w .jav  a2  s .  c o  m*/
            return new ResourceBuilder(id(theValue)).addType(getType(theValue)).addProperty(VALUE, aResult);
        }
    }

    final Resource aId = id(theValue);

    final IRI aType = getType(theValue);

    try {
        final ModelBuilder aGraph = new ModelBuilder(mValueFactory);

        ResourceBuilder aBuilder = aGraph.instance(aType, aId);

        for (Map.Entry<String, Object> aEntry : PropertyUtils.describe(theValue).entrySet()) {
            final PropertyDescriptor aDescriptor = PropertyUtils.getPropertyDescriptor(theValue,
                    aEntry.getKey());

            if (isIgnored(aDescriptor)) {
                continue;
            }

            final IRI aProperty = getProperty(aDescriptor);

            if (aProperty == null) {
                continue;
            }

            final Object aObj = aEntry.getValue();

            if (aObj != null) {
                setValue(aGraph, aBuilder, aDescriptor, aProperty, aObj);
            }
        }

        return aBuilder;
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        Throwables.propagateIfInstanceOf(e, RDFMappingException.class);
        throw new RDFMappingException(e);
    }
}

From source file:it.polimi.modaclouds.monitoring.kb.api.FusekiKBAPI.java

/**
 * get all object properties except for the class
 * /*w w w  .  j  a va  2s .  c  om*/
 * @param object
 * @return
 */
private Map<String, Object> getJavaProperties(Object object) {
    Map<String, Object> properties = new HashMap<String, Object>();
    try {
        properties = PropertyUtils.describe(object);
        properties.remove("class");
        // properties.put(KBConfig.javaClassProperty,
        // object.getClass().getName());
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot retrieve object properties for serialization", e);
    }
    return properties;
}

From source file:com.m2a.struts.M2ALoginAction.java

/**
 * Assume that helpers are ProcessBeans, execute each, and
 * process outcome.//from   w w w. j a v  a  2s. c om
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The ActionForm
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @param helpers The object instantiated from type given as parameter.
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 */
protected void executeLogic(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, Object[] helpers) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("*** Executing executeLogic()");
    }
    if (log.isDebugEnabled()) {
        log.debug("*** Ready to process ProcessBeans");
    }

    Map properties = null;
    for (int i = 0; i < helpers.length; i++) {

        if (log.isDebugEnabled()) {
            log.debug("*** Processing ProcessBean number " + i);
        }
        // Get helper instantiated by ancestor
        ProcessBean dataBean = (ProcessBean) helpers[i];

        properties = null;
        if (null != form) {
            if (form instanceof M2AFormBase) {
                if (log.isDebugEnabled()) {
                    log.debug("*** Form is an instance of M2AFormBase, setting SessionLocale");
                }
                M2AFormBase formBean = (M2AFormBase) form;
                // Pass up the Locale
                dataBean.setLocale(formBean.getSessionLocale());
            }
            if (log.isDebugEnabled()) {
                log.debug("*** Converting form data as properties map");
            }
            properties = PropertyUtils.describe(form);
        } // end null form

        if (log.isDebugEnabled()) {
            log.debug("*** Setting value for RemoteServer");
        }
        // Pass up the RemoteServer (if any)
        dataBean.setRemoteServer(getRemoteServer());

        // Execute business logic, using values from  map
        if (log.isDebugEnabled()) {
            log.debug("*** Ready to execute business logic in ProcessBean");
        }
        ProcessResult result = (ProcessResult) dataBean.execute(properties);
        if (log.isDebugEnabled()) {
            log.debug("*** Ready to process ProcessResult from ProcessBean");
        }
        // Analyze result of business logic
        checkOutcome(mapping, form, request, response, result);

    } // end for

}

From source file:com.m2a.struts.M2AProcessBridgeAction.java

/**
 * Assume that helpers are ProcessBeans, execute each, and
 * process outcome.//from w  w  w .  j  a v a  2  s  .com
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The ActionForm
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @param helpers The object instantiated from type given as parameter.
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 */
protected void executeLogic(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, Object[] helpers) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("*** Executing executeLogic()");
    }
    // Retrieve user profile, if any
    Map userMap = getUserProfile(mapping, form, request, response);

    if ((null != userMap) && (null != form)) {
        if (log.isDebugEnabled()) {
            log.debug("*** Merging UserProfile values with passed form");
        }
        BeanUtils.copyProperties(form, userMap);
        System.err.println("REACHED" + userMap.get("customerCountry"));
    }

    if (log.isDebugEnabled()) {
        log.debug("*** Ready to process ProcessBeans");
    }

    Map properties = null;
    for (int i = 0; i < helpers.length; i++) {

        if (log.isDebugEnabled()) {
            log.debug("*** Processing ProcessBean number " + i);
        }
        // Get helper instantiated by ancestor
        ProcessBean dataBean = (ProcessBean) helpers[i];

        properties = null;
        if (null != form) {
            if (form instanceof M2AFormBase) {
                if (log.isDebugEnabled()) {
                    log.debug("*** Form is an instance of M2AFormBase, setting SessionLocale");
                }
                M2AFormBase formBean = (M2AFormBase) form;
                // Pass up the Locale
                dataBean.setLocale(formBean.getSessionLocale());
            }
            if (log.isDebugEnabled()) {
                log.debug("*** Converting form data as properties map");
            }
            properties = PropertyUtils.describe(form);
        } // end null form
        else if (null != userMap) {
            // if no form, but is profile, still use profile
            properties = userMap;
        }
        if (log.isDebugEnabled()) {
            log.debug("*** Setting value for RemoteServer");
        }
        // Pass up the RemoteServer (if any)
        dataBean.setRemoteServer(getRemoteServer());

        // Execute business logic, using values from  map
        if (log.isDebugEnabled()) {
            log.debug("*** Ready to execute business logic in ProcessBean");
        }
        ProcessResult result = (ProcessResult) dataBean.execute(properties);
        if (log.isDebugEnabled()) {
            log.debug("*** Ready to process ProcessResult from ProcessBean");
        }
        // Analyze result of business logic
        checkOutcome(mapping, form, request, response, result);

    } // end for

}

From source file:it.polimi.tower4clouds.manager.MonitoringManager.java

@SuppressWarnings("unchecked")
private void updateExistingRelations(Set<Resource> resources) {
    try {//from   www. j a  va  2s.co  m
        Map<String, Object> properties;
        for (Resource resource : resources) {
            if (registeredResources.containsKey(resource.getId())) {
                Resource registeredResource = registeredResources.get(resource.getId());
                properties = PropertyUtils.describe(resource);
                for (Entry<String, Object> property : properties.entrySet()) {
                    if (property.getValue() instanceof Set) {
                        ((Set<Resource>) property.getValue()).addAll((Set<? extends Resource>) PropertyUtils
                                .getProperty(registeredResource, property.getKey()));
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:gemlite.core.internal.db.DBSynchronizer.java

/**
 * Get or create a {@link PreparedStatement} for an insert operation.
 *//*from  w ww . j a  va2  s .c o m*/
protected PreparedStatement getExecutableInsertPrepStmntPKBased(AsyncEvent pkEvent, PreparedStatement prevPS)
        throws SQLException {
    final String regionName = pkEvent.getRegion().getName();
    PreparedStatement ps = this.insertStmntMap.get(regionName);

    IMapperTool tool = DomainRegistry.getMapperTool(regionName);
    String tableName = DomainRegistry.regionToTable(regionName);
    List<String> valueFields = tool.getValueFieldNames();

    if (ps == null) {
        final String dmlString = AsyncEventHelper.getInsertString(tableName, valueFields);
        if (logger.isDebugEnabled()) {
            logger.info("DBSynchronizer::getExecutableInsertPrepStmntPKBased: " + "preparing '" + dmlString
                    + "' for event: " + pkEvent);
        }
        ps = conn.prepareStatement(dmlString);
        this.insertStmntMap.put(tableName, ps);
    } else if (prevPS == ps) {
        // add a new batch of values
        ps.addBatch();
    }
    int paramIndex = 1;
    Class valueClass = tool.getValueClass();
    for (int colIdx = 0; colIdx < valueFields.size(); colIdx++) {
        String field = valueFields.get(colIdx);
        try {
            Map map = PropertyUtils.describe(pkEvent.getDeserializedValue());
            Object val = map.get(field);
            String type = valueClass.getDeclaredField(field).getType().getName();
            helper.setColumnInPrepStatement(type, val, ps, this, paramIndex);
        } catch (Exception e) {
            throw new SQLException(e);
        }
        paramIndex++;
    }
    return ps;
}

From source file:gemlite.core.internal.db.DBSynchronizer.java

/**
 * Get or create a {@link PreparedStatement} for a primary key based update
 * operation.// w w  w .  j ava2s. c  om
 */
protected PreparedStatement getExecutableUpdatePrepStmntPKBased(AsyncEvent pkEvent, PreparedStatement prevPS)
        throws SQLException {
    final String regionName = pkEvent.getRegion().getName();
    IMapperTool tool = DomainRegistry.getMapperTool(regionName);
    String tableName = DomainRegistry.regionToTable(regionName);
    List<String> valueFields = tool.getValueFieldNames();

    final int numUpdatedCols = valueFields.size();
    StringBuilder searchKeyBuff = new StringBuilder(tableName);
    int paramIndex;
    for (paramIndex = 0; paramIndex < numUpdatedCols; paramIndex++) {
        searchKeyBuff.append('_');
        searchKeyBuff.append(valueFields.get(paramIndex));
    }
    String searchKey = searchKeyBuff.toString();
    final Object pkValues = pkEvent.getDeserializedValue();
    final List<String> keyFields = tool.getKeyFieldNames();
    PreparedStatement ps = this.updtStmntMap.get(searchKey);
    if (ps == null) {
        final String dmlString = AsyncEventHelper.getUpdateString(tableName, keyFields, valueFields);
        if (logger.isDebugEnabled()) {
            logger.info("DBSynchronizer::getExecutableInsertPrepStmntPKBased: " + "preparing '" + dmlString
                    + "' for event: " + pkEvent);
        }
        ps = conn.prepareStatement(dmlString);
        this.updtStmntMap.put(searchKey, ps);
    } else if (prevPS == ps) {
        // add a new batch of values
        ps.addBatch();
    }
    // Set updated col values
    Class valueClass = tool.getValueClass();
    Class keyClass = tool.getKeyClass();
    for (paramIndex = 1; paramIndex <= numUpdatedCols; paramIndex++) {
        String field = valueFields.get(paramIndex - 1);
        try {
            Map map = PropertyUtils.describe(pkEvent.getDeserializedValue());
            Object val = map.get(field);
            String type = valueClass.getDeclaredField(field).getType().getName();
            helper.setColumnInPrepStatement(type, val, ps, this, paramIndex);
        } catch (Exception e) {
            throw new SQLException(e);
        }
    }
    // Now set the Pk values
    setKeysInPrepStatement(pkValues, keyFields, valueClass, ps, paramIndex);
    return ps;
}