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:com.google.template.soy.pysrc.internal.GeneratePySanitizeEscapingDirectiveCode.java

@Override
protected void useExistingLibraryFunction(StringBuilder outputCode, String identifier,
        String existingFunction) {
    String fnName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, identifier);
    outputCode.append("\ndef ").append(fnName).append("_helper(v):\n").append("  return ")
            .append(existingFunction).append("(str(v))\n").append("\n");
}

From source file:org.intellij.erlang.refactoring.introduce.ErlangExtractFunctionHandler.java

private static void perform(@NotNull Editor editor, @NotNull List<ErlangExpression> selection) {
    final ErlangExpression first = ContainerUtil.getFirstItem(selection);
    final ErlangFunction function = PsiTreeUtil.getParentOfType(first, ErlangFunction.class);
    final ErlangExpression last = selection.get(selection.size() - 1);
    assert first != null;
    assert function != null;
    assert last != null;

    Pair<List<ErlangNamedElement>, List<ErlangNamedElement>> analyze = analyze(selection);

    final Project project = first.getProject();
    List<ErlangNamedElement> inParams = analyze.first;
    List<ErlangNamedElement> outParams = analyze.second;

    String shorten = ErlangRefactoringUtil.shorten(last, "extracted");
    String name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, shorten);
    ErlangExtractFunctionDialog dialog = new ErlangExtractFunctionDialog(project, name, inParams);

    if (ApplicationManager.getApplication().isUnitTestMode() || dialog.showAndGet()) {
        String functionName = dialog.getFunctionName();
        String bindings = bindings(outParams);
        String bindingsEx = StringUtil.isEmpty(bindings) ? bindings : ",\n" + bindings;
        final String bindingsS = StringUtil.isEmpty(bindings) ? bindings : bindings + " = ";

        final String signature = generateSignature(functionName, inParams);
        final String functionText = signature + " ->\n" + StringUtil.join(selection, PsiElement::getText, ",\n")
                + bindingsEx + ".";

        try {//from   w w  w  .ja  va 2 s. co m
            PsiFile file = first.getContainingFile();
            new WriteCommandAction(editor.getProject(), "Extract function", file) {
                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    ErlangFunction newFunction = ErlangElementFactory.createFunctionFromText(project,
                            functionText);

                    PsiElement functionParent = function.getParent();
                    PsiElement added = functionParent.addAfter(newFunction, function);
                    functionParent.addBefore(newLine(), added);
                    functionParent.addAfter(newLine(), function);

                    PsiElement parent = first.getParent();
                    parent.addBefore(
                            ErlangElementFactory.createExpressionFromText(getProject(), bindingsS + signature),
                            first);
                    parent.deleteChildRange(first, last);
                }

                private PsiElement newLine() {
                    return ErlangElementFactory.createLeafFromText(project, "\n");
                }
            }.execute();
        } catch (Throwable throwable) {
            LOGGER.warn(throwable);
        }
    }

    Disposer.dispose(dialog.getDisposable());
}

From source file:com.ning.billing.util.dao.LowerToCamelBeanMapper.java

public T map(final int row, final ResultSet rs, final StatementContext ctx) throws SQLException {
    final T bean;
    try {/*from   w ww . j  a  v a 2 s.  com*/
        bean = type.newInstance();
    } catch (Exception e) {
        throw new IllegalArgumentException(
                String.format("A bean, %s, was mapped " + "which was not instantiable", type.getName()), e);
    }

    final Class beanClass = bean.getClass();
    final ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 1; i <= metadata.getColumnCount(); ++i) {
        final String name = metadata.getColumnLabel(i).toLowerCase();

        final PropertyDescriptor descriptor = properties.get(name);

        if (descriptor != null) {
            final Class<?> type = descriptor.getPropertyType();

            Object value;

            if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) {
                value = rs.getBoolean(i);
            } else if (type.isAssignableFrom(Byte.class) || type.isAssignableFrom(byte.class)) {
                value = rs.getByte(i);
            } else if (type.isAssignableFrom(Short.class) || type.isAssignableFrom(short.class)) {
                value = rs.getShort(i);
            } else if (type.isAssignableFrom(Integer.class) || type.isAssignableFrom(int.class)) {
                value = rs.getInt(i);
            } else if (type.isAssignableFrom(Long.class) || type.isAssignableFrom(long.class)) {
                value = rs.getLong(i);
            } else if (type.isAssignableFrom(Float.class) || type.isAssignableFrom(float.class)) {
                value = rs.getFloat(i);
            } else if (type.isAssignableFrom(Double.class) || type.isAssignableFrom(double.class)) {
                value = rs.getDouble(i);
            } else if (type.isAssignableFrom(BigDecimal.class)) {
                value = rs.getBigDecimal(i);
            } else if (type.isAssignableFrom(DateTime.class)) {
                final Timestamp timestamp = rs.getTimestamp(i);
                value = timestamp == null ? null : new DateTime(timestamp).toDateTime(DateTimeZone.UTC);
            } else if (type.isAssignableFrom(Time.class)) {
                value = rs.getTime(i);
            } else if (type.isAssignableFrom(LocalDate.class)) {
                final Date date = rs.getDate(i);
                value = date == null ? null : new LocalDate(date, DateTimeZone.UTC);
            } else if (type.isAssignableFrom(DateTimeZone.class)) {
                final String dateTimeZoneString = rs.getString(i);
                value = dateTimeZoneString == null ? null : DateTimeZone.forID(dateTimeZoneString);
            } else if (type.isAssignableFrom(String.class)) {
                value = rs.getString(i);
            } else if (type.isAssignableFrom(UUID.class)) {
                final String uuidString = rs.getString(i);
                value = uuidString == null ? null : UUID.fromString(uuidString);
            } else if (type.isEnum()) {
                final String enumString = rs.getString(i);
                //noinspection unchecked
                value = enumString == null ? null : Enum.valueOf((Class<Enum>) type, enumString);
            } else {
                value = rs.getObject(i);
            }

            if (rs.wasNull() && !type.isPrimitive()) {
                value = null;
            }

            try {
                final Method writeMethod = descriptor.getWriteMethod();
                if (writeMethod != null) {
                    writeMethod.invoke(bean, value);
                } else {
                    final String camelCasedName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name);
                    final Field field = getField(beanClass, camelCasedName);
                    field.setAccessible(true); // Often private...
                    field.set(bean, value);
                }
            } catch (NoSuchFieldException e) {
                throw new IllegalArgumentException(
                        String.format("Unable to find field for " + "property, %s", name), e);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException(
                        String.format("Unable to access setter for " + "property, %s", name), e);
            } catch (InvocationTargetException e) {
                throw new IllegalArgumentException(String.format(
                        "Invocation target exception trying to " + "invoker setter for the %s property", name),
                        e);
            } catch (NullPointerException e) {
                throw new IllegalArgumentException(
                        String.format("No appropriate method to " + "write value %s ", value.toString()), e);
            }
        }
    }

    return bean;
}

From source file:datamine.storage.idl.generator.java.InterfaceGenerator.java

public static String getDefaultDerivedClassName(String tableName) {
    return new StringBuilder().append(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName))
            .append("DefaultDerivedValues").toString();
}

From source file:com.facebook.buck.skylark.parser.RuleFunctionFactory.java

/**
 * Populates provided {@code builder} with values from {@code kwargs} assuming {@code ruleClass}
 * as the target {@link BaseDescription} class.
 *
 * @param kwargs The keyword arguments and their values passed to rule function in build file.
 * @param builder The map builder used for storing extracted attributes and their values.
 * @param allParamInfo The parameter information for every build rule attribute.
 *///  w w  w .j a  va2  s . c  om
private void populateAttributes(Map<String, Object> kwargs, ImmutableMap.Builder<String, Object> builder,
        ImmutableMap<String, ParamInfo> allParamInfo) {
    for (Map.Entry<String, Object> kwargEntry : kwargs.entrySet()) {
        String paramName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, kwargEntry.getKey());
        if (!allParamInfo.containsKey(paramName) && !(IMPLICIT_ATTRIBUTES.contains(kwargEntry.getKey()))) {
            throw new IllegalArgumentException(kwargEntry.getKey() + " is not a recognized attribute");
        }
        if (Runtime.NONE.equals(kwargEntry.getValue())) {
            continue;
        }
        builder.put(paramName, kwargEntry.getValue());
    }
}

From source file:org.knight.examples.guava.strings.StringsExamples.java

private void caseFormat() {
    String s1 = "CamelNamingRule";
    //return camel-naming-rule
    log("convert to LOWER_HYPHEN: " + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, s1));

    String s2 = "HYPHEN-Naming-Rule";
    //use Converter interface to convert hyphen style to underscore style
    //the source format does not conform to the assumed format
    //so the behavior of this method is undefined
    //this Converter.convert() actually calls CaseFormat.to() method in the last step
    log("convert to LOWER_UNDERSCORE: "
            + CaseFormat.LOWER_HYPHEN.converterTo(CaseFormat.LOWER_UNDERSCORE).convert(s2));
}

From source file:com.geemvc.i18n.message.DefaultCompositeMessageResolver.java

protected String controllerName(RequestContext requestCtx) {
    Class<?> controllerClass = requestCtx.requestHandler().controllerClass();

    String name = controllerClass.getSimpleName();

    if (name.endsWith(controllerSuffix)) {
        name = name.replace(controllerSuffix, Str.EMPTY);
    } else if (name.endsWith(actionSuffix)) {
        name = name.replace(actionSuffix, Str.EMPTY);
    }//from w  w  w. java 2 s  .  c o  m

    return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
}

From source file:com.google.template.soy.pysrc.internal.GeneratePySanitizeEscapingDirectiveCode.java

@Override
protected void generateHelperFunction(StringBuilder outputCode, DirectiveDigest digest) {
    String name = digest.getDirectiveName();
    String fnName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, name);
    outputCode.append("\ndef ").append(fnName).append("_helper(value):\n").append("  value = str(value)\n");
    if (digest.getFilterName() != null) {
        String filterName = digest.getFilterName();
        outputCode.append("  if not _FILTER_FOR_").append(filterName).append(".search(value):\n");
        // TODO(dcphillips): Raising a debugging assertion error could be useful.
        outputCode.append("    return '").append(digest.getInnocuousOutput()).append("'\n").append("\n");
    }//from   w ww .j  a  v  a 2s. c  o m

    if (digest.getNonAsciiPrefix() != null) {
        // TODO: We can add a second replace of all non-ascii codepoints below.
        throw new UnsupportedOperationException("Non ASCII prefix escapers not implemented yet.");
    }
    if (digest.getEscapesName() != null) {
        String escapeMapName = digest.getEscapesName();
        String matcherName = digest.getMatcherName();
        outputCode.append("  return _MATCHER_FOR_").append(matcherName).append(".sub(\n")
                .append("      _REPLACER_FOR_").append(escapeMapName).append(", value)\n");
    } else {
        outputCode.append("  return value\n");
    }
    outputCode.append("\n");
}

From source file:datamine.storage.idl.generator.java.InterfaceGenerator.java

public static String getGetterName(Field field) {
    FieldType type = field.getType();/*from www  . j a  va 2  s .com*/
    if (type instanceof PrimitiveFieldType
            && ((PrimitiveFieldType) type).getPrimitiveType() == PrimitiveType.BOOL) {
        return new StringBuilder().append("is")
                .append(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, field.getName())).toString();
    }
    return new StringBuilder().append("get")
            .append(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, field.getName())).toString();
}

From source file:proto.src.main.java.com.google.gson.protobuf.ProtoTypeAdapter.java

/**
 * Creates a new {@link ProtoTypeAdapter} builder, defaulting enum serialization to
 * {@link EnumSerialization#NAME} and converting field serialization from
 * {@link CaseFormat#LOWER_UNDERSCORE} to {@link CaseFormat#LOWER_CAMEL}.
 *///from  w w w.  j av a  2  s. c  o  m
public static Builder newBuilder() {
    return new Builder(EnumSerialization.NAME, CaseFormat.LOWER_UNDERSCORE, CaseFormat.LOWER_CAMEL);
}