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:nl.knaw.dans.common.lang.search.bean.SearchBeanUtil.java

public static Object getFieldValue(Object searchBean, String propertyName) throws SecurityException,
        NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    String getMethodName = "get" + StringUtils.capitalize(propertyName);
    Method getMethod = searchBean.getClass().getMethod(getMethodName, new Class[] {});
    return getMethod.invoke(searchBean);
}

From source file:nl.knaw.dans.dccd.application.services.DccdProjectValidationService.java

/**
 * find the required fields and then checks if set 
 * using the JAXB annotations /*  w  w  w  . j a v a2 s .  co m*/
 * 
 * The JAXB object fields are of the correct type, so no extra validation needed
 * and also the structure cannot be wrong
 * 
 * @param tridas
 * @return
 */
private List<ValidationErrorMessage> validateForRequiredTridasFields(Object tridas) {
    final List<ValidationErrorMessage> errorMessages = new ArrayList<ValidationErrorMessage>();

    //logger.debug("Validating required fields for object of class: " + tridas.getClass().getSimpleName());

    // NOTE an object has a lot of fields; all from Object down to the specific class...
    //
    // find all properties with required = true:
    //@XmlElement(name = "type", required = true)
    // and then call the isSet method
    Class tridasClass = tridas.getClass();
    Collection<Field> values = ClassUtil.getAllFields(tridasClass).values();
    for (java.lang.reflect.Field classField : values) {
        boolean isRequired = false;

        // determine the field is required
        isRequired = isFieldRequired(classField);

        String fieldName = classField.getName();
        String getMethodName = "get" + StringUtils.capitalize(fieldName);
        String isSetMethodName = "isSet" + StringUtils.capitalize(fieldName);

        Boolean isSet = false;
        Object fieldObject = null;
        // retrieve the methods and call them
        try {
            Method isSetMethod = null;
            Method getMethod = null;
            isSetMethod = tridasClass.getMethod(isSetMethodName);
            getMethod = tridasClass.getMethod(getMethodName);
            // JAXB, so we assume isSet returns boolean
            isSet = (Boolean) isSetMethod.invoke(tridas);
            fieldObject = getMethod.invoke(tridas);
        } catch (NoSuchMethodException e) {
            continue; //skip this field, probably no JAXB TRiDaS generated class 
        } catch (SecurityException e) {
            continue; //skip this field 
        } catch (IllegalArgumentException e) {
            continue; //skip this field
        } catch (IllegalAccessException e) {
            continue; //skip this field
        } catch (InvocationTargetException e) {
            continue; //skip this field
        }

        // Required fields only
        if (isRequired) {
            if (!isSet) {
                // required field missing
                logger.debug("Missing required " + fieldName);
                errorMessages.add(new ValidationErrorMessage(MISSING_REQUIRED_FIELD_MSG, tridasClass.getName(),
                        fieldName));
            } else {
                //logger.debug("Required field \'" + fieldName + "\' was set");
                // assume if it is set, the object return should not be null
                //
                // Handle empty fields (set but empty)
                // do extra check for strings that might be empty...
                if (fieldObject instanceof String) {
                    if (((String) fieldObject).trim().isEmpty()) {
                        logger.debug("Missing required \'" + fieldName + "\' was empty or whitespace string");
                        errorMessages.add(new ValidationErrorMessage(MISSING_REQUIRED_FIELD_MSG,
                                tridasClass.getName(), fieldName));
                    }
                }
            }
        }

        // All fields set, required or not
        // Validating sub Objects 
        if (isSet) {
            if (fieldObject instanceof List) {
                // Handle List objects
                List listField = (List) fieldObject; // we can cast
                errorMessages.addAll(
                        validateListFieldItemsForRequiredTridasFields(listField, tridasClass, fieldName));
            } else {
                // not a List, just a normal field
                // validate the sub fields (recurse into tree)               
                errorMessages
                        .addAll(validateSubFieldForRequiredTridasFields(fieldObject, tridasClass, fieldName));
            }
        }
    }

    return errorMessages;
}

From source file:nl.knaw.huygens.timbuctoo.rest.providers.HTMLGenerator.java

private String camelCaseUnescape(String fieldName) {
    // See: http://stackoverflow.com/a/2560017/713326
    return StringUtils.capitalize(fieldName.replaceAll("[_^.-@!]", " ").trim()).replaceAll(String.format(
            "%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])"), " ");
}

From source file:nl.knaw.huygens.timbuctoo.tools.importer.neww.PublisherNormalizer.java

public String preprocess(String text) {
    // remove suspect entries
    if (text.contains("(") || text.contains("[") || text.contains("etc.") || text.startsWith("in ")) {
        return "";
    }/* w  w  w.j  a  va 2  s  .  c o  m*/

    text = StringUtils.capitalize(text);
    text = text.replaceAll("/", " / ");
    text = text.replaceAll("\\band\\b", "&");
    text = text.replaceAll("\\bco\\b", "Co");
    text = text.replaceAll("\\ben\\b", "&");
    text = text.replaceAll("\\bet\\b", "&");

    text = text.replaceAll("\\b([A-Z])\\s+", "$1. ");
    text = text.replaceAll("\\b([A-Z]\\.)(\\w\\w)", "$1 $2");
    text = text.replaceAll("\\b([A-Z]\\.)\\s+([A-Z]\\.)", "$1$2");

    text = text.replaceAll("[\\s\\u00A0]+", " ").trim();

    text = text.replaceAll("& [Cc]omp\\.", "& Co.");
    text = text.replaceAll("& [Cc]ompany", "& Co.");
    text = text.replaceAll("& [Cc]o\\.?$", "& Co.");
    text = text.replaceAll("& son", "& Son");
    text = text.replaceAll("& de", "& De");
    text = text.replaceAll("& van", "& Van");
    text = text.replaceAll("& Zn\\.?", "& Zoon");
    text = text.replaceAll("& zoon", "& Zoon");

    if (text.contains("etc.")) {
        text = "";
    }

    return (text.length() > 50 || text.matches(".*?\\d.*?")) ? "" : text;
}

From source file:nl.strohalm.cyclos.utils.conversion.KeyToHelpNameConverter.java

private String convert(final String string) {
    final String[] array = StringUtils.split(string, '.');
    final StringBuffer converted = new StringBuffer(string.length());
    for (int i = 0; i < array.length; i++) {
        final String token = (i == 0) ? array[i] : StringUtils.capitalize(array[i]);
        converted.append(token);//from w ww  . j  a v a2s  . c  o m
    }
    return converted.toString();
}

From source file:no.sesat.search.view.velocity.DateFormattingDirective.java

protected String formatDate(String input, String navName) throws ParseException {
    if (input.substring(2, 3).equals("-")) {
        // Form one or two
        if (input.length() == 10) {
            return formatFormTwo(input, "newsdateOnly".equals(navName));
        } else {//from ww  w. j a  v a 2s  .co m
            return StringUtils.capitalize(formatFormOne(input));
        }
    } else {
        // From three or four
        if (input.length() == 10) {
            return formatFormFour(input, "newsdateOnly".equals(navName));
        } else {
            return StringUtils.capitalize(formatFormThree(input));
        }
    }
}

From source file:nu.staldal.lsp.wrapper.ReadonlyBeanMap.java

private Member tryToLookupMember(final String property, final String... prefixes) {
    final Class<? extends Object> beanClass = bean.getClass();

    for (final String prefix : prefixes) {
        try {/*from  w  w  w . j a v  a2s . c  o m*/
            final String methodName = prefix + StringUtils.capitalize(property);
            return beanClass.getMethod(methodName);
        } catch (NoSuchMethodException ignored) {
        }
    }

    try {
        return beanClass.getField(property);
    } catch (NoSuchFieldException ignored) {
    }

    try {
        return beanClass.getMethod(property);
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:nz.co.senanque.schemabuilder.NameHandler.java

private static String fixCase(String str) {
    StringBuilder buff = new StringBuilder();

    String[] tokens = str.split("_");
    for (String i : tokens) {
        buff.append(StringUtils.capitalize(i.toLowerCase()));
    }/*from  w  w w.jav  a  2  s.  co  m*/
    return buff.toString();
}

From source file:nz.co.senanque.workflow.conf.FormFactoryImpl.java

@Override
public WorkflowForm getForm(String formName) {
    if (m_formsMap != null && !m_formsMap.isEmpty()) {
        Map<String, String> environmentEntry = m_formsMap.get(m_environmentName);
        if (environmentEntry == null) {
            environmentEntry = m_formsMap.values().iterator().next();
        }//w w w . java2 s .c  om
        String beanName = environmentEntry.get(formName);
        if (beanName == null) {
            beanName = m_environmentName + StringUtils.capitalize(formName);
        }
        return m_beanFactory.getBean(beanName, WorkflowForm.class);
    }
    String beanName = m_environmentName + StringUtils.capitalize(formName);
    return m_beanFactory.getBean(beanName, WorkflowForm.class);
}

From source file:omero.cmd.graphs.DuplicateI.java

/**
 * Duplicate model object properties, linking them as appropriate with each other and with other model objects.
 * @throws GraphException if duplication failed
 *//*from w  w  w .  j  a  v a2s. c om*/
private void setDuplicatePropertyValues() throws GraphException {
    /* organize duplicate index by class name and ID */
    final Map<Entry<String, Long>, IObject> duplicatesByOriginalClassAndId = new HashMap<Entry<String, Long>, IObject>();
    for (final Entry<IObject, IObject> originalAndDuplicate : originalsToDuplicates.entrySet()) {
        final IObject original = originalAndDuplicate.getKey();
        final String originalClass = Hibernate.getClass(original).getName();
        final Long originalId = original.getId();
        final IObject duplicate = originalAndDuplicate.getValue();
        duplicatesByOriginalClassAndId.put(Maps.immutableEntry(originalClass, originalId), duplicate);
    }
    /* allow lookup regardless of if original is actually a Hibernate proxy object */
    final Function<Object, Object> duplicateLookup = new Function<Object, Object>() {
        @Override
        public Object apply(Object original) {
            if (original instanceof IObject) {
                final String originalClass;
                if (original instanceof HibernateProxy) {
                    originalClass = Hibernate.getClass(original).getName();
                } else {
                    originalClass = original.getClass().getName();
                }
                final Long originalId = ((IObject) original).getId();
                return duplicatesByOriginalClassAndId.get(Maps.immutableEntry(originalClass, originalId));
            } else {
                return null;
            }
        }
    };
    /* copy property values into duplicates and link with other model objects */
    final Session session = helper.getSession();
    for (final Entry<IObject, IObject> originalAndDuplicate : originalsToDuplicates.entrySet()) {
        final IObject original = originalAndDuplicate.getKey();
        final IObject duplicate = originalAndDuplicate.getValue();
        final String originalClass = Hibernate.getClass(original).getName();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("copying properties from " + originalClass + ":" + original.getId());
        }
        try {
            /* process property values for a given object that is duplicated */
            for (final String superclassName : graphPathBean.getSuperclassesOfReflexive(originalClass)) {
                /* process property values that link from the duplicate to other model objects */
                for (final Entry<String, String> forwardLink : graphPathBean.getLinkedTo(superclassName)) {
                    /* next forward link */
                    final String linkedClassName = forwardLink.getKey();
                    final String property = forwardLink.getValue();
                    /* ignore details for now, duplicates never preserve original ownership */
                    if (property.startsWith("details.")) {
                        continue;
                    }
                    /* note which of the objects to which the original links should be ignored */
                    final Set<Long> linkedToIdsToIgnore = new HashSet<Long>();
                    for (final Entry<String, Collection<Long>> linkedToClassIds : graphTraversal
                            .getLinkeds(superclassName, property, original.getId()).asMap().entrySet()) {
                        final String linkedToClass = linkedToClassIds.getKey();
                        final Collection<Long> linkedToIds = linkedToClassIds.getValue();
                        if (classifier.getClass(
                                Class.forName(linkedToClass).asSubclass(IObject.class)) == Inclusion.IGNORE) {
                            linkedToIdsToIgnore.addAll(linkedToIds);
                        }
                    }
                    /* check for another accessor for inaccessible properties */
                    if (graphPathBean.isPropertyAccessible(superclassName, property)) {
                        /* copy the linking from the original's property over to the duplicate's */
                        Object value;
                        try {
                            value = PropertyUtils.getNestedProperty(original, property);
                        } catch (NestedNullException e) {
                            continue;
                        }
                        if (value instanceof Collection) {
                            /* if a collection property, include only the objects that aren't to be ignored */
                            final Collection<IObject> valueCollection = (Collection<IObject>) value;
                            final Collection<IObject> valueToCopy;
                            if (value instanceof List) {
                                valueToCopy = new ArrayList<IObject>();
                            } else if (value instanceof Set) {
                                valueToCopy = new HashSet<IObject>();
                            } else {
                                throw new GraphException("unexpected collection type: " + value.getClass());
                            }
                            for (final IObject linkedTo : valueCollection) {
                                if (!linkedToIdsToIgnore.contains(linkedTo.getId())) {
                                    valueToCopy.add(linkedTo);
                                }
                            }
                            value = valueToCopy;
                        } else if (value instanceof IObject) {
                            /* if the property value is to be ignored then null it */
                            if (linkedToIdsToIgnore.contains(((IObject) value).getId())) {
                                value = null;
                            }
                        }
                        /* copy the property value, replacing originals with corresponding duplicates */
                        final Object duplicateValue = GraphUtil.copyComplexValue(duplicateLookup, value);
                        try {
                            PropertyUtils.setNestedProperty(duplicate, property, duplicateValue);
                        } catch (NestedNullException e) {
                            throw new GraphException(
                                    "cannot set property " + superclassName + '.' + property + " on duplicate");
                        }
                    } else {
                        /* this could be a one-to-many property with direct accessors protected */
                        final Class<? extends IObject> linkerClass = Class.forName(superclassName)
                                .asSubclass(IObject.class);
                        final Class<? extends IObject> linkedClass = Class.forName(linkedClassName)
                                .asSubclass(IObject.class);
                        final Method reader, writer;
                        try {
                            reader = linkerClass.getMethod("iterate" + StringUtils.capitalize(property));
                            writer = linkerClass.getMethod("add" + linkedClass.getSimpleName(), linkedClass);
                        } catch (NoSuchMethodException | SecurityException e) {
                            /* no luck, so ignore this property */
                            continue;
                        }
                        /* copy the linking from the original's property over to the duplicate's */
                        final Iterator<IObject> linkedTos = (Iterator<IObject>) reader.invoke(original);
                        while (linkedTos.hasNext()) {
                            final IObject linkedTo = linkedTos.next();
                            /* copy only links to other duplicates, as otherwise we may steal objects from the original */
                            final IObject duplicateOfLinkedTo = (IObject) duplicateLookup.apply(linkedTo);
                            if (duplicateOfLinkedTo != null) {
                                writer.invoke(duplicate, duplicateOfLinkedTo);
                            }
                        }
                    }
                }
                /* process property values that link to the duplicate from other model objects */
                for (final Entry<String, String> backwardLink : graphPathBean.getLinkedBy(superclassName)) {
                    /* next backward link */
                    final String linkingClass = backwardLink.getKey();
                    final String property = backwardLink.getValue();
                    /* ignore inaccessible properties */
                    if (!graphPathBean.isPropertyAccessible(linkingClass, property)) {
                        continue;
                    }
                    for (final Entry<String, Collection<Long>> linkedFromClassIds : graphTraversal
                            .getLinkers(linkingClass, property, original.getId()).asMap().entrySet()) {
                        final String linkedFromClass = linkedFromClassIds.getKey();
                        final Collection<Long> linkedFromIds = linkedFromClassIds.getValue();
                        if (classifier.getClass(
                                Class.forName(linkedFromClass).asSubclass(IObject.class)) == Inclusion.IGNORE) {
                            /* these linkers are to be ignored */
                            continue;
                        }
                        /* load the instances that link to the original */
                        final String rootQuery = "FROM " + linkedFromClass + " WHERE id IN (:ids)";
                        for (final List<Long> idsBatch : Iterables.partition(linkedFromIds, BATCH_SIZE)) {
                            final List<IObject> linkers = session.createQuery(rootQuery)
                                    .setParameterList("ids", idsBatch).list();
                            for (final IObject linker : linkers) {
                                if (originalsToDuplicates.containsKey(linker)) {
                                    /* ignore linkers that are to be duplicated, those are handled as forward links */
                                    continue;
                                }
                                /* copy the linking from the original's property over to the duplicate's */
                                Object value;
                                try {
                                    value = PropertyUtils.getNestedProperty(linker, property);
                                } catch (NestedNullException e) {
                                    continue;
                                }
                                /* for linkers only adjust collection properties */
                                if (value instanceof Collection) {
                                    final Collection<IObject> valueCollection = (Collection<IObject>) value;
                                    final Collection<IObject> newDuplicates = new ArrayList<IObject>();
                                    for (final IObject originalLinker : valueCollection) {
                                        final IObject duplicateOfValue = originalsToDuplicates
                                                .get(originalLinker);
                                        if (duplicateOfValue != null) {
                                            /* previous had just original, now include duplicate too */
                                            newDuplicates.add(duplicateOfValue);
                                        }
                                    }
                                    valueCollection.addAll(newDuplicates);
                                }
                            }
                        }
                    }
                }
                /* process property values that do not relate to edges in the model object graph */
                for (final String property : graphPathBean.getSimpleProperties(superclassName)) {
                    /* ignore inaccessible properties */
                    if (!graphPathBean.isPropertyAccessible(superclassName, property)) {
                        continue;
                    }
                    /* copy original property value to duplicate */
                    final Object value = PropertyUtils.getProperty(original, property);
                    PropertyUtils.setProperty(duplicate, property,
                            GraphUtil.copyComplexValue(duplicateLookup, value));
                }
            }
        } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException
                | NoSuchMethodException e) {
            throw new GraphException("failed to duplicate " + originalClass + ':' + original.getId());
        }
    }
}