Example usage for com.google.common.base CaseFormat UPPER_CAMEL

List of usage examples for com.google.common.base CaseFormat UPPER_CAMEL

Introduction

In this page you can find the example usage for com.google.common.base CaseFormat UPPER_CAMEL.

Prototype

CaseFormat UPPER_CAMEL

To view the source code for com.google.common.base CaseFormat UPPER_CAMEL.

Click Source Link

Document

Java and C++ class naming convention, e.g., "UpperCamel".

Usage

From source file:org.abstractmeta.reflectify.plugin.ReflectifyGenerator.java

private void generateProviders(JavaTypeBuilder typeBuilder, JavaType sourceType, Type reflectifyType) {
    Map<String, Integer> providerCounter = new HashMap<String, Integer>();
    JavaMethodBuilder methodBuilder = new JavaMethodBuilder();
    methodBuilder.addModifier("protected").setName("registerProviders").setResultType(void.class);
    methodBuilder.addParameter("providers", new ParameterizedTypeImpl(null, List.class,
            new ParameterizedTypeImpl(null, Reflectify.Provider.class, reflectifyType)));
    methodBuilder.addBody("\n");
    if (sourceType.getConstructors() == null) {
        return;//  w w w  . j  a  v  a  2s  .  co  m
    }
    if (sourceType.getModifiers().contains("abstract")) {
        return;
    }
    for (JavaConstructor constructor : sourceType.getConstructors()) {
        String sourceTypeSimpleName = JavaTypeUtil.getSimpleClassName(sourceType.getName(), true);

        String constructorCounterPostfix = getOccurrence(providerCounter,
                JavaTypeUtil.getSimpleClassName(sourceType.getName(), false));
        String providerClassName = StringUtil.format(CaseFormat.UPPER_CAMEL,
                JavaTypeUtil.getSimpleClassName(sourceType.getName(), false),
                "provider" + constructorCounterPostfix, CaseFormat.LOWER_CAMEL);
        JavaTypeBuilder providerClassBuilder = methodBuilder.addNestedJavaType();
        providerClassBuilder.setName(providerClassName)
                .addSuperInterface(new ParameterizedTypeImpl(null, Reflectify.Provider.class, reflectifyType));
        String parameters = Joiner.on(", ").join(getArgumentClasses(constructor.getParameterTypes()));
        if (!parameters.isEmpty())
            parameters = ", " + parameters;
        providerClassBuilder.addConstructor(new JavaConstructorBuilder().setName(providerClassName)
                .addBody(String.format("super(%s.class%s);", sourceTypeSimpleName, parameters)).build());
        providerClassBuilder.setSuperType(AbstractProvider.class);
        buildArgumentSetterClasses(providerClassBuilder, reflectifyType, sourceTypeSimpleName,
                constructor.getParameterTypes());
        methodBuilder.addBody(String.format(String.format("providers.add(new %s());", providerClassName)));
        JavaMethodBuilder getMethodProvider = new JavaMethodBuilder().addModifier("public").setName("get")
                .setResultType(reflectifyType);
        String constructorParameters = Joiner.on(", ")
                .join(getArgumentSetterMethodArgumentNames(constructor.getParameterTypes()));
        boolean exceptionHandling = constructor.getExceptionTypes() != null
                && !constructor.getExceptionTypes().isEmpty();

        if (exceptionHandling) {
            getMethodProvider.addBody("try {");
        }
        getMethodProvider.addBody((exceptionHandling ? "    " : "")
                + String.format("return new %s(%s);", sourceTypeSimpleName, constructorParameters));
        if (exceptionHandling) {
            getMethodProvider.addBody("} catch(Exception e) {");
            getMethodProvider.addBody(String.format(
                    "    throw new RuntimeException(\"Failed to instantiate %s\", e);", sourceTypeSimpleName));
            getMethodProvider.addBody("}");
        }

        providerClassBuilder.addMethod(getMethodProvider.build());
    }
    typeBuilder.addMethod(methodBuilder.build());
}

From source file:com.google.api.codegen.util.Name.java

/** Returns the identifier in upper-camel format. */
public String toUpperCamel() {
    return toCamel(CaseFormat.UPPER_CAMEL);
}

From source file:com.opengamma.basics.schedule.StubConvention.java

/**
 * Obtains the type from a unique name./*from   w  w w .j  a  v a 2s  .c om*/
 * 
 * @param uniqueName  the unique name
 * @return the type
 * @throws IllegalArgumentException if the name is not known
 */
@FromString
public static StubConvention of(String uniqueName) {
    ArgChecker.notNull(uniqueName, "uniqueName");
    return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, uniqueName));
}

From source file:com.geemvc.taglib.GeemvcTagSupport.java

protected String toElementId(String name, String idSuffix) {
    StringBuilder id = new StringBuilder(ELEMENT_ID_PREFIX).append(CaseFormat.UPPER_CAMEL
            .to(CaseFormat.LOWER_HYPHEN, name).replace(Char.SQUARE_BRACKET_OPEN, Char.HYPHEN)
            .replace(Char.SQUARE_BRACKET_CLOSE, Char.HYPHEN).replace(Char.DOT, Char.HYPHEN)
            .replace(Char.SPACE, Char.HYPHEN).replace(Char.UNDERSCORE, Char.HYPHEN)
            .replace(Str.HYPHEN_2x, Str.HYPHEN));

    if (id.charAt(id.length() - 1) == Char.HYPHEN)
        id.deleteCharAt(id.length() - 1);

    if (!Str.isEmpty(idSuffix)) {
        id.append(Char.HYPHEN)/* w  w  w . ja va2s.c  o  m*/
                .append(idSuffix.toLowerCase().replace(Char.SQUARE_BRACKET_OPEN, Char.HYPHEN)
                        .replace(Char.SQUARE_BRACKET_CLOSE, Char.HYPHEN).replace(Char.DOT, Char.HYPHEN)
                        .replace(Char.SPACE, Char.HYPHEN).replace(Char.UNDERSCORE, Char.HYPHEN)
                        .replace(Str.HYPHEN_2x, Str.HYPHEN));
    }

    if (id.charAt(id.length() - 1) == Char.HYPHEN)
        id.deleteCharAt(id.length() - 1);

    return id.toString();
}

From source file:ninja.template.TemplateEngineFreemarker.java

@Override
public void invoke(Context context, Result result) {

    Object object = result.getRenderable();

    Map map;/* w  w  w.  j a v a  2 s. co  m*/
    // if the object is null we simply render an empty map...
    if (object == null) {
        map = Maps.newHashMap();

    } else if (object instanceof Map) {
        map = (Map) object;

    } else {
        // We are getting an arbitrary Object and put that into
        // the root of freemarker

        // If you are rendering something like Results.ok().render(new MyObject())
        // Assume MyObject has a public String name field.            
        // You can then access the fields in the template like that:
        // ${myObject.publicField}            

        String realClassNameLowerCamelCase = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL,
                object.getClass().getSimpleName());

        map = Maps.newHashMap();
        map.put(realClassNameLowerCamelCase, object);

    }

    // set language from framework. You can access
    // it in the templates as ${lang}
    Optional<String> language = lang.getLanguage(context, Optional.of(result));
    if (language.isPresent()) {
        map.put("lang", language.get());
    }

    // put all entries of the session cookie to the map.
    // You can access the values by their key in the cookie
    if (!context.getSession().isEmpty()) {
        map.put("session", context.getSession().getData());
    }

    map.put("contextPath", context.getContextPath());

    //////////////////////////////////////////////////////////////////////
    // A method that renders i18n messages and can also render messages with 
    // placeholders directly in your template:
    // E.g.: ${i18n("mykey", myPlaceholderVariable)}
    //////////////////////////////////////////////////////////////////////
    map.put("i18n", new TemplateEngineFreemarkerI18nMethod(messages, context, result));

    Optional<String> requestLang = lang.getLanguage(context, Optional.of(result));
    Locale locale = lang.getLocaleFromStringOrDefault(requestLang);
    map.put("prettyTime", new TemplateEngineFreemarkerPrettyTimeMethod(locale));

    map.put("reverseRoute", templateEngineFreemarkerReverseRouteMethod);
    map.put("assetsAt", templateEngineFreemarkerAssetsAtMethod);
    map.put("webJarsAt", templateEngineFreemarkerWebJarsAtMethod);

    map.put("authenticityToken", new TemplateEngineFreemarkerAuthenticityTokenDirective(context));
    map.put("authenticityForm", new TemplateEngineFreemarkerAuthenticityFormDirective(context));

    ///////////////////////////////////////////////////////////////////////
    // Convenience method to translate possible flash scope keys.
    // !!! If you want to set messages with placeholders please do that
    // !!! in your controller. We only can set simple messages.
    // Eg. A message like "errorMessage=my name is: {0}" => translate in controller and pass directly.
    //     A message like " errorMessage=An error occurred" => use that as errorMessage.  
    //
    // get keys via ${flash.KEYNAME}
    //////////////////////////////////////////////////////////////////////
    Map<String, String> translatedFlashCookieMap = Maps.newHashMap();
    for (Entry<String, String> entry : context.getFlashScope().getCurrentFlashCookieData().entrySet()) {

        String messageValue = null;

        Optional<String> messageValueOptional = messages.get(entry.getValue(), context, Optional.of(result));

        if (!messageValueOptional.isPresent()) {
            messageValue = entry.getValue();
        } else {
            messageValue = messageValueOptional.get();
        }
        // new way
        translatedFlashCookieMap.put(entry.getKey(), messageValue);
    }

    // now we can retrieve flash cookie messages via ${flash.MESSAGE_KEY}
    map.put("flash", translatedFlashCookieMap);

    // Specify the data source where the template files come from.
    // Here I set a file directory for it:
    String templateName = templateEngineHelper.getTemplateForResult(context.getRoute(), result,
            this.fileSuffix);

    Template freemarkerTemplate = null;

    try {

        freemarkerTemplate = cfg.getTemplate(templateName);

        // Fully buffer the response so in the case of a template error we can 
        // return the applications 500 error message. Without fully buffering 
        // we can't guarantee we haven't flushed part of the response to the
        // client.
        StringWriter buffer = new StringWriter(64 * 1024);
        freemarkerTemplate.process(map, buffer);

        ResponseStreams responseStreams = context.finalizeHeaders(result);
        try (Writer writer = responseStreams.getWriter()) {
            writer.write(buffer.toString());
        }
    } catch (Exception cause) {

        // delegate rendering exception handling back to Ninja
        throwRenderingException(context, result, cause, templateName);

    }
}

From source file:com.google.api.codegen.util.Name.java

private String toCamel(CaseFormat caseFormat) {
    StringBuffer buffer = new StringBuffer();
    boolean firstPiece = true;
    for (NamePiece namePiece : namePieces) {
        if (firstPiece && caseFormat.equals(CaseFormat.LOWER_CAMEL)) {
            buffer.append(namePiece.caseFormat.to(CaseFormat.LOWER_CAMEL, namePiece.identifier));
        } else {//from  w w w  . j a  v a  2  s. c  om
            CaseFormat toCaseFormat = CaseFormat.UPPER_CAMEL;
            if (namePiece.casingMode.equals(CasingMode.UPPER_CAMEL_TO_SQUASHED_UPPERCASE)) {
                toCaseFormat = CaseFormat.UPPER_UNDERSCORE;
            }
            buffer.append(namePiece.caseFormat.to(toCaseFormat, namePiece.identifier));
        }
        firstPiece = false;
    }
    return buffer.toString();
}

From source file:eu.supersede.dynadapt.aom.dsl.resources.constants.AbstractUMLPackageConstant.java

protected static String toConstantName(String name) {
    return CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, name).replaceAll("__", "_");
}

From source file:com.google.javascript.jscomp.PolymerPassStaticUtils.java

/**
 * @return The PolymerElement type string for a class definition.
 *//* w w  w  .  j  av a 2  s. com*/
public static String getPolymerElementType(final PolymerClassDefinition cls) {
    String nativeElementName = cls.nativeBaseElement == null ? ""
            : CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, cls.nativeBaseElement);
    return SimpleFormat.format("Polymer%sElement", nativeElementName);
}

From source file:org.gaul.s3proxy.S3ErrorCode.java

private S3ErrorCode(int httpStatusCode, String message) {
    this.errorCode = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());
    this.httpStatusCode = httpStatusCode;
    this.message = requireNonNull(message);
}

From source file:org.rakam.client.builder.document.SlateDocumentGenerator.java

private MarkdownBuilder generateApiTags(MarkdownBuilder markdownBuilder) {
    if (!swagger.getTags().isEmpty()) {
        Map<String, Tag> tags = swagger.getTags().stream()
                .collect(Collectors.toMap(t -> t.getName().toLowerCase(), Function.identity()));
        Set<String> nonOrderedTags = new HashSet<>(tags.keySet());
        nonOrderedTags.removeAll(tagsOrder);
        Stream.concat(tagsOrder.stream(), nonOrderedTags.stream()).forEachOrdered(tagName -> {
            Tag tag = tags.get(tagName.toLowerCase());
            if (tag == null) {
                LOGGER.warn("tag not found:" + tagName);
            } else {
                String name = tag.getName();
                String description = tag.getDescription();
                markdownBuilder.documentTitle(
                        CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name.replaceAll("-", " ")))
                        .newLine().textLine(description).newLine();
                processOperation(markdownBuilder, name);
            }/* ww w. ja v  a  2s. c o m*/
        });
        markdownBuilder.newLine();
    }
    return markdownBuilder;
}