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

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

Introduction

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

Prototype

public static String capitalize(final String str) 

Source Link

Document

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

Usage

From source file:net.sourceforge.pmd.benchmark.TimedOperationCategory.java

public String displayName() {
    final String[] parts = name().toLowerCase(Locale.getDefault()).split("_");
    final StringBuilder sb = new StringBuilder();
    for (final String part : parts) {
        sb.append(StringUtils.capitalize(part)).append(' ');
    }//from   w  ww  .  ja  v a 2 s.  co m
    sb.setLength(sb.length() - 1); // remove the final space
    return sb.toString();
}

From source file:net.sourceforge.pmd.lang.java.rule.codestyle.LinguisticNamingRule.java

private void checkTransformMethods(ASTMethodDeclaration node, Object data, String nameOfMethod) {
    ASTResultType resultType = node.getResultType();
    List<String> infixes = getProperty(TRANSFORM_METHOD_NAMES_PROPERTY);
    for (String infix : infixes) {
        if (resultType.isVoid() && containsWord(nameOfMethod, StringUtils.capitalize(infix))) {
            // "To" or any other configured infix in the middle somewhere
            addViolationWithMessage(data, node,
                    "Linguistics Antipattern - The transform method ''{0}'' should not return void linguistically",
                    new Object[] { nameOfMethod });
            // the first violation is sufficient - it is still the same method we are analyzing here
            break;
        }/*w w w.  j av a  2  s .  co m*/
    }
}

From source file:net.sourceforge.pmd.lang.java.rule.errorprone.AvoidBranchingStatementAsLastInLoopRule.java

private static PropertyDescriptor<List<String>> propertyFor(String stmtName) {
    return PropertyFactory
            .enumListProperty("check" + StringUtils.capitalize(stmtName) + "LoopTypes", LOOP_TYPES_MAPPINGS)
            .desc("List of loop types in which " + stmtName + " statements will be checked")
            .defaultValue(DEFAULTS).build();
}

From source file:net.sourceforge.pmd.lang.java.rule.errorprone.BeanMembersShouldSerializeRule.java

@Override
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
    if (node.isInterface()) {
        return data;
    }/*from   ww  w.j  a  v  a  2  s .co  m*/

    if (hasLombokAnnotation(node)) {
        return super.visit(node, data);
    }

    Map<MethodNameDeclaration, List<NameOccurrence>> methods = node.getScope()
            .getEnclosingScope(ClassScope.class).getMethodDeclarations();
    List<ASTMethodDeclarator> getSetMethList = new ArrayList<>(methods.size());
    for (MethodNameDeclaration d : methods.keySet()) {
        ASTMethodDeclarator mnd = d.getMethodNameDeclaratorNode();
        if (isBeanAccessor(mnd)) {
            getSetMethList.add(mnd);
        }
    }

    String[] methNameArray = imagesOf(getSetMethList);

    Arrays.sort(methNameArray);

    Map<VariableNameDeclaration, List<NameOccurrence>> vars = node.getScope()
            .getDeclarations(VariableNameDeclaration.class);
    for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : vars.entrySet()) {
        VariableNameDeclaration decl = entry.getKey();
        AccessNode accessNodeParent = decl.getAccessNodeParent();
        if (entry.getValue().isEmpty() || accessNodeParent.isTransient() || accessNodeParent.isStatic()
                || hasIgnoredAnnotation((Annotatable) accessNodeParent)) {
            continue;
        }
        String varName = StringUtils.capitalize(trimIfPrefix(decl.getImage()));
        boolean hasGetMethod = Arrays.binarySearch(methNameArray, "get" + varName) >= 0
                || Arrays.binarySearch(methNameArray, "is" + varName) >= 0;
        boolean hasSetMethod = Arrays.binarySearch(methNameArray, "set" + varName) >= 0;
        // Note that a Setter method is not applicable to a final
        // variable...
        if (!hasGetMethod || !accessNodeParent.isFinal() && !hasSetMethod) {
            addViolation(data, decl.getNode(), decl.getImage());
        }
    }
    return super.visit(node, data);
}

From source file:net.sourceforge.pmd.properties.constraints.ConstraintFactory.java

/**
 * Builds a new validator from a predicate, and description.
 *
 * @param pred                  The predicate. If it returns
 *                              false on a value, then the
 *                              value is deemed to have a
 *                              problem//  www. ja  v  a  2  s . co  m
 * @param constraintDescription Description of the constraint,
 *                              see {@link PropertyConstraint#getConstraintDescription()}.
 * @param <U>                   Type of value to validate
 *
 * @return A new validator
 */
@Experimental
public static <U> PropertyConstraint<U> fromPredicate(final Predicate<? super U> pred,
        final String constraintDescription) {
    return new PropertyConstraint<U>() {

        @Override
        public boolean test(U value) {
            return pred.test(value);
        }

        // TODO message could be better, eg include name of the property
        @Override
        public String validate(U value) {
            return pred.test(value) ? null
                    : "Constraint violated on property value '" + value + "' (" + constraintDescription + ")";
        }

        @Override
        public String getConstraintDescription() {
            return StringUtils.capitalize(constraintDescription);
        }

        @Override
        public PropertyConstraint<Iterable<? extends U>> toCollectionConstraint() {
            final PropertyConstraint<U> thisValidator = this;
            return ConstraintFactory
                    .<Iterable<? extends U>>fromPredicate(new Predicate<Iterable<? extends U>>() {
                        @Override
                        public boolean test(Iterable<? extends U> us) {
                            for (U u : us) {
                                if (!thisValidator.test(u)) {
                                    return false;
                                }
                            }
                            return true;
                        }
                    }, "Components " + StringUtils.uncapitalize(thisValidator.getConstraintDescription()));
        }
    };
}

From source file:net.sourceforge.pmd.util.StringUtil.java

/**
 * Converts the given string to Camel case,
 * that is, removing all spaces, and capitalising
 * the first letter of each word except the first.
 *
 * <p>The second parameter can be used to force the
 * words to be converted to lowercase before capitalising.
 * This can be useful if eg the first word contains
 * several uppercase letters./*from w  w w  .j av  a  2s  .  com*/
 *
 * @param name           The string to convert
 * @param forceLowerCase Whether to force removal of all upper
 *                       case letters except on word start
 *
 * @return The string converted to Camel case
 */
public static String toCamelCase(String name, boolean forceLowerCase) {
    StringBuilder sb = new StringBuilder();
    boolean isFirst = true;
    for (String word : name.trim().split("\\s++")) {
        String pretreated = forceLowerCase ? word.toLowerCase(Locale.ROOT) : word;
        if (isFirst) {
            sb.append(pretreated);
            isFirst = false;
        } else {
            sb.append(StringUtils.capitalize(pretreated));
        }
    }
    return sb.toString();
}

From source file:net.thucydides.core.util.Inflector.java

/**
 * Capitalizes the first word and turns underscores into spaces and strips trailing "_id" and any supplied removable tokens.
 * Like {@link #titleCase(String, String[])}, this is meant for creating pretty output.
 *
 * Examples://from   www.j  a va 2  s  .com
 *
 * <pre>
 *   inflector.humanize(&quot;employee_salary&quot;)       #=&gt; &quot;Employee salary&quot;
 *   inflector.humanize(&quot;author_id&quot;)             #=&gt; &quot;Author&quot;
 * </pre>
 *
 *
 *
 * @param lowerCaseAndUnderscoredWords the input to be humanized
 * @param removableTokens optional array of tokens that are to be removed
 * @return the humanized string
 * @see #titleCase(String, String[])
 */
public String humanize(String lowerCaseAndUnderscoredWords, String... removableTokens) {

    String result = humanReadableFormOf(lowerCaseAndUnderscoredWords, removableTokens);

    Set<Acronym> acronyms = Acronym.acronymsIn(result);

    result = result.toLowerCase();

    for (Acronym acronym : acronyms) {
        result = acronym.restoreIn(result);
    }

    return StringUtils.capitalize(result);
}

From source file:nivance.jpa.cassandra.prepare.convert.MappingCassandraConverter.java

public List<Clause> getKeyPart(final CassandraPersistentEntity<?> entity, final Object valueBean) {
    final List<Clause> result = new LinkedList<Clause>();
    entity.doWithProperties(new PropertyHandler<CassandraPersistentProperty>() {
        public void doWithPersistentProperty(CassandraPersistentProperty prop) {
            //TODO
            if (prop.getKeyPart() != null) {
                //keypart?
                Method method = ReflectionUtils.findMethod(entity.getType(),
                        "get" + StringUtils.capitalize(prop.getColumnName()));
                Object id = ReflectionUtils.invokeMethod(method, valueBean);
                result.add(QueryBuilder.eq(prop.getColumnName(), id));
            }//from   w w w.  j a  v a  2  s  .c  o  m
        }
    });
    if (result.isEmpty()) {
        throw new MappingException(
                "Could not form a where clause for the primary key for an entity " + entity.getName());
    }
    return result;
}

From source file:nl.inl.util.TestStringUtil.java

@Test
public void testCapitalize() {
    Assert.assertEquals("Aap", StringUtils.capitalize("aap"));
    Assert.assertEquals("AAP", StringUtils.capitalize("AAP"));
    Assert.assertEquals("'aap'", StringUtils.capitalize("'aap'"));
}

From source file:org.adorsys.waguia.lightxls.generic.EasyXlsClazzLoader.java

public List<T> loadClazz() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
        InstantiationException {// ww w  . j  a  v  a2s . c  o m
    List<T> result = new ArrayList<T>();

    Field[] declaredFields = clazz.getDeclaredFields();
    int numberOfSheets = workbook.getNumberOfSheets();
    Method[] declaredMethods = clazz.getDeclaredMethods();
    if (classInSheetFinder == null)
        classInSheetFinder = new ClassInSheetFinder();
    List<String> sheetNames = new ArrayList<String>();
    for (int i = 0; i < numberOfSheets; i++) {
        sheetNames.add(workbook.getSheetAt(i).getSheetName());
    }
    int position = classInSheetFinder.find(clazz.getSimpleName(),
            (String[]) sheetNames.toArray(new String[sheetNames.size()]));
    if (position == -1)
        throw new RuntimeErrorException(null, "Unable to find the class's sheet");
    Sheet clazzSheet = workbook.getSheetAt(position);
    // assuming that the first row will contains class's properties. so this is
    // how to get columnNames.
    Row row = clazzSheet.getRow(HEADER_INDEX);
    Iterator<Cell> cellIterator = row.cellIterator();
    List<String> columnNames = new ArrayList<String>();
    while (cellIterator.hasNext()) {
        Cell cell = (Cell) cellIterator.next();
        columnNames.add(cell.getStringCellValue());
    }
    if (this.sheetColumnToClazzFieldMatching == null)
        this.sheetColumnToClazzFieldMatching = new SheetColumnToClazzFieldMatching();

    if (sheetColumnToClazzFieldMatching.checkMatching(
            (String[]) columnNames.toArray(new String[columnNames.size()]), declaredFields,
            declaredMethods) == false)
        throw new RuntimeException("Matching Error. Please recheck matching rules");
    Iterator<Row> rowIterator = clazzSheet.rowIterator();
    if (fieldToColumnComparator == null)
        this.fieldToColumnComparator = new FieldToColumnComparator();
    int numberOfIteration = 0;
    while (rowIterator.hasNext()) {
        Row nextRow = rowIterator.next();
        Object newInstance = clazz.newInstance();
        if (numberOfIteration == HEADER_INDEX) {
            numberOfIteration++;
            continue;
        }
        for (int i = 0; i < declaredFields.length; i++) {
            Field field = declaredFields[i];
            if (!columnNames.contains(field.getName()))
                continue;
            String correspondinMethodName = "set" + StringUtils.capitalize(field.getName());
            for (int j = 0; j < declaredMethods.length; j++) {
                Method method = declaredMethods[j];
                if (!method.getName().equals(correspondinMethodName))
                    continue;
                int index = 0;
                //Find the correct field's range in the list of columns.
                for (String string : columnNames) {
                    if (fieldToColumnComparator.compare(field.getName(), string) == 0) {
                        Class<?> type = field.getType();
                        if (exelPropertyReader == null) {
                            exelPropertyReader = new ExelPropertyReader(field, type, newInstance,
                                    nextRow.getCell(index), method);
                            exelPropertyReader.readProperty();
                        } else {
                            exelPropertyReader.setField(field);
                            exelPropertyReader.setCell(nextRow.getCell(index));
                            exelPropertyReader.setMethod(method);
                            exelPropertyReader.setNewInstance(newInstance);
                            exelPropertyReader.setType(type);
                            exelPropertyReader.readProperty();
                        }
                        index++;
                        continue;
                    }
                    index++;
                }
            }
        }
        result.add((T) newInstance);
        numberOfIteration++;
    }
    return result;
}