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

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

Introduction

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

Prototype

CaseFormat LOWER_HYPHEN

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

Click Source Link

Document

Hyphenated variable naming convention, e.g., "lower-hyphen".

Usage

From source file:com.axelor.meta.schema.views.AbstractWidget.java

@XmlTransient
public Map<String, Object> getWidgetAttrs() {
    if (otherAttributes == null || otherAttributes.isEmpty()) {
        return null;
    }/*from  w  ww  . java 2 s.  c  o m*/
    final Map<String, Object> attrs = Maps.newHashMap();
    for (QName qn : otherAttributes.keySet()) {
        String name = qn.getLocalPart();
        String value = otherAttributes.get(qn);
        if (name.startsWith("x-") || name.startsWith("data-")) {
            name = name.replaceFirst("^(x|data)-", "");
            name = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name);
            attrs.put(name, value);
        }
    }
    if (attrs.containsKey("target") && !attrs.containsKey("targetName")) {
        try {
            Class<?> target = ClassUtils.findClass(attrs.get("target").toString());
            String targetName = Mapper.of(target).getNameField().getName();
            attrs.put("targetName", targetName);
        } catch (Exception e) {
        }
    }
    return attrs;
}

From source file:gobblin.converter.avro.FlattenNestedKeyConverter.java

@Override
public Schema convertSchema(Schema inputSchema, WorkUnitState workUnit) throws SchemaConversionException {
    // Clear previous state
    fieldNameMap.clear();//from   ww w  . j  av  a  2  s  .  c o  m

    Config config = ConfigUtils.propertiesToConfig(workUnit.getProperties())
            .getConfig(getClass().getSimpleName());
    List<String> nestedKeys = ConfigUtils.getStringList(config, FIELDS_TO_FLATTEN);

    List<Field> fields = new ArrayList<>();
    // Clone the existing fields
    for (Field field : inputSchema.getFields()) {
        fields.add(new Field(field.name(), field.schema(), field.doc(), field.defaultVal(), field.order()));
    }

    // Convert each of nested keys into a top level field
    for (String key : nestedKeys) {
        if (!key.contains(FIELD_LOCATION_DELIMITER)) {
            continue;
        }

        String nestedKey = key.trim();
        // Create camel-cased name
        String hyphenizedKey = nestedKey.replace(FIELD_LOCATION_DELIMITER, "-");
        String name = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, hyphenizedKey);
        if (fieldNameMap.containsKey(name)) {
            // Duplicate
            continue;
        }
        fieldNameMap.put(name, nestedKey);

        // Find the field
        Optional<Field> optional = AvroUtils.getField(inputSchema, nestedKey);
        if (!optional.isPresent()) {
            throw new SchemaConversionException("Unable to get field with location: " + nestedKey);
        }
        Field field = optional.get();

        // Make a copy under a new name
        Field copy = new Field(name, field.schema(), field.doc(), field.defaultVal(), field.order());
        fields.add(copy);
    }

    Schema outputSchema = Schema.createRecord(inputSchema.getName(), inputSchema.getDoc(),
            inputSchema.getNamespace(), inputSchema.isError());
    outputSchema.setFields(fields);
    return outputSchema;
}

From source file:org.jclouds.tools.ant.taskdefs.compute.ComputeTask.java

/**
 * makes a connection to the compute service and invokes
 *//*from   w w  w  .j ava 2  s  .c o m*/
public void execute() throws BuildException {
    ComputeServiceContext context = computeMap.get(HttpUtils.createUri(provider));

    try {
        for (String action : Splitter.on(',').split(actions)) {
            Action act = Action.valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, action));
            try {
                invokeActionOnService(act, context.getComputeService());
            } catch (RunNodesException e) {
                throw new BuildException(e);
            } catch (IOException e) {
                throw new BuildException(e);
            }
        }
    } finally {
        context.close();
    }
}

From source file:brooklyn.entity.basic.Lifecycle.java

/**
 * The text representation of the {@link #name()}.
 *
 * This is formatted as lower case characters, with hyphens instead of spaces.
 *///from ww w  .j av  a 2  s. co m
public String value() {
    return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());
}

From source file:com.github.jcustenborder.kafka.connect.cdc.SchemaGenerator.java

private static CaseFormat caseFormat(CDCSourceConnectorConfig.CaseFormat inputCaseFormat) {
    CaseFormat inputFormat;//from www .j  av a2s.  c  o m
    switch (inputCaseFormat) {
    case LOWER_CAMEL:
        inputFormat = CaseFormat.LOWER_CAMEL;
        break;
    case LOWER_HYPHEN:
        inputFormat = CaseFormat.LOWER_HYPHEN;
        break;
    case LOWER_UNDERSCORE:
        inputFormat = CaseFormat.LOWER_UNDERSCORE;
        break;
    case UPPER_CAMEL:
        inputFormat = CaseFormat.UPPER_CAMEL;
        break;
    case UPPER_UNDERSCORE:
        inputFormat = CaseFormat.UPPER_UNDERSCORE;
        break;
    default:
        throw new UnsupportedOperationException(
                String.format("'%s' is not a supported case format.", inputCaseFormat));
    }
    return inputFormat;
}

From source file:org.apache.gobblin.converter.avro.FlattenNestedKeyConverter.java

@Override
public Schema convertSchema(Schema inputSchema, WorkUnitState workUnit) throws SchemaConversionException {
    // Clear previous state
    fieldNameMap.clear();//  www . j a  v  a  2  s  .  co m

    Config config = ConfigUtils.propertiesToConfig(workUnit.getProperties())
            .getConfig(getClass().getSimpleName());
    List<String> nestedKeys = ConfigUtils.getStringList(config, FIELDS_TO_FLATTEN);
    // No keys need flatten
    if (nestedKeys == null || nestedKeys.size() == 0) {
        return inputSchema;
    }

    List<Field> fields = new ArrayList<>();
    // Clone the existing fields
    for (Field field : inputSchema.getFields()) {
        fields.add(new Field(field.name(), field.schema(), field.doc(), field.defaultValue(), field.order()));
    }

    // Convert each of nested keys into a top level field
    for (String key : nestedKeys) {
        if (!key.contains(FIELD_LOCATION_DELIMITER)) {
            continue;
        }

        String nestedKey = key.trim();
        // Create camel-cased name
        String hyphenizedKey = nestedKey.replace(FIELD_LOCATION_DELIMITER, "-");
        String name = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, hyphenizedKey);
        if (fieldNameMap.containsKey(name)) {
            // Duplicate
            continue;
        }
        fieldNameMap.put(name, nestedKey);

        // Find the field
        Optional<Field> optional = AvroUtils.getField(inputSchema, nestedKey);
        if (!optional.isPresent()) {
            throw new SchemaConversionException("Unable to get field with location: " + nestedKey);
        }
        Field field = optional.get();

        // Make a copy under a new name
        Field copy = new Field(name, field.schema(), field.doc(), field.defaultValue(), field.order());
        fields.add(copy);
    }

    Schema outputSchema = Schema.createRecord(inputSchema.getName(), inputSchema.getDoc(),
            inputSchema.getNamespace(), inputSchema.isError());
    outputSchema.setFields(fields);
    return outputSchema;
}

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

/**
 * Validates the class definition and if valid, destructively extracts the class definition from
 * the AST.//from  w  ww . j  ava 2  s .  c  o  m
 */
@Nullable
static PolymerClassDefinition extractFromCallNode(Node callNode, AbstractCompiler compiler,
        GlobalNamespace globalNames) {
    Node descriptor = NodeUtil.getArgumentForCallOrNew(callNode, 0);
    if (descriptor == null || !descriptor.isObjectLit()) {
        // report bad class definition
        compiler.report(JSError.make(callNode, PolymerPassErrors.POLYMER_DESCRIPTOR_NOT_VALID));
        return null;
    }

    int paramCount = callNode.getChildCount() - 1;
    if (paramCount != 1) {
        compiler.report(JSError.make(callNode, PolymerPassErrors.POLYMER_UNEXPECTED_PARAMS));
        return null;
    }

    Node elName = NodeUtil.getFirstPropMatchingKey(descriptor, "is");
    if (elName == null) {
        compiler.report(JSError.make(callNode, PolymerPassErrors.POLYMER_MISSING_IS));
        return null;
    }

    Node target;
    if (NodeUtil.isNameDeclaration(callNode.getGrandparent())) {
        target = IR.name(callNode.getParent().getString());
    } else if (callNode.getParent().isAssign()) {
        target = callNode.getParent().getFirstChild().cloneTree();
    } else {
        String elNameStringBase = elName.isQualifiedName() ? elName.getQualifiedName().replace('.', '$')
                : elName.getString();
        String elNameString = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, elNameStringBase);
        elNameString += "Element";
        target = IR.name(elNameString);
    }

    JSDocInfo classInfo = NodeUtil.getBestJSDocInfo(target);

    JSDocInfo ctorInfo = null;
    Node constructor = NodeUtil.getFirstPropMatchingKey(descriptor, "factoryImpl");
    if (constructor == null) {
        constructor = NodeUtil.emptyFunction();
        compiler.reportChangeToChangeScope(constructor);
        constructor.useSourceInfoFromForTree(callNode);
    } else {
        ctorInfo = NodeUtil.getBestJSDocInfo(constructor);
    }

    Node baseClass = NodeUtil.getFirstPropMatchingKey(descriptor, "extends");
    String nativeBaseElement = baseClass == null ? null : baseClass.getString();

    Node behaviorArray = NodeUtil.getFirstPropMatchingKey(descriptor, "behaviors");
    PolymerBehaviorExtractor behaviorExtractor = new PolymerBehaviorExtractor(compiler, globalNames);
    ImmutableList<BehaviorDefinition> behaviors = behaviorExtractor.extractBehaviors(behaviorArray);
    List<MemberDefinition> allProperties = new ArrayList<>();
    for (BehaviorDefinition behavior : behaviors) {
        overwriteMembersIfPresent(allProperties, behavior.props);
    }
    overwriteMembersIfPresent(allProperties,
            PolymerPassStaticUtils.extractProperties(descriptor, DefinitionType.ObjectLiteral, compiler,
                    /** constructor= */
                    null));

    FeatureSet newFeatures = null;
    if (!behaviors.isEmpty()) {
        newFeatures = behaviors.get(0).features;
        for (int i = 1; i < behaviors.size(); i++) {
            newFeatures = newFeatures.union(behaviors.get(i).features);
        }
    }

    List<MemberDefinition> methods = new ArrayList<>();
    for (Node keyNode : descriptor.children()) {
        boolean isFunctionDefinition = keyNode.isMemberFunctionDef()
                || (keyNode.isStringKey() && keyNode.getFirstChild().isFunction());
        if (isFunctionDefinition) {
            methods.add(
                    new MemberDefinition(NodeUtil.getBestJSDocInfo(keyNode), keyNode, keyNode.getFirstChild()));
        }
    }

    return new PolymerClassDefinition(DefinitionType.ObjectLiteral, callNode, target, descriptor, classInfo,
            new MemberDefinition(ctorInfo, null, constructor), nativeBaseElement, allProperties, methods,
            behaviors, newFeatures);
}

From source file:com.facebook.buck.features.python.PythonUtil.java

public static ImmutableMap<Path, SourcePath> getModules(BuildTarget target, ActionGraphBuilder graphBuilder,
        SourcePathRuleFinder ruleFinder, SourcePathResolver pathResolver, PythonPlatform pythonPlatform,
        CxxPlatform cxxPlatform, String parameter, Path baseModule, SourceSortedSet items,
        PatternMatchedCollection<SourceSortedSet> platformItems,
        Optional<VersionMatchedCollection<SourceSortedSet>> versionItems,
        Optional<ImmutableMap<BuildTarget, Version>> versions) {
    return CxxGenruleDescription.fixupSourcePaths(graphBuilder, ruleFinder, cxxPlatform, ImmutableMap
            .<Path, SourcePath>builder()
            .putAll(PythonUtil.toModuleMap(target, pathResolver, parameter, baseModule,
                    ImmutableList.of(items)))
            .putAll(PythonUtil.toModuleMap(target, pathResolver,
                    "platform" + CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, parameter), baseModule,
                    Iterables.concat(platformItems.getMatchingValues(pythonPlatform.getFlavor().toString()),
                            platformItems.getMatchingValues(cxxPlatform.getFlavor().toString()))))
            .putAll(PythonUtil.toModuleMap(target, pathResolver,
                    "versioned" + CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, parameter), baseModule,
                    versions.isPresent() && versionItems.isPresent()
                            ? versionItems.get().getMatchingValues(versions.get())
                            : ImmutableList.of()))
            .build());/*w  w w. ja  v a  2 s  . c  o  m*/
}

From source file:com.cinchapi.concourse.server.http.EndpointContainer.java

/**
 * Given a {@link RoutingKey}, return the canonical namespace that should be
 * used as a prefix when referring to the container's classes.
 * //from w  w w . j a v a2  s  .c o m
 * <p>
 * The namespace is instrumental for properly constructing the URI where the
 * container's functionality lives.
 * </p>
 * 
 * @param id a {@link RoutingKey}
 * @return the canonical namespace to use when constructing the URI
 */
private static String getCanonicalNamespace(RoutingKey id) {
    String namespace;
    if (id.group.equals("com.cinchapi")) {
        if (id.module.equals("server")) {
            namespace = id.cls;
        } else {
            namespace = Strings.join('/', id.module, id.cls);
        }
    } else {
        namespace = Strings.join('/', id.group, id.module, id.cls);
    }
    namespace = namespace.replace("Router", "");
    namespace = namespace.replace("Index", "");
    namespace = namespace.replaceAll("\\.", "/");
    namespace = namespace.replaceAll("_", "/");
    namespace = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, namespace);
    namespace = namespace.replaceAll("/-", "/");
    namespace = Strings.ensureStartsWith(namespace, "/");
    namespace = Strings.ensureEndsWith(namespace, "/");
    return namespace;
}

From source file:org.ballerinalang.composer.service.workspace.tools.ModelGenerator.java

public static JsonObject getContext() {
    // Set alias for the classes
    alias.put("ImportNode", "ImportPackageNode");
    alias.put("RecordLiteralKeyValueNode", "RecordKeyValueNode");
    alias.put("XmlnsNode", "XMLNSDeclarationNode");
    alias.put("ArrayLiteralExprNode", "ArrayLiteralNode");
    alias.put("BinaryExprNode", "BinaryExpressionNode");
    alias.put("ConnectorInitExprNode", "ConnectorInitNode");
    alias.put("FieldBasedAccessExprNode", "FieldBasedAccessNode");
    alias.put("IndexBasedAccessExprNode", "IndexBasedAccessNode");
    alias.put("LambdaNode", "LambdaFunctionNode");
    alias.put("RecordLiteralExprNode", "RecordLiteralNode");
    alias.put("SimpleVariableRefNode", "SimpleVariableReferenceNode");
    alias.put("TernaryExprNode", "TernaryExpressionNode");
    alias.put("TypeCastExprNode", "TypeCastNode");
    alias.put("TypeConversionExprNode", "TypeConversionNode");
    alias.put("UnaryExprNode", "UnaryExpressionNode");
    alias.put("XmlAttributeNode", "XMLAttributeNode");
    alias.put("XmlCommentLiteralNode", "XMLCommentLiteralNode");
    alias.put("XmlElementLiteralNode", "XMLElementLiteralNode");
    alias.put("XmlPiLiteralNode", "XMLProcessingInstructionLiteralNode");
    alias.put("XmlQnameNode", "XMLQNameNode");
    alias.put("XmlQuotedStringNode", "XMLQuotedStringNode");
    alias.put("XmlTextLiteralNode", "XMLTextLiteralNode");
    alias.put("TryNode", "TryCatchFinallyNode");
    alias.put("VariableDefNode", "VariableDefinitionNode");
    alias.put("BuiltInRefTypeNode", "BuiltInReferenceTypeNode");
    alias.put("EnumeratorNode", "EnumNode");

    List<Class<?>> list = ModelGenerator.find("org.ballerinalang.model.tree");

    NodeKind[] nodeKinds = NodeKind.class.getEnumConstants();
    JsonObject nodes = new JsonObject();
    for (NodeKind node : nodeKinds) {
        String nodeKind = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, node.toString());
        String nodeClassName = nodeKind + "Node";
        try {//from   w w w .  j a  va 2s  . c o  m
            String actualClassName = (alias.get(nodeClassName) != null) ? alias.get(nodeClassName)
                    : nodeClassName;
            Class<?> clazz = list.stream()
                    .filter(nodeClass -> nodeClass.getSimpleName().equals(actualClassName)).findFirst().get();

            JsonObject nodeObj = new JsonObject();
            nodeObj.addProperty("kind", nodeKind);
            nodeObj.addProperty("name", nodeClassName);
            nodeObj.addProperty("fileName", CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, nodeClassName));
            JsonArray attr = new JsonArray();
            JsonArray bools = new JsonArray();
            JsonArray imports = new JsonArray();
            List<String> parents = Arrays.asList(clazz.getInterfaces()).stream()
                    .map(parent -> parent.getSimpleName()).collect(Collectors.toList());

            // tag object with supper type
            if (parents.contains("StatementNode")) {
                nodeObj.addProperty("isStatement", true);
                JsonObject imp = new JsonObject();
                imp.addProperty("returnType", "StatementNode");
                imp.addProperty("returnTypeFile", "statement-node");
                imports.add(imp);
            } else {
                nodeObj.addProperty("isStatement", false);
            }

            if (parents.contains("ExpressionNode")) {
                nodeObj.addProperty("isExpression", true);
                JsonObject imp = new JsonObject();
                imp.addProperty("returnType", "ExpressionNode");
                imp.addProperty("returnTypeFile", "expression-node");
                imports.add(imp);
            } else {
                nodeObj.addProperty("isExpression", false);
            }

            if (!parents.contains("StatementNode") && !parents.contains("ExpressionNode")) {
                JsonObject imp = new JsonObject();
                imp.addProperty("returnType", "Node");
                imp.addProperty("returnTypeFile", "node");
                imports.add(imp);
            }

            Method[] methods = clazz.getMethods();
            for (Method m : methods) {
                String methodName = m.getName();
                if ("getKind".equals(methodName) || "getWS".equals(methodName)
                        || "getPosition".equals(methodName)) {
                    continue;
                }
                if (methodName.startsWith("get")) {
                    JsonObject attribute = new JsonObject();
                    JsonObject imp = new JsonObject();
                    attribute.addProperty("property", toJsonName(m.getName(), 3));
                    attribute.addProperty("methodSuffix", m.getName().substring(3));
                    attribute.addProperty("list", List.class.isAssignableFrom(m.getReturnType()));
                    attribute.addProperty("isNode", Node.class.isAssignableFrom(m.getReturnType()));
                    if (Node.class.isAssignableFrom(m.getReturnType())) {
                        String returnClass = m.getReturnType().getSimpleName();
                        if (alias.containsValue(m.getReturnType().getSimpleName())) {
                            returnClass = getKindForAliasClass(m.getReturnType().getSimpleName());
                        }
                        imp.addProperty("returnType", returnClass);
                        attribute.addProperty("returnType", returnClass);
                        imp.addProperty("returnTypeFile",
                                CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, returnClass));
                        if (!imports.contains(imp)) {
                            imports.add(imp);
                        }
                    }
                    attr.add(attribute);
                }
                if (methodName.startsWith("is")) {
                    JsonObject attribute = new JsonObject();
                    JsonObject imp = new JsonObject();
                    attribute.addProperty("property", toJsonName(m.getName(), 2));
                    attribute.addProperty("methodSuffix", m.getName().substring(2));
                    attribute.addProperty("list", List.class.isAssignableFrom(m.getReturnType()));
                    attribute.addProperty("isNode", Node.class.isAssignableFrom(m.getReturnType()));
                    if (Node.class.isAssignableFrom(m.getReturnType())) {
                        String returnClass = m.getReturnType().getSimpleName();
                        if (alias.containsValue(m.getReturnType().getSimpleName())) {
                            returnClass = getKindForAliasClass(m.getReturnType().getSimpleName());
                        }
                        imp.addProperty("returnType", returnClass);
                        attribute.addProperty("returnType", returnClass);
                        imp.addProperty("returnTypeFile",
                                CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, returnClass));
                        if (!imports.contains(imp)) {
                            imports.add(imp);
                        }
                    }
                    bools.add(attribute);
                }
            }
            nodeObj.add("attributes", attr);
            nodeObj.add("bools", bools);
            nodeObj.add("imports", imports);
            nodes.add(nodeClassName, nodeObj);
        } catch (NoSuchElementException e) {
            out.println("alias.put(\"" + nodeClassName + "\", \"\");");
        }
    }
    out.println(nodes);
    return nodes;
}