Example usage for org.apache.commons.lang StringUtils capitalize

List of usage examples for org.apache.commons.lang StringUtils capitalize

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils capitalize.

Prototype

public static String capitalize(String str) 

Source Link

Document

Capitalizes a String changing the first letter to title case as per Character#toTitleCase(char) .

Usage

From source file:org.apache.openjpa.enhance.PCEnhancer.java

/**
 * Return the name of the setter method for the given field.
 *//*  w w  w  .  j  a  v  a  2  s.  c  om*/
private static String getSetterName(FieldMetaData fmd) {
    return "set" + StringUtils.capitalize(fmd.getName());
}

From source file:org.apache.openjpa.enhance.PCEnhancer.java

/**
 * Helper method to add a stock method to the bytecode. Each
 * stock method simply delegates to a corresponding StateManager method.
 * Given the StateManager method, then, this function translates it into
 * the wrapper method that should be added to the bytecode.
 *///from ww w  . j ava 2  s. c  o m
private void translateFromStateManagerMethod(Method m, boolean isDirtyCheckMethod) {
    // form the name of the method by prepending 'pc' to the sm method
    String name = PRE + StringUtils.capitalize(m.getName());
    Class[] params = m.getParameterTypes();
    Class returnType = m.getReturnType();

    // add the method to the pc
    BCMethod method = _pc.declareMethod(name, returnType, params);
    Code code = method.getCode(true);

    // if (pcStateManager == null) return <default>;
    loadManagedInstance(code, false);
    code.getfield().setField(SM, SMTYPE);
    JumpInstruction ifins = code.ifnonnull();
    if (returnType.equals(boolean.class))
        code.constant().setValue(false);
    else if (!returnType.equals(void.class))
        code.constant().setNull();
    code.xreturn().setType(returnType);

    // if this is the dirty-check method and we're subclassing but not
    // redefining, hook into PCHelper to do the dirty check
    if (isDirtyCheckMethod && !getRedefine()) {
        // RedefinitionHelper.dirtyCheck(sm);
        ifins.setTarget(loadManagedInstance(code, false));
        code.getfield().setField(SM, SMTYPE);
        code.dup(); // for the return statement below
        code.invokestatic().setMethod(RedefinitionHelper.class, "dirtyCheck", void.class,
                new Class[] { SMTYPE });
    } else {
        ifins.setTarget(loadManagedInstance(code, false));
        code.getfield().setField(SM, SMTYPE);
    }

    // return pcStateManager.<method> (<args>);
    // managed instance loaded above in if-else block
    for (int i = 0; i < params.length; i++)
        code.xload().setParam(i);
    code.invokeinterface().setMethod(m);
    code.xreturn().setType(returnType);

    code.calculateMaxStack();
    code.calculateMaxLocals();
}

From source file:org.apache.openjpa.enhance.PCEnhancer.java

/**
 * Return the proper getter method of the {@link Reflection} helper for
 * a field or getter method of the given type.
 *//*from   www  .  j a  v  a2s  . co m*/
private Method getReflectionGetterMethod(Class type, Class argType) throws NoSuchMethodException {
    String name = "get";
    if (type.isPrimitive())
        name += StringUtils.capitalize(type.getName());
    return Reflection.class.getMethod(name, new Class[] { Object.class, argType });
}

From source file:org.apache.openjpa.enhance.PCEnhancer.java

/**
 * Adds a non-static getter that delegates to the super methods, and
 * performs any necessary field tracking.
 *//*from www  .j  a va 2s . c om*/
private void addSubclassGetMethod(FieldMetaData fmd) {
    String methName = "get" + StringUtils.capitalize(fmd.getName());
    if (_managedType.getMethods(methName, new Class[0]).length == 0)
        methName = "is" + StringUtils.capitalize(fmd.getName());
    BCMethod getter = _pc.declareMethod(methName, fmd.getDeclaredType(), null);
    setVisibilityToSuperMethod(getter);
    getter.makePublic();
    Code code = getter.getCode(true);

    // if we're not already tracking field access via reflection, then we
    // must make the getter hook in lazy loading before accessing the super
    // method.
    if (!getRedefine())
        addNotifyAccess(code, fmd);

    code.aload().setThis();
    code.invokespecial().setMethod(_managedType.getType(), methName, fmd.getDeclaredType(), null);
    code.xreturn().setType(fmd.getDeclaredType());
    code.calculateMaxLocals();
    code.calculateMaxStack();
}

From source file:org.apache.openjpa.enhance.PCSubclassValidator.java

private Method setterForField(FieldMetaData fmd) {
    try {/*from w ww. j  a v  a 2 s .co m*/
        return fmd.getDeclaringType().getDeclaredMethod("set" + StringUtils.capitalize(fmd.getName()),
                new Class[] { fmd.getDeclaredType() });
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:org.apache.openjpa.enhance.Reflection.java

/**
 * Return the getter method matching the given property name, optionally
 * throwing an exception if none.//from   w w  w  .  java  2s.c  o m
 */
public static Method findGetter(Class cls, String prop, boolean mustExist) {
    Method m = getGetterMethod(cls, prop);
    if (m != null) {
        return m;
    }
    String capProp = StringUtils.capitalize(prop);
    try {
        // this algorithm searches for a get<prop> or is<prop> method in
        // a breadth-first manner.
        for (Class c = cls; c != null && c != Object.class; c = c.getSuperclass()) {
            m = getDeclaredMethod(c, "get" + capProp, null);
            if (m != null) {
                setGetterMethod(cls, prop, m);
                return m;
            } else {
                m = getDeclaredMethod(c, "is" + capProp, null);
                if (m != null && (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class)) {
                    setGetterMethod(cls, prop, m);
                    return m;
                }
            }
        }
    } catch (Exception e) {
        throw new GeneralException(e);
    }

    if (mustExist)
        throw new UserException(_loc.get("bad-getter", cls, prop));
    return null;
}

From source file:org.apache.openjpa.enhance.Reflection.java

/**
 * Return the setter method matching the given property name, optionally
 * throwing an exception if none./*from   w  w w . j  a  v a  2s .c o m*/
 */
public static Method findSetter(Class cls, String prop, Class param, boolean mustExist) {
    Method m = getSetterMethod(cls, prop);
    if (m != null) {
        return m;
    }
    String name = "set" + StringUtils.capitalize(prop);
    try {
        for (Class c = cls; c != null && c != Object.class; c = c.getSuperclass()) {
            m = getDeclaredMethod(c, name, param);
            if (m != null) {
                setSetterMethod(cls, prop, m);
                return m;
            }
        }
    } catch (Exception e) {
        throw new GeneralException(e);
    }

    if (mustExist)
        throw new UserException(_loc.get("bad-setter", cls, prop));
    return null;
}

From source file:org.apache.openjpa.enhance.Reflection.java

/**
 * Gets all bean-style property names of the given Class or its superclass.
 * A bean-style property 'abc' exists in Class C iff C has declared 
 * following pair of methods:/*from  w  w w  . j  a  va 2s.c o  m*/
 *   public void setAbc(Y y) or public C setAbc(Y y)
 *   public Y getAbc();
 *   
 * If a getter property is annotated with {@link Reflectable}, then
 * it is ignored.
 *   
 */
public static Set<String> getBeanStylePropertyNames(Class<?> c) {
    if (c == null)
        return Collections.emptySet();
    Set<String> result = beanPropertiesNameCache.get(c);
    if (result != null) {
        return result;
    }
    Method[] methods = c.getMethods();
    if (methods == null || methods.length < 2)
        return Collections.emptySet();
    result = new TreeSet<String>();
    for (Method m : methods) {
        if (m.getName().startsWith("get")) {
            if (!canReflect(m))
                continue;
            String prop = StringUtils.capitalize(m.getName().substring("get".length()));
            Class<?> rtype = m.getReturnType();
            try {
                Method setter = c.getMethod("set" + prop, new Class<?>[] { rtype });
                if (setter.getReturnType() == void.class || setter.getReturnType().isAssignableFrom(c))
                    result.add(prop);
            } catch (NoSuchMethodException e) {

            }
        }
    }
    beanPropertiesNameCache.put(c, result);
    return result;
}

From source file:org.apache.openjpa.kernel.ResultPacker.java

/**
 * Return the set method for the given property.
 *///from w  ww.jav  a 2  s  . c  o  m
private static Member findSet(String alias, Class<?> type, Field[] fields, Method[] methods) {
    if (StringUtils.isEmpty(alias))
        return null;
    if (type == Object.class)
        type = null;

    // check public fields first
    Field field = null;
    for (int i = 0; i < fields.length; i++) {
        // if we find a field with the exact name, either return it
        // if it's the right type or give up if it's not
        if (fields[i].getName().equals(alias)) {
            if (type == null || Filters.canConvert(type, fields[i].getType(), true))
                return fields[i];
            break;
        }

        // otherwise if we find a field with the right name but the
        // wrong case, record it and if we don't find an exact match
        // for a field or setter we'll use it
        if (field == null && fields[i].getName().equalsIgnoreCase(alias)
                && (type == null || Filters.canConvert(type, fields[i].getType(), true)))
            field = fields[i];
    }

    // check setter methods
    String setName = "set" + StringUtils.capitalize(alias);
    Method method = null;
    boolean eqName = false;
    Class<?>[] params;
    for (int i = 0; i < methods.length; i++) {
        if (!methods[i].getName().equalsIgnoreCase(setName))
            continue;
        params = methods[i].getParameterTypes();
        if (params.length != 1)
            continue;

        if (type != null && params[0] == Object.class) {
            // we found a generic object setter; now see if the name
            // is an exact match, and if so record this setter.  if we
            // don't find an exact type match later, we'll use it.  if
            // the names are not an exact match, only record this setter
            // if we haven't found any others that match at all
            if (methods[i].getName().equals(setName)) {
                eqName = true;
                method = methods[i];
            } else if (method == null)
                method = methods[i];
        } else if (type == null || Filters.canConvert(type, params[0], true)) {
            // we found a setter with the right type; now see if the name
            // is an exact match.  if so, return the setter.  if not,
            // record the setter only if we haven't found a generic one
            // with an exact name match
            if (methods[i].getName().equals(setName))
                return methods[i];
            if (method == null || !eqName)
                method = methods[i];
        }
    }

    // if we have an exact method name match, return it; otherwise favor
    // an inexact field to an inexact method
    if (eqName || field == null)
        return method;
    return field;
}

From source file:org.apache.openjpa.lib.conf.ConfigurationImpl.java

/**
 * Create a property descriptor for the given value.
 *//*from w  ww . j  a va2 s  .  c  o  m*/
private PropertyDescriptor getPropertyDescriptor(Value val) throws IntrospectionException {
    String prop = val.getProperty();
    prop = prop.substring(prop.lastIndexOf('.') + 1);

    // set up property descriptor
    PropertyDescriptor pd;
    try {
        pd = new PropertyDescriptor(Introspector.decapitalize(prop), getClass());
    } catch (IntrospectionException ie) {
        // if there aren't any methods for this value(i.e., if it's a
        // dynamically-added value), then an IntrospectionException will
        // be thrown. Try to create a PD with no read or write methods.
        pd = new PropertyDescriptor(Introspector.decapitalize(prop), (Method) null, (Method) null);
    }
    pd.setDisplayName(findLocalized(prop + "-name", true, val.getScope()));
    pd.setShortDescription(findLocalized(prop + "-desc", true, val.getScope()));
    pd.setExpert("true".equals(findLocalized(prop + "-expert", false, val.getScope())));

    try {
        pd.setReadMethod(getClass().getMethod("get" + StringUtils.capitalize(prop), (Class[]) null));
        pd.setWriteMethod(getClass().getMethod("set" + StringUtils.capitalize(prop),
                new Class[] { pd.getReadMethod().getReturnType() }));
    } catch (Throwable t) {
        // if an error occurs, it might be because the value is a
        // dynamic property.
    }

    String type = findLocalized(prop + "-type", true, val.getScope());
    if (type != null)
        pd.setValue(ATTRIBUTE_TYPE, type);

    String cat = findLocalized(prop + "-cat", false, val.getScope());
    if (cat != null)
        pd.setValue(ATTRIBUTE_CATEGORY, cat);

    pd.setValue(ATTRIBUTE_XML, toXMLName(prop));

    String order = findLocalized(prop + "-displayorder", false, val.getScope());
    if (order != null)
        pd.setValue(ATTRIBUTE_ORDER, order);

    // collect allowed values from alias keys, listed values, and
    // interface implementors
    Collection<String> allowed = new TreeSet<String>();
    List<String> aliases = Collections.emptyList();
    if (val.getAliases() != null) {
        aliases = Arrays.asList(val.getAliases());
        for (int i = 0; i < aliases.size(); i += 2)
            allowed.add(aliases.get(i));
    }
    String[] vals = Strings.split(findLocalized(prop + "-values", false, val.getScope()), ",", 0);
    for (int i = 0; i < vals.length; i++)
        if (!aliases.contains(vals[i]))
            allowed.add(vals[i]);
    try {
        Class<?> intf = Class.forName(findLocalized(prop + "-interface", true, val.getScope()), false,
                getClass().getClassLoader());
        pd.setValue(ATTRIBUTE_INTERFACE, intf.getName());
        String[] impls = Services.getImplementors(intf);
        for (int i = 0; i < impls.length; i++)
            if (!aliases.contains(impls[i]))
                allowed.add(impls[i]);
    } catch (Throwable t) {
    }
    if (!allowed.isEmpty())
        pd.setValue(ATTRIBUTE_ALLOWED_VALUES, (String[]) allowed.toArray(new String[allowed.size()]));

    return pd;
}