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:com.thoughtworks.go.config.exceptions.EntityType.java

public String alreadyExists(String id) {
    return format("%s %s '%s' already exists!", StringUtils.capitalize(this.entityType),
            this.nameOrId.descriptor, id);
}

From source file:com.kurniakue.kurse.ReqContext.java

public boolean process() throws Exception {
    String beanName = getJsonRequest().bean;
    String className = StringUtils.capitalize(beanName);
    String fullClassName = "com.kurniakue.kurse.bean." + className;
    Class clazz;//from   ww w .j a  v  a 2s  .  co  m
    try {
        clazz = Class.forName(fullClassName);
        Object bean = clazz.newInstance();
        Method method = clazz.getMethod(getJsonRequest().method);
        method.invoke(bean);
    } catch (Exception exc) {
        exc.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.neatresults.mgnltweaks.ui.action.SaveDialogFormAction.java

@Override
public void execute() throws ActionExecutionException {
    // First Validate
    validator.showValidation(true);//from w ww. jav a 2 s. c om
    if (validator.isValid()) {
        try {
            final Node node = item.applyChanges();
            // Set the Node name.
            setNodeName(node, item);
            // WTF was whomever at JR dev team thinking?
            for (Property prop : in((Iterator<Property>) node.getProperties())) {
                if (prop.getType() == PropertyType.STRING && StringUtils.isEmpty(prop.getValue().getString())) {
                    prop.remove();
                }
            }
            Node actions = node.addNode("actions", NodeTypes.ContentNode.NAME);
            setAction(node, actions, "commit", "info.magnolia.ui.form.action.SaveFormActionDefinition");
            setAction(node, actions, "cancel", "info.magnolia.ui.form.action.CancelFormActionDefinition");

            Node tabs = node.addNode("form", NodeTypes.ContentNode.NAME).addNode("tabs",
                    NodeTypes.ContentNode.NAME);
            for (Node n : in((Iterator<Node>) node.getNodes("tabs*"))) {
                if (n.hasProperty("field")) {
                    String name = n.getProperty("field").getString();

                    Node tab = tabs.addNode(Path.getUniqueLabel(tabs, Path.getValidatedLabel(name)),
                            NodeTypes.ContentNode.NAME);
                    tab.setProperty("label", StringUtils.capitalize(name));
                    tab.addNode("fields", NodeTypes.ContentNode.NAME);
                }
                n.remove();
            }
            node.getSession().save();
        } catch (final RepositoryException e) {
            throw new ActionExecutionException(e);
        }
        callback.onSuccess(getDefinition().getName());
    } else {
        log.info("Validation error(s) occurred. No save performed.");
    }
}

From source file:com.msopentech.odatajclient.testservice.AbstractServices.java

/**
 * Provide sample lartge metadata./*w  w  w  .  j  a  va  2  s .c om*/
 *
 * @return metadata.
 */
@GET
@Path("/large/$metadata")
@Produces("application/xml")
public Response getLargeMetadata() {
    return getMetadata("large" + StringUtils.capitalize(METADATA));
}

From source file:de.jcup.egradle.codeassist.dsl.MethodUtils.java

/**
 * Calculates method identification in percentage (100= 100%).<br>
 * <br>// w  ww .ja  v a2s  .c o  m
 * <ul>
 * <li>If a method is exact same 100% is returned</li>
 * <li>If a method is has same name, same param size, but x parameters of n
 * are not equal 50%-100% is returned</li>
 * <li>If a method is has same name, but param size is not equal 50% is
 * returned</li>
 * </ul>
 * 
 * @param method
 * @param itemIdentifier
 * @param itemParameters
 * @return percentage
 */
public static int calculateMethodIdentificationPercentage(Method method, String itemIdentifier,
        String... itemParameters) {
    if (method == null) {
        return 0;
    }
    if (itemIdentifier == null) {
        return 0;
    }
    String methodName = method.getName();
    if (methodName == null) {
        return 0;
    }
    if (itemParameters == null) {
        itemParameters = new String[] {};
    }
    int percentage;
    if (itemIdentifier.equals(methodName)) {
        percentage = 50;// 50% reached because name is equal
    } else {
        if (!methodName.startsWith("get") && !methodName.startsWith("set")) {
            return 0;
        }
        if (methodName.length() == 3) {
            return 0;
        }
        String methodPartName = StringUtils.substring(methodName, 3);
        String buildMethodPartName = StringUtils.capitalize(itemIdentifier);
        if (!methodPartName.equals(buildMethodPartName)) {
            return 0;
        }
        percentage = 49;// 49% reached because name is not equal but it
        // seems groovy magic for get/set,
        // 49% because if there would exists a method with
        // absolute same name this should matter more!
    }
    /* -------------------------------- */
    /* - start percentage calculation - */
    /* -------------------------------- */

    /* name okay, could be ... */

    List<Parameter> parameters = method.getParameters();
    /* check size same */
    int paramSize = parameters.size();
    if (paramSize != itemParameters.length) {
        return percentage;
    }

    if (paramSize == 0) {
        /* speed up and avoid failures on percentage calculation */
        return percentage + 50;
    }

    /* okay at least same size */
    int pos = 0;
    int percentPerCorrectParam = 50 / paramSize;

    int paramPercents = 0;
    boolean allParamsSame = true;
    for (Parameter p : parameters) {
        String itemParam = itemParameters[pos++];
        if (p == null) {
            /* should never happen */
            continue;
        }
        if (itemParam == null) {
            continue;
        }
        /*
         * if item parameter is with color we remove this meta information
         */
        itemParam = StringUtils.substringBefore(itemParam, ":");

        String typeAsString = p.getTypeAsString();
        if (!typeAsString.equals(itemParam)) {
            allParamsSame = false;
        } else {
            paramPercents += percentPerCorrectParam;
        }
    }
    if (allParamsSame) {
        percentage += 50;
    } else {
        if (paramPercents >= 50) {
            /* should never happen but... */
            paramPercents = 49;
        }
        percentage += paramPercents;
    }
    return percentage;
}

From source file:io.bibleget.BibleGetFrame.java

/**
 *
 * @throws ClassNotFoundException/*from  ww  w.j  a  v a  2 s .c  om*/
 */
private void prepareDynamicInformation() throws ClassNotFoundException {
    biblegetDB = BibleGetDB.getInstance();
    String bibleVersionsStr = biblegetDB.getMetaData("VERSIONS");
    JsonReader jsonReader = Json.createReader(new StringReader(bibleVersionsStr));
    JsonObject bibleVersionsObj = jsonReader.readObject();
    Set<String> versionsabbrev = bibleVersionsObj.keySet();
    bibleVersions = new BasicEventList<>();
    if (!versionsabbrev.isEmpty()) {
        for (String s : versionsabbrev) {
            String versionStr = bibleVersionsObj.getString(s); //store these in an array
            String[] array;
            array = versionStr.split("\\|");
            bibleVersions.add(new BibleVersion(s, array[0], array[1],
                    StringUtils.capitalize(new Locale(array[2]).getDisplayLanguage())));
        }
    }

    List<String> preferredVersions = new ArrayList<>();
    String retVal = (String) biblegetDB.getOption("PREFERREDVERSIONS");
    if (null == retVal) {
        //System.out.println("Attempt to retrieve PREFERREDVERSIONS from the Database resulted in null value");
    } else {
        //System.out.println("Retrieved PREFERREDVERSIONS from the Database. Value is:"+retVal);
        String[] favoriteVersions = StringUtils.split(retVal, ',');
        preferredVersions = Arrays.asList(favoriteVersions);
    }
    if (preferredVersions.isEmpty()) {
        preferredVersions.add("NVBSE");
    }
    List<Integer> preferredVersionsIndices = new ArrayList<>();

    versionsByLang = new SeparatorList<>(bibleVersions, new VersionComparator(), 1, 1000);
    int listLength = versionsByLang.size();
    enabledFlags = new boolean[listLength];
    ListIterator itr = versionsByLang.listIterator();
    while (itr.hasNext()) {
        int idx = itr.nextIndex();
        Object next = itr.next();
        enabledFlags[idx] = !(next.getClass().getSimpleName().equals("GroupSeparator"));
        if (next.getClass().getSimpleName().equals("BibleVersion")) {
            BibleVersion thisBibleVersion = (BibleVersion) next;
            if (preferredVersions.contains(thisBibleVersion.getAbbrev())) {
                preferredVersionsIndices.add(idx);
            }
        }
    }
    indices = ArrayUtils
            .toPrimitive(preferredVersionsIndices.toArray(new Integer[preferredVersionsIndices.size()]));
    //System.out.println("value of indices array: "+Arrays.toString(indices));

}

From source file:edu.usu.sdl.openstorefront.usecase.ValidationUseCase.java

private <T> String generateWhereClause(T example, String parentFieldName) {
    StringBuilder where = new StringBuilder();

    try {/*from   w  w w .j a va 2 s  .c  o m*/
        Map fieldMap = BeanUtils.describe(example);
        boolean addAnd = false;
        for (Object field : fieldMap.keySet()) {

            if ("class".equalsIgnoreCase(field.toString()) == false) {
                Object value = fieldMap.get(field);
                if (value != null) {

                    Method method = example.getClass()
                            .getMethod("get" + StringUtils.capitalize(field.toString()), (Class<?>[]) null);
                    Object returnObj = method.invoke(example, (Object[]) null);
                    if (ReflectionUtil.isComplexClass(returnObj.getClass())) {
                        if (StringUtils.isNotBlank(parentFieldName)) {
                            parentFieldName = parentFieldName + ".";
                        }
                        parentFieldName = parentFieldName + field;
                        where.append(generateWhereClause(returnObj, parentFieldName));
                    } else {
                        if (addAnd) {
                            where.append(" AND ");
                        } else {
                            addAnd = true;
                            where.append(" ");
                        }

                        String fieldName = field.toString();
                        if (StringUtils.isNotBlank(parentFieldName)) {
                            fieldName = parentFieldName + "." + fieldName;
                        }

                        where.append(fieldName).append(" = :").append(fieldName.replace(".", "_"))
                                .append("Param");
                    }
                }
            }
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        throw new RuntimeException(ex);
    }
    return where.toString();
}

From source file:com.ericsson.eiffel.remrem.semantics.schemas.SchemaFile.java

/**
 * /*from w w  w.  ja v  a 2s  .c o  m*/
 * This method is used to adding the attributes JavaType ,ExtendsJavaType
 * and other required properties to input jsons
 * 
 * @param jsonContent
 *            -Eiffel repo json file content sent as an input parameter
 * @param jsonElementName
 *            -Name of the json elements as an input parameter
 * @param jsonObject
 *            -Json object is sent as an input to this to add required json
 *            properties to generate event pojo's
 */
private void addAttributesToJsonSchema(JsonObject jsonContent, String jsonElementName, JsonObject jsonObject) {
    Set<Entry<String, JsonElement>> values = jsonContent.entrySet();
    Iterator<Entry<String, JsonElement>> keyValue = values.iterator();
    while (keyValue.hasNext()) {
        Entry<String, JsonElement> valueSet = keyValue.next();
        if (valueSet.getValue().isJsonObject()) {
            String name = valueSet.getKey();
            String previousObjectName = jsonElementName;
            if (name.equals(EiffelConstants.META)) {
                isMeta = true;
            }
            if (name.equals(EiffelConstants.TYPE) && isMeta) {
                isMeta = false;
            }
            addingItemsProperties(name, valueSet.getValue(), jsonObject, previousObjectName);
        } else {
            if (EiffelConstants.TYPE.equals(valueSet.getKey())) {
                if (EiffelConstants.OBJECTTYPE.equals(valueSet.getValue().getAsString())) {
                    jsonObject.add(EiffelConstants.TYPE, valueSet.getValue());
                    if (isEvent) {
                        jsonObject.add(EiffelConstants.JAVA_TYPE,
                                parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS
                                        .concat(StringUtils.capitalize(jsonElementName))));
                        jsonObject.add(EiffelConstants.EXTENDS_JAVA_CLASS,
                                parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS_EVENT));
                        isEvent = false;

                    } else {
                        jsonElementName = modifyClassName(jsonElementName);
                        String newClassName = StringUtils.capitalize(jsonElementName);
                        if (jsonElementName.equals(EiffelConstants.META)) {
                            // To generate event specific Meta class
                            jsonObject.add(EiffelConstants.JAVA_TYPE,
                                    parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS
                                            .concat(this.eventName + "" + newClassName)));
                            JsonArray list = new JsonArray();
                            list.add("com.ericsson.eiffel.semantics.events.Meta");
                            jsonObject.add(EiffelConstants.JAVA_INTERFACES, list);
                        } else if (jsonElementName.equals(EiffelConstants.DATA)
                                || jsonElementName.equals(EiffelConstants.OUTCOME)) {
                            // Data and Outcome is different at event level
                            jsonObject.add(EiffelConstants.JAVA_TYPE,
                                    parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS
                                            .concat(this.eventName + "" + newClassName)));
                        } else if (jsonElementName.equals(EiffelConstants.ISSUE)) {
                            jsonObject.add(EiffelConstants.JAVA_TYPE,
                                    parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS
                                            .concat(this.eventName + "" + newClassName)));
                        } else {
                            jsonObject.add(EiffelConstants.JAVA_TYPE, parser.parse(
                                    EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS.concat(newClassName)));
                        }
                    }
                } else {
                    jsonObject.add(EiffelConstants.TYPE, valueSet.getValue());
                    if (jsonElementName.equals(EiffelConstants.TIME)) {
                        jsonObject.add(EiffelConstants.FORMAT, parser.parse(EiffelConstants.UTC_MILLISEC));
                    }
                }
            } else {
                jsonObject.add(valueSet.getKey(), valueSet.getValue());
            }
        }
    }
    if (values.isEmpty()) {
        // If value field doesn't have any data type we make it to
        // accept either object or string value
        JsonArray array = new JsonArray();
        JsonObject obj1 = new JsonObject();
        JsonObject obj2 = new JsonObject();
        JsonObject obj3 = new JsonObject();
        JsonObject obj4 = new JsonObject();
        obj1.add(EiffelConstants.TYPE, parser.parse(EiffelConstants.OBJECTTYPE));
        obj2.add(EiffelConstants.TYPE, parser.parse(EiffelConstants.STRING));
        obj3.add(EiffelConstants.TYPE, parser.parse(EiffelConstants.ARRAY));
        obj4.add(EiffelConstants.TYPE, parser.parse(EiffelConstants.NUMBER));
        array.add(obj1);
        array.add(obj2);
        array.add(obj3);
        array.add(obj4);
        jsonObject.add(EiffelConstants.ANYOF, array);

    }
}

From source file:com.hesine.manager.generate.Generate.java

public static void execute(File curProjectPath) {
    // ==========  ?? ====================

    // ??????//from w w  w.j  ava2  s .  com
    // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className}

    // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4?
    String packageName = "com.hesine.manager";

    //      String moduleName = "function";         // ???sys
    String moduleName = ""; // ???sys
    String tableName = "tb_product"; // ???sys
    String subModuleName = ""; // ?????
    String className = "product"; // ??product
    String classAuthor = "Jason"; // ThinkGem
    String functionName = "?"; // ??
    List<Map<String, String>> fileds = new ArrayList<Map<String, String>>();
    // map
    Map<String, String> dataName = new HashMap<String, String>();
    dataName.put("dataType", "String");
    dataName.put("name", "name");
    dataName.put("methodName", "Name");
    dataName.put("comment", "??");
    dataName.put("dbName", "name");

    Map<String, String> dataDesc = new HashMap<String, String>();
    dataDesc.put("dataType", "String");
    dataDesc.put("name", "description");
    dataDesc.put("methodName", "Description");
    dataDesc.put("comment", "??");
    dataDesc.put("dbName", "description");

    fileds.add(dataName);
    fileds.add(dataDesc);

    // ???
    Boolean isEnable = true;

    // ==========  ?? ====================

    if (!isEnable) {
        logger.error("????isEnable = true");
        return;
    }

    //        StringUtils.isBlank(moduleName) ||
    if (StringUtils.isBlank(packageName) || StringUtils.isBlank(className)
            || StringUtils.isBlank(functionName)) {
        logger.error("??????????????");
        return;
    }

    // ?
    String separator = File.separator;

    // ?
    File projectPath = curProjectPath;
    while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) {
        projectPath = projectPath.getParentFile();
    }
    logger.info("Project Path: {}", projectPath);

    // ?
    String tplPath = StringUtils.replace(projectPath + "/src/main/java/com/hesine/manager/generate/template",
            "/", separator);
    logger.info("Template Path: {}", tplPath);

    // Java
    String javaPath = StringUtils.replaceEach(
            projectPath + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." },
            new String[] { separator, separator });
    logger.info("Java Path: {}", javaPath);

    // Xml
    String xmlPath = StringUtils.replace(projectPath + "/src/main/resources/mybatis", "/", separator);
    logger.info("Xml Path: {}", xmlPath);

    // 
    String viewPath = StringUtils.replace(projectPath + "/src/main/webapp/WEB-INF/views", "/", separator);
    logger.info("View Path: {}", viewPath);

    // ???
    Map<String, Object> model = Maps.newHashMap();
    model.put("packageName", StringUtils.lowerCase(packageName));
    model.put("moduleName", StringUtils.lowerCase(moduleName));
    model.put("subModuleName",
            StringUtils.isNotBlank(subModuleName) ? "." + StringUtils.lowerCase(subModuleName) : "");
    model.put("className", StringUtils.uncapitalize(className));
    model.put("ClassName", StringUtils.capitalize(className));
    model.put("classAuthor", StringUtils.isNotBlank(classAuthor) ? classAuthor : "Generate Tools");
    model.put("classVersion", DateUtils.getDate());
    model.put("functionName", functionName);
    //      model.put("tableName", model.get("moduleName")+(StringUtils.isNotBlank(subModuleName)
    //            ?"_"+StringUtils.lowerCase(subModuleName):"")+"_"+model.get("className"));
    model.put("tableName", tableName);

    model.put("urlPrefix",
            model.get("moduleName")
                    + (StringUtils.isNotBlank(subModuleName) ? "/" + StringUtils.lowerCase(subModuleName) : "")
                    + "/" + model.get("className"));
    model.put("viewPrefix", //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+
            model.get("urlPrefix"));
    model.put("permissionPrefix",
            model.get("moduleName")
                    + (StringUtils.isNotBlank(subModuleName) ? ":" + StringUtils.lowerCase(subModuleName) : "")
                    + ":" + model.get("className"));
    model.put("fileds", fileds);

    //        // ? Entity
    //        FileGenUtils.generateEntity(tplPath, javaPath, model);
    //
    //        // ? sqlMap
    //        FileGenUtils.generateSqlMap(tplPath, xmlPath, model);
    //
    //        // ? Model
    //        FileGenUtils.generateModel(tplPath, javaPath, model);
    //
    //        // ? Dao
    //        FileGenUtils.generateDao(tplPath, javaPath, model);
    //
    //        // ? Service
    //        FileGenUtils.generateService(tplPath, javaPath, model);
    //
    //        // ? ServiceImpl
    //        FileGenUtils.generateServiceImpl(tplPath, javaPath, model);
    //
    //        // ? Controller
    //        FileGenUtils.generateController(tplPath, javaPath, model);

    // ? add.ftl
    FileGenUtils.generateAddFtl(tplPath, viewPath, model);

    // ? edit.ftl
    FileGenUtils.generateEditFtl(tplPath, viewPath, model);

    // ? list.ftl
    FileGenUtils.generateListFtl(tplPath, viewPath, model);

    logger.info("Generate Success.");
}

From source file:forge.game.mana.ManaPool.java

public final List<Mana> clearPool(boolean isEndOfPhase) {
    // isEndOfPhase parameter: true = end of phase, false = mana drain effect
    List<Mana> cleared = new ArrayList<Mana>();
    if (floatingMana.isEmpty()) {
        return cleared;
    }//from ww  w  . ja  v  a2s  . c  o m

    if (isEndOfPhase
            && owner.getGame().getStaticEffects().getGlobalRuleChange(GlobalRuleChange.manapoolsDontEmpty)) {
        return cleared;
    }

    final boolean convertToColorless = owner.hasKeyword("Convert unused mana to Colorless");

    final List<Byte> keys = Lists.newArrayList(floatingMana.keySet());
    if (isEndOfPhase) {
        for (final Byte c : Lists.newArrayList(keys)) {
            final String captName = StringUtils.capitalize(MagicColor.toLongString(c));
            if (owner.hasKeyword(
                    captName + " mana doesn't empty from your mana pool as steps and phases end.")) {
                keys.remove(c);
            }
        }
    }
    if (convertToColorless) {
        keys.remove(Byte.valueOf(MagicColor.COLORLESS));
    }

    for (Byte b : keys) {
        Collection<Mana> cm = floatingMana.get(b);
        if (isEndOfPhase && !owner.getGame().getPhaseHandler().is(PhaseType.CLEANUP)) {
            final List<Mana> pMana = new ArrayList<Mana>();
            for (final Mana mana : cm) {
                if (mana.getManaAbility() != null && mana.getManaAbility().isPersistentMana()) {
                    pMana.add(mana);
                }
            }
            cm.removeAll(pMana);
            if (convertToColorless) {
                convertManaColor(b, MagicColor.COLORLESS);
                cm.addAll(pMana);
            } else {
                cleared.addAll(cm);
                cm.clear();
                floatingMana.putAll(b, pMana);
            }
        } else {
            if (convertToColorless) {
                convertManaColor(b, MagicColor.COLORLESS);
            } else {
                cleared.addAll(cm);
                cm.clear();
            }
        }
    }

    owner.updateManaForView();
    owner.getGame().fireEvent(new GameEventManaPool(owner, EventValueChangeType.Cleared, null));
    return cleared;
}