com.smallchill.core.toolbox.Func.java Source code

Java tutorial

Introduction

Here is the source code for com.smallchill.core.toolbox.Func.java

Source

/**
 * Copyright (c) 2015-2016, Chill Zhuang  (smallchill@163.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.smallchill.core.toolbox;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.smallchill.common.vo.User;
import com.smallchill.core.constant.ConstCache;
import com.smallchill.core.constant.ConstConfig;
import com.smallchill.core.interfaces.ILoader;
import com.smallchill.core.plugins.dao.Blade;
import com.smallchill.core.toolbox.kit.CacheKit;
import com.smallchill.core.toolbox.kit.StrKit;
import com.smallchill.system.model.Dept;
import com.smallchill.system.model.Dict;
import com.smallchill.system.model.Parameter;
import com.smallchill.system.model.Role;

/**
 * ?
 */
public class Func {

    /**
     * ?<br>
     * ????<br>
     * 1. obj1 == null && obj2 == null; 2. obj1.equals(obj2)
     * 
     * @param obj1
     *            1
     * @param obj2
     *            2
     * @return ?
     */
    public static boolean equals(Object obj1, Object obj2) {
        return (obj1 != null) ? (obj1.equals(obj2)) : (obj2 == null);
    }

    /**
     * length?sizelength?????
     * 
     * @param obj
     *            
     * @return 
     */
    public static int length(Object obj) {
        if (obj == null) {
            return 0;
        }
        if (obj instanceof CharSequence) {
            return ((CharSequence) obj).length();
        }
        if (obj instanceof Collection) {
            return ((Collection<?>) obj).size();
        }
        if (obj instanceof Map) {
            return ((Map<?, ?>) obj).size();
        }

        int count;
        if (obj instanceof Iterator) {
            Iterator<?> iter = (Iterator<?>) obj;
            count = 0;
            while (iter.hasNext()) {
                count++;
                iter.next();
            }
            return count;
        }
        if (obj instanceof Enumeration) {
            Enumeration<?> enumeration = (Enumeration<?>) obj;
            count = 0;
            while (enumeration.hasMoreElements()) {
                count++;
                enumeration.nextElement();
            }
            return count;
        }
        if (obj.getClass().isArray() == true) {
            return Array.getLength(obj);
        }
        return -1;
    }

    /**
     * ??
     * 
     * @param obj
     *            
     * @param element
     *            
     * @return ??
     */
    public static boolean contains(Object obj, Object element) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof String) {
            if (element == null) {
                return false;
            }
            return ((String) obj).contains(element.toString());
        }
        if (obj instanceof Collection) {
            return ((Collection<?>) obj).contains(element);
        }
        if (obj instanceof Map) {
            return ((Map<?, ?>) obj).values().contains(element);
        }

        if (obj instanceof Iterator) {
            Iterator<?> iter = (Iterator<?>) obj;
            while (iter.hasNext()) {
                Object o = iter.next();
                if (equals(o, element)) {
                    return true;
                }
            }
            return false;
        }
        if (obj instanceof Enumeration) {
            Enumeration<?> enumeration = (Enumeration<?>) obj;
            while (enumeration.hasMoreElements()) {
                Object o = enumeration.nextElement();
                if (equals(o, element)) {
                    return true;
                }
            }
            return false;
        }
        if (obj.getClass().isArray() == true) {
            int len = Array.getLength(obj);
            for (int i = 0; i < len; i++) {
                Object o = Array.get(obj, i);
                if (equals(o, element)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * ?
     * 
     * @param obj
     *            String,List,Map,Object[],int[],long[]
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static boolean isEmpty(Object o) {
        if (o == null) {
            return true;
        }
        if (o instanceof String) {
            if (o.toString().trim().equals("")) {
                return true;
            }
        } else if (o instanceof List) {
            if (((List) o).size() == 0) {
                return true;
            }
        } else if (o instanceof Map) {
            if (((Map) o).size() == 0) {
                return true;
            }
        } else if (o instanceof Set) {
            if (((Set) o).size() == 0) {
                return true;
            }
        } else if (o instanceof Object[]) {
            if (((Object[]) o).length == 0) {
                return true;
            }
        } else if (o instanceof int[]) {
            if (((int[]) o).length == 0) {
                return true;
            }
        } else if (o instanceof long[]) {
            if (((long[]) o).length == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * ? Empty Object
     * 
     * @param os
     *            
     * @return
     */
    public static boolean isOneEmpty(Object... os) {
        for (Object o : os) {
            if (isEmpty(o)) {
                return true;
            }
        }
        return false;
    }

    /**
     * ? Empty Object
     * 
     * @param os
     * @return
     */
    public static boolean isAllEmpty(Object... os) {
        for (Object o : os) {
            if (!isEmpty(o)) {
                return false;
            }
        }
        return true;
    }

    /**
     * ?
     * 
     * @param obj
     * @return
     */
    public static boolean isNum(Object obj) {
        try {
            Integer.parseInt(obj.toString());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * , 
     * 
     * @param str
     * @return
     */
    public static Object getValue(Object str, Object defaultValue) {
        if (isEmpty(str)) {
            return defaultValue;
        }
        return str;
    }

    /**
     * ? ??
     * 
     * @param str
     * @return
     */
    public static String format(Object str) {
        if (null == str) {
            return "";
        }
        return str.toString().trim();
    }

    /**
     * ?
     * 
     * @param template
     *            ?? {} 
     * @param values
     *            ?
     * @return ??
     */
    public static String format(String template, Object... values) {
        return StrKit.format(template, values);
    }

    /**
     * ?
     * 
     * @param template
     *            ?? {key} 
     * @param map
     *            ?
     * @return ??
     */
    public static String format(String template, Map<?, ?> map) {
        return StrKit.format(template, map);
    }

    /**
     * ->int
     * 
     * @param obj
     * @return
     */
    public static int toInt(Object obj) {
        return Integer.parseInt(obj.toString());
    }

    /**
     * ->int
     * 
     * @param obj
     * @param defaultValue
     * @return
     */
    public static int toInt(Object obj, int defaultValue) {
        try {
            if (isEmpty(obj)) {
                return defaultValue;
            }
            return toInt(obj);
        } catch (Exception ex) {
            return defaultValue;
        }
    }

    /**
     * ->long
     * 
     * @param obj
     * @return
     */
    public static long toLong(Object obj) {
        return Long.parseLong(obj.toString());
    }

    /**
     * ->long
     * 
     * @param obj
     * @param defaultValue
     * @return
     */
    public static long toLong(Object obj, long defaultValue) {
        try {
            if (isEmpty(obj)) {
                return defaultValue;
            }
            return toLong(obj);
        } catch (Exception ex) {
            return defaultValue;
        }
    }

    /**
     * ->double
     * 
     * @param obj
     * @return
     */
    public static double toDouble(Object obj) {
        return Double.parseDouble(obj.toString());
    }

    public static String encodeUrl(String url) {
        try {
            url = isEmpty(url) ? "" : url;
            url = URLEncoder.encode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }

    public static String decodeUrl(String url) {
        try {
            url = isEmpty(url) ? "" : url;
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * mapkey?
     * 
     * @param map
     * @return Map<String,Object>
     */
    public static Map<String, Object> caseInsensitiveMap(Map<String, Object> map) {
        Map<String, Object> tempMap = new HashMap<>();
        for (String key : map.keySet()) {
            tempMap.put(key.toLowerCase(), map.get(key));
        }
        return tempMap;
    }

    /**
      * ?map?
      *
      * @param <K> Key
      * @param <V> Value
      * @param map ??
      * @return 
      */
    public static <K, V> V getFirstOrNull(Map<K, V> map) {
        V obj = null;
        for (Entry<K, V> entry : map.entrySet()) {
            obj = entry.getValue();
            if (obj != null) {
                break;
            }
        }
        return obj;
    }

    /**
     * StringBuilder
     * 
     * @return StringBuilder
     */
    public static StringBuilder builder(String... strs) {
        final StringBuilder sb = new StringBuilder();
        for (String str : strs) {
            sb.append(str);
        }
        return sb;
    }

    /**
     * StringBuilder
     * 
     * @return StringBuilder
     */
    public static void builder(StringBuilder sb, String... strs) {
        for (String str : strs) {
            sb.append(str);
        }
    }

    /**
     * ??: ?sql?? ?,?,?
     * 
     * @param size
     * @return String
     */
    public static String sqlHolder(int size) {
        String[] paras = new String[size];
        Arrays.fill(paras, "?");
        return StringUtils.join(paras, ',');
    }

    /**
     * ?sql??list
     * 
     * @param ids
     * @return List<Object>
     */
    public static List<Object> listHolder(String ids) {
        final List<Object> parameters = new ArrayList<Object>();
        String[] idarr = ids.split(",");
        for (int i = 0; i < idarr.length; i++) {
            parameters.add(idarr[i]);
        }
        return parameters;
    }

    /**
     * ?
     * @param code ?
     * @param num  ??
     * @return
     */
    public static String getDictName(final Object code, final Object num) {
        Dict dict = CacheKit.get(ConstCache.DICT_CACHE, "getDictName_" + code + "_" + num, new ILoader() {
            @Override
            public Object load() {
                return Blade.create(Dict.class).findFirstBy("code=#{code} and num=#{num}",
                        Record.create().set("code", code).set("num", num));
            }
        });
        if (null == dict) {
            return "";
        }
        return dict.getName();
    }

    /**
     * ???
     * @param roleId id
     * @return
     */
    public static String getRoleName(final Object roleIds) {
        if (isEmpty(roleIds)) {
            return "";
        }
        final String[] roleIdArr = roleIds.toString().split(",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < roleIdArr.length; i++) {
            final String roleId = roleIdArr[i];
            Role role = CacheKit.get(ConstCache.DICT_CACHE, "getRoleName" + "_" + roleId, new ILoader() {
                @Override
                public Object load() {
                    return Blade.create(Role.class).findById(roleId);
                }
            });
            sb.append(role.getName()).append(",");
        }
        return StrKit.removeSuffix(sb.toString(), ",");
    }

    /**
     * ???
     * @param userId id
     * @return
     */
    public static String getUserName(final Object userId) {
        User user = CacheKit.get(ConstCache.DICT_CACHE, "getUserName" + "_" + userId, new ILoader() {
            @Override
            public Object load() {
                return Blade.create(User.class).findById(userId);
            }
        });
        if (null == user) {
            return "";
        }
        return user.getName();
    }

    /**
     * ???
     * @param deptIds id?
     * @return
     */
    public static String getDeptName(final Object deptIds) {
        if (isEmpty(deptIds)) {
            return "";
        }
        final String[] deptIdArr = deptIds.toString().split(",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < deptIdArr.length; i++) {
            final String deptId = deptIdArr[i];
            Dept dept = CacheKit.get(ConstCache.DICT_CACHE, "getDeptName" + "_" + deptId, new ILoader() {
                @Override
                public Object load() {
                    return Blade.create(Dept.class).findById(deptId);
                }
            });
            sb.append(dept.getSimplename()).append(",");
        }
        return StrKit.removeSuffix(sb.toString(), ",");
    }

    /**   
     * ???
     * @param code ??
     * @return String
    */
    public static String getParamByCode(String code) {
        Parameter param = Blade.create(Parameter.class).findFirstBy("code = #{code} and status = 1",
                Record.create().set("code", code));
        return param.getPara();
    }

    public static boolean isOracle() {
        return (ConstConfig.dbType.equals("oracle"));
    }

    public static boolean isMySql() {
        return (ConstConfig.dbType.equals("mysql"));
    }

}