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

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

Introduction

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

Prototype

public ConvertUtilsBean() 

Source Link

Document

Construct a bean with standard converters registered

Usage

From source file:ch.algotrader.adapter.ib.DefaultIBOrderMessageFactory.java

public DefaultIBOrderMessageFactory(IBConfig iBConfig) {
    this.iBConfig = iBConfig;
    this.convertUtils = new ConvertUtilsBean();
}

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()));
    }// w  w w  . 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.cyclopsgroup.waterview.utils.TypeUtils.java

/**
 * @return Convert utils//from w ww.java 2  s  .co m
 */
public synchronized static ConvertUtilsBean getConvertUtils() {
    if (convertUtils == null) {
        convertUtils = new ConvertUtilsBean();
        convertUtils.register(new DateConverter(), Date.class);
        convertUtils.register(new StringConverterAdapter(), String.class);
    }

    return convertUtils;
}

From source file:com.utest.webservice.builders.Builder.java

public Ti toInfo(final To object, final UriBuilder ub, Object... uriBuilderArgs) throws Exception {
    Ti result;//from   w w  w . ja v  a2s . c  om
    final Constructor<Ti> constr = infoClass.getConstructor(new Class[] {});
    if (constr == null) {
        throw new IllegalArgumentException("No default constructor found for " + infoClass.getName());
    }
    result = constr.newInstance(new Object[] {});
    ConvertUtilsBean cub = new ConvertUtilsBean();
    // do not throw exceptions on null values
    cub.register(false, true, 0);
    BeanUtilsBean bub = new BeanUtilsBean(cub);
    bub.copyProperties(result, object);
    // PropertyUtils.copyProperties(result, object);
    if (object instanceof LocalizedEntity) {
        LocalizedEntity localizedEntity = (LocalizedEntity) object;
        LocaleDescriptable localDescriptable = localizedEntity.getLocale(Locale.DEFAULT_LOCALE);
        // PropertyUtils.copyProperties(result, localDescriptable);
        bub.copyProperties(result, localDescriptable);
    }
    Map<?, ?> resultProperties = PropertyUtils.describe(result);
    // don't return password field
    if (resultProperties.containsKey("password")) {
        PropertyUtils.setProperty(result, "password", null);
    }
    //
    populateLocators(result, ub);
    //
    if (result instanceof BaseInfo) {
        populateIdentityAndTimeline((BaseInfo) result, object, ub, uriBuilderArgs);
    }

    // special handling for descendands of Builder
    populateExtendedProperties(result, object, ub, uriBuilderArgs);

    return result;
}

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

/**
 * This method takes the current value of the field in question in the bean
 * passed in and converts it to a string.
 * It works for all of the primitives, wrapped primitives,
 * {@link java.lang.String}, {@link java.math.BigDecimal}, and
 * {@link java.math.BigInteger}.// ww  w . j  a v  a 2  s  .co  m
 * 
 * @throws CsvDataTypeMismatchException If there is an error converting
 *   value to a string
 */
// The rest of the JavaDoc is automatically inherited from the base class.
@Override
protected String convertToWrite(Object value)
        throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
    // Validation
    if (value == null) {
        if (required) {
            throw new CsvRequiredFieldEmptyException();
        } else {
            return null;
        }
    }

    // Conversion
    String result;
    try {
        if (StringUtils.isEmpty(locale)) {
            ConvertUtilsBean converter = new ConvertUtilsBean();
            result = converter.convert(value);
        } else {
            LocaleConvertUtilsBean converter = new LocaleConvertUtilsBean();
            converter.setDefaultLocale(new Locale(locale));
            result = converter.convert(value);
        }
    } catch (ConversionException e) {
        CsvDataTypeMismatchException csve = new CsvDataTypeMismatchException(
                "The field must be primitive, boxed primitive, BigDecimal, BigInteger or String types only.");
        csve.initCause(e);
        throw csve;
    }
    return result;
}

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);
    }/*from   w w w.j  a  va  2s. c om*/
    return source;
}

From source file:com.meidusa.venus.frontend.http.VenusPoolFactory.java

@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
    logger.trace("current Venus Client id=" + PacketConstant.VENUS_CLIENT_ID);

    beanContext = new BeanContext() {
        public Object getBean(String beanName) {
            if (beanFactory != null) {
                return beanFactory.getBean(beanName);
            } else {
                return null;
            }//from  w w w.  j  a v a  2s  .c  o m
        }

        public Object createBean(Class clazz) throws Exception {
            if (beanFactory instanceof AutowireCapableBeanFactory) {
                AutowireCapableBeanFactory factory = (AutowireCapableBeanFactory) beanFactory;
                return factory.autowire(clazz, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
            }
            return null;
        }
    };

    BeanContextBean.getInstance().setBeanContext(beanContext);
    VenusBeanUtilsBean.setInstance(new BeanUtilsBean(new ConvertUtilsBean(), new PropertyUtilsBean()) {

        public void setProperty(Object bean, String name, Object value)
                throws IllegalAccessException, InvocationTargetException {
            if (value instanceof String) {
                PropertyDescriptor descriptor = null;
                try {
                    descriptor = getPropertyUtils().getPropertyDescriptor(bean, name);
                    if (descriptor == null) {
                        return; // Skip this property setter
                    } else {
                        if (descriptor.getPropertyType().isEnum()) {
                            Class<Enum> clazz = (Class<Enum>) descriptor.getPropertyType();
                            value = Enum.valueOf(clazz, (String) value);
                        } else {
                            Object temp = null;
                            try {
                                temp = ConfigUtil.filter((String) value, beanContext);
                            } catch (Exception e) {
                            }
                            if (temp == null) {
                                temp = ConfigUtil.filter((String) value);
                            }
                            value = temp;
                        }
                    }
                } catch (NoSuchMethodException e) {
                    return; // Skip this property setter
                }
            }
            super.setProperty(bean, name, value);
        }

    });

    reloadConfiguration();

    __RELOAD: {
        if (enableReload) {
            File[] files = new File[this.configFiles.length];
            for (int i = 0; i < this.configFiles.length; i++) {
                try {
                    files[i] = ResourceUtils.getFile(configFiles[i].trim());
                } catch (FileNotFoundException e) {
                    logger.warn(e.getMessage());
                    enableReload = false;
                    logger.warn("venus serviceFactory configuration reload disabled!");
                    break __RELOAD;
                }
            }
            VenusFileWatchdog dog = new VenusFileWatchdog(files);
            dog.setDelay(1000 * 10);
            dog.start();
        }
    }
}

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 {//  w w w. jav  a  2 s  .  c  o m
            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:com.meidusa.venus.client.VenusServiceFactory.java

@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
    logger.trace("current Venus Client id=" + PacketConstant.VENUS_CLIENT_ID);
    if (venusExceptionFactory == null) {
        XmlVenusExceptionFactory xmlVenusExceptionFactory = new XmlVenusExceptionFactory();

        //3.0.8??? exception ?
        //xmlVenusExceptionFactory.setConfigFiles(new String[] { "classpath:com/meidusa/venus/exception/VenusSystemException.xml" });
        xmlVenusExceptionFactory.init();
        this.venusExceptionFactory = xmlVenusExceptionFactory;
    }/*www .  j  av  a 2  s  . c om*/

    handler.setVenusExceptionFactory(venusExceptionFactory);
    if (enableAsync) {
        if (connector == null) {
            this.connector = new ConnectionConnector("connection Connector");
            connector.setDaemon(true);

        }

        if (connManager == null) {
            try {
                connManager = new ConnectionManager("Connection Manager", this.getAsyncExecutorSize());
            } catch (IOException e) {
                throw new InitialisationException(e);
            }
            connManager.setDaemon(true);
            connManager.start();
        }

        connector.setProcessors(new ConnectionManager[] { connManager });
        connector.start();
    }

    beanContext = new ClientBeanContext(beanFactory);
    BeanContextBean.getInstance().setBeanContext(beanContext);
    VenusBeanUtilsBean
            .setInstance(new ClientBeanUtilsBean(new ConvertUtilsBean(), new PropertyUtilsBean(), beanContext));
    AthenaExtensionResolver.getInstance().resolver();
    handler.setContainer(this.container);
    reloadConfiguration();

    __RELOAD: {
        if (enableReload) {
            File[] files = new File[this.configFiles.length];
            for (int i = 0; i < this.configFiles.length; i++) {
                try {
                    files[i] = ResourceUtils.getFile(configFiles[i].trim());
                } catch (FileNotFoundException e) {
                    logger.warn(e.getMessage());
                    enableReload = false;
                    logger.warn("venus serviceFactory configuration reload disabled!");
                    break __RELOAD;
                }
            }
            VenusFileWatchdog dog = new VenusFileWatchdog(files);
            dog.setDelay(1000 * 10);
            dog.start();
        }
    }
}