Commit 3647b776 by stylefeng

抽象出工具类和异常

parent 461f2460
......@@ -15,6 +15,30 @@
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
package com.stylefeng;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
package com.stylefeng.guns.core.exception;
/**
* @Description 业务异常的封装
* @author fengshuonan
* @date 2016年11月12日 下午5:05:10
*/
@SuppressWarnings("serial")
public class GunsException extends RuntimeException{
//友好提示的code码
private int friendlyCode;
//友好提示
private String friendlyMsg;
//业务异常跳转的页面
private String urlPath;
public GunsException(GunsExceptionEnum bizExceptionEnum){
this.friendlyCode = bizExceptionEnum.getCode();
this.friendlyMsg = bizExceptionEnum.getMessage();
this.urlPath = bizExceptionEnum.getUrlPath();
}
public int getCode() {
return friendlyCode;
}
public void setCode(int code) {
this.friendlyCode = code;
}
public String getMessage() {
return friendlyMsg;
}
public void setMessage(String message) {
this.friendlyMsg = message;
}
public String getUrlPath() {
return urlPath;
}
public void setUrlPath(String urlPath) {
this.urlPath = urlPath;
}
}
package com.stylefeng.guns.core.exception;
/**
* @Description 所有业务异常的枚举
* @author fengshuonan
* @date 2016年11月12日 下午5:04:51
*/
public enum GunsExceptionEnum {
/**
* 文件上传
*/
FILE_READING_ERROR(400,"FILE_READING_ERROR!"),
FILE_NOT_FOUND(400,"FILE_NOT_FOUND!"),
/**
* 错误的请求
*/
REQUEST_NULL(400, "请求有错误"),
SERVER_ERROR(500, "服务器异常");
GunsExceptionEnum(int code, String message) {
this.friendlyCode = code;
this.friendlyMsg = message;
}
GunsExceptionEnum(int code, String message, String urlPath) {
this.friendlyCode = code;
this.friendlyMsg = message;
this.urlPath = urlPath;
}
private int friendlyCode;
private String friendlyMsg;
private String urlPath;
public int getCode() {
return friendlyCode;
}
public void setCode(int code) {
this.friendlyCode = code;
}
public String getMessage() {
return friendlyMsg;
}
public void setMessage(String message) {
this.friendlyMsg = message;
}
public String getUrlPath() {
return urlPath;
}
public void setUrlPath(String urlPath) {
this.urlPath = urlPath;
}
}
/**
* Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stylefeng.guns.core.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
/**
* 获取YYYY格式
*
* @return
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 获取YYYY格式
*
* @return
*/
public static String getYear(Date date) {
return formatDate(date, "yyyy");
}
/**
* 获取YYYY-MM-DD格式
*
* @return
*/
public static String getDay() {
return formatDate(new Date(), "yyyy-MM-dd");
}
/**
* 获取YYYY-MM-DD格式
*
* @return
*/
public static String getDay(Date date) {
return formatDate(date, "yyyy-MM-dd");
}
/**
* 获取YYYYMMDD格式
*
* @return
*/
public static String getDays() {
return formatDate(new Date(), "yyyyMMdd");
}
/**
* 获取YYYYMMDD格式
*
* @return
*/
public static String getDays(Date date) {
return formatDate(date, "yyyyMMdd");
}
/**
* 获取YYYY-MM-DD HH:mm:ss格式
*
* @return
*/
public static String getTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 获取YYYY-MM-DD HH:mm:ss.SSS格式
*
* @return
*/
public static String getMsTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
}
/**
* 获取YYYYMMDDHHmmss格式
*
* @return
*/
public static String getAllTime() {
return formatDate(new Date(), "yyyyMMddHHmmss");
}
/**
* 获取YYYY-MM-DD HH:mm:ss格式
*
* @return
*/
public static String getTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
public static String formatDate(Date date, String pattern) {
String formatDate = null;
if (StringUtils.isNotBlank(pattern)) {
formatDate = DateFormatUtils.format(date, pattern);
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* @Title: compareDate
* @Description:(日期比较,如果s>=e 返回true 否则返回false)
* @param s
* @param e
* @return boolean
* @throws
* @author luguosui
*/
public static boolean compareDate(String s, String e) {
if (parseDate(s) == null || parseDate(e) == null) {
return false;
}
return parseDate(s).getTime() >= parseDate(e).getTime();
}
/**
* 格式化日期
*
* @return
*/
public static Date parseDate(String date) {
return parse(date,"yyyy-MM-dd");
}
/**
* 格式化日期
*
* @return
*/
public static Date parseTime(String date) {
return parse(date,"yyyy-MM-dd HH:mm:ss");
}
/**
* 格式化日期
*
* @return
*/
public static Date parse(String date, String pattern) {
try {
return DateUtils.parseDate(date,pattern);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 格式化日期
*
* @return
*/
public static String format(Date date, String pattern) {
return DateFormatUtils.format(date, pattern);
}
/**
* 把日期转换为Timestamp
*
* @param date
* @return
*/
public static Timestamp format(Date date) {
return new Timestamp(date.getTime());
}
/**
* 校验日期是否合法
*
* @return
*/
public static boolean isValidDate(String s) {
return parse(s, "yyyy-MM-dd HH:mm:ss") != null;
}
/**
* 校验日期是否合法
*
* @return
*/
public static boolean isValidDate(String s, String pattern) {
return parse(s, pattern) != null;
}
public static int getDiffYear(String startTime, String endTime) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(
startTime).getTime()) / (1000 * 60 * 60 * 24)) / 365);
return years;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return 0;
}
}
/**
* <li>功能描述:时间相减得到天数
*
* @param beginDateStr
* @param endDateStr
* @return long
* @author Administrator
*/
public static long getDaySub(String beginDateStr, String endDateStr) {
long day = 0;
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd");
Date beginDate = null;
Date endDate = null;
try {
beginDate = format.parse(beginDateStr);
endDate = format.parse(endDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
// System.out.println("相隔的天数="+day);
return day;
}
/**
* 得到n天之后的日期
*
* @param days
* @return
*/
public static String getAfterDayDate(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sdfd.format(date);
return dateStr;
}
/**
* 得到n天之后是周几
*
* @param days
* @return
*/
public static String getAfterDayWeek(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("E");
String dateStr = sdf.format(date);
return dateStr;
}
/**
* 格式化Oracle Date
* @param value
* @return
*/
// public static String buildDateValue(Object value){
// if(Func.isOracle()){
// return "to_date('"+ value +"','yyyy-mm-dd HH24:MI:SS')";
// }else{
// return Func.toStr(value);
// }
// }
public static void main(String[] args) {
System.out.println(getTime(new Date()));
System.out.println(getAfterDayWeek("3"));
}
}
package com.stylefeng.guns.core.util;
import com.stylefeng.guns.core.exception.GunsExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileUtil {
private static Logger log = LoggerFactory.getLogger(FileUtil.class);
/**
* NIO way
*/
public static byte[] toByteArray(String filename) {
File f = new File(filename);
if (!f.exists()) {
log.error("文件未找到!" + filename);
throw new GunsException(GunsExceptionEnum.FILE_NOT_FOUND);
}
FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
// System.out.println("reading");
}
return byteBuffer.array();
} catch (IOException e) {
throw new GunsException(GunsExceptionEnum.FILE_READING_ERROR);
} finally {
try {
channel.close();
} catch (IOException e) {
throw new GunsException(GunsExceptionEnum.FILE_READING_ERROR);
}
try {
fs.close();
} catch (IOException e) {
throw new GunsException(GunsExceptionEnum.FILE_READING_ERROR);
}
}
}
}
\ No newline at end of file
package com.stylefeng.guns.core.util;
import javax.servlet.http.HttpSession;
/**
* 非Controller中获取当前session的工具类
*
* @author fengshuonan
* @date 2016年11月28日 上午10:24:31
*/
public class HttpSessionHolder {
private static ThreadLocal<HttpSession> tl = new ThreadLocal<HttpSession>();
public static void put(HttpSession s) {
tl.set(s);
}
public static HttpSession get() {
return tl.get();
}
public static void remove() {
tl.remove();
}
}
package com.stylefeng.guns.core.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5加密类(封装jdk自带的md5加密方法)
*
* @author fengshuonan
* @date 2016年12月2日 下午4:14:22
*/
public class MD5Util {
public static String encrypt(String source) {
return encodeMd5(source.getBytes());
}
private static String encodeMd5(byte[] source) {
try {
return encodeHex(MessageDigest.getInstance("MD5").digest(source));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
private static String encodeHex(byte[] bytes) {
StringBuffer buffer = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10)
buffer.append("0");
buffer.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buffer.toString();
}
public static void main(String[] args) {
System.out.println(encrypt("123456"));
}
}
package com.stylefeng.guns.core.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* 数字格式化的类
*
* @author fengshuonan
* @date 2016年11月30日 下午5:58:40
*/
public class NumUtil {
/**
* @Description 保留指定位数的小数(少的位数不补零)
* @author fengshuonan
*/
public static String keepRandomPoint(Double value, int n) {
if (value == null) {
value = 0.00;
return new BigDecimal(value).setScale(n, RoundingMode.HALF_UP).toString();
} else {
return new BigDecimal(value).setScale(n, RoundingMode.HALF_UP).toString();
}
}
/**
* @Description 浮点保留两位小数(少的位数不补零)
* @author fengshuonan
*/
public static String keep2Point(double value) {
return keepRandomPoint(value, 2);
}
/**
* @Description 浮点保留1位小数(少的位数不补零)
* @author fengshuonan
*/
public static String keep1Point(double value) {
return keepRandomPoint(value, 1);
}
/**
* @Description 浮点保留任意位小数(少位补零)
* @author fengshuonan
*/
public static String keepRandomPointZero(double value, int n) {
DecimalFormat df = new DecimalFormat("#0.00");
return df.format(Double.valueOf(keepRandomPoint(value, n)));
}
/**
* @Description 浮点保留两位小数(少位补零)
* @author fengshuonan
*/
public static String keep2PointZero(double value) {
return keepRandomPointZero(value, 2);
}
/**
* @Description 获取任意小数点位的百分比表示
* @author fengshuonan
*/
public static String percentRandomPoint(double value, int n) {
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setGroupingUsed(false);
percent.setMaximumFractionDigits(n);
return percent.format(value);
}
/**
* @Description 百分比保留两位小数
* @author fengshuonan
*/
public static String percent2Point(double value) {
return percentRandomPoint(value, 2);
}
/**
* @Description 获取格式化经纬度后的小数(保留3位)
* @author fengshuonan
*/
public static String latLngPoint(double value) {
return keepRandomPoint(value, 3);
}
}
package com.stylefeng.guns.core.util;
import java.util.Random;
/***
*
* 得到中文首字母
*
* @author lxm_09
*
*/
public class PingYinUtil {
public static void main(String[] args) {
String str = "这是一个测试";
System.out.println("中文首字母:" + getPYIndexStr(str, true));
}
/**
* 返回首字母
*/
public static String getPYIndexStr(String strChinese, boolean bUpCase) {
try {
StringBuffer buffer = new StringBuffer();
byte b[] = strChinese.getBytes("GBK");// 把中文转化成byte数组
for (int i = 0; i < b.length; i++) {
if ((b[i] & 255) > 128) {
int char1 = b[i++] & 255;
char1 <<= 8;// 左移运算符用“<<”表示,是将运算符左边的对象,向左移动运算符右边指定的位数,并且在低位补零。其实,向左移n位,就相当于乘上2的n次方
int chart = char1 + (b[i] & 255);
buffer.append(getPYIndexChar((char) chart, bUpCase));
continue;
}
char c = (char) b[i];
if (!Character.isJavaIdentifierPart(c))// 确定指定字符是否可以是 Java
// 标识符中首字符以外的部分。
c = 'A';
buffer.append(c);
}
return buffer.toString();
} catch (Exception e) {
System.out.println((new StringBuilder()).append("\u53D6\u4E2D\u6587\u62FC\u97F3\u6709\u9519")
.append(e.getMessage()).toString());
}
return null;
}
/**
* 得到首字母
*/
private static char getPYIndexChar(char strChinese, boolean bUpCase) {
int charGBK = strChinese;
char result;
if (charGBK >= 45217 && charGBK <= 45252)
result = 'A';
else
if (charGBK >= 45253 && charGBK <= 45760)
result = 'B';
else
if (charGBK >= 45761 && charGBK <= 46317)
result = 'C';
else
if (charGBK >= 46318 && charGBK <= 46825)
result = 'D';
else
if (charGBK >= 46826 && charGBK <= 47009)
result = 'E';
else
if (charGBK >= 47010 && charGBK <= 47296)
result = 'F';
else
if (charGBK >= 47297 && charGBK <= 47613)
result = 'G';
else
if (charGBK >= 47614 && charGBK <= 48118)
result = 'H';
else
if (charGBK >= 48119 && charGBK <= 49061)
result = 'J';
else
if (charGBK >= 49062 && charGBK <= 49323)
result = 'K';
else
if (charGBK >= 49324 && charGBK <= 49895)
result = 'L';
else
if (charGBK >= 49896 && charGBK <= 50370)
result = 'M';
else
if (charGBK >= 50371 && charGBK <= 50613)
result = 'N';
else
if (charGBK >= 50614 && charGBK <= 50621)
result = 'O';
else
if (charGBK >= 50622 && charGBK <= 50905)
result = 'P';
else
if (charGBK >= 50906 && charGBK <= 51386)
result = 'Q';
else
if (charGBK >= 51387 && charGBK <= 51445)
result = 'R';
else
if (charGBK >= 51446 && charGBK <= 52217)
result = 'S';
else
if (charGBK >= 52218 && charGBK <= 52697)
result = 'T';
else
if (charGBK >= 52698 && charGBK <= 52979)
result = 'W';
else
if (charGBK >= 52980 && charGBK <= 53688)
result = 'X';
else
if (charGBK >= 53689 && charGBK <= 54480)
result = 'Y';
else
if (charGBK >= 54481 && charGBK <= 55289)
result = 'Z';
else
result = (char) (65 + (new Random()).nextInt(25));
if (!bUpCase)
result = Character.toLowerCase(result);
return result;
}
}
\ No newline at end of file
package com.stylefeng.guns.core.util;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
/**
* 资源文件相关的操作类
*
* @author fengshuonan
* @date 2016年11月17日 下午10:09:23
*/
public class ResKit {
/**
* @Description 批量获取ClassPath下的资源文件
* @author fengshuonan
*/
public static Resource[] getClassPathResources(String pattern) {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
return resolver.getResources(pattern);
} catch (IOException e) {
throw new RuntimeException("加载resource文件时,找不到文件,所找文件为:" + pattern);
}
}
/**
* @Description 批量获取ClassPath下的资源文件
* @author fengshuonan
*/
public static String getClassPathFile(String file) {
//return ResKit.class.getClassLoader().getResource(file).getPath();
return Thread.currentThread().getContextClassLoader().getResource(file).getPath();
}
}
package com.stylefeng.guns.core.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
*
* @author fengshuonan
* @date 2016年11月27日 下午3:32:11
*/
@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
assertApplicationContext();
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
assertApplicationContext();
return (T) applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> requiredType) {
assertApplicationContext();
return applicationContext.getBean(requiredType);
}
private static void assertApplicationContext() {
if (SpringContextHolder.applicationContext == null) {
throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
}
}
}
package com.stylefeng.guns.core.util;
import java.util.ArrayList;
import java.util.List;
/**
* sql语句工具类
*
* @author fengshuonan
* @date 2016年12月6日 下午1:01:54
*/
public class SqlUtil {
/**
* @Description 根据集合的大小,输出相应个数"?"
* @author fengshuonan
*/
public static String parse(List<?> list) {
String str = "";
if (list != null && list.size() > 0) {
str = str + "?";
for (int i = 1; i < list.size(); i++) {
str = str + ",?";
}
}
return str;
}
public static void main(String[] args) {
ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add(2);
arrayList.add(2);
System.out.println(parse(arrayList));
}
}
/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stylefeng.guns.core.util.qr;
import java.awt.image.BufferedImage;
/**
* Encapsulates custom configuration used in methods of {@link MatrixToImageWriter}.
*/
public final class MatrixToImageConfig {
public static final int BLACK = 0xFF000000;
public static final int WHITE = 0xFFFFFFFF;
private final int onColor;
private final int offColor;
/**
* Creates a default config with on color {@link #BLACK} and off color {@link #WHITE}, generating normal
* black-on-white barcodes.
*/
public MatrixToImageConfig() {
this(BLACK, WHITE);
}
/**
* @param onColor pixel on color, specified as an ARGB value as an int
* @param offColor pixel off color, specified as an ARGB value as an int
*/
public MatrixToImageConfig(int onColor, int offColor) {
this.onColor = onColor;
this.offColor = offColor;
}
public int getPixelOnColor() {
return onColor;
}
public int getPixelOffColor() {
return offColor;
}
int getBufferedImageColorModel() {
// Use faster BINARY if colors match default
return onColor == BLACK && offColor == WHITE ? BufferedImage.TYPE_BYTE_BINARY : BufferedImage.TYPE_INT_RGB;
}
}
\ No newline at end of file
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stylefeng.guns.core.util.qr;
import com.google.zxing.common.BitMatrix;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
/**
* Writes a {@link BitMatrix} to {@link BufferedImage},
* file or stream. Provided here instead of core since it depends on
* Java SE libraries.
*
* @author Sean Owen
*/
public final class MatrixToImageWriter {
private static final MatrixToImageConfig DEFAULT_CONFIG = new MatrixToImageConfig();
private MatrixToImageWriter() {}
/**
* Renders a {@link BitMatrix} as an image, where "false" bits are rendered
* as white, and "true" bits are rendered as black.
*/
public static BufferedImage toBufferedImage(BitMatrix matrix) {
return toBufferedImage(matrix, DEFAULT_CONFIG);
}
/**
* As {@link #toBufferedImage(BitMatrix)}, but allows customization of the output.
*/
public static BufferedImage toBufferedImage(BitMatrix matrix, MatrixToImageConfig config) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, config.getBufferedImageColorModel());
int onColor = config.getPixelOnColor();
int offColor = config.getPixelOffColor();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? onColor : offColor);
}
}
return image;
}
/**
* @deprecated use {@link #writeToPath(BitMatrix, String, Path)}
*/
@Deprecated
public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
writeToPath(matrix, format, file.toPath());
}
/**
* Writes a {@link BitMatrix} to a file.
*
* @see #toBufferedImage(BitMatrix)
*/
public static void writeToPath(BitMatrix matrix, String format, Path file) throws IOException {
writeToPath(matrix, format, file, DEFAULT_CONFIG);
}
/**
* @deprecated use {@link #writeToPath(BitMatrix, String, Path, MatrixToImageConfig)}
*/
@Deprecated
public static void writeToFile(BitMatrix matrix, String format, File file, MatrixToImageConfig config)
throws IOException {
writeToPath(matrix, format, file.toPath(), config);
}
/**
* As {@link #writeToFile(BitMatrix, String, File)}, but allows customization of the output.
*/
public static void writeToPath(BitMatrix matrix, String format, Path file, MatrixToImageConfig config)
throws IOException {
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, file.toFile())) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
/**
* Writes a {@link BitMatrix} to a stream.
*
* @see #toBufferedImage(BitMatrix)
*/
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
writeToStream(matrix, format, stream, DEFAULT_CONFIG);
}
/**
* As {@link #writeToStream(BitMatrix, String, OutputStream)}, but allows customization of the output.
*/
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream, MatrixToImageConfig config)
throws IOException {
BufferedImage image = toBufferedImage(matrix, config);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
}
}
\ No newline at end of file
package com.stylefeng.guns.core.util.qr;
/**
* 二维码图片对象
*
* @author fengshuonan
* @date 2016年12月8日 上午11:37:09
*/
public class QrImage {
/**
* 二维码的内容
*/
private String qrContent;
/**
* 二维码的宽度
*/
private int qrWidth;
/**
* 二维码的高度
*/
private int qrHeight;
/**
* 二维码中间图标的文件路径
*/
private String qrIconFilePath;
/**
* 二维码中间小图标的边长
*/
private int qrIconWidth;
/**
* 顶部文字的高度
*/
private int topWrodHeight;
/**
* 文字的大小
*/
private int wordSize;
/**
* 文字的内容
*/
private String wordContent;
/**
* 文件的输出路径
*/
private String fileOutputPath;
public static class Builder {
private String qrContent;
private int qrWidth;
private int qrHeight;
private String qrIconFilePath;
private int topWrodHeight;
private int wordSize;
private String wordContent;
private String fileOutputPath;
private int qrIconWidth;
public Builder() {
}
public Builder setQrContent(String qrContent) {
this.qrContent = qrContent;
return this;
}
public Builder setQrWidth(int qrWidth) {
this.qrWidth = qrWidth;
return this;
}
public Builder setQrHeight(int qrHeight) {
this.qrHeight = qrHeight;
return this;
}
public Builder setQrIconFilePath(String qrIconFilePath) {
this.qrIconFilePath = qrIconFilePath;
return this;
}
public Builder setTopWrodHeight(int topWrodHeight) {
this.topWrodHeight = topWrodHeight;
return this;
}
public Builder setWordSize(int wordSize) {
this.wordSize = wordSize;
return this;
}
public Builder setWordContent(String wordContent) {
this.wordContent = wordContent;
return this;
}
public Builder setFileOutputPath(String fileOutputPath) {
this.fileOutputPath = fileOutputPath;
return this;
}
public Builder setQrIconWidth(int qrIconWidth) {
this.qrIconWidth = qrIconWidth;
return this;
}
public QrImage build() {
return new QrImage(this.qrContent, this.qrWidth, this.qrHeight, this.qrIconFilePath, this.qrIconWidth,
this.topWrodHeight, this.wordSize, this.wordContent, this.fileOutputPath);
}
}
public QrImage(String qrContent, int qrWidth, int qrHeight, String qrIconFilePath, int qrIconWidth,
int topWrodHeight, int wordSize, String wordContent, String fileOutputPath) {
super();
this.qrContent = qrContent;
this.qrWidth = qrWidth;
this.qrHeight = qrHeight;
this.qrIconFilePath = qrIconFilePath;
this.qrIconWidth = qrIconWidth;
this.topWrodHeight = topWrodHeight;
this.wordSize = wordSize;
this.wordContent = wordContent;
this.fileOutputPath = fileOutputPath;
}
public String getQrContent() {
return qrContent;
}
public int getQrWidth() {
return qrWidth;
}
public int getQrHeight() {
return qrHeight;
}
public String getQrIconFilePath() {
return qrIconFilePath;
}
public int getTopWrodHeight() {
return topWrodHeight;
}
public int getWordSize() {
return wordSize;
}
public String getWordContent() {
return wordContent;
}
public String getFileOutputPath() {
return fileOutputPath;
}
public int getQrIconWidth() {
return qrIconWidth;
}
}
package com.stylefeng.guns.core.util.support;
import java.util.HashMap;
import java.util.Map;
/**
* 基本变量类型的枚举
* @author xiaoleilu
*/
public enum BasicType {
BYTE, SHORT, INT, INTEGER, LONG, DOUBLE, FLOAT, BOOLEAN, CHAR, CHARACTER, STRING;
/** 原始类型为Key,包装类型为Value,例如: int.class -> Integer.class. */
public static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<Class<?>, Class<?>>(8);
/** 包装类型为Key,原始类型为Value,例如: Integer.class -> int.class. */
public static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>(8);
static {
wrapperPrimitiveMap.put(Boolean.class, boolean.class);
wrapperPrimitiveMap.put(Byte.class, byte.class);
wrapperPrimitiveMap.put(Character.class, char.class);
wrapperPrimitiveMap.put(Double.class, double.class);
wrapperPrimitiveMap.put(Float.class, float.class);
wrapperPrimitiveMap.put(Integer.class, int.class);
wrapperPrimitiveMap.put(Long.class, long.class);
wrapperPrimitiveMap.put(Short.class, short.class);
for (Map.Entry<Class<?>, Class<?>> entry : wrapperPrimitiveMap.entrySet()) {
primitiveWrapperMap.put(entry.getValue(), entry.getKey());
}
}
}
package com.stylefeng.guns.core.util.support;
import com.stylefeng.guns.core.util.support.exception.ToolBoxException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* 类工具类
* 1、扫描指定包下的所有类<br>
* 参考 http://www.oschina.net/code/snippet_234657_22722
* @author seaside_hi, xiaoleilu, chill
*
*/
public class ClassKit {
private ClassKit() {
// 静态类不可实例化
}
/**
* 是否为标准的类<br>
* 这个类必须:<br>
* 1、非接口 2、非抽象类 3、非Enum枚举 4、非数组 5、非注解 6、非原始类型(int, long等)
*
* @param clazz 类
* @return 是否为标准类
*/
public static boolean isNormalClass(Class<?> clazz) {
return null != clazz && false == clazz.isInterface() && false == isAbstract(clazz) && false == clazz.isEnum() && false == clazz.isArray() && false == clazz.isAnnotation() && false == clazz
.isSynthetic() && false == clazz.isPrimitive();
}
/**
* 是否为抽象类
*
* @param clazz 类
* @return 是否为抽象类
*/
public static boolean isAbstract(Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers());
}
/**
* 实例化对象
*
* @param clazz 类名
* @return 对象
*/
@SuppressWarnings("unchecked")
public static <T> T newInstance(String clazz) {
if (null == clazz)
return null;
try {
return (T) Class.forName(clazz).newInstance();
} catch (Exception e) {
throw new ToolBoxException(StrKit.format("Instance class [{}] error!", clazz), e);
}
}
/**
* 实例化对象
*
* @param clazz 类
* @return 对象
*/
public static <T> T newInstance(Class<T> clazz) {
if (null == clazz)
return null;
try {
return (T) clazz.newInstance();
} catch (Exception e) {
throw new ToolBoxException(StrKit.format("Instance class [{}] error!", clazz), e);
}
}
/**
* 实例化对象
*
* @param clazz 类
* @return 对象
*/
public static <T> T newInstance(Class<T> clazz, Object... params) {
if (null == clazz)
return null;
if (CollectionKit.isEmpty(params)) {
return newInstance(clazz);
}
try {
return clazz.getDeclaredConstructor(getClasses(params)).newInstance(params);
} catch (Exception e) {
throw new ToolBoxException(StrKit.format("Instance class [{}] error!", clazz), e);
}
}
/**
* 获得对象数组的类数组
* @param objects 对象数组
* @return 类数组
*/
public static Class<?>[] getClasses(Object... objects){
Class<?>[] classes = new Class<?>[objects.length];
for (int i = 0; i < objects.length; i++) {
classes[i] = objects[i].getClass();
}
return classes;
}
/**
* 检查目标类是否可以从原类转化<br>
* 转化包括:<br>
* 1、原类是对象,目标类型是原类型实现的接口<br>
* 2、目标类型是原类型的父类<br>
* 3、两者是原始类型或者包装类型(相互转换)
*
* @param targetType 目标类型
* @param sourceType 原类型
* @return 是否可转化
*/
public static boolean isAssignable(Class<?> targetType, Class<?> sourceType) {
if (null == targetType || null == sourceType) {
return false;
}
// 对象类型
if (targetType.isAssignableFrom(sourceType)) {
return true;
}
// 基本类型
if (targetType.isPrimitive()) {
// 原始类型
Class<?> resolvedPrimitive = BasicType.wrapperPrimitiveMap.get(sourceType);
if (resolvedPrimitive != null && targetType.equals(resolvedPrimitive)) {
return true;
}
} else {
// 包装类型
Class<?> resolvedWrapper = BasicType.primitiveWrapperMap.get(sourceType);
if (resolvedWrapper != null && targetType.isAssignableFrom(resolvedWrapper)) {
return true;
}
}
return false;
}
/**
* 设置方法为可访问
*
* @param method 方法
* @return 方法
*/
public static Method setAccessible(Method method) {
if (null != method && ClassKit.isNotPublic(method)) {
method.setAccessible(true);
}
return method;
}
/**
* 指定类是否为非public
*
* @param clazz 类
* @return 是否为非public
*/
public static boolean isNotPublic(Class<?> clazz) {
return false == isPublic(clazz);
}
/**
* 指定方法是否为非public
*
* @param method 方法
* @return 是否为非public
*/
public static boolean isNotPublic(Method method) {
return false == isPublic(method);
}
/**
* 指定类是否为Public
*
* @param clazz 类
* @return 是否为public
*/
public static boolean isPublic(Class<?> clazz) {
if (null == clazz) {
throw new NullPointerException("Class to provided is null.");
}
return Modifier.isPublic(clazz.getModifiers());
}
/**
* 指定方法是否为Public
*
* @param method 方法
* @return 是否为public
*/
public static boolean isPublic(Method method) {
if (null == method) {
throw new NullPointerException("Method to provided is null.");
}
return isPublic(method.getDeclaringClass());
}
}
\ No newline at end of file
package com.stylefeng.guns.core.util.support;
import java.util.Date;
/**
* 封装java.util.Date
* @author xiaoleilu
*
*/
public class DateTime extends Date{
private static final long serialVersionUID = -5395712593979185936L;
/**
* 转换JDK date为 DateTime
* @param date JDK Date
* @return DateTime
*/
public static DateTime parse(Date date) {
return new DateTime(date);
}
/**
* 当前时间
*/
public DateTime() {
super();
}
/**
* 给定日期的构造
* @param date 日期
*/
public DateTime(Date date) {
this(date.getTime());
}
/**
* 给定日期毫秒数的构造
* @param timeMillis 日期毫秒数
*/
public DateTime(long timeMillis) {
super(timeMillis);
}
@Override
public String toString() {
return DateTimeKit.formatDateTime(this);
}
public String toString(String format) {
return DateTimeKit.format(this, format);
}
/**
* @return 输出精确到毫秒的标准日期形式
*/
public String toMsStr() {
return DateTimeKit.format(this, DateTimeKit.NORM_DATETIME_MS_PATTERN);
}
/**
* @return java.util.Date
*/
public Date toDate() {
return new Date(this.getTime());
}
}
package com.stylefeng.guns.core.util.support;
import java.nio.charset.Charset;
/**
* 十六进制(简写为hex或下标16)在数学中是一种逢16进1的进位制,一般用数字0到9和字母A到F表示(其中:A~F即10~15)。<br>
* 例如十进制数57,在二进制写作111001,在16进制写作39。<br>
* 像java,c这样的语言为了区分十六进制和十进制数值,会在十六进制数的前面加上 0x,比如0x20是十进制的32,而不是十进制的20<br>
*
* 参考:https://my.oschina.net/xinxingegeya/blog/287476
*
* @author Looly
*
*/
public class HexKit {
/**
* 用于建立十六进制字符的输出的小写字符数组
*/
private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* 用于建立十六进制字符的输出的大写字符数组
*/
private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
//---------------------------------------------------------------------------------------------------- encode
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data) {
return encodeHex(data, true);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param str 字符串
* @param charset 编码
* @return 十六进制char[]
*/
public static char[] encodeHex(String str, Charset charset) {
return encodeHex(StrKit.getBytes(str, charset), true);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @return 十六进制String
*/
public static String encodeHexStr(byte[] data) {
return encodeHexStr(data, true);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
* @return 十六进制String
*/
public static String encodeHexStr(byte[] data, boolean toLowerCase) {
return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
//---------------------------------------------------------------------------------------------------- decode
/**
* 将十六进制字符数组转换为字符串
*
* @param hexStr 十六进制String
* @param charset 编码
* @return 字符串
*/
public static String decodeHexStr(String hexStr, Charset charset) {
if(StrKit.isEmpty(hexStr)){
return hexStr;
}
return decodeHexStr(hexStr.toCharArray(), charset);
}
/**
* 将十六进制字符数组转换为字符串
*
* @param hexData 十六进制char[]
* @param charset 编码
* @return 字符串
*/
public static String decodeHexStr(char[] hexData, Charset charset) {
return StrKit.str(decodeHex(hexData), charset);
}
/**
* 将十六进制字符数组转换为字节数组
*
* @param hexData 十六进制char[]
* @return byte[]
* @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常
*/
public static byte[] decodeHex(char[] hexData) {
int len = hexData.length;
if ((len & 0x01) != 0) {
throw new RuntimeException("Odd number of characters.");
}
byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(hexData[j], j) << 4;
j++;
f = f | toDigit(hexData[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
//---------------------------------------------------------------------------------------- Private method start
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制String
*/
private static String encodeHexStr(byte[] data, char[] toDigits) {
return new String(encodeHex(data, toDigits));
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制char[]
*/
private static char[] encodeHex(byte[] data, char[] toDigits) {
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
/**
* 将十六进制字符转换成一个整数
*
* @param ch 十六进制char
* @param index 十六进制字符在字符数组中的位置
* @return 一个整数
* @throws RuntimeException 当ch不是一个合法的十六进制字符时,抛出运行时异常
*/
private static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index);
}
return digit;
}
//---------------------------------------------------------------------------------------- Private method end
/**
* 2进制转16进制
* @param bString 2进制字符串
* @return
*/
public static String binary2Hex(String bString) {
if (bString == null || bString.equals("") || bString.length() % 8 != 0)
return null;
StringBuffer tmp = new StringBuffer();
int iTmp = 0;
for (int i = 0; i < bString.length(); i += 4) {
iTmp = 0;
for (int j = 0; j < 4; j++) {
iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
}
tmp.append(Integer.toHexString(iTmp));
}
return tmp.toString();
}
/**
* 16进制转2进制
* @param hexString
* @return
*/
public static String hex2Binary(String hexString) {
if (hexString == null || hexString.length() % 2 != 0)
return null;
String bString = "", tmp;
for (int i = 0; i < hexString.length(); i++) {
tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
bString += tmp.substring(tmp.length() - 4);
}
return bString;
}
/**
* 将二进制转换成16进制
* @param buf
* @return
*/
public static String binary2Hex(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
* @param hexStr
* @return
*/
public static byte[] hex2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
/**
* Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stylefeng.guns.core.util.support;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpKit {
public static String getIp(){
return HttpKit.getRequest().getRemoteHost();
}
/**
* 获取所有请求的值
*/
public static Map<String, String> getRequestParameters() {
HashMap<String, String> values = new HashMap<>();
HttpServletRequest request = HttpKit.getRequest();
Enumeration enums = request.getParameterNames();
while ( enums.hasMoreElements()){
String paramName = (String) enums.nextElement();
String paramValue = request.getParameter(paramName);
values.put(paramName, paramValue);
}
return values;
}
/**
* 获取 HttpServletRequest
*/
public static HttpServletResponse getResponse() {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
return response;
}
/**
* 获取 包装防Xss Sql注入的 HttpServletRequest
* @return request
*/
public static HttpServletRequest getRequest() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return new WafRequestWrapper(request);
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, Map<String, String> param) {
String result = "";
BufferedReader in = null;
try {
String para = "";
for (String key : param.keySet()) {
para += (key + "=" + param.get(key) + "&");
}
if (para.lastIndexOf("&") > 0) {
para = para.substring(0, para.length() - 1);
}
String urlNameString = url + "?" + para;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, String> param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
String para = "";
for (String key : param.keySet()) {
para += (key + "=" + param.get(key) + "&");
}
if (para.lastIndexOf("&") > 0) {
para = para.substring(0, para.length() - 1);
}
String urlNameString = url + "?" + para;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
package com.stylefeng.guns.core.util.support;
/**
* 一些通用的函数
*
* @author Looly
*
*/
public class ObjectKit {
/**
* 比较两个对象是否相等。<br>
* 相同的条件有两个,满足其一即可:<br>
* 1. obj1 == null && obj2 == null; 2. obj1.equals(obj2)
*
* @param obj1 对象1
* @param obj2 对象2
* @return 是否相等
*/
public static boolean equals(Object obj1, Object obj2) {
return (obj1 != null) ? (obj1.equals(obj2)) : (obj2 == null);
}
}
package com.stylefeng.guns.core.util.support;
/**
* 分页工具类
*
* @author xiaoleilu
*
*/
public class PageKit {
/**
* 将页数和每页条目数转换为开始位置和结束位置<br>
* 此方法用于不包括结束位置的分页方法<br>
* 例如:<br>
* 页码:1,每页10 -> [0, 10]<br>
* 页码:2,每页10 -> [10, 20]<br>
* 。。。<br>
*
* @param pageNo
* 页码(从1计数)
* @param countPerPage
* 每页条目数
* @return 第一个数为开始位置,第二个数为结束位置
*/
public static int[] transToStartEnd(int pageNo, int countPerPage) {
if (pageNo < 1) {
pageNo = 1;
}
if (countPerPage < 1) {
countPerPage = 0;
// LogKit.warn("Count per page [" + countPerPage + "] is not valid!");
}
int start = (pageNo - 1) * countPerPage;
int end = start + countPerPage;
return new int[] { start, end };
}
/**
* 根据总数计算总页数
*
* @param totalCount
* 总数
* @param numPerPage
* 每页数
* @return 总页数
*/
public static int totalPage(int totalCount, int numPerPage) {
if (numPerPage == 0) {
return 0;
}
return totalCount % numPerPage == 0 ? (totalCount / numPerPage)
: (totalCount / numPerPage + 1);
}
}
/**
* Copyright (c) 2011-2014, hubin (jobob@qq.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stylefeng.guns.core.util.support;
import java.util.regex.Pattern;
/**
* Web防火墙工具类
* <p>
* @author hubin
* @Date 2014-5-8
*/
public class WafKit {
/**
* @Description 过滤XSS脚本内容
* @param value
* 待处理内容
* @return
*/
public static String stripXSS(String value) {
String rlt = null;
if (null != value) {
// NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
// avoid encoded attacks.
// value = ESAPI.encoder().canonicalize(value);
// Avoid null characters
rlt = value.replaceAll("", "");
// Avoid anything between script tags
Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid anything in a src='...' type of expression
/*scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");
scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");*/
// Remove any lonesome </script> tag
scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Remove any lonesome <script ...> tag
scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid eval(...) expressions
scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid expression(...) expressions
scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid javascript:... expressions
scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid vbscript:... expressions
scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid onload= expressions
scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");
}
return rlt;
}
/**
* @Description 过滤SQL注入内容
* @param value
* 待处理内容
* @return
*/
public static String stripSqlInjection(String value) {
return (null == value) ? null : value.replaceAll("('.+--)|(--)|(%7C)", ""); //value.replaceAll("('.+--)|(--)|(\\|)|(%7C)", "");
}
/**
* @Description 过滤SQL/XSS注入内容
* @param value
* 待处理内容
* @return
*/
public static String stripSqlXSS(String value) {
return stripXSS(stripSqlInjection(value));
}
}
/**
* Copyright (c) 2011-2014, hubin (jobob@qq.com).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.stylefeng.guns.core.util.support;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;
/**
* Request请求过滤包装
* <p>
* @author hubin
* @Date 2014-5-8
*/
public class WafRequestWrapper extends HttpServletRequestWrapper {
private boolean filterXSS = true;
private boolean filterSQL = true;
public WafRequestWrapper(HttpServletRequest request, boolean filterXSS, boolean filterSQL) {
super(request);
this.filterXSS = filterXSS;
this.filterSQL = filterSQL;
}
public WafRequestWrapper(HttpServletRequest request) {
this(request, true, true);
}
/**
* @Description 数组参数过滤
* @param parameter
* 过滤参数
* @return
*/
@Override
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if ( values == null ) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for ( int i = 0 ; i < count ; i++ ) {
encodedValues[i] = filterParamString(values[i]);
}
return encodedValues;
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Map getParameterMap() {
Map<String, String[]> primary = super.getParameterMap();
Map<String, String[]> result = new HashMap<String, String[]>(primary.size());
for ( Map.Entry<String, String[]> entry : primary.entrySet() ) {
result.put(entry.getKey(), filterEntryString(entry.getValue()));
}
return result;
}
protected String[] filterEntryString(String[] rawValue) {
for ( int i = 0 ; i < rawValue.length ; i++ ) {
rawValue[i] = filterParamString(rawValue[i]);
}
return rawValue;
}
/**
* @Description 参数过滤
* @param parameter
* 过滤参数
* @return
*/
@Override
public String getParameter(String parameter) {
return filterParamString(super.getParameter(parameter));
}
/**
* @Description 请求头过滤
* @param name
* 过滤内容
* @return
*/
@Override
public String getHeader(String name) {
return filterParamString(super.getHeader(name));
}
/**
* @Description Cookie内容过滤
* @return
*/
@Override
public Cookie[] getCookies() {
Cookie[] existingCookies = super.getCookies();
if (existingCookies != null) {
for (int i = 0 ; i < existingCookies.length ; ++i) {
Cookie cookie = existingCookies[i];
cookie.setValue(filterParamString(cookie.getValue()));
}
}
return existingCookies;
}
/**
* @Description 过滤字符串内容
* @param rawValue
* 待处理内容
* @return
*/
protected String filterParamString(String rawValue) {
if (null == rawValue) {
return null;
}
String tmpStr = rawValue;
if (this.filterXSS) {
tmpStr = WafKit.stripXSS(rawValue);
}
if (this.filterSQL) {
tmpStr = WafKit.stripSqlInjection(tmpStr);
}
return tmpStr;
}
}
/**
* Copyright (c) 2015-2017, Chill Zhuang 庄骞 (smallchill@163.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stylefeng.guns.core.util.support.exception;
import com.stylefeng.guns.core.util.support.StrKit;
/**
* 工具类初始化异常
*/
public class ToolBoxException extends RuntimeException{
private static final long serialVersionUID = 8247610319171014183L;
public ToolBoxException(Throwable e) {
super(e.getMessage(), e);
}
public ToolBoxException(String message) {
super(message);
}
public ToolBoxException(String messageTemplate, Object... params) {
super(StrKit.format(messageTemplate, params));
}
public ToolBoxException(String message, Throwable throwable) {
super(message, throwable);
}
public ToolBoxException(Throwable throwable, String messageTemplate, Object... params) {
super(StrKit.format(messageTemplate, params), throwable);
}
}
package com.stylefeng.guns.core.util.xss;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class XssFilter implements Filter {
FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XssHttpServletRequestWrapper(
(HttpServletRequest) request), response);
}
}
\ No newline at end of file
package com.stylefeng.guns.core.util.xss;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = cleanXSS(values[i]);
}
return encodedValues;
}
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
if (value == null) {
return null;
}
return cleanXSS(value);
}
public String getHeader(String name) {
String value = super.getHeader(name);
if (value == null)
return null;
return cleanXSS(value);
}
private String cleanXSS(String value) {
//You'll need to remove the spaces from the html entities below
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
return value;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment