發表於 工具

chrome查到網頁request的流量的方式

1.於chrome => click “F12″ Button,顯示如下頁面
連至欲觀察流量的頁面,
於下方即可看到每個request的url、status(http code)、size(若為cache會顯示from disk cache)

1.PNG
2.有相關篩選可以選擇,於下方內click right mouse,
有清除cache、cookies選項、將檔案開啟在source panel或新頁面,
其中Save as HAR with content是將此分析結果儲存為har檔,
har檔為JSon格式故可以用開啟json的工具觀察,
網路上已有相關的讀取程式。

2.png

發表於 程式分享

多個查詢及執行由同一組程式執行

想將多個查詢及產生檔案之程式碼(每組程式均有不同的運作邏輯),
以下是我規劃的架構(由spring4 + struts2 + hibernate5):

1.PNG

相關程式碼架構示意如下:
一、設定檔
1.struts.xml

...
 <action name="DTDayReport_*" class="com.xxx.action.DTDayReportAction" method="{1}">
 <result name="success">/ajax/DTDayReport.jsp</result>
 <result name="{1}" type="json">
 <param name="root">dataMap</param>
 </result>
 </action>
...

2.(enum) DayReport.java

public enum DayReport {
    SNP("SNP", "檔案一", "com.xxx.bean.DTRptXXX1"), 
    SNT("SNT", "檔案二", "com.xxx.bean.DTRptXXX2"), 
    SNT("SNT", "檔案三", "com.xxx.bean.DTRptXXX3");
    
    protected String id;
    protected String desc;
    protected String className;
    
    private DayReport(String id, String desc, String className) {
        this.id = id;
        this.desc = desc;
        this.className = className;
    }

    public String getId() {
        return id;
    }

    public String getDesc() {
        return desc;
    }

    public String getClassName() {
        return className;
    }
}

3.DTReportCol.java

public class DTReportCol {
    private String colId;
    private String colDesc;
    private String colType; //String, double , int, Date
    private int digit;      //顯示小數位數
    private String dateFmt; //Ex.yyyy-mm-dd
    private String codeType;

    public DTReportCol(String colId, String colDesc, String colType, int digit, String dateFmt) {
        this(colId, colDesc, colType, digit, dateFmt, "");
    }

    public DTReportCol(String colId, String colDesc, String colType, int digit, String dateFmt, String codeType) {
        super();
        this.colId = colId;
        this.colDesc = colDesc;
        this.colType = colType;
        this.digit = digit;
        this.dateFmt = dateFmt;
        this.codeType = codeType;
    }

    public String getColId() {
        return colId;
    }
    
    public void setColId(String colId) {
        this.colId = colId;
    }
    
    public String getColDesc() {
        return colDesc;
    }
    
    public void setColDesc(String colDesc) {
        this.colDesc = colDesc;
    }
    
    public String getColType() {
        return colType;
    }
    
    public void setColType(String colType) {
        this.colType = colType;
    }
    
    public int getDigit() {
        return digit;
    }
    
    public void setDigit(int digit) {
        this.digit = digit;
    }
    
    public String getDateFmt() {
        return dateFmt;
    }
    
    public void setDateFmt(String dateFmt) {
        this.dateFmt = dateFmt;
    }
    
    public String getCodeType() {
        return codeType;
    }

    public void setCodeType(String codeType) {
        this.codeType = codeType;
    }

    @Override
    public String toString() {
        return "DTReportCol [colId=" + colId + ", colDesc=" + colDesc + ", colType=" + colType + ", digit=" + digit
                + ", dateFmt=" + dateFmt + ", codeType=" + codeType + "]";
    }
}

4.(interface) DTRptInterface.java

import java.util.LinkedList;
import com.xxx.entity.DTReportCol;

public interface DTRptInterface {
    public abstract String retriveFileName();
    public abstract LinkedList retriveCols();
    public abstract boolean rerunByDate(String applyDate_in, String errorMsg, String modifyEmp);
    public abstract boolean removeByDate(String applyDate_in, String errorMsg, String modifyEmp);
}

二、bean檔
1.DTRptDayPK.java

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class DTRptDayPK implements Serializable {
    @Column(name = "applyDate")
    private Date applyDate;
    @Column(name = "rowIdx")
    private int rowIdx;
    
    public DTRptDayPK() {
        
    }

    public DTRptDayPK(Date applyDate, int rowIdx) {
        super();
        this.applyDate = applyDate;
        this.rowIdx = rowIdx;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((applyDate == null) ? 0 : applyDate.hashCode());
        result = prime * result + rowIdx;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        DTRptDayPK other = (DTRptDayPK) obj;
        if (applyDate == null) {
            if (other.applyDate != null)
                return false;
        } else if (!applyDate.equals(other.applyDate))
            return false;
        if (rowIdx != other.rowIdx)
            return false;
        return true;
    }

    public Date getApplyDate() {
        return applyDate;
    }

    public void setApplyDate(Date applyDate) {
        this.applyDate = applyDate;
    }

    public int getRowIdx() {
        return rowIdx;
    }

    public void setRowIdx(int rowIdx) {
        this.rowIdx = rowIdx;
    }

    @Override
    public String toString() {
        return "DTRptDayPK [applyDate=" + applyDate + ", rowIdx=" + rowIdx + "]";
    }
}

2.DTRptXXX1.java – 與DayReport.java配合設定,可n個

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
...

@Entity
@Table(name = "DTRptXXX1")
public class DTRptXXX1 implements Serializable, DTRptInterface {
    @EmbeddedId
    @AttributeOverrides({
        @AttributeOverride(
            name = "applyDate",
            column = @Column(name = "applyDate")),
        @AttributeOverride(
            name = "rowIdx",
            column = @Column(name = "rowIdx"))
    })
    protected DTRptXXX1PK dtRptDayPK;
    
    //請新增相關欄位
    ... 
    @Column(name = "modifyTime")
    private Date modifyTime;
    @Column(name = "modifyEmp")
    private String modifyEmp;
    
    public DTRptXXX1() {
        
    }

    public DTRptXXX1(DTRptDayPK dtRptDayPK, ... , Date modifyTime, String modifyEmp) {
        super();
        //請新增相關欄位
    ... 
        this.modifyTime = modifyTime;
        this.modifyEmp = modifyEmp;
    }

    public DTRptDayPK getDtRptDayPK() {
        return dtRptDayPK;
    }

    public void setDtRptDayPK(DTRptDayPK dtRptDayPK) {
        this.dtRptDayPK = dtRptDayPK;
    }

    public String getApplyComp() {
        return applyComp;
    }

    //請新增相關欄位之set及get function
    ... 
    
    public Date getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }

    public String getModifyEmp() {
        return modifyEmp;
    }

    public void setModifyEmp(String modifyEmp) {
        this.modifyEmp = modifyEmp;
    }
    
    @Override
    public String toString() {
        return "DTRptSNP [dtRptDayPK=" + dtRptDayPK + 
                ...
                ", modifyTime=" + modifyTime + ", modifyEmp=" + modifyEmp + "]";
    }
    
    @Override
    public String retriveFileName() {
        return "DTRptXXX1.txt";
    }
    
    @Override
    public LinkedList retriveCols() {
        LinkedList dtReportColList = new LinkedList<>();
        
        //請新增相關欄位
        ...
        dtReportColList.add(new DTReportCol("modifyTime", "修改時間", "Date", 0, "yyyy-mm-dd HH:mm:ss"));
        dtReportColList.add(new DTReportCol("modifyEmp", "修改人員", "String", 0, null));

        return dtReportColList;
    }

    @Override
    public boolean rerunByDate(String applyDate_in, String errorMsg, String modifyEmp) {
        DTServiceEntry dtServiceEntry = new DTServiceEntry();
        
        //1.條件判斷
        ...
        
        //2.清除舊資料
        boolean bRemoveOK = removeByDate(applyDate_in, errorMsg, modifyEmp);
        if (bRemoveOK == false) {
            errorMsg = "清除舊資料失敗" + errorMsg + ".";
            return false;
        }
        
        //3.取得資料
        ...
        
        //4.寫入資料庫
        ...
        
        //5.寫入檔案
        ...

        return bOK_modify;
    }

    @Override
    public boolean removeByDate(String applyDate_in, String errorMsg, String modifyEmp) {
        DTServiceEntry dtServiceEntry = new DTServiceEntry();
        Logger logger = LogManager.getLogger(this.getClass().getName());
        
        //1.清除舊資料
        ...
        
        //2.清除舊檔案
        ...
        
        return true;
    }
}

三、(View) DTDayReport.jsp
javascript呼叫後端action的主要程式碼示意如下

 //footable
 var myfootable = {
 first : true,
 rerun : function() {
 var kindVal = $('#s2_kind').find(':selected').val();
 var settleDateVal = $('#settleDate').val();
 if (kindVal.length <= 0 || settleDateVal.length <= 0) {
 if (myfootable.first == false) {
 $('#modal-body-msg').text("請輸入種類及日期.");
 $('#messageModal').modal('show');
 }
 myfootable.first = false;
 return;
 }
 myfootable.first = false;
 
 var formData = {kind : kindVal, settleDate : settleDateVal}; 
 $.ajax({
 url : 'DTDayReport_getJsonRerun.action',
 type: "POST",
 data : formData,
 dataType : 'json',
 success : myfootable.ajax_loaddata,
 error : function(xhr, statusText, error) { 
 alert("錯誤! 無法取得資料.");
 }
 });
 },
 query : function () {
 var kindVal = $('#s2_kind').find(':selected').val();
 var settleDateVal = $('#settleDate').val();
 if (kindVal.length <= 0 || settleDateVal.length <= 0) {
 if (myfootable.first == false) {
 $('#modal-body-msg').text("請輸入種類及日期.");
 $('#messageModal').modal('show');
 }
 myfootable.first = false;
 return;
 }
 myfootable.first = false;
 
 var formData = {kind : kindVal, settleDate : settleDateVal}; 
 $.ajax({
 url : 'DTDayReport_getJson.action',
 type: "POST",
 data : formData,
 dataType : 'json',
 success : myfootable.ajax_loaddata,
 error : function(xhr, statusText, error) { 
 alert("錯誤! 無法取得資料.");
 }
 });
 },
 ajax_loaddata : function(data) {
 $("#footable tbody tr").each(function(index, elem) {
 $(elem).remove();
 });
 
 $.each(data, function(index, item) {
 if (index == "result") {
 if (item.show == true || (item.success == false && myfootable.first == false)) {
 $('#modal-body-msg').text(item.message);
 $('#messageModal').modal('show');
 }
 } else if (index == 'TRANDATE') {
 $('.date-picker').datepicker('change', {dateFormat: 'yy-mm-dd', maxDate: item});
 } else if (index == 'dtRpt' && item != null) {
 $.each(item, function(index2, item2) { 
 var row = myfootable.create_table_row(item2);
 $('#footable tbody').append(row);
 });
 } else if (index == 'settleT2Date') {
 $('#settleT2Date').val(item);
 }
 });
 myfootable.first = false;
 $('#footable').trigger('footable_initialize');
 },
 create_table_row : function (item) {
 var row = '<tr>';
 $.each(reportColList, function(index_col, item_col) {
 var colId = ((item_col.colId == 'applyDate' || item_col.colId == 'rowIdx') 
 ? ('dtRptDayPK.' + item_col.colId) : item_col.colId);
 var sVal = eval('item.' + colId);
 
 //1.日期
 if (item_col.colType == 'Date') {
 sVal = sVal.replace('T',' ');
 if (item_col.dateFmt == 'yyyy-mm-dd')
 sVal = sVal.substring(0, 10);
 }
 //2.代碼mapping
 if (item_col.codeType != null && item_col.codeType.length > 0) {
 var mapObj = codeMap[item_col.codeType];
 if (mapObj !== undefined) {
 if (mapObj[sVal] !== undefined)
 sVal = sVal + '-' + mapObj[sVal];
 }
 }
 
 row += '<td data-value="' + sVal + '">' + sVal + '</td>';
 });
 
 row += '</tr>';
 return row;
 },
 downloadFile : function(e) { 
 e.preventDefault();
 
 var kindVal = $('#s2_kind').find(':selected').val();
 var settleDateVal = $('#settleDate').val();
 if (kindVal.length <= 0 || settleDateVal.length <= 0) {
 if (myfootable.first == false) {
 $('#modal-body-msg').text("請輸入種類及日期.");
 $('#messageModal').modal('show');
 }
 return;
 }
 
 var url = 'DTDayReport.action?kind=' + kindVal + '&type=Download&settleDate=' + settleDateVal;
 window.open(url, "_blank").focus();
 }
 }

 

四、(Action) DTDayReportAction.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
...

public class DTDayReportAction extends BaseAction {
    private static String rootPath = "DownloadPath_Ftp";
    
    //將被Struts2序列化為JSON字符串的對象  
    private Map<String, Object> dataMap = new LinkedHashMap<String, Object>();
    //Query
    private String kind;
    private String type;    //Download=下載檔案
    private String settleDate;
    
    public DTDayReportAction() {
        super();
        myPlatFormList.add(new UserPrivItem(PlatForm.DERIVTRADE.toString(), "DTDaySettle"));
    }
    /** 
     * Struts2序列化指定?性?,必?有??性的getter方法,??上,如果?有?性,而只有getter方法也是可以的 
     * @return 
     */  
    public Map<String, Object> getDataMap() {  
        return dataMap;  
    } 
    
    public void setDataMap(Map<String, Object> dataMap) {
        this.dataMap = dataMap;
    }
    
    //Query
    public String getKind() {
        return kind;
    }
    
    public void setKind(String kind) {
        this.kind = kind;
    }
    
    public String getType() {
        return type;
    }
    
    public void setType(String type) {
        this.type = type;
    }
    
    public String getSettleDate() {
        return settleDate;
    }
    
    public void setSettleDate(String settleDate) {
        this.settleDate = settleDate;
    }
    
    public String getJson() {
        boolean bSuccess = true;
        String message = "";
        
        dataMap.clear();
        
        //1.回覆結果 
        Map<String, Object> dataMessage = new LinkedHashMap<String, Object>();
        dataMessage.put("success", bSuccess);
        dataMessage.put("message", message);
        dataMessage.put("show", false);
        dataMap.put("result", dataMessage);
        
        //2.取得目前交易及前一結帳日
        String tranDate = ...
        request.setAttribute("TRANDATE", tranDate);
                
        //3.取得資料
        retriveData();
                
        return "getJson";
    }   
    
    public String getJsonRerun() {
        boolean bSuccess = false;
        String message = "";
        dataMap.clear();
        
        //1.取得欄位
        for (DayReport dayReport : DayReport.values()) {
            if (dayReport.getId().compareTo(kind) != 0)
               continue;
            
            final String className = dayReport.getClassName();
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    try {
                        UserItem userItem = (UserItem) session.getAttribute("UserItem");
                        Class<?> dayReportClass = Class.forName(className); 
                        Constructor<?> constructor = dayReportClass.getDeclaredConstructor();
                        DTRptInterface obj = (DTRptInterface) constructor.newInstance();
                        Method method = dayReportClass.getMethod("rerunByDate", 
                                            new Class[] {String.class, String.class, String.class});
                            
                        String errorMsg = "";
                        boolean bRerunOK = (boolean) method.invoke(obj, settleDate, errorMsg, userItem.getUsername());
                        logger.info("bRerunOK: " + bRerunOK + ", errorMsg: " + errorMsg);
                    } catch (ClassNotFoundException e1) {
                        logger.error("kind=" + kind + " : ClassNotFoundException - " + e1.getMessage());
                    } catch (NoSuchMethodException e2) {
                        logger.error("kind=" + kind + " : : NoSuchMethodException - " + e2.getMessage());   
                    } catch (IllegalAccessException e3) {
                        logger.error("kind=" + kind + " : IllegalAccessException - " + e3.getMessage());
                    } catch (InvocationTargetException e4) {
                        logger.error("kind=" + kind + " : InvocationTargetException - " + e4.getMessage());
                        e4.printStackTrace();
                    } catch (InstantiationException e5) {
                        logger.error("kind=" + kind + " : InstantiationException - " + e5.getMessage());
                    }
                }
            });
            thread.start();
            try {
                thread.join(300 * 1000);
            } catch (InterruptedException e) {
                logger.error(e.getMessage());
            }

            bSuccess = true;
            break;
        }

        message = (bSuccess == true) ? "重新產出資料中,請確認." : "重新產出資料失敗,請確認.";
        
        //2.回傳結果 
        Map<String, Object> dataMessage = new LinkedHashMap<String, Object>();
        dataMessage.put("success", bSuccess);
        dataMessage.put("message", message);
        dataMessage.put("show", true);
        dataMap.put("result", dataMessage);
                
        //3.取得目前交易及前一日期
        String tranDate = ...
        request.setAttribute("TRANDATE", tranDate);
        
        //4.取得資料
        retriveData();
                
        return "getJsonRerun";
    }
    
    //取得清單
    private boolean retriveData() {
        if (kind.compareToIgnoreCase(DayReport.DTRptXXX1.getId()) == 0) {
            List dtRptXXX1List = ...
            dataMap.put("dtRpt", dtRptXXX1List);
        } else if (kind.compareToIgnoreCase(DayReport.DTRptXXX2.getId()) == 0) {
            ...
        } else
            return false;
        return true;
    }
    
    @Override
    public String execute() throws Exception {
        //下載檔案
        if (type != null && type.compareToIgnoreCase("Download") == 0) {
            String fileName = retriveFileName();
            if (fileName == null || fileName.trim().length() <= 0) {                 response.getWriter().println("Get File error");                 return NONE;            }                       String filePath = SysConfigUtil.getValue(application, rootPath) + File.separator +                      settleDate.replace("-", "") + File.separator + fileName;            logger.info("download filePath= " + filePath);                              FileInputStream fis = null;             try {               //1.開檔              fis = new FileInputStream(filePath);                                        //2.顯示檔案                byte[] buffer = new byte[1024];                 int len = 0;                String docFileName = java.net.URLEncoder.encode(fileName, "UTF-8");                 response.setHeader("Content-Disposition", "attachment;filename=".concat(docFileName));              String extension = DataUtil.getExtension(fileName);                 response.setContentType(getContentType(extension));                 OutputStream out = response.getOutputStream();              while ((len = fis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
                response.getWriter().println("Get Image error");
            } finally {
                if (fis != null)
                    fis.close();
            }
                    
            return NONE;
        }
                
        //1.取得目前交易及前一結帳日
        String tranDate = ...
        request.setAttribute("TRANDATE", tranDate);
        
        //2.取得欄位
        for (DayReport dayReport : DayReport.values()) {            
            if (dayReport.getId().compareTo(kind) == 0) {
                try {
                    Class<?> dayReportClass = Class.forName(dayReport.getClassName()); 
                    Constructor<?> constructor = dayReportClass.getDeclaredConstructor();
                    DTRptInterface obj = (DTRptInterface) constructor.newInstance();
                    
                    Method method = dayReportClass.getMethod("retriveCols", new Class[] {});
                    LinkedList dtReportColList = (LinkedList) method.invoke(obj);

                    logger.info(dtReportColList);
                    request.setAttribute("dtReportColList", dtReportColList);
                } catch (ClassNotFoundException e1) {
                    logger.error("kind=" + kind + " : ClassNotFoundException - " + e1.getMessage());
                } catch (NoSuchMethodException e2) {
                    logger.error("kind=" + kind + " : : NoSuchMethodException - " + e2.getMessage());   
                } catch (IllegalAccessException e3) {
                    logger.error("kind=" + kind + " : IllegalAccessException - " + e3.getMessage());
                } catch (InvocationTargetException e4) {
                    logger.error("kind=" + kind + " : InvocationTargetException - " + e4.getMessage());
                } catch (InstantiationException e5) {
                    logger.error("kind=" + kind + " : InstantiationException - " + e5.getMessage());
                }
                
                break;
            }
        }
        
        return super.execute();
    }
    
    /**
     * 取得檔案名稱
     * @return
     */
    private String retriveFileName() {
        String fileName = null;
        for (DayReport dayReport : DayReport.values()) {
            if (dayReport.getId().compareTo(kind) != 0)
               continue;
            
            String className = dayReport.getClassName();            
            try {
                Class<?> dayReportClass = Class.forName(className); 
                Constructor<?> constructor = dayReportClass.getDeclaredConstructor();
                DTRptInterface obj = (DTRptInterface) constructor.newInstance();
                Method method = dayReportClass.getMethod("retriveFileName", new Class[] {});

                fileName = (String) method.invoke(obj);
                logger.info("fileName: " + fileName);
            } catch (ClassNotFoundException e1) {
                logger.error("kind=" + kind + " : ClassNotFoundException - " + e1.getStackTrace());
            } catch (NoSuchMethodException e2) {
                logger.error("kind=" + kind + " : : NoSuchMethodException - " + e2.getStackTrace());    
            } catch (IllegalAccessException e3) {
                logger.error("kind=" + kind + " : IllegalAccessException - " + e3.getStackTrace());
            } catch (InvocationTargetException e4) {
                logger.error("kind=" + kind + " : InvocationTargetException - " + e4.getStackTrace());
            } catch (InstantiationException e5) {
                logger.error("kind=" + kind + " : InstantiationException - " + e5.getStackTrace());
            }
            break;
        }
        
        return fileName;
    }
}

五、執行結果 : 每個查詢報表畫面類似如下

1.PNG

發表於 程式分享

java產生縮圖

因開發網站上大部份的圖均是透過管理介面讓管理者自行維運,
但有些圖檔過大,
故寫了一段產生縮圖的程式以免使用開啟網頁時塞爆頻寬。

1.指定圖檔寬度 : 傳入來源檔路徑(含檔名)、目的檔路徑(含檔名)、檔案副檔名、寬度

   public void change2SmallImg_w(String fromImgPath, String destImgPath, String imgType, int maxWidth) {
        try {
            File fiBig = new File(fromImgPath);
            File foSmall = new File(destImgPath);

            AffineTransform transform = new AffineTransform();
            BufferedImage bis = ImageIO.read(fiBig);
            //原来的高宽
            int w = bis.getWidth();
            int h = bis.getHeight();
            
            //等比例缩放 
            int nowWidth = maxWidth;
            int nowHeight = (nowWidth * h) / w;
            if (nowHeight > maxWidth) {
                nowHeight = maxWidth;
                nowWidth = (nowHeight * w) / h;
            }

            double sx = (double) nowWidth / w;
            double sy = (double) nowHeight / h;

            transform.setToScale(sx, sy);

            AffineTransformOp ato = new AffineTransformOp(transform, null);
            BufferedImage bid = new BufferedImage(nowWidth, nowHeight,
                    (imgType.compareToIgnoreCase("png") == 0) 
                        ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis, bid);
            
            ImageIO.write(bid, imgType, foSmall);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2.指定圖檔高度 : 傳入來源檔路徑(含檔名)、目的檔路徑(含檔名)、檔案副檔名、高度

   public void change2SmallImg_h(String fromImgPath, String destImgPath, String imgType, int maxHeight) {
        try {
            File fiBig = new File(fromImgPath);
            File foSmall = new File(destImgPath);

            AffineTransform transform = new AffineTransform();
            BufferedImage bis = ImageIO.read(fiBig);
            //原来的高宽
            int w = bis.getWidth();
            int h = bis.getHeight();
            
            //等比例缩放 
            int nowHeight = maxHeight;
            int nowWidth = (nowHeight * w) / h;
            if (nowWidth > maxHeight) {
                nowWidth = maxHeight;
                nowHeight = (nowWidth * h) / w;
            }

            double sx = (double) nowWidth / w;
            double sy = (double) nowHeight / h;

            transform.setToScale(sx, sy);

            AffineTransformOp ato = new AffineTransformOp(transform, null);
            BufferedImage bid = new BufferedImage(nowWidth, nowHeight,
                    (imgType.compareToIgnoreCase("png") == 0) 
                        ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_3BYTE_BGR);
            ato.filter(bis, bid);
            
            ImageIO.write(bid, imgType, foSmall);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
發表於 程式分享

使用iText將word功能變數convert 成 pdf

本篇為使用word功能變數,convert word to pdf,並解決中文顯示問題之延伸,主要說明如何將多個套表檔整合至一支程式,以spring + struts2 + hibernate做開發,呈現其設計模式:
一、DB Schema
1.DTPdfTemplate (PDF版型檔)

2.DTPdfCol (PDF版型欄位檔)

二、hibernate bean
1.DTPdfTemplatePK.java

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class DTPdfTemplatePK implements Serializable {
    @Column(name = "kind")
    private int kind;
    @Column(name = "commSeqno")
    private int commSeqno;
    
    public DTPdfTemplatePK() {
        
    }

    public DTPdfTemplatePK(int kind, int commSeqno) {
        super();
        this.kind = kind;
        this.commSeqno = commSeqno;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + commSeqno;
        result = prime * result + kind;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        DTPdfTemplatePK other = (DTPdfTemplatePK) obj;
        if (commSeqno != other.commSeqno)
            return false;
        if (kind != other.kind)
            return false;
        return true;
    }

    public int getKind() {
        return kind;
    }

    public void setKind(int kind) {
        this.kind = kind;
    }

    public int getCommSeqno() {
        return commSeqno;
    }

    public void setCommSeqno(int commSeqno) {
        this.commSeqno = commSeqno;
    }

    @Override
    public String toString() {
        return "DTPdfTemplatePK [kind=" + kind + ", commSeqno=" + commSeqno + "]";
    }
}

2.DTPdfTemplate.java

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "DTPdfTemplate")
public class DTPdfTemplate implements Serializable {
    @EmbeddedId
    @AttributeOverrides({
        @AttributeOverride(
            name = "kind",
            column = @Column(name = "kind")),
        @AttributeOverride(
            name = "commSeqno",
            column = @Column(name = "commSeqno"))
    })
    protected DTPdfTemplatePK dtPdfTemplatePK;
    @Column(name = "docFileName")
    protected String docFileName;
    @Column(name = "docType")
    protected String docType;
    @Column(name = "docSrc")
    protected byte[] docSrc;
    @Column(name = "modifyTime")
    protected Date modifyTime;
    @Column(name = "modifyEmp")
    protected String modifyEmp;
    
    public DTPdfTemplate() {
        
    }
    
    public DTPdfTemplate(DTPdfTemplatePK dtPdfTemplatePK) {
        super();
        this.dtPdfTemplatePK = dtPdfTemplatePK;
    }

    public DTPdfTemplate(DTPdfTemplatePK dtPdfTemplatePK, String docFileName, String docType, byte[] docSrc,
            Date modifyTime, String modifyEmp) {
        super();
        this.dtPdfTemplatePK = dtPdfTemplatePK;
        this.docFileName = docFileName;
        this.docType = docType;
        this.docSrc = docSrc;
        this.modifyTime = modifyTime;
        this.modifyEmp = modifyEmp;
    }
    
    public DTPdfTemplatePK getDtPdfTemplatePK() {
        return dtPdfTemplatePK;
    }

    public void setDtPdfTemplatePK(DTPdfTemplatePK dtPdfTemplatePK) {
        this.dtPdfTemplatePK = dtPdfTemplatePK;
    }

    public String getDocFileName() {
        return docFileName;
    }

    public void setDocFileName(String docFileName) {
        this.docFileName = docFileName;
    }

    public String getDocType() {
        return docType;
    }

    public void setDocType(String docType) {
        this.docType = docType;
    }

    public byte[] getDocSrc() {
        return docSrc;
    }

    public void setDocSrc(byte[] docSrc) {
        this.docSrc = docSrc;
    }

    public Date getModifyTime() {
        return modifyTime;
    }
    
    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }
    
    public String getModifyEmp() {
        return modifyEmp;
    }
    
    public void setModifyEmp(String modifyEmp) {
        this.modifyEmp = modifyEmp;
    }

    @Override
    public String toString() {
        return "DTPdfTemplate [dtPdfTemplatePK=" + dtPdfTemplatePK + ", docFileName=" + docFileName + ", docType="
                + docType + ", docSrc=" + Arrays.toString(docSrc) + ", modifyTime=" + modifyTime + ", modifyEmp="
                + modifyEmp + "]";
    }   
}

3.DTPdfColPK.java

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class DTPdfColPK implements Serializable {
    @Column(name = "kind")
    private int kind;
    @Column(name = "colSeqno")
    private int colSeqno;
    
    public DTPdfColPK() {
        
    }

    public DTPdfColPK(int kind, int colSeqno) {
        super();
        this.kind = kind;
        this.colSeqno = colSeqno;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + colSeqno;
        result = prime * result + kind;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        DTPdfColPK other = (DTPdfColPK) obj;
        if (colSeqno != other.colSeqno)
            return false;
        if (kind != other.kind)
            return false;
        return true;
    }

    public int getKind() {
        return kind;
    }

    public void setKind(int kind) {
        this.kind = kind;
    }

    public int getColSeqno() {
        return colSeqno;
    }

    public void setColSeqno(int colSeqno) {
        this.colSeqno = colSeqno;
    }

    @Override
    public String toString() {
        return "DTPdfColPK [kind=" + kind + ", colSeqno=" + colSeqno + "]";
    }
}

4.DTPdfCol.java

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "DTPdfCol")
public class DTPdfCol implements Serializable {
    @EmbeddedId
    @AttributeOverrides({
        @AttributeOverride(
            name = "kind",
            column = @Column(name = "kind")),
        @AttributeOverride(
            name = "commSeqno",
            column = @Column(name = "commSeqno"))
    })
    protected DTPdfColPK dtPdfColPK;
    @Column(name = "colName")
    protected String colName;
    @Column(name = "colDesc")
    protected String colDesc;
    @Column(name = "testVal")
    protected String testVal;
    @Column(name = "modifyTime")
    protected Date modifyTime;
    @Column(name = "modifyEmp")
    protected String modifyEmp;
    
    public DTPdfCol() {
        
    }
    
    public DTPdfCol(DTPdfColPK dtPdfColPK) {
        super();
        this.dtPdfColPK = dtPdfColPK;
    }
    
    public DTPdfCol(DTPdfColPK dtPdfColPK, String colName, String colDesc, String testVal, Date modifyTime,
            String modifyEmp) {
        super();
        this.dtPdfColPK = dtPdfColPK;
        this.colName = colName;
        this.colDesc = colDesc;
        this.testVal = testVal;
        this.modifyTime = modifyTime;
        this.modifyEmp = modifyEmp;
    }

    public DTPdfColPK getDtPdfColPK() {
        return dtPdfColPK;
    }

    public void setDtPdfColPK(DTPdfColPK dtPdfColPK) {
        this.dtPdfColPK = dtPdfColPK;
    }

    public String getColName() {
        return colName;
    }

    public void setColName(String colName) {
        this.colName = colName;
    }

    public String getColDesc() {
        return colDesc;
    }

    public void setColDesc(String colDesc) {
        this.colDesc = colDesc;
    }

    public String getTestVal() {
        return testVal;
    }

    public void setTestVal(String testVal) {
        this.testVal = testVal;
    }

    public Date getModifyTime() {
        return modifyTime;
    }
    
    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }
    
    public String getModifyEmp() {
        return modifyEmp;
    }
    
    public void setModifyEmp(String modifyEmp) {
        this.modifyEmp = modifyEmp;
    }

    @Override
    public String toString() {
        return "DTPdfCol [dtPdfColPK=" + dtPdfColPK + ", colName=" + colName + ", colDesc=" + colDesc + ", testVal="
                + testVal + ", modifyTime=" + modifyTime + ", modifyEmp=" + modifyEmp + "]";
    }   
}

三、hibernate sql
1.public DTPdfTemplate retriveDTPdfTemplate(int kind, int commSeqno): 取得套表的word原始檔

   @Override
    @Transactional(readOnly=true)
    public List retriveDTPdfTemplate(int kind) {
        Session session = getSession();
        try {
            Query query = session.createQuery(
                    " FROM DTPdfTemplate c WHERE kidn = :Kind Order By commSeqno ASC");
            query.setParameter("Kind", kind);
            List dtPdfTemplateList = query.list();
            return dtPdfTemplateList;
        } catch (Exception e) {
            logger.error(e);
            return null;
        } finally {
            if (session != null && session.isOpen() == true)
                session.close();
        }
    }

2.public List retriveDTPdfCol(int kind): 取得套表功能變數欄位對應

   @Override
    @Transactional(readOnly=true)
    public List retriveDTPdfCol(int kind) {
        Session session = getSession();
        try {
            Query query = session.createQuery(
                    " FROM DTPdfCol c WHERE kind = :Kind");
            query.setParameter("Kind", kind);
            List dtPdfColList = query.list();
            return dtPdfColList;
        } catch (Exception e) {
            logger.error(e);
            return null;
        } finally {
            if (session != null && session.isOpen() == true)
                session.close();
        }
    }

四、其它參數class
1.PDFTemplateKind.java : 套表類型參數值

public enum PDFTemplateKind {
    ProductDesc(1, "檔案1") , 
    TradeConfirm(2, "檔案2"),
    NewTrade(3, "檔案3"),
    ExpireTrade(4, "檔案4"),
    ELNExpireNotice(5 , "檔案5", "檔案5-A"),
    PGNExpireNotice(6 , "檔案5", "檔案5-B"),
    ELNEarlyTerminate(7 , "檔案7", "檔案7-A"),
    PGNEarlyTerminate(8 , "檔案7", "檔案7-B");
    
    private int id;
    private String desc;
    private String title;

    private PDFTemplateKind(int id, String desc) {
        this.id = id;
        this.desc = desc;
        this.title = desc;
    }
    
    private PDFTemplateKind(int id, String desc, String title) {
        this.id = id;
        this.desc = desc;
        this.title = title;
    }
    
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getDesc() {
        return desc;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

2.DTPdfShowItem.java : 欲呈現的資料

public class DTPdfShowItem {
    private int kind;
    private int tradeSeqno;
    private int mentionSeqno;           //kind = 4 ~ 8
        //以下新增各property...
    ....
    
    public DTPdfShowItem(int kind, int tradeSeqno, int mentionSeqno) {
        super();
        this.kind = kind;
        this.tradeSeqno = tradeSeqno;
        this.mentionSeqno = mentionSeqno;
    }

    //依欄位設定set、get function
        ...
    
    @Override
    public String toString() {
        return "DTPdfShowItem [kind=" + kind + ..... //依上方property設定
    }

五、DTPdfShowAction.java (主要程式邏輯)

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import com.lowagie.text.FontFactory;
import fr.opensagres.xdocreport.converter.ConverterTypeTo;
import fr.opensagres.xdocreport.converter.ConverterTypeVia;
import fr.opensagres.xdocreport.converter.Options;
import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;

public class DTPdfShowAction extends BaseAction {   
    private int kind;
    private int tradeSeqno;
    private int mentionSeqno;
    
    public DTPdfShowAction() {
            super();
    }
    
    public int getKind() {
        return kind;
    }

    public void setKind(int kind) {
        this.kind = kind;
    }
    
    public int getTradeSeqno() {
        return tradeSeqno;
    }

    public void setTradeSeqno(int tradeSeqno) {
        this.tradeSeqno = tradeSeqno;
    }

    public int getMentionSeqno() {
        return mentionSeqno;
    }

    public void setMentionSeqno(int mentionSeqno) {
        this.mentionSeqno = mentionSeqno;
    }

    public String execute() throws Exception {
        //1.判斷傳入參數
        if (kind > 8) {
            logger.error("No Docment match");
            response.getWriter().println("No Docment match");
            return NONE;
        }
        
        if (kind == PDFTemplateKind.ProductDesc.getId() || 
            kind == PDFTemplateKind.TradeConfirm.getId() || 
            kind == PDFTemplateKind.NewTrade.getId()) {
            if (tradeSeqno <= 0) {
                logger.error("tradeSeqno error");
                response.getWriter().println("tradeSeqno error");
                return NONE;
            }
        } else {
            if (mentionSeqno <= 0) {
                logger.error("mentionSeqno error");
                response.getWriter().println("mentionSeqno error");
                return NONE;
            }
        }
        
        //2.取得此筆資料相關訊息
        DTServiceEntry dtServiceEntry = new DTServiceEntry();
        DTPdfShowItem dtPdfShowItem = new DTPdfShowItem(kind, tradeSeqno, mentionSeqno);
        
        boolean bOK = retriveSourceData(dtServiceEntry, dtPdfShowItem);
        if (bOK == false) {
            logger.error("retrive Source Data error");
            response.getWriter().println("retrive Source Data error");
            return NONE;
        }
        logger.info(dtPdfShowItem);
        
        //3.取得此筆資料明細
        List dtPdfColList = dtServiceEntry.retriveDTPdfCol(kind);   
        if (dtPdfColList == null || dtPdfColList.size() <= 0) {
            logger.error("retrive DTPdfCol error");
            response.getWriter().println("retrive DTPdfCol error");
            return NONE;
        }
        
        bOK = mappingColData(dtServiceEntry, dtPdfShowItem, dtPdfColList);
        if (bOK == false) {
            logger.error("retrive Col Data error");
            response.getWriter().println("retrive Col Data error");
            return NONE;
        }
        logger.info(dtPdfColList);
        
        int commSeqno = (kind == PDFTemplateKind.ProductDesc.getId() || kind == PDFTemplateKind.TradeConfirm.getId()) ? dtPdfShowItem.getDtInqPrice().getCommSeqno() : 0;
        DTPdfTemplate dtPdfTemplate = dtServiceEntry.retriveDTPdfTemplate(kind, commSeqno);
        if (dtPdfTemplate != null) {
            try {
                // 1) Load Docx file by filling Velocity template engine and cache
                InputStream in = new ByteArrayInputStream(dtPdfTemplate.getDocSrc());
                IXDocReport report = XDocReportRegistry.getRegistry().loadReport(
                                        in, TemplateEngineKind.Velocity);
             
                // 2) Create context Java model
                IContext context = report.createContext();
                //DTPdfProject project = new DTPdfProject("PDF範例-" + dtPdfTemplate.getDocFileName());
                DTPdfProject project = new DTPdfProject(dtPdfShowItem.getPdfFileName());
                context.put("project", project);
             
                for (DTPdfCol dtPdfCol : dtPdfColList) {
                    logger.info(dtPdfCol);
                    context.put(dtPdfCol.getColName(), dtPdfCol.getTestVal());
                } 
             
                // 3) Generate report by merging Java model with the Docx
                ByteArrayOutputStream outPdf = new ByteArrayOutputStream();
                PdfOptions pdfOptions = PdfOptions.create();                
                FontFactory.registerDirectory(application.getRealPath("/") + "WEB-INF" + File.separator + "classes" + File.separator + "fonts" + File.separator);
                Options options = Options.getTo(ConverterTypeTo.PDF).via(ConverterTypeVia.XWPF).subOptions(pdfOptions);
                report.convert(context, options, outPdf);
             
                // 4) 顯示檔案
                String docFileName = java.net.URLEncoder.encode(dtPdfShowItem.getPdfFileName(), "UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=".concat(docFileName));
                response.setContentType(getContentType("pdf"));
                OutputStream out = response.getOutputStream();
                out.write(outPdf.toByteArray());
                out.close(); 
            } catch (IOException e1) {
                logger.error(e1);
            } catch (XDocReportException e2) {
                logger.error(e2);
            }
        } else {
            logger.error("No Docment - kind : " + kind + ", commSeqno : " +  commSeqno);
            response.getWriter().println("No Docment");
        }

        return NONE;
    }
    
    /**
     * 取得相關資料
     * @param dtPdfShowItem
     * @return
     */
    private boolean retriveSourceData(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem) {
        //mapping 實際資料至dtPdfShowItem,請自行撰寫,此處省略
        ...
        return true;
    }
    
    /**
     * 取得此筆資料明細
     * @param dtServiceEntry
     * @param dtPdfShowItem
     * @param dtPdfColList
     * @return
     */
    private boolean mappingColData(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem,
            List dtPdfColList) {
        //依pdf版型對應,取得套表相關對應值,於對應mappingColData_[1~n]函數實做
        if (dtPdfShowItem.getKind() == PDFTemplateKind.ProductDesc.getId()) { 
            return mappingColData_1(dtServiceEntry, dtPdfShowItem, dtPdfColList);
        } else if (dtPdfShowItem.getKind() == PDFTemplateKind.TradeConfirm.getId()) {
            return mappingColData_2(dtServiceEntry, dtPdfShowItem, dtPdfColList);
        } else if (dtPdfShowItem.getKind() == PDFTemplateKind.NewTrade.getId()) { 
            return mappingColData_3(dtServiceEntry, dtPdfShowItem, dtPdfColList);
        } else if (dtPdfShowItem.getKind() == PDFTemplateKind.ExpireTrade.getId()) { 
            return mappingColData_4(dtServiceEntry, dtPdfShowItem, dtPdfColList);
        } else if (dtPdfShowItem.getKind() == PDFTemplateKind.ELNExpireNotice.getId()) {
            return mappingColData_5(dtServiceEntry, dtPdfShowItem, dtPdfColList);
        } else if (dtPdfShowItem.getKind() == PDFTemplateKind.PGNExpireNotice.getId()) {
            return mappingColData_6(dtServiceEntry, dtPdfShowItem, dtPdfColList);
        } else if (dtPdfShowItem.getKind() == PDFTemplateKind.ELNEarlyTerminate.getId()) { 
            return mappingColData_7(dtServiceEntry, dtPdfShowItem, dtPdfColList);
        } else if (dtPdfShowItem.getKind() == PDFTemplateKind.PGNEarlyTerminate.getId()) {
            return mappingColData_8(dtServiceEntry, dtPdfShowItem, dtPdfColList);
        }
        
        return true;
    }
    
    /**
     * @param dtServiceEntry
     * @param dtPdfShowItem
     * @param dtPdfColList
     * @return
     */
    private boolean mappingColData_1(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem,
            List dtPdfColList) {
        for (DTPdfCol dtPdfCol : dtPdfColList) {
            String colName = dtPdfCol.getColName();
            if (colName.compareToIgnoreCase("trade.targetName") == 0) 
                dtPdfCol.setTestVal(dtPdfShowItem.getDtInqPrice().getTargetName());
            else if (colName.compareToIgnoreCase("trade.riskLevel") == 0) 
                dtPdfCol.setTestVal("RR" + Integer.toString(dtPdfShowItem.getDtInqPrice().getCommRiskLevel()));
            //依實際資料做mapping
            ...
            } else {
                dtPdfCol.setTestVal("");
            }
        }
        return true;
    }
    
    /**
     * @param dtServiceEntry
     * @param dtPdfShowItem
     * @param dtPdfColList
     * @return
     */
    private boolean mappingColData_2(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem,
            List dtPdfColList) {
        for (DTPdfCol dtPdfCol : dtPdfColList) {
            String colName = dtPdfCol.getColName();
            
            if (colName.compareToIgnoreCase("client.name") == 0)
                dtPdfCol.setTestVal(dtPdfShowItem.getClientName());
            else if (colName.compareToIgnoreCase("client.addr") == 0)
                dtPdfCol.setTestVal(dtPdfShowItem.getClientAddr());
            //依實際資料做mapping
            ...
            } else {
                dtPdfCol.setTestVal("");
            }
        }
        return true;
    }
    
    /**
     * @param dtServiceEntry
     * @param dtPdfShowItem
     * @param dtPdfColList
     * @return
     */
    private boolean mappingColData_3(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem,
            List dtPdfColList) {
        DRServiceEntry drServiceEntry = new DRServiceEntry();
        
        for (DTPdfCol dtPdfCol : dtPdfColList) {
            String colName = dtPdfCol.getColName();
            
            if (colName.compareToIgnoreCase("trade.seqno") == 0) {  
                String value = dtPdfShowItem.getDtTrade().getProdSeqno();
                dtPdfCol.setTestVal((value == null) ? "尚未產出" : value);
            } else if (colName.compareToIgnoreCase("trade.targetId") == 0)
                dtPdfCol.setTestVal(dtPdfShowItem.getDtInqPrice().getTargetId());
            //依實際資料做mapping
            ...
            else {
                dtPdfCol.setTestVal("");
            }
        }
        return true;
    }
    
    /**
     * @param dtServiceEntry
     * @param dtPdfShowItem
     * @param dtPdfColList
     * @return
     */
    private boolean mappingColData_4(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem,
            List dtPdfColList) {
        for (DTPdfCol dtPdfCol : dtPdfColList) {
            String colName = dtPdfCol.getColName();
            
            if (colName.compareToIgnoreCase("trade.cateId") == 0)
                dtPdfCol.setTestVal(dtPdfShowItem.getMentionTypeDesc());
            //依實際資料做mapping
            ...
            else {
                dtPdfCol.setTestVal("");
            }
        }
        return true;
    }
    
    /**
     * @param dtServiceEntry
     * @param dtPdfShowItem
     * @param dtPdfColList
     * @return
     */
    private boolean mappingColData_5(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem,
            List dtPdfColList) {
        for (DTPdfCol dtPdfCol : dtPdfColList) {
            String colName = dtPdfCol.getColName();
            
            if (colName.compareToIgnoreCase("client.name") == 0)
                dtPdfCol.setTestVal(dtPdfShowItem.getClientName());
            //依實際資料做mapping
            ...
            } else {
                dtPdfCol.setTestVal("");
            }
        }
        return true;
    }
    
    /**
     * @param dtServiceEntry
     * @param dtPdfShowItem
     * @param dtPdfColList
     * @return
     */
    private boolean mappingColData_6(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem,
            List dtPdfColList) {
        for (DTPdfCol dtPdfCol : dtPdfColList) {
            String colName = dtPdfCol.getColName();
            
            if (colName.compareToIgnoreCase("client.name") == 0)
                dtPdfCol.setTestVal(dtPdfShowItem.getClientName());
            //依實際資料做mapping
            ...
            } else {
                dtPdfCol.setTestVal("");
            }
        }
        return true;
    }
    
    /**
     * @param dtServiceEntry
     * @param dtPdfShowItem
     * @param dtPdfColList
     * @return
     */
    private boolean mappingColData_7(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem,
            List dtPdfColList) {
        for (DTPdfCol dtPdfCol : dtPdfColList) {
            String colName = dtPdfCol.getColName();
            
            if (colName.compareToIgnoreCase("client.name") == 0)
                dtPdfCol.setTestVal(dtPdfShowItem.getClientName());
            //依實際資料做mapping
            ...
            } else {
                dtPdfCol.setTestVal("");
            }
        }
        return true;
    }
    
    /**
     * @param dtServiceEntry
     * @param dtPdfShowItem
     * @param dtPdfColList
     * @return
     */
    private boolean mappingColData_8(DTServiceEntry dtServiceEntry, DTPdfShowItem dtPdfShowItem,
            List dtPdfColList) {
        for (DTPdfCol dtPdfCol : dtPdfColList) {
            String colName = dtPdfCol.getColName();
            
            if (colName.compareToIgnoreCase("client.name") == 0)
                dtPdfCol.setTestVal(dtPdfShowItem.getClientName());
            //依實際資料做mapping
            ...
            } else {
                dtPdfCol.setTestVal("");
            }
        }
        return true;
    }
}
發表於 程式分享

javascript股票走勢圖繪圖及好用的Timeline介紹

一、股票走勢圖繪圖
之前為了網頁能繪製股票走勢圖購買了highstock的license (我是買綁domain的license),
今天找到用d3.js套件,
若只是顯示,不做互動是可以試用看看~http://arnauddri.github.io/d3-stock/

二、Timeline
1.Responsive Timeline
網址: https://codecanyon.net/item/first-responsive-timeline/19352502?ref=pxcr
費用: 美金12元
Demo: http://iscoalarcon.cidcode.net/timeline/
說明: 可以為網站或投資組合創建自己的時間表。是基於CSS3和jQuery,包括非常簡單的編輯界面,現代設計和各種過渡風格。 包括超過40多種動畫,10多種風格。 支援responsive,且支援所有HTML內容,如iframe,文本,圖像,視頻,音頻等。 適用於從PC、Mobile及Pad,且支援各式瀏覽器。 可使用任何獨立的動畫庫(包括圖例)在javascript中進行動畫。
1.PNG
1.PNG
1.PNG
1.PNG

2.vis.js
網址: http://visjs.org
費用: 基於MIT license
Demo: http://visjs.org/timeline_examples.html
說明: 一個動態的,基於瀏覽器的可視化庫。 旨在易於使用,處理大量的動態數據,由DataSet、Timeline、Network、Graph2d和Graph3d組成。
1.PNG

3.Timeglider.js
網址: http://timeglider.com/widget/
費用: 非商業免費,商業請參考-https://timeglider.com/widget/?p=license
Demo: https://timeglider.com/widget/kitchen_sink.html
說明: 適用於iOS和Android觸控設備; Windows Surface設備仍然存在問題。數據可使用JSON格式或來自頁面上現有的JavaScript資料。
1.PNG

發表於 程式分享

java取得package下的class及function清單,供前端網頁選取時使用

1.先設定3個class

1) JBMethodItem

import java.util.LinkedList;
import java.util.List;

public class JBClassItem {
    private String className;
    private String classLongName;
    private List methodList = new LinkedList();
    
    public JBClassItem(String className, String classLongName) {
        super();
        this.className = className;
        this.classLongName = classLongName;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
    
    public String getClassLongName() {
        return classLongName;
    }

    public void setClassLongName(String classLongName) {
        this.classLongName = classLongName;
    }

    public List getMethodList() {
        return methodList;
    }

    public void setMethodList(List methodList) {
        this.methodList = methodList;
    }
    
    public void addMethodList(JBMethodItem jbMethodItem) {
        this.methodList.add(jbMethodItem);
    }

    @Override
    public String toString() {
        String sBuffer = "JBClassItem [className=" + className + ", classLongName=" + classLongName + ", methodList=";
        for (JBMethodItem jbMethodItem : methodList)
            sBuffer += jbMethodItem;
        sBuffer += "]";
        return sBuffer;
    }
}

2) JBMethodItem

import java.util.Iterator;
import java.util.LinkedHashMap;

public class JBMethodItem {
    private String methodName;
    private LinkedHashMap<Integer, JBParamItem> params = new LinkedHashMap<Integer, JBParamItem>();
    
    public JBMethodItem(String methodName) {
        super();
        this.methodName = methodName;
    }
    
    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }
    
    public LinkedHashMap<Integer, JBParamItem> getParams() {
        return params;
    }

    public void setParams(LinkedHashMap<Integer, JBParamItem> params) {
        this.params = params;
    }

    public void addParams(Integer paramIdx, String paramType) {
        JBParamItem paramItem = params.get(paramIdx);
        if (paramItem == null) {
            paramItem = new JBParamItem(paramIdx);
        }
        paramItem.setParamType(paramType);
        
        params.put(paramIdx, paramItem);
    }
    
    @Override
    public String toString() {
        String sBuffer = "JBMethodItem [methodName=" + methodName + ", params=";
        Iterator it = params.keySet().iterator();
        while (it.hasNext()) {      
            Integer iKey = (Integer) it.next();     
            JBParamItem jbParamItem = (JBParamItem) params.get(iKey);
            sBuffer += "\n" + jbParamItem;
        }
        sBuffer += "]";
        return sBuffer;
    }
}

3) JBParamItem

public class JBParamItem {
    private int paramIdx;
    private String paramType;
    
    public JBParamItem(int paramIdx) {
        super();
        this.paramIdx = paramIdx;
    }

    public int getParamIdx() {
        return paramIdx;
    }
    
    public void setParamIdx(int paramIdx) {
        this.paramIdx = paramIdx;
    }
    
    public String getParamType() {
        return paramType;
    }
    
    public void setParamType(String paramType) {
        this.paramType = paramType;
    }

    @Override
    public String toString() {
        return "JBParamItem [paramIdx=" + paramIdx + ", paramType=" + paramType + "]";
    }
}

2.主要程式碼

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.*;
....
....
public class JBMainMonitorAction extends BaseAction {
    @Override
    public String execute() throws Exception {
        //取得package下class 清單
        List jbClassItemList = retriveClassItemList(logger);
        for (JBClassItem jbClassItem : jbClassItemList)
            logger.debug(jbClassItem);
        request.setAttribute("jbClassItemList", jbClassItemList);
        
        return super.execute();
    }

    /**
     * 取得package下class 清單
     * @throws IOException 
     * @throws ClassNotFoundException 
     */
    private static List retriveClassItemList(Logger logger) 
            throws ClassNotFoundException, IOException {
        List classItemList = new LinkedList();
        
        List classList = getClasses("com.tssco.util.job");
        for (Class classTmp : classList) {
            if (classTmp.getSuperclass().getSimpleName().compareToIgnoreCase("SuperMonTask") != 0)
                continue;

            JBClassItem jbClassItem = new JBClassItem(classTmp.getSimpleName(), classTmp.getName());            
            Method[] method = classTmp.getDeclaredMethods();
            for (int iIdx_m = 0; iIdx_m < method.length; iIdx_m++) {                 if (method[iIdx_m].getReturnType().toString().compareToIgnoreCase("boolean") != 0)                  continue;               List modNames = Arrays.asList(Modifier.toString(method[iIdx_m].getModifiers()).split("\\s"));               boolean bPublic = false;                int iElseCnt = 0;               for (String modifier : modNames) {                  if (modifier.compareToIgnoreCase("public") == 0)                        bPublic = true;                     else                        iElseCnt++;                 }               if (iElseCnt > 0 || bPublic == false)
                    continue;
                
                JBMethodItem jbMethodItem = new JBMethodItem(method[iIdx_m].getName());
                Class<?>[] paramList = method[iIdx_m].getParameterTypes();
                int paramIdx = 0;
                for (Class paramTmp : paramList) {
                    logger.info(paramTmp.getSimpleName());
                    jbMethodItem.addParams(++paramIdx, paramTmp.getSimpleName());
                }
                
                jbClassItem.addMethodList(jbMethodItem);
            }
            
            if (jbClassItem.getMethodList().size() > 0)
                classItemList.add(jbClassItem);
        }
        
        return classItemList;
    }
    
    private static List getClasses(String packageName) throws ClassNotFoundException, IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace('.', '/');
        Enumeration resources = classLoader.getResources(path);
        List dirs = new ArrayList();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        ArrayList classes = new ArrayList();
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName));
        }
        return classes;
    }
    
    private static List findClasses(File directory, String packageName) throws ClassNotFoundException {
        List classes = new ArrayList();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }
}

3.前端javascript可加上此段讓互動時可以選取

1

   //取得package下class 清單
    var classMap = new Object();
<%
    List jbClassItemList = (List) request.getAttribute("jbClassItemList");
    for (JBClassItem jbClassItem : jbClassItemList) {
        String className = jbClassItem.getClassName();
        String classLongName = jbClassItem.getClassLongName();
        String methodMapName = "methodMap_" + className;
        out.println("var " + methodMapName + " = new Object();");
        List methodList = jbClassItem.getMethodList();
        for (JBMethodItem jbMethodItem : methodList) {
            String methodName = jbMethodItem.getMethodName();
            LinkedHashMap<Integer, JBParamItem> params = jbMethodItem.getParams();
            String paramListName = "paramList_" + className + "_" + methodName;
            out.println("var " + paramListName + " = [];");
            
            List paramList = new ArrayList(params.values());
            for (JBParamItem JBParamItem : paramList) {
                String paramType = JBParamItem.getParamType();
                if (paramType.compareTo("int") == 0)
                    paramType = "Integer";
                out.println(paramListName + ".push({'paramIdx': " + JBParamItem.getParamIdx() + 
                        ",'paramType': '" + paramType + "'});");
            }
%>
            <%= methodMapName %>['<%= methodName %>'] = {'name' : '<%= methodName %>', 'paramList' : <%= paramListName %>};
<%       } %>
        classMap['<%= classLongName %>'] = {'name' : '<%= className %>', 'longName' : '<%= classLongName %>', 
                    'methodMap' : <%= methodMapName %>};
<%   } %>

4.前端javascript就可取其值做應用了。

發表於 工具

eclipse內import github專案

1.下載套件EGit

Eclipse => Eclipse Marketplace => git => EGit => Install

1.PNG

2.找到欲下載的github

Ex.https://github.com/line/line-bot-sdk-java

3

3.設定Import github專案之路徑

1) Eclipse => File => Import => Git => 選取"Projects from Git" => Click “Next" Button

2

2) 選"Clone URI" => “Next" Button

2-2.PNG

3) 輸入github路徑,Ex.https://github.com/line/line-bot-sdk-java.git

其它欄位均自動帶出 => Click “Next" Button

4.PNG

4.Import專案

1) 選取全部 => Click “Next" Button

5.PNG

2) Click “Next" Button

6.PNG

3) 選取"Import as general project" (請依專案狀況選取) => Click “Next" Button

7.PNG

4) Click “Next" Button

8.PNG

5) Import結果如下

9.PNG

發表於 工具

eclipse新增svn : 使用subclipse

在eclipse上使用install New Software及 Eclipse Marketplace因出現PKIX path building failed,

(subclipse install路徑 : https://dl.bintray.com/subclipse/releases/subclipse/latest/)

就想說用手動安裝subclipse,步驟如下 :

1.下載 subclipse plugin : 我是用4.2.2

https://dl.bintray.com/subclipse/releases/subclipse/subclipse-4.2.2.zip

2.解壓縮zip檔,分別將路徑下的plugins及features複製至eclipse相對應的路徑下

3.重新啟動eclipse

4.設定SVN Client

Eclipse => Window => Preferences => Team => SVN

=> 彈出一個大大的對話框,報一個Failed to load JavaHL Library.錯誤

=> 按OK Button

=> 於SVN介面: Client只看到"JavaHL (JNI) Not available",未看到SVNKit,故需要再安裝SVNKit

1) 下載plugin檔 : 我使用1.8.1版本 (https://svnkit.com/download.php)

2) 解壓縮zip檔,分別將路徑下的plugins及features複製至eclipse相對應的路徑下

3) 重新啟動eclipse

5.再次設定SVN Client

Eclipse => Window => Preferences => Team => SVN

=> 彈出一個大大的對話框,報一個Failed to load JavaHL Library.錯誤

=> 按確定 => SVN介面: Client選取"SVNKit (Pure Java)…"選項

=> 按OK Button

6.設定Perspective為 “瀏覽SVN檔案庫"

Eclipse => Window => Perspective => Open Perspective => Other

=> 選取 “瀏覽SVN檔案庫" => OK Button

7.設定SVN位置

於"SVN檔案庫" click 右鍵 => 新增 => 檔案庫位置

=> Url請輸入SVN位置,Ex.https://xxx.xx.xx.xx:8443/svn/grace_svn/

即可在Eclipse做SVN版本控管了。

 

呈現畫面如下,請參考!

發表於 程式分享

Hibernate 5.2 version -> org.hibernate.Query class and methods deprecate?

原本使用org.hibernate.Query於hibernate升級至5.2版出現The type Query<R> is deprecated,
許多method也出現deprecate訊息,
原本

import org.hibernate.Query;
...
Query query = session.createQuery(" FROM WABlog c Order By blogId desc");
query.setMaxResults(iMaxRecord);
query.setFirstResult(0);
List<WABlog> waBlogList = query.list();

需調整為

import javax.persistence.TypedQuery;
...
TypedQuery<WABlog> query = session.createQuery(" FROM WABlog c Order By blogId desc");
query.setMaxResults(iMaxRecord);
query.setFirstResult(0);
List<WABlog> waBlogList = query.getResultList();
發表於 程式分享

java restful Demo code with spring + hibernate

github : https://github.com/yahuihuang/java/tree/master/restfulTest

1.create table and stored procedure in mysql database
1) DB/1.cr_table.sql
2) DB/2.cr_SP.sql

2.maven command for pom.xml

3.change config
1) src/sysConfig.xml : modify pwd.deskey value , the value you can edit for your prefer
<entry key="pwd.deskey">XXXXXX</entry>

2) WebContent/WEB-INF/applicationContext_WA.xml
a.change mysql db connection
<property name="jdbcUrl" value="jdbc:mysql://XXX.XX.XX.XX:3306/XXXXXX?characterEncoding=utf-8&amp;autoReconnect=true" />
b.change mysql db user and password,
the password should be encrypt, you can edit WebContent/DesTest.jsp sIn variable,
and get output string , then put in password property.
<bean id="dataSourceProperties" class="info.codingfun.restful.util.PropertiesEncryptFactoryBean">
<property name="properties">
<props>
<prop key="user">XXXXXXX</prop>
<prop key="password">XXXXXXX</prop>
</props>
</property>
</bean>

4.insert some data in mysql table : WABlog

5.test
1) http://127.0.0.1:8080/restfulTest/services/blogservice/getpost/1
http://127.0.0.1:8080/restfulTest/services/blogservice/getpost/1.xml
@GET Request: None
Content-Type: application/x-www-form-urlencoded
accept: application/json

2) http://127.0.0.1:8080/restfulTest/services/blogservice/getallpost
http://127.0.0.1:8080/restfulTest/services/blogservice/getallpost.xml
@GET Request: None
Content-Type: application/x-www-form-urlencoded
accept: application/json

3) http://127.0.0.1:8080/restfulTest/services/blogservice/addpost
@POST Request:
<?xml version="1.0″ encoding="UTF-8″ standalone="yes"?>
<BlogPostType xmlns="http://codingfun.info/restful/xsd">
<title>title-1</title>
<slogan>slogan-1</slogan>
<description>description-1</description>
<status>1</status>
<modifyEmp>grace</modifyEmp>
</BlogPostType>
Content-Type: application/xml
accept: application/x-www-form-urlencoded

4) http://localhost:8080/restfulTest/services/blogservice/updatepost
@PUT Request:
{
“blogId": 1,
“title": “title-2″,
“slogan": “slogan-2″,
“description": “description-2″,
“status": 1,
“modifyTime": “2017-03-06T09:05:34.000+08:00″,
“modifyEmp": “grace"
}
Content-Type: application/json
accept: application/x-www-form-urlencoded

5) http://localhost:8080/restfulTest/services/blogservice/deletepost
@DELETE Request:
{
“blogId": 1
}
Content-Type: application/json
accept: application/x-www-form-urlencoded