Example usage for org.springframework.util StringUtils capitalize

List of usage examples for org.springframework.util StringUtils capitalize

Introduction

In this page you can find the example usage for org.springframework.util StringUtils capitalize.

Prototype

public static String capitalize(String str) 

Source Link

Document

Capitalize a String , changing the first letter to upper case as per Character#toUpperCase(char) .

Usage

From source file:org.springframework.jdbc.core.AbstractBeanPropertyRowMapper.java

protected Object doMapRow(ResultSet rs, int rowNumber) throws SQLException {
    if (getMappedClass() == null)
        throw new InvalidDataAccessApiUsageException("Target class was not specified - it is mandatory");
    Object result;//from  w  w w  .j a v  a 2  s . co  m
    try {
        result = this.defaultConstruct.newInstance((Object[]) null);
    } catch (IllegalAccessException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InvocationTargetException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InstantiationException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    }
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    for (int i = 1; i <= columns; i++) {
        String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase();
        PersistentField fieldMeta = (PersistentField) this.mappedFields.get(column);
        if (fieldMeta != null) {
            BeanWrapper bw = new BeanWrapperImpl(mappedClass);
            bw.setWrappedInstance(result);
            fieldMeta.setSqlType(rsmd.getColumnType(i));
            Object value = null;
            Class fieldType = fieldMeta.getJavaType();
            if (fieldType.equals(String.class)) {
                value = rs.getString(column);
            } else if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) {
                value = new Byte(rs.getByte(column));
            } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
                value = new Short(rs.getShort(column));
            } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                value = new Integer(rs.getInt(column));
            } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                value = new Long(rs.getLong(column));
            } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                value = new Float(rs.getFloat(column));
            } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                value = new Double(rs.getDouble(column));
            } else if (fieldType.equals(BigDecimal.class)) {
                value = rs.getBigDecimal(column);
            } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
                value = (rs.getBoolean(column)) ? Boolean.TRUE : Boolean.FALSE;
            } else if (fieldType.equals(java.util.Date.class) || fieldType.equals(java.sql.Timestamp.class)
                    || fieldType.equals(java.sql.Time.class) || fieldType.equals(Number.class)) {
                value = JdbcUtils.getResultSetValue(rs, rs.findColumn(column));
            }
            if (value != null) {
                if (bw.isWritableProperty(fieldMeta.getFieldName())) {
                    try {
                        if (logger.isDebugEnabled() && rowNumber == 0) {
                            logger.debug("Mapping column named \"" + column + "\""
                                    + " containing values of SQL type " + fieldMeta.getSqlType()
                                    + " to property \"" + fieldMeta.getFieldName() + "\"" + " of type "
                                    + fieldMeta.getJavaType());
                        }
                        bw.setPropertyValue(fieldMeta.getFieldName(), value);
                    } catch (NotWritablePropertyException ex) {
                        throw new DataRetrievalFailureException(
                                "Unable to map column " + column + " to property " + fieldMeta.getFieldName(),
                                ex);
                    }
                } else {
                    if (rowNumber == 0) {
                        logger.warn("Unable to access the setter for " + fieldMeta.getFieldName()
                                + ".  Check that " + "set" + StringUtils.capitalize(fieldMeta.getFieldName())
                                + " is declared and has public access.");
                    }
                }
            }
        }
    }
    return result;
}

From source file:org.springframework.jmx.support.JmxUtils.java

/**
 * Return the JMX attribute name to use for the given JavaBeans property.
 * <p>When using strict casing, a JavaBean property with a getter method
 * such as {@code getFoo()} translates to an attribute called
 * {@code Foo}. With strict casing disabled, {@code getFoo()}
 * would translate to just {@code foo}.// w  w  w  .j  a  v  a2  s  .  c  o m
 * @param property the JavaBeans property descriptor
 * @param useStrictCasing whether to use strict casing
 * @return the JMX attribute name to use
 */
public static String getAttributeName(PropertyDescriptor property, boolean useStrictCasing) {
    if (useStrictCasing) {
        return StringUtils.capitalize(property.getName());
    } else {
        return property.getName();
    }
}

From source file:org.springframework.scripting.support.ScriptFactoryPostProcessor.java

/**
 * Create a config interface for the given bean definition, defining setter
 * methods for the defined property values as well as an init method and
 * a destroy method (if defined)./*w ww .j  a va  2 s.  c  om*/
 * <p>This implementation creates the interface via CGLIB's InterfaceMaker,
 * determining the property types from the given interfaces (as far as possible).
 * @param bd the bean definition (property values etc) to create a
 * config interface for
 * @param interfaces the interfaces to check against (might define
 * getters corresponding to the setters we're supposed to generate)
 * @return the config interface
 * @see org.springframework.cglib.proxy.InterfaceMaker
 * @see org.springframework.beans.BeanUtils#findPropertyType
 */
protected Class<?> createConfigInterface(BeanDefinition bd, @Nullable Class<?>[] interfaces) {
    InterfaceMaker maker = new InterfaceMaker();
    PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues();
    for (PropertyValue pv : pvs) {
        String propertyName = pv.getName();
        Class<?> propertyType = BeanUtils.findPropertyType(propertyName, interfaces);
        String setterName = "set" + StringUtils.capitalize(propertyName);
        Signature signature = new Signature(setterName, Type.VOID_TYPE,
                new Type[] { Type.getType(propertyType) });
        maker.add(signature, new Type[0]);
    }
    if (bd instanceof AbstractBeanDefinition) {
        AbstractBeanDefinition abd = (AbstractBeanDefinition) bd;
        if (abd.getInitMethodName() != null) {
            Signature signature = new Signature(abd.getInitMethodName(), Type.VOID_TYPE, new Type[0]);
            maker.add(signature, new Type[0]);
        }
        if (StringUtils.hasText(abd.getDestroyMethodName())) {
            Signature signature = new Signature(abd.getDestroyMethodName(), Type.VOID_TYPE, new Type[0]);
            maker.add(signature, new Type[0]);
        }
    }
    return maker.create();
}

From source file:org.springframework.test.util.ReflectionTestUtils.java

/**
 * Invoke the setter method with the given {@code name} on the supplied
 * target object with the supplied {@code value}.
 * <p>This method traverses the class hierarchy in search of the desired
 * method. In addition, an attempt will be made to make non-{@code public}
 * methods <em>accessible</em>, thus allowing one to invoke {@code protected},
 * {@code private}, and <em>package-private</em> setter methods.
 * <p>In addition, this method supports JavaBean-style <em>property</em>
 * names. For example, if you wish to set the {@code name} property on the
 * target object, you may pass either &quot;name&quot; or
 * &quot;setName&quot; as the method name.
 * @param target the target object on which to invoke the specified setter
 * method/*from  w w w  .jav  a  2  s.c  o  m*/
 * @param name the name of the setter method to invoke or the corresponding
 * property name
 * @param value the value to provide to the setter method
 * @param type the formal parameter type declared by the setter method
 * @see ReflectionUtils#findMethod(Class, String, Class[])
 * @see ReflectionUtils#makeAccessible(Method)
 * @see ReflectionUtils#invokeMethod(Method, Object, Object[])
 */
public static void invokeSetterMethod(Object target, String name, @Nullable Object value,
        @Nullable Class<?> type) {
    Assert.notNull(target, "Target object must not be null");
    Assert.hasText(name, "Method name must not be empty");
    Class<?>[] paramTypes = (type != null ? new Class<?>[] { type } : null);

    String setterMethodName = name;
    if (!name.startsWith(SETTER_PREFIX)) {
        setterMethodName = SETTER_PREFIX + StringUtils.capitalize(name);
    }

    Method method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
    if (method == null && !setterMethodName.equals(name)) {
        setterMethodName = name;
        method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
    }
    if (method == null) {
        throw new IllegalArgumentException(
                String.format("Could not find setter method '%s' on %s with parameter type [%s]",
                        setterMethodName, safeToString(target), type));
    }

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Invoking setter method '%s' on %s with value [%s]", setterMethodName,
                safeToString(target), value));
    }

    ReflectionUtils.makeAccessible(method);
    ReflectionUtils.invokeMethod(method, target, value);
}

From source file:org.springframework.test.util.ReflectionTestUtils.java

/**
 * Invoke the getter method with the given {@code name} on the supplied
 * target object with the supplied {@code value}.
 * <p>This method traverses the class hierarchy in search of the desired
 * method. In addition, an attempt will be made to make non-{@code public}
 * methods <em>accessible</em>, thus allowing one to invoke {@code protected},
 * {@code private}, and <em>package-private</em> getter methods.
 * <p>In addition, this method supports JavaBean-style <em>property</em>
 * names. For example, if you wish to get the {@code name} property on the
 * target object, you may pass either &quot;name&quot; or
 * &quot;getName&quot; as the method name.
 * @param target the target object on which to invoke the specified getter
 * method/*from  w  ww.  ja va2 s. c om*/
 * @param name the name of the getter method to invoke or the corresponding
 * property name
 * @return the value returned from the invocation
 * @see ReflectionUtils#findMethod(Class, String, Class[])
 * @see ReflectionUtils#makeAccessible(Method)
 * @see ReflectionUtils#invokeMethod(Method, Object, Object[])
 */
@Nullable
public static Object invokeGetterMethod(Object target, String name) {
    Assert.notNull(target, "Target object must not be null");
    Assert.hasText(name, "Method name must not be empty");

    String getterMethodName = name;
    if (!name.startsWith(GETTER_PREFIX)) {
        getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
    }
    Method method = ReflectionUtils.findMethod(target.getClass(), getterMethodName);
    if (method == null && !getterMethodName.equals(name)) {
        getterMethodName = name;
        method = ReflectionUtils.findMethod(target.getClass(), getterMethodName);
    }
    if (method == null) {
        throw new IllegalArgumentException(String.format("Could not find getter method '%s' on %s",
                getterMethodName, safeToString(target)));
    }

    if (logger.isDebugEnabled()) {
        logger.debug(
                String.format("Invoking getter method '%s' on %s", getterMethodName, safeToString(target)));
    }
    ReflectionUtils.makeAccessible(method);
    return ReflectionUtils.invokeMethod(method, target);
}

From source file:org.springframework.webflow.validation.ValidationHelper.java

private boolean invokeValidateMethodForCurrentState(Object model) {
    String methodName = "validate" + StringUtils.capitalize(requestContext.getCurrentState().getId());
    // preferred/* w  ww .  j  a  v  a2s. c  o  m*/
    Method validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName,
            new Class[] { ValidationContext.class });
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Invoking current state model validation method '" + methodName + "(ValidationContext)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, model,
                new Object[] { new DefaultValidationContext(requestContext, eventId, mappingResults) });
        return true;
    }
    // web flow 2.0.3 or < compatibility only
    validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName,
            new Class[] { MessageContext.class });
    if (validateMethod != null) {
        ReflectionUtils.invokeMethod(validateMethod, model,
                new Object[] { requestContext.getMessageContext() });
        return true;
    }
    // mvc 2 compatibility only
    validateMethod = ReflectionUtils.findMethod(model.getClass(), methodName, new Class[] { Errors.class });
    if (validateMethod != null) {
        MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
                model, expressionParser, messageCodesResolver, mappingResults);
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking current state model validation method '" + methodName + "(Errors)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, model, new Object[] { errors });
        return true;
    }
    return false;
}

From source file:org.springframework.webflow.validation.ValidationHelper.java

private boolean invokeValidatorValidateMethodForCurrentState(Object model, Object validator) {
    String methodName = "validate" + StringUtils.capitalize(requestContext.getCurrentState().getId());
    // preferred//ww  w. j ava  2s  .  c om
    Method validateMethod = findValidationMethod(model, validator, methodName, ValidationContext.class);
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking current state validator method '"
                    + ClassUtils.getShortName(validator.getClass()) + "." + methodName + "("
                    + ClassUtils.getShortName(model.getClass()) + ", ValidationContext)'");
        }
        ReflectionUtils.invokeMethod(validateMethod, validator,
                new Object[] { model, new DefaultValidationContext(requestContext, eventId, mappingResults) });
        return true;
    }
    // mvc 2 compatibility only
    validateMethod = findValidationMethod(model, validator, methodName, Errors.class);
    if (validateMethod != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking current state validator method '"
                    + ClassUtils.getShortName(validator.getClass()) + "." + methodName + "("
                    + ClassUtils.getShortName(model.getClass()) + ", Errors)'");
        }
        MessageContextErrors errors = new MessageContextErrors(requestContext.getMessageContext(), modelName,
                model, expressionParser, messageCodesResolver, mappingResults);
        ReflectionUtils.invokeMethod(validateMethod, validator, new Object[] { model, errors });
        return true;
    }
    // web flow 2.0.0 to 2.0.3 compatibility only [to remove in web flow 3]
    validateMethod = findValidationMethod(model, validator, methodName, MessageContext.class);
    if (validateMethod != null) {
        ReflectionUtils.invokeMethod(validateMethod, validator,
                new Object[] { model, requestContext.getMessageContext() });
        return true;
    }
    return false;
}

From source file:org.usergrid.tools.Command.java

/**
 * @param args// w  w  w .  j a  va 2 s . co m
 */
public static void main(String[] args) {

    if ((args == null) || (args.length < 1)) {
        System.out.println("No command specified");
        return;
    }

    String command = args[0];

    Class<?> clazz = null;

    try {
        clazz = Class.forName(command);
    } catch (ClassNotFoundException e) {
    }

    if (clazz == null) {
        try {
            clazz = Class.forName("org.usergrid.tools." + command);
        } catch (ClassNotFoundException e) {
        }
    }

    if (clazz == null) {
        try {
            clazz = Class.forName("org.usergrid.tools." + StringUtils.capitalize(command));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    if (clazz == null) {
        System.out.println("Unable to find command");
        return;
    }

    args = Arrays.copyOfRange(args, 1, args.length);

    try {
        if (ToolBase.class.isAssignableFrom(clazz)) {
            ToolBase tool = (ToolBase) clazz.newInstance();
            tool.startTool(args);
        } else {
            MethodUtils.invokeStaticMethod(clazz, "main", (Object) args);
        }
    } catch (NoSuchMethodException e) {
        System.out.println("Unable to invoke command");
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        System.out.println("Unable to invoke command");
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        System.out.println("Error while invoking command");
        e.printStackTrace();
    } catch (InstantiationException e) {
        System.out.println("Error while instantiating tool object");
        e.printStackTrace();
    }
}