工具方法整理

Excel工具类:

  1 import net.sf.jxls.transformer.XLSTransformer;
  2 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  3 import org.apache.poi.ss.usermodel.Workbook;
  4 import org.jxls.reader.ReaderBuilder;
  5 import org.jxls.reader.XLSReadStatus;
  6 import org.jxls.reader.XLSReader;
  7 import org.springframework.util.ResourceUtils;
  8 import org.springframework.web.multipart.MultipartFile;
  9 import org.xml.sax.SAXException;
 10 
 11 import javax.servlet.http.HttpServletResponse;
 12 import java.io.*;
 13 import java.util.*;
 14 
 15 public class ExcelUtil {
 16 
 17     /**
 18      * @param beans    Map<String, Object>,数据集合
 19      * @param path     String,模板路径
 20      * @param fileName String,文件名
 21      * @param response HttpServletResponse
 22      * @Title: exportExcel
 23      * @Description: 导出Excel执行方法
 24      */
 25     public static void exportExcel(Map<String, Object> beans, String path, String fileName,
 26                                    HttpServletResponse response) {
 27         FileInputStream fileInputStream = null;
 28         OutputStream outputStream = null;
 29         XLSTransformer transformer = new XLSTransformer();
 30         try {
 31             // 文件名称
 32             fileName = fileName + "_" + DateUtil.format(new Date(), DateUtil.PATTERN[4]) + ".xls";
 33             // 获得写入文件名称的OutputStream
 34             response.setContentType("application/x-excel");
 35             response.setHeader("Content-Disposition", "attachment;filename=".concat(new String(fileName.getBytes
 36                     ("GB2312"), "ISO-8859-1")));
 37             outputStream = response.getOutputStream();
 38             //获取模板路径
 39             File file = ResourceUtils.getFile("classpath:template_excel");
 40             // 获得模板的输入流
 41             fileInputStream = new FileInputStream(file + "/" + path);
 42             // 将beans通过模板输入流写到workbook中
 43             Workbook workbook = transformer.transformXLS(fileInputStream, beans);
 44             workbook.write(outputStream);
 45             workbook.close();
 46         } catch (Exception e) {
 47             e.printStackTrace();
 48         } finally {
 49             if (fileInputStream != null) {
 50                 try {
 51                     fileInputStream.close();
 52                 } catch (IOException e) {
 53                     e.printStackTrace();
 54                 }
 55             }
 56             if (outputStream != null) {
 57                 try {
 58                     outputStream.close();
 59                 } catch (IOException e) {
 60                     e.printStackTrace();
 61                 }
 62             }
 63         }
 64     }
 65 
 66     /**
 67      * @param file      MultipartFile,上传的文件
 68      * @param xmlConfig String,xml路径
 69      * @param clazz     Class<T>
 70      * @return List<T>
 71      * @Title: exportExcel
 72      * @Description: 导入Excel执行方法
 73      */
 74     public static <T> List<T> importExcel(MultipartFile file, String xmlConfig, String listKey, Class<T> clazz) {
 75         InputStream inputXLS = null;
 76         InputStream inputXML = null;
 77         try {
 78             inputXML = clazz.getClass().getResourceAsStream(xmlConfig);
 79             XLSReader mainReader = ReaderBuilder.buildFromXML(inputXML);
 80             inputXLS = new BufferedInputStream(file.getInputStream());
 81             List<T> list = new ArrayList<>();
 82             Map<String, Object> beans = new HashMap<>();
 83             beans.put(listKey, list);
 84 
 85             XLSReadStatus readStatus = mainReader.read(inputXLS, beans);
 86             if (readStatus.isStatusOK()) {
 87                 return list;
 88             }
 89         } catch (IOException | SAXException | InvalidFormatException e) {
 90             e.printStackTrace();
 91         } finally {
 92             try {
 93                 if (inputXML != null) {
 94                     inputXML.close();
 95                 }
 96                 if (inputXLS != null) {
 97                     inputXLS.close();
 98                 }
 99             } catch (IOException e) {
100                 e.printStackTrace();
101             }
102         }
103         return null;
104     }
105 }
View Code

Date工具类:

  1 import org.springframework.util.StringUtils;
  2 
  3 import java.text.SimpleDateFormat;
  4 import java.time.Instant;
  5 import java.time.LocalDate;
  6 import java.time.LocalDateTime;
  7 import java.time.ZoneId;
  8 import java.time.format.DateTimeFormatter;
  9 import java.util.*;
 10 
 11 /**
 12  * Date工具类
 13  */
 14 public class DateUtil {
 15 
 16     // 默认使用系统当前时区
 17     private static final ZoneId ZONE = ZoneId.systemDefault();
 18 
 19     public static String[] PATTERN = new String[]{"yyyy-MM", "yyyyMM", "yyyy/MM", "yyyyMMdd", "yyyy-MM-dd",
 20             "yyyy/MM/dd", "yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss", "yyyy"};
 21 
 22 
 23     /**
 24      * LocalDate转String
 25      *
 26      * @param date
 27      * @param pattern
 28      * @return String
 29      */
 30     public static String formatLocalDate(LocalDate date, String pattern) {
 31         try {
 32             DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);
 33             return dateFormat.format(date);
 34         } catch (Exception e) {
 35             e.printStackTrace();
 36         }
 37         return "";
 38     }
 39 
 40     /**
 41      * Date转LocalDate
 42      *
 43      * @param date
 44      * @return String
 45      */
 46     public static LocalDate dateToLocalDate(Date date) {
 47         try {
 48             Instant instant = date.toInstant();
 49             LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZONE);
 50             return localDateTime.toLocalDate();
 51         } catch (Exception e) {
 52             e.printStackTrace();
 53         }
 54         return null;
 55     }
 56 
 57     /**
 58      * Date转LocalDate
 59      *
 60      * @param localDate
 61      * @return String
 62      */
 63     public static Date localDateToDate(LocalDate localDate) {
 64         try {
 65             Instant instant = localDate.atStartOfDay().atZone(ZONE).toInstant();
 66             return Date.from(instant);
 67         } catch (Exception e) {
 68             e.printStackTrace();
 69         }
 70         return null;
 71     }
 72 
 73     /**
 74      * String转Date
 75      *
 76      * @param str
 77      * @param pattern
 78      * @return Date
 79      */
 80     public static Date parseDate(String str, String pattern) {
 81         try {
 82             if (str != null && str.length() > 0) {
 83                 SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
 84                 return dateFormat.parse(str);
 85             }
 86         } catch (Exception e) {
 87             e.printStackTrace();
 88         }
 89         return null;
 90     }
 91 
 92     /**
 93      * Date转String
 94      *
 95      * @param date
 96      * @param pattern
 97      * @return String
 98      */
 99     public static String format(Date date, String pattern) {
100         try {
101             SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
102             return dateFormat.format(date);
103         } catch (Exception e) {
104             e.printStackTrace();
105         }
106         return "";
107     }
108 
109     //Date转换为LocalDateTime
110     public static LocalDateTime convertDateToLDT(Date date) {
111         return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
112     }
113 
114     //LocalDateTime转换为Date
115     public static Date convertLDTToDate(LocalDateTime time) {
116         return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
117     }
118 
119     /**
120      * 获取本周的第一天和最后一天
121      */
122     public static Map<String, Object> getWeekBeginAndEndTime(Date date) {
123         //获取本周开始时间
124         Calendar calendarStart = Calendar.getInstance();
125         calendarStart.setFirstDayOfWeek(Calendar.MONDAY);
126         calendarStart.setTime(date);
127         calendarStart.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
128         //获取本周结束时间
129         Calendar calendarEnd = Calendar.getInstance();
130         calendarEnd.setFirstDayOfWeek(Calendar.MONDAY);
131         calendarEnd.setTime(date);
132         calendarEnd.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
133 
134         //时间格式化
135         String weekBeginTime = format(calendarStart.getTime(), PATTERN[4]);
136         String weekEndTime = format(calendarEnd.getTime(), PATTERN[4]);
137         //返回信息
138         Map<String, Object> map = new HashMap<>();
139         map.put("weekBeginTime", weekBeginTime);
140         map.put("weekEndTime", weekEndTime);
141         return map;
142     }
143 
144     public static Map<String, Object> getMonthStartAndEndTime(Date date) {
145         //获取本月第一天
146         Calendar calendarMonthStart = Calendar.getInstance();
147         calendarMonthStart.add(Calendar.MONTH, 0);
148         calendarMonthStart.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
149         //获取本月最后一天
150         Calendar calendarMonthEnd = Calendar.getInstance();
151         calendarMonthEnd.set(Calendar.DAY_OF_MONTH, calendarMonthEnd.getActualMaximum(Calendar.DAY_OF_MONTH));
152         //格式化
153         SimpleDateFormat format = new SimpleDateFormat(PATTERN[4]);
154         String monthBeginTime = format.format(calendarMonthStart.getTime());
155         String monthEndTime = format.format(calendarMonthEnd.getTime());
156         Map<String, Object> map = new HashMap<>();
157         map.put("monthBeginTime", monthBeginTime);
158         map.put("monthEndTime", monthEndTime);
159         return map;
160     }
161 
162     /**
163      * 获取开始时间至结束时间这几个月时间
164      *
165      * @param startTime
166      * @param endTime
167      * @return List<Date>
168      */
169     public static List<Date> getMonthDate(Date startTime, Date endTime) {
170         if (startTime == null || endTime == null) {
171             return null;
172         }
173 
174         List<Date> list = new ArrayList<>();
175 
176         Calendar min = Calendar.getInstance();
177         Calendar max = Calendar.getInstance();
178 
179         min.setTime(startTime);
180         min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
181 
182         max.setTime(endTime);
183         max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
184 
185         Calendar curr = min;
186         while (curr.before(max)) {
187             list.add(curr.getTime());
188             curr.add(Calendar.MONTH, 1);
189         }
190         return list;
191     }
192 
193     public static void main(String[] args){
194         Date date = new Date(2018,9,18);
195         String season = getSeason(date);
196         System.out.println(season);
197     }
198 
199     /**
200      * 获取开始时间至结束时间这几个月时间
201      *
202      * @param startTime
203      * @param endTime
204      * @return List<String>
205      */
206     public static List<String> getMonthDateToString(Date startTime, Date endTime) {
207         List<String> list = new ArrayList<>();
208 
209         Calendar min = Calendar.getInstance();
210         Calendar max = Calendar.getInstance();
211 
212         min.setTime(startTime);
213         min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
214 
215         max.setTime(endTime);
216         max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
217 
218         Calendar curr = min;
219         while (curr.before(max)) {
220             list.add(format(curr.getTime(), PATTERN[0]));
221             curr.add(Calendar.MONTH, 1);
222         }
223         return list;
224     }
225 
226     /**
227      * 1 第一季度 2 第二季度 3 第三季度 4 第四季度
228      *
229      * @param date
230      * @return
231      */
232     public static String getSeason(Date date) {
233         Calendar c = Calendar.getInstance();
234         String season = format(date, PATTERN[9]);
235         c.setTime(date);
236 
237         int month = c.get(Calendar.MONTH);
238         switch (month) {
239             case Calendar.JANUARY:
240             case Calendar.FEBRUARY:
241             case Calendar.MARCH:
242                 season += "年1季度";
243                 break;
244             case Calendar.APRIL:
245             case Calendar.MAY:
246             case Calendar.JUNE:
247                 season += "年2季度";
248                 break;
249             case Calendar.JULY:
250             case Calendar.AUGUST:
251             case Calendar.SEPTEMBER:
252                 season += "年3季度";
253                 break;
254             case Calendar.OCTOBER:
255             case Calendar.NOVEMBER:
256             case Calendar.DECEMBER:
257                 season += "年4季度";
258                 break;
259             default:
260                 break;
261         }
262         return season;
263     }
264 
265     public static List<String> getSeasonList(Date startDate, Date endDate) {
266         if (startDate == null || endDate == null) {
267             return null;
268         }
269 
270         List<Date> monthList = getMonthDate(startDate, endDate);
271 
272         List<String> seasonList = new ArrayList<>();
273 
274         for (Date date : monthList) {
275             String season = DateUtil.getSeason(date);
276             if (!seasonList.contains(season)) {
277                 seasonList.add(season);
278             }
279         }
280         return seasonList;
281     }
282 
283     public static List<String> getYearList(Date startDate, Date endDate) {
284         if (startDate == null || endDate == null) {
285             return null;
286         }
287         List<String> list = new ArrayList<>();
288 
289         Calendar min = Calendar.getInstance();
290         Calendar max = Calendar.getInstance();
291 
292         min.setTime(startDate);
293         min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
294 
295         max.setTime(endDate);
296         max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
297 
298         Calendar curr = min;
299         while (curr.before(max)) {
300             list.add(format(curr.getTime(), PATTERN[9]));
301             curr.add(Calendar.YEAR, 1);
302         }
303         return list;
304     }
305 
306     public static String getSeasonBeginTime(String season) {
307         if(StringUtils.isEmpty(season)){
308             return null;
309         }
310         String[] seasonArray = season.split("年");
311         if(seasonArray.length!=2 || StringUtils.isEmpty(seasonArray[1])){
312             return null;
313         }
314         Calendar calendar = Calendar.getInstance();
315         String seasonNum = seasonArray[1].substring(0,1);
316         switch (seasonNum) {
317             case "1":
318                 calendar.set(Integer.valueOf(seasonArray[0]), Calendar.JANUARY, 1);
319                 calendar.set(Calendar.DAY_OF_MONTH, 1);
320                 calendar.set(Calendar.HOUR_OF_DAY, 0);
321                 calendar.set(Calendar.MINUTE, 0);
322                 calendar.set(Calendar.SECOND, 0);
323                 break;
324             case "2":
325                 calendar.set(Integer.valueOf(seasonArray[0]), Calendar.APRIL, 1);
326                 calendar.set(Calendar.DAY_OF_MONTH, 1);
327                 calendar.set(Calendar.HOUR_OF_DAY, 0);
328                 calendar.set(Calendar.MINUTE, 0);
329                 calendar.set(Calendar.SECOND, 0);
330                 break;
331             case "3":
332                 calendar.set(Integer.valueOf(seasonArray[0]), Calendar.JULY, 1);
333                 calendar.set(Calendar.DAY_OF_MONTH, 1);
334                 calendar.set(Calendar.HOUR_OF_DAY, 0);
335                 calendar.set(Calendar.MINUTE, 0);
336                 calendar.set(Calendar.SECOND, 0);
337                 break;
338             case "4":
339                 calendar.set(Integer.valueOf(seasonArray[0]), Calendar.OCTOBER, 1);
340                 calendar.set(Calendar.DAY_OF_MONTH, 1);
341                 calendar.set(Calendar.HOUR_OF_DAY, 0);
342                 calendar.set(Calendar.MINUTE, 0);
343                 calendar.set(Calendar.SECOND, 0);
344                 break;
345             default:
346                 break;
347         }
348         return DateUtil.format(calendar.getTime(), PATTERN[7]);
349     }
350 
351     public static String getSeasonEndTime(String season) {
352         if(StringUtils.isEmpty(season)){
353             return null;
354         }
355         String[] seasonArray = season.split("年");
356         if(seasonArray.length!=2 || StringUtils.isEmpty(seasonArray[1])){
357             return null;
358         }
359         Calendar calendar = Calendar.getInstance();
360         String seasonNum = seasonArray[1].substring(0,1);
361         switch (seasonNum) {
362             case "1":
363                 calendar.set(Integer.valueOf(seasonArray[0]), Calendar.MARCH, 1);
364                 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
365                 calendar.set(Calendar.HOUR_OF_DAY, 23);
366                 calendar.set(Calendar.MINUTE, 59);
367                 calendar.set(Calendar.SECOND, 59);
368                 break;
369             case "2":
370                 calendar.set(Integer.valueOf(seasonArray[0]), Calendar.JUNE, 1);
371                 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
372                 calendar.set(Calendar.HOUR_OF_DAY, 23);
373                 calendar.set(Calendar.MINUTE, 59);
374                 calendar.set(Calendar.SECOND, 59);
375                 break;
376             case "3":
377                 calendar.set(Integer.valueOf(seasonArray[0]), Calendar.SEPTEMBER, 1);
378                 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
379                 calendar.set(Calendar.HOUR_OF_DAY, 23);
380                 calendar.set(Calendar.MINUTE, 59);
381                 calendar.set(Calendar.SECOND, 59);
382                 break;
383             case "4":
384                 calendar.set(Integer.valueOf(seasonArray[0]), Calendar.DECEMBER, 1);
385                 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
386                 calendar.set(Calendar.HOUR_OF_DAY, 23);
387                 calendar.set(Calendar.MINUTE, 59);
388                 calendar.set(Calendar.SECOND, 59);
389                 break;
390             default:
391                 break;
392         }
393         return DateUtil.format(calendar.getTime(), PATTERN[7]);
394     }
395 
396     public static String getMonthBeginTime(Date date) {
397         if(date == null){
398             return null;
399         }
400         Calendar calendar = Calendar.getInstance();
401         calendar.setTime(date);
402         calendar.set(Calendar.DAY_OF_MONTH, 1);
403         calendar.set(Calendar.HOUR_OF_DAY, 0);
404         calendar.set(Calendar.MINUTE, 0);
405         calendar.set(Calendar.SECOND, 0);
406         return DateUtil.format(calendar.getTime(), PATTERN[7]);
407     }
408     public static String getMonthEndTime(Date date) {
409         if(date == null){
410             return null;
411         }
412         Calendar calendar = Calendar.getInstance();
413         calendar.setTime(date);
414         calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
415         calendar.set(Calendar.HOUR_OF_DAY, 23);
416         calendar.set(Calendar.MINUTE, 59);
417         calendar.set(Calendar.SECOND, 59);
418         return DateUtil.format(calendar.getTime(), PATTERN[7]);
419     }
420 
421     public static Date getYearBeginDate(Date date) {
422         if(date == null){
423             return null;
424         }
425         Calendar calendar = Calendar.getInstance();
426         calendar.setTime(date);
427         calendar.set(Calendar.MONTH, 0);
428         calendar.set(Calendar.DAY_OF_MONTH, 1);
429         calendar.set(Calendar.HOUR_OF_DAY, 0);
430         calendar.set(Calendar.MINUTE, 0);
431         calendar.set(Calendar.SECOND, 0);
432         return calendar.getTime();
433     }
434 
435     public static Date getYearEndDate(Date date) {
436         if(date == null){
437             return null;
438         }
439         Calendar calendar = Calendar.getInstance();
440         calendar.setTime(date);
441         calendar.set(Calendar.MONTH, 11);
442         calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
443         calendar.set(Calendar.HOUR_OF_DAY, 23);
444         calendar.set(Calendar.MINUTE, 59);
445         calendar.set(Calendar.SECOND, 59);
446         return calendar.getTime();
447     }
448 
449     public static String getYearBeginTime(Date date) {
450         if(date == null){
451             return null;
452         }
453         Calendar calendar = Calendar.getInstance();
454         calendar.setTime(date);
455         calendar.set(Calendar.MONTH, 0);
456         calendar.set(Calendar.DAY_OF_MONTH, 1);
457         calendar.set(Calendar.HOUR_OF_DAY, 0);
458         calendar.set(Calendar.MINUTE, 0);
459         calendar.set(Calendar.SECOND, 0);
460         return DateUtil.format(calendar.getTime(), PATTERN[7]);
461     }
462 
463     public static String getYearEndTime(Date date) {
464         if(date == null){
465             return null;
466         }
467         Calendar calendar = Calendar.getInstance();
468         calendar.setTime(date);
469         calendar.set(Calendar.MONTH, 11);
470         calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
471         calendar.set(Calendar.HOUR_OF_DAY, 23);
472         calendar.set(Calendar.MINUTE, 59);
473         calendar.set(Calendar.SECOND, 59);
474         return DateUtil.format(calendar.getTime(), PATTERN[7]);
475     }
476 
477 //    public static void main(String[] args){
478 //        String startTime = "2018年2季度";
479 //        startTime = startTime.split("年")[1].substring(0,1);
480 //        System.out.println(startTime);
481 //    }
482 
483 }
View Code

正则表达式工具类:

  1 import com.alibaba.fastjson.JSON;
  2 import org.springframework.util.StringUtils;
  3 
  4 import java.util.regex.Matcher;
  5 import java.util.regex.Pattern;
  6 
  7 
  8 public class CheckParam {
  9     //验证手机号码的正则表达式
 10     private static final String regexp_mobile="^(13|14|15|17|18)[0-9]{9}$";
 11     //验证身份证号的正则表达式
 12     public static final String id_card_regx = "^\\d{15}$|^\\d{17}[0-9Xx]$";
 13     private static final String EmptyMes = "不能为空!";
 14     private static final String SplitChar = ",|\\,";
 15     //验证listingNo的正则表达式
 16     private static final String listingNo_regx = "^[\\w\\d]{12}$";
 17 
 18     /**
 19      * Object非空校验
 20      * 
 21      * @param strJson
 22      *            字段名称用","分隔 eg: 用户ID,用户名,.....
 23      * @param strJson
 24      *                字段名称用","分隔 eg: userId,userName,.....
 25      * @param objects
 26      *            对应strJson的字段值,要一一对应
 27      * @return 校验成功返回"",否则返回相应错误。
 28      * 详细用法:
 29      *  CheckEmptyString("用户ID,用户名称","userId,userName",object,object);
 30      * </pre>
 31      */
 32     public static ResultFactory CheckEmptyObject(String strJson,String keys, Object... objects) {
 33         ResultFactory result = new ResultFactory();
 34         String[] strArr = strJson.split(SplitChar);
 35         String[] keysArr = keys.split(SplitChar);
 36         if (strArr.length != objects.length) {
 37             return result.setErrorCode(ErrorCode.BAD_REQUEST).addError("param","参数对应错误!");
 38         }
 39         for (int i = 0; i < strArr.length; i++) {
 40             if (objects[i] == null) {
 41                 result.setErrorCode(ErrorCode.BAD_REQUEST).addError(keysArr[i],strArr[i] + EmptyMes);
 42                 continue;
 43             }
 44             if (objects[i].getClass().equals(String.class)) {
 45                 if (StringUtils.isEmpty(objects[i].toString())) {
 46                     result.setErrorCode(ErrorCode.BAD_REQUEST).addError(keysArr[i],strArr[i] + EmptyMes);
 47                 }
 48                 continue;
 49             }
 50         }
 51         return result;
 52     }
 53 
 54     /**
 55      * 校验手机号码
 56      *
 57      * @param mobile 手机号码
 58      * @return true 正确 false 错误
 59      * @throws Exception
 60      */
 61     public static boolean checkMobile(String mobile) throws Exception{
 62         boolean flag = false;
 63         try {
 64             Pattern pattern = Pattern.compile(regexp_mobile);
 65             Matcher matcher = pattern.matcher(mobile);
 66             flag = matcher.matches();
 67         } catch (Exception e) {
 68             throw e;
 69         }
 70 
 71         return flag;
 72     }
 73 
 74     /**
 75      * 身份证号码校验
 76      *
 77      * @param idCard
 78      * @return true 正确 false 错误
 79      * @throws Exception
 80      */
 81     public static boolean checkIdCard(String idCard) throws Exception{
 82         boolean flag = false;
 83         try {
 84             Pattern pattern = Pattern.compile(id_card_regx);
 85             Matcher matcher = pattern.matcher(idCard);
 86             flag = matcher.matches();
 87         } catch (Exception e) {
 88             throw e;
 89         }
 90         return flag;
 91     }
 92 
 93     /**
 94      *
 95      * @param listingNo
 96      * @return true正确,false错误
 97      * @throws Exception
 98      */
 99     public static boolean checkListingNo(String listingNo) {
100         boolean flag = false;
101         try {
102             Pattern pattern = Pattern.compile(listingNo_regx);
103             Matcher matcher = pattern.matcher(listingNo);
104             flag = matcher.matches();
105         } catch (Exception e) {
106             throw e;
107         }
108 
109         return flag;
110     }
111 
112     public static void main(String[] args) {
113         System.out.println(JSON.toJSONString(CheckEmptyObject("用户ID,用户名", "userId,userName", "", "")));
114     }
115 }
View Code

MD5工具类:

 1 import java.io.FileNotFoundException;
 2 import java.security.MessageDigest;
 3 import java.security.NoSuchAlgorithmException;
 4 
 5 public class MD5Util {
 6 
 7     public static String getFileMD5String(byte[] uploadBytes){
 8         String result = "";
 9         try {
10             MessageDigest md = MessageDigest.getInstance("MD5");
11             md.update(uploadBytes);
12             byte b[] = md.digest();
13             int i;
14             StringBuffer buf = new StringBuffer();
15             for (int offset = 0; offset < b.length; offset++) {
16                 i = b[offset];
17                 if (i < 0)
18                     i += 256;
19                 if (i < 16)
20                     buf.append("0");
21                 buf.append(Integer.toHexString(i));
22             }
23             result = buf.toString();
24         } catch (NoSuchAlgorithmException e) {
25             e.printStackTrace();
26         }
27         return result;
28     }
29 
30     public static void main(String[] args) throws FileNotFoundException {
31         byte[] b = {1,1,1,0};
32         String result = getFileMD5String(b);
33         System.out.println(result);
34     }
35 
36 }
View Code

OSS文件上传工具类:

 1 import com.aliyun.oss.OSSClient;
 2 import com.aliyun.oss.model.ObjectMetadata;
 3 import com.aliyun.oss.model.PutObjectResult;
 4 
 5 import java.io.File;
 6 import java.io.FileInputStream;
 7 import java.io.FileNotFoundException;
 8 import java.io.InputStream;
 9 import java.net.URL;
10 import java.util.Date;
11 
12 /**
13  * Oss统一工具类
14  *
15  * @author BUER
16  */
17 public class OssUtil {
18 
19     private static final String accessKeyId = "LTAI8OAyueumjZY9";
20     private static final String accessKeySecret = "XdaGhjCJvPKrI4jumAs2IkUU5owDXg";
21     private static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
22     private static final String bucketName = "sdljbim"; //存储空间
23     private static final long overTime = 3600 * 1000;
24 
25     private static OSSClient ossClient = null;
26 
27     static {
28         if (ossClient == null) {
29             ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
30         }
31     }
32 
33     /**
34      * 上传图片到OSS
35      *
36      * @param objectName  文件名,带除上传bucket以外的文件夹路径
37      * @param inputStream
38      * @param len         文件长度
39      * @return
40      */
41     public static String uploadFile(String objectName, InputStream inputStream, Long len) {
42         // 创建上传Object的Metadata
43         ObjectMetadata meta = new ObjectMetadata();
44         // 必须设置ContentLength
45         meta.setContentLength(len);
46         // 上传Object.
47         PutObjectResult result = ossClient.putObject(bucketName, objectName, inputStream, meta);
48         // 打印ETag
49         return result.getETag();
50     }
51 
52     /**
53      * 获取文件访问地址(设置URL过期时间为1小时)
54      * </p>
55      *
56      * @param objectName 文件名
57      * @return URL 图片访问绝对路径
58      */
59     public static String getFileUrl(String objectName) {
60         String urlStr = null;
61         if (objectName != null && objectName.length() > 0) {
62             while (objectName.indexOf("/") == 0) {
63                 objectName = objectName.substring(1);
64             }
65             // 设置URL过期时间为1小时
66             Date expiration = new Date(new Date().getTime() + overTime);
67             // 创建URL
68             URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
69             if (url != null) {
70                 urlStr = url.toString();
71                 urlStr = urlStr.split("\\?")[0];
72             }
73         }
74         return urlStr;
75     }
76 
77     /**
78      * 删除OSS中的文件
79      *
80      * @param objectName
81      */
82     public static void deleteFile(String objectName) {
83         // 删除文件。
84         ossClient.deleteObject(bucketName, objectName);
85     }
86 
87     public static void main(String[] args) throws FileNotFoundException {
88         File file = new File("C:\\Users\\BUER\\Pictures\\1-1G121203437.jpg");
89         InputStream is = new FileInputStream(file);
90         String res = OssUtil.uploadFile("1G121203437.jpg", is, file.length());
91         String url = getFileUrl("1G121203437.jpg");
92         System.out.println(url);
93     }
94 }
View Code

分页工具类:

 1 public class PageUtil {
 2 
 3     /**
 4      * 创建分页
 5      * @param pageNum
 6      *            页码
 7      * @param pageSize
 8      *            每页显示数量
 9      * @return
10      */
11     public static int getRowIndex(int pageNum, int pageSize) {
12         int rowIndex = (pageNum - 1) * pageSize;
13         return rowIndex;
14     }
15 
16 }
View Code

图片验证码工具类:

  1 import sun.misc.BASE64Decoder;
  2 import sun.misc.BASE64Encoder;
  3 
  4 import javax.imageio.ImageIO;
  5 import java.awt.Color;
  6 import java.awt.Font;
  7 import java.awt.Graphics;
  8 import java.awt.Graphics2D;
  9 import java.awt.RenderingHints;
 10 import java.awt.geom.AffineTransform;
 11 import java.awt.image.BufferedImage;
 12 import java.io.ByteArrayOutputStream;
 13 import java.io.File;
 14 import java.io.FileOutputStream;
 15 import java.io.IOException;
 16 import java.util.Arrays;
 17 import java.util.HashMap;
 18 import java.util.Map;
 19 import java.util.Random;
 20 
 21 /**
 22  * 图片验证码工具类
 23  */
 24 public class RandomCodeUtil {
 25     private static Random random = new Random();
 26 
 27     private static Color getRandColor(int fc, int bc) {
 28         if (fc > 255)
 29             fc = 255;
 30         if (bc > 255)
 31             bc = 255;
 32         int r = fc + random.nextInt(bc - fc);
 33         int g = fc + random.nextInt(bc - fc);
 34         int b = fc + random.nextInt(bc - fc);
 35         return new Color(r, g, b);
 36     }
 37 
 38     private static int getRandomIntColor() {
 39         int[] rgb = getRandomRgb();
 40         int color = 0;
 41         for (int c : rgb) {
 42             color = color << 8;
 43             color = color | c;
 44         }
 45         return color;
 46     }
 47 
 48     private static int[] getRandomRgb() {
 49         int[] rgb = new int[3];
 50         for (int i = 0; i < 3; i++) {
 51             rgb[i] = random.nextInt(255);
 52         }
 53         return rgb;
 54     }
 55 
 56     private static void shear(Graphics g, int w1, int h1, Color color) {
 57         shearX(g, w1, h1, color);
 58         shearY(g, w1, h1, color);
 59     }
 60 
 61     private static void shearX(Graphics g, int w1, int h1, Color color) {
 62 
 63         int period = random.nextInt(2);
 64 
 65         boolean borderGap = true;
 66         int frames = 1;
 67         int phase = random.nextInt(2);
 68 
 69         for (int i = 0; i < h1; i++) {
 70             double d = (double) (period >> 1)
 71                     * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
 72             g.copyArea(0, i, w1, 1, (int) d, 0);
 73             if (borderGap) {
 74                 g.setColor(color);
 75                 g.drawLine((int) d, i, 0, i);
 76                 g.drawLine((int) d + w1, i, w1, i);
 77             }
 78         }
 79 
 80     }
 81 
 82     private static void shearY(Graphics g, int w1, int h1, Color color) {
 83 
 84         int period = random.nextInt(40) + 10; // 50;
 85 
 86         boolean borderGap = true;
 87         int frames = 20;
 88         int phase = 7;
 89         for (int i = 0; i < w1; i++) {
 90             double d = (double) (period >> 1)
 91                     * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
 92             g.copyArea(i, 0, 1, h1, 0, (int) d);
 93             if (borderGap) {
 94                 g.setColor(color);
 95                 g.drawLine(i, (int) d, i, 0);
 96                 g.drawLine(i, (int) d + h1, i, h1);
 97             }
 98 
 99         }
100     }
101 
102     /**
103      * 生成指定长度的随机数字和字母
104      *
105      * @param length
106      * @return
107      */
108     public static String getStringRandom(int length) {
109         String val = "";
110         Random random = new Random();
111         for (int i = 0; i < length; i++) {
112             String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
113             switch (charOrNum) {
114                 case "char":
115                     int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
116                     val += (char) (random.nextInt(26) + temp);
117                     break;
118                 case "num":
119                     val += String.valueOf(random.nextInt(10));
120                     break;
121             }
122         }
123         return val;
124     }
125 
126     /**
127      * Base64编码的验证码图片
128      *
129      * @param w
130      * @param h
131      * @param code
132      * @return
133      * @throws Exception
134      */
135     public static Map<String, String> imageToBase64(int w, int h, String code) throws Exception {
136         Map<String, String> result = new HashMap<String, String>();
137         int verifySize = code.length();
138         BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
139         Random rand = new Random();
140         Graphics2D g2 = image.createGraphics();
141         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
142         Color[] colors = new Color[5];
143         Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
144                 Color.ORANGE, Color.PINK, Color.YELLOW};
145         float[] fractions = new float[colors.length];
146         for (int i = 0; i < colors.length; i++) {
147             colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
148             fractions[i] = rand.nextFloat();
149         }
150         Arrays.sort(fractions);
151 
152         g2.setColor(Color.GRAY);// 设置边框色
153         g2.fillRect(0, 0, w, h);
154 
155         Color c = getRandColor(200, 250);
156         g2.setColor(c);// 设置背景色
157         g2.fillRect(0, 2, w, h - 4);
158 
159         // 绘制干扰线
160         Random random = new Random();
161         g2.setColor(getRandColor(160, 200));// 设置线条的颜色
162         for (int i = 0; i < 20; i++) {
163             int x = random.nextInt(w - 1);
164             int y = random.nextInt(h - 1);
165             int xl = random.nextInt(6) + 1;
166             int yl = random.nextInt(12) + 1;
167             g2.drawLine(x, y, x + xl + 40, y + yl + 20);
168         }
169 
170         // 添加噪点
171         float yawpRate = 0.05f;// 噪声率
172         int area = (int) (yawpRate * w * h);
173         for (int i = 0; i < area; i++) {
174             int x = random.nextInt(w);
175             int y = random.nextInt(h);
176             int rgb = getRandomIntColor();
177             image.setRGB(x, y, rgb);
178         }
179 
180         shear(g2, w, h, c);// 使图片扭曲
181 
182         g2.setColor(getRandColor(100, 160));
183         int fontSize = h - 4;
184         Font font = new Font("Arial", Font.ITALIC, fontSize);
185         g2.setFont(font);
186         char[] chars = code.toCharArray();
187         for (int i = 0; i < verifySize; i++) {
188             AffineTransform affine = new AffineTransform();
189             affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1),
190                     (w / verifySize) * i + fontSize / 2, h / 2);
191             g2.setTransform(affine);
192             g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
193         }
194         g2.dispose();
195         ByteArrayOutputStream baos = new ByteArrayOutputStream();
196         ImageIO.write(image, "jpg", baos);
197         result.put("randomCodeBase64", new BASE64Encoder().encode(baos.toByteArray()));
198         result.put("randomCode", code);
199         return result;
200     }
201 
202     /**
203      * 将Base64位编码的图片进行解码,并保存到指定目录
204      *
205      * @param base64 base64编码的图片信息
206      * @return
207      */
208     public static void base64ToImage(String base64) {
209         BASE64Decoder decoder = new BASE64Decoder();
210         try {
211             File file = new File("D:/test.jpg");
212             FileOutputStream write = new FileOutputStream(file);
213             byte[] decoderBytes = decoder.decodeBuffer(base64);
214             write.write(decoderBytes);
215             write.close();
216         } catch (IOException e) {
217             e.printStackTrace();
218         }
219     }
220 
221     public static void main(String[] args) throws Exception {
222         Map<String, String> resuhResult = imageToBase64(120, 40, getStringRandom(4));
223         String base64 = (String) resuhResult.get("base64");
224         String imgCode = (String) resuhResult.get("imgCode");
225         System.out.println("base64"+base64);
226         System.out.println("imgCode"+imgCode);
227         base64ToImage(base64);
228     }
229 }
View Code

ErrorCode错误码工具类:

 1 public enum ErrorCode {
 2 
 3     OK(200, "OK"),
 4     BAD_REQUEST(400, "Bad Request"),
 5     UNAUTHORIZED(401, "Unauthorized"),
 6     PAYMENT_REQUIRED(402, "Payment Required"),
 7     FORBIDDEN(403, "Forbidden"),
 8     NOT_FOUND(404, "Not Found"),
 9     METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
10     SERVER_ERROR(500, "Server Error"),
11     COMP_NOT_EXIST(400100, "构件不存在"),
12     SELECT_IS_NULL(400020, "查询为空"),
13     ADD_ERROR(400021, "添加失败"),
14     EDIT_ERROR(400022, "编辑失败"),
15     DELETE_ERROR(400023, "删除失败"),
16     PASSWORD_ERROR(400030, "密码错误"),
17     ACCOUNT_PASSWORD_IS_NULL(400010, "账号密码不能为空"),
18     PASSWORD_NOT_SAME(400040,"密码不一致"),
19     OLDPASSWORD_ERROR(400050, "旧密码错误"),
20     PARAM_IS_NULL(400060,"参数不能为空"),
21     USERNAME_IS_USED(400070,"用户名已被使用"),
22     UPLOAD_ERROR(400080,"上传失败"),
23     UPLOAD_SUCCESS(0, "图片上传成功");
24 
25 
26     private final int value;
27     private final String message;
28 
29     ErrorCode(int value, String reasonPhrase) {
30         this.value = value;
31         this.message = reasonPhrase;
32     }
33 
34     public int value() {
35         return this.value;
36     }
37 
38     public String getMessage(){
39         return this.message;
40     }
41 }
View Code

 

转载于:https://www.cnblogs.com/txppp/p/10216283.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值