spring cloud(五)核心core公共jar包

本系列文章均参考:朝雨忆轻尘,感谢博主!

这里还有他的技术交流群:429854222,欢迎大家支持博主

若有侵权,还请告知,一定删除

文档目录如下(与博主不尽相同,根据项目有所增减,大家根据需求cv)

spring cloud(五)核心core公共jar包_第1张图片

包括常用的restful API结果集封装、mybatis分页查询封装、加解密等等常用工具类,根据自需自取。

源码:

/**
 * 常量管理
 */ 
public interface SysConstants {

	/**
	 * 系统管理员用户名
	 */
	String ADMIN = "admin";
	
}

这个常量暂且可理解为用户每次操作的对象判断是不是超管,如改权限,如果是超管就不允许改变权限。

/**
 * 自定义异常
 */
public class TestException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	
    private String msg;
    private int code = 500;
    
    public TestException(String msg) {
		super(msg);
		this.msg = msg;
	}
	
	public TestException(String msg, Throwable e) {
		super(msg, e);
		this.msg = msg;
	}
	
	public TestException(String msg, int code) {
		super(msg);
		this.msg = msg;
		this.code = code;
	}
	
	public TestException(String msg, int code, Throwable e) {
		super(msg, e);
		this.msg = msg;
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}
	
}

自定义异常类

/**
 * HTTP结果封装
 */
public class HttpResult {

	private int code = 200;
	private String msg;
	private Object data;
	
	public static HttpResult error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
	}
	
	public static HttpResult error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}
	
	public static HttpResult error(int code, String msg) {
		HttpResult r = new HttpResult();
		r.setCode(code);
		r.setMsg(msg);
		return r;
	}

	public static HttpResult ok(String msg) {
		HttpResult r = new HttpResult();
		r.setMsg(msg);
		return r;
	}
	
	public static HttpResult ok(Object data) {
		HttpResult r = new HttpResult();
		r.setData(data);
		return r;
	}
	
	public static HttpResult ok() {
		return new HttpResult();
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}
	
}

restful API返回结果统一封装,使代码变得优雅

/**
 * Constants enumerating the HTTP status codes.
 * All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and
 * RFC2518 (WebDAV) are listed.
 *
 * @see StatusLine
 *
 * @since 4.0
 */
public interface HttpStatus {

    // --- 1xx Informational ---

    /** {@code 100 Continue} (HTTP/1.1 - RFC 2616) */
    public static final int SC_CONTINUE = 100;
    /** {@code 101 Switching Protocols} (HTTP/1.1 - RFC 2616)*/
    public static final int SC_SWITCHING_PROTOCOLS = 101;
    /** {@code 102 Processing} (WebDAV - RFC 2518) */
    public static final int SC_PROCESSING = 102;

    // --- 2xx Success ---

    /** {@code 200 OK} (HTTP/1.0 - RFC 1945) */
    public static final int SC_OK = 200;
    /** {@code 201 Created} (HTTP/1.0 - RFC 1945) */
    public static final int SC_CREATED = 201;
    /** {@code 202 Accepted} (HTTP/1.0 - RFC 1945) */
    public static final int SC_ACCEPTED = 202;
    /** {@code 203 Non Authoritative Information} (HTTP/1.1 - RFC 2616) */
    public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    /** {@code 204 No Content} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NO_CONTENT = 204;
    /** {@code 205 Reset Content} (HTTP/1.1 - RFC 2616) */
    public static final int SC_RESET_CONTENT = 205;
    /** {@code 206 Partial Content} (HTTP/1.1 - RFC 2616) */
    public static final int SC_PARTIAL_CONTENT = 206;
    /**
     * {@code 207 Multi-Status} (WebDAV - RFC 2518)
     * or
     * {@code 207 Partial Update OK} (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)
     */
    public static final int SC_MULTI_STATUS = 207;

    // --- 3xx Redirection ---

    /** {@code 300 Mutliple Choices} (HTTP/1.1 - RFC 2616) */
    public static final int SC_MULTIPLE_CHOICES = 300;
    /** {@code 301 Moved Permanently} (HTTP/1.0 - RFC 1945) */
    public static final int SC_MOVED_PERMANENTLY = 301;
    /** {@code 302 Moved Temporarily} (Sometimes {@code Found}) (HTTP/1.0 - RFC 1945) */
    public static final int SC_MOVED_TEMPORARILY = 302;
    /** {@code 303 See Other} (HTTP/1.1 - RFC 2616) */
    public static final int SC_SEE_OTHER = 303;
    /** {@code 304 Not Modified} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NOT_MODIFIED = 304;
    /** {@code 305 Use Proxy} (HTTP/1.1 - RFC 2616) */
    public static final int SC_USE_PROXY = 305;
    /** {@code 307 Temporary Redirect} (HTTP/1.1 - RFC 2616) */
    public static final int SC_TEMPORARY_REDIRECT = 307;

    // --- 4xx Client Error ---

    /** {@code 400 Bad Request} (HTTP/1.1 - RFC 2616) */
    public static final int SC_BAD_REQUEST = 400;
    /** {@code 401 Unauthorized} (HTTP/1.0 - RFC 1945) */
    public static final int SC_UNAUTHORIZED = 401;
    /** {@code 402 Payment Required} (HTTP/1.1 - RFC 2616) */
    public static final int SC_PAYMENT_REQUIRED = 402;
    /** {@code 403 Forbidden} (HTTP/1.0 - RFC 1945) */
    public static final int SC_FORBIDDEN = 403;
    /** {@code 404 Not Found} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NOT_FOUND = 404;
    /** {@code 405 Method Not Allowed} (HTTP/1.1 - RFC 2616) */
    public static final int SC_METHOD_NOT_ALLOWED = 405;
    /** {@code 406 Not Acceptable} (HTTP/1.1 - RFC 2616) */
    public static final int SC_NOT_ACCEPTABLE = 406;
    /** {@code 407 Proxy Authentication Required} (HTTP/1.1 - RFC 2616)*/
    public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    /** {@code 408 Request Timeout} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUEST_TIMEOUT = 408;
    /** {@code 409 Conflict} (HTTP/1.1 - RFC 2616) */
    public static final int SC_CONFLICT = 409;
    /** {@code 410 Gone} (HTTP/1.1 - RFC 2616) */
    public static final int SC_GONE = 410;
    /** {@code 411 Length Required} (HTTP/1.1 - RFC 2616) */
    public static final int SC_LENGTH_REQUIRED = 411;
    /** {@code 412 Precondition Failed} (HTTP/1.1 - RFC 2616) */
    public static final int SC_PRECONDITION_FAILED = 412;
    /** {@code 413 Request Entity Too Large} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUEST_TOO_LONG = 413;
    /** {@code 414 Request-URI Too Long} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUEST_URI_TOO_LONG = 414;
    /** {@code 415 Unsupported Media Type} (HTTP/1.1 - RFC 2616) */
    public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    /** {@code 416 Requested Range Not Satisfiable} (HTTP/1.1 - RFC 2616) */
    public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    /** {@code 417 Expectation Failed} (HTTP/1.1 - RFC 2616) */
    public static final int SC_EXPECTATION_FAILED = 417;

    /**
     * Static constant for a 418 error.
     * {@code 418 Unprocessable Entity} (WebDAV drafts?)
     * or {@code 418 Reauthentication Required} (HTTP/1.1 drafts?)
     */
    // not used
    // public static final int SC_UNPROCESSABLE_ENTITY = 418;

    /**
     * Static constant for a 419 error.
     * {@code 419 Insufficient Space on Resource}
     * (WebDAV - draft-ietf-webdav-protocol-05?)
     * or {@code 419 Proxy Reauthentication Required}
     * (HTTP/1.1 drafts?)
     */
    public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419;
    /**
     * Static constant for a 420 error.
     * {@code 420 Method Failure}
     * (WebDAV - draft-ietf-webdav-protocol-05?)
     */
    public static final int SC_METHOD_FAILURE = 420;
    /** {@code 422 Unprocessable Entity} (WebDAV - RFC 2518) */
    public static final int SC_UNPROCESSABLE_ENTITY = 422;
    /** {@code 423 Locked} (WebDAV - RFC 2518) */
    public static final int SC_LOCKED = 423;
    /** {@code 424 Failed Dependency} (WebDAV - RFC 2518) */
    public static final int SC_FAILED_DEPENDENCY = 424;

    // --- 5xx Server Error ---

    /** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */
    public static final int SC_INTERNAL_SERVER_ERROR = 500;
    /** {@code 501 Not Implemented} (HTTP/1.0 - RFC 1945) */
    public static final int SC_NOT_IMPLEMENTED = 501;
    /** {@code 502 Bad Gateway} (HTTP/1.0 - RFC 1945) */
    public static final int SC_BAD_GATEWAY = 502;
    /** {@code 503 Service Unavailable} (HTTP/1.0 - RFC 1945) */
    public static final int SC_SERVICE_UNAVAILABLE = 503;
    /** {@code 504 Gateway Timeout} (HTTP/1.1 - RFC 2616) */
    public static final int SC_GATEWAY_TIMEOUT = 504;
    /** {@code 505 HTTP Version Not Supported} (HTTP/1.1 - RFC 2616) */
    public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;

    /** {@code 507 Insufficient Storage} (WebDAV - RFC 2518) */
    public static final int SC_INSUFFICIENT_STORAGE = 507;

}

常见的错误返回码常量集

/**
 * 分页查询列过滤器
 */
public class ColumnFilter {

	/**
	 * 过滤列名
	 */
	private String name;
	/**
	 * 查询的值
	 */
	private String value;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	
}

分页查询时所带的条件查询辅助类,如需根据username查询时,ColumnFilter.set("username"),然后在查询时取出

/**
 * MyBatis 分页查询助手
 */
public class MybatisPageHelper {

	public static final String findPage = "findPage";
	
	/**
	 * 分页查询, 约定查询方法名为 “findPage” 
	 * @param pageRequest 分页请求
	 * @param mapper Dao对象,MyBatis的 Mapper	
	 * @param args 方法参数
	 * @return
	 */
	public static PageResult findPage(PageRequest pageRequest, Object mapper) {
		return findPage(pageRequest, mapper, findPage);
	}
	
	/**
	 * 调用分页插件进行分页查询
	 * @param pageRequest 分页请求
	 * @param mapper Dao对象,MyBatis的 Mapper	
	 * @param queryMethodName 要分页的查询方法名
	 * @param args 方法参数
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static PageResult findPage(PageRequest pageRequest, Object mapper, String queryMethodName, Object... args) {
		// 设置分页参数
		int pageNum = pageRequest.getPageNum();
		int pageSize = pageRequest.getPageSize();
		PageHelper.startPage(pageNum, pageSize);
		// 利用反射调用查询方法
		Object result = ReflectionUtils.invoke(mapper, queryMethodName, args);
		return getPageResult(pageRequest, new PageInfo((List) result));
	}

	/**
	 * 将分页信息封装到统一的接口
	 * @param pageRequest 
	 * @param page
	 * @return
	 */
	private static PageResult getPageResult(PageRequest pageRequest, PageInfo pageInfo) {
		PageResult pageResult = new PageResult();
        pageResult.setPageNum(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotalSize(pageInfo.getTotal());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setContent(pageInfo.getList());
		return pageResult;
	}

}

分页查询封装

/**
 * 分页请求
 */
public class PageRequest {
	/**
	 * 当前页码
	 */
	private int pageNum = 1;
	/**
	 * 每页数量
	 */
	private int pageSize = 10;
	/**
	 * 每页数量
	 */
	private Map columnFilters = new HashMap();
	
	public int getPageNum() {
		return pageNum;
	}
	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public Map getColumnFilters() {
		return columnFilters;
	}
	public void setColumnFilters(Map columnFilters) {
		this.columnFilters = columnFilters;
	}
	public ColumnFilter getColumnFilter(String name) {
		return columnFilters.get(name);
	}
}

分页请求封装,之前的ColumnFilter用于此处

/**
 * 分页返回结果
 */
public class PageResult {
	/**
	 * 当前页码
	 */
	private int pageNum;
	/**
	 * 每页数量
	 */
	private int pageSize;
	/**
	 * 记录总数
	 */
	private long totalSize;
	/**
	 * 页码总数
	 */
	private int totalPages;
	/**
	 * 分页数据
	 */
	private List content;
	public int getPageNum() {
		return pageNum;
	}
	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public long getTotalSize() {
		return totalSize;
	}
	public void setTotalSize(long totalSize) {
		this.totalSize = totalSize;
	}
	public int getTotalPages() {
		return totalPages;
	}
	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}
	public List getContent() {
		return content;
	}
	public void setContent(List content) {
		this.content = content;
	}
}

分页查询结果封装

import redis.clients.jedis.Jedis;

public class JedisUtils {
	
	private static Jedis jedis = new Jedis("localhost",6379);;
	// 过期时间/生存时间
    protected static int  expireTime = 60 * 60 *24;
	public static Jedis getInstance(){
		return jedis;
	}
	
	public static void set(String key,String value){
		jedis.set(key, value);
//		jedis.expire(key, expireTime);
	}
	
	public static String get(String key){
//		jedis.expire(key, expireTime);
		return jedis.get(key);
	}
}

Jedis辅助(不需要@Autowired,直接使用)

@Component
public class Redis {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * expire为过期时间,秒为单位
     *
     * @param key
     * @param value
     * @param expire
     */
    public void set(String key, String value, long expire) {
    	stringRedisTemplate.opsForValue().set(key, value, expire, TimeUnit.SECONDS);
    }

    public void set(String key, String value) {
    	if(value == null) {
    		return;
    	}
    	stringRedisTemplate.opsForValue().set(key, value);
    }

    public Object get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    public void delete(String key) {
    	stringRedisTemplate.delete(key);
    }
}

Redis,需要注入才可使用

/**
 * 通用CURD接口
 */
public interface CurdService {
	
	/**
	 * 保存操作
	 * @param record
	 * @return
	 */
	int save(T record);
	
	/**
	 * 删除操作
	 * @param record
	 * @return
	 */
	int delete(T record);
	
	/**
	 * 批量删除操作
	 * @param entities
	 */
	int delete(List records);
	
	/**
	 * 根据ID查询
	 * @param id
	 * @return
	 */
	T findById(Long id);
	
    /**
     * 分页查询
	 * 这里统一封装了分页请求和结果,避免直接引入具体框架的分页对象, 如MyBatis或JPA的分页对象
	 * 从而避免因为替换ORM框架而导致服务层、控制层的分页接口也需要变动的情况,替换ORM框架也不会
	 * 影响服务层以上的分页接口,起到了解耦的作用
	 * @param pageRequest 自定义,统一分页查询请求
	 * @return PageResult 自定义,统一分页查询结果
     */
	PageResult findPage(PageRequest pageRequest);
	
}

通用增删改查类,一般类继承此类基本够用了

public class Crypt {
	
	public static void main(String[] args) throws Exception {
		
	}

	private static Key AESkey = null;
	private static Cipher cipher = null;
	static {
		// 生成Key
		KeyGenerator keyGenerator = null;
		try {
			keyGenerator = KeyGenerator.getInstance("AES");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		keyGenerator.init(128);
		keyGenerator.init(128, new SecureRandom("test123".getBytes()));
		// 使用上面这种初始化方法可以特定种子来生成密钥,这样加密后的密文是唯一固定的。
		SecretKey secretKey = keyGenerator.generateKey();
		byte[] keyBytes = secretKey.getEncoded();

		// Key转换
		AESkey = new SecretKeySpec(keyBytes, "AES");

		try {
			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchPaddingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public static boolean check32(String check){
		if(StringUtils.isBlank(check)||check.length()>32){
			return true;
		}
		return false;
	}

	/**
	 * 加密
	 * @param encodeStr
	 * @return
	 * @throws Exception
	 */
	public static String encode(String encodeStr) throws Exception {
		// 加密
		cipher.init(Cipher.ENCRYPT_MODE, AESkey);
		byte[] encodeResult = cipher.doFinal(encodeStr.getBytes());
		return toHexString(encodeResult);
	}
	/**
	 * 解密
	 * @param encodeStr
	 * @return
	 * @throws Exception
	 */
	public static String decode(String decodeStr) throws Exception {
		if (decodeStr == null || decodeStr.length()%32 != 0) {
			return null;
		}
		// 解密
		cipher.init(Cipher.DECRYPT_MODE, AESkey);
		byte[] decodeResult = cipher.doFinal(toByteArray(decodeStr));
		return new String(decodeResult);
	}

	private static byte[] toByteArray(String hexString) {
		if (hexString == null || hexString.length() == 0)
			return null;
		hexString = hexString.toLowerCase();
		final byte[] byteArray = new byte[hexString.length() >> 1];
		int index = 0;
		for (int i = 0; i < hexString.length(); i++) {
			if (index > hexString.length() - 1)
				return byteArray;
			byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
			byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
			byteArray[i] = (byte) (highDit << 4 | lowDit);
			index += 2;
		}
		return byteArray;
	}

	/**
	 * byte[] to Hex string.
	 *
	 * @param byteArray
	 *            the byte array
	 * @return the string
	 */

	private static String toHexString(byte[] byteArray) {
		final StringBuilder hexString = new StringBuilder("");
		if (byteArray == null || byteArray.length <= 0)
			return null;
		for (int i = 0; i < byteArray.length; i++) {
			int v = byteArray[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				hexString.append(0);
			}
			hexString.append(hv);
		}
		return hexString.toString().toLowerCase();
	}

}

AES加解密

/**
 * 日期时间相关工具
 */
public class DateTimeUtils {

	public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	public static final String YYYYMMDD_FORMAT = "yyyyMMdd";
	
	public static void main(String[] args) {
		System.out.println(getYYYYMMDD(new Date()));
	}
	
	/**
	 * 获取当前标准格式化日期时间
	 * @param date
	 * @return
	 */
	public static String getDateTime() {
		return getDateTime(new Date());
	}
	
	/**
	 * 标准格式化日期时间
	 * @param date
	 * @return
	 */
	public static String getDateTime(Date date) {
		return (new SimpleDateFormat(DATE_FORMAT)).format(date);
	}
	
	public static String getYYYYMMDD(Date date) {
		return (new SimpleDateFormat(YYYYMMDD_FORMAT)).format(date);
	}
}

时间工具

public class FileUtils {
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}


	public static void main(String[] args) {
		String[] s = getAllByExcel("F:/model.xlsx");
		for (int i = 0; i < s.length; i++) {
			System.out.println(s[i]);
		}
		
	}

	public static String[] getAllByExcel(String filepath) {
		try {
			// 同时支持Excel 2003、2007
			File excelFile = new File(filepath); // 创建文件对象
			FileInputStream is = new FileInputStream(excelFile); // 文件流
			Workbook workbook = WorkbookFactory.create(is); // 这种方式 Excel
			
			String[] res = readExcel(workbook, 0, 1, 0);
			
			return res;
			/*String[] room = new String[4];
			String tempCampus = "";
			int campus = 0;
			String tempTb = "";
			int tb = 0;
			for (int i = 0; i < res.length; i++) {
				res[i].substring(0, res[i].length()-1);
				room = res[i].split("_");
				
				if(tempCampus.equals(room[0])){
					System.out.print("校区:"+room[0]);
					
				}else{
					System.out.print("校区change");
					System.out.print("校区:"+room[0]);
					tempCampus = room[0];
				}
				System.out.print("\t");
				if(tempTb.equals(room[1])){
					System.out.print("教学楼:"+room[1]);
				}else{
					System.out.print("教学楼change");
					System.out.print("教学楼:"+room[1]);
					tempTb = room[1];
				}
				System.out.print("\t");
				System.out.print("教师编号:"+room[2]+" \t 教室名称:"+room[3]);
				System.out.println();
			}*/
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	private static String[] readExcel(Workbook wb, int sheetIndex, int startReadLine, int tailLine) {
		Sheet sheet = wb.getSheetAt(sheetIndex);
		Row row = null;
		String[] res = new String[sheet.getLastRowNum() - tailLine + 1];

		for (int i = startReadLine; i < sheet.getLastRowNum() - tailLine + 1; i++) {
			
			row = sheet.getRow(i);
			res[i] = "";
			for (Cell c : row) {
				boolean isMerge = isMergedRegion(sheet, i, c.getColumnIndex());
				// 判断是否具有合并单元格
				if (isMerge) {
					String rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
					//System.out.print(rs + "_"+ row.getRowNum()+"_"+c.getColumnIndex() +"_");
					res[i] += rs+ "_";
				} else {
					res[i] += getCellValue(c)+ "_";
				}
			}
			//System.out.println();
		}
		
		if(startReadLine > 0){
			String[] result = new String[res.length - startReadLine];
			for (int i = 0; i < startReadLine; i++) {
				for (int j = 0; j < res.length; j++) {
					if(j == res.length - 1)
						continue;
					res[j] = res[j+1];
				}
			}
			for (int i = 0; i < result.length; i++) {
				result[i] = res[i];
			}
			return result;
		}else{
			return res;
		}
	}

	private static boolean isMergedRegion(Sheet sheet, int row, int column) {
		int sheetMergeCount = sheet.getNumMergedRegions();
		for (int i = 0; i < sheetMergeCount; i++) {
			CellRangeAddress range = sheet.getMergedRegion(i);
			int firstColumn = range.getFirstColumn();
			int lastColumn = range.getLastColumn();
			int firstRow = range.getFirstRow();
			int lastRow = range.getLastRow();
			if (row >= firstRow && row <= lastRow) {
				if (column >= firstColumn && column <= lastColumn) {
					return true;
				}
			}
		}
		return false;
	}

	public static String getMergedRegionValue(Sheet sheet, int row, int column) {
		int sheetMergeCount = sheet.getNumMergedRegions();

		for (int i = 0; i < sheetMergeCount; i++) {
			CellRangeAddress ca = sheet.getMergedRegion(i);
			int firstColumn = ca.getFirstColumn();
			int lastColumn = ca.getLastColumn();
			int firstRow = ca.getFirstRow();
			int lastRow = ca.getLastRow();

			if (row >= firstRow && row <= lastRow) {

				if (column >= firstColumn && column <= lastColumn) {
					Row fRow = sheet.getRow(firstRow);
					Cell fCell = fRow.getCell(firstColumn);
					return getCellValue(fCell);
				}
			}
		}

		return null;
	}

	private static String getCellValue(Cell cell) {
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		String cellValue = "";
		int cellType = cell.getCellType();
		switch (cellType) {
		case Cell.CELL_TYPE_STRING: // 文本
			cellValue = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_NUMERIC: // 数字、日期
			if (DateUtil.isCellDateFormatted(cell)) {
				cellValue = fmt.format(cell.getDateCellValue()); // 日期型
			} else {
				cellValue = String.valueOf((int) cell.getNumericCellValue()); // 数字
			}
			break;
		case Cell.CELL_TYPE_BOOLEAN: // 布尔型
			cellValue = String.valueOf(cell.getBooleanCellValue());
			break;
		case Cell.CELL_TYPE_BLANK: // 空白
			cellValue = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_ERROR: // 错误
			cellValue = "错误";
			break;
		case Cell.CELL_TYPE_FORMULA: // 公式
			cellValue = "错误";
			break;
		default:
			cellValue = "错误";
		}
		return cellValue;
	}

}

Excel读取工具

/**
 * HTTP工具类
 */
public class HttpContextUtils {

	public static HttpServletRequest getHttpServletRequest() {
		try {
			return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}
}

获取request工具

/**
 * IO相关工具类
 */
public class IOUtils {

	/**
	 * 关闭对象,连接
	 * @param closeable
	 */
    public static void closeQuietly(final Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (final IOException ioe) {
            // ignore
        }
    }
}

IO工具

/**
 * IP相关工具类
 */
public class IPUtils {
	private static Logger logger = LoggerFactory.getLogger(IPUtils.class);

	/**
	 * 获取IP地址
	 * 
	 * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
	 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {
    	String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
        	logger.error("IPUtils ERROR ", e);
        }
        
//        //使用代理,则获取第一个IP地址
//        if(StringUtils.isEmpty(ip) && ip.length() > 15) {
//			if(ip.indexOf(",") > 0) {
//				ip = ip.substring(0, ip.indexOf(","));
//			}
//		}
        
        return ip;
    }
	
	public static boolean isIP(String ip) {
		String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
		return ip.matches(rexp);
	}
	
}

IP工具

public class matchUtil {
	public static boolean isIP(String ip) {
		String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
		return ip.matches(rexp);
	}
	
	public static boolean isMobile(String mobile) {
		String rexp = "^1(3|4|5|7|8)\\d{9}$";
		return mobile.matches(rexp);
	}
	
	public static boolean isEmail(String email) {
		String rexp = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$";
		return email.matches(rexp);
	}
	
	public static final boolean isMatch(T orderStr, T[] orderList) {
		if (orderStr == null || orderList.length == 0 || orderStr.getClass() != orderList[0].getClass()) {
			return false;
		}
		for (int i = 0; i < orderList.length; i++) {
			if (orderStr.equals(orderList[i])) {
				return true;
			}
		}
		return false;
	}

	public static boolean isMatch(Integer orderStr, Integer[] orderList) {
		if (orderStr == null || orderList.length == 0 || orderStr.getClass() != orderList[0].getClass()) {
			return false;
		}
		for (int i = 0; i < orderList.length; i++) {
			if (orderStr.equals(orderList[i])) {
				return true;
			}
		}
		return false;
	}

	public static boolean isMatch(Long orderStr, Long[] orderList) {
		if (orderStr == null || orderList.length == 0 || orderStr.getClass() != orderList[0].getClass()) {
			return false;
		}
		for (int i = 0; i < orderList.length; i++) {
			if (orderStr.equals(orderList[i])) {
				return true;
			}
		}
		return false;
	}
	
	
}

常用正则匹配工具,数组是否包含

public class PingUtils {
	public static boolean ping(String ipAddress) throws Exception {
        int  timeOut =  2000 ;  //超时应该在3钞以上        
        try {
        	boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut);     // 当返回值是true时,说明host是可用的,false则不可。
            return status;
		} catch (Exception e) {
			// TODO: handle exception
		}
        return false;
    }
	
	 public static boolean ping(String ipAddress, int pingTimes, int timeOut) {  
	        BufferedReader in = null;  
	        Runtime r = Runtime.getRuntime();  // 将要执行的ping命令,此命令是windows格式的命令  
	        String pingCommand = "ping " + ipAddress + " -n " + pingTimes    + " -w " + timeOut;  
	        try {   // 执行命令并获取输出  
	            System.out.println(pingCommand);   
	            Process p = r.exec(pingCommand);   
	            if (p == null) {    
	                return false;   
	            }
	            in = new BufferedReader(new InputStreamReader(p.getInputStream()));   // 逐行检查输出,计算类似出现=23ms TTL=62字样的次数  
	            int connectedCount = 0;   
	            String line = null;   
	            while ((line = in.readLine()) != null) {    
	                connectedCount += getCheckResult(line);   
	            }   // 如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真  
	            return connectedCount == pingTimes;  
	        } catch (Exception ex) {   
	            ex.printStackTrace();   // 出现异常则返回假  
	            return false;  
	        } finally {   
	            try {    
	                in.close();   
	            } catch (IOException e) {    
	                e.printStackTrace();   
	            }  
	        }
	    }
	    //若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
	    private static int getCheckResult(String line) {  // System.out.println("控制台输出的结果为:"+line);  
	        Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)",    Pattern.CASE_INSENSITIVE);  
	        Matcher matcher = pattern.matcher(line);  
	        while (matcher.find()) {
	            return 1;
	        }
	        return 0; 
	    }
	public static void main(String[] args) throws Exception {/*
		long a = System.currentTimeMillis();
		for (int i = 0; i < 50; i++) {
			System.out.println(ping("192.168.1.99"));
		}
		System.out.println(System.currentTimeMillis() - a);
		a = System.currentTimeMillis();
		for (int i = 0; i < 50; i++) {
			System.out.println(ping("192.168.1.99",1,3000));
		}
		System.out.println(System.currentTimeMillis() - a);
	*/}
}

网络PING工具

/**
 * 反射相关辅助方法
 */
public class ReflectionUtils {

	
	/**
	 * 根据方法名调用指定对象的方法
	 * @param object 要调用方法的对象
	 * @param method 要调用的方法名
	 * @param args 参数对象数组
	 * @return
	 */
	public static Object invoke(Object object, String method, Object... args) {
		Object result = null;
		Class clazz = object.getClass();
		Method queryMethod = getMethod(clazz, method, args);
		if(queryMethod != null) {
			try {
				result = queryMethod.invoke(object, args);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		} else {
			try {
				throw new NoSuchMethodException(clazz.getName() + " 类中没有找到 " + method + " 方法。");
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	/**
	 * 根据方法名和参数对象查找方法
	 * @param clazz
	 * @param name
	 * @param args 参数实例数据
	 * @return
	 */
	public static Method getMethod(Class clazz, String name, Object[] args) {
		Method queryMethod = null;
		Method[] methods = clazz.getMethods();
		for(Method method:methods) {
			if(method.getName().equals(name)) {
				Class[] parameterTypes = method.getParameterTypes();
				if(parameterTypes.length == args.length) {
					boolean isSameMethod = true;
					for(int i=0; i

反射工具

public final class SpringUtils implements BeanFactoryPostProcessor {
 
 
	private static ConfigurableListableBeanFactory beanFactory; // Spring应用上下文环境
 
 
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		SpringUtils.beanFactory = beanFactory;
	}
 
 
	/**
	 * 获取对象
	 * 
	 * @param name
	 * @return Object 一个以所给名字注册的bean的实例
	 * @throws org.springframework.beans.BeansException
	 * 
	 */
	@SuppressWarnings("unchecked")
	public static  T getBean(String name) throws BeansException {
		return (T) beanFactory.getBean(name);
	}
 
 
	/**
	 * 获取类型为requiredType的对象
	 * 
	 * @param clz
	 * @return
	 * @throws org.springframework.beans.BeansException
	 * 
	 */
	public static  T getBean(Class clz) throws BeansException {
		@SuppressWarnings("unchecked")
		T result = (T) beanFactory.getBean(clz);
		return result;
	}
 
 
	/**
	 * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
	 * 
	 * @param name
	 * @return boolean
	 */
	public static boolean containsBean(String name) {
		return beanFactory.containsBean(name);
	}
 
 
	/**
	 * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
	 * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
	 * 
	 * @param name
	 * @return boolean
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * 
	 */
	public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
		return beanFactory.isSingleton(name);
	}
 
 
	/**
	 * @param name
	 * @return Class 注册对象的类型
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * 
	 */
	public static Class getType(String name) throws NoSuchBeanDefinitionException {
		return beanFactory.getType(name);
	}
 
 
	/**
	 * 如果给定的bean名字在bean定义中有别名,则返回这些别名
	 * 
	 * @param name
	 * @return
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * 
	 */
	public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
		return beanFactory.getAliases(name);
	}
 
 
}

普通类获取spring bean对象工具

/**
 * 字符串工具类
 * 
 * @author Louis
 * @date Sep 1, 2018
 */
public class StringUtils {

	/**
	 * 判空操作
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isBlank(String value) {
		return value == null || "".equals(value) || "null".equals(value) || "undefined".equals(value);
	}

	public static boolean contains(String str, String searchStr) {
		if (str == null || searchStr == null) {
			return false;
		}
		return str.indexOf(searchStr) >= 0;
	}
}

字符串工具

public class TokenUtils {
	/**
     * 获取请求的token
     */
	public static String getRequestToken(HttpServletRequest httpRequest){
        // 从header中获取token
        String token = httpRequest.getHeader("token");
        // 如果header中不存在token,则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = httpRequest.getParameter("token");
        }
        return token;
    }
}

密钥生成工具

---------------------------------------

大概就这些,告辞!

你可能感兴趣的:(JAVA随记,utils)