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

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

Introduction

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

Prototype

CaseFormat UPPER_UNDERSCORE

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

Click Source Link

Document

Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE".

Usage

From source file:org.brooth.jeta.apt.processors.ObservableProcessor.java

public boolean process(TypeSpec.Builder builder, RoundContext context) {
    ClassName masterClassName = ClassName.get(context.metacodeContext().masterElement());
    builder.addSuperinterface(/* w  w  w . jav a2  s  .c  om*/
            ParameterizedTypeName.get(ClassName.get(ObservableMetacode.class), masterClassName));

    MethodSpec.Builder applyMethodSpecBuilder = MethodSpec.methodBuilder("applyObservable")
            .addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(void.class)
            .addParameter(masterClassName, "master");

    for (Element element : context.elements()) {
        String fieldName = element.getSimpleName().toString();

        String monitorFiledName = fieldName + "_MONITOR";
        builder.addField(FieldSpec.builder(Object.class, monitorFiledName)
                .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("new Object()")
                .build());

        TypeName observersTypeName = TypeName.get(element.asType());
        TypeName mapTypeName = ParameterizedTypeName.get(ClassName.get(Map.class), masterClassName,
                observersTypeName);
        FieldSpec observersField = FieldSpec.builder(mapTypeName, fieldName)
                .addModifiers(Modifier.PRIVATE, Modifier.STATIC).initializer("new $T()", ParameterizedTypeName
                        .get(ClassName.get(WeakHashMap.class), masterClassName, observersTypeName))
                .build();
        builder.addField(observersField);

        String eventTypeStr = observersTypeName.toString();
        int i = eventTypeStr.indexOf('<');
        if (i == -1)
            throw new IllegalArgumentException(
                    "Not valid @Subject usage, define event type as generic of Observers");

        eventTypeStr = eventTypeStr.substring(i + 1, eventTypeStr.lastIndexOf('>'));
        String methodHashName = "get" + CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL,
                CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, eventTypeStr).replaceAll("\\.", "_"))
                + "Observers";

        MethodSpec getObserversMethodSpec = MethodSpec.methodBuilder(methodHashName)
                .addModifiers(Modifier.STATIC, Modifier.PUBLIC).returns(observersTypeName)
                .addParameter(masterClassName, "master")
                .addStatement("$T result = $L.get(master)", observersTypeName, fieldName)
                .beginControlFlow("if (result == null)").beginControlFlow("synchronized ($L)", monitorFiledName)
                .beginControlFlow("if (!$L.containsKey(master))", fieldName)
                .addStatement("result = new $T()", observersTypeName)
                .addStatement("$L.put(master, result)", fieldName).endControlFlow().endControlFlow()
                .endControlFlow().addStatement("return result").build();
        builder.addMethod(getObserversMethodSpec);

        applyMethodSpecBuilder.addStatement("master.$L = $L(master)", fieldName, methodHashName);
    }
    builder.addMethod(applyMethodSpecBuilder.build());

    return false;
}

From source file:com.github.jcustenborder.kafka.connect.utils.templates.model.SchemaData.java

String type(Schema schema) {
    String result;//from  www. j  av  a2  s  .  c  o  m
    switch (schema.type()) {
    case ARRAY:
        result = String.format("Array of %s", type(schema.valueSchema()));
        break;
    case MAP:
        result = String.format("Map of %s, %s", type(schema.keySchema()), type(schema.valueSchema()));
        break;
    default:
        result = String.format(":ref:`schema-%s`",
                CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, schema.type().toString()));
        break;
    }
    return result;
}

From source file:org.apache.airavata.userprofile.core.AbstractThriftDeserializer.java

@Override
public T deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final T instance = newInstance();
    final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    final ObjectNode rootNode = (ObjectNode) mapper.readTree(jp);
    final Iterator<Map.Entry<String, JsonNode>> iterator = rootNode.fields();

    while (iterator.hasNext()) {
        final Map.Entry<String, JsonNode> currentField = iterator.next();
        try {/*from  www. j a v  a2 s  .  c o m*/
            /*
             * If the current node is not a null value, process it.  Otherwise,
             * skip it.  Jackson will treat the null as a 0 for primitive
             * number types, which in turn will make Thrift think the field
             * has been set. Also we ignore the MongoDB specific _id field
             */
            if (!currentField.getKey().equalsIgnoreCase("_id")
                    && currentField.getValue().getNodeType() != JsonNodeType.NULL) {
                final E field = getField(
                        CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, currentField.getKey()));
                final JsonParser parser = currentField.getValue().traverse();
                parser.setCodec(mapper);
                final Object value = mapper.readValue(parser, generateValueType(instance, field));
                if (value != null) {
                    log.debug(String.format("Field %s produced value %s of type %s.", currentField.getKey(),
                            value, value.getClass().getName()));
                    instance.setFieldValue(field, value);
                } else {
                    log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
                }
            } else {
                log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
            }
        } catch (final NoSuchFieldException | IllegalArgumentException e) {
            log.error("Unable to de-serialize field '{}'.", currentField.getKey(), e);
            ctxt.mappingException(e.getMessage());
        }
    }

    try {
        // Validate that the instance contains all required fields.
        validate(instance);
    } catch (final TException e) {
        log.error(String.format("Unable to deserialize JSON '%s' to type '%s'.", jp.getValueAsString(),
                instance.getClass().getName(), e));
        ctxt.mappingException(e.getMessage());
    }

    return instance;
}

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

private Description checkImmutable(VariableTree tree, VisitorState state, Symbol.VarSymbol sym, String name) {
    Type type = sym.type;/*from www.j  a  v  a  2  s  .  c  o m*/
    if (type == null) {
        return Description.NO_MATCH;
    }
    switch (name) {
    case "serialVersionUID":
        // mandated by the Serializable API
        return Description.NO_MATCH;
    default:
        break;
    }
    if (name.toUpperCase().equals(name)) {
        return Description.NO_MATCH;
    }
    if (state.getTypes().unboxedTypeOrType(type).isPrimitive()
            || ASTHelpers.isSameType(type, state.getSymtab().stringType, state)
            || type.tsym.getKind() == ElementKind.ENUM) {
        String constName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, name);
        if (constName.startsWith("K_")) {
            constName = constName.substring("K_".length());
        }
        return buildDescription(tree)
                .setMessage(String.format("%ss are immutable, field should be named '%s'",
                        sym.type.tsym.getSimpleName(), constName))
                .addFix(SuggestedFixes.renameVariable(tree, constName, state)).build();
    }
    return Description.NO_MATCH;
}

From source file:com.spectralogic.ds3cli.Ds3Cli.java

private CliCommand getCommandExecutor() throws CommandException {
    final String commandName = this.args.getCommand();

    final String commandCamel = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, commandName);

    final Iterator<CliCommand> implementations = getAllCommands();
    while (implementations.hasNext()) {
        final CliCommand implementation = implementations.next();
        final String className = implementation.getClass().getSimpleName();
        if (className.equalsIgnoreCase(commandCamel)) {
            return implementation.withProvider(this.ds3Provider, this.fileUtils);
        }/*from  w ww.  j  a  va 2  s .  c o m*/
    }
    throw new CommandException("No command class: " + commandName);
}

From source file:net.centro.rtb.monitoringcenter.metrics.system.jvm.ThreadMetricSet.java

ThreadMetricSet() {
    this.threadMXBean = ManagementFactory.getThreadMXBean();
    this.deadlockDetector = new ThreadDeadlockDetector();

    Map<String, Metric> metricsByNames = new HashMap<>();

    this.currentThreadsGauge = new Gauge<Integer>() {
        @Override/*from  w w w  .  j  a va2  s.c o  m*/
        public Integer getValue() {
            return threadMXBean.getThreadCount();
        }
    };
    metricsByNames.put("currentCount", currentThreadsGauge);

    this.peakThreadsGauge = new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return threadMXBean.getPeakThreadCount();
        }
    };
    metricsByNames.put("peakCount", peakThreadsGauge);

    this.daemonThreadsGauge = new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return threadMXBean.getPeakThreadCount();
        }
    };
    metricsByNames.put("daemons", daemonThreadsGauge);

    this.deadlockedThreadsGauge = new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return deadlockDetector.getDeadlockedThreads().size();
        }
    };
    metricsByNames.put("deadlocked", deadlockedThreadsGauge);

    Map<Thread.State, Gauge<Integer>> threadsGaugesByThreadStates = new HashMap<>();
    for (final Thread.State state : Thread.State.values()) {
        String metricName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, state.toString());

        Gauge<Integer> threadsGauge = new Gauge<Integer>() {
            @Override
            public Integer getValue() {
                return getThreadCount(state);
            }
        };
        threadsGaugesByThreadStates.put(state, threadsGauge);
        metricsByNames.put(metricName, threadsGauge);
    }
    this.threadsGaugesByThreadStates = threadsGaugesByThreadStates;

    this.metricsByNames = metricsByNames;
}

From source file:org.brooth.jeta.apt.processors.ObserverProcessor.java

public boolean process(TypeSpec.Builder builder, RoundContext context) {
    ClassName masterClassName = ClassName.get(context.metacodeContext().masterElement());
    builder.addSuperinterface(/* w ww  .  j  av a  2s.co m*/
            ParameterizedTypeName.get(ClassName.get(ObserverMetacode.class), masterClassName));
    ClassName handlerClassName = ClassName.get(ObserverHandler.class);

    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("applyObservers").addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC).returns(handlerClassName)
            .addParameter(masterClassName, "master", Modifier.FINAL).addParameter(Object.class, "observable")
            .addParameter(Class.class, "observableClass")
            .addStatement("$T handler = new $T()", handlerClassName, handlerClassName);

    for (Element element : context.elements()) {
        final Observe annotation = element.getAnnotation(Observe.class);
        String observableClass = MetacodeUtils.extractClassName(new Runnable() {
            public void run() {
                annotation.value();
            }
        });
        ClassName observableTypeName = ClassName.bestGuess(observableClass);
        ClassName metacodeTypeName = ClassName.bestGuess(MetacodeUtils.toMetacodeName(observableClass));

        List<? extends VariableElement> params = ((ExecutableElement) element).getParameters();
        if (params.size() != 1)
            throw new IllegalArgumentException("Observer method must have one parameter (event)");
        TypeName eventTypeName = TypeName.get(params.get(0).asType());
        if (eventTypeName instanceof ParameterizedTypeName)
            eventTypeName = ((ParameterizedTypeName) eventTypeName).rawType;

        String methodHashName = "get"
                + CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, CaseFormat.UPPER_CAMEL
                        .to(CaseFormat.UPPER_UNDERSCORE, eventTypeName.toString()).replaceAll("\\.", "_"))
                + "Observers";

        TypeSpec eventObserverTypeSpec = TypeSpec.anonymousClassBuilder("")
                .addSuperinterface(ParameterizedTypeName.get(ClassName.get(EventObserver.class), eventTypeName))
                .addMethod(MethodSpec.methodBuilder("onEvent").addAnnotation(Override.class)
                        .addModifiers(Modifier.PUBLIC).addParameter(eventTypeName, "event").returns(void.class)
                        .addStatement("master.$N(event)", element.getSimpleName().toString()).build())
                .build();

        methodBuilder.beginControlFlow("if ($T.class == observableClass)", observableTypeName)
                .addStatement("handler.add($T.class, $T.class,\n$T.$L(($T) observable).\nregister($L))",
                        observableTypeName, eventTypeName, metacodeTypeName, methodHashName, observableTypeName,
                        eventObserverTypeSpec)
                .endControlFlow();
    }
    methodBuilder.addStatement("return handler");
    builder.addMethod(methodBuilder.build());
    return false;
}

From source file:cn.patterncat.metrics.jvm.ThreadMetricSet.java

ThreadMetricSet() {
    this.threadMXBean = ManagementFactory.getThreadMXBean();
    this.deadlockDetector = new ThreadDeadlockDetector();

    Map<String, Metric> metricsByNames = new HashMap<>();

    this.currentThreadsGauge = new Gauge<Integer>() {
        @Override//from   w  ww  .  ja  v  a 2s  .  c  o m
        public Integer getValue() {
            return threadMXBean.getThreadCount();
        }
    };
    metricsByNames.put("currentCount", currentThreadsGauge);

    this.peakThreadsGauge = new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return threadMXBean.getPeakThreadCount();
        }
    };
    metricsByNames.put("peakCount", peakThreadsGauge);

    this.daemonThreadsGauge = new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return threadMXBean.getDaemonThreadCount();
        }
    };
    metricsByNames.put("daemonCount", daemonThreadsGauge);

    this.deadlockedThreadsGauge = new Gauge<Integer>() {
        @Override
        public Integer getValue() {
            return deadlockDetector.getDeadlockedThreads().size();
        }
    };
    metricsByNames.put("deadlockCount", deadlockedThreadsGauge);

    Map<Thread.State, Gauge<Integer>> threadsGaugesByThreadStates = new HashMap<>();
    for (final Thread.State state : Thread.State.values()) {
        String metricName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, state.toString());

        Gauge<Integer> threadsGauge = new Gauge<Integer>() {
            @Override
            public Integer getValue() {
                return getThreadCount(state);
            }
        };
        threadsGaugesByThreadStates.put(state, threadsGauge);
        metricsByNames.put(metricName, threadsGauge);
    }
    this.threadsGaugesByThreadStates = threadsGaugesByThreadStates;

    this.metricsByNames = metricsByNames;
}

From source file:org.apache.phoenix.util.json.JsonUpsertExecutor.java

@Override
protected void execute(Map<?, ?> record) {
    int fieldIndex = 0;
    String colName = null;/* w w w  .  j  a  v  a  2  s.co  m*/
    try {
        if (record.size() < conversionFunctions.size()) {
            String message = String.format("JSON record does not have enough values (has %d, but needs %d)",
                    record.size(), conversionFunctions.size());
            throw new IllegalArgumentException(message);
        }
        for (fieldIndex = 0; fieldIndex < conversionFunctions.size(); fieldIndex++) {
            colName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_UNDERSCORE,
                    columnInfos.get(fieldIndex).getColumnName());
            if (colName.contains(".")) {
                StringBuilder sb = new StringBuilder();
                String[] parts = colName.split("\\.");
                // assume first part is the column family name; omita
                for (int i = 1; i < parts.length; i++) {
                    sb.append(parts[i]);
                    if (i != parts.length - 1) {
                        sb.append(".");
                    }
                }
                colName = sb.toString();
            }
            if (colName.contains("\"")) {
                colName = colName.replace("\"", "");
            }
            Object sqlValue = conversionFunctions.get(fieldIndex).apply(record.get(colName));
            if (sqlValue != null) {
                preparedStatement.setObject(fieldIndex + 1, sqlValue);
            } else {
                preparedStatement.setNull(fieldIndex + 1, dataTypes.get(fieldIndex).getSqlType());
            }
        }
        preparedStatement.execute();
        upsertListener.upsertDone(++upsertCount);
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            // Even though this is an error we only log it with debug logging because we're notifying the
            // listener, and it can do its own logging if needed
            LOG.debug("Error on record " + record + ", fieldIndex " + fieldIndex + ", colName " + colName, e);
        }
        upsertListener.errorOnRecord(record,
                new Exception("fieldIndex: " + fieldIndex + ", colName " + colName, e));
    }
}

From source file:ratpack.config.internal.source.EnvironmentConfigSource.java

public static Function<String, String> camelCase() {
    return Function.fromGuava(CaseFormat.UPPER_UNDERSCORE.converterTo(CaseFormat.LOWER_CAMEL));
}