com.shenit.commons.utils.ShenStrings.java Source code

Java tutorial

Introduction

Here is the source code for com.shenit.commons.utils.ShenStrings.java

Source

/***********************************************************************************************************************
 * 
 * Copyright (C) 2013, 2014 by huanju (http://www.yy.com)
 * http://www.yy.com/
 *
 ***********************************************************************************************************************
 *
 * 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.shenit.commons.utils;

import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 
 * @author jiangnan
 *
 */
public final class ShenStrings {
    private static final Logger LOG = LoggerFactory.getLogger(ShenStrings.class);

    public static final String SPACE = " ";
    public static final String DELIMITER_COMMA = ",";
    public static final String DELIMITER_DOT = ".";
    public static final String DELIMITER_DASH = "-";
    public static final String DELIMITER_UNDERSCORE = "_";
    public static final String LIKE_PATTERN = "%";
    public static final String NULL = "null";
    public static final String FALSE = "false";
    public static final String COLON = ":";
    public static final String SEMICOLON = ";";
    public static final String LINE_SEPERATOR = "\r\n";

    public static final String ASTAR = "*";

    /**
    * ???replacement.
    * @param source 
    * @param replacement ?
    * @param patterns ??
    * @return
    */
    public static String replaceAll(String source, String replacement, String... patterns) {
        for (String pattern : patterns) {
            source = source.replaceAll(pattern, replacement);
        }
        return source;
    }

    /**
     * ??
     * @param source
     * @param suffix
     * @return
     */
    public static String appendIfNotEndsWith(String source, String suffix) {
        if (StringUtils.isEmpty(source))
            return suffix;
        else if (source.endsWith(suffix) || StringUtils.isEmpty(suffix))
            return source;
        return source + suffix;
    }

    /**
     * To camel format
     * @param str
     * @return
     */
    public static String camel(String str) {
        if (str.indexOf(DELIMITER_UNDERSCORE) < 0)
            return str;
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, str(str));
    }

    /**
     * To underscore format
     * @param str
     * @return
     */
    public static String underscore(String str) {
        if (str.indexOf(DELIMITER_UNDERSCORE) > 0)
            return str;
        return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, str(str));
    }

    /**
     * ?
     * @param val
     * @return
     */
    public static String str(Object val) {
        return val == null ? StringUtils.EMPTY : val.toString();
    }

    /**
     * ?IP
     * @param str
     * @return
     */
    public static boolean isIp(String str) {
        if (str.indexOf(DELIMITER_DOT) < 0)
            return false;
        String[] secs = str.split(DELIMITER_DOT);
        //we don't support IPv6 yet!!
        if (secs.length != 4)
            return false;
        boolean isIp = true;
        int ipSec;
        for (String sec : secs) {
            if (StringUtils.isNumeric(sec)) {
                ipSec = Integer.parseInt(sec);
                isIp = !ValidationUtils.in(ipSec, 0, 255);
            }
            if (!isIp)
                break;
        }
        return isIp;
    }

    /**
     * ?UTF8??
     * @param source
     * @return
     */
    public static byte[] bytes(String source) {
        return bytes(source, null);
    }

    /**
     * ?
     * @param source
     * @param enc
     * @return
     */
    public static byte[] bytes(String source, String enc) {
        if (source == null)
            return null;
        try {
            return source.getBytes(DataUtils.first(enc, HttpUtils.ENC_UTF8));
        } catch (UnsupportedEncodingException e) {
        }
        return null;
    }

    /**
     * @param string
     * @param wrapping
     * @return
     */
    public static String wrap(String string, String wrapping) {
        if (string == null)
            return null;
        return StringUtils.isEmpty(string) ? (wrapping + wrapping) : (wrapping + string + wrapping);
    }

    /**
     * ??
     * @param str
     * @param search
     * @return
     */
    public static int indexOf(String str, String search) {
        return str == null ? -1 : str.indexOf(search);
    }

    /**
     * ?
     * @param str
     * @param search
     * @return
     */
    public static boolean has(String str, String search) {
        return indexOf(str, search) > -1;
    }

    /**
     * ?
     * @param str
     * @return
     */
    public static boolean isDigital(String str) {
        if (StringUtils.isEmpty(str))
            return false;
        boolean result = true;
        try {
            Double.parseDouble(str);
        } catch (Throwable t) {
            result = false;
        }
        return result;
    }

    /**
     * Split a string with delimiter
     * @param str
     * @param delimiter
     * @return
     */
    public static String[] split(String str, String delimiter) {
        return StringUtils.isEmpty(str) ? null : str.split(delimiter);
    }

    /**
     * Split a string with delimiter
     * @param str
     * @param delimiter
     * @return
     */
    public static List<String> splitAsArray(String str, String delimiter) {
        return Arrays.asList(split(str, delimiter));
    }

    /**
     * ?IP:Port?ip/port?pair <br/>
     * <strong>?</strong>???
     * 
     * @param addresStr ?;eg.: localhost:1234;localhost:4321
     * @return Pair.left:ip Pair.right:port
     */
    public static List<Pair<String, Integer>> parseNetAddresses(String addresStr) {
        List<Pair<String, Integer>> pairs = new ArrayList<>();

        String[] addres = split(addresStr, SEMICOLON);
        if (addres == null)
            return pairs;

        // ????
        for (String addr : addres) {
            String[] pair = split(addr, COLON);
            String ip = pair[0];
            int port = Integer.parseInt(pair[1]);
            pairs.add(Pair.of(ip, port));
        }

        return pairs;
    }

    /**
     * Substring between given strings
     * @param str String to operate
     * @param startEnd ?
     * @return
     */
    public static String between(String str, String... startEnd) {
        return between(str, startEnd.length > 0 ? indexOf(str, startEnd[0]) + startEnd[0].length() : -1,
                startEnd.length > 1 ? indexOf(str, startEnd[1]) : -1);
    }

    /**
     * Join with seperators.
     * @param objs
     * @return
     */
    public static String joinWithSeperator(Object... objs) {
        if (ShenArrays.isEmpty(objs))
            return org.apache.commons.lang3.StringUtils.EMPTY;
        if (objs.length == 1)
            return str(objs[0]);
        String seperator = str(objs[objs.length - 1]);
        objs = ArrayUtils.remove(objs, objs.length - 1);
        List<String> items = Arrays.stream(objs).filter(item -> item != null).map(item -> {
            if (item.getClass().isArray()) {
                Object[] newObjs = Arrays.copyOf((Object[]) item, len(item) + 1);
                newObjs[newObjs.length - 1] = seperator;
                return joinWithSeperator(newObjs);
            } else {
                return str(item);
            }

        }).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
        return joinAll(items, seperator);
    }

    /**
     * ?
     * @param str
     * @return
     */
    public static int len(Object str) {
        return StringUtils.length(str(str));
    }

    /**
     * join with character separator
     * @param list
     * @param separator
     * @return
     */
    public static String joinAll(List<?> list, char separator) {
        return joinAll(list, String.valueOf(separator));
    }

    /**
     * Joins list of string items to a single string, where items are separated
     * with a defined separator.
     *
     * @param list      to join into string
     * @param separator to be used between elements
     * @return items joined into a single string
     */
    public static String joinAll(List<?> list, String separator) {

        if (separator == null || separator.toString().equalsIgnoreCase("")) {
            throw new IllegalArgumentException("Missing separator!");
        }

        String output = "";

        if (list != null && list.size() > 0) {
            for (int i = 1; i <= list.size(); i++) {
                output = output + list.get(i - 1);
                if (i < list.size()) {
                    output = output + separator;
                }
            }
        }

        return output;
    }

    /**
     * Get string fragment between two index
     * @param str String to operate
     * @param startEnd Start and end index
     * @return
     */
    public static String between(String str, int... startEnd) {
        if (StringUtils.isEmpty(str)) {
            LOG.warn("[between] Illegal input");
            return null;
        }
        if (startEnd.length > 0 && startEnd[0] > -1)
            str = str.substring(startEnd[0]);
        if (startEnd.length > 1 && startEnd[1] > -1)
            str = str.substring(0, startEnd[1] - (startEnd[0] < 0 ? 0 : startEnd[0]));
        return str;
    }
}