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

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

Introduction

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

Prototype

public static boolean isWriteable(Object bean, String name) 

Source Link

Document

Return true if the specified property name identifies a writeable property on the specified bean; otherwise, return false.

For more details see PropertyUtilsBean.

Usage

From source file:com.bstek.dorado.view.config.definition.ViewConfigDefinition.java

protected void injectResourceString(ViewConfig viewConfig, String key, String resourceString) throws Exception {
    Object object = viewConfig;//from ww  w .  j a  v a  2s.  c  om
    ResourceInjection resourceInjection = object.getClass().getAnnotation(ResourceInjection.class);

    String[] sections = StringUtils.split(key, ".");
    int len = sections.length;
    for (int i = 0; i < len; i++) {
        String section = sections[i];
        boolean isObject = section.charAt(0) == '#';
        if (isObject) {
            section = section.substring(1);
        }

        if (i == 0 && section.equals("view")) {
            object = viewConfig.getView();
        } else if (isObject) {
            if (object == viewConfig) {
                object = viewConfig.getDataType(section);
                if (object == null && viewConfig.getView() != null) {
                    object = viewConfig.getView().getViewElement(section);
                }
            } else {
                if (resourceInjection == null) {
                    throwInvalidResourceKey(key);
                }
                String methodName = resourceInjection.subObjectMethod();
                if (StringUtils.isEmpty(methodName)) {
                    throwInvalidResourceKey(key);
                }
                object = MethodUtils.invokeExactMethod(object, methodName, new String[] { section });
            }
            if (object == null) {
                break;
            }
            resourceInjection = object.getClass().getAnnotation(ResourceInjection.class);

            if (i == len - 1) {
                String[] defaultProperties;
                if (resourceInjection == null) {
                    defaultProperties = DEFAULT_PROPERTIES;
                } else {
                    defaultProperties = resourceInjection.defaultProperty();
                }

                boolean found = false;
                for (String property : defaultProperties) {
                    if (PropertyUtils.isWriteable(object, property)) {
                        if (PropertyUtils.getSimpleProperty(object, property) == null) {
                            PropertyUtils.setSimpleProperty(object, property, resourceString);
                        }
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    throwInvalidResourceKey(key);
                }
            }
        } else {
            if (i == len - 1) {
                if (PropertyUtils.getSimpleProperty(object, section) == null) {
                    PropertyUtils.setSimpleProperty(object, section, resourceString);
                }
            } else {
                object = PropertyUtils.getSimpleProperty(object, section);
            }
        }
    }
}

From source file:io.milton.http.annotated.AbstractAnnotationHandler.java

/**
 * Returns true if it was able to set the property
 *
 * @param source//from w  ww . j ava 2s.  c o m
 * @param value
 * @param propNames
 * @return
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
protected boolean attemptToSetProperty(Object source, Object value, String... propNames)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    for (String propName : propNames) {
        if (PropertyUtils.isWriteable(source, propName)) {
            PropertyUtils.setProperty(source, propName, value);
            return true;
        }
    }
    return false;
}

From source file:com.rsmart.kuali.kfs.sys.batch.service.impl.BatchFeedHelperServiceImpl.java

/**
 * @see com.rsmart.kuali.kfs.sys.batch.service.BatchFeedHelperService#performForceUppercase(java.lang.String, java.lang.Object)
 *//*from  ww  w . j  a  va 2  s .co m*/
public void performForceUppercase(String entryName, Object businessObject) {
    DataDictionary dataDictionary = dataDictionaryService.getDataDictionary();

    DataDictionaryEntry entry = dataDictionary.getDictionaryObjectEntry(entryName);
    if (entry == null) {
        return;
    }

    List<AttributeDefinition> attributes = ((DataDictionaryEntryBase) entry).getAttributes();
    for (AttributeDefinition attribute : attributes) {
        try {
            if (!attribute.getForceUppercase()
                    || !PropertyUtils.isWriteable(businessObject, attribute.getName())) {
                continue;
            }

            Object currentValue = ObjectUtils.getPropertyValue(businessObject, attribute.getName());
            if (currentValue != null && String.class.isAssignableFrom(currentValue.getClass())) {
                try {
                    ObjectUtils.setObjectProperty(businessObject, attribute.getName(),
                            currentValue.toString().toUpperCase());
                } catch (Exception e) {
                    LOG.error("cannot uppercase property " + attribute.getName() + " in bo class " + entryName,
                            e);
                    throw new RuntimeException(
                            "cannot uppercase property " + attribute.getName() + " in bo class " + entryName,
                            e);
                }
            }
        } catch (Exception e) {
            LOG.warn("cannot uppercase property: " + attribute.getName() + "; " + e.getMessage());
            continue;
        }
    }
}

From source file:com.bstek.dorado.data.config.definition.DataTypeDefinition.java

protected void injectResourceString(EntityDataType dataType, String key, String resourceString)
        throws Exception {
    Object object = dataType;//from  w ww.jav  a2 s.com
    ResourceInjection resourceInjection = object.getClass().getAnnotation(ResourceInjection.class);

    String[] sections = StringUtils.split(key, ".");
    int len = sections.length;
    for (int i = 0; i < len; i++) {
        String section = sections[i];
        boolean isObject = section.charAt(0) == '#';

        if (isObject) {
            section = section.substring(1);

            if (resourceInjection == null) {
                throwInvalidResourceKey(key);
            }
            String methodName = resourceInjection.subObjectMethod();
            if (StringUtils.isEmpty(methodName)) {
                throwInvalidResourceKey(key);
            }
            object = MethodUtils.invokeExactMethod(object, methodName, new String[] { section });
            if (object == null) {
                break;
            }
            resourceInjection = object.getClass().getAnnotation(ResourceInjection.class);

            if (i == len - 1) {
                String[] defaultProperties;
                if (resourceInjection == null) {
                    defaultProperties = DEFAULT_PROPERTIES;
                } else {
                    defaultProperties = resourceInjection.defaultProperty();
                }

                boolean found = false;
                for (String property : defaultProperties) {
                    if (PropertyUtils.isWriteable(object, property)) {
                        // if (PropertyUtils.getSimpleProperty(object,
                        // property) == null) {
                        PropertyUtils.setSimpleProperty(object, property, resourceString);
                        // }
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    throwInvalidResourceKey(key);
                }
            }
        } else {
            if (i == len - 1) {
                if (PropertyUtils.getSimpleProperty(object, section) == null) {
                    PropertyUtils.setSimpleProperty(object, section, resourceString);
                }
            } else {
                object = PropertyUtils.getSimpleProperty(object, section);
            }
        }
    }
}

From source file:com.eviware.soapui.model.propertyexpansion.PropertyExpansionUtils.java

public static Collection<? extends PropertyExpansion> extractPropertyExpansions(ModelItem modelItem,
        Object target, String propertyName) {
    List<PropertyExpansion> result = new ArrayList<PropertyExpansion>();
    Set<String> expansions = new HashSet<String>();

    try {/* w  w w. j  av a  2  s .  c  om*/
        Object property = PropertyUtils.getProperty(target, propertyName);
        if (property instanceof String && PropertyUtils.isWriteable(target, propertyName)) {
            String str = property.toString();

            if (!StringUtils.isNullOrEmpty(str)) {
                int ix = str.indexOf("${");
                while (ix != -1) {
                    // TODO handle nested property-expansions..
                    int ix2 = str.indexOf('}', ix + 2);
                    if (ix2 == -1)
                        break;

                    String expansion = str.substring(ix + 2, ix2);
                    if (!expansions.contains(expansion)) {
                        MutablePropertyExpansion tp = createMutablePropertyExpansion(expansion, modelItem,
                                target, propertyName);
                        if (tp != null) {
                            result.add(tp);
                            expansions.add(expansion);
                        }
                    }

                    str = str.substring(ix2);
                    ix = str.indexOf("${");
                }
            }
        }
    } catch (Exception e) {
        SoapUI.logError(e);
    }

    return result;
}

From source file:net.openkoncept.vroom.VroomController.java

private void processRequestSubmit(HttpServletRequest request, HttpServletResponse response, Map paramMap)
        throws ServletException {
    // change the URI below with the actual page who invoked the request.

    String uri = request.getParameter(CALLER_URI);
    String id = request.getParameter(ID);
    String method = request.getParameter(METHOD);
    String beanClass = request.getParameter(BEAN_CLASS);
    String var = request.getParameter(VAR);
    String scope = request.getParameter(SCOPE);

    if (paramMap != null) {
        uri = (String) ((ArrayList) paramMap.get(CALLER_URI)).get(0);
        id = (String) ((ArrayList) paramMap.get(ID)).get(0);
        method = (String) ((ArrayList) paramMap.get(METHOD)).get(0);
        beanClass = (String) ((ArrayList) paramMap.get(BEAN_CLASS)).get(0);
        var = (String) ((ArrayList) paramMap.get(VAR)).get(0);
        scope = (String) ((ArrayList) paramMap.get(SCOPE)).get(0);
    }/* w w  w.  j a  va2s.c o m*/

    Object beanObject;
    String outcome = null;

    // call form method...

    try {
        Class clazz = Class.forName(beanClass);
        Class elemClass = clazz;
        String eId, eProperty, eBeanClass, eVar, eScope, eFormat;
        // Setting values to beans before calling the method...
        List<Element> elements = VroomConfig.getInstance().getElements(uri, id, method, beanClass, var, scope);
        for (Element e : elements) {
            eId = e.getId();
            eProperty = (e.getProperty() != null) ? e.getProperty() : eId;
            eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass;
            eVar = (e.getVar() != null) ? e.getVar() : var;
            eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope;
            eFormat = e.getFormat();
            if (!elemClass.getName().equals(eBeanClass)) {
                try {
                    elemClass = Class.forName(eBeanClass);
                } catch (ClassNotFoundException ex) {
                    throw new ServletException("Failed to load class for element [" + eId + "]", ex);
                }
            }
            if (elemClass != null) {
                try {
                    Object obj = getObjectFromScope(request, elemClass, eVar, eScope);
                    if (PropertyUtils.isWriteable(obj, eProperty)) {
                        Class propType = PropertyUtils.getPropertyType(obj, eProperty);
                        Object[] paramValues = request.getParameterValues(eId);
                        Object value = null;
                        value = getParameterValue(propType, eId, paramValues, eFormat, paramMap);
                        PropertyUtils.setProperty(obj, eProperty, value);
                    }
                } catch (InstantiationException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                } catch (IllegalAccessException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                }
            }
        }
        // Calling the method...
        beanObject = getObjectFromScope(request, clazz, var, scope);
        Class[] signature = new Class[] { HttpServletRequest.class, HttpServletResponse.class };
        Method m = clazz.getMethod(method, signature);
        Object object = m.invoke(beanObject, new Object[] { request, response });
        // Getting updating values from beans to pass as postback for the forward calls.
        Map<String, Object> postbackMap = new HashMap<String, Object>();
        for (Element e : elements) {
            eId = e.getId();
            eProperty = (e.getProperty() != null) ? e.getProperty() : eId;
            eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass;
            eVar = (e.getVar() != null) ? e.getVar() : var;
            eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope;
            eFormat = e.getFormat();
            if (!elemClass.getName().equals(eBeanClass)) {
                try {
                    elemClass = Class.forName(eBeanClass);
                } catch (ClassNotFoundException ex) {
                    throw new ServletException("Failed to load class for element [" + eId + "]", ex);
                }
            }
            if (elemClass != null) {
                try {
                    Object obj = getObjectFromScope(request, elemClass, eVar, eScope);
                    if (PropertyUtils.isReadable(obj, eProperty)) {
                        //                            Class propType = PropertyUtils.getPropertyType(obj, eProperty);
                        //                            Object[] paramValues = request.getParameterValues(eId);
                        //                            Object value = null;
                        //                            value = getParameterValue(propType, eId, paramValues, eFormat, paramMap);
                        //                            PropertyUtils.setProperty(obj, eProperty, value);
                        Object value = PropertyUtils.getProperty(obj, eProperty);
                        postbackMap.put(eId, value);
                    }
                } catch (InstantiationException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                } catch (IllegalAccessException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                }
            }
        }
        if (object == null || object instanceof String) {
            outcome = (String) object;
            Navigation n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope,
                    outcome);
            if (n == null) {
                n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope, "default");
            }
            if (n != null) {
                String url = n.getUrl();
                if (url == null) {
                    url = "/";
                }
                url = url.replaceAll("#\\{contextPath}", request.getContextPath());
                if (n.isForward()) {
                    String ctxPath = request.getContextPath();
                    if (url.startsWith(ctxPath)) {
                        url = url.substring(ctxPath.length());
                    }
                    PrintWriter pw = response.getWriter();
                    VroomResponseWrapper responseWrapper = new VroomResponseWrapper(response);
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, responseWrapper);
                    StringBuffer sbHtml = new StringBuffer(responseWrapper.toString());
                    VroomHtmlProcessor.addHeadMetaTags(sbHtml, uri, VroomConfig.getInstance());
                    VroomHtmlProcessor.addHeadLinks(sbHtml, uri, VroomConfig.getInstance());
                    VroomHtmlProcessor.addRequiredScripts(sbHtml, request);
                    VroomHtmlProcessor.addInitScript(sbHtml, uri, request);
                    VroomHtmlProcessor.addHeadScripts(sbHtml, uri, VroomConfig.getInstance(), request);
                    VroomHtmlProcessor.addStylesheets(sbHtml, uri, VroomConfig.getInstance(), request);
                    // Add postback values to webpage through javascript...
                    VroomHtmlProcessor.addPostbackScript(sbHtml, uri, request, postbackMap);
                    String html = sbHtml.toString().replaceAll("#\\{contextPath}", request.getContextPath());
                    response.setContentLength(html.length());
                    pw.print(html);
                } else {
                    response.sendRedirect(url);
                }
            } else {
                throw new ServletException("No navigation found for outcome [" + outcome + "]");
            }
        }

    } catch (ClassNotFoundException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (InstantiationException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (IllegalAccessException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (NoSuchMethodException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (InvocationTargetException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (IOException ex) {
        throw new ServletException("Navigation Failed for outcome [" + outcome + "]", ex);
    }
}

From source file:com.p6spy.engine.spy.XADataSourceTest.java

public void setXADSProperties(XADataSource ds, String url, String userName, String password)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (url.contains(":derby:") || url.contains(":sqlfire:")) {
        PropertyUtils.setProperty(ds, "databaseName", "p6spy_xds");
        PropertyUtils.setProperty(ds, "createDatabase", "create");
        return;/*from  ww w  .  ja  v a  2s .com*/
    } else if (url.contains(":firebirdsql:")) {
        PropertyUtils.setProperty(ds, "databaseName", url.replace("jdbc:firebirdsql:", ""));
    } else if (PropertyUtils.isWriteable(ds, "URL")) {
        PropertyUtils.setProperty(ds, "URL", url);
    } else if (PropertyUtils.isWriteable(ds, "Url")) {
        PropertyUtils.setProperty(ds, "Url", url);
    } else if (PropertyUtils.isWriteable(ds, "url")) {
        PropertyUtils.setProperty(ds, "url", url);
    } else if (PropertyUtils.isWriteable(ds, "serverName") && PropertyUtils.isWriteable(ds, "portNumber")
            && PropertyUtils.isWriteable(ds, "databaseName") && URL_PATTERN.matcher(url).matches()) {

        final Matcher matcher = URL_PATTERN.matcher(url);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("url in incorrect format: " + url);
        }
        final String host = matcher.group(2);
        final String port = matcher.group(3);
        final String db = matcher.group(4);

        PropertyUtils.setProperty(ds, "serverName", host);
        if (null != port && !port.isEmpty()) {
            PropertyUtils.setProperty(ds, "portNumber", Integer.parseInt(port));
        }
        PropertyUtils.setProperty(ds, "databaseName", db);
    } else {
        throw new IllegalArgumentException(
                "Datasource imlpementation not supported by tests (yet) (for url setting): " + ds);
    }

    if (PropertyUtils.isWriteable(ds, "userName")) {
        PropertyUtils.setProperty(ds, "userName", userName);
    } else if (PropertyUtils.isWriteable(ds, "user")) {
        PropertyUtils.setProperty(ds, "user", userName);
    } else {
        throw new IllegalArgumentException(
                "Datasource imlpementation not supported by tests (yet) (for username setting): " + ds);
    }

    if (PropertyUtils.isWriteable(ds, "password")) {
        PropertyUtils.setProperty(ds, "password", password);
    } else {
        throw new IllegalArgumentException(
                "Datasource imlpementation not supported by tests (yet) (for password setting): " + ds);
    }
}

From source file:com.all.tracker.controllers.DownloadMetricsController.java

public <T> T setFeatures(String[] features, Class<T> clazz)
        throws InstantiationException, IllegalAccessException {
    if (clazz == null || features == null || features.length == 0) {
        log.error("exception when try to create a SyncAble entity");
        return null;
    }//from  w  w w .ja  v  a2  s.  c om
    T obj = clazz.newInstance();
    for (String item : features) {
        String[] feature = splitMetrics(item, charset_inside);
        if (feature.length == 2) {
            if (PropertyUtils.isWriteable(obj, feature[0])) {
                try {
                    PropertyUtils.setProperty(obj, feature[0], feature[1]);
                } catch (InvocationTargetException e) {
                    log.error(e.getMessage());
                } catch (NoSuchMethodException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }
    return obj;
}

From source file:com.all.shared.sync.SyncGenericConverter.java

private static <T> T fillInstance(T instance, Map<String, Object> attributes) {
    if (instance != null) {
        for (String attribute : attributes.keySet()) {
            if (PropertyUtils.isWriteable(instance, attribute)) {
                try {
                    Class<?> type = PropertyUtils.getPropertyType(instance, attribute);
                    if (instance instanceof ComplexSyncAble) {
                        ComplexSyncAble postSyncAble = (ComplexSyncAble) instance;
                        if (postSyncAble.requiresPostProcessing(attribute)) {
                            continue;
                        }/*from w  w w. ja v a 2  s .co  m*/
                    }
                    Object value = readValue(attribute, type, attributes);
                    PropertyUtils.setProperty(instance, attribute, value);
                } catch (Exception e) {
                    LOGGER.error("Could not fill attribute " + attribute + " to instance of type "
                            + instance.getClass() + ". This attribute will be ignored.", e);
                }
            }
        }
    }
    return instance;
}

From source file:com.all.shared.json.JsonConverter.java

@SuppressWarnings("unchecked")
private static <T> T cleanAndConvert(JSONObject jsonObject, Class<T> clazz) {
    try {/*from   ww  w . j a v  a  2s  .  c  om*/
        Iterator<String> keys = jsonObject.keys();
        T instance = clazz.newInstance();
        while (keys.hasNext()) {
            String key = keys.next();
            if (!PropertyUtils.isWriteable(instance, key)) {
                keys.remove();
            }
        }
        return (T) JSONObject.toBean(jsonObject, clazz);
    } catch (Exception e) {
        throw new IllegalArgumentException("Could not convert from json to bean of type " + clazz.getName(), e);
    }
}