CommonUtils.java 16.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
package com.cnlive.shenhe.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base32;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Administrator
 */
public class CommonUtils {
    private static char[] md5Chars = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'
    };

    public static boolean isNull(Object object) {
        if (object == null) {
            return true;
        }
        return false;
    }

    public static boolean isNotNull(Object object) {
        if (object == null) {
            return false;
        }
        return true;
    }

    public static Timestamp getCurrentTime() {
        return new Timestamp(System.currentTimeMillis());
    }

    /**
     * 获取当前时间加上一个时间(分钟算)
     */
    public static Timestamp getAddTime(Integer addTime) {
        return new Timestamp(System.currentTimeMillis() + addTime * 60 * 1000);
    }

    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str.trim())) {
            return true;
        }
        return false;
    }

    public static boolean isNotEmpty(String str) {
        if (str != null && !"".equals(str.trim())) {
            return true;
        }
        return false;
    }

    public static String formatDate(Date data, String pattern) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        String format = dateFormat.format(data);
        return format;
    }

    /**
     * 解析命令字符串
     *
     * @param command
     * @return
     * @author fan xiao chun
     * @date 2016年9月5日
     */
    public static Map<String, String> parseCommand(String command) {
        Map<String, String> cmdMap = new HashMap<String, String>();
        String[] items = command.split("&");
        for (String item : items) {
            int splitIndex = item.indexOf("=");
            String key = item.substring(0, splitIndex);
            String value = item.substring(splitIndex + 1);
            cmdMap.put(key, value);
        }
        return cmdMap;
    }

    /**
     * 四舍五入
     *
     * @param num
     * @param digit
     * @return
     * @author fan xiao chun
     * @date 2016年9月21日
     */
    public static float getRound(float num, int digit) {
        BigDecimal b = new BigDecimal(num);
        float f1 = b.setScale(digit, BigDecimal.ROUND_HALF_UP).floatValue();
        return f1;
    }

    /**
     * 获取当前时间戳
     *
     * @return
     */
    public static long getCurrentMillisecond() {
        return System.currentTimeMillis();
    }

    /**
     * 按指定格式解析日期
     *
     * @param date
     * @param pattern
     * @return
     * @throws ParseException
     */
    public static Timestamp parseDate(String date, String pattern) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        return new Timestamp(dateFormat.parse(date).getTime());
    }

    /**
     * 获取本机ip
     *
     * @return
     * @date 2017年3月12日
     * @author fanxiaochun
     */
    public static String getLocalIp() {
        try {
            if (isWindowsOS()) {
                return InetAddress.getLocalHost().getHostAddress();
            } else {
                return getLinuxLocalIp();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static String decodeBase32(String str) {
        Base32 base32 = new Base32();
        try {
            return new String(base32.decode(str.getBytes("utf-8")), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String encodeBase32(String str) {
        Base32 base32 = new Base32();
        try {
            return base32.encodeAsString(str.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String toHexString(byte[] b) {
        char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[b[i] & 0x0f]);
        }
        return sb.toString();
    }

    public static String Bit32(String SourceString) {
        try {

            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(SourceString.getBytes());
            byte[] messageDigest = digest.digest();
            return toHexString(messageDigest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String Bit16(String SourceString) {
        try {
            return Bit32(SourceString).substring(8, 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static int getShortSide(String res) {
        String[] resArr = res.split("x");
        int width = Integer.parseInt(resArr[0]);
        int height = Integer.parseInt(resArr[1]);

        if (width > height) {
            return height;
        }

        return width;
    }

    /**
     * 获取短边长度
     *
     * @param width
     * @param height
     * @return
     */
    public static int getShortSide(int width, int height) {
        if (width > height) {
            return height;
        }

        return width;
    }

    /**
     * md5加密
     *
     * @param str
     * @return
     */
    public static String md5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(str.getBytes("UTF-8"));
        byte[] digest = md5.digest();
        char[] chars = toHexChars(digest);
        return new String(chars);
    }

    private static char[] toHexChars(byte[] digest) {
        char[] chars = new char[digest.length * 2];
        int i = 0;
        byte[] abyte0 = digest;
        int j = abyte0.length;
        for (int k = 0; k < j; k++) {
            byte b = abyte0[k];
            char c0 = md5Chars[(b & 0xf0) >> 4];
            chars[i++] = c0;
            char c1 = md5Chars[b & 0xf];
            chars[i++] = c1;
        }

        return chars;
    }


    /**
     * 判断操作系统是否是Windows
     *
     * @return
     */
    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    /**
     * 获取本地Host名称
     */
    public static String getLocalHostName() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostName();
    }

    /**
     * 获取Linux下的IP地址
     *
     * @return IP地址
     * @throws SocketException
     */
    private static String getLinuxLocalIp() throws SocketException {
        String ip = "";
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
            NetworkInterface intf = en.nextElement();
            String name = intf.getName();
            if (!name.contains("docker") && !name.contains("lo")) {
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipaddress = inetAddress.getHostAddress().toString();
                        if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                            ip = ipaddress;
                        }
                    }
                }
            }
        }

        return ip;
    }


    /**
     * 文件大小格式化
     *
     * @param bSize b单位
     * @return
     */
    public static String sizeFormat(long bSize) {
        String size = "";
        float kbSize = bSize / 1024.0f;
        if (kbSize >= 1.0f) {
            float mbSize = kbSize / 1024.0f;
            if (mbSize >= 1.0f) {
                float gbSize = mbSize / 1024.0f;
                if (gbSize >= 1.0f) {
                    size = getRound(gbSize, 2) + "G";
                } else {
                    size = getRound(mbSize, 2) + "M";
                }
            } else {
                size = getRound(kbSize, 2) + "K";
            }
        } else {
            size = getRound(bSize, 2) + "B";
        }
        return size;
    }

    /**
     * 相比返回最大值
     *
     * @param width
     * @param height
     * @return
     */
    public static int max(int width, int height) {
        if (width > height) {
            return width;
        }
        return height;
    }

    /**
     * 将秒转换成固定格式时分秒输出
     *
     * @param second
     * @param separator
     * @return
     * @author fan xiao chun
     */

    public static String secondTimeFormat(long second, String separator) {
        int secondCardinal = 1;
        int minuteCardinal = secondCardinal * 60;
        int hourCardinal = minuteCardinal * 60;

        String hourStr = null;
        String minuteStr = null;
        String secondStr = null;

        long hour = 0;
        long minute = 0;
        String timeStr = null;

        if ((hour = second / hourCardinal) > 0) {
            second = second - hourCardinal * hour;
        }
        if ((minute = second / minuteCardinal) > 0) {
            second = second - minuteCardinal * minute;
        }

        hourStr = (String.valueOf(hour).length() == 1) ? "0" + hour : hour + "";
        minuteStr = (String.valueOf(minute).length() == 1) ? "0" + minute : minute + "";
        secondStr = (String.valueOf(second).length() == 1) ? "0" + second : second + "";
        return hourStr + separator + minuteStr + separator + secondStr;
    }

    /**
     * 将固定格式时分秒输出转换成秒
     *
     * @param timeStr
     * @param separator
     * @return
     * @author fan xiao chun
     */
    public static long timeStrToSecond(String timeStr, String separator) {
        int secondCardinal = 1;
        int minuteCardinal = secondCardinal * 60;
        int hourCardinal = minuteCardinal * 60;

        String[] timeArr = timeStr.split(separator);
        long hour = Long.parseLong(timeArr[0]);
        long minute = Long.parseLong(timeArr[1]);
        long second = Long.parseLong(timeArr[2]);
        return hour * hourCardinal + minute * minuteCardinal + second;
    }

    /**
     * 获取异常日志
     *
     * @param ex
     * @return
     */
    public static String getExceptioniInformation(Throwable ex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e) {
            return null;
        }
        return ret;
    }

    /**
     * 将对象转成map形式
     *
     * @param o
     * @return
     */
    public static Map objectToMap(Object o) {
        return (Map) JSONObject.toJSON(o);
    }


    /**
     * 判断当前json数组是否为空
     *
     * @param jsonArray
     * @return
     */
    public static boolean isEmpty(JSONArray jsonArray) {
        if (isNotNull(jsonArray) && !jsonArray.isEmpty()) {
            return false;
        }
        return true;
    }

    /**
     * 返回当前时间,格式HH:mm:ss new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
     *
     * @return String 当前时间
     */
    public static String getCurrentDate(String formatStr) {
        String time = null;
        try {
            DateFormat myformat = new SimpleDateFormat(formatStr);
            time = myformat.format(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }


    public static boolean isAjax(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType)) {
            return true;
        }
        return false;
    }

    /**
     * 将字符串匹配替换成占位符形式
     *
     * @param str
     * @param separator
     * @return
     */
    public static String format(String str, String regex, String separator) {
        String temp = "";
        String[] pathArr = null;
        if (str.startsWith(separator)) {
            temp = separator;
            pathArr = str.replaceFirst(separator, "").split(separator);
        } else {
            pathArr = str.split(separator);
        }
        int perchIndex = 0;
        String path = null;
        for (int i = 0; i < pathArr.length; i++) {
            path = pathArr[i];
            if (path.matches("\\d+") || path.indexOf("%2C") >= 0 || path.indexOf(",") >= 0) {
                //path = path.replaceFirst("(\\d+)", String.format("%s%d%s", "{", perchIndex, "}"));
                path = "{" + perchIndex + "}";
                perchIndex++;
            }
            temp += path;
            if (i != pathArr.length - 1) {
                temp += separator;
            }
        }
        return temp;
    }

    public static <T> T toObject(Object o, Class<T> tClass) {
        return JSONObject.parseObject(JSONObject.toJSONString(o), tClass);
    }

    /**
     * 判断json中是否有该key的json对象,如果没有将该key添加到json中,并返回key代表的json對象
     *
     * @param jsonObject
     * @param key
     * @return
     */
    public static JSONObject getJSONObject(JSONObject jsonObject, String key) {
        JSONObject obj = jsonObject.getJSONObject(key);
        if (CommonUtils.isNull(obj)) {
            obj = new JSONObject();
            jsonObject.put(key, obj);
        }
        return obj;
    }

    /**
     * 判断jsonArr中是否有该key的json对象,如果没有将该key添加到json中,并返回key代表的jsonArr對象
     *
     * @param jsonObject
     * @param key
     * @return
     */
    public static JSONArray getJSONArray(JSONObject jsonObject, String key) {
        JSONArray obj = jsonObject.getJSONArray(key);
        if (CommonUtils.isNull(obj)) {
            obj = new JSONArray();
            jsonObject.put(key, obj);
        }
        return obj;
    }


    /**
     * 判断是否是网络地址
     *
     * @param url
     */
    public static boolean isHttpUrl(String url) {
        if (isNotEmpty(url)) {
            if (url.startsWith("http://") || url.startsWith("https://")) {
                return true;
            }
        }
        return false;
    }

    public static Timestamp getTimestamp(String timeStr, String fromPattern) {
        Timestamp dateTime = null;
        try {
            SimpleDateFormat formatter = null;
            if (isEmpty(fromPattern)) {
                formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            } else {
                formatter = new SimpleDateFormat(fromPattern);
            }
            Date day = formatter.parse(timeStr);
            dateTime = new Timestamp(day.getTime());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return dateTime;
    }

    /**
     * 获取直播、直播申请中的预计开始、结束时间
     *
     * @return
     */
    public static Date getStartAndEndTime(String preStartAndEndTime) {
        if (CommonUtils.isNotEmpty(preStartAndEndTime)) {
            return new Timestamp(Long.parseLong(preStartAndEndTime));
        }
        return null;
    }
}