org.apache.commons.lang3.exception.ExceptionUtils.ExceptionUtils.getStackTrace(Throwable)
ref: https://stackoverflow.com/questions/1149703/how-can-i-convert-a-stack-trace-to-a-string
org.apache.commons.lang3.exception.ExceptionUtils.ExceptionUtils.getStackTrace(Throwable)
ref: https://stackoverflow.com/questions/1149703/how-can-i-convert-a-stack-trace-to-a-string
import java.util.Random; public static void main(String[] args) { System.out.println(new Random().nextInt(90)+10); //86 (取10~99) System.out.println(new Random().nextInt(10)); //3 (取0~9) System.out.println(new Random().nextInt(9)+1); //4 (取1~9) System.out.println(new Random().nextInt(2)); //1 (取0~9) }
new Random().nextInt(n):取0~(n-1)之正整數
n需為正數
refer: https://docs.oracle.com/javase/7/docs/api/java/util/Random.htm
gson使用 @SerializedName
@SerializedName("data") private String name;
jackson使用
@JsonProperty("data") private String name;
REFER
序列和反序列設定,可以設定物件轉換模式
EX:
package com.bean.response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @lombok.Data @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Response { @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) String message; @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) String code; }
HttpServletResponse.sendRedirect()
RequestDispatcher.forward()
refer:
https://ithelp.ithome.com.tw/articles/10185109
public static <T> List<T> copyPropertiesList(List<?> src, Class<T> clazz) { if (CollectionUtils.isNotEmpty(src)) { Gson gson = new GsonBuilder().serializeNulls().create(); List<T> lst = new ArrayList<>(); JsonArray array = JsonParser.parseString(gson.toJson(src)).getAsJsonArray(); for (JsonElement elem : array) { lst.add(new Gson().fromJson(elem, clazz)); } return lst; }else{ return null; } }
@Test public void StringToChar() throws Exception { String str = "14239626"; for (int i = 0; i < str.length(); ++i) { int tmp = (str.charAt(i) - 48); System.out.print(tmp); //14239626 } for (int i = 0; i < str.length(); ++i) { int tmp2 = Integer.parseInt(String.valueOf(str.charAt(i))); System.out.print(tmp2); //14239626 } for (int i = 0; i < str.length(); ++i) { int tmp3 = Character.getNumericValue(str.charAt(i)); //char 數字的NumericValue等於自己 System.out.print(tmp3); //14239626 } //Char("48")~Char("57") = 0~9 //Char(0)~Char(9) = 48~57 for (int i = 0; i < str.length(); ++i) { int tmp4 = (str.charAt(i)); System.out.print(tmp4); //4952505157545054 } }
Method visibility and@Cacheable/@CachePut/@CacheEvict
When using proxies, you should apply the @Cache*annotations only to methods with public visibility.
If you do annotate protected, private or package-visible methods with these annotations, no error is raised, but the annotated method does not exhibit the configured caching settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods as it changes the bytecode itself.
Ref : https://docs.spring.io/spring/docs/3.2.0.RC1/reference/html/cache.html
java Data object 用 JSONObject.fromObject 或 JSONArray.fromObject做轉換的時候,
會轉成一個[ object object]的模式,如下:
"itemDateFrom":{"date":18,"hours":0,"seconds":0,"month":8,"nanos":0,"timezoneOffset":-480,"year":119,"minutes":0,"time":1568736000000,"day":3}
因為和預期 ( YYYY/MM/DD ) 不同,可以加入自定義轉換方式
public class DateValue implements JsonValueProcessor{ private String format ="yyyy/MM/dd"; public DateValue(){ super(); } public DateValue(String datePattern){ super(); this.format = datePattern; } @Override public Object processArrayValue(Object value, JsonConfig config) { return process(value); } @Override public Object processObjectValue(String key, Object value, JsonConfig config) { return process(value); } private Object process(Object value){ if(value instanceof Date){ SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(value); } return value == null ? "" : value.toString(); } }
JsonConfig jsonConfig = new JsonConfig(); jsonConfig.registerJsonValueProcessor(Date.class , new DateValue()); //jsonConfig.registerJsonValueProcessor(Date.class , new DateValue("yyyy-MM-dd")); JSONArray.fromObject(rtnProductUsableVoList,jsonConfig);
HttpServletResponse res; //Cache-Control HTTP1.1 //Pragma Expires HTTP1.0 res.setHeader( "Pragma", "no-cache" ); //與Cache-Control: no-cache相同,會被Cache-Control覆蓋 res.addHeader( "Cache-Control", "must-revalidate" ); res.addHeader( "Cache-Control", "no-cache" ); //發request向server確認是否取得新資料 res.addHeader( "Cache-Control", "no-store" ); //完全不Cache res.setDateHeader("Expires", 0); //CACHE過期時間,與Cache-Control: max-age相同,會被Cache-Control覆蓋
被Cache資料,可以從DevTool看到 from disk cache的字樣,以及max-age存活時間
如果程式調整了資料沒有改變,建議先來確定瀏覽器的狀況
參考資料:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching_FAQ#Cache_validation
改寫的時候,遇到 java.io.IOException: Bad file descriptor 錯誤,
發現是因為InputStream沒有好好處理完就做close()了,
針對緩衝部分還是要注意一下
File thisFile= new File("file's src "); /* 1. use Files.newInputStream() Opens a file, returning an input stream to read from the file. The stream will not be buffered, and is not required to support the mark or reset methods. */ InputStream is = Files.newInputStream(thisFile.toPath());
/* 2. get byte[] */ File thisFile= new File("file's src "); InputStream thisFileIs = null; try{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); thisFileIs = new FileInputStream(thisFile); byte[] thisFileIsByte = new byte[1024]; int len = 0; while ((len = thisFileIs .read(thisFileIsByte )) != -1) { outStream.write(thisFileIsByte , 0, len); } byte[] in_b = outStream.toByteArray(); }catch(IOException e){ } finally { if(thisFileIs != null) { try{ thisFileIs.close(); }catch(IOException e) { } } }
上述等同
InputStream thisFileIs = null; try{ thisFileIs = new FileInputStream(thisFile); byte[] in_b = IOUtils.toByteArray(new FileInputStream(thisFile)); //這行 }catch(IOException e){ } finally { if(thisFileIs != null) { try{ thisFileIs.close(); }catch(IOException e) { } } }
最近在操作時間習慣用 Calendar (java.util.Calendar)
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
//--
Calendar now = Calendar.getInstance(); //初始取得現在時間 //Get DATA int month = now.get(Calendar.MONTH) + 1; //取月份 - 月份是從0開始,+1成為一般人了解的月份 //Set DATA now.set(Calendar.MONTH, 0); //設定時間至指定月份(1月) now.set(Calendar.DAY_OF_MONTH, 1); //設定時間至1個月的第幾天(1日) //Calculation DATA now.add(Calendar.MONTH, 7); //加減月份(加7個月) now.add(Calendar.MONTH, -7); //加減月份(減7個月) //時間設為一天的最後一秒 public Calendar setDayTimeToLastSec(Calendar calendar) { calendar.set(11, 23); calendar.set(12, 59); calendar.set(13, 59); calendar.set(14, 999); return calendar; } //時間設為一天的開始 public Calendar setDayTimeToFirSec(Calendar calendar) { calendar.set(11, 0); calendar.set(12, 0); calendar.set(13, 0); calendar.set(14, 0); return calendar; } //上個月的最後一天 public Calendar getLMLD() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, 1); //設為這個月第一天 cal.add(Calendar.DATE, -1); //倒回一天 = 上個月最後一天 return cal; //時間在此略過處理 }
java.util.Date cannot be cast to java.sql.Date
Date date=new Date(); new java.sql.Date(date.getTime()) ; https://stackoverflow.com/questions/18614836/using-setdate-in-preparedstatement
執行時產生 runtime exception ( unchecked exception ):
class selfException extends RuntimeException{ }
應受控制產生 Checked Exception :
class selfException extends Exception{ }
參考資料:https://openhome.cc/Gossip/Java/ThrowableHierarchy.html
把EXCEL資料爬出成bean
雖然好像有一些人寫了用ANNOCATION去對應BEAN的JAR檔
不過先用簡單的方式來做一次吧
重點是beanTitle 要和EXCEL資料對應到,EXCEL的一行的第一格會是beanTitle[0]
public void mainWork(){ String filePath = "feebeeApSet.xlsx"; String[] beanTitle = {"id", "type", "startDate"}; //excel欄位對應到bean的tag this.translateToBeanFromXls(filePath, TestBean.class, beanTitle); //call function } //testBean.class public class TestBean implements Serializable { private String id; private String type; private String startDate; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } } public <T> List<T> translateToBeanFromXls(String filePath, Class<T> objT, String[] beanTitle) throws Exception { List<T> beanList = new LinkedList<T>(); if(StringUtils.isBlank(filePath) || objT == null || ArrayUtils.isEmpty(beanTitle)){ //data is null! }else{ FileInputStream fs = null; XSSFWorkbook workbook = null; try{ int beanTitleSize = beanTitle.length; fs = new FileInputStream(filePath); //EXCEL workbook workbook = new XSSFWorkbook(fs); //EXCEL sheet XSSFSheet sheet = workbook.getSheetAt(0); //row num int rowNum = sheet.getPhysicalNumberOfRows(); log.info(filePath + "_rowNum: " + rowNum); //總行數 int lastRowIndex = sheet.getLastRowNum(); log.info(filePath + "_lastRowNum: " + lastRowIndex); //TITLE單位格數 int titleLastCellNum = sheet.getRow(0).getLastCellNum(); log.info(filePath + "_title.lastCellNum: " + titleLastCellNum); //判斷EXCEL是否基本資料錯誤 //1.含title 最低限制為兩列 //2.TITLE的格數須與beanTitle資料相同 if (rowNum < 2) { //ERROR }else if(beanTitleSize!=titleLastCellNum){ //ERROR }else{ for(int i = 1; i <= lastRowIndex; i++) { XSSFRow row = sheet.getRow(i); //判斷該行的單元數和beanTitle數是否能相應 int thisLastCellNum = row.getLastCellNum(); if(beanTitleSize!=thisLastCellNum){ //ERROR }else{ T bean = objT.newInstance(); //處理格數 for (int j = 0; j < thisLastCellNum; j++) { XSSFCell cell = row.getCell(j); Object cellValue = null; switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_BLANK: cellValue = ""; break; case XSSFCell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue().trim(); break; case XSSFCell.CELL_TYPE_BOOLEAN: cellValue = cell.getBooleanCellValue(); break; case XSSFCell.CELL_TYPE_NUMERIC: short format = cell.getCellStyle().getDataFormat(); if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cellValue = formater.format(date); }else if(format == 14 || format == 31 || format == 57 || format == 58){ DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); Date date = DateUtil.getJavaDate(cell.getNumericCellValue()); cellValue = formater.format(date); }else if (format == 20 || format == 32) { DateFormat formater = new SimpleDateFormat("HH:mm"); Date date = DateUtil.getJavaDate(cell.getNumericCellValue()); cellValue = formater.format(date); } else{ cellValue = cell.getNumericCellValue(); } break; default: //其他格式不處理 cellValue = null; break; } if(cellValue!=null){ // 轉成bean BeanUtils.setProperty(bean, beanTitle[j], cellValue); } } beanList.add(bean); } } } }finally{ if(fs!=null){fs.close();} } } return beanList; }
sheet.getPhysicalNumberOfRows();
獲取有記錄的行數 (NULL列數略過不計)
sheet.getLastRowNum();
獲取最後行數,回傳值為最後行數-1 (只有一行的話回傳0)
the number of the last row contained in this sheet, zero based.
Owing to idiosyncrasies in the excel file format, if the result of calling this method is zero, you can't tell if that means there are zero rows on the sheet, or one at position zero. For that case, additionally call getPhysicalNumberOfRows() to tell if there is a row at position zero or not.
判斷string是否是數字
NumberUtils.isNumber(string) =>將被廢棄,建議使用 isCreatable(String)
現在發布的 Class NumberUtils 底層可以看到直接轉用 isCreatable(String)了
/** * NumberUtils.isNumber Deprecated. * This feature will be removed in Lang 4.0, use isCreatable(String) instead */ NumberUtils.isNumber("123"); //true NumberUtils.isNumber("qwe"); //false NumberUtils.isCreatable("123"); //true NumberUtils.isCreatable("qwe"); //false NumberUtils.isCreatable(""); //false NumberUtils.isCreatable(" "); //false NumberUtils.isCreatable(null); //false
取得當前類名、方法名
public class AbcTest{ @Test public void testMethod() throws Exception { //AbcTest.testMethod System.out.println(this.getClass().getSimpleName()+"."+Thread.currentThread().getStackTrace()[1].getMethodName()); } }
資料送到前端的時候不想送一些沒用的東西出來,把null過濾掉
User user = new User(); //1. Gson gson = new Gson(); gson.toJson(user ); //return String (no null object) //2. JSONObject.fromObject(user).toString() //contains null object
String str = "1 2 3 4"; str = str.replaceAll("[\\s|\\ ]{2,}", " "); //等於 [ \t\n\x0B\f\r] 空白字元 System.out.println(str); //1 2 3 4