com.pureinfo.srm.project.CodeGenerator.java Source code

Java tutorial

Introduction

Here is the source code for com.pureinfo.srm.project.CodeGenerator.java

Source

/**
 * PureInfo Command
 * @(#)CodeGenerator.java   1.0 2006-11-3
 * 
 * Copyright(c) 2004-2005, PureInfo Information Technology Corp. Ltd. 
 * All rights reserved, see the license file.
 * 
 * www.pureinfo.com.cn
 */

package com.pureinfo.srm.project;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.pureinfo.ark.content.ArkContentHelper;
import com.pureinfo.ark.content.domain.IContentMgr;
import com.pureinfo.dolphin.DolphinHelper;
import com.pureinfo.dolphin.model.DolphinObject;
import com.pureinfo.dolphin.model.IObjects;
import com.pureinfo.dolphin.persister.IStatement;
import com.pureinfo.force.exception.PureException;
import com.pureinfo.srm.outlay.domain.IIDTableMgr;
import com.pureinfo.srm.outlay.model.IDTable;

/**
 * <P>
 * Created on 2006-11-3 14:56:03 <BR>
 * Last modified on 2006-11-3
 * </P>
 * TODO describe CodeGenerator here ...
 * 
 * @author elmar.chen
 * @version 1.0, 2006-11-3
 * @since Command 1.0
 */
public abstract class CodeGenerator implements ICodeGnerator {

    private static Logger logger = Logger.getLogger(CodeGenerator.class);

    protected static final String PLACE_HOLDER = "\000\000";

    protected abstract String[] getTokens(Object[] _params) throws PureException;

    protected abstract String getPattern();

    protected abstract String getIndentifier();

    protected abstract int getSerialWidth();

    protected abstract int getMaxSerial();

    /**
     * @throws PureException
     * @see com.pureinfo.srm.project.ICodeGnerator#getNextCode()
     */
    public CodeInfo getNextCode(Object[] _params) throws PureException {

        CodeInfo ci = new CodeInfo();
        String[] tokens = getTokens(_params);
        String sPattern = getPattern();

        int nSerialNumber = getSerialNumber(_params);
        int round = nSerialNumber / getMaxSerial();

        boolean isCross = (nSerialNumber % getMaxSerial()) == 1 && nSerialNumber != 1;

        String sCode = makeUpCode(tokens, sPattern, nSerialNumber);

        CarageInof carageInof = getCarageInof();
        String sCodeAny = makeUpCode(tokens, sPattern, PLACE_HOLDER);
        if (carageInof != null) {
            if (isDup(sCode, carageInof)) {
                int nCurrSerial = pickUpSerialFromCode(sCode, sCodeAny);

                nSerialNumber = findNextToken(nCurrSerial, sCodeAny, carageInof);
                if (nSerialNumber < nCurrSerial) {
                    round += 1;
                    isCross = true;
                    nSerialNumber += round * getMaxSerial();
                }
                logger.debug("code " + sCode + " is dup, find new " + nSerialNumber + "for it");
                if (getKeyTokenIdxes().length == tokens.length) {
                    setIdTable(_params, nSerialNumber);
                }
                sCode = makeUpCode(tokens, sPattern, nSerialNumber);
                ci.findAfterDup = true;
            }
        }

        ci.round = round;
        ci.value = sCode;
        ci.cross_boundary = isCross;
        return ci;
    }

    /**
     * @param _sCodeAny2
     * @param _carageInof
     * @param _sCarageInof
     * @throws PureException
     */
    private int findNextToken(int _nCurrSerial, String _sCodeAny, CarageInof _carageInof) throws PureException {
        IContentMgr mgr = ArkContentHelper.getContentMgrOf(_carageInof.clazz);
        String sDigital = "";
        for (int i = 0; i < getSerialWidth(); i++) {
            sDigital += "[0-9]";
        }
        String sCodeReg = _sCodeAny.replaceAll(PLACE_HOLDER, sDigital);
        String sStrSQL = "select {this." + _carageInof.property + "} as CODE from {this} where {this."
                + _carageInof.property + "} regexp '" + sCodeReg + "' order by {this." + _carageInof.property + "}";
        IObjects codes = null;
        IStatement stat = null;
        try {
            stat = mgr.createQuery(sStrSQL, 0);
            codes = stat.executeQuery();
            DolphinObject code = null;
            int lastSerial = 0;
            int smallerSerial = -1;
            int lastBigSerial = _nCurrSerial;
            while ((code = codes.next()) != null) {
                String sCode = code.getStrProperty("CODE");
                logger.debug(sCode);
                int currSerial = pickUpSerialFromCode(sCode, _sCodeAny);
                int nSerial = currSerial;
                if (nSerial > lastBigSerial) {
                    if (nSerial - lastBigSerial > 1)
                        return lastBigSerial + 1;
                    lastBigSerial = nSerial;
                }
                if (smallerSerial > 0)
                    continue;
                if (nSerial - lastSerial > 1) {
                    smallerSerial = lastSerial + 1;
                }
            }
            return smallerSerial;
        } finally {
            DolphinHelper.clear(codes, stat);
        }
    }

    /**
     * @param _sCode
     * @return
     */
    private int pickUpSerialFromCode(String _sCode, String _sCodeAny) {

        int idx = _sCodeAny.indexOf(PLACE_HOLDER.charAt(0));
        String sSerial = _sCode.substring(idx, idx + getSerialWidth());
        return Integer.parseInt(sSerial);
    }

    private String makeUpCode(String[] tokens, String sPattern, int nSerialNumber) throws PureException {
        String sSerialNum = formatSerial(nSerialNumber);
        return makeUpCode(tokens, sPattern, sSerialNum);
    }

    private String makeUpCode(String[] tokens, String sPattern, String sSerialNum) {
        StringBuffer sbuff = new StringBuffer();
        boolean isLastCharDollar = false;
        for (int i = 0; i < sPattern.length(); i++) {
            char ch = sPattern.charAt(i);
            if (isLastCharDollar) {
                if (ch == 'Y') {
                    char cDnum = sPattern.charAt(i + 1);
                    int nDigital = 4;
                    if (cDnum >= '0' && cDnum <= '9') {
                        nDigital = cDnum - '0';
                        i++;
                    }
                    sbuff.append(getYear(nDigital));
                } else if (ch == 'S') {

                    sbuff.append(sSerialNum);
                } else if (ch >= '0' && ch <= '9') {
                    sbuff.append(tokens[ch - '0']);
                } else {
                    sbuff.append(ch);
                }
                isLastCharDollar = false;
            } else {
                if (ch == '$') {
                    isLastCharDollar = true;
                } else {
                    sbuff.append(ch);
                    isLastCharDollar = false;
                }
            }
        }

        String str = sbuff.toString();
        sbuff.setLength(0);
        return str;
    }

    /**
     * @param _sCode
     * @param _carageInof
     * @return
     * @throws PureException
     *  
     */
    private boolean isDup(String _sCode, CarageInof _carageInof) throws PureException {
        final String sStrSQL = "select {this." + _carageInof.property + "} from {this} where {this."
                + _carageInof.property + "}=?";

        IContentMgr mgr = ArkContentHelper.getContentMgrOf(_carageInof.clazz);
        IStatement stat = null;
        try {
            stat = mgr.createQuery(sStrSQL, 1);
            stat.setString(0, _sCode);
            return stat.executeStat() != null;
        } finally {
            if (stat != null)
                stat.clear(true);
        }
    }

    private String formatSerial(int num) throws PureException {
        num = num % getMaxSerial();
        if (num == 0)
            num = getMaxSerial();
        return StringUtils.leftPad("" + num, getSerialWidth(), '0');
    }

    /**
     * @throws PureException
     * @see com.pureinfo.srm.project.ICodeGnerator#advance()
     */
    public void advance(Object[] _params) throws PureException {
        setIdTable(_params, -1);
    }

    protected void setIdTable(Object[] _params, int nValue) throws PureException {
        IIDTableMgr mgr = (IIDTableMgr) ArkContentHelper.getContentMgrOf(IDTable.class);
        IDTable table = getIDTableItem(makeIDTableName(_params));
        if (nValue < 0)
            nValue = table.getIdValue() + 1;
        table.setIdValue(nValue);
        mgr.save(table);
    }

    private int getSerialNumber(Object[] _params) throws PureException {
        String sName = makeIDTableName(_params);
        IDTable table = getIDTableItem(sName);
        return table.getIdValue() + 1;
    }

    private String makeIDTableName(Object[] _sParams) throws PureException {
        return "#" + getIndentifier() + "#" + StringUtils.join(getKeyTokens(_sParams), '#');
    }

    private IDTable getIDTableItem(String _sName) throws PureException {
        IIDTableMgr mgr = (IIDTableMgr) ArkContentHelper.getContentMgrOf(IDTable.class);
        IDTable item = mgr.lookupByIdName(_sName, 0);
        return item;
    }

    protected String[] getKeyTokens(Object[] _sParams) throws PureException {
        int[] arrKeyTokenIdxes = getKeyTokenIdxes();
        String[] sTokens = getTokens(_sParams);

        if (arrKeyTokenIdxes == null) {
            return sTokens;
        }
        String[] keyTokens = new String[arrKeyTokenIdxes.length];
        for (int i = 0; i < keyTokens.length; i++) {
            keyTokens[i] = sTokens[arrKeyTokenIdxes[i]];
        }
        return keyTokens;
    }

    protected int[] getKeyTokenIdxes() {
        return null;
    }

    public static String getYear(int _nDigitals) {
        if (_nDigitals > 4 || _nDigitals < 0) {
            _nDigitals = 4;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        String sYear = "" + cal.get(Calendar.YEAR);
        return sYear.substring(4 - _nDigitals);
    }

    protected CarageInof getCarageInof() {
        return null;
    }

    protected static class CarageInof {
        Class clazz;

        String property;

        public CarageInof(Class _clazz, String _sProperty) {
            clazz = _clazz;
            property = _sProperty;
        }
    }
}