This commit is contained in:
2019-03-07 10:24:29 +08:00
parent 6c8c683c31
commit e057d613b9
215 changed files with 70917 additions and 118 deletions

View File

@@ -0,0 +1,78 @@
package net.tccn.base;
import org.redkale.convert.json.JsonConvert;
/**
* Created by liangxianyou at 2018/7/30 16:51.
*/
public class JBean {
private int code;
private String message;
private Object body;
private long timestamp;
public static JBean by(int code, String message){
JBean jBean = new JBean();
jBean.code = code;
jBean.message = message;
jBean.timestamp = System.currentTimeMillis();
return jBean;
}
public static JBean by(int code, String message, Object result){
JBean jBean = new JBean();
jBean.code = code;
jBean.message = message;
jBean.body = result;
jBean.timestamp = System.currentTimeMillis();
return jBean;
}
public JBean set(int code, String message){
this.code = code;
this.message = message;
return this;
}
public JBean set(int code, String message, Object result){
this.code = code;
this.message = message;
this.body = result;
this.timestamp = System.currentTimeMillis();
return this;
}
public JBean setCode(int code) {
this.code = code;
return this;
}
public JBean setMessage(String message) {
this.message = message;
return this;
}
public JBean setBody(Object body) {
this.body = body;
return this;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
public Object getBody() {
return body;
}
public long getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}

View File

@@ -0,0 +1,156 @@
package net.tccn.base;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* Created by liangxianyou@eversec.cn at 2018/3/12 14:17.
*/
public class Kv<K,V> extends LinkedHashMap {
public static Kv of(){
return new Kv();
}
public static Kv of(Object k, Object v){
return new Kv().set(k,v);
}
public Kv<K, V> set(K k, V v){
put(k, v);
return this;
}
public static Kv toKv(Object m) {
return toKv(m, Kv.of(), m.getClass());
}
private static Kv toKv(Object m, Kv kv, Class clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
if (!kv.containsKey(field.getName())) {
kv.set(field.getName(), field.get(m));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Class superclass = clazz.getSuperclass();
if (superclass != null) {
kv = toKv(m, kv, superclass);
}
return kv;
}
public <T> T toBean(Class<T> type) {
return (T) toBean(this, type);
}
// 首字母大写
private static Function<String, String> upFirst = (s) -> {
return s.substring(0, 1).toUpperCase() + s.substring(1);
};
private static Map<Class, Class[]> clazzMap = new HashMap<>();
static {
clazzMap.put(ArrayList.class, new Class[]{List.class, ArrayList.class, String.class});
clazzMap.put(HashMap.class, new Class[]{Map.class, HashMap.class, String.class});
clazzMap.put(Long.class, new Class[]{Long.class, Integer.class, long.class, int.class, short.class, String.class});
clazzMap.put(String.class, new Class[]{String.class, Integer.class, Date.class});
clazzMap.put(Double.class, new Class[]{Double.class, Long.class, Integer.class, long.class, int.class, short.class, String.class});
}
private static Predicate<Class> isNumber = (t) -> {
return t == Integer.class || t == int.class
|| t == Long.class || t == long.class
|| t == Double.class || t == double.class
;
};
public static <T> T toBean(Map<String, Object> m, Class<T> type) {
try {
Object obj = type.newInstance();
m.forEach((k, v) -> {
String methodName = "set" + upFirst.apply(k);
Method method = null;
Class[] clazzs = clazzMap.get(v == null ? null : v.getClass());
if (clazzs == null) {
//doc.set(k, v);
} else {
for (Class clazz : clazzs) {
try {
method = type.getDeclaredMethod(methodName, clazz);
} catch (NoSuchMethodException e) {
}
if (method != null) {
try {
if (v == null || "".equals(v)) {
} else if (v.getClass() == Long.class && clazz != Long.class) {//多种数值类型的处理
Object _v;
switch (clazz.getSimpleName()) {
case "int":
case "Long": _v = v; break;
case "Integer": _v = (int)((long) v); break;
case "short":
case "Short": _v = (short)((long) v); break;
default: _v = v;
}
method.invoke(obj, _v);
} else if (v.getClass() == Double.class) {
Object _v = null;
if (isNumber.test(clazz)) {
switch (clazz.getSimpleName()) {
case "long":
case "Long": _v = (long)(double) v; break;
case "int":
case "Integer": _v = (int)((double) v); break;
case "short":
case "Short": _v = (int)(double) v; break;
default: _v = v;
}
} else if (clazz == String.class){
_v = String.valueOf(v);
}
method.invoke(obj, _v);
} else if (v.getClass() == String.class && clazz == Date.class) {
Date _v = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) v);
method.invoke(obj, _v);
} else if (v.getClass() == String.class && clazz == Integer.class) {
Object _v = (int)Double.parseDouble((String) v);
method.invoke(obj, _v);
}
else {
method.invoke(obj, v);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
break;
}
}
}
});
return (T) obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,39 @@
package net.tccn.base;
import java.util.List;
/**
* Created by JUECHENG at 2018/5/7 11:20.
*/
public class PageBean<M> {
private List<M> rows;
private long total;
public static PageBean by(List rows, long total) {
return new PageBean(rows, total);
}
public PageBean() {
}
public PageBean(List<M> rows, long total) {
this.rows = rows;
this.total = total;
}
public List<M> getRows() {
return rows;
}
public void setRows(List<M> rows) {
this.rows = rows;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
}

View File

@@ -0,0 +1,290 @@
package net.tccn.base.arango;
import com.arangodb.*;
import com.arangodb.entity.DocumentCreateEntity;
import com.arangodb.entity.DocumentDeleteEntity;
import com.arangodb.entity.MultiDocumentEntity;
import javax.persistence.Table;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.Arrays.asList;
/**
* 管理 数据源连接对象
* @author: liangxianyou at 2018/12/15 11:35.
*/
public class ArangoSource {
public Logger logger = Logger.getLogger(this.getClass().getSimpleName());
private ArangoDB arangoDb;
private static Map<String, ArangoSource> sources = new HashMap();
static {
init();
}
public static void init() {
sources.put("main", new ArangoSource(new ArangoDB.Builder().host("120.24.230.60", 8529).user("root").password("abc123").build()));
sources.put("abc", new ArangoSource(new ArangoDB.Builder().host("192.168.199.135", 8529).user("root").password("root").build()));
}
public ArangoSource(ArangoDB arangoDb) {
this.arangoDb = arangoDb;
}
public static ArangoSource use() {
return use("main");
}
public static ArangoSource use(String unit) {
if (unit == null || unit.isEmpty()) {
unit = "main";
}
return sources.get(unit);
}
public ArangoDB arangoDB() {
return arangoDb;
}
public ArangoDatabase db(String db) {
return arangoDb.db(db);
}
public <T extends Doc> ArangoCollection collection(Doc<T> doc) {
return collection(doc.getClass());
}
public <T extends Doc> ArangoCollection collection(Class<T> type) {
Table table = type.getAnnotation(Table.class);
//createDb(table.catalog());
return arangoDb.db(table.catalog()).collection(table.name());
}
public boolean createDb(String db) {
ArangoDatabase database = arangoDb.db(db);
if (!database.exists()) {
return database.create();
}
logger.log(Level.INFO, "arango database exists");
return true;
}
public <T extends Doc> ArangoCollection createDocument(Doc<T> doc) {
Class<? extends Doc> type = doc.getClass();
Table table = type.getAnnotation(Table.class);
ArangoDatabase database = arangoDb.db(table.catalog());
if (!database.exists()) {
database.create();
}
ArangoCollection collection = database.collection(table.name());
if (!collection.exists()) {
collection.create();
}
return collection;
}
// 首字母大写
private static Function<String, String> upFirst = (s) -> {
return s.substring(0, 1).toUpperCase() + s.substring(1);
};
private static Map<Class, Class[]> clazzMap = new HashMap<>();
static {
clazzMap.put(ArrayList.class, new Class[]{List.class, ArrayList.class, String.class});
clazzMap.put(HashMap.class, new Class[]{Map.class, HashMap.class, String.class});
clazzMap.put(Long.class, new Class[]{Long.class, Integer.class, long.class, int.class, short.class, String.class});
clazzMap.put(String.class, new Class[]{String.class});
}
/**
* 还原 Doc对象
* @param map
* @param type
* @param <T>
* @return
*/
public <T extends Doc> T toDoc1(Map<String, Object> map, Class<T> type) {
try {
Doc doc = type.newInstance();
map.forEach((k, v) -> {
String methodName = "set" + upFirst.apply(k);
Method method = null;
Class[] clazzs = clazzMap.get(v == null ? null : v.getClass());
if (clazzs == null) {
doc.set(k, v);
} else {
for (Class clazz : clazzs) {
try {
method = type.getDeclaredMethod(methodName, clazz);
} catch (NoSuchMethodException e) {
}
if (method != null) {
try {
if (v.getClass() == Long.class && clazz != Long.class) {//多种数值类型的处理
Object _v;
switch (clazz.getSimpleName()) {
case "int":
case "Integer": _v = (int)((long) v); break;
case "short":
case "Short": _v = (short)((long) v); break;
default: _v = v;
}
System.out.println(clazz.getSimpleName());
method.invoke(doc, _v);
} else {
method.invoke(doc, v);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
doc.set(k, v);
} catch (InvocationTargetException e) {
e.printStackTrace();
doc.set(k, v);
}
break;
}
}
}
if (method == null) {
doc.set(k, v);
}
});
return (T) doc;
} catch (Exception e) {
}
return null;
}
private Predicate isEmpty = (x) -> {
if (x == null)
return true;
if (x instanceof List)
return ((List) x).isEmpty();
if (x instanceof String)
return ((String) x).isEmpty();
if (x instanceof Map)
return ((Map) x).isEmpty();
if (x instanceof Collection)
return ((Collection) x).isEmpty();
return false;
};
/**
* Doc 转为查询对象
* @param t
* @param <T>
* @return
*/
private Function<Doc, StringBuilder> filterBuilder = (t) -> {
Table table = t.getClass().getAnnotation(Table.class);
StringBuilder buf = new StringBuilder();
buf.append("for d in ").append(table.name());
buf.append(" filter 1==1");
t.toDoc().forEach((k, v) -> {
if (v != null && (v.getClass() == String.class || v instanceof Number)) {
buf.append(" and d.").append(k).append("==");
}
if (v.getClass() == String.class) {
buf.append("'").append(v).append("'");
} else if (v instanceof Number) {
buf.append(v);
}
});
return buf;
};
private Function<Doc, StringBuilder> orderBuilder = (t) -> {
StringBuilder buf = new StringBuilder();
Map<String, Integer> order = t.getOrder();
if (isEmpty.test(order)) {
return buf;
}
buf.append(" sort ");
order.forEach((k, v) -> {
buf.append("d.").append(k).append(v == 1 ? " desc," : " asc,");
});
buf.deleteCharAt(buf.length() - 1);
return buf;
};
private Function<Doc, StringBuilder> returnBuilder = (t) -> {
StringBuilder buf = new StringBuilder();
if (isEmpty.test(t.get_Shows())) {
return buf.append(" return d");
}
buf.append(" return {");
t.get_Shows().forEach(x -> {
buf.append(x).append(":d.").append(x).append(",");
});
buf.deleteCharAt(buf.length() - 1).append("}");
return buf;
};
public <T extends Doc> String parseAqlCount(T t) {
StringBuilder buf = new StringBuilder();
buf.append(filterBuilder.apply(t));
buf.append(" COLLECT WITH COUNT INTO total");
buf.append(" return total");
//logger.log(Level.INFO, buf.toString());
return buf.toString();
}
public <T extends Doc> String parseAql(T t, int offset, int ps) {
if (offset < 0) offset = 0;
if (ps <= 0) ps = 1000;
StringBuilder buf = new StringBuilder();
buf.append(filterBuilder.apply(t));
buf.append(orderBuilder.apply(t));
buf.append(" limit ").append(offset).append(",").append(ps);
buf.append(returnBuilder.apply(t));
//logger.log(Level.INFO, buf.toString());
return buf.toString();
}
//----------------------------------------
//ok
public <T extends Doc> T save(T doc) {
DocumentCreateEntity<Map> tmap = collection(doc).insertDocument(doc.toDoc());
doc.setKey(tmap.getKey());
doc.setId(tmap.getId());
return doc;
}
//ok
public <T extends Doc> void update(T doc) {
collection(doc).updateDocument(doc.getKey(), doc.toDoc());
}
//ok
public <T extends Doc> T getDoc(Object key, Class<T> type) {
return collection(type).getDocument(String.valueOf(key), type);
}
//ok
public <T extends Doc> DocumentDeleteEntity<Void> delete(String key, Class<T> type) {
return collection(type).deleteDocument(key);
}
//ok
public <T extends Doc> MultiDocumentEntity<DocumentDeleteEntity<Void>> deleteAll(Doc<T> ... docs) {
return collection(docs[0]).deleteDocuments(asList(docs));
}
public <T extends Doc> MultiDocumentEntity find(Collection keys, Class<T> type) {
return collection(type).getDocuments(keys, type);
}
}

View File

@@ -0,0 +1,251 @@
package net.tccn.base.arango;
import com.arangodb.ArangoCollection;
import com.arangodb.ArangoDBException;
import com.arangodb.ArangoDatabase;
import com.arangodb.entity.DocumentCreateEntity;
import javax.persistence.Table;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
/**
* @author: liangxianyou at 2018/12/1 22:59.
*/
public abstract class Doc<T extends Doc> {
private HashMap attr = new HashMap();
private String _id;
private String _key;
private Set<String> _shows;
private Map _order;
public String getId() {
return _id;
}
public void setId(String id) {
this._id = id;
}
public String getKey() {
return _key;
}
public void setKey(String key) {
this._key = key;
}
public Doc<T> set(String k, Object v) {
attr.put(k, v);
return this;
}
public <V> V get(String k) {
return (V)attr.get(k);
}
public T setShows(String... show) {
if (_shows == null) {
_shows = new HashSet<>();
}
for (String s : show) {
_shows.add(s);
}
return (T) this;
}
public Set<String> get_Shows() {
return _shows;
}
public void set_Shows(Set<String> shows) {
this._shows = shows;
}
public T setOrder(String col, int desc) {
if (_order == null) {
_order = new LinkedHashMap();
}
_order.put(col, desc);
return (T) this;
}
public Map<String, Integer> getOrder() {
return _order;
}
/*public void setOrder(Map order) {
this._order = order;
}*/
/*@Override
public String toString() {
//convert.
String doc = convert.convertTo(this);
if (attr.size() == 0) {
return doc;
}
StringBuilder builder = new StringBuilder();
if (attr.size() != 0) {
String attrStr = convert.convertTo(attr);
builder.append("{");
builder.append(attrStr, 1, attrStr.length() - 1);
builder.append(",");
builder.append(doc, 1, doc.length()); //builder.append(doc.substring(1));
}
return builder.toString();
}*/
private Function<String, String> fieldName = (s) -> {
return s.replace("get", "").substring(0, 1).toLowerCase() + s.substring(4);
};
/**
* 提取Doc 属性到 Map用于存贮到Arango中
* 提取规则:
* 1、将doc中自带非空 !=null 属性提取都map中
* 2、将attr中属性覆盖到map中如果attr中存在同名属性attr为主
* @return
*/
public Map toDoc() {
HashMap clone = (HashMap) attr.clone();
Class<? extends Doc> type = this.getClass();
Method[] methods = type.getDeclaredMethods();
for (Method method : methods) {
String name = method.getName();
if (name.startsWith("get") && method.getParameterCount() == 0) {
//Type mt = method.getAnnotatedReturnType().getType();
try {
//System.out.println(method.getName());
Object v = method.invoke(this);
if (v != null) {
clone.put(fieldName.apply(name), v);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
return clone;
}
//---------------------------------------------------------------------------------------------------
private ArangoSource arangoSource;
private ArangoDatabase db;
private ArangoCollection collection;
private static ConcurrentHashMap<Class, Doc> daos = new ConcurrentHashMap();
public Doc() {
Table table = this.getClass().getAnnotation(Table.class);
String sourceName = null;
Source source = this.getClass().getAnnotation(Source.class);
if (source != null) {
sourceName = source.name();
}
arangoSource = ArangoSource.use(sourceName);
this.db = arangoSource.db(table.catalog());
this.collection = arangoSource.collection(this);
}
public final static <T extends Doc> T dao(Class<T> type) {
if (daos.get(type) == null) {
try {
daos.put(type, type.newInstance());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return (T) daos.get(type);
}
//ok
public T save() {
DocumentCreateEntity<Map> tmap = collection.insertDocument(this.toDoc());
this.setId(tmap.getId());
this.setKey(tmap.getKey());
return (T) this;
}
//ok
public void update() {
collection.updateDocument(this.getKey(), this.toDoc());
}
public T findFirst(T t) {
return findFirst(arangoSource.parseAql(t, 0, 1), (Class<T>) t.getClass());
}
public List<T> find() {
return find((T) this, 0, 1000);
}
public List<T> find(T t) {
return find(t, 0, 1000);
}
public <T extends Doc> List<T> find(T t, int offset, int pn) {
return find(arangoSource.parseAql(t, offset, pn), (Class<T>)this.getClass());
}
public <T> List<T> find(String aql, Class<T> clazz) {
try {
return db.query(aql, clazz).asListRemaining();
} catch (ArangoDBException e) {
System.out.println(aql);
e.printStackTrace();
ArangoSource.init();
}
return db.query(aql, clazz).asListRemaining();
}
public <T> T findFirst(String aql, Class<T> clazz) {
try {
return db.query(aql, clazz).first();
} catch (ArangoDBException e) {
System.out.println(aql);
e.printStackTrace();
ArangoSource.init();
}
return db.query(aql, clazz).first();
}
public long count() {
return count(this);
}
public <T extends Doc> long count(T t) {
return db.query(arangoSource.parseAqlCount(t), long.class).first();
}
//ok
public <T extends Doc> T findByKey(Object key) {
return (T) collection.getDocument(String.valueOf(key), this.getClass());
}
//ok
public void delete() {
collection.deleteDocument(getKey());
}
public void delete(Collection<String> key) {
collection.deleteDocuments(key);
}
}

View File

@@ -0,0 +1,15 @@
package net.tccn.base.arango;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author: liangxianyou at 2018/12/22 0:32.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Source {
String name() default "";
}