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:brooklyn.util.flags.TypeCoercions.java

/**
 * Type coercion {@link Function function} for {@link Enum enums}.
 * <p>//  w  ww  .  j a v a  2s.com
 * Tries to convert the string to {@link CaseFormat#UPPER_UNDERSCORE} first,
 * handling all of the different {@link CaseFormat format} possibilites. Failing 
 * that, it tries a case-insensitive comparison with the valid enum values.
 * <p>
 * Returns {@code defaultValue} if the string cannot be converted.
 *
 * @see TypeCoercions#coerce(Object, Class)
 * @see Enum#valueOf(Class, String)
 */
public static <E extends Enum<E>> Function<String, E> stringToEnum(final Class<E> type,
        @Nullable final E defaultValue) {
    return new Function<String, E>() {
        @Override
        public E apply(String input) {
            Preconditions.checkNotNull(input, "input");
            List<String> options = ImmutableList.of(input,
                    CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, input),
                    CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, input),
                    CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, input),
                    CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, input));
            for (String value : options) {
                try {
                    return Enum.valueOf(type, value);
                } catch (IllegalArgumentException iae) {
                    continue;
                }
            }
            Maybe<E> result = Enums.valueOfIgnoreCase(type, input);
            return (result.isPresent()) ? result.get() : defaultValue;
        }
    };
}

From source file:org.solenopsis.checkstyle.JavadocDetailNodeParser.java

/**
 * Gets token type of ParseTree node from JavadocTokenTypes class.
 * @param node ParseTree node./*from w  ww  .  j  a v  a 2s .  c  o m*/
 * @return token type from JavadocTokenTypes
 */
private static int getTokenType(ParseTree node) {
    final int tokenType;

    if (node.getChildCount() == 0) {
        tokenType = ((TerminalNode) node).getSymbol().getType();
    } else {
        final String className = getNodeClassNameWithoutContext(node);
        final String typeName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, className);
        tokenType = JavadocUtils.getTokenId(typeName);
    }

    return tokenType;
}

From source file:org.ballerinalang.langserver.compiler.format.TextDocumentFormatUtil.java

/**
 * Generate json representation for the given node.
 *
 * @param node              Node to get the json representation
 * @param anonStructs       Map of anonymous structs
 * @param symbolMetaInfoMap symbol meta information map
 * @return {@link JsonElement}          Json Representation of the node
 * @throws JSONGenerationException when Json error occurs
 *///w w w .  java 2 s  . com
public static JsonElement generateJSON(Node node, Map<String, Node> anonStructs,
        Map<BLangNode, List<SymbolMetaInfo>> symbolMetaInfoMap) throws JSONGenerationException {
    if (node == null) {
        return JsonNull.INSTANCE;
    }
    Set<Method> methods = ClassUtils.getAllInterfaces(node.getClass()).stream()
            .flatMap(aClass -> Arrays.stream(aClass.getMethods())).collect(Collectors.toSet());
    JsonObject nodeJson = new JsonObject();

    JsonArray wsJsonArray = new JsonArray();
    Set<Whitespace> ws = node.getWS();
    if (ws != null && !ws.isEmpty()) {
        for (Whitespace whitespace : ws) {
            JsonObject wsJson = new JsonObject();
            wsJson.addProperty("ws", whitespace.getWs());
            wsJson.addProperty("i", whitespace.getIndex());
            wsJson.addProperty("text", whitespace.getPrevious());
            wsJson.addProperty("static", whitespace.isStatic());
            wsJsonArray.add(wsJson);
        }
        nodeJson.add("ws", wsJsonArray);
    }
    Diagnostic.DiagnosticPosition position = node.getPosition();
    if (position != null) {
        JsonObject positionJson = new JsonObject();
        positionJson.addProperty("startColumn", position.getStartColumn());
        positionJson.addProperty("startLine", position.getStartLine());
        positionJson.addProperty("endColumn", position.getEndColumn());
        positionJson.addProperty("endLine", position.getEndLine());
        nodeJson.add("position", positionJson);
    }

    /* Virtual props */

    // Add UUID for each node.
    nodeJson.addProperty("id", UUID.randomUUID().toString());

    // Add the visible endpoints for a given node
    if (symbolMetaInfoMap.containsKey(node)) {
        List<SymbolMetaInfo> endpointMetaList = symbolMetaInfoMap.get(node);
        JsonArray endpoints = new JsonArray();
        endpointMetaList.forEach(symbolMetaInfo -> endpoints.add(symbolMetaInfo.getJson()));
        nodeJson.add("VisibleEndpoints", endpoints);
    }

    JsonArray type = getType(node);
    if (type != null) {
        nodeJson.add(SYMBOL_TYPE, type);
    }
    if (node.getKind() == NodeKind.INVOCATION) {
        assert node instanceof BLangInvocation : node.getClass();
        BLangInvocation invocation = (BLangInvocation) node;
        if (invocation.symbol != null && invocation.symbol.kind != null) {
            nodeJson.addProperty(INVOCATION_TYPE, invocation.symbol.kind.toString());
        }
    }

    for (Method m : methods) {
        String name = m.getName();

        if (name.equals("getWS") || name.equals("getPosition")) {
            continue;
        }

        String jsonName;
        if (name.startsWith("get")) {
            jsonName = toJsonName(name, 3);
        } else if (name.startsWith("is")) {
            jsonName = toJsonName(name, 2);
        } else {
            continue;
        }

        Object prop = null;
        try {
            prop = m.invoke(node);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new JSONGenerationException("Error occurred while generating JSON", e);
        }

        /* Literal class - This class is escaped in backend to address cases like "ss\"" and 8.0 and null */
        if ((node.getKind() == NodeKind.LITERAL || node.getKind() == NodeKind.NUMERIC_LITERAL)
                && "value".equals(jsonName)) {
            if (prop instanceof String) {
                nodeJson.addProperty(jsonName, '"' + StringEscapeUtils.escapeJava((String) prop) + '"');
                nodeJson.addProperty(UNESCAPED_VALUE, String.valueOf(prop));
            } else {
                nodeJson.addProperty(jsonName, String.valueOf(prop));
            }
            continue;
        }

        if (node.getKind() == NodeKind.ANNOTATION && node instanceof BLangAnnotation) {
            JsonArray attachmentPoints = new JsonArray();
            ((BLangAnnotation) node).getAttachPoints().stream().map(AttachPoint::getValue)
                    .map(JsonPrimitive::new).forEach(attachmentPoints::add);
            nodeJson.add("attachmentPoints", attachmentPoints);
        }

        if (prop instanceof List && jsonName.equals("types")) {
            // Currently we don't need any Symbols for the UI. So skipping for now.
            continue;
        }

        /* Node classes */
        if (prop instanceof Node) {
            nodeJson.add(jsonName, generateJSON((Node) prop, anonStructs, symbolMetaInfoMap));
        } else if (prop instanceof List) {
            List listProp = (List) prop;
            JsonArray listPropJson = new JsonArray();
            nodeJson.add(jsonName, listPropJson);
            for (Object listPropItem : listProp) {
                if (listPropItem instanceof Node) {
                    /* Remove top level anon func and struct */
                    if (node.getKind() == NodeKind.COMPILATION_UNIT) {
                        if (listPropItem instanceof BLangFunction
                                && (((BLangFunction) listPropItem)).name.value.startsWith("$lambda$")) {
                            continue;
                        }
                    }
                    listPropJson.add(generateJSON((Node) listPropItem, anonStructs, symbolMetaInfoMap));
                } else if (listPropItem instanceof BLangRecordVarRef.BLangRecordVarRefKeyValue) {
                    listPropJson.add(generateJSON(
                            ((BLangRecordVarRef.BLangRecordVarRefKeyValue) listPropItem).getVariableName(),
                            anonStructs, symbolMetaInfoMap));
                    listPropJson.add(generateJSON(
                            ((BLangRecordVarRef.BLangRecordVarRefKeyValue) listPropItem).getBindingPattern(),
                            anonStructs, symbolMetaInfoMap));
                } else if (listPropItem instanceof BLangRecordVariable.BLangRecordVariableKeyValue) {
                    listPropJson.add(generateJSON(
                            ((BLangRecordVariable.BLangRecordVariableKeyValue) listPropItem).getKey(),
                            anonStructs, symbolMetaInfoMap));
                    listPropJson.add(generateJSON(
                            ((BLangRecordVariable.BLangRecordVariableKeyValue) listPropItem).getValue(),
                            anonStructs, symbolMetaInfoMap));
                } else if (listPropItem instanceof String) {
                    listPropJson.add((String) listPropItem);
                } else {
                    logger.debug("Can't serialize " + jsonName + ", has a an array of " + listPropItem);
                }
            }
            /* Runtime model classes */
        } else if (prop instanceof Set && jsonName.equals("flags")) {
            Set flags = (Set) prop;
            for (Flag flag : Flag.values()) {
                nodeJson.addProperty(StringUtils.lowerCase(flag.toString()), flags.contains(flag));
            }
        } else if (prop instanceof Set) {
            // TODO : limit this else if to getInputs getOutputs of transform.
            Set vars = (Set) prop;
            JsonArray listVarJson = new JsonArray();
            nodeJson.add(jsonName, listVarJson);
            for (Object obj : vars) {
                listVarJson.add(obj.toString());
            }
        } else if (prop instanceof NodeKind) {
            String kindName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, prop.toString());
            nodeJson.addProperty(jsonName, kindName);
        } else if (prop instanceof OperatorKind) {
            nodeJson.addProperty(jsonName, prop.toString());
            /* Generic classes */
        } else if (prop instanceof String) {
            nodeJson.addProperty(jsonName, (String) prop);
        } else if (prop instanceof Number) {
            nodeJson.addProperty(jsonName, (Number) prop);
        } else if (prop instanceof Boolean) {
            nodeJson.addProperty(jsonName, (Boolean) prop);
        } else if (prop instanceof Enum) {
            nodeJson.addProperty(jsonName, StringUtils.lowerCase(((Enum) prop).name()));
        } else if (prop instanceof int[]) {
            int[] intArray = ((int[]) prop);
            JsonArray intArrayPropJson = new JsonArray();
            nodeJson.add(jsonName, intArrayPropJson);
            for (int intProp : intArray) {
                intArrayPropJson.add(intProp);
            }
        } else if (prop != null) {
            nodeJson.addProperty(jsonName, prop.toString());
        }
    }
    return nodeJson;
}

From source file:com.axelor.web.service.RestService.java

@GET
@Path("{id}/{field}/download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@SuppressWarnings("all")
public javax.ws.rs.core.Response download(@PathParam("id") Long id, @PathParam("field") String field,
        @QueryParam("image") boolean isImage) throws IOException {

    boolean isAttachment = MetaFile.class.getName().equals(getModel());

    Class klass = getResource().getModel();
    Mapper mapper = Mapper.of(klass);//from   www.  j  a  v a2s  .  co m
    Model bean = JPA.find(klass, id);

    if (isAttachment) {
        final String fileName = (String) mapper.get(bean, "fileName");
        final String filePath = (String) mapper.get(bean, "filePath");
        final File inputFile = FileUtils.getFile(uploadPath, filePath);
        if (!inputFile.exists()) {
            return javax.ws.rs.core.Response.status(Status.NOT_FOUND).build();
        }
        return javax.ws.rs.core.Response.ok(new StreamingOutput() {

            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                uploadSave(new FileInputStream(inputFile), output);
            }
        }).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
    }

    String fileName = getModel() + "_" + field;
    Object data = mapper.get(bean, field);

    if (isImage) {
        String base64 = BLANK_IMAGE;
        if (data instanceof byte[]) {
            base64 = new String((byte[]) data);
        }
        try {
            base64 = base64.substring(base64.indexOf(";base64,") + 8);
            data = DatatypeConverter.parseBase64Binary(base64);
        } catch (Exception e) {
        }
        return javax.ws.rs.core.Response.ok(data).build();
    }

    fileName = fileName.replaceAll("\\s", "") + "_" + id;
    fileName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fileName);

    if (data == null) {
        return javax.ws.rs.core.Response.noContent().build();
    }

    return javax.ws.rs.core.Response.ok(data)
            .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
}

From source file:org.embulk.cli.EmbulkNew.java

private String getDisplayName(final String name) {
    final String[] nameSplit = name.split("_");
    final ArrayList<String> nameComposition = new ArrayList<String>();
    for (String namePart : nameSplit) {
        nameComposition.add(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, namePart));
    }//  w w w.  j ava  2 s . co  m
    return Joiner.on(" ").join(nameComposition);
}

From source file:org.immutables.value.processor.meta.ValueType.java

public String getDocumentName() {
    Optional<RepositoryMirror> repositoryAnnotation = RepositoryMirror.find(element);
    if (repositoryAnnotation.isPresent()) {
        String value = repositoryAnnotation.get().value();
        if (!value.isEmpty()) {
            return value;
        }// w w w  .j av a 2s. co  m
    }
    return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, name());
}

From source file:org.jooby.assets.AssetAggregator.java

/**
 * @return Aggregator's name.
 */
public String name() {
    return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName());
}

From source file:org.jclouds.virtualbox.functions.MastersLoadingCache.java

private String getOsTypeId(String os_family, boolean os_64bit) {
    String osFamily = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, os_family);
    return os_64bit ? osFamily + "_64" : osFamily;
}

From source file:dagger2.internal.codegen.ComponentGenerator.java

/**
 * Writes out a builder for a component or subcomponent.
 *
 * @param input the component or subcomponent
 * @param componentApiName the API name of the component we're building (not our impl)
 * @param componentImplName the implementation name of the component we're building
 * @param componentWriter the class we're adding this builder to
 * @param componentContributionFields a map of member selects so we can later use the fields
 *//*w  w  w.ja va 2 s .co  m*/
private ClassWriter writeBuilder(BindingGraph input, ClassName componentApiName, ClassName componentImplName,
        ClassWriter componentWriter, Map<TypeElement, MemberSelect> componentContributionFields) {
    ClassWriter builderWriter;
    Optional<BuilderSpec> builderSpec = input.componentDescriptor().builderSpec();
    switch (input.componentDescriptor().kind()) {
    case COMPONENT:
    case PRODUCTION_COMPONENT:
        builderWriter = componentWriter.addNestedClass("Builder");
        builderWriter.addModifiers(STATIC);

        // Only top-level components have the factory builder() method.
        // Mirror the user's builder API type if they had one.
        MethodWriter builderFactoryMethod = builderSpec.isPresent()
                ? componentWriter.addMethod(builderSpec.get().builderDefinitionType().asType(), "builder")
                : componentWriter.addMethod(builderWriter, "builder");
        builderFactoryMethod.addModifiers(PUBLIC, STATIC);
        builderFactoryMethod.body().addSnippet("return new %s();", builderWriter.name());
        break;
    case SUBCOMPONENT:
        verify(builderSpec.isPresent()); // we only write subcomponent builders if there was a spec
        builderWriter = componentWriter.addNestedClass(componentApiName.simpleName() + "Builder");
        break;
    default:
        throw new IllegalStateException();
    }
    builderWriter.addModifiers(FINAL);
    builderWriter.addConstructor().addModifiers(PRIVATE);
    if (builderSpec.isPresent()) {
        builderWriter.addModifiers(PRIVATE);
        TypeElement builderType = builderSpec.get().builderDefinitionType();
        switch (builderType.getKind()) {
        case CLASS:
            builderWriter.setSuperType(builderType);
            break;
        case INTERFACE:
            builderWriter.addImplementedType(builderType);
            break;
        default:
            throw new IllegalStateException("not a class or interface: " + builderType);
        }
    } else {
        builderWriter.addModifiers(PUBLIC);
    }

    // the full set of types that calling code uses to construct a component instance
    ImmutableMap<TypeElement, String> componentContributionNames = ImmutableMap
            .copyOf(Maps.asMap(
                    Sets.union(
                            Sets.union(input.transitiveModules().keySet(),
                                    input.componentDescriptor().dependencies()),
                            input.componentDescriptor().executorDependency().asSet()),
                    Functions.compose(CaseFormat.UPPER_CAMEL.converterTo(LOWER_CAMEL),
                            new Function<TypeElement, String>() {
                                @Override
                                public String apply(TypeElement input) {
                                    return input.getSimpleName().toString();
                                }
                            })));

    MethodWriter buildMethod;
    if (builderSpec.isPresent()) {
        ExecutableElement specBuildMethod = builderSpec.get().buildMethod();
        // Note: we don't use the specBuildMethod.getReturnType() as the return type
        // because it might be a type variable.  We make use of covariant returns to allow
        // us to return the component type, which will always be valid.
        buildMethod = builderWriter.addMethod(componentApiName, specBuildMethod.getSimpleName().toString());
        buildMethod.annotate(Override.class);
    } else {
        buildMethod = builderWriter.addMethod(componentApiName, "build");
    }
    buildMethod.addModifiers(PUBLIC);

    for (Entry<TypeElement, String> entry : componentContributionNames.entrySet()) {
        TypeElement contributionElement = entry.getKey();
        String contributionName = entry.getValue();
        FieldWriter builderField = builderWriter.addField(contributionElement, contributionName);
        builderField.addModifiers(PRIVATE);
        componentContributionFields.put(contributionElement, MemberSelect.instanceSelect(componentImplName,
                Snippet.format("builder.%s", builderField.name())));
        if (componentCanMakeNewInstances(contributionElement)) {
            buildMethod.body().addSnippet("if (%s == null) {", builderField.name())
                    .addSnippet("  this.%s = new %s();", builderField.name(),
                            ClassName.fromTypeElement(contributionElement))
                    .addSnippet("}");
        } else {
            buildMethod.body().addSnippet("if (%s == null) {", builderField.name())
                    .addSnippet("  throw new IllegalStateException(\"%s must be set\");", builderField.name())
                    .addSnippet("}");
        }
        MethodWriter builderMethod;
        boolean returnsVoid = false;
        if (builderSpec.isPresent()) {
            ExecutableElement method = builderSpec.get().methodMap().get(contributionElement);
            if (method == null) { // no method in the API, nothing to write out.
                continue;
            }
            // If the return type is void, we add a method with the void return type.
            // Otherwise we use the builderWriter and take advantage of covariant returns
            // (so that we don't have to worry about setter methods that return type variables).
            if (method.getReturnType().getKind().equals(TypeKind.VOID)) {
                returnsVoid = true;
                builderMethod = builderWriter.addMethod(method.getReturnType(),
                        method.getSimpleName().toString());
            } else {
                builderMethod = builderWriter.addMethod(builderWriter, method.getSimpleName().toString());
            }
            builderMethod.annotate(Override.class);
        } else {
            builderMethod = builderWriter.addMethod(builderWriter, contributionName);
        }
        // TODO(gak): Mirror the API's visibility.
        // (Makes no difference to the user since this class is private,
        //  but makes generated code prettier.)
        builderMethod.addModifiers(PUBLIC);
        builderMethod.addParameter(contributionElement, contributionName);
        builderMethod.body().addSnippet("if (%s == null) {", contributionName)
                .addSnippet("  throw new NullPointerException(%s);", StringLiteral.forValue(contributionName))
                .addSnippet("}").addSnippet("this.%s = %s;", builderField.name(), contributionName);
        if (!returnsVoid) {
            builderMethod.body().addSnippet("return this;");
        }
    }
    buildMethod.body().addSnippet("return new %s(this);", componentImplName);
    return builderWriter;
}

From source file:com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.java

/**
 * Gets token type of ParseTree node from JavadocTokenTypes class.
 * @param node ParseTree node./* w w  w  . j a va 2s. com*/
 * @return token type from JavadocTokenTypes
 */
private static int getTokenType(ParseTree node) {
    int tokenType;

    if (node.getChildCount() == 0) {
        tokenType = ((TerminalNode) node).getSymbol().getType();
    } else {
        final String className = getNodeClassNameWithoutContext(node);
        final String typeName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, className);
        tokenType = JavadocUtils.getTokenId(typeName);
    }

    return tokenType;
}