Total Pageviews

2013/12/05

How to pad a string with spaces when size of data is unknown in Microsoft SQL Server

Requirement
When I select a character data with varchar(6) from Microsoft SQL Server....

And these data should have fixed length in report.
If the data is 01, it should right pad with 4 spaces.
If the data is 01234, it should right pad with 1 space.

Solution
If we would like to meet this requirement in SQL Server, we can use 'CAST' function which provided by SQL Server
select cast(repno as char(6)) from NSS313FA  

Utilizing cast function in SQL statement, you can get fixed length in report no matter how long the data is.
   


2013/12/04

How to display column footer immediately without any spaces after details band

Problem
This is my report design in iReport:

Here is the Detail property and Column Footer property setting:

But...as I generate pdf, there has unnecessary spaces between Detail band and Column Footer band.

Solution
Step1. Right click --> property

Step2. Check the "Float column footer" property

Then this problem will be solved. There will not have any spaces between Detail band and Column Footer band.








2013/11/29

Why I can't print dashed lines?

Problem
This is my setting in iReport. The line had been set as dashed line.

And you can see the dashed line in chrome pdf viewer


But as I print this pdf file, I cannot see the dashed line!



Root Cause
It may result from some problem in Chrome PDF Viewer.

Solution
Go to chrome://plugins/
 Disable Chrome PDF Viewer and Enable Adboe Reader

Then click the print button.

See...the dashed line had shown in my paper





Why can't I save PDF in Chrome?

Problem
My chrome version is up-to-date.

But why I can't save PDF after viewing it within Chrome, the save button does not work.


Root Cause
It may result from some problem in Chrome PDF Viewer.

Solution
Go to chrome://plugins/
 Disable Chrome PDF Viewer and Enable Adboe Reader

Then the save button is working now!



2013/11/27

How to convert the amount from Arabic numerals to Chinese number (如何將阿拉伯數字金額轉大寫國字)

Requirement
In our payment slip, we need to convert the amount from Arabic numerals to Chinese number. ex. 325250 will be converted to 參拾貳萬伍仟貳佰伍拾.


Solution
Here has a utility method to do conversion.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
   /**  
    * Convert to Chinese amount  
    *   
    * @param amount  
    *      the amount  
    * @return the string  
    */  
   public static String convertToChineseAmt(Long amount) {  
     String num[] = { "零", "壹", "貳", "參", "肆", "伍", "陸", "柒", "捌", "玖" };  
      String xx[] = { "拾", "佰", "仟" };  
      String yy[] = { "萬", "億", "兆", "京" };  
      String chineseAmt = "";  
      int i;  
      int temp;  
      boolean first = true;  
      boolean zero = false;  
      for (i = 0; (int) (amount / (long) Math.pow(10, i)) != 0; i++) {  
        ;// 計算位數i  
      }  
      if (i == 0) {  
        return num[0];  
      }  
      for (int k = (i - 1) / 4; k >= 0; k--) {  
        temp = (int) ((amount / (long) Math.pow(10, 4 * k)) % (int) Math.pow(10, 4));  
        if (temp == 0) {  
          zero = true;  
          continue;  
        }  
        for (int x = 3; x >= 0; x--) {  
          if (first) {  
            x = (i - 1) % 4;  
            first = false;  
          }  
          if (temp / (int) Math.pow(10, x) % 10 == 0) {  
            zero = true;  
          } else {  
            if (zero) {  
              chineseAmt += num[0];  
              zero = false;  
            }  
            chineseAmt += num[temp / (int) Math.pow(10, x) % 10];  
            if (x > 0) {  
              chineseAmt += xx[x - 1];  
            }  
          }  
        }  
        if (k > 0) {  
          chineseAmt = chineseAmt + yy[k - 1];  
        }  
      }  
      return chineseAmt;  
    }  

Test
We inputted three amount into this method to do conversion
1
2
3
4
5
    public static void main(String args[]) {  
      System.out.println(ReportUtils.convertToChineseAmt(2500L));  
      System.out.println(ReportUtils.convertToChineseAmt(50100L));  
      System.out.println(ReportUtils.convertToChineseAmt(325250L));  
    }  



The result is as bellows:
1
2
3
  貳仟伍佰  
  伍萬零壹佰  
  參拾貳萬伍仟貳佰伍拾  

2013/11/26

How to clear an array in AngularJS?

Question
If we have an array in AngularJS, how do I clear its content?

Answer
If we have an array, ex.
 $scope.itemarray = ['A', 'B', 'C'];  

If we would like to clear its content in specific situation, what we need to do is as bellowing:
 $scope.itemarray.length = 0;  

2013/11/25

How to do collection filter in Java

Requirement
Assume I have a collection of Cta612pDto, and this collection contains:
1:  [Cta612pDto [acc=0100, amt=13033356, seqnm=(*)年度預算支出, ypay=null, formattedAmt=null],   
2:  Cta612pDto [acc=0101, amt=3809733, seqnm=  一般政務支出                                , ypay=null, formattedAmt=null],   
3:  Cta612pDto [acc=0102, amt=3894280, seqnm=  國防支出                                  , ypay=null, formattedAmt=null],   
4:  Cta612pDto [acc=0103, amt=2532563, seqnm=  教育科學文化支出                              , ypay=null, formattedAmt=null],   
5:  Cta612pDto [acc=0104, amt=1655232, seqnm=  經濟發展支出                                , ypay=null, formattedAmt=null],   
6:  Cta612pDto [acc=0105, amt=460708, seqnm=  社會福利支出                                , ypay=null, formattedAmt=null],   
7:  Cta612pDto [acc=0106, amt=59111, seqnm=  社區發展及環境保護支出                           , ypay=null, formattedAmt=null],   
8:  Cta612pDto [acc=0107, amt=366285, seqnm=  退休撫卹支出                                , ypay=null, formattedAmt=null],   
9:  Cta612pDto [acc=0109, amt=255444, seqnm=  一般補助及其他支出                             , ypay=null, formattedAmt=null],   
10:  Cta612pDto [acc=0200, amt=130015, seqnm=(*)以前年度支出                                 , ypay=null, formattedAmt=null],   
11:  Cta612pDto [acc=0400, amt=14271298, seqnm=(*)特種基金及保管款支出                             , ypay=null, formattedAmt=null],   
12:  Cta612pDto [acc=0500, amt=0, seqnm=(*)國庫券及短期借款還本支出, ypay=null, formattedAmt=null],   
13:  Cta612pDto [acc=8888, amt=1539861, seqnm=null, ypay=null, formattedAmt=null],   
14:  Cta612pDto [acc=9800, amt=757028109, seqnm=合計, ypay=null, formattedAmt=null],   
15:  Cta612pDto [acc=9900, amt=849981138506, seqnm=累計, ypay=null, formattedAmt=null],   
16:  Cta612pDto [acc=9991, amt=1539861, seqnm=  支付註銷, ypay=null, formattedAmt=null],   
17:  Cta612pDto [acc=9992, amt=728053579, seqnm=  支出收回, ypay=null, formattedAmt=null],   
18:  Cta612pDto [acc=9999, amt=728053579, seqnm=null, ypay=null, formattedAmt=null]]  

We need to remove some java beans from this collection when acc is 8888 or 9999.

Solution
We can make good use of PredicateUtils.nonePredicate to define our conditions which provide by Apache commons Collection. It will create a new Predicate that returns true if none of the specified predicates are true. If the array of predicates is empty, then this predicate returns true. 
And also use CollectionUtils.filter to filter the collection by applying a Predicate to each element.
1:      BeanPropertyValueEqualsPredicate acc8888Predicate = new BeanPropertyValueEqualsPredicate(  
2:          "acc", "8888");  
3:      BeanPropertyValueEqualsPredicate acc9999Predicate = new BeanPropertyValueEqualsPredicate(  
4:          "acc", "9999");  
5:      Predicate predicate = PredicateUtils.nonePredicate(new Predicate[] { acc8888Predicate,  
6:          acc9999Predicate });  
7:      CollectionUtils.filter(dataList, predicate);  

After doing CollectionUtils.filter, you can find out two java beans had been removed from data list collection.
1:  [Cta612pDto [acc=0100, amt=13033356, seqnm=(*)年度預算支出, ypay=null, formattedAmt=13,033,356.00],   
2:  Cta612pDto [acc=0101, amt=3809733, seqnm=  一般政務支出                                , ypay=null, formattedAmt=3,809,733.00   ],   
3:  Cta612pDto [acc=0102, amt=3894280, seqnm=  國防支出                                  , ypay=null, formattedAmt=3,894,280.00   ],   
4:  Cta612pDto [acc=0103, amt=2532563, seqnm=  教育科學文化支出                              , ypay=null, formattedAmt=2,532,563.00   ],   
5:  Cta612pDto [acc=0104, amt=1655232, seqnm=  經濟發展支出                                , ypay=null, formattedAmt=1,655,232.00   ],   
6:  Cta612pDto [acc=0105, amt=460708, seqnm=  社會福利支出                                , ypay=null, formattedAmt=460,708.00   ],   
7:  Cta612pDto [acc=0106, amt=59111, seqnm=  社區發展及環境保護支出                           , ypay=null, formattedAmt=59,111.00   ],   
8:  Cta612pDto [acc=0107, amt=366285, seqnm=  退休撫卹支出                                , ypay=null, formattedAmt=366,285.00   ],   
9:  Cta612pDto [acc=0109, amt=255444, seqnm=  一般補助及其他支出                             , ypay=null, formattedAmt=255,444.00   ],   
10:  Cta612pDto [acc=0200, amt=130015, seqnm=(*)以前年度支出                                 , ypay=null, formattedAmt=130,015.00],   
11:  Cta612pDto [acc=0400, amt=14271298, seqnm=(*)特種基金及保管款支出                             , ypay=null, formattedAmt=14,271,298.00],   
12:  Cta612pDto [acc=0500, amt=0, seqnm=(*)國庫券及短期借款還本支出, ypay=null, formattedAmt=0.00],   
13:  Cta612pDto [acc=9800, amt=757028109, seqnm=合計, ypay=null, formattedAmt=757,028,109.00],   
14:  Cta612pDto [acc=9900, amt=849981138506, seqnm=累計, ypay=null, formattedAmt=849,981,138,506.00],   
15:  Cta612pDto [acc=9991, amt=1539861, seqnm=  支付註銷, ypay=null, formattedAmt=1,539,861.00   ],   
16:  Cta612pDto [acc=9992, amt=728053579, seqnm=  支出收回, ypay=null, formattedAmt=728,053,579.00   ]]  

2013/11/22

Why iReport eat my spaces

Requirement
We had a report requirement as bellows:
You can see some items' amount need to do indent. Others don't.

Problem
Here we add 7 single-byte spaces for some items' amount to do indent based on specific conditions.
1:   DecimalFormat df = new DecimalFormat();  
2:      df.setMaximumFractionDigits(2);  
3:      df.setMinimumFractionDigits(2);  
4:      for (Cta612pDto vo : dataList) {  
5:        if (StringUtils.startsWith(vo.getSeqnm(), "(*)") || "9800".equals(vo.getAcc())  
6:            || "9900".equals(vo.getAcc())) {  
7:          vo.setFormattedAmt(df.format(vo.getAmt()));  
8:        } else {  
9:          vo.setFormattedAmt(df.format(vo.getAmt()) + "       ");  
10:        }  
11:        formattedList.add(vo);  
12:      }  

But it does not work:

Root cause
 The iReport seem trim your spaces automatically. Therefore, it does not work for this circumstance.

Solution
We need to use double-byte spaces(全形空白) instead of single-byte spaces(半形空白).
1:   DecimalFormat df = new DecimalFormat();  
2:      df.setMaximumFractionDigits(2);  
3:      df.setMinimumFractionDigits(2);  
4:      for (Cta612pDto vo : dataList) {  
5:        if (StringUtils.startsWith(vo.getSeqnm(), "(*)") || "9800".equals(vo.getAcc())  
6:            || "9900".equals(vo.getAcc())) {  
7:          vo.setFormattedAmt(df.format(vo.getAmt()));  
8:        } else {  
9:          vo.setFormattedAmt(df.format(vo.getAmt()) + "   ");  
10:        }  
11:        formattedList.add(vo);  
12:      }  


2013/11/18

AngularJS - How to remove unnecessary blank option in dynamic drop down list

Based on AngularJS - How to create dynamic drop down list this post, you had learned how to create a dynamic drop down list via AnguarJS.

Problem
But we found out a problem, AngularJS will create an empty option in the dynamic drop down list and will place at first location. It's not my expected result.

Solution
You can set a default value to your dynamic drop down list, then you can fix your problem. Here is code snippet:
1:      //query  
2:      $scope.query = function(){  
3:        var result = nss702rService.query('rest/', $scope.model);  
4:        result.then(function(response){  
5:         $scope.dpNos = response;  
6:         //if have more than one record in dpNos,  
7:         //then set the first option as its default value  
8:         if($scope.dpNos.length > 0){  
9:           $scope.model.dpNo = $scope.dpNos[0].uid;  
10:         }  
11:       });  
12:      };  

Check the result. You won't find the empty option in the dynamic drop down list


AngularJS - How to create dynamic drop down list

Requirement
The "區局代號" drop down list in this page should generate dynamically from database

The sql statement is as bellows:
1:  select UID, NAME   
2:  from UAA001V1   
3:  where ORGCD = 'cht12345' and UID <> '957500';  

And expected to retrieve two records

How to do it
[Step1] Create an value object class to store the result.
1:  /**  
2:   *   
3:   */  
4:  package gov.nta.nss.dto;  
5:  import java.io.Serializable;  
6:  // TODO: Auto-generated Javadoc  
7:  /**  
8:   * The Class UAA001V1Bean.  
9:   */  
10:  public class UAA001V1Bean implements Serializable {  
11:    private static final long serialVersionUID = -7541446851729769394L;  
12:    // 機關代號  
13:    private String uid;  
14:    // 機關名稱  
15:    private String name;  
16:    /**  
17:     * Gets the uid.  
18:     *   
19:     * @return the uid  
20:     */  
21:    public String getUid() {  
22:      return uid;  
23:    }  
24:    /**  
25:     * Sets the uid.  
26:     *   
27:     * @param uid  
28:     *      the uid to set  
29:     */  
30:    public void setUid(String uid) {  
31:      this.uid = uid;  
32:    }  
33:    /**  
34:     * Gets the name.  
35:     *   
36:     * @return the name  
37:     */  
38:    public String getName() {  
39:      return name;  
40:    }  
41:    /**  
42:     * Sets the name.  
43:     *   
44:     * @param name  
45:     *      the name to set  
46:     */  
47:    public void setName(String name) {  
48:      this.name = name;  
49:    }  
50:    /**  
51:     * {@inheritDoc}  
52:     */  
53:    @Override  
54:    public String toString() {  
55:      return "UAA001V1Bean [uid=" + uid + ", name=" + name + "]";  
56:    }  
57:  }  

[Step2] Create a controller class, and do query to return a List of UAA001V1Bean
1:  /**  
2:   *   
3:   */  
4:  package gov.nta.nss.web.rest;  
5:  import gov.nta.nss.Messages;  
6:  import gov.nta.nss.dto.UAA001V1Bean;  
7:  import gov.nta.nss.service.Nss702rService;  
8:  import gov.nta.nss.web.dto.Nss702r;  
9:  import java.util.List;  
10:  import org.apache.commons.collections.CollectionUtils;  
11:  import org.slf4j.Logger;  
12:  import org.slf4j.LoggerFactory;  
13:  import org.springframework.beans.factory.annotation.Autowired;  
14:  import org.springframework.http.MediaType;  
15:  import org.springframework.stereotype.Controller;  
16:  import org.springframework.web.bind.annotation.RequestBody;  
17:  import org.springframework.web.bind.annotation.RequestMapping;  
18:  import org.springframework.web.bind.annotation.RequestMethod;  
19:  import org.springframework.web.bind.annotation.ResponseBody;  
20:  import com.cht.commons.web.Alerter;  
21:  /**  
22:   *   
23:   */  
24:  @Controller  
25:  @RequestMapping("NSS702R/rest/")  
26:  public class Nss702rResouce {  
27:    private final static Logger LOG = LoggerFactory.getLogger(Nss702rResouce.class);  
28:    @Autowired  
29:    private Nss702rService nss702rService;  
30:    /**  
31:     * Gets the uaa001v1 beans.  
32:     *   
33:     * @return the uaa001v1 beans  
34:     */  
35:    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)  
36:    public @ResponseBody  
37:    List<UAA001V1Bean> getUaa001v1Beans(@RequestBody Nss702r nss702r, Alerter alerter) {  
38:      // find all 區局代號 list  
39:      List<UAA001V1Bean> uaa001v1Beans = nss702rService.getUaa001v1Beans();  
40:      LOG.info("uaa001v1Beans=" + uaa001v1Beans.toString());  
41:      // if List of UAA001V1Bean is empty, return "找不到區局代號"  
42:      if (CollectionUtils.isEmpty(uaa001v1Beans)) {  
43:        alerter.info(Messages.nss702r_dpno_not_exist());  
44:      }  
45:      return uaa001v1Beans;  
46:    }  
47:  }  

[Step3] js file (only includes code snippet)
1:       //......................  
2:      //query  
3:      $scope.query = function(){  
4:        var result = nss702rService.query('rest/', $scope.model);  
5:        result.then(function(response){  
6:         $scope.dpNos = response;   
7:       });  
8:      };  
9:      $scope.refresh = function(){  
10:        $scope.query();  
11:      };  
12:      $scope.refresh();  
13:            //......................  

[Step4] html file  (only includes code snippet)
1:           <div class="form-group col-sm-5">  
2:            <label class="control-label">區局代號 :</label>  
3:            <select class="form-control" style="width: 80%;"  
4:                id="dpNo" name="dpNo" data-ng-model="model.dpNo"  
5:                data-ng-options="dpNo.uid as dpNo.name for dpNo in dpNos">  
6:            </select>  
7:           </div>  

Check the result

2013/11/15

How to adjust column width to fit the contents in Apache POI

Problem
I utilized Apache POI to write data into excel file. But I found out each cell width has the same default width, it does not adjust it's width based on its contents.

Solution
You can call autoSizeColumn method in HSSFSheet to fix this problem.
Here is the JavaDoc: http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html#autoSizeColumn(int, boolean)
If you have 10 columns, you need to call autoSizeColumn 10 times in for-loop.
For example.
1:          for (int resizeCnt = 0; resizeCnt < pdateSet.size() + 3; resizeCnt++) {  
2:            sheet.autoSizeColumn(resizeCnt);  
3:          }  
Check the result after we call autoSizeColumn. 
You can see some columns' width may not really fit the contents, but it's much better than the original one.

Apache Commons Application - Predicate Chain

Requirement
If you have a collection of value object, and would like to do search just like SQL.
And you may have more complex requirement, ex. two or more search criteria.
You may can try Apache Commons CollectionUtils and BeanUtils.

Example
Prepare a bean class whose named person with 3 attributes (name, birthPlace and department)
1:  /**  
2:   *   
3:   */  
4:  package test.collection;  
5:  import java.io.Serializable;  
6:  // TODO: Auto-generated Javadoc  
7:  /**  
8:   * The Class Person.  
9:   *   
10:   * @author albert  
11:   */  
12:  public class Person implements Serializable {  
13:       /** The Constant serialVersionUID. */  
14:       private static final long serialVersionUID = -4637096033730683016L;  
15:       /** The name. */  
16:       private String name;  
17:       /** The birth place. */  
18:       private String birthPlace;  
19:       /** The department. */  
20:       private String department;  
21:       /**  
22:        * Instantiates a new person.  
23:        */  
24:       public Person() {  
25:            super();  
26:            // TODO Auto-generated constructor stub  
27:       }  
28:       /**  
29:        * Instantiates a new person.  
30:        *   
31:        * @param name  
32:        *      the name  
33:        * @param birthPlace  
34:        *      the birth place  
35:        * @param department  
36:        *      the department  
37:        */  
38:       public Person(String name, String birthPlace, String department) {  
39:            super();  
40:            this.name = name;  
41:            this.birthPlace = birthPlace;  
42:            this.department = department;  
43:       }  
44:       /**  
45:        * Gets the name.  
46:        *   
47:        * @return the name  
48:        */  
49:       public String getName() {  
50:            return name;  
51:       }  
52:       /**  
53:        * Sets the name.  
54:        *   
55:        * @param name  
56:        *      the new name  
57:        */  
58:       public void setName(String name) {  
59:            this.name = name;  
60:       }  
61:       /**  
62:        * Gets the birth place.  
63:        *   
64:        * @return the birth place  
65:        */  
66:       public String getBirthPlace() {  
67:            return birthPlace;  
68:       }  
69:       /**  
70:        * Sets the birth place.  
71:        *   
72:        * @param birthPlace  
73:        *      the new birth place  
74:        */  
75:       public void setBirthPlace(String birthPlace) {  
76:            this.birthPlace = birthPlace;  
77:       }  
78:       /**  
79:        * Gets the department.  
80:        *   
81:        * @return the department  
82:        */  
83:       public String getDepartment() {  
84:            return department;  
85:       }  
86:       /**  
87:        * Sets the department.  
88:        *   
89:        * @param department  
90:        *      the new department  
91:        */  
92:       public void setDepartment(String department) {  
93:            this.department = department;  
94:       }  
95:       /*  
96:        * (non-Javadoc)  
97:        *   
98:        * @see java.lang.Object#toString()  
99:        */  
100:       @Override  
101:       public String toString() {  
102:            return "Person [birthPlace=" + birthPlace + ", department="  
103:                      + department + ", name=" + name + "]";  
104:       }  
105:  }  

Here is our CollectionTest class to demonstrate how to do filter in collection via Apache Commons CollectionUtils and BeanUtils.
The entry point is main method.

  • Step1. Call setUpData to create test data (List of Person).
  • Step2. Call filterDataWithTwoCriteria and pass search criteria (find out the person who birthPlace is 'ChiaYi' and work at 'DEPT1' department)
1:  package test.collection;  
2:  import java.util.ArrayList;  
3:  import java.util.List;  
4:  import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;  
5:  import org.apache.commons.collections.CollectionUtils;  
6:  import org.apache.commons.collections.Predicate;  
7:  import org.apache.commons.collections.PredicateUtils;  
8:  // TODO: Auto-generated Javadoc  
9:  /**  
10:   * The Class CollectionTest.  
11:   */  
12:  public class CollectionTest {  
13:       /** The person list. */  
14:       List<Person> personList = new ArrayList<Person>();  
15:       /**  
16:        * Sets up data.  
17:        */  
18:       void setUpData() {  
19:            personList.add(new Person("Albert", "ChiaYi", "DEPT1"));  
20:            personList.add(new Person("Mandy", "Taipei", "DEPT2"));  
21:            personList.add(new Person("Alex", "ChiaYi", "DEPT1"));  
22:            personList.add(new Person("Chris", "Taipei", "DEPT1"));  
23:       }  
24:       /**  
25:        * Filter data with two criteria.  
26:        *   
27:        * @param birthPlace  
28:        *      the birth place  
29:        * @param department  
30:        *      the department  
31:        */  
32:       @SuppressWarnings("unchecked")  
33:       void filterDataWithTwoCriteria(String birthPlace, String department) {  
34:            // set up birth place predicate  
35:            BeanPropertyValueEqualsPredicate birthPlacePredicate = new BeanPropertyValueEqualsPredicate(  
36:                      "birthPlace", birthPlace);  
37:            // set up department predicate  
38:            BeanPropertyValueEqualsPredicate departmentPredicate = new BeanPropertyValueEqualsPredicate(  
39:                      "department", department);  
40:            // Create a new Predicate that returns true only if all of the specified  
41:            // predicates are true (i.e. birthPlace='ChiaYi' and department='DEPT1')  
42:            Predicate predicates = PredicateUtils.allPredicate(new Predicate[] {  
43:                      birthPlacePredicate, departmentPredicate });  
44:            // Selects all elements from input collection which match the given  
45:            // predicate into an output collection.  
46:            List<Person> persons = (List<Person>) CollectionUtils.select(  
47:                      personList, predicates);  
48:            // print the output collection  
49:            if (CollectionUtils.isNotEmpty(persons)) {  
50:                 for (Person person : persons) {  
51:                      System.out.println(person.toString());  
52:                 }  
53:            }  
54:       }  
55:       /**  
56:        * The main method.  
57:        *   
58:        * @param args  
59:        *      the arguments  
60:        */  
61:       public static void main(String[] args) {  
62:            CollectionTest test = new CollectionTest();  
63:            // Sets up data  
64:            test.setUpData();  
65:            // find the person who birth place is ChiaYi and work at DEPT1  
66:            // department  
67:            test.filterDataWithTwoCriteria("ChiaYi", "DEPT1");  
68:       }  
69:  }  

After executing this standalone Java application, the console will print the person whose birth place is 'ChiaYi' and work at 'DEPT1' department
1:  Person [birthPlace=ChiaYi, department=DEPT1, name=Albert]  
2:  Person [birthPlace=ChiaYi, department=DEPT1, name=Alex]  

2013/11/14

How to set currecny cell to right-justified horizontal alignment and apply 1000 separator in Apache POI

Problem
We utilized Apache POI to write excel, but some currency cells do not right-justified horizontal alignment and do not apply 1000 separator.

Solution
1:          //create CellStyle, and define style information  
2:          CellStyle cs = workbook.createCellStyle();  
3:          cs.setBorderBottom((short) 1);  
4:          cs.setBorderTop((short) 1);  
5:          cs.setBorderLeft((short) 1);  
6:          cs.setBorderRight((short) 1);  
7:          cs.setAlignment(CellStyle.ALIGN_RIGHT);//right-justified horizontal alignment  
8:          cs.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));//apply 1000 separator  
9:          .....  
10:          .....  
11:          //set cs, the CellStyle with style information which we defined, into cell  
12:          cell.setCellStyle(cs);  


For more DataFormat information, you can check it:

Check the result

Here you can find more useful information: http://javacrazyer.iteye.com/blog/894850

2013/11/12

POI 常用API筆記

參考資料來源:http://become.wei-ting.net/2011/11/poiexcel.html

1:  File tempFile = new File(filePath,filename);//建立儲存檔案  
2:  Workbook workbook = new HSSFWorkbook();//建立Excel物件  
3:  String safeName = WorkbookUtil.createSafeSheetName(SHEETNAME);   
4:  Sheet sheet = workbook.createSheet(safeName);//建立工作表  
5:  Row row1 = sheet.createRow((short)0);//建立工作列  
6:  //字型設定  
7:  Font font = workbook.createFont();  
8:  font.setColor(HSSFColor.WHITE.index);//顏色  
9:  font.setBoldweight(Font.BOLDWEIGHT_BOLD); //粗體  
10:  //設定儲存格格式  
11:  CellStyle styleRow1 = workbook.createCellStyle();  
12:  styleRow1.setFillForegroundColor(HSSFColor.GREEN.index);//填滿顏色  
13:  styleRow1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
14:  styleRow1.setFont(font);//設定字體  
15:  styleRow1.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平置中  
16:  styleRow1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直置中  
17:  //設定框線  
18:  styleRow1.setBorderBottom((short)1);  
19:  styleRow1.setBorderTop((short)1);  
20:  styleRow1.setBorderLeft((short)1);  
21:  styleRow1.setBorderRight((short)1);  
22:  styleRow1.setWrapText(true);//自動換行  
23:  Cell cell = row1.createCell(0);//建立儲存格  
24:  cell.setCellStyle(styleRow1);//套用格式  
25:  cell.setCellValue(CELLTEXT);//設定內容  
26:  sheet.autoSizeColumn(0);//自動調整欄位寬度  
27:  //儲存檔案  
28:  FileOutputStream fileOut = new FileOutputStream(tempFile);  
29:  workbook.write(fileOut);  
30:  fileOut.close();  

How do I do redirect in AngularJS

Question
I would like to do window.location (JavaScript way) to redirect page.
How do I do in AngularJS?

Answer
You can use $window.location.href=[your link]

Example
According to the system analysis specification, system should redirect to specific page based on the option which chose by user.


1:  <div class="form-group col-sm-5">  
2:            <label class="control-label">選擇查詢報表 :</label>  
3:            <select class="form-control" data-ng-change="update()"  
4:                id="reportName" name="reportName"   
5:                data-ng-model="model.reportName" >  
6:              <option value="" >請選擇</option>  
7:              <option value="ETS401R">收支狀況日報表 (總表)</option>  
8:              <option value="ETS402R">收支狀況日報表 (支出明細表)</option>  
9:              <option value="ETS403R">收支狀況日報表 (支入明細表)</option>  
10:              <option value="ETS407R">年度國庫現金餘額表</option>  
11:            </select>  
12:           </div>  

We can define $window.location.href in js file.
1:  $scope.update = function(){  
2:        var reportName = $scope.model.reportName;  
3:        $window.location.href = '/nss/'+reportName+'/';  
4:      };  

How to fix com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException

Exception
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "reportName" (class gov.nta.ets.web.dto.Ets405rFormBean), not marked as ignorable (4 known properties: , "accYy", "type", "data", "funcId"])
 at [Source: java.io.ByteArrayInputStream@57a9b75a; line: 4, column: 18] (through reference chain: gov.nta.ets.web.dto.Ets405rFormBean["reportName"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79) [jackson-databind-2.2.3.jar:]

Root Cause
This exception means that there are get and set methods of an object in your class and Jackson is unable to figure out during serialization and deserialization process.

Solution
Apply @JsonIgnore on getter method, i.e. getReportName
1:   /**  
2:     * Gets the report name.  
3:     *   
4:     * @return the reportName  
5:     */  
6:    @JsonIgnore  
7:    public String getReportName() {  
8:      return reportName;  
9:    }  

2013/10/17

Windows 無法自動偵測此網路的proxy設定


今天在公司,突然電腦無法上網,出現 "Windows 無法自動偵測此網路的proxy設定 (Windows could not automatically detect this network's proxy settings)"此錯誤訊息
檢查了網路孔沒問題、ip相關設定沒問題,也重開機了,還是無法上網

最後 Google 到兩個指令,依照以下四步驟就可以解決了(只是還是不知道原因是什麼):

  1. 打開命令提示字元 (open command line)
  2. 執行 netsh winsock reset (execute netsh winsock reset)
  3. 執行 netsh int ipv4 reset (execute netsh int ipv4 reset)
  4. 重開機 (reboot)


Reference:http://answers.microsoft.com/en-us/windows/forum/windows_7-networking/windows-could-not-automatically-detect-this/d243dea1-d1c8-4c4a-ba96-2b49bc9bab1a

2013/09/24

How to Change User in TortoiseSVN

Question
When I authenticate with a Subversion server, the username and password are cached locally so I don't have to keep entering them each time. But I would like to clear username and password data for some reasons, how do I do?

Answer
1. Right Click --> Settings

2. Choose "Saved Data", then click "Clear" button which besides Authentication data. It clear all authentication data, then you can enter another username and password.