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:ch.algotrader.esper.aggregation.GenericTALibFunctionFactory.java

private Class<?> getReturnClass(String className, Map<String, Class<?>> fields)
        throws CannotCompileException, NotFoundException {

    String fqClassName = this.getClass().getPackage().getName() + ".talib." + className;

    try {//from   w  ww.  ja v a  2s. co m
        // see if the class already exists
        return Class.forName(fqClassName);

    } catch (ClassNotFoundException e) {

        // otherwise create the class
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.makeClass(fqClassName);

        for (Map.Entry<String, Class<?>> entry : fields.entrySet()) {

            // generate a public field (we don't need a setter)
            String fieldName = entry.getKey();
            CtClass valueClass = pool.get(entry.getValue().getName());
            CtField ctField = new CtField(valueClass, fieldName, ctClass);
            ctField.setModifiers(Modifier.PUBLIC);
            ctClass.addField(ctField);

            // generate the getter method
            String methodName = "get" + StringUtils.capitalize(fieldName);
            CtMethod ctMethod = CtNewMethod.make(valueClass, methodName, new CtClass[] {}, new CtClass[] {},
                    "{ return this." + fieldName + ";}", ctClass);
            ctClass.addMethod(ctMethod);
        }
        return ctClass.toClass();
    }
}

From source file:eu.europeana.corelib.edm.utils.EdmUtils.java

private static Country convertMapToCountry(Map<String, List<String>> edmCountry) {

    if (edmCountry != null && edmCountry.size() > 0) {
        Country country = new Country();
        StringBuilder sb = new StringBuilder();
        String[] splitCountry = edmCountry.entrySet().iterator().next().getValue().get(0).split(SPACE);
        for (String countryWord : splitCountry) {
            if (StringUtils.equals("and", countryWord)) {
                sb.append(countryWord);//from ww w .  ja v a2  s .  co  m
            } else {
                sb.append(StringUtils.capitalize(countryWord));
            }
            sb.append(SPACE);
        }
        String countryFixed = sb.toString().replace(" Of ", " of ").trim();
        country.setCountry(CountryCodes.convert(countryFixed));

        return country;
    }
    return null;
}

From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java

private File compile(SubnodeConfiguration languageConf, String transformTypeString, File srcTransformFile,
        File jobTransformDir) throws CompilationException, IOException {
    // Determine correct compiler, returning if none specified
    String compiler = languageConf.getString("compiler-" + transformTypeString, "");
    if (compiler.isEmpty())
        compiler = languageConf.getString("compiler", "");
    if (compiler.isEmpty())
        return srcTransformFile;

    // Determine destination filename
    File compiledTransformFile = new File(jobTransformDir, "compiled-job-" + transformTypeString);

    // Create map to replace ${wmr:...} variables.
    // NOTE: Commons Configuration's built-in interpolator does not work here
    //  for some reason.
    File jobTempDir = getJobTempDir();
    Hashtable<String, String> variableMap = new Hashtable<String, String>();
    File libDir = getLibraryDirectory(languageConf);
    variableMap.put("wmr:lib.dir", (libDir != null) ? libDir.toString() : "");
    variableMap.put("wmr:src.dir", relativizeFile(srcTransformFile.getParentFile(), jobTempDir).toString());
    variableMap.put("wmr:src.file", relativizeFile(srcTransformFile, jobTempDir).toString());
    variableMap.put("wmr:dest.dir", relativizeFile(jobTransformDir, jobTempDir).toString());
    variableMap.put("wmr:dest.file", relativizeFile(compiledTransformFile, jobTempDir).toString());

    // Replace variables in compiler string
    compiler = StrSubstitutor.replace(compiler, variableMap);

    // Run the compiler

    CommandLine compilerCommand = CommandLine.parse(compiler);
    DefaultExecutor exec = new DefaultExecutor();
    ExecuteWatchdog dog = new ExecuteWatchdog(60000); // 1 minute
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output);
    exec.setWorkingDirectory(jobTempDir);
    exec.setWatchdog(dog);/*from  w  ww . j a va  2s .  c  o m*/
    exec.setStreamHandler(pump);
    exec.setExitValues(null); // Can't get the exit code if it throws exception

    int exitStatus = -1;
    try {
        exitStatus = exec.execute(compilerCommand);
    } catch (IOException ex) {
        // NOTE: Exit status is still -1 in this case, since exception was thrown
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));
    }

    // Check for successful exit

    if (exitStatus != 0)
        throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus,
                new String(output.toByteArray()));

    // Check that output exists and is readable, and make it executable

    if (!compiledTransformFile.isFile())
        throw new CompilationException(
                "Compiler did not output a " + transformTypeString
                        + " executable (or it was not a regular file).",
                exitStatus, new String(output.toByteArray()));

    if (!compiledTransformFile.canRead())
        throw new IOException(StringUtils.capitalize(transformTypeString)
                + " executable output from compiler was not readable: " + compiledTransformFile.toString());

    if (!compiledTransformFile.canExecute())
        compiledTransformFile.setExecutable(true, false);

    return compiledTransformFile;
}

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

private String getSetterName(String fieldName) {
    if (fieldName.startsWith("_")) {
        fieldName = fieldName.substring(1);
    }/*from ww w . j  av a2 s .  co m*/
    return "set" + StringUtils.capitalize(fieldName);
}

From source file:com.haulmont.cuba.gui.xml.layout.loaders.DataGridLoader.java

protected Column loadColumn(DataGrid component, Element element, Datasource ds) {
    String id = element.attributeValue("id");
    String property = element.attributeValue("property");

    if (id == null) {
        if (property != null) {
            id = property;/*from  w  ww  . ja va 2  s  . co  m*/
        } else {
            throw new GuiDevelopmentException("A column must have whether id or property specified",
                    context.getCurrentFrameId(), "DataGrid ID", component.getId());
        }
    }

    Column column;
    if (property != null) {
        MetaPropertyPath metaPropertyPath = AppBeans.get(MetadataTools.NAME, MetadataTools.class)
                .resolveMetaPropertyPath(ds.getMetaClass(), property);
        column = component.addColumn(id, metaPropertyPath);
    } else {
        column = component.addColumn(id, null);
    }

    String expandRatio = element.attributeValue("expandRatio");
    if (StringUtils.isNotEmpty(expandRatio)) {
        column.setExpandRatio(Integer.parseInt(expandRatio));
    }

    String collapsed = element.attributeValue("collapsed");
    if (StringUtils.isNotEmpty(collapsed)) {
        column.setCollapsed(Boolean.parseBoolean(collapsed));
    }

    String collapsible = element.attributeValue("collapsible");
    if (StringUtils.isNotEmpty(collapsible)) {
        column.setCollapsible(Boolean.parseBoolean(collapsible));
    }

    String collapsingToggleCaption = element.attributeValue("collapsingToggleCaption");
    if (StringUtils.isNotEmpty(collapsingToggleCaption)) {
        collapsingToggleCaption = loadResourceString(collapsingToggleCaption);
        column.setCollapsingToggleCaption(collapsingToggleCaption);
    }

    String sortable = element.attributeValue("sortable");
    if (StringUtils.isNotEmpty(sortable)) {
        column.setSortable(Boolean.parseBoolean(sortable));
    }

    String resizable = element.attributeValue("resizable");
    if (StringUtils.isNotEmpty(resizable)) {
        column.setResizable(Boolean.parseBoolean(resizable));
    }

    String editable = element.attributeValue("editable");
    if (StringUtils.isNotEmpty(editable)) {
        column.setEditable(Boolean.parseBoolean(editable));
    }

    // Default caption set to columns when it is added to a DataGrid,
    // so we need to set caption as null to get caption from
    // metaProperty if 'caption' attribute is empty
    column.setCaption(null);
    String caption = loadCaption(element);

    if (caption == null) {
        String columnCaption;
        if (column.getPropertyPath() != null) {
            MetaProperty metaProperty = column.getPropertyPath().getMetaProperty();
            String propertyName = metaProperty.getName();

            if (DynamicAttributesUtils.isDynamicAttribute(metaProperty)) {
                CategoryAttribute categoryAttribute = DynamicAttributesUtils.getCategoryAttribute(metaProperty);
                columnCaption = LocaleHelper.isLocalizedValueDefined(categoryAttribute.getLocaleNames())
                        ? categoryAttribute.getLocaleName()
                        : StringUtils.capitalize(categoryAttribute.getName());
            } else {
                MetaClass propertyMetaClass = metadataTools
                        .getPropertyEnclosingMetaClass(column.getPropertyPath());
                columnCaption = messageTools.getPropertyCaption(propertyMetaClass, propertyName);
            }
        } else {
            Class<?> declaringClass = ds.getMetaClass().getJavaClass();
            String className = declaringClass.getName();
            int i = className.lastIndexOf('.');
            if (i > -1) {
                className = className.substring(i + 1);
            }
            columnCaption = messages.getMessage(declaringClass, className + "." + id);
        }
        column.setCaption(columnCaption);
    } else {
        column.setCaption(caption);
    }

    column.setXmlDescriptor(element);

    Integer width = loadWidth(element, "width");
    if (width != null) {
        column.setWidth(width);
    }

    Integer minimumWidth = loadWidth(element, "minimumWidth");
    if (minimumWidth != null) {
        column.setMinimumWidth(minimumWidth);
    }

    Integer maximumWidth = loadWidth(element, "maximumWidth");
    if (maximumWidth != null) {
        column.setMaximumWidth(maximumWidth);
    }

    column.setFormatter(loadFormatter(element));

    return column;
}

From source file:ddf.catalog.metrics.SourceMetricsImpl.java

protected String getRrdFilename(String sourceId, String collectorName) {

    // Based on the sourceId and collectorName, generate the name of the RRD file.
    // This RRD file will be of the form "source<sourceId><collectorName>.rrd" with
    // the non-alphanumeric characters stripped out and the next character after any
    // non-alphanumeric capitalized.
    // Example://  w ww  .j av  a2 s  .c o m
    //     Given sourceId = dib30rhel-58 and collectorName = Queries.TotalResults
    //     The resulting RRD filename would be: sourceDib30rhel58QueriesTotalResults.rrd
    String[] sourceIdParts = sourceId.split(ALPHA_NUMERIC_REGEX);
    String newSourceId = "";
    for (String part : sourceIdParts) {
        newSourceId += StringUtils.capitalize(part);
    }
    String rrdPath = "source" + newSourceId + collectorName;
    LOGGER.debug("BEFORE: rrdPath = " + rrdPath);

    // Sterilize RRD path name by removing any non-alphanumeric characters - this would confuse the
    // URL being generated for this RRD path in the Metrics tab of Admin console.
    rrdPath = rrdPath.replaceAll(ALPHA_NUMERIC_REGEX, "");
    rrdPath += RRD_FILENAME_EXTENSION;
    LOGGER.debug("AFTER: rrdPath = " + rrdPath);

    return rrdPath;
}

From source file:net.sf.firemox.clickable.target.card.CardFactory.java

/**
 * Read from the specified stream the state picture options. The current
 * offset of the stream must pointing on the number of state pictures.
 * <ul>/*from w ww  .java  2  s .  c  o m*/
 * Structure of InputStream : Data[size]
 * <li>number of states [1]</li>
 * <li>state picture name i + \0 [...]</li>
 * <li>state value i + \0 [...]</li>
 * <li>state picture x i [2]</li>
 * <li>state picture y i [2]</li>
 * <li>state picture width i [2]</li>
 * <li>state picture height i [2]</li>
 * </ul>
 * <br>
 * Read from the specified stream the tooltip filters. The current offset of
 * the stream must pointing on the number of tooltip filters.
 * <ul>
 * Structure of stream : Data[size]
 * <li>display powerANDtoughness yes=1,no=0 [1]</li>
 * <li>display states yes=1,no=0 [1]</li>
 * <li>display types yes=1,no=0 [1]</li>
 * <li>display colors yes=1,no=0 [1]</li>
 * <li>display properties yes=1,no=0 [1]</li>
 * <li>display damage yes=1,no=0 [1]</li>
 * <li>filter [...]</li>
 * </ul>
 * 
 * @param input
 *          the stream containing settings.
 * @throws IOException
 *           If some other I/O error occurs
 */
public static void init(InputStream input) throws IOException {
    loadedCards.clear();
    // load state pictures of card
    statePictures = new StatePicture[input.read()];
    for (int i = 0; i < statePictures.length; i++) {
        statePictures[i] = new StatePicture(input);
    }

    // load tooltip filters
    tooltipFilters = new TooltipFilter[input.read()];
    for (int i = 0; i < tooltipFilters.length; i++) {
        tooltipFilters[i] = new TooltipFilter(input);
    }

    // read types name export (this list must be sorted)
    int count = input.read();
    exportedIdCardNames = new String[count];
    exportedIdCardValues = new int[count];
    for (int i = 0; i < count; i++) {
        exportedIdCardNames[i] = StringUtils
                .capitalize(LanguageManagerMDB.getString(MToolKit.readString(input)));
        exportedIdCardValues[i] = MToolKit.readInt16(input);
    }

    // read properties name export (this list must be sorted)
    exportedProperties = new TreeMap<Integer, String>();
    for (int i = MToolKit.readInt16(input); i-- > 0;) {
        final Integer key = Integer.valueOf(MToolKit.readInt16(input));
        exportedProperties.put(key,
                StringUtils.capitalize(LanguageManagerMDB.getString(MToolKit.readString(input))));
    }

    // property pictures
    if (propertyPicturesHTML != null) {
        propertyPicturesHTML.clear();
        propertyPictures.clear();
    } else {
        propertyPictures = new HashMap<Integer, Image>();
        propertyPicturesHTML = new HashMap<Integer, String>();
    }
    for (int i = MToolKit.readInt16(input); i-- > 0;) {
        final int property = MToolKit.readInt16(input);
        final String pictureStr = MToolKit.readString(input);
        if (pictureStr.length() > 0) {
            final String pictureName = "properties/" + pictureStr;
            propertyPicturesHTML.put(property,
                    "<img src='file:///" + MToolKit.getTbsHtmlPicture(pictureName) + "'>&nbsp;");
            final String pictureFile = MToolKit.getTbsPicture("properties/" + pictureStr);
            if (pictureFile != null) {
                propertyPictures.put(property, Picture.loadImage(pictureFile));
            } else if (MagicUIComponents.isUILoaded()) {
                Log.error(
                        "Unable to load property picture '" + MToolKit.getTbsPicture(pictureName, false) + "'");
            }
        }
    }

    // Add system card
    loadedCards.put("system", new CardModelImpl("system"));
}

From source file:hudson.security.HudsonPrivateSecurityRealmTest.java

private void createAccountByAdmin(String login) throws Exception {
    // user should not exist before
    assertNull(User.getById(login, false));

    JenkinsRule.WebClient wc = j.createWebClient();
    wc.login("admin");

    spySecurityListener.loggedInUsernames.clear();

    HtmlPage page = wc.goTo("securityRealm/addUser");
    HtmlForm form = page.getForms().stream()
            .filter(htmlForm -> htmlForm.getActionAttribute().endsWith("/securityRealm/createAccountByAdmin"))
            .findFirst().orElseThrow(() -> new AssertionError("Form must be present"));

    form.getInputByName("username").setValueAttribute(login);
    form.getInputByName("password1").setValueAttribute(login);
    form.getInputByName("password2").setValueAttribute(login);
    form.getInputByName("fullname").setValueAttribute(StringUtils.capitalize(login));
    form.getInputByName("email").setValueAttribute(login + "@" + login + ".com");

    HtmlPage p = j.submit(form);//w w  w. j a v  a  2  s . c o m
    assertEquals(200, p.getWebResponse().getStatusCode());
    assertTrue(p.getDocumentElement().getElementsByAttribute("div", "class", "error").isEmpty());

    assertNotNull(User.getById(login, false));
}

From source file:com.taobao.android.builder.tools.manifest.AtlasProxy.java

public static void addAtlasProxyClazz(Document document, Set<String> nonProxyChannels, Result result) {

    Element root = document.getRootElement();// 

    List<? extends Node> serviceNodes = root.selectNodes("//@android:process");

    String packageName = root.attribute("package").getStringValue();

    Set<String> processNames = new HashSet<>();
    processNames.add(packageName);/*from  w w  w . j  a v  a 2 s.  c om*/

    for (Node node : serviceNodes) {
        if (null != node && StringUtils.isNotEmpty(node.getStringValue())) {
            String value = node.getStringValue();
            processNames.add(value);
        }
    }

    processNames.removeAll(nonProxyChannels);

    List<String> elementNames = Lists.newArrayList("activity", "service", "provider");

    Element applicationElement = root.element("application");

    for (String processName : processNames) {

        for (String elementName : elementNames) {

            String processClazzName = processName.replace(":", "").replace(".", "_");
            String fullClazzName = "ATLASPROXY_" + processClazzName + "_" + StringUtils.capitalize(elementName);

            if ("activity".equals(elementName)) {
                result.proxyActivities.add(fullClazzName);
            } else if ("service".equals(elementName)) {
                result.proxyServices.add(fullClazzName);
            } else {
                result.proxyProviders.add(fullClazzName);
            }

            Element newElement = applicationElement.addElement(elementName);
            newElement.addAttribute("android:name", ATLAS_PROXY_PACKAGE + "." + fullClazzName);

            if (!packageName.equals(processName)) {
                newElement.addAttribute("android:process", processName);
            }

            boolean isProvider = "provider".equals(elementName);
            if (isProvider) {
                newElement.addAttribute("android:authorities", ATLAS_PROXY_PACKAGE + "." + fullClazzName);
            }

        }

    }

}

From source file:com.manydesigns.elements.fields.search.SelectSearchField.java

private void valueToXhtmlMultipleSelection(XhtmlBuffer xb) {
    xb.writeLabel(StringUtils.capitalize(label), id, ATTR_NAME_HTML_CLASS);
    xb.openElement("div");
    xb.addAttribute("class", "controls");

    Object[] values = getValues();
    Map<Object, SelectionModel.Option> options = selectionModel.getOptions(selectionModelIndex);
    xb.openElement("select");
    xb.addAttribute("id", id);
    xb.addAttribute("name", inputName);
    xb.addAttribute("multiple", "multiple");
    xb.addAttribute("size", "5");

    boolean checked;

    for (Map.Entry<Object, SelectionModel.Option> option : options.entrySet()) {
        if (!option.getValue().active) {
            continue;
        }//from   w  ww.  ja v a  2  s  . co m
        Object optionValue = option.getKey();
        String optionStringValue = OgnlUtils.convertValueToString(optionValue);
        String optionLabel = option.getValue().label;
        checked = ArrayUtils.contains(values, optionValue);
        xb.writeOption(optionStringValue, checked, optionLabel);
    }
    xb.closeElement("select");
    xb.closeElement("div");
}