Commit b005cd9b authored by yanxia54's avatar yanxia54

Merge branch 'master' of http://git.tbd.yanzuoguang.com/yzg/yzg-util into xy

parents 3ed486f4 5bd236fc
......@@ -2,8 +2,7 @@ package com.yanzuoguang.util.cache;
import com.yanzuoguang.util.helper.StringHelper;
import java.util.Date;
import java.util.Map;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
......@@ -216,6 +215,19 @@ public class MemoryCache<T> {
MemoryCacheCenter.CLEAR_LIST.remove(this);
}
/**
* 获取所有的关键字
*
* @return
*/
public synchronized Collection<T> getValues() {
List<T> list = new ArrayList<>();
for(MemoryCacheItem<T> item:cache.values()){
list.add(item.getData());
}
return list;
}
/**
* 获取所有的关键字
*
......
......@@ -29,8 +29,8 @@ public class HttpCodeException extends RuntimeCodeException {
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
* throw new HttpCodeException("01","该订单已过期",order);
* throw new HttpCodeException("02","该订单未到使用时间",order);
*
* @param message  错误消息
* @param target  错误数据源,如订单数据
......@@ -41,8 +41,8 @@ public class HttpCodeException extends RuntimeCodeException {
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
* throw new HttpCodeException("01","该订单已过期",order);
* throw new HttpCodeException("02","该订单未到使用时间",order);
*
* @param message  错误消息
* @param target  错误数据源,如订单数据
......@@ -57,8 +57,8 @@ public class HttpCodeException extends RuntimeCodeException {
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
* throw new HttpCodeException("01","该订单已过期",order);
* throw new HttpCodeException("02","该订单未到使用时间",order);
*
* @param code  错误码
* @param message  错误消息
......@@ -70,8 +70,8 @@ public class HttpCodeException extends RuntimeCodeException {
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
* throw new HttpCodeException("01","该订单已过期",order);
* throw new HttpCodeException("02","该订单未到使用时间",order);
*
* @param code  错误码
* @param message  错误消息
......
......@@ -56,8 +56,8 @@ public class RuntimeCodeException extends RuntimeException {
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
* throw new RuntimeCodeException("01","该订单已过期",order);
* throw new RuntimeCodeException("02","该订单未到使用时间",order);
*
* @param message  错误消息
* @param target  错误数据源,如订单数据
......@@ -69,8 +69,8 @@ public class RuntimeCodeException extends RuntimeException {
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
* throw new RuntimeCodeException("01","该订单已过期",order);
* throw new RuntimeCodeException("02","该订单未到使用时间",order);
*
* @param message  错误消息
* @param target  错误数据源,如订单数据
......@@ -86,8 +86,8 @@ public class RuntimeCodeException extends RuntimeException {
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
* throw new RuntimeCodeException("01","该订单已过期",order);
* throw new RuntimeCodeException("02","该订单未到使用时间",order);
*
* @param code  错误码
* @param message  错误消息
......@@ -101,8 +101,8 @@ public class RuntimeCodeException extends RuntimeException {
/**
* 构造函数
* throw new CodeException("01","该订单已过期",order);
* throw new CodeException("02","该订单未到使用时间",order);
* throw new RuntimeCodeException("01","该订单已过期",order);
* throw new RuntimeCodeException("02","该订单未到使用时间",order);
*
* @param code  错误码
* @param message  错误消息
......
......@@ -61,7 +61,7 @@ public class AreaHelper {
String city = fromAreaId.substring(3);
String ret = city.substring(0, length - 3);
String retSimple = getSimple(ret);
String retSimple = getSimple(ret, false);
if (StringHelper.compare(ret, retSimple)) {
return getFull(country + retSimple);
}
......@@ -75,11 +75,21 @@ public class AreaHelper {
* @return
*/
public static String getSimple(String fromAreaId) {
return getSimple(fromAreaId, true);
}
/**
* 获取简写Id
*
* @param fromAreaId
* @return
*/
public static String getSimple(String fromAreaId, boolean isFull) {
if (StringHelper.isEmpty(fromAreaId) || fromAreaId.length() <= 3) {
return fromAreaId;
}
String to = StringHelper.trimEnd(fromAreaId, "00");
if (to.length() < COUNTRY_LENGTH) {
if (to.length() < COUNTRY_LENGTH && isFull) {
to = getFull(to).substring(0, COUNTRY_LENGTH);
}
return to;
......@@ -116,7 +126,7 @@ public class AreaHelper {
if (StringHelper.isEmpty(fromAreaId)) {
return fromAreaId;
}
String simpleId = getSimple(fromAreaId);
String simpleId = getSimple(fromAreaId, true);
String parentSimpleId = StringHelper.EMPTY;
if (simpleId.length() > COUNTRY_LENGTH) {
parentSimpleId = simpleId.substring(0, simpleId.length() - 2);
......
......@@ -20,6 +20,7 @@ public class DateHelper {
public static final String FORMAT_YEAR_END_STRING = "yyyy-12-31";
public static final String FORMAT_MONTH_STRING = "yyyy-MM-01";
public static final String FORMAT_DAY_STRING = "yyyy-MM-dd";
public static final String FORMAT_TIME_STRING = "HH:mm:ss";
public static final String FORMAT_DAY_HOUR_STRING = "yyyy-MM-dd HH:00:00";
public static final String FORMAT_SECOND_STRING = "yyyy-MM-dd HH:mm:ss";
......@@ -757,6 +758,18 @@ public class DateHelper {
return to;
}
/**
* 获取时间为指定格式的字符串,为null则返回空字符串
*
* @param format 格式 yyyy-MM-dd HH:mm:ss
* @param date 字符串
* @return 转换后的结果
*/
public static String getDateTimeString(String format, String date) {
Date dt = getDateTime(date);
return getDateTimeString(format, dt);
}
/**
* 比较时间
*
......
package com.yanzuoguang.util.helper;
import com.yanzuoguang.util.contants.SystemContants;
import com.yanzuoguang.util.exception.CodeException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.SecureRandom;
/**
* DES加密
*
* @author 颜佐光
*/
public class DesHelper {
private static final String ALGORITHM_DES = "des";
/**
* DES加密
*
* @param key 秘钥key
* @param content 待加密内容
* @return byte[]
*/
public static String DESEncrypt(final String key, final String content) {
try {
byte[] from = content.getBytes(SystemContants.UTF8);
byte[] to = processCipher(from, getSecretKey(key), Cipher.ENCRYPT_MODE, ALGORITHM_DES);
return RsaHelper.encodeBase64(to);
} catch (UnsupportedEncodingException ex) {
throw new CodeException("加密失败:" + ex.getMessage(), ex);
}
}
/**
* DES解密
*
* @param key 秘钥key
* @param encoderContent 已加密内容
* @return byte[]
*/
public static String DESDecrypt(final String key, final String encoderContent) {
try {
byte[] from = RsaHelper.decodeBase64(encoderContent);
byte[] to = processCipher(from, getSecretKey(key), Cipher.DECRYPT_MODE, ALGORITHM_DES);
return new String(to, SystemContants.UTF8);
} catch (UnsupportedEncodingException ex) {
throw new CodeException("解密失败:" + ex.getMessage(), ex);
}
}
/**
* 根据key生成秘钥
*
* @param key 给定key,要求key至少长度为8个字符
* @return SecretKey
*/
public static SecretKey getSecretKey(final String key) {
try {
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory instance = SecretKeyFactory.getInstance(ALGORITHM_DES);
SecretKey secretKey = instance.generateSecret(desKeySpec);
return secretKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 加密/解密处理
*
* @param processData 待处理的数据
* @param key 提供的密钥
* @param opsMode 工作模式
* @param algorithm 使用的算法
* @return byte[]
*/
private static byte[] processCipher(final byte[] processData, final Key key,
final int opsMode, final String algorithm) {
try {
SecureRandom secureRandom = new SecureRandom();
Cipher cipher = Cipher.getInstance(algorithm);
//初始化
cipher.init(opsMode, key, secureRandom);
return cipher.doFinal(processData);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
......@@ -18,11 +18,11 @@ public class FormulaHelper {
private static final String REGEX_DOUBLE = "^[-+]?[0-9]*\\.?[0-9]+$";
private static final String REGEX_QUOT = "(^.*?)\\((.+?)\\)(.*?$)";
private static final String REGEX_CALC_ADD_PLUS = "(^.*?)([+\\-])(.*?$)";
private static final String REGEX_CALC_MULTIPLY_MOD = "(^.*?)([*/])(.*?$)";
private static final String REGEX_CALC_ADD_PLUS = "(^.*)([+\\-])(.*?$)";
private static final String REGEX_CALC_MULTIPLY_MOD = "(^.*)([*/])(.*?$)";
private static final String REGEX_CALC_TAG = "[+\\-*/()]+";
private static final String EMPTY_CHAR = " ";
public static String TEMP_VAR_NAME = "@temp";
private static final String TEMP_VAR_NAME = "@temp";
private static FormulaHelper calcInstance = new FormulaHelper();
......@@ -49,7 +49,7 @@ public class FormulaHelper {
public static final int getExcelIndex(String columnName) {
columnName = columnName.toLowerCase();
if (!columnName.matches("^[a-z]+$")) {
throw YzgError.getRuntimeException("013",columnName);
throw YzgError.getRuntimeException("013", columnName);
}
// 从名称转换列序号
int formulaColumnIndex = 0;
......@@ -195,7 +195,7 @@ public class FormulaHelper {
} else {
ret = StringHelper.toDouble(varValues.get(formula));
}
System.out.println("公式: " + formula + " 值" + ret);
// System.out.println("公式: " + formula + " 值" + ret);
return ret;
}
......
......@@ -250,6 +250,9 @@ public class HttpHelper {
* @throws IOException
*/
private static BufferedReader readStream(InputStream stream, StringBuilder result, String charset) throws IOException {
if (stream == null) {
return null;
}
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
BufferedReader in = new BufferedReader(new InputStreamReader(stream, charset));
String line;
......
......@@ -296,7 +296,7 @@ public final class RsaHelper {
* @return
* @throws Exception
*/
private static String encodeBase64(byte[] source) {
public static String encodeBase64(byte[] source) {
try {
byte[] to = Base64Utils.encode(source);
return new String(to, SystemContants.UTF8);
......@@ -312,7 +312,7 @@ public final class RsaHelper {
* @return
* @throws Exception
*/
private static byte[] decodeBase64(String target) {
public static byte[] decodeBase64(String target) {
try {
byte[] from = target.getBytes(SystemContants.UTF8);
return Base64Utils.decode(from);
......
......@@ -8,6 +8,7 @@ public class TestAreaHelper {
public void test() {
System.out.println(AreaHelper.getSimple("100000000"));
System.out.println(AreaHelper.getFull("100"));
System.out.println(AreaHelper.getAreaId("100000000"));
String from = "100500103";
// from = 1999;
......
package helper;
import com.yanzuoguang.util.helper.DesHelper;
import org.junit.Test;
public class TestDes {
String pwd = "tubida@yanzuoguang@good@boy@!@#^%$";
// String str = "{\"c\":\"64711099423332\",\"l\":1631524416,\"s\":\"671ec2998053b6de9b76bc8d09e00f1b\",\"t\":\"company-pangding-0000001\"}";
String str = "64711099423332,1631524416,company-pangding-0000001,671ec2";
@Test
public void test() {
System.out.println(str.length());
String des = DesHelper.DESEncrypt(pwd, str);
System.out.println(des.length());
System.out.println(des);
}
}
......@@ -24,6 +24,25 @@ public class TestFormulaHelper {
}));
}
@Test
public void testMul() {
System.out.println(FormulaHelper.calc("(100-0)-2"));
System.out.println(FormulaHelper.calc("100-0-2"));
System.out.println(FormulaHelper.calc("100*2/3+2*5"));
System.out.println(FormulaHelper.calc("8+3*4"));
System.out.println(FormulaHelper.calc("(8+4)*3"));
System.out.println(FormulaHelper.calc(" 8-6/3"));
System.out.println(FormulaHelper.calc("(8-5)/3"));
System.out.println(FormulaHelper.calc("(1-2)*(3-4)"));
System.out.println(FormulaHelper.calc("1+(2+3)/(1+4)"));
System.out.println(FormulaHelper.calc("1+(2-5)/(2+4)"));
// System.out.println(FormulaHelper.calc(""));
}
@Test
public void test1() {
......
......@@ -297,6 +297,10 @@ public class DaoConst {
* 根据字段添加统计
*/
public static final int FIELD_ADD_GROUP = 8;
/**
* 根据字段替换统计
*/
public static final int FIELD_REPLACE_GROUP = 9;
/**
* SQL语句类型-普通语句
......
......@@ -60,7 +60,7 @@ public interface SqlCond<T extends SqlCond> {
*
* @return
*/
SqlCond copy();
T copy();
/**
* 判断条件是否相等
......
......@@ -88,7 +88,7 @@ public class SqlCondDefault extends SqlCondBase<SqlCondDefault> {
* @return
*/
@Override
public SqlCond copy() {
public SqlCondDefault copy() {
SqlCondDefault cond = new SqlCondDefault(this.debugRunnable, this.fields);
return cond;
}
......
......@@ -114,7 +114,7 @@ public class SqlCondEquals extends SqlCondBase<SqlCondEquals> {
* @return
*/
@Override
public SqlCond copy() {
public SqlCondEquals copy() {
SqlCondEquals cond = new SqlCondEquals(this.debugRunnable, this.fields, this.vals);
return cond;
}
......
......@@ -107,7 +107,7 @@ public class SqlCondItem extends SqlCondBase<SqlCondItem> {
* @return
*/
@Override
public SqlCond copy() {
public SqlCondItem copy() {
SqlCondItem cond = new SqlCondItem(this.debugRunnable, this.fields);
return cond;
}
......
package com.yanzuoguang.dao.cond;
import com.yanzuoguang.dao.impl.SqlData;
import com.yanzuoguang.dao.impl.SqlDataField;
import java.util.List;
import java.util.Map;
/**
* 默认条件
*
* @author 颜佐光
*/
public class SqlCondOr implements SqlCond<SqlCondOr> {
public SqlCondOr(SqlCond... conds) {
}
/**
* 获取包含的字段
*
* @return
*/
@Override
public List<String> getFields() {
return null;
}
/**
* 获取字段值
*
* @param model
* @return
*/
@Override
public List<Object> getValues(Object model) {
return null;
}
/**
* 将当前条件复制为新的对象
*
* @return
*/
@Override
public SqlCondOr copy() {
return null;
}
/**
* 判断条件是否相等
*
* @param cond
* @return
*/
@Override
public boolean equalsExecute(SqlCondOr cond) {
return false;
}
/**
* 获取新的SQL语句
*
* @param sql
* @param sqlData
* @param field
* @param model
* @param codeMap
* @return
*/
@Override
public String getSql(String sql, SqlData sqlData, SqlDataField field, Object model, Map codeMap) {
return null;
}
}
......@@ -502,42 +502,51 @@ public abstract class BaseDaoSql {
* @return 查询的结果
*/
public <T extends Object> PageSizeData<T> queryPage(Class<T> cls, PageSizeReqVo pageSize, String sqlName, Object model, QueryPara queryPara) {
// 获取需要执行的SQL语句
SqlData from = this.getSql(sqlName);
// 设置基本参数值
PageSizeData<T> data = new PageSizeData<T>();
data.setPageIndex(pageSize.getPageIndex());
data.setPageSize(pageSize.getPageSize());
// 对SQL语句进行分页处理
SqlData to = from.copy();
to = getSqlQueryPara(to, queryPara, false);
to.addCode("{LIMIT}", " LIMIT " + pageSize.getPageStart() + "," + pageSize.getPageSize());
// 按照分页查询数据
List<Object> paras = new ArrayList<Object>();
String sql = this.getQueryPara(paras, to, model);
// 查询实体数据
List<T> list = this.queryWithCache(cls, sqlName, sql, paras.toArray());
data.setList(list);
// 设置基本参数值
{
// 获取需要执行的SQL语句
SqlData from = this.getSql(sqlName);
// 对SQL语句进行分页处理
SqlData to = from.copy();
to = getSqlQueryPara(to, queryPara, false);
to.addCode("{LIMIT}", " LIMIT " + pageSize.getPageStart() + "," + pageSize.getPageSize());
// 按照分页查询数据
List<Object> baseParas = new ArrayList<Object>();
String sql = this.getQueryPara(baseParas, to, model);
// 查询实体数据
List<T> list = this.queryWithCache(cls, sqlName, sql, baseParas.toArray());
data.setList(list);
}
// 查询分页总条数的SQL语句
String sqlTo = sql;
// 获取分页查询的SQL语句
SqlData fromPageSize = getSql(sqlName + TableSqlCache.PAGE_SIZE_TAG, false);
if (fromPageSize != null) {
sqlTo = getQueryPara(new ArrayList<>(), fromPageSize, model);
{
SqlData fromPageSize = getSql(sqlName + TableSqlCache.PAGE_SIZE_TAG, false);
if (fromPageSize == null) {
// 获取需要执行的SQL语句
fromPageSize = this.getSql(sqlName);
}
fromPageSize = fromPageSize.copy();
// 按照分页查询数据
List<Object> baseParas = new ArrayList<Object>();
String sql = this.getQueryPara(baseParas, fromPageSize, model);
sql = sql.trim();
// 查询总数据量
String sqlSize = "SELECT COUNT(1) FROM (" +
// 去掉最后一个order by
sql.replaceAll("(?i)(ORDER\\s+BY\\s+[^)]+){0,1}(limit\\s+\\d+,\\d+\\s*){0,1}$", "")
// 去掉第一个 SELECT a.*
.replaceAll("(^SELECT)\\s+a\\.\\*", "$1 1 AS __id")
+ ") t";
data.setPageTotal(StringHelper.toInt(queryCellWithCache(String.format("%s.Size", sqlName), sqlSize, baseParas.toArray())));
}
sqlTo = sqlTo.trim();
// 查询总数据量
String sqlSize = "SELECT COUNT(1) FROM (" +
// 去掉最后一个order by
sqlTo.replaceAll("(?i)(ORDER\\s+BY\\s+[^)]+){0,1}(limit\\s+\\d+,\\d+\\s*){0,1}$", "")
// 去掉第一个 SELECT a.*
.replaceAll("(^SELECT)\\s+a\\.\\*", "$1 1 AS __id")
+ ") t";
data.setPageTotal(StringHelper.toInt(queryCellWithCache(String.format("%s.Size", sqlName), sqlSize, paras.toArray())));
return data;
}
......
......@@ -4,6 +4,7 @@ package com.yanzuoguang.dao.impl;
* 累加接口
*
* @param <T>
* @author 颜佐光
*/
public interface GroupAdd<T extends GroupAdd> {
/***
......
......@@ -119,6 +119,15 @@ public class TableSqlCache {
this.table.addGroupSql(this, tableWhereField, addField);
}
/**
* 生成GroupSQL语句
*
* @param tableWhereField
* @param addField
*/
public void addGroup(TableFieldString tableWhereField, TableFieldString replaceField, TableFieldString addField) {
this.table.addGroupSql(this, tableWhereField, replaceField, addField);
}
/**
* 生成GroupSQL语句
......
......@@ -258,9 +258,11 @@ public class TableStruct {
* @return 获取统计纬度列
*/
public List<TableFieldVo> getGroupLatitudeFields() {
List<TableFieldVo> commonField = getFieldActionList(DaoConst.FIELD_COMMON,
DaoConst.FIELD_ADD_GROUP, DaoConst.FIELD_MD5);
return commonField;
return getFieldActionList(DaoConst.FIELD_COMMON,
DaoConst.FIELD_ADD_GROUP,
DaoConst.FIELD_REPLACE_GROUP,
DaoConst.FIELD_MD5
);
}
/**
......@@ -424,8 +426,9 @@ public class TableStruct {
*/
private void initAddGroup(TableSqlCache table) {
List<TableFieldVo> addGroupField = getFieldActionList(DaoConst.FIELD_ADD_GROUP);
List<TableFieldVo> replaceGroupField = getFieldActionList(DaoConst.FIELD_REPLACE_GROUP);
List<TableFieldVo> commonField = this.getGroupLatitudeFields();
this.addGroupSql(table, commonField, addGroupField);
this.addGroupSql(table, commonField, replaceGroupField, addGroupField);
}
/**
......@@ -724,8 +727,10 @@ public class TableStruct {
*/
private List<TableFieldVo> getFieldString(TableFieldString fieldFrom) {
List<TableFieldVo> list = new ArrayList<>();
for (String fieldName : fieldFrom.getFields()) {
list.add(this.getField(fieldName));
if (fieldFrom != null) {
for (String fieldName : fieldFrom.getFields()) {
list.add(this.getField(fieldName));
}
}
return list;
}
......@@ -759,10 +764,10 @@ public class TableStruct {
*
* @param sqlTableData 需要生成的实体
* @param whereFields WHERE字段
* @param updateFields 需要增加的值的字段
* @param addFields 需要增加的值的字段
*/
public void addGroupSql(TableSqlCache sqlTableData, TableFieldString whereFields, TableFieldString updateFields) {
addGroupSql(sqlTableData, getFieldString(whereFields), getFieldString(updateFields));
public void addGroupSql(TableSqlCache sqlTableData, TableFieldString whereFields, TableFieldString addFields) {
addGroupSql(sqlTableData, whereFields, null, addFields);
}
/**
......@@ -770,18 +775,39 @@ public class TableStruct {
*
* @param sqlTableData 需要生成的实体
* @param whereFields WHERE字段
* @param updateFields 需要增加的值的字段
* @param addFields 需要增加的值的字段
*/
private void addGroupSql(TableSqlCache sqlTableData, List<TableFieldVo> whereFields, List<TableFieldVo> updateFields) {
public void addGroupSql(TableSqlCache sqlTableData, TableFieldString whereFields, TableFieldString replaceFields, TableFieldString addFields) {
addGroupSql(sqlTableData, getFieldString(whereFields), getFieldString(replaceFields), getFieldString(addFields));
}
/**
* 生成统计的SQL语句
*
* @param sqlTableData 需要生成的实体
* @param replaceFields WHERE字段
* @param addFields 需要增加的值的字段
*/
private void addGroupSql(TableSqlCache sqlTableData, List<TableFieldVo> whereFields, List<TableFieldVo> replaceFields, List<TableFieldVo> addFields) {
List<TableFieldVo> prmaryKey = this.getFieldActionList(DaoConst.FIELD_PRIMARY);
// 生成统计加载SQL语句
SqlData sqlLoad = this.releaseSql(DaoConst.SQL_TYPE_ADD_GROUP, DaoConst.GROUP_QUERY, DaoConst.SQL_LOAD,
StringHelper.EMPTY, new ArrayList<>(), whereFields);
sqlLoad.addParaConst(DaoConst.CODE_FIELD_DEFAULT_NAME, DaoConst.CODE_FIELD, DaoConst.CODE_FIELD_DEFAULT);
// 生成统计累加SQL语句
SqlData sqlGroupAdd = this.releaseSql(DaoConst.SQL_TYPE_ADD_GROUP, DaoConst.GROUP_ADD, DaoConst.SQL_UPDATE,
DaoConst.CODE_GROUP_ADD, updateFields, prmaryKey);
if (updateFields.isEmpty()) {
DaoConst.CODE_GROUP_ADD, addFields, prmaryKey);
// 当没有字段时,直接修改主键
if (addFields.isEmpty()) {
sqlGroupAdd.addCode(DaoConst.CODE_FIELD, String.format("%s=%s", prmaryKey.get(0).inputName, prmaryKey.get(0).inputName));
}
// 生成覆盖值
if (replaceFields != null) {
for (TableFieldVo field : replaceFields) {
sqlGroupAdd.addPara(field.inputName, DaoConst.CODE_FIELD, String.format(",a.%s=?", field.name));
}
}
sqlTableData.add(sqlLoad);
sqlTableData.add(sqlGroupAdd);
}
......@@ -856,8 +882,8 @@ public class TableStruct {
tos.add(from);
mapFrom.put(key, from);
} else {
T histor = mapFrom.get(key);
histor.add(from);
T history = mapFrom.get(key);
history.add(from);
}
}
......
......@@ -27,11 +27,20 @@ public class DbPrintSql {
public String getStringSql(String sql, Object... paras) {
StringBuilder sb = new StringBuilder();
// 进行SQL语句参数替换,后面增加一个空格,方便后续用正则表达式进行替换处理
String[] split = sql.split("\\?");
// 参数位置
int pos = 0;
// 进行SQL语句参数替换,后面增加一个空格,方便后续用正则表达式进行替换处理
for (Object item : paras) {
// 循环获取参数
while (pos < split.length) {
// 获取位置信息
sb.append(split[pos]);
// 获取位置
if (pos == split.length - 1) {
break;
}
// 获取对象
Object item = paras.length > pos ? paras[pos] : null;
String str = StringHelper.toString(item);
String strTo = str;
if (str == null) {
......@@ -41,15 +50,11 @@ public class DbPrintSql {
} else {
strTo = "'" + str.replace("'", "''") + "'";
}
sb.append(split[pos]);
pos++;
sb.append(strTo);
}
while (pos < split.length) {
sb.append(split[pos]);
pos++;
}
return sb.toString();
}
......@@ -64,17 +69,21 @@ public class DbPrintSql {
* @param paras 参数
*/
public void print(Class targetClass, String sqlName, long start, int row, String sql, Object... paras) {
// 日志表忽略打印
if (!configDb.isPrintSql()) {
return;
}
if (!StringHelper.isEmpty(configDb.getPrintSqlFilter())) {
if (sql.matches(configDb.getPrintSqlFilter())) {
try {
// 日志表忽略打印
if (!configDb.isPrintSql()) {
return;
}
if (!StringHelper.isEmpty(configDb.getPrintSqlFilter())) {
if (sql.matches(configDb.getPrintSqlFilter())) {
return;
}
}
sql = getStringSql(sql, paras);
// 打印SQL语句
Log.infoTag(DbPrintSql.class, String.format("%d row %s.%s", row, targetClass.getSimpleName(), sqlName), sql);
} catch (Exception ex) {
Log.error(DbPrintSql.class, ex);
}
sql = getStringSql(sql, paras);
// 打印SQL语句
Log.infoTag(DbPrintSql.class, String.format("%d row %s.%s", row, targetClass.getSimpleName(), sqlName), sql);
}
}
import com.yanzuoguang.dao.DaoConst;
import com.yanzuoguang.dao.impl.SqlData;
import com.yanzuoguang.dao.impl.TableSqlCache;
import com.yanzuoguang.dao.impl.TableStruct;
import com.yanzuoguang.db.impl.DbPrintSql;
import com.yanzuoguang.util.helper.JsonHelper;
import org.junit.Test;
public class TestDbPrintSql {
@Test
public void test() {
DbPrintSql printSql = new DbPrintSql();
String stringSql = printSql.getStringSql("select * from where id = ? AND name = ? and removeFlag = 0 ", "1");
System.out.println(stringSql);
}
@Test
public void testTableStruct() {
TableSqlCache cache = new TableSqlCache();
TableStruct table = new TableStruct("test", TestTableGroupVo.class);
table.init(cache);
SqlData sqlData = cache.getNameCache().get(DaoConst.GROUP_ADD);
System.out.println(JsonHelper.serialize(sqlData, true));
}
@Test
public void testTableStruct1() {
TableSqlCache cache = new TableSqlCache();
TableStruct table = new TableStruct("test", TestTableGroupVo1.class);
table.init(cache);
SqlData sqlData = cache.getNameCache().get(DaoConst.GROUP_ADD);
System.out.println(JsonHelper.serialize(sqlData, true));
}
@Test
public void testTable() {
TableSqlCache cache = new TableSqlCache();
TableStruct table = new TableStruct("test", TestTableGroupVo.class);
table.init(cache);
System.out.println(JsonHelper.serialize(cache.getNameCache(), true));
}
}
import com.yanzuoguang.dao.DaoConst;
import com.yanzuoguang.dao.TableAnnotation;
@TableAnnotation("db_time")
public class TestTableGroupVo {
@TableAnnotation("id")
private String id;
@TableAnnotation("createDate")
private String createDate;
@TableAnnotation(value = "total", type = DaoConst.FIELD_REPLACE_GROUP)
private int total;
@TableAnnotation(value = "total1", type = DaoConst.FIELD_REPLACE_GROUP)
private int total1;
@TableAnnotation(value = "has", type = DaoConst.FIELD_ADD_GROUP)
private int has;
@TableAnnotation(value = "has1", type = DaoConst.FIELD_ADD_GROUP)
private int has1;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getTotal1() {
return total1;
}
public void setTotal1(int total1) {
this.total1 = total1;
}
public int getHas() {
return has;
}
public void setHas(int has) {
this.has = has;
}
public int getHas1() {
return has1;
}
public void setHas1(int has1) {
this.has1 = has1;
}
}
import com.yanzuoguang.dao.DaoConst;
import com.yanzuoguang.dao.TableAnnotation;
@TableAnnotation("db_time")
public class TestTableGroupVo1 {
@TableAnnotation("id")
private String id;
@TableAnnotation("createDate")
private String createDate;
@TableAnnotation(value = "total", type = DaoConst.FIELD_REPLACE_GROUP)
private int total;
@TableAnnotation(value = "total1", type = DaoConst.FIELD_REPLACE_GROUP)
private int total1;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getTotal1() {
return total1;
}
public void setTotal1(int total1) {
this.total1 = total1;
}
}
package com.yanzuoguang.media;
/**
* 获取视频是否已经在处理
*
* @author 颜佐光
*/
public interface MediaCache extends MediaCacheBase {
}
package com.yanzuoguang.media;
/**
* 视频缓存处理
*
* @author 颜佐光
*/
public interface MediaCacheBase {
/**
* 获取缓存是否正在执行
*
* @param req 需要运行的请求参数
* @param runnable 当没有运行时,需要执行的函数
* @return
*/
MediaResVo start(MediaReqVo req, Runnable runnable);
/**
* 获取缓存是否正在运行
*
* @param req
* @return
*/
MediaResVo get(MediaReqVo req);
/**
* 写入处理结果到缓存中
*
* @param res
*/
void sub(MediaResVo res);
/**
* 锁定临时文件,防止被人修改
*
* @param req
* @param runnable
*/
void lockTempFile(MediaReqVo req, Runnable runnable);
}
package com.yanzuoguang.media;
import com.yanzuoguang.util.helper.JsonHelper;
import java.util.HashMap;
import java.util.Map;
/**
* 本地缓存实现
*
* @author 颜佐光
*/
public class MediaCacheLocal implements MediaCacheBase {
private Map<String, MapLock> mapLock = new HashMap<String, MapLock>();
/**
* 获取缓存是否正在执行
*
* @param req 需要运行的请求参数
* @param runnable 当没有运行时,需要执行的函数
* @return
*/
@Override
public MediaResVo start(MediaReqVo req, Runnable runnable) {
// 获取锁
MapLock mapLock = getMapLock(req);
// 锁定缓存对象,防止多人执行
synchronized (mapLock) {
// 读取历史缓存
MediaResVo tempRes = mapLock.res;
// 写入结果到缓存
mapLock.res = JsonHelper.to(req, MediaResVo.class);
// 判断历史缓存的次数,确定是否执行
if (tempRes == null || tempRes.getCount() < 1) {
// 执行时,会开启线程下载视频,并转换为截图文件
runnable.run();
}
// 返回缓存中的结果
return mapLock.res;
}
}
/**
* 获取缓存是否正在运行
*
* @param req
* @return
*/
@Override
public MediaResVo get(MediaReqVo req) {
// 获取锁
MapLock mapLock = getMapLock(req);
// 锁定缓存对象,防止多人执行
synchronized (mapLock) {
return mapLock.res;
}
}
/**
* 写入处理结果到缓存中
*
* @param res
*/
@Override
public void sub(MediaResVo res) {
// 获取锁
MapLock mapLock = getMapLock(res);
// 锁定缓存对象,防止多人执行
synchronized (mapLock) {
mapLock.res.subCount();
}
}
/**
* 锁定临时文件,防止被人修改
*
* @param req
* @param runnable
*/
@Override
public void lockTempFile(MediaReqVo req, Runnable runnable) {
MapLock lock = getMapLock(req);
synchronized (lock.lockTemp) {
runnable.run();
}
}
private MapLock getMapLock(MediaReqVo req) {
synchronized (mapLock) {
MapLock lock = this.mapLock.get(req.getUrl());
if (lock == null) {
lock = new MapLock();
this.mapLock.put(req.getUrl(), lock);
}
return lock;
}
}
private static class MapLock {
Object lockTemp = new Object();
MediaResVo res;
}
}
package com.yanzuoguang.media;
import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.helper.FileHelper;
import com.yanzuoguang.util.helper.JsonHelper;
import com.yanzuoguang.util.thread.ThreadHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
/**
* 直播首页操作
*
* @author 颜佐光
*/
@Component
public class MediaFirst {
/**
* 判断该视频是否已经实现处理
*/
@Autowired(required = false)
private MediaCache cache;
private MediaCacheBase cacheLocal = new MediaCacheLocal();
public MediaFirst() {
}
private MediaCacheBase getCache() {
if (cache != null) {
return cache;
}
return cacheLocal;
}
public MediaFirst(MediaCache cache) {
this.cache = cache;
}
public MediaResVo start(MediaReqVo req) {
if (cache == null) {
throw new CodeException("请通过程序编写视频缓存处理对象");
}
// 将临时文件移动到正式文件
cache.lockTempFile(req, new Runnable() {
@Override
public void run() {
File file = getFile(req);
File fileTemp = getFileTemp(req);
FileHelper.createDirectory(file.getParentFile());
if (fileTemp.exists()) {
fileTemp.renameTo(file);
}
}
});
// 通过判断,当没有开启线程运行时,则开启线程运行
return this.getCache().start(req, new Runnable() {
@Override
public void run() {
// 开始开启线程运行
ThreadHelper.runThread(new Runnable() {
@Override
public void run() {
handle(req);
}
});
}
});
}
private File getFile(MediaReqVo req) {
return new File(req.getImageUrl());
}
private File getFileTemp(MediaReqVo req) {
return new File(req.getImageUrl() + ".tmp");
}
private File getDownM3muFile(MediaReqVo req) {
return null;
}
private File getCatTempFile(MediaReqVo req) {
return null;
}
private void handle(MediaReqVo req) {
do {
MediaResVo res = cache.get(req);
if (res == null) {
res = JsonHelper.to(req, MediaResVo.class);
}
// 下载m3mu并转换成mp4
downM3mu(req);
// 转换为图片
catImage(req);
// 将下载临时文件移动到临时文件
cache.lockTempFile(req, new Runnable() {
@Override
public void run() {
File catTemp = getCatTempFile(req);
File fileTemp = getFileTemp(req);
if (catTemp.exists()) {
catTemp.renameTo(fileTemp);
}
}
});
// 写入缓存
cache.sub(res);
// 判断是否还有执行次数
if (res.getCount() < 1) {
break;
}
// 等待下一次截图
ThreadHelper.sleep(res.getSplit());
} while (true);
}
private void downM3mu(MediaReqVo req) {
}
private void catImage(MediaReqVo req) {
}
}
package com.yanzuoguang.media;
import com.yanzuoguang.util.vo.BaseVo;
import io.swagger.annotations.ApiModelProperty;
/**
* 获取视频首页请求参数
*
* @author 颜佐光
*/
public class MediaReqVo extends BaseVo {
/**
* 汲取视频的url
*/
@ApiModelProperty(notes = "m3mu地址")
private String url;
/**
* m3mu地址截取次数
*/
@ApiModelProperty(notes = "m3mu地址截取次数")
private int count;
/**
* m3mu地址截取间隔时间
*/
@ApiModelProperty(notes = "m3mu地址截取间隔时间")
private int split;
/**
* m3mu缓存的图片地址
*/
@ApiModelProperty(notes = "m3mu缓存的图片地址")
private String imageUrl;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getSplit() {
return split;
}
public void setSplit(int split) {
this.split = split;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
package com.yanzuoguang.media;
/**
* 获取视频结果
*
* @author 颜佐光
*/
public class MediaResVo extends MediaReqVo {
public void subCount() {
this.setCount(this.getCount() - 1);
}
}
package helper;
import com.yanzuoguang.media.MediaFirst;
import com.yanzuoguang.media.MediaReqVo;
import com.yanzuoguang.media.MediaResVo;
import com.yanzuoguang.util.thread.ThreadHelper;
import org.junit.Test;
import java.io.File;
public class MediaFirstTest {
@Test
public void test() {
MediaFirst first = new MediaFirst();
for (int i = 0; i < 1000; i++) {
MediaResVo start = first.start(new MediaReqVo());
File file = new File(start.getImageUrl());
if (file.exists()) {
System.out.println("文件" + file.getAbsolutePath() + "已经存在");
} else {
System.out.println("文件" + file.getAbsolutePath() + "不存在");
}
ThreadHelper.sleep(5000);
}
}
}
......@@ -2,6 +2,7 @@ package helper;
import com.yanzuoguang.util.MediaHelper;
import com.yanzuoguang.util.MediaParameter;
import com.yanzuoguang.util.YzgError;
import org.junit.Test;
import java.io.File;
......
......@@ -45,7 +45,8 @@ public class MessagePlan extends BaseVo {
return 0;
}
long time = System.currentTimeMillis() - this.getStart();
return this.message.getDedTime() - time;
long dedTime = this.message.getDedTime() - time;
return Math.max(dedTime, 0);
}
public MessageVo getMessage() {
......
package helper;
import com.yanzuoguang.util.PrinterHelper;
import com.yanzuoguang.util.YzgError;
import com.yanzuoguang.util.helper.FileHelper;
import com.yanzuoguang.util.helper.JsonHelper;
import com.yanzuoguang.util.printer.ConvertPlan;
......
......@@ -23,7 +23,7 @@ public class CacheLock implements Runnable {
private Cache cache;
/**
* Redis 锁定时间(秒)
* Redis 锁定时间(秒)
*/
private int lockTime;
......@@ -137,13 +137,16 @@ public class CacheLock implements Runnable {
}
private void funcRun() {
if (this.waitCount > 0 && this.funcWait != null) {
funcWait.run();
}
if (this.func != null) {
func.run();
try {
if (this.waitCount > 0 && this.funcWait != null) {
funcWait.run();
}
if (this.func != null) {
func.run();
}
} finally {
runFlag = true;
}
runFlag = true;
}
/**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment