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.jenkinsci.plugins.tokenmacro.DataBoundTokenMacro.java

/**
 * Builds up the {@link #setters} map that encapsulates where/how to set the value.
 *//*w w w.  j  av  a 2 s.com*/
private synchronized void buildMap() {
    if (setters != null)
        return;

    setters = new HashMap<String, Setter>();
    for (final Field f : getClass().getFields()) {
        final Parameter p = f.getAnnotation(Parameter.class);
        if (p != null) {
            setters.put(f.getName(), new Setter() {
                public Class getType() {
                    return f.getType();
                }

                public void set(Object target, Object value) {
                    try {
                        f.set(target, value);
                    } catch (IllegalAccessException e) {
                        throw (IllegalAccessError) new IllegalAccessError(e.getMessage()).initCause(e);
                    }
                }

                public boolean required() {
                    return p.required();
                }
            });
        }
    }

    for (final Method m : getClass().getMethods()) {
        final Parameter p = m.getAnnotation(Parameter.class);
        if (p != null) {
            final Class<?>[] pt = m.getParameterTypes();
            if (pt.length != 1)
                throw new IllegalArgumentException(
                        "Expecting one-arg method for @Parameter but found " + m + " instead");

            String name = m.getName();
            if (name.startsWith("set")) {
                name = Introspector.decapitalize(name.substring(3));
            }

            setters.put(name, new Setter() {
                public Class getType() {
                    return pt[0];
                }

                public void set(Object target, Object value) {
                    try {
                        m.invoke(target, value);
                    } catch (IllegalAccessException e) {
                        throw (IllegalAccessError) new IllegalAccessError(e.getMessage()).initCause(e);
                    } catch (InvocationTargetException e) {
                        throw new Error(e);
                    }
                }

                public boolean required() {
                    return p.required();
                }
            });
        }
    }
}

From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java

/**
 * Computes arguments suitable to pass to {@link #instantiate} to reconstruct this object.
 * @param o a data-bound object//ww  w. jav a 2  s . c  o m
 * @return constructor and/or setter parameters
 * @throws UnsupportedOperationException if the class does not follow the expected structure
 */
public static Map<String, Object> uninstantiate(Object o) throws UnsupportedOperationException {
    Class<?> clazz = o.getClass();
    Map<String, Object> r = new TreeMap<String, Object>();
    String[] names;
    try {
        names = loadConstructorParamNames(clazz);
    } catch (NoStaplerConstructorException x) {
        throw new UnsupportedOperationException(x);
    }
    for (String name : names) {
        inspect(r, o, clazz, name);
    }
    r.values().removeAll(Collections.singleton(null));
    Map<String, Object> constructorOnlyDataBoundProps = new TreeMap<String, Object>(r);
    List<String> dataBoundSetters = new ArrayList<String>();
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
        for (Field f : c.getDeclaredFields()) {
            if (f.isAnnotationPresent(DataBoundSetter.class)) {
                String field = f.getName();
                dataBoundSetters.add(field);
                inspect(r, o, clazz, field);
            }
        }
        for (Method m : c.getDeclaredMethods()) {
            if (m.isAnnotationPresent(DataBoundSetter.class) && m.getName().startsWith("set")) {
                String field = Introspector.decapitalize(m.getName().substring(3));
                dataBoundSetters.add(field);
                inspect(r, o, clazz, field);
            }
        }
    }
    clearDefaultSetters(clazz, r, constructorOnlyDataBoundProps, dataBoundSetters);
    return r;
}

From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java

/**
 * Injects via {@link DataBoundSetter}//from   www  . j  ava 2  s  . co m
 */
private static void injectSetters(Object o, Map<String, ?> arguments) throws Exception {
    for (Class<?> c = o.getClass(); c != null; c = c.getSuperclass()) {
        for (Field f : c.getDeclaredFields()) {
            if (f.isAnnotationPresent(DataBoundSetter.class)) {
                f.setAccessible(true);
                if (arguments.containsKey(f.getName())) {
                    Object v = arguments.get(f.getName());
                    f.set(o, v != null ? coerce(c.getName() + "." + f.getName(), f.getType(), v) : null);
                }
            }
        }
        for (Method m : c.getDeclaredMethods()) {
            if (m.isAnnotationPresent(DataBoundSetter.class)) {
                Type[] parameterTypes = m.getGenericParameterTypes();
                if (!m.getName().startsWith("set") || parameterTypes.length != 1) {
                    throw new IllegalStateException(m + " cannot be a @DataBoundSetter");
                }
                m.setAccessible(true);
                Object[] args = buildArguments(c, arguments, parameterTypes,
                        new String[] { Introspector.decapitalize(m.getName().substring(3)) }, false);
                if (args != null) {
                    m.invoke(o, args);
                }
            }
        }
    }
}

From source file:org.kie.workbench.common.forms.adf.processors.FormDefinitionsProcessor.java

private String extractFieldName(String methodName, int index) {
    if (methodName.length() <= index) {
        throw new IllegalArgumentException("MethodName ( '" + methodName + "' ) size < " + index);
    }/*from   ww  w. jav  a  2  s .co m*/
    return Introspector.decapitalize(methodName.substring(index));
}

From source file:org.libreplan.business.common.LibrePlanClassValidator.java

public String getPropertyName(XMember member) {
    //Do no try to cache the result in a map, it's actually much slower (2.x time)
    String propertyName;/*from ww w. ja  v  a  2  s.co m*/
    if (XProperty.class.isAssignableFrom(member.getClass())) {
        propertyName = member.getName();
    } else if (XMethod.class.isAssignableFrom(member.getClass())) {
        propertyName = member.getName();
        if (propertyName.startsWith("is")) {
            propertyName = Introspector.decapitalize(propertyName.substring(2));
        } else if (propertyName.startsWith("get")) {
            propertyName = Introspector.decapitalize(propertyName.substring(3));
        }
        //do nothing for non getter method, in case someone want to validate a PO Method
    } else {
        throw new AssertionFailure("Unexpected member: " + member.getClass().getName());
    }
    return propertyName;
}

From source file:org.openmrs.xml.OpenmrsLabelLogic.java

/**
 * @see org.simpleframework.xml.graph.LabelLogic#getLabel(java.lang.Class, java.lang.Object,
 *      java.lang.Class, org.simpleframework.xml.stream.NodeMap)
 *//*  w ww. j  a v a  2  s  .  com*/
@SuppressWarnings("unchecked")
public String getLabel(Class field, Object value, Class real, NodeMap node) {
    String simpleName = real.getSimpleName();
    simpleName = Introspector.decapitalize(simpleName);
    Class type = value.getClass();

    if (type != field || !node.getName().equals(simpleName)) {

        // default value for "label"'s value is the name of the class
        String realClassName = real.getName();

        // if its a hibernate set, get the real object's type
        if (value instanceof PersistentCollection) {
            realClassName = getHibernateInstanceClass(type.getName());
        }

        // if we're cglib enhanced, ignore putting this class on the node
        if (!realClassName.contains("CGLIB")) {

            // don't have to return the classes for basic things
            if (type != field) {
                return realClassName;
            }
        } else {
            // check for each of the overriding pojo types
            for (String objectName : new String[] { "User", "Patient", "ComplexObs", "ConceptNumeric" }) {
                String className = "org.openmrs." + objectName;
                if (realClassName.startsWith(className) && !field.getName().equals(className)) {
                    return className;
                }
            }

            return realClassName.substring(0, realClassName.indexOf("$$EnhancerByCGLIB"));
        }
    }

    // don't put a label in
    return null;
}

From source file:org.opentestsystem.delivery.testreg.service.impl.TestRegUberEntityRelationshipServiceImpl.java

private List<List<String>> buildPathwaysFromBottomUp(final boolean includeEntityTypeWithId,
        final boolean logEntityErrors) {

    final long start = System.currentTimeMillis();
    LOGGER.debug("running startup buildPathwaysFromBottomUp...");
    final List<TestRegUberEntityBottomUpPathwayBuilder> testRegUberEntityBottomUpPathwayBuilders = new ArrayList<>();

    final List<List<String>> pathwaysFromBottomUp = new ArrayList<>();
    for (final FormatType sb11EntityFormatType : Lists.reverse(getOrderedSb11EntityFormatTypes())) {
        for (final TestRegistrationBase testRegistrationBase : this.testRegPersister
                .findAll(sb11EntityFormatType)) {
            LOGGER.trace(/* w  w w . j a  v a  2 s .c  o m*/
                    "creating a testRegUberEntityBottomUpPathwayBuilder (thread) to handle building a pathway: "
                            + System.currentTimeMillis());
            final TestRegUberEntityBottomUpPathwayBuilder testRegUberEntityBottomUpPathwayBuilder = new TestRegUberEntityBottomUpPathwayBuilder(
                    (Sb11Entity) testRegistrationBase, includeEntityTypeWithId, this.testRegPersister,
                    this.sb11EntityService);
            testRegUberEntityBottomUpPathwayBuilders.add(testRegUberEntityBottomUpPathwayBuilder);
            testRegUberEntityBottomUpPathwayBuilder.run();
        }
    }

    if (logEntityErrors) {
        // collecting errors
        LOGGER.debug("collecting errors from testRegUberEntityBottomUpPathwayBuilder (threads)...");
        final Map<String, String> errorMessageMap = new HashMap<>();
        for (final TestRegUberEntityBottomUpPathwayBuilder testRegUberEntityBottomUpPathwayBuilder : testRegUberEntityBottomUpPathwayBuilders) {
            for (final Map.Entry<String, String> entry : testRegUberEntityBottomUpPathwayBuilder
                    .getErrorMessageMap().entrySet()) {
                errorMessageMap.put(entry.getKey(), entry.getValue());
            }
        }
        // loop over errors and log them...
        for (final String entityError : errorMessageMap.values()) {
            LOGGER.warn(entityError);
        }
    }

    // ==================================================================================================
    // log proposed mongo commands to fix bad entity data
    // ==================================================================================================
    final boolean fixBadData = true;
    // there actually may not be a client yet
    final List<ClientEntity> clientEntities = this.clientRepository.findAll();
    if (!CollectionUtils.isEmpty(clientEntities) && fixBadData) {
        final Map<String, Sb11Entity> deleteTheseEntities = new HashMap<>();
        final Map<String, Sb11Entity> resetParentOnTheseEntities = new HashMap<>();
        LOGGER.debug(
                "collecting invalid entity information results from testRegUberEntityBottomUpPathwayBuilder (threads)...");
        for (final TestRegUberEntityBottomUpPathwayBuilder testRegUberEntityBottomUpPathwayBuilder : testRegUberEntityBottomUpPathwayBuilders) {
            deleteTheseEntities.putAll(testRegUberEntityBottomUpPathwayBuilder.getDeleteTheseEntities());
            resetParentOnTheseEntities
                    .putAll(testRegUberEntityBottomUpPathwayBuilder.getResetParentOnTheseEntities());
        }

        final ClientEntity clientEntity = clientEntities.get(0);
        final StringBuilder sb = new StringBuilder();

        // loop thru and construct the update command to set all these entities to the CLIENT
        for (final Map.Entry<String, Sb11Entity> entry : resetParentOnTheseEntities.entrySet()) {
            if (!deleteTheseEntities.containsKey(entry.getKey())) {
                final Sb11Entity entity = entry.getValue();
                final String collectionName = Introspector
                        .decapitalize(entity.getEntityType().getEntityClass().getSimpleName());
                sb.append("db.").append(collectionName).append(".update(").append("\n");
                sb.append("  { _id: { $in: [ObjectId('" + entity.getId() + "'), ]}},").append("\n");
                sb.append("  { $set: {").append("\n");
                sb.append("    parentId: '" + clientEntity.getId() + "',").append("\n");
                sb.append("    parentEntityId: '" + clientEntity.getEntityId() + "',").append("\n");
                sb.append("    parentEntityType: '" + HierarchyLevel.CLIENT.name() + "',").append("\n");
                sb.append("  }},").append("\n");
                sb.append("  { upsert: false, multi: true }").append("\n");
                sb.append(")").append("\n");
            }
        }

        // loop thru and construct the remove command for these invalid entity objects
        for (final Map.Entry<String, Sb11Entity> entry : deleteTheseEntities.entrySet()) {
            final Sb11Entity entity = entry.getValue();
            final String collectionName = Introspector
                    .decapitalize(entity.getEntityType().getEntityClass().getSimpleName());
            sb.append("db.").append(collectionName).append(".remove(").append("\n");
            sb.append("  { _id: { $in: [ObjectId('" + entity.getId() + "'), ]}}").append("\n");
            sb.append(")").append("\n");
        }

        // ensure we have them also clear their persisted cache map
        if (sb.length() > 0) {
            sb.append("db.cacheMap.remove()").append("\n");
            LOGGER.error(
                    "FIX BAD DATA: use these mongo commands to update (and possibly delete) invalid/corrupt entity objects:\n"
                            + sb.toString());
        }
    }
    // ==================================================================================================
    // ==================================================================================================
    // ==================================================================================================

    // collect results
    LOGGER.debug("collecting results from testRegUberEntityBottomUpPathwayBuilder (threads)...");
    for (final TestRegUberEntityBottomUpPathwayBuilder testRegUberEntityBottomUpPathwayBuilder : testRegUberEntityBottomUpPathwayBuilders) {
        pathwaysFromBottomUp.add(testRegUberEntityBottomUpPathwayBuilder.getPathway());
    }

    LOGGER.debug(
            "completed startup buildPathwaysFromBottomUp: took " + (System.currentTimeMillis() - start) + "ms");
    return pathwaysFromBottomUp;
}

From source file:org.springframework.beans.AbstractVetoableChangeListener.java

/**
 * Creates new AbstractVetoableChangeListener.
 * Caches validation methods for efficiency.
 *//* w  ww.  j av  a 2s.c om*/
public AbstractVetoableChangeListener() throws SecurityException {
    // Look at all methods in the subclass, trying to find
    // methods that are validators according to our criteria
    Method[] methods = getClass().getMethods();
    for (int i = 0; i < methods.length; i++) {
        // We're looking for methods with names starting with the given prefix,
        // and two parameters: the value (which may be of any type, primitive or object)
        // and a PropertyChangeEvent.
        if (methods[i].getName().startsWith(VALIDATE_METHOD_PREFIX)
                && methods[i].getParameterTypes().length == 2
                && PropertyChangeEvent.class.isAssignableFrom(methods[i].getParameterTypes()[1])) {
            // We've found a potential validator: it has the right number of parameters
            // and its name begins with validate...
            logger.debug("Found potential validator method [" + methods[i] + "]");
            Class[] exceptions = methods[i].getExceptionTypes();
            // We don't care about the return type, but we must ensure that
            // the method throws only one checked exception, PropertyVetoException
            if (exceptions.length == 1 && PropertyVetoException.class.isAssignableFrom(exceptions[0])) {
                // We have a valid validator method
                // Ensure it's accessible (for example, it might be a method on an inner class)
                methods[i].setAccessible(true);
                String propertyName = Introspector
                        .decapitalize(methods[i].getName().substring(VALIDATE_METHOD_PREFIX.length()));
                validationMethodHash.put(propertyName, methods[i]);
                logger.debug(methods[i] + " is validator for property " + propertyName);
            } else {
                logger.debug("Invalid validator");
            }
        } else {
            logger.debug("Method [" + methods[i] + "] is not a validator");
        }
    }
}

From source file:org.springframework.integration.config.MessagingGatewayRegistrar.java

public BeanDefinitionHolder parse(Map<String, Object> gatewayAttributes) {

    String defaultPayloadExpression = (String) gatewayAttributes.get("defaultPayloadExpression");

    @SuppressWarnings("unchecked")
    Map<String, Object>[] defaultHeaders = (Map<String, Object>[]) gatewayAttributes.get("defaultHeaders");

    String defaultRequestChannel = (String) gatewayAttributes.get("defaultRequestChannel");
    String defaultReplyChannel = (String) gatewayAttributes.get("defaultReplyChannel");
    String errorChannel = (String) gatewayAttributes.get("errorChannel");
    String asyncExecutor = (String) gatewayAttributes.get("asyncExecutor");
    String mapper = (String) gatewayAttributes.get("mapper");

    boolean hasMapper = StringUtils.hasText(mapper);
    boolean hasDefaultPayloadExpression = StringUtils.hasText(defaultPayloadExpression);
    Assert.state(!hasMapper || !hasDefaultPayloadExpression,
            "'defaultPayloadExpression' is not allowed when a 'mapper' is provided");

    boolean hasDefaultHeaders = !ObjectUtils.isEmpty(defaultHeaders);
    Assert.state(!hasMapper || !hasDefaultHeaders,
            "'defaultHeaders' are not allowed when a 'mapper' is provided");

    BeanDefinitionBuilder gatewayProxyBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(GatewayProxyFactoryBean.class);

    if (hasDefaultHeaders || hasDefaultPayloadExpression) {
        BeanDefinitionBuilder methodMetadataBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(GatewayMethodMetadata.class);
        if (hasDefaultPayloadExpression) {
            methodMetadataBuilder.addPropertyValue("payloadExpression", defaultPayloadExpression);
        }/*from  ww w . j  a v a  2 s .c  o  m*/
        Map<String, Object> headerExpressions = new ManagedMap<String, Object>();
        for (Map<String, Object> header : defaultHeaders) {
            String headerValue = (String) header.get("value");
            String headerExpression = (String) header.get("expression");
            boolean hasValue = StringUtils.hasText(headerValue);

            if (!(hasValue ^ StringUtils.hasText(headerExpression))) {
                throw new BeanDefinitionStoreException(
                        "exactly one of 'value' or 'expression' " + "is required on a gateway's header.");
            }

            BeanDefinition expressionDef = new RootBeanDefinition(
                    hasValue ? LiteralExpression.class : ExpressionFactoryBean.class);
            expressionDef.getConstructorArgumentValues()
                    .addGenericArgumentValue(hasValue ? headerValue : headerExpression);

            headerExpressions.put((String) header.get("name"), expressionDef);
        }
        methodMetadataBuilder.addPropertyValue("headerExpressions", headerExpressions);
        gatewayProxyBuilder.addPropertyValue("globalMethodMetadata", methodMetadataBuilder.getBeanDefinition());
    }

    if (StringUtils.hasText(defaultRequestChannel)) {
        gatewayProxyBuilder.addPropertyReference("defaultRequestChannel", defaultRequestChannel);
    }
    if (StringUtils.hasText(defaultReplyChannel)) {
        gatewayProxyBuilder.addPropertyReference("defaultReplyChannel", defaultReplyChannel);
    }
    if (StringUtils.hasText(errorChannel)) {
        gatewayProxyBuilder.addPropertyReference("errorChannel", errorChannel);
    }
    if (StringUtils.hasText(asyncExecutor)) {
        gatewayProxyBuilder.addPropertyReference("asyncExecutor", asyncExecutor);
    }
    if (StringUtils.hasText(mapper)) {
        gatewayProxyBuilder.addPropertyReference("mapper", mapper);
    }

    gatewayProxyBuilder.addPropertyValue("defaultRequestTimeout",
            gatewayAttributes.get("defaultRequestTimeout"));
    gatewayProxyBuilder.addPropertyValue("defaultReplyTimeout", gatewayAttributes.get("defaultReplyTimeout"));
    gatewayProxyBuilder.addPropertyValue("methodMetadataMap", gatewayAttributes.get("methods"));

    String serviceInterface = (String) gatewayAttributes.get("serviceInterface");
    if (!StringUtils.hasText(serviceInterface)) {
        serviceInterface = "org.springframework.integration.gateway.RequestReplyExchanger";
    }
    String id = (String) gatewayAttributes.get("name");
    if (!StringUtils.hasText(id)) {
        id = Introspector.decapitalize(serviceInterface.substring(serviceInterface.lastIndexOf(".") + 1));
    }

    gatewayProxyBuilder.addConstructorArgValue(serviceInterface);

    return new BeanDefinitionHolder(gatewayProxyBuilder.getBeanDefinition(), id);
}

From source file:org.springframework.util.ClassUtils.java

/**
 * Return the short string name of a Java class in decapitalized
 * JavaBeans property format.//from  w  ww  .  jav a 2s . c  om
 * @param clazz the class
 * @return the short name rendered in a standard JavaBeans property format
 * @see java.beans.Introspector#decapitalize(String)
 */
public static String getShortNameAsProperty(Class clazz) {
    return Introspector.decapitalize(getShortName(clazz));
}