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.facebook.buck.cxx.CxxGenruleDescription.java

@Override
protected MacroHandler getMacroHandlerForParseTimeDeps() {
    ImmutableMap.Builder<String, MacroExpander> macros = ImmutableMap.builder();
    macros.put("exe", new ExecutableMacroExpander());
    macros.put("location", new LocationMacroExpander());
    macros.put("location-platform", new LocationMacroExpander());
    macros.put("platform-name", new StringExpander(""));
    macros.put("cc", new CxxPlatformParseTimeDepsExpander(cxxPlatforms));
    macros.put("cxx", new CxxPlatformParseTimeDepsExpander(cxxPlatforms));
    macros.put("cflags", new StringExpander(""));
    macros.put("cxxflags", new StringExpander(""));
    macros.put("cppflags", new ParseTimeDepsExpander(Filter.NONE));
    macros.put("cxxppflags", new ParseTimeDepsExpander(Filter.NONE));
    macros.put("solibs", new ParseTimeDepsExpander(Filter.NONE));
    macros.put("ld", new CxxPlatformParseTimeDepsExpander(cxxPlatforms));
    for (Linker.LinkableDepType style : Linker.LinkableDepType.values()) {
        for (Filter filter : Filter.values()) {
            macros.put(String.format("ldflags-%s%s",
                    CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, style.toString()),
                    filter == Filter.PARAM ? "-filter" : ""), new ParseTimeDepsExpander(filter));
        }/*from  w w  w.ja v  a  2 s.c  om*/
    }
    return new MacroHandler(macros.build());
}

From source file:com.geemvc.taglib.GeemvcTagSupport.java

protected String toElementId(String name, String idSuffix) {
    StringBuilder id = new StringBuilder(ELEMENT_ID_PREFIX).append(CaseFormat.UPPER_CAMEL
            .to(CaseFormat.LOWER_HYPHEN, name).replace(Char.SQUARE_BRACKET_OPEN, Char.HYPHEN)
            .replace(Char.SQUARE_BRACKET_CLOSE, Char.HYPHEN).replace(Char.DOT, Char.HYPHEN)
            .replace(Char.SPACE, Char.HYPHEN).replace(Char.UNDERSCORE, Char.HYPHEN)
            .replace(Str.HYPHEN_2x, Str.HYPHEN));

    if (id.charAt(id.length() - 1) == Char.HYPHEN)
        id.deleteCharAt(id.length() - 1);

    if (!Str.isEmpty(idSuffix)) {
        id.append(Char.HYPHEN)//from  ww  w  . j av  a 2 s  .  c  om
                .append(idSuffix.toLowerCase().replace(Char.SQUARE_BRACKET_OPEN, Char.HYPHEN)
                        .replace(Char.SQUARE_BRACKET_CLOSE, Char.HYPHEN).replace(Char.DOT, Char.HYPHEN)
                        .replace(Char.SPACE, Char.HYPHEN).replace(Char.UNDERSCORE, Char.HYPHEN)
                        .replace(Str.HYPHEN_2x, Str.HYPHEN));
    }

    if (id.charAt(id.length() - 1) == Char.HYPHEN)
        id.deleteCharAt(id.length() - 1);

    return id.toString();
}

From source file:org.apache.brooklyn.entity.group.SshCommandMembershipTrackingPolicy.java

@SuppressWarnings("unchecked")
public void execute(Entity target, String command, String type, String memberId) {
    if (Entities.isNoLongerManaged(target))
        return;/*from  ww w  . ja v a2  s. com*/
    Lifecycle state = target.getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    if (state == Lifecycle.STOPPING || state == Lifecycle.STOPPED)
        return;

    Collection<? extends Location> locations = Locations.getLocationsCheckingAncestors(target.getLocations(),
            target);
    Maybe<SshMachineLocation> machine = Machines.findUniqueMachineLocation(locations, SshMachineLocation.class);
    if (machine.isAbsentOrNull()) {
        LOG.debug("No machine available to execute command");
        return;
    }

    LOG.info("Executing command on {}: {}", machine.get(), command);
    String executionDir = config().get(EXECUTION_DIR);
    String sshCommand = SshCommandSensor.makeCommandExecutingInDirectory(command, executionDir,
            (EntityInternal) target);

    // Set things from the entities defined shell environment, overriding with our config
    Map<String, Object> env = MutableMap.of();
    env.putAll(MutableMap.copyOf(entity.config().get(BrooklynConfigKeys.SHELL_ENVIRONMENT)));
    env.putAll(MutableMap.copyOf(config().get(BrooklynConfigKeys.SHELL_ENVIRONMENT)));

    // Add variables describing this invocation
    env.put(EVENT_TYPE, type);
    env.put(MEMBER_ID, memberId);

    // Try to resolve the configuration in the env Map
    try {
        env = (Map<String, Object>) Tasks.resolveDeepValue(env, Object.class,
                ((EntityInternal) entity).getExecutionContext());
    } catch (InterruptedException | ExecutionException e) {
        throw Exceptions.propagate(e);
    }

    // Execute the command with the serialized environment strings
    ShellEnvironmentSerializer serializer = new ShellEnvironmentSerializer(getManagementContext());
    SshEffectorTasks.SshEffectorTaskFactory<String> task = SshEffectorTasks.ssh(sshCommand)
            .machine(machine.get()).requiringZeroAndReturningStdout()
            .summary("group-" + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, type))
            .environmentVariables(serializer.serialize(env));

    String output = DynamicTasks.submit(task.newTask(), target).getUnchecked();
    LOG.trace("Command returned: {}", output);
}

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

/**
 * @return The PolymerElement type string for a class definition.
 *///from w  w  w  .  j a  v a  2 s.  co  m
public static String getPolymerElementType(final PolymerClassDefinition cls) {
    String nativeElementName = cls.nativeBaseElement == null ? ""
            : CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, cls.nativeBaseElement);
    return SimpleFormat.format("Polymer%sElement", nativeElementName);
}

From source file:com.google.polymer.HtmlRenamer.java

private static void renameAllAttributeKeys(ImmutableMap<String, String> renameMap, Element element) {
    Attributes attributes = element.attributes();
    for (Attribute attribute : attributes) {
        String key = attribute.getKey();
        // Polymer events are referenced as strings. As a result they do not participate in renaming.
        // Additionally, it is not valid to have a Polymer property start with "on".
        if (!key.startsWith("on-")) {
            String renamedProperty = renameMap.get(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, key));
            if (renamedProperty != null) {
                attribute.setKey(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, renamedProperty));
            }//w  ww. jav  a 2s .com
        }
    }
}

From source file:com.attribyte.relay.wp.WPSupplier.java

@Override
public void init(final Properties props, final Optional<ByteString> savedState, final Logger logger)
        throws Exception {

    if (isInit.compareAndSet(false, true)) {

        this.logger = logger;

        logger.info("Initializing WP supplier...");

        final long siteId = Long.parseLong(props.getProperty("siteId", "0"));
        if (siteId < 1L) {
            throw new Exception("A 'siteId' must be specified");
        }/*w ww . ja v  a2 s . c  o  m*/

        final Set<String> cachedTaxonomies = ImmutableSet.of(TAG_TAXONOMY, CATEGORY_TAXONOMY);
        final Duration taxonomyCacheTimeout = Duration.ofMinutes(30); //TODO: Configure
        final Duration userCacheTimeout = Duration.ofMinutes(30); //TODO: Configure
        initPools(props, logger);
        this.db = new DB(defaultConnectionPool, siteId, cachedTaxonomies, taxonomyCacheTimeout,
                userCacheTimeout);

        Properties siteProps = new InitUtil("site.", props, false).getProperties();
        Site overrideSite = new Site(siteProps);
        this.site = this.db.selectSite().overrideWith(overrideSite);

        logger.info(
                String.format("Initialized site %d - %s", this.site.id, Strings.nullToEmpty(this.site.title)));

        if (savedState.isPresent()) {
            startMeta = PostMeta.fromBytes(savedState.get());
        } else {
            startMeta = PostMeta.ZERO;
        }

        this.selectSleepMillis = Integer.parseInt(props.getProperty("selectSleepMillis", "30000"));

        this.selectAll = props.getProperty("selectAll", "false").equalsIgnoreCase("true");
        if (this.selectAll) {
            this.stopId = this.db.selectMaxPostId();
        } else {
            this.stopId = 0L;
        }

        String supplyIdsFileStr = props.getProperty("supplyIdsFile", "");
        if (!supplyIdsFileStr.isEmpty()) {
            this.selectAll = true;
            File supplyIdsFile = new File(supplyIdsFileStr);
            logger.info(String.format("Using 'supplyIdsFile', '%s'", supplyIdsFile.getAbsolutePath()));
            this.supplyIds = Lists.newArrayListWithExpectedSize(1024);
            List<String> lines = Files.readLines(supplyIdsFile, Charsets.UTF_8);
            for (String line : lines) {
                line = line.trim();
                if (line.isEmpty() || line.startsWith("#")) {
                    continue;
                }
                Long id = Longs.tryParse(line);
                if (id != null) {
                    this.supplyIds.add(id);
                    logger.info(String.format("Adding supplied id, '%d'", id));
                }
            }

        } else {
            this.supplyIds = null;
        }

        this.maxSelected = Integer.parseInt(props.getProperty("maxSelected", "500"));

        String allowedStatusStr = props.getProperty("allowedStatus", "").trim();
        if (!allowedStatusStr.isEmpty()) {
            if (allowedStatusStr.equalsIgnoreCase("all")) {
                this.allowedStatus = ALL_STATUS;
            } else {
                this.allowedStatus = ImmutableSet
                        .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedStatusStr).stream()
                                .map(Post.Status::fromString).collect(Collectors.toSet()));
            }
        } else {
            this.allowedStatus = DEFAULT_ALLOWED_STATUS;
        }

        String allowedTypesStr = props.getProperty("allowedTypes", "").trim();
        if (!allowedStatusStr.isEmpty()) {
            this.allowedTypes = ImmutableSet
                    .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedTypesStr)).stream()
                    .map(Post.Type::fromString).collect(Collectors.toSet());
        } else {
            this.allowedTypes = DEFAULT_ALLOWED_TYPES;
        }

        String allowedPostMetaStr = props.getProperty("allowedPostMeta", "").trim();
        if (!allowedPostMetaStr.isEmpty()) {
            this.allowedPostMeta = ImmutableSet
                    .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedPostMetaStr));
        } else {
            this.allowedPostMeta = ImmutableSet.of();
        }

        String allowedImageMetaStr = props.getProperty("allowedImageMeta", "").trim();
        if (!allowedImageMetaStr.isEmpty()) {
            this.allowedImageMeta = ImmutableSet
                    .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedImageMetaStr));
        } else {
            this.allowedImageMeta = ImmutableSet.of();
        }

        String allowedUserMetaStr = props.getProperty("allowedUserMeta", "").trim();
        if (!allowedUserMetaStr.isEmpty()) {
            this.allowedUserMeta = ImmutableSet
                    .copyOf(Splitter.on(',').omitEmptyStrings().splitToList(allowedUserMetaStr));
        } else {
            this.allowedUserMeta = ImmutableSet.of();
        }

        String metaNameCaseFormat = props.getProperty("metaNameCaseFormat", "").trim().toLowerCase();
        switch (metaNameCaseFormat) {
        case "lower_camel":
            this.metaNameCaseFormat = CaseFormat.LOWER_CAMEL;
            break;
        case "lower_hyphen":
            this.metaNameCaseFormat = CaseFormat.LOWER_HYPHEN;
            break;
        case "upper_camel":
            this.metaNameCaseFormat = CaseFormat.UPPER_CAMEL;
            break;
        case "upper_underscore":
            this.metaNameCaseFormat = CaseFormat.UPPER_UNDERSCORE;
            break;
        default:
            this.metaNameCaseFormat = null;
        }

        this.excerptOutputField = props.getProperty("excerptOutputField", "summary").toLowerCase().trim();

        this.stopOnLostMessage = props.getProperty("stopOnLostMessage", "false").equalsIgnoreCase("true");

        this.logReplicationMessage = props.getProperty("logReplicationMessage", "false")
                .equalsIgnoreCase("true");

        this.originId = props.getProperty("originId", "");

        Properties dusterProps = new InitUtil("duster.", props, false).getProperties();
        if (dusterProps.size() > 0) {
            this.httpClient = new JettyClient();
            this.httpClient.init("http.", props, logger);
            this.dusterClient = new DusterClient(dusterProps, httpClient, logger);
            logger.info("Duster is enabled...");
        } else {
            logger.info("Duster is disabled...");
        }

        if (!props.getProperty("contentTransformer", "").trim().isEmpty()) {
            this.contentTransformer = (ContentTransformer) (Class
                    .forName(props.getProperty("contentTransformer")).newInstance());
            this.contentTransformer.init(props);
        } else if (props.getProperty("cleanShortcodes", "true").equalsIgnoreCase("true")) {
            this.contentTransformer = new ShortcodeCleaner();
        }

        if (!props.getProperty("postTransformer", "").trim().isEmpty()) {
            this.postTransformer = (PostTransformer) (Class.forName(props.getProperty("postTransformer"))
                    .newInstance());
            this.postTransformer.init(props);
        } else {
            this.postTransformer = null;
        }

        if (!props.getProperty("postFilter", "").trim().isEmpty()) {
            this.postFilter = (PostFilter) (Class.forName(props.getProperty("postFilter")).newInstance());
            this.postFilter.init(props);
        } else {
            this.postFilter = null;
        }

        String dbDir = props.getProperty("metadb.dir", "").trim();
        if (dbDir.isEmpty()) {
            this.metaDB = null;
        } else {
            logger.info(String.format("Initializing meta db, '%s'...", dbDir));
            File metaDir = new File(dbDir);
            if (!metaDir.exists()) {
                throw new Exception(String.format("The 'metadb.dir' must exist ('%s')", dbDir));
            }
            this.metaDB = new PostMetaDB(metaDir);
        }

        Long modifiedOffsetHours = Longs.tryParse(props.getProperty("modifiedOffsetHours", "0"));
        this.modifiedOffsetMillis = modifiedOffsetHours != null ? modifiedOffsetHours * 3600 * 1000L : 0L;
        if (this.modifiedOffsetMillis != 0L) {
            logger.info(String.format("Set modified select offset to %d millis", this.modifiedOffsetMillis));
        }

        this.replicateScheduledState = props.getProperty("replicateScheduledState", "true")
                .equalsIgnoreCase("true");
        this.replicatePendingState = props.getProperty("replicatePendingState", "false")
                .equalsIgnoreCase("true");

        logger.info("Initialized WP supplier...");

    }
}

From source file:com.cinchapi.concourse.importer.cli.ImportCli.java

/**
 * Given an alias (or fully qualified class name) attempt to load a "custom"
 * importer that is not already defined in the {@link #importers built-in}
 * collection.//w w  w. j  ava  2 s  .co m
 * 
 * @param alias a conventional alias (FileTypeImporter --> file-type) or a
 *            fully qualified class name
 * @return the {@link Class} that corresponds to the custom importer
 * @throws ClassNotFoundException
 */
@SuppressWarnings("unchecked")
private static Class<? extends Importer> getCustomImporterClass(String alias) throws ClassNotFoundException {
    try {
        return (Class<? extends Importer>) Class.forName(alias);
    } catch (ClassNotFoundException e) {
        // Attempt to determine the correct class name from the alias by
        // loading the server's classpath. For the record, this is hella
        // slow.
        Reflections.log = null; // turn off reflection logging
        Reflections reflections = new Reflections();
        char firstChar = alias.charAt(0);
        for (Class<? extends Importer> clazz : reflections.getSubTypesOf(Importer.class)) {
            String name = clazz.getSimpleName();
            if (name.length() == 0) { // Skip anonymous subclasses
                continue;
            }
            char nameFirstChar = name.charAt(0);
            if (!Modifier.isAbstract(clazz.getModifiers()) && (nameFirstChar == Character.toUpperCase(firstChar)
                    || nameFirstChar == Character.toLowerCase(firstChar))) {
                String expected = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, clazz.getSimpleName())
                        .replaceAll("-importer", "");
                if (alias.equals(expected)) {
                    return clazz;
                }
            }
        }
        throw e;
    }
}

From source file:com.jwebmp.core.htmlbuilder.javascript.JavaScriptPart.java

/**
 * Renders the fields (getDeclaredFields()) as a map of html attributes
 *
 * @return//from  ww w.j a v a  2 s .c  om
 */
public Map<String, String> toAttributes() {
    Map<String, String> map = new LinkedHashMap<>();

    Field[] fields = getClass().getDeclaredFields();
    for (Field field : fields) {
        if (Modifier.isFinal(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        field.setAccessible(true);
        try {
            Object result = field.get(this);
            if (result != null) {
                if (JavaScriptPart.class.isAssignableFrom(result.getClass())) {
                    map.put(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, field.getName()),
                            ((JavaScriptPart) result).toString(true));
                } else {
                    map.put(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, field.getName()),
                            result.toString());
                }
            }
        } catch (Exception e) {
            JavaScriptPart.log.log(Level.WARNING, "Cant format as attributes", e);
        }
    }
    return map;
}

From source file:brooklyn.util.flags.TypeCoercions.java

/**
 * Type coercion {@link Function function} for {@link Enum enums}.
 * <p>//from   ww  w  .j  ava2 s. c om
 * 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:com.facebook.buck.cxx.CxxGenruleDescription.java

private ImmutableMap<String, MacroReplacer> getMacroReplacersForTargetTranslation(BuildTarget target,
        CellPathResolver cellNames, TargetNodeTranslator translator) {
    BuildTargetPatternParser<?> buildTargetPatternParser = BuildTargetPatternParser
            .forBaseName(target.getBaseName());

    ImmutableMap.Builder<String, MacroReplacer> macros = ImmutableMap.builder();

    ImmutableList.of("exe", "location", "location-platform", "cppflags", "cxxppflags", "solibs")
            .forEach(name -> macros.put(name, new TargetTranslatorMacroReplacer(new AsIsMacroReplacer(name),
                    Filter.NONE, buildTargetPatternParser, cellNames, translator)));

    ImmutableList.of("platform-name", "cc", "cflags", "cxx", "cxxflags", "ld")
            .forEach(name -> macros.put(name, new AsIsMacroReplacer(name)));

    for (Linker.LinkableDepType style : Linker.LinkableDepType.values()) {
        for (Filter filter : Filter.values()) {
            String name = String.format("ldflags-%s%s",
                    CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, style.toString()),
                    filter == Filter.PARAM ? "-filter" : "");
            macros.put(name, new TargetTranslatorMacroReplacer(new AsIsMacroReplacer(name), filter,
                    buildTargetPatternParser, cellNames, translator));
        }/*from  ww w . j av  a  2s  .co  m*/
    }
    return macros.build();
}