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:com.sinosoft.one.mvc.web.impl.module.ControllerRef.java

private void init() {
    List<MethodRef> actions = new LinkedList<MethodRef>();
    Class<?> clz = controllerClass;
    ///*from  ww  w  .  j  a va2 s .  c  om*/
    List<Method> pastMethods = new LinkedList<Method>();
    while (true) {
        Method[] declaredMethods = clz.getDeclaredMethods();

        //class?ReqMethodvalue??ReqMethod?methodName
        //sort?,???????0?0+1??,??????
        Arrays.sort(declaredMethods, new Comparator<Method>() {
            public int compare(Method o1, Method o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        //?ReqMethod?ReqMethod.value?
        Map<ReqMethod, Method> checkReqMethod = new HashMap<ReqMethod, Method>();

        for (Method method : declaredMethods) {
            if (quicklyPass(pastMethods, method, controllerClass)) {
                continue;
            }

            Map<ReqMethod, String[]> shotcutMappings = collectsShotcutMappings(method);
            if (shotcutMappings.size() == 0) {
                if (ignoresCommonMethod(method)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("ignores common methods of controller " + controllerClass.getName() + "#"
                                + method.getName());
                    }
                } else {
                    // TODO: ?0.91.0?201007??
                    if ("get".equals(method.getName()) || "index".equals(method.getName())) {
                        // ??get/index@Get?@Get??
                        throw new IllegalArgumentException(
                                "please add @Get to " + controllerClass.getName() + "#" + method.getName());
                    }
                    if ("post".equals(method.getName()) || "delete".equals(method.getName())
                            || "put".equals(method.getName())) {
                        // ??post/delete/put@Get/@Delete/@Put?@Get??
                        throw new IllegalArgumentException(
                                "please add @" + StringUtils.capitalize(method.getName()) + " to "
                                        + controllerClass.getName() + "#" + method.getName());
                    }
                    shotcutMappings = new HashMap<ReqMethod, String[]>();
                    shotcutMappings.put(ReqMethod.GET, new String[] { "/" + method.getName() });
                    shotcutMappings.put(ReqMethod.POST, new String[] { "/" + method.getName() });
                }
            }
            if (shotcutMappings.size() > 0) {
                MethodRef methodRef = new MethodRef();
                for (Map.Entry<ReqMethod, String[]> entry : shotcutMappings.entrySet()) {

                    //?ReqMethod?ReqMethod.value?
                    if (entry.getValue().length == 1 && entry.getValue()[0].equals("")) {
                        if (checkReqMethod.get(entry.getKey()) == null) {
                            checkReqMethod.put(entry.getKey(), method);
                        } else {
                            entry.setValue(new String[] { "/" + method.getName() });
                        }
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("[MethodPath] create:" + entry.getKey() + "="
                                + Arrays.toString(entry.getValue()));
                    }
                    methodRef.addMapping(entry.getKey(), entry.getValue());
                }
                methodRef.setMethod(method);
                actions.add(methodRef);
            }
        }
        for (int i = 0; i < declaredMethods.length; i++) {
            pastMethods.add(declaredMethods[i]);
        }
        clz = clz.getSuperclass();
        if (clz == null || clz.getAnnotation(AsSuperController.class) == null) {
            break;
        }
    }
    this.actions = actions;
}

From source file:ch.entwine.weblounge.kernel.runtime.EnvironmentService.java

/**
 * {@inheritDoc}/*  w  w w.  j  ava 2s . co m*/
 * 
 * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
 */
@SuppressWarnings("rawtypes")
public void updated(Dictionary properties) throws ConfigurationException {
    if (properties == null)
        return;

    // Environment
    Environment env = null;
    String environmentValue = StringUtils.trimToNull((String) properties.get(OPT_ENVIRONMENT));
    if (StringUtils.isNotBlank(environmentValue)) {
        try {
            env = Environment.valueOf(StringUtils.capitalize(environmentValue));
            logger.debug("Configured value for the default runtime environment is '{}'",
                    env.toString().toLowerCase());
        } catch (IllegalArgumentException e) {
            throw new ConfigurationException(OPT_ENVIRONMENT, environmentValue);
        }
    } else {
        env = DEFAULT_ENVIRONMENT;
        logger.debug("Using default value '{}' for runtime environment", env.toString().toLowerCase());
    }

    // Did the setting change?
    if (!env.equals(environment)) {
        this.environment = env;
        if (registration != null) {
            try {
                registration.unregister();
            } catch (IllegalStateException e) {
                // Never mind, the service has been unregistered already
            } catch (Throwable t) {
                logger.error("Unregistering runtime environment failed: {}", t.getMessage());
            }
        }
        registration = bundleContext.registerService(Environment.class.getName(), environment, null);
        logger.info("Runtime environment set to '{}'", environment.toString().toLowerCase());
    }
}

From source file:CubaEnhancer.java

private void enhanceSetters(CtClass ctClass)
        throws NotFoundException, CannotCompileException, ClassNotFoundException {
    for (CtMethod ctMethod : ctClass.getDeclaredMethods()) {
        final String name = ctMethod.getName();
        if (Modifier.isAbstract(ctMethod.getModifiers()) || !name.startsWith("set")
                || ctMethod.getReturnType() != CtClass.voidType || ctMethod.getParameterTypes().length != 1)
            continue;

        String fieldName = StringUtils.uncapitalize(name.substring(3));

        // check if the setter is for a persistent or transient property
        CtMethod persistenceMethod = null;
        for (CtMethod method : ctClass.getDeclaredMethods()) {
            if (method.getName().equals("_persistence_set_" + fieldName)) {
                persistenceMethod = method;
                break;
            }//  w  ww .  j a va  2 s  . c om
        }
        if (persistenceMethod == null) {
            // can be a transient property
            CtField ctField = null;
            CtField[] declaredFields = ctClass.getDeclaredFields();
            for (CtField field : declaredFields) {
                if (field.getName().equals(fieldName)) {
                    ctField = field;
                    break;
                }
            }
            if (ctField == null)
                continue; // no field
            // check if the field is annotated with @MetaProperty
            // cannot use ctField.getAnnotation() because of problem with classpath in child projects
            AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) ctField.getFieldInfo()
                    .getAttribute(AnnotationsAttribute.visibleTag);
            if (annotationsAttribute == null
                    || annotationsAttribute.getAnnotation(METAPROPERTY_ANNOTATION) == null)
                continue;
        }

        CtClass setterParamType = ctMethod.getParameterTypes()[0];

        if (setterParamType.isPrimitive()) {
            throw new IllegalStateException(
                    String.format("Unable to enhance field %s.%s with primitive type %s. Use type %s.",
                            ctClass.getName(), fieldName, setterParamType.getSimpleName(),
                            StringUtils.capitalize(setterParamType.getSimpleName())));
        }

        ctMethod.addLocalVariable("__prev", setterParamType);

        ctMethod.insertBefore("__prev = this.get" + StringUtils.capitalize(fieldName) + "();");

        ctMethod.insertAfter(
                "if (!com.haulmont.chile.core.model.utils.InstanceUtils.propertyValueEquals(__prev, $1)) {"
                        + "  this.propertyChanged(\"" + fieldName + "\", __prev, $1);" + "}");
    }
}

From source file:eu.crydee.alignment.aligner.cr.BritannicaCR.java

@Override
public void getNext(JCas jcas) throws IOException, CollectionException {
    JCas eleV, briV;/*from  w ww  . j  a  va  2 s  .com*/
    try {
        eleV = ViewCreatorAnnotator.createViewSafely(jcas, eleName);
        briV = ViewCreatorAnnotator.createViewSafely(jcas, normalName);
    } catch (AnalysisEngineProcessException ex) {
        throw new CollectionException(ex);
    }
    jcas.setDocumentLanguage("en");
    eleV.setDocumentLanguage("en");
    briV.setDocumentLanguage("en");
    String eleFilepath = filesNames[currentIndex], normalFilepath = eleFilepath.replace("-ele.ada", "-bri.ada"),
            annName = eleFilepath.replace("-ele.ada", "-hum.txt"),
            name = StringUtils.capitalize(eleFilepath.replace("-ele.ada", ""));
    File ele = new File(corpus, eleFilepath), bri = new File(corpus, normalFilepath),
            ann = new File(anns, annName);
    ListMultimap<Integer, Integer> eleBriGold = ArrayListMultimap.create(),
            briEleGold = ArrayListMultimap.create();
    try (BufferedReader br = new BufferedReader(new FileReader(ann))) {
        String line;
        int k = 0;
        int i = -1;
        while ((line = br.readLine()) != null) {
            switch (k % 3) {
            case 0:
                i = Integer.parseInt(line.split(" ")[0]);
                break;
            case 1:
                int j = Integer.parseInt(line.split(" ")[0]);
                eleBriGold.put(i, j);
                briEleGold.put(j, i);
                break;
            case 2:
                break;
            }
            ++k;
        }
    }
    StringBuilder eleSb = new StringBuilder(), normalSb = new StringBuilder();
    List<Sentence> eleSents = new ArrayList<>(), briSents = new ArrayList<>();
    handleAda(ele, eleSb, eleSents, eleV);
    handleAda(bri, normalSb, briSents, briV);
    for (Integer eleIndex : eleBriGold.keySet()) {
        Sentence eleSent = eleSents.get(eleIndex - 1);
        List<Integer> briIndeces = eleBriGold.get(eleIndex);
        eleSent.setGoldSimilarities(new FSArray(eleV, briIndeces.size()));
        for (int i = 0, l = briIndeces.size(); i < l; ++i) {
            Sentence briSent = briSents.get(briIndeces.get(i) - 1);
            eleSent.setGoldSimilarities(i, briSent);
        }
    }
    for (Integer briIndex : briEleGold.keySet()) {
        Sentence briSent = briSents.get(briIndex - 1);
        List<Integer> eleIndeces = briEleGold.get(briIndex);
        briSent.setGoldSimilarities(new FSArray(briV, eleIndeces.size()));
        for (int i = 0, l = eleIndeces.size(); i < l; ++i) {
            Sentence eleSent = eleSents.get(eleIndeces.get(i) - 1);
            briSent.setGoldSimilarities(i, eleSent);
        }
    }
    eleV.setDocumentText(eleSb.toString());
    briV.setDocumentText(normalSb.toString());
    jcas.setDocumentText(FileUtils.readFileToString(ann));
    for (JCas j : new JCas[] { eleV, briV, jcas }) {
        Document document = new Document(j, 0, j.getDocumentText().length() - 1);
        document.setName(name);
        document.addToIndexes();
    }
    ++currentIndex;
}

From source file:net.sf.firemox.ui.component.CardPropertiesPanel.java

/**
 * Read and add from the given input stream the content of the given panel.
 * //from   ww w  .  jav a2  s  .co m
 * @param parent
 *          the panel were the read content would be added.
 * @param dbStream
 *          the source stream.
 * @throws Exception
 *           If some I/O or reflection error occurs.
 */
private void fillTaskPane(final JComponent parent, final InputStream dbStream)
        throws IOException, InstantiationException, IllegalAccessException, InvocationTargetException,
        NoSuchMethodException, ClassNotFoundException {
    final int count = dbStream.read();
    for (int i = 0; i < count; i++) {
        final int elementType = dbStream.read();
        switch (elementType) {
        case NESTED_ELEMENT:
            final JTaskPaneGroup nested = new JTaskPaneGroup();
            nested.setTitle(LanguageManagerMDB.getString(MToolKit.readString(dbStream)));
            fillTaskPane(nested, dbStream);
            parent.add(nested);
            break;
        case ATTRIBUTE:
            final Action action = (Action) Class
                    .forName(new StringBuilder(TaskAction.class.getPackage().getName()).append(".")
                            .append(StringUtils.capitalize(MToolKit.readString(dbStream))).append("Action")
                            .toString())
                    .getConstructor(new Class[] { InputStream.class }).newInstance(new Object[] { dbStream });
            ((JTaskPaneGroup) parent).add(action);
            break;
        default:
            throw new RuntimeException("unknown element type : " + elementType);
        }
    }

}

From source file:com.flexive.war.javascript.tree.StructureTreeEditor.java

/**
 * Creates a new group assignment from a given group assignment
 * with optionally a new alias which is also used as label if specified.
 *
 * @param orgAssignmentId source assignment
 * @param newAlias new alias (may be null)
 * @param xPath destination xpath// www .  j  av a 2  s.  c  o  m
 * @param type destination type
 * @return the created group assignment
 * @throws FxNotFoundException
 * @throws FxInvalidParameterException
 */
private FxGroupAssignmentEdit createReusedGroupAssignment(long orgAssignmentId, String newAlias, String xPath,
        FxType type) throws FxNotFoundException, FxInvalidParameterException {
    FxGroupAssignment assignment = (FxGroupAssignment) CacheAdmin.getEnvironment()
            .getAssignment(orgAssignmentId);
    FxGroupAssignmentEdit group;
    group = FxGroupAssignmentEdit.createNew(assignment, type,
            StringUtils.isBlank(newAlias) ? assignment.getAlias() : newAlias, xPath);
    if (!StringUtils.isBlank(newAlias))
        group.getLabel().setDefaultTranslation(StringUtils.capitalize(newAlias));
    return group;
}

From source file:edu.ku.brc.specify.toycode.mexconabio.FileMakerToMySQL.java

public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) {
    buffer.setLength(0);/*from  w ww  . ja v  a2  s .  c o  m*/

    if (localName.equals("FIELD")) {
        if (doColSizes) {
            FieldDef fldDef = new FieldDef();
            fields.add(fldDef);

            for (int i = 0; i < attrs.getLength(); i++) {
                String attr = attrs.getLocalName(i);
                String value = attrs.getValue(i);
                if (attr.equals("EMPTYOK")) {
                    fldDef.setNullable(value.equals("YES"));

                } else if (attr.equals("NAME")) {
                    value = StringUtils.capitalize(value.trim());
                    value = StringUtils.deleteWhitespace(value);
                    //value = StringUtils.replace(value, "", "n");
                    value = StringUtils.replace(value, ":", "");
                    value = StringUtils.replace(value, ";", "");
                    //value = StringUtils.replace(value, "", "a");
                    value = StringUtils.replace(value, ".", "");
                    //value = StringUtils.replace(value, "", "a");
                    //value = StringUtils.replace(value, "", "a");
                    value = StringUtils.replace(value, "/", "");

                    //System.out.println(value);

                    if ((value.charAt(0) >= '0' && value.charAt(0) <= '9') || value.equalsIgnoreCase("New")
                            || value.equalsIgnoreCase("Group")) {
                        value = "Fld" + value;
                    }

                    fldDef.setName(value);

                } else if (attr.equals("TYPE")) {
                    if (value.equals("TEXT")) {
                        fldDef.setType(DataType.eText);

                    } else if (value.equals("NUMBER")) {
                        fldDef.setType(DataType.eNumber);

                    } else if (value.equals("DATE")) {
                        fldDef.setType(DataType.eDate);

                    } else if (value.equals("TIME")) {
                        fldDef.setType(DataType.eTime);
                    } else {
                        System.err.println("Unknown Type[" + value + "]");
                    }
                }
                //System.out.println(attrs.getLocalName(i)+" = "+attrs.getValue(i));
            }
        }

    } else if (localName.equals("ROW")) {
        for (int i = 0; i < attrs.getLength(); i++) {
            String attr = attrs.getLocalName(i);
            String value = attrs.getValue(i);
            if (attr.equals("RECORDID")) {
                rowNum = Integer.parseInt(value);
                break;
            }
        }
    }
}

From source file:com.alibaba.jstorm.ui.model.pages.SupervisorPage.java

public TableData getWokerTable(SupervisorWorkers supervisorWorkers, Map<String, String> paramMap,
        Map<String, Object> nimbusConf) {
    TableData table = new TableData();
    List<String> headers = table.getHeaders();
    List<Map<String, ColumnData>> lines = table.getLines();
    table.setName(StringUtils.capitalize(UIDef.WOKER));

    headers.add(StringUtils.capitalize(UIDef.PORT));
    headers.add(UIDef.HEADER_UPTIME);// w ww  .j  a v  a2 s. c o m
    headers.add(StringUtils.capitalize(UIDef.TOPOLOGY));
    headers.add(UIDef.HEADER_TASK_LIST);
    headers.add(UIDef.HEADER_LOG);
    headers.add(StringUtils.capitalize(UIDef.JSTACK));

    List<WorkerSummary> workerSummaries = supervisorWorkers.get_workers();
    if (workerSummaries == null) {
        LOG.error("Failed to get workers of " + paramMap.get(UIDef.HOST));
        return table;
    }

    int logServerPort = ConfigExtension.getSupervisorDeamonHttpserverPort(nimbusConf);

    for (WorkerSummary workerSummary : workerSummaries) {
        Map<String, ColumnData> line = new HashMap<String, ColumnData>();
        lines.add(line);

        ColumnData portColumn = new ColumnData();
        portColumn.addText(String.valueOf(workerSummary.get_port()));
        line.put(StringUtils.capitalize(UIDef.PORT), portColumn);

        ColumnData uptimeColumn = new ColumnData();
        int uptime = workerSummary.get_uptime();
        uptimeColumn.addText(StatBuckets.prettyUptimeStr(uptime));
        line.put(UIDef.HEADER_UPTIME, uptimeColumn);

        ColumnData topologyColumn = new ColumnData();
        topologyColumn.addText(workerSummary.get_topology());
        line.put(StringUtils.capitalize(UIDef.TOPOLOGY), topologyColumn);

        ColumnData taskIdColumn = new ColumnData();
        line.put(UIDef.HEADER_TASK_LIST, taskIdColumn);
        for (TaskComponent taskComponent : workerSummary.get_tasks()) {
            LinkData linkData = new LinkData();
            taskIdColumn.addLinkData(linkData);
            linkData.setUrl(UIDef.LINK_WINDOW_TABLE);
            linkData.setText(taskComponent.get_component() + "-" + taskComponent.get_taskId());
            linkData.addParam(UIDef.CLUSTER, paramMap.get(UIDef.CLUSTER));
            linkData.addParam(UIDef.PAGE_TYPE, UIDef.PAGE_TYPE_COMPONENT);
            linkData.addParam(UIDef.TOPOLOGY, workerSummary.get_topology());
            linkData.addParam(UIDef.COMPONENT, taskComponent.get_component());
        }

        ColumnData logColumn = new ColumnData();
        LinkData logLink = new LinkData();
        logColumn.addLinkData(logLink);
        line.put(UIDef.HEADER_LOG, logColumn);

        logLink.setUrl(UIDef.LINK_LOG);
        logLink.setText(UIDef.HEADER_LOG.toLowerCase());
        logLink.addParam(UIDef.CLUSTER, paramMap.get(UIDef.CLUSTER));
        logLink.addParam(UIDef.PAGE_TYPE, UIDef.PAGE_TYPE_LOG);
        logLink.addParam(UIDef.HOST, NetWorkUtils.host2Ip(supervisorWorkers.get_supervisor().get_host()));
        logLink.addParam(UIDef.TOPOLOGY, workerSummary.get_topology());
        logLink.addParam(UIDef.PORT, String.valueOf(workerSummary.get_port()));
        logLink.addParam(UIDef.LOG_SERVER_PORT, String.valueOf(logServerPort));

        ColumnData jstackColumn = new ColumnData();
        LinkData jstackLink = new LinkData();
        jstackColumn.addLinkData(jstackLink);
        line.put(StringUtils.capitalize(UIDef.JSTACK), jstackColumn);

        jstackLink.setUrl(UIDef.LINK_TABLE_PAGE);
        jstackLink.setText(UIDef.JSTACK);
        jstackLink.addParam(UIDef.CLUSTER, paramMap.get(UIDef.CLUSTER));
        jstackLink.addParam(UIDef.PAGE_TYPE, UIDef.PAGE_TYPE_JSTACK);
        jstackLink.addParam(UIDef.HOST, supervisorWorkers.get_supervisor().get_host());
        jstackLink.addParam(UIDef.TOPOLOGY, workerSummary.get_topology());
        jstackLink.addParam(UIDef.PORT, String.valueOf(workerSummary.get_port()));
        jstackLink.addParam(UIDef.LOG_SERVER_PORT, String.valueOf(logServerPort));
    }
    return table;
}

From source file:info.magnolia.templating.elements.InitElement.java

@Override
public void begin(Appendable out) throws IOException, RenderException {
    if (!isAdmin()) {
        return;//from w w  w  .  jav a  2  s.  co  m
    }

    Node content = getPassedContent();
    if (content == null) {
        content = currentContent();
    }

    TemplateDefinition templateDefinition = getRequiredTemplateDefinition();

    dialog = resolveDialog(templateDefinition);

    Sources src = new Sources(MgnlContext.getContextPath());
    MarkupHelper helper = new MarkupHelper(out);
    helper.append("<!-- begin js and css added by @cms.init -->\n");
    helper.append("<meta name=\"gwt:property\" content=\"locale=" + i18nContentSupport.getLocale() + "\"/>\n");
    helper.append(src.getHtmlCss());
    helper.append(src.getHtmlJs());
    //TODO see SCRUM-1239, we will probably get rid of the init tag in 5.0
    //helper.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PAGE_EDITOR_CSS + "\"></link>\n");
    //helper.append("<script type=\"text/javascript\" src=\"" + PAGE_EDITOR_JS_SOURCE + "\"></script>\n");

    helper.openComment(CMS_PAGE_TAG);
    if (content != null) {
        helper.attribute(AreaDirective.CONTENT_ATTRIBUTE, getNodePath(content));
    }
    helper.attribute("dialog", dialog);
    helper.attribute("preview", String.valueOf(MgnlContext.getAggregationState().isPreviewMode()));

    //here we provide the page editor with the available locales and their respective URI for the current page
    if (i18nAuthoringSupport.isEnabled() && i18nContentSupport.isEnabled()
            && i18nContentSupport.getLocales().size() > 1) {

        Content currentPage = MgnlContext.getAggregationState().getMainContent();
        String currentUri = createURI(currentPage, i18nContentSupport.getLocale());
        helper.attribute("currentURI", currentUri);

        List<String> availableLocales = new ArrayList<String>();

        for (Locale locale : i18nContentSupport.getLocales()) {
            String uri = createURI(currentPage, locale);
            String label = StringUtils.capitalize(locale.getDisplayLanguage(locale));
            if (StringUtils.isNotEmpty(locale.getCountry())) {
                label += " (" + StringUtils.capitalize(locale.getDisplayCountry()) + ")";
            }
            availableLocales.add(label + ":" + uri);
        }

        helper.attribute("availableLocales", StringUtils.join(availableLocales, ","));
    }

    helper.append(" -->\n");
    helper.closeComment(CMS_PAGE_TAG);

}

From source file:ml.shifu.shifu.util.ClassUtils.java

public static Method getDeclaredGetter(String name, Class<?> clazz) throws NoSuchMethodException {
    return getDeclaredMethod("get" + StringUtils.capitalize(name), clazz);
}