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

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

Introduction

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

Prototype

CaseFormat LOWER_UNDERSCORE

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

Click Source Link

Document

C++ variable naming convention, e.g., "lower_underscore".

Usage

From source file:dk.dma.enumgenerator.Generator.java

public CodegenClass generateClass() {
    CodegenClass c = new CodegenClass();
    c.setPackage("dk.dma.enumgenerator.test");
    c.setDefinition("public final class " + unit.name);

    c.addField("private final ", unit.type(), " ", v, ";");
    c.addField("private final ", unit.name, "Unit unit;");

    CodegenMethod con = c.addMethod("(", unit.type(), " ", v, ", ", unit.name, "Unit unit)");
    con.add("this.", v, " = ", v, ";");
    con.add("this.unit = unit;");

    // c.newMethod(")
    CodegenMethod getUnit = c.addMethod("public ", u, " getUnit()");
    getUnit.add("return unit;");

    for (Val val : unit.vals.values()) {
        CodegenMethod m = c.addMethod("public ", unit.type(), " to", val.name, "()");
        m.add("return unit.to" + val.name, "(", v, ");");
        m.javadoc().set("Returns the " + v + " in "
                + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, val.name).replace("_", " ") + ".");
        m.javadoc().addParameter(v, "the " + v + " to convert");
        m.javadoc().addReturn("the converted " + v);
        // m.throwNewUnsupportedOperationException("fuckoff");
    }//from  w  w  w  . j  a  v a  2  s .co m

    // Generate Serializer

    // c.addInnerClass("static final class Serializer implements ", ValueSerializer.class, "<", unit.name, ">");

    return c;
}

From source file:com.shenit.commons.utils.ShenStrings.java

/**
 * To underscore format/*from w w w.  j  a  va2  s . c  o  m*/
 * @param str
 * @return
 */
public static String underscore(String str) {
    if (str.indexOf(DELIMITER_UNDERSCORE) > 0)
        return str;
    return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, str(str));
}

From source file:org.apache.brooklyn.util.javalang.coerce.EnumTypeCoercions.java

public static <E extends Enum<E>> Maybe<E> tryCoerce(String input, Class<E> targetType) {
    if (input == null)
        return null;
    if (targetType == null)
        return Maybe.absent("Null enum type");
    if (!targetType.isEnum())
        return Maybe.absent("Type '" + targetType + "' is not an enum");

    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 {/*from   w w  w.  j a  v  a  2s  .c  o  m*/
            return Maybe.of(Enum.valueOf(targetType, value));
        } catch (IllegalArgumentException iae) {
            continue;
        }
    }
    Maybe<E> result = Enums.valueOfIgnoreCase(targetType, input);
    if (result.isPresent())
        return result;
    return Maybe.absent(new ClassCoercionException(
            "Invalid value '" + input + "' for " + JavaClassNames.simpleClassName(targetType)
                    + "; expected one of " + Arrays.asList(Enums.values(targetType))));
}

From source file:org.apache.beam.runners.core.construction.PipelineOptionsTranslation.java

/** Converts the provided {@link Struct} into {@link PipelineOptions}. */
public static PipelineOptions fromProto(Struct protoOptions) {
    try {//  w ww . j av a2  s. c o  m
        Map<String, TreeNode> mapWithoutUrns = new HashMap<>();
        TreeNode rootOptions = MAPPER.readTree(JsonFormat.printer().print(protoOptions));
        Iterator<String> optionsKeys = rootOptions.fieldNames();
        while (optionsKeys.hasNext()) {
            String optionKey = optionsKeys.next();
            TreeNode optionValue = rootOptions.get(optionKey);
            mapWithoutUrns.put(
                    CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,
                            optionKey.substring("beam:option:".length(), optionKey.length() - ":v1".length())),
                    optionValue);
        }
        return MAPPER.readValue(MAPPER.writeValueAsString(ImmutableMap.of("options", mapWithoutUrns)),
                PipelineOptions.class);
    } catch (IOException e) {
        throw new RuntimeException("Failed to read PipelineOptions from Protocol", e);
    }
}

From source file:org.seedstack.seed.core.internal.diagnostic.tool.ErrorCodePrinter.java

private String formatCamelCase(String value) {
    String result = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, value).replace("_", " ");
    return result.substring(0, 1).toUpperCase(Locale.ENGLISH) + result.substring(1);
}

From source file:datamine.storage.recordbuffers.idl.generator.RecordMetaWrapperGenerator.java

public static String getBaseClassName(String tableName) {
    return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName) + "Metadata";
}

From source file:io.soliton.protobuf.json.Messages.java

/**
 * Converts a JSON object to a protobuf message
 *
 * @param builder the proto message type builder
 * @param input the JSON object to convert
 *//*from www. jav a 2 s.c  o m*/
public static Message fromJson(Message.Builder builder, JsonObject input) throws Exception {
    Descriptors.Descriptor descriptor = builder.getDescriptorForType();
    for (Map.Entry<String, JsonElement> entry : input.entrySet()) {
        String protoName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey());
        Descriptors.FieldDescriptor field = descriptor.findFieldByName(protoName);
        if (field == null) {
            throw new Exception("Can't find descriptor for field " + protoName);
        }
        if (field.isRepeated()) {
            if (!entry.getValue().isJsonArray()) {
                // fail
            }
            JsonArray array = entry.getValue().getAsJsonArray();
            for (JsonElement item : array) {
                builder.addRepeatedField(field, parseField(field, item, builder));
            }
        } else {
            builder.setField(field, parseField(field, entry.getValue(), builder));
        }
    }
    return builder.build();
}

From source file:com.google.errorprone.bugpatterns.ArgumentParameterUtils.java

private static HashSet<String> splitStringTermsToSet(String name) {
    // TODO(yulissa): Handle constants in the form of upper underscore
    String nameSplit = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
    return Sets.newHashSet(Splitter.on('_').trimResults().omitEmptyStrings().splitToList(nameSplit));
}

From source file:com.facebook.buck.rules.modern.impl.DefaultClassInfo.java

DefaultClassInfo(Class<?> clazz, Optional<ClassInfo<? super T>> superInfo) {
    this.type = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, clazz.getSimpleName()).intern();
    this.superInfo = superInfo;

    Optional<Class<?>> immutableBase = findImmutableBase(clazz);
    ImmutableList.Builder<FieldInfo<?>> fieldsBuilder = ImmutableList.builder();
    if (immutableBase.isPresent()) {
        ImmutableMap<Field, Boolean> parameterFields = parameterFieldsFromFields(clazz);
        ImmutableMap<Field, Method> parameterMethods = findMethodsForFields(parameterFields.keySet(), clazz);
        parameterFields.forEach((field, isLazy) -> {
            Method method = parameterMethods.get(field);
            if (method == null) {
                return;
            }//from w  w  w .  j  a v  a2  s. c om
            AddToRuleKey addAnnotation = method.getAnnotation(AddToRuleKey.class);
            // TODO(cjhopman): Add @ExcludeFromRuleKey annotation and require that all fields are
            // either explicitly added or explicitly excluded.
            Optional<CustomFieldBehavior> customBehavior = Optional
                    .ofNullable(method.getDeclaredAnnotation(CustomFieldBehavior.class));
            if (addAnnotation != null && !addAnnotation.stringify()) {
                if (isLazy) {
                    throw new RuntimeException(
                            "@Value.Lazy fields cannot be @AddToRuleKey, change it to @Value.Derived.");
                }
                Nullable methodNullable = method.getAnnotation(Nullable.class);
                boolean methodOptional = Optional.class.isAssignableFrom(method.getReturnType());
                fieldsBuilder.add(
                        forFieldWithBehavior(field, methodNullable != null || methodOptional, customBehavior));
            } else {
                fieldsBuilder.add(excludedField(field, customBehavior));
            }
        });
    } else {
        for (final Field field : clazz.getDeclaredFields()) {
            // TODO(cjhopman): Make this a Precondition.
            if (!Modifier.isFinal(field.getModifiers())) {
                LOG.warn("All fields of a Buildable must be final (%s.%s)", clazz.getSimpleName(),
                        field.getName());
            }

            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            field.setAccessible(true);

            Optional<CustomFieldBehavior> customBehavior = Optional
                    .ofNullable(field.getDeclaredAnnotation(CustomFieldBehavior.class));
            AddToRuleKey addAnnotation = field.getAnnotation(AddToRuleKey.class);
            // TODO(cjhopman): Add @ExcludeFromRuleKey annotation and require that all fields are either
            // explicitly added or explicitly excluded.
            if (addAnnotation != null && !addAnnotation.stringify()) {
                fieldsBuilder.add(forFieldWithBehavior(field, field.getAnnotation(Nullable.class) != null,
                        customBehavior));
            } else {
                fieldsBuilder.add(excludedField(field, customBehavior));
            }
        }
    }

    if (clazz.isMemberClass()) {
        // TODO(cjhopman): This should also iterate over the outer class's class hierarchy.
        Class<?> outerClazz = clazz.getDeclaringClass();
        // I don't think this can happen, but if it does, this needs to be updated to handle it
        // correctly.
        Preconditions.checkArgument(
                !outerClazz.isAnonymousClass() && !outerClazz.isMemberClass() && !outerClazz.isLocalClass());
        for (final Field field : outerClazz.getDeclaredFields()) {
            field.setAccessible(true);
            if (!Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            // TODO(cjhopman): Make this a Precondition.
            if (!Modifier.isFinal(field.getModifiers())) {
                LOG.warn("All static fields of a Buildable's outer class must be final (%s.%s)",
                        outerClazz.getSimpleName(), field.getName());
            }
        }
    }
    this.fields = fieldsBuilder.build();
}

From source file:edu.berkeley.ground.postgres.dao.version.PostgresItemDao.java

@Override
public T retrieveFromDatabase(String sourceKey) throws GroundException {
    return this.retrieve(String.format(SqlConstants.SELECT_STAR_BY_SOURCE_KEY,
            CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, this.getType().getSimpleName()), sourceKey),
            sourceKey);//ww  w .j av a2  s .c om
}