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.femtoparsec.jnlmin.linesearch.AbstractLineSearch.java

private void setProperty(Map<String, Map<Class<?>, Method>> unaryMethods, String propertyName, Object value) {
    try {/*from  w  w w  .ja v  a  2 s.  c  om*/
        final String setterName = String.format("set%s", StringUtils.capitalize(propertyName));
        Method setter = this.findClosestMethod(unaryMethods, setterName, value.getClass());
        setter.invoke(this, value);
    } catch (NoSuchMethodException e) {
        throw new UnknownLineSearchPropertyException(this.getName(), propertyName, value);
    } catch (Exception e) {
        throw new InvalidLineSearchPropertyValueException(this.getName(), propertyName, value);
    }
}

From source file:com.iorga.webappwatcher.analyzer.ws.statistics.DailyStatisticsWS.java

@GET
@Path("/compute")
public StreamingOutput compute() throws ClassNotFoundException, IOException {
    final List<DayStatistic> computeDayStatistics = durationPerPrincipalStats.computeDayStatistics();
    return new StreamingOutput() {
        @Override/*from  ww  w  .j  a  va  2 s.  c om*/
        public void write(final OutputStream output) throws IOException, WebApplicationException {
            final JsonGenerator generator = OBJECT_MAPPER.getJsonFactory().createJsonGenerator(output,
                    JsonEncoding.UTF8);
            generator.writeStartArray();
            for (final DayStatistic dayStatistic : computeDayStatistics) {
                generator.writeStartObject();
                generator.writeFieldName("startDate");
                OBJECT_MAPPER.writeValue(generator, dayStatistic.getStartDate());
                generator.writeFieldName("endDate");
                OBJECT_MAPPER.writeValue(generator, dayStatistic.getEndDate());
                generator.writeArrayFieldStart("statistics");
                // write each statistic
                for (final String statisticType : new String[] { "distinctUsers", "numberOfRequests",
                        "durationsFor1clickSum", "durationsFor1clickMean", "durationsFor1clickMedian",
                        "durationsFor1click90c", "durationsFor1clickMin", "durationsFor1clickMax" }) {
                    //                  generator.writeFieldName(statisticType);
                    generator.writeStartObject();
                    generator.writeStringField("type", statisticType);
                    // get the statistics from the dayStatistic
                    DescriptiveStatistics descriptiveStatistics;
                    try {
                        descriptiveStatistics = (DescriptiveStatistics) dayStatistic.getClass()
                                .getMethod("get" + StringUtils.capitalize(statisticType)).invoke(dayStatistic);
                    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                            | NoSuchMethodException | SecurityException e) {
                        throw new IOException(
                                "Problem while invoking getter for statisticType " + statisticType, e);
                    }
                    generator.writeNumberField("min", descriptiveStatistics.getMin());
                    generator.writeNumberField("max", descriptiveStatistics.getMax());
                    generator.writeNumberField("mean", descriptiveStatistics.getMean());
                    generator.writeNumberField("median", descriptiveStatistics.getPercentile(50));
                    generator.writeEndObject();
                }
                generator.writeEndArray();
                generator.writeFieldName("distinctPrincipalsSize");
                OBJECT_MAPPER.writeValue(generator, dayStatistic.getPrincipals().size());
                generator.writeEndObject();
            }
            generator.writeEndArray();

            generator.flush(); // required else all the stream is not sent
        }
    };
}

From source file:com.mebigfatguy.junitflood.generator.simple.SimpleGenerator.java

private void generateUnitTest(ClassNode classNode) throws IOException {
    String className = classNode.name;
    int lastSlashPos = className.lastIndexOf('/');
    String packageName = (lastSlashPos >= 0) ? className.substring(0, lastSlashPos) : "";
    className = (lastSlashPos > 0) ? className.substring(lastSlashPos + 1) : className;

    File f = new File(configuration.getOutputDirectory(), packageName);
    f.mkdirs();//from w ww.  ja v  a  2s. c  om

    f = new File(f, className + "Test.java");
    if (!f.exists()) {
        try (PrintWriter pw = new PrintWriter(
                new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8")))) {

            pw.println("package " + packageName.replaceAll("/", ".") + ";");
            pw.println();
            pw.println("public class " + className + "Test {");

            for (MethodNode node : (List<MethodNode>) classNode.methods) {

                if (isTestable(node)) {
                    pw.println("\t@Test");
                    pw.println("\tpublic void test" + StringUtils.capitalize(node.name) + "{} {");
                    pw.println("\t}");
                }
            }

            pw.println("}");
        } catch (UnsupportedEncodingException e) {
        }
    }
}

From source file:it.larusba.integration.neo4j.jsonloader.transformer.AttributeBasedJsonTransformer.java

/**
 * It recursively parses a <code>Map</code> representation of the JSON
 * document./*w w  w  .java  2  s . c o m*/
 * 
 * @param documentId
 * @param documentType
 * @param documentMap
 * @return
 */
@SuppressWarnings("unchecked")
public String transform(String documentId, String documentType, Map<String, Object> documentMap) {

    StringBuffer rootNode = new StringBuffer();
    List<String> childNodes = new ArrayList<String>();
    List<String> childRelationships = new ArrayList<String>();

    String nodeReference = (documentType != null) ? StringUtils.lowerCase(documentType) : "document";
    String nodeLabel = StringUtils.capitalize(nodeReference);

    rootNode.append("CREATE (").append(nodeReference).append(":").append(nodeLabel);

    boolean firstAttr = true;

    for (String attributeName : documentMap.keySet()) {

        Object attributeValue = documentMap.get(attributeName);

        if (attributeValue instanceof Map) {

            childNodes.add(transform(documentId, attributeName, (Map<String, Object>) attributeValue));

            childRelationships
                    .add(new StringBuffer().append("CREATE (").append(nodeReference).append(")-[").append(":")
                            .append(nodeReference.toUpperCase()).append("_").append(attributeName.toUpperCase())
                            .append("]->(").append(attributeName).append(")").toString());
        } else {

            if (firstAttr) {
                rootNode.append(" { ");

                if (documentId != null) {
                    rootNode.append("_documentId: '").append(documentId).append("', ");
                }

                firstAttr = false;
            } else {
                rootNode.append(", ");
            }

            if (attributeValue != null) {
                rootNode.append(attributeName).append(": ");

                if (attributeValue instanceof String) {
                    rootNode.append("'").append(attributeValue).append("'");
                } else {
                    rootNode.append(attributeValue);
                }
            }
        }
    }

    rootNode.append(" })");

    StringBuffer cypher = new StringBuffer();

    cypher.append(rootNode);

    for (String childNode : childNodes) {

        cypher.append("\n").append(childNode);
    }

    for (String childRelationship : childRelationships) {

        cypher.append("\n").append(childRelationship);
    }

    return cypher.toString();
}

From source file:ch.cyberduck.ui.cocoa.ProgressController.java

/**
 * Resets both the progress and status field
 *//*  w  ww .  ja  va  2s  .  c  om*/
@Override
public void awakeFromNib() {
    this.progress(MessageFormat.format(LocaleFactory.localizedString("{0} of {1}"),
            sizeFormatter.format(transfer.getTransferred()), sizeFormatter.format(transfer.getSize())));
    this.message(StringUtils.EMPTY);
    this.status(LocaleFactory.localizedString(transfer.isComplete()
            ? String.format("%s complete", StringUtils.capitalize(transfer.getType().name()))
            : "Transfer incomplete", "Status"));
    super.awakeFromNib();
}

From source file:ca.uhn.fhir.context.RuntimeChildChoiceDefinition.java

@SuppressWarnings("unchecked")
@Override/*from w w w. jav a2 s.  co m*/
void sealAndInitialize(FhirContext theContext,
        Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
    myNameToChildDefinition = new HashMap<String, BaseRuntimeElementDefinition<?>>();
    myDatatypeToElementName = new HashMap<Class<? extends IBase>, String>();
    myDatatypeToElementDefinition = new HashMap<Class<? extends IBase>, BaseRuntimeElementDefinition<?>>();
    myResourceTypes = new ArrayList<Class<? extends IBaseResource>>();

    if (theContext.getVersion().getVersion().equals(FhirVersionEnum.DSTU1)) {
        myReferenceSuffix = "Resource";
    } else {
        myReferenceSuffix = "Reference";
    }

    for (Class<? extends IBase> next : myChoiceTypes) {

        String elementName = null;
        BaseRuntimeElementDefinition<?> nextDef;
        boolean nonPreferred = false;
        if (IBaseResource.class.isAssignableFrom(next)) {
            elementName = getElementName() + StringUtils.capitalize(next.getSimpleName());
            List<Class<? extends IBaseResource>> types = new ArrayList<Class<? extends IBaseResource>>();
            types.add((Class<? extends IBaseResource>) next);
            nextDef = findResourceReferenceDefinition(theClassToElementDefinitions);

            myNameToChildDefinition.put(getElementName() + "Reference", nextDef);
            myNameToChildDefinition.put(getElementName() + "Resource", nextDef);

            myResourceTypes.add((Class<? extends IBaseResource>) next);

        } else {
            nextDef = theClassToElementDefinitions.get(next);
            BaseRuntimeElementDefinition<?> nextDefForChoice = nextDef;

            /*
             * In HAPI 1.3 the following applied:
             * Elements which are called foo[x] and have a choice which is a profiled datatype must use the
             * unprofiled datatype as the element name. E.g. if foo[x] allows markdown as a datatype, it calls the
             * element fooString when encoded, because markdown is a profile of string. This is according to the
             * FHIR spec
             * 
             * Note that as of HAPI 1.4 this applies only to non-primitive datatypes after discussion
             * with Grahame.
             */
            if (nextDef instanceof IRuntimeDatatypeDefinition) {
                IRuntimeDatatypeDefinition nextDefDatatype = (IRuntimeDatatypeDefinition) nextDef;
                if (nextDefDatatype.getProfileOf() != null && !IPrimitiveType.class.isAssignableFrom(next)) {
                    nextDefForChoice = null;
                    nonPreferred = true;
                    Class<? extends IBaseDatatype> profileType = nextDefDatatype.getProfileOf();
                    BaseRuntimeElementDefinition<?> elementDef = theClassToElementDefinitions.get(profileType);
                    elementName = getElementName() + StringUtils.capitalize(elementDef.getName());
                }
            }
            if (nextDefForChoice != null) {
                elementName = getElementName() + StringUtils.capitalize(nextDefForChoice.getName());
            }
        }

        // I don't see how elementName could be null here, but eclipse complains..
        if (elementName != null) {
            if (myNameToChildDefinition.containsKey(elementName) == false || !nonPreferred) {
                myNameToChildDefinition.put(elementName, nextDef);
            }
        }

        /*
         * If this is a resource reference, the element name is "fooNameReference"
         */
        if (IBaseResource.class.isAssignableFrom(next) || IBaseReference.class.isAssignableFrom(next)) {
            next = theContext.getVersion().getResourceReferenceType();
            elementName = getElementName() + myReferenceSuffix;
        }

        myDatatypeToElementDefinition.put(next, nextDef);

        if (myDatatypeToElementName.containsKey(next)) {
            String existing = myDatatypeToElementName.get(next);
            if (!existing.equals(elementName)) {
                throw new ConfigurationException("Already have element name " + existing + " for datatype "
                        + next.getSimpleName() + " in " + getElementName() + ", cannot add " + elementName);
            }
        } else {
            myDatatypeToElementName.put(next, elementName);
        }
    }

    myNameToChildDefinition = Collections.unmodifiableMap(myNameToChildDefinition);
    myDatatypeToElementName = Collections.unmodifiableMap(myDatatypeToElementName);
    myDatatypeToElementDefinition = Collections.unmodifiableMap(myDatatypeToElementDefinition);
    myResourceTypes = Collections.unmodifiableList(myResourceTypes);
}

From source file:com.thoughtworks.go.config.exceptions.EntityType.java

public String notFoundMessage(List<?> ids) {
    return format("%ss %ss '%s' were not found!", StringUtils.capitalize(this.entityType),
            this.nameOrId.descriptor, StringUtils.join(ids, ","));
}

From source file:com.quartercode.femtoweb.impl.ActionUriResolver.java

/**
 * Returns the {@link Action} which is mapped to the given URI and located in the given package or a subpackage.
 * See {@link Context#getAction(String)} for more information.
 *
 * @param actionBasePackage The name of the package the action class must be located in somehow (subpackages are allowed).
 *        For example, the URI {@code /some/test} and the package {@code com.quartercode.femtowebtest.actions} would result in the
 *        class name {@code com.quartercode.femtowebtest.actions.some.TestAction}.
 * @param uri The URI whose mapped action class should be returned.
 * @return The action class which is mapped to the given URI.
 * @throws ActionNotFoundException If no action class is mapped to the given URI.
 */// ww w  .  ja  v  a2s .c  o  m
@SuppressWarnings("unchecked")
public static Class<? extends Action> getAction(String actionBasePackage, String uri)
        throws ActionNotFoundException {

    // Remove any "/" from the start and the end of the URI
    String trimmedUri = StringUtils.strip(uri, "/");

    // Replace all "/" with ".", add the action base package to the front, capitalize the last URI part, append "Action" to the last URI part
    // Example: "/path/to/someTest" -> "path.to.SomeTest")
    String[] uriComponents = splitAtLastSeparator(trimmedUri, "/");
    String actionFQCNPackage = uriComponents[0].replace('/', '.');
    String actionFQCNName = StringUtils.capitalize(uriComponents[1]) + "Action";
    String actionFQCN = joinNonBlankItems(".", actionBasePackage, actionFQCNPackage, actionFQCNName);

    try {
        Class<?> c = Class.forName(actionFQCN);

        if (!Action.class.isAssignableFrom(c) || c.isAnnotationPresent(IgnoreAction.class)) {
            throw new ActionNotFoundException(uri, actionFQCN);
        } else {
            return (Class<? extends Action>) c;
        }
    } catch (ClassNotFoundException e) {
        throw new ActionNotFoundException(e, uri, actionFQCN);
    }
}

From source file:io.github.swagger2markup.markup.builder.internal.markdown.MarkdownBuilder.java

@Override
public MarkupDocBuilder block(String text, final MarkupBlockStyle style, String title,
        MarkupAdmonition admonition) {/*from  w  ww . jav a  2 s . co  m*/
    if (admonition != null)
        documentBuilder.append(StringUtils.capitalize(admonition.name().toLowerCase()));
    if (title != null) {
        if (admonition != null)
            documentBuilder.append(" | ");
        documentBuilder.append(title);
    }
    if (admonition != null || title != null)
        documentBuilder.append(" : ").append(newLine);

    delimitedBlockText(new Markup() {
        public String toString() {
            return BLOCK_STYLE.get(style);
        }
    }, text);
    return this;
}

From source file:apm.generate.Generate.java

public static void parameters(String packageName, String moduleName, String className, String classAuthor,
        String functionName, String tableName, String entityContent, String flag) throws Exception {
    // ==========  ?? ====================
    // ??????/*from  ww w .  j  av a2 s .  co m*/
    // ?{packageName}/{moduleName}/{dao,entity,service,web}/{subModuleName}/{className}
    // packageName ????applicationContext.xmlsrping-mvc.xml?base-package?packagesToScan?4?

    //String packageName = "lms.modules";//???

    //String moduleName = "test";         //???sys
    String subModuleName = ""; // ?????? 
    //String className = "test";         // ??user
    //String classAuthor = "htd";         // ThinkGem
    //String functionName = "";         //??

    // ???
    Boolean isEnable = true;

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

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

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

    // ?
    String separator = File.separator;

    // ?
    File projectPath = new DefaultResourceLoader().getResource("").getFile();
    while (!new File(projectPath.getPath() + separator + "src" + separator + "main").exists()) {
        projectPath = projectPath.getParentFile();
    }
    //logger.info("Project Path: {}", projectPath);
    System.out.println("-------------------------------------------------");
    System.out.println(":" + projectPath);
    // ?
    String tplPath = StringUtils.replace(projectPath + "/src/main/java/apm/generate/template", "/", separator);
    //logger.info("Template Path: {}", tplPath);
    System.out.println("?:" + tplPath);
    // Java
    String javaPath = StringUtils.replaceEach(
            projectPath + "/src/main/java/" + StringUtils.lowerCase(packageName), new String[] { "/", "." },
            new String[] { separator, separator });
    //logger.info("Java Path: {}", javaPath);
    System.out.println("Java:" + javaPath);
    // 
    String viewPath = StringUtils.replace(projectPath + "/src/main/webapp/WEB-INF/views", "/", separator);
    //logger.info("View Path: {}", viewPath);
    System.out.println(":" + viewPath);
    // ???
    Configuration cfg = new Configuration();
    cfg.setDirectoryForTemplateLoading(new File(tplPath));

    // ???
    Map<String, String> model = Maps.newHashMap();
    model.put("packageName", StringUtils.lowerCase(packageName));
    model.put("moduleName", 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", tableName);

    model.put("urlPrefix", "/" + model.get("className"));
    model.put("viewUrlPrefix", "/" + model.get("moduleName"));
    model.put("returnPrefix", "modules" + //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+
            model.get("viewUrlPrefix") + "/" + model.get("className"));
    model.put("viewPrefix", //StringUtils.substringAfterLast(model.get("packageName"),".")+"/"+
            model.get("urlPrefix"));

    model.put("permissionPrefix", model.get("className"));
    String[] strs = entityContent.split("##");
    model.put("columnContent", strs[0]);
    model.put("entityContent", strs[1]);

    System.out.println("-------------------------?------------------------");
    Template template = null;
    String content = null;
    String filePath = null;
    if (flag.indexOf("entity") != -1 || flag.length() == 0) {
        // ? Entity
        template = cfg.getTemplate("entity.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "entity" + separator
                + StringUtils.lowerCase(subModuleName) + model.get("ClassName") + ".java";
        writeFile(content, filePath);
        System.out.println("? Entity:" + filePath);
    }

    if (flag.indexOf("dao") != -1 || flag.length() == 0) {

        // ? Dao
        template = cfg.getTemplate("dao.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "dao" + separator
                + StringUtils.lowerCase(subModuleName) + model.get("ClassName") + "Dao.java";
        writeFile(content, filePath);
        System.out.println("? Dao:" + filePath);

    }

    if (flag.indexOf("service") != -1 || flag.length() == 0) {

        // ? Service
        template = cfg.getTemplate("service.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "service" + separator
                + StringUtils.lowerCase(subModuleName) + model.get("ClassName") + "Service.java";
        writeFile(content, filePath);
        System.out.println("? Service:" + filePath);

    }

    if (flag.indexOf("controler") != -1 || flag.length() == 0) {

        // ? Controller
        template = cfg.getTemplate("controller.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = javaPath + separator + model.get("moduleName") + separator + "web" + separator
                + StringUtils.lowerCase(subModuleName) + model.get("ClassName") + "Controller.java";
        writeFile(content, filePath);
        System.out.println("? Controller:" + filePath);

    }

    if (flag.indexOf("form") != -1 || flag.length() == 0) {

        // ? ViewForm
        template = cfg.getTemplate("viewForm.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".")
                + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName)
                + model.get("className") + "Form.jsp";
        writeFile(content, filePath);
        System.out.println("? ViewForm:" + filePath);

    }

    if (flag.indexOf("list") != -1 || flag.length() == 0) {

        // ? ViewList
        template = cfg.getTemplate("viewList.ftl");
        content = FreeMarkers.renderTemplate(template, model);
        filePath = viewPath + separator + StringUtils.substringAfterLast(model.get("packageName"), ".")
                + separator + model.get("moduleName") + separator + StringUtils.lowerCase(subModuleName)
                + model.get("className") + "List.jsp";
        writeFile(content, filePath);
        System.out.println("? ViewList:" + filePath);

    }

}