Example usage for org.apache.commons.beanutils ConvertUtilsBean convert

List of usage examples for org.apache.commons.beanutils ConvertUtilsBean convert

Introduction

In this page you can find the example usage for org.apache.commons.beanutils ConvertUtilsBean convert.

Prototype

public Object convert(String values[], Class clazz) 

Source Link

Document

Convert an array of specified values to an array of objects of the specified class (if possible).

Usage

From source file:de.micromata.genome.gwiki.utils.ClassUtils.java

public static Object convert(Object source, Class<?> cls) {
    ConvertUtilsBean converter = new ConvertUtilsBean();
    if (source instanceof String[]) {
        return converter.convert((String[]) source, cls);
    } else if (source instanceof String) {
        return converter.convert((String) source, cls);
    }/*  w  ww .j a  va 2 s.com*/
    return source;
}

From source file:com.custardsource.maven.plugins.jmx.SetAttribute.java

@Override
public Object execute(MBeanServerConnection connection) throws Exception {
    ObjectName name = new ObjectName(objectName);
    ConvertUtilsBean converter = new ConvertUtilsBean();

    Object attributeValue = converter.convert(value, ClassUtils.getClass(type));
    connection.setAttribute(name, new Attribute(attributeName, attributeValue));
    return connection.getAttribute(name, attributeName);
}

From source file:com.custardsource.maven.plugins.jmx.Invoke.java

@Override
public Object execute(MBeanServerConnection connection) throws Exception {
    ObjectName name = new ObjectName(objectName);
    int len = parameters == null ? 0 : parameters.length;
    String[] signature = new String[len];
    Object[] arguments = new Object[len];

    ConvertUtilsBean converter = new ConvertUtilsBean();

    for (int i = 0; i < len; i++) {
        signature[i] = parameters[i].getType();
        arguments[i] = converter.convert(parameters[i].getValue(),
                ClassUtils.getClass(parameters[i].getType()));
        if (signature[i].equals("java.lang.String") && arguments[i] == null) {
            arguments[i] = "";
        }//from  w  w w  .  j a va  2  s  .co  m
    }
    return connection.invoke(name, operation, arguments, signature);
}

From source file:com.opencsv.bean.BeanFieldPrimitiveTypes.java

@Override
protected Object convert(String value) throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
    if (required && StringUtils.isBlank(value)) {
        throw new CsvRequiredFieldEmptyException(
                String.format("Field '%s' is mandatory but no value was provided.", field.getName()));
    }/*  www .j av a2 s. c o m*/

    Object o = null;

    if (StringUtils.isNotBlank(value)) {
        try {
            if (StringUtils.isEmpty(locale)) {
                ConvertUtilsBean converter = new ConvertUtilsBean();
                converter.register(true, false, 0);
                o = converter.convert(value, field.getType());
            } else {
                LocaleConvertUtilsBean lcub = new LocaleConvertUtilsBean();
                lcub.setDefaultLocale(new Locale(locale));
                o = lcub.convert(value, field.getType());
            }
        } catch (ConversionException e) {
            CsvDataTypeMismatchException csve = new CsvDataTypeMismatchException(value, field.getType(),
                    "Conversion of " + value + " to " + field.getType().getCanonicalName() + " failed.");
            csve.initCause(e);
            throw csve;
        }
    }
    return o;
}

From source file:com.linkedin.databus.core.util.TestConfigManager.java

@Test
public void testPaddedInt() throws Exception {
    ConvertUtilsBean convertUtils = new ConvertUtilsBean();
    Integer intValue = (Integer) convertUtils.convert("456", int.class);

    assertEquals("correct int value", 456, intValue.intValue());
    BeanUtilsBean beanUtils = new BeanUtilsBean();
    PropertyDescriptor propDesc = beanUtils.getPropertyUtils().getPropertyDescriptor(_configBuilder,
            "intSetting");
    assertEquals("correct setting type", int.class, propDesc.getPropertyType());

    _configManager.setSetting("com.linkedin.databus2.intSetting", " 123 ");
    DynamicConfig config = _configManager.getReadOnlyConfig();
    assertEquals("correct int value", 123, config.getIntSetting());
}

From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java

@SuppressWarnings("checkstyle:JavadocMethod")
public void callMethod(final RoutingContext routingContext) {
    final String microserviceName = routingContext.request().getParam("microservice");
    final String methodName = routingContext.request().getParam("method");
    final Bean bean = gatewayRegistry.get(microserviceName);

    routingContext.request().bodyHandler(buffer -> {
        final JsonObject mainJsonObject = new JsonObject(buffer.toString());

        try {//from w  w w.ja  va2  s  .  com
            final Class<?> beanClass = bean.getBeanClass();
            List<Method> methods = Arrays.asList(beanClass.getDeclaredMethods()).stream()
                    .filter(method -> method.getName().equals(methodName)
                            && method.getParameterCount() == mainJsonObject.size())
                    .collect(Collectors.toList());

            if (methods.size() == 0) {
                throw new IllegalStateException(
                        String.format("No such method %s with compatible parameters.", methodName));
            }

            if (methods.size() > 1) {
                throw new IllegalStateException("Overridden methods are not supported yet.");
            }

            final Method m = methods.get(0);

            final Parameter[] methodParams = m.getParameters();
            final Object[] paramValues = new Object[methodParams.length];
            final ConvertUtilsBean convert = new ConvertUtilsBean();
            for (int i = 0; i < methodParams.length; i++) {
                final Parameter methodParameter = methodParams[i];
                final String paramName = getParamName(methodParameter, m, beanClass);
                final Object jsonObject = mainJsonObject.getValue(paramName);
                paramValues[i] = convert.convert(jsonObject, methodParameter.getType());
            }

            @SuppressWarnings("unchecked")
            Set<Object> services = context.lookupLocalMicroservice(
                    new MicroserviceMetaData(microserviceName, beanClass, bean.getQualifiers()));
            JsonObject response = new JsonObject();
            try {
                Object result = m.invoke(services.iterator().next(), paramValues);
                response.put("result", Json.encodePrettily(result));
                response.put("resultPlain", JsonWriter.objectToJson(result));
            } catch (Exception e) {
                response.put("exception", e.toString());
                response.put("stackTrace", stackTraceAsString(e));
                log.warn("Could not call method: ", e);
            }

            routingContext.response().end(response.encodePrettily());
        } catch (Exception e) {
            log.warn(String.format("Unable to call method %s#%s: ", microserviceName, methodName), e);
            routingContext.response().setStatusCode(503).end("Resource not available.");
        }
    });
}

From source file:nl.openweb.jcr.Importer.java

private Value toJcrValue(Session session, Object value, String propertyName) throws RepositoryException {
    Value result;//  w ww .  j av a 2s. c  o  m
    ValueFactory valueFactory = session.getValueFactory();
    String valueType = NodeBeanUtils.getValueType(value);
    ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
    int type = PropertyType.valueFromName(valueType);
    String valueAsString = NodeBeanUtils.getValueAsString(value);
    if (addUnknownTypes && type == PropertyType.NAME) {
        if (JCR_MIXIN_TYPES.equals(propertyName)) {
            NodeTypeUtils.createMixin(session, valueAsString);
        } else {
            NodeTypeUtils.createNodeType(session, valueAsString);
        }
    }
    switch (type) {
    case PropertyType.BOOLEAN:
        result = valueFactory.createValue((Boolean) convertUtilsBean.convert(valueAsString, Boolean.class));
        break;
    case PropertyType.DOUBLE:
        result = valueFactory.createValue((Double) convertUtilsBean.convert(valueAsString, Double.class));
        break;
    case PropertyType.LONG:
        result = valueFactory.createValue((Long) convertUtilsBean.convert(valueAsString, Long.class));
        break;
    default:
        result = valueFactory.createValue(valueAsString, type);
        break;
    }
    return result;
}

From source file:nl.openweb.jcr.NodeBeanUtils.java

private static Object convertValue(String value, String type) {
    Object result;//from   ww  w.  j  a va2 s  . c  om
    if (!NATIVE_TYPES.contains(type)) {
        Map<String, Object> map = new HashMap<>();
        map.put(PRIMITIVE_TYPE, type);
        map.put(VALUE, value);
        result = map;
    } else {
        ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();
        result = convertUtilsBean.convert(value, getType(type));
    }
    return result;

}

From source file:org.beangle.ems.security.restrict.service.CsvDataResolver.java

@SuppressWarnings("unchecked")
public <T> List<T> unmarshal(RestrictField field, String source) {
    if (StringUtils.isEmpty(source)) {
        return Collections.emptyList();
    }/* ww  w. j  a  va 2s  .  co m*/
    List<String> properties = CollectUtils.newArrayList();
    if (null != field.getKeyName()) {
        properties.add(field.getKeyName());
    }
    if (null != field.getPropertyNames()) {
        String[] names = StringUtils.split(field.getPropertyNames(), ",");
        properties.addAll(Arrays.asList(names));
    }
    String[] datas = StringUtils.split(source, ",");
    try {
        Class<?> type = null;
        type = Class.forName(field.getType());
        List<T> rs = CollectUtils.newArrayList();
        if (properties.isEmpty()) {
            ConvertUtilsBean converter = Converter.getDefault();
            for (String data : datas) {
                rs.add((T) converter.convert(data, type));
            }
            return rs;
        } else {
            properties.clear();
            int startIndex = 0;
            String[] names = new String[] { field.getKeyName() };
            if (-1 != datas[0].indexOf(';')) {
                names = StringUtils.split(datas[0], ";");
                startIndex = 1;
            }
            properties.addAll(Arrays.asList(names));
            for (int i = startIndex; i < datas.length; i++) {
                Object obj = type.newInstance();
                String[] dataItems = StringUtils.split(datas[i], ";");
                for (int j = 0; j < properties.size(); j++) {
                    BeanUtils.setProperty(obj, properties.get(j), dataItems[j]);
                }
                rs.add((T) obj);
            }
        }
        return rs;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.opencms.workplace.CmsWidgetDialogParameter.java

/**
 * "Commits" (writes) the value of this widget back to the underlying base object.<p> 
 * //  w  w w .j av  a 2s.c  o  m
 * @param dialog the widget dialog where the parameter is used on
 * 
 * @throws CmsException in case the String value of the widget is invalid for the base Object
 */
@SuppressWarnings("unchecked")
public void commitValue(CmsWidgetDialog dialog) throws CmsException {

    if (m_baseCollection == null) {
        PropertyUtilsBean bean = new PropertyUtilsBean();
        ConvertUtilsBean converter = new ConvertUtilsBean();
        Object value = null;
        try {
            Class<?> type = bean.getPropertyType(m_baseObject, m_baseObjectProperty);
            value = converter.convert(m_value, type);
            bean.setNestedProperty(m_baseObject, m_baseObjectProperty, value);
            setError(null);
        } catch (InvocationTargetException e) {
            setError(e.getTargetException());
            throw new CmsWidgetException(Messages.get().container(Messages.ERR_PROPERTY_WRITE_3, value,
                    dialog.keyDefault(A_CmsWidget.getLabelKey(this), getKey()),
                    m_baseObject.getClass().getName()), e.getTargetException(), this);
        } catch (Exception e) {
            setError(e);
            throw new CmsWidgetException(Messages.get().container(Messages.ERR_PROPERTY_WRITE_3, value,
                    dialog.keyDefault(A_CmsWidget.getLabelKey(this), getKey()),
                    m_baseObject.getClass().getName()), e, this);
        }
    } else if (m_baseCollection instanceof SortedMap) {
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_value)) {
            int pos = m_value.indexOf('=');
            if ((pos > 0) && (pos < (m_value.length() - 1))) {
                String key = m_value.substring(0, pos);
                String value = m_value.substring(pos + 1);
                @SuppressWarnings("rawtypes")
                SortedMap map = (SortedMap) m_baseCollection;
                if (map.containsKey(key)) {
                    Object val = map.get(key);
                    CmsWidgetException error = new CmsWidgetException(
                            Messages.get().container(Messages.ERR_MAP_DUPLICATE_KEY_3,
                                    dialog.keyDefault(A_CmsWidget.getLabelKey(this), getKey()), key, val),
                            this);
                    setError(error);
                    throw error;
                }
                map.put(key, value);
            } else {
                CmsWidgetException error = new CmsWidgetException(
                        Messages.get().container(Messages.ERR_MAP_PARAMETER_FORM_1,
                                dialog.keyDefault(A_CmsWidget.getLabelKey(this), getKey())),
                        this);
                setError(error);
                throw error;
            }
        }
    } else if (m_baseCollection instanceof List) {
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_value)) {
            @SuppressWarnings("rawtypes")
            List list = (List) m_baseCollection;
            list.add(m_value);
        }
    }
}