com.github.tomregan.utilities.StringUtilities.java Source code

Java tutorial

Introduction

Here is the source code for com.github.tomregan.utilities.StringUtilities.java

Source

/*
 * Copyright 2013 Tom Regan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.tomregan.utilities;

import org.apache.commons.lang.WordUtils;

import static com.google.common.base.CaseFormat.*;

/**
 * Utility methods for converting user input to Java-esque identifiers.
 */
public class StringUtilities {
    private boolean isUpperCamelCase(String result) {
        return result.matches("[A-Z]+[a-z]+([A-Z]+[a-z]*)*");
    }

    private boolean isLowerCamelCase(String result) {
        return result.matches("[a-z]+([A-Z]+[a-z]+)*");
    }

    private boolean isValidJavaIdentifier(char[] characters) {
        for (char character : characters) {
            if (!Character.isJavaIdentifierPart(character)) {
                return false;
            }
        }
        return true;
    }

    boolean isValidJavaIdentifier(final String identifier) {
        return Character.isJavaIdentifierStart(identifier.charAt(0))
                && isValidJavaIdentifier(identifier.toCharArray());
    }

    public String toCamelCase(String string) {
        String result;
        String trim = string.trim();
        if (isUpperCamelCase(trim)) {
            result = trim;
        } else if (isLowerCamelCase(trim)) {
            result = WordUtils.capitalize(trim);
        } else {
            //This is a deliberate guess to pick the right conversion
            result = trim.contains("-") ? LOWER_HYPHEN.to(UPPER_CAMEL, trim)
                    : UPPER_UNDERSCORE.to(UPPER_CAMEL, trim);
        }
        return result;
    }

    public String toUpperUnderscore(String string) {
        String result = string.trim();
        return result.contains("-") ? LOWER_HYPHEN.to(UPPER_UNDERSCORE, result)
                : UPPER_CAMEL.to(UPPER_UNDERSCORE, result);
    }
}