目前分類:java (40)

瀏覽方式: 標題列表 簡短摘要

gson使用 @SerializedName

  @SerializedName("data")
  private String name;

 

jackson使用

  @JsonProperty("data")
  private String name;

 

REFER

https://www.javadoc.io/doc/com.google.code.gson/gson/2.6.2/com/google/gson/annotations/SerializedName.html

 

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

序列和反序列設定,可以設定物件轉換模式

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;

}

refer:  http://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonProperty.Access.html


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

HttpServletResponse.sendRedirect()

  • 使用相對地址會導到port80
  • 瀏覽器端工作,瀏覽器會出現重定向頁面的URL
  • url可帶參數

RequestDispatcher.forward()

  • 伺服器的內部機制
  • url不能帶參數 (可使用response.setAttribute)

refer:

https://ithelp.ithome.com.tw/articles/10185109


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

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;
        }
}

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

  @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
    }
  }

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

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

 


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

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 ) 不同,可以加入自定義轉換方式

  1. 先自定一個轉換定義
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();   
    }
}
  1. 進行轉換
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class , new DateValue());
//jsonConfig.registerJsonValueProcessor(Date.class , new DateValue("yyyy-MM-dd"));
JSONArray.fromObject(rtnProductUsableVoList,jsonConfig);

 


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

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存活時間
如果程式調整了資料沒有改變,建議先來確定瀏覽器的狀況

aaa.JPG

 

 

參考資料:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching_FAQ#Cache_validation

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

改寫的時候,遇到 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) {
    }  
  }  
}

 

 

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

最近在操作時間習慣用 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;
        //時間在此略過處理
        }

 


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

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

 

 


咪卡恰比 發表在 痞客邦 留言(0) 人氣()

執行時產生 runtime exception  ( unchecked exception ):

  • extends Exception
  • 程式上會有開發者無法預期的錯誤
  • 異常會一路拋出至JVM處理
class selfException extends RuntimeException{
}

應受控制產生  Checked Exception :

  • 此類型錯誤應該被處理(開發者認知會有異常發生)
  • 需用try catch於當下處理
    class selfException extends Exception{
    }

參考資料:https://openhome.cc/Gossip/Java/ThrowableHierarchy.html


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

把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;
}

 


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

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.

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

判斷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

 

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isNumber-java.lang.String-


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

取得當前類名、方法名


public class AbcTest{
  @Test
  public void testMethod() throws Exception {
    //AbcTest.testMethod
    System.out.println(this.getClass().getSimpleName()+"."+Thread.currentThread().getStackTrace()[1].getMethodName());
  }
}

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

資料送到前端的時候不想送一些沒用的東西出來,把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

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

 

String str = "1 2  3   4";
str = str.replaceAll("[\\s|\\&nbsp;]{2,}", " ");
//等於 [ \t\n\x0B\f\r] 空白字元
System.out.println(str); //1 2 3 4

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

public Blob newBlobByInputStream(InputStream inputStream){
        Blob blob = null;
        
        try{
            blob = Hibernate.getLobCreator(getCurrentSession()).createBlob(inputStream,inputStream.available());
        }catch(Exception e){ }
        return blob;
}

public Blob newBlobByInputStream(InputStream inputStream){
        Blob blob = null;
        
        try{
            blob = Hibernate.createBlob(inputStream);
        }catch(Exception e){ }
        return blob;
}

public Blob newBlobByString(String str){
 Blob blob = null;                  
  try{
    blob  = new SerialBlob(str.getBytes("UTF-8"));//String 转 blob
  }catch(Exception e){ }
  return blob; 
}

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

long startTime=System.nanoTime();
//測試的動作
long endTime=System.nanoTime();
System.out.println("執行時間: "+(endTime-startTime)+" NS ");  

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

«12