├── .gitignore ├── LICENSE ├── README.md ├── pom.xml ├── repo └── com │ └── github │ └── java-utils │ ├── 1.0 │ ├── java-utils-1.0-sources.jar │ ├── java-utils-1.0-sources.jar.md5 │ ├── java-utils-1.0-sources.jar.sha1 │ ├── java-utils-1.0.jar │ ├── java-utils-1.0.jar.md5 │ ├── java-utils-1.0.jar.sha1 │ ├── java-utils-1.0.pom │ ├── java-utils-1.0.pom.md5 │ └── java-utils-1.0.pom.sha1 │ ├── maven-metadata.xml │ ├── maven-metadata.xml.md5 │ └── maven-metadata.xml.sha1 └── src └── main └── java └── com └── github └── javautils ├── Constants.java ├── date └── DateUtil.java ├── encrypt ├── BASE64Decoder.java ├── BASE64Encoder.java ├── CharacterDecoder.java ├── CharacterEncoder.java └── EncryptionUtil.java ├── image ├── ImageCompressUtil.java └── ImageUtil.java ├── io └── FileUtil.java ├── math └── BigDecimalUtil.java ├── net ├── HttpUtil.java ├── IpUtil.java └── RequestUtil.java ├── regular └── Regular.java ├── string └── StringUtil.java └── web └── CookieUtils.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | 3 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 朋也 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 日常使用的Java工具整理 2 | 3 | ### 日期 4 | 5 | - [DateUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/date/DateUtil.java) 6 | 7 | ### 加密 8 | 9 | - [BASE64Decoder](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/encrypt/BASE64Decoder.java) 10 | - [BASE64Encoder](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/encrypt/BASE64Encoder.java) 11 | - [CharacterDecoder](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/encrypt/CharacterDecoder.java) 12 | - [CharacterEncoder](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/encrypt/CharacterEncoder.java) 13 | - [EncryptionUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/encrypt/EncryptionUtil.java) 14 | 15 | ### 图片处理 16 | 17 | - [ImageCompressUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/image/ImageCompressUtil.java) 18 | - [ImageUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/image/ImageUtil.java) 19 | 20 | ### IO 21 | 22 | - [FileUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/io/FileUtil.java) 23 | 24 | ### 计算 25 | 26 | - [BigDecimalUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/math/BigDecimalUtil.java) 27 | 28 | ### 网络 29 | 30 | - [HttpUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/net/HttpUtil.java) 31 | - [IpUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/net/IpUtil.java) 32 | - [RequestUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/net/RequestUtil.java) 33 | 34 | ### 正则 35 | 36 | - [Regular](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/regular/Regular.java) 37 | 38 | ### 字符串 39 | 40 | - [StringUtil](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/string/StringUtil.java) 41 | 42 | ### 常量 43 | 44 | - [Constants](https://github.com/tomoya92/java-utils/blob/master/src/main/java/com/github/javautils/Constants.java) 45 | 46 | ## 本地安装使用 47 | 48 | 克隆并编译安装 49 | 50 | windows电脑还需要修改一下pom.xml里的插件配置 51 | 52 | ``` 53 | 54 | ${java.home}/lib/rt.jar:${java.home}/lib/jce.jar 55 | ``` 56 | 57 | 然后安装下面命令操作就可以将 `java-utils` 安装到本地了 58 | 59 | ``` 60 | git clone https://github.com/tomoya92/java-utils.git 61 | cd java-utils 62 | mvn install -Dmaven.test.skip=true 63 | ``` 64 | 65 | 在个人项目里的`pom.xml`里添加依赖 66 | 67 | ```xml 68 | 69 | com.github 70 | java-utils 71 | 1.0 72 | 73 | ``` 74 | 75 | ## 贡献 76 | 77 | 欢迎提pr 78 | 79 | ## 感谢 80 | 81 | [@qq347447474](https://github.com/qq347447474) 82 | [JFinal工具类](http://git.oschina.net/jfinal/jfinal/tree/master/src/com/jfinal/kit?dir=1&filepath=src%2Fcom%2Fjfinal%2Fkit&oid=3712944c6c6eaa8531193b50681913617c0de33f&sha=15064f54a9d73939bd72a56f698ad95972654f09) 83 | 84 | ## 免责声明 85 | 86 | 本开源仓库内的工具类代码来自网络收集以及码农朋友提供,如果涉及侵权,请告知删除 87 | 88 | ## 开源协议 89 | 90 | MIT -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github 8 | java-utils 9 | 1.0 10 | 11 | 12 | 13 | javax.servlet 14 | javax.servlet-api 15 | 3.1.0 16 | 17 | 18 | 19 | 20 | 21 | maven-repo 22 | file:/Users/tomoya/git/github/java-utils/repo 23 | 24 | 25 | 26 | 27 | 28 | 29 | org.apache.maven.plugins 30 | maven-compiler-plugin 31 | 3.5.1 32 | 33 | 1.8 34 | 1.8 35 | UTF-8 36 | 37 | 38 | 39 | ${java.home}/lib/rt.jar:${java.home}/lib/jce.jar 40 | 41 | 42 | 43 | 44 | maven-source-plugin 45 | 2.4 46 | 47 | 48 | package 49 | 50 | jar-no-fork 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /repo/com/github/java-utils/1.0/java-utils-1.0-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atjiu/java-utils/5df4e5f6f64c166101835c35782aece635b2f6c8/repo/com/github/java-utils/1.0/java-utils-1.0-sources.jar -------------------------------------------------------------------------------- /repo/com/github/java-utils/1.0/java-utils-1.0-sources.jar.md5: -------------------------------------------------------------------------------- 1 | 1f855f5d99117bbb4a3c30c78b40bc23 -------------------------------------------------------------------------------- /repo/com/github/java-utils/1.0/java-utils-1.0-sources.jar.sha1: -------------------------------------------------------------------------------- 1 | 91367f15531464f32c7b7ec05abc94e1f36132b0 -------------------------------------------------------------------------------- /repo/com/github/java-utils/1.0/java-utils-1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/atjiu/java-utils/5df4e5f6f64c166101835c35782aece635b2f6c8/repo/com/github/java-utils/1.0/java-utils-1.0.jar -------------------------------------------------------------------------------- /repo/com/github/java-utils/1.0/java-utils-1.0.jar.md5: -------------------------------------------------------------------------------- 1 | 5387c54636e2a836bcaa74f41ae6195d -------------------------------------------------------------------------------- /repo/com/github/java-utils/1.0/java-utils-1.0.jar.sha1: -------------------------------------------------------------------------------- 1 | c43aa4a4d6bdc1f0f66adea4de1b6a433e9a6545 -------------------------------------------------------------------------------- /repo/com/github/java-utils/1.0/java-utils-1.0.pom: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github 8 | java-utils 9 | 1.0 10 | 11 | 12 | 13 | javax.servlet 14 | javax.servlet-api 15 | 3.1.0 16 | 17 | 18 | 19 | 20 | 21 | maven-repo 22 | file:/Users/tomoya/git/github/java-utils/repo 23 | 24 | 25 | 26 | 27 | 28 | 29 | org.apache.maven.plugins 30 | maven-compiler-plugin 31 | 3.5.1 32 | 33 | 1.8 34 | 1.8 35 | UTF-8 36 | 37 | 38 | 39 | ${java.home}/lib/rt.jar:${java.home}/lib/jce.jar 40 | 41 | 42 | 43 | 44 | maven-source-plugin 45 | 2.4 46 | 47 | 48 | package 49 | 50 | jar-no-fork 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /repo/com/github/java-utils/1.0/java-utils-1.0.pom.md5: -------------------------------------------------------------------------------- 1 | 613df43bd81d8597bda7ba46c5d4c9f0 -------------------------------------------------------------------------------- /repo/com/github/java-utils/1.0/java-utils-1.0.pom.sha1: -------------------------------------------------------------------------------- 1 | 55ae4c3a8b46af15da537b3718102f54ab7aaf53 -------------------------------------------------------------------------------- /repo/com/github/java-utils/maven-metadata.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | com.github 4 | java-utils 5 | 6 | 1.0 7 | 8 | 1.0 9 | 10 | 20161024071946 11 | 12 | 13 | -------------------------------------------------------------------------------- /repo/com/github/java-utils/maven-metadata.xml.md5: -------------------------------------------------------------------------------- 1 | c7c6c42a10bfcb1bfcd6342ba074040c -------------------------------------------------------------------------------- /repo/com/github/java-utils/maven-metadata.xml.sha1: -------------------------------------------------------------------------------- 1 | d51996cd76ddc682ea9ba6177140c3fda8e94960 -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/Constants.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils; 2 | 3 | /** 4 | * Created by tomoya on 16/8/31. 5 | */ 6 | public interface Constants { 7 | 8 | String ENCODING = "UTF-8"; 9 | String FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss"; 10 | String FORMAT_DATE = "yyyy-MM-dd"; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/date/DateUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.date; 2 | 3 | import com.github.javautils.Constants; 4 | import com.github.javautils.string.StringUtil; 5 | 6 | import java.text.ParseException; 7 | import java.text.SimpleDateFormat; 8 | import java.util.Calendar; 9 | import java.util.Date; 10 | import java.util.TimeZone; 11 | 12 | /** 13 | * Created by tomoya. 14 | * Copyright (c) 2016, All Rights Reserved. 15 | * http://tomoya.cn 16 | */ 17 | public class DateUtil { 18 | 19 | /** 20 | * 格式化成日期时间字符串 21 | * 22 | * @param date 23 | * @return 24 | */ 25 | public static String formatDateTime(Date date) { 26 | if (date == null) return null; 27 | SimpleDateFormat sdf = new SimpleDateFormat(Constants.FORMAT_DATETIME); 28 | sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); 29 | return sdf.format(date); 30 | } 31 | 32 | /** 33 | * 格式化成日期字符串 34 | * 35 | * @param date 36 | * @return 37 | */ 38 | public static String formatDate(Date date) { 39 | if (date == null) return null; 40 | SimpleDateFormat sdf = new SimpleDateFormat(Constants.FORMAT_DATE); 41 | sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); 42 | return sdf.format(date); 43 | } 44 | 45 | /** 46 | * 格式化成自定义类型的日期字符串 47 | * 48 | * @param date 49 | * @param style 自定义类型 50 | * @return 51 | */ 52 | public static String formatDateTime(Date date, String style) { 53 | if (date == null) return null; 54 | SimpleDateFormat sdf = new SimpleDateFormat(style); 55 | sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); 56 | return sdf.format(date); 57 | } 58 | 59 | /** 60 | * 按照格式化类型将字符串转时间 61 | * 62 | * @param dateString 63 | * @param style 64 | * @return 65 | */ 66 | public static Date string2Date(String dateString, String style) { 67 | if (StringUtil.isBlank(dateString)) return null; 68 | Date date = new Date(); 69 | SimpleDateFormat strToDate = new SimpleDateFormat(style); 70 | try { 71 | date = strToDate.parse(dateString); 72 | } catch (ParseException e) { 73 | e.printStackTrace(); 74 | } 75 | return date; 76 | } 77 | 78 | /** 79 | * 判断传入的时间是否在当前时间之后,返回boolean值 80 | * true: 过期 81 | * false: 还没过期 82 | * 83 | * @param date 84 | * @return 85 | */ 86 | public static boolean isExpire(Date date) { 87 | if (date.before(new Date())) return true; 88 | return false; 89 | } 90 | 91 | /** 92 | * 获取 传入 date 之后 hour 小时的日期 93 | * 94 | * @param date 95 | * @param hour 96 | * @return 97 | */ 98 | public static Date getHourAfter(Date date, int hour) { 99 | Calendar calendar = Calendar.getInstance(); 100 | calendar.setTime(date); 101 | calendar.set(Calendar.HOUR, hour + 1); 102 | return calendar.getTime(); 103 | } 104 | 105 | /** 106 | * 获取 传入 date 之前 hour 小时的日期 107 | * 108 | * @param date 109 | * @param hour 110 | * @return 111 | */ 112 | public static Date getHourBefore(Date date, int hour) { 113 | Calendar calendar = Calendar.getInstance(); 114 | calendar.setTime(date); 115 | calendar.set(Calendar.HOUR, -(hour - 1)); 116 | return calendar.getTime(); 117 | } 118 | 119 | /** 120 | * 获取 传入 date 之前 day 天的日期 121 | * 122 | * @param date 123 | * @param day 124 | * @return 125 | */ 126 | public static Date getDateBefore(Date date, int day) { 127 | Calendar calendar = Calendar.getInstance(); 128 | calendar.setTime(date); 129 | calendar.add(Calendar.DAY_OF_MONTH, -day); 130 | return calendar.getTime(); 131 | } 132 | 133 | /** 134 | * 获取 传入 date 之后 day 天的日期 135 | * 136 | * @param date 137 | * @param day 138 | * @return 139 | */ 140 | public static Date getDateAfter(Date date, int day) { 141 | Calendar calendar = Calendar.getInstance(); 142 | calendar.setTime(date); 143 | calendar.add(Calendar.DAY_OF_MONTH, day); 144 | return calendar.getTime(); 145 | } 146 | 147 | /** 148 | * 获取 传入 date 之后 minute 分钟的日期 149 | * 150 | * @param date 151 | * @param minute 152 | * @return 153 | */ 154 | public static Date getMinuteAfter(Date date, int minute) { 155 | Calendar calendar = Calendar.getInstance(); 156 | calendar.setTime(date); 157 | calendar.add(Calendar.MINUTE, minute); 158 | return calendar.getTime(); 159 | } 160 | 161 | /** 162 | * 获取 传入 date 之前 minute 分钟的日期 163 | * 164 | * @param date 165 | * @param minute 166 | * @return 167 | */ 168 | public static Date getMinuteBefore(Date date, int minute) { 169 | Calendar calendar = Calendar.getInstance(); 170 | calendar.setTime(date); 171 | calendar.add(Calendar.MINUTE, -minute); 172 | return calendar.getTime(); 173 | } 174 | 175 | } -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/encrypt/BASE64Decoder.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.encrypt; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.OutputStream; 6 | 7 | public class BASE64Decoder extends CharacterDecoder { 8 | 9 | public BASE64Decoder() { 10 | decode_buffer = new byte[4]; 11 | } 12 | 13 | protected int bytesPerAtom() { 14 | return 4; 15 | } 16 | 17 | protected int bytesPerLine() { 18 | return 72; 19 | } 20 | 21 | protected void decodeAtom(InputStream inputstream, OutputStream outputstream, int i) 22 | throws IOException { 23 | byte byte0 = -1; 24 | byte byte1 = -1; 25 | byte byte2 = -1; 26 | byte byte3 = -1; 27 | if (i < 2) 28 | throw new IOException("BASE64Decoder: Not enough bytes for an atom."); 29 | int j; 30 | do { 31 | j = inputstream.read(); 32 | if (j == -1) 33 | throw new IOException("StreamExhausted"); 34 | } while (j == 10 || j == 13); 35 | decode_buffer[0] = (byte) j; 36 | j = readFully(inputstream, decode_buffer, 1, i - 1); 37 | if (j == -1) 38 | throw new IOException("StreamExhausted"); 39 | if (i > 3 && decode_buffer[3] == 61) 40 | i = 3; 41 | if (i > 2 && decode_buffer[2] == 61) 42 | i = 2; 43 | switch (i) { 44 | case 4: // '\004' 45 | byte3 = pem_convert_array[decode_buffer[3] & 0xff]; 46 | // fall through 47 | 48 | case 3: // '\003' 49 | byte2 = pem_convert_array[decode_buffer[2] & 0xff]; 50 | // fall through 51 | 52 | case 2: // '\002' 53 | byte1 = pem_convert_array[decode_buffer[1] & 0xff]; 54 | byte0 = pem_convert_array[decode_buffer[0] & 0xff]; 55 | // fall through 56 | 57 | default: 58 | switch (i) { 59 | case 2: // '\002' 60 | outputstream.write((byte) (byte0 << 2 & 0xfc | byte1 >>> 4 & 3)); 61 | break; 62 | 63 | case 3: // '\003' 64 | outputstream.write((byte) (byte0 << 2 & 0xfc | byte1 >>> 4 & 3)); 65 | outputstream.write((byte) (byte1 << 4 & 0xf0 | byte2 >>> 2 & 0xf)); 66 | break; 67 | 68 | case 4: // '\004' 69 | outputstream.write((byte) (byte0 << 2 & 0xfc | byte1 >>> 4 & 3)); 70 | outputstream.write((byte) (byte1 << 4 & 0xf0 | byte2 >>> 2 & 0xf)); 71 | outputstream.write((byte) (byte2 << 6 & 0xc0 | byte3 & 0x3f)); 72 | break; 73 | } 74 | break; 75 | } 76 | } 77 | 78 | private static final char pem_array[] = { 79 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 80 | 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 81 | 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 82 | 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 83 | 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 84 | 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', 85 | '8', '9', '+', '/' 86 | }; 87 | private static final byte pem_convert_array[]; 88 | byte decode_buffer[]; 89 | 90 | static { 91 | pem_convert_array = new byte[256]; 92 | for (int i = 0; i < 255; i++) 93 | pem_convert_array[i] = -1; 94 | 95 | for (int j = 0; j < pem_array.length; j++) 96 | pem_convert_array[pem_array[j]] = (byte) j; 97 | 98 | } 99 | } -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/encrypt/BASE64Encoder.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.encrypt; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | 6 | /** 7 | *

8 | * Description:base64编码类 9 | *

10 | */ 11 | public class BASE64Encoder extends CharacterEncoder { 12 | 13 | public BASE64Encoder() { 14 | } 15 | 16 | protected int bytesPerAtom() { 17 | return 3; 18 | } 19 | 20 | protected int bytesPerLine() { 21 | return 57; 22 | } 23 | 24 | protected void encodeAtom(OutputStream outputstream, byte abyte0[], int i, int j) throws IOException { 25 | if (j == 1) { 26 | byte byte0 = abyte0[i]; 27 | int k = 0; 28 | outputstream.write(pem_array[byte0 >>> 2 & 0x3f]); 29 | outputstream.write(pem_array[(byte0 << 4 & 0x30) + (k >>> 4 & 0xf)]); 30 | outputstream.write(61); 31 | outputstream.write(61); 32 | } else if (j == 2) { 33 | byte byte1 = abyte0[i]; 34 | byte byte3 = abyte0[i + 1]; 35 | int l = 0; 36 | outputstream.write(pem_array[byte1 >>> 2 & 0x3f]); 37 | outputstream.write(pem_array[(byte1 << 4 & 0x30) + (byte3 >>> 4 & 0xf)]); 38 | outputstream.write(pem_array[(byte3 << 2 & 0x3c) + (l >>> 6 & 3)]); 39 | outputstream.write(61); 40 | } else { 41 | byte byte2 = abyte0[i]; 42 | byte byte4 = abyte0[i + 1]; 43 | byte byte5 = abyte0[i + 2]; 44 | outputstream.write(pem_array[byte2 >>> 2 & 0x3f]); 45 | outputstream.write(pem_array[(byte2 << 4 & 0x30) + (byte4 >>> 4 & 0xf)]); 46 | outputstream.write(pem_array[(byte4 << 2 & 0x3c) + (byte5 >>> 6 & 3)]); 47 | outputstream.write(pem_array[byte5 & 0x3f]); 48 | } 49 | } 50 | 51 | private static final char pem_array[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 52 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', 53 | '7', '8', '9', '+', '/'}; 54 | 55 | } -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/encrypt/CharacterDecoder.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.encrypt; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | 9 | public abstract class CharacterDecoder { 10 | 11 | public CharacterDecoder() { 12 | } 13 | 14 | protected abstract int bytesPerAtom(); 15 | 16 | protected abstract int bytesPerLine(); 17 | 18 | protected void decodeBufferPrefix(InputStream inputstream, OutputStream outputstream) 19 | throws IOException { 20 | } 21 | 22 | protected void decodeBufferSuffix(InputStream inputstream, OutputStream outputstream) 23 | throws IOException { 24 | } 25 | 26 | protected int decodeLinePrefix(InputStream inputstream, OutputStream outputstream) 27 | throws IOException { 28 | return bytesPerLine(); 29 | } 30 | 31 | protected void decodeLineSuffix(InputStream inputstream, OutputStream outputstream) 32 | throws IOException { 33 | } 34 | 35 | protected void decodeAtom(InputStream inputstream, OutputStream outputstream, int i) 36 | throws IOException { 37 | throw new IOException("StreamExhausted"); 38 | } 39 | 40 | protected int readFully(InputStream inputstream, byte abyte0[], int i, int j) 41 | throws IOException { 42 | for (int k = 0; k < j; k++) { 43 | int l = inputstream.read(); 44 | if (l == -1) 45 | return k != 0 ? k : -1; 46 | abyte0[k + i] = (byte) l; 47 | } 48 | 49 | return j; 50 | } 51 | 52 | @SuppressWarnings("unused") 53 | public void decodeBuffer(InputStream inputstream, OutputStream outputstream) 54 | throws IOException { 55 | int j = 0; 56 | decodeBufferPrefix(inputstream, outputstream); 57 | try { 58 | do { 59 | int k = decodeLinePrefix(inputstream, outputstream); 60 | int i; 61 | for (i = 0; i + bytesPerAtom() < k; i += bytesPerAtom()) { 62 | decodeAtom(inputstream, outputstream, bytesPerAtom()); 63 | j += bytesPerAtom(); 64 | } 65 | 66 | if (i + bytesPerAtom() == k) { 67 | decodeAtom(inputstream, outputstream, bytesPerAtom()); 68 | j += bytesPerAtom(); 69 | } else { 70 | decodeAtom(inputstream, outputstream, k - i); 71 | j += k - i; 72 | } 73 | decodeLineSuffix(inputstream, outputstream); 74 | } while (true); 75 | } catch (IOException e) { 76 | if (e.getMessage().equals("StreamExhausted")) 77 | decodeBufferSuffix(inputstream, outputstream); 78 | else 79 | throw e; 80 | } 81 | } 82 | 83 | public byte[] decodeBuffer(String s) 84 | throws IOException { 85 | byte abyte0[] = s.getBytes(); 86 | ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0); 87 | ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); 88 | decodeBuffer(((InputStream) (bytearrayinputstream)), ((OutputStream) (bytearrayoutputstream))); 89 | return bytearrayoutputstream.toByteArray(); 90 | } 91 | 92 | public String decodeStr(String s) throws IOException { 93 | return new String(decodeBuffer(s)); 94 | } 95 | 96 | public byte[] decodeBuffer(InputStream inputstream) 97 | throws IOException { 98 | ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); 99 | decodeBuffer(inputstream, ((OutputStream) (bytearrayoutputstream))); 100 | return bytearrayoutputstream.toByteArray(); 101 | } 102 | } -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/encrypt/CharacterEncoder.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.encrypt; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | import java.io.PrintStream; 9 | 10 | /** 11 | * Description:base64解码类 12 | */ 13 | public abstract class CharacterEncoder { 14 | 15 | public CharacterEncoder() { 16 | } 17 | 18 | protected abstract int bytesPerAtom(); 19 | 20 | protected abstract int bytesPerLine(); 21 | 22 | protected void encodeBufferPrefix(OutputStream outputstream) 23 | throws IOException { 24 | pStream = new PrintStream(outputstream); 25 | } 26 | 27 | protected void encodeBufferSuffix(OutputStream outputstream) 28 | throws IOException { 29 | } 30 | 31 | protected void encodeLinePrefix(OutputStream outputstream, int i) 32 | throws IOException { 33 | } 34 | 35 | protected void encodeLineSuffix(OutputStream outputstream) 36 | throws IOException { 37 | //pStream.println(); 38 | } 39 | 40 | protected abstract void encodeAtom(OutputStream outputstream, byte abyte0[], int i, int j) 41 | throws IOException; 42 | 43 | protected int readFully(InputStream inputstream, byte abyte0[]) 44 | throws IOException { 45 | for (int i = 0; i < abyte0.length; i++) { 46 | int j = inputstream.read(); 47 | if (j == -1) 48 | return i; 49 | abyte0[i] = (byte) j; 50 | } 51 | 52 | return abyte0.length; 53 | } 54 | 55 | public void encode(InputStream inputstream, OutputStream outputstream) 56 | throws IOException { 57 | byte abyte0[] = new byte[bytesPerLine()]; 58 | encodeBufferPrefix(outputstream); 59 | do { 60 | int j = readFully(inputstream, abyte0); 61 | if (j == 0) 62 | break; 63 | encodeLinePrefix(outputstream, j); 64 | for (int i = 0; i < j; i += bytesPerAtom()) 65 | if (i + bytesPerAtom() <= j) 66 | encodeAtom(outputstream, abyte0, i, bytesPerAtom()); 67 | else 68 | encodeAtom(outputstream, abyte0, i, j - i); 69 | 70 | if (j < bytesPerLine()) 71 | break; 72 | encodeLineSuffix(outputstream); 73 | } while (true); 74 | encodeBufferSuffix(outputstream); 75 | } 76 | 77 | public void encode(byte abyte0[], OutputStream outputstream) 78 | throws IOException { 79 | ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0); 80 | encode(((InputStream) (bytearrayinputstream)), outputstream); 81 | } 82 | 83 | public String encode(byte abyte0[]) { 84 | ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); 85 | ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0); 86 | String s = null; 87 | try { 88 | encode(((InputStream) (bytearrayinputstream)), ((OutputStream) (bytearrayoutputstream))); 89 | s = bytearrayoutputstream.toString("8859_1"); 90 | } catch (Exception exception) { 91 | throw new Error("ChracterEncoder::encodeBuffer internal error"); 92 | } 93 | return s; 94 | } 95 | 96 | public void encodeBuffer(InputStream inputstream, OutputStream outputstream) 97 | throws IOException { 98 | byte abyte0[] = new byte[bytesPerLine()]; 99 | encodeBufferPrefix(outputstream); 100 | int j; 101 | do { 102 | j = readFully(inputstream, abyte0); 103 | if (j == 0) 104 | break; 105 | encodeLinePrefix(outputstream, j); 106 | for (int i = 0; i < j; i += bytesPerAtom()) 107 | if (i + bytesPerAtom() <= j) 108 | encodeAtom(outputstream, abyte0, i, bytesPerAtom()); 109 | else 110 | encodeAtom(outputstream, abyte0, i, j - i); 111 | 112 | encodeLineSuffix(outputstream); 113 | } while (j >= bytesPerLine()); 114 | encodeBufferSuffix(outputstream); 115 | } 116 | 117 | public void encodeBuffer(byte abyte0[], OutputStream outputstream) 118 | throws IOException { 119 | ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0); 120 | encodeBuffer(((InputStream) (bytearrayinputstream)), outputstream); 121 | } 122 | 123 | public String encodeBuffer(byte abyte0[]) { 124 | ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); 125 | ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0); 126 | try { 127 | encodeBuffer(((InputStream) (bytearrayinputstream)), ((OutputStream) (bytearrayoutputstream))); 128 | } catch (Exception exception) { 129 | throw new Error("ChracterEncoder::encodeBuffer internal error"); 130 | } 131 | return bytearrayoutputstream.toString(); 132 | } 133 | 134 | private static int mCurrentLineLength = 0; 135 | 136 | public static String encode_qp(byte[] content) { 137 | if (content == null) { 138 | return null; 139 | } 140 | StringBuilder out = new StringBuilder(); 141 | 142 | mCurrentLineLength = 0; 143 | int requiredLength = 0; 144 | for (int index = 0; index < content.length; index++) { 145 | byte c = content[index]; 146 | if ((c >= 33) && (c <= 126) && (c != 61)) { 147 | requiredLength = 1; 148 | checkLineLength(requiredLength, out); 149 | out.append((char) c); 150 | } else { 151 | requiredLength = 3; 152 | checkLineLength(requiredLength, out); 153 | out.append('='); 154 | out.append(String.format("%02X", new Object[]{Byte.valueOf(c)})); 155 | } 156 | } 157 | return out.toString(); 158 | } 159 | 160 | private static void checkLineLength(int required, StringBuilder out) { 161 | if (required + mCurrentLineLength > 998) { 162 | out.append("=/r/n"); 163 | mCurrentLineLength = required; 164 | } else { 165 | mCurrentLineLength += required; 166 | } 167 | } 168 | 169 | protected PrintStream pStream; 170 | } -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/encrypt/EncryptionUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.encrypt; 2 | 3 | import java.security.MessageDigest; 4 | 5 | public class EncryptionUtil { 6 | 7 | private static final java.security.SecureRandom random = new java.security.SecureRandom(); 8 | private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 9 | 10 | public static String md5(String srcStr) { 11 | return hash("MD5", srcStr); 12 | } 13 | 14 | public static String sha1(String srcStr) { 15 | return hash("SHA-1", srcStr); 16 | } 17 | 18 | public static String sha256(String srcStr) { 19 | return hash("SHA-256", srcStr); 20 | } 21 | 22 | public static String sha384(String srcStr) { 23 | return hash("SHA-384", srcStr); 24 | } 25 | 26 | public static String sha512(String srcStr) { 27 | return hash("SHA-512", srcStr); 28 | } 29 | 30 | public static String hash(String algorithm, String srcStr) { 31 | try { 32 | MessageDigest md = MessageDigest.getInstance(algorithm); 33 | byte[] bytes = md.digest(srcStr.getBytes("utf-8")); 34 | return toHex(bytes); 35 | } catch (Exception e) { 36 | throw new RuntimeException(e); 37 | } 38 | } 39 | 40 | private static String toHex(byte[] bytes) { 41 | StringBuilder ret = new StringBuilder(bytes.length * 2); 42 | for (int i = 0; i < bytes.length; i++) { 43 | ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]); 44 | ret.append(HEX_DIGITS[bytes[i] & 0x0f]); 45 | } 46 | return ret.toString(); 47 | } 48 | 49 | /** 50 | * md5 128bit 16bytes 51 | * sha1 160bit 20bytes 52 | * sha256 256bit 32bytes 53 | * sha384 384bit 48bites 54 | * sha512 512bit 64bites 55 | */ 56 | public static String generateSalt(int numberOfBytes) { 57 | byte[] salt = new byte[numberOfBytes]; 58 | random.nextBytes(salt); 59 | return toHex(salt); 60 | } 61 | 62 | /** 63 | * 码表; 64 | */ 65 | public static char[] encodeTable = {'A', 'B', 'C', 'D', 66 | 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 67 | 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 68 | 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 69 | 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', 70 | '4', '5', '6', '7', '8', '9', '+', '/'}; 71 | 72 | /** 73 | * Base64的编码; 74 | * 75 | * @param value 76 | * @return 77 | */ 78 | public static String encoderBase64(byte[] value) { 79 | StringBuilder sb = new StringBuilder(); 80 | //获取编码字节是3的倍数; 81 | int len = value.length; 82 | int len3 = len / 3; 83 | //先处理没有加换行符; 84 | for (int i = 0; i < len3; i++) { 85 | 86 | //得到第一个字符; 87 | int b1 = (value[i * 3] >> 2) & 0x3F; 88 | char c1 = encodeTable[b1]; 89 | sb.append(c1); 90 | 91 | //得到第二个字符; 92 | int b2 = ((value[i * 3] << 4 & 0x3F) + (value[i * 3 + 1] >> 4)) & 0x3F; 93 | char c2 = encodeTable[b2]; 94 | sb.append(c2); 95 | 96 | //得到第三个字符; 97 | int b3 = ((value[i * 3 + 1] << 2 & 0x3C) + (value[i * 3 + 2] >> 6)) & 0x3F; 98 | char c3 = encodeTable[b3]; 99 | sb.append(c3); 100 | 101 | //得到第四个字符; 102 | int b4 = value[i * 3 + 2] & 0x3F; 103 | char c4 = encodeTable[b4]; 104 | sb.append(c4); 105 | 106 | } 107 | 108 | //如果有剩余的字符就补0; 109 | //剩余的个数; 110 | int less = len % 3; 111 | if (less == 1) {//剩余一个字符--补充两个等号;; 112 | 113 | //得到第一个字符; 114 | int b1 = value[len3 * 3] >> 2 & 0x3F; 115 | char c1 = encodeTable[b1]; 116 | sb.append(c1); 117 | 118 | //得到第二个字符; 119 | int b2 = (value[len3 * 3] << 4 & 0x30) & 0x3F; 120 | char c2 = encodeTable[b2]; 121 | sb.append(c2); 122 | sb.append("=="); 123 | 124 | } else if (less == 2) {//剩余两个字符--补充一个等号; 125 | 126 | //得到第一个字符; 127 | int b1 = value[len3 * 3] >> 2 & 0x3F; 128 | char c1 = encodeTable[b1]; 129 | sb.append(c1); 130 | 131 | //得到第二个字符; 132 | int b2 = ((value[len3 * 3] << 4 & 0x30) + (value[len3 * 3 + 1] >> 4)) & 0x3F; 133 | char c2 = encodeTable[b2]; 134 | sb.append(c2); 135 | 136 | //得到第三个字符; 137 | int b3 = (value[len3 * 3 + 1] << 2 & 0x3C) & 0x3F; 138 | char c3 = encodeTable[b3]; 139 | sb.append(c3); 140 | sb.append("="); 141 | 142 | } 143 | 144 | return sb.toString(); 145 | } 146 | 147 | /** 148 | * Base64的解码; 149 | * 150 | * @param value 151 | * @return 152 | */ 153 | public static String decoderBase64(byte[] value) { 154 | 155 | //每四个一组进行解码; 156 | int len = value.length; 157 | int len4 = len / 4; 158 | StringBuilder sb = new StringBuilder(); 159 | //除去末尾的四个可能特殊的字符; 160 | int i = 0; 161 | for (i = 0; i < len4 - 1; i++) { 162 | 163 | //第一个字符; 164 | byte b1 = (byte) ((char2Index((char) value[i * 4]) << 2) + (char2Index((char) value[i * 4 + 1]) >> 4)); 165 | sb.append((char) b1); 166 | //第二个字符; 167 | byte b2 = (byte) ((char2Index((char) value[i * 4 + 1]) << 4) 168 | + (char2Index((char) value[i * 4 + 2]) >> 2)); 169 | sb.append((char) b2); 170 | //第三个字符; 171 | byte b3 = (byte) ((char2Index((char) value[i * 4 + 2]) << 6) + (char2Index((char) value[i * 4 + 3]))); 172 | sb.append((char) b3); 173 | 174 | } 175 | 176 | //处理最后的四个字符串; 177 | for (int j = 0; j < 3; j++) { 178 | int index = i * 4 + j; 179 | if ((char) value[index + 1] != '=') { 180 | 181 | if (j == 0) { 182 | byte b = (byte) ((char2Index((char) value[index]) << 2) 183 | + (char2Index((char) value[index + 1]) >> 4)); 184 | sb.append((char) b); 185 | } else if (j == 1) { 186 | byte b = (byte) ((char2Index((char) value[index]) << 4) 187 | + (char2Index((char) value[index + 1]) >> 2)); 188 | sb.append((char) b); 189 | } else if (j == 2) { 190 | byte b = (byte) ((char2Index((char) value[index]) << 6) 191 | + (char2Index((char) value[index + 1]))); 192 | sb.append((char) b); 193 | } 194 | 195 | } else { 196 | break; 197 | } 198 | } 199 | 200 | return sb.toString(); 201 | } 202 | 203 | /** 204 | * 将码表中的字符映射到索引值; 205 | * 206 | * @param ch 207 | * @return 208 | */ 209 | public static int char2Index(char ch) { 210 | if (ch >= 'A' && ch <= 'Z') { 211 | return ch - 'A'; 212 | } else if (ch >= 'a' && ch <= 'z') { 213 | return 26 + ch - 'a'; 214 | } else if (ch >= '0' && ch <= '9') { 215 | return 52 + ch - '0'; 216 | } else if (ch == '+') { 217 | return 62; 218 | } else if (ch == '/') { 219 | return 63; 220 | } 221 | return 0; 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/image/ImageCompressUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.image; 2 | 3 | import com.sun.image.codec.jpeg.JPEGCodec; 4 | import com.sun.image.codec.jpeg.JPEGEncodeParam; 5 | import com.sun.image.codec.jpeg.JPEGImageEncoder; 6 | 7 | import java.awt.Image; 8 | import java.awt.image.BufferedImage; 9 | import java.io.File; 10 | import java.io.FileNotFoundException; 11 | import java.io.FileOutputStream; 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | 15 | import javax.imageio.ImageIO; 16 | 17 | /** 18 | * 图片压缩 19 | */ 20 | public class ImageCompressUtil { 21 | /** 22 | * 直接指定压缩后的宽高: 23 | * (先保存原文件,再压缩、上传) 24 | * 25 | * @param oldFile 要进行压缩的文件全路径 26 | * @param width 压缩后的宽度 27 | * @param height 压缩后的高度 28 | * @param quality 压缩质量 29 | * @param smallIcon 文件名的小小后缀(注意,非文件后缀名称),入压缩文件名是yasuo.jpg,则压缩后文件名是yasuo(+smallIcon).jpg 30 | * @return 返回压缩后的文件的全路径 31 | */ 32 | public static String zipImageFile(String oldFile, int width, int height, 33 | float quality, String smallIcon) { 34 | if (oldFile == null) { 35 | return null; 36 | } 37 | String newImage = null; 38 | try { 39 | /**对服务器上的临时文件进行处理 */ 40 | Image srcFile = ImageIO.read(new File(oldFile)); 41 | /** 宽,高设定 */ 42 | BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 43 | tag.getGraphics().drawImage(srcFile, 0, 0, width, height, null); 44 | String filePrex = oldFile.substring(0, oldFile.indexOf('.')); 45 | /** 压缩后的文件名 */ 46 | newImage = filePrex + smallIcon + oldFile.substring(filePrex.length()); 47 | /** 压缩之后临时存放位置 */ 48 | FileOutputStream out = new FileOutputStream(newImage); 49 | JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 50 | JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag); 51 | /** 压缩质量 */ 52 | jep.setQuality(quality, true); 53 | encoder.encode(tag, jep); 54 | out.close(); 55 | } catch (FileNotFoundException e) { 56 | e.printStackTrace(); 57 | } catch (IOException e) { 58 | e.printStackTrace(); 59 | } 60 | return newImage; 61 | } 62 | 63 | /** 64 | * 保存文件到服务器临时路径(用于文件上传) 65 | * 66 | * @param fileName 67 | * @param is 68 | * @return 文件全路径 69 | */ 70 | public static String writeFile(String fileName, InputStream is) { 71 | if (fileName == null || fileName.trim().length() == 0) { 72 | return null; 73 | } 74 | try { 75 | /** 首先保存到临时文件 */ 76 | FileOutputStream fos = new FileOutputStream(fileName); 77 | byte[] readBytes = new byte[512];// 缓冲大小 78 | int readed = 0; 79 | while ((readed = is.read(readBytes)) > 0) { 80 | fos.write(readBytes, 0, readed); 81 | } 82 | fos.close(); 83 | is.close(); 84 | } catch (FileNotFoundException e) { 85 | e.printStackTrace(); 86 | } catch (IOException e) { 87 | e.printStackTrace(); 88 | } 89 | return fileName; 90 | } 91 | 92 | /** 93 | * 等比例压缩算法: 94 | * 算法思想:根据压缩基数和压缩比来压缩原图,生产一张图片效果最接近原图的缩略图 95 | * 96 | * @param srcURL 原图地址 97 | * @param deskURL 缩略图地址 98 | * @param comBase 压缩基数 99 | * @param scale 压缩限制(宽/高)比例 一般用1: 100 | * 当scale>=1,缩略图height=comBase,width按原图宽高比例;若scale<1,缩略图width=comBase,height按原图宽高比例 101 | * @throws Exception 102 | */ 103 | public static void saveMinPhoto(String srcURL, String deskURL, double comBase, 104 | double scale) throws Exception { 105 | File srcFile = new java.io.File(srcURL); 106 | Image src = ImageIO.read(srcFile); 107 | int srcHeight = src.getHeight(null); 108 | int srcWidth = src.getWidth(null); 109 | int deskHeight = 0;// 缩略图高 110 | int deskWidth = 0;// 缩略图宽 111 | double srcScale = (double) srcHeight / srcWidth; 112 | /**缩略图宽高算法*/ 113 | if ((double) srcHeight > comBase || (double) srcWidth > comBase) { 114 | if (srcScale >= scale || 1 / srcScale > scale) { 115 | if (srcScale >= scale) { 116 | deskHeight = (int) comBase; 117 | deskWidth = srcWidth * deskHeight / srcHeight; 118 | } else { 119 | deskWidth = (int) comBase; 120 | deskHeight = srcHeight * deskWidth / srcWidth; 121 | } 122 | } else { 123 | if ((double) srcHeight > comBase) { 124 | deskHeight = (int) comBase; 125 | deskWidth = srcWidth * deskHeight / srcHeight; 126 | } else { 127 | deskWidth = (int) comBase; 128 | deskHeight = srcHeight * deskWidth / srcWidth; 129 | } 130 | } 131 | } else { 132 | deskHeight = srcHeight; 133 | deskWidth = srcWidth; 134 | } 135 | BufferedImage tag = new BufferedImage(deskWidth, deskHeight, BufferedImage.TYPE_3BYTE_BGR); 136 | tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeight, null); //绘制缩小后的图 137 | FileOutputStream deskImage = new FileOutputStream(deskURL); //输出到文件流 138 | JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(deskImage); 139 | encoder.encode(tag); //近JPEG编码 140 | deskImage.close(); 141 | } 142 | 143 | public static void main(String args[]) throws Exception { 144 | ImageCompressUtil.zipImageFile("D:/1462844071014.jpg", 140, 140, 1f, "x2"); 145 | ImageCompressUtil.saveMinPhoto("D:/1462844071014.jpg", "d:/1462844071014_thumb.jpg", 140, 0.9d); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/image/ImageUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.image; 2 | 3 | import com.github.javautils.encrypt.BASE64Decoder; 4 | import com.github.javautils.encrypt.BASE64Encoder; 5 | 6 | import java.awt.AlphaComposite; 7 | import java.awt.Graphics2D; 8 | import java.awt.Image; 9 | import java.awt.RenderingHints; 10 | import java.awt.image.BufferedImage; 11 | import java.io.ByteArrayOutputStream; 12 | import java.io.File; 13 | import java.io.FileInputStream; 14 | import java.io.FileOutputStream; 15 | import java.io.IOException; 16 | import java.io.InputStream; 17 | import java.io.OutputStream; 18 | 19 | import javax.imageio.ImageIO; 20 | import javax.swing.ImageIcon; 21 | 22 | /** 23 | * 图片处理工具类 24 | */ 25 | public class ImageUtil { 26 | 27 | /** 28 | * 给图片添加水印、可设置水印图片旋转角度 29 | * 30 | * @param iconPath 水印图片路径 31 | * @param srcImgFile 源图片路径 32 | * @param degree 水印图片旋转角度 33 | */ 34 | public static byte[] markImageByIcon(String iconPath, File srcImgFile, Integer degree) { 35 | OutputStream os = null; 36 | try { 37 | Image srcImg = ImageIO.read(srcImgFile); 38 | 39 | BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), 40 | BufferedImage.TYPE_INT_RGB); 41 | 42 | // 得到画笔对象 43 | Graphics2D g = buffImg.createGraphics(); 44 | 45 | // 设置对线段的锯齿状边缘处理 46 | g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 47 | 48 | g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 49 | 0, null); 50 | 51 | if (null == degree) { 52 | // 设置水印旋转 53 | // g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() 54 | // / 2, (double) buffImg.getHeight() / 2); 55 | degree = 0; 56 | } 57 | 58 | // 水印图象的路径 水印一般为gif或者png的,这样可设置透明度 59 | ImageIcon imgIcon = new ImageIcon(iconPath); 60 | 61 | // 得到Image对象。 62 | Image img = imgIcon.getImage(); 63 | 64 | float alpha = 0.6f; // 透明度 65 | g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); 66 | 67 | // 表示水印图片的位置 68 | if (srcImg.getWidth(null) > 200 && srcImg.getHeight(null) > 50) { 69 | int x = 1; 70 | int y = 1; 71 | for (int i = 0; i < 1000; i++) { 72 | // 设置水印旋转 73 | g.rotate(Math.toRadians(degree), (double) x, (double) y); 74 | g.drawImage(img, x, y, null); 75 | g = buffImg.createGraphics(); 76 | x += 300; 77 | if (x >= srcImg.getWidth(null)) { 78 | x = 0; 79 | y += 300; 80 | } 81 | if (x >= (srcImg.getWidth(null) + 200) && (y >= srcImg.getHeight(null) + 100)) { 82 | break; 83 | } 84 | } 85 | } else { 86 | g.drawImage(img, srcImg.getWidth(null) / 2, srcImg.getHeight(null) / 2, null); 87 | } 88 | /* 89 | * g.drawImage(img, 0, 0, null); g.drawImage(img, 30, 30, null); 90 | * g.drawImage(img, 60, 60, null); g.drawImage(img, 90, 90, null); 91 | * g.drawImage(img, 120, 120, null); g.drawImage(img, 150, 300, 92 | * null); 93 | */ 94 | 95 | g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); 96 | 97 | g.dispose(); 98 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 99 | ImageIO.write(buffImg, "jpg", bos); 100 | byte[] data = bos.toByteArray(); 101 | return data; 102 | } catch (Exception e) { 103 | e.printStackTrace(); 104 | } finally { 105 | try { 106 | if (null != os) 107 | os.close(); 108 | } catch (Exception e) { 109 | e.printStackTrace(); 110 | } 111 | } 112 | return null; 113 | } 114 | 115 | // 图片转化成base64字符串 116 | public static String GetImageStr(String url) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 117 | String imgFile = url;// 待处理的图片 118 | InputStream in = null; 119 | byte[] data = null; 120 | // 读取图片字节数组 121 | try { 122 | in = new FileInputStream(imgFile); 123 | data = new byte[in.available()]; 124 | in.read(data); 125 | in.close(); 126 | } catch (IOException e) { 127 | e.printStackTrace(); 128 | } 129 | // 对字节数组Base64编码 130 | BASE64Encoder encoder = new BASE64Encoder(); 131 | return encoder.encode(data);// 返回Base64编码过的字节数组字符串 132 | } 133 | 134 | // base64字符串转化成图片 135 | public static boolean GenerateImage(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片 136 | if (imgStr == null) // 图像数据为空 137 | return false; 138 | BASE64Decoder decoder = new BASE64Decoder(); 139 | try { 140 | // Base64解码 141 | byte[] b = decoder.decodeBuffer(imgStr); 142 | for (int i = 0; i < b.length; ++i) { 143 | if (b[i] < 0) {// 调整异常数据 144 | b[i] += 256; 145 | } 146 | } 147 | // 生成jpeg图片 148 | // String imgFilePath = "C:/Users/Star/Desktop/test22.png";// 新生成的图片 149 | OutputStream out = new FileOutputStream(imgFilePath); 150 | out.write(b); 151 | out.flush(); 152 | out.close(); 153 | return true; 154 | } catch (Exception e) { 155 | return false; 156 | } 157 | } 158 | 159 | } 160 | -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/io/FileUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.io; 2 | 3 | import java.io.File; 4 | 5 | public class FileUtil { 6 | 7 | /** 8 | * 文件删除 9 | * 10 | * @param file 11 | */ 12 | public static void delete(File file) { 13 | if (file != null && file.exists()) { 14 | if (file.isFile()) { 15 | file.delete(); 16 | } else if (file.isDirectory()) { 17 | File files[] = file.listFiles(); 18 | for (int i = 0; i < files.length; i++) { 19 | delete(files[i]); 20 | } 21 | } 22 | file.delete(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/math/BigDecimalUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.math; 2 | 3 | import com.github.javautils.string.StringUtil; 4 | 5 | import java.math.BigDecimal; 6 | import java.text.DecimalFormat; 7 | import java.text.NumberFormat; 8 | 9 | /** 10 | * 工具类-BigDecimal 11 | * 12 | * @author yangwen 13 | * @version 1.0 14 | * @date 2016年4月7日 下午6:21:36 15 | */ 16 | public class BigDecimalUtil { 17 | 18 | /** 19 | * 默认精确的小数位 20 | */ 21 | private static int DEF_DIV_POINT = 10; 22 | 23 | /** 24 | * 提供精确的小数位处理,去掉保留位数后的数字 25 | * 26 | * @param num 需要处理的数字 27 | * @param point 小数点后保留几位 28 | * @return 去掉保留位数后的结果 29 | */ 30 | public static double decimal(double num, int point) { 31 | if (point < 0) { 32 | throw new IllegalArgumentException("The point must be a positive integer or zero"); 33 | } 34 | BigDecimal b = new BigDecimal(Double.toString(num)); 35 | BigDecimal one = new BigDecimal("1"); 36 | return b.divide(one, point, BigDecimal.ROUND_DOWN).doubleValue(); 37 | } 38 | 39 | /** 40 | * 提供精确的加法运算 41 | * 42 | * @param params 参数数组 43 | * @return 和 44 | */ 45 | public static double add(double... params) { 46 | BigDecimal b1 = new BigDecimal(0); 47 | for (double param : params) { 48 | BigDecimal b2 = new BigDecimal(Double.toString(param)); 49 | b1 = b1.add(b2); 50 | } 51 | return b1.doubleValue(); 52 | } 53 | 54 | /** 55 | * 提供精确的减法运算 56 | * 57 | * @param v1 被减数 58 | * @param v2 减数 59 | * @return 两个参数的差 60 | */ 61 | public static double sub(double v1, double v2) { 62 | BigDecimal b1 = new BigDecimal(Double.toString(v1)); 63 | BigDecimal b2 = new BigDecimal(Double.toString(v2)); 64 | return b1.subtract(b2).doubleValue(); 65 | } 66 | 67 | /** 68 | * 提供精确的乘法运算 69 | * 70 | * @param params 参数数组 71 | * @return 动态参数的积 72 | */ 73 | public static double mul(double... params) { 74 | BigDecimal b1 = new BigDecimal(1); 75 | for (double param : params) { 76 | BigDecimal b2 = new BigDecimal(Double.toString(param)); 77 | b1 = b1.multiply(b2); 78 | } 79 | return b1.doubleValue(); 80 | } 81 | 82 | /** 83 | * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入 84 | * 85 | * @param v1 被除数 86 | * @param v2 除数 87 | * @return 两个参数的商 88 | */ 89 | public static double div(double v1, double v2) { 90 | return div(v1, v2, DEF_DIV_POINT); 91 | } 92 | 93 | /** 94 | * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入 95 | * 96 | * @param v1 被除数 97 | * @param v2 除数 98 | * @param point 表示需要精确到小数点以后几位 99 | * @return 两个参数的商 100 | */ 101 | public static double div(double v1, double v2, int point) { 102 | if (point < 0) { 103 | throw new IllegalArgumentException("The point must be a positive integer or zero"); 104 | } 105 | BigDecimal b1 = new BigDecimal(Double.toString(v1)); 106 | BigDecimal b2 = new BigDecimal(Double.toString(v2)); 107 | return b1.divide(b2, point, BigDecimal.ROUND_HALF_UP).doubleValue(); 108 | } 109 | 110 | /** 111 | * 提供精确的小数位四舍五入处理 112 | * 113 | * @param v 需要四舍五入的数字 114 | * @param point 小数点后保留几位 115 | * @return 四舍五入后的结果 116 | */ 117 | public static double round(double v, int point) { 118 | if (point < 0) { 119 | throw new IllegalArgumentException("The point must be a positive integer or zero"); 120 | } 121 | BigDecimal b = new BigDecimal(Double.toString(v)); 122 | BigDecimal one = new BigDecimal("1"); 123 | return b.divide(one, point, BigDecimal.ROUND_HALF_UP).doubleValue(); 124 | } 125 | 126 | /** 127 | * 提供精确的小数位(2位)四舍五入处理 128 | * 129 | * @param v 需要四舍五入的数字 130 | * @return 四舍五入后的结果 131 | */ 132 | public static double round(double v) { 133 | BigDecimal b = new BigDecimal(Double.toString(v)); 134 | BigDecimal one = new BigDecimal("1"); 135 | return b.divide(one, 2, BigDecimal.ROUND_HALF_UP).doubleValue(); 136 | } 137 | 138 | /** 139 | * 提供精确的小数位四舍五入处理 140 | * 141 | * @param v 需要四舍五入的数字字符串 142 | * @param point 小数点后保留几位 143 | * @return 四舍五入后的结果 144 | */ 145 | public static double round(String v, int point) { 146 | if (point < 0) { 147 | throw new IllegalArgumentException("The point must be a positive integer or zero"); 148 | } 149 | BigDecimal b = new BigDecimal(v); 150 | BigDecimal one = new BigDecimal("1"); 151 | return b.divide(one, point, BigDecimal.ROUND_HALF_UP).doubleValue(); 152 | } 153 | 154 | /** 155 | * 提供精确的小数位(2位)四舍五入处理 156 | * 157 | * @param v 需要四舍五入的数字字符串 158 | * @return 四舍五入后的结果 159 | */ 160 | public static double round(String v) { 161 | if (StringUtil.isBlank(v)) { 162 | return 0; 163 | } 164 | BigDecimal b = new BigDecimal(v); 165 | BigDecimal one = new BigDecimal("1"); 166 | return b.divide(one, 2, BigDecimal.ROUND_HALF_UP).doubleValue(); 167 | } 168 | 169 | /** 170 | * 金额格式化 171 | * 172 | * @param s 金额 173 | * @param len 小数位数 174 | * @return 格式后的金额 175 | */ 176 | 177 | public static String insertComma(String s, int len) { 178 | if (s == null || s.length() < 1) { 179 | return ""; 180 | } 181 | NumberFormat formater = null; 182 | double num = Double.parseDouble(s); 183 | if (len == 0) { 184 | formater = new DecimalFormat("###,###"); 185 | } else { 186 | StringBuffer buff = new StringBuffer(); 187 | buff.append("###,###."); 188 | for (int i = 0; i < len; i++) { 189 | buff.append("#"); 190 | } 191 | formater = new DecimalFormat(buff.toString()); 192 | } 193 | return formater.format(num); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/net/HttpUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.net; 2 | 3 | import com.github.javautils.string.StringUtil; 4 | 5 | import javax.net.ssl.*; 6 | import javax.servlet.http.HttpServletRequest; 7 | import java.io.*; 8 | import java.net.HttpURLConnection; 9 | import java.net.URL; 10 | import java.net.URLEncoder; 11 | import java.security.KeyManagementException; 12 | import java.security.NoSuchAlgorithmException; 13 | import java.security.NoSuchProviderException; 14 | import java.security.cert.CertificateException; 15 | import java.security.cert.X509Certificate; 16 | import java.util.Map; 17 | 18 | public class HttpUtil { 19 | 20 | private HttpUtil() { 21 | } 22 | 23 | /** 24 | * https 域名校验 25 | */ 26 | private class TrustAnyHostnameVerifier implements HostnameVerifier { 27 | public boolean verify(String hostname, SSLSession session) { 28 | return true; 29 | } 30 | } 31 | 32 | /** 33 | * https 证书管理 34 | */ 35 | private class TrustAnyTrustManager implements X509TrustManager { 36 | public X509Certificate[] getAcceptedIssuers() { 37 | return null; 38 | } 39 | 40 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 41 | } 42 | 43 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 44 | } 45 | } 46 | 47 | private static final String GET = "GET"; 48 | private static final String POST = "POST"; 49 | private static String CHARSET = "UTF-8"; 50 | 51 | private static final SSLSocketFactory sslSocketFactory = initSSLSocketFactory(); 52 | private static final TrustAnyHostnameVerifier trustAnyHostnameVerifier = new HttpUtil().new TrustAnyHostnameVerifier(); 53 | 54 | private static SSLSocketFactory initSSLSocketFactory() { 55 | try { 56 | TrustManager[] tm = {new HttpUtil().new TrustAnyTrustManager()}; 57 | SSLContext sslContext = SSLContext.getInstance("TLS"); // ("TLS", "SunJSSE"); 58 | sslContext.init(null, tm, new java.security.SecureRandom()); 59 | return sslContext.getSocketFactory(); 60 | } catch (Exception e) { 61 | throw new RuntimeException(e); 62 | } 63 | } 64 | 65 | public static void setCharSet(String charSet) { 66 | if (StringUtil.isBlank(charSet)) { 67 | throw new IllegalArgumentException("charSet can not be blank."); 68 | } 69 | HttpUtil.CHARSET = charSet; 70 | } 71 | 72 | private static HttpURLConnection getHttpConnection(String url, String method, Map headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { 73 | URL _url = new URL(url); 74 | HttpURLConnection conn = (HttpURLConnection) _url.openConnection(); 75 | if (conn instanceof HttpsURLConnection) { 76 | ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory); 77 | ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier); 78 | } 79 | 80 | conn.setRequestMethod(method); 81 | conn.setDoOutput(true); 82 | conn.setDoInput(true); 83 | 84 | conn.setConnectTimeout(19000); 85 | conn.setReadTimeout(19000); 86 | 87 | conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 88 | conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); 89 | 90 | if (headers != null && !headers.isEmpty()) 91 | for (Map.Entry entry : headers.entrySet()) 92 | conn.setRequestProperty(entry.getKey(), entry.getValue()); 93 | 94 | return conn; 95 | } 96 | 97 | /** 98 | * Send GET request 99 | */ 100 | public static String get(String url, Map queryParas, Map headers) { 101 | HttpURLConnection conn = null; 102 | try { 103 | conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), GET, headers); 104 | conn.connect(); 105 | return readResponseString(conn); 106 | } catch (Exception e) { 107 | throw new RuntimeException(e); 108 | } finally { 109 | if (conn != null) { 110 | conn.disconnect(); 111 | } 112 | } 113 | } 114 | 115 | public static String get(String url, Map queryParas) { 116 | return get(url, queryParas, null); 117 | } 118 | 119 | public static String get(String url) { 120 | return get(url, null, null); 121 | } 122 | 123 | /** 124 | * Send POST request 125 | */ 126 | public static String post(String url, Map queryParas, String data, Map headers) { 127 | HttpURLConnection conn = null; 128 | try { 129 | conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers); 130 | conn.connect(); 131 | 132 | OutputStream out = conn.getOutputStream(); 133 | out.write(data.getBytes(CHARSET)); 134 | out.flush(); 135 | out.close(); 136 | 137 | return readResponseString(conn); 138 | } catch (Exception e) { 139 | throw new RuntimeException(e); 140 | } finally { 141 | if (conn != null) { 142 | conn.disconnect(); 143 | } 144 | } 145 | } 146 | 147 | public static String post(String url, Map queryParas, String data) { 148 | return post(url, queryParas, data, null); 149 | } 150 | 151 | public static String post(String url, String data, Map headers) { 152 | return post(url, null, data, headers); 153 | } 154 | 155 | public static String post(String url, String data) { 156 | return post(url, null, data, null); 157 | } 158 | 159 | private static String readResponseString(HttpURLConnection conn) { 160 | StringBuilder sb = new StringBuilder(); 161 | InputStream inputStream = null; 162 | try { 163 | inputStream = conn.getInputStream(); 164 | BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET)); 165 | String line = null; 166 | while ((line = reader.readLine()) != null) { 167 | sb.append(line).append("\n"); 168 | } 169 | return sb.toString(); 170 | } catch (Exception e) { 171 | throw new RuntimeException(e); 172 | } finally { 173 | if (inputStream != null) { 174 | try { 175 | inputStream.close(); 176 | } catch (IOException e) { 177 | e.printStackTrace(); 178 | } 179 | } 180 | } 181 | } 182 | 183 | /** 184 | * Build queryString of the url 185 | */ 186 | private static String buildUrlWithQueryString(String url, Map queryParas) { 187 | if (queryParas == null || queryParas.isEmpty()) 188 | return url; 189 | 190 | StringBuilder sb = new StringBuilder(url); 191 | boolean isFirst; 192 | if (!url.contains("?")) { 193 | isFirst = true; 194 | sb.append("?"); 195 | } else { 196 | isFirst = false; 197 | } 198 | 199 | for (Map.Entry entry : queryParas.entrySet()) { 200 | if (isFirst) isFirst = false; 201 | else sb.append("&"); 202 | 203 | String key = entry.getKey(); 204 | String value = entry.getValue(); 205 | if (StringUtil.notBlank(value)) 206 | try { 207 | value = URLEncoder.encode(value, CHARSET); 208 | } catch (UnsupportedEncodingException e) { 209 | throw new RuntimeException(e); 210 | } 211 | sb.append(key).append("=").append(value); 212 | } 213 | return sb.toString(); 214 | } 215 | 216 | public static String readData(HttpServletRequest request) { 217 | BufferedReader br = null; 218 | try { 219 | StringBuilder result = new StringBuilder(); 220 | br = request.getReader(); 221 | for (String line; (line = br.readLine()) != null; ) { 222 | if (result.length() > 0) { 223 | result.append("\n"); 224 | } 225 | result.append(line); 226 | } 227 | 228 | return result.toString(); 229 | } catch (IOException e) { 230 | throw new RuntimeException(e); 231 | } finally { 232 | if (br != null) 233 | try { 234 | br.close(); 235 | } catch (IOException e) { 236 | e.printStackTrace(); 237 | } 238 | } 239 | } 240 | 241 | } -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/net/IpUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.net; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | public class IpUtil { 6 | public IpUtil() { 7 | } 8 | 9 | public static String getIpAddr(HttpServletRequest request) { 10 | String ip = request.getHeader("x-forwarded-for"); 11 | if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 12 | ip = request.getHeader("Proxy-Client-IP"); 13 | } 14 | 15 | if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 16 | ip = request.getHeader("WL-Proxy-Client-IP"); 17 | } 18 | 19 | if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 20 | ip = request.getRemoteAddr(); 21 | } 22 | 23 | return ip; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/net/RequestUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.net; 2 | 3 | import com.github.javautils.string.StringUtil; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | 7 | /** 8 | * Created by tomoya on 16/9/27. 9 | */ 10 | public class RequestUtil { 11 | 12 | /** 13 | * 获取重定向之前的请求完整路径 14 | * @param request 15 | * @return 16 | */ 17 | public static String getBeforeUrl(HttpServletRequest request) { 18 | String url = request.getRequestURL().toString(); 19 | String query = request.getQueryString(); 20 | if(StringUtil.notBlank(query)) { 21 | url += "?" + query; 22 | } 23 | return url; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/regular/Regular.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.regular; 2 | 3 | /** 4 | * Created by tomoya on 16/8/31. 5 | */ 6 | public interface Regular { 7 | 8 | /** 9 | * 邮件正则 10 | */ 11 | String EMAIL = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; 12 | 13 | /** 14 | * html标签正则 15 | */ 16 | String HTML = "<[.[^<]]*>"; 17 | 18 | /** 19 | * 查找一段文本里以 @ 开头的正则 20 | */ 21 | String AT = "@([a-zA-Z_0-9-/b]+)\\s"; 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/string/StringUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.string; 2 | 3 | import com.github.javautils.encrypt.EncryptionUtil; 4 | import com.github.javautils.regular.Regular; 5 | 6 | import java.util.*; 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | 10 | public class StringUtil { 11 | 12 | static final char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 13 | static final char[] digits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; 14 | static final Random rand = new Random(); 15 | 16 | /** 17 | * 首字母变小写 18 | */ 19 | public static String firstCharToLowerCase(String str) { 20 | char firstChar = str.charAt(0); 21 | if (firstChar >= 'A' && firstChar <= 'Z') { 22 | char[] arr = str.toCharArray(); 23 | arr[0] += ('a' - 'A'); 24 | return new String(arr); 25 | } 26 | return str; 27 | } 28 | 29 | /** 30 | * 首字母变大写 31 | */ 32 | public static String firstCharToUpperCase(String str) { 33 | char firstChar = str.charAt(0); 34 | if (firstChar >= 'a' && firstChar <= 'z') { 35 | char[] arr = str.toCharArray(); 36 | arr[0] -= ('a' - 'A'); 37 | return new String(arr); 38 | } 39 | return str; 40 | } 41 | 42 | /** 43 | * 字符串为 null 或者为 "" 时返回 true 44 | */ 45 | public static boolean isBlank(String str) { 46 | return str == null || "".equals(str.trim()); 47 | } 48 | 49 | /** 50 | * 字符串不为 null 而且不为 "" 时返回 true 51 | */ 52 | public static boolean notBlank(String str) { 53 | return str != null && !"".equals(str.trim()); 54 | } 55 | 56 | public static boolean notBlank(String... strings) { 57 | if (strings == null) 58 | return false; 59 | for (String str : strings) 60 | if (str == null || "".equals(str.trim())) 61 | return false; 62 | return true; 63 | } 64 | 65 | public static boolean notNull(Object... paras) { 66 | if (paras == null) 67 | return false; 68 | for (Object obj : paras) 69 | if (obj == null) 70 | return false; 71 | return true; 72 | } 73 | 74 | public static String toCamelCase(String stringWithUnderline) { 75 | if (stringWithUnderline.indexOf('_') == -1) 76 | return stringWithUnderline; 77 | 78 | stringWithUnderline = stringWithUnderline.toLowerCase(); 79 | char[] fromArray = stringWithUnderline.toCharArray(); 80 | char[] toArray = new char[fromArray.length]; 81 | int j = 0; 82 | for (int i = 0; i < fromArray.length; i++) { 83 | if (fromArray[i] == '_') { 84 | // 当前字符为下划线时,将指针后移一位,将紧随下划线后面一个字符转成大写并存放 85 | i++; 86 | if (i < fromArray.length) 87 | toArray[j++] = Character.toUpperCase(fromArray[i]); 88 | } else { 89 | toArray[j++] = fromArray[i]; 90 | } 91 | } 92 | return new String(toArray, 0, j); 93 | } 94 | 95 | public static String join(String[] stringArray) { 96 | StringBuilder sb = new StringBuilder(); 97 | for (String s : stringArray) 98 | sb.append(s); 99 | return sb.toString(); 100 | } 101 | 102 | public static String join(String[] stringArray, String separator) { 103 | StringBuilder sb = new StringBuilder(); 104 | for (int i = 0; i < stringArray.length; i++) { 105 | if (i > 0) 106 | sb.append(separator); 107 | sb.append(stringArray[i]); 108 | } 109 | return sb.toString(); 110 | } 111 | 112 | /** 113 | * 验证email的合法性 114 | * 115 | * @param email 116 | * @return 117 | */ 118 | public static boolean isEmail(String email) { 119 | if (isBlank(email)) { 120 | return false; 121 | } else { 122 | Pattern pattern = Pattern.compile(Regular.EMAIL); 123 | Matcher matcher = pattern.matcher(email); 124 | return matcher.matches(); 125 | } 126 | } 127 | 128 | /** 129 | * 后去一串去掉 - 的uuid字符串 130 | * 131 | * @return 132 | */ 133 | public static String getUUID() { 134 | String uuid = UUID.randomUUID().toString(); 135 | return uuid.replaceAll("-", ""); 136 | } 137 | 138 | /** 139 | * 随机指定长度的字符串 140 | * 141 | * @param length 142 | * @return 143 | */ 144 | public static String randomString(int length) { 145 | StringBuffer sb = new StringBuffer(); 146 | for (int loop = 0; loop < length; ++loop) { 147 | sb.append(hexDigits[rand.nextInt(hexDigits.length)]); 148 | } 149 | return sb.toString(); 150 | } 151 | 152 | /** 153 | * 随机指定长度的数字 154 | * 155 | * @param length 156 | * @return 157 | */ 158 | public static String randomNumber(int length) { 159 | StringBuffer sb = new StringBuffer(); 160 | for (int loop = 0; loop < length; ++loop) { 161 | sb.append(digits[rand.nextInt(digits.length)]); 162 | } 163 | return sb.toString(); 164 | } 165 | 166 | /** 167 | * 将html过滤掉 168 | * 169 | * @param s 170 | * @return 171 | */ 172 | public static String noHtml(String s) { 173 | if (isBlank(s)) return ""; 174 | else return s.replaceAll(Regular.HTML, ""); 175 | } 176 | 177 | /** 178 | * 转义html 179 | * 180 | * @param s 181 | * @return 182 | */ 183 | public static String transHtml(String s) { 184 | if (isBlank(s)) return ""; 185 | else return s.replace("<", "<").replace(">", ">"); 186 | } 187 | 188 | /** 189 | * 查找一段文本里以 @ 开头的字符串 190 | * 191 | * @param str 192 | * @return 193 | */ 194 | public static List fetchUsers(String str) { 195 | List ats = new ArrayList(); 196 | String pattern = Regular.AT; 197 | Pattern regex = Pattern.compile(pattern); 198 | Matcher regexMatcher = regex.matcher(str); 199 | while (regexMatcher.find()) { 200 | ats.add(regexMatcher.group(1)); 201 | } 202 | return ats; 203 | } 204 | 205 | public static int str2int(String s) { 206 | if (s == null || s.equals("")) { 207 | return 0; 208 | } else { 209 | return Integer.parseInt(s); 210 | } 211 | } 212 | 213 | /** 214 | * json字符串转换成 Map 215 | * 依赖Gson包 216 | */ 217 | // public static Map parseToMap(String jsonString) { 218 | // return new Gson().fromJson(jsonString, new TypeToken>() {}.getType()); 219 | // } 220 | 221 | } -------------------------------------------------------------------------------- /src/main/java/com/github/javautils/web/CookieUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.javautils.web; 2 | 3 | import javax.servlet.http.Cookie; 4 | import javax.servlet.http.HttpServletRequest; 5 | import javax.servlet.http.HttpServletResponse; 6 | 7 | public final class CookieUtils { 8 | 9 | private HttpServletRequest request; 10 | private HttpServletResponse response; 11 | 12 | public CookieUtils(HttpServletRequest request, HttpServletResponse response) { 13 | this.request = request; 14 | this.response = response; 15 | } 16 | 17 | /** 18 | * Get cookie value by cookie name. 19 | */ 20 | public String getCookie(String name, String defaultValue) { 21 | Cookie cookie = getCookieObject(name); 22 | return cookie != null ? cookie.getValue() : defaultValue; 23 | } 24 | 25 | /** 26 | * Get cookie value by cookie name. 27 | */ 28 | public String getCookie(String name) { 29 | return getCookie(name, null); 30 | } 31 | 32 | /** 33 | * Get cookie value by cookie name and convert to Integer. 34 | */ 35 | public Integer getCookieToInt(String name) { 36 | String result = getCookie(name); 37 | return result != null ? Integer.parseInt(result) : null; 38 | } 39 | 40 | /** 41 | * Get cookie value by cookie name and convert to Integer. 42 | */ 43 | public Integer getCookieToInt(String name, Integer defaultValue) { 44 | String result = getCookie(name); 45 | return result != null ? Integer.parseInt(result) : defaultValue; 46 | } 47 | 48 | /** 49 | * Get cookie value by cookie name and convert to Long. 50 | */ 51 | public Long getCookieToLong(String name) { 52 | String result = getCookie(name); 53 | return result != null ? Long.parseLong(result) : null; 54 | } 55 | 56 | /** 57 | * Get cookie value by cookie name and convert to Long. 58 | */ 59 | public Long getCookieToLong(String name, Long defaultValue) { 60 | String result = getCookie(name); 61 | return result != null ? Long.parseLong(result) : defaultValue; 62 | } 63 | 64 | /** 65 | * Get cookie object by cookie name. 66 | */ 67 | public Cookie getCookieObject(String name) { 68 | Cookie[] cookies = request.getCookies(); 69 | if (cookies != null) 70 | for (Cookie cookie : cookies) 71 | if (cookie.getName().equals(name)) 72 | return cookie; 73 | return null; 74 | } 75 | 76 | /** 77 | * Get all cookie objects. 78 | */ 79 | public Cookie[] getCookieObjects() { 80 | Cookie[] result = request.getCookies(); 81 | return result != null ? result : new Cookie[0]; 82 | } 83 | 84 | /** 85 | * Set Cookie. 86 | * @param name cookie name 87 | * @param value cookie value 88 | * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately. n>0 : max age in n seconds. 89 | * @param isHttpOnly true if this cookie is to be marked as HttpOnly, false otherwise 90 | */ 91 | public void setCookie(String name, String value, int maxAgeInSeconds, boolean isHttpOnly) { 92 | doSetCookie(name, value, maxAgeInSeconds, null, null, isHttpOnly); 93 | } 94 | 95 | /** 96 | * Set Cookie. 97 | * @param name cookie name 98 | * @param value cookie value 99 | * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately. n>0 : max age in n seconds. 100 | */ 101 | public void setCookie(String name, String value, int maxAgeInSeconds) { 102 | doSetCookie(name, value, maxAgeInSeconds, null, null, null); 103 | } 104 | 105 | /** 106 | * Set Cookie to response. 107 | */ 108 | public void setCookie(HttpServletResponse response, Cookie cookie) { 109 | response.addCookie(cookie); 110 | } 111 | 112 | /** 113 | * Set Cookie to response. 114 | * @param name cookie name 115 | * @param value cookie value 116 | * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately. n>0 : max age in n seconds. 117 | * @param path see Cookie.setPath(String) 118 | * @param isHttpOnly true if this cookie is to be marked as HttpOnly, false otherwise 119 | */ 120 | public void setCookie(String name, String value, int maxAgeInSeconds, String path, boolean isHttpOnly) { 121 | doSetCookie(name, value, maxAgeInSeconds, path, null, isHttpOnly); 122 | } 123 | 124 | /** 125 | * Set Cookie to response. 126 | * @param name cookie name 127 | * @param value cookie value 128 | * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately. n>0 : max age in n seconds. 129 | * @param path see Cookie.setPath(String) 130 | */ 131 | public void setCookie(String name, String value, int maxAgeInSeconds, String path) { 132 | doSetCookie(name, value, maxAgeInSeconds, path, null, null); 133 | } 134 | 135 | /** 136 | * Set Cookie to response. 137 | * @param name cookie name 138 | * @param value cookie value 139 | * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately. n>0 : max age in n seconds. 140 | * @param path see Cookie.setPath(String) 141 | * @param domain the domain name within which this cookie is visible; form is according to RFC 2109 142 | * @param isHttpOnly true if this cookie is to be marked as HttpOnly, false otherwise 143 | */ 144 | public void setCookie(String name, String value, int maxAgeInSeconds, String path, String domain, boolean isHttpOnly) { 145 | doSetCookie(name, value, maxAgeInSeconds, path, domain, isHttpOnly); 146 | } 147 | 148 | /** 149 | * Remove Cookie. 150 | */ 151 | public void removeCookie(String name) { 152 | doSetCookie(name, null, 0, null, null, null); 153 | } 154 | 155 | /** 156 | * Remove Cookie. 157 | */ 158 | public void removeCookie(String name, String path) { 159 | doSetCookie(name, null, 0, path, null, null); 160 | } 161 | 162 | /** 163 | * Remove Cookie. 164 | */ 165 | public void removeCookie(String name, String path, String domain) { 166 | doSetCookie(name, null, 0, path, domain, null); 167 | } 168 | 169 | private void doSetCookie(String name, String value, int maxAgeInSeconds, String path, String domain, Boolean isHttpOnly) { 170 | Cookie cookie = new Cookie(name, value); 171 | cookie.setMaxAge(maxAgeInSeconds); 172 | // set the default path value to "/" 173 | if (path == null) { 174 | path = "/"; 175 | } 176 | cookie.setPath(path); 177 | 178 | if (domain != null) { 179 | cookie.setDomain(domain); 180 | } 181 | if (isHttpOnly != null) { 182 | cookie.setHttpOnly(isHttpOnly); 183 | } 184 | response.addCookie(cookie); 185 | } 186 | 187 | } --------------------------------------------------------------------------------