JAva認証ID番号

7236 ワード


import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 *      ,              ,             <br>
 *        :6     +8   +3    +1    
 * 
 * @author liuex
 * 
 */
public class IDCard {
    /**
     *         
     */
    private final String cardNumber;
    //          ,                
    private Boolean cacheValidateResult = null;
    //       ,               
    private Date cacheBirthDate = null;
 
    public boolean validate() {
        if (null == cacheValidateResult) {
            boolean result = true;
            //         
            result = result && (null != cardNumber);
            //        18(  )
            result = result && NEW_CARD_NUMBER_LENGTH == cardNumber.length();
            //       17         
            for (int i = 0; result && i < NEW_CARD_NUMBER_LENGTH - 1; i++) {
                char ch = cardNumber.charAt(i);
                result = result && ch >= '0' && ch <= '9';
            }
            //       18     
            result = result
                    && (calculateVerifyCode(cardNumber) == cardNumber
                            .charAt(NEW_CARD_NUMBER_LENGTH - 1));
            //             ,      1900 
            try {
                Date birthDate = this.getBirthDate();
                result = result && null != birthDate;
                result = result && birthDate.before(new Date());
                result = result && birthDate.after(MINIMAL_BIRTH_DATE);
                /**
                 *        、 、     ,       [1,12],     [1,31],       、  、      ,
                 *         
                 */
                String birthdayPart = this.getBirthDayPart();
                String realBirthdayPart = this.createBirthDateParser().format(
                        birthDate);
                result = result && (birthdayPart.equals(realBirthdayPart));
            } catch (Exception e) {
                result = false;
            }
            // TODO                 
            cacheValidateResult = Boolean.valueOf(result);
        }
        return cacheValidateResult;
    }
 
    /**
     *    15      ,      18 
     * 
     * @param cardNumber
     */
    public IDCard(String cardNumber) {
        if (null != cardNumber) {
            cardNumber = cardNumber.trim();
            if (OLD_CARD_NUMBER_LENGTH == cardNumber.length()) {
                cardNumber = contertToNewCardNumber(cardNumber);
            }
        }
        this.cardNumber = cardNumber;
    }
 
    public String getCardNumber() {
        return cardNumber;
    }
 
    public String getAddressCode() {
        this.checkIfValid();
        return this.cardNumber.substring(0, 6);
    }
 
    public Date getBirthDate() {
        if (null == this.cacheBirthDate) {
            try {
                this.cacheBirthDate = this.createBirthDateParser().parse(
                        this.getBirthDayPart());
            } catch (Exception e) {
                throw new RuntimeException("          ");
            }
        }
        return new Date(this.cacheBirthDate.getTime());
    }
 
    public boolean isMale() {
        return 1 == this.getGenderCode();
    }
 
    public boolean isFemal() {
        return false == this.isMale();
    }
 
    /**
     *        17 ,     ,     
     * 
     * @return
     */
    private int getGenderCode() {
        this.checkIfValid();
        char genderCode = this.cardNumber.charAt(NEW_CARD_NUMBER_LENGTH - 2);
        return (((int) (genderCode - '0')) & 0x1);
    }
 
    private String getBirthDayPart() {
        return this.cardNumber.substring(6, 14);
    }
 
    private SimpleDateFormat createBirthDateParser() {
        return new SimpleDateFormat(BIRTH_DATE_FORMAT);
    }
 
    private void checkIfValid() {
        if (false == this.validate()) {
            throw new RuntimeException("        !");
        }
    }
 
    //               
    private final static String BIRTH_DATE_FORMAT = "yyyyMMdd";
    //           ,1900 1 1 
    private final static Date MINIMAL_BIRTH_DATE = new Date(-2209017600000L);
    private final static int NEW_CARD_NUMBER_LENGTH = 18;
    private final static int OLD_CARD_NUMBER_LENGTH = 15;
    /**
     * 18            
     */
    private final static char[] VERIFY_CODE = { '1', '0', 'X', '9', '8', '7',
            '6', '5', '4', '3', '2' };
    /**
     * 18     ,              
     */
    private final static int[] VERIFY_CODE_WEIGHT = { 7, 9, 10, 5, 8, 4, 2, 1,
            6, 3, 7, 9, 10, 5, 8, 4, 2 };
 
    /**
     * <li>   (     ):<br/>
     * <ul>
     * <li>               S = Sum(Ai * Wi), i = 0...16 ,   17       ;
     * Ai:   i             Wi:   i         Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4
     * 2;</li>
     * <li>    Y = mod(S, 11)</li>
     * <li>            Y: 0 1 2 3 4 5 6 7 8 9 10    : 1 0 X 9 8 7 6 5 4 3 2</li>
     * </ul>
     * 
     * @param cardNumber
     * @return
     */
    private static char calculateVerifyCode(CharSequence cardNumber) {
        int sum = 0;
        for (int i = 0; i < NEW_CARD_NUMBER_LENGTH - 1; i++) {
            char ch = cardNumber.charAt(i);
            sum += ((int) (ch - '0')) * VERIFY_CODE_WEIGHT[i];
        }
        return VERIFY_CODE[sum % 11];
    }
 
    /**
     *  15         18      <br>
     * 15       18          :<br>
     * 1、15       ,"    "   2 ,       "19",  20  <br>
     * 2、15            。18     ,        17   
     * 
     * @param cardNumber
     * @return
     */
    private static String contertToNewCardNumber(String oldCardNumber) {
        StringBuilder buf = new StringBuilder(NEW_CARD_NUMBER_LENGTH);
        buf.append(oldCardNumber.substring(0, 6));
        buf.append("19");
        buf.append(oldCardNumber.substring(6));
        buf.append(IDCard.calculateVerifyCode(buf));
        return buf.toString();
    }
    public static void main(String[] args) {
    	System.out.println(new IDCard("123456789456985").validate());
	}
}