Example usage for java.beans Introspector decapitalize

List of usage examples for java.beans Introspector decapitalize

Introduction

In this page you can find the example usage for java.beans Introspector decapitalize.

Prototype

public static String decapitalize(String name) 

Source Link

Document

Utility method to take a string and convert it to normal Java variable name capitalization.

Usage

From source file:org.apache.axis.utils.JavaUtils.java

/**
 * Map an XML name to a Java identifier per
 * the mapping rules of JSR 101 (in version 1.0 this is
 * "Chapter 20: Appendix: Mapping of XML Names"
 * /*from   w w  w.  j  a v  a  2 s . c  om*/
 * @param name is the xml name
 * @return the java name per JSR 101 specification
 */
public static String xmlNameToJava(String name) {
    // protect ourselves from garbage
    if (name == null || name.equals(""))
        return name;

    char[] nameArray = name.toCharArray();
    int nameLen = name.length();
    StringBuffer result = new StringBuffer(nameLen);
    boolean wordStart = false;

    // The mapping indicates to convert first character.
    int i = 0;
    while (i < nameLen && (isPunctuation(nameArray[i]) || !Character.isJavaIdentifierStart(nameArray[i]))) {
        i++;
    }
    if (i < nameLen) {
        // Decapitalization code used to be here, but we use the
        // Introspector function now after we filter out all bad chars.

        result.append(nameArray[i]);
        //wordStart = !Character.isLetter(nameArray[i]);
        wordStart = !Character.isLetter(nameArray[i]) && nameArray[i] != "_".charAt(0);
    } else {
        // The identifier cannot be mapped strictly according to
        // JSR 101
        if (Character.isJavaIdentifierPart(nameArray[0])) {
            result.append("_" + nameArray[0]);
        } else {
            // The XML identifier does not contain any characters
            // we can map to Java.  Using the length of the string
            // will make it somewhat unique.
            result.append("_" + nameArray.length);
        }
    }

    // The mapping indicates to skip over
    // all characters that are not letters or
    // digits.  The first letter/digit
    // following a skipped character is
    // upper-cased.
    for (++i; i < nameLen; ++i) {
        char c = nameArray[i];

        // if this is a bad char, skip it and remember to capitalize next
        // good character we encounter
        if (isPunctuation(c) || !Character.isJavaIdentifierPart(c)) {
            wordStart = true;
            continue;
        }
        if (wordStart && Character.isLowerCase(c)) {
            result.append(Character.toUpperCase(c));
        } else {
            result.append(c);
        }
        // If c is not a character, but is a legal Java
        // identifier character, capitalize the next character.
        // For example:  "22hi" becomes "22Hi"
        //wordStart = !Character.isLetter(c);
        wordStart = !Character.isLetter(c) && c != "_".charAt(0);
    }

    // covert back to a String
    String newName = result.toString();

    // Follow JavaBean rules, but we need to check if the first 
    // letter is uppercase first
    if (Character.isUpperCase(newName.charAt(0)))
        newName = Introspector.decapitalize(newName);

    // check for Java keywords
    if (isJavaKeyword(newName))
        newName = makeNonJavaKeyword(newName);

    return newName;
}

From source file:org.apache.bval.util.MethodAccess.java

/**
 * Process bean properties getter by applying the JavaBean naming conventions.
 *
 * @param member the member for which to get the property name.
 * @return The bean method name with the "is" or "get" prefix stripped off, <code>null</code>
 *         the method name id not according to the JavaBeans standard.
 *//*  w  w w .  j a v  a2  s .  c o  m*/
public static String getPropertyName(Method member) {
    final String methodName = member.getName();
    if (methodName.startsWith("is")) {
        return Introspector.decapitalize(methodName.substring(2));
    }
    if (methodName.startsWith("get")) {
        return Introspector.decapitalize(methodName.substring(3));
    }
    return null;
}

From source file:org.apache.jcs.config.PropertySetter.java

/**
 * Set a property on this PropertySetter's Object. If successful, this
 * method will invoke a setter method on the underlying Object. The setter
 * is the one for the specified property name and the value is determined
 * partly from the setter argument type and partly from the value specified
 * in the call to this method./*  www . j  ava2 s. com*/
 * <p>
 *
 * If the setter expects a String no conversion is necessary. If it expects
 * an int, then an attempt is made to convert 'value' to an int using new
 * Integer(value). If the setter expects a boolean, the conversion is by new
 * Boolean(value).
 *
 * @param name
 *            name of the property
 * @param value
 *            String value of the property
 */

public void setProperty(String name, String value) {
    if (value == null) {
        return;
    }

    name = Introspector.decapitalize(name);
    PropertyDescriptor prop = getPropertyDescriptor(name);

    //log.debug("---------Key: "+name+", type="+prop.getPropertyType());

    if (prop == null) {
        log.warn("No such property [" + name + "] in " + obj.getClass().getName() + ".");
    } else {
        try {
            setProperty(prop, name, value);
        } catch (PropertySetterException ex) {
            log.warn("Failed to set property " + name + " to value \"" + value + "\". " + ex.getMessage());
        }
    }
}

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

/**
 * Create a property descriptor for the given value.
 *///from w ww .  ja  v a 2  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;
}

From source file:org.carrot2.workbench.core.helpers.SimpleXmlMemento.java

/**
 * Mimics SimpleXML's naming for classes without {@link Root#name()}.
 *//*from ww w  . j  av a  2  s .c  om*/
private static String getClassName(Class<?> type) {
    if (type.isArray())
        type = type.getComponentType();
    final String name = type.getSimpleName();
    if (type.isPrimitive())
        return name;
    else
        return Introspector.decapitalize(name);
}

From source file:org.compass.core.accessor.BasicPropertyAccessor.java

private static Method setterMethod(Class theClass, String propertyName) {

    BasicGetter getter = getGetterOrNull(theClass, propertyName);
    Class returnType = (getter == null) ? null : getter.getReturnType();

    Method[] methods = theClass.getDeclaredMethods();
    Method potentialSetter = null;
    for (Method method : methods) {
        String methodName = method.getName();

        if (method.getParameterTypes().length == 1 && methodName.startsWith("set")) {
            String testStdMethod = Introspector.decapitalize(methodName.substring(3));
            String testOldMethod = methodName.substring(3);
            if (testStdMethod.equals(propertyName) || testOldMethod.equals(propertyName)) {
                potentialSetter = method;
                if (returnType == null || method.getParameterTypes()[0].equals(returnType))
                    return potentialSetter;
            }/*from   w ww  . j  a v a2 s.  co m*/
        }
    }
    return potentialSetter;
}

From source file:org.compass.core.accessor.BasicPropertyAccessor.java

private static Method getterMethod(Class theClass, String propertyName) {

    Method[] methods = theClass.getDeclaredMethods();
    for (Method method : methods) {
        // only carry on if the method has no parameters
        if (method.getParameterTypes().length == 0) {
            String methodName = method.getName();

            // try "get"
            if (methodName.startsWith("get")) {
                String testStdMethod = Introspector.decapitalize(methodName.substring(3));
                String testOldMethod = methodName.substring(3);
                if (testStdMethod.equals(propertyName) || testOldMethod.equals(propertyName))
                    return method;

            }//from ww  w  .  j  ava 2s.  c om

            // if not "get" then try "is"
            /*
             * boolean isBoolean =
             * methods[i].getReturnType().equals(Boolean.class) ||
             * methods[i].getReturnType().equals(boolean.class);
             */
            if (methodName.startsWith("is")) {
                String testStdMethod = Introspector.decapitalize(methodName.substring(2));
                String testOldMethod = methodName.substring(2);
                if (testStdMethod.equals(propertyName) || testOldMethod.equals(propertyName))
                    return method;
            }
        }
    }
    return null;
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

private static String getQualifiedPropertyName(Method method) {
    // strip Method name to property name
    String propertyName;/*from  ww w  .j  a  va  2  s  . c  om*/
    {
        propertyName = method.getName();
        if (propertyName.startsWith("is")) {
            propertyName = propertyName.substring(2);
        } else if (propertyName.startsWith("get")) {
            propertyName = propertyName.substring(3);
        } else if (propertyName.startsWith("set")) {
            propertyName = propertyName.substring(3);
        }
        propertyName = Introspector.decapitalize(propertyName);
    }
    // include also type
    String types;
    {
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length == 0) {
            types = "(" + getFullyQualifiedName(method.getReturnType(), false) + ")";
        } else {
            StringBuilder buffer = new StringBuilder();
            appendParameterTypes(buffer, parameterTypes);
            types = buffer.toString();
        }
    }
    // return qualified property name
    return propertyName + types;
}

From source file:org.grails.datastore.mapping.reflect.ClassPropertyFetcher.java

private void processMethod(Method method) {
    if (method.isSynthetic()) {
        return;//  ww w. jav  a2 s .  co m
    }
    if (!Modifier.isPublic(method.getModifiers())) {
        return;
    }
    if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) {
        if (method.getParameterTypes().length == 0) {
            String name = method.getName();
            if (name.indexOf('$') == -1) {
                if (name.length() > 3 && name.startsWith("get") && Character.isUpperCase(name.charAt(3))) {
                    name = name.substring(3);
                } else if (name.length() > 2 && name.startsWith("is") && Character.isUpperCase(name.charAt(2))
                        && (method.getReturnType() == Boolean.class
                                || method.getReturnType() == boolean.class)) {
                    name = name.substring(2);
                }
                PropertyFetcher fetcher = new GetterPropertyFetcher(method, true);
                List<PropertyFetcher> propertyFetchers = staticFetchers.get(name);
                if (propertyFetchers == null) {
                    staticFetchers.put(name, propertyFetchers = new ArrayList<PropertyFetcher>());
                }
                propertyFetchers.add(fetcher);
                String decapitalized = Introspector.decapitalize(name);
                if (!decapitalized.equals(name)) {
                    propertyFetchers = staticFetchers.get(decapitalized);
                    if (propertyFetchers == null) {
                        staticFetchers.put(decapitalized, propertyFetchers = new ArrayList<PropertyFetcher>());
                    }
                    propertyFetchers.add(fetcher);
                }
            }
        }
    }
}

From source file:org.gvnix.web.screen.roo.addon.AbstractPatternJspMetadataListener.java

protected String uncapitalize(String term) {
    // [ROO-1790] this is needed to adhere to the JavaBean naming
    // conventions (see JavaBean spec section 8.8)
    return Introspector.decapitalize(StringUtils.capitalize(term));
}