| | |
| | | import java.sql.Timestamp; |
| | | import java.time.LocalDate; |
| | | |
| | | /** |
| | | * Lunarswirls180 |
| | | * @author WWW |
| | | */ |
| | | @Data |
| | | @AllArgsConstructor |
| | | @SuppressWarnings("ALL") |
| | |
| | | import java.sql.Timestamp; |
| | | import java.time.LocalDate; |
| | | |
| | | /** |
| | | * Mooncontour |
| | | * @author WWW |
| | | */ |
| | | @Data |
| | | @AllArgsConstructor |
| | | @SuppressWarnings("ALL") |
| | |
| | | import java.sql.Timestamp; |
| | | import java.time.LocalDate; |
| | | |
| | | /** |
| | | * Robbins8km |
| | | * @author WWW |
| | | */ |
| | | @Data |
| | | @AllArgsConstructor |
| | | @SuppressWarnings("ALL") |
| | |
| | | import java.sql.Timestamp; |
| | | import java.time.LocalDate; |
| | | |
| | | /** |
| | | * Wrinkleridges180 |
| | | * @author WWW |
| | | */ |
| | | @Data |
| | | @AllArgsConstructor |
| | | @SuppressWarnings("ALL") |
| | |
| | | import java.util.ArrayList; |
| | | import java.util.List; |
| | | |
| | | /** |
| | | * 数简.删除-结果实体类 |
| | | * |
| | | * @author WWW |
| | | * @date 2023-09-01 |
| | | */ |
| | | @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming") |
| | | @SuppressWarnings("ALL") |
| | | public class DeleteResultEntity implements Serializable { |
| | | private static final long serialVersionUID = -6859400504807647005L; |
| | | |
| | |
| | | |
| | | import java.io.Serializable; |
| | | |
| | | /** |
| | | * 数简.创建图层-结果类 |
| | | * @author WWW |
| | | * @date 2023-08-31 |
| | | */ |
| | | @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming") |
| | | @SuppressWarnings("ALL") |
| | | public class LayerResultEntity implements Serializable { |
| | | private static final long serialVersionUID = -1916127613292276655L; |
| | | |
| | |
| | | import javax.crypto.spec.SecretKeySpec; |
| | | import java.util.Base64; |
| | | |
| | | /** |
| | | * AES加密帮助 |
| | | * @author WWW |
| | | */ |
| | | @SuppressWarnings("restriction") |
| | | @SuppressWarnings("ALL") |
| | | public class AesHelper { |
| | | /** |
| | | * 密钥长度必须是16 |
| | | */ |
| | | private static final String DEFAULT_KEY = "A#s_lF_sErve_k.y"; |
| | | |
| | | private static final String KEY_ALGORITHM = "AES"; |
| | | |
| | | /** |
| | | * 算法 |
| | | */ |
| | | private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding"; |
| | | |
| | | /** |
| | | * aes解密 |
| | | * |
| | | * @param encrypt 内容 |
| | | * @return |
| | | * @throws Exception |
| | | */ |
| | | public static String decrypt(String encrypt) throws Exception { |
| | | return decrypt(encrypt, DEFAULT_KEY); |
| | | } |
| | | |
| | | /** |
| | | * aes加密 |
| | | * |
| | | * @param content 内容 |
| | | * @return |
| | | * @throws Exception |
| | | */ |
| | | public static String encrypt(String content) throws Exception { |
| | | return encrypt(content, DEFAULT_KEY); |
| | | } |
| | | |
| | | /** |
| | | * base 64 encode |
| | | * |
| | | * @param bytes 待编码的byte[] |
| | | * @return 编码后的base64 code |
| | | */ |
| | | private static String base64Encode(byte[] bytes) { |
| | | return Base64.getEncoder().encodeToString(bytes); |
| | | } |
| | | |
| | | /** |
| | | * base 64 decode |
| | | * |
| | | * @param base64Code 待解码的base64 code |
| | | * @return 解码后的byte[] |
| | | * @throws Exception |
| | | */ |
| | | private static byte[] base64Decode(String base64Code) { |
| | | return StringHelper.isEmpty(base64Code) ? null : Base64.getDecoder().decode(base64Code); |
| | | } |
| | | |
| | | /** |
| | | * AES加密 |
| | | * |
| | | * @param content 待加密的内容 |
| | | * @param encryptKey 加密密钥 |
| | | * @return 加密后的byte[] |
| | | * @throws Exception |
| | | */ |
| | | private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception { |
| | | // KeyGenerator kGen = KeyGenerator.getInstance(KEY_ALGORITHM) |
| | | // kGen.init(128) |
| | |
| | | return cipher.doFinal(content.getBytes("utf-8")); |
| | | } |
| | | |
| | | /** |
| | | * AES加密为base 64 code |
| | | * |
| | | * @param content 待加密的内容 |
| | | * @param encryptKey 加密密钥 |
| | | * @return 加密后的base 64 code |
| | | * @throws Exception |
| | | */ |
| | | public static String encrypt(String content, String encryptKey) throws Exception { |
| | | return base64Encode(aesEncryptToBytes(content, encryptKey)); |
| | | } |
| | | |
| | | /** |
| | | * 将base 64 code AES解密 |
| | | * |
| | | * @param encryptStr 待解密的base 64 code |
| | | * @param decryptKey 解密密钥 |
| | | * @return 解密后的string |
| | | * @throws Exception |
| | | */ |
| | | public static String decrypt(String encryptStr, String decryptKey) throws Exception { |
| | | return StringHelper.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey); |
| | | } |
| | | |
| | | /** |
| | | * AES解密 |
| | | * |
| | | * @param encryptBytes 待解密的byte[] |
| | | * @param decryptKey 解密密钥 |
| | | * @return 解密后的String |
| | | * @throws Exception |
| | | */ |
| | | private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception { |
| | | // KeyGenerator kGen = KeyGenerator.getInstance(KEY_ALGORITHM) |
| | | // kGen.init(128) |
| | |
| | | import java.util.concurrent.ScheduledExecutorService; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | /** |
| | | * 异步帮助类 |
| | | * @author WWW |
| | | * @date 2023-07-10 |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | public class AsyncHelper { |
| | | /** |
| | | * 操作延迟10毫秒 |
| | | */ |
| | | private final static int OPERATE_DELAY_TIME = 10; |
| | | |
| | | // private final static AsyncHelper INSTANCE = new AsyncHelper(); |
| | |
| | | public AsyncHelper() { |
| | | } |
| | | |
| | | /** |
| | | * 执行任务 |
| | | */ |
| | | public void execute(TimerTask task) { |
| | | executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS); |
| | | } |
| | | |
| | | /** |
| | | * 关闭任务 |
| | | */ |
| | | public void shutdown() { |
| | | shutdownAndAwaitTermination(executor); |
| | | } |
| | | |
| | | /** |
| | | * 停止任务线程池 |
| | | */ |
| | | public static void shutdownAndAwaitTermination(ExecutorService pool) { |
| | | try { |
| | | if (null == pool || pool.isShutdown()) { |
| | |
| | | |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * Excel帮助类 |
| | | * @author WWW |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | public class ExcelHelper { |
| | | /** |
| | | * 读取Excel |
| | | * |
| | | * @param pathName 文件路径 |
| | | * @param <T> 泛型类 |
| | | * @return 泛型类集合 |
| | | */ |
| | | public static <T> List<T> readExcel(Class<?> clazz, String pathName) { |
| | | ExcelHead head = getExcelHead(clazz); |
| | | int headRowNumber = head == null ? 1 : head.headRows(); |
| | |
| | | return list; |
| | | } |
| | | |
| | | /** |
| | | * 获取Excel头注解类 |
| | | * |
| | | * @param clazz Class |
| | | * @param <T> 泛型类 |
| | | * @return 头行数 |
| | | */ |
| | | public static <T> ExcelHead getExcelHead(Class<?> clazz) { |
| | | ExcelHead head = clazz.getAnnotation(ExcelHead.class); |
| | | |
| | | return head; |
| | | } |
| | | |
| | | /** |
| | | * 写入Excel模板 |
| | | * |
| | | * @param source 源文件(模板) |
| | | * @param target 目录文件 |
| | | * @param map 数据源 |
| | | */ |
| | | public static <T> void writeToTemplate(String source, String target, Map<String, List<T>> map) { |
| | | // 根据模板写入数据,如果目标文件不存在,则自动创建文件 |
| | | ExcelWriter excelWriter = EasyExcel.write(target).withTemplate(source).build(); |
| | | |
| | | // 在工作簿0中写入数据,如果模板中不存在练习工作簿,则会在目标文件中自动创建 |
| | | WriteSheet writeSheet = EasyExcel.writerSheet(0).build(); |
| | | |
| | | // 垂直写入数据,如果要水平写入,将VERTICAL替换为HORIZONTAL |
| | | FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build(); |
| | | |
| | | // 写入数据 |
| | | map.forEach((k, v) -> excelWriter.fill(new FillWrapper(k, v), fillConfig, writeSheet)); |
| | | |
| | | // 结束写入 |
| | | excelWriter.finish(); |
| | | } |
| | | } |
| | |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * GDAL帮助类 |
| | | * @author WWW |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | public class GdalHelper { |
| | | private final static Log log = LogFactory.getLog(GdalHelper.class); |
| | | |
| | | public static void init(String gdalPath) { |
| | | // 支持中文路径 |
| | | gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); |
| | | // 属性表支持中文:CP936 |
| | | gdal.SetConfigOption("SHAPE_ENCODING", ""); |
| | | gdal.SetConfigOption("PGEO_DRIVER_TEMPLATE", "DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=%s"); |
| | | gdal.SetConfigOption("MDB_DRIVER_TEMPLATE", "DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=%s"); |
| | | |
| | | // 配置环境变量 |
| | | if (!StringHelper.isEmpty(gdalPath)) { |
| | | gdal.SetConfigOption("GDAL_DATA", gdalPath + File.separator + "gdal-data"); |
| | | gdal.SetConfigOption("PROJ_LIB", gdalPath + File.separator + "proj7" + File.separator + "share"); |
| | |
| | | } |
| | | } |
| | | |
| | | // 注册所有的驱动 |
| | | gdal.AllRegister(); |
| | | ogr.RegisterAll(); |
| | | GeoHelper.initSr(); |
| | | } |
| | | |
| | | /** |
| | | * 读取tif文件 |
| | | * |
| | | * @param fileName |
| | | */ |
| | | public static void readTif(String fileName) { |
| | | // 读取影像数据 |
| | | Dataset dataset = gdal.Open(fileName, gdalconstConstants.GA_ReadOnly); |
| | |
| | | return; |
| | | } |
| | | |
| | | // providing various methods for a format specific driver. |
| | | Driver driver = dataset.GetDriver(); |
| | | System.out.println("driver name: " + driver.getLongName()); |
| | | |
| | | // 读取影像信息 |
| | | int xSize = dataset.getRasterXSize(); |
| | | int ySzie = dataset.getRasterYSize(); |
| | | int rasterCount = dataset.getRasterCount(); |
| | | System.out.println("dataset xSize: " + xSize + ", ySzie = " + ySzie + ", rasterCount = " + rasterCount); |
| | | |
| | | Band band = dataset.GetRasterBand(1); |
| | | // the data type of the band. |
| | | int type = band.GetRasterDataType(); |
| | | System.out.println("data type = " + type + ", " + (type == gdalconstConstants.GDT_Byte)); |
| | | |
| | | // Frees the native resource associated to a Dataset object and close the file. |
| | | dataset.delete(); |
| | | |
| | | gdal.GDALDestroyDriverManager(); |
| | | } |
| | | |
| | | /** |
| | | * 读取shp文件 |
| | | * |
| | | * @param filePath |
| | | */ |
| | | public static void readShp(String filePath) { |
| | | try { |
| | | org.gdal.ogr.Driver driver = ogr.GetDriverByName("ESRI shapefile"); |
| | |
| | | Map<String, Object> fieldMap = new HashMap(5); |
| | | for (int i = 0, count = featureDefn.GetFieldCount(); i < count; i++) { |
| | | FieldDefn fieldDefn = featureDefn.GetFieldDefn(i); |
| | | //得到属性字段类型 |
| | | int fieldType = fieldDefn.GetFieldType(); |
| | | String fieldTypeName = fieldDefn.GetFieldTypeName(fieldType); |
| | | //得到属性字段名称 |
| | | String fieldName = fieldDefn.GetName(); |
| | | |
| | | fieldMap.put(fieldTypeName, fieldName); |
| | |
| | | dataSource = driver.Open(filePath, 0); |
| | | int num = dataSource.GetLayerCount(); |
| | | for (int i = 0; i < num; i++) { |
| | | // 获取图层 |
| | | Layer layer = dataSource.GetLayer(i); |
| | | // 表名称 |
| | | String strlayerName = layer.GetName(); |
| | | // 获取图层要数个数 |
| | | long count = layer.GetFeatureCount(); |
| | | if (0 != count) { |
| | | do { |
| | | // 获取图层下的要素 |
| | | Feature feature = layer.GetNextFeature(); |
| | | if (null == feature) { |
| | | break; |
| | | } |
| | | // 获取边界坐标 |
| | | |
| | | Geometry geometry = feature.GetGeometryRef(); |
| | | if (geometry != null) { |
| | | String geometryJson = geometry.ExportToJson(); |
| | |
| | | } |
| | | } |
| | | Map map = new HashMap(5); |
| | | //获取属性 |
| | | for (int p = 0; p < feature.GetFieldCount(); p++) { |
| | | map.put(feature.GetFieldDefnRef(p).GetName(), getProperty(feature, p)); |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 读取gdb文件 |
| | | * |
| | | * @param filePath |
| | | */ |
| | | public static void readGdb(String filePath) { |
| | | try { |
| | | org.gdal.ogr.Driver driver = ogr.GetDriverByName("OpenFileGDB"); |
| | |
| | | DataSource dataSource = driver.Open(filePath, 0); |
| | | |
| | | for (int i = 0, count = dataSource.GetLayerCount(); i < count; i++) { |
| | | // 获取图层 |
| | | Layer layer = dataSource.GetLayer(i); |
| | | System.out.println(i + "\t" + layer.GetName()); |
| | | do { |
| | | // 获取图层下的要素 |
| | | Feature feature = layer.GetNextFeature(); |
| | | if (null == feature) { |
| | | break; |
| | | } |
| | | // 获取样式,这里是空,待确定 |
| | | |
| | | System.out.println(feature.GetStyleString()); |
| | | // 获取geometry,也可以ExportToWkb() gml等等 |
| | | System.out.println(feature.GetGeometryRef().ExportToWkt()); |
| | | // 获取属性 |
| | | System.out.println("----------------------------------"); |
| | | for (int p = 0; p < feature.GetFieldCount(); p++) { |
| | | System.out.println(feature.GetFieldDefnRef(p).GetName() + "\t" + getProperty(feature, p)); |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 属性获取器 |
| | | */ |
| | | @FunctionalInterface |
| | | private interface PropertyGetter { |
| | | /** |
| | | * 获取属性 |
| | | * |
| | | * @param feature |
| | | * @param index |
| | | * @return |
| | | */ |
| | | Object get(Feature feature, int index); |
| | | } |
| | | |
| | | private static final PropertyGetter STRING_PROPERTY_GETTER = (feature, index) -> feature.GetFieldAsString(index); |
| | | |
| | | /** |
| | | * feature.GetFieldType(index)得到一个属性类型的int值,该值对应具体类型 |
| | | */ |
| | | private static final PropertyGetter[] PROPERTY_GETTERS = new PropertyGetter[]{ |
| | | // 0-Integer |
| | | (feature, index) -> feature.GetFieldAsInteger(index), |
| | |
| | | |
| | | import java.awt.geom.Point2D; |
| | | |
| | | /** |
| | | * Geo帮助类 |
| | | * @author WWW |
| | | * @date 2023-09-14 |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | public class GeoHelper { |
| | | public static SpatialReference sr4326; |
| | | |
| | |
| | | |
| | | private final static Log log = LogFactory.getLog(GeoHelper.class); |
| | | |
| | | /** |
| | | * 初始化坐标系 |
| | | */ |
| | | public static void initSr() { |
| | | try { |
| | | sr4326 = new SpatialReference(); |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 获取距离 |
| | | */ |
| | | public static double getDistance(double x1, double y1, double x2, double y2) { |
| | | GeodeticCalculator geodeticCalculator = new GeodeticCalculator(crs104903); |
| | | geodeticCalculator.setStartingGeographicPoint(x1, y1); |
| | |
| | | return geodeticCalculator.getOrthodromicDistance(); |
| | | } |
| | | |
| | | /** |
| | | * 获取距离2 |
| | | */ |
| | | public static double getDistance2(double lon1, double lat1, double lon2, double lat2) { |
| | | double radLat1 = Math.toRadians(lat1); |
| | | double radLat2 = Math.toRadians(lat2); |
| | |
| | | return s * MOON_RADIUS; |
| | | } |
| | | |
| | | /** |
| | | * 获取方向角 |
| | | */ |
| | | public static double getBearing(double x1, double y1, double x2, double y2) { |
| | | return (90 - Math.toDegrees(Math.atan2(x2 - x1, y2 - y1)) + 360) % 360; |
| | | } |
| | | |
| | | /** |
| | | * 获取角度 |
| | | */ |
| | | public static double getAngle(double x1, double y1, double x2, double y2) { |
| | | DirectPosition2D p1 = new DirectPosition2D(crs104903, x1, y1); |
| | | DirectPosition2D p2 = new DirectPosition2D(crs104903, x2, y2); |
| | |
| | | return gc.getAzimuth(); |
| | | } |
| | | |
| | | /** |
| | | * 获取角度2 |
| | | */ |
| | | public static double getAngle2(double x1, double y1, double x2, double y2) { |
| | | DirectPosition2D p1 = new DirectPosition2D(x1, y1); |
| | | DirectPosition2D p2 = new DirectPosition2D(x2, y2); |
| | |
| | | return gc.getAzimuth(); |
| | | } |
| | | |
| | | /** |
| | | * 根据距离和角度获取目标点 |
| | | */ |
| | | public static Point2D getPointByDistanceAndAngle(double x, double y, double angle, double distance) { |
| | | DirectPosition2D p1 = new DirectPosition2D(x, y); |
| | | |
| | |
| | | return gc.getDestinationGeographicPoint(); |
| | | } |
| | | |
| | | /** |
| | | * 坐标转换 |
| | | */ |
| | | public static double[] csTransform(double x, double y, int epsg) throws Exception { |
| | | CRSAuthorityFactory factory = CRS.getAuthorityFactory(true); |
| | | CoordinateReferenceSystem target = factory.createCoordinateReferenceSystem("EPSG:4326"); |
| | |
| | | import java.security.MessageDigest; |
| | | import java.util.Random; |
| | | |
| | | /** |
| | | * MD5帮助类 |
| | | * @author WWW |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | public class Md5Helper { |
| | | private final static int M3 = 3; |
| | | |
| | |
| | | |
| | | private final static int M48 = 48; |
| | | |
| | | /** |
| | | * 生成含有随机盐的密码 |
| | | * |
| | | * @param password |
| | | * @return |
| | | */ |
| | | public static String generate(String password) { |
| | | Random r = new Random(); |
| | | StringBuilder sb = new StringBuilder(16); |
| | |
| | | return new String(cs); |
| | | } |
| | | |
| | | /** |
| | | * 校验密码是否正确 |
| | | * |
| | | * @param password |
| | | * @param md5 |
| | | * @return |
| | | */ |
| | | public static boolean verify(String password, String md5) { |
| | | char[] cs1 = new char[32]; |
| | | char[] cs2 = new char[16]; |
| | |
| | | return md5Hex(password + salt).equals(new String(cs1)); |
| | | } |
| | | |
| | | /** |
| | | * 获取十六进制字符串形式的MD5摘要 |
| | | * |
| | | * @param src |
| | | * @return |
| | | */ |
| | | public static String md5Hex(String src) { |
| | | try { |
| | | MessageDigest md5 = MessageDigest.getInstance("MD5"); |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 反转 |
| | | * |
| | | * @param pass |
| | | * @return |
| | | */ |
| | | public static String reverse(String pass) { |
| | | StringBuilder sb = new StringBuilder(pass); |
| | | |
| | | return sb.reverse().toString(); |
| | | } |
| | | |
| | | /** |
| | | * 验证密码 |
| | | * |
| | | * @param originalPassword |
| | | * @param dbPassword |
| | | * @return |
| | | */ |
| | | public static boolean validatePassword(String originalPassword, String dbPassword) { |
| | | return verify(originalPassword, reverse(dbPassword)); |
| | | } |
| | |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * Rest服务帮助类 |
| | | * @author WWW |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | public class RestHelper { |
| | | private static RestTemplate restTemplate; |
| | | |
| | | private final static Log log = LogFactory.getLog(RestHelper.class); |
| | | |
| | | /** |
| | | * 获取RestTemplate |
| | | * |
| | | * @return RestTemplate |
| | | */ |
| | | public static RestTemplate getRestTemplate() { |
| | | if (restTemplate == null) { |
| | | restTemplate = SpringContextHelper.getBean(RestTemplate.class); |
| | |
| | | return restTemplate; |
| | | } |
| | | |
| | | /** |
| | | * Get请求-HttpURLConnection |
| | | * |
| | | * @param url URL地址 |
| | | * @return 字符串 |
| | | * @throws IOException IO异常 |
| | | */ |
| | | public static String getForConn(String url) throws IOException { |
| | | BufferedReader br = null; |
| | | HttpURLConnection conn = null; |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Post请求-HttpURLConnection |
| | | * |
| | | * @param url URL地址 |
| | | * @param query 查询条件 |
| | | * @return 字符串 |
| | | * @throws IOException IO异常 |
| | | */ |
| | | public static String postForConn(String url, String query) throws IOException { |
| | | BufferedReader br = null; |
| | | HttpURLConnection conn = null; |
| | |
| | | URL restUrl = new URL(url); |
| | | |
| | | conn = (HttpURLConnection) restUrl.openConnection(); |
| | | // POST,GET,PUT,DELETE |
| | | conn.setRequestMethod("POST"); |
| | | conn.setRequestProperty("Content-Type", "application/json"); |
| | | conn.setDoOutput(true); |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Get请求-CloseableHttpClient |
| | | * |
| | | * @param uri Uri地址 |
| | | * @return 响应字符串 |
| | | */ |
| | | public static String get(String uri) { |
| | | try { |
| | | CloseableHttpClient httpClient = HttpClients.custom().build(); |
| | |
| | | HttpGet httpGet = new HttpGet(uri); |
| | | |
| | | CloseableHttpResponse closeResponse = httpClient.execute(httpGet); |
| | | // 取出返回体 |
| | | |
| | | HttpEntity entity = closeResponse.getEntity(); |
| | | |
| | | return EntityUtils.toString(entity, StaticData.TEXT_ENCODER); |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * Post请求-CloseableHttpClient |
| | | * |
| | | * @param uri Uri地址 |
| | | * @param postData 待发送数据 |
| | | * @return 响应字符串 |
| | | */ |
| | | public static String post(String uri, List<NameValuePair> postData) { |
| | | try { |
| | | CloseableHttpClient httpClient = HttpClients.custom().build(); |
| | |
| | | |
| | | CloseableHttpResponse closeResponse = httpClient.execute(httpPost); |
| | | |
| | | // 取出返回体 |
| | | HttpEntity entity = closeResponse.getEntity(); |
| | | |
| | | return EntityUtils.toString(entity, StaticData.TEXT_ENCODER); |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 获取错误信息 |
| | | * |
| | | * @param uri Uri地址 |
| | | * @param ex 异常 |
| | | * @return 错误信息 |
| | | */ |
| | | public static String getErrorInfo(String uri, Exception ex) { |
| | | Map<String, Object> map = new LinkedHashMap<>(); |
| | | map.put("result", null); |
| | |
| | | return map.toString(); |
| | | } |
| | | |
| | | /** |
| | | * GET请求(REST) |
| | | */ |
| | | public static String getForRest(String uri) { |
| | | RestTemplate rest = getRestTemplate(); |
| | | |
| | | return rest.getForObject(uri, String.class); |
| | | } |
| | | |
| | | /** |
| | | * GET请求(REST) |
| | | */ |
| | | public static <T> T getForRest(String uri, Class<T> clazz) { |
| | | RestTemplate rest = getRestTemplate(); |
| | | |
| | | return rest.getForObject(uri, clazz); |
| | | } |
| | | |
| | | /** |
| | | * POST请求(REST) |
| | | */ |
| | | public static String postForRest(String uri, Map<String, Object> map) { |
| | | RestTemplate rest = getRestTemplate(); |
| | | |
| | | return rest.postForObject(uri, map, String.class); |
| | | } |
| | | |
| | | /** |
| | | * POST请求(REST) |
| | | */ |
| | | public static <T> String postForRest(String uri, List<T> list) { |
| | | RestTemplate rest = getRestTemplate(); |
| | | |
| | | return rest.postForObject(uri, list, String.class); |
| | | } |
| | | |
| | | /** |
| | | * POST请求(REST) |
| | | */ |
| | | public static <T> String postForRest(String uri, T t) { |
| | | RestTemplate rest = getRestTemplate(); |
| | | |
| | | return rest.postForObject(uri, t, String.class); |
| | | } |
| | | |
| | | /** |
| | | * DELETE请求(REST) |
| | | */ |
| | | public static void deleteForRest(String uri) { |
| | | RestTemplate rest = getRestTemplate(); |
| | | |
| | | rest.delete(uri); |
| | | } |
| | | |
| | | /** |
| | | * DELETE请求(REST) |
| | | */ |
| | | public static void deleteForRest(String uri, Map<String, Object> map) { |
| | | RestTemplate rest = getRestTemplate(); |
| | | |
| | |
| | | import java.util.HashMap; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * RSA工具类 |
| | | * @author WWW |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | public class RsaHelper { |
| | | /** |
| | | * 私钥 |
| | | */ |
| | | private static String privateKey; |
| | | |
| | | /** |
| | | * 公钥 |
| | | */ |
| | | private static String publicKey; |
| | | |
| | | /** |
| | | * 密钥算法 |
| | | */ |
| | | private static final String KEY_ALGORITHM = "RSA"; |
| | | |
| | | /** |
| | | * RSA密钥长度:1024 或 2048 |
| | | */ |
| | | private static final int DEFAULT_RSA_KEY_SIZE = 1024; |
| | | |
| | | /** |
| | | * 日志 |
| | | */ |
| | | private final static Log log = LogFactory.getLog(RsaHelper.class); |
| | | |
| | | /** |
| | | * 生成公私钥 |
| | | */ |
| | | public static void generate() { |
| | | Map<String, String> result = generateRsaKey(DEFAULT_RSA_KEY_SIZE); |
| | | System.out.println("公钥为:" + result.get("publicKey")); |
| | | System.out.println("私钥为:" + result.get("privateKey")); |
| | | } |
| | | |
| | | /** |
| | | * 获取RSA加密私钥 |
| | | * |
| | | * @return |
| | | * @throws IOException |
| | | */ |
| | | public static String getPrivateKey() throws IOException { |
| | | if (privateKey == null) { |
| | | InputStream inPrivate = new ClassPathResource("config" + File.separator + "rsa_private_key.txt").getInputStream(); |
| | |
| | | return privateKey; |
| | | } |
| | | |
| | | /** |
| | | * 获取RSA加密公钥 |
| | | * |
| | | * @return |
| | | * @throws IOException |
| | | */ |
| | | public static String getPublicKey() throws IOException { |
| | | if (publicKey == null) { |
| | | InputStream inPrivate = new ClassPathResource("config" + File.separator + "rsa_public_key.txt").getInputStream(); |
| | |
| | | return publicKey; |
| | | } |
| | | |
| | | /** |
| | | * 读取文本文件 |
| | | * |
| | | * @param fileName 文件路径 |
| | | * @return |
| | | * @throws IOException |
| | | */ |
| | | public static String readFile(String fileName) throws IOException { |
| | | File file = new File(fileName); |
| | | BufferedReader br = new BufferedReader(new FileReader(file)); |
| | |
| | | return result.toString(); |
| | | } |
| | | |
| | | /** |
| | | * 把inputStream转成String |
| | | * |
| | | * @param is |
| | | * @return |
| | | * @throws IOException |
| | | */ |
| | | private static String inputStream2String(InputStream is) throws IOException { |
| | | ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| | | |
| | |
| | | return str; |
| | | } |
| | | |
| | | /** |
| | | * 生成RSA的公私钥 |
| | | * |
| | | * @param keySize 1025 或 2048 |
| | | * @return |
| | | */ |
| | | public static Map<String, String> generateRsaKey(int keySize) { |
| | | Map<String, String> result = new HashMap<>(2); |
| | | try { |
| | | KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); |
| | | |
| | | // 初始化密钥对生成器,密钥大小为1024 2048位 |
| | | keyPairGen.initialize(keySize, new SecureRandom()); |
| | | |
| | | // 生成一个密钥对,保存在keyPair中 |
| | | KeyPair keyPair = keyPairGen.generateKeyPair(); |
| | | |
| | | // 得到公钥字符串 |
| | | String pub = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded())); |
| | | result.put("publicKey", pub); |
| | | |
| | | // 得到私钥字符串 |
| | | String pri = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())); |
| | | result.put("privateKey", pri); |
| | | } catch (Exception ex) { |
| | |
| | | return result; |
| | | } |
| | | |
| | | /** |
| | | * RSA私钥解密 |
| | | * |
| | | * @param str 加密的字符串 |
| | | * @return 解密字符串 |
| | | * @throws Exception 加密过程中的异常信息 |
| | | */ |
| | | public static String decrypt(String str) throws Exception { |
| | | // 64位解码加密后的字符串 |
| | | byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8)); |
| | | |
| | | // Base64编码的私钥 |
| | | byte[] decoded = Base64.decodeBase64(getPrivateKey()); |
| | | RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); |
| | | |
| | | // RSA解密:RSA/ECB/NoPadding |
| | | // RSA/ECB/NoPadding |
| | | Cipher cipher = Cipher.getInstance("RSA"); |
| | | cipher.init(Cipher.DECRYPT_MODE, priKey); |
| | | |
| | |
| | | return outStr; |
| | | } |
| | | |
| | | /** |
| | | * RSA公钥加密 |
| | | * |
| | | * @param str 需要加密的字符串 |
| | | * @return 密文 |
| | | * @throws Exception 加密过程中的异常信息 |
| | | */ |
| | | public static String encrypt(String str) throws Exception { |
| | | // Base64编码的公钥 |
| | | byte[] decoded = Base64.decodeBase64(getPublicKey()); |
| | | |
| | | RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); |
| | | |
| | | // RSA加密:RSA/ECB/NoPadding |
| | | // RSA/ECB/NoPadding |
| | | Cipher cipher = Cipher.getInstance("RSA"); |
| | | cipher.init(Cipher.ENCRYPT_MODE, pubKey); |
| | | |
| | |
| | | import org.springframework.context.ApplicationContextAware; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | /** |
| | | * Spring上下文帮助类 |
| | | * @author WWW |
| | | */ |
| | | @Component |
| | | @SuppressWarnings("ALL") |
| | | public class SpringContextHelper implements ApplicationContextAware { |
| | | private static ApplicationContext context = null; |
| | | |
| | | /** |
| | | * 设置应用程序上下文 |
| | | * |
| | | * @param applicationContext |
| | | * @throws BeansException |
| | | */ |
| | | @Override |
| | | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { |
| | | context = applicationContext; |
| | | } |
| | | |
| | | /** |
| | | * 根据名称获取Bean |
| | | * |
| | | * @param name 类名称 |
| | | * @return |
| | | */ |
| | | public static <T> T getBean(String name) { |
| | | return (T) context.getBean(name); |
| | | } |
| | | |
| | | /** |
| | | * 根据类型获取Bean |
| | | * |
| | | * @param clazz 类 |
| | | * @param <T> 泛型 |
| | | * @return |
| | | */ |
| | | public static <T> T getBean(Class<T> clazz) { |
| | | return context.getBean(clazz); |
| | | } |
| | | |
| | | /** |
| | | * 判断是否包含对应名称的Bean对象 |
| | | * |
| | | * @param name Bean名称 |
| | | * @return 包含:返回true,否则返回false。 |
| | | */ |
| | | public static boolean containsBean(String name) { |
| | | return context.containsBean(name); |
| | | } |
| | | |
| | | /** |
| | | * 获取对应Bean名称的类型 |
| | | * |
| | | * @param name Bean名称 |
| | | * @return 返回对应的Bean类型 |
| | | */ |
| | | public static Class<?> getType(String name) { |
| | | return context.getType(name); |
| | | } |
| | | |
| | | /** |
| | | * 获取上下文对象,可进行各种Spring的上下文操作 |
| | | * |
| | | * @return Spring上下文对象 |
| | | */ |
| | | public static ApplicationContext getContext() { |
| | | return context; |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 获取当前环境 |
| | | * |
| | | * @return Profile |
| | | */ |
| | | public static String getActiveProfile() { |
| | | return context.getEnvironment().getActiveProfiles()[0]; |
| | | } |
| | |
| | | import java.util.regex.Matcher; |
| | | import java.util.regex.Pattern; |
| | | |
| | | /** |
| | | * 字符串帮助类 |
| | | * @author WWW |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | public class StringHelper { |
| | | /** |
| | | * 数字正则 |
| | | */ |
| | | public static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d+(\\.\\d+)?"); |
| | | |
| | | /** |
| | | * 格式化当前系统日期 1 |
| | | */ |
| | | public static final SimpleDateFormat YMD_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); |
| | | |
| | | /** |
| | | * 格式化当前系统日期 2 |
| | | */ |
| | | public static final SimpleDateFormat YMDHMS_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); |
| | | |
| | | /** |
| | | * 格式化当前系统日期 3 |
| | | */ |
| | | public static final SimpleDateFormat YMD2_FORMAT = new SimpleDateFormat("yyyyMMdd"); |
| | | |
| | | /** |
| | | * 格式化当前系统日期 4 |
| | | */ |
| | | public static final SimpleDateFormat YMDHMS2_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); |
| | | |
| | | /** |
| | | * 判断字符串,是否为整数 |
| | | */ |
| | | public static boolean isInteger(String str) { |
| | | return str != null && str.matches("[0-9]+"); |
| | | } |
| | | |
| | | /** |
| | | * 判断字符串,是否为浮点数 |
| | | */ |
| | | public static boolean isNumeric(String str) { |
| | | return str != null && str.matches("-?\\d+(\\.\\d+)?"); |
| | | } |
| | | |
| | | /** |
| | | * 判断字符串,是否为浮点数 |
| | | */ |
| | | public static boolean isNumeric2(String str) { |
| | | return str != null && NUMBER_PATTERN.matcher(str).matches(); |
| | | } |
| | | |
| | | /** |
| | | * 日期正则 |
| | | */ |
| | | public static Pattern datePattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/]((((0?[13578])|(1[02]))[\\-\\/]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/]((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/]((((0?[13578])|(1[02]))[\\-\\/]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/]((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$"); |
| | | |
| | | /** |
| | | * SQL正则 |
| | | */ |
| | | public static Pattern sqlPattern = Pattern.compile("|and|exec|execute|insert|select|delete|update|count|drop|\\*|%|chr|mid|master|truncate|char|declare|sitename|net user|xp_cmdshell|;|or|-|\\+|,|like"); |
| | | |
| | | /** |
| | | * 字符串转为日期 |
| | | */ |
| | | public static Date parseDate(String str) { |
| | | try { |
| | | return YMD_FORMAT.parse(str); |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 字符串转为日期时间 |
| | | */ |
| | | public static Date parseTime(String str) { |
| | | try { |
| | | return YMDHMS_FORMAT.parse(str); |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 判断值是否为日期格式 |
| | | */ |
| | | public static boolean isDate(String strDate) { |
| | | Matcher m = datePattern.matcher(strDate); |
| | | |
| | | return m.matches(); |
| | | } |
| | | |
| | | /** |
| | | * 字符串,是否为null 或 "" |
| | | */ |
| | | public static boolean isNull(String str) { |
| | | return null == str || str.length() == 0; |
| | | } |
| | | |
| | | /** |
| | | * 字符串,是否为空null和空格 |
| | | */ |
| | | public static boolean isEmpty(String str) { |
| | | return null == str || "".equals(str.trim()); |
| | | } |
| | | |
| | | /** |
| | | * 获取 like 字符串 |
| | | */ |
| | | public static String getLikeStr(String str) { |
| | | return StringHelper.isEmpty(str) ? null : "%" + str.trim() + "%"; |
| | | } |
| | | |
| | | /** |
| | | * 获取 like 字符串 |
| | | */ |
| | | public static String getLikeUpperStr(String str) { |
| | | return StringHelper.isEmpty(str) ? null : "%" + str.trim().toUpperCase() + "%"; |
| | | } |
| | | |
| | | /** |
| | | * 获取 右like 字符串 |
| | | */ |
| | | public static String getRightLike(String str) { |
| | | return StringHelper.isEmpty(str) ? null : str.trim() + "%"; |
| | | } |
| | | |
| | | /** |
| | | * 获取图形的WKT字符串 |
| | | */ |
| | | public static String getGeomWkt(String wkt) { |
| | | if (StringHelper.isEmpty(wkt)) { |
| | | return "null"; |
| | |
| | | return String.format("ST_GeomFromText('%s')", wkt); |
| | | } |
| | | |
| | | /** |
| | | * 首字母大写 |
| | | */ |
| | | public static String firstCharToUpperCase(String str) { |
| | | return str.substring(0, 1).toUpperCase() + str.substring(1); |
| | | } |
| | | |
| | | /** |
| | | * 首字母小写 |
| | | */ |
| | | public static String firstCharToLowerCase(String str) { |
| | | return str.substring(0, 1).toLowerCase() + str.substring(1); |
| | | } |
| | | |
| | | /** |
| | | * 判断值是否存在SQL注入 |
| | | * |
| | | * @param str 字符串 |
| | | * @return 是/否 |
| | | */ |
| | | public static boolean isSqlInjection(String str) { |
| | | if (null == str) { |
| | | return false; |
| | |
| | | return m.matches(); |
| | | } |
| | | |
| | | /** |
| | | * 校验密码是/否合法 |
| | | * |
| | | * @param pwd 密码 |
| | | * @return 是/否为无效的 |
| | | */ |
| | | public static boolean isPwdInvalid(String pwd) { |
| | | return !Pattern.matches(StaticData.PWD_REG, pwd); |
| | | } |
| | | |
| | | /** |
| | | * 获取GUID |
| | | */ |
| | | public static String getGuid() { |
| | | return UUID.randomUUID().toString(); |
| | | } |
| | | |
| | | /** |
| | | * 获取分钟差数 |
| | | */ |
| | | public static long getMinuteDifference(Timestamp ts) { |
| | | return (ts.getTime() - System.currentTimeMillis()) / 1000 / 60; |
| | | } |
| | | |
| | | /** |
| | | * 连接List集合 |
| | | * |
| | | * @param list list 整数集合 |
| | | * @param join join 连接字符 |
| | | * @param <T> 泛型类 |
| | | * @return 字符串 |
| | | */ |
| | | public static <T> String join(List<T> list, String join) { |
| | | if (null == list || list.isEmpty()) { |
| | | return ""; |
| | |
| | | } |
| | | |
| | | if (sb.length() > 0 && sb.lastIndexOf(join) == sb.length() - join.length()) { |
| | | // 删除从索引 start 开始到 end 之间的字符,即 前包括 后不包括。 |
| | | sb.delete(sb.length() - join.length(), sb.length()); |
| | | } |
| | | |
| | | return sb.toString(); |
| | | } |
| | | |
| | | /** |
| | | * 字符串转整数集合 |
| | | */ |
| | | public static List<Integer> strToIntegers(String str) { |
| | | if (StringHelper.isEmpty(str)) { |
| | | return null; |
| | |
| | | import java.sql.Timestamp; |
| | | import java.util.*; |
| | | |
| | | /** |
| | | * Web帮助类 |
| | | * @author WWW |
| | | */ |
| | | @SuppressWarnings("ALL") |
| | | public class WebHelper { |
| | | private final static String UNKNOWN = "unknown"; |
| | | |
| | |
| | | |
| | | private final static Log log = LogFactory.getLog(WebHelper.class); |
| | | |
| | | /** |
| | | * 保留小数位 |
| | | */ |
| | | public static double round(double val, double size) { |
| | | double power = Math.pow(10.0, size); |
| | | |
| | | return Math.round(val * power) / power; |
| | | } |
| | | |
| | | /** |
| | | * 获取GUID |
| | | */ |
| | | public static String getGuid() { |
| | | return UUID.randomUUID().toString(); |
| | | } |
| | | |
| | | /** |
| | | * 获取用户ip |
| | | */ |
| | | public static String getIpAddress(HttpServletRequest request) { |
| | | String ip = request.getHeader("X-Forwarded-For"); |
| | | if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { |
| | |
| | | return ip; |
| | | } |
| | | |
| | | /** |
| | | * 获取当前时间的Timestamp |
| | | */ |
| | | public static Timestamp getCurrentTimestamp() { |
| | | return new Timestamp(System.currentTimeMillis()); |
| | | } |
| | | |
| | | /** |
| | | * 获取当前时间指定分钟数后的Timestamp |
| | | */ |
| | | public static Timestamp getTimestamp(int min) { |
| | | Calendar now = Calendar.getInstance(); |
| | | now.add(Calendar.MINUTE, min); |
| | |
| | | return new Timestamp(now.getTimeInMillis()); |
| | | } |
| | | |
| | | /** |
| | | * 从Cookie中获取token |
| | | */ |
| | | public static String getTokenFromCookie(HttpServletRequest request) { |
| | | Cookie[] cookies = request.getCookies(); |
| | | if (cookies == null || cookies.length == 0) { |
| | |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 向Cookie中添加token |
| | | */ |
| | | public static void saveToken2Cookie(String token, HttpServletRequest request, HttpServletResponse response) { |
| | | // 先删除 |
| | | deleteCookies(request, response); |
| | | |
| | | // 再保存 |
| | | saveCookie(StaticData.TOKEN_COOKIE_KEY, token, response); |
| | | } |
| | | |
| | | /** |
| | | * 保存Cookie |
| | | */ |
| | | public static void saveCookie(String key, String value, HttpServletResponse response) { |
| | | Cookie cookie = new Cookie(key, value); |
| | | // 设置cookie失效时间,单位为秒 |
| | | cookie.setMaxAge(SettingData.COOKIE_MAX_AGE); |
| | | cookie.setHttpOnly(false); |
| | | cookie.setPath("/"); |
| | |
| | | response.addCookie(cookie); |
| | | } |
| | | |
| | | /** |
| | | * 删除cookie中的值 |
| | | */ |
| | | public static void deleteCookie(String cookieKey, HttpServletRequest request, HttpServletResponse response) { |
| | | Cookie[] cookies = request.getCookies(); |
| | | if (cookies != null && cookies.length > 0) { |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 删除所有Cookie |
| | | */ |
| | | public static void deleteCookies(HttpServletRequest request, HttpServletResponse response) { |
| | | Cookie[] cookies = request.getCookies(); |
| | | if (cookies != null && cookies.length > 0) { |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 根据键获取Cookie值 |
| | | */ |
| | | public static String getCookieByKey(String key, HttpServletRequest request) { |
| | | Cookie[] cookies = request.getCookies(); |
| | | if (cookies == null || cookies.length == 0) { |
| | |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 获取Token |
| | | */ |
| | | public static String getToken(HttpServletRequest request) { |
| | | // 1.从url参数中,获取token |
| | | String token = request.getParameter(StaticData.TOKEN_KEY); |
| | | |
| | | // 2.为空,则从header里获取 |
| | | if (token == null) { |
| | | token = request.getHeader(StaticData.TOKEN_KEY); |
| | | } |
| | | |
| | | // 3.还为空,则从cookie里获取 |
| | | if (token == null) { |
| | | token = getTokenFromCookie(request); |
| | | } |
| | |
| | | return token; |
| | | } |
| | | |
| | | /** |
| | | * 获取Request |
| | | */ |
| | | public static HttpServletRequest getRequest() { |
| | | ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); |
| | | |
| | | return servletRequestAttributes.getRequest(); |
| | | } |
| | | |
| | | /** |
| | | * 获取Response |
| | | */ |
| | | public static HttpServletResponse getResponse() { |
| | | ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); |
| | | |
| | | return servletRequestAttributes.getResponse(); |
| | | } |
| | | |
| | | /** |
| | | * 获取Session |
| | | */ |
| | | public static HttpSession getSession() { |
| | | return getRequest().getSession(); |
| | | } |
| | | |
| | | /** |
| | | * 获取真实路径 |
| | | */ |
| | | public static String getRealPath(String path) { |
| | | HttpServletRequest req = getRequest(); |
| | | ServletContext ctx = req.getSession().getServletContext(); |
| | |
| | | return ctx.getRealPath("/" + path); |
| | | } |
| | | |
| | | /** |
| | | * 输出str至前端 |
| | | */ |
| | | public static boolean writeStr2Page(HttpServletResponse res, String str) { |
| | | try { |
| | | res.setContentType("application/json;charset=UTF-8"); |
| | |
| | | return false; |
| | | } |
| | | |
| | | /** |
| | | * 输出json至前端 |
| | | */ |
| | | public static void writeJson2Page(HttpServletResponse res, String str) { |
| | | String json = JSON.toJSONString(new ResponseMsg<>(HttpStatus.ERROR, str)); |
| | | writeStr2Page(res, json); |
| | | } |
| | | |
| | | /** |
| | | * 获取错误JSON |
| | | */ |
| | | public static String getErrJson(HttpStatus status, String msg) { |
| | | return JSON.toJSONString(new ResponseMsg<String>(status, msg)); |
| | | } |
| | | |
| | | /** |
| | | * 写响应信息 |
| | | */ |
| | | public static void writeInfo(HttpStatus status, String info, HttpServletResponse res) { |
| | | WebHelper.writeStr2Page(res, WebHelper.getErrJson(status, info)); |
| | | } |
| | | |
| | | /** |
| | | * 获取随机整数 |
| | | */ |
| | | public static int getRandomInt(int min, int max) { |
| | | return new Random().nextInt(max) % (max - min + 1) + min; |
| | | } |
| | | |
| | | /** |
| | | * 下载文件 |
| | | */ |
| | | public static void download(String file, String fileName, HttpServletResponse res) throws Exception { |
| | | download(file, fileName, false, res); |
| | | } |
| | | |
| | | /** |
| | | * 下载文件 |
| | | * |
| | | * @param file 文件 |
| | | * @param fileName 文件名 |
| | | * @param res 响应 |
| | | * @throws Exception 异常 |
| | | */ |
| | | public static void download(String file, String fileName, boolean inline, HttpServletResponse res) throws Exception { |
| | | if (StringHelper.isEmpty(fileName)) { |
| | | fileName = StringHelper.YMDHMS2_FORMAT.format(new Date()); |
| | |
| | | fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"); |
| | | String dispose = inline ? "inline" : "attachment"; |
| | | |
| | | // 设置响应头中文件的下载方式为附件方式,以及设置文件名 |
| | | res.setHeader("Content-Disposition", dispose + "; filename*=UTF-8''" + fileName); |
| | | // 设置响应头的编码格式为 UTF-8 |
| | | res.setCharacterEncoding("UTF-8"); |
| | | |
| | | // 通过response对象设置响应数据格式(如:"text/plain; charset=utf-8") |
| | | String ext = FileHelper.getExtension(file); |
| | | String mime = FileHelper.getMime(ext); |
| | | res.setContentType(mime); |
| | | |
| | | // 通过response对象,获取到输出流 |
| | | ServletOutputStream outputStream = res.getOutputStream(); |
| | | // 定义输入流,通过输入流读取文件内容 |
| | | FileInputStream fileInputStream = new FileInputStream(file); |
| | | |
| | | int len = 0; |
| | | byte[] bytes = new byte[1024]; |
| | | while ((len = fileInputStream.read(bytes)) != -1) { |
| | | // 通过输入流读取文件数据,然后通过上述的输出流写回浏览器 |
| | | outputStream.write(bytes, 0, len); |
| | | outputStream.flush(); |
| | | } |
| | | |
| | | // 关闭资源 |
| | | fileInputStream.close(); |
| | | outputStream.close(); |
| | | } |
| | | |
| | | /** |
| | | * 执行命令 |
| | | * |
| | | * @param cmd 命令 |
| | | */ |
| | | public static void exec(String cmd) { |
| | | try { |
| | | Process process = Runtime.getRuntime().exec(cmd); |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 获取请求的参数值 |
| | | * |
| | | * @param req 请求 |
| | | * @param key 参数名 |
| | | * @return 参数值 |
| | | */ |
| | | public static String getReqParamVal(HttpServletRequest req, String key) { |
| | | Map<String, String[]> maps = req.getParameterMap(); |
| | | for (Map.Entry<String, String[]> entry : maps.entrySet()) { |
| | |
| | | return null; |
| | | } |
| | | |
| | | /** |
| | | * 获取请求的参数值 |
| | | * |
| | | * @param req 请求 |
| | | * @param key 参数名 |
| | | * @return 参数值 |
| | | */ |
| | | public static String[] getReqParamVals(HttpServletRequest req, String key) { |
| | | Map<String, String[]> maps = req.getParameterMap(); |
| | | for (Map.Entry<String, String[]> entry : maps.entrySet()) { |