import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 查找数据库(对应关系表)拿到最新的编码,
* 1.为null,则可以直接使用编码:【00】;
* 2.否则可以使用此工具类获取下一个编码,最大为【ZZ】;
*
* @return String nextSequence
* @throws Exception
*/
@Component
public class NextSequenceUtil {
/** 日志对象 */
private static final Logger logger = LoggerFactory.getLogger(NextSequenceUtil.class);
public static String defaultSequence = "00";
static String bwords[] = {"0", "1", "2", "3", "4", "5", "6", "7","8", "9",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R","S", "T", "U", "V", "W", "X", "Y", "Z"};
//获取当前编码的下一个编码
public static synchronized String getNextSequence(String sequence){
//如果为【ZZ】,最大的编码,则直接返回
if(isFalseSequence(sequence)||"ZZ".equals(sequence)){
logger.debug("入参"+sequence+"有误,直接返回");
return sequence;
}
String nextSequence = "";
try{
nextSequence = getSequence(sequence);
}catch(Exception e){
logger.error(e.getMessage());
throw new RuntimeException(e.getMessage());
}
if(sequence.equals(nextSequence)){
logger.error("获取编码重复:"+nextSequence);
throw new RuntimeException("获取编码重复");
}
logger.info("getNextSequence:"+nextSequence);
return nextSequence;
}
//判断sequence正确性
private static boolean isFalseSequence(String sequence){
boolean isFalse = false;
//为空或者不足2位长度
if(StringUtils.isBlank(sequence)||sequence.length()!=2){
isFalse = true;
}else{
//第一个字符
char firstChar = sequence.charAt(0);
int firstIndex = getIndex(firstChar);
//最后一个字符
char lastChar = sequence.charAt(1);
int lastIndex = getIndex(lastChar);
//数组库中找不对应的字符
if(firstIndex == -1 ||lastIndex == -1){
isFalse = true;
}
}
return isFalse;
}
//获取sequence
private static String getSequence(String sequence){
//第一个字符
char firstChar = sequence.charAt(0);
int firstIndex = getIndex(firstChar);
if(firstIndex == -1){
throw new RuntimeException("获取字符位置出错");
}
//最后一个字符
char lastChar = sequence.charAt(1);
int lastIndex = getIndex(lastChar);
if(lastIndex == -1){
throw new RuntimeException("获取字符位置出错");
}
//如果字符是最后一位(Z),则从0重新开始
if(lastIndex == bwords.length-1){
lastIndex = 0;
//如果第一个字符也是最后一位(Z),则报错
if(firstIndex == bwords.length-1){
throw new RuntimeException("获取编码出错");
}else{
firstIndex++;
}
//修改第一个字符并将最后一个字符置为数组的第一个字符
sequence = bwords[firstIndex]+bwords[lastIndex];
}else{
lastIndex++;
//第一个字符不变只修改最后一个字符
sequence = bwords[firstIndex]+bwords[lastIndex];
}
return sequence;
}
//获取字符位置
private static int getIndex(char word) {
String bword = String.valueOf(word);
for (int i = 0; i < bwords.length; i++) {
if (bwords[i].equals(bword)) {
return i;
}
}
return -1;
}
}
获取编码(00-ZZ)
最新推荐文章于 2021-11-18 14:40:51 发布