日期工具类
import org.apache.commons.lang3.time.DateFormatUtils;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class DateUtil extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
public static final String HH_MM_SS = "HH:mm:ss";
public static final String YYYYMMDD = "yyyyMMdd";
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static final String DATE_PATTERN_YYYYMMDD = "yyyy/MM/dd";
public static final String WEEK_FLAG = "EEEE";
private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
public static final String MONDAY = "星期一";
public static final String TUESDAY = "星期二";
public static final String WEDNESDAY = "星期三";
public static final String THURSDAY = "星期四";
public static final String FRIDAY = "星期五";
public static final String SATURDAY = "星期六";
public static final String SUNDAY = "星期日";
public static SimpleDateFormat getYyyyMmDdHhMmSs() {
return new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
}
public static SimpleDateFormat getDEFAULT_FORMATTER() {
return new SimpleDateFormat(YYYY_MM_DD);
}
public static String getDate(Date date, String dateFormat) {
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
return format.format(date);
}
public static Date getDate(String date, String fromFormat) {
try {
SimpleDateFormat fromSimpleDateFormat = new SimpleDateFormat(fromFormat);
return fromSimpleDateFormat.parse(date);
} catch (Exception e) {
e.getMessage();
}
return null;
}
public static Date getDate(String date) {
SimpleDateFormat sdf = getYyyyMmDdHhMmSs();
try {
return sdf.parse(date);
} catch (Exception e) {
e.getMessage();
}
return null;
}
public static Date startOfDay(Date date) throws ParseException {
return new SimpleDateFormat(YYYY_MM_DD).parse(new SimpleDateFormat(YYYY_MM_DD).format(date));
}
public static Date anotherDay(Date date, int i) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, i);
Date result = cal.getTime();
return result;
}
public static Date strToDate(String strDate) {
SimpleDateFormat formatter = getDEFAULT_FORMATTER();
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
public static String dateToStr(Date dateDate) {
if (dateDate == null) {
return null;
}
SimpleDateFormat formatter = getDEFAULT_FORMATTER();
return formatter.format(dateDate);
}
public static String dateTimeToStr(Date dateDate) {
SimpleDateFormat formatter = getYyyyMmDdHhMmSs();
return formatter.format(dateDate);
}
public static String dateTimeToStr() {
Date dateDate = new Date();
SimpleDateFormat formatter = getYyyyMmDdHhMmSs();
return formatter.format(dateDate);
}
public static final String getCurrentDateToString() {
Calendar calendar = Calendar.getInstance();
int i = calendar.get(1);
int j = calendar.get(2) + 1;
int k = calendar.get(5);
return String.valueOf(i + (j >= 10 ? "" + j : "0" + j) + (k >= 10 ? "" + k : "0" + k));
}
public static Date stepYear(Date sourceDate, int year) {
Calendar c = Calendar.getInstance();
c.setTime(sourceDate);
c.add(Calendar.YEAR, year);
return c.getTime();
}
public static Date stepMonth(Date sourceDate, int month) {
Calendar c = Calendar.getInstance();
c.setTime(sourceDate);
c.add(Calendar.MONTH, month);
return c.getTime();
}
public static String getCurrentDate() {
return DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss").substring(0, 10);
}
public static Date transferDate(Date date) {
if (date != null) {
return DateUtil.getDate(getCurrentDate() + " " + DateUtil.getDate(date, "yyyy-MM-dd HH:mm:ss").substring(11, 19));
}
return null;
}
public static Date transferDateTime(String date) {
if (date != null) {
return DateUtil.getDate(date + " " + DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss").substring(11, 19));
}
return null;
}
public static Date dateTimeToTimeEndZero(Date dateTime) {
String dateTimeString = DateUtil.getDate(dateTime, DateUtil.YYYY_MM_DD_HH_MM_SS);
return getDate(dateTimeString.substring(0, 10) + " 00:00:00");
}
public static Date dateTimeEndWidth(Date dateTime) {
String dateTimeString = DateUtil.getDate(dateTime, DateUtil.YYYY_MM_DD_HH_MM_SS);
return getDate(dateTimeString.substring(0, 10) + " 23:59:59");
}
public static Date dateTimeYearEndWidth(Date dateTime) {
String dateTimeString = DateUtil.getDate(dateTime, DateUtil.YYYY_MM_DD_HH_MM_SS);
return getDate(dateTimeString.substring(0, 4) + "-12-31 23:59:59");
}
public static Date getNowDate() {
return new Date();
}
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}
public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static final String datePath(String format) {
Date now = new Date();
return DateFormatUtils.format(now, format);
}
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
public static String getDatePoor(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long diff = endDate.getTime() - nowDate.getTime();
long day = diff / nd;
long hour = diff % nd / nh;
long min = diff % nd % nh / nm;
return day + "天" + hour + "小时" + min + "分钟";
}
public static int differentDaysByMillisecond(Date date1, Date date2) {
return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
}
public static int differentHourByMillisecond(Date date1, Date date2) {
return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600)));
}
public static int differentMinByMillisecond(Date date1, Date date2) {
return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 60)));
}
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
public static ArrayList<String> getLastDays(int intervals) {
ArrayList<String> pastDaysList = new ArrayList<>();
for (int i = intervals; i > 0; i--) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - i);
Date today = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
pastDaysList.add(format.format(today));
}
return pastDaysList;
}
}
字符串工具类
import com.st.microservice.plugin.text.StrFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils extends org.apache.commons.lang3.StringUtils {
private static final String NULLSTR = "";
private static final char SEPARATOR = '_';
public static <T> T nvl(T value, T defaultValue) {
return value != null ? value : defaultValue;
}
public static boolean isEmpty(Collection<?> coll) {
return isNull(coll) || coll.isEmpty();
}
public static boolean isNotEmpty(Collection<?> coll) {
return !isEmpty(coll);
}
public static boolean isEmpty(Object[] objects) {
return isNull(objects) || (objects.length == 0);
}
public static boolean isNotEmpty(Object[] objects) {
return !isEmpty(objects);
}
public static boolean isEmpty(Map<?, ?> map) {
return isNull(map) || map.isEmpty();
}
public static boolean isNotEmpty(Map<?, ?> map) {
return !isEmpty(map);
}
public static boolean isEmpty(String str) {
return isNull(str) || NULLSTR.equals(str.trim());
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
public static boolean isEmpty(Long l) {
return isNull(l);
}
public static boolean isNotEmpty(Long l) {
return !isEmpty(l);
}
public static boolean isNull(Object object) {
return null == object;
}
public static boolean isNotNull(Object object) {
return !isNull(object);
}
public static boolean isArray(Object object) {
return isNotNull(object) && object.getClass().isArray();
}
public static String trim(String str) {
return (str == null ? "" : str.trim());
}
public static String substring(final String str, int start) {
if (str == null) {
return NULLSTR;
}
if (start < 0) {
start = str.length() + start;
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return NULLSTR;
}
return str.substring(start);
}
public static String substring(final String str, int start, int end) {
if (str == null) {
return NULLSTR;
}
if (end < 0) {
end = str.length() + end;
}
if (start < 0) {
start = str.length() + start;
}
if (end > str.length()) {
end = str.length();
}
if (start > end) {
return NULLSTR;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
public static String format(String template, Object... params) {
if (isEmpty(params) || isEmpty(template)) {
return template;
}
return StrFormatter.format(template, params);
}
public static final Set<String> str2Set(String str, String sep) {
return new HashSet<String>(str2List(str, sep, true, false));
}
public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
List<String> list = new ArrayList<String>();
if (StringUtils.isEmpty(str)) {
return list;
}
if (filterBlank && StringUtils.isBlank(str)) {
return list;
}
String[] split = str.split(sep);
for (String string : split) {
if (filterBlank && StringUtils.isBlank(string)) {
continue;
}
if (trim) {
string = string.trim();
}
list.add(string);
}
return list;
}
public static String toUnderScoreCase(String str) {
if (str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean preCharIsUpperCase = true;
boolean curreCharIsUpperCase = true;
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i > 0) {
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
} else {
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1)) {
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
sb.append(SEPARATOR);
} else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
public static boolean inStringIgnoreCase(String str, String... strs) {
if (str != null && strs != null) {
for (String s : strs) {
if (str.equalsIgnoreCase(trim(s))) {
return true;
}
}
}
return false;
}
public static String convertToCamelCase(String name) {
StringBuilder result = new StringBuilder();
if (name == null || name.isEmpty()) {
return "";
} else if (!name.contains("_")) {
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
String[] camels = name.split("_");
for (String camel : camels) {
if (camel.isEmpty()) {
continue;
}
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
}
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
public static String toUnderscore(String str) {
if (str == null) {
return null;
}
Pattern compile = Pattern.compile("[A-Z]");
Matcher matcher = compile.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj) {
return (T) obj;
}
public static String toLow(String val) {
if (StringUtils.isNotNull(val)) {
return val.toLowerCase();
}
return val;
}
private List<String> getDistrictCode(String areaCode) {
String[] split = areaCode.split("_");
List<String> list = new ArrayList<>();
list.add(areaCode.substring(0, 2) + "0000");
list.add(areaCode.substring(0, 4) + "00");
list.add(areaCode);
return list;
}
}
文件工具类
public static List<File> getAllFile(File dirFile){
if(Objects.isNull(dirFile) || !dirFile.exists() || dirFile.isFile())
return null;
File[] childrenFiles = dirFile.listFiles();
if(Objects.isNull(childrenFiles) || childrenFiles.length == 0)
return null;
List<File> files = new ArrayList<>();
for(File childFile : childrenFiles) {
if(childFile.isFile()) {
files.add(childFile);
}else {
List<File> cFiles = getAllFile(childFile);
if(Objects.isNull(cFiles) || cFiles.isEmpty()) continue;
files.addAll(cFiles);
}
}
return files;
}
阿里云短信工具类
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dypnsapi20170525</artifactId>
<version>1.0.6</version>
</dependency>
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.st.microservice.plugin.aliyun.constant.SmsEnum;
import com.st.microservice.plugin.redis.RedisCache;
import com.st.microservice.plugin.uitl.AssertUtils;
import com.st.microservice.plugin.uitl.VerifyCodeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Component
public class SmsUtils {
private static final Logger logger = LoggerFactory.getLogger(SmsUtils.class);
@Resource
private RedisCache redisCache;
private static final String PRODUCT = "Dysmsapi";
private static final String DOMAIN = "dysmsapi.aliyuncs.com";
@Value("${aliyun.keyId:}")
private String accessKeyId;
@Value("${aliyun.keySecret:}")
private String accessKeySecret;
private static String signName = "XXXX";
private SendSmsResponse sendParam(String mobile, String param, String templateCode) throws ClientException {
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN);
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(mobile);
request.setSignName(signName);
request.setTemplateCode(templateCode);
request.setTemplateParam(param);
request.setOutId("");
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
return sendSmsResponse;
}
private boolean sendCode(String mobile, String code, String templateCode) {
try {
SendSmsResponse response = sendParam(mobile, "{\"code\":" + code + "}", templateCode);
return true;
} catch (Exception e) {
logger.error("发送短信异常", e);
}
return false;
}
public boolean sendJson(String mobile, String content, String templateCode) {
try {
SendSmsResponse response = sendParam(mobile, content, templateCode);
return true;
} catch (Exception e) {
logger.error("发送短信异常", e);
}
return false;
}
}
序列号生成工具类(redis)
import com.st.microservice.plugin.core.utils.DateUtil;
import com.st.microservice.plugin.core.utils.spring.SpringUtils;
import com.st.microservice.plugin.redis.RedisCache;
import com.st.microservice.plugin.uitl.StringUtils;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@Component
public class SerialNoUtil {
private static RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
public static String serialNoMinute(String bizCode) {
LocalDateTime now = LocalDateTime.now();
String date = DateUtil.getDate(new Date(), "yyMMdd");
String minute = now.getHour() * 3600 + now.getMinute() * 60 + "";
String redisKeyPrefix = bizCode + date + minute;
long increment = redisCache.incr(redisKeyPrefix, 1);
if (increment == 1) {
redisCache.expire(redisKeyPrefix, 60, TimeUnit.SECONDS);
}
return redisKeyPrefix + StringUtils.leftPad(String.valueOf(increment), 6, "0");
}
public static String serialNoDay(String bizCode) {
LocalDateTime now = LocalDateTime.now();
String date = DateUtil.getDate(new Date(), "yyMMdd");
String redisKeyPrefix = bizCode + date;
long increment = redisCache.incr(redisKeyPrefix, 1);
if (increment == 1) {
redisCache.expire(redisKeyPrefix, SerialNoUtil.getSecondNumber(), TimeUnit.SECONDS);
}
return redisKeyPrefix + StringUtils.leftPad(String.valueOf(increment), 6, "0");
}
private static int getSecondNumber() {
LocalTime midnight = LocalTime.MIDNIGHT;
LocalDate today = LocalDate.now();
LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);
LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1);
long seconds = TimeUnit.NANOSECONDS.toSeconds(Duration.between(LocalDateTime.now(), tomorrowMidnight).toNanos());
return (int) seconds;
}
}
身份证校验工具类
import lombok.extern.slf4j.Slf4j;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@Slf4j
public class IdCardUtil {
private static String[] cityCode = {"11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35",
"36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65",
"71", "81", "82", "91"};
private static int power[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
public static boolean isValidatedAllIdcard(String idcard) {
if (idcard == null || "".equals(idcard)) {
return false;
}
int s = 15;
if (idcard.length() == s) {
return validate15IdCard(idcard);
}
int s1 = 18;
if (idcard.length() == s1) {
return validate18IdCard(idcard);
}
return false;
}
public static boolean validate18IdCard(String idcard) {
if (idcard == null) {
return false;
}
int s = 18;
if (idcard.length() != s) {
log.error("身份证位数不正确!");
return false;
}
String idcard17 = idcard.substring(0, 17);
if (!isDigital(idcard17)) {
return false;
}
String provinceid = idcard.substring(0, 2);
if (!checkProvinceid(provinceid)) {
return false;
}
String birthday = idcard.substring(6, 14);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try {
Date birthDate = sdf.parse(birthday);
String tmpDate = sdf.format(birthDate);
if (!tmpDate.equals(birthday)) {
return false;
}
} catch (ParseException e1) {
return false;
}
String idcard18Code = idcard.substring(17, 18);
char c[] = idcard17.toCharArray();
int bit[] = convertCharToInt(c);
int sum17 = 0;
sum17 = getPowerSum(bit);
String checkCode = getCheckCodeBySum(sum17);
if (null == checkCode) {
return false;
}
if (!idcard18Code.equalsIgnoreCase(checkCode)) {
return false;
}
return true;
}
public static boolean validate15IdCard(String idcard) {
if (idcard == null) {
return false;
}
int s = 15;
if (idcard.length() != s) {
return false;
}
if (!isDigital(idcard)) {
return false;
}
String provinceid = idcard.substring(0, 2);
if (!checkProvinceid(provinceid)) {
return false;
}
String birthday = idcard.substring(6, 12);
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
try {
Date birthDate = sdf.parse(birthday);
String tmpDate = sdf.format(birthDate);
if (!tmpDate.equals(birthday)) {
return false;
}
} catch (ParseException e1) {
return false;
}
return true;
}
public static String convertIdcarBy15bit(String idcard) {
if (idcard == null) {
return null;
}
int s = 15;
if (idcard.length() != s) {
return null;
}
if (!isDigital(idcard)) {
return null;
}
String provinceid = idcard.substring(0, 2);
if (!checkProvinceid(provinceid)) {
return null;
}
String birthday = idcard.substring(6, 12);
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
Date birthdate = null;
try {
birthdate = sdf.parse(birthday);
String tmpDate = sdf.format(birthdate);
if (!tmpDate.equals(birthday)) {
return null;
}
} catch (ParseException e1) {
return null;
}
Calendar cday = Calendar.getInstance();
cday.setTime(birthdate);
String year = String.valueOf(cday.get(Calendar.YEAR));
String idcard17 = idcard.substring(0, 6) + year + idcard.substring(8);
char c[] = idcard17.toCharArray();
String checkCode = "";
int bit[] = convertCharToInt(c);
int sum17 = 0;
sum17 = getPowerSum(bit);
checkCode = getCheckCodeBySum(sum17);
if (null == checkCode) {
return null;
}
idcard17 += checkCode;
return idcard17;
}
private static boolean checkProvinceid(String provinceid) {
for (String id : cityCode) {
if (id.equals(provinceid)) {
return true;
}
}
return false;
}
private static boolean isDigital(String str) {
return str.matches("^[0-9]*$");
}
private static int getPowerSum(int[] bit) {
int sum = 0;
if (power.length != bit.length) {
return sum;
}
for (int i = 0; i < bit.length; i++) {
for (int j = 0; j < power.length; j++) {
if (i == j) {
sum = sum + bit[i] * power[j];
}
}
}
return sum;
}
private static String getCheckCodeBySum(int sum17) {
String checkCode = null;
switch (sum17 % 11) {
case 10:
checkCode = "2";
break;
case 9:
checkCode = "3";
break;
case 8:
checkCode = "4";
break;
case 7:
checkCode = "5";
break;
case 6:
checkCode = "6";
break;
case 5:
checkCode = "7";
break;
case 4:
checkCode = "8";
break;
case 3:
checkCode = "9";
break;
case 2:
checkCode = "x";
break;
case 1:
checkCode = "0";
break;
case 0:
checkCode = "1";
break;
default:
}
return checkCode;
}
private static int[] convertCharToInt(char[] c) throws NumberFormatException {
int[] a = new int[c.length];
int k = 0;
for (char temp : c) {
a[k++] = Integer.parseInt(String.valueOf(temp));
}
return a;
}
}
随机数工具类
import java.awt.*;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class RandomUtil {
public static final String BASE_NUMBER = "0123456789";
public static final String BASE_CHAR = "abcdefghijklmnopqrstuvwxyz";
public static final String BASE_CHAR_NUMBER = BASE_CHAR + BASE_NUMBER;
public static ThreadLocalRandom getRandom() {
return ThreadLocalRandom.current();
}
public static SecureRandom createSecureRandom(byte[] seed) {
return (null == seed) ? new SecureRandom() : new SecureRandom(seed);
}
public static SecureRandom getSecureRandom() {
try {
return SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
throw new Exception(e);
}
}
public static Random getRandom(boolean isSecure) {
return isSecure ? getSecureRandom() : getRandom();
}
public static boolean randomBoolean() {
return 0 == randomInt(2);
}
public static int randomInt(int min, int max) {
return getRandom().nextInt(min, max);
}
public static int randomInt() {
return getRandom().nextInt();
}
public static int randomInt(int limit) {
return getRandom().nextInt(limit);
}
public static long randomLong(long min, long max) {
return getRandom().nextLong(min, max);
}
public static long randomLong() {
return getRandom().nextLong();
}
public static long randomLong(long limit) {
return getRandom().nextLong(limit);
}
public static double randomDouble(double min, double max) {
return getRandom().nextDouble(min, max);
}
public static double randomDouble() {
return getRandom().nextDouble();
}
public static double randomDouble(double limit) {
return getRandom().nextDouble(limit);
}
public static byte[] randomBytes(int length) {
byte[] bytes = new byte[length];
getRandom().nextBytes(bytes);
return bytes;
}
public static <T> T randomEle(List<T> list) {
return randomEle(list, list.size());
}
public static <T> T randomEle(List<T> list, int limit) {
return list.get(randomInt(limit));
}
public static <T> T randomEle(T[] array) {
return randomEle(array, array.length);
}
public static <T> T randomEle(T[] array, int limit) {
return array[randomInt(limit)];
}
public static <T> List<T> randomEles(List<T> list, int count) {
final List<T> result = new ArrayList<>(count);
int limit = list.size();
while (result.size() < count) {
result.add(randomEle(list, limit));
}
return result;
}
public static String randomString(int length) {
return randomString(BASE_CHAR_NUMBER, length);
}
public static String randomStringUpper(int length) {
return randomString(BASE_CHAR_NUMBER, length).toUpperCase();
}
public static String randomNumbers(int length) {
return randomString(BASE_NUMBER, length);
}
public static String randomString(String baseString, int length) {
final StringBuilder sb = new StringBuilder(length);
if (length < 1) {
length = 1;
}
int baseLength = baseString.length();
for (int i = 0; i < length; i++) {
int number = randomInt(baseLength);
sb.append(baseString.charAt(number));
}
return sb.toString();
}
public static int randomNumber() {
return randomChar(BASE_NUMBER);
}
public static char randomChar() {
return randomChar(BASE_CHAR_NUMBER);
}
public static char randomChar(String baseString) {
return baseString.charAt(randomInt(baseString.length()));
}
public static Color randomColor() {
final Random random = getRandom();
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
}