001package org.kuali.ole.ingest.util;
002
003import org.apache.log4j.Logger;
004
005/**
006 * Created with IntelliJ IDEA.
007 * User: ?
008 * Date: 11/6/12
009 * Time: 3:38 PM
010 * To change this template use File | Settings | File Templates.
011 */
012public class ISSNUtil
013{
014    private String issn;
015    private static Logger logger = Logger.getLogger( ISSNUtil.class );
016
017
018    public ISSNUtil(String issn) throws Exception
019    {
020        this.issn = issn.replace( "-", "" ); // remove hyphens
021        if( this.issn == null || this.issn.length() != 8 )
022        {
023            logger.debug( "ISSN length=" + this.issn.length() );
024            throw new Exception( "Bad ISSN length:" + this.issn );
025        }
026    }
027
028
029    public ISSNUtil(int issn)
030    {}
031
032
033    public int getCheckSum()
034    {
035        int sum = 0;
036        int weight = 0;
037
038        for( int i = 0; i < 7; i++ )
039        {
040            switch( i ){
041                case 0:
042                    weight = 8;
043                    break;
044                case 1:
045                    weight = 7;
046                    break;
047                case 2:
048                    weight = 6;
049                    break;
050                case 3:
051                    weight = 5;
052                    break;
053                case 4:
054                    weight = 4;
055                    break;
056                case 5:
057                    weight = 3;
058                    break;
059                case 6:
060                    weight = 2;
061                    break;
062            }
063
064            char c = issn.charAt( i );
065            int n = Character.digit( c, 10 ); // convert character to digit
066            sum += ( n * weight );
067        }
068
069        int cSum = sum % 11;
070
071        return cSum == 0 ? cSum : 11 - cSum;
072    }
073
074
075    /**
076     * @return whether this ISBN has a correct checksum
077     */
078    public boolean hasCorrectChecksum()
079    {
080        char checksumChar;
081        int checksum = getCheckSum(); // get the calculated check sum digit
082
083        if( checksum == 10 )
084        {
085            checksumChar = 'X';
086        }
087        else
088        {
089            checksumChar = Character.forDigit( checksum, 10 ); // convert digit to character
090        }
091
092        char fileDigit = issn.charAt( 7 ); // check sum char
093
094        return checksumChar == fileDigit;
095    }
096
097}