diff --git a/luqj-common/src/main/java/com/luqj/qiniu/task/QiNiuRefreshTokenTask.java b/luqj-common/src/main/java/com/luqj/qiniu/task/QiNiuRefreshTokenTask.java index f9538e5..f581b4e 100644 --- a/luqj-common/src/main/java/com/luqj/qiniu/task/QiNiuRefreshTokenTask.java +++ b/luqj-common/src/main/java/com/luqj/qiniu/task/QiNiuRefreshTokenTask.java @@ -20,7 +20,7 @@ public class QiNiuRefreshTokenTask { private IQiniuService qiniuService; // @Scheduled(cron = "0/10 * * * * ?") - @Scheduled(cron = "* 0/10 * * * ?") + @Scheduled(cron = "0 */10 * * * ?") public void refreshQiniuToken() { qiniuService.refreshQiniuToken(); diff --git a/luqj-common/src/main/java/com/luqj/util/ArithmeticEnum.java b/luqj-common/src/main/java/com/luqj/util/ArithmeticEnum.java new file mode 100644 index 0000000..112950c --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/ArithmeticEnum.java @@ -0,0 +1,102 @@ +package com.luqj.util; + + +/** + * 算术符号 + * @author chenzm + */ +public enum ArithmeticEnum { + + /**左括号**/ + lb("(", "左括号", -1), + /**右括号**/ + rb(")", "右括号", -1), + + /**乘**/ + multiply("*", "乘", -3), + /**除**/ + division("/", "除", -3), + + /**加**/ + addition("+", "加", -4), + /**减**/ + subtract("-", "减", -4), + + /**大于**/ + gt(">", "大于", -6), + /**小于**/ + lt("<", "小于", -6), + /**大于等于**/ + gte(">=", "大于等于", -6), + /**小于等于**/ + lte("<=", "小于等于", -6); + + /**符号**/ + private String symbol; + + /**优先级**/ + private int priority; + + private String desc; + + private ArithmeticEnum(String symbol, String desc, int priority) { + this.symbol = symbol; + this.desc = desc; + this.priority = priority; + } + + public boolean isEqualBySymbol(String c) { + return this.getSymbol().equals(c); + } + + public boolean isEqualBySymbol(char c) { + return this.getSymbol().equals("" + c); + } + + public String getSymbol() { + return symbol; + } + + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + /** + * 获取符号等级 + */ + public static int getSymbolLevel(String c) { + return getArithmeticEnum(c).getPriority(); + } + + public static ArithmeticEnum getArithmeticEnum(String c) { + for(ArithmeticEnum t : ArithmeticEnum.values()) { + if(t.getSymbol().equals(c)) { + return t; + } + } + return null; + } + + public static boolean containsKey(String c) { + if(getArithmeticEnum(c) != null) { + return true; + } + return false; + } +} diff --git a/luqj-common/src/main/java/com/luqj/util/CharBuffer.java b/luqj-common/src/main/java/com/luqj/util/CharBuffer.java new file mode 100644 index 0000000..0d4b14f --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/CharBuffer.java @@ -0,0 +1,567 @@ +package com.luqj.util; + + +import com.luqj.util.parse.SymbolSet; + +import java.util.NoSuchElementException; + +/** + * 字符缓存 + */ +public class CharBuffer { + + transient int size = 0; + + transient Node first; + + transient Node last; + + transient int modCount = 0; + + public CharBuffer() { + } + + public CharBuffer(String str) { + for(char c : str.toCharArray()) { + this.add(c); + } + } + + public CharBuffer(char[] chs) { + for(char c : chs) { + this.add(c); + } + } + + public String asString() { + return new String(this.toArray()); + } + + public void addStr(String str) { + for(char c : str.toCharArray()) { + this.add(c); + } + } + + /** + * Links e as first element. + */ + private void linkFirst(char e) { + final Node f = first; + final Node newNode = new Node(null, e, f); + first = newNode; + if (f == null) + last = newNode; + else + f.prev = newNode; + size++; + modCount++; + } + + + void linkLast(char e) { + final Node l = last; + final Node newNode = new Node(l, e, null); + last = newNode; + if (l == null) + first = newNode; + else + l.next = newNode; + size++; + modCount++; + } + + /** + * Inserts element e before non-null Node succ. + */ + void linkBefore(char e, Node succ) { + // assert succ != null; + final Node pred = succ.prev; + final Node newNode = new Node(pred, e, succ); + succ.prev = newNode; + if (pred == null) + first = newNode; + else + pred.next = newNode; + size++; + modCount++; + } + + /** + * Unlinks non-null first node f. + */ + private char unlinkFirst(Node f) { + // assert f == first && f != null; + final char element = f.item; + final Node next = f.next; + //f.item = ' '; + f.next = null; // help GC + first = next; + if (next == null) + last = null; + else + next.prev = null; + size--; + modCount++; + return element; + } + + /** + * Unlinks non-null last node l. + */ + private char unlinkLast(Node l) { + // assert l == last && l != null; + final char element = l.item; + final Node prev = l.prev; + //l.item = null; + l.prev = null; // help GC + last = prev; + if (prev == null) + first = null; + else + prev.next = null; + size--; + modCount++; + return element; + } + + /** + * Unlinks non-null node x. + */ + char unlink(Node x) { + // assert x != null; + final char element = x.item; + final Node next = x.next; + final Node prev = x.prev; + + if (prev == null) { + first = next; + } else { + prev.next = next; + x.prev = null; + } + + if (next == null) { + last = prev; + } else { + next.prev = prev; + x.next = null; + } + + //x.item = null; + size--; + modCount++; + return element; + } + + /** + * Returns the first element in this list. + * + * @return the first element in this list + * @throws NoSuchElementException if this list is empty + */ + public char getFirst() { + final Node f = first; + if (f == null) + throw new NoSuchElementException(); + return f.item; + } + + /** + * Returns the last element in this list. + * + * @return the last element in this list + * @throws NoSuchElementException if this list is empty + */ + public char getLast() { + final Node l = last; + if (l == null) + throw new NoSuchElementException(); + return l.item; + } + + /** + * Removes and returns the first element from this list. + * + * @return the first element from this list + * @throws NoSuchElementException if this list is empty + */ + public char removeFirst() { + final Node f = first; + if (f == null) + throw new NoSuchElementException(); + return unlinkFirst(f); + } + + /** + * Removes and returns the last element from this list. + * + * @return the last element from this list + * @throws NoSuchElementException if this list is empty + */ + public char removeLast() { + final Node l = last; + if (l == null) + throw new NoSuchElementException(); + return unlinkLast(l); + } + + /** + * Inserts the specified element at the beginning of this list. + * + * @param e the element to add + */ + public void addFirst(char e) { + linkFirst(e); + } + + /** + * Appends the specified element to the end of this list. + * + *

This method is equivalent to {@link #add}. + * + * @param e the element to add + */ + public void addLast(char e) { + linkLast(e); + } + + /** + * Returns the number of elements in this list. + * + * @return the number of elements in this list + */ + public int size() { + return size; + } + + /** + * Appends the specified element to the end of this list. + * + *

This method is equivalent to {@link #addLast}. + * + * @param e element to be appended to this list + * @return {@code true} (as specified by + */ + public boolean add(char e) { + linkLast(e); + return true; + } + + + + + /** + * Removes all of the elements from this list. + * The list will be empty after this call returns. + */ + public void clear() { + // Clearing all of the links between nodes is "unnecessary", but: + // - helps a generational GC if the discarded nodes inhabit + // more than one generation + // - is sure to free memory even if there is a reachable Iterator + for (Node x = first; x != null; ) { + Node next = x.next; + //x.item = null; + x.next = null; + x.prev = null; + x = next; + } + first = last = null; + size = 0; + modCount++; + } + + + // Positional Access Operations + + /** + * Returns the element at the specified position in this list. + * + * @param index index of the element to return + * @return the element at the specified position in this list + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public char get(int index) { + //checkElementIndex(index); + return node(index).item; + } + + + + /** + * Tells if the argument is the index of an existing element. + */ + private boolean isElementIndex(int index) { + return index >= 0 && index < size; + } + + /** + * Tells if the argument is the index of a valid position for an + * iterator or an add operation. + */ + private boolean isPositionIndex(int index) { + return index >= 0 && index <= size; + } + + /** + * Constructs an IndexOutOfBoundsException detail message. + * Of the many possible refactorings of the error handling code, + * this "outlining" performs best with both server and client VMs. + */ + private String outOfBoundsMsg(int index) { + return "Index: "+index+", Size: "+size; + } + + /*private void checkElementIndex(int index) { + if (!isElementIndex(index)) + throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); + }*/ + + /* private void checkPositionIndex(int index) { + if (!isPositionIndex(index)) + throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); + }*/ + + /** + * Returns the (non-null) Node at the specified element index. + */ + Node node(int index) { + // assert isElementIndex(index); + + if (index < (size >> 1)) { + Node x = first; + for (int i = 0; i < index; i++) + x = x.next; + return x; + } else { + Node x = last; + for (int i = size - 1; i > index; i--) + x = x.prev; + return x; + } + } + + + /** + * Retrieves and removes the head (first element) of this list. + * + * @return the head of this list, or {@code null} if this list is empty + * @since 1.5 + */ + public char poll() { + final Node f = first; + return (f == null) ? null : unlinkFirst(f); + } + + /** + * Retrieves and removes the head (first element) of this list. + * + * @return the head of this list + * @throws NoSuchElementException if this list is empty + * @since 1.5 + */ + public char remove() { + return removeFirst(); + } + + /** + * Adds the specified element as the tail (last element) of this list. + * + * @param e the element to add + * @since 1.5 + */ + public boolean offer(char e) { + return add(e); + } + + // Deque operations + /** + * Inserts the specified element at the front of this list. + * + * @param e the element to insert + * @since 1.6 + */ + public boolean offerFirst(char e) { + addFirst(e); + return true; + } + + /** + * Inserts the specified element at the end of this list. + * + * @param e the element to insert + * @since 1.6 + */ + public boolean offerLast(char e) { + addLast(e); + return true; + } + + /** + * Retrieves, but does not remove, the first element of this list, + * or returns {@code null} if this list is empty. + * + * @return the first element of this list, or {@code null} + * if this list is empty + * @since 1.6 + */ + public char peekFirst() { + final Node f = first; + return (f == null) ? null : f.item; + } + + public boolean isEmpty() { + return size() == 0; + } + + /** + * Retrieves, but does not remove, the last element of this list, + * or returns {@code null} if this list is empty. + * + * @return the last element of this list, or {@code null} + * if this list is empty + * @since 1.6 + */ + public char peekLast() { + final Node l = last; + return (l == null) ? null : l.item; + } + + /** + * Retrieves and removes the first element of this list, + * or returns {@code null} if this list is empty. + * + * @return the first element of this list, or {@code null} if + * this list is empty + * @since 1.6 + */ + public char pollFirst() { + final Node f = first; + return (f == null) ? null : unlinkFirst(f); + } + + /** + * Retrieves and removes the last element of this list, + * or returns {@code null} if this list is empty. + * + * @return the last element of this list, or {@code null} if + * this list is empty + * @since 1.6 + */ + public char pollLast() { + final Node l = last; + return (l == null) ? null : unlinkLast(l); + } + + /** + * Pushes an element onto the stack represented by this list. In other + * words, inserts the element at the front of this list. + * + *

This method is equivalent to {@link #addFirst}. + * + * @param e the element to push + * @since 1.6 + */ + public void push(char e) { + addFirst(e); + } + + /** + * Pops an element from the stack represented by this list. In other + * words, removes and returns the first element of this list. + * + *

This method is equivalent to {@link #removeFirst()}. + * + * @return the element at the front of this list (which is the top + * of the stack represented by this list) + * @throws NoSuchElementException if this list is empty + * @since 1.6 + */ + public char pop() { + return removeFirst(); + } + + private static class Node { + char item; + Node next; + Node prev; + + Node(Node prev, char element, Node next) { + this.item = element; + this.next = next; + this.prev = prev; + } + } + + + + /** + * Returns an array containing all of the elements in this list + * in proper sequence (from first to last element). + * + *

The returned array will be "safe" in that no references to it are + * maintained by this list. (In other words, this method must allocate + * a new array). The caller is thus free to modify the returned array. + * + *

This method acts as bridge between array-based and collection-based + * APIs. + * + * @return an array containing all of the elements in this list + * in proper sequence + */ + public char[] toArray() { + char[] result = new char[size]; + int i = 0; + for (Node x = first; x != null; x = x.next) + result[i++] = x.item; + return result; + } + + public char[] subArray(int start,int end){ + if (start < 0) + throw new ArrayIndexOutOfBoundsException(start); + if (end > size) + throw new StringIndexOutOfBoundsException(end); + if (start > end) + throw new ArrayIndexOutOfBoundsException(end - start); + int size = end-start; + char[] result = new char[size]; + int iStart = 0; + for (Node x = first; x != null && iStart < end; x = x.next){ + if(iStart >= start){ + result[iStart - start] = x.item; + } + iStart++; + } + return result; + } + + + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + for (Node x = first; x != null; x = x.next) + sb.append(x.item+","); + return "["+sb.toString()+"]"; + } + + /** + * 是否是文本 + * @return + */ + public boolean isText() { + boolean isNull = true; + for(char c : this.toArray()) { + if(c != SymbolSet.SYMBOL_NULL) { + isNull = false; + break; + } + } + return this.size() > 0 && !isNull; + } + + + private static final long serialVersionUID = 876323262645176354L; +} diff --git a/luqj-common/src/main/java/com/luqj/util/FileSystemUtil.java b/luqj-common/src/main/java/com/luqj/util/FileSystemUtil.java new file mode 100644 index 0000000..e27d14e --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/FileSystemUtil.java @@ -0,0 +1,137 @@ +package com.luqj.util; + + +import com.luqj.util.assertion.Assert; + +import java.io.File; +import java.io.FileFilter; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + + +public class FileSystemUtil { + + private static final char SYSTEM_SEPARATOR = File.separatorChar; + + private static final char WINDOWS_SEPARATOR = '\\'; + + /** + * 递归获取指定目录下的所有文件 + * @param dir + * @param filterDir 子目录是否返回在集合中 + * @return + */ + public static final List getAllFiles(File dir,boolean filterDir,FileFilter filter){ + Assert.logic(dir.isDirectory() && dir.canRead(),dir+"必须是目录且可读"); + List result = new ArrayList(); + File[] files = null; + if(filter != null){ + files = dir.listFiles(filter); + }else{ + files = dir.listFiles(); + } + for (File file : files) { + if(file.isDirectory()){ + if(filterDir){ + result.add(file); + } + result.addAll(getAllFiles(file, filterDir, filter)); + }else{ + result.add(file); + } + } + return result; + } + + /** + * 强制删除文件 + * 引用org.apache.commons.io.FileUtils代码 + * @param file + * @throws IOException + */ + public static void forceDelete(File file) throws IOException { + if (file.isDirectory()) { + deleteDirectory(file); + } else { + boolean filePresent = file.exists(); + if (!file.delete()) { + if (!filePresent){ + throw new FileNotFoundException("File does not exist: " + file); + } + String message = + "Unable to delete file: " + file; + throw new IOException(message); + } + } + } + + public static void deleteDirectory(File directory) throws IOException { + if (!directory.exists()) { + return; + } + + if (!isSymlink(directory)) { + cleanDirectory(directory); + } + + if (!directory.delete()) { + String message = + "Unable to delete directory " + directory + "."; + throw new IOException(message); + } + } + + public static boolean isSymlink(File file) throws IOException { + if (file == null) { + throw new NullPointerException("File must not be null"); + } + if (SYSTEM_SEPARATOR == WINDOWS_SEPARATOR) { + return false; + } + File fileInCanonicalDir = null; + if (file.getParent() == null) { + fileInCanonicalDir = file; + } else { + File canonicalDir = file.getParentFile().getCanonicalFile(); + fileInCanonicalDir = new File(canonicalDir, file.getName()); + } + + if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) { + return false; + } else { + return true; + } + } + + public static void cleanDirectory(File directory) throws IOException { + if (!directory.exists()) { + String message = directory + " does not exist"; + throw new IllegalArgumentException(message); + } + + if (!directory.isDirectory()) { + String message = directory + " is not a directory"; + throw new IllegalArgumentException(message); + } + + File[] files = directory.listFiles(); + if (files == null) { // null if security restricted + throw new IOException("Failed to list contents of " + directory); + } + + IOException exception = null; + for (File file : files) { + try { + forceDelete(file); + } catch (IOException ioe) { + exception = ioe; + } + } + + if (null != exception) { + throw exception; + } + } +} diff --git a/luqj-common/src/main/java/com/luqj/util/IdentificationNumberUtils.java b/luqj-common/src/main/java/com/luqj/util/IdentificationNumberUtils.java new file mode 100644 index 0000000..c3798c7 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/IdentificationNumberUtils.java @@ -0,0 +1,322 @@ +package com.luqj.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +/** + * Created: 2016/7/5. + * Author: Qiannan Lu + */ +public class IdentificationNumberUtils { + private final static Logger logger = LoggerFactory.getLogger(IdentificationNumberUtils.class); + + /** + * 获取身份证号的出生日期字符串 + * + * @param idCard 身份证号 + * @return 出生日期字符串 + */ + public static String birthday(String idCard) { + if (StringUtils.isBlank(idCard) + || idCard.length() <= 14) { + logger.error("传入身份证号{}位数不对!", idCard); + return null; + } + + return id15ToId18(idCard).substring(6, 14); + } + + /** + * 获取身份证号的出生日期 + * + * @param idCard 身份证号 + * @return 出生日期 + */ + public static Date birthDate(String idCard) { + + String birthDay = birthday(idCard); + + if (birthDay == null) return null; + try { + return new SimpleDateFormat("yyyyMMdd").parse(birthDay); + } catch (Exception e) { + logger.error("提取身份证号{}出生日期出错", idCard, e); + return null; + } + } + + /** + * 获取身份证号的年份信息 + * + * @param idCard 身份证号 + * @return 年份信息 + */ + public static String year(String idCard) { + Calendar calendar = getBirthDateCalendar(idCard); + + return calendar == null ? null : Integer.toString(calendar.get(Calendar.YEAR)); + } + + /** + * 获取身份证号的月份信息 从1月开始 + * + * @param idCard 身份证号 + * @return 月份信息 + */ + public static String month(String idCard) { + Calendar calendar = getBirthDateCalendar(idCard); + + return calendar == null ? null : Integer.toString(calendar.get(Calendar.MONTH) + 1); + } + + /** + * 获取身份证号的日期信息 月份中的日期 + * + * @param idCard 身份证号 + * @return 日期信息 + */ + public static String day(String idCard) { + Calendar calendar = getBirthDateCalendar(idCard); + + return calendar == null ? null : Integer.toString(calendar.get(Calendar.DATE)); + } + + /** + * 获取身份证号的日期信息 一年中的日期 + * + * @param idCard 身份证号 + * @return 日期信息 + */ + public static String dayOfYear(String idCard) { + + Calendar calendar = getBirthDateCalendar(idCard); + + return calendar == null ? null : Integer.toString(calendar.get(Calendar.DAY_OF_YEAR)); + } + + /** + * 获取身份证号的出生日期信息 + * + * @param idCard 身份证号 + * @return 出生日期 + */ + private static Calendar getBirthDateCalendar(String idCard) { + Date birthDate = birthDate(idCard); + + if (birthDate == null) return null; + + Calendar calendar = Calendar.getInstance(); + calendar.setTime(birthDate); + return calendar; + } + + /** + * 18位身份证转15位. + * + * @param id18 18为身份证号 + * @return 15位身份证号 + */ + public static String id18ToId15(String id18) { + return id18.substring(0, 6) + id18.substring(8, 17); + } + + /** + * 15位身份证转18位. + * + * @param id15 15位身份证号 + * @return 18位身份证号 + */ + public static String id15ToId18(String id15) { + int IdLength = id15.length(); + String id18; + switch (IdLength) { + case 15: + String serial = id15.substring(IdLength - 3); + if (serial.equals("996") || serial.equals("997") || serial.equals("998") || serial.equals("999")) { + id18 = id15.substring(0, 6) + "18" + id15.substring(IdLength - 9); + } else { + id18 = id15.substring(0, 6) + "19" + id15.substring(IdLength - 9); + } + id18 = id18 + getIdCheckBit(id18); + break; + case 17: + id18 = id15 + getIdCheckBit(id15); + break; + case 18: + id18 = id15; + break; + default: + id18 = id15; + } + return id18; + } + + /** + * 判断传入的字符串是否是身份证号,如果是18位 会判断最后一位标志位 + * 如果是15位则返回false + * + * @param idCard 身份证号 + * @return 是否是真是身份证号 + */ + public static boolean isValid(String idCard) { + + boolean isLooksLike = isLooksLike(idCard); + + if (isLooksLike && idCard.length() == 18) { + String x = getIdCheckBit(idCard); + if (x.equals("" + idCard.charAt(17))) + return true; + } + return false; + } + + /** + * 判断传入的字符串(15位或者18位)是否是身份证号,其他直接返回false + * @param idCard 身份证号 + * @return 是否是真是身份证号 + */ + public static boolean checkIsIdCard(String idCard) { + boolean isLooksLike = isLooksLike(idCard); + if (isLooksLike && idCard.length() == 18) { + String x = getIdCheckBit(idCard); + if (x.equals("" + idCard.charAt(17))) + return true; + } + if (isLooksLike && idCard.length() == 15) { + String x = getIdCheckBit(id15ToId18(idCard)); + if (x.equals("" + id15ToId18(idCard).charAt(17))) + return true; + } + return false; + } + + /** + * 判断传入的字符串是否像是身份证号,只会判断出身年月信息 + * + * @param idCard 身份证号 + * @return 是否像身份证号 + */ + public static boolean isLooksLike(String idCard) { + if (idCard.length() == 15) { + + String birthday = idCard.substring(6, 12); + + return isYear(birthday.substring(0, 2)) && isMonth(birthday.substring(2, 4)) && isDay(birthday.substring(4, 6)); + } else if (idCard.length() == 18) { + String birthday = idCard.substring(6, 14); + return isYear(birthday.substring(0, 4)) && isMonth(birthday.substring(4, 6)) && isDay(birthday.substring(6, 8)); + } + return false; + } + + /** + * 判断数字是否符合年份 + * + * @param year 数字 + */ + private static boolean isYear(String year) { + if (year.length() == 4) { + try { + int y = Integer.parseInt(year); + if (y < 1900 || y > 2100) { + return false; + } + } catch (Exception e) { + return false; + } + } + return true; + } + + /** + * 判断数字是否符合月份 + * + * @param month 数字 + */ + private static boolean isMonth(String month) { + try { + int m = Integer.parseInt(month); + if (m < 1 || m > 12) { + return false; + } + } catch (Exception e) { + return false; + } + return true; + } + + /** + * 判断数字是否符合日期 + * + * @param day 数字 + */ + private static boolean isDay(String day) { + try { + int d = Integer.parseInt(day); + if (d < 1 || d > 31) { + return false; + } + } catch (Exception e) { + return false; + } + return true; + } + + /** + * 获取18位身份证号的校验位 + * + * @param id18 18位身份证号 + * @return 校验位 + */ + public static String getIdCheckBit(String id18) { + String[] strCheckChar = new String[11]; + int[] nWeight = new int[18]; + strCheckChar[0] = "1"; + strCheckChar[1] = "0"; + strCheckChar[2] = "X"; + strCheckChar[3] = "9"; + strCheckChar[4] = "8"; + strCheckChar[5] = "7"; + strCheckChar[6] = "6"; + strCheckChar[7] = "5"; + strCheckChar[8] = "4"; + strCheckChar[9] = "3"; + strCheckChar[10] = "2"; + + nWeight[0] = 7; + nWeight[1] = 9; + nWeight[2] = 10; + nWeight[3] = 5; + nWeight[4] = 8; + nWeight[5] = 4; + nWeight[6] = 2; + nWeight[7] = 1; + nWeight[8] = 6; + nWeight[9] = 3; + nWeight[10] = 7; + nWeight[11] = 9; + nWeight[12] = 10; + nWeight[13] = 5; + nWeight[14] = 8; + nWeight[15] = 4; + nWeight[16] = 2; + nWeight[17] = 1; + + int sumMulti = 0; + for (int i = 0; i <= 16; i++) { + String ch = id18.substring(i, i + 1); + sumMulti = sumMulti + (Integer.parseInt(ch) * nWeight[i]); + } + int resultMod = sumMulti % 11; + return strCheckChar[resultMod]; + } + + + public static void main(String[] args) { + + } +} diff --git a/luqj-common/src/main/java/com/luqj/util/LinkedMultiValueMap.java b/luqj-common/src/main/java/com/luqj/util/LinkedMultiValueMap.java new file mode 100644 index 0000000..a5a6c0f --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/LinkedMultiValueMap.java @@ -0,0 +1,169 @@ +/* + * Copyright 2002-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.luqj.util; + +import java.io.Serializable; +import java.util.*; + +/** + * Simple implementation of {@link MultiValueMap} that wraps a {@link LinkedHashMap}, + * storing multiple values in a {@link LinkedList}. + * + *

This Map implementation is generally not thread-safe. It is primarily designed + * for data structures exposed from request objects, for use in a single thread only. + * + * @author Arjen Poutsma + * @author Juergen Hoeller + * @since 3.0 + */ +public class LinkedMultiValueMap implements MultiValueMap, Serializable { + + private static final long serialVersionUID = 3801124242820219131L; + + private final Map> targetMap; + + + /** + * Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap}. + */ + public LinkedMultiValueMap() { + this.targetMap = new LinkedHashMap>(); + } + + /** + * Create a new LinkedMultiValueMap that wraps a {@link LinkedHashMap} + * with the given initial capacity. + * @param initialCapacity the initial capacity + */ + public LinkedMultiValueMap(int initialCapacity) { + this.targetMap = new LinkedHashMap>(initialCapacity); + } + + /** + * Copy constructor: Create a new LinkedMultiValueMap with the same mappings + * as the specified Map. + * @param otherMap the Map whose mappings are to be placed in this Map + */ + public LinkedMultiValueMap(Map> otherMap) { + this.targetMap = new LinkedHashMap>(otherMap); + } + + + // MultiValueMap implementation + + public void add(K key, V value) { + List values = this.targetMap.get(key); + if (values == null) { + values = new LinkedList(); + this.targetMap.put(key, values); + } + values.add(value); + } + + public V getFirst(K key) { + List values = this.targetMap.get(key); + return (values != null ? values.get(0) : null); + } + + public void set(K key, V value) { + List values = new LinkedList(); + values.add(value); + this.targetMap.put(key, values); + } + + public void setAll(Map values) { + for (Entry entry : values.entrySet()) { + set(entry.getKey(), entry.getValue()); + } + } + + public Map toSingleValueMap() { + LinkedHashMap singleValueMap = new LinkedHashMap(this.targetMap.size()); + for (Entry> entry : targetMap.entrySet()) { + singleValueMap.put(entry.getKey(), entry.getValue().get(0)); + } + return singleValueMap; + } + + + // Map implementation + + public int size() { + return this.targetMap.size(); + } + + public boolean isEmpty() { + return this.targetMap.isEmpty(); + } + + public boolean containsKey(Object key) { + return this.targetMap.containsKey(key); + } + + public boolean containsValue(Object value) { + return this.targetMap.containsValue(value); + } + + public List get(Object key) { + return this.targetMap.get(key); + } + + public List put(K key, List value) { + return this.targetMap.put(key, value); + } + + public List remove(Object key) { + return this.targetMap.remove(key); + } + + public void putAll(Map> m) { + this.targetMap.putAll(m); + } + + public void clear() { + this.targetMap.clear(); + } + + public Set keySet() { + return this.targetMap.keySet(); + } + + public Collection> values() { + return this.targetMap.values(); + } + + public Set>> entrySet() { + return this.targetMap.entrySet(); + } + + + @Override + public boolean equals(Object obj) { + return this.targetMap.equals(obj); + } + + @Override + public int hashCode() { + return this.targetMap.hashCode(); + } + + @Override + public String toString() { + return this.targetMap.toString(); + } + +} diff --git a/luqj-common/src/main/java/com/luqj/util/MapSortUtil.java b/luqj-common/src/main/java/com/luqj/util/MapSortUtil.java new file mode 100644 index 0000000..f03a258 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/MapSortUtil.java @@ -0,0 +1,153 @@ +package com.luqj.util; + +import java.util.*; + +/** + * Created by lucheng on 2017/8/23. + */ +public class MapSortUtil { + /** + * 使用 Map按key进行排序 + * + * @param map + * @return + */ + public static TreeMap sortMapByKey(Map map, String direction) { + if (map == null || map.isEmpty()) { + return null; + } + + TreeMap sortMap = new TreeMap( + new MapKeyComparator(direction)); + + sortMap.putAll(map); + + return sortMap; + } + + + /** + * 使用 Map按value进行排序 + * @param oriMap + * @param direction + * @return + */ + public static Map sortMapByValue(Map oriMap, String direction) { + if (oriMap == null || oriMap.isEmpty()) { + return null; + } + Map sortedMap = new LinkedHashMap(); + List> entryList = new ArrayList>( + oriMap.entrySet()); + Collections.sort(entryList, new MapValueComparator(direction)); + + Iterator> iter = entryList.iterator(); + Map.Entry tmpEntry = null; + while (iter.hasNext()) { + tmpEntry = iter.next(); + sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue()); + } + return sortedMap; + } + + /** + * 返回某个index对应的值 + * + * @param map + * @param index + * @return + */ + public static Double getKeyByIndex(Map map, int index) { + int sumCount = 0; + Double result = null; + for (Map.Entry newEntry : map.entrySet()) { + Double number = newEntry.getKey(); + Integer count = newEntry.getValue(); + sumCount += count; + if (index <= sumCount) { + result = number; + break; + } + } + return result; + } + + public static class MapKeyComparator implements Comparator { + + private String direction; + + public MapKeyComparator(String direction) { + this.direction = direction; + } + + @Override + public int compare(Double o1, Double o2) { + if ("DESC".equals(direction)) + return o2.compareTo(o1); // 降序 + else + return o1.compareTo(o2); + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + } + + public static class MapValueComparator implements Comparator> { + + private String direction; + + public MapValueComparator(String direction) { + this.direction = direction; + } + + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + if ("DESC".equals(direction)) + return o2.getValue().compareTo(o1.getValue()); // 降序 + else + return o1.getValue().compareTo(o2.getValue()); + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + } + + + public static void main(String args[]) { + Map map = new HashMap<>(); + map.put(100.21, 10); + map.put(120.21, 20); + map.put(104.21, 30); + map.put(99.32, 70); + map.put(114.22, 45); + + TreeMap newMap = sortMapByKey(map, "DESC"); + System.out.println("after sortByKey:"); + for (Map.Entry entry : newMap.entrySet()) { + System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue()); + } + System.out.println("lastKey:" + newMap.lastKey()); + System.out.println("lastEntry:" + newMap.lastEntry().getValue()); + + Map valueMap = sortMapByValue(map, "DESC"); + System.out.println("---------------------------"); + System.out.println("after sortByValue:"); + for (Map.Entry entry : valueMap.entrySet()) { + System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue()); + } + System.out.println("firstKey:" + valueMap.entrySet().iterator().next().getKey()); + System.out.println("firstValue:" + valueMap.entrySet().iterator().next().getValue()); + } + +} diff --git a/luqj-common/src/main/java/com/luqj/util/MultiValueMap.java b/luqj-common/src/main/java/com/luqj/util/MultiValueMap.java new file mode 100644 index 0000000..f3fffc5 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/MultiValueMap.java @@ -0,0 +1,63 @@ +/* + * Copyright 2002-2009 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.luqj.util; + +import java.util.List; +import java.util.Map; + +/** + * Extension of the {@code Map} interface that stores multiple values. + * + * @author Arjen Poutsma + * @since 3.0 + */ +public interface MultiValueMap extends Map> { + + /** + * Return the first value for the given key. + * @param key the key + * @return the first value for the specified key, or null + */ + V getFirst(K key); + + /** + * Add the given single value to the current list of values for the given key. + * @param key the key + * @param value the value to be added + */ + void add(K key, V value); + + /** + * Set the given single value under the given key. + * @param key the key + * @param value the value to set + */ + void set(K key, V value); + + /** + * Set the given values under. + * @param values the values. + */ + void setAll(Map values); + + /** + * Returns the first values contained in this {@code MultiValueMap}. + * @return a single value representation of this map + */ + Map toSingleValueMap(); + +} diff --git a/luqj-common/src/main/java/com/luqj/util/NumFormat.java b/luqj-common/src/main/java/com/luqj/util/NumFormat.java new file mode 100644 index 0000000..85a3949 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/NumFormat.java @@ -0,0 +1,460 @@ +package com.luqj.util; + + + +import com.luqj.util.assertion.Assert; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Date; +import java.sql.Timestamp; +import java.text.DecimalFormat; + +public abstract class NumFormat { + + /** + * 设置double类型的精确度 + * @param scale 小数点后保留的位数 + * @param number 要精确度的值 + * @return + */ + public static double setScale(double number,int scale){ + if(Double.isNaN(number)){ + return 0; + } + if(Double.isInfinite(number)){ + return 0; + } + return new BigDecimal(number).setScale(scale,BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + /** + * 将NUMBER转换成String如果value为Null则返回空字符串 + * @param value + * @return + * @author:lwei + */ + public static String toString(Number value){ + return value == null ? "" : value.toString(); + } + + /** + * 将Date转换成Long + * @param value + * @return + */ + public static long $Date(Object value) { + if(value == null){ + return 0; + } + if(value instanceof Date) { + return ((Date) value).getTime(); + } + return $Long(value.toString()); + } + + /** + * 将Timestamp转换成Long + * @param value + * @return + */ + public static long $Timestamp(Object value) { + if(value == null){ + return 0; + } + if(value instanceof Timestamp) { + return ((Timestamp) value).getTime(); + } + return $Long(value.toString()); + } + + /** + * 将类型转换为LONG + * @param value + * @return + */ + public static long $Long(Long value){ + return value != null ? value.longValue() : 0; + } + + /** + * 将类型转换为LONG + * @param value + * @return + */ + public static long $Long(String value){ + return Validator.hasText(value) ? Long.valueOf(value.trim()) : 0; + } + + /** + * 将类型转换为LONG + * @param value + * @return + */ + public static long $Long(Object value){ + if(value == null){ + return 0; + } + if(value instanceof Long) { + return (Long)value; + } + return $Long(value.toString()); + } + + public static long $Long(BigDecimal value){ + return value != null ? value.longValue() : 0; + } + + public static long $Long(BigInteger value){ + return value != null ? value.longValue() : 0; + } + + + public static long $Long(Double value){ + return value != null ? value.longValue() : 0; + } + + public static int $Intger(Integer value){ + return value != null ? value.intValue() : 0; + } + + public static int $Intger(Double value){ + return value != null ? value.intValue() : 0; + } + + public static int $Intger(String value){ + return Validator.hasText(value) ? Integer.valueOf(value.trim()) : 0; + } + + public static int $Intger(Object value){ + if(value == null){ + return 0; + } + if(value instanceof Integer) { + return (Integer)value; + } + return $Intger(value.toString()); + } + + public static int $Intger(BigDecimal value){ + return value != null ? value.intValue() : 0; + } + + public static int $Intger(BigInteger value){ + return value != null ? value.intValue() : 0; + } + + + public static double $Double(Double value){ + return value != null ? value.doubleValue() : 0; + } + + public static double $Double(String value){ + return Validator.hasText(value) ? Double.valueOf(value.trim()) : 0; + } + + public static double $Double(BigDecimal value){ + return value != null ? value.doubleValue() : 0; + } + + public static double $Double(BigInteger value){ + return value != null ? value.doubleValue() : 0; + } + + public static double $Double(Object value){ + if(value == null){ + return 0; + } + if(value instanceof Double) { + return (Double)value; + } + return $Double(value.toString()); + } + + + + + public static float $Float(Float value){ + return value != null ? value.floatValue() : 0; + } + + public static double $Float(String value){ + return Validator.hasText(value) ? Float.valueOf(value.trim()) : 0; + } + + public static double $Float(BigDecimal value){ + return value != null ? value.floatValue() : 0; + } + + public static double $Float(BigInteger value){ + return value != null ? value.floatValue() : 0; + } + + public static double $Float(Object value){ + if(value == null){ + return 0; + } + if(value instanceof Float) { + return (Float)value; + } + return $Float(value.toString()); + } + + public static short $Short(Short value){ + return value != null ? value.shortValue() : 0; + } + + public static short $Short(String value){ + return Validator.hasText(value) ? Short.valueOf(value.trim()) : 0; + } + + public static short $Short(BigDecimal value){ + return value != null ? value.shortValue() : 0; + } + + public static short $Short(BigInteger value){ + return value != null ? value.shortValue() : 0; + } + + public static short $Short(Object value){ + if(value == null){ + return 0; + } + if(value instanceof Short) { + return (Short)value; + } + return $Short(value.toString()); + } + + public static byte $Byte(Byte value){ + return value != null ? value.byteValue() : 0; + } + + public static byte $Byte(BigDecimal value){ + return value != null ? value.byteValue() : 0; + } + + public static byte $Byte(BigInteger value){ + return value != null ? value.byteValue() : 0; + } + + public static byte $Byte(String value){ + return Validator.hasText(value) ? Byte.valueOf(value.trim()) : 0; + } + + public static byte $Byte(Object value){ + return Validator.notNull(value) ? $Byte(value.toString()) : 0; + } + + /** + * 将指定的Number对象转换为指定的类型对象 + * + * @param number the number to convert + * @return 目标类型的对象 + */ + public static Number convertNumber(Number number, Class targetClass) + throws IllegalArgumentException { + Assert.notNull(number, "Number对象不可以为null"); + Assert.notNull(targetClass, "Number目标类对象参数不可以为null"); + if (targetClass.isInstance(number)) { + return number; + }else if (targetClass.equals(Byte.class)) { + long value = number.longValue(); + if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { + raiseOverflowException(number, targetClass); + } + return new Byte(number.byteValue()); + }else if (targetClass.equals(Short.class)) { + long value = number.longValue(); + if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { + raiseOverflowException(number, targetClass); + } + return new Short(number.shortValue()); + }else if (targetClass.equals(Integer.class)) { + long value = number.longValue(); + if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { + raiseOverflowException(number, targetClass); + } + return new Integer(number.intValue()); + }else if (targetClass.equals(Long.class)) { + return new Long(number.longValue()); + }else if (targetClass.equals(Float.class)) { + return new Float(number.floatValue()); + }else if (targetClass.equals(Double.class)) { + return new Double(number.doubleValue()); + }else if (targetClass.equals(BigInteger.class)) { + return BigInteger.valueOf(number.longValue()); + }else if (targetClass.equals(BigDecimal.class)) { + // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double) + // (see BigDecimal javadoc for details) + return new BigDecimal(number.toString()); + }else { + throw new IllegalArgumentException("无法将值为 [" + number + "] 类型为 [" + + number.getClass().getName() + "] 的对象转换为 [" + targetClass.getName() + "]"); + } + } + + /** + * 如果指定的值超过了指定的类型的值所能容纳的最大或最小值将抛该异常 + * @param number 需要转换的值 + * @param targetClass 目标对象的类型 + */ + private static void raiseOverflowException(Number number, Class targetClass) { + throw new IllegalArgumentException("无法将值为 [" + number + "] 类型为 [" + + number.getClass().getName() + "] 的对象转换为 [" + targetClass.getName() + "]: 值超过了目标对象的值得范围"); + } + + /** + * 将字符串格式转换为指定的目标类的Number对象 + * @param text 需要转换的字符串 + * @param targetClass 目标类型 + * @return 目标类型的对象 + * @throws IllegalArgumentException 如果不支持指定的目标类型的话将抛该异常 + */ + public static Number parseNumber(String text,Class targetClass) { + Assert.notNull(text, "字符串参数不可以为null"); + Assert.notNull(targetClass, "Number目标类对象参数不可以为null"); + String trimmed = text.trim(); + if (targetClass.equals(Byte.class)) { + return Byte.decode(trimmed); + } + else if (targetClass.equals(Short.class)) { + return Short.decode(trimmed); + } + else if (targetClass.equals(Integer.class)) { + return Integer.decode(trimmed); + } + else if (targetClass.equals(Long.class)) { + return Long.decode(trimmed); + } + else if (targetClass.equals(Float.class)) { + return Float.valueOf(trimmed); + } + else if (targetClass.equals(Double.class)) { + return Double.valueOf(trimmed); + } + else if (targetClass.equals(BigInteger.class)) { + return decodeBigInteger(trimmed); + } + else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) { + return new BigDecimal(trimmed); + } + else { + throw new IllegalArgumentException( + "转换失败! String [" + text + "] to target class [" + targetClass.getName() + "]"); + } + } + + /** + * 将字符串转换为BigInteger + * + *

指定的字符串如果是可以是负数表示或者十六进制,八进制表示 + * 负数表示前面加-,十六进制表示前面加0x 0X #,八进制表示前面加0

+ * @param value 要转换的字符串 + * @return 返回BigInteger对象 + * @see BigInteger#BigInteger(String, int) + */ + private static BigInteger decodeBigInteger(String value) { + int radix = 10;//基数 + int index = 0;//串索引 + boolean negative = false;//判断是否为负数 + if (value.startsWith("-")) { + negative = true; + index++; + } + if (value.startsWith("0x", index) || value.startsWith("0X", index)) { + index += 2; + radix = 16; + } + else if (value.startsWith("#", index)) { + index++; + radix = 16; + } + else if (value.startsWith("0", index) && value.length() > 1 + index) { + index++; + radix = 8; + } + BigInteger result = new BigInteger(value.substring(index), radix); + return (negative ? result.negate() : result); + } + + + /** + * + * @param number + * @return + */ + public static String setString(double number){ + return number==0?"  ":String.valueOf(number); + } + + /** + * 两个Double类型相加后返回Double类型(如果其中一个为NULL则视为0) + * @param value1 + * @param value2 + * @return + */ + public static Double addValue(Double value1,Double value2){ + return $Double(value1)+$Double(value2); + } + + /** + * 两个Long类型相加后返回Long类型(如果其中一个为NULL则视为0) + * @param value1 + * @param value2 + * @return + */ + public static Long addValue(Long value1,Long value2){ + return $Long(value1)+$Long(value2); + } + + /** + * 将double类型的数据改为非科学记数法表示 + * @param unFormatedNumber + * @return + */ + public static String formateNonScience(double unFormatedNumber){ + DecimalFormat format = new DecimalFormat("#0.000"); + return format.format(unFormatedNumber); + } + + + + + + public static Number parseNum(Class targetClass,Number v){ + + if(targetClass.equals(Byte.class)){ + return Byte.valueOf(v.byteValue()); + } + else if (targetClass.equals(Short.class)) { + return Short.valueOf(v.shortValue()); + } + else if (targetClass.equals(Integer.class)) { + return Integer.valueOf(v.intValue()); + } + else if (targetClass.equals(Long.class)) { + return Long.valueOf(v.longValue()); + } + else if (targetClass.equals(Float.class)) { + return Float.valueOf(0); + } + else if (targetClass.equals(Double.class)) { + return Double.valueOf(v.doubleValue()); + } + else if (targetClass.equals(BigInteger.class)) { + return new BigInteger(String.valueOf(v.longValue())); + } + else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) { + return new BigDecimal(v.doubleValue()); + } + else { + throw new IllegalArgumentException( + "类型[" + targetClass.getName() + "],无法初始化0值"); + } + } + + + + +} diff --git a/luqj-common/src/main/java/com/luqj/util/StringUtils.java b/luqj-common/src/main/java/com/luqj/util/StringUtils.java new file mode 100644 index 0000000..4cbe2a5 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/StringUtils.java @@ -0,0 +1,1869 @@ +/** + * 版权所有:厦门市巨龙软件工程有限公司 + * Copyright 2009 Xiamen Dragon Software Eng. Co. Ltd. + * All right reserved. + *==================================================== + * 文件名称: StringUtils.java + * 修订记录: + * No 日期 作者(操作:具体内容) + * 1. Mar 3, 2009 何志昭(创建:创建文件) + * 2004-11-16 陈雄华更改了splitString方法、增加了toVisualString方法、增加了subStringCount方法 + * 2. Mar 3, 2009 根据dragonsoft_checks.xml规范进行调整 + *==================================================== + * 类描述: + * + */ +package com.luqj.util; + +import java.security.MessageDigest; +import java.sql.Date; +import java.sql.Time; +import java.sql.Timestamp; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +/** + *

+ * 字符串处理工具类.
+ * <blockquote>
+ * <b>数字格式化样式</b>
+ * <table border=0 cellspacing=3 cellpadding=0 width="90%">
+ * 
+ *      
+ * Symbol
+ * 
+ *      
+ * Location
+ * 
+ *      
+ * Localized
+ * 
+ *      
+ * Meaning
+ * 
+ *  
+ *  
+ *      
+ * 0
+ *      
+ * Number
+ * 
+ *      
+ * Yes
+ * 
+ *      
+ * Digit
+ * 
+ *  
+ *  
+ *      
+ * #
+ * 
+ *      
+ * Number
+ * 
+ *      
+ * Yes
+ * 
+ *      
+ * Digit, zero shows as absent
+ * 
+ *  
+ *  
+ *      
+ * .
+ * 
+ *      
+ * Number
+ * 
+ *      
+ * Yes
+ * 
+ *      
+ * Decimal separator or monetary decimal separator
+ * 
+ *  
+ *  
+ *      
+ * -
+ * 
+ *      
+ * Number
+ * 
+ *      
+ * Yes
+ * 
+ *      
+ * Minus sign
+ * 
+ *  
+ *  
+ *      
+ * ,
+ * 
+ *      
+ * Number
+ * 
+ *      
+ * Yes
+ * 
+ *      
+ * Grouping separator
+ * 
+ *  
+ *  
+ *      
+ * E
+ *      
+ * Number
+ * 
+ *      
+ * Yes
+ * 
+ *      
+ * Separates mantissa and exponent in scientific notation.
+ * 
+ * Need not be quoted in prefix or suffix.
+ * 
+ *  
+ *  
+ *      
+ * ;
+ * 
+ *      
+ * Subpattern boundary
+ * 
+ *      
+ * Yes
+ * 
+ *      
+ * Separates positive and negative subpatterns
+ * 
+ *  
+ *  
+ *      
+ * %
+ * 
+ *      
+ * Prefix or suffix
+ * 
+ *      
+ * Yes
+ * 
+ *      
+ * Multiply by 100 and show as percentage
+ * 
+ *  
+ *  
+ *      
+ *  \u2030
+ * 
+ *      
+ * Prefix or suffix
+ * 
+ *      
+ * Yes
+ * 
+ *      
+ * Multiply by 1000 and show as per mille
+ * 
+ *  
+ *  
+ *      
+ * ¤
+ *  (
+ * 
+ * \u00A4
+ * 
+ * )
+ * 
+ *      
+ * Prefix or suffix
+ * 
+ *      
+ * No
+ * 
+ *      
+ * Currency sign, replaced by currency symbol.  If
+ *          doubled, replaced by international currency symbol.
+ *          If present in a pattern, the monetary decimal separator
+ *          is used instead of the decimal separator.
+ * 
+ *  
+ *  
+ *      
+ * '
+ * 
+ *      
+ * Prefix or suffix
+ * 
+ *      
+ * No
+ * 
+ *      
+ * Used to quote special characters in a prefix or suffix,
+ *          for example,
+ * 
+ * "'#'#"
+ * 
+ *  formats 123 to
+ * 
+ * "#123"
+ * 
+ * .  To create a single quote
+ *          itself, use two in a row:
+ * 
+ * "# o''clock"
+ * 
+ * .
+ * 
+ *   
+ * </table>
+ *
+ * <b>符号(Symbol)通常是组合在一起使用的,例如下表</b>
+ * <table border=0 cellspacing=3 cellpadding=0 width="90%">
+ * 
+ *         
+ * 输入
+ * 
+ *         
+ * 格式
+ * 
+ *         
+ * 输出
+ * 
+ *     
+ *     
+ *         
+ * 1234.123456
+ * 
+ *         
+ * 0
+ *         
+ * 1234
+ * 
+ *     
+ *     
+ *         
+ * 0.00
+ * 
+ *         
+ * 1234.12
+ * 
+ *     
+ *     
+ *         
+ * 0.###
+ * 
+ *         
+ * 1234.123
+ * 
+ *     
+ *     
+ *         
+ * 0.0000
+ * 
+ *         
+ * 1234.1235
+ * 
+ *     
+ *     
+ *         
+ * 00000000.00
+ * 
+ *         
+ * 00001234.12
+ * 
+ *     
+ *     
+ *         
+ * ,000.00
+ * 
+ *         
+ * 1,234.12
+ * 
+ *     
+ *     
+ *         
+ * ,00.00000000
+ * 
+ *         
+ * 12,34.12345600
+ * 
+ *     
+ *     
+ *         
+ * 0.00%
+ * 
+ *         
+ * 123412.35%
+ * 
+ *     
+ *     
+ *         
+ * 1234.100056
+ * 
+ *         
+ * 0
+ *         
+ * 1234
+ * 
+ *     
+ *     
+ *         
+ * 0.00
+ * 
+ *         
+ * 1234.10
+ * 
+ *     
+ *     
+ *         
+ * 0.##
+ * 
+ *         
+ * 1234.1
+ * 
+ *     
+ *     
+ *         
+ * (人民币),000.00
+ * 
+ *         
+ * (人民币)1,234.10
+ * 
+ *     
+ *     
+ *         
+ * ,000.########
+ * 
+ *         
+ * 1,234.100056
+ * 
+ *     
+ * </table>
+ * 
+ * 注:0与#功能类似,区别在于用0表示位数时,格式化后的首尾的0会显示,而用#表示位数时,首尾的0不显示 + * </blockquote> + *
+ * + *
+ *
+ *
JDK版本:
+ *
+ *
1.4
+ *
+ * + * @author 涂传滨,伊新煦,陈雄华,谢计生 + * @version 1.0 + * @since 1.0 + * @see DecimalFormat + */ +public final class StringUtils { + + /** 字符长度 */ + public static final int CHAR_LEN = 1; + + /** 字节长度 */ + public static final int BYTE_LEN = 2; + + final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");; + + public static boolean notBlank(String str) { + return !isBlank(str); + } + + public static boolean notBlank(String... strings) { + if (strings == null || strings.length == 0) { + return false; + } + for (String str : strings) { + if (isBlank(str)) { + return false; + } + } + return true; + } + + public static boolean hasText(String text) { + if (text == null) + return false; + for (int i = 0; i < text.length(); i++) { + if (!Character.isWhitespace(text.charAt(i))) + return true; + } + return false; + } + + public static String parseDateToString(Object obj){ + + String dateStr = null; + + if(obj == null){ + return null; + } + + if(obj.getClass().getName().equals("java.sql.Date")){ + Date date = (Date) obj; + return String.valueOf(date.getTime()); + }else if(obj.getClass().getName().equals("java.sql.Timestamp")){ + Timestamp date = (Timestamp) obj; + return String.valueOf(date.getTime()); + }else if(obj.getClass().getName().equals("java.sql.Time")){ + Time date = (Time) obj; + return String.valueOf(date.getTime()); + }else{ + return String.valueOf(obj); + } + + /*if(obj.getClass().getName().equals("java.sql.Date")|| + obj.getClass().getName().equals("java.sql.Timestamp")|| + obj.getClass().getName().equals("java.sql.Time")){ + try { + Date date = (Date) obj; + date.getTime(); + dateStr = DATE_FORMAT.format(obj); + } catch (ArrayIndexOutOfBoundsException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + logger.error("出现异常的数据"+obj); + throw new ArrayIndexOutOfBoundsException("数组越界"+obj); + } + }else{ + return (String)obj; + } + */ + //return dateStr; + + } + + + public static String uuid(){ + return UUID.randomUUID().toString().replaceAll("-", ""); + } + + + public static String lowerFirst(String v){ + return v.replaceFirst(v.substring(0,1), v.substring(0,1).toLowerCase()); + } + + public static String upFirst(String v){ + return v.replaceFirst(v.substring(0,1), v.substring(0,1).toUpperCase()); + } + + /** + * 数字字符串转化为整数 + * + * @param intStr + * String 待转化的数字字符串 + * @param intDef + * int 当intStr为空或空字符串时返回的缺省值 + * @return int 返回由数字字符串转化成的数字,当intStr为空或空字符串时,返回缺省值intDef + */ + public static int getInt(String intStr, int intDef) { + if (null == intStr || "".equals(intStr.trim())) { + return intDef; + } + + int intRetu = intDef; + + Double db = new Double(intStr); + intRetu = db.intValue(); + return intRetu; + } + + /** + * 数字字符串转化为整数,在转化时发生异常,则返回0 + * + * @param intStr + * String 待转化的数字字符串 + * @return int 返回由数字字符串转化成的整数,当intStr为空或空字符串时,返回0 + */ + public static int getInt(String intStr) { + return getInt(intStr, 0); + } + + /** + * 数字字符串转化为双精数字 + * + * @param dbstr + * String 待转化的数字字符串 + * @param dbDef + * double 当dbstr为空或空字符串时返回的缺省值 + * @return double 返回由数字字符串转化成的数字,当dbstr为空或空字符串时,则返回缺省值dbDef + */ + public static double getDouble(String dbstr, double dbDef) { + + if (null == dbstr || "".equals(dbstr.trim())) { + return dbDef; + } + double dbRetu = dbDef; + Double db = new Double(dbstr); + dbRetu = db.doubleValue(); + return dbRetu; + } + + /** + * 数字字符串转化为双精数字,在转化时发生异常,则返回0 + * + * @param dbstr + * String 待转化的数字字符串 + * @return double 返回由数字字符串转化成的数字,当dbstr为空或空字符串时,则返回0。 + */ + public static double getDouble(String dbstr) { + return getDouble(dbstr, 0); + } + + /** + * 数字字符串转化为长整型 + * + * @param longstr + * String 待转化的数字字符串 + * @param longDef + * long 当longstr为空或空字符串时返回的缺省值 + * @return long 返回由数字字符串转化成的数字,当longstr为空或空字符串时,则返回缺省值longDef + */ + public static long getLong(String longstr, long longDef) { + if (null == longstr || "".equals(longstr.trim())) { + return longDef; + } + long longRetu = longDef; + + Double db = new Double(longstr); + longRetu = db.longValue(); + + return longRetu; + } + + /** + * 数字字符串转化为长整型,在转化时发生异常,则返回0 + * + * @param longstr + * String 待转化的数字字符串 + * @return long 返回由数字字符串转化成的数字,当longstr为空或空字符串时,则返回0。 + */ + public static long getLong(String longstr) { + return getLong(longstr, 0); + } + + /** + * 字符串转化为布尔型 + * + * @param booleanstr + * String 待转化的字符串 + * @param booleanDef + * boolean 当字符串为空或为null时返回的值 + * @return boolean 返回转化化的布尔值,只有当booleanstr为字符串“true”(忽略大小写)时才返回true,
+ * 如果在转化时发生异常(只有为null时),则返回缺省值booleanDef + */ + public static boolean getBoolean(String booleanstr, boolean booleanDef) { + if (null == booleanstr) { + return booleanDef; + } + boolean booleanRetu = booleanDef; + if ("true".equalsIgnoreCase(booleanstr.trim())) { + booleanRetu = true; + } + + return booleanRetu; + } + + /** + * 字符串转化为布尔型.
+ * 只有当booleanstr为字符串“true”(忽略大小写)时才返回true,其它都返回false, 包括booleanstr为null + * + * @param booleanstr + * String 待转化的字符串 + * @return boolean 返回转化化的布尔值, + */ + public static boolean getBoolean(String booleanstr) { + return getBoolean(booleanstr, false); + } + + /** + * 双精数字格式化,返回字符串 + * + * @param db + * double 待格式化的双精数字 + * @param fmt + * String 格式化样式,参见类说明,
+ * fmt非法时,db将按原样转化为字符串后返回。 + * @return String 格式化后的数字,以字符串方式返回 + */ + public static String getNumFormat(double db, String fmt) { + String retu = ""; + if (null == fmt || "".equals(fmt.trim())) { + return Double.toString(db); + } + + try { + DecimalFormat decimalformat = new DecimalFormat(fmt); + retu = decimalformat.format(db); + decimalformat = null; + } catch (IllegalArgumentException iaex) { + // ialog.error(ex.getMessage()); + retu = Double.toString(db); + } + return retu; + } + + /** + * 双精数字格式化,把入参中的双精数格式化为带两位小数的数字字符串 + * + * @param db + * double 待格式化的双精数字 + * @return String 格式化为两位小数的数字字符串 + */ + public static String getNumFormat(double db) { + return getNumFormat(db, "0.00"); + } + + /** + * 数字字符串格式化,返回字符串 + * + * @param numStr + * String 待格式化的数字字符串,
+ * 如果numStr参数不是的数字则不进行格式化,按原样返回 + * @param fmt + * String 格式化样式,参见类说明
+ * fmt非法时,将把numStr按原样返回。 + * @return String 格式化后的字符串 + */ + public static String getNumFormat(String numStr, String fmt) { + double db = getDouble(numStr, 0); + return getNumFormat(db, fmt); + } + + /** + * 数字字符串格式化,把入参中的数字字符串格式化为带两位小数的数字字符串 + * + * @param numStr + * String 待格式化的数字字符串,
+ * 如果numStr参数不是的数字则不进行格式化,按原样返回 + * @return String 格式化为两位小数的数字字符串 + */ + public static String getNumFormat(String numStr) { + return getNumFormat(numStr, "0.00"); + } + + /** + * 普通字符串转化为网页中可显示的,如回车转化为<br>. + * + * @param str + * String 待转化的字符串 + * @return String 转化后的字符串 + */ + public static String htmlEncode(String str) { + String retu = null; + if (null == str || "".equals(str.trim())) { + retu = str; + } else { + String html = str; + //StringUtils tool = new StringUtils(); + html = replaceString(html, "&", "&"); + html = replaceString(html, "<", "<"); + html = replaceString(html, ">", ">"); + html = replaceString(html, "\r\n", "\n"); + html = replaceString(html, "\n", "
"); + html = replaceString(html, "\t", " "); + html = replaceString(html, " ", " "); + html = replaceString(html, "\"", """); + retu = html; + html = null; + } + return retu; + } + + /** + * 字符串替换,把str字符串中的所有oldStr子串替换为newStr字串 + * + * @param sourceStr + * String 将被替换的字符串,为null时不执行任何替换操作 + * @param oldStr + * String 将被替换的子串,为null或为空字符串时不执行替换操作 + * @param newStr + * String 将被替换成的子串,为null时不执行替换操作 + * @param isIgnoreCase + * boolean 是否忽略大小写,true表忽略大小写,false表大小写敏感。 + * @return String 替换后的字符串 + */ + public static String replaceString(String sourceStr, String oldStr, String newStr, boolean isIgnoreCase) { + if (sourceStr == null || oldStr == null || oldStr.equals("")) { + return null; + } + String strRetStr = sourceStr; + int pos = strRetStr.indexOf(oldStr); + while (pos != -1) { + strRetStr = strRetStr.substring(0, pos) + newStr + strRetStr.substring(pos + oldStr.length()); + pos = strRetStr.indexOf(oldStr, pos + newStr.length()); + } + return strRetStr; + } + + /** + * 字符串替换,把str字符串中的所有oldStr子串替换为newStr字串(大小写敏感) + * + * @param sourceStr + * String 将被替换的字符串,为null时不执行任何替换操作 + * @param oldStr + * String 将被替换的子串,为null或为空字符串时不执行替换操作 + * @param newStr + * String 将被替换成的子串,为null时不执行替换操作 + * @return String 替换后的字符串 + */ + public static String replaceString(String sourceStr, String oldStr, String newStr) { + return replaceString(sourceStr, oldStr, newStr, false); + } + + /** + * 字符串按指定分隔符分解为一个数组(大小写敏感).
+ * 例子:
+ * String[] array = StringUtils.splictString("AA/BBB/CCC//DDDD//" , "/" ); + *
+ * 结果:
+ * array[0]="AA" array[1]="BBB" array[2]="CCC" array[3]="DDDD" + * + * @param sourceStr + * String 源字符串 + * @param splitStr + * String 分隔符 + * @param isTrim + * boolean + * @return String[] 字符串数组,
+ * 源字符串为null或为空字符串时,返回长度为1的数组,元素值为空字符串
+ * 分隔符为null或为空字符串时,返回长度为1的数组,元素值为源字符串 + */ + public static String[] splitString(String sourceStr, String splitStr, boolean isTrim) { + String newSourceStr = sourceStr; + String newSplitStr = splitStr; + + if (newSourceStr == null || newSplitStr == null) { + return null; + } + + if (isTrim) // 去掉开始和结束的分隔符 + { + // 开头的间隔符去掉 + while (newSourceStr.indexOf(newSplitStr) == 0) { + newSourceStr = newSourceStr.substring(newSplitStr.length()); + } + + // 尾部的间隔符去掉 + while (newSourceStr.indexOf(newSplitStr, newSourceStr.length() - newSplitStr.length()) > -1) { + newSourceStr = newSourceStr.substring(0, sourceStr.length() - newSplitStr.length()); + } + } + if (newSourceStr.equals("") || newSplitStr.equals("")) { + return null; + } + return splitString(newSourceStr, newSplitStr); + } + + /** + * 功能简述 :把字符串放入一个数组 + * + * @param sourceStr + * 要被放入的字符串 + * @param splitStr + * 间隔符 + * @return 转换后的数组,sourceStr或splitStr = null 或 "" 返回null + */ + public static String[] splitString(String sourceStr, String splitStr) { + String newSourceStr = sourceStr; + String newSplitStr = splitStr; + + if (newSourceStr == null || newSplitStr == null) { + return null; + } + if (newSourceStr.equals("") || newSplitStr.equals("")) { + return null; + } + int intArraySize = subStringCount(newSourceStr, newSplitStr); + // 如果为-1则返回 + if (intArraySize == -1) { + return null; + } + + newSourceStr += newSplitStr; + + String[] strRetArr = new String[intArraySize + 1]; + int intpos = newSourceStr.indexOf(newSplitStr); + int intArrayPos = 0; + while (intpos != -1) { + strRetArr[intArrayPos++] = newSourceStr.substring(0, intpos); + newSourceStr = newSourceStr.substring(intpos + newSplitStr.length()); + intpos = newSourceStr.indexOf(newSplitStr); + } + + return strRetArr; + } + + /** + * 功能简述 :把字符串放入一个数组 + * @param sourceStr + * 要被放入的字符串 + * @param splitStr + * 间隔符 + * @return 转换后的List,sourceStr或splitStr = null 或 "" 返回元素个数为0的List + */ + public static List splitString2List(String sourceStr, String splitStr) { + String[] tempArr = splitString(sourceStr, splitStr); + List resultList = new ArrayList(); + if (tempArr != null) { + for (int i = 0; i < tempArr.length; i++) { + resultList.add(tempArr[i]); + } + } + return resultList; + } + + /** + * 功能简述 :把字符串放入一个数组 + * + * @param sourceStr + * 要被放入的字符串 + * @param splitStr + * 间隔符 + * @param isTrim + * boolean + * @return 转换后的List,sourceStr或splitStr = null 或 "" 返回元素个数为0的List + */ + public static List splitString2List(String sourceStr, String splitStr, boolean isTrim) { + String[] tempArr = splitString(sourceStr, splitStr, isTrim); + List resultList = new ArrayList(); + if (tempArr != null) { + for (int i = 0; i < tempArr.length; i++) { + resultList.add(tempArr[i]); + } + } + return resultList; + } + + /** + * 功能简述 :在一个字符串中查找字符串个数(不区分大小写) + * + * @param sourceStr + * 要被查询的字符串 + * @param subStr + * 要查找的字符串 + * @return 找到的个数 + */ + public static int subStringCount(String sourceStr, String subStr) { + // 如果是空指针则返回-1 + if (sourceStr == null || subStr == null) { + return -1; + } + if (sourceStr.equals("") || subStr.equals("")) { + return -1; + } + int result = 0; + int intPos = sourceStr.toUpperCase().indexOf(subStr.toUpperCase()); + while (intPos != -1) { + result++; + intPos = sourceStr.toUpperCase().indexOf(subStr.toUpperCase(), intPos + subStr.length()); + } + + return result; + } + + /** + * 用指定的分隔符把字符串数组合并成一个字符串. 数组为null或长度为0时返回空字符串
+ * 例子:
+ * String[] array = {"1",null,"","3"};
+ * StringUtils.arrayToString(array,"|");
+ * 返回结果:1|||3 + * + * @param array + * String[] 待合并的数组 + * @param splitStr + * String 数组各元素合并后,它们之间的分隔符,为null时用空字符串代替 + * @return String 合并后的字符串 + */ + public static String arrayToString(String[] array, String splitStr) { + if (null == array || 0 == array.length) { + return ""; + } + String newSplitStr = splitStr; + if (null == newSplitStr) { + newSplitStr = ""; + } + StringBuffer strBuf = new StringBuffer(""); + int len = array.length; + for (int i = 0; i < len - 1; i++) { + strBuf.append((null == array[i]) ? "" : array[i]).append(newSplitStr); + } + strBuf.append((null == array[len - 1]) ? "" : array[len - 1]); + + return strBuf.toString(); + } + + /** + * 用默认分隔符 | 把字符串数组合并成一个字符串. 数组为null或长度为0时返回空字符串 + * + * @param array + * String[] 待合并的数组 + * @return String 合并后的字符串 + */ + public static String arrayToString(String[] array) { + return arrayToString(array, "|"); + } + + /** + * 判断字符串是否为null或为空字符串(包括只含空格的字符串) + * + * @param str + * String 待检查的字符串 + * @return boolean 如果为null或空字符串(包括只含空格的字符串)则返回true,否则返回false + */ + public static boolean isNullBlank(String str) { + return (null == str || "".equals(str.trim())) ? true : false; + } + + /** + * 从字符串中得到指定位置的子串(按分隔符分隔,大小写敏感).
+ * 例子:
+ * StringUtils.decomposeString("a||b|c|d","|",1);
+ * StringUtils.decomposeString("a||b|c|d","|",2);
+ * StringUtils.decomposeString("a||b|c|d","|",3);
+ * StringUtils.decomposeString("a||b|c|d","|",4);
+ * StringUtils.decomposeString("a||b|c|d","|",5);
+ * 返回结果:
+ * a,空字符串,b,c,d + * + * @param sourceStr + * String 源字符串 + * @param splitStr + * String 分隔符 + * @param pos + * int 位置,从1开始 + * @return String 返回指定位置的子串。
+ * 当分隔符为null或为空字符串时返回源字符串;
+ * 当源字符串为null或为空字符串时返回空字符串;
+ * 当指定位置小于1或大于分隔符个数-1时返回空字符串。 + */ + public static String decomposeString(String sourceStr, String splitStr, int pos) { + String retu = ""; + String newSourceStr = sourceStr; + if (null == newSourceStr || "".equals(newSourceStr.trim())) { + return ""; + } + + if (pos <= 0) { + return ""; + } + + if (null == splitStr || "".equals(splitStr)) { + return sourceStr; + } + + newSourceStr = newSourceStr + splitStr; + String tmpStr = newSourceStr; + + int splitLen = splitStr.length(); + int tmpLen = tmpStr.length(); + + for (int i = 0; i < pos - 1; i++) { + int tmpPosi = tmpStr.indexOf(splitStr); + if (tmpPosi < 0 || tmpPosi + splitLen >= tmpLen) { + tmpStr = splitStr; + break; + } else { + tmpStr = tmpStr.substring(tmpPosi + splitLen); + } + } + retu = tmpStr.substring(0, tmpStr.indexOf(splitStr)); + return retu; + } + + /** + * 从字符串中得到指定位置的子串(按分隔符 | 分隔). + * + * @param sourceStr + * String 源字符串 + * @param pos + * int 位置,从1开始 + * @return String 返回指定位置的子串。
+ * 当分隔符为null或为空字符串时返回源字符串;
+ * 当源字符串为null或为空字符串时返回空字符串;
+ * 当指定位置小于1或大于分隔符个数-1时返回空字符串。 + */ + public static String decomposeString(String sourceStr, int pos) { + return decomposeString(sourceStr, "|", pos); + } + + /** + * 删除指定的前导、后导子串(大小写敏感).
+ * 例子:
+ * StringUtils.trim("and and username = '123' and password = 'abc' and + * ","and ");
+ * 结果:username = '123' and password = 'abc' + * + * @param sourceStr + * String 待删除的字符串 + * @param removeChar + * char 子串 + * @return String 处理后的字符串 + */ + public static String trim(String sourceStr, char removeChar) { + if (sourceStr == null) { + return null; + } + String newSourceStr = sourceStr; + + newSourceStr = newSourceStr.trim(); + int loIntBegin = 0; + int loIntEnd = 0; + int loIntLen = newSourceStr.length(); + for (int i = 0; i < loIntLen; i++) { + if (newSourceStr.charAt(i) == removeChar) { + loIntBegin++; + } else { + break; + } + } + for (int i = 0; i < loIntLen; i++) { + if (newSourceStr.charAt(loIntLen - 1 - i) == removeChar) { + loIntEnd++; + } else { + break; + } + } + return newSourceStr.substring(loIntBegin, loIntLen - loIntEnd); + } + + /** + * 删除指定的前导、后导子串(大小写敏感).
+ * 例子:
+ * StringUtils.trim("and and username = '123' and password = 'abc' and + * ","and ");
+ * 结果:username = '123' and password = 'abc' + * + * @param sourceStr + * String 待删除的字符串 + * @param removeChar + * char 子串 + * @param end + * true 只trim末尾,false 只trim头部 + * @return String 处理后的字符串 + */ + public static String trim(String sourceStr, char removeChar, boolean end) { + if (sourceStr == null) { + return null; + } + String newSourceStr = sourceStr; + + newSourceStr = newSourceStr.trim(); + int loIntBegin = 0; + int loIntEnd = 0; + int loIntLen = newSourceStr.length(); + for (int i = 0; i < loIntLen; i++) { + if (newSourceStr.charAt(i) == removeChar) { + loIntBegin++; + } else { + break; + } + } + for (int i = 0; i < loIntLen; i++) { + if (newSourceStr.charAt(loIntLen - 1 - i) == removeChar) { + loIntEnd++; + } else { + break; + } + } + if (end) { + return newSourceStr.substring(0, loIntLen - loIntEnd); + } else { + return newSourceStr.substring(loIntBegin); + } + } + + /** + *
+	 * 将字符串截短到特定的长度,一个中文是两个字节的长度,但是是1个字符的长度,例:
+	 * 1)truncate("巨龙软件公司",2,CHAR_LEN) = "巨龙"
+	 * 2)truncate("巨龙软件公司",2,BYTE_LEN) = "巨"
+	 * 3)truncate("dragonsoft",2,CHAR_LEN) = "dr"
+	 * 4)truncate("dragonsoft",2,BYTE_LEN) = "dr"
+	 * 
+ * + * @param str + * String 需要截的字符串 + * @param len + * int 截到的目标长度 + * @param lenType + * int 长度类型,字符长度{@link CHAR_LEN},字符长度{@link BYTE_LEN} + * @return String + */ + public static String truncate(String str, int len, int lenType) { + if (str == null) { + return str; + } + // 字符长度 + if (lenType == CHAR_LEN) { + if (str.length() <= len) { + return str; + } else { + return str.substring(0, len); + } + } else // 字节长度 + { + StringBuffer sb = new StringBuffer(); + int temp = 0; + + for (int i = 0; i < str.length(); i++) { + if (i < len) // 是否到指定的长度 + { + temp = ("" + str.charAt(i)).getBytes().length; + if (i + temp <= len) { + sb.append(str.charAt(i)); + } else { + break; + } + } else { + break; + } + } + return sb.toString(); + } + } + + /** + * 从源字符串中从第一个字符开始取出给定长度的字串.
+ * 源字符串长度大于len时,尾巴追加一个appendStr串 + * + * @param sourceStr + * String 源字符串 + * @param len + * int 取出的长度 + * @param appendStr + * String 追加的字符串(常用的appendStr为...) + * @return String 取出的子串 + */ + public static String substring(String sourceStr, int len, String appendStr) { + if (null == sourceStr || "".equals(sourceStr)) { + return sourceStr; + } + if (len <= 0) { + return ""; + } + + String newappendStr = appendStr; + if (null == newappendStr) { + newappendStr = ""; + } + + int sourceLen = sourceStr.length(); + if (len >= sourceLen) { + return sourceStr; + } else { + return sourceStr.substring(0, len) + newappendStr; + } + } + + /** + * 产生指定长度随机字符串(包括字母及数字). + * + * @param length + * int 随机字符串长度 + * @return String 随机字符串 + */ + public static String random(int length) { + String retu = ""; + int d1; + int d2; + char[] letters = initLetters(); + //int[] numbers = initNumbers(); + + for (int i = 0; i < length; i++) { + // d1 = ((int) (Math.random() * 10) % 2); + d1 = (int) (Math.random() * 10) % 2; + + if (d1 == 0) { // use a letter + // d2 = ((int) (Math.random() * 100) % 52); + d2 = (int) (Math.random() * 100) % 52; + retu += letters[d2]; + } else if (d1 == 1) { // use a number + retu += (int) (Math.random() * 10); + } + } + return retu; + } + + /** + * 产生纯字母的随机字符串 + * + * @param length + * int 随机字符串长度 + * @return String 随机字符串 + */ + public static String randomString(int length) { + String retu = ""; + int d2; + char[] letters = initLetters(); + + for (int i = 0; i < length; i++) { + // d2 = ((int) (Math.random() * 100) % 52); + d2 = (int) (Math.random() * 100) % 52; + retu += letters[d2]; + } + return retu; + } + + /** + * 产生纯数字随机字符串 + * + * @param length + * int 随机字符串长度 + * @return String 随机字符串 + */ + public static String randomNumber(int length) { + String retu = ""; + //int[] numbers = initNumbers(); + + for (int i = 0; i < length; i++) { + retu += (int) (Math.random() * 10); + } + return retu; + } + + /** + * 内部方法,产生字母数组 + * + * @return char[] + */ + private static char[] initLetters() { + char[] ca = new char[52]; + for (int i = 0; i < 26; i++) { + ca[i] = (char) (65 + i); + } + for (int i = 26; i < 52; i++) { + ca[i] = (char) (71 + i); + } + return ca; + } + + /** + * 内部方法,产生数字数组 + * + * @return int[] + */ + /*private static int[] initNumbers() { + int[] na = new int[10]; + for (int i = 0; i < 10; i++) { + na[i] = i; + } + return na; + }*/ + + /** + * 对字符串进行加减密处理. + * + * @param source + * String 待加减密处理的字符串 + * @param flag + * boolean true表进行加密,false表进行减密 + * @return String 处理后的字符串.
+ * source为空则返回原字符串source,
+ * 如果source中含有中文字符则对这一中文字符不处理. + */ + public static String encrypt(String source, boolean flag) { + if (null == source || "".equals(source.trim())) { + return source; + } + String lsKEY1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz~!@#$%^&*(),.;[]{}"; + String lsKEY2 = "&*()AD;[BFLCGH]{PQ}EI!JKRYZ1MSTXNO23UV,.Wcd45ef6lm7g@h0a#$nij8ob%^ptvz9ku~qrswxy"; + + char[] chSource = source.toCharArray(); + + StringBuffer strBuf = new StringBuffer(chSource.length); + + int pos; + int len = chSource.length; + for (int i = 0; i < len; i++) { + if (flag) { // 加密 + pos = lsKEY1.indexOf(chSource[i]); + if (pos >= 0) { + strBuf.append(lsKEY2.substring(pos, pos + 1)); + } else { + strBuf.append(chSource[i]); + } + } else { // 减密 + pos = lsKEY2.indexOf(chSource[i]); + if (pos >= 0) { + strBuf.append(lsKEY1.substring(pos, pos + 1)); + } else { + strBuf.append(chSource[i]); + } + } + } + + return strBuf.toString(); + + } + + /** + * 将null字符串转换为空串,方便HTML的显示 + * + * @param sourceStr + * 待处理的字符串 + * @return String 处理的的字符串 + */ + public static String toVisualString(String sourceStr) { + if (sourceStr == null || sourceStr.equals("")) { + return ""; + } else { + return sourceStr; + } + } + + /** + * 将字段填充到指定的长度 + * + * @param sourceStr + * String 操作字符串 + * @param length + * int 指定长度 + * @param withChar + * char 填充的字符 + * @param isPadToEnd + * boolean 是否填充在字符的尾部 true :是 ,false:填充在头部 + * @return String + */ + public static String pad(String sourceStr, int length, char withChar, boolean isPadToEnd) { + if (sourceStr == null) { + return null; + } + if (sourceStr.length() >= length) { + return sourceStr; + } + + StringBuffer sb = new StringBuffer(sourceStr); + for (int i = 0; i < length - sourceStr.length(); i++) { + if (isPadToEnd) { + sb.append(withChar); + } else { + sb.insert(0, withChar); + } + } + return sb.toString(); + + } + + /** + * 首字母大写 + * @return + */ + public static String capToUpper(String str){ + if (str == null) { + return null; + } + if(str.length()<0){ + return ""; + } + return str.substring(0,1).toUpperCase()+str.substring(1); + } + /** + * main + * + * @param args + * String[] + * @author:Administrator + */ + + + /** + * 将身份证号码转换为18位 + * + * @param xIdCode + * String + * @return String + */ + public static String idTo18(String xIdCode) { + return IdentificationNumberUtils.id15ToId18(xIdCode); + } + + /** + * 将身份证号转换为15位 + * + * @param xIdCode + * String + * @return String + */ + public static String idTo15(String xIdCode) { + return IdentificationNumberUtils.id18ToId15(xIdCode); + } + + /** + * getIdCheckBit + * + * @param xId + * id + * @return String + * @author:Administrator + */ + private static String getIdCheckBit(String xId) { + return IdentificationNumberUtils.getIdCheckBit(xId); + } + + /** + * MD5加密算法 + * + * @更新时间:Apr 22, 2008 + * @更新作者:Ryan Wong + * @param s + * String + * @return String + */ + public static String md5(String s) { + char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + try { + byte[] strTemp = s.getBytes(); + MessageDigest mdTemp = MessageDigest.getInstance("MD5"); + mdTemp.update(strTemp); + byte[] md = mdTemp.digest(); + int j = md.length; + char[] str = new char[j * 2]; + int k = 0; + for (int i = 0; i < j; i++) { + byte byte0 = md[i]; + str[k++] = hexDigits[byte0 >>> 4 & 0xf]; + str[k++] = hexDigits[byte0 & 0xf]; + } + return new String(str); + } catch (Exception e) { + return null; + } + } + + /** + * 取得字符串中间的几位 + * + * @更新时间:Apr 22, 2008 + * @更新作者:Ryan Wong + * @param strsource + * str_source + * @param midlength + * midlength + * @return String + */ + public static String getMidString(String strsource, int midlength) { + String strMid = ""; + int length = strsource.length(); + if (midlength > length) { + return null; + } + if (length % 2 == 0) { + if (midlength % 2 != 0) { + return null; + } + strMid = strsource.substring(length / 2 - midlength / 2, length / 2 + midlength / 2); + + } else { + if (midlength % 2 == 0) { + return null; + } + strMid = strsource.substring((length - 1) / 2 - (midlength - 1) / 2, (length - 1) / 2 + + (midlength - 1) / 2 + 1); + + } + return strMid; + } + + public static boolean isNotBlank(String value){ + return (value!=null) && !value.equals(""); + } + + public static boolean isBlank(String value){ + return (value==null) || value.equals(""); + } + /** + * getStringToInt + * @param value String + * @param defaultInt int + * @return int + * @author:Administrator + */ + public static int getStringToInt(String value, int defaultInt) { + int i = defaultInt; + if (isNotBlank(value) ) { + Integer intObject = getStringByInt(value); + if(intObject!=null){ + return intObject.intValue(); + } + } + return i; + } + + /** + * 字符串替换 + * @param value String + * @param replaceChar String + * @return String + * @author:Administrator + */ + public static String replaceStr(String value, String replaceChar) { + String returnValue = ""; + if (isNotBlank(value)) { + returnValue = value.replaceAll("[" + replaceChar + "]", ""); + } + return returnValue; + } + + /** + * getNullByString + * @param value String + * @return String + * @author:Administrator + */ + public static String getNullByString(String value) { + String values = ""; + if (isNotBlank(value)) { + values = value.trim(); + } + return values; + } + + /** + * getNullByString + * @param value String + * @param defaultValue String + * @return String + * @author:Administrator + */ + public static String getNullByString(String value, String defaultValue) { + String values = ""; + if (isNotBlank(value)) { + values = value; + } else { + values = defaultValue; + } + return values; + } + + /** + * getStringByInt + * @param value String + * @return Integer + * @author:Administrator + */ + public static Integer getStringByInt(String value) { + Integer intValue = null; + if (isNotBlank(value) ) { + try{ + intValue = Integer.valueOf(value); + } catch(NumberFormatException ex){ + + } + } + return intValue; + } + + /** + * getStringByMaxLen + * @param value String + * @param maxLen int + * @return String + * @author:Administrator + */ + public static String getStringByMaxLen(String value, int maxLen) { + String returnValue = ""; + if (isNotBlank(value)) { + returnValue = value.length() > maxLen ? value.substring(0, maxLen) : value; + } + return returnValue; + } + + /** + * getCheckBoxValueByStr + * @param value String + * @return String + * @author:Administrator + */ + public static String getCheckBoxValueByStr(String value) { + String returnValue = ""; + if (isNotBlank(value)) { + if (value.equals("on")) { + returnValue = "1"; + } else { + returnValue = "0"; + } + } + return returnValue; + } + + /** + * 删除字符两端的空字符串 + * + * @author cailj + * @param str + * @return + */ + public static String trim(String str) { + return str != null ? str.trim() : null; + } + + /** + * 进行字符规格化(全角转半角,大写转小写处理) + * @param input + * @return char + */ + public static char[] regularize(char[] input){ + + for(int i = 0; i < input.length; i ++){ + input[i] = regularize(input[i]); + } + return input; + } + + /** + * 进行字符规格化(全角转半角,大写转小写处理) + * @param input + * @return char + */ + public static char regularize(char input){ + if (input == 12288) { + input = (char) 32; + + }else if (input > 65280 && input < 65375) { + input = (char) (input - 65248); + + }else if (input >= 'A' && input <= 'Z') { + input |= 32; + } + return input; + } + + /** + * 进行字符规格化(全角转半角,大写转小写处理) + * @param input + * @return char + */ + public static String regularize(String input){ + if(StringUtils.isBlank(input)) return ""; + + char[] inputChars = input.toCharArray(); + for(int i = 0; i < inputChars.length; i ++){ + inputChars[i] = regularize(inputChars[i]); + } + return new String(inputChars); + } + + /** + * 字符反转 + * eg: reverse(abc) = cba + * @param str + * @return + */ + public static String reverse(String str) { + char[] chrs = str.toCharArray(); + int n = chrs.length - 1; + for (int j = (n-1) >> 1; j >= 0; --j) { + char temp = chrs[j]; + char temp2 = chrs[n - j]; + chrs[j] = temp2; + chrs[n - j] = temp; + } + return new String(chrs, 0, chrs.length); + } + /** + * 字符串是否是 数字类型 + * @param str + * @return + */ + public static boolean isNumber(String str){ + + if(isInteger(str)||isFloat(str)){ + return true; + }else{ + return false; + } + + } + + /** + * 判断字符串是否为浮点型 + * @param str + * @return + */ + public static boolean isFloat(String str){ + + if(StringUtils.isNullBlank(str))return false; + + Pattern pattern= Pattern.compile("^[-\\+]?\\d+\\.{0,1}[\\d]+$"); + return pattern.matcher(str).matches(); + } + + /** + * 判断字符串是否是整数 + * @param str + * @return + */ + public static boolean isInteger(String str){ + + if(StringUtils.isNullBlank(str))return false; + + Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$"); + return pattern.matcher(str).matches(); + } + + /** + * 忽略正则关键字 + * @param keyword 正在表达式关键字 例如"\t","\d","*"等 + * @return 返回正则表达式 + */ + public static String ignoreRegexKeyword(String keyword){ + return "\\Q"+keyword+"\\E"; + } + + /** + * + * @param str + * @param character + * @return + */ + public static String removeLastCharacter(String str, String character){ + if(str==null||str.length()==0){ + return str; + } + int en=-1; + if((en=str.lastIndexOf(character))>=0&&(en+character.length()==str.length())){ + return str.substring(0,en); + }else{ + return str; + } + } + public static String ignoreKeyword(String txt){ + if(txt==null){ + return null; + } + String str=ignoreKeyword(txt,"n"); + str=ignoreKeyword(str,"t"); + return str; + } + public static String ignoreKeyword(Object object){ + return ignoreKeyword(String.valueOf(object)); + } + public static String ignoreKeyword(String txt, String keyWord){ + if(txt==null){ + return null; + } + + if(txt.length()==0||isBlank(keyWord)){ + return txt; + } + return txt.replaceAll("\\"+keyWord,"\\\\"+keyWord); + } + + + + + /** + * 下划线转驼峰法 + * @param line 源字符串 + * @param smallCamel 大小驼峰,是否为小驼峰 + * @return 转换后的字符串 + */ + public static String underline2Camel(String line, boolean smallCamel){ + if(line==null||"".equals(line)){ + return ""; + } + StringBuffer sb=new StringBuffer(); + Pattern pattern= Pattern.compile("([A-Za-z\\d]+)(_)?"); + Matcher matcher=pattern.matcher(line); + while(matcher.find()){ + String word=matcher.group(); + sb.append(smallCamel&&matcher.start()==0? Character.toLowerCase(word.charAt(0)): Character.toUpperCase(word.charAt(0))); + int index=word.lastIndexOf('_'); + if(index>0){ + sb.append(word.substring(1, index).toLowerCase()); + }else{ + sb.append(word.substring(1).toLowerCase()); + } + } + return sb.toString(); + } + /** + * 驼峰法转下划线 + * @param line 源字符串 + * @return 转换后的字符串 + */ + public static String camel2Underline(String line){ + if(line==null||"".equals(line)){ + return ""; + } + line= String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1)); + StringBuffer sb=new StringBuffer(); + Pattern pattern= Pattern.compile("[A-Z]([a-z\\d]+)?"); + Matcher matcher=pattern.matcher(line); + while(matcher.find()){ + String word=matcher.group(); + sb.append(word.toUpperCase()); + sb.append(matcher.end()==line.length()?"":"_"); + } + return sb.toString(); + } + + + //IOS端version比较大小 param1>param2 返回 1 =返回0 <返回-1 + public static int compareVersion(String versionClient,String versionServe){ + //版本长度 + String[] cArr = versionClient.split("\\."); + String[] sArr = versionServe.split("\\."); + int diff = cArr.length-sArr.length; + int result = 0; + + //补齐长度 + if(diff>0){ + sArr = align(sArr,cArr,diff); + }else{ + cArr = align(cArr,sArr,-diff); + } + + for(int i=0;i0){ + param2 = align(param2,param1,diff2); + }else{ + param1 = align(param1,param2,-diff2); + } + + int param11 = Integer.parseInt(StringUtils.arrayToString(param1,"")); + int param22 = Integer.parseInt(StringUtils.arrayToString(param2,"")); + + if(param11>param22){ + result = 1; + break; + }else if(param11Assert + * + *
 --描述说明--
+ *

+ * 
+ * --样例--
+ *   Assert obj = new Assert();
+ *   obj.method();
+ * 
+ * JDK版本:JDK1.4 + * @author 李炜 + */ +public abstract class Validator { + /** + * 判断表达式是否为true + * @param expression 要判断的表达式 + */ + public static boolean isTrue(boolean expression) { + return expression; + } + + + /** + * 判断表达式是否为0 + * @param expression 要判断的表达式 + */ + public static boolean isZero(int num) { + return num == 0; + } + + + /** + * 判断表达式是否为非空 + * @param expression 要判断的表达式 + */ + public static boolean notZero(int num, String message) { + return num == 0; + } + + + + /** + * 判断表达式是否为空 + * @param expression 要判断的表达式 + */ + public static boolean isNull(Object object) { + return object == null; + } + + + + /** + * 判断表达式是否为非空 + * @param expression 要判断的表达式 + */ + public static boolean notNull(Object object) { + return object != null; + } + + /** + * 判断字符串长度是否大于指定长度 + * @param text 字符串 + * @param size 指定长度 + */ + public static boolean gtLength(String text,int size){ + return notNull(text) && text.length() > size; + } + + + public static boolean gtLength(Collection collection,int size){ + return notNull(collection) && collection.size() > size; + } + + public static boolean gtLength(Map collection,int size){ + return notNull(collection) && collection.size() > size; + } + + + /** + * 判断字符串长度是否小于指定长度 + * @param text 字符串 + * @param size 指定长度 + */ + public static boolean ltLength(String text,int size){ + return notNull(text) && text.length() < size; + } + + public static boolean ltLength(Collection collection,int size){ + return notNull(collection) && collection.size()< size; + } + + public static boolean ltLength(Map collection,int size){ + return notNull(collection) && collection.size()< size; + } + + /** + * 判断text是否为有内容字符串 + * @param text 要判断的字符串 + */ + public static boolean hasLength(String text) { + return notNull(text) && gtLength(text, 0); + } + + public static boolean hasLength(Object[] arrays){ + return notNull(arrays) && arrays.length > 0; + } + + /** + * 判断text是否为有内容字符串 + * @param text 要判断的字符串 + */ + public static boolean hasLength(StringBuffer text) { + return notNull(text) && gtLength(text.toString(), 0); + } + + + /** + * 判断text是否为有内容,如果都是空白字符也将抛异常 + * @param text 要判断的字符串 + */ + public static boolean hasText(String text) { + return notNull(text) && gtLength(text.trim(), 0); + } + + public static boolean hasText(StringBuffer sb){ + return notNull(sb) && gtLength(sb.toString().trim(), 0); + } + + /** + * 判断数组是否大于指定长度 + * @param array 数组 + * @param size 长度 + */ + public static boolean gtSize(Object[] array,int size){ + return notNull(array) && array.length > size; + } + + /** + * 判断数组是否小于指定长度 + * @param array 数组 + * @param size 长度 + */ + public static boolean ltSize(Object[] array,int size){ + return notNull(array) && array.length < size; + } + + + /** + * 判断数组是否为空数组 + * @param array 要判断的数租 + */ + public static boolean notEmpty(Object[] array) { + return notNull(array) && gtSize(array, 0); + } + + + /** + * 判断集合是否为空集合对象 + * @param array 要判断的集合对象 + */ + public static boolean notEmpty(Collection collection) { + return notNull(collection) && !collection.isEmpty(); + } + + + + + /** + * 判断Map是否为空对象,有默认消息 + * @param array 要判断的Map + * @throws IllegalArgumentException 如果是空集合对象或者null + */ + public static boolean notEmpty(Map map) { + return notNull(map) && !map.isEmpty(); + } + + + /** + *判断指定的 Object 是否与此 type 所表示的对象赋值兼容 + * @param 用于检查的Class对象 + * @param obj 用于检查的对象 + */ + public static boolean isInstanceOf(Class type, Object obj, String message) { + return notNull(type) && type.isInstance(obj); + } + + + /** + * 判断两个类型是否相同 + * @param type1 + * @param type2 + */ + public static boolean isSameType(Class type1,Class type2,String message){ + return notNull(type1) && notNull(type2) && type1.equals(type2); + } + + + /** + * 判断一个class对象调用newInstance,是否成功 + * @param type + */ + public static boolean isNewInstanceOf(Class type){ + if(notNull(type)){ + try { + type.newInstance(); + return true; + } catch (Exception e) { + return false; + } + }else{ + return false; + } + } + + + /** + * 判断superType.isAssignableFrom(subType)是否为true + * @param superType 超类 + * @param subType 子类 + */ + public static boolean isAssignable(Class superType, Class subType) { + return notNull(superType) && notNull(subType) && superType.isAssignableFrom(subType); + } + + + + + +} diff --git a/luqj-common/src/main/java/com/luqj/util/assertion/Assert.java b/luqj-common/src/main/java/com/luqj/util/assertion/Assert.java new file mode 100644 index 0000000..edee462 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/assertion/Assert.java @@ -0,0 +1,395 @@ +/** +* 版权所有:厦门市巨龙软件工程有限公司 +* Copyright 2010 Xiamen Dragon Software Eng. Co. Ltd. +* All right reserved. +*==================================================== +* 文件名称: Assert.java +* 修订记录: +* No 日期 作者(操作:具体内容) +* 1. 2010-8-6 李炜(创建:创建文件) +*==================================================== +* 类描述:(说明未实现或其它不应生成javadoc的内容) +* +*/ +package com.luqj.util.assertion; + + +import com.luqj.util.log.LogUtil; + +import java.util.Collection; +import java.util.Map; + +/** + *
Assert
+ * + *
 --描述说明--
+ *

+ * 
+ * --样例--
+ *   Assert obj = new Assert();
+ *   obj.method();
+ * 
+ * JDK版本:JDK1.4 + * @author 李炜 + */ +public abstract class Assert { + /** + * 断言表达式是否为true + * @param expression 要断言的表达式 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果不是true + */ + public static void isTrue(boolean expression, String message) { + if (!expression) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言表达式是否为true,有默认消息 + * @param expression 要断言的表达式 + * @throws IllegalArgumentException 如果不是true + */ + public static void isTrue(boolean expression) { + isTrue(expression, "[断言失败] - 参数必须是 true"); + } + + /** + * 断言表达式是否为0 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果不是空 + */ + public static void isZero(long num, String message) { + if (num != 0) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言表达式是否为空,有默认消息 + * @throws IllegalArgumentException 如果不是空 + */ + public static void isZero(long num) { + isZero(num, "[断言失败] - 参数值必须是0"); + } + + /** + * 断言表达式是否为非空 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果不是非空 + */ + public static void notZero(long num, String message) { + if (num == 0) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言表达式是否为非空,有默认消息 + * @throws IllegalArgumentException 如果不是非空 + */ + public static void notZero(long num) { + notZero(num, "[断言失败] - 参数必须非0"); + } + + + /** + * 断言表达式是否为空 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果不是空 + */ + public static void isNull(Object object, String message) { + if (object != null) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言表达式是否为空,有默认消息 + * @throws IllegalArgumentException 如果不是空 + */ + public static void isNull(Object object) { + isNull(object, "[断言失败] - 参数必须是 null"); + } + + + + /** + * 断言表达式是否为非空 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果不是非空 + */ + public static void notNull(Object object, String message) { + if (object == null) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言表达式是否为非空,有默认消息 + * @throws IllegalArgumentException 如果不是非空 + */ + public static void notNull(Object object) { + notNull(object, "[断言失败] - 参数必须是非空对象"); + } + + + + /** + * 断言表达式是否为非空,有默认消息 + * @throws IllegalArgumentException 如果不是非空 + */ + public static void notNull(Object... objects) { + for (int i = 0; i < objects.length; i++) { + notNull(objects[i], "[断言失败] - 参数["+i+"]必须是非空对象"); + } + } + + /** + * 断言text是否为有内容字符串 + * @param text 要断言的字符串 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果是空串或null对象 + */ + public static void hasLength(String text, String message) { + if (text == null || text.length() == 0) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言text是否为有内容字符串,有默认消息 + * @param text 要断言的字符串 + * @throws IllegalArgumentException 如果是空串或null对象 + */ + public static void hasLength(String text) { + hasLength(text, + "[断言失败] - 参数必须是非空字符串"); + } + + /** + * 断言text是否为有内容,如果都是空白字符也将抛异常 + * @param text 要断言的字符串 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果是空串或null对象,或所有内容为空白字符 + */ + public static void hasText(String text, String message) { + if (text == null || text.trim().length() == 0) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言text是否为有内容,如果都是空白字符也将抛异常,有默认消息 + * @param text 要断言的字符串 + * @throws IllegalArgumentException 如果是空串或null对象,或所有内容为空白字符 + */ + public static void hasText(String text) { + hasText(text, + "[断言失败] - text必须是有内容的,有内容指不是全部为空白字符的字符串"); + } + + + /** + * 断言数组是否为空数组 + * @param array 要断言的数租 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果是空数组或者null + */ + public static void notEmpty(Object[] array, String message) { + if (array == null || array.length == 0) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言数组是否为空数组,有默认消息 + * @param array 要断言的数租 + * @throws IllegalArgumentException 如果是空数组或者null + */ + public static void notEmpty(Object[] array) { + notEmpty(array, "[断言失败] - 参数数组必须是非空数组"); + } + + /** + * 断言集合是否为空集合对象 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果是空集合对象或者null + */ + public static void notEmpty(Collection collection, String message) { + if (collection == null || collection.isEmpty()) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言集合是否为空集合对象,有默认消息 + * @throws IllegalArgumentException 如果是空集合对象或者null + */ + public static void notEmpty(Collection collection) { + notEmpty(collection, + "[断言失败] - 集合参数必须是有内容的"); + } + + /** + * 断言Map是否为空对象 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果是空集合对象或者null + */ + public static void notEmpty(Map map, String message) { + if (map == null || map.isEmpty()) { + throw new IllegalArgumentException(message); + } + } + + /** + * 断言Map是否为空对象,有默认消息 + * @throws IllegalArgumentException 如果是空集合对象或者null + */ + public static void notEmpty(Map map) { + notEmpty(map, "[断言失败] - Map参数必须是有内容的"); + } + + + /** + *断言指定的 Object 是否与此 type 所表示的对象赋值兼容 + * @param obj 用于检查的对象 + * @throws IllegalArgumentException 如果不兼容 + */ + public static void isInstanceOf(Class clazz, Object obj) { + isInstanceOf(clazz, obj, ""); + } + + /** + *断言指定的 Object 是否与此 type 所表示的对象赋值兼容 + * @param obj 用于检查的对象 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果不兼容 + */ + public static void isInstanceOf(Class type, Object obj, String message) { + notNull(type, "类型对象不可为空"); + if (!type.isInstance(obj)) { + throw new IllegalArgumentException(message + + "Object of class [" + (obj != null ? obj.getClass().getName() : "null") + + "] must be an instance of " + type); + } + } + + + /** + * 断言一个class对象调用newInstance,是否成功 + * @param type + * @throws IllegalArgumentException 如果不成功 + */ + public static void isNewInstanceOf(Class type){ + isNewInstanceOf(type,""); + } + + /** + * 断言两个类型是否相同 + * @param type1 + * @param type2 + */ + public static void isSameType(Class type1,Class type2,String message){ + notNull(type1,"类型对象不可为空"); + notNull(type2,"类型对象不可为空"); + if(!type1.equals(type2)){ + throw new IllegalArgumentException(message); + } + } + + /** + * 断言两个类型是否相同 + * @param type1 + * @param type2 + */ + public static void isSameType(Class type1,Class type2){ + isSameType(type1, type2, "必须是相同类型"); + } + + /** + * 断言一个class对象调用newInstance,是否成功 + * @param type + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果不成功 + */ + public static void isNewInstanceOf(Class type,String message){ + notNull(type,"类型对象不可为空"); + try { + type.newInstance(); + } catch (InstantiationException e) { + + throw new IllegalArgumentException(message + + "Class [" + type +"] must be can new instance "); + } catch (IllegalAccessException e) { + + throw new IllegalArgumentException(message + + "Class [" + type +"] must be can new instance "); + } + } + + /** + * 断言superType.isAssignableFrom(subType)是否为true + * @param superType 超类 + * @param subType 子类 + * @throws IllegalArgumentException 如果调用该方法为false + */ + public static void isAssignable(Class superType, Class subType) { + isAssignable(superType, subType, ""); + } + + /** + * 断言superType.isAssignableFrom(subType)是否为true + * @param superType 超类 + * @param subType 子类 + * @param message 抛异常以后的消息 + * @throws IllegalArgumentException 如果调用该方法为false + */ + public static void isAssignable(Class superType, Class subType, String message) { + notNull(superType, "超类的类对象必须为非空"); + if (subType == null || !superType.isAssignableFrom(subType)) { + throw new IllegalArgumentException(message + subType + " is not assignable to " + superType); + } + } + + + /** + * 断言一个对象所属状态值是否为true + * @param expression 要断言的状态表达式 + * @param message 抛异常以后的消息 + * @throws IllegalStateException 如果表达式为false + */ + public static void state(boolean expression, String message) { + if (!expression) { + throw new IllegalStateException(message); + } + } + + + /** + * 断言一个对象所属状态值是否为true,有默认消息 + * @param expression 要断言的状态表达式 + * @throws IllegalStateException 如果表达式为false + */ + public static void state(boolean expression) { + state(expression, "[断言失败] - 状态表达式必须式true"); + } + + public static void logic(boolean expression,String message){ + if (!expression) { + throw new IllegalLogicException(message); + } + } + + public static void logic(boolean expression){ + logic(expression, "[断言失败] - 逻辑表达式必须是true"); + } + + public static void fail(String message){ + throw new IllegalLogicException(message); + } + + public static void fail(String message,Throwable e){ + throw new IllegalLogicException(LogUtil.exceptionMsg(message,e),e); + } +} diff --git a/luqj-common/src/main/java/com/luqj/util/assertion/IllegalLogicException.java b/luqj-common/src/main/java/com/luqj/util/assertion/IllegalLogicException.java new file mode 100644 index 0000000..a1c5f36 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/assertion/IllegalLogicException.java @@ -0,0 +1,21 @@ +package com.luqj.util.assertion; + +public class IllegalLogicException extends RuntimeException { + + public IllegalLogicException() { + super(); + } + + public IllegalLogicException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + public IllegalLogicException(String arg0) { + super(arg0); + } + + public IllegalLogicException(Throwable arg0) { + super(arg0); + } + +} diff --git a/luqj-common/src/main/java/com/luqj/util/date/DateUtils.java b/luqj-common/src/main/java/com/luqj/util/date/DateUtils.java new file mode 100644 index 0000000..c7546ce --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/date/DateUtils.java @@ -0,0 +1,1331 @@ +/** + * 版权所有:厦门市巨龙软件工程有限公司 + * Copyright 2009 Xiamen Dragon Software Eng. Co. Ltd. + * All right reserved. + *==================================================== + * 文件名称: DateUtils.java + * 修订记录: + * No 日期 作者(操作:具体内容) + * 1. Mar 3, 2009 何志昭(创建:创建文件) + * 2. Mar 3, 2009 根据dragonsoft_checks.xml规范进行调整 + *==================================================== + * 类描述: + * + */ +package com.luqj.util.date; + + +import com.luqj.util.StringUtils; +import com.luqj.util.Validator; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +/** + * + * + * + *
+ *
+ *
JDK版本:
+ *
+ *
1.4
+ *
+ * + * @author 陈雄华,姚建斌,谢计生 + * @version 1.0 + * @see Java + * simpleDateFormat Tutorial + * @see Date + * @see Calendar + * @see SimpleDateFormat + * @since 1.0 + */ +public class DateUtils { + + /**一分钟的秒数*/ + public static final int SECONDS_ONE_MINUTE = 60; + + /**一秒的毫秒数*/ + public static final int MILLISECONDS_ONE_SECOND = 1000; + + /**一小时的秒数*/ + public static final int SECONDS_ONE_HOUR = 60 * SECONDS_ONE_MINUTE; + + /**一天的秒数*/ + public static final int SECONDS_ONE_DAY = 24 * SECONDS_ONE_HOUR; + + /** 数据库存储的时间格式串,如yyyymmdd 或yyyymmddHHMiSS */ + public static final int DB_STORE_DATE = 1; + + /** 用连字符-分隔的时间时间格式串,如yyyy-mm-dd 或yyyy-mm-dd HH:Mi:SS */ + public static final int HYPHEN_DISPLAY_DATE = 2; + + /** 用连字符.分隔的时间时间格式串,如yyyy.mm.dd 或yyyy.mm.dd HH:Mi:SS */ + public static final int DOT_DISPLAY_DATE = 3; + + /** 用中文字符分隔的时间格式串,如yyyy年mm月dd 或yyyy年mm月dd HH:Mi:SS */ + public static final int CN_DISPLAY_DATE = 4; + /** 日期的开始时间戳*/ + public static final String DB_STORE_DATE_BEGIN = "000000"; + /** 日期的结束时间戳*/ + public static final String DB_STORE_DATE_END = "235959"; + + + /** + * 获取当前月份的第一天 + * @return 第一天的日期对象 + * @author:李炜 + */ + public static Date getCurMonthFirstDate(){ + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); + return calendar.getTime(); + } + + /** + * 获取当前月份的最后一天 + * @return 最后一天的日期对象 + * @author:李炜 + */ + public static Date getCurMonthLastDay() { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); + return calendar.getTime(); + } + + + /** + * 获取日期的开始时间戳 + * @param storeDate 数据库存储日期,格式yyyyMMddHHmmss + * @return storeDate + * @author:李炜 + */ + public static String getStoreDateBegin(String storeDate){ + if(storeDate.length() >= 8){ + return storeDate.substring(0,8)+DB_STORE_DATE_BEGIN; + }else{ + return storeDate; + } + } + + /** + * 获取日期的结束时间戳 + * @param storeDate 数据库存储日期,格式yyyyMMddHHmmss + * @return storeDate + * @author:李炜 + */ + public static String getStoreDateEnd(String storeDate){ + if(storeDate.length() >= 8){ + return storeDate.substring(0,8)+DB_STORE_DATE_END; + }else{ + return storeDate; + } + } + + + /** + * 得到精确到秒的格式化当前时间串 + * + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link #EN_HTML_DISPLAY_DATE},{@link #CN_HTML_DISPLAY_DATE} + * @return 当前时间格式化时间串 + */ + public static String getCurrTimeStr(int formatType) { + return getTimeStr(new Date(), formatType); + } + + /** + * 得到精确到秒的格式化时间串 + * + * @param date + * 指定时间 + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link #HYPHEN_DISPLAY_DATE},{@link #DOT_DISPLAY_DATE} + * @return 指定时间的格式化时间串 + */ + public static String getTimeStr(Date date, int formatType) { + if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) { + throw new IllegalArgumentException("时间格式化类型不是合法的值。"); + } else { + String formatStr = null; + switch (formatType) { + case DB_STORE_DATE: + formatStr = "yyyyMMddHHmmss"; + break; + case HYPHEN_DISPLAY_DATE: + formatStr = "yyyy'-'MM'-'dd HH:mm:ss"; + break; + case DOT_DISPLAY_DATE: + formatStr = "yyyy.MM.dd HH:mm:ss"; + break; + case CN_DISPLAY_DATE: + formatStr = "yyyy'年'MM'月'dd HH:mm:ss"; + break; + default: + formatStr = "yyyyMMddHHmmss"; + break; + } + SimpleDateFormat sdf = new SimpleDateFormat(formatStr); + return sdf.format(date); + } + } + + /** + * 得到精确到天的当前格式化日期串 + * + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link #EN_HTML_DISPLAY_DATE},{@link #CN_HTML_DISPLAY_DATE} + * @return String + */ + public static String getCurrDateStr(int formatType) { + return getDateStr(new Date(), formatType); + } + + /** + * 得到精确到天的指定时间格式化日期串 + * + * @param date + * 指定时间 + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link #EN_HTML_DISPLAY_DATE},{@link #CN_HTML_DISPLAY_DATE} + * @return 指定时间格式化日期串 + */ + public static String getDateStr(Date date, int formatType) { + if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) { + throw new IllegalArgumentException("时间格式化类型不是合法的值。"); + } else { + String formatStr = null; + switch (formatType) { + case DB_STORE_DATE: + formatStr = "yyyyMMdd"; + break; + case HYPHEN_DISPLAY_DATE: + formatStr = "yyyy-MM-dd"; + break; + case DOT_DISPLAY_DATE: + formatStr = "yyyy.MM.dd"; + break; + case CN_DISPLAY_DATE: + formatStr = "yyyy'年'MM'月'dd"; + break; + default: + formatStr = "yyyyMMdd"; + break; + } + SimpleDateFormat sdf = new SimpleDateFormat(formatStr); + return sdf.format(date); + } + } + + /** + * 得到精确到月的当前时间格式化年月串 + * + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link #EN_HTML_DISPLAY_DATE},{@link #CN_HTML_DISPLAY_DATE} + * @return 精确到月当前时间格式化年月串 + */ + public static String getYearMonthStr(int formatType) { + return getYearMonthStr(new Date(), formatType); + } + + /** + * 得到精确到月的指定时间格式化年月串 + * + * @param date + * 指定的时间 + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link #EN_HTML_DISPLAY_DATE},{@link #CN_HTML_DISPLAY_DATE} + * @return 精确到月当前时间格式化年月串 + */ + public static String getYearMonthStr(Date date, int formatType) { + if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) { + throw new IllegalArgumentException("时间格式化类型不是合法的值。"); + } else { + String formatStr = null; + switch (formatType) { + case DB_STORE_DATE: + formatStr = "yyyyMM"; + break; + case HYPHEN_DISPLAY_DATE: + formatStr = "yyyy-MM"; + break; + case DOT_DISPLAY_DATE: + formatStr = "yyyy.MM"; + break; + case CN_DISPLAY_DATE: + formatStr = "yyyy'年'MM'月'"; + break; + default: + formatStr = "yyyyMM"; + break; + } + + SimpleDateFormat sdf = new SimpleDateFormat(formatStr); + return sdf.format(date); + } + } + + /** + * 将数据库存储的日期格式串转换为各种显示的格式 + * + * @param dateStr + * 最小6位,最大14位的数据库存储格式时间串如:20041212 + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link #EN_HTML_DISPLAY_DATE},{@link #CN_HTML_DISPLAY_DATE} + * @return 格式化的时间串 + */ + public static String toDisplayStr(String dateStr, int formatType) { + if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) { + throw new IllegalArgumentException("时间格式化类型不是合法的值。"); + } + if (dateStr == null || dateStr.length() < 6 || dateStr.length() > 14 || formatType == DB_STORE_DATE) { + return StringUtils.toVisualString(dateStr); + } else { + char[] charArr = null; + switch (formatType) { + case HYPHEN_DISPLAY_DATE: + charArr = new char[] { '-', '-', ' ', ':', ':' }; + break; + case DOT_DISPLAY_DATE: + charArr = new char[] { '.', '.', ' ', ':', ':' }; + break; + case CN_DISPLAY_DATE: + charArr = new char[] { '年', '月', ' ', ':', ':' }; + break; + default: + charArr = new char[] { '-', '-', ' ', ':', ':' }; + } + try { + SimpleDateFormat sdf1 = null; + SimpleDateFormat sdf2 = null; + switch (dateStr.length()) { + case 6: + sdf1 = new SimpleDateFormat("yyyyMM"); + sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM"); + break; + case 8: + sdf1 = new SimpleDateFormat("yyyyMMdd"); + sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'" + charArr[1] + "'dd"); + break; + case 10: + sdf1 = new SimpleDateFormat("yyyyMMddHH"); + sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'" + charArr[1] + "'dd'" + + "+charArr[2]" + "'HH"); + break; + case 12: + sdf1 = new SimpleDateFormat("yyyyMMddHHmm"); + sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'" + charArr[1] + "'dd'" + charArr[2] + + "'HH'" + charArr[3] + "'mm"); + break; + case 14: + sdf1 = new SimpleDateFormat("yyyyMMddHHmmss"); + sdf2 = new SimpleDateFormat("yyyy'" + charArr[0] + "'MM'" + charArr[1] + "'dd'" + charArr[2] + + "'HH'" + charArr[3] + "'mm'" + charArr[4] + "'ss"); + break; + default: + return dateStr; + } + return sdf2.format(sdf1.parse(dateStr)); + } catch (ParseException ex) { + return dateStr; + } + } + } + + /** + * 将显示格式的时间字符串转换为数据库存储的类型 + * + * @param dateStr + * 最小4位,最大19位。显示的时间格式时间串如:2004-12-12 + * @return 数据库存储的时间字符串 + */ + public static String toStoreStr(String dateStr) { + if (dateStr == null || dateStr.trim().equals("")) { + return ""; + } + StringBuffer strBuf = new StringBuffer(); + for (int i = 0; i < dateStr.length(); i++) { + if (dateStr.charAt(i) >= '0' && dateStr.charAt(i) <= '9') { + strBuf.append(dateStr.charAt(i)); + } + } + return strBuf.toString(); + } + + /** + * 将生日存储的时间格式转化为年龄(周岁,小数点后不计) + * + * @param birthdayStr + * 生日字段 "yyyymmdd" + * @return 年龄 + */ + public static String birthdayToAge(String birthdayStr) { + if (birthdayStr == null || birthdayStr.length() < 6) { + return ""; + } else { + int birthYear = Integer.parseInt(birthdayStr.substring(0, 4)); + int birthMonth = Integer.parseInt(birthdayStr.substring(4, 6)); + Calendar cal = new GregorianCalendar(); + int currYear = cal.get(Calendar.YEAR); + int currMonth = cal.get(Calendar.MONTH); + int age = currYear - birthYear; + age -= (currMonth < birthMonth) ? 1 : 0; + return "" + age; + } + } + + /** + * + * @param dateTimeStr + * String 格式化的时间串 + * @param formatType + * 数据格式类型 {@link #DB_STORE_DATE},{@link #EN_HTML_DISPLAY_DATE},{@link #CN_HTML_DISPLAY_DATE} + * @param detal + * int 增加或减少的时间 + * @param field + * int 参见Calendar中关于时间字段属性的定义 + * @return String 返回的 + */ + public static String add(String dateTimeStr, int formatType, int detal, int field) { + if (dateTimeStr == null || dateTimeStr.length() < 6) { + return dateTimeStr; + } else { + try { + String formatStr = null; + switch (formatType) { + case DB_STORE_DATE: + formatStr = "yyyyMMddHHmmss"; + break; + case HYPHEN_DISPLAY_DATE: + formatStr = "yyyy-MM-dd HH:mm:ss"; + break; + case DOT_DISPLAY_DATE: + formatStr = "yyyy.MM.dd HH:mm:ss"; + break; + case CN_DISPLAY_DATE: + formatStr = "yyyy'年'MM'月' HH:mm:ss"; + break; + default: + formatStr = "yyyyMMddHHmmss"; + break; + } + + formatStr = formatStr.substring(0, dateTimeStr.length()); + SimpleDateFormat sdf = new SimpleDateFormat(formatStr); + Date d = sdf.parse(dateTimeStr); + GregorianCalendar g = new GregorianCalendar(); + g.setTime(d); + g.add(field, detal); + d = g.getTime(); + return sdf.format(d); + } catch (ParseException ex) { + + return dateTimeStr; + } + } + } + + // /** + // * @param date Date 时间 + // * @param detal int 增加的时间 + // * @param field int 参见Calendar中关于时间字段属性的定义 + // * @return Date + // */ + // public static Date add(Date date, int detal, int field) + // { + // Calendar g = new GregorianCalendar(); + // g.setTime(date); + // g.add(field, detal); + // return g.getTime(); + // } + /** + * 日期、时间格式化 + * + * @param date + * Date 将要被格式化的日期对象 + * @param outFmt + * String 返回样式,参照类说明,如:yyyy年MM月dd日 + * @return String 格式化后的日期、时间字符串,data为null时返回null,outFmt非法时返回yyyyMMdd格式 + */ + public static String getDateFormat(Date date, String outFmt) { + if (null == date) { + return null; + } + String newOutFmt = outFmt; + + if (null == newOutFmt || "".equals(newOutFmt.trim())) { // outFmt非法 + newOutFmt = "yyyyMMdd"; + } + + String retu = null; + SimpleDateFormat dateFormat = null; + try { + dateFormat = new SimpleDateFormat(newOutFmt); + } catch (IllegalArgumentException iaex) { // outFmt非法 + dateFormat = new SimpleDateFormat("yyyyMMdd"); + } + retu = dateFormat.format(date); + + dateFormat = null; + + return retu; + } + + /** + * 把日期时间对象格式化为yyyyMMdd样式 + * + * @param date + * Date 将要被格式化的日期对象 + * @return String 格式化后的日期、时间字符串,如:20041001 + */ + public static String getDateFormat(Date date) { + return getDateFormat(date, "yyyyMMdd"); + } + + /** + * 把日期时间对象格式化为yyyyMMdd样式 + * + * @param date + * Date 将要被格式化的日期对象 + * @return String 格式化后的日期、时间字符串,如:20041001 + */ + public static String getDateFormatByFmt(Date date,String outFmt) { + return getDateFormat(date, outFmt); + } + + /** + * 把系统当前日期时间格式化为指定的样式 + * + * @param outFmt + * String 返回样式,参照类说明,如:yyyy年MM月dd日 + * @return String 格式化后的日期、时间字符串,如:2004年10月01日 + */ + public static String getDateFormat(String outFmt) { + return getDateFormat(new Date(), outFmt); + } + + /** + * 把系统当前日期时间格式化为默认样式yyyyMMdd + * + * @return String 格式化后的日期、时间字符串,如:20041001 + */ + public static String getDateFormat() { + return getDateFormat(new Date(), "yyyyMMdd"); + } + + /** + * 日期、时间格式化 + * + * @param millis + * long the number of milliseconds(毫秒) since January 1, 1970, + * 00:00:00 GMT. + * @param outFmt + * String 返回样式,参照类说明,如:yyyy年MM月dd日 + * @return String 格式化后的日期、时间字符串 + */ + public static String getDateFormat(long millis, String outFmt) { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(millis); + + String retu = getDateFormat(calendar.getTime(), outFmt); + calendar = null; + return retu; + } + + /** + * 日期、时间格式化 + * + * @param datestr + * String 存在一定格式的日期、时间字符串,如:20041001、200410011503 + * @param inFmt + * String 对datestr参数格式说明,参照类说明,如:yyyyMMdd、yyyyMMddHHmm + * @param outFmt + * String 返回样式,参照类说明,如:yyyy年MM月dd日 + * @throws ParseException + * 当datestr不能格式化为inFmt格式时抛出此异常 + * @return String 格式化后的日期、时间字符串,如:2004年10月01日、2004年10月01日
+ * 输出样式outFmt非法时,使用yyyyMMdd格式输出 + */ + public static String getDateFormat(String datestr, String inFmt, String outFmt) throws ParseException { + if (null == datestr || "".equals(datestr.trim())) { + return datestr; + } + + if (null == inFmt || "".equals(inFmt.trim())) { + return datestr; + } + + String newOutFmt = outFmt; + if (null == newOutFmt || "".equals(newOutFmt.trim())) { // 输出样式非法 + newOutFmt = "yyyyMMdd"; + } + + Date inDate = getDate(datestr, inFmt); + + if (null == inDate) { // 根据inFmt分析datestr时抛出异常 + return datestr; + } + + String retu = getDateFormat(inDate, newOutFmt); + inDate = null; + return retu; + } + + /** + * 把日期时间字符串,按inFmt样式转化为日期对象,然后格式化为默认样式yyyyMMdd + * + * @param datestr + * String 存在一定格式的日期、时间字符串,如:20041001、200410011503 + * @param inFmt + * String 对datestr参数格式说明,参照类说明,如:yyyyMMdd、yyyyMMddHHmm + * @throws ParseException + * 当datestr不能格式化为inFmt格式时抛出此异常 + * @return String 格式化后的日期、时间字符串,如:20041001、20041001 + */ + public static String getDateFormat(String datestr, String inFmt) throws ParseException { + return getDateFormat(datestr, inFmt, "yyyyMMdd"); + } + + /** + * 根据inFmt的样式,日期时间字符串转化为日期时间对象 + * + * @param datestr + * String 日期时间字符串,如:20041001、2004年10月01日 15:03 + * @param inFmt + * String 对datestr参数格式说明,参照类说明,如yyyyMMdd、yyyy年MM月dd日 HH:mm + * @throws ParseException + * 当datestr不能格式化为inFmt格式时抛出此异常 + * @return Date 日期时间对象,格式inFmt非法时,使用yyyyMMdd格式 + */ + public static Date getFillDate(String datestr, String inFmt,boolean end) throws ParseException { + if (null == datestr || "".equals(datestr.trim())) { + return null; + } + + String newInFmt = inFmt; + if (null == newInFmt || "".equals(newInFmt.trim())) { // inFmt非法 + newInFmt = "yyyyMMdd"; + } + String[] endFlag = new String[]{"9","5"}; + String endStr = ""; + if(datestr.length()!=newInFmt.length()){ + int len = newInFmt.length()-datestr.length(); + if(end){ + for(int i=len;i>0;i--){ + endStr=endFlag[(i+1)%2]+endStr; + } + }else{ + for(int i=len;i>0;i--){ + endStr+="0"; + } + } + } + + datestr=datestr.trim()+endStr; + Date inDate = null; + + // 依据inFmt格式把日期字符串转化为日期对象 + SimpleDateFormat inDateFormat = new SimpleDateFormat(newInFmt); + inDateFormat.setLenient(true); + inDate = inDateFormat.parse(datestr); + + inDateFormat = null; + return inDate; + } + /** + * 根据inFmt的样式,日期时间字符串转化为sql日期时间对象 + * + * @param datestr + * String 日期时间字符串,如:20041001、2004年10月01日 15:03 + * @param inFmt + * String 对datestr参数格式说明,参照类说明,如yyyyMMdd、yyyy年MM月dd日 HH:mm + * @throws ParseException + * 当datestr不能格式化为inFmt格式时抛出此异常 + * @return Date 日期时间对象,格式inFmt非法时,使用yyyyMMdd格式 + */ + public static java.sql.Date getSqlDate(String datestr,String inFmt) throws ParseException{ + Date utilDate = getDate(datestr, inFmt); + return new java.sql.Date(utilDate.getTime()); + } + + /** + * 根据inFmt的样式,日期时间字符串转化为日期时间对象 + * + * @param datestr + * String 日期时间字符串,如:20041001、2004年10月01日 15:03 + * @param inFmt + * String 对datestr参数格式说明,参照类说明,如yyyyMMdd、yyyy年MM月dd日 HH:mm + * @throws ParseException + * 当datestr不能格式化为inFmt格式时抛出此异常 + * @return Date 日期时间对象,格式inFmt非法时,使用yyyyMMdd格式 + */ + public static Date getDate(String datestr, String inFmt) throws ParseException { + if (null == datestr || "".equals(datestr.trim())) { + return null; + } + + String newInFmt = inFmt; + if (null == newInFmt || "".equals(newInFmt.trim())) { // inFmt非法 + newInFmt = "yyyyMMdd"; + } + + Date inDate = null; + + // 依据inFmt格式把日期字符串转化为日期对象 + SimpleDateFormat inDateFormat = new SimpleDateFormat(newInFmt); + inDateFormat.setLenient(true); + inDate = inDateFormat.parse(datestr); + + inDateFormat = null; + return inDate; + } + + /** + * + * @param date1 + * @param date2 + * @return + * @author:李炜 + */ + public static int dateDiff(Date date1,Date date2){ + if(date1.compareTo(date2) == 0){ + return 0; + } + long second = Math.abs((date1.getTime() - date2.getTime())) / 1000; + return (int) (second / SECONDS_ONE_DAY); + } + + /** + * 相差的时间(单位:秒) + * @param date1 + * @param date2 + * @return + */ + public static long secondDiff(Date date1,Date date2){ + if(date1.compareTo(date2) == 0){ + return 0; + } + long second = Math.abs((date1.getTime() - date2.getTime())) / 1000; + return second; + } + + + public static int dateCompare(Date date1,Date date2){ + if(date1 == null){ + return -1; + } + if(date2 == null){ + return -1; + } + if(date1.compareTo(date2) == 0){ + return 0; + } + long second =(date1.getTime() - date2.getTime()) / 1000; + return (int) (second / SECONDS_ONE_DAY); + } + + + + public static int dateSimpleCompare(String dateStr1,String dateStr2,String format){ + + Date date1 = null; + Date date2 = null; + try { + SimpleDateFormat dateFormat = new SimpleDateFormat(format); + date1 = dateFormat.parse(dateStr1); + date2 = dateFormat.parse(dateStr2); + if(date1.getTime()>date2.getTime()){ + return 1; + }else if(date1.getTime() + * 例子: + * + *
+     * <blockquote>
+     * 计算去年今天星期几
+     * Date date = DateUtils.addDate(new Date(),Calendar.YEAR,-1);
+     * System.out.println(DateUtils.getDateFormat(date,"E"));
+     * 打印60天后是什么日期,并显示为 yyyy-MM-dd 星期
+     * Date date = DateUtils.addDate(new Date(),Calendar.DATE,60);
+     * System.out.println(DateUtils.getDateFormat(date,"yyyy-MM-dd E"));
+     * </blockquote>
+     * 
+ * + * @param date + * Date 需要调整的日期时间对象 + * @param calendarField + * int 对日期时间对象以什么单位进行调整: + * + *
+     * <blockquote>
+     * 年 Calendar.YEAR
+     * 月 Calendar.MONTH
+     * 日 Calendar.DATE
+     * 时 Calendar.HOUR
+     * 分 Calendar.MINUTE
+     * 秒 Calendar.SECOND
+     * </blockquote>
+     * 
+ * + * @param amount + * int 调整数量,>0表向后调整(明天,明年),<0表向前调整(昨天,去年) + * @return Date 调整后的日期时间对象 + */ + public static Date addDate(Date date, int calendarField, int amount) { + if (null == date) { + return date; + } + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.add(calendarField, amount); + return calendar.getTime(); + } + + /** + * 对日期时间对象进行调整. + * + * @param datestr + * String 需要调整的日期时间字符串,它的格式为yyyyMMdd + * @param calendarField + * int 对日期时间对象以什么单位进行调整 + * @param amount + * int 调整数量 + * @throws ParseException + * 当datestr不能格式化为yyyyMMdd格式时抛出此异常 + * @return Date 调整后的日期时间对象 + * @see #addDate(Date, int, int) + */ + public static Date addDate(String datestr, int calendarField, int amount) throws ParseException { + return addDate(getDate(datestr, "yyyyMMdd"), calendarField, amount); + } + + /** + * 根据出生日期,计算出在某一个日期的年龄 + * + * @param birthday + * Date 出生日期时间对象 + * @param date2 + * Date 计算日期对象 + * @return int 返回date2那一天出生日期为birthday的年龄,如果birthday大于date2则返回-1 + */ + public static int getAge(Date birthday, Date date2) { + if (null == birthday || null == date2) { + return -1; + } + + if (birthday.after(date2)) { // birthday大于date2 + return -1; + } + + int ibdYear = StringUtils.getInt(getDateFormat(birthday, "yyyy"), -1); + int idate2Year = StringUtils.getInt(getDateFormat(date2, "yyyy"), -1); + + if (ibdYear < 0 || idate2Year < 0) { + return -1; + } + if (ibdYear > idate2Year) { + return -1; + } + + return idate2Year - ibdYear + 1; + } + + /** + * 根据出生日期,计算出当前的年龄 + * + * @param birthday + * Date 出生日期时间对象 + * @return int 返回出生日期为birthday的年龄,如果birthday大于当前系统日期则返回-1 + */ + public static int getAge(Date birthday) { + return getAge(birthday, new Date()); + } + + /** + * 根据出生日期,计算出当前的年龄 + * + * @param birthdaystr + * String 出生日期时间字符串,其格式一定为yyyyMMdd + * @throws ParseException + * 当datestr不能格式化为yyyyMMdd格式时抛出此异常 + * @return int 返回出生日期为birthday的年龄,如果birthday大于当前系统日期则返回-1 + */ + public static int getAge(String birthdaystr) throws ParseException { + return getAge(getDate(birthdaystr, "yyyyMMdd")); + } + + public static String dbCurrtime(){ + return getCurrTime(DB_STORE_DATE); + } + + /** + * 得到14位的当前格式化时间 + * + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link + * @return java.lang.String + */ + public static String getCurrTime(int formatType) { + if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) { + throw new IllegalArgumentException("时间格式化类型不是合法的值。"); + } else { + String formatStr = null; + switch (formatType) { + case DB_STORE_DATE: + formatStr = "yyyyMMddHHmmss"; + break; + case HYPHEN_DISPLAY_DATE: + formatStr = "yyyy-MM-dd HH:mm:ss"; + break; + case DOT_DISPLAY_DATE: + formatStr = "yyyy.MM.dd HH:mm:ss"; + break; + case CN_DISPLAY_DATE: + formatStr = "yyyy年MM月dd HH:mm:ss"; + break; + default: + formatStr = "yyyyMMddHHmmss"; + break; + } + SimpleDateFormat sdf = new SimpleDateFormat(formatStr); + return sdf.format(new Date()); + } + } + + /** + * 得到8位的当前格式化日期 + * + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link + * @return java.lang.String + */ + public static String getCurrDate(int formatType) { + if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) { + throw new IllegalArgumentException("时间格式化类型不是合法的值。"); + } else { + String formatStr = null; + switch (formatType) { + case DB_STORE_DATE: + formatStr = "yyyyMMdd"; + break; + case HYPHEN_DISPLAY_DATE: + formatStr = "yyyy-MM-dd"; + break; + case DOT_DISPLAY_DATE: + formatStr = "yyyy.MM.dd"; + break; + case CN_DISPLAY_DATE: + formatStr = "yyyy'年'MM'月'dd"; + break; + default: + formatStr = "yyyyMMdd"; + break; + } + SimpleDateFormat sdf = new SimpleDateFormat(formatStr); + return sdf.format(new Date()); + } + } + + /** + * 得到6位的当前格式化年月 + * + * @param formatType + * 时间格式的类型{@link #DB_STORE_DATE},{@link + * @return java.lang.String + */ + public static String getYearMonth(int formatType) { + if (formatType < DB_STORE_DATE || formatType > CN_DISPLAY_DATE) { + throw new IllegalArgumentException("时间格式化类型不是合法的值。"); + } else { + String formatStr = null; + switch (formatType) { + case DB_STORE_DATE: + formatStr = "yyyyMM"; + break; + case HYPHEN_DISPLAY_DATE: + formatStr = "yyyy-MM"; + break; + case DOT_DISPLAY_DATE: + formatStr = "yyyy.MM"; + break; + case CN_DISPLAY_DATE: + formatStr = "yyyy'年'MM'月'"; + break; + default: + formatStr = "yyyyMM"; + break; + } + SimpleDateFormat sdf = new SimpleDateFormat(formatStr); + return sdf.format(new Date()); + } + } + + /** + * 获取时间所对应的毫秒 + * + * @param datetime + * String 时间字符串 + * @param inFmt + * String 时间格式化串 + * @return long 毫秒数 + * @throws ParseException + * ParseException + */ + public static long getTimeValue(String datetime, String inFmt) throws ParseException { + return getDate(datetime, inFmt).getTime(); + } + + /** + * 两个秒数只差 + * @param startTime + * @param endTime + * @param inFmt + * @return + */ + public static long consumeSecondsValue(String startTime,String endTime,String inFmt) throws ParseException{ + long startSeconds = getTimeValue(startTime,inFmt); + long endSeconds = getTimeValue(endTime,inFmt); + return (endSeconds - startSeconds)/1000; + } + + /** + * 获取时间字符串 + * + * @param milliSeconds + * long 从1970年到现在的毫 + * @param formatType + * int 时间类型 + * @return String 时间字符串 + */ + public static String getTimeStr(long milliSeconds, int formatType) { + Date d = new Date(milliSeconds); + return getTimeStr(d, formatType); + } + + + + /** + * getTimeByValue + * + * @param time + * 时间 + * @param timeOldFormat + * 旧时间格式 + * @param timeNewFormat + * 新时间格式 + * @return String + * @author:Administrator + */ + public static String getTimeByValue(String time, String timeOldFormat, String timeNewFormat) { + SimpleDateFormat oldSdf = new SimpleDateFormat(timeOldFormat); + SimpleDateFormat newSdf = new SimpleDateFormat(timeNewFormat); + String newTime = time; + try { + if (Validator.hasText(time)) { + // Date times = oldSdf.parse(time); + newTime = newSdf.format(oldSdf.parse(time)); + } + } catch (ParseException e1) { + + } + return newTime; + } + + + /** + * 返回上月的起始日期和结束日期,格式YYYYMMDD + * @param time + * @return + * @author:lwei + */ + public static String[] getLastMonthBetweenDay(Date time){ + Calendar cal = Calendar.getInstance(); + cal.setTime(time); + int year = 0; + int month = cal.get(Calendar.MONTH)-1; // 上个月月份 + if (month == 0) { + year = cal.get(Calendar.YEAR) - 1; + month = 12; + } else { + year = cal.get(Calendar.YEAR); + } + Calendar c = Calendar.getInstance(); + c.set(year, month, 1); + int startDay = c.getActualMinimum(Calendar.DAY_OF_MONTH);//起始天数 + int endDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); // 结束天数 + c.set(year, month,startDay); + String startTime = getDateFormat(c.getTime()); + c.clear(); + c.set(year, month,endDay); + String endTime = getDateFormat(c.getTime()); + return new String[]{startTime,endTime}; + } + + /** + * 返回上月的起始日期和结束日期,格式YYYYMMDD + * @param time + * @return + * @author:huanglm + */ + public static String[] getLastMonthBetweenDayByFmt(Date time,String fmt){ + Calendar cal = Calendar.getInstance(); + cal.setTime(time); + int year = 0; + int month = cal.get(Calendar.MONTH)-1; // 上个月月份 + if (month == 0) { + year = cal.get(Calendar.YEAR) - 1; + month = 12; + } else { + year = cal.get(Calendar.YEAR); + } + Calendar c = Calendar.getInstance(); + c.set(year, month, 1); + int startDay = c.getActualMinimum(Calendar.DAY_OF_MONTH);//起始天数 + int endDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); // 结束天数 + c.set(year, month,startDay); + String startTime = getDateFormatByFmt(c.getTime(),fmt); + c.clear(); + c.set(year, month,endDay); + String endTime = getDateFormatByFmt(c.getTime(),fmt); + return new String[]{startTime,endTime}; + } + + + + /** + * 获取两时间字符串的时间间隔描述 + * 例如:2010-10-10 10:10:10与2010-10-20 20:20:20 + * 的时间间隔描述串为:10天10时10分10秒 + * 如果开始时间大于结束时间返回负数,如:-10时10分10秒 + * + * @param beginTime 开始时间字符串 + * @param endTime 结束时间字符串 + * @param inFmt String 时间格式化串 + * @return 两时间字符串的时间差 如:12天03时25分08秒 + */ + public static String getTimeBetweenStr(String beginTime,String endTime,String inFmt){ + SimpleDateFormat dfs = new SimpleDateFormat(inFmt); + StringBuffer timeStrBuf = new StringBuffer(); + try { + Date begin = dfs.parse(beginTime); + Date end = dfs.parse(endTime); + if (begin.compareTo(end) == 0 ) { + return "1秒"; //如果开始时间等于结束时间 直接返回1秒 + } + long between = (end.getTime() - begin.getTime()) / 1000; //除以1000是为了转换成秒 + if (between < 0 ) { + timeStrBuf.append("-"); + between = -between; + } + long day = between / (24*60*60); + long hour = between % (24*60*60) / 3600; + long minute = between % (60*60) / 60; + long second = between % 60; + if (day != 0) { + timeStrBuf.append(String.valueOf(day)+"天" ); + } + if (hour != 0) { + timeStrBuf.append(String.valueOf(hour)+"时" ); + } + + if(minute != 0 ) { + timeStrBuf.append(String.valueOf(minute)+"分" ); + } + if (second != 0 ) { + timeStrBuf.append(String.valueOf(second)+"秒" ); + } + } catch (Exception e) { + return null; + } + return timeStrBuf.toString(); + } + + /** + * 给时间加上或减去指定毫秒,秒,分,时,天、月或年等,返回变动后的时间 + * + * @param date 要加减前的时间,如果不传,则为当前日期 + * @param field 时间域,有Calendar.MILLISECOND,Calendar.SECOND,Calendar.MINUTE,
+ * * Calendar.HOUR,Calendar.DATE, Calendar.MONTH,Calendar.YEAR + * @param amount 按指定时间域加减的时间数量,正数为加,负数为减。 + * @author huanglm + * @return 变动后的时间 + */ + public static Date add(Date date, int field, int amount) { + if (date == null) { + date = new Date(); + } + + Calendar cal = Calendar.getInstance(); + cal.setTime(date); + cal.add(field, amount); + + return cal.getTime(); + } + + /** + * + * @param date + * @param amount + * @author huanglm + * @return + */ + public static Date addMilliSecond(Date date, int amount) { + return add(date, Calendar.MILLISECOND, amount); + } + + /** + * + * + * @param date + * @param amount + * @author huanglm + * @return + */ + public static Date addSecond(Date date, int amount) { + return add(date, Calendar.SECOND, amount); + } + + /** + * + * @param date + * @param amount + * @author huanglm + * @return + */ + public static Date addMiunte(Date date, int amount) { + return add(date, Calendar.MINUTE, amount); + } + + /** + * + * @param date + * @param amount + * @author huanglm + * @return + */ + public static Date addHour(Date date, int amount) { + return add(date, Calendar.HOUR, amount); + } + + /** + * + * @param date + * @param amount + * @author huanglm + * @return + */ + public static Date addDay(Date date, int amount) { + return add(date, Calendar.DATE, amount); + } + + /** + * + * @param date + * @param amount + * @author huanglm + * @return + */ + public static Date addMonth(Date date, int amount) { + return add(date, Calendar.MONTH, amount); + } + + /** + * + * @param date + * @param amount + * @author huanglm + * @return + */ + public static Date addYear(Date date, int amount) { + return add(date, Calendar.YEAR, amount); + } + public static final SimpleDateFormat YYYYMMDDHHMMSS_DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); + public static Date ORIGINAL_DATE = null; + static { + try { + ORIGINAL_DATE = YYYYMMDDHHMMSS_DATE_FORMAT.parse("19700101080000"); + } catch (ParseException e) { + + } + } + /** + * 从19700101080000开始增加指定的秒数 + * @param amount + * @return + */ + public static Date addSecond(int amount) { + return addSecond(ORIGINAL_DATE, amount); + } + /** + * 从19700101080000开始增加指定的秒数 + * @param amount + * @return + */ + public static String addSecondToString(int amount) { + return YYYYMMDDHHMMSS_DATE_FORMAT.format(addSecond(ORIGINAL_DATE, amount)); + } + /** + * 测试 + * + * @param args + * args + * @throws ParseException + * ParseException + * @author:Administrator + */ + public static void main(String[] args) throws ParseException { + Date date=new Date(); + System.out.println(addMonth(DateUtils.getDate("2024-01-29","yyyy-mm-dd"),1)); + date.setTime(1491040070000l); + System.out.println(getTimeStr(date,2)); + } + +} diff --git a/luqj-common/src/main/java/com/luqj/util/log/LogUtil.java b/luqj-common/src/main/java/com/luqj/util/log/LogUtil.java new file mode 100644 index 0000000..6e25eeb --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/log/LogUtil.java @@ -0,0 +1,174 @@ +package com.luqj.util.log; + +import java.io.PrintWriter; +import java.io.StringWriter; + +public abstract class LogUtil { + + private static String getStackTrace(Throwable t) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + try { + t.printStackTrace(pw); + return sw.toString(); + } finally { + pw.close(); + } + } + + public static String exceptionMsg(String msg, Throwable e) { + return msg + ",异常消息[" + getStackTrace(e) + "]"; + } + + public static String exceptionSimpleMsg(String msg, Throwable e) { + return msg + ",异常消息[" + e.getLocalizedMessage() + "]"; + } + + /** + * 获取计算程序运行的时钟 + * + * @return clock + */ + public static Clock getClock() { + return new Clock() { + /**开始时间*/ + private long startTime = System.nanoTime(); + + /** + * 消耗时间[毫秒] + * @return 消耗时间 + */ + public long consume() { + return LogUtil.consume(startTime, System.nanoTime()); + } + + /** + * 结束时间 + */ + public long getEnd() { + return System.nanoTime(); + } + + /** + * 开始时间 + */ + public long getStart() { + return startTime; + } + + public long consumeSecond() { + return LogUtil.consumeSecond(startTime, System.nanoTime()); + } + }; + } + + + /** + * 消耗时间[纳秒] + * + * @return 消耗时间 秒 + */ + public static long consumeNano(long startTime, long endTime) { + return (endTime - startTime) / 1000000000 + 1; + } + + /** + * 消耗时间[微秒] + * + * @return 消耗时间 秒 + */ + public static long consume(long startTime, long endTime) { + return (endTime - startTime) / 1000000 + 1; + } + + /** + * 消耗时间[耗秒] + * + * @return 消耗时间 秒 + */ + public static long consumeSecond(long startTime, long endTime) { + return (endTime - startTime) / 1000 + 1; + } + + /** + * getRootCause + * 获取异常的原始异常,用于反馈异常的真实原因。 + * + * @param ex 异常信息 + * @return 原始异常,最底层异常 + * @author 林小松 + */ + public static Throwable getRootCause(Throwable ex) { + Throwable cause = ex; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + return cause; + } + + /** + * 递归寻找根异常异常信息 + * + * @param ex 异常 + * @return 异常信息 + */ + public static String traceRootExceptionInfo(Throwable ex) { + Throwable cause = ex; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + return cause.toString(); + } + + /** + * 递归寻找引起异常的所有异常信息 + * + * @param ex 异常 + * @return 异常信息 + */ + public static String tarceExceptionInfo(Throwable ex) { + StringBuffer sb = new StringBuffer(); + Throwable cause = ex; + sb.insert(0, cause); + while (cause.getCause() != null) { + cause = cause.getCause(); + sb.insert(0, cause.toString()); + } + return sb.toString(); + } + + public static interface Clock { + + + /** + * 返回程序消耗的毫秒数 + * + * @return 消耗毫秒数 + */ + long consume(); + + /** + * 返回程序消耗的秒数 + * + * @return 消耗秒数 + */ + long consumeSecond(); + + /** + * 返回开始时间 + * + * @return 开始时间 + * @author:lwei + */ + long getStart(); + + /** + * 返回结束时间 + * + * @return 结束时间 + * @author:lwei + */ + long getEnd(); + } + +} diff --git a/luqj-common/src/main/java/com/luqj/util/parse/SymbolSet.java b/luqj-common/src/main/java/com/luqj/util/parse/SymbolSet.java new file mode 100644 index 0000000..7a53441 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/parse/SymbolSet.java @@ -0,0 +1,65 @@ +package com.luqj.util.parse; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 符号集 + * @author chenzm + */ +public class SymbolSet { + /**等号*/ + public final static String SYMBOL_EQ = "="; + + /**空字符*/ + public final static Character SYMBOL_NULL = ' '; + + /**逗号*/ + public final static String SYMBOL_COMMA = ","; + + /**双引号*/ + public final static String SYMBOL_DQM = "\""; + + /**单引号*/ + public final static String SYMBOL_SQM = "\'"; + + public static String chr2Str(char chr) { + return "" + chr; + } + + static boolean isInSymbol(Map> symBolPos, int charPos, String ...symbols){ + for(String symbol : symbols) { + if(!symBolPos.containsKey(symbol)) { + return false; + } + List posInfo = symBolPos.get(symbol); + for(int i = 0; i < posInfo.size(); ) { + if(charPos > posInfo.get(i) && charPos < posInfo.get(i + 1)) { + return true; + } + i+=2; + } + } + return false; + } + + static Map> getSymBolPos(String exp) { + Map> map = new HashMap>(); + String[] symbols = new String[]{ + SYMBOL_SQM, SYMBOL_DQM + }; + for(String symbol : symbols) { + map.put(symbol, new ArrayList(exp.length())); + int charPos = 0; + for(char c : exp.toCharArray()) { + if(c == symbol.charAt(0)) { + map.get(symbol).add(charPos); + } + charPos++; + } + } + return map; + } +} diff --git a/luqj-common/src/main/java/com/luqj/util/reflect/ClassUtils.java b/luqj-common/src/main/java/com/luqj/util/reflect/ClassUtils.java new file mode 100644 index 0000000..7a809c5 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/reflect/ClassUtils.java @@ -0,0 +1,762 @@ +package com.luqj.util.reflect; + +import com.luqj.util.NumFormat; +import com.luqj.util.assertion.Assert; +import javassist.*; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.LocalVariableAttribute; +import javassist.bytecode.MethodInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Modifier; +import java.lang.reflect.*; +import java.net.URL; +import java.net.URLDecoder; +import java.util.*; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +public class ClassUtils { + private static Logger LOGGER = LoggerFactory.getLogger(ClassUtils.class); + + private static ClassPool pool = ClassPool.getDefault(); + + static { + + } + + + public static Annotation[] getAnnotation(Class type, Class annotation) { + + List list = new ArrayList(); + Class clazz = type; + for (; clazz != Object.class; clazz = clazz.getSuperclass()) { + try { + if (clazz.getAnnotation(annotation) != null) { + list.add(clazz.getAnnotation(annotation)); + } + } catch (Exception e) { + // 这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 + // 如果这里的异常打印或者往外抛,则就不会执行clazz = + // clazz.getSuperclass(),最后就不会进入到父类中了 + + } + } + return list.toArray(new Annotation[]{}); + } + + /** + * 通过反射,获得定义Class时声明的父类的范型参数的类型. + * 如public BookManager extends GenricManager + * + * @param clazz clazz The class to introspect + * @param index the Index of the generic ddeclaration,start from 0. + */ + @SuppressWarnings("rawtypes") + public static Class getSuperClassGenericity(Class clazz, int index) throws IndexOutOfBoundsException { + Type genType = clazz.getGenericSuperclass(); + if (!(genType instanceof ParameterizedType)) { + return Object.class; + } + Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); + if (index >= params.length || index < 0) { + return Object.class; + } + if (!(params[index] instanceof Class)) { + return Object.class; + } + return (Class) params[index]; + } + + public static String getDefBeanName(Class classType) { + String name = classType.getSimpleName(); + String firstChat = name.substring(0, 1).toLowerCase(); + return firstChat + name.subSequence(1, name.length()); + } + + public static T instanceByConstructor(Class tClass,Object... constructorParams) throws Throwable{ + Class[] constructorTypes = new Class[constructorParams.length]; + for (int i = 0; i < constructorParams.length; i++) { + constructorTypes[i] = constructorParams[i].getClass(); + } + Constructor cla = tClass.getDeclaredConstructor(constructorTypes); + return (T) cla.newInstance(constructorParams); + } + + public static String classPackageAsResourcePath(Class clazz) { + if (clazz == null) { + return ""; + } + String className = clazz.getName(); + int packageEndIndex = className.lastIndexOf('.'); + if (packageEndIndex == -1) { + return ""; + } + String packageName = className.substring(0, packageEndIndex); + return packageName.replace('.', '/'); + } + + + public static ClassLoader getDefaultClassLoader() { + ClassLoader cl = null; + try { + cl = Thread.currentThread().getContextClassLoader(); + } catch (Throwable ex) { + // Cannot access thread context ClassLoader - falling back to system class loader... + } + if (cl == null) { + // No thread context class loader -> use class loader of this class. + cl = ClassUtils.class.getClassLoader(); + } + return cl; + } + + public static Map getMethodParams(Class clas, Method m) throws NotFoundException { + Map params = new LinkedHashMap(); + pool.insertClassPath(new ClassClassPath(clas)); + CtClass ctClass = pool.get(clas.getName()); + CtMethod cm = ctClass.getDeclaredMethod(m.getName()); + MethodInfo methodInfo = cm.getMethodInfo(); + Class[] parameterTypes = m.getParameterTypes(); + Type[] parameterGTypes = m.getGenericParameterTypes(); + CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); + LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute + .getAttribute(LocalVariableAttribute.tag); + if (attr == null) { + throw new NotFoundException(codeAttribute.toString()); + } + String[] paramNames = new String[cm.getParameterTypes().length]; + int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; + for (int j = 0; j < paramNames.length; j++) { + MethodParam mp = new MethodParam(j, attr.variableName(j + pos), parameterTypes[j]); + mp.setT(getTypeGenericity(parameterGTypes[j])); + params.put(mp.getName(), mp); + } + LOGGER.trace("方法[" + m.getName() + "]参数为" + params); + return params; + } + + /** + * 获取类型属性的泛型类型 + * + * @return + */ + public static Class[] getTypeGenericity(Type fc) { + if (fc == null) { + return new Class[]{}; + } + // 【3】如果是泛型参数的类型 + if (fc instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) fc; + Type[] ts = pt.getActualTypeArguments(); + List> t = new ArrayList>(); + for (int i = 0; i < ts.length; i++) { + if (ts[i] instanceof WildcardType) { + //泛型可能是 + } else { + t.add((Class) ts[i]); + } + + } + return t.toArray(new Class[]{}); + } else { + return new Class[]{}; + } + } + + + public static boolean isListType(Field field) { + return isListType(field.getType()); + } + + public static boolean isListType(Class objType) { + Class[] interfaces = objType.getInterfaces(); + for (Class i : interfaces) { + if (i.equals(List.class)) { + return true; + } + } + return objType.isAssignableFrom(List.class); + } + + public static boolean isMapType(Field field) { + Class fieldClazz = field.getType(); + return isMapType(fieldClazz); + } + + public static boolean isMapType(Class objType) { + return isType(objType, Map.class); + } + + public static boolean isSetType(Field field) { + Class fieldClazz = field.getType(); + return isSetType(fieldClazz); + } + + public static boolean isSetType(Class objType) { + return isType(objType, Set.class); + } + + /** + * @return + */ + public static boolean isType(Class parentType, Class child) { + return parentType.isAssignableFrom(child); + } + + /** + * 获取List类型属性的泛型类型 + * + * @param field + * @return + */ + public static Type getSetFieldGenericity(Field field) { + Class fieldClazz = field.getType(); + Assert.logic(isSetType(fieldClazz), "属性类型必须为Set类型"); + Type fc = field.getGenericType(); // 关键的地方,如果是List类型,得到其Generic的类型 + if (fc == null) { + return null; + } + // 【3】如果是泛型参数的类型 + if (fc instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) fc; + return pt.getActualTypeArguments()[0]; // 【4】 + } else { + return null; + } + } + + + /** + * 获取List类型属性的泛型类型 + * + * @param field + * @return + */ + public static Type[] getMapFieldGenericity(Field field) { + Class fieldClazz = field.getType(); + Assert.logic(isMapType(fieldClazz), "属性类型必须为Map类型"); + Type fc = field.getGenericType(); // 关键的地方,如果是List类型,得到其Generic的类型 + if (fc == null) { + return null; + } + // 【3】如果是泛型参数的类型 + if (fc instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) fc; + return pt.getActualTypeArguments(); // 【4】 + } else { + return null; + } + } + + /** + * 获取List类型属性的泛型类型 + * + * @param field + * @return + */ + public static Class getListGenericity(Field field) { + Class fieldClazz = field.getType(); + Assert.logic(isListType(fieldClazz), "属性类型必须为List类型"); + Type fc = field.getGenericType(); // 关键的地方,如果是List类型,得到其Generic的类型 + if (fc == null) { + return null; + } + // 【3】如果是泛型参数的类型 + if (fc instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) fc; + return (Class) pt.getActualTypeArguments()[0]; // 【4】 + } else { + return null; + } + } + + /** + * 获取List类型属性的泛型类型 + * + * @param field + * @return + */ + public static Class getListFieldGenericity(Field field) { + Class fieldClazz = field.getType(); + Assert.logic(fieldClazz.isAssignableFrom(List.class), "属性类型必须为List类型"); + Type fc = field.getGenericType(); // 关键的地方,如果是List类型,得到其Generic的类型 + if (fc == null) { + return null; + } + // 【3】如果是泛型参数的类型 + if (fc instanceof ParameterizedType) { + ParameterizedType pt = (ParameterizedType) fc; + return (Class) pt.getActualTypeArguments()[0]; // 【4】 + } else { + return null; + } + } + + /** + * 判断属性名是否存在避免调用 getField(String name) 抛异常 + * + * @param type + * @return + */ + public static boolean existField(Class type, Class fieldType) { + if (fieldType == null) { + return false; + } + Field[] fs = getDeclaredFields(type); + for (Field field : fs) { + if (field.getType().equals(fieldType)) { + return true; + } + } + return false; + } + + + public static Method getDeclaredMethod(Object object, String methodName, Class... parameterTypes) { + Method method = null; + for (Class clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) { + try { + clazz.getMethods(); + method = clazz.getMethod(methodName, parameterTypes); + return method; + } catch (Exception e) { + //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 + //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了 + + } + } + return null; + } + + public static Method[] getDeclaredMethods(Object object) { + List list = new ArrayList(); + for (Class clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) { + try { + for (Method method : clazz.getDeclaredMethods()) { + if (!Modifier.isStatic(method.getModifiers())) { + list.add(method); + } + } + } catch (Exception e) { + //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 + //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了 + + } + } + return list.toArray(new Method[]{}); + } + + /** + * 递归获取所有的接口 + * + * @param clazz + * @return + */ + public static Class[] getInterfaces(Class clazz) { + List> list = new LinkedList>(); + Class[] interfaces = clazz.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) { + Class ifs = interfaces[i]; + list.add(ifs); + list.addAll(Arrays.asList(getInterfaces(ifs))); + } + return list.toArray(new Class[list.size()]); + } + + + /** + * 直接调用对象方法, 而忽略修饰符(private, protected, default) + * + * @param object : 子类对象 + * @param methodName : 父类中的方法名 + * @param parameterTypes : 父类中的方法参数类型 + * @param parameters : 父类中的方法参数 + * @return 父类中方法的执行结果 + */ + + public static Object invokeMethod(Object object, String methodName, Class[] parameterTypes, + Object[] parameters) { + //根据 对象、方法名和对应的方法参数 通过反射 调用上面的方法获取 Method 对象 + Method method = getDeclaredMethod(object, methodName, parameterTypes); + Assert.notNull(method, "方法[" + methodName + "]不允许为空"); + //抑制Java对方法进行检查,主要是针对私有方法而言 + method.setAccessible(true); + try { + if (null != method) { + // 调用object 的 method 所代表的方法,其方法的参数是 parameters + return method.invoke(object, parameters); + } + } catch (Exception e) { + + throw new IllegalArgumentException("方法执行异常,异常消息[" + e.getMessage() + "]", e); + } + return null; + } + + + /** + * 包括父类的属性 + * + * @param type + * @return + */ + public static Field[] getDeclaredFields(Class type) { + List list = new ArrayList(); + Class clazz = type; + for (; clazz != Object.class; clazz = clazz.getSuperclass()) { + try { + for (Field field : clazz.getDeclaredFields()) { + if (!Modifier.isStatic(field.getModifiers())) { + list.add(field); + } + } + } catch (Exception e) { + // 这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 + // 如果这里的异常打印或者往外抛,则就不会执行clazz = + // clazz.getSuperclass(),最后就不会进入到父类中了 + + } + } + return list.toArray(new Field[]{}); + } + + + public static Field[] getDeclaredFields(Class type, Class a) { + List fs = new ArrayList<>(); + Field[] fields = getDeclaredFields(type); + for (Field field : fields) { + if (field.getType().getAnnotation(a) != null) { + fs.add(field); + } + } + return fs.toArray(new Field[]{}); + } + + /** + * 包括父类的属性 + * + * @param type + * @param fieldName + * @return + */ + public static Field getDeclaredFields(Class type, String fieldName) { + Field field = null; + Class clazz = type; + for (; clazz != Object.class; clazz = clazz.getSuperclass()) { + try { + field = clazz.getDeclaredField(fieldName); + return field; + } catch (Exception e) { + // 这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 + // 如果这里的异常打印或者往外抛,则就不会执行clazz = + // clazz.getSuperclass(),最后就不会进入到父类中了 + + } + } + return null; + } + + /** + * 判断属性名是否存在避免调用 getField(String name) 抛异常 + * + * @param type + * @param fieldName + * @return + */ + public static boolean existField(Class type, String fieldName) { + if (fieldName == null) { + return false; + } + return getDeclaredFields(type, fieldName) != null; + } + + /** + * 递归寻找属性的类型 + * + * @param beanType 根类型 + * @param fieldStr 如bean.field.field + * @return + */ + public static final Class[] getTypes(Class beanType, String fieldStr) { + Assert.notNull(beanType, "根类型不允许为空"); + Assert.hasText(fieldStr, "属性串不允许为空"); + String[] fieldNames = fieldStr.split("\\."); + List> returnTypes = new ArrayList>(); + + Class returnType = beanType; + for (String fn : fieldNames) { + if (ClassUtils.existField(returnType, fn)) { + Field f; + f = getDeclaredFields(returnType, fn); + returnTypes.add(f.getType()); + returnType = f.getType(); + } else { + return returnTypes.toArray(new Class[0]); + } + } + return returnTypes.toArray(new Class[0]); + } + + + public static final boolean isBaseType(Field field) { + Assert.notNull(field, "属性不允许为空!"); + return isBaseType(field.getType()); + } + + public static final Object initBaseValue(Class objType) { + return parseBaseValue(objType, ""); + } + + + public static final Object parseBaseValue(Class objType, Object value) { + Assert.logic(isBaseType(objType), "需要转换的必须是基本类型"); + if (Short.class.equals(objType) || short.class.equals(objType)) { + return NumFormat.$Long(value); + } else if (Integer.class.equals(objType) || int.class.equals(objType)) { + return NumFormat.$Intger(value); + } else if (Long.class.equals(objType) || long.class.equals(objType)) { + return NumFormat.$Long(value); + } else if (Float.class.equals(objType) || float.class.equals(objType)) { + return NumFormat.$Float(value); + } else if (Double.class.equals(objType) || double.class.equals(objType)) { + return NumFormat.$Double(value); + } else if (String.class.equals(objType)) { + return value; + } else if (Boolean.class.equals(objType) || boolean.class.equals(objType)) { + if (value == null) { + return Boolean.FALSE; + } else { + return Boolean.getBoolean(value.toString()); + } + + } + return null; + } + + + public static final Object parseBaseValue(Class objType, String value) { + Assert.logic(isBaseType(objType), "需要转换的必须是基本类型"); + if (Short.class.equals(objType) || short.class.equals(objType)) { + return NumFormat.$Short(value.trim()); + } else if (Integer.class.equals(objType) || int.class.equals(objType)) { + return NumFormat.$Intger(value.trim()); + } else if (Long.class.equals(objType) || long.class.equals(objType)) { + return NumFormat.$Long(value.trim()); + } else if (Float.class.equals(objType) || float.class.equals(objType)) { + return NumFormat.$Float(value.trim()); + } else if (Double.class.equals(objType) || double.class.equals(objType)) { + return NumFormat.$Double(value.trim()); + } else if (String.class.equals(objType)) { + return value; + } else if (Boolean.class.equals(objType) || boolean.class.equals(objType)) { + return Boolean.parseBoolean(value.trim()); + } + return null; + } + + public static final boolean isBaseType(Class beanType) { + Assert.notNull(beanType, "类型不允许为空!"); + return beanType.isPrimitive() + || String.class.equals(beanType) + || Long.class.equals(beanType) + || Short.class.equals(beanType) + || Character.class.equals(beanType) + || Integer.class.equals(beanType) + || Double.class.equals(beanType) + || Boolean.class.equals(beanType) + || Float.class.equals(beanType); + } + + public static final Object newInstance(Class beanType, String fieldStr) + throws InstantiationException, + IllegalAccessException, SecurityException, NoSuchFieldException { + Assert.notNull(beanType, "根类型不允许为空"); + Assert.hasText(fieldStr, "属性串不允许为空"); + + Class[] types = getTypes(beanType, fieldStr); + if (types.length == 0) { + return null; + } + String[] fieldNames = fieldStr.split("\\."); + Object root = beanType.newInstance(); + Object obj = root; + Class tmpType = beanType; + int i = 0; + for (Class type : types) { + Object objTmp = type.newInstance(); + GSetterUtil.setValueBySetter(obj, tmpType.getDeclaredField(fieldNames[i]), objTmp); + obj = objTmp; + tmpType = type; + i++; + } + return GSetterUtil.getValueByGetter(root, beanType.getDeclaredField(fieldNames[0])); + } + + + /** + * 递归寻找属性的类型 + * + * @param beanType 根类型 + * @param fieldStr 如bean.field.field + * @return + */ + public static final Class getType(Class beanType, String fieldStr) { + Assert.notNull(beanType, "根类型不允许为空"); + Assert.hasText(fieldStr, "属性串不允许为空"); + String[] fieldNames = fieldStr.split("\\."); + Class returnType = beanType; + for (String fn : fieldNames) { + if (ClassUtils.existField(returnType, fn)) { + Field f; + try { + f = getDeclaredFields(returnType, fn); + returnType = f.getType(); + } catch (NullPointerException e) { + //找不到字段返回NULL + + return null; + } + } else { + return null; + } + } + return returnType; + } + + /** + * 获取某个包下面的class + * + * @param pack + * @return + */ + public static List getClasssFromPackage(String pack) { + List classNames = new ArrayList(); + // 是否循环搜索子包 + boolean recursive = true; + // 包名字 + String packageName = pack; + // 包名对应的路径名称 + String packageDirName = packageName.replace('.', '/'); + Enumeration dirs; + try { + dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); + while (dirs.hasMoreElements()) { + URL url = dirs.nextElement(); + String protocol = url.getProtocol(); + if ("file".equals(protocol)) { + System.out.println("file类型的扫描"); + String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); + findClassInPackageByFile(packageName, filePath, recursive, classNames); + } else if ("jar".equals(protocol)) { + System.out.println("jar类型的扫描"); + } + } + } catch (Exception e) { + + } + return classNames; + } + + private static void findClassInPackageByFile(String packageName, String filePath, final boolean recursive, List clazzNames) { + File dir = new File(filePath); + if (!dir.exists() || !dir.isDirectory()) { + return; + } + // 在给定的目录下找到所有的文件,并且进行条件过滤 + File[] dirFiles = dir.listFiles(new FileFilter() { + @Override + public boolean accept(File file) { + boolean acceptDir = recursive && file.isDirectory();// 接受dir目录 + boolean acceptClass = file.getName().endsWith("class");// 接受class文件 + return acceptDir || acceptClass; + } + }); + + for (File file : dirFiles) { + if (file.isDirectory()) { + findClassInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, clazzNames); + } else { + String className = file.getName().substring(0, file.getName().length() - 6); + try { + clazzNames.add(packageName + "." + className); + } catch (Exception e) { + + } + } + } + } + + /** + * 从jar文件中读取指定目录下面的所有的class文件 + * + * @param jarPath jar文件存放的位置 + * @param jarPath 指定的文件目录 + * @return 所有的的class的对象 + */ + public static List getClasssFromJarFile(String jarPath) { + List classNameList = new ArrayList<>(); + JarFile jarFile = null; + try { + jarFile = new JarFile(jarPath); + } catch (IOException e1) { + + } + List jarEntryList = new ArrayList<>(); + Enumeration ee = jarFile.entries(); + while (ee.hasMoreElements()) { + JarEntry entry = ee.nextElement(); +// entry.getName().startsWith(filePath) && + if (entry.getName().endsWith(".class")) { + jarEntryList.add(entry); + } + } + for (JarEntry entry : jarEntryList) { + String className = entry.getName().replace('/', '.'); + className = className.substring(0, className.length() - 6); + classNameList.add(className); + } + return classNameList; + } + + public static Class[] getMethodParamTypes(Object classInstance, String methodName) { + Class[] paramTypes = null; + try { + Method[] methods = classInstance.getClass().getMethods();//全部方法 + for (int i = 0; i < methods.length; i++) { + if (methodName.equals(methods[i].getName())) {//和传入方法名匹配 + Class[] params = methods[i].getParameterTypes(); + paramTypes = new Class[params.length]; + for (int j = 0; j < params.length; j++) { + paramTypes[j] = Class.forName(params[j].getName()); + } + break; + } + } + }catch (Throwable e) { + throw new IllegalStateException("获取方法参数类型失败", e); + } + return paramTypes; + } + + public static Method findDeclaredMethod(Object object, String methodName) { + Method execMethod = null; + for (Method method : object.getClass().getDeclaredMethods()) { + if (method.getName().equals(methodName)) { + execMethod = method; + break; + } + } + return execMethod; + } + + public static void main(String[] args) { + System.out.println(Arrays.asList(getDeclaredFields(ClassUtils.class))); + } + +} diff --git a/luqj-common/src/main/java/com/luqj/util/reflect/GSetterUtil.java b/luqj-common/src/main/java/com/luqj/util/reflect/GSetterUtil.java new file mode 100644 index 0000000..7224550 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/reflect/GSetterUtil.java @@ -0,0 +1,196 @@ +package com.luqj.util.reflect; + +import com.luqj.util.assertion.Assert; +import com.luqj.util.log.LogUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +public abstract class GSetterUtil { + private static Logger _log = LoggerFactory.getLogger(GSetterUtil.class); + + public static final String PREFIX_GETTER = "get"; + + public static final String PREFIX_SETTER = "set"; + + + public static Object getValueByGetter(Object obj,String fieldName){ + Field f = ClassUtils.getDeclaredFields(obj.getClass(), fieldName); + Assert.notNull(f, obj.getClass()+",找不到指定的属性["+fieldName+"]"); + return getValueByGetter(obj, f); + } + + /** + * 判断属性是否可操作,是否有公共getter,setter方法 + * @return + */ + public static boolean isOpAbleField(Class type,Field f){ + return getGetter(type, f) != null && getSetter(type, f) != null; + } + + /** + * 判断指定的对象属性是否存在getter方法 + * @param f + * @return + */ + public static boolean existGetter(Class type,Field f){ + return getGetter(type, f) != null; + } + + /** + * 判断指定的对象属性是否存在setter方法 + * @param f + * @return + */ + public static boolean existSetter(Class type,Field f){ + return getSetter(type, f) != null; + } + + public static void setValueBySetter(Object obj,Field f,Object paramValue){ + setValueBySetter(obj, f.getName(), paramValue,f.getType()); + } + + public static void setValueBySetter(Object obj,String fieldName,Object paramValue,Class paramType){ + Method m = getSetter(obj.getClass(),fieldName,paramType); + Assert.notNull(m,obj.getClass().getSimpleName()+"属性["+fieldName+"]不存在setter方法"); + try { + m.invoke(obj,paramValue); + } catch (Throwable e) { + + _log.error(LogUtil.exceptionMsg("["+fieldName+"]set方法"+m.getName()+"设置出现异常", e),e); + } + } + + public static Object getValueByGetter(Object obj,Field f){ + Method m = getGetter(obj.getClass(), f); + Assert.notNull(m,"属性["+f.getName()+"]不存在getter方法"); + try { + return m.invoke(obj); + } catch (Throwable e) { + + _log.error(LogUtil.exceptionMsg(f+"set方法"+m.getName()+"设置出现异常", e)); + return null; + } + } + + public static String getGetterMethodName(String fieldName){ + Assert.hasText(fieldName,"属性名必须有内容!"); + return PREFIX_GETTER + upperFirstChar(fieldName); + } + + public static String getSetterMethodName(String fieldName){ + Assert.hasText(fieldName,"属性名必须有内容!"); + return PREFIX_SETTER + upperFirstChar(fieldName); + } + + public static String upperFirstChar(String fieldName){ + return fieldName.substring(0,1).toUpperCase() + + fieldName.substring(1,fieldName.length()); + } + + public static String lowerFirstChar(String fieldName){ + return fieldName.substring(0,1).toLowerCase() + + fieldName.substring(1,fieldName.length()); + } + + + public static boolean isGetter(Method method){ + return method.getModifiers() == Modifier.PUBLIC + && method.getName().length() > PREFIX_GETTER.length() + && method.getName().startsWith(PREFIX_GETTER) + && method.getParameterTypes().length == 0; + } + + public static boolean isSetter(Method method){ + return (method.getModifiers() & Modifier.PUBLIC) == 1 + && method.getName().length() > PREFIX_SETTER.length() + && method.getName().startsWith(PREFIX_SETTER) + && method.getParameterTypes().length == 1; + } + + /** + * 获取setter方法,如果找不到或达不到要求返回NULL + * @param type + * @param f + * @return + */ + public static Method getSetter(Class type,String fieldName,Class fieldType){ + try { + Method m = type.getMethod(getSetterMethodName(fieldName), fieldType); + if(isSetter(m)){ + return m; + }else{ + return null; + } + } catch (Exception e) { + return null; + } + } + + + /** + * 获取setter方法,如果找不到或达不到要求返回NULL + * @param type + * @param f + * @return + */ + public static Method getSetter(Class type,Field f){ + return getSetter(type, f.getName(), f.getType()); + } + + + + /** + * 获取getter方法,如果找不到或达不到要求返回NULL + * @param type + * @param f + * @return + */ + public static Method getGetter(Class type,Field f){ + try { + Method m = type.getMethod(getGetterMethodName(f.getName())); + if(isGetter(m)){ + return m; + }else{ + return null; + } + } catch (Exception e) { + return null; + } + } + + + /** + * 根据setter方法获取属性名 + * @param method + * @return + */ + public static String getFieldNameBySetter(Method method){ + //get开头且没有参数 + Assert.notNull(method,"方法不允许为NULL"); + Assert.logic(isSetter(method), + method.getName()+"["+method.getParameterTypes().length+"]不是JAVA标准set方法"); + String fieldName = method.getName().substring(PREFIX_SETTER.length()); + fieldName = lowerFirstChar(fieldName); + return fieldName; + } + + /** + * 根据getter方法获取属性名 + * @param method + * @return + */ + public static String getFieldNameByGetter(Method method){ + //get开头且没有参数 + Assert.notNull(method,"方法不允许为NULL"); + Assert.logic(isGetter(method), + method.getName()+"["+method.getParameterTypes().length+"]不是JAVA标准get方法"); + String fieldName = method.getName().substring(PREFIX_GETTER.length()); + fieldName = lowerFirstChar(fieldName); + return fieldName; + } + +} diff --git a/luqj-common/src/main/java/com/luqj/util/reflect/JarUtils.java b/luqj-common/src/main/java/com/luqj/util/reflect/JarUtils.java new file mode 100644 index 0000000..33bb0e7 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/reflect/JarUtils.java @@ -0,0 +1,139 @@ +package com.luqj.util.reflect; + + + +import com.luqj.util.assertion.Assert; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +public class JarUtils { + + + public static interface JarOperator { + void operate(JarFile jar, String className, JarEntry entry); + } + + + public static class ClassLoaderOP implements JarOperator { + + private ClassLoader loader; + private Method md1; + + public ClassLoaderOP(ClassLoader loader) { + super(); + try { + this.loader = loader; + md1 = ClassLoader.class.getDeclaredMethod( + "defineClass", + String.class, byte[].class, int.class, int.class); + md1.setAccessible(true); + } catch (Exception e) { + Assert.fail("jar文件加载初始化异常,异常消息[" + e.getMessage() + "]"); + } + } + + @Override + public void operate(JarFile jar, String className, JarEntry entry) { + try { + InputStream is = jar.getInputStream(entry); + ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); + byte[] packData = new byte[2048]; + int readLen = 0; + while (-1 != (readLen = is.read(packData))) { + dataOut.write(packData, 0, readLen); + } + if (dataOut.size() <= 0) { + throw new ClassNotFoundException(className); + } + byte[] classFile = dataOut.toByteArray(); + md1.invoke(loader, className, classFile, 0, classFile.length); + } catch (Exception e) { + + Assert.fail("类:" + className + "加载异常,异常消息[" + e.getMessage() + "]"); + } + } + } + + public static void operateJar(String file, JarOperator op) { + try { + JarFile jar = new JarFile(file); + Enumeration d = jar.entries(); + while (d.hasMoreElements()) { + JarEntry entry = (JarEntry) d.nextElement(); + if (entry.getName().endsWith(".class")) { + String name = entry.getName(); + name = name.substring(0, name.length() - 6); + name = name.replaceAll("/", "."); + op.operate(jar, name, entry); + } + } + } catch (IOException e) { + + Assert.fail("解析JAR:" + file + "出现异常,异常消息[" + e.getMessage() + "]"); + } + } + + public static void loadClass(String file, ClassLoader loader) { + ClassLoaderOP op = new ClassLoaderOP(loader); + operateJar(file, op); + } + + + /** + * 获取所有的 JAVA类信息 + * + * @param file + * @return 返回全局类名 + */ + public static Collection getAllClassInfo(String file) { + List infos = new ArrayList(); + try { + JarFile jar = new JarFile(file); + Enumeration d = jar.entries(); + while (d.hasMoreElements()) { + JarEntry entry = (JarEntry) d.nextElement(); + if (entry.getName().endsWith(".class")) { + String name = entry.getName(); + name = name.substring(0, name.length() - 6); + name = name.replaceAll("/", "."); + infos.add(name); + } + } + return infos; + } catch (IOException e) { + + Assert.fail("解析JAR:" + file + "出现异常,异常消息[" + e.getMessage() + "]"); + } + return infos; + } + + public static Collection getResources(String filePath, String dirPath) { + List infos = new ArrayList(); + try { + JarFile jar = new JarFile(filePath); + Enumeration d = jar.entries(); + while (d.hasMoreElements()) { + JarEntry entry = (JarEntry) d.nextElement(); + if (entry.getName().startsWith(dirPath) && !entry.isDirectory()) { + infos.add(entry.getName()); + } + } + return infos; + } catch (IOException e) { + + Assert.fail("解析JAR:" + filePath + "出现异常,异常消息[" + e.getMessage() + "]"); + } + return infos; + } + + +} diff --git a/luqj-common/src/main/java/com/luqj/util/reflect/MethodParam.java b/luqj-common/src/main/java/com/luqj/util/reflect/MethodParam.java new file mode 100644 index 0000000..7efeb19 --- /dev/null +++ b/luqj-common/src/main/java/com/luqj/util/reflect/MethodParam.java @@ -0,0 +1,73 @@ +package com.luqj.util.reflect; + +public class MethodParam { + + private int index; + + private String name; + + private Class type; + + /** + * 参数的泛型类型集合 + */ + private Class[] t; + + private Object value; + + + public MethodParam(int index, String name, Class type) { + super(); + this.index = index; + this.name = name; + this.type = type; + } + + public Class[] getT() { + return t; + } + + + public void setT(Class[] ts) { + t = ts; + } + + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + @Override + public String toString() { + return "MethodParam [index=" + index + ", name=" + name + ", type=" + type + "]"; + } + + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Class getType() { + return type; + } + + public void setType(Class type) { + this.type = type; + } +} diff --git a/luqj-djl/pom.xml b/luqj-djl/pom.xml new file mode 100644 index 0000000..887036c --- /dev/null +++ b/luqj-djl/pom.xml @@ -0,0 +1,286 @@ + + 4.0.0 + + com.ruoyi + ruoyi + 3.4.0 + + luqj-djl + 3.4.0 + jar + + luqj-djl + http://maven.apache.org + + + UTF-8 + 0.34.0 + 1.1.0 + 1.5.11 + + macosx-arm64 + linux-x86_64 + linux-arm64 + windows-x86_64 + + + win-x86_64 + linux-x86_64 + linux-aarch64 + osx-aarch64 + + + + + ai.djl + bom + ${djl.version} + pom + import + + + cn.smartjavaai + bom + ${smartjavaai.version} + pom + + import + + + com.microsoft.onnxruntime + onnxruntime + 1.16.3 + + + + + + + cn.smartjavaai + ocr + + + + + ai.djl.pytorch + pytorch-jni + 2.7.1-0.34.0 + runtime + + + + + + org.bytedeco + javacpp + ${javacv.version} + ${javacv.platform.windows-x86_64} + + + org.bytedeco + ffmpeg + 7.1-1.5.11 + ${javacv.platform.windows-x86_64} + + + + org.bytedeco + openblas + 0.3.26-1.5.10 + ${javacv.platform.windows-x86_64} + + + + org.bytedeco + opencv + 4.9.0-1.5.10 + ${javacv.platform.windows-x86_64} + + + + ai.djl.pytorch + pytorch-native-cpu + ${djl.platform.windows-x86_64} + 2.7.1 + runtime + + + + + + + org.bytedeco + javacpp + ${javacv.version} + ${javacv.platform.linux-x86_64} + + + org.bytedeco + ffmpeg + 7.1-1.5.11 + ${javacv.platform.linux-x86_64} + + + + org.bytedeco + openblas + 0.3.26-1.5.10 + ${javacv.platform.linux-x86_64} + + + + org.bytedeco + opencv + 4.9.0-1.5.10 + ${javacv.platform.linux-x86_64} + + + + ai.djl.pytorch + pytorch-native-cpu + ${djl.platform.linux-x86_64} + 2.7.1 + runtime + + + + + org.bytedeco + javacpp + ${javacv.version} + ${javacv.platform.linux-arm64} + + + org.bytedeco + ffmpeg + 7.1-1.5.11 + ${javacv.platform.linux-arm64} + + + + org.bytedeco + openblas + 0.3.26-1.5.10 + ${javacv.platform.linux-arm64} + + + + org.bytedeco + opencv + 4.9.0-1.5.10 + ${javacv.platform.linux-arm64} + + + + ai.djl.pytorch + pytorch-native-cpu + ${djl.platform.linux-aarch64} + 2.7.1 + runtime + + + + + + org.bytedeco + javacpp + ${javacv.version} + ${javacv.platform.macosx-arm64} + + + org.bytedeco + ffmpeg + 7.1-1.5.11 + ${javacv.platform.macosx-arm64} + + + + org.bytedeco + openblas + 0.3.26-1.5.10 + ${javacv.platform.macosx-arm64} + + + + org.bytedeco + opencv + 4.9.0-1.5.10 + ${javacv.platform.macosx-arm64} + + + + ai.djl.pytorch + pytorch-native-cpu + ${djl.platform.osx-aarch64} + 2.7.1 + runtime + + + ai.djl + api + 0.34.0 + + + + + ai.djl.pytorch + pytorch-engine + 0.34.0 + + + + ai.djl + api + + + ai.djl + basicdataset + + + ai.djl + model-zoo + + + ai.djl.timeseries + timeseries + + + ai.djl.huggingface + tokenizers + + + ai.djl.audio + audio + + + + ai.djl.mxnet + mxnet-model-zoo + + + + ai.djl.pytorch + pytorch-model-zoo + + + + ai.djl.tensorflow + tensorflow-model-zoo + + + + ai.djl.onnxruntime + onnxruntime-engine + + + com.hankcs + hanlp + portable-1.8.1 + + + org.springframework + spring-context + + + diff --git a/luqj-djl/src/main/java/com/luqj/djl/init/DjlInit.java b/luqj-djl/src/main/java/com/luqj/djl/init/DjlInit.java new file mode 100644 index 0000000..c998c1d --- /dev/null +++ b/luqj-djl/src/main/java/com/luqj/djl/init/DjlInit.java @@ -0,0 +1,21 @@ +package com.luqj.djl.init; + +import com.luqj.djl.utils.EmbeddingModelSingleton; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.Arrays; + +@Component +public class DjlInit { + @Value("${simcse.path:}") + private String simcsePath; + @PostConstruct + private void init() throws Exception { +// umsVideoService.deleteRecommentByQuery("cn"); +// EmbeddingModelSingleton.getCriteria(simcsePath); +// float[] queryVector = EmbeddingModelSingleton.embed("测试用户"); +// System.out.println(Arrays.toString(queryVector)); + } +} diff --git a/luqj-djl/src/main/java/com/luqj/djl/utils/EmbeddingModelSingleton.java b/luqj-djl/src/main/java/com/luqj/djl/utils/EmbeddingModelSingleton.java new file mode 100644 index 0000000..7056750 --- /dev/null +++ b/luqj-djl/src/main/java/com/luqj/djl/utils/EmbeddingModelSingleton.java @@ -0,0 +1,71 @@ +package com.luqj.djl.utils; + +import ai.djl.Device; +import ai.djl.huggingface.translator.TextEmbeddingTranslatorFactory; +import ai.djl.inference.Predictor; +import ai.djl.repository.zoo.Criteria; +import ai.djl.repository.zoo.ZooModel; +import ai.djl.training.util.ProgressBar; +import lombok.extern.slf4j.Slf4j; + +import java.nio.file.Paths; + +@Slf4j +public class EmbeddingModelSingleton { + + private static volatile Criteria criteriaInstance; + private static volatile ZooModel model; + + private EmbeddingModelSingleton() { + // 私有构造函数,防止外部实例化 + } + + public static float[] embed(String text) { + try { + try (Predictor predictor = model.newPredictor()) { + return predictor.predict(text); + } + } catch (Exception e) { + log.error(e.getMessage()); + throw new RuntimeException(e); + } + } + + public static double cosine(float[] a, float[] b) { + double dot = 0, na = 0, nb = 0; + for (int i = 0; i < a.length; i++) { + dot += a[i] * b[i]; + na += a[i] * a[i]; + nb += b[i] * b[i]; + } + return dot / (Math.sqrt(na) * Math.sqrt(nb) + 1e-8); + } + + /** + * 获取 Criteria 单例 + */ + public static Criteria getCriteria(String path) { + if (criteriaInstance == null) { + synchronized (EmbeddingModelSingleton.class) { + if (criteriaInstance == null) { + criteriaInstance = Criteria.builder() + .setTypes(String.class, float[].class) + .optModelPath(Paths.get(path)) +// .optModelUrls("djl://ai.djl.huggingface.pytorch/princeton-nlp/unsup-simcse-roberta-base") + .optEngine("PyTorch") + .optDevice(Device.cpu()) + .optTranslatorFactory(new TextEmbeddingTranslatorFactory()) + .optModelName("sup-simcse-bert-base-uncased.pt") + .optProgress(new ProgressBar()) + .build(); + try { + model = criteriaInstance.loadModel(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + } + return criteriaInstance; + } +} diff --git a/luqj-ec/pom.xml b/luqj-ec/pom.xml new file mode 100644 index 0000000..38d6948 --- /dev/null +++ b/luqj-ec/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + com.ruoyi + ruoyi + 3.4.0 + + + luqj-ec + jar + + luqj-ec + http://maven.apache.org + + + UTF-8 + + + + + com.ruoyi + ruoyi-common + + + com.baomidou + mybatis-plus-extension + 3.4.0 + + + com.ruoyi + luqj-common + 3.4.0 + + + diff --git a/luqj-ec/src/main/java/com/luqj/ec/controller/EcCommandResultController.java b/luqj-ec/src/main/java/com/luqj/ec/controller/EcCommandResultController.java new file mode 100644 index 0000000..38b0618 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/controller/EcCommandResultController.java @@ -0,0 +1,118 @@ +package com.luqj.ec.controller; +import com.ruoyi.common.select.Ids; +import com.ruoyi.common.select.SelectItem; +import java.util.List; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.luqj.ec.domain.EcCommandResult; +import com.luqj.ec.domain.EcCommandResultPlus; +import com.luqj.ec.service.IEcCommandResultService; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.common.core.page.TableDataInfo; + +/** + * 指令执行结果(客户端回传)Controller + * + * @author luqj + * @date 2026-02-27 + */ +@RestController +@RequestMapping("/ec/ec-command-result") +public class EcCommandResultController extends BaseController +{ + @Autowired + private IEcCommandResultService ecCommandResultService; + @PreAuthorize("@ss.hasPermi('ec:ec-command-result:getByIds')") + @PostMapping("/getByIds") + public AjaxResult getByIds(@RequestBody Ids ids) + { + List list = ecCommandResultService.getByIds(ids.getLongIds(),EcCommandResultPlus::getErrorMsg,EcCommandResultPlus::getId); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('ec:ec-command-result:select')") + @GetMapping("/select") + public AjaxResult select(String keyword) + { + List list = ecCommandResultService.select(keyword); + return AjaxResult.success(list); + } + /** + * 查询指令执行结果(客户端回传)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command-result:list')") + @GetMapping("/list") + public TableDataInfo list(EcCommandResult ecCommandResult) + { + startPage(); + List list = ecCommandResultService.selectEcCommandResultList(ecCommandResult); + return getDataTable(list); + } + + /** + * 导出指令执行结果(客户端回传)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command-result:export')") + @Log(title = "指令执行结果(客户端回传)", businessType = BusinessType.EXPORT) + @GetMapping("/export") + public AjaxResult export(EcCommandResult ecCommandResult) + { + List list = ecCommandResultService.selectEcCommandResultList(ecCommandResult); + ExcelUtil util = new ExcelUtil(EcCommandResult.class); + return util.exportExcel(list, "ec-command-result"); + } + + /** + * 获取指令执行结果(客户端回传)详细信息 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command-result:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) + { + return AjaxResult.success(ecCommandResultService.selectEcCommandResultById(id)); + } + + /** + * 新增指令执行结果(客户端回传) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command-result:add')") + @Log(title = "指令执行结果(客户端回传)", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody EcCommandResult ecCommandResult) + { + return toAjax(ecCommandResultService.insertEcCommandResult(ecCommandResult)); + } + + /** + * 修改指令执行结果(客户端回传) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command-result:edit')") + @Log(title = "指令执行结果(客户端回传)", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody EcCommandResult ecCommandResult) + { + return toAjax(ecCommandResultService.updateEcCommandResult(ecCommandResult)); + } + + /** + * 删除指令执行结果(客户端回传) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command-result:remove')") + @Log(title = "指令执行结果(客户端回传)", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) + { + return toAjax(ecCommandResultService.deleteEcCommandResultByIds(ids)); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/controller/EcControlTaskController.java b/luqj-ec/src/main/java/com/luqj/ec/controller/EcControlTaskController.java new file mode 100644 index 0000000..750416a --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/controller/EcControlTaskController.java @@ -0,0 +1,118 @@ +package com.luqj.ec.controller; +import com.ruoyi.common.select.Ids; +import com.ruoyi.common.select.SelectItem; +import java.util.List; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.luqj.ec.domain.EcControlTask; +import com.luqj.ec.domain.EcControlTaskPlus; +import com.luqj.ec.service.IEcControlTaskService; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.common.core.page.TableDataInfo; + +/** + * 任务(群控核心)Controller + * + * @author luqj + * @date 2026-02-27 + */ +@RestController +@RequestMapping("/ec/ec-task") +public class EcControlTaskController extends BaseController +{ + @Autowired + private IEcControlTaskService ecControlTaskService; + @PreAuthorize("@ss.hasPermi('ec:ec-task:getByIds')") + @PostMapping("/getByIds") + public AjaxResult getByIds(@RequestBody Ids ids) + { + List list = ecControlTaskService.getByIds(ids.getLongIds(),EcControlTaskPlus::getTaskName,EcControlTaskPlus::getId); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('ec:ec-task:select')") + @GetMapping("/select") + public AjaxResult select(String keyword) + { + List list = ecControlTaskService.select(keyword); + return AjaxResult.success(list); + } + /** + * 查询任务(群控核心)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task:list')") + @GetMapping("/list") + public TableDataInfo list(EcControlTask ecControlTask) + { + startPage(); + List list = ecControlTaskService.selectEcControlTaskList(ecControlTask); + return getDataTable(list); + } + + /** + * 导出任务(群控核心)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task:export')") + @Log(title = "任务(群控核心)", businessType = BusinessType.EXPORT) + @GetMapping("/export") + public AjaxResult export(EcControlTask ecControlTask) + { + List list = ecControlTaskService.selectEcControlTaskList(ecControlTask); + ExcelUtil util = new ExcelUtil(EcControlTask.class); + return util.exportExcel(list, "ec-task"); + } + + /** + * 获取任务(群控核心)详细信息 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) + { + return AjaxResult.success(ecControlTaskService.selectEcControlTaskById(id)); + } + + /** + * 新增任务(群控核心) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task:add')") + @Log(title = "任务(群控核心)", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody EcControlTask ecControlTask) + { + return toAjax(ecControlTaskService.insertEcControlTask(ecControlTask)); + } + + /** + * 修改任务(群控核心) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task:edit')") + @Log(title = "任务(群控核心)", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody EcControlTask ecControlTask) + { + return toAjax(ecControlTaskService.updateEcControlTask(ecControlTask)); + } + + /** + * 删除任务(群控核心) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task:remove')") + @Log(title = "任务(群控核心)", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) + { + return toAjax(ecControlTaskService.deleteEcControlTaskByIds(ids)); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceCommandController.java b/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceCommandController.java new file mode 100644 index 0000000..191e12b --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceCommandController.java @@ -0,0 +1,118 @@ +package com.luqj.ec.controller; +import com.ruoyi.common.select.Ids; +import com.ruoyi.common.select.SelectItem; +import java.util.List; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.luqj.ec.domain.EcDeviceCommand; +import com.luqj.ec.domain.EcDeviceCommandPlus; +import com.luqj.ec.service.IEcDeviceCommandService; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.common.core.page.TableDataInfo; + +/** + * 控制指令(单条指令)Controller + * + * @author luqj + * @date 2026-02-27 + */ +@RestController +@RequestMapping("/ec/ec-command") +public class EcDeviceCommandController extends BaseController +{ + @Autowired + private IEcDeviceCommandService ecDeviceCommandService; + @PreAuthorize("@ss.hasPermi('ec:ec-command:getByIds')") + @PostMapping("/getByIds") + public AjaxResult getByIds(@RequestBody Ids ids) + { + List list = ecDeviceCommandService.getByIds(ids.getLongIds(),EcDeviceCommandPlus::getCommandType,EcDeviceCommandPlus::getId); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('ec:ec-command:select')") + @GetMapping("/select") + public AjaxResult select(String keyword) + { + List list = ecDeviceCommandService.select(keyword); + return AjaxResult.success(list); + } + /** + * 查询控制指令(单条指令)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command:list')") + @GetMapping("/list") + public TableDataInfo list(EcDeviceCommand ecDeviceCommand) + { + startPage(); + List list = ecDeviceCommandService.selectEcDeviceCommandList(ecDeviceCommand); + return getDataTable(list); + } + + /** + * 导出控制指令(单条指令)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command:export')") + @Log(title = "控制指令(单条指令)", businessType = BusinessType.EXPORT) + @GetMapping("/export") + public AjaxResult export(EcDeviceCommand ecDeviceCommand) + { + List list = ecDeviceCommandService.selectEcDeviceCommandList(ecDeviceCommand); + ExcelUtil util = new ExcelUtil(EcDeviceCommand.class); + return util.exportExcel(list, "ec-command"); + } + + /** + * 获取控制指令(单条指令)详细信息 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) + { + return AjaxResult.success(ecDeviceCommandService.selectEcDeviceCommandById(id)); + } + + /** + * 新增控制指令(单条指令) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command:add')") + @Log(title = "控制指令(单条指令)", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody EcDeviceCommand ecDeviceCommand) + { + return toAjax(ecDeviceCommandService.insertEcDeviceCommand(ecDeviceCommand)); + } + + /** + * 修改控制指令(单条指令) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command:edit')") + @Log(title = "控制指令(单条指令)", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody EcDeviceCommand ecDeviceCommand) + { + return toAjax(ecDeviceCommandService.updateEcDeviceCommand(ecDeviceCommand)); + } + + /** + * 删除控制指令(单条指令) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-command:remove')") + @Log(title = "控制指令(单条指令)", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) + { + return toAjax(ecDeviceCommandService.deleteEcDeviceCommandByIds(ids)); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceController.java b/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceController.java new file mode 100644 index 0000000..d935cc7 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceController.java @@ -0,0 +1,118 @@ +package com.luqj.ec.controller; +import com.ruoyi.common.select.Ids; +import com.ruoyi.common.select.SelectItem; +import java.util.List; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.luqj.ec.domain.EcDevice; +import com.luqj.ec.domain.EcDevicePlus; +import com.luqj.ec.service.IEcDeviceService; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.common.core.page.TableDataInfo; + +/** + * 设备(手机设备)Controller + * + * @author luqj + * @date 2026-02-27 + */ +@RestController +@RequestMapping("/ec/ec-device") +public class EcDeviceController extends BaseController +{ + @Autowired + private IEcDeviceService ecDeviceService; + @PreAuthorize("@ss.hasPermi('ec:ec-device:getByIds')") + @PostMapping("/getByIds") + public AjaxResult getByIds(@RequestBody Ids ids) + { + List list = ecDeviceService.getByIds(ids.getLongIds(),EcDevicePlus::getDeviceCode,EcDevicePlus::getId); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('ec:ec-device:select')") + @GetMapping("/select") + public AjaxResult select(String keyword) + { + List list = ecDeviceService.select(keyword); + return AjaxResult.success(list); + } + /** + * 查询设备(手机设备)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device:list')") + @GetMapping("/list") + public TableDataInfo list(EcDevice ecDevice) + { + startPage(); + List list = ecDeviceService.selectEcDeviceList(ecDevice); + return getDataTable(list); + } + + /** + * 导出设备(手机设备)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device:export')") + @Log(title = "设备(手机设备)", businessType = BusinessType.EXPORT) + @GetMapping("/export") + public AjaxResult export(EcDevice ecDevice) + { + List list = ecDeviceService.selectEcDeviceList(ecDevice); + ExcelUtil util = new ExcelUtil(EcDevice.class); + return util.exportExcel(list, "ec-device"); + } + + /** + * 获取设备(手机设备)详细信息 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) + { + return AjaxResult.success(ecDeviceService.selectEcDeviceById(id)); + } + + /** + * 新增设备(手机设备) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device:add')") + @Log(title = "设备(手机设备)", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody EcDevice ecDevice) + { + return toAjax(ecDeviceService.insertEcDevice(ecDevice)); + } + + /** + * 修改设备(手机设备) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device:edit')") + @Log(title = "设备(手机设备)", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody EcDevice ecDevice) + { + return toAjax(ecDeviceService.updateEcDevice(ecDevice)); + } + + /** + * 删除设备(手机设备) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device:remove')") + @Log(title = "设备(手机设备)", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) + { + return toAjax(ecDeviceService.deleteEcDeviceByIds(ids)); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceStatusController.java b/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceStatusController.java new file mode 100644 index 0000000..63ebdf1 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceStatusController.java @@ -0,0 +1,118 @@ +package com.luqj.ec.controller; +import com.ruoyi.common.select.Ids; +import com.ruoyi.common.select.SelectItem; +import java.util.List; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.luqj.ec.domain.EcDeviceStatus; +import com.luqj.ec.domain.EcDeviceStatusPlus; +import com.luqj.ec.service.IEcDeviceStatusService; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.common.core.page.TableDataInfo; + +/** + * 设备心跳 & 状态(高频)Controller + * + * @author luqj + * @date 2026-02-27 + */ +@RestController +@RequestMapping("/ec/ec-device-status") +public class EcDeviceStatusController extends BaseController +{ + @Autowired + private IEcDeviceStatusService ecDeviceStatusService; + @PreAuthorize("@ss.hasPermi('ec:ec-device-status:getByIds')") + @PostMapping("/getByIds") + public AjaxResult getByIds(@RequestBody Ids ids) + { + List list = ecDeviceStatusService.getByIds(ids.getLongIds(),EcDeviceStatusPlus::getDeviceId,EcDeviceStatusPlus::getId); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('ec:ec-device-status:select')") + @GetMapping("/select") + public AjaxResult select(String keyword) + { + List list = ecDeviceStatusService.select(keyword); + return AjaxResult.success(list); + } + /** + * 查询设备心跳 & 状态(高频)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device-status:list')") + @GetMapping("/list") + public TableDataInfo list(EcDeviceStatus ecDeviceStatus) + { + startPage(); + List list = ecDeviceStatusService.selectEcDeviceStatusList(ecDeviceStatus); + return getDataTable(list); + } + + /** + * 导出设备心跳 & 状态(高频)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device-status:export')") + @Log(title = "设备心跳 & 状态(高频)", businessType = BusinessType.EXPORT) + @GetMapping("/export") + public AjaxResult export(EcDeviceStatus ecDeviceStatus) + { + List list = ecDeviceStatusService.selectEcDeviceStatusList(ecDeviceStatus); + ExcelUtil util = new ExcelUtil(EcDeviceStatus.class); + return util.exportExcel(list, "ec-device-status"); + } + + /** + * 获取设备心跳 & 状态(高频)详细信息 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device-status:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) + { + return AjaxResult.success(ecDeviceStatusService.selectEcDeviceStatusById(id)); + } + + /** + * 新增设备心跳 & 状态(高频) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device-status:add')") + @Log(title = "设备心跳 & 状态(高频)", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody EcDeviceStatus ecDeviceStatus) + { + return toAjax(ecDeviceStatusService.insertEcDeviceStatus(ecDeviceStatus)); + } + + /** + * 修改设备心跳 & 状态(高频) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device-status:edit')") + @Log(title = "设备心跳 & 状态(高频)", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody EcDeviceStatus ecDeviceStatus) + { + return toAjax(ecDeviceStatusService.updateEcDeviceStatus(ecDeviceStatus)); + } + + /** + * 删除设备心跳 & 状态(高频) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-device-status:remove')") + @Log(title = "设备心跳 & 状态(高频)", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) + { + return toAjax(ecDeviceStatusService.deleteEcDeviceStatusByIds(ids)); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/controller/EcTaskCommandController.java b/luqj-ec/src/main/java/com/luqj/ec/controller/EcTaskCommandController.java new file mode 100644 index 0000000..9d822e1 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/controller/EcTaskCommandController.java @@ -0,0 +1,118 @@ +package com.luqj.ec.controller; +import com.ruoyi.common.select.Ids; +import com.ruoyi.common.select.SelectItem; +import java.util.List; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.luqj.ec.domain.EcTaskCommand; +import com.luqj.ec.domain.EcTaskCommandPlus; +import com.luqj.ec.service.IEcTaskCommandService; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.common.core.page.TableDataInfo; + +/** + * 任务指令明细(一个任务多条指令)Controller + * + * @author luqj + * @date 2026-02-27 + */ +@RestController +@RequestMapping("/ec/ec-task-command") +public class EcTaskCommandController extends BaseController +{ + @Autowired + private IEcTaskCommandService ecTaskCommandService; + @PreAuthorize("@ss.hasPermi('ec:ec-task-command:getByIds')") + @PostMapping("/getByIds") + public AjaxResult getByIds(@RequestBody Ids ids) + { + List list = ecTaskCommandService.getByIds(ids.getLongIds(),EcTaskCommandPlus::getCommandType,EcTaskCommandPlus::getId); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('ec:ec-task-command:select')") + @GetMapping("/select") + public AjaxResult select(String keyword) + { + List list = ecTaskCommandService.select(keyword); + return AjaxResult.success(list); + } + /** + * 查询任务指令明细(一个任务多条指令)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-command:list')") + @GetMapping("/list") + public TableDataInfo list(EcTaskCommand ecTaskCommand) + { + startPage(); + List list = ecTaskCommandService.selectEcTaskCommandList(ecTaskCommand); + return getDataTable(list); + } + + /** + * 导出任务指令明细(一个任务多条指令)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-command:export')") + @Log(title = "任务指令明细(一个任务多条指令)", businessType = BusinessType.EXPORT) + @GetMapping("/export") + public AjaxResult export(EcTaskCommand ecTaskCommand) + { + List list = ecTaskCommandService.selectEcTaskCommandList(ecTaskCommand); + ExcelUtil util = new ExcelUtil(EcTaskCommand.class); + return util.exportExcel(list, "ec-task-command"); + } + + /** + * 获取任务指令明细(一个任务多条指令)详细信息 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-command:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) + { + return AjaxResult.success(ecTaskCommandService.selectEcTaskCommandById(id)); + } + + /** + * 新增任务指令明细(一个任务多条指令) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-command:add')") + @Log(title = "任务指令明细(一个任务多条指令)", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody EcTaskCommand ecTaskCommand) + { + return toAjax(ecTaskCommandService.insertEcTaskCommand(ecTaskCommand)); + } + + /** + * 修改任务指令明细(一个任务多条指令) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-command:edit')") + @Log(title = "任务指令明细(一个任务多条指令)", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody EcTaskCommand ecTaskCommand) + { + return toAjax(ecTaskCommandService.updateEcTaskCommand(ecTaskCommand)); + } + + /** + * 删除任务指令明细(一个任务多条指令) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-command:remove')") + @Log(title = "任务指令明细(一个任务多条指令)", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) + { + return toAjax(ecTaskCommandService.deleteEcTaskCommandByIds(ids)); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/controller/EcTaskDeviceController.java b/luqj-ec/src/main/java/com/luqj/ec/controller/EcTaskDeviceController.java new file mode 100644 index 0000000..6d2c836 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/controller/EcTaskDeviceController.java @@ -0,0 +1,118 @@ +package com.luqj.ec.controller; +import com.ruoyi.common.select.Ids; +import com.ruoyi.common.select.SelectItem; +import java.util.List; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.enums.BusinessType; +import com.luqj.ec.domain.EcTaskDevice; +import com.luqj.ec.domain.EcTaskDevicePlus; +import com.luqj.ec.service.IEcTaskDeviceService; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.common.core.page.TableDataInfo; + +/** + * 任务-设备关联(一任务多设备)Controller + * + * @author luqj + * @date 2026-02-27 + */ +@RestController +@RequestMapping("/ec/ec-task-device") +public class EcTaskDeviceController extends BaseController +{ + @Autowired + private IEcTaskDeviceService ecTaskDeviceService; + @PreAuthorize("@ss.hasPermi('ec:ec-task-device:getByIds')") + @PostMapping("/getByIds") + public AjaxResult getByIds(@RequestBody Ids ids) + { + List list = ecTaskDeviceService.getByIds(ids.getLongIds(),EcTaskDevicePlus::getStatus,EcTaskDevicePlus::getId); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('ec:ec-task-device:select')") + @GetMapping("/select") + public AjaxResult select(String keyword) + { + List list = ecTaskDeviceService.select(keyword); + return AjaxResult.success(list); + } + /** + * 查询任务-设备关联(一任务多设备)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-device:list')") + @GetMapping("/list") + public TableDataInfo list(EcTaskDevice ecTaskDevice) + { + startPage(); + List list = ecTaskDeviceService.selectEcTaskDeviceList(ecTaskDevice); + return getDataTable(list); + } + + /** + * 导出任务-设备关联(一任务多设备)列表 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-device:export')") + @Log(title = "任务-设备关联(一任务多设备)", businessType = BusinessType.EXPORT) + @GetMapping("/export") + public AjaxResult export(EcTaskDevice ecTaskDevice) + { + List list = ecTaskDeviceService.selectEcTaskDeviceList(ecTaskDevice); + ExcelUtil util = new ExcelUtil(EcTaskDevice.class); + return util.exportExcel(list, "ec-task-device"); + } + + /** + * 获取任务-设备关联(一任务多设备)详细信息 + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-device:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) + { + return AjaxResult.success(ecTaskDeviceService.selectEcTaskDeviceById(id)); + } + + /** + * 新增任务-设备关联(一任务多设备) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-device:add')") + @Log(title = "任务-设备关联(一任务多设备)", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody EcTaskDevice ecTaskDevice) + { + return toAjax(ecTaskDeviceService.insertEcTaskDevice(ecTaskDevice)); + } + + /** + * 修改任务-设备关联(一任务多设备) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-device:edit')") + @Log(title = "任务-设备关联(一任务多设备)", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody EcTaskDevice ecTaskDevice) + { + return toAjax(ecTaskDeviceService.updateEcTaskDevice(ecTaskDevice)); + } + + /** + * 删除任务-设备关联(一任务多设备) + */ + @PreAuthorize("@ss.hasPermi('ec:ec-task-device:remove')") + @Log(title = "任务-设备关联(一任务多设备)", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) + { + return toAjax(ecTaskDeviceService.deleteEcTaskDeviceByIds(ids)); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcCommandResult.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcCommandResult.java new file mode 100644 index 0000000..2c3820d --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcCommandResult.java @@ -0,0 +1,124 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +/** + * 指令执行结果(客户端回传)对象 ec_command_result + * + * @author luqj + * @date 2026-02-27 + */ +public class EcCommandResult extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + + /** 命令ID */ + @Excel(name = "命令ID") + private Long commandId; + + /** 设备ID */ + @Excel(name = "设备ID") + private Long deviceId; + + /** 返回结果 */ + @Excel(name = "返回结果") + private Integer result; + + /** 错误信息 */ + @Excel(name = "错误信息") + private String errorMsg; + + /** 返回信息 */ + @Excel(name = "返回信息") + private String responseData; + + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setCommandId(Long commandId) + { + this.commandId = commandId; + } + + public Long getCommandId() + { + return commandId; + } + public void setDeviceId(Long deviceId) + { + this.deviceId = deviceId; + } + + public Long getDeviceId() + { + return deviceId; + } + public void setResult(Integer result) + { + this.result = result; + } + + public Integer getResult() + { + return result; + } + public void setErrorMsg(String errorMsg) + { + this.errorMsg = errorMsg; + } + + public String getErrorMsg() + { + return errorMsg; + } + public void setResponseData(String responseData) + { + this.responseData = responseData; + } + + public String getResponseData() + { + return responseData; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("commandId", getCommandId()) + .append("deviceId", getDeviceId()) + .append("result", getResult()) + .append("errorMsg", getErrorMsg()) + .append("responseData", getResponseData()) + .append("createdAt", getCreatedAt()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcCommandResultPlus.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcCommandResultPlus.java new file mode 100644 index 0000000..0e2b03b --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcCommandResultPlus.java @@ -0,0 +1,120 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +import java.util.Date; +import com.baomidou.mybatisplus.annotation.TableName; +/** + * 指令执行结果(客户端回传)对象 ec_command_result + * + * @author luqj + * @date 2026-02-27 + */ +@TableName(value = "ec_command_result") +public class EcCommandResultPlus implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + /** 命令ID */ + @Excel(name = "命令ID") + private Long commandId; + /** 设备ID */ + @Excel(name = "设备ID") + private Long deviceId; + /** 返回结果 */ + @Excel(name = "返回结果") + private Integer result; + /** 错误信息 */ + @Excel(name = "错误信息") + private String errorMsg; + /** 返回信息 */ + @Excel(name = "返回信息") + private String responseData; + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setCommandId(Long commandId) + { + this.commandId = commandId; + } + + public Long getCommandId() + { + return commandId; + } + public void setDeviceId(Long deviceId) + { + this.deviceId = deviceId; + } + + public Long getDeviceId() + { + return deviceId; + } + public void setResult(Integer result) + { + this.result = result; + } + + public Integer getResult() + { + return result; + } + public void setErrorMsg(String errorMsg) + { + this.errorMsg = errorMsg; + } + + public String getErrorMsg() + { + return errorMsg; + } + public void setResponseData(String responseData) + { + this.responseData = responseData; + } + + public String getResponseData() + { + return responseData; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("commandId", getCommandId()) + .append("deviceId", getDeviceId()) + .append("result", getResult()) + .append("errorMsg", getErrorMsg()) + .append("responseData", getResponseData()) + .append("createdAt", getCreatedAt()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcControlTask.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcControlTask.java new file mode 100644 index 0000000..ac4a52f --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcControlTask.java @@ -0,0 +1,139 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +/** + * 任务(群控核心)对象 ec_control_task + * + * @author luqj + * @date 2026-02-27 + */ +public class EcControlTask extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + + /** 任务名称 */ + @Excel(name = "任务名称") + private String taskName; + + /** 任务类型 */ + @Excel(name = "任务类型") + private Integer taskType; + + /** 用户ID */ + @Excel(name = "用户ID") + private Long userId; + + /** 状态 */ + @Excel(name = "状态") + private Integer status; + + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + + /** 更新时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + + /** 应用ID */ + @Excel(name = "应用ID") + private Long appId; + + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTaskName(String taskName) + { + this.taskName = taskName; + } + + public String getTaskName() + { + return taskName; + } + public void setTaskType(Integer taskType) + { + this.taskType = taskType; + } + + public Integer getTaskType() + { + return taskType; + } + public void setUserId(Long userId) + { + this.userId = userId; + } + + public Long getUserId() + { + return userId; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + public void setAppId(Long appId) + { + this.appId = appId; + } + + public Long getAppId() + { + return appId; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("taskName", getTaskName()) + .append("taskType", getTaskType()) + .append("userId", getUserId()) + .append("status", getStatus()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .append("appId", getAppId()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcControlTaskPlus.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcControlTaskPlus.java new file mode 100644 index 0000000..9b87bae --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcControlTaskPlus.java @@ -0,0 +1,134 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +import java.util.Date; +import com.baomidou.mybatisplus.annotation.TableName; +/** + * 任务(群控核心)对象 ec_control_task + * + * @author luqj + * @date 2026-02-27 + */ +@TableName(value = "ec_control_task") +public class EcControlTaskPlus implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + /** 任务名称 */ + @Excel(name = "任务名称") + private String taskName; + /** 任务类型 */ + @Excel(name = "任务类型") + private Integer taskType; + /** 用户ID */ + @Excel(name = "用户ID") + private Long userId; + /** 状态 */ + @Excel(name = "状态") + private Integer status; + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + /** 更新时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + /** 应用ID */ + @Excel(name = "应用ID") + private Long appId; + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTaskName(String taskName) + { + this.taskName = taskName; + } + + public String getTaskName() + { + return taskName; + } + public void setTaskType(Integer taskType) + { + this.taskType = taskType; + } + + public Integer getTaskType() + { + return taskType; + } + public void setUserId(Long userId) + { + this.userId = userId; + } + + public Long getUserId() + { + return userId; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + public void setAppId(Long appId) + { + this.appId = appId; + } + + public Long getAppId() + { + return appId; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("taskName", getTaskName()) + .append("taskType", getTaskType()) + .append("userId", getUserId()) + .append("status", getStatus()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .append("appId", getAppId()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcDevice.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDevice.java new file mode 100644 index 0000000..e2a9f31 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDevice.java @@ -0,0 +1,292 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +/** + * 设备(手机设备)对象 ec_device + * + * @author luqj + * @date 2026-02-27 + */ +public class EcDevice extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + + /** 设备唯一标识 */ + @Excel(name = "设备唯一标识") + private String deviceCode; + + /** 品牌 */ + @Excel(name = "品牌") + private String brand; + + /** 模型 */ + @Excel(name = "模型") + private String model; + + /** 系统类型 */ + @Excel(name = "系统类型") + private String osType; + + /** 系统版本 */ + @Excel(name = "系统版本") + private String osVersion; + + /** 版本 */ + @Excel(name = "版本") + private String appVersion; + + /** 状态 */ + @Excel(name = "状态") + private Integer status; + + /** 最后在线时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "最后在线时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date lastOnlineTime; + + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + + /** 更新时间 */ + private Date updatedAt; + + /** ip地址 */ + @Excel(name = "ip地址") + private String ipAddress; + + /** 最后截图 */ + @Excel(name = "最后截图") + private String lastScreenPic; + + /** 宽度 */ + @Excel(name = "宽度") + private Integer widthNum; + + /** 高度 */ + @Excel(name = "高度") + private Integer heightNum; + + /** 控制类型 */ + @Excel(name = "控制类型") + private Integer controlType; + + /** 应用ID */ + @Excel(name = "应用ID") + private Long appId; + + /** 用户ID */ + @Excel(name = "用户ID") + private Long userId; + + /** 密钥 */ + @Excel(name = "密钥") + private String secretKey; + + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setDeviceCode(String deviceCode) + { + this.deviceCode = deviceCode; + } + + public String getDeviceCode() + { + return deviceCode; + } + public void setBrand(String brand) + { + this.brand = brand; + } + + public String getBrand() + { + return brand; + } + public void setModel(String model) + { + this.model = model; + } + + public String getModel() + { + return model; + } + public void setOsType(String osType) + { + this.osType = osType; + } + + public String getOsType() + { + return osType; + } + public void setOsVersion(String osVersion) + { + this.osVersion = osVersion; + } + + public String getOsVersion() + { + return osVersion; + } + public void setAppVersion(String appVersion) + { + this.appVersion = appVersion; + } + + public String getAppVersion() + { + return appVersion; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setLastOnlineTime(Date lastOnlineTime) + { + this.lastOnlineTime = lastOnlineTime; + } + + public Date getLastOnlineTime() + { + return lastOnlineTime; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + public void setIpAddress(String ipAddress) + { + this.ipAddress = ipAddress; + } + + public String getIpAddress() + { + return ipAddress; + } + public void setLastScreenPic(String lastScreenPic) + { + this.lastScreenPic = lastScreenPic; + } + + public String getLastScreenPic() + { + return lastScreenPic; + } + public void setWidthNum(Integer widthNum) + { + this.widthNum = widthNum; + } + + public Integer getWidthNum() + { + return widthNum; + } + public void setHeightNum(Integer heightNum) + { + this.heightNum = heightNum; + } + + public Integer getHeightNum() + { + return heightNum; + } + public void setControlType(Integer controlType) + { + this.controlType = controlType; + } + + public Integer getControlType() + { + return controlType; + } + public void setAppId(Long appId) + { + this.appId = appId; + } + + public Long getAppId() + { + return appId; + } + public void setUserId(Long userId) + { + this.userId = userId; + } + + public Long getUserId() + { + return userId; + } + public void setSecretKey(String secretKey) + { + this.secretKey = secretKey; + } + + public String getSecretKey() + { + return secretKey; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("deviceCode", getDeviceCode()) + .append("brand", getBrand()) + .append("model", getModel()) + .append("osType", getOsType()) + .append("osVersion", getOsVersion()) + .append("appVersion", getAppVersion()) + .append("status", getStatus()) + .append("lastOnlineTime", getLastOnlineTime()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .append("ipAddress", getIpAddress()) + .append("lastScreenPic", getLastScreenPic()) + .append("widthNum", getWidthNum()) + .append("heightNum", getHeightNum()) + .append("controlType", getControlType()) + .append("appId", getAppId()) + .append("userId", getUserId()) + .append("secretKey", getSecretKey()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceCommand.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceCommand.java new file mode 100644 index 0000000..dce8466 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceCommand.java @@ -0,0 +1,140 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +/** + * 控制指令(单条指令)对象 ec_device_command + * + * @author luqj + * @date 2026-02-27 + */ +public class EcDeviceCommand extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + + /** 设备ID */ + @Excel(name = "设备ID") + private Long deviceId; + + /** 命令类型 */ + @Excel(name = "命令类型") + private String commandType; + + /** 指令参数 */ + @Excel(name = "指令参数") + private String commandContent; + + /** 状态 */ + @Excel(name = "状态") + private Integer status; + + /** 发送时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "发送时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date sendTime; + + /** 执行时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "执行时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date executeTime; + + /** 完成时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "完成时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date finishTime; + + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setDeviceId(Long deviceId) + { + this.deviceId = deviceId; + } + + public Long getDeviceId() + { + return deviceId; + } + public void setCommandType(String commandType) + { + this.commandType = commandType; + } + + public String getCommandType() + { + return commandType; + } + public void setCommandContent(String commandContent) + { + this.commandContent = commandContent; + } + + public String getCommandContent() + { + return commandContent; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setSendTime(Date sendTime) + { + this.sendTime = sendTime; + } + + public Date getSendTime() + { + return sendTime; + } + public void setExecuteTime(Date executeTime) + { + this.executeTime = executeTime; + } + + public Date getExecuteTime() + { + return executeTime; + } + public void setFinishTime(Date finishTime) + { + this.finishTime = finishTime; + } + + public Date getFinishTime() + { + return finishTime; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("deviceId", getDeviceId()) + .append("commandType", getCommandType()) + .append("commandContent", getCommandContent()) + .append("status", getStatus()) + .append("sendTime", getSendTime()) + .append("executeTime", getExecuteTime()) + .append("finishTime", getFinishTime()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceCommandPlus.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceCommandPlus.java new file mode 100644 index 0000000..0bfc024 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceCommandPlus.java @@ -0,0 +1,135 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +import java.util.Date; +import com.baomidou.mybatisplus.annotation.TableName; +/** + * 控制指令(单条指令)对象 ec_device_command + * + * @author luqj + * @date 2026-02-27 + */ +@TableName(value = "ec_device_command") +public class EcDeviceCommandPlus implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + /** 设备ID */ + @Excel(name = "设备ID") + private Long deviceId; + /** 命令类型 */ + @Excel(name = "命令类型") + private String commandType; + /** 指令参数 */ + @Excel(name = "指令参数") + private String commandContent; + /** 状态 */ + @Excel(name = "状态") + private Integer status; + /** 发送时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "发送时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date sendTime; + /** 执行时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "执行时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date executeTime; + /** 完成时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "完成时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date finishTime; + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setDeviceId(Long deviceId) + { + this.deviceId = deviceId; + } + + public Long getDeviceId() + { + return deviceId; + } + public void setCommandType(String commandType) + { + this.commandType = commandType; + } + + public String getCommandType() + { + return commandType; + } + public void setCommandContent(String commandContent) + { + this.commandContent = commandContent; + } + + public String getCommandContent() + { + return commandContent; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setSendTime(Date sendTime) + { + this.sendTime = sendTime; + } + + public Date getSendTime() + { + return sendTime; + } + public void setExecuteTime(Date executeTime) + { + this.executeTime = executeTime; + } + + public Date getExecuteTime() + { + return executeTime; + } + public void setFinishTime(Date finishTime) + { + this.finishTime = finishTime; + } + + public Date getFinishTime() + { + return finishTime; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("deviceId", getDeviceId()) + .append("commandType", getCommandType()) + .append("commandContent", getCommandContent()) + .append("status", getStatus()) + .append("sendTime", getSendTime()) + .append("executeTime", getExecuteTime()) + .append("finishTime", getFinishTime()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcDevicePlus.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDevicePlus.java new file mode 100644 index 0000000..f514dd2 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDevicePlus.java @@ -0,0 +1,276 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +import java.util.Date; +import com.baomidou.mybatisplus.annotation.TableName; +/** + * 设备(手机设备)对象 ec_device + * + * @author luqj + * @date 2026-02-27 + */ +@TableName(value = "ec_device") +public class EcDevicePlus implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + /** 设备唯一标识 */ + @Excel(name = "设备唯一标识") + private String deviceCode; + /** 品牌 */ + @Excel(name = "品牌") + private String brand; + /** 模型 */ + @Excel(name = "模型") + private String model; + /** 系统类型 */ + @Excel(name = "系统类型") + private String osType; + /** 系统版本 */ + @Excel(name = "系统版本") + private String osVersion; + /** 版本 */ + @Excel(name = "版本") + private String appVersion; + /** 状态 */ + @Excel(name = "状态") + private Integer status; + /** 最后在线时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "最后在线时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date lastOnlineTime; + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + /** 更新时间 */ + private Date updatedAt; + /** ip地址 */ + @Excel(name = "ip地址") + private String ipAddress; + /** 最后截图 */ + @Excel(name = "最后截图") + private String lastScreenPic; + /** 宽度 */ + @Excel(name = "宽度") + private Integer widthNum; + /** 高度 */ + @Excel(name = "高度") + private Integer heightNum; + /** 控制类型 */ + @Excel(name = "控制类型") + private Integer controlType; + /** 应用ID */ + @Excel(name = "应用ID") + private Long appId; + /** 用户ID */ + @Excel(name = "用户ID") + private Long userId; + /** 密钥 */ + @Excel(name = "密钥") + private String secretKey; + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setDeviceCode(String deviceCode) + { + this.deviceCode = deviceCode; + } + + public String getDeviceCode() + { + return deviceCode; + } + public void setBrand(String brand) + { + this.brand = brand; + } + + public String getBrand() + { + return brand; + } + public void setModel(String model) + { + this.model = model; + } + + public String getModel() + { + return model; + } + public void setOsType(String osType) + { + this.osType = osType; + } + + public String getOsType() + { + return osType; + } + public void setOsVersion(String osVersion) + { + this.osVersion = osVersion; + } + + public String getOsVersion() + { + return osVersion; + } + public void setAppVersion(String appVersion) + { + this.appVersion = appVersion; + } + + public String getAppVersion() + { + return appVersion; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setLastOnlineTime(Date lastOnlineTime) + { + this.lastOnlineTime = lastOnlineTime; + } + + public Date getLastOnlineTime() + { + return lastOnlineTime; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + public void setIpAddress(String ipAddress) + { + this.ipAddress = ipAddress; + } + + public String getIpAddress() + { + return ipAddress; + } + public void setLastScreenPic(String lastScreenPic) + { + this.lastScreenPic = lastScreenPic; + } + + public String getLastScreenPic() + { + return lastScreenPic; + } + public void setWidthNum(Integer widthNum) + { + this.widthNum = widthNum; + } + + public Integer getWidthNum() + { + return widthNum; + } + public void setHeightNum(Integer heightNum) + { + this.heightNum = heightNum; + } + + public Integer getHeightNum() + { + return heightNum; + } + public void setControlType(Integer controlType) + { + this.controlType = controlType; + } + + public Integer getControlType() + { + return controlType; + } + public void setAppId(Long appId) + { + this.appId = appId; + } + + public Long getAppId() + { + return appId; + } + public void setUserId(Long userId) + { + this.userId = userId; + } + + public Long getUserId() + { + return userId; + } + public void setSecretKey(String secretKey) + { + this.secretKey = secretKey; + } + + public String getSecretKey() + { + return secretKey; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("deviceCode", getDeviceCode()) + .append("brand", getBrand()) + .append("model", getModel()) + .append("osType", getOsType()) + .append("osVersion", getOsVersion()) + .append("appVersion", getAppVersion()) + .append("status", getStatus()) + .append("lastOnlineTime", getLastOnlineTime()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .append("ipAddress", getIpAddress()) + .append("lastScreenPic", getLastScreenPic()) + .append("widthNum", getWidthNum()) + .append("heightNum", getHeightNum()) + .append("controlType", getControlType()) + .append("appId", getAppId()) + .append("userId", getUserId()) + .append("secretKey", getSecretKey()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceStatus.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceStatus.java new file mode 100644 index 0000000..b4153fc --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceStatus.java @@ -0,0 +1,154 @@ +package com.luqj.ec.domain; + +import java.math.BigDecimal; +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +/** + * 设备心跳 & 状态(高频)对象 ec_device_status + * + * @author luqj + * @date 2026-02-27 + */ +public class EcDeviceStatus extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + + /** 设备ID */ + @Excel(name = "设备ID") + private Long deviceId; + + /** 电量百分比 */ + @Excel(name = "电量百分比") + private Long battery; + + /** 网络类型 */ + @Excel(name = "网络类型") + private String networkType; + + /** cpu状态 */ + @Excel(name = "cpu状态") + private BigDecimal cpuUsage; + + /** 内存状态 */ + @Excel(name = "内存状态") + private BigDecimal memoryUsage; + + /** 屏幕状态 */ + @Excel(name = "屏幕状态") + private Integer screenOn; + + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setDeviceId(Long deviceId) + { + this.deviceId = deviceId; + } + + public Long getDeviceId() + { + return deviceId; + } + public void setBattery(Long battery) + { + this.battery = battery; + } + + public Long getBattery() + { + return battery; + } + public void setNetworkType(String networkType) + { + this.networkType = networkType; + } + + public String getNetworkType() + { + return networkType; + } + public void setCpuUsage(BigDecimal cpuUsage) + { + this.cpuUsage = cpuUsage; + } + + public BigDecimal getCpuUsage() + { + return cpuUsage; + } + public void setMemoryUsage(BigDecimal memoryUsage) + { + this.memoryUsage = memoryUsage; + } + + public BigDecimal getMemoryUsage() + { + return memoryUsage; + } + public void setScreenOn(Integer screenOn) + { + this.screenOn = screenOn; + } + + public Integer getScreenOn() + { + return screenOn; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("deviceId", getDeviceId()) + .append("battery", getBattery()) + .append("networkType", getNetworkType()) + .append("cpuUsage", getCpuUsage()) + .append("memoryUsage", getMemoryUsage()) + .append("screenOn", getScreenOn()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceStatusPlus.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceStatusPlus.java new file mode 100644 index 0000000..74bf91e --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcDeviceStatusPlus.java @@ -0,0 +1,148 @@ +package com.luqj.ec.domain; + +import java.math.BigDecimal; +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +import java.util.Date; +import com.baomidou.mybatisplus.annotation.TableName; +/** + * 设备心跳 & 状态(高频)对象 ec_device_status + * + * @author luqj + * @date 2026-02-27 + */ +@TableName(value = "ec_device_status") +public class EcDeviceStatusPlus implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + /** 设备ID */ + @Excel(name = "设备ID") + private Long deviceId; + /** 电量百分比 */ + @Excel(name = "电量百分比") + private Long battery; + /** 网络类型 */ + @Excel(name = "网络类型") + private String networkType; + /** cpu状态 */ + @Excel(name = "cpu状态") + private BigDecimal cpuUsage; + /** 内存状态 */ + @Excel(name = "内存状态") + private BigDecimal memoryUsage; + /** 屏幕状态 */ + @Excel(name = "屏幕状态") + private Integer screenOn; + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setDeviceId(Long deviceId) + { + this.deviceId = deviceId; + } + + public Long getDeviceId() + { + return deviceId; + } + public void setBattery(Long battery) + { + this.battery = battery; + } + + public Long getBattery() + { + return battery; + } + public void setNetworkType(String networkType) + { + this.networkType = networkType; + } + + public String getNetworkType() + { + return networkType; + } + public void setCpuUsage(BigDecimal cpuUsage) + { + this.cpuUsage = cpuUsage; + } + + public BigDecimal getCpuUsage() + { + return cpuUsage; + } + public void setMemoryUsage(BigDecimal memoryUsage) + { + this.memoryUsage = memoryUsage; + } + + public BigDecimal getMemoryUsage() + { + return memoryUsage; + } + public void setScreenOn(Integer screenOn) + { + this.screenOn = screenOn; + } + + public Integer getScreenOn() + { + return screenOn; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("deviceId", getDeviceId()) + .append("battery", getBattery()) + .append("networkType", getNetworkType()) + .append("cpuUsage", getCpuUsage()) + .append("memoryUsage", getMemoryUsage()) + .append("screenOn", getScreenOn()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskCommand.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskCommand.java new file mode 100644 index 0000000..347503b --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskCommand.java @@ -0,0 +1,93 @@ +package com.luqj.ec.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +/** + * 任务指令明细(一个任务多条指令)对象 ec_task_command + * + * @author luqj + * @date 2026-02-27 + */ +public class EcTaskCommand extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + + /** 任务ID */ + @Excel(name = "任务ID") + private Long taskId; + + /** 执行顺序 */ + @Excel(name = "执行顺序") + private Long stepOrder; + + /** 指令类型 */ + @Excel(name = "指令类型") + private String commandType; + + /** 指令参数 */ + @Excel(name = "指令参数") + private String commandContent; + + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTaskId(Long taskId) + { + this.taskId = taskId; + } + + public Long getTaskId() + { + return taskId; + } + public void setStepOrder(Long stepOrder) + { + this.stepOrder = stepOrder; + } + + public Long getStepOrder() + { + return stepOrder; + } + public void setCommandType(String commandType) + { + this.commandType = commandType; + } + + public String getCommandType() + { + return commandType; + } + public void setCommandContent(String commandContent) + { + this.commandContent = commandContent; + } + + public String getCommandContent() + { + return commandContent; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("taskId", getTaskId()) + .append("stepOrder", getStepOrder()) + .append("commandType", getCommandType()) + .append("commandContent", getCommandContent()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskCommandPlus.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskCommandPlus.java new file mode 100644 index 0000000..3e12620 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskCommandPlus.java @@ -0,0 +1,91 @@ +package com.luqj.ec.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +import java.util.Date; +import com.baomidou.mybatisplus.annotation.TableName; +/** + * 任务指令明细(一个任务多条指令)对象 ec_task_command + * + * @author luqj + * @date 2026-02-27 + */ +@TableName(value = "ec_task_command") +public class EcTaskCommandPlus implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + /** 任务ID */ + @Excel(name = "任务ID") + private Long taskId; + /** 执行顺序 */ + @Excel(name = "执行顺序") + private Long stepOrder; + /** 指令类型 */ + @Excel(name = "指令类型") + private String commandType; + /** 指令参数 */ + @Excel(name = "指令参数") + private String commandContent; + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTaskId(Long taskId) + { + this.taskId = taskId; + } + + public Long getTaskId() + { + return taskId; + } + public void setStepOrder(Long stepOrder) + { + this.stepOrder = stepOrder; + } + + public Long getStepOrder() + { + return stepOrder; + } + public void setCommandType(String commandType) + { + this.commandType = commandType; + } + + public String getCommandType() + { + return commandType; + } + public void setCommandContent(String commandContent) + { + this.commandContent = commandContent; + } + + public String getCommandContent() + { + return commandContent; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("taskId", getTaskId()) + .append("stepOrder", getStepOrder()) + .append("commandType", getCommandType()) + .append("commandContent", getCommandContent()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskDevice.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskDevice.java new file mode 100644 index 0000000..6e71e5d --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskDevice.java @@ -0,0 +1,96 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +/** + * 任务-设备关联(一任务多设备)对象 ec_task_device + * + * @author luqj + * @date 2026-02-27 + */ +public class EcTaskDevice extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + + /** 任务ID */ + @Excel(name = "任务ID") + private Long taskId; + + /** 设备ID */ + @Excel(name = "设备ID") + private Long deviceId; + + /** 状态 */ + @Excel(name = "状态") + private Integer status; + + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTaskId(Long taskId) + { + this.taskId = taskId; + } + + public Long getTaskId() + { + return taskId; + } + public void setDeviceId(Long deviceId) + { + this.deviceId = deviceId; + } + + public Long getDeviceId() + { + return deviceId; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("taskId", getTaskId()) + .append("deviceId", getDeviceId()) + .append("status", getStatus()) + .append("updatedAt", getUpdatedAt()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskDevicePlus.java b/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskDevicePlus.java new file mode 100644 index 0000000..e785951 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/domain/EcTaskDevicePlus.java @@ -0,0 +1,94 @@ +package com.luqj.ec.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +import java.util.Date; +import com.baomidou.mybatisplus.annotation.TableName; +/** + * 任务-设备关联(一任务多设备)对象 ec_task_device + * + * @author luqj + * @date 2026-02-27 + */ +@TableName(value = "ec_task_device") +public class EcTaskDevicePlus implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + /** 任务ID */ + @Excel(name = "任务ID") + private Long taskId; + /** 设备ID */ + @Excel(name = "设备ID") + private Long deviceId; + /** 状态 */ + @Excel(name = "状态") + private Integer status; + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTaskId(Long taskId) + { + this.taskId = taskId; + } + + public Long getTaskId() + { + return taskId; + } + public void setDeviceId(Long deviceId) + { + this.deviceId = deviceId; + } + + public Long getDeviceId() + { + return deviceId; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("taskId", getTaskId()) + .append("deviceId", getDeviceId()) + .append("status", getStatus()) + .append("updatedAt", getUpdatedAt()) + .toString(); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/mapper/EcCommandResultMapper.java b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcCommandResultMapper.java new file mode 100644 index 0000000..e716bc2 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcCommandResultMapper.java @@ -0,0 +1,65 @@ +package com.luqj.ec.mapper; + +import java.util.List; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import com.luqj.ec.domain.EcCommandResult; +import com.luqj.ec.domain.EcCommandResultPlus; + +/** + * 指令执行结果(客户端回传)Mapper接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface EcCommandResultMapper extends BaseMapper +{ + /** + * 查询指令执行结果(客户端回传) + * + * @param id 指令执行结果(客户端回传)ID + * @return 指令执行结果(客户端回传) + */ + public EcCommandResult selectEcCommandResultById(Long id); + + /** + * 查询指令执行结果(客户端回传)列表 + * + * @param ecCommandResult 指令执行结果(客户端回传) + * @return 指令执行结果(客户端回传)集合 + */ + public List selectEcCommandResultList(EcCommandResult ecCommandResult); + + /** + * 新增指令执行结果(客户端回传) + * + * @param ecCommandResult 指令执行结果(客户端回传) + * @return 结果 + */ + public int insertEcCommandResult(EcCommandResult ecCommandResult); + + /** + * 修改指令执行结果(客户端回传) + * + * @param ecCommandResult 指令执行结果(客户端回传) + * @return 结果 + */ + public int updateEcCommandResult(EcCommandResult ecCommandResult); + + /** + * 删除指令执行结果(客户端回传) + * + * @param id 指令执行结果(客户端回传)ID + * @return 结果 + */ + public int deleteEcCommandResultById(Long id); + + /** + * 批量删除指令执行结果(客户端回传) + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteEcCommandResultByIds(Long[] ids); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/mapper/EcControlTaskMapper.java b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcControlTaskMapper.java new file mode 100644 index 0000000..305d293 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcControlTaskMapper.java @@ -0,0 +1,65 @@ +package com.luqj.ec.mapper; + +import java.util.List; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import com.luqj.ec.domain.EcControlTask; +import com.luqj.ec.domain.EcControlTaskPlus; + +/** + * 任务(群控核心)Mapper接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface EcControlTaskMapper extends BaseMapper +{ + /** + * 查询任务(群控核心) + * + * @param id 任务(群控核心)ID + * @return 任务(群控核心) + */ + public EcControlTask selectEcControlTaskById(Long id); + + /** + * 查询任务(群控核心)列表 + * + * @param ecControlTask 任务(群控核心) + * @return 任务(群控核心)集合 + */ + public List selectEcControlTaskList(EcControlTask ecControlTask); + + /** + * 新增任务(群控核心) + * + * @param ecControlTask 任务(群控核心) + * @return 结果 + */ + public int insertEcControlTask(EcControlTask ecControlTask); + + /** + * 修改任务(群控核心) + * + * @param ecControlTask 任务(群控核心) + * @return 结果 + */ + public int updateEcControlTask(EcControlTask ecControlTask); + + /** + * 删除任务(群控核心) + * + * @param id 任务(群控核心)ID + * @return 结果 + */ + public int deleteEcControlTaskById(Long id); + + /** + * 批量删除任务(群控核心) + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteEcControlTaskByIds(Long[] ids); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/mapper/EcDeviceCommandMapper.java b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcDeviceCommandMapper.java new file mode 100644 index 0000000..403cc4c --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcDeviceCommandMapper.java @@ -0,0 +1,65 @@ +package com.luqj.ec.mapper; + +import java.util.List; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import com.luqj.ec.domain.EcDeviceCommand; +import com.luqj.ec.domain.EcDeviceCommandPlus; + +/** + * 控制指令(单条指令)Mapper接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface EcDeviceCommandMapper extends BaseMapper +{ + /** + * 查询控制指令(单条指令) + * + * @param id 控制指令(单条指令)ID + * @return 控制指令(单条指令) + */ + public EcDeviceCommand selectEcDeviceCommandById(Long id); + + /** + * 查询控制指令(单条指令)列表 + * + * @param ecDeviceCommand 控制指令(单条指令) + * @return 控制指令(单条指令)集合 + */ + public List selectEcDeviceCommandList(EcDeviceCommand ecDeviceCommand); + + /** + * 新增控制指令(单条指令) + * + * @param ecDeviceCommand 控制指令(单条指令) + * @return 结果 + */ + public int insertEcDeviceCommand(EcDeviceCommand ecDeviceCommand); + + /** + * 修改控制指令(单条指令) + * + * @param ecDeviceCommand 控制指令(单条指令) + * @return 结果 + */ + public int updateEcDeviceCommand(EcDeviceCommand ecDeviceCommand); + + /** + * 删除控制指令(单条指令) + * + * @param id 控制指令(单条指令)ID + * @return 结果 + */ + public int deleteEcDeviceCommandById(Long id); + + /** + * 批量删除控制指令(单条指令) + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteEcDeviceCommandByIds(Long[] ids); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/mapper/EcDeviceMapper.java b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcDeviceMapper.java new file mode 100644 index 0000000..1f8712a --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcDeviceMapper.java @@ -0,0 +1,65 @@ +package com.luqj.ec.mapper; + +import java.util.List; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import com.luqj.ec.domain.EcDevice; +import com.luqj.ec.domain.EcDevicePlus; + +/** + * 设备(手机设备)Mapper接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface EcDeviceMapper extends BaseMapper +{ + /** + * 查询设备(手机设备) + * + * @param id 设备(手机设备)ID + * @return 设备(手机设备) + */ + public EcDevice selectEcDeviceById(Long id); + + /** + * 查询设备(手机设备)列表 + * + * @param ecDevice 设备(手机设备) + * @return 设备(手机设备)集合 + */ + public List selectEcDeviceList(EcDevice ecDevice); + + /** + * 新增设备(手机设备) + * + * @param ecDevice 设备(手机设备) + * @return 结果 + */ + public int insertEcDevice(EcDevice ecDevice); + + /** + * 修改设备(手机设备) + * + * @param ecDevice 设备(手机设备) + * @return 结果 + */ + public int updateEcDevice(EcDevice ecDevice); + + /** + * 删除设备(手机设备) + * + * @param id 设备(手机设备)ID + * @return 结果 + */ + public int deleteEcDeviceById(Long id); + + /** + * 批量删除设备(手机设备) + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteEcDeviceByIds(Long[] ids); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/mapper/EcDeviceStatusMapper.java b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcDeviceStatusMapper.java new file mode 100644 index 0000000..b3909a5 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcDeviceStatusMapper.java @@ -0,0 +1,65 @@ +package com.luqj.ec.mapper; + +import java.util.List; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import com.luqj.ec.domain.EcDeviceStatus; +import com.luqj.ec.domain.EcDeviceStatusPlus; + +/** + * 设备心跳 & 状态(高频)Mapper接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface EcDeviceStatusMapper extends BaseMapper +{ + /** + * 查询设备心跳 & 状态(高频) + * + * @param id 设备心跳 & 状态(高频)ID + * @return 设备心跳 & 状态(高频) + */ + public EcDeviceStatus selectEcDeviceStatusById(Long id); + + /** + * 查询设备心跳 & 状态(高频)列表 + * + * @param ecDeviceStatus 设备心跳 & 状态(高频) + * @return 设备心跳 & 状态(高频)集合 + */ + public List selectEcDeviceStatusList(EcDeviceStatus ecDeviceStatus); + + /** + * 新增设备心跳 & 状态(高频) + * + * @param ecDeviceStatus 设备心跳 & 状态(高频) + * @return 结果 + */ + public int insertEcDeviceStatus(EcDeviceStatus ecDeviceStatus); + + /** + * 修改设备心跳 & 状态(高频) + * + * @param ecDeviceStatus 设备心跳 & 状态(高频) + * @return 结果 + */ + public int updateEcDeviceStatus(EcDeviceStatus ecDeviceStatus); + + /** + * 删除设备心跳 & 状态(高频) + * + * @param id 设备心跳 & 状态(高频)ID + * @return 结果 + */ + public int deleteEcDeviceStatusById(Long id); + + /** + * 批量删除设备心跳 & 状态(高频) + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteEcDeviceStatusByIds(Long[] ids); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/mapper/EcTaskCommandMapper.java b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcTaskCommandMapper.java new file mode 100644 index 0000000..1188938 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcTaskCommandMapper.java @@ -0,0 +1,65 @@ +package com.luqj.ec.mapper; + +import java.util.List; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import com.luqj.ec.domain.EcTaskCommand; +import com.luqj.ec.domain.EcTaskCommandPlus; + +/** + * 任务指令明细(一个任务多条指令)Mapper接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface EcTaskCommandMapper extends BaseMapper +{ + /** + * 查询任务指令明细(一个任务多条指令) + * + * @param id 任务指令明细(一个任务多条指令)ID + * @return 任务指令明细(一个任务多条指令) + */ + public EcTaskCommand selectEcTaskCommandById(Long id); + + /** + * 查询任务指令明细(一个任务多条指令)列表 + * + * @param ecTaskCommand 任务指令明细(一个任务多条指令) + * @return 任务指令明细(一个任务多条指令)集合 + */ + public List selectEcTaskCommandList(EcTaskCommand ecTaskCommand); + + /** + * 新增任务指令明细(一个任务多条指令) + * + * @param ecTaskCommand 任务指令明细(一个任务多条指令) + * @return 结果 + */ + public int insertEcTaskCommand(EcTaskCommand ecTaskCommand); + + /** + * 修改任务指令明细(一个任务多条指令) + * + * @param ecTaskCommand 任务指令明细(一个任务多条指令) + * @return 结果 + */ + public int updateEcTaskCommand(EcTaskCommand ecTaskCommand); + + /** + * 删除任务指令明细(一个任务多条指令) + * + * @param id 任务指令明细(一个任务多条指令)ID + * @return 结果 + */ + public int deleteEcTaskCommandById(Long id); + + /** + * 批量删除任务指令明细(一个任务多条指令) + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteEcTaskCommandByIds(Long[] ids); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/mapper/EcTaskDeviceMapper.java b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcTaskDeviceMapper.java new file mode 100644 index 0000000..c99cad0 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/mapper/EcTaskDeviceMapper.java @@ -0,0 +1,65 @@ +package com.luqj.ec.mapper; + +import java.util.List; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import com.luqj.ec.domain.EcTaskDevice; +import com.luqj.ec.domain.EcTaskDevicePlus; + +/** + * 任务-设备关联(一任务多设备)Mapper接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface EcTaskDeviceMapper extends BaseMapper +{ + /** + * 查询任务-设备关联(一任务多设备) + * + * @param id 任务-设备关联(一任务多设备)ID + * @return 任务-设备关联(一任务多设备) + */ + public EcTaskDevice selectEcTaskDeviceById(Long id); + + /** + * 查询任务-设备关联(一任务多设备)列表 + * + * @param ecTaskDevice 任务-设备关联(一任务多设备) + * @return 任务-设备关联(一任务多设备)集合 + */ + public List selectEcTaskDeviceList(EcTaskDevice ecTaskDevice); + + /** + * 新增任务-设备关联(一任务多设备) + * + * @param ecTaskDevice 任务-设备关联(一任务多设备) + * @return 结果 + */ + public int insertEcTaskDevice(EcTaskDevice ecTaskDevice); + + /** + * 修改任务-设备关联(一任务多设备) + * + * @param ecTaskDevice 任务-设备关联(一任务多设备) + * @return 结果 + */ + public int updateEcTaskDevice(EcTaskDevice ecTaskDevice); + + /** + * 删除任务-设备关联(一任务多设备) + * + * @param id 任务-设备关联(一任务多设备)ID + * @return 结果 + */ + public int deleteEcTaskDeviceById(Long id); + + /** + * 批量删除任务-设备关联(一任务多设备) + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteEcTaskDeviceByIds(Long[] ids); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/IEcCommandResultService.java b/luqj-ec/src/main/java/com/luqj/ec/service/IEcCommandResultService.java new file mode 100644 index 0000000..25b525c --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/IEcCommandResultService.java @@ -0,0 +1,89 @@ +package com.luqj.ec.service; +import java.util.Map; +import java.util.List; +import com.luqj.ec.domain.EcCommandResult; +import com.luqj.ec.domain.EcCommandResultPlus; +import com.baomidou.mybatisplus.extension.service.IService; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.ruoyi.common.select.SelectItem; +/** + * 指令执行结果(客户端回传)Service接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface IEcCommandResultService extends IService +{ + + List select(String keyword); + /** + * 查询指令执行结果(客户端回传) + * + * @param id 指令执行结果(客户端回传)ID + * @return 指令执行结果(客户端回传) + */ + public EcCommandResult selectEcCommandResultById(Long id); + + /** + * 查询指令执行结果(客户端回传)列表 + * + * @param ecCommandResult 指令执行结果(客户端回传) + * @return 指令执行结果(客户端回传)集合 + */ + public List selectEcCommandResultList(EcCommandResult ecCommandResult); + + /** + * 新增指令执行结果(客户端回传) + * + * @param ecCommandResult 指令执行结果(客户端回传) + * @return 结果 + */ + public int insertEcCommandResult(EcCommandResult ecCommandResult); + + /** + * 修改指令执行结果(客户端回传) + * + * @param ecCommandResult 指令执行结果(客户端回传) + * @return 结果 + */ + public int updateEcCommandResult(EcCommandResult ecCommandResult); + + /** + * 批量删除指令执行结果(客户端回传) + * + * @param ids 需要删除的指令执行结果(客户端回传)ID + * @return 结果 + */ + public int deleteEcCommandResultByIds(Long[] ids); + + /** + * 删除指令执行结果(客户端回传)信息 + * + * @param id 指令执行结果(客户端回传)ID + * @return 结果 + */ + public int deleteEcCommandResultById(Long id); + + List getByIds(List ids, SFunction... columns); + + EcCommandResultPlus getById(Long id, SFunction... columns); + + Map getMapByIds(List ids, SFunction... columns); + + List getByIds(List ids); + + Map getMapByIds(List ids); + + /** + * @param field sum 字段 + * @param where 条件 + * @param tClass 返回类型 + * @param + * @return + */ + T sum(String field, String where, Class tClass); + + Long count(String where); + + List countByGroupBy(String select, String where, String groupby, Class tClass); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/IEcControlTaskService.java b/luqj-ec/src/main/java/com/luqj/ec/service/IEcControlTaskService.java new file mode 100644 index 0000000..43a8cdc --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/IEcControlTaskService.java @@ -0,0 +1,89 @@ +package com.luqj.ec.service; +import java.util.Map; +import java.util.List; +import com.luqj.ec.domain.EcControlTask; +import com.luqj.ec.domain.EcControlTaskPlus; +import com.baomidou.mybatisplus.extension.service.IService; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.ruoyi.common.select.SelectItem; +/** + * 任务(群控核心)Service接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface IEcControlTaskService extends IService +{ + + List select(String keyword); + /** + * 查询任务(群控核心) + * + * @param id 任务(群控核心)ID + * @return 任务(群控核心) + */ + public EcControlTask selectEcControlTaskById(Long id); + + /** + * 查询任务(群控核心)列表 + * + * @param ecControlTask 任务(群控核心) + * @return 任务(群控核心)集合 + */ + public List selectEcControlTaskList(EcControlTask ecControlTask); + + /** + * 新增任务(群控核心) + * + * @param ecControlTask 任务(群控核心) + * @return 结果 + */ + public int insertEcControlTask(EcControlTask ecControlTask); + + /** + * 修改任务(群控核心) + * + * @param ecControlTask 任务(群控核心) + * @return 结果 + */ + public int updateEcControlTask(EcControlTask ecControlTask); + + /** + * 批量删除任务(群控核心) + * + * @param ids 需要删除的任务(群控核心)ID + * @return 结果 + */ + public int deleteEcControlTaskByIds(Long[] ids); + + /** + * 删除任务(群控核心)信息 + * + * @param id 任务(群控核心)ID + * @return 结果 + */ + public int deleteEcControlTaskById(Long id); + + List getByIds(List ids, SFunction... columns); + + EcControlTaskPlus getById(Long id, SFunction... columns); + + Map getMapByIds(List ids, SFunction... columns); + + List getByIds(List ids); + + Map getMapByIds(List ids); + + /** + * @param field sum 字段 + * @param where 条件 + * @param tClass 返回类型 + * @param + * @return + */ + T sum(String field, String where, Class tClass); + + Long count(String where); + + List countByGroupBy(String select, String where, String groupby, Class tClass); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceCommandService.java b/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceCommandService.java new file mode 100644 index 0000000..837cf6c --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceCommandService.java @@ -0,0 +1,89 @@ +package com.luqj.ec.service; +import java.util.Map; +import java.util.List; +import com.luqj.ec.domain.EcDeviceCommand; +import com.luqj.ec.domain.EcDeviceCommandPlus; +import com.baomidou.mybatisplus.extension.service.IService; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.ruoyi.common.select.SelectItem; +/** + * 控制指令(单条指令)Service接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface IEcDeviceCommandService extends IService +{ + + List select(String keyword); + /** + * 查询控制指令(单条指令) + * + * @param id 控制指令(单条指令)ID + * @return 控制指令(单条指令) + */ + public EcDeviceCommand selectEcDeviceCommandById(Long id); + + /** + * 查询控制指令(单条指令)列表 + * + * @param ecDeviceCommand 控制指令(单条指令) + * @return 控制指令(单条指令)集合 + */ + public List selectEcDeviceCommandList(EcDeviceCommand ecDeviceCommand); + + /** + * 新增控制指令(单条指令) + * + * @param ecDeviceCommand 控制指令(单条指令) + * @return 结果 + */ + public int insertEcDeviceCommand(EcDeviceCommand ecDeviceCommand); + + /** + * 修改控制指令(单条指令) + * + * @param ecDeviceCommand 控制指令(单条指令) + * @return 结果 + */ + public int updateEcDeviceCommand(EcDeviceCommand ecDeviceCommand); + + /** + * 批量删除控制指令(单条指令) + * + * @param ids 需要删除的控制指令(单条指令)ID + * @return 结果 + */ + public int deleteEcDeviceCommandByIds(Long[] ids); + + /** + * 删除控制指令(单条指令)信息 + * + * @param id 控制指令(单条指令)ID + * @return 结果 + */ + public int deleteEcDeviceCommandById(Long id); + + List getByIds(List ids, SFunction... columns); + + EcDeviceCommandPlus getById(Long id, SFunction... columns); + + Map getMapByIds(List ids, SFunction... columns); + + List getByIds(List ids); + + Map getMapByIds(List ids); + + /** + * @param field sum 字段 + * @param where 条件 + * @param tClass 返回类型 + * @param + * @return + */ + T sum(String field, String where, Class tClass); + + Long count(String where); + + List countByGroupBy(String select, String where, String groupby, Class tClass); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceService.java b/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceService.java new file mode 100644 index 0000000..6cb8ca4 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceService.java @@ -0,0 +1,89 @@ +package com.luqj.ec.service; +import java.util.Map; +import java.util.List; +import com.luqj.ec.domain.EcDevice; +import com.luqj.ec.domain.EcDevicePlus; +import com.baomidou.mybatisplus.extension.service.IService; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.ruoyi.common.select.SelectItem; +/** + * 设备(手机设备)Service接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface IEcDeviceService extends IService +{ + + List select(String keyword); + /** + * 查询设备(手机设备) + * + * @param id 设备(手机设备)ID + * @return 设备(手机设备) + */ + public EcDevice selectEcDeviceById(Long id); + + /** + * 查询设备(手机设备)列表 + * + * @param ecDevice 设备(手机设备) + * @return 设备(手机设备)集合 + */ + public List selectEcDeviceList(EcDevice ecDevice); + + /** + * 新增设备(手机设备) + * + * @param ecDevice 设备(手机设备) + * @return 结果 + */ + public int insertEcDevice(EcDevice ecDevice); + + /** + * 修改设备(手机设备) + * + * @param ecDevice 设备(手机设备) + * @return 结果 + */ + public int updateEcDevice(EcDevice ecDevice); + + /** + * 批量删除设备(手机设备) + * + * @param ids 需要删除的设备(手机设备)ID + * @return 结果 + */ + public int deleteEcDeviceByIds(Long[] ids); + + /** + * 删除设备(手机设备)信息 + * + * @param id 设备(手机设备)ID + * @return 结果 + */ + public int deleteEcDeviceById(Long id); + + List getByIds(List ids, SFunction... columns); + + EcDevicePlus getById(Long id, SFunction... columns); + + Map getMapByIds(List ids, SFunction... columns); + + List getByIds(List ids); + + Map getMapByIds(List ids); + + /** + * @param field sum 字段 + * @param where 条件 + * @param tClass 返回类型 + * @param + * @return + */ + T sum(String field, String where, Class tClass); + + Long count(String where); + + List countByGroupBy(String select, String where, String groupby, Class tClass); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceStatusService.java b/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceStatusService.java new file mode 100644 index 0000000..b68c014 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceStatusService.java @@ -0,0 +1,89 @@ +package com.luqj.ec.service; +import java.util.Map; +import java.util.List; +import com.luqj.ec.domain.EcDeviceStatus; +import com.luqj.ec.domain.EcDeviceStatusPlus; +import com.baomidou.mybatisplus.extension.service.IService; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.ruoyi.common.select.SelectItem; +/** + * 设备心跳 & 状态(高频)Service接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface IEcDeviceStatusService extends IService +{ + + List select(String keyword); + /** + * 查询设备心跳 & 状态(高频) + * + * @param id 设备心跳 & 状态(高频)ID + * @return 设备心跳 & 状态(高频) + */ + public EcDeviceStatus selectEcDeviceStatusById(Long id); + + /** + * 查询设备心跳 & 状态(高频)列表 + * + * @param ecDeviceStatus 设备心跳 & 状态(高频) + * @return 设备心跳 & 状态(高频)集合 + */ + public List selectEcDeviceStatusList(EcDeviceStatus ecDeviceStatus); + + /** + * 新增设备心跳 & 状态(高频) + * + * @param ecDeviceStatus 设备心跳 & 状态(高频) + * @return 结果 + */ + public int insertEcDeviceStatus(EcDeviceStatus ecDeviceStatus); + + /** + * 修改设备心跳 & 状态(高频) + * + * @param ecDeviceStatus 设备心跳 & 状态(高频) + * @return 结果 + */ + public int updateEcDeviceStatus(EcDeviceStatus ecDeviceStatus); + + /** + * 批量删除设备心跳 & 状态(高频) + * + * @param ids 需要删除的设备心跳 & 状态(高频)ID + * @return 结果 + */ + public int deleteEcDeviceStatusByIds(Long[] ids); + + /** + * 删除设备心跳 & 状态(高频)信息 + * + * @param id 设备心跳 & 状态(高频)ID + * @return 结果 + */ + public int deleteEcDeviceStatusById(Long id); + + List getByIds(List ids, SFunction... columns); + + EcDeviceStatusPlus getById(Long id, SFunction... columns); + + Map getMapByIds(List ids, SFunction... columns); + + List getByIds(List ids); + + Map getMapByIds(List ids); + + /** + * @param field sum 字段 + * @param where 条件 + * @param tClass 返回类型 + * @param + * @return + */ + T sum(String field, String where, Class tClass); + + Long count(String where); + + List countByGroupBy(String select, String where, String groupby, Class tClass); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/IEcTaskCommandService.java b/luqj-ec/src/main/java/com/luqj/ec/service/IEcTaskCommandService.java new file mode 100644 index 0000000..dae4ba9 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/IEcTaskCommandService.java @@ -0,0 +1,89 @@ +package com.luqj.ec.service; +import java.util.Map; +import java.util.List; +import com.luqj.ec.domain.EcTaskCommand; +import com.luqj.ec.domain.EcTaskCommandPlus; +import com.baomidou.mybatisplus.extension.service.IService; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.ruoyi.common.select.SelectItem; +/** + * 任务指令明细(一个任务多条指令)Service接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface IEcTaskCommandService extends IService +{ + + List select(String keyword); + /** + * 查询任务指令明细(一个任务多条指令) + * + * @param id 任务指令明细(一个任务多条指令)ID + * @return 任务指令明细(一个任务多条指令) + */ + public EcTaskCommand selectEcTaskCommandById(Long id); + + /** + * 查询任务指令明细(一个任务多条指令)列表 + * + * @param ecTaskCommand 任务指令明细(一个任务多条指令) + * @return 任务指令明细(一个任务多条指令)集合 + */ + public List selectEcTaskCommandList(EcTaskCommand ecTaskCommand); + + /** + * 新增任务指令明细(一个任务多条指令) + * + * @param ecTaskCommand 任务指令明细(一个任务多条指令) + * @return 结果 + */ + public int insertEcTaskCommand(EcTaskCommand ecTaskCommand); + + /** + * 修改任务指令明细(一个任务多条指令) + * + * @param ecTaskCommand 任务指令明细(一个任务多条指令) + * @return 结果 + */ + public int updateEcTaskCommand(EcTaskCommand ecTaskCommand); + + /** + * 批量删除任务指令明细(一个任务多条指令) + * + * @param ids 需要删除的任务指令明细(一个任务多条指令)ID + * @return 结果 + */ + public int deleteEcTaskCommandByIds(Long[] ids); + + /** + * 删除任务指令明细(一个任务多条指令)信息 + * + * @param id 任务指令明细(一个任务多条指令)ID + * @return 结果 + */ + public int deleteEcTaskCommandById(Long id); + + List getByIds(List ids, SFunction... columns); + + EcTaskCommandPlus getById(Long id, SFunction... columns); + + Map getMapByIds(List ids, SFunction... columns); + + List getByIds(List ids); + + Map getMapByIds(List ids); + + /** + * @param field sum 字段 + * @param where 条件 + * @param tClass 返回类型 + * @param + * @return + */ + T sum(String field, String where, Class tClass); + + Long count(String where); + + List countByGroupBy(String select, String where, String groupby, Class tClass); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/IEcTaskDeviceService.java b/luqj-ec/src/main/java/com/luqj/ec/service/IEcTaskDeviceService.java new file mode 100644 index 0000000..5648940 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/IEcTaskDeviceService.java @@ -0,0 +1,89 @@ +package com.luqj.ec.service; +import java.util.Map; +import java.util.List; +import com.luqj.ec.domain.EcTaskDevice; +import com.luqj.ec.domain.EcTaskDevicePlus; +import com.baomidou.mybatisplus.extension.service.IService; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.ruoyi.common.select.SelectItem; +/** + * 任务-设备关联(一任务多设备)Service接口 + * + * @author luqj + * @date 2026-02-27 + */ +public interface IEcTaskDeviceService extends IService +{ + + List select(String keyword); + /** + * 查询任务-设备关联(一任务多设备) + * + * @param id 任务-设备关联(一任务多设备)ID + * @return 任务-设备关联(一任务多设备) + */ + public EcTaskDevice selectEcTaskDeviceById(Long id); + + /** + * 查询任务-设备关联(一任务多设备)列表 + * + * @param ecTaskDevice 任务-设备关联(一任务多设备) + * @return 任务-设备关联(一任务多设备)集合 + */ + public List selectEcTaskDeviceList(EcTaskDevice ecTaskDevice); + + /** + * 新增任务-设备关联(一任务多设备) + * + * @param ecTaskDevice 任务-设备关联(一任务多设备) + * @return 结果 + */ + public int insertEcTaskDevice(EcTaskDevice ecTaskDevice); + + /** + * 修改任务-设备关联(一任务多设备) + * + * @param ecTaskDevice 任务-设备关联(一任务多设备) + * @return 结果 + */ + public int updateEcTaskDevice(EcTaskDevice ecTaskDevice); + + /** + * 批量删除任务-设备关联(一任务多设备) + * + * @param ids 需要删除的任务-设备关联(一任务多设备)ID + * @return 结果 + */ + public int deleteEcTaskDeviceByIds(Long[] ids); + + /** + * 删除任务-设备关联(一任务多设备)信息 + * + * @param id 任务-设备关联(一任务多设备)ID + * @return 结果 + */ + public int deleteEcTaskDeviceById(Long id); + + List getByIds(List ids, SFunction... columns); + + EcTaskDevicePlus getById(Long id, SFunction... columns); + + Map getMapByIds(List ids, SFunction... columns); + + List getByIds(List ids); + + Map getMapByIds(List ids); + + /** + * @param field sum 字段 + * @param where 条件 + * @param tClass 返回类型 + * @param + * @return + */ + T sum(String field, String where, Class tClass); + + Long count(String where); + + List countByGroupBy(String select, String where, String groupby, Class tClass); +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcCommandResultServiceImpl.java b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcCommandResultServiceImpl.java new file mode 100644 index 0000000..35608e1 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcCommandResultServiceImpl.java @@ -0,0 +1,200 @@ +package com.luqj.ec.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.luqj.ec.domain.EcCommandResult; +import com.luqj.ec.domain.EcCommandResultPlus; +import com.luqj.ec.mapper.EcCommandResultMapper; +import com.luqj.ec.service.IEcCommandResultService; +import com.ruoyi.common.select.SelectItem; +import com.ruoyi.common.utils.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 指令执行结果(客户端回传)Service业务层处理 + * + * @author luqj + * @date 2026-02-27 + */ +@Service +public class EcCommandResultServiceImpl extends ServiceImpl implements IEcCommandResultService { + @Autowired + private EcCommandResultMapper ecCommandResultMapper; + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public List getByIds(List ids, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).in(EcCommandResultPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + @Override + public List select(String keyword) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(EcCommandResultPlus::getId, EcCommandResultPlus::getResult) + .like(EcCommandResultPlus::getResult, keyword); + List list = this.list(lambdaQueryWrapper); + List result = new ArrayList<>(); + for (EcCommandResultPlus item : list) { + SelectItem selectItem = new SelectItem(); + selectItem.setName(item.getResult()+""); + selectItem.setId(item.getId()); + result.add(selectItem); + } + return result; + } + + @Override + public EcCommandResultPlus getById(Long id, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).eq(EcCommandResultPlus::getId, id); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids, SFunction... columns) { + List list = this.getByIds(ids, columns); + Map map = new HashMap<>(); + for (EcCommandResultPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public Map getMapByIds(List ids) { + List list = this.getByIds(ids); + Map map = new HashMap<>(); + for (EcCommandResultPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getByIds(List ids) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper().in(EcCommandResultPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + public T sum(String field, String where, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" sum(" + field + ") as total "); + stringBuffer.append(" from ec_command_result "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass); + return result; + } + + public Long count(String where) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" count(1)"); + stringBuffer.append(" from "); + stringBuffer.append(" ec_command_result "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class); + return result; + } + + public List countByGroupBy(String select, String where, String groupby, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(select); + stringBuffer.append(" from "); + stringBuffer.append(" ec_command_result "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + stringBuffer.append(" group by "); + stringBuffer.append(groupby); + List result = jdbcTemplate.queryForList(stringBuffer.toString()); + List tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass); + return tList; + } + + /** + * 查询指令执行结果(客户端回传) + * + * @param id 指令执行结果(客户端回传)ID + * @return 指令执行结果(客户端回传) + */ + @Override + public EcCommandResult selectEcCommandResultById(Long id) { + return ecCommandResultMapper.selectEcCommandResultById(id); + } + + /** + * 查询指令执行结果(客户端回传)列表 + * + * @param ecCommandResult 指令执行结果(客户端回传) + * @return 指令执行结果(客户端回传) + */ + @Override + public List selectEcCommandResultList(EcCommandResult ecCommandResult) { + return ecCommandResultMapper.selectEcCommandResultList(ecCommandResult); + } + + /** + * 新增指令执行结果(客户端回传) + * + * @param ecCommandResult 指令执行结果(客户端回传) + * @return 结果 + */ + @Override + public int insertEcCommandResult(EcCommandResult ecCommandResult) { + return ecCommandResultMapper.insertEcCommandResult(ecCommandResult); + } + + /** + * 修改指令执行结果(客户端回传) + * + * @param ecCommandResult 指令执行结果(客户端回传) + * @return 结果 + */ + @Override + public int updateEcCommandResult(EcCommandResult ecCommandResult) { + return ecCommandResultMapper.updateEcCommandResult(ecCommandResult); + } + + /** + * 批量删除指令执行结果(客户端回传) + * + * @param ids 需要删除的指令执行结果(客户端回传)ID + * @return 结果 + */ + @Override + public int deleteEcCommandResultByIds(Long[] ids) { + return ecCommandResultMapper.deleteEcCommandResultByIds(ids); + } + + /** + * 删除指令执行结果(客户端回传)信息 + * + * @param id 指令执行结果(客户端回传)ID + * @return 结果 + */ + @Override + public int deleteEcCommandResultById(Long id) { + return ecCommandResultMapper.deleteEcCommandResultById(id); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcControlTaskServiceImpl.java b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcControlTaskServiceImpl.java new file mode 100644 index 0000000..93ff856 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcControlTaskServiceImpl.java @@ -0,0 +1,205 @@ +package com.luqj.ec.service.impl; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; + +import java.util.ArrayList; +import java.util.HashMap; +import com.ruoyi.common.utils.StringUtils; +import com.alibaba.fastjson.JSONArray; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.luqj.ec.mapper.EcControlTaskMapper; +import com.luqj.ec.domain.EcControlTask; +import com.luqj.ec.domain.EcControlTaskPlus; +import com.luqj.ec.service.IEcControlTaskService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import com.ruoyi.common.select.SelectItem; +/** + * 任务(群控核心)Service业务层处理 + * + * @author luqj + * @date 2026-02-27 + */ +@Service +public class EcControlTaskServiceImpl extends ServiceImpl implements IEcControlTaskService +{ + @Autowired + private EcControlTaskMapper ecControlTaskMapper; + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public List getByIds(List ids, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).in(EcControlTaskPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + @Override + public List select(String keyword) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(EcControlTaskPlus::getId, EcControlTaskPlus::getTaskName) + .like(EcControlTaskPlus::getTaskName, keyword); + List list = this.list(lambdaQueryWrapper); + List result =new ArrayList<>(); + for (EcControlTaskPlus item : list){ + SelectItem selectItem = new SelectItem(); + selectItem.setName(item.getTaskName()); + selectItem.setId(item.getId()); + result.add(selectItem); + } + return result; + } + @Override + public EcControlTaskPlus getById(Long id, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).eq(EcControlTaskPlus::getId, id); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids, SFunction... columns) { + List list = this.getByIds(ids, columns); + Map map = new HashMap<>(); + for (EcControlTaskPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public Map getMapByIds(List ids) { + List list = this.getByIds(ids); + Map map = new HashMap<>(); + for (EcControlTaskPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getByIds(List ids) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper().in(EcControlTaskPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + public T sum(String field, String where, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" sum(" + field + ") as total "); + stringBuffer.append(" from ec_control_task "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass); + return result; + } + + public Long count(String where) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" count(1)"); + stringBuffer.append(" from "); + stringBuffer.append(" ec_control_task "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class); + return result; + } + + public List countByGroupBy(String select, String where, String groupby, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(select); + stringBuffer.append(" from "); + stringBuffer.append(" ec_control_task "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + stringBuffer.append(" group by "); + stringBuffer.append(groupby); + List result = jdbcTemplate.queryForList(stringBuffer.toString()); + List tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass); + return tList; + } + /** + * 查询任务(群控核心) + * + * @param id 任务(群控核心)ID + * @return 任务(群控核心) + */ + @Override + public EcControlTask selectEcControlTaskById(Long id) + { + return ecControlTaskMapper.selectEcControlTaskById(id); + } + + /** + * 查询任务(群控核心)列表 + * + * @param ecControlTask 任务(群控核心) + * @return 任务(群控核心) + */ + @Override + public List selectEcControlTaskList(EcControlTask ecControlTask) + { + return ecControlTaskMapper.selectEcControlTaskList(ecControlTask); + } + + /** + * 新增任务(群控核心) + * + * @param ecControlTask 任务(群控核心) + * @return 结果 + */ + @Override + public int insertEcControlTask(EcControlTask ecControlTask) + { + return ecControlTaskMapper.insertEcControlTask(ecControlTask); + } + + /** + * 修改任务(群控核心) + * + * @param ecControlTask 任务(群控核心) + * @return 结果 + */ + @Override + public int updateEcControlTask(EcControlTask ecControlTask) + { + return ecControlTaskMapper.updateEcControlTask(ecControlTask); + } + + /** + * 批量删除任务(群控核心) + * + * @param ids 需要删除的任务(群控核心)ID + * @return 结果 + */ + @Override + public int deleteEcControlTaskByIds(Long[] ids) + { + return ecControlTaskMapper.deleteEcControlTaskByIds(ids); + } + + /** + * 删除任务(群控核心)信息 + * + * @param id 任务(群控核心)ID + * @return 结果 + */ + @Override + public int deleteEcControlTaskById(Long id) + { + return ecControlTaskMapper.deleteEcControlTaskById(id); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceCommandServiceImpl.java b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceCommandServiceImpl.java new file mode 100644 index 0000000..253d4eb --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceCommandServiceImpl.java @@ -0,0 +1,205 @@ +package com.luqj.ec.service.impl; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; + +import java.util.ArrayList; +import java.util.HashMap; +import com.ruoyi.common.utils.StringUtils; +import com.alibaba.fastjson.JSONArray; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.luqj.ec.mapper.EcDeviceCommandMapper; +import com.luqj.ec.domain.EcDeviceCommand; +import com.luqj.ec.domain.EcDeviceCommandPlus; +import com.luqj.ec.service.IEcDeviceCommandService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import com.ruoyi.common.select.SelectItem; +/** + * 控制指令(单条指令)Service业务层处理 + * + * @author luqj + * @date 2026-02-27 + */ +@Service +public class EcDeviceCommandServiceImpl extends ServiceImpl implements IEcDeviceCommandService +{ + @Autowired + private EcDeviceCommandMapper ecDeviceCommandMapper; + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public List getByIds(List ids, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).in(EcDeviceCommandPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + @Override + public List select(String keyword) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(EcDeviceCommandPlus::getId, EcDeviceCommandPlus::getCommandType) + .like(EcDeviceCommandPlus::getCommandType, keyword); + List list = this.list(lambdaQueryWrapper); + List result =new ArrayList<>(); + for (EcDeviceCommandPlus item : list){ + SelectItem selectItem = new SelectItem(); + selectItem.setName(item.getCommandType()); + selectItem.setId(item.getId()); + result.add(selectItem); + } + return result; + } + @Override + public EcDeviceCommandPlus getById(Long id, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).eq(EcDeviceCommandPlus::getId, id); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids, SFunction... columns) { + List list = this.getByIds(ids, columns); + Map map = new HashMap<>(); + for (EcDeviceCommandPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public Map getMapByIds(List ids) { + List list = this.getByIds(ids); + Map map = new HashMap<>(); + for (EcDeviceCommandPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getByIds(List ids) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper().in(EcDeviceCommandPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + public T sum(String field, String where, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" sum(" + field + ") as total "); + stringBuffer.append(" from ec_device_command "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass); + return result; + } + + public Long count(String where) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" count(1)"); + stringBuffer.append(" from "); + stringBuffer.append(" ec_device_command "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class); + return result; + } + + public List countByGroupBy(String select, String where, String groupby, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(select); + stringBuffer.append(" from "); + stringBuffer.append(" ec_device_command "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + stringBuffer.append(" group by "); + stringBuffer.append(groupby); + List result = jdbcTemplate.queryForList(stringBuffer.toString()); + List tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass); + return tList; + } + /** + * 查询控制指令(单条指令) + * + * @param id 控制指令(单条指令)ID + * @return 控制指令(单条指令) + */ + @Override + public EcDeviceCommand selectEcDeviceCommandById(Long id) + { + return ecDeviceCommandMapper.selectEcDeviceCommandById(id); + } + + /** + * 查询控制指令(单条指令)列表 + * + * @param ecDeviceCommand 控制指令(单条指令) + * @return 控制指令(单条指令) + */ + @Override + public List selectEcDeviceCommandList(EcDeviceCommand ecDeviceCommand) + { + return ecDeviceCommandMapper.selectEcDeviceCommandList(ecDeviceCommand); + } + + /** + * 新增控制指令(单条指令) + * + * @param ecDeviceCommand 控制指令(单条指令) + * @return 结果 + */ + @Override + public int insertEcDeviceCommand(EcDeviceCommand ecDeviceCommand) + { + return ecDeviceCommandMapper.insertEcDeviceCommand(ecDeviceCommand); + } + + /** + * 修改控制指令(单条指令) + * + * @param ecDeviceCommand 控制指令(单条指令) + * @return 结果 + */ + @Override + public int updateEcDeviceCommand(EcDeviceCommand ecDeviceCommand) + { + return ecDeviceCommandMapper.updateEcDeviceCommand(ecDeviceCommand); + } + + /** + * 批量删除控制指令(单条指令) + * + * @param ids 需要删除的控制指令(单条指令)ID + * @return 结果 + */ + @Override + public int deleteEcDeviceCommandByIds(Long[] ids) + { + return ecDeviceCommandMapper.deleteEcDeviceCommandByIds(ids); + } + + /** + * 删除控制指令(单条指令)信息 + * + * @param id 控制指令(单条指令)ID + * @return 结果 + */ + @Override + public int deleteEcDeviceCommandById(Long id) + { + return ecDeviceCommandMapper.deleteEcDeviceCommandById(id); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceServiceImpl.java b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceServiceImpl.java new file mode 100644 index 0000000..295ae97 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceServiceImpl.java @@ -0,0 +1,205 @@ +package com.luqj.ec.service.impl; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; + +import java.util.ArrayList; +import java.util.HashMap; +import com.ruoyi.common.utils.StringUtils; +import com.alibaba.fastjson.JSONArray; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.luqj.ec.mapper.EcDeviceMapper; +import com.luqj.ec.domain.EcDevice; +import com.luqj.ec.domain.EcDevicePlus; +import com.luqj.ec.service.IEcDeviceService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import com.ruoyi.common.select.SelectItem; +/** + * 设备(手机设备)Service业务层处理 + * + * @author luqj + * @date 2026-02-27 + */ +@Service +public class EcDeviceServiceImpl extends ServiceImpl implements IEcDeviceService +{ + @Autowired + private EcDeviceMapper ecDeviceMapper; + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public List getByIds(List ids, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).in(EcDevicePlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + @Override + public List select(String keyword) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(EcDevicePlus::getId, EcDevicePlus::getDeviceCode) + .like(EcDevicePlus::getDeviceCode, keyword); + List list = this.list(lambdaQueryWrapper); + List result =new ArrayList<>(); + for (EcDevicePlus item : list){ + SelectItem selectItem = new SelectItem(); + selectItem.setName(item.getDeviceCode()); + selectItem.setId(item.getId()); + result.add(selectItem); + } + return result; + } + @Override + public EcDevicePlus getById(Long id, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).eq(EcDevicePlus::getId, id); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids, SFunction... columns) { + List list = this.getByIds(ids, columns); + Map map = new HashMap<>(); + for (EcDevicePlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public Map getMapByIds(List ids) { + List list = this.getByIds(ids); + Map map = new HashMap<>(); + for (EcDevicePlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getByIds(List ids) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper().in(EcDevicePlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + public T sum(String field, String where, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" sum(" + field + ") as total "); + stringBuffer.append(" from ec_device "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass); + return result; + } + + public Long count(String where) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" count(1)"); + stringBuffer.append(" from "); + stringBuffer.append(" ec_device "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class); + return result; + } + + public List countByGroupBy(String select, String where, String groupby, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(select); + stringBuffer.append(" from "); + stringBuffer.append(" ec_device "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + stringBuffer.append(" group by "); + stringBuffer.append(groupby); + List result = jdbcTemplate.queryForList(stringBuffer.toString()); + List tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass); + return tList; + } + /** + * 查询设备(手机设备) + * + * @param id 设备(手机设备)ID + * @return 设备(手机设备) + */ + @Override + public EcDevice selectEcDeviceById(Long id) + { + return ecDeviceMapper.selectEcDeviceById(id); + } + + /** + * 查询设备(手机设备)列表 + * + * @param ecDevice 设备(手机设备) + * @return 设备(手机设备) + */ + @Override + public List selectEcDeviceList(EcDevice ecDevice) + { + return ecDeviceMapper.selectEcDeviceList(ecDevice); + } + + /** + * 新增设备(手机设备) + * + * @param ecDevice 设备(手机设备) + * @return 结果 + */ + @Override + public int insertEcDevice(EcDevice ecDevice) + { + return ecDeviceMapper.insertEcDevice(ecDevice); + } + + /** + * 修改设备(手机设备) + * + * @param ecDevice 设备(手机设备) + * @return 结果 + */ + @Override + public int updateEcDevice(EcDevice ecDevice) + { + return ecDeviceMapper.updateEcDevice(ecDevice); + } + + /** + * 批量删除设备(手机设备) + * + * @param ids 需要删除的设备(手机设备)ID + * @return 结果 + */ + @Override + public int deleteEcDeviceByIds(Long[] ids) + { + return ecDeviceMapper.deleteEcDeviceByIds(ids); + } + + /** + * 删除设备(手机设备)信息 + * + * @param id 设备(手机设备)ID + * @return 结果 + */ + @Override + public int deleteEcDeviceById(Long id) + { + return ecDeviceMapper.deleteEcDeviceById(id); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceStatusServiceImpl.java b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceStatusServiceImpl.java new file mode 100644 index 0000000..7afcf87 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceStatusServiceImpl.java @@ -0,0 +1,205 @@ +package com.luqj.ec.service.impl; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; + +import java.util.ArrayList; +import java.util.HashMap; +import com.ruoyi.common.utils.StringUtils; +import com.alibaba.fastjson.JSONArray; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.luqj.ec.mapper.EcDeviceStatusMapper; +import com.luqj.ec.domain.EcDeviceStatus; +import com.luqj.ec.domain.EcDeviceStatusPlus; +import com.luqj.ec.service.IEcDeviceStatusService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import com.ruoyi.common.select.SelectItem; +/** + * 设备心跳 & 状态(高频)Service业务层处理 + * + * @author luqj + * @date 2026-02-27 + */ +@Service +public class EcDeviceStatusServiceImpl extends ServiceImpl implements IEcDeviceStatusService +{ + @Autowired + private EcDeviceStatusMapper ecDeviceStatusMapper; + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public List getByIds(List ids, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).in(EcDeviceStatusPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + @Override + public List select(String keyword) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(EcDeviceStatusPlus::getId, EcDeviceStatusPlus::getDeviceId) + .like(EcDeviceStatusPlus::getDeviceId, keyword); + List list = this.list(lambdaQueryWrapper); + List result =new ArrayList<>(); + for (EcDeviceStatusPlus item : list){ + SelectItem selectItem = new SelectItem(); + selectItem.setName(item.getDeviceId()+""); + selectItem.setId(item.getId()); + result.add(selectItem); + } + return result; + } + @Override + public EcDeviceStatusPlus getById(Long id, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).eq(EcDeviceStatusPlus::getId, id); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids, SFunction... columns) { + List list = this.getByIds(ids, columns); + Map map = new HashMap<>(); + for (EcDeviceStatusPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public Map getMapByIds(List ids) { + List list = this.getByIds(ids); + Map map = new HashMap<>(); + for (EcDeviceStatusPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getByIds(List ids) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper().in(EcDeviceStatusPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + public T sum(String field, String where, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" sum(" + field + ") as total "); + stringBuffer.append(" from ec_device_status "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass); + return result; + } + + public Long count(String where) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" count(1)"); + stringBuffer.append(" from "); + stringBuffer.append(" ec_device_status "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class); + return result; + } + + public List countByGroupBy(String select, String where, String groupby, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(select); + stringBuffer.append(" from "); + stringBuffer.append(" ec_device_status "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + stringBuffer.append(" group by "); + stringBuffer.append(groupby); + List result = jdbcTemplate.queryForList(stringBuffer.toString()); + List tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass); + return tList; + } + /** + * 查询设备心跳 & 状态(高频) + * + * @param id 设备心跳 & 状态(高频)ID + * @return 设备心跳 & 状态(高频) + */ + @Override + public EcDeviceStatus selectEcDeviceStatusById(Long id) + { + return ecDeviceStatusMapper.selectEcDeviceStatusById(id); + } + + /** + * 查询设备心跳 & 状态(高频)列表 + * + * @param ecDeviceStatus 设备心跳 & 状态(高频) + * @return 设备心跳 & 状态(高频) + */ + @Override + public List selectEcDeviceStatusList(EcDeviceStatus ecDeviceStatus) + { + return ecDeviceStatusMapper.selectEcDeviceStatusList(ecDeviceStatus); + } + + /** + * 新增设备心跳 & 状态(高频) + * + * @param ecDeviceStatus 设备心跳 & 状态(高频) + * @return 结果 + */ + @Override + public int insertEcDeviceStatus(EcDeviceStatus ecDeviceStatus) + { + return ecDeviceStatusMapper.insertEcDeviceStatus(ecDeviceStatus); + } + + /** + * 修改设备心跳 & 状态(高频) + * + * @param ecDeviceStatus 设备心跳 & 状态(高频) + * @return 结果 + */ + @Override + public int updateEcDeviceStatus(EcDeviceStatus ecDeviceStatus) + { + return ecDeviceStatusMapper.updateEcDeviceStatus(ecDeviceStatus); + } + + /** + * 批量删除设备心跳 & 状态(高频) + * + * @param ids 需要删除的设备心跳 & 状态(高频)ID + * @return 结果 + */ + @Override + public int deleteEcDeviceStatusByIds(Long[] ids) + { + return ecDeviceStatusMapper.deleteEcDeviceStatusByIds(ids); + } + + /** + * 删除设备心跳 & 状态(高频)信息 + * + * @param id 设备心跳 & 状态(高频)ID + * @return 结果 + */ + @Override + public int deleteEcDeviceStatusById(Long id) + { + return ecDeviceStatusMapper.deleteEcDeviceStatusById(id); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcTaskCommandServiceImpl.java b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcTaskCommandServiceImpl.java new file mode 100644 index 0000000..d05dc7f --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcTaskCommandServiceImpl.java @@ -0,0 +1,205 @@ +package com.luqj.ec.service.impl; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; + +import java.util.ArrayList; +import java.util.HashMap; +import com.ruoyi.common.utils.StringUtils; +import com.alibaba.fastjson.JSONArray; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.luqj.ec.mapper.EcTaskCommandMapper; +import com.luqj.ec.domain.EcTaskCommand; +import com.luqj.ec.domain.EcTaskCommandPlus; +import com.luqj.ec.service.IEcTaskCommandService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import com.ruoyi.common.select.SelectItem; +/** + * 任务指令明细(一个任务多条指令)Service业务层处理 + * + * @author luqj + * @date 2026-02-27 + */ +@Service +public class EcTaskCommandServiceImpl extends ServiceImpl implements IEcTaskCommandService +{ + @Autowired + private EcTaskCommandMapper ecTaskCommandMapper; + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public List getByIds(List ids, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).in(EcTaskCommandPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + @Override + public List select(String keyword) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(EcTaskCommandPlus::getId, EcTaskCommandPlus::getCommandType) + .like(EcTaskCommandPlus::getCommandType, keyword); + List list = this.list(lambdaQueryWrapper); + List result =new ArrayList<>(); + for (EcTaskCommandPlus item : list){ + SelectItem selectItem = new SelectItem(); + selectItem.setName(item.getCommandType()); + selectItem.setId(item.getId()); + result.add(selectItem); + } + return result; + } + @Override + public EcTaskCommandPlus getById(Long id, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).eq(EcTaskCommandPlus::getId, id); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids, SFunction... columns) { + List list = this.getByIds(ids, columns); + Map map = new HashMap<>(); + for (EcTaskCommandPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public Map getMapByIds(List ids) { + List list = this.getByIds(ids); + Map map = new HashMap<>(); + for (EcTaskCommandPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getByIds(List ids) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper().in(EcTaskCommandPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + public T sum(String field, String where, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" sum(" + field + ") as total "); + stringBuffer.append(" from ec_task_command "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass); + return result; + } + + public Long count(String where) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" count(1)"); + stringBuffer.append(" from "); + stringBuffer.append(" ec_task_command "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class); + return result; + } + + public List countByGroupBy(String select, String where, String groupby, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(select); + stringBuffer.append(" from "); + stringBuffer.append(" ec_task_command "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + stringBuffer.append(" group by "); + stringBuffer.append(groupby); + List result = jdbcTemplate.queryForList(stringBuffer.toString()); + List tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass); + return tList; + } + /** + * 查询任务指令明细(一个任务多条指令) + * + * @param id 任务指令明细(一个任务多条指令)ID + * @return 任务指令明细(一个任务多条指令) + */ + @Override + public EcTaskCommand selectEcTaskCommandById(Long id) + { + return ecTaskCommandMapper.selectEcTaskCommandById(id); + } + + /** + * 查询任务指令明细(一个任务多条指令)列表 + * + * @param ecTaskCommand 任务指令明细(一个任务多条指令) + * @return 任务指令明细(一个任务多条指令) + */ + @Override + public List selectEcTaskCommandList(EcTaskCommand ecTaskCommand) + { + return ecTaskCommandMapper.selectEcTaskCommandList(ecTaskCommand); + } + + /** + * 新增任务指令明细(一个任务多条指令) + * + * @param ecTaskCommand 任务指令明细(一个任务多条指令) + * @return 结果 + */ + @Override + public int insertEcTaskCommand(EcTaskCommand ecTaskCommand) + { + return ecTaskCommandMapper.insertEcTaskCommand(ecTaskCommand); + } + + /** + * 修改任务指令明细(一个任务多条指令) + * + * @param ecTaskCommand 任务指令明细(一个任务多条指令) + * @return 结果 + */ + @Override + public int updateEcTaskCommand(EcTaskCommand ecTaskCommand) + { + return ecTaskCommandMapper.updateEcTaskCommand(ecTaskCommand); + } + + /** + * 批量删除任务指令明细(一个任务多条指令) + * + * @param ids 需要删除的任务指令明细(一个任务多条指令)ID + * @return 结果 + */ + @Override + public int deleteEcTaskCommandByIds(Long[] ids) + { + return ecTaskCommandMapper.deleteEcTaskCommandByIds(ids); + } + + /** + * 删除任务指令明细(一个任务多条指令)信息 + * + * @param id 任务指令明细(一个任务多条指令)ID + * @return 结果 + */ + @Override + public int deleteEcTaskCommandById(Long id) + { + return ecTaskCommandMapper.deleteEcTaskCommandById(id); + } +} diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcTaskDeviceServiceImpl.java b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcTaskDeviceServiceImpl.java new file mode 100644 index 0000000..d232041 --- /dev/null +++ b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcTaskDeviceServiceImpl.java @@ -0,0 +1,205 @@ +package com.luqj.ec.service.impl; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; + +import java.util.ArrayList; +import java.util.HashMap; +import com.ruoyi.common.utils.StringUtils; +import com.alibaba.fastjson.JSONArray; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.luqj.ec.mapper.EcTaskDeviceMapper; +import com.luqj.ec.domain.EcTaskDevice; +import com.luqj.ec.domain.EcTaskDevicePlus; +import com.luqj.ec.service.IEcTaskDeviceService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import com.ruoyi.common.select.SelectItem; +/** + * 任务-设备关联(一任务多设备)Service业务层处理 + * + * @author luqj + * @date 2026-02-27 + */ +@Service +public class EcTaskDeviceServiceImpl extends ServiceImpl implements IEcTaskDeviceService +{ + @Autowired + private EcTaskDeviceMapper ecTaskDeviceMapper; + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public List getByIds(List ids, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).in(EcTaskDevicePlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + @Override + public List select(String keyword) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(EcTaskDevicePlus::getId, EcTaskDevicePlus::getStatus) + .like(EcTaskDevicePlus::getStatus, keyword); + List list = this.list(lambdaQueryWrapper); + List result =new ArrayList<>(); + for (EcTaskDevicePlus item : list){ + SelectItem selectItem = new SelectItem(); + selectItem.setName(item.getStatus()+""); + selectItem.setId(item.getId()); + result.add(selectItem); + } + return result; + } + @Override + public EcTaskDevicePlus getById(Long id, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).eq(EcTaskDevicePlus::getId, id); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids, SFunction... columns) { + List list = this.getByIds(ids, columns); + Map map = new HashMap<>(); + for (EcTaskDevicePlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public Map getMapByIds(List ids) { + List list = this.getByIds(ids); + Map map = new HashMap<>(); + for (EcTaskDevicePlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getByIds(List ids) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper().in(EcTaskDevicePlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + public T sum(String field, String where, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" sum(" + field + ") as total "); + stringBuffer.append(" from ec_task_device "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass); + return result; + } + + public Long count(String where) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" count(1)"); + stringBuffer.append(" from "); + stringBuffer.append(" ec_task_device "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class); + return result; + } + + public List countByGroupBy(String select, String where, String groupby, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(select); + stringBuffer.append(" from "); + stringBuffer.append(" ec_task_device "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + stringBuffer.append(" group by "); + stringBuffer.append(groupby); + List result = jdbcTemplate.queryForList(stringBuffer.toString()); + List tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass); + return tList; + } + /** + * 查询任务-设备关联(一任务多设备) + * + * @param id 任务-设备关联(一任务多设备)ID + * @return 任务-设备关联(一任务多设备) + */ + @Override + public EcTaskDevice selectEcTaskDeviceById(Long id) + { + return ecTaskDeviceMapper.selectEcTaskDeviceById(id); + } + + /** + * 查询任务-设备关联(一任务多设备)列表 + * + * @param ecTaskDevice 任务-设备关联(一任务多设备) + * @return 任务-设备关联(一任务多设备) + */ + @Override + public List selectEcTaskDeviceList(EcTaskDevice ecTaskDevice) + { + return ecTaskDeviceMapper.selectEcTaskDeviceList(ecTaskDevice); + } + + /** + * 新增任务-设备关联(一任务多设备) + * + * @param ecTaskDevice 任务-设备关联(一任务多设备) + * @return 结果 + */ + @Override + public int insertEcTaskDevice(EcTaskDevice ecTaskDevice) + { + return ecTaskDeviceMapper.insertEcTaskDevice(ecTaskDevice); + } + + /** + * 修改任务-设备关联(一任务多设备) + * + * @param ecTaskDevice 任务-设备关联(一任务多设备) + * @return 结果 + */ + @Override + public int updateEcTaskDevice(EcTaskDevice ecTaskDevice) + { + return ecTaskDeviceMapper.updateEcTaskDevice(ecTaskDevice); + } + + /** + * 批量删除任务-设备关联(一任务多设备) + * + * @param ids 需要删除的任务-设备关联(一任务多设备)ID + * @return 结果 + */ + @Override + public int deleteEcTaskDeviceByIds(Long[] ids) + { + return ecTaskDeviceMapper.deleteEcTaskDeviceByIds(ids); + } + + /** + * 删除任务-设备关联(一任务多设备)信息 + * + * @param id 任务-设备关联(一任务多设备)ID + * @return 结果 + */ + @Override + public int deleteEcTaskDeviceById(Long id) + { + return ecTaskDeviceMapper.deleteEcTaskDeviceById(id); + } +} diff --git a/luqj-ec/src/main/resources/mapper/ec/EcCommandResultMapper.xml b/luqj-ec/src/main/resources/mapper/ec/EcCommandResultMapper.xml new file mode 100644 index 0000000..d76d0a4 --- /dev/null +++ b/luqj-ec/src/main/resources/mapper/ec/EcCommandResultMapper.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + select id, command_id, device_id, result, error_msg, response_data, created_at from ec_command_result + + + + + + + + insert into ec_command_result + + command_id, + device_id, + result, + error_msg, + response_data, + created_at, + + + #{commandId}, + #{deviceId}, + #{result}, + #{errorMsg}, + #{responseData}, + #{createdAt}, + + + + + update ec_command_result + + command_id = #{commandId}, + device_id = #{deviceId}, + result = #{result}, + error_msg = #{errorMsg}, + response_data = #{responseData}, + created_at = #{createdAt}, + + where id = #{id} + + + + delete from ec_command_result where id = #{id} + + + + delete from ec_command_result where id in + + #{id} + + + \ No newline at end of file diff --git a/luqj-ec/src/main/resources/mapper/ec/EcControlTaskMapper.xml b/luqj-ec/src/main/resources/mapper/ec/EcControlTaskMapper.xml new file mode 100644 index 0000000..0fd0737 --- /dev/null +++ b/luqj-ec/src/main/resources/mapper/ec/EcControlTaskMapper.xml @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + select id, task_name, task_type, user_id, status, created_at, updated_at, app_id from ec_control_task + + + + + + + + insert into ec_control_task + + task_name, + task_type, + user_id, + status, + created_at, + updated_at, + app_id, + + + #{taskName}, + #{taskType}, + #{userId}, + #{status}, + #{createdAt}, + #{updatedAt}, + #{appId}, + + + + + update ec_control_task + + task_name = #{taskName}, + task_type = #{taskType}, + user_id = #{userId}, + status = #{status}, + created_at = #{createdAt}, + updated_at = #{updatedAt}, + app_id = #{appId}, + + where id = #{id} + + + + delete from ec_control_task where id = #{id} + + + + delete from ec_control_task where id in + + #{id} + + + \ No newline at end of file diff --git a/luqj-ec/src/main/resources/mapper/ec/EcDeviceCommandMapper.xml b/luqj-ec/src/main/resources/mapper/ec/EcDeviceCommandMapper.xml new file mode 100644 index 0000000..43724b6 --- /dev/null +++ b/luqj-ec/src/main/resources/mapper/ec/EcDeviceCommandMapper.xml @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + select id, device_id, command_type, command_content, status, send_time, execute_time, finish_time from ec_device_command + + + + + + + + insert into ec_device_command + + device_id, + command_type, + command_content, + status, + send_time, + execute_time, + finish_time, + + + #{deviceId}, + #{commandType}, + #{commandContent}, + #{status}, + #{sendTime}, + #{executeTime}, + #{finishTime}, + + + + + update ec_device_command + + device_id = #{deviceId}, + command_type = #{commandType}, + command_content = #{commandContent}, + status = #{status}, + send_time = #{sendTime}, + execute_time = #{executeTime}, + finish_time = #{finishTime}, + + where id = #{id} + + + + delete from ec_device_command where id = #{id} + + + + delete from ec_device_command where id in + + #{id} + + + \ No newline at end of file diff --git a/luqj-ec/src/main/resources/mapper/ec/EcDeviceMapper.xml b/luqj-ec/src/main/resources/mapper/ec/EcDeviceMapper.xml new file mode 100644 index 0000000..0028e57 --- /dev/null +++ b/luqj-ec/src/main/resources/mapper/ec/EcDeviceMapper.xml @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + select id, device_code, brand, model, os_type, os_version, app_version, status, last_online_time, created_at, updated_at, ip_address, last_screen_pic, width_num, height_num, control_type, app_id, user_id, secret_key from ec_device + + + + + + + + insert into ec_device + + device_code, + brand, + model, + os_type, + os_version, + app_version, + status, + last_online_time, + created_at, + updated_at, + ip_address, + last_screen_pic, + width_num, + height_num, + control_type, + app_id, + user_id, + secret_key, + + + #{deviceCode}, + #{brand}, + #{model}, + #{osType}, + #{osVersion}, + #{appVersion}, + #{status}, + #{lastOnlineTime}, + #{createdAt}, + #{updatedAt}, + #{ipAddress}, + #{lastScreenPic}, + #{widthNum}, + #{heightNum}, + #{controlType}, + #{appId}, + #{userId}, + #{secretKey}, + + + + + update ec_device + + device_code = #{deviceCode}, + brand = #{brand}, + model = #{model}, + os_type = #{osType}, + os_version = #{osVersion}, + app_version = #{appVersion}, + status = #{status}, + last_online_time = #{lastOnlineTime}, + created_at = #{createdAt}, + updated_at = #{updatedAt}, + ip_address = #{ipAddress}, + last_screen_pic = #{lastScreenPic}, + width_num = #{widthNum}, + height_num = #{heightNum}, + control_type = #{controlType}, + app_id = #{appId}, + user_id = #{userId}, + secret_key = #{secretKey}, + + where id = #{id} + + + + delete from ec_device where id = #{id} + + + + delete from ec_device where id in + + #{id} + + + \ No newline at end of file diff --git a/luqj-ec/src/main/resources/mapper/ec/EcDeviceStatusMapper.xml b/luqj-ec/src/main/resources/mapper/ec/EcDeviceStatusMapper.xml new file mode 100644 index 0000000..2c75e7f --- /dev/null +++ b/luqj-ec/src/main/resources/mapper/ec/EcDeviceStatusMapper.xml @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + select id, device_id, battery, network_type, cpu_usage, memory_usage, screen_on, created_at, updated_at from ec_device_status + + + + + + + + insert into ec_device_status + + device_id, + battery, + network_type, + cpu_usage, + memory_usage, + screen_on, + created_at, + updated_at, + + + #{deviceId}, + #{battery}, + #{networkType}, + #{cpuUsage}, + #{memoryUsage}, + #{screenOn}, + #{createdAt}, + #{updatedAt}, + + + + + update ec_device_status + + device_id = #{deviceId}, + battery = #{battery}, + network_type = #{networkType}, + cpu_usage = #{cpuUsage}, + memory_usage = #{memoryUsage}, + screen_on = #{screenOn}, + created_at = #{createdAt}, + updated_at = #{updatedAt}, + + where id = #{id} + + + + delete from ec_device_status where id = #{id} + + + + delete from ec_device_status where id in + + #{id} + + + \ No newline at end of file diff --git a/luqj-ec/src/main/resources/mapper/ec/EcTaskCommandMapper.xml b/luqj-ec/src/main/resources/mapper/ec/EcTaskCommandMapper.xml new file mode 100644 index 0000000..620c39c --- /dev/null +++ b/luqj-ec/src/main/resources/mapper/ec/EcTaskCommandMapper.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + select id, task_id, step_order, command_type, command_content from ec_task_command + + + + + + + + insert into ec_task_command + + task_id, + step_order, + command_type, + command_content, + + + #{taskId}, + #{stepOrder}, + #{commandType}, + #{commandContent}, + + + + + update ec_task_command + + task_id = #{taskId}, + step_order = #{stepOrder}, + command_type = #{commandType}, + command_content = #{commandContent}, + + where id = #{id} + + + + delete from ec_task_command where id = #{id} + + + + delete from ec_task_command where id in + + #{id} + + + \ No newline at end of file diff --git a/luqj-ec/src/main/resources/mapper/ec/EcTaskDeviceMapper.xml b/luqj-ec/src/main/resources/mapper/ec/EcTaskDeviceMapper.xml new file mode 100644 index 0000000..6c16f9c --- /dev/null +++ b/luqj-ec/src/main/resources/mapper/ec/EcTaskDeviceMapper.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + select id, task_id, device_id, status, updated_at from ec_task_device + + + + + + + + insert into ec_task_device + + task_id, + device_id, + status, + updated_at, + + + #{taskId}, + #{deviceId}, + #{status}, + #{updatedAt}, + + + + + update ec_task_device + + task_id = #{taskId}, + device_id = #{deviceId}, + status = #{status}, + updated_at = #{updatedAt}, + + where id = #{id} + + + + delete from ec_task_device where id = #{id} + + + + delete from ec_task_device where id in + + #{id} + + + \ No newline at end of file diff --git a/luqj-plugin-demo/pom.xml b/luqj-plugin-demo/pom.xml new file mode 100644 index 0000000..53d70a5 --- /dev/null +++ b/luqj-plugin-demo/pom.xml @@ -0,0 +1,78 @@ + + 4.0.0 + + org.adminframework.boot + luqj-plugin-demo + 1.0 + jar + + luqj-plugin-demo + http://maven.apache.org + + + UTF-8 + D:\luqj-plugins\plugin-demo\1.0.0 + + + + + org.adminframework.boot + luqj-plugin-interface + 2.3.0 + + + com.ruoyi + luqj-plugin + 3.4.0 + compile + + + ant-contrib + ant-contrib + 1.0b3 + true + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 3.1.0 + + + copy + install + + run + + + + + + + + + + + copying handler.jar to plugin dir ... + + + + + current os is ${os.name}, will not copy handler.jar to plugin dir + + + + + + + + + + + diff --git a/luqj-plugin-demo/src/main/java/org/code/modules/plugin/demo/PluginTestService.java b/luqj-plugin-demo/src/main/java/org/code/modules/plugin/demo/PluginTestService.java new file mode 100644 index 0000000..8f9c434 --- /dev/null +++ b/luqj-plugin-demo/src/main/java/org/code/modules/plugin/demo/PluginTestService.java @@ -0,0 +1,12 @@ +package org.code.modules.plugin.demo; + +import org.code.modules.plugins.annotation.PluginBean; +import org.code.modules.plugins.annotation.PluginType; +import org.code.modules.plugins.service.IPluginTest; +@PluginBean(name = "pluginDemo", beanType = PluginType.DB_PLUGIN) +public class PluginTestService implements IPluginTest { + @Override + public String funcExec(String str) { + return "hahah"; + } +} diff --git a/luqj-plugin-demo/src/main/resources/config.properties b/luqj-plugin-demo/src/main/resources/config.properties new file mode 100644 index 0000000..5133955 --- /dev/null +++ b/luqj-plugin-demo/src/main/resources/config.properties @@ -0,0 +1,2 @@ +isLoad=true +jarName=lu-admin-plugin-demo-1.0.jar \ No newline at end of file diff --git a/luqj-plugin-interface/pom.xml b/luqj-plugin-interface/pom.xml new file mode 100644 index 0000000..463753e --- /dev/null +++ b/luqj-plugin-interface/pom.xml @@ -0,0 +1,25 @@ + + 4.0.0 + + org.adminframework.boot + luqj-plugin-interface + 2.3.0 + jar + + luqj-plugin-interface + http://maven.apache.org + + + UTF-8 + + + + + junit + junit + 3.8.1 + test + + + diff --git a/luqj-plugin-interface/src/main/java/org/code/modules/plugins/service/FormulaPluginHelp.java b/luqj-plugin-interface/src/main/java/org/code/modules/plugins/service/FormulaPluginHelp.java new file mode 100644 index 0000000..8fd62ad --- /dev/null +++ b/luqj-plugin-interface/src/main/java/org/code/modules/plugins/service/FormulaPluginHelp.java @@ -0,0 +1,9 @@ +package org.code.modules.plugins.service; +import java.util.Map; +import java.util.Set; + +public interface FormulaPluginHelp { + Set parseFieldList(String var1); + + Object execFormula(String var1, Map var2); +} \ No newline at end of file diff --git a/luqj-plugin-interface/src/main/java/org/code/modules/plugins/service/IPluginTest.java b/luqj-plugin-interface/src/main/java/org/code/modules/plugins/service/IPluginTest.java new file mode 100644 index 0000000..95c5515 --- /dev/null +++ b/luqj-plugin-interface/src/main/java/org/code/modules/plugins/service/IPluginTest.java @@ -0,0 +1,5 @@ +package org.code.modules.plugins.service; + +public interface IPluginTest { + String funcExec(String str); +} diff --git a/luqj-plugin/pom.xml b/luqj-plugin/pom.xml new file mode 100644 index 0000000..aefca26 --- /dev/null +++ b/luqj-plugin/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + + com.ruoyi + ruoyi + 3.4.0 + + + luqj-plugin + jar + + luqj-plugin + http://maven.apache.org + + + UTF-8 + + + + + net.sf.json-lib + json-lib + 2.3 + jdk13 + + + commons-io + commons-io + 2.6 + + + com.google.guava + guava + 33.0.0-jre + + + com.ruoyi + luqj-common + 3.4.0 + + + diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/PluginBeanFactory.java b/luqj-plugin/src/main/java/org/code/modules/plugins/PluginBeanFactory.java new file mode 100644 index 0000000..cb21273 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/PluginBeanFactory.java @@ -0,0 +1,142 @@ +package org.code.modules.plugins; + +import com.luqj.util.log.LogUtil; +import com.luqj.util.reflect.ClassUtils; +import com.luqj.util.reflect.GSetterUtil; +import org.code.modules.plugins.service.IBeanFactory; +import org.code.modules.plugins.service.IPluginRegistry; +import org.code.modules.plugins.service.IllegalPluginException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.DependsOn; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.lang.reflect.Field; +@DependsOn(value = "defPluginRegistry") +@Component(value = "pluginBeanFactory") +public class PluginBeanFactory implements IBeanFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(PluginBeanFactory.class); + @Autowired + private IPluginRegistry pluginRegistry; + @Autowired + @Qualifier("springBeanFactory") + private IBeanFactory springBeanFactory; + @PostConstruct + public void init() { + pluginRegistry.init(); + } + + public T getBean(String beanName, Class beanClass) { + if (beanName.endsWith("Action")) { + LOGGER.debug("获取bean: {}", beanName); + } + return getBean(beanName, "def", beanClass); + } + + + @Override + public T getBean(String beanName, String version, Class beanClass) { + try { + T obj = pluginRegistry.instancePluginBean(beanName, version, beanClass); + if (obj != null) { + injectBean(obj); + return obj; + } else { + if (this.springBeanFactory.containsBean(beanName)) { + return this.springBeanFactory.getBean(beanName, beanClass); + } else { + LOGGER.debug("找不到指定的bean[{}]", beanName); + return null; + } + } + } catch (Throwable e) { + + LOGGER.error(LogUtil.exceptionMsg("bean[" + beanName + ":" + version + "],加载异常", e), e); + new IllegalPluginException(LogUtil.exceptionMsg("bean[" + beanName + ":" + version + "],加载异常", e), e); + return null; + } + } + + @Override + public Object getBean(String beanName) { + return getBean(beanName, Object.class); + } + + + @Override + public void injectBean(Object obj, String version) { + Class classType = obj.getClass(); + Field[] fields = ClassUtils.getDeclaredFields(classType); + for (Field field : fields) { + try { + if (this.springBeanFactory.containsBean(field.getName())) { + if (GSetterUtil.existSetter(classType, field)) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace(classType.getSimpleName() + "." + field.getName() + "spring注入成功!"); + } + GSetterUtil.setValueBySetter(obj, field, this.springBeanFactory.getBean(field.getName())); + } + } else if (this.pluginRegistry.containsPluginBean(field.getName()) + && GSetterUtil.getValueByGetter(obj, field) == null) {//有值不注入 + Object fBean = this.getBean(field.getName(), Object.class); + injectBean(fBean, version); + GSetterUtil.setValueBySetter(obj, field, fBean); + } + } catch (Throwable e) { + LOGGER.error(classType.getSimpleName() + "." + field.getName() + + "注入异常,异常消息[" + e.getMessage() + "]", e); + } + } + } + + public void injectBean(Object obj) { + Class classType = obj.getClass(); + Field[] fields = ClassUtils.getDeclaredFields(classType); + for (Field field : fields) { + try { + if (this.springBeanFactory.containsBean(field.getName())) { + if (GSetterUtil.existSetter(classType, field)) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace(classType.getSimpleName() + "." + field.getName() + "spring注入成功!"); + } + GSetterUtil.setValueBySetter(obj, field, this.springBeanFactory.getBean(field.getName())); + } + } else if (this.pluginRegistry.containsPluginBean(field.getName()) + && GSetterUtil.getValueByGetter(obj, field) == null) {//有值不注入 + Object fBean = this.getBean(field.getName()); + injectBean(fBean); + GSetterUtil.setValueBySetter(obj, field, fBean); + } + } catch (Throwable e) { + LOGGER.error(classType.getSimpleName() + "." + field.getName() + + "注入异常,异常消息[" + e.getMessage() + "]", e); + } + } + } + + + @Override + public boolean containsBean(String beanName) { + return pluginRegistry.containsPluginBean(beanName) + || springBeanFactory.containsBean(beanName); + } + + @Override + public void autowireComponent(Object bean) { + + } + + + public IPluginRegistry getPluginRegistry() { + return pluginRegistry; + } + + public void setPluginRegistry(IPluginRegistry pluginRegistry) { + this.pluginRegistry = pluginRegistry; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/SpringBeanFactory.java b/luqj-plugin/src/main/java/org/code/modules/plugins/SpringBeanFactory.java new file mode 100644 index 0000000..ed686c7 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/SpringBeanFactory.java @@ -0,0 +1,67 @@ +package org.code.modules.plugins;; + +import com.luqj.util.assertion.Assert; +import org.code.modules.plugins.service.IBeanFactory; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component(value = "springBeanFactory") +public class SpringBeanFactory implements ApplicationContextAware, IBeanFactory { + private static ApplicationContext applicationContext; + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + if (SpringBeanFactory.applicationContext == null) { + SpringBeanFactory.applicationContext = applicationContext; + } + System.out.println("========ApplicationContext配置成功========"); + System.out.println("========在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象========"); + System.out.println("========applicationContext=" + SpringBeanFactory.applicationContext + "========"); + } + + /** + * 获取applicationContext + * + * @return + */ + public static ApplicationContext getApplicationContext() { + return applicationContext; + } + + + @Override + public boolean containsBean(String beanName) { + return this.applicationContext.containsBean(beanName); + } + + @Override + public T getBean(String beanName, Class beanClass) { + return applicationContext.getBean(beanName, beanClass); + } + + @Override + public Object getBean(String beanName) { + return applicationContext.getBean(beanName); + } + + @Override + public void injectBean(Object obj) { + Assert.fail("此类禁用此方法"); + } + + public void injectBean(Object obj, String version) { + Assert.fail("此类禁用此方法"); + } + + @Override + public void autowireComponent(Object bean) { + + } + + @Override + public T getBean(String beanName, String version, Class beanClass) { + // TODO Auto-generated method stub + return getBean(beanName, beanClass); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/DBTypeMapping.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/DBTypeMapping.java new file mode 100644 index 0000000..bba37a5 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/DBTypeMapping.java @@ -0,0 +1,16 @@ +package org.code.modules.plugins.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface DBTypeMapping { + + String name(); + + String dbType(); + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/EtlApiDubboService.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/EtlApiDubboService.java new file mode 100644 index 0000000..55ae653 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/EtlApiDubboService.java @@ -0,0 +1,12 @@ +package org.code.modules.plugins.annotation; + +import org.springframework.stereotype.Component; + +import java.lang.annotation.*; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Component +public @interface EtlApiDubboService { +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/EtlApiSave.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/EtlApiSave.java new file mode 100644 index 0000000..0e6e179 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/EtlApiSave.java @@ -0,0 +1,11 @@ +package org.code.modules.plugins.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface EtlApiSave { +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/EtlApiService.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/EtlApiService.java new file mode 100644 index 0000000..13c782e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/EtlApiService.java @@ -0,0 +1,13 @@ +package org.code.modules.plugins.annotation; + +import org.springframework.stereotype.Component; + +import java.lang.annotation.*; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Component +public @interface EtlApiService { + String pluginCode(); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginAttribute.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginAttribute.java new file mode 100644 index 0000000..fa0911d --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginAttribute.java @@ -0,0 +1,17 @@ +package org.code.modules.plugins.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Created by chenzm on 2016/12/27. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface PluginAttribute { + String code() default ""; + String name(); + String type() default ""; +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginBackup.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginBackup.java new file mode 100644 index 0000000..01d16d3 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginBackup.java @@ -0,0 +1,21 @@ +package org.code.modules.plugins.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 实现数据备份所需的插件 + * @author xufm + * @date 2018/4/2 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface PluginBackup { + /** + * 别名 + * @return + */ + String name() default ""; +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginBean.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginBean.java new file mode 100644 index 0000000..fdfba18 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginBean.java @@ -0,0 +1,107 @@ +package org.code.modules.plugins.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface PluginBean { + /** + * 插件名称 + * + * @return + */ + String name() default ""; + + /** + * 别名 + * + * @return + */ + String aliasName() default ""; + + /** + * 插件类 + * + * @return + */ + PluginEnum clazz() default PluginEnum.DEFAULT; + + /** + * 插件所属分类 + * + * @return + */ + String pluginClassify() default ""; + + /** + * 插件类型 + * + * @return + */ + PluginType beanType(); + + /** + * 分区模式 + * + * @return + */ + String partitionPattern() default ""; + + /** + * 线程模式 + * + * @return + */ + String workThreadPattern() default ""; + + /** + * 分区 + * + * @return + */ + PluginPartition[] partitions() default {}; + + /** + * 执行模式 + * + * @return + */ + EnumExecuteMod executeMod() default EnumExecuteMod.NOTHING; + + + enum EnumExecuteMod { + /** + * 表示不显示 + */ + NOTHING(""), + /** + * ETL显示 + */ + ETL("1"), + /** + * 魔方显示 + */ + MF("2"), + /** + * 所有都显示 + */ + ALL("3"); + + private String code; + + EnumExecuteMod(String code) { + this.code = code; + } + + public String getCode() { + return code; + } + } +} + + + diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginEnum.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginEnum.java new file mode 100644 index 0000000..2ef3c08 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginEnum.java @@ -0,0 +1,30 @@ +package org.code.modules.plugins.annotation; + +/** + * 插件类型 + * Created by chenzm on 2017/1/12. + */ +public enum PluginEnum { + INPUT_PLUGIN("输入插件", "org.code.modules.plugin.common.InputTransPlugin"), + + OUTPUT_PLUGIN("输出插件", "org.code.modules.plugin.common.OutputTransPlugin"), + + TRANSFORM_PLUGIN("转换插件", "org.code.modules.plugin.common.TransformPlugin"), + + BATCH_TRANSFORM_PLUGIN("批量转换插件", "org.code.modules.plugin.common.BatchTransformPlugin"), + + SAVEPOINT_PLUGIN("增量输出插件", "org.code.modules.plugin.common.SavePointTransformPlugin"), + + AGGREGATOR_PLUGIN("聚合插件", "org.code.modules.plugin.common.AggregatorPlugin"), + + DEFAULT("", ""); + + public String name; + + public String javaClass; + + PluginEnum(String name, String javaClass) { + this.name = name; + this.javaClass = javaClass; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginPartition.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginPartition.java new file mode 100644 index 0000000..d33065b --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginPartition.java @@ -0,0 +1,30 @@ +package org.code.modules.plugins.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 分区注解 + * Created by chenzm on 2016/12/27. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface PluginPartition { + String code() default ""; + + String name(); + + String type(); + + String pattern(); + + String javaClass(); + + /** + * 是否默认分区 + * @return + */ + boolean isDefaultPartition() default false; +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginType.java new file mode 100644 index 0000000..6c43485 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/PluginType.java @@ -0,0 +1,11 @@ +package org.code.modules.plugins.annotation; + +public enum PluginType { + DB_PLUGIN, + ETL_TRANS_PLUGIN, + BS_PLUGIN, + ETL_TRANS_EXP, + //ETL的VO对象 + ETL_TRANS_META, + FUNC, +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/TransNonStandard.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/TransNonStandard.java new file mode 100644 index 0000000..8bd6511 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/TransNonStandard.java @@ -0,0 +1,16 @@ +package org.code.modules.plugins.annotation; + +import org.code.modules.plugins.types.TypeEnum; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface TransNonStandard { + + TypeEnum stdType(); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/TransStandard.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/TransStandard.java new file mode 100644 index 0000000..b5842f4 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/TransStandard.java @@ -0,0 +1,14 @@ +package org.code.modules.plugins.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface TransStandard { + + String typeCode(); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Asscocation.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Asscocation.java new file mode 100644 index 0000000..2e5b55a --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Asscocation.java @@ -0,0 +1,15 @@ +package org.code.modules.plugins.annotation.function; + +public @interface Asscocation { + String relationName(); + + Asscocation.RefType refType() default Asscocation.RefType.aggregation; + + public static enum RefType { + aggregation, + composite; + + private RefType() { + } + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Feature.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Feature.java new file mode 100644 index 0000000..fee0c1e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Feature.java @@ -0,0 +1,30 @@ +package org.code.modules.plugins.annotation.function; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD}) +public @interface Feature { + Feature.RefType refType() default Feature.RefType.aggregation; + + Feature.HandlerType handler() default Feature.HandlerType.HANDLER; + + public static enum RefType { + aggregation, + composite; + + private RefType() { + } + } + + public static enum HandlerType { + IGNORE, + HANDLER; + + private HandlerType() { + } + } +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Meta.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Meta.java new file mode 100644 index 0000000..7aefed2 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Meta.java @@ -0,0 +1,11 @@ +package org.code.modules.plugins.annotation.function; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +public @interface Meta { +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Relation.java b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Relation.java new file mode 100644 index 0000000..0d89968 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/annotation/function/Relation.java @@ -0,0 +1,15 @@ +package org.code.modules.plugins.annotation.function; + +public @interface Relation { + String relationName(); + + Relation.RefType refType() default Relation.RefType.aggregation; + + public static enum RefType { + aggregation, + composite; + + private RefType() { + } + } +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/data/RowData.java b/luqj-plugin/src/main/java/org/code/modules/plugins/data/RowData.java new file mode 100644 index 0000000..090a1c1 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/data/RowData.java @@ -0,0 +1,110 @@ +package org.code.modules.plugins.data; + + +import com.luqj.util.LinkedMultiValueMap; +import com.ruoyi.common.utils.StringUtils; +import org.code.modules.plugins.plugin.IIdentifierGenerator; +import org.code.modules.plugins.plugin.IRow; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + + +/** + * 数据行 + * Created by chenzm on 2017/1/6. + */ +public class RowData extends LinkedMultiValueMap implements IRow { + + private static final String IS_END_ROW = "$D_IS_END_ROW"; + + private transient IIdentifierGenerator identifierGenerator = DEFAULT_GENERATOR; + + private boolean isLastRowForDataSet=false; + + private String rowId; + + private String sourceId; + + /** + * 默认的ID生成器 + */ + private transient static final IIdentifierGenerator DEFAULT_GENERATOR = new IIdentifierGenerator() { + @Override + public String generate(IRow row) { + return UUID.randomUUID().toString(); + } + }; + + public RowData() { + } + public RowData(Map> row){ + this.putAll(row); + } + + public RowData(IIdentifierGenerator generator) { + this.identifierGenerator = generator; + } + + public RowData(boolean isEndRow) { + this.set(IS_END_ROW, isEndRow); + } + + public void reset(Map> row) { + this.clear(); + this.putAll(row); + } + + @Override + public String rowId() { + if (StringUtils.isBlank(rowId)) { + if(identifierGenerator==null){ + this.rowId=StringUtils.uuid(); + }else{ + this.rowId=identifierGenerator.generate(this); + } + } + return this.rowId; + } + + /** + * 是否结束行 + * @return + */ + @Override + public boolean isEndRow() { + if(!this.containsKey(IS_END_ROW) || this.getFirst(IS_END_ROW) == null) { + return false; + } + return (Boolean) this.getFirst(IS_END_ROW); + } + + @Override + public boolean isLastRowForDataSet() { + return this.isLastRowForDataSet; + } + + @Override + public String getSourceId() { + + return this.sourceId; + } + + public void markLastRowForDataSet(){ + this.isLastRowForDataSet=true; + } + + @Override + public void setIdentifierGenerator(IIdentifierGenerator generator) { + this.identifierGenerator = generator; + } + + public void setEndRow(boolean endRow) { + this.set(IS_END_ROW, endRow); + } + + public IIdentifierGenerator getIdentifierGenerator() { + return identifierGenerator; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/FuncEnum.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/FuncEnum.java new file mode 100644 index 0000000..3777869 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/FuncEnum.java @@ -0,0 +1,210 @@ +package org.code.modules.plugins.function; + +import java.util.HashSet; +import java.util.Set; + +/** + * 内置函数枚举类型 + * + * @author chenzm + */ +public enum FuncEnum { + BAG("BAG", 0, "包函数对参数不进行任何的计算直接返回参数 (系统级函数,NULL-OBJECT模式)", "org.code.modules.plugins.function.method.BagFunc"), + + REVERSE_LONG_TO_DATE("REVERSE_LONG_TO_DATE", 0, "数字转时间格式", "com.code.std.function.method.datetime.ReverseLongToDateFunc"), + TO_DATE("CHAR_TO_DATE", 0, "字符串转时间格式", "com.code.std.function.method.datetime.ToDateFunc"), + TO_CHAR("DATE_TO_CHAR", 0, "时间转字符串格式", "com.code.std.function.method.datetime.ToCharFunc"), + SYS_TIME("SYS_TIME", 0, "获取系统时间", "com.code.std.function.method.datetime.SysTimeFunc"), + MILLISECONDS("MILLISECONDS", 0, "获取毫秒数", "com.code.std.function.method.datetime.MilliSeconds"), + DATE_ADD("DATE_ADD", 0, "时间添加函数", "com.code.std.function.method.date.AddDayFunc"), + + + MAX("MAX", 0, "从一组数字中返回最大值", "com.code.std.function.method.mathematical.MaxFunc"), + MIN("MIN", 0, "从一组数字中返回最小值", "com.code.std.function.method.mathematical.MinFunc"), + AVG("AVG", 0, "从一组数字获取平均值", "com.code.std.function.method.mathematical.AvgFunc"), + SUM("SUM", 0, "一组数字的总和", "com.code.std.function.method.mathematical.SumFunc"), + CHAR_TO_NUMBER("CHAR_TO_NUMBER", 0, "文本转成数字", "com.code.std.function.method.mathematical.ToNumberFunc"), + NUMBER_TO_CHAR("NUMBER_TO_CHAR", 0, "数字转成文本", "com.code.std.function.method.text.ToCharFunc"), + POW("POW", 0, "求平方数", "com.code.std.function.method.mathematical.PowFunc"), + + RAVG("RAVG", 1, "数据集间求平均值", "com.code.std.function.method.mathematical.dataset.RAvgFunc"), + RMASS("RMASS", 1, "数据集间求众数", "com.code.std.function.method.mathematical.dataset.RMassFunc"), + RMAX("RMAX", 1, "数据集间求最大值", "com.code.std.function.method.mathematical.dataset.RMaxFunc"), + RMAX_LENGTH("RMAX_LENGTH", 1, "数据集间求最长值", "com.code.std.function.method.mathematical.dataset.RMaxLengthFunc"), + RMAX_MIDVALUE("RMAX_MIDVALUE", 1, "数据集间求中位数", "com.code.std.function.method.mathematical.dataset.RMidValueFunc"), + RMIN("RMIN", 1, "数据集间求最小值", "com.code.std.function.method.mathematical.dataset.RMinFunc"), + RMIN_LENGTH("RMIN_LENGTH", 1, "数据集间求最短值", "com.code.std.function.method.mathematical.dataset.RMinLengthFunc"), + RQTR3("RQTR3", 1, "数据集间求四分位数Q3", "com.code.std.function.method.mathematical.dataset.RQtr3Func"), + RQTR("RQTR", 1, "数据集间求四分位数Q1", "com.code.std.function.method.mathematical.dataset.RQtrFunc"), + RQTR_MINUS("RQTR_MINUS", 1, "数据集间求四分位数极差", "com.code.std.function.method.mathematical.dataset.RQtrMinusFunc"), + RRANGE("RRANGE", 1, "数据集间求极差", "com.code.std.function.method.mathematical.dataset.RRangeFunc"), + RSTDDEV("RSTDDEV", 1, "数据集间求标准差", "com.code.std.function.method.mathematical.dataset.RStdDevFunc"), + RVALUERANGE("RVALUERANGE", 1, "数据集间求值分布", "com.code.std.function.method.mathematical.dataset.RValueRangeFunc"), + RVARIANCE("RVARIANCE", 1, "数据集间求方差", "com.code.std.function.method.mathematical.dataset.RVarianceFunc"), + RVALSTA("RVALSTA", 1, "值统计", "com.code.std.function.method.mathematical.dataset.RValStaFunc"), + RSUM("RSUM", 1, "数据集间求和", "com.code.std.function.method.mathematical.dataset.RSumFunc"), + + + TRUE("TRUE", 0, "返回常数true值", "com.code.std.function.method.logical.TrueFunc"), + OR("OR", 0, "计算一组布尔参数的逻辑或", "com.code.std.function.method.logical.OrFunc"), + AND("AND", 0, "计算一组布尔参数的逻辑 与", "com.code.std.function.method.logical.AndFunc"), + IF("IF", 0, "返回两个值中的一个,根据条件", "com.code.std.function.method.logical.IfFunc"), + EQ("EQ", 0, "两个数值参数间的逻辑比较是否相等", "com.code.std.function.method.logical.EqFunc"), + GT("GT", 0, "两个数值参数间的逻辑比较是否大于", "com.code.std.function.method.logical.GtFunc"), + GTE("GTE", 0, "两个数值参数间的逻辑比较是否大于等于", "com.code.std.function.method.logical.GteFunc"), + LT("LT", 0, "两个数值参数间的逻辑比较是否小于", "com.code.std.function.method.logical.LtFunc"), + LTE("LTE", 0, "两个数值参数间的逻辑比较是否小于等于", "com.code.std.function.method.logical.LteFunc"), + NOT("NOT", 0, "计算逻辑NOT", "com.code.std.function.method.logical.NotFunc"), + XOR("XOR", 0, "计算逻辑XOR", "com.code.std.function.method.logical.XorFunc"), + MATCH("MATCH", 0, "逻辑匹配函数", "com.code.std.function.method.logical.MatchFunc"), + + CHOOSE("CHOOSE", 0, "使用索引从值的列表返回一个值", "com.code.std.function.method.information.ChooseFunc"), + ISBLANK("ISBLANK", 0, "如果参数值为空返回TRUE,否则返回FALSE", "com.code.std.function.method.information.IsBlankFunc"), + ISNUMBER("ISNUMBER", 0, "如果参数值为数字返回TRUE,否则返回FALSE", "com.code.std.function.method.information.IsNumberFunc"), + ISTEXT("ISTEXT", 0, "如果参数值为文本返回TRUE,否则返回FALSE", "com.code.std.function.method.information.IsTextFunc"), + + TEXT("TEXT", 0, "返回转换为文本的值", "com.code.std.function.method.text.TextFunc"), + TRIM("TRIM", 0, "返回文本去空后的值", "com.code.std.function.method.text.TrimFunc"), + UPPER("UPPER", 0, "小写字母转换为大写字母", "com.code.std.function.method.text.UpperFunc"), + LEN("LEN", 0, "返回文本的长度", "com.code.std.function.method.text.LenFunc"), + LOWER("LOWER", 0, "大写字母转换为小写字母", "com.code.std.function.method.text.LowerFunc"), + SUBSTRING("SUBSTRING", 0, "文本截取函数", "com.code.std.function.method.text.SubstringFunc"), + REPLACE("REPLACE", 0, "文本替换函数", "com.code.std.function.method.text.ReplaceFunc"), + EXACT("EXACT", 0, "比较两个字符串是否一致", "com.code.std.function.method.text.ExactFunc"), + FIND("FIND", 0, "查找字符串的位置", "com.code.std.function.method.text.FindFunc"), + CONCAT("CONCAT", 0, "字符串连接函数", "com.code.std.function.method.text.ConcatFunc"), + CONCAT_MULTI("CONCAT_MULTI", 0, "字符串连接函数(可变长参数)", "com.code.std.function.method.text.ConcatFunc"), + SPLITROW("SPLITROW", 0, "一行拆分成多行", "com.code.std.function.method.text.SplitIntoMultiRows"), + JSONPARSE("JSONPARSE", 0, "JSON解析", "com.code.std.function.method.text.JsonParseFunc"), + SPLIT("SPLIT", 0, "文本切分", "com.code.std.function.method.text.SplitFunc"), + INCLUDE("INCLUDE", 0, "包含函数", "com.code.std.function.method.text.IncludeFunc"), + + DECODE("DECODE", 0, "decode函数解析", "com.code.std.function.method.text.DecodeFunc"), + TO_ARRAY("TO_ARRAY", 0, "字符串转数组", "com.code.std.function.method.text.ToArrayFunc"), + + BIZ_IDCARD_GENDER("BIZ_IDCARD_GENDER", 0, "身份证查询性别函数", "com.code.std.function.method.biz.IdCardGenderFunc"), + BIZ_IDCARD_BIRTH("BIZ_IDCARD_BIRTH", 0, "身份证查询日期函数", "com.code.std.function.method.biz.IdCardBirthDay"), + BIZ_KEYPERSON_FILTER("BIZ_KEYPERSON_FILTER", 0, "前科人员筛选函数", "com.code.std.function.method.biz.KeyPersonFilterFunc"), + BIZ_MERGE_KEYPERSON("BIZ_MERGE_KEYPERSON", 0, "前科人员合并函数", "com.code.std.function.method.biz.MergeKeyPersonFunc"), + + DATA_COMPARISON("DATA_COMPARISON", 0, "数据比对", ""), + REDIS_DELETE("REDIS_DELETE", 0, "redis数据删除", ""), + REDIS_VALUES("REDIS_VALUES", 0, "redis取值", ""), + QUERY_CACHE("QUERY_CACHE", 0, "redis缓存查询", ""), + + + BERNOULLI_SAMPLER("BERNOULLI_SAMPLER", 0, "伯努利数据抽样", ""), + POISSON_SAMPLER("POISSON_SAMPLER", 0, "泊松数据抽样", ""), + RESERVOIR_SAMPLER("RESERVOIR_SAMPLER", 0, "水塘抽样", " "), + + + TEMPLATE_FUNCTION_A("TEMPLATE_FUNCTION_A", 0, "空模板", "com.code.std.function.method.biz.TemplateFunctionA"), + + REDUCE_BY_COUNT("REDUCE_BY_COUNT", 0, "reduce统计函数", "com.code.std.function.method.reduce.CountNumberFunc"), + + PLATENO_FILTER("PLATENO_FILTER", 0, "过滤数据", "com.code.std.function.method.fatePlate.PlateNOFilterFunc"), + PLATENO_TEST("PLATENO_TEST", 0, "车牌测试数据", "com.code.std.function.method.fatePlate.PlateNOTestFunc"), + + //fakePlate + STR_CONTAINS("STR_CONTAINS", 0, "判断是否包含字符串", "com.code.std.function.method.fatePlate.StrContainsFunc"), + UTC_DATE_PARSE("UTC_DATE_PARSE", 0, "转换东八区时间", "com.code.std.function.method.fatePlate.UTCDateParseFunc"), + DISTINCT_SORT_VEHICLE("DISTINCT_SORT_VEHICLE", 0, "去重并排序卡口", "com.code.std.function.method.fatePlate.DistinctSortVehicleFunc"), + SPLIT_VEHICLE_TUPPLE("SPLIT_VEHICLE_TUPPLE", 0, "拆分卡口元组", "com.code.std.function.method.fatePlate.SplitVehicleTuppleFunc"), + SUSPECT_FAKE("SUSPECT_FAKE", 0, "嫌疑车查找", "com.code.std.function.method.fatePlate.SuspectFakeFunc"), +// MINUTES_DIFF("MINUTES_DIFF", 0, "时间差,返回分钟", "com.code.std.function.method.fatePlate.MinutesDiffFunc"), + MINUTES_COMPARE("MINUTES_COMPARE", 0, "时间差(单位:分钟)和某一阈值的比较", "com.code.std.function.method.fatePlate.MinutesCompareFunc"), + NUM_KEY_SORT("NUM_KEY_SORT", 0, "针对数字类型列排序", "com.code.std.function.method.fatePlate.NumKeySortFunc"), + NUM_KEY_SORT_DISTINCT("NUM_KEY_SORT_DISTINCT", 0, "针对数字类型列排序,并去重", "com.code.std.function.method.fatePlate.NumKeySortDistinctFunc"), + SPLIT_TUPPLE("SPLIT_TUPPLE", 0, "划分二元组", "com.code.std.function.method.fatePlate.SplitTuppleFunc"), +// NUM_COMPARE("NUM_COMPARE", 0, "数值比较", "com.code.std.function.method.fatePlate.NumCompareFunc"), + MILLIS_TO_STRING("MILLIS_TO_STRING", 0, "时间戳转字符串", "com.code.std.function.method.fatePlate.MillisToString"), + STR_KEY_SORT("STR_KEY_SORT", 0, "针对字符串类型列排序", "com.code.std.function.method.sort.StrKeySortFunc"), + STR_KEY_SORT_DISTINCT("STR_KEY_SORT_DISTINCT", 0, "针对字符串类型列排序,并去重", "com.code.std.function.method.sort.StrKeySortDistinctFunc"), + DAYS_COMPARE("DAYS_COMPARE", 0, "时间差(单位:天数)和某一阈值比较", "com.code.std.function.method.date.DaysCompareFunc"), + DAYS_DIFF("DAYS_DIFF", 0, "时间差,返回天数", "com.code.std.function.method.date.DaysDiffFunc"), + HOURS_COMPARE("HOURS_COMPARE", 0, "时间差(单位:小时)和某一阈值比较", "com.code.std.function.method.date.HoursCompareFunc"), + HOURS_DIFF("HOURS_DIFF", 0, "时间差,返回小时", "com.code.std.function.method.date.HoursDiffFunc"), + SECONDS_COMPARE("SECONDS_COMPARE", 0, "时间差(单位:秒)和某一阈值比较", "com.code.std.function.method.date.SecondsCompareFunc"), + SECONDS_DIFF("SECONDS_DIFF", 0, "时间差,返回秒", "com.code.std.function.method.date.SecondsDiffFunc"), + MD5("MD5", 0, "MD5加密", "com.code.std.function.method.encrypt.MD5Func"), + CEIL("CEIL", 0, "大于输入数的整数", "com.code.std.function.method.mathematical.CeilFunc"), +// FLOOR("FLOOR", 0, "不小于输入数的整数", "com.code.std.function.method.mathematical.FloorFunc"), +// ROUND("ROUND", 0, "四舍五入", "com.code.std.function.method.mathematical.RoundFunc"), + SYS_GUID("SYS_GUID", 0, "生成唯一主键,不传参默认生成32位,传入指定数字生成指定位数的主键", "com.code.std.function.method.encrypt.SysGUIDFunc"), + REDUCE_DISTINCT("REDUCE_DISTINCT",0,"数据去重","com.code.std.function.method.distinctSort.ReduceDistinctFunc"), + REDUCE_STR_KEY_ASC_DISTINCT("REDUCE_STR_KEY_ASC_DISTINCT",0,"字符串排序并去重","com.code.std.function.method.distinctSort.ReduceStrKeyAscDistinctFunc"), + REDUCE_NUM_KEY_ASC_DISTINCT("REDUCE_NUM_KEY_ASC_DISTINCT",0,"数字排序并去重","com.code.std.function.method.distinctSort.ReduceNumKeyAscDistinctFunc"), + REDUCE_STR_KEY_ASC("REDUCE_STR_KEY_ASC",0,"字符串排序","com.code.std.function.method.distinctSort.ReduceStrKeyAscFunc"), + REDUCE_NUM_KEY_ASC("REDUCE_NUM_KEY_ASC",0,"数字排序","com.code.std.function.method.distinctSort.ReduceNumKeyAscFunc"), + LONG_LAT_DISTANCE("LONG_LAT_DISTANCE",0,"计算经纬度","com.code.std.function.method.mathematical.LongLatDistanceFunc"), + CACHING_FAKE("CACHING_FAKE",0,"福州卡口对比函数","com.code.std.function.method.caching.CachingFakeFunc"), + + //异常处理类 + TRY_CATCH("TRY_CATCH", 0, "异常处理类", "com.code.std.function.method.exception.TryCatchFunc"), + + CACHING_APPLY("CACHING_APPLY", 0, "缓存迭代计算", "com.code.std.function.method.caching.CachingApply"), + + DATE_WINDOW_EXPAND("DATE_WINDOW_EXPAND", 0, "时间戳函数", "com.code.std.function.method.reduce.DateWindowExpandFunc"), + MERGE_VALUE("MERGE_VALUE", 0, "合并数据", "com.code.std.function.method.reduce.MergeValFunc"), + + REDUCE_MAP("REDUCE_MAP", 0, "REDUCE_MAP函数", "com.code.std.function.method.reduce.ReduceMapFunc"), + + FREQ_STA("FREQ_STA", 0, "今日频率统计与之前N天频率比较", "com.code.std.function.method.biz.FreqStaFunc"); + + String code; + String name; + int dataform; + String clazz; + + FuncEnum(String code, int dataform, String name, String clazz) { + this.code = code; + this.dataform = dataform; + this.name = name; + this.clazz = clazz; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getClazz() { + return clazz; + } + + public void setClazz(String clazz) { + this.clazz = clazz; + } + + public int getDataform() { + return dataform; + } + + public void setDataform(int dataform) { + this.dataform = dataform; + } + + + static Set funcSet = new HashSet(FuncEnum.values().length); + + public static Set funcSet() { + if (funcSet.size() > 0) { + return funcSet; + } + for (FuncEnum func : FuncEnum.values()) { + funcSet.add(func.getCode()); + } + return funcSet; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/IExpression.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IExpression.java new file mode 100644 index 0000000..19c1316 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IExpression.java @@ -0,0 +1,14 @@ +package org.code.modules.plugins.function; + +/** + * 表达式接口 + * @author chenzm + */ +public interface IExpression { + /** + * 执行表达式 + * @param context + * @return + */ + public IParam execExpression(IExpressionContext context); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/IExpressionContext.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IExpressionContext.java new file mode 100644 index 0000000..c7a0a76 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IExpressionContext.java @@ -0,0 +1,17 @@ +package org.code.modules.plugins.function; + +import java.util.Set; + +/** + * 表达式上下文 + * @author chenzm + */ +public interface IExpressionContext { + public Object getExpressionData(String key); + + public void setExpressionData(String key, Object obj); + + public void clear(); + + public Set keySet(); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/IExpressionParse.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IExpressionParse.java new file mode 100644 index 0000000..3695e2e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IExpressionParse.java @@ -0,0 +1,10 @@ +package org.code.modules.plugins.function; + +public interface IExpressionParse { + /** + * 解析表达式 + * @param expression + * @return + */ + public IExpression parseExpression(String expression); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/IFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IFunc.java new file mode 100644 index 0000000..1ea16ec --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IFunc.java @@ -0,0 +1,14 @@ +package org.code.modules.plugins.function; + +/** + * 函数 + * @author chenzm + */ +public interface IFunc { + /** + * 公式 + * @param args + * @return + */ + public IParam fx(IParam... args); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/IIteratorWrap.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IIteratorWrap.java new file mode 100644 index 0000000..3301e83 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IIteratorWrap.java @@ -0,0 +1,9 @@ +package org.code.modules.plugins.function; + +import java.util.Iterator; + +public interface IIteratorWrap extends Iterator { + public void reset(); + + public void finish(); +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/IParam.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IParam.java new file mode 100644 index 0000000..819d322 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/IParam.java @@ -0,0 +1,22 @@ +package org.code.modules.plugins.function; + + +/** + * 参数接口 + * @author chenzm + */ +public interface IParam{ + public void setVal(Object val); + + /*public Object getVal(String paramName);*/ + + public Object getVal(); + + public String getParamName(); + + public Class getValType(); + + public int getPrecision(); + + public int getLength(); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncBean.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncBean.java new file mode 100644 index 0000000..3bcaca5 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncBean.java @@ -0,0 +1,56 @@ +package org.code.modules.plugins.function.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 函数注解 + * Created by chenzm on 2016/12/27. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface FuncBean { + /** + * 函数英文名 + * @return + */ + String code(); + + /** + * 函数中文名 + * @return + */ + String name() default ""; + + /** + * 函数描述 + * @return + */ + String memo() ; + + /** + * 函数类全路径 + * @return + */ + String clazz() default ""; + + /** + * 分类目录 + * @return + */ + String classifyDir(); + + /** + * 函数类型 + * @return + */ + FuncTypeEnum funcType(); + + /** + * 函数例子 + * @return + */ + FuncExample[] examples() default {}; +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncExample.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncExample.java new file mode 100644 index 0000000..5c29dc8 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncExample.java @@ -0,0 +1,24 @@ +package org.code.modules.plugins.function.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 函数例子 + * Created by chenzm on 2017/11/24. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface FuncExample { + String code() default ""; + + String name() default ""; + + String memo(); + + String input() default ""; + + String result() default ""; +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncMethod.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncMethod.java new file mode 100644 index 0000000..283d614 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncMethod.java @@ -0,0 +1,25 @@ +package org.code.modules.plugins.function.annotation; + + +import org.code.modules.plugins.types.TypeEnum; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 函数方法 + * Created by chenzm on 2017/11/24. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface FuncMethod { + String code() default ""; + + String name() default ""; + + FuncParam outputParam() default @FuncParam(name = "返回值为VOID方法", valType = TypeEnum.String); + + FuncParam[] inputParams() default {}; +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncParam.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncParam.java new file mode 100644 index 0000000..7cb6ba0 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncParam.java @@ -0,0 +1,65 @@ +package org.code.modules.plugins.function.annotation; + + +import org.code.modules.plugins.types.TypeEnum; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 函数参数注解 + * Created by chenzm on 2016/12/27. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +public @interface FuncParam { + /** + * 参数英文名 + * @return + */ + String code() default ""; + + /** + * 参数中文名 + * @return + */ + String name(); + + /** + * 值类型 + * @return + */ + TypeEnum valType() default TypeEnum.String; + + /** + * 值精度 + * @return + */ + int precision() default 0; + + /** + * 值长度 + * @return + */ + int length() default 0; + + /** + * 默认值 + * @return + */ + String defVal() default ""; + + /** + * 是否是Any + * @return + */ + boolean isAny() default false; + + /** + * 是否不为空 + * @return + */ + boolean isNotNull() default false; +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncTypeEnum.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncTypeEnum.java new file mode 100644 index 0000000..78ccc3f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/annotation/FuncTypeEnum.java @@ -0,0 +1,49 @@ +package org.code.modules.plugins.function.annotation; + +/** + * 函数类型枚举 + * Created by chenzm on 2017/11/23. + */ +public enum FuncTypeEnum { + NORMAL("NORMAL", "普通函数", "每次函数执行都返回数据"), + + AGGREGATION("AGGREGATION", "聚合函数", "按key汇集统计数据的结果"), + + FLAT_MAP("FLAT_MAP", "FLAT MAP函数", "FLAT MAP函数"); + + private String code; + + private String name; + + private String memo; + + FuncTypeEnum(String code, String name, String memo) { + this.code = code; + this.name = name; + this.memo = memo; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMemo() { + return memo; + } + + public void setMemo(String memo) { + this.memo = memo; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/CachingTransException.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/CachingTransException.java new file mode 100644 index 0000000..22c6d74 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/CachingTransException.java @@ -0,0 +1,25 @@ +package org.code.modules.plugins.function.cache; + +/** + * Created by liwei on 2017/9/25. + */ +public class CachingTransException extends RuntimeException{ + public CachingTransException() { + } + + public CachingTransException(String message) { + super(message); + } + + public CachingTransException(String message, Throwable cause) { + super(message, cause); + } + + public CachingTransException(Throwable cause) { + super(cause); + } + + public CachingTransException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/FreqSeriesRolling.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/FreqSeriesRolling.java new file mode 100644 index 0000000..ff8050e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/FreqSeriesRolling.java @@ -0,0 +1,112 @@ +package org.code.modules.plugins.function.cache; + + + +import com.luqj.util.Validator; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by liwei on 2017/9/19. + */ + + +public class FreqSeriesRolling implements IRollingCaching{ + + private int windowsSize; + + private IListCaching caching; + + private IRollingDataFormat dataFormat; + + public FreqSeriesRolling(int windowsSize){ + this.windowsSize = windowsSize; + } + + + public APPLY_VAL rollingAfter(String key,VAL val, IRollingApply apply, boolean fullApply) throws CachingTransException{ + ICacheContainer.ICachingTransaction trans = null; + try{ + APPLY_VAL applyVal = null; + trans = caching.createTrans(); + trans.begin(key); + List queues = caching.getVal(new IListCaching.ListCacheKey(key),trans); + if(!fullApply || (fullApply && !Validator.ltLength(queues,windowsSize))){ + Map v = new LinkedHashMap<>(); + int i = 0; + for (String vk : queues){ + v.put(dataFormat.toVal(vk),dataFormat.toIDX(i)); + i++; + } + applyVal = apply.apply(key,v); + } + if(queues.size() >= windowsSize){ + caching.delFirst(key,false,trans); + } + List v = new ArrayList<>(); + v.add(dataFormat.fromVal(val)); + caching.set(new IListCaching.ListCacheKey(key, IListCaching.ListCacheKey.ListCacheKeyType.RIGHT),v,trans); + trans.commit(); + return applyVal; + }finally { + trans.end(); + } + + } + + public APPLY_VAL rollingBefore(String key, VAL val, IRollingApply apply, boolean fullApply) throws CachingTransException{ + ICacheContainer.ICachingTransaction trans = null; + try{ + APPLY_VAL applyVal = null; + trans = caching.createTrans(); + trans.begin(key); + List queues = caching.getVal(new IListCaching.ListCacheKey(key),trans); + + if(!fullApply || (fullApply && !Validator.ltLength(queues,windowsSize))){ + + queues.remove(0); + + queues.add(dataFormat.fromVal(val)); + + Map v = new LinkedHashMap<>(); + int i = 0; + for (String vk : queues){ + v.put(dataFormat.toVal(vk),dataFormat.toIDX(i)); + i++; + } + applyVal = apply.apply(key,v); + } + + if(queues.size() >= windowsSize){ + caching.delFirst(key,false); + } + List v = new ArrayList<>(); + v.add(dataFormat.fromVal(val)); + caching.set(new IListCaching.ListCacheKey(key),v); + trans.commit(); + return applyVal; + }finally { + trans.end(); + } + } + + public IListCaching getCaching() { + return caching; + } + + public void setCaching(IListCaching caching) { + this.caching = caching; + } + + public IRollingDataFormat getDataFormat() { + return dataFormat; + } + + public void setDataFormat(IRollingDataFormat dataFormat) { + this.dataFormat = dataFormat; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/ICacheContainer.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/ICacheContainer.java new file mode 100644 index 0000000..e7d941b --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/ICacheContainer.java @@ -0,0 +1,69 @@ +package org.code.modules.plugins.function.cache; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; + +/** + * Created by liwei on 2017/9/11. + */ +public interface ICacheContainer { + + void init(); + + void setCache(CONN cnn, KEY key, VAL val) throws Throwable; + + void delCache(CONN cnn, KEY s) throws Throwable; + + VAL getCache(CONN cnn, KEY key) throws Throwable; + + long incrBy(CONN cnn, KEY key, long v)throws Throwable; + + Set getAllKey(CONN cnn)throws Throwable; + + Map getBatchCache(CONN cnn, Collection key) throws Throwable; + + void batchSet(CONN cnn, Map val); + + ICachingTransaction createTrans(boolean hasTrans); + + + boolean isEmpty(VAL val); + + + void flushDB(); + + void close(); + + + static enum EnumConnType{ + KEEP_ALIVE, + SHORT_CONN + } + + + static interface ICachingTransaction{ + void begin(KEY key); + boolean commit(); + void end(); + boolean hasLock(); + + } + + + static interface ICacheContainerConnController{ + + void init(Map values); + + CONN getConn(); + + void release(CONN conn); + + void destroy(); + + } + + EnumConnType getConnType(); + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/ICaching.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/ICaching.java new file mode 100644 index 0000000..9b51c61 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/ICaching.java @@ -0,0 +1,51 @@ +package org.code.modules.plugins.function.cache; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; + +/** + * Created by liwei on 2017/9/11. + */ +public interface ICaching{ + + String info(); + + void init(); + + boolean isLazyLoading(); + + VAL getVal(KEY key); + + Set getAllKey(); + + VAL getVal(KEY key, ICacheContainer.ICachingTransaction trans); + + Map getBatchVal(Collection key); + + Map getBatchVal(Collection val, ICacheContainer.ICachingTransaction trans); + + void set(KEY key, VAL val); + + void set(KEY key, VAL val, ICacheContainer.ICachingTransaction trans); + + void del(KEY key); + + void del(KEY key, ICacheContainer.ICachingTransaction trans); + + void delCacheOnly(KEY key); + + void delCacheOnly(KEY key, ICacheContainer.ICachingTransaction trans); + + void batchSet(Map val, Object... obj); + + Map getParams(); + + void setParams(Map params); + + void close(); + + public ICacheContainer.ICachingTransaction createTrans(); + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/IListCaching.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/IListCaching.java new file mode 100644 index 0000000..50d9480 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/IListCaching.java @@ -0,0 +1,108 @@ +package org.code.modules.plugins.function.cache; + + +import com.luqj.util.assertion.Assert; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by liwei on 2017/9/13. + */ +public interface IListCaching extends ICaching> { + + void delFirst(String key, boolean delDB); + + void delFirst(String key, boolean delDB, ICacheContainer.ICachingTransaction trans); + + void delLast(String key, boolean delDB); + + void delLast(String key, boolean delDB, ICacheContainer.ICachingTransaction trans); + + + public static class ListCacheKey{ + + private String key; + + private int count; + + //通过值操作数据时使用该字段 + private List fields = new ArrayList<>(); + + private ListCacheKeyType type = ListCacheKeyType.ALL; + + + public ListCacheKey(String key) { + Assert.notNull(key,"key不允许为空!"); + this.key = key; + this.count = count; + for (String field : fields){ + this.fields.add(field); + } + } + public ListCacheKey(String key,ListCacheKeyType type) { + Assert.notNull(key,"key不允许为空!"); + this.key = key; + this.type = type; + this.count = count; + for (String field : fields){ + this.fields.add(field); + } + } + + + @Override + public String toString() { + return key; + } + + public ListCacheKey(String key, ListCacheKeyType type, int count, String...fields) { + Assert.notNull(key,"key不允许为空!"); + this.key = key; + this.type = type; + this.count = count; + for (String field : fields){ + this.fields.add(field); + } + } + + + + public int getCount() { + return count; + } + + public ListCacheKeyType getType() { + return type; + } + + public void setType(ListCacheKeyType type) { + this.type = type; + } + + public boolean existFields(String field){ + return fields.contains(field); + } + + public boolean hasFiled(){ + return fields.size() > 0; + } + + public String getKey() { + return key; + } + + public List getFields() { + return fields; + } + + + + public static enum ListCacheKeyType{ + ALL, + RIGHT, + LEFT, + } + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/IRollingCaching.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/IRollingCaching.java new file mode 100644 index 0000000..c253518 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/cache/IRollingCaching.java @@ -0,0 +1,30 @@ +package org.code.modules.plugins.function.cache; + +import java.util.Map; + +/** + * Created by liwei on 2017/9/13. + */ +public interface IRollingCaching{ + + + + + static interface IRollingApply{ + + APPLY_VAL apply(String key, Map val); + + } + + + static interface IRollingDataFormat{ + + String fromVal(VAL val); + + VAL toVal(String val); + + double fromIdx(IDX idx); + + IDX toIDX(double idx); + }; +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/AbstractFormulaExpression.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/AbstractFormulaExpression.java new file mode 100644 index 0000000..f39384e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/AbstractFormulaExpression.java @@ -0,0 +1,65 @@ +package org.code.modules.plugins.function.expression; + +import org.code.modules.plugins.function.IExpression; +import org.code.modules.plugins.function.IExpressionContext; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.apache.commons.lang.StringUtils; + +import java.util.Arrays; + +/** + * 抽象函数表达式 (函数加参数才能具体表达某一件事情) + * @author chenzm + */ +public abstract class AbstractFormulaExpression implements IExpression { + protected IFunc func; + + protected IParam[] args = null; + + public AbstractFormulaExpression(IFunc f, IParam ...args) { + this.func = f; + this.args = args; + } + + public static FormulaExpression createFuncExpression(Class clazz, IParam ...args) { + try { + return new FormulaExpression(clazz.newInstance(), args); + } catch (Exception e) { + throw new IllegalStateException("创建函数表达式失败", e); + } + } + + @Override + public IParam execExpression(IExpressionContext context) { + for(IParam value : this.args) { + //有参数名称就会去表达式上下文取值然后设置到参数对象里面-字段参数 + if(StringUtils.isNotBlank(value.getParamName())) { + value.setVal(context.getExpressionData(value.getParamName())); + } + } + return this.func.fx(args); + } + + public abstract void addParam(IParam value); + + protected IParam[] grow(IParam[] buf, int newCapacity) { + return Arrays.copyOf(buf, newCapacity); + } + + public IFunc getFunc() { + return func; + } + + public void setFunc(IFunc func) { + this.func = func; + } + + public IParam[] getArgs() { + return args; + } + + public void setArgs(IParam[] args) { + this.args = args; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/CombinationExpression.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/CombinationExpression.java new file mode 100644 index 0000000..fadbef0 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/CombinationExpression.java @@ -0,0 +1,99 @@ +package org.code.modules.plugins.function.expression; + +import org.code.modules.plugins.function.IExpression; +import org.code.modules.plugins.function.IExpressionContext; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTryCatchFunc; +import com.luqj.util.assertion.Assert; +import com.luqj.util.log.LogUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * 组合表达式(组合模式) + * + * @author chenzm + */ +public class CombinationExpression extends AbstractFormulaExpression implements IExpression { + + protected List exps = new ArrayList(); + + private List buf = new ArrayList(); + + //位置信息格式:参数的起始位置 + private int[] expPosInfo = new int[0]; + + public CombinationExpression(IFunc f, IParam... args) { + super(f, args); + } + + @Override + public IParam execExpression(IExpressionContext context) { + try { + if (super.args.length == 0) { + List argList = new ArrayList(); + int pos = 0; + for (Object obj : buf) { + if (obj instanceof IParam) { + argList.add((IParam) obj); + } else { + this.expPosInfo = Arrays.copyOf(this.expPosInfo, this.expPosInfo.length + 1); + this.expPosInfo[exps.size()] = pos; + exps.add((IExpression) obj); + argList.add(((IExpression) obj).execExpression(context)); + } + pos++; + } + super.args = argList.toArray(new IParam[argList.size()]); + } else { + int pos = 0; + for (IExpression exp : exps) { + super.args[expPosInfo[pos]] = exp.execExpression(context); + pos++; + } + } + } catch (Throwable e) { + if (!isTryCatch()) { + throw e; + } + + IParam errorParam = AbstractTryCatchFunc.createExceptionParam( + LogUtil.exceptionMsg(String.format("%s执行错误", this.func.getClass().getName()), e) + ); + Assert.logic(buf.size() > 0, String.format("异常消息处理类[%s]参数至少要有一个", this.func.getClass().getName())); + + IParam[] errorParams = null; + if (buf.size() == 1) { + errorParams = new IParam[]{errorParam}; + } else { + Object errorHandler = buf.get(1); + if (buf.get(1) instanceof IParam) + errorParams = new IParam[]{errorParam, (IParam) errorHandler}; + else + errorParams = new IParam[]{errorParam, ((IExpression) errorHandler).execExpression(context)}; + } + return super.func.fx(errorParams); + } + return super.execExpression(context); + } + + private boolean isTryCatch() { + return AbstractTryCatchFunc.class.isAssignableFrom(this.func.getClass()); + } + + @Override + public void addParam(IParam value) { + this.buf.add(value); + } + + public void addExpression(IExpression expression) { + this.buf.add(expression); + } + + public void addParamOrExp(Object obj) { + this.buf.add(obj); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/DefaultExpressionContext.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/DefaultExpressionContext.java new file mode 100644 index 0000000..b429664 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/DefaultExpressionContext.java @@ -0,0 +1,43 @@ +package org.code.modules.plugins.function.expression; + +import org.code.modules.plugins.function.IExpressionContext; +import net.sf.json.JSONObject; +import org.apache.commons.lang.StringUtils; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * 默认的表达式上下文 + * @author chenzm + */ +public class DefaultExpressionContext implements IExpressionContext{ + + private Map data = new HashMap(); + + @Override + public Object getExpressionData(String key) { + return this.data.get(StringUtils.upperCase(key)); + } + + @Override + public void setExpressionData(String key, Object val) { + this.data.put(StringUtils.upperCase(key), val); + } + + @Override + public void clear() { + data.clear(); + } + + @Override + public Set keySet() { + return data.keySet(); + } + + @Override + public String toString() { + return JSONObject.fromObject(data).toString(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/FormulaExpression.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/FormulaExpression.java new file mode 100644 index 0000000..1d28407 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/expression/FormulaExpression.java @@ -0,0 +1,28 @@ +package org.code.modules.plugins.function.expression; + +import org.code.modules.plugins.function.IExpression; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; + +/** + * 基础的算式表达式 + * @author chenzm + */ +public class FormulaExpression extends AbstractFormulaExpression implements IExpression { + + public FormulaExpression(IFunc f, IParam ...args) { + super(f, args); + } + + @Override + public void addParam(IParam value) { + if(this.args == null) { + this.args = new IParam[1]; + this.args[0] = value; + }else { + int len = this.args.length; + this.args = grow(this.args, len + 1); + this.args[len] = value; + } + } +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractFunc.java new file mode 100644 index 0000000..7371c01 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractFunc.java @@ -0,0 +1,87 @@ +package org.code.modules.plugins.function.method; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +/** + * 抽象公式函数 + * @author chenzm + */ +public abstract class AbstractFunc implements IFunc { + + protected boolean isReset = true; + + @Override + public IParam fx(IParam... args) { + if(args.length == 0) { + return getDefVal(); + } + return _fx(args); + } + + + + /** + * 默认返回值 + * @return + */ + protected abstract IParam getDefVal(); + + /** + * 公式 + * @param args + * @return + */ + public abstract IParam _fx(IParam[] args); + + /** + * 是否重置 + * @return + */ + public boolean isReset() { + return this.isReset; + } + + /** + * 关闭重置 + */ + public void disableReset() { + this.isReset = false; + } + + /** + * 开启重置 + */ + public void enableReset() { + this.isReset = true; + } + + /** + * 获取兼容性最高的类型 + * @param args + * @return + */ + protected StandTypeParam initStandTypeParam(IParam ...args) { + TypeEnum type = null; + for(int i = 0; i < args.length; i++) { + if(args[i].getValType() == null) { + continue; + } + + if(type == null) { + type = TypeEnum.valueOf(args[i].getValType().getSimpleName()); + }else { + TypeEnum t = TypeEnum.valueOf(args[i].getValType().getSimpleName()); + if(t.getPriority() > type.getPriority()) { + type = t; + } + } + } + + if(type == null) return null; + + return StandTypeParam.createParamByType(type); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractLogicalFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractLogicalFunc.java new file mode 100644 index 0000000..97f1b20 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractLogicalFunc.java @@ -0,0 +1,31 @@ +package org.code.modules.plugins.function.method; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 抽象逻辑函数模板 + * @author chenzm + */ +public abstract class AbstractLogicalFunc extends AbstractFunc implements IFunc{ + + private static final IParam _true = StandTypeParam.createConstantParam(true); + + private static final IParam _false = StandTypeParam.createConstantParam(false); + + protected StandTypeParam result = null; + + @Override + protected IParam getDefVal() { + return _true; + } + + protected IParam _true() { + return _true; + } + + protected IParam _false() { + return _false; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractMathFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractMathFunc.java new file mode 100644 index 0000000..a73d4a8 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractMathFunc.java @@ -0,0 +1,192 @@ +package org.code.modules.plugins.function.method; + +import com.luqj.util.ArithmeticEnum; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +/** + * 抽象数学公式函数模板 + * @author chenzm + */ +public abstract class AbstractMathFunc extends AbstractFunc implements IFunc { + + private static final IParam zero = StandTypeParam.createConstantParam(0); + + @Override + protected IParam getDefVal() { + return zero; + } + + protected void formulaOp(ArithmeticEnum op, IParam arg0, IParam arg1, StandTypeParam result) { + switch(op) { + case addition: + switch(result.getTypeEnum()) { + case Short: + result.setVal(ParamFormat.format(arg0).shortValue() + ParamFormat.format(arg1).shortValue()); + break; + case Integer: + result.setVal(ParamFormat.format(arg0).intValue() + ParamFormat.format(arg1).intValue()); + break; + case Long: + result.setVal(ParamFormat.format(arg0).longValue() + ParamFormat.format(arg1).longValue()); + break; + case Float: + result.setVal(ParamFormat.format(arg0).floatValue() + ParamFormat.format(arg1).floatValue()); + break; + default: + result.setVal(ParamFormat.format(arg0).doubleValue() + ParamFormat.format(arg1).doubleValue()); + } + break; + + case subtract: + switch(result.getTypeEnum()) { + case Short: + result.setVal(ParamFormat.format(arg0).shortValue() - ParamFormat.format(arg1).shortValue()); + break; + case Integer: + result.setVal(ParamFormat.format(arg0).intValue() - ParamFormat.format(arg1).intValue()); + break; + case Long: + result.setVal(ParamFormat.format(arg0).longValue() - ParamFormat.format(arg1).longValue()); + break; + case Float: + result.setVal(ParamFormat.format(arg0).floatValue() - ParamFormat.format(arg1).floatValue()); + break; + default: + result.setVal(ParamFormat.format(arg0).doubleValue() - ParamFormat.format(arg1).doubleValue()); + } + break; + + case multiply: + switch(result.getTypeEnum()) { + case Short: + result.setVal(ParamFormat.format(arg0).shortValue() * ParamFormat.format(arg1).shortValue()); + break; + case Integer: + result.setVal(ParamFormat.format(arg0).intValue() * ParamFormat.format(arg1).intValue()); + break; + case Long: + result.setVal(ParamFormat.format(arg0).longValue() * ParamFormat.format(arg1).longValue()); + break; + case Float: + result.setVal(ParamFormat.format(arg0).floatValue() * ParamFormat.format(arg1).floatValue()); + break; + default: + result.setVal(ParamFormat.format(arg0).doubleValue() * ParamFormat.format(arg1).doubleValue()); + } + break; + + case division: + switch(result.getTypeEnum()) { + case Short: + result.setVal(ParamFormat.format(arg0).shortValue() / ParamFormat.format(arg1).shortValue()); + break; + case Integer: + result.setVal(ParamFormat.format(arg0).intValue() / ParamFormat.format(arg1).intValue()); + break; + case Long: + result.setVal(ParamFormat.format(arg0).longValue() / ParamFormat.format(arg1).longValue()); + break; + case Float: + result.setVal(ParamFormat.format(arg0).floatValue() / ParamFormat.format(arg1).floatValue()); + break; + default: + result.setVal(ParamFormat.format(arg0).doubleValue() / ParamFormat.format(arg1).doubleValue()); + } + break; + + case lt: + switch(result.getTypeEnum()) { + case Short: + result.setVal(ParamFormat.format(arg0).shortValue() < ParamFormat.format(arg1).shortValue() ? 1 : 0); + break; + case Integer: + result.setVal(ParamFormat.format(arg0).intValue() < ParamFormat.format(arg1).intValue() ? 1 : 0); + break; + case Long: + result.setVal(ParamFormat.format(arg0).longValue() < ParamFormat.format(arg1).longValue() ? 1 : 0); + break; + case Float: + result.setVal(ParamFormat.format(arg0).floatValue() < ParamFormat.format(arg1).floatValue() ? 1 : 0); + break; + case String: + result.setVal(ComparatorFactory.getInstance().getComparator(String.class, TypeEnum.String).compare(ParamFormat.obj2Str(arg0), ParamFormat.obj2Str(arg1)) < 0 ? 1 : 0); + break; + default: + result.setVal(ParamFormat.format(arg0).doubleValue() < ParamFormat.format(arg1).doubleValue() ? 1 : 0); + } + break; + + case lte: + switch(result.getTypeEnum()) { + case Short: + result.setVal(ParamFormat.format(arg0).shortValue() <= ParamFormat.format(arg1).shortValue() ? 1 : 0); + break; + case Integer: + result.setVal(ParamFormat.format(arg0).intValue() <= ParamFormat.format(arg1).intValue() ? 1 : 0); + break; + case Long: + result.setVal(ParamFormat.format(arg0).longValue() <= ParamFormat.format(arg1).longValue() ? 1 : 0); + break; + case Float: + result.setVal(ParamFormat.format(arg0).floatValue() <= ParamFormat.format(arg1).floatValue() ? 1 : 0); + break; + case String: + result.setVal(ComparatorFactory.getInstance().getComparator(String.class, TypeEnum.String).compare(ParamFormat.obj2Str(arg0), ParamFormat.obj2Str(arg1)) <= 0 ? 1 : 0); + break; + default: + result.setVal(ParamFormat.format(arg0).doubleValue() <= ParamFormat.format(arg1).doubleValue() ? 1 : 0); + } + break; + + case gt: + switch(result.getTypeEnum()) { + case Short: + result.setVal(ParamFormat.format(arg0).shortValue() > ParamFormat.format(arg1).shortValue() ? 1 : 0); + break; + case Integer: + result.setVal(ParamFormat.format(arg0).intValue() > ParamFormat.format(arg1).intValue() ? 1 : 0); + break; + case Long: + result.setVal(ParamFormat.format(arg0).longValue() > ParamFormat.format(arg1).longValue() ? 1 : 0); + break; + case Float: + result.setVal(ParamFormat.format(arg0).floatValue() > ParamFormat.format(arg1).floatValue() ? 1 : 0); + break; + case String: + result.setVal(ComparatorFactory.getInstance().getComparator(String.class, TypeEnum.String).compare(ParamFormat.obj2Str(arg0), ParamFormat.obj2Str(arg1)) > 0 ? 1 : 0); + break; + default: + result.setVal(ParamFormat.format(arg0).doubleValue() > ParamFormat.format(arg1).doubleValue() ? 1 : 0); + } + break; + + case gte: + switch(result.getTypeEnum()) { + case Short: + result.setVal(ParamFormat.format(arg0).shortValue() >= ParamFormat.format(arg1).shortValue() ? 1 : 0); + break; + case Integer: + result.setVal(ParamFormat.format(arg0).intValue() >= ParamFormat.format(arg1).intValue() ? 1 : 0); + break; + case Long: + result.setVal(ParamFormat.format(arg0).longValue() >= ParamFormat.format(arg1).longValue() ? 1 : 0); + break; + case Float: + result.setVal(ParamFormat.format(arg0).floatValue() >= ParamFormat.format(arg1).floatValue() ? 1 : 0); + break; + case String: + result.setVal(ComparatorFactory.getInstance().getComparator(String.class, TypeEnum.String).compare(ParamFormat.obj2Str(arg0), ParamFormat.obj2Str(arg1)) >= 0 ? 1 : 0); + break; + default: + result.setVal(ParamFormat.format(arg0).doubleValue() >= ParamFormat.format(arg1).doubleValue() ? 1 : 0); + } + break; + default: + throw new IllegalArgumentException("暂不支持运算符号:" + op.getSymbol()); + } + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractTextFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractTextFunc.java new file mode 100644 index 0000000..93a3072 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractTextFunc.java @@ -0,0 +1,15 @@ +package org.code.modules.plugins.function.method; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.StandTypeParam; + +public abstract class AbstractTextFunc extends AbstractFunc implements IFunc{ + + protected static final IParam _nullChr = StandTypeParam.createConstantParam(""); + + @Override + protected IParam getDefVal() { + return _nullChr; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractTryCatchFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractTryCatchFunc.java new file mode 100644 index 0000000..6a1eb40 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/AbstractTryCatchFunc.java @@ -0,0 +1,32 @@ +package org.code.modules.plugins.function.method; + +import com.luqj.util.StringUtils; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.StringType; + +public abstract class AbstractTryCatchFunc implements IFunc { + public static final String EXCEPTION_MESSAGE = "$DRAGON_EXCEPTION_MESSAGE"; + + public static IParam createExceptionParam(String errorMsg) { + StandTypeParam errorParam = StandTypeParam.createFieldParam(EXCEPTION_MESSAGE, StringType.BASE); + errorParam.setVal(errorMsg); + return errorParam; + } + + /** + * 是否发生错误 + * + * @param param + * @return + */ + protected boolean isError(IParam param) { + if (param != null + && StringUtils.isNotBlank(param.getParamName()) + && param.getParamName().equals(EXCEPTION_MESSAGE)) { + return true; + } + return false; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/BagFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/BagFunc.java new file mode 100644 index 0000000..746d707 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/BagFunc.java @@ -0,0 +1,17 @@ +package org.code.modules.plugins.function.method; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; + +/** + * 包函数 eg (3) = 3,(6) = 6 + * Created by chenzm on 2017/2/18. + */ +public class BagFunc implements IFunc{ + @Override + public IParam fx(IParam... args) { + if(args.length == 0) + return null; + return args[0]; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/ComparatorFactory.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/ComparatorFactory.java new file mode 100644 index 0000000..806e46b --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/ComparatorFactory.java @@ -0,0 +1,106 @@ +package org.code.modules.plugins.function.method; + +import org.code.modules.plugins.types.TypeEnum; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; + +public class ComparatorFactory { + private static ComparatorFactory factory = null; + + private Map> comparatorMap; + + public ComparatorFactory() { + comparatorMap = new HashMap>(); + comparatorMap.put(TypeEnum.Short, new Comparator(){ + @Override + public int compare(Short o1, Short o2) { + return o1.compareTo(o2); + } + }); + comparatorMap.put(TypeEnum.Integer, new Comparator(){ + @Override + public int compare(Integer o1, Integer o2) { + return o1.compareTo(o2); + } + }); + comparatorMap.put(TypeEnum.Long, new Comparator(){ + @Override + public int compare(Long o1, Long o2) { + return o1.compareTo(o2); + } + }); + comparatorMap.put(TypeEnum.Float, new Comparator(){ + @Override + public int compare(Float o1, Float o2) { + return o1.compareTo(o2); + } + }); + comparatorMap.put(TypeEnum.Double, new Comparator(){ + @Override + public int compare(Double o1, Double o2) { + return o1.compareTo(o2); + } + }); + comparatorMap.put(TypeEnum.BigInteger, new Comparator(){ + @Override + public int compare(BigInteger o1, BigInteger o2) { + return o1.compareTo(o2); + } + }); + comparatorMap.put(TypeEnum.BigDecimal, new Comparator(){ + @Override + public int compare(BigDecimal o1, BigDecimal o2) { + return o1.compareTo(o2); + } + }); + comparatorMap.put(TypeEnum.Boolean, new Comparator(){ + @Override + public int compare(Boolean o1, Boolean o2) { + return o1.compareTo(o2); + } + }); + comparatorMap.put(TypeEnum.String, new Comparator(){ + @Override + public int compare(String o1, String o2) { + return o1.compareTo(o2); + } + }); + comparatorMap.put(TypeEnum.Date, new Comparator(){ + @Override + public int compare(Object o1, Object o2) { + if(o1 instanceof java.sql.Date) { + return ((java.sql.Date)o1).compareTo((java.sql.Date)o2); + } + return ((java.util.Date)o1).compareTo((java.util.Date)o2); + } + }); + } + + public static ComparatorFactory getInstance() { + if(factory == null) { + synchronized (ComparatorFactory.class) { + if(factory == null) + factory = new ComparatorFactory(); + } + } + return factory; + } + + public Comparator getComparator(TypeEnum type) { + if(!this.comparatorMap.containsKey(type)) { + throw new IllegalArgumentException("没有找到" +type.toString() + "类型的比较器"); + } + return this.comparatorMap.get(type); + } + + public Comparator getComparator(Class clazz, TypeEnum type) { + if(!this.comparatorMap.containsKey(type)) { + throw new IllegalArgumentException("没有找到" +type.toString() + "类型的比较器"); + } + return (Comparator)this.comparatorMap.get(type); + } +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/AbstractDateFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/AbstractDateFunc.java new file mode 100644 index 0000000..4023b6c --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/AbstractDateFunc.java @@ -0,0 +1,14 @@ +package org.code.modules.plugins.function.method.datetime; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; + +public abstract class AbstractDateFunc implements IFunc{ + + @Override + public IParam fx(IParam... args) { + return format(args); + } + + public abstract IParam format(IParam[] args); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/MilliSeconds.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/MilliSeconds.java new file mode 100644 index 0000000..6d9203f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/MilliSeconds.java @@ -0,0 +1,46 @@ +package org.code.modules.plugins.function.method.datetime; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; +import com.luqj.util.assertion.Assert; + +import java.util.Calendar; + +/** + * 毫秒数 + * Created by chenzm on 2017/9/18. + */ +public class MilliSeconds extends AbstractDateFunc implements IFunc { + private Calendar calendar = null; + + private StandTypeParam sysMillis = StandTypeParam.createParamByType(TypeEnum.Long); + + @Override + public IParam format(IParam[] args) { + Assert.logic(args.length == 2, "参数长度不匹配"); + if (calendar == null) { + calendar = Calendar.getInstance(); + } + calendar.setTimeInMillis(System.currentTimeMillis()); + + int val = ParamFormat.format(args[0]).intValue(); + String unit = ParamFormat.obj2Str(args[1]); + Assert.hasText(unit, "单位不能为空"); + unit = unit.toUpperCase(); + + if ("YEAR".equals(unit)) { + calendar.add(Calendar.YEAR, val); + } else if ("MONTH".equals(unit)) { + calendar.add(Calendar.MONTH, val); + } else if ("DAY_OF_YEAR".equals(unit)) { + calendar.add(Calendar.DAY_OF_YEAR, val); + } else { + throw new IllegalArgumentException("赞不支持时间单位[" + unit + "]"); + } + sysMillis.setVal(calendar.getTimeInMillis()); + return sysMillis; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/ReverseLongToDateFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/ReverseLongToDateFunc.java new file mode 100644 index 0000000..a1bfa71 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/ReverseLongToDateFunc.java @@ -0,0 +1,59 @@ +package org.code.modules.plugins.function.method.datetime; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +import java.util.Date; + +/** + * 字符串转成时间格式转换函数 + */ +public class ReverseLongToDateFunc extends AbstractDateFunc implements IFunc { + + private StandTypeParam date = StandTypeParam.createParamByType(TypeEnum.Date); + + /** + * 时间类型 + */ + enum DateEnum { + NORMAL_DATE("0"), + SQL_DATE("1"), + SQL_TIMESTAMP("2"), + SQL_TIME("3"); + + private String code; + + public boolean isEq(String code) { + if (this.code.equals(code)) { + return true; + } + return false; + } + + DateEnum(String code) { + this.code = code; + } + } + + @Override + public IParam format(IParam[] args) { + if (ParamFormat.argIsNull(args[0])) { + return null; + } + String dateType = args.length > 1 && !ParamFormat.argIsNull(args[1]) ? ParamFormat.obj2Str(args[1]) : "1"; + Long time=Long.MAX_VALUE-Long.valueOf(args[0].getVal().toString()); + if (DateEnum.SQL_DATE.isEq(dateType)) { + date.setVal(new java.sql.Date(time)); + } else if (DateEnum.NORMAL_DATE.isEq(dateType)) { + date.setVal(new Date(time)); + } else if (DateEnum.SQL_TIMESTAMP.isEq(dateType)) { + date.setVal(new java.sql.Timestamp(time)); + } else if (DateEnum.SQL_TIME.isEq(dateType)) { + date.setVal(new java.sql.Time(time)); + } + return date; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/SysTimeFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/SysTimeFunc.java new file mode 100644 index 0000000..635b93a --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/SysTimeFunc.java @@ -0,0 +1,27 @@ +package org.code.modules.plugins.function.method.datetime; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 系统时间函数 + * Created by chenzm on 2017/9/18. + */ +public class SysTimeFunc extends AbstractDateFunc implements IFunc { + private StandTypeParam param = StandTypeParam.createParamByType(TypeEnum.String); + + @Override + public IParam format(IParam[] args) { + long milliSeconds = ParamFormat.format(args[0]).longValue(); + String outFmt = ParamFormat.obj2Str(args[1]); + SimpleDateFormat sdf = new SimpleDateFormat(outFmt); + param.setVal(sdf.format(new Date(milliSeconds))); + return param; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/ToCharFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/ToCharFunc.java new file mode 100644 index 0000000..9761b37 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/ToCharFunc.java @@ -0,0 +1,47 @@ +package org.code.modules.plugins.function.method.datetime; + +import com.luqj.util.date.DateUtils; +import com.luqj.util.assertion.Assert; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +import java.text.ParseException; + +/** + * 时间格式转成字符串日期 + * Created by chenzm on 2017/3/1. + */ +public class ToCharFunc extends AbstractDateFunc implements IFunc { + private StandTypeParam dateStr = StandTypeParam.createParamByType(TypeEnum.String); + + @Override + public IParam format(IParam[] args) { + if (ParamFormat.argIsNull(args[0])) { + if (args.length > 2) { + return args[2]; + } + dateStr.setVal(null); + return dateStr; + } + if (ParamFormat.isDate(args[0])) { + Assert.logic(!ParamFormat.argIsNull(args[1]), "输出的时间格式必须填写"); + if ("oracle.sql.timestamp".equalsIgnoreCase(args[0].getVal().getClass().getName())) { + java.util.Date dateVal = null; + try { + dateVal = DateUtils.getDate(args[0].getVal().toString(), "yyyy-MM-dd HH:mm:ss"); + } catch (ParseException e) { + throw new IllegalStateException("", e); + } + dateStr.setVal(DateUtils.getDateFormat(dateVal, ParamFormat.obj2Str(args[1]))); + } else { + dateStr.setVal(DateUtils.getDateFormat((java.util.Date) args[0].getVal(), ParamFormat.obj2Str(args[1]))); + } + } else { + dateStr.setVal(args[0].getVal().toString()); + } + return dateStr; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/ToDateFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/ToDateFunc.java new file mode 100644 index 0000000..ca229cf --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/datetime/ToDateFunc.java @@ -0,0 +1,74 @@ +package org.code.modules.plugins.function.method.datetime; + +import com.luqj.util.date.DateUtils; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +import java.text.ParseException; +import java.util.Date; + +/** + * 字符串转成时间格式转换函数 + */ +public class ToDateFunc extends AbstractDateFunc implements IFunc{ + + private StandTypeParam date = StandTypeParam.createParamByType(TypeEnum.Date); + + /** + * 时间类型 + */ + enum DateEnum{ + NORMAL_DATE("0"), + SQL_DATE("1"), + SQL_TIMESTAMP("2") , + SQL_TIME("3"); + + private String code; + + public boolean isEq(String code) { + if(this.code.equals(code)) { + return true; + } + return false; + } + + DateEnum(String code) { + this.code = code; + } + } + + @Override + public IParam format(IParam[] args) { + if(ParamFormat.argIsNull(args[0])){ + date.setVal(null); + return date; + } + if(ParamFormat.argIsNull(args[1])){ + throw new IllegalArgumentException("字符串的时间格式必须填写"); + } + String dateType = args.length > 2 && !ParamFormat.argIsNull(args[2]) ? ParamFormat.obj2Str(args[2]) : "1"; + Date val = null; + try { + val = DateUtils.getDate(ParamFormat.obj2Str(args[0]), ParamFormat.obj2Str(args[1])); + } catch (ParseException e) { + throw new IllegalArgumentException("SQL时间转换异常", e); + } + if(val == null) { + date.setVal(null); + return date; + } + if(DateEnum.SQL_DATE.isEq(dateType)){ + date.setVal(new java.sql.Date(val.getTime())); + } else if(DateEnum.NORMAL_DATE.isEq(dateType)){ + date.setVal(val); + }else if(DateEnum.SQL_TIMESTAMP.isEq(dateType)) { + date.setVal(new java.sql.Timestamp(val.getTime())); + }else if(DateEnum.SQL_TIME.isEq(dateType)){ + date.setVal(new java.sql.Time(val.getTime())); + } + return date; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/exception/TryCatchFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/exception/TryCatchFunc.java new file mode 100644 index 0000000..88bbdc7 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/exception/TryCatchFunc.java @@ -0,0 +1,26 @@ +package org.code.modules.plugins.function.method.exception; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTryCatchFunc; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class TryCatchFunc extends AbstractTryCatchFunc implements IFunc { + + private IParam result = StandTypeParam.createParamByType(TypeEnum.Boolean); + + @Override + public IParam fx(IParam... args) { + boolean isError = isError(args[0]); + if(!isError) { + return args[0]; + } + if(args.length == 1) { + result.setVal(false); + }else { + return args[1]; + } + return result; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/ChooseFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/ChooseFunc.java new file mode 100644 index 0000000..000a765 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/ChooseFunc.java @@ -0,0 +1,25 @@ +package org.code.modules.plugins.function.method.information; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +/** + * 选择函数 + * @author chenzm + */ +public class ChooseFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(ParamFormat.argIsNull(args[0])) { + return null; + } + int index = ParamFormat.format(args[0]).intValue(); + if(index >= args.length || index <= 0 ) { + throw new IllegalStateException("ChooseFunc索引越界 index:" + index + " 参数个数:" + args.length); + } + return args[index]; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/IsBlankFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/IsBlankFunc.java new file mode 100644 index 0000000..fc1a3b6 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/IsBlankFunc.java @@ -0,0 +1,23 @@ +package org.code.modules.plugins.function.method.information; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import com.luqj.util.StringUtils; + +public class IsBlankFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length == 0 ) { + throw new IllegalStateException("IsBlankFunc函数参数只能一个"); + } + if(args[0].getVal() == null ) { + return _true(); + }else if(args[0].getValType() == String.class && + StringUtils.isBlank((String)args[0].getVal())) { + return _true(); + } + return _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/IsNumberFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/IsNumberFunc.java new file mode 100644 index 0000000..b6c834f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/IsNumberFunc.java @@ -0,0 +1,21 @@ +package org.code.modules.plugins.function.method.information; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class IsNumberFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length == 0 ) { + throw new IllegalStateException("IsNumberFunc函数参数只能一个"); + } + + if(args[0].getVal() != null && ParamFormat.isNumber(args[0])) { + return _true(); + } + return _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/IsTextFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/IsTextFunc.java new file mode 100644 index 0000000..5660947 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/information/IsTextFunc.java @@ -0,0 +1,19 @@ +package org.code.modules.plugins.function.method.information; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; + +public class IsTextFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length == 0 ) { + throw new IllegalStateException("IsTextFunc函数参数只能一个"); + } + if(args[0].getVal() != null && args[0].getValType() == String.class) { + return _true(); + } + return _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/AndFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/AndFunc.java new file mode 100644 index 0000000..db91993 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/AndFunc.java @@ -0,0 +1,19 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class AndFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + for(IParam arg : args) { + if(ParamFormat.format(arg).intValue() == 0) { + return _false(); + } + } + return _true(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/EqFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/EqFunc.java new file mode 100644 index 0000000..2179f3a --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/EqFunc.java @@ -0,0 +1,24 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +/** + * @author chenqg + * @date 2018/6/28 19:02 + * @Description: TODO + */ +public class EqFunc extends AbstractLogicalFunc implements IFunc { + @Override + public IParam _fx(IParam[] args) { + if (args.length != 2) { + throw new IllegalArgumentException("EqFunc函数的参数必须是两个"); + } + if (ParamFormat.isEqual(args[0], args[1])) { + return _true(); + } + return _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/GtFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/GtFunc.java new file mode 100644 index 0000000..71337fc --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/GtFunc.java @@ -0,0 +1,20 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class GtFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 2) { + throw new IllegalArgumentException("GtFunc函数的参数必须是两个"); + } + if(ParamFormat.format(args[0]).doubleValue() > ParamFormat.format(args[1]).doubleValue()) { + return _true(); + } + return _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/GteFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/GteFunc.java new file mode 100644 index 0000000..3b8e918 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/GteFunc.java @@ -0,0 +1,20 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class GteFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 2) { + throw new IllegalArgumentException("GteFunc函数的参数必须是两个"); + } + if(ParamFormat.format(args[0]).doubleValue() >= ParamFormat.format(args[1]).doubleValue()) { + return _true(); + } + return _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/IfFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/IfFunc.java new file mode 100644 index 0000000..78f6882 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/IfFunc.java @@ -0,0 +1,20 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class IfFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length <= 1) { + throw new IllegalArgumentException("IfFunc函数的参数必须大于一个"); + } + if(ParamFormat.format(args[0]).intValue() != 0){ + return args[1]; + } + return args[2]; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/LtFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/LtFunc.java new file mode 100644 index 0000000..0d8a538 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/LtFunc.java @@ -0,0 +1,20 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class LtFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 2) { + throw new IllegalArgumentException("LtFunc函数的参数必须是两个"); + } + if(ParamFormat.format(args[0]).doubleValue() < ParamFormat.format(args[1]).doubleValue()) { + return _true(); + } + return _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/LteFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/LteFunc.java new file mode 100644 index 0000000..ff3c2ff --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/LteFunc.java @@ -0,0 +1,20 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class LteFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 2) { + throw new IllegalArgumentException("LteFunc函数的参数必须是两个"); + } + if(ParamFormat.format(args[0]).doubleValue() <= ParamFormat.format(args[1]).doubleValue()) { + return _true(); + } + return _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/MatchFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/MatchFunc.java new file mode 100644 index 0000000..c9cd528 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/MatchFunc.java @@ -0,0 +1,26 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 逻辑匹配函数 + * Created by chenzm on 2017/9/18. + */ +public class MatchFunc extends AbstractLogicalFunc implements IFunc { + + @Override + public IParam _fx(IParam[] args) { + int length = args.length / 2 * 2; + for(int i = 0; i < length; ) { + if(ParamFormat.toBoolean(args[i])) { + return args[i + 1]; + } + i = i + 2; + } + return StandTypeParam.createConstantParam(""); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/NotFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/NotFunc.java new file mode 100644 index 0000000..114822a --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/NotFunc.java @@ -0,0 +1,17 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class NotFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 1) { + throw new IllegalArgumentException("NotFunc函数的参数只能有一个"); + } + return ParamFormat.format(args[0]).intValue() == 0 ? _true() : _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/OrFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/OrFunc.java new file mode 100644 index 0000000..99bd3e1 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/OrFunc.java @@ -0,0 +1,19 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class OrFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + for(IParam arg : args) { + if(ParamFormat.format(arg).intValue() != 0) { + return _true(); + } + } + return _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/TrueFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/TrueFunc.java new file mode 100644 index 0000000..021d41c --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/TrueFunc.java @@ -0,0 +1,16 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; + +public class TrueFunc extends AbstractLogicalFunc implements IFunc{ + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 0) { + throw new IllegalArgumentException("TrueFunc函数的不能有参数"); + } + return _true(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/XorFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/XorFunc.java new file mode 100644 index 0000000..d5e44d6 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/logical/XorFunc.java @@ -0,0 +1,21 @@ +package org.code.modules.plugins.function.method.logical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractLogicalFunc; +import org.code.modules.plugins.function.param.ParamFormat; + +public class XorFunc extends AbstractLogicalFunc implements IFunc{ + @Override + public IParam _fx(IParam[] args) { + int t = ParamFormat.format(args[0]).intValue(); + for(int i = 1; i < args.length; i ++) { + if( t != ParamFormat.format(args[i]).intValue()) {//不同true + t = 1; + }else { + t = 0; + } + } + return t != 0 ? _true() : _false(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/AvgFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/AvgFunc.java new file mode 100644 index 0000000..9b3c12b --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/AvgFunc.java @@ -0,0 +1,34 @@ +package org.code.modules.plugins.function.method.mathematical; + + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 平均值函数 + * @author chenzm + */ +public class AvgFunc extends AbstractMathFunc implements IFunc{ + + final Double INIT_VALUE = Double.valueOf(0); + + private StandTypeParam avg = StandTypeParam.createConstantParam(INIT_VALUE); + + @Override + public IParam _fx(IParam[] args) { + + if(isReset()) { + avg.setVal(INIT_VALUE); + } + + Double t = (Double)avg.getVal(); + for(IParam arg : args) { + t += NumFormat.$Double(arg.getVal()); + } + avg.setVal(t * 1.0f / args.length); + return avg; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/MathFormulaFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/MathFormulaFunc.java new file mode 100644 index 0000000..3ebe2f8 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/MathFormulaFunc.java @@ -0,0 +1,45 @@ +package org.code.modules.plugins.function.method.mathematical; + +import com.luqj.util.ArithmeticEnum;; +import com.luqj.util.assertion.Assert; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 数学算式函数(加减乘除) + * + * @author chenzm + */ +public class MathFormulaFunc extends AbstractMathFunc implements IFunc { + + protected ArithmeticEnum op; + + private StandTypeParam result = null; + + public MathFormulaFunc(ArithmeticEnum op) { + this.op = op; + } + + public MathFormulaFunc() { + } + + @Override + public IParam _fx(IParam[] args) { + if (args.length < 2 || args.length > 3) { + throw new IllegalArgumentException(op.getDesc() + "函数的参数最多是三个"); + } + if (result == null) { + if (this.op == null) { + Assert.logic(args.length == 3, "函数的参数必须是三个"); + this.op = ArithmeticEnum.getArithmeticEnum(ParamFormat.obj2Str(args[2])); + Assert.logic(this.op != null, "暂不支持" + ParamFormat.obj2Str(args[2]) + "操作符号"); + } + this.result = super.initStandTypeParam(args); + } + formulaOp(op, args[0], args[1], result); + return result; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/MaxFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/MaxFunc.java new file mode 100644 index 0000000..43fccce --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/MaxFunc.java @@ -0,0 +1,31 @@ +package org.code.modules.plugins.function.method.mathematical; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +public class MaxFunc extends AbstractMathFunc implements IFunc{ + + final double INIT_VALUE = Integer.MIN_VALUE * 1.0d; + + private StandTypeParam max = StandTypeParam.createConstantParam(INIT_VALUE); + + @Override + public IParam _fx(IParam[] args) { + if(isReset()) { + max.setVal(INIT_VALUE); + } + + Double t = (Double)max.getVal(); + for(IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + if(t.compareTo(val) < 0) { + t = val; + } + } + max.setVal(t); + return max; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/MinFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/MinFunc.java new file mode 100644 index 0000000..48ea31f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/MinFunc.java @@ -0,0 +1,31 @@ +package org.code.modules.plugins.function.method.mathematical; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +public class MinFunc extends AbstractMathFunc implements IFunc{ + + final double INIT_VALUE = Integer.MAX_VALUE * 1.0; + + private StandTypeParam min = StandTypeParam.createConstantParam(INIT_VALUE); + + @Override + public IParam _fx(IParam[] args) { + if(isReset()) { + min.setVal(INIT_VALUE); + } + + Double t = (Double)min.getVal(); + for(IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + if(t.compareTo(val) > 0) { + t = val; + } + } + min.setVal(t); + return min; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/PowFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/PowFunc.java new file mode 100644 index 0000000..8a92e6c --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/PowFunc.java @@ -0,0 +1,28 @@ +package org.code.modules.plugins.function.method.mathematical; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +/** + * Created by chenzm on 2017/2/22. + */ +public class PowFunc extends AbstractMathFunc implements IFunc { + + private StandTypeParam min = StandTypeParam.createParamByType(TypeEnum.Double); + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 2){ + throw new IllegalArgumentException("参数必须是一个"); + } + if(ParamFormat.argIsNull(args[0])) { + return null; + } + min.setVal(Math.pow(ParamFormat.format(args[0]).doubleValue(), ParamFormat.format(args[1]).intValue())); + return min; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/SumFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/SumFunc.java new file mode 100644 index 0000000..fd6d852 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/SumFunc.java @@ -0,0 +1,33 @@ +package org.code.modules.plugins.function.method.mathematical; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 求和函数 + * @author chenzm + */ +public class SumFunc extends AbstractMathFunc implements IFunc{ + + final Double INIT_VALUE = Double.valueOf(0); + + private StandTypeParam sum = StandTypeParam.createConstantParam(INIT_VALUE); + + @Override + public IParam _fx(IParam[] args) { + + if(isReset()) { + sum.setVal(INIT_VALUE); + } + + Double t = (Double)sum.getVal(); + for(IParam arg : args) { + t += NumFormat.$Double(arg.getVal()); + } + sum.setVal(t); + return sum; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RAvgFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RAvgFunc.java new file mode 100644 index 0000000..db056ab --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RAvgFunc.java @@ -0,0 +1,37 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; +import com.luqj.util.NumFormat; + +/** + * 平均值函数 + * Created by lucheng on 2017/8/29. + */ +public class RAvgFunc extends AbstractMathFunc implements IFunc { + + final Double INIT_VALUE = Double.valueOf(0); + + private StandTypeParam avg = StandTypeParam.createConstantParam(INIT_VALUE); + + private Integer count = 0; + + private Double sum = Double.valueOf(0); + + @Override + public IParam _fx(IParam[] args) { + count++; + for (IParam arg : args) { + sum += NumFormat.$Double(arg.getVal()); + } + double value = (double) Math.round(sum * 100 / count) / 100; + avg.setVal(value); + return avg; + } + + public Double getAvgValue() { + return (Double) avg.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMassFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMassFunc.java new file mode 100644 index 0000000..ffe8ea5 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMassFunc.java @@ -0,0 +1,39 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + + +import com.luqj.util.MapSortUtil; +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +import java.util.HashMap; +import java.util.Map; + +/** + * 众数函数 + * Created by lucheng on 2017/8/29. + */ +public class RMassFunc extends AbstractMathFunc implements IFunc { + + private Map valMap = new HashMap(); + + private StandTypeParam mass = StandTypeParam.createConstantParam(new Double("0")); + + @Override + public IParam _fx(IParam[] args) { + for (IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + valMap.put(val, valMap.get(val) == null ? 1 : (valMap.get(val) + 1)); + } + Map valueMap = MapSortUtil.sortMapByValue(valMap, "DESC"); + Double massValue = valueMap.entrySet().iterator().next().getKey(); // 众数 + mass.setVal(massValue); + return mass; + } + + public Double getMassValue() { + return (Double) mass.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMaxFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMaxFunc.java new file mode 100644 index 0000000..7ae445f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMaxFunc.java @@ -0,0 +1,35 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 最大值函数 + * Created by lucheng on 2017/8/28. + */ +public class RMaxFunc extends AbstractMathFunc implements IFunc { + + final double INIT_VALUE = Double.MIN_VALUE; + + private StandTypeParam max = StandTypeParam.createConstantParam(INIT_VALUE); + + @Override + public IParam _fx(IParam[] args) { + Double t = (Double) max.getVal(); + for (IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + if (t.compareTo(val) < 0) { + t = val; + } + } + max.setVal(t); + return max; + } + + public Double getMaxValue() { + return (Double) max.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMaxLengthFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMaxLengthFunc.java new file mode 100644 index 0000000..e995456 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMaxLengthFunc.java @@ -0,0 +1,34 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 最长值函数 + * Created by lucheng on 2017/8/29. + */ +public class RMaxLengthFunc extends AbstractMathFunc implements IFunc { + + final int INIT_VALUE = Integer.MIN_VALUE; + + private StandTypeParam maxLength = StandTypeParam.createConstantParam(INIT_VALUE); + + @Override + public IParam _fx(IParam[] args) { + Integer t = (Integer) maxLength.getVal(); + for (IParam arg : args) { + Integer val = arg.getVal().toString().length(); + if (t.compareTo(val) < 0) { + t = val; + } + } + maxLength.setVal(t); + return maxLength; + } + + public Integer getMaxLengthValue() { + return (Integer) maxLength.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMidValueFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMidValueFunc.java new file mode 100644 index 0000000..294328b --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMidValueFunc.java @@ -0,0 +1,66 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.MapSortUtil; +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +/** + * 中位数函数 + * Created by lucheng on 2017/8/31. + */ +public class RMidValueFunc extends AbstractMathFunc implements IFunc { + + private Map valMap = new HashMap(); + + private StandTypeParam midVal = StandTypeParam.createConstantParam(new Double("0")); + + private Integer count = 0; + + @Override + public IParam _fx(IParam[] args) { + count++; + for (IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + valMap.put(val, valMap.get(val) == null ? 1 : (valMap.get(val) + 1)); + } + + Integer pos1 = null, pos2 = null; + if (count % 2 == 0) { // 偶数个 + pos1 = count / 2; + pos2 = count / 2 + 1; + } else { // 奇数个 + pos1 = count / 2 + 1; + } + // key从小到大排序 + TreeMap newRange = MapSortUtil.sortMapByKey(valMap, "ASC"); + Integer sumCount = 0; + Double middleValue = null; //中位数 + for (Map.Entry newEntry : newRange.entrySet()) { + // Double number = newEntry.getKey(); + Integer count = newEntry.getValue(); + sumCount += count; + } + if (pos2 == null && pos1 <= sumCount) { // 奇数个 + Double number = MapSortUtil.getKeyByIndex(newRange, pos1); + middleValue = new Double(number); + } else { + Double number1 = MapSortUtil.getKeyByIndex(newRange, pos1); + Double number2 = MapSortUtil.getKeyByIndex(newRange, pos2); + middleValue = new Double((number1 + number2) / 2); + } + midVal.setVal(middleValue); + return midVal; + } + + public Double getMidValue() { + return (Double) midVal.getVal(); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMinFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMinFunc.java new file mode 100644 index 0000000..11b3bc9 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMinFunc.java @@ -0,0 +1,35 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 最小值函数 + * Created by lucheng on 2017/8/29. + */ +public class RMinFunc extends AbstractMathFunc implements IFunc { + + final double INIT_VALUE = Double.MAX_VALUE; + + private StandTypeParam min = StandTypeParam.createConstantParam(INIT_VALUE); + + @Override + public IParam _fx(IParam[] args) { + Double t = (Double) min.getVal(); + for (IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + if (t.compareTo(val) > 0) { + t = val; + } + } + min.setVal(t); + return min; + } + + public Double getMinValue() { + return (Double) min.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMinLengthFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMinLengthFunc.java new file mode 100644 index 0000000..8fc8b69 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RMinLengthFunc.java @@ -0,0 +1,34 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 最短值函数 + * Created by lucheng on 2017/8/29. + */ +public class RMinLengthFunc extends AbstractMathFunc implements IFunc { + + final int INIT_VALUE = Integer.MAX_VALUE; + + private StandTypeParam minLength = StandTypeParam.createConstantParam(INIT_VALUE); + + @Override + public IParam _fx(IParam[] args) { + Integer t = (Integer) minLength.getVal(); + for (IParam arg : args) { + Integer val = arg.getVal().toString().length(); + if (t.compareTo(val) > 0) { + t = val; + } + } + minLength.setVal(t); + return minLength; + } + + public Integer getMinLengthValue() { + return (Integer) minLength.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RQtr3Func.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RQtr3Func.java new file mode 100644 index 0000000..fc5d42e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RQtr3Func.java @@ -0,0 +1,51 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.MapSortUtil; +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +/** + * 四分位数q3 + * Created by lucheng on 2017/8/31. + */ +public class RQtr3Func extends AbstractMathFunc implements IFunc { + + private Map valMap = new HashMap(); + + private StandTypeParam qtr3 = StandTypeParam.createConstantParam(new Double("0")); + + private Integer count = 0; + + @Override + public IParam _fx(IParam[] args) { + count++; + for (IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + valMap.put(val, valMap.get(val) == null ? 1 : (valMap.get(val) + 1)); + } + TreeMap newRange = MapSortUtil.sortMapByKey(valMap, "ASC"); + + double p3 = 3 * (count + 1) / 4; + if (p3 < 1) { + p3 = 1; + } + int d3 = (int) p3; + double f3 = MapSortUtil.getKeyByIndex(newRange, d3); + double a3 = count >= (d3 + 1) ? MapSortUtil.getKeyByIndex(newRange, d3 + 1) : 0; + double q3 = f3 * (1 - (p3 - d3)) + a3 * (p3 - d3); + + qtr3.setVal(q3); + return qtr3; + } + + public Double getQtr3Value() { + return (Double) qtr3.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RQtrFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RQtrFunc.java new file mode 100644 index 0000000..797c64e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RQtrFunc.java @@ -0,0 +1,51 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.MapSortUtil; +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +/** + * 四分位数q1 + * Created by lucheng on 2017/8/31. + */ +public class RQtrFunc extends AbstractMathFunc implements IFunc { + + private Map valMap = new HashMap(); + + private StandTypeParam qtr = StandTypeParam.createConstantParam(new Double("0")); + + private Integer count = 0; + + @Override + public IParam _fx(IParam[] args) { + count++; + for (IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + valMap.put(val, valMap.get(val) == null ? 1 : (valMap.get(val) + 1)); + } + TreeMap newRange = MapSortUtil.sortMapByKey(valMap, "ASC"); + + double p1 = (count + 1) / 4; + if (p1 < 1) { + p1 = 1; + } + int d1 = (int) p1; // 向下取整 + double f1 = MapSortUtil.getKeyByIndex(newRange, d1); + double a1 = count >= (d1 + 1) ? MapSortUtil.getKeyByIndex(newRange, d1 + 1) : 0; + double q1 = f1 * (1 - (p1 - d1)) + a1 * (p1 - d1); + + qtr.setVal(q1); + return qtr; + } + + public Double getQtrValue() { + return (Double) qtr.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RQtrMinusFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RQtrMinusFunc.java new file mode 100644 index 0000000..0faf468 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RQtrMinusFunc.java @@ -0,0 +1,63 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.MapSortUtil; +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +/** + * 四分位数极差函数 + * Created by lucheng on 2017/8/31. + */ +public class RQtrMinusFunc extends AbstractMathFunc implements IFunc { + + private Map valMap = new HashMap(); + + private StandTypeParam qtrMinus = StandTypeParam.createConstantParam(new Double("0")); + + private Integer count = 0; + + @Override + public IParam _fx(IParam[] args) { + count++; + for (IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + valMap.put(val, valMap.get(val) == null ? 1 : (valMap.get(val) + 1)); + } + TreeMap newRange = MapSortUtil.sortMapByKey(valMap, "ASC"); + + double p1 = (count + 1) / 4; + if (p1 < 1) { + p1 = 1; + } + int d1 = (int) p1; // 向下取整 + double f1 = MapSortUtil.getKeyByIndex(newRange, d1); + double a1 = count >= (d1 + 1) ? MapSortUtil.getKeyByIndex(newRange, d1 + 1) : 0; + double q1 = f1 * (1 - (p1 - d1)) + a1 * (p1 - d1); + + double p3 = 3 * (count + 1) / 4; + if (p3 < 1) { + p3 = 1; + } + int d3 = (int) p3; + double f3 = MapSortUtil.getKeyByIndex(newRange, d3); + double a3 = count >= (d3 + 1) ? MapSortUtil.getKeyByIndex(newRange, d3 + 1) : 0; + double q3 = f3 * (1 - (p3 - d3)) + a3 * (p3 - d3); + + // 四分位数极差 + double qMinus = q3 - q1; + qtrMinus.setVal(qMinus); + return qtrMinus; + } + + public Double getQtrMinus() { + return (Double) qtrMinus.getVal(); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RRangeFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RRangeFunc.java new file mode 100644 index 0000000..ad39f13 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RRangeFunc.java @@ -0,0 +1,45 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 极差函数 + * Created by lucheng on 2017/8/29. + */ +public class RRangeFunc extends AbstractMathFunc implements IFunc { + + + private StandTypeParam max = StandTypeParam.createConstantParam(Double.MIN_VALUE); + + private StandTypeParam min = StandTypeParam.createConstantParam(Double.MAX_VALUE); + + private StandTypeParam range = StandTypeParam.createConstantParam(new Double("0")); + + @Override + public IParam _fx(IParam[] args) { + Double tMax = (Double) max.getVal(); + Double tMin = (Double) min.getVal(); + for (IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + if (tMax.compareTo(val) < 0) { + tMax = val; + } + if (tMin.compareTo(val) > 0) { + tMin = val; + } + } + max.setVal(tMax); + min.setVal(tMin); + Double rangeVal = (Double) max.getVal() - (Double) min.getVal(); + range.setVal(rangeVal); + return range; + } + + public Double getRangeValue() { + return (Double) range.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RStdDevFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RStdDevFunc.java new file mode 100644 index 0000000..b0ed274 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RStdDevFunc.java @@ -0,0 +1,47 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 标准差公式 + * Created by lucheng on 2017/8/29. + */ +public class RStdDevFunc extends AbstractMathFunc implements IFunc { + + final Double INIT_VALUE = Double.valueOf(0); + + private StandTypeParam sum = StandTypeParam.createConstantParam(INIT_VALUE); + + private StandTypeParam sum2 = StandTypeParam.createConstantParam(INIT_VALUE); + + private StandTypeParam variance = StandTypeParam.createConstantParam(INIT_VALUE); + + private Integer count = 0; + + @Override + public IParam _fx(IParam[] args) { + count++; + Double s = (Double) sum.getVal(); + Double s2 = (Double) sum2.getVal(); + for (IParam arg : args) { + s += NumFormat.$Double(arg.getVal()); + s2 += (NumFormat.$Double(arg.getVal()) * NumFormat.$Double(arg.getVal())); + } + Double avgValue = s * 1.0f / count; + Double var = s2 / count - avgValue * avgValue; + sum.setVal(s); + sum2.setVal(s2); + variance.setVal(var); + return variance; + } + + public Double getStdDevValue() { + double var = (double) variance.getVal(); + double sqrt = Math.sqrt(var); + return (double) Math.round(sqrt * 100) / 100; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RValueRangeFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RValueRangeFunc.java new file mode 100644 index 0000000..1c92f09 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RValueRangeFunc.java @@ -0,0 +1,40 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.SimpleIteratorParam; +import org.code.modules.plugins.function.param.StandardMutlValTypeParam; +import org.code.modules.plugins.types.MapType; + +import java.util.HashMap; +import java.util.Map; + +/** + * 值分布函数 + * Created by lucheng on 2017/8/29. + */ +public class RValueRangeFunc extends AbstractMathFunc implements IFunc { + + private Map valMap = new HashMap(); + + private StandardMutlValTypeParam param = null; + + public RValueRangeFunc() { + param = new SimpleIteratorParam(new MapType(Integer.class), valMap); + } + + @Override + public IParam _fx(IParam[] args) { + for (IParam arg : args) { + Double val = NumFormat.$Double(arg.getVal()); + valMap.put(val, valMap.get(val) == null ? 1 : (valMap.get(val) + 1)); + } + return param; + } + + public Map getRangeMap() { + return (Map) param.getVal(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RVarianceFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RVarianceFunc.java new file mode 100644 index 0000000..647e82a --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/mathematical/dataset/RVarianceFunc.java @@ -0,0 +1,46 @@ +package org.code.modules.plugins.function.method.mathematical.dataset; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractMathFunc; +import org.code.modules.plugins.function.param.StandTypeParam; + +/** + * 方差公式 + * Created by lucheng on 2017/8/29. + */ +public class RVarianceFunc extends AbstractMathFunc implements IFunc { + + final Double INIT_VALUE = Double.valueOf(0); + + private StandTypeParam sum = StandTypeParam.createConstantParam(INIT_VALUE); + + private StandTypeParam sum2 = StandTypeParam.createConstantParam(INIT_VALUE); + + private StandTypeParam variance = StandTypeParam.createConstantParam(INIT_VALUE); + + private Integer count = 0; + + @Override + public IParam _fx(IParam[] args) { + count++; + Double s = (Double) sum.getVal(); + Double s2 = (Double) sum2.getVal(); + for (IParam arg : args) { + s += NumFormat.$Double(arg.getVal()); + s2 += (NumFormat.$Double(arg.getVal()) * NumFormat.$Double(arg.getVal())); + } + Double avgValue = s * 1.0f / count; + Double var = s2 / count - avgValue * avgValue; + sum.setVal(s); + sum2.setVal(s2); + variance.setVal(var); + return variance; + } + + public Double getVarianceValue() { + double var = (double) variance.getVal(); + return (double) Math.round(var * 100) / 100; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/series/SeriesFreq.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/series/SeriesFreq.java new file mode 100644 index 0000000..7cd0681 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/series/SeriesFreq.java @@ -0,0 +1,50 @@ +package org.code.modules.plugins.function.method.series; + +import org.code.modules.plugins.function.IExpression; +import org.code.modules.plugins.function.IExpressionContext; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.cache.FreqSeriesRolling; +import org.code.modules.plugins.function.cache.IRollingCaching; +import org.code.modules.plugins.function.expression.DefaultExpressionContext; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.function.parse.ExpressionParse; +import org.code.modules.plugins.types.TypeEnum; + +import java.util.Map; + +/** + * Created by liwei on 2017/9/20. + */ +public class SeriesFreq implements IFunc { + + + private FreqSeriesRolling cachingRolling; + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.Double); + private IExpression expression; + private IExpressionContext cxt; + + IRollingCaching.IRollingApply apply = new IRollingCaching.IRollingApply () { + @Override + public Double apply(String key, Map val) { + double result2 = 0; + for (Double v : val.keySet()){ + cxt.setExpressionData("VAL" ,v); + result2 = ParamFormat.format(expression.execExpression(cxt)).doubleValue(); + } + return result2; + } + }; + + @Override + public IParam fx(IParam... args) { + if(expression != null){ + String exp = ParamFormat.obj2Str(args[2]); + expression = ExpressionParse.createDefaultParse().parseExpression(exp); + cxt = new DefaultExpressionContext(); + } + result.setVal(cachingRolling.rollingBefore(ParamFormat.obj2Str(args[0]),ParamFormat.format(args[1]).doubleValue(),apply,true)); ; + return result; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/ConcatFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/ConcatFunc.java new file mode 100644 index 0000000..268f529 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/ConcatFunc.java @@ -0,0 +1,26 @@ +package org.code.modules.plugins.function.method.text; + + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class ConcatFunc extends AbstractTextFunc implements IFunc{ + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.String); + + private StringBuilder builder = new StringBuilder(); + + @Override + public IParam _fx(IParam[] args) { + if(builder.length() > 0) + builder.delete(0, builder.length()); + for(IParam arg : args) { + builder.append(ParamFormat.obj2Str(arg)); + } + result.setVal(builder.toString()); + return result; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/ExactFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/ExactFunc.java new file mode 100644 index 0000000..bc8f33e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/ExactFunc.java @@ -0,0 +1,21 @@ +package org.code.modules.plugins.function.method.text; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class ExactFunc extends AbstractTextFunc implements IFunc{ + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.Boolean); + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 2) { + throw new IllegalArgumentException("EXACT函数参数必须是两个"); + } + result.setVal(ParamFormat.isEqual(args[0], args[1])); + return result; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/FindFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/FindFunc.java new file mode 100644 index 0000000..03e48ac --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/FindFunc.java @@ -0,0 +1,23 @@ +package org.code.modules.plugins.function.method.text; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class FindFunc extends AbstractTextFunc implements IFunc{ + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.Integer); + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 2) { + throw new IllegalArgumentException("FindFunc函数参数有且只有两个参数"); + } + if(!ParamFormat.argIsNull(args[0]) ) { + result.setVal(ParamFormat.obj2Str(args[0]).indexOf(ParamFormat.obj2Str(args[1]))); + } + return result; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/JsonParseFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/JsonParseFunc.java new file mode 100644 index 0000000..c6c1936 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/JsonParseFunc.java @@ -0,0 +1,62 @@ +package org.code.modules.plugins.function.method.text; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.SimpleIteratorParam; +import org.code.modules.plugins.function.param.StandardMutlValTypeParam; +import org.code.modules.plugins.types.MapType; +import net.sf.json.JSONObject; + +import java.util.HashMap; +import java.util.Map; + +/** + * JSON函数解析 + */ +public class JsonParseFunc extends AbstractTextFunc implements IFunc{ + private Map valMap = new HashMap(); + + private StandardMutlValTypeParam param = null; + + public JsonParseFunc() { + param = new SimpleIteratorParam(new MapType(Object.class), valMap); + } + + @Override + public IParam _fx(IParam[] args) { + if(ParamFormat.argIsNull(args[0])) { + return null; + } + + //clear data + this.valMap.clear(); + + JSONObject jsonObj = null; + try { + jsonObj = JSONObject.fromObject(ParamFormat.obj2Str(args[0])); + }catch (Exception e) { + throw new IllegalStateException("[" + ParamFormat.obj2Str(args[0]) + "]数据解析异常", e); + } + + for(int i = 1; i < args.length; i++) { + String key = ParamFormat.obj2Str(args[i]); + valMap.put(key, getObj(jsonObj, key)); + } + return param; + } + + private Object getObj(JSONObject jsonObj, String name) { + if(name.contains(".")) { + String[] objProperties = name.split("\\."); + JSONObject temp = jsonObj; + for(int i = 0; i < objProperties.length - 1; i++) { + temp = temp.getJSONObject(objProperties[i]); + } + return temp.get(objProperties[objProperties.length - 1]).toString(); + }else { + return jsonObj.get(name).toString(); + } + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/LenFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/LenFunc.java new file mode 100644 index 0000000..2912171 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/LenFunc.java @@ -0,0 +1,27 @@ +package org.code.modules.plugins.function.method.text; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class LenFunc extends AbstractTextFunc implements IFunc{ + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.Integer); + + + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 1) { + throw new IllegalArgumentException("Len函数参数只能有一个"); + } + if(!ParamFormat.argIsNull(args[0])) { + result.setVal(ParamFormat.obj2Str(args[0]).length()); + }else { + result.setVal(0); + } + return result; + } +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/LowerFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/LowerFunc.java new file mode 100644 index 0000000..78b0014 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/LowerFunc.java @@ -0,0 +1,23 @@ +package org.code.modules.plugins.function.method.text; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class LowerFunc extends AbstractTextFunc implements IFunc{ + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.String); + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 1) { + throw new IllegalArgumentException("LOWER函数参数只能有一个"); + } + if(!ParamFormat.argIsNull(args[0])) { + result.setVal(ParamFormat.obj2Str(args[0]).toLowerCase()); + } + return result; + } +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/ReplaceFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/ReplaceFunc.java new file mode 100644 index 0000000..e7dd2b8 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/ReplaceFunc.java @@ -0,0 +1,45 @@ +package org.code.modules.plugins.function.method.text; + +import com.luqj.util.NumFormat; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class ReplaceFunc extends AbstractTextFunc implements IFunc{ + private StandTypeParam result = null; + + int type = 0; + + @Override + public IParam _fx(IParam[] args) { + if(args.length < 3 || args.length > 4) { + throw new IllegalArgumentException("REPLACE函数参数必须是大于等于三个"); + } + + if(result == null) { + result = StandTypeParam.createParamByType(TypeEnum.String); + if(args.length == 4) { + type = NumFormat.$Intger(args[3]); + } + } + + if(args[0].getVal() != null) { + switch(type) { + case 0: + result.setVal(ParamFormat.obj2Str(args[0]).replaceAll(ParamFormat.obj2Str(args[1]), ParamFormat.obj2Str(args[2]))); + break; + case 1: + result.setVal(ParamFormat.obj2Str(args[0]).replace(ParamFormat.obj2Str(args[1]), ParamFormat.obj2Str(args[2]))); + break; + case 2: + result.setVal(ParamFormat.obj2Str(args[0]).replaceFirst(ParamFormat.obj2Str(args[1]), ParamFormat.obj2Str(args[2]))); + break; + } + return result; + } + return _nullChr; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/SubstringFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/SubstringFunc.java new file mode 100644 index 0000000..47bd123 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/SubstringFunc.java @@ -0,0 +1,35 @@ +package org.code.modules.plugins.function.method.text; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class SubstringFunc extends AbstractTextFunc implements IFunc { + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.String); + + @Override + public IParam _fx(IParam[] args) { + if (args.length < 2 || args.length > 3) { + throw new IllegalArgumentException("TRIM函数参数必须是两个或者三个"); + } + + if (ParamFormat.argIsNull(args[0])) { + return super.getDefVal(); + } + + String str = ParamFormat.obj2Str(args[0]); + + int limit = str.length(); + int start = Math.min(ParamFormat.format(args[1]).intValue(), limit); + if (args.length == 2) + result.setVal(str.substring(start)); + else { + int end = Math.min(ParamFormat.format(args[2]).intValue(), limit); + result.setVal(str.substring(start, end)); + } + return result; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/TextFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/TextFunc.java new file mode 100644 index 0000000..eeb0fe4 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/TextFunc.java @@ -0,0 +1,24 @@ +package org.code.modules.plugins.function.method.text; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class TextFunc extends AbstractTextFunc implements IFunc{ + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.String); + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 1) { + throw new IllegalArgumentException("TEXT函数参数只能有一个"); + } + if(!ParamFormat.argIsNull(args[0])) { + result.setVal(ParamFormat.obj2Str(args[0]).trim()); + return result; + } + return _nullChr; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/TrimFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/TrimFunc.java new file mode 100644 index 0000000..51db8bc --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/TrimFunc.java @@ -0,0 +1,24 @@ +package org.code.modules.plugins.function.method.text; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class TrimFunc extends AbstractTextFunc implements IFunc{ + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.String); + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 1) { + throw new IllegalArgumentException("TRIM函数参数只能有一个"); + } + if(args[0].getVal() != null) { + result.setVal(ParamFormat.obj2Str(args[0]).trim()); + return result; + } + return _nullChr; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/UpperFunc.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/UpperFunc.java new file mode 100644 index 0000000..7b807ad --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/method/text/UpperFunc.java @@ -0,0 +1,24 @@ +package org.code.modules.plugins.function.method.text; + +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.function.method.AbstractTextFunc; +import org.code.modules.plugins.function.param.ParamFormat; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.types.TypeEnum; + +public class UpperFunc extends AbstractTextFunc implements IFunc{ + private StandTypeParam result = StandTypeParam.createParamByType(TypeEnum.String); + + @Override + public IParam _fx(IParam[] args) { + if(args.length != 1) { + throw new IllegalArgumentException("UPPER函数参数只能有一个"); + } + if(args[0].getVal() != null) { + result.setVal(ParamFormat.obj2Str(args[0]).toUpperCase()); + return result; + } + return _nullChr; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/AbstractParam.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/AbstractParam.java new file mode 100644 index 0000000..1f970d1 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/AbstractParam.java @@ -0,0 +1,52 @@ +package org.code.modules.plugins.function.param; + +import org.code.modules.plugins.function.IParam; + +public abstract class AbstractParam implements IParam{ + + protected Object paramValue = null; + + protected String paramName = null; + + public AbstractParam(Object obj) { + this.setVal(obj); + } + + public AbstractParam(String paramName, Object obj) { + this.setVal(obj); + this.paramName = paramName; + } + + @Override + public void setVal(Object val) { + this.paramValue = val; + } + + /*@Override + public T getVal(String paramName) { + if(this.paramValue == null) { + return null; + } + if(this.paramValue instanceof Map) { + return (T)((Map) this.paramValue).get(paramName); + } + return (T)this.paramValue; + }*/ + + @Override + public Object getVal() { + if(this.paramValue == null) { + return null; + } + return this.paramValue; + } + + @Override + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/ParamFormat.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/ParamFormat.java new file mode 100644 index 0000000..abba1c6 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/ParamFormat.java @@ -0,0 +1,143 @@ +package org.code.modules.plugins.function.param; + +import com.luqj.util.NumFormat; +import com.luqj.util.StringUtils; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.types.TypeEnum; + +/** + * 参数格式化 + * @author chenzm + */ +public class ParamFormat { + /** + * 数据格式化 + * @param arg0 + * @return + */ + public static Number format(IParam arg0) { + if(arg0.getValType() == Boolean.class) { + if(((Boolean)arg0.getVal()) == false) { + return 0; + } + return 1; + } + + switch(TypeEnum.valueOf(arg0.getValType().getSimpleName())) { + case Short: + return NumFormat.$Short(arg0.getVal()); + case Integer: + return NumFormat.$Intger(arg0.getVal()); + case Long: + return NumFormat.$Long(arg0.getVal()); + case Float: + return NumFormat.$Float(arg0.getVal()); + case Date: + return NumFormat.$Date(arg0.getVal()); + case Timestamp: + return NumFormat.$Timestamp(arg0.getVal()); + /*case Double: + case String:*/ + default: + return NumFormat.$Double(arg0.getVal()); + } + } + + public static String obj2Str(IParam arg) { + return ((StandTypeParam)arg).format(); + } + + public static boolean argIsNull(IParam arg) { + if(arg == null || arg.getVal() == null) { + return true; + } + if(arg.getValType() == String.class) { + return StringUtils.isBlank(obj2Str(arg)); + } + return false; + } + + /** + * 是否是数字 + * @param arg + * @return + */ + public static boolean isNumber(IParam arg) { + if(argIsNull(arg)) { + return false; + } + switch(TypeEnum.valueOf(arg.getValType().getSimpleName())) { + case Short: + case Integer: + case Long: + case Float: + case Double: + case BigInteger: + case BigDecimal: + return true; + default: + return false; + } + } + + /** + * 是否是日期 + * @param arg + * @return + */ + public static boolean isDate(IParam arg) { + if(argIsNull(arg)) { + return false; + } + if(arg.getValType() == java.util.Date.class) { + return true; + } + switch(TypeEnum.valueOf(arg.getValType().getSimpleName())) { + case Date: + case Timestamp: + case Time: + return true; + default: + return false; + } + } + + /** + * 参数是否相等 + * @param a + * @param b + * @return + */ + public static boolean isEqual(IParam a, IParam b) { + if (ParamFormat.isNumber(a) && ParamFormat.isNumber(b)) { + return ParamFormat.format(a).doubleValue() == ParamFormat.format(b).doubleValue(); + } else if (a.getVal() == null && b.getVal() == null) { + return true; + } else if (a.getVal() != null && a.getVal().equals(b.getVal())) { + return true; + } else if (b.getVal() != null && b.getVal().equals(a.getVal())) { + return true; + } else { + return false; + } + } + + public static boolean toBoolean(IParam paramVal) { + Object param = paramVal.getVal(); + if(param == null) { + return false; + }else if(param instanceof Boolean) { + return (Boolean)param; + }else if(Boolean.TRUE.toString().equals(param.toString())) { + return true; + }else if(Boolean.FALSE.toString().equals(param.toString())) { + return false; + } + try { + return (Integer) param == 1 ? true : false; + }catch (Exception e) { + throw new IllegalStateException(String.format("检查函数的返回值是否是布尔值[paramName=%s;paramValue=%s;class=%s]", + paramVal.getParamName(), paramVal.getValType(), paramVal.getVal().toString()), e); + } + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/SimpleIteratorParam.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/SimpleIteratorParam.java new file mode 100644 index 0000000..68d907a --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/SimpleIteratorParam.java @@ -0,0 +1,80 @@ +package org.code.modules.plugins.function.param; + + +import org.code.modules.plugins.types.StandardMutlValType; +import org.code.modules.plugins.types.StandardMutlValType.ValEntity; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * 默认的Iterator包装器 + * + * @author chenzm + */ +public class SimpleIteratorParam extends StandardMutlValTypeParam { + + private List entitys = new ArrayList(3); + ; + + private List> tempList = new ArrayList>(1); + + private List> dataList; + + private Iterator> it; + + public SimpleIteratorParam(Object obj) { + super(obj); + } + + public SimpleIteratorParam(StandardMutlValType mutlValType, Object paramVal) { + super(mutlValType, paramVal); + } + + @Override + public void reset() { + this.it = null; + this.dataList = null; + this.entitys.clear(); + if (this.getVal() instanceof Map) { + Map data = (Map) this.getVal(); + this.tempList.clear(); + this.tempList.add(data); + this.dataList = tempList; + } else if (this.getVal() instanceof List) { + this.dataList = (List>) this.getVal(); + } else { + throw new IllegalArgumentException("暂不支持" + this.getVal().getClass() + " data:" + this.getVal()); + } + if (this.dataList != null) { + this.it = dataList.iterator(); + } + } + + @Override + public boolean hasNext() { + if (it == null) + return false; + return it.hasNext(); + } + + @Override + public List next() { + Map data = it.next(); + for (String key : data.keySet()) { + entitys.add(new ValEntity(key, 0, data.get(key))); + } + return entitys; + } + + @Override + public void remove() { + + } + + @Override + public void finish() { + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/StandTypeParam.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/StandTypeParam.java new file mode 100644 index 0000000..6f5e147 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/StandTypeParam.java @@ -0,0 +1,84 @@ +package org.code.modules.plugins.function.param; + +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.types.StandardType; +import org.code.modules.plugins.types.StandardTypeFactory; +import org.code.modules.plugins.types.TypeEnum; + +/** + * 标准类型参数 + * @author chenzm + * @param + */ +public class StandTypeParam extends AbstractParam implements IParam{ + + private StandardType stdType; + + private TypeEnum typeEnum; + + protected StandTypeParam(Object obj) { + super(obj); + } + + protected StandTypeParam(StandardType stdType, Object paramVal) { + super(paramVal); + this.stdType = stdType; + } + + protected StandTypeParam(String fieldName, StandardType fieldType, Object paramValue) { + super(fieldName, paramValue); + this.stdType = fieldType; + } + + @Override + public void setVal(Object val) { + this.paramValue = val; + if(this.stdType == null && paramValue != null) { + this.stdType = StandardTypeFactory.createType(paramValue.getClass().getSimpleName(), 10, 0); + } + } + + public static StandTypeParam createConstantParam(Object paramValue) { + return new StandTypeParam(StandardTypeFactory.createType(paramValue.getClass().getSimpleName(), 10, 0), paramValue); + } + + public static StandTypeParam createParamByType(TypeEnum filedType) { + return new StandTypeParam(StandardTypeFactory.createType(filedType.toString(), 10, 0), null); + } + + public static StandTypeParam createFieldParam(String fieldName, StandardType filedType) { + return new StandTypeParam(fieldName, filedType, null); + } + + public static StandTypeParam createFieldParam(String fieldName, TypeEnum filedType, int len, int Precsn) { + StandTypeParam param = createParamByType(filedType); + param.paramName = fieldName; + return param; + } + + @Override + public Class getValType() { + return stdType == null ? null : stdType.getReturnedClass(); + } + + @Override + public int getPrecision() { + return stdType.getPrecsn(); + } + + @Override + public int getLength() { + return stdType.getLength(); + } + + public String format() { + return this.stdType.format(this.paramValue); + } + + public TypeEnum getTypeEnum() { + if(this.typeEnum == null) { + this.typeEnum = TypeEnum.valueOf(this.getValType().getSimpleName()); + } + return this.typeEnum; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/StandardMutlValTypeParam.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/StandardMutlValTypeParam.java new file mode 100644 index 0000000..d14364d --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/param/StandardMutlValTypeParam.java @@ -0,0 +1,69 @@ +package org.code.modules.plugins.function.param; + +import org.code.modules.plugins.function.IIteratorWrap; +import org.code.modules.plugins.function.IParam; +import org.code.modules.plugins.types.StandardMutlValType; +import org.code.modules.plugins.types.StandardMutlValType.ValEntity; +import org.code.modules.plugins.types.TypeEnum; + +import java.util.Collection; +import java.util.List; + +/** + * 标准多值类型参数 + * @author chenzm + */ +public abstract class StandardMutlValTypeParam extends AbstractParam implements IParam, IIteratorWrap> { + + protected StandardMutlValType mutlValType; + + protected TypeEnum typeEnum; + + protected StandardMutlValTypeParam(Object obj) { + super(obj); + } + + protected StandardMutlValTypeParam(StandardMutlValType mutlValType, Object paramVal) { + super(paramVal); + this.mutlValType = mutlValType; + } + + protected StandardMutlValTypeParam(String fieldName, StandardMutlValType fieldType, Object paramValue) { + super(fieldName, paramValue); + this.mutlValType = fieldType; + } + + @Override + public void setVal(Object val) { + this.paramValue = val; + /*if(this.mutlValType == null && paramValue != null) { + this.mutlValType = StandardTypeFactory.createType(paramValue.getClass().getSimpleName(), 10, 0); + }*/ + } + + @Override + public Class getValType() { + return mutlValType == null ? null : mutlValType.getReturnedClass(); + } + + @Override + public int getPrecision() { + return mutlValType.getPrecsn(); + } + + @Override + public int getLength() { + return mutlValType.getLength(); + } + + public Collection format() { + return this.mutlValType.format(this.paramValue); + } + + public TypeEnum getTypeEnum() { + if(this.typeEnum == null) { + this.typeEnum = TypeEnum.valueOf(this.getValType().getSimpleName()); + } + return this.typeEnum; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/parse/ExpressionParse.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/parse/ExpressionParse.java new file mode 100644 index 0000000..cd45ed6 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/parse/ExpressionParse.java @@ -0,0 +1,225 @@ +package org.code.modules.plugins.function.parse; + +import com.luqj.util.ArithmeticEnum;; +import com.luqj.util.assertion.Assert; +import org.code.modules.plugins.function.FuncEnum; +import org.code.modules.plugins.function.IExpression; +import org.code.modules.plugins.function.IExpressionParse; +import org.code.modules.plugins.function.IFunc; +import org.code.modules.plugins.function.expression.CombinationExpression; +import org.code.modules.plugins.function.expression.FormulaExpression; +import org.code.modules.plugins.function.method.mathematical.MathFormulaFunc; +import org.code.modules.plugins.function.param.StandTypeParam; +import org.code.modules.plugins.function.parse.SyntaxParse.SyntaxNode; +import org.code.modules.plugins.function.parse.SyntaxParse.SyntaxType; +import org.code.modules.plugins.types.TypeEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.DecimalFormat; +import java.text.ParseException; +import java.util.*; + +/** + * 表达式解析 + * + * @author chenzm + */ +public abstract class ExpressionParse implements IExpressionParse { + /** + * 函数集 + */ + private Set funcSet; + + /** + * 语法解析器 + */ + private SyntaxParse syntaxParse = null; + + private static final DecimalFormat decimalFormat = new DecimalFormat(); + private static final Logger logger = LoggerFactory.getLogger(ExpressionParse.class); + + public ExpressionParse(Set funcSet) { + this.funcSet = funcSet; + this.syntaxParse = SyntaxParse.createSyntaxParse(funcSet); + } + + /** + * 获取语法树 + * + * @param exp + * @return + */ + public SyntaxNode getSyntaxTree(String exp) { + return syntaxParse.syntaxParse(exp); + } + + /** + * 解析表达式 + * + * @return + */ + @Override + public IExpression parseExpression(String expression) { + Assert.hasText(expression, "表达式不能为空"); + expression = expression.trim(); + SyntaxNode syntaxTree = syntaxParse.syntaxParse(expression); + if (logger.isDebugEnabled()) { + logger.debug("解析函数表达式:" + expression); + SyntaxNode.showTree(syntaxTree); + } + return parseFuncExpression(syntaxTree); + } + + /** + * 解析函数表达式 MAX(1,3, MIN(1, 1+ IF([A],[B], [B] * 10) ), 1 + MAX(1,3) * 10 + MIN(3, 4) ) + * + * @param node + * @return + */ + private IExpression parseFuncExpression(SyntaxNode node) { + IExpression exp = null; + if (node.exitsChild()) { + String funName = node.syntaxType == SyntaxType.Bag ? "BAG" : node.getKey(); + if (node.syntaxType == SyntaxType.Bag) { + Assert.logic(node.exitsChild() && node.childs().size() == 1, + "[" + node.startPos + "," + node.endPos + ")位置发生错误,包里面的参数只能是一个"); + } + CombinationExpression combinationExp = new CombinationExpression(createFunction(funName)); + for (SyntaxNode child : node.childs()) { + switch (child.syntaxType) { + case Func: + case Bag: + combinationExp.addExpression(parseFuncExpression(child)); + break; + case FunctionFormula: + combinationExp.addExpression(parseFunctionFormula(child)); + break; + default: + combinationExp.addParam(getStandTypeParam(child)); + } + } + exp = combinationExp; + } else { + FormulaExpression baseExp = new FormulaExpression(createFunction(node.getKey())); + for (SyntaxNode child : node.childs()) { + baseExp.addParam(getStandTypeParam(child)); + } + exp = baseExp; + } + return exp; + } + + /** + * 解析算式表达式 eg: 1 + MAX(1,3) * 10 + MIN(3, 4),把函数当成一个整体 (代元法) + * + * @param exp + * @return + */ + private IExpression parseFunctionFormula(SyntaxNode exp) { + Stack valueStack = new Stack(); + for (SyntaxNode node : SyntaxParse.suffixSyntaxStack(exp)) { + if (ArithmeticEnum.containsKey(node.getKey())) { + Object b = valueStack.pop(); + Object a = valueStack.pop(); + CombinationExpression cx = new CombinationExpression(new MathFormulaFunc(ArithmeticEnum.getArithmeticEnum(node.getKey()))); + cx.addParamOrExp(a); + cx.addParamOrExp(b); + valueStack.push(cx); + } else if (node.syntaxType == SyntaxType.Func) { + valueStack.add(parseFuncExpression(node)); + } else { + valueStack.add(getStandTypeParam(node)); + } + } + return (IExpression) valueStack.get(0); + } + + public static StandTypeParam getStandTypeParam(SyntaxNode paramNode) { + String val = paramNode.getKey(); + if (SyntaxType.Text == paramNode.syntaxType) { + String qm = "" + val.charAt(0); + val = val.substring(val.indexOf(qm) + 1, val.lastIndexOf(qm)); + return StandTypeParam.createConstantParam(val); + } + + if (SyntaxType.Field == paramNode.syntaxType) { + String field = val.substring(1, val.length() - 1); + return StandTypeParam.createFieldParam(field, null); + } + + if (SyntaxType.Number == paramNode.syntaxType) { + StandTypeParam param = StandTypeParam.createParamByType(TypeEnum.Float); + try { + param.setVal(decimalFormat.parse(val).floatValue()); + } catch (ParseException e) { + throw new IllegalArgumentException("数字解析异常", e); + } + return param; + } + throw new IllegalArgumentException("未知的类型[" + "KEY:" + paramNode.getKey() + ",TYPE:" + paramNode.syntaxType + "]"); + } + + /** + * 是否是函数 + * + * @param funcName + * @return + */ + protected boolean isFunc(String funcName) { + return this.funcSet.contains(funcName.trim().toUpperCase()); + } + + /** + * 创建函数 + * + * @param funcName + * @return + */ + protected abstract IFunc createFunction(String funcName); + + /** + * 获取字段 + * + * @param exp + * @return + */ + public Set getFieldSet(String exp) { + return this.lookupField(this.getSyntaxTree(exp)); + } + + private Set lookupField(SyntaxNode tree) { + Set fieldList = new LinkedHashSet<>(); + if (tree.syntaxType() == SyntaxParse.SyntaxType.Field) { + fieldList.add(tree.getKey().substring(1, tree.getKey().length() - 1)); + } + if (tree.childs() != null) { + for (SyntaxParse.SyntaxNode child : tree.childs()) { + fieldList.addAll(lookupField(child)); + } + } + return fieldList; + } + + /** + * 创建默认解析器 + * + * @return + */ + public static ExpressionParse createDefaultParse() { + final Map funcMap = new HashMap(); + for (FuncEnum func : FuncEnum.values()) { + funcMap.put(func.getCode(), func.getClazz()); + } + return new ExpressionParse(funcMap.keySet()) { + @Override + public IFunc createFunction(String funcName) { + try { + return (IFunc) Class.forName(funcMap.get(funcName.toUpperCase())).newInstance(); + } catch (Exception e) { + throw new IllegalStateException("函数【" + funcName + "】", e); + } + } + }; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/parse/SymbolSet.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/parse/SymbolSet.java new file mode 100644 index 0000000..c27bc32 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/parse/SymbolSet.java @@ -0,0 +1,65 @@ +package org.code.modules.plugins.function.parse; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 符号集 + * @author chenzm + */ +public class SymbolSet { + /**等号*/ + public final static String SYMBOL_EQ = "="; + + /**空字符*/ + public final static Character SYMBOL_NULL = ' '; + + /**逗号*/ + public final static String SYMBOL_COMMA = ","; + + /**双引号*/ + public final static String SYMBOL_DQM = "\""; + + /**单引号*/ + public final static String SYMBOL_SQM = "\'"; + + public static String chr2Str(char chr) { + return "" + chr; + } + + static boolean isInSymbol(Map> symBolPos, int charPos, String ...symbols){ + for(String symbol : symbols) { + if(!symBolPos.containsKey(symbol)) { + return false; + } + List posInfo = symBolPos.get(symbol); + for(int i = 0; i < posInfo.size(); ) { + if(charPos > posInfo.get(i) && charPos < posInfo.get(i + 1)) { + return true; + } + i+=2; + } + } + return false; + } + + static Map> getSymBolPos(String exp) { + Map> map = new HashMap>(); + String[] symbols = new String[]{ + SYMBOL_SQM, SYMBOL_DQM + }; + for(String symbol : symbols) { + map.put(symbol, new ArrayList(exp.length())); + int charPos = 0; + for(char c : exp.toCharArray()) { + if(c == symbol.charAt(0)) { + map.get(symbol).add(charPos); + } + charPos++; + } + } + return map; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/function/parse/SyntaxParse.java b/luqj-plugin/src/main/java/org/code/modules/plugins/function/parse/SyntaxParse.java new file mode 100644 index 0000000..49d2aa4 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/function/parse/SyntaxParse.java @@ -0,0 +1,499 @@ +package org.code.modules.plugins.function.parse; + +import com.luqj.util.ArithmeticEnum;; +import com.luqj.util.CharBuffer; +import com.luqj.util.StringUtils; +import com.luqj.util.assertion.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; +import java.util.regex.Pattern; + +/** + * 语法解析器 + * + * @author chenzm + */ +public class SyntaxParse { + + /** + * 函数集合 + **/ + private Set functionSet; + + /** + * 字段表达式 + **/ + private static final String fieldPattern = "(?<=\\[)[\\S\\s]*(?=\\])"; + + private static final Logger logger = LoggerFactory.getLogger(SyntaxParse.class); + + protected SyntaxParse(Set functionSet) { + this.functionSet = functionSet; + } + + public static SyntaxParse createSyntaxParse(Set functionSet) { + return new SyntaxParse(functionSet); + } + + /** + * 是否是数学算式 + * + * @param exp + * @return + */ + public SyntaxType getSyntaxType(String exp) { + exp = exp.trim(); + if (exp.startsWith(SymbolSet.SYMBOL_SQM) + || exp.startsWith(SymbolSet.SYMBOL_DQM)) { + return SyntaxType.Text; + } + + //判断是否是字段 + if (exp.startsWith("[") && exp.endsWith("]") && Pattern.compile(fieldPattern).matcher(exp).find()) { + return SyntaxType.Field; + } + + //判断是否是数字 + if (StringUtils.isNumber(exp)) { + return SyntaxType.Number; + } + + return null; + } + + /** + * 是否是运算符号 +, -, *, /, >, <, >=, <= + * + * @param c + * @return + */ + private boolean isArithmetic(Stack syntaxStack, CharBuffer preNode, String c) { + if (ArithmeticEnum.getArithmeticEnum(c) == null) { + return false; + } + //如果符号'-'前面的值不是数字,该符号不是减法符号‘-’而是负数符号‘-’ + if (ArithmeticEnum.subtract.isEqualBySymbol(c)) { + if (syntaxStack.peek().syntaxType == SyntaxType.Comma) { + return false; + } + if (syntaxStack.peek().syntaxType == SyntaxType.Func) { + return true; + } + SyntaxType preNodeType = createSyntaxNode(preNode, -1).syntaxType; + if (preNodeType == SyntaxType.Number || preNodeType == SyntaxType.Field) { + return true; + } + return false; + } + if (ArithmeticEnum.rb.isEqualBySymbol(c) || ArithmeticEnum.lb.isEqualBySymbol(c)) { + return false; + } + return true; + } + + /** + * 函数语法表达式解析 + * + * @param expression 语法表达式 eg:sum([b], sum([a], 1 , 2)) + * @return 语法树 + */ + public SyntaxNode syntaxParse(String expression) { + checkMissingBracket(expression); + + String c = ""; + int qmCount = 0;//引号次数 + int charPos = 0; + boolean isText = false; + CharBuffer buf = new CharBuffer(); + Stack syntaxStack = new Stack(); + for (char v : expression.toCharArray()) { + c += v; + if (c.equals(SymbolSet.SYMBOL_SQM) || c.equals(SymbolSet.SYMBOL_DQM)) { + qmCount = (qmCount + 1) % 2; + isText = qmCount == 1; + } + if ((ArithmeticEnum.lt.isEqualBySymbol(c) || ArithmeticEnum.gt.isEqualBySymbol(c)) + && SymbolSet.SYMBOL_EQ.equals("" + expression.charAt(charPos + 1))) { + charPos++; + continue; + } + if (isText) { + buf.addStr(c); + } else if (isArithmetic(syntaxStack, buf, c)) { + if (buf.isText()) { + syntaxStack.push(createSyntaxNode(buf, charPos)); + } + syntaxStack.push( + SyntaxNode.createNode(c.toCharArray(), + charPos, charPos + 1, SyntaxType.Arithmetic) + ); + buf.clear(); + } else if (ArithmeticEnum.lb.isEqualBySymbol(c)) { + /**如果没有函数名则产生一个虚拟的BAG节点'()' 比如1 + (1 + 2) 用于标识为了数据的先后计算 */ + syntaxStack.push(createSyntaxNode(buf, charPos)); + syntaxStack.push( + SyntaxNode.createNode(c.toCharArray(), + charPos, charPos + 1, SyntaxType.Arithmetic) + ); + buf.clear(); + } else if (ArithmeticEnum.rb.isEqualBySymbol(c)) { + if (buf.isText()) { + syntaxStack.push(createSyntaxNode(buf, charPos)); + buf.clear(); + } + mergeNode(syntaxStack); + SyntaxNode word = syntaxStack.pop(); + Stack nodeQueue = new Stack(); + while (!ArithmeticEnum.lb.isEqualBySymbol(word.getKey())) { + if (word.syntaxType != SyntaxType.Comma) + nodeQueue.push(word); + word = syntaxStack.pop(); + } + SyntaxNode parent = syntaxStack.pop(); + if (functionSet.contains(parent.getKey().toUpperCase())) { + parent.asFunc(); + } else if (parent.syntaxType == null) { + parent.syntaxType = SyntaxType.Bag; + } + while (nodeQueue.size() > 0) { + SyntaxNode child = nodeQueue.pop(); + if (child.startPos > parent.startPos) { + parent.addChild(child); + } else { + throw new IllegalArgumentException(charPos + "位置附近拼写错误"); + } + } + syntaxStack.push(parent); + } else if (SymbolSet.SYMBOL_COMMA.equals(c)) { + if (buf.isText()) { + syntaxStack.push(createSyntaxNode(buf, charPos)); + buf.clear(); + } + mergeNode(syntaxStack); + syntaxStack.push( + SyntaxNode.createNode(c.toCharArray(), + charPos, charPos + 1, SyntaxType.Comma) + ); + } else { + buf.addStr(c); + } + c = ""; + charPos++; + } + return syntaxStack.pop(); + } + + /** + * 遇到逗号和左括号时候 则寻找FunctionFormula节点将其合并 + * + * @param syntaxStack + * @return + */ + private SyntaxNode mergeNode(Stack syntaxStack) { + SyntaxNode t = null; + while (syntaxStack.size() > 1 && + syntaxStack.get(syntaxStack.size() - 2).syntaxType == SyntaxType.Arithmetic && + !ArithmeticEnum.lb.isEqualBySymbol(syntaxStack.get(syntaxStack.size() - 2).getKey())) { + if (t == null) { + t = SyntaxNode.createNode(null, -1, -1, SyntaxType.FunctionFormula); + } + //操作值 + SyntaxNode val = syntaxStack.pop(); + t.addChild(0, val); + + //操作符号 + SyntaxNode arithmetic = syntaxStack.pop(); + t.addChild(0, arithmetic); + } + if (t != null && t.exitsChild()) { + t.startPos = t.firstChild().startPos; + t.endPos = t.lastChild().startPos; + } + if (t != null) { + //操作值 + t.addChild(0, syntaxStack.pop()); + syntaxStack.push(t); + } + return t; + } + + /** + * 创建语法节点 + * + * @return + */ + private SyntaxNode createSyntaxNode(CharBuffer func, int charPos) { + SyntaxNode node = SyntaxNode.createNode(func.toArray(), charPos - func.size(), charPos); + node.syntaxType = getSyntaxType(node.getKey()); + return node; + } + + /** + * 获取后缀语法堆栈 + * + * @param root + * @return + */ + public static List suffixSyntaxStack(SyntaxNode root) { + Assert.logic(root.syntaxType == SyntaxType.FunctionFormula, + "[" + root.toString() + "]不是函数算式表达式"); + + Stack symbolStack = new Stack(); + List outputQueue = new LinkedList(); + for (SyntaxNode syntaxNode : syntaxStack(root)) { + if (ArithmeticEnum.rb.isEqualBySymbol(syntaxNode.getKey()) + && syntaxNode.syntaxType == SyntaxType.Arithmetic) { + SyntaxNode sbl = symbolStack.pop(); + while (!ArithmeticEnum.lb.isEqualBySymbol(sbl.getKey())) { + outputQueue.add(sbl); + sbl = symbolStack.pop(); + } + } else if (syntaxNode.syntaxType == SyntaxType.Arithmetic) { + while (symbolStack.size() > 0 && + ArithmeticEnum.getSymbolLevel(syntaxNode.getKey()) <= ArithmeticEnum.getSymbolLevel(symbolStack.peek().getKey()) && + !ArithmeticEnum.lb.isEqualBySymbol(symbolStack.peek().getKey())) { + outputQueue.add(symbolStack.pop()); + } + symbolStack.push(syntaxNode); + } else { + outputQueue.add(syntaxNode); + } + } + while (symbolStack.size() > 0) { + outputQueue.add(symbolStack.pop()); + } + return outputQueue; + } + + /** + * 获取中缀语法栈 + * + * @param root + * @return + */ + public static List syntaxStack(SyntaxNode root) { + List dataList = new LinkedList(); + if (root.syntaxType != SyntaxType.FunctionFormula && root.syntaxType != SyntaxType.Bag) { + dataList.add(root); + } + if (root.exitsChild()) { + if (root.syntaxType == SyntaxType.Bag) { + dataList.add( + SyntaxNode.createNode(ArithmeticEnum.lb.getSymbol().toCharArray(), + root.startPos, root.startPos + 1, SyntaxType.Arithmetic) + ); + } + for (SyntaxNode child : root.childs()) { + //如果是函数把它看成一个整体, 例如 1 + 2 + MAX(10, 15) 把 'MAX(10, 5)' 当成一个整体 (代元法) + if (child.syntaxType == SyntaxType.Func) { + dataList.add(child); + } else { + dataList.addAll(syntaxStack(child)); + } + } + if (root.syntaxType == SyntaxType.Bag) { + dataList.add( + SyntaxNode.createNode(ArithmeticEnum.rb.getSymbol().toCharArray(), + root.endPos - 1, root.endPos, SyntaxType.Arithmetic) + ); + } + } + return dataList; + } + + /** + * 是否缺失括号 + * + * @return + */ + private void checkMissingBracket(String expression) { + int l = 0, r = 0; + Map> symbolPos = SymbolSet.getSymBolPos(expression); + int charPos = 0; + for (char c : expression.toCharArray()) { + if (ArithmeticEnum.lb.isEqualBySymbol(c) && + !SymbolSet.isInSymbol(symbolPos, charPos, SymbolSet.SYMBOL_SQM, SymbolSet.SYMBOL_DQM)) + l++; + else if (ArithmeticEnum.rb.isEqualBySymbol(c) && + !SymbolSet.isInSymbol(symbolPos, charPos, SymbolSet.SYMBOL_SQM, SymbolSet.SYMBOL_DQM)) + r++; + charPos++; + } + if (l != r) + throw new IllegalArgumentException(l < r ? "缺失左括号" : "缺失右括号"); + } + + /** + * 语法节点 + * + * @author chenzm + */ + public static class SyntaxNode { + CharBuffer buffer = null; + + private List childs = new ArrayList(); + + int startPos; + + int endPos; + + /** + * 判断参数是否是数学算式 + */ + SyntaxType syntaxType = null; + + public SyntaxNode(char[] chars, int start, int end, SyntaxType syntaxType) { + buffer = new CharBuffer(chars); + this.startPos = start; + this.endPos = end; + this.syntaxType = syntaxType; + } + + public String getKey() { + return StringUtils.trim(new String(buffer.toArray()), SymbolSet.SYMBOL_NULL); + } + + public void asFunc() { + this.syntaxType = SyntaxType.Func; + } + + public List childs() { + return this.childs; + } + + /** + * 是否是数学算式表达式 + * + * @return + */ + public SyntaxType syntaxType() { + return this.syntaxType; + } + + public boolean exitsChild() { + if (this.childs == null || this.childs.size() == 0) { + return false; + } + return true; + } + + public SyntaxNode firstChild() { + if (!exitsChild()) return null; + return this.childs.get(0); + } + + public SyntaxNode lastChild() { + if (!exitsChild()) return null; + return this.childs.get(this.childs.size() - 1); + } + + public void addChild(SyntaxNode child) { + addChild(this.childs == null ? 0 : this.childs.size(), child); + } + + public void addChild(int index, SyntaxNode child) { + Assert.notNull(child.syntaxType, "【KEY:" + child.getKey() + ",TYPE:" + child.syntaxType + "】是未知的类型节点"); + this.childs.add(index, child); + } + + public static SyntaxNode createNode(char[] str, int start, int end) { + return new SyntaxNode(str, start, end, null); + } + + public static SyntaxNode createNode(char[] str, int start, int end, SyntaxType type) { + return new SyntaxNode(str == null ? new char[]{} : str, start, end, type); + } + + public void setKey(String key) { + this.buffer.clear(); + for (char c : key.toCharArray()) { + this.buffer.add(c); + } + this.endPos = this.startPos + key.length(); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + toString(this, builder); + return builder.toString(); + } + + private void toString(SyntaxNode node, StringBuilder builder) { + if (node.syntaxType == SyntaxType.Func) { + builder.append(node.getKey() + "("); + if (node.childs != null) { + for (int i = 0; i < node.childs().size(); i++) { + if (i != 0) { + builder.append(","); + } + toString(node.childs().get(i), builder); + } + } + builder.append(")"); + } else { + builder.append(node.getKey()); + } + } + + public static void showTree(SyntaxNode tree) { + StringBuilder builder = new StringBuilder(); + showTree(0, tree, builder); + logger.debug(builder.toString()); + } + + private static void showTree(int level, SyntaxNode tree, StringBuilder builder) { + builder.append("\n"); + for (int i = 0; i < level; i++) { + builder.append("----"); + } + builder.append(tree.getKey() + " " + tree.syntaxType()); + if (tree.childs != null) { + for (SyntaxNode child : tree.childs) { + showTree(level + 1, child, builder); + } + } + } + } + + /** + * 算式类型 + * + * @author chenzm + */ + public enum SyntaxType { + + /** + * 函数算式表达式(组合节点) + * eg:MAX(1,2,3,[A]) > 12 + 5 , 1+2+3+4 或者 [A] + [B] + 1 + 2 + */ + FunctionFormula("函数算式表达式"), + + Func("函数"), + + Field("字段"), + + Text("文本"), + + Number("数字"), + + //左右括号 eg: (1 + 3) + Bag("包"), + + Arithmetic("算术符号"), + + Comma("逗号"); + + private String desc; + + SyntaxType(String desc) { + this.desc = desc; + } + + public String getDesc() { + return this.desc; + } + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/loader/BaseClassLoader.java b/luqj-plugin/src/main/java/org/code/modules/plugins/loader/BaseClassLoader.java new file mode 100644 index 0000000..71f7b93 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/loader/BaseClassLoader.java @@ -0,0 +1,129 @@ +package org.code.modules.plugins.loader; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.URL; +import java.net.URLClassLoader; + +public class BaseClassLoader extends URLClassLoader { + + private static final Logger log = LoggerFactory.getLogger(BoundClassLoader.class); + + protected String name; + + protected String version; + + /** + * 判断是否需要加载父亲 + */ + protected boolean findParent = true; + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public boolean isFindParent() { + return findParent; + } + + public void setFindParent(boolean findParent) { + this.findParent = findParent; + } + + public BaseClassLoader(URL[] url, + ClassLoader classLoader, String[] patterns) { + super(url, classLoader); + } + + + public BaseClassLoader(URL[] url, + ClassLoader classLoader) { + super(url, classLoader); + } + + public BaseClassLoader(URL[] url, + ClassLoader classLoader, String name, String[] patterns) { + super(url, classLoader); + this.name = name; + } + + + @Override + protected Class loadClass(String className, boolean resolve) + throws ClassNotFoundException { + return loadClassThisFirst(className, resolve); + } + + protected Class loadClassThisFirst(String className, boolean resolve) + throws ClassNotFoundException { + if (findParent) { + // 首先从本身加载,找不到的从父亲加载 + try { + return loadClassFromThis(className, resolve); + } catch (ClassNotFoundException e) { + //e.printStackTrace(); + // ignore + } catch (NoClassDefFoundError e) { + //e.printStackTrace(); + // ignore + } + return loadClassFromParent(className, resolve); + } else { + return loadClassFromThis(className, resolve); + } + + } + + + public Class loadClassFromParent(String className, boolean resolve) throws ClassNotFoundException { + Class clz; + if ((clz = getParent().loadClass(className)) != null) { + if (log.isTraceEnabled()) { + log.trace(className + "从父加载器加载"); + } + if (resolve) { + resolveClass(clz); + } + return clz; + } + throw new ClassNotFoundException("Could not find :" + className); + } + + public synchronized Class loadClassFromThis(String className, boolean resolve) throws ClassNotFoundException { + Class clz = null; + if ((clz = findLoadedClass(className)) != null) { + if (log.isTraceEnabled()) { + log.trace(this + className + "已经从自身加载器加载"); + } + if (resolve) { + resolveClass(clz); + } + return clz; + } + if ((clz = findClass(className)) != null) { + if (log.isTraceEnabled()) { + log.trace(this + className + "正在从自身加载器加载"); + } + if (resolve) { + resolveClass(clz); + } + return clz; + } + return clz; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/loader/BoundClassLoader.java b/luqj-plugin/src/main/java/org/code/modules/plugins/loader/BoundClassLoader.java new file mode 100644 index 0000000..c53179f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/loader/BoundClassLoader.java @@ -0,0 +1,61 @@ +package org.code.modules.plugins.loader; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashSet; +import java.util.Set; + +public class BoundClassLoader extends ClassLoader { + + private static final Logger log = LoggerFactory.getLogger(BoundClassLoader.class); + + private Set importClassLoader = new HashSet(); + + public void addImportLoader(PluginClassLoader loader) { + this.importClassLoader.add(loader); + } + + + public BoundClassLoader() { + super(); + } + + + public BoundClassLoader(ClassLoader parent) { + super(parent); + } + + @Override + public Class loadClass(String className) + throws ClassNotFoundException { + return loadClass(className, false); + } + + + @Override + protected Class loadClass(String className, boolean resolve) + throws ClassNotFoundException { + return loadClassFromImports(className, resolve); + } + + + protected Class loadClassFromImports(String className, boolean resolve) throws ClassNotFoundException { + Class clz = null; + for (PluginClassLoader loader : this.importClassLoader) { + clz = loader.loadClass(className, false); + if (clz != null) { + if (log.isTraceEnabled()) { + log.trace(className + "从" + loader + "加载"); + } + if (resolve) { + resolveClass(clz); + } + break; + } + } + return clz; + } + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/loader/PluginClassLoader.java b/luqj-plugin/src/main/java/org/code/modules/plugins/loader/PluginClassLoader.java new file mode 100644 index 0000000..a581e6f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/loader/PluginClassLoader.java @@ -0,0 +1,96 @@ +package org.code.modules.plugins.loader; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +public class PluginClassLoader extends BaseClassLoader { + + private static final Logger log = LoggerFactory.getLogger(BoundClassLoader.class); + + private final List patterns; + + public PluginClassLoader(URL[] url, ClassLoader classLoader, + String[] patterns) { + super(url, classLoader); + this.patterns = initPatterns(patterns); + } + + public void addURL(URL url) { + super.addURL(url); + } + + public void addURLs(URL[] urls) { + for (URL url : urls) { + super.addURL(url); + } + } + + public PluginClassLoader(ClassLoader classLoader) { + super(new URL[]{}, classLoader); + this.patterns = initPatterns(null); + } + + public PluginClassLoader(URL[] url, ClassLoader classLoader) { + super(url, classLoader); + this.patterns = initPatterns(null); + } + + public PluginClassLoader(URL[] url, ClassLoader classLoader, String name, + String[] patterns) { + super(url, classLoader); + this.name = name; + this.patterns = initPatterns(patterns); + } + + private List initPatterns(String[] patterns) { + List result = new ArrayList(); + if (patterns != null) { + for (String pattern : patterns) { + result.add(Pattern.compile(pattern)); + } + } + return result; + } + + @Override + public Class loadClass(String className) throws ClassNotFoundException { + return loadClass(className, false); + } + + @Override + protected synchronized Class loadClass(String className, boolean resolve) + throws ClassNotFoundException { + for (Pattern pattern : patterns) { + if (pattern.matcher(className).matches()) { + return loadClassParentFirst(className, resolve); + } else { + return loadClassThisFirst(className, resolve); + } + } + return loadClassThisFirst(className, resolve); + } + + private Class loadClassParentFirst(String arg0, boolean arg1) + throws ClassNotFoundException { + try { + return loadClassFromParent(arg0, arg1); + } catch (ClassNotFoundException e) { + // ignore + } catch (NoClassDefFoundError e) { + // ignore + } + return loadClassFromThis(arg0, arg1); + } + + + @Override + public String toString() { + return "[" + name + "." + version + "]加载器"; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/meta/AbstractPluginMetaBackup.java b/luqj-plugin/src/main/java/org/code/modules/plugins/meta/AbstractPluginMetaBackup.java new file mode 100644 index 0000000..4b92875 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/meta/AbstractPluginMetaBackup.java @@ -0,0 +1,11 @@ +package org.code.modules.plugins.meta; + +import org.code.modules.plugins.service.IPluginMetaBackup; + +/** + * + * @author xufm + * @date 2018/4/2 + */ +public abstract class AbstractPluginMetaBackup implements IPluginMetaBackup { +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/meta/BackupMeta.java b/luqj-plugin/src/main/java/org/code/modules/plugins/meta/BackupMeta.java new file mode 100644 index 0000000..bd51a66 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/meta/BackupMeta.java @@ -0,0 +1,12 @@ +package org.code.modules.plugins.meta; + +import java.io.Serializable; + +/** + * 备份对象 + * @author xufm + * @date 2018/5/28 + */ +public abstract class BackupMeta implements Serializable{ + private static final long serialVersionUID = 7600345767838450122L; +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/meta/PluginMeta.java b/luqj-plugin/src/main/java/org/code/modules/plugins/meta/PluginMeta.java new file mode 100644 index 0000000..9a4092c --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/meta/PluginMeta.java @@ -0,0 +1,89 @@ +package org.code.modules.plugins.meta; + +import org.code.modules.plugins.annotation.PluginAttribute; + +import java.io.Serializable; + + +/** + * 元数据信息 基础字段 + * Created by chenzm on 2016/12/29. + */ +public abstract class PluginMeta implements Serializable{ + @PluginAttribute(name="是否增量") + protected String isIncrement; + + @PluginAttribute(name="增量字段") + protected String insertTime; + + @PluginAttribute(name="更新字段") + protected String updateTime; + + @PluginAttribute(name="异常策略") + protected String exceptionStrategy; + + @PluginAttribute(name="版本") + protected String version; + + @PluginAttribute(name="软件英文名") + protected String softwareCode; + + @PluginAttribute(name="对象ID") + protected String modelElementId; + + public String getIsIncrement() { + return isIncrement; + } + + public void setIsIncrement(String isIncrement) { + this.isIncrement = isIncrement; + } + + public String getInsertTime() { + return insertTime; + } + + public void setInsertTime(String insertTime) { + this.insertTime = insertTime; + } + + public String getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(String updateTime) { + this.updateTime = updateTime; + } + + public String getExceptionStrategy() { + return exceptionStrategy; + } + + public void setExceptionStrategy(String exceptionStrategy) { + this.exceptionStrategy = exceptionStrategy; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getSoftwareCode() { + return softwareCode; + } + + public void setSoftwareCode(String softwareCode) { + this.softwareCode = softwareCode; + } + + public String getModelElementId() { + return modelElementId; + } + + public void setModelElementId(String modelElementId) { + this.modelElementId = modelElementId; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/model/PluginBeanMeta.java b/luqj-plugin/src/main/java/org/code/modules/plugins/model/PluginBeanMeta.java new file mode 100644 index 0000000..3869fde --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/model/PluginBeanMeta.java @@ -0,0 +1,53 @@ +package org.code.modules.plugins.model; + + +import org.code.modules.plugins.loader.PluginClassLoader; + +public class PluginBeanMeta { + private String beanName; + private String className; + private String version; + private PluginClassLoader classLoader; + + + public void setVersion(String version) { + this.version = version; + } + + public PluginBeanMeta(String beanName, String className, + PluginClassLoader classLoader) { + super(); + this.beanName = beanName; + this.className = className; + this.classLoader = classLoader; + } + + public String getBeanName() { + return beanName; + } + + public void setBeanName(String beanName) { + this.beanName = beanName; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public PluginClassLoader getClassLoader() { + return classLoader; + } + + + public String getVersion() { + return version; + } + + public void setClassLoader(PluginClassLoader classLoader) { + this.classLoader = classLoader; + } +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/plugin/IIdentifierGenerator.java b/luqj-plugin/src/main/java/org/code/modules/plugins/plugin/IIdentifierGenerator.java new file mode 100644 index 0000000..18b2c19 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/plugin/IIdentifierGenerator.java @@ -0,0 +1,10 @@ +package org.code.modules.plugins.plugin; + +import java.io.Serializable; + +/** + * Created by chenzm on 2017/5/9. + */ +public interface IIdentifierGenerator extends Serializable{ + String generate(IRow row); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/plugin/IRow.java b/luqj-plugin/src/main/java/org/code/modules/plugins/plugin/IRow.java new file mode 100644 index 0000000..2f56409 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/plugin/IRow.java @@ -0,0 +1,30 @@ +package org.code.modules.plugins.plugin; + + +import com.luqj.util.MultiValueMap; + +/** + * 数据行接口 + * Created by chenzm on 2017/1/6. + */ +public interface IRow extends MultiValueMap { + + K rowId(); + + + boolean isEndRow(); + + /** + * 是否是数据块的最后一条 + * @return + */ + boolean isLastRowForDataSet(); + + /** + * 获取源头的id + * @return 如果是一生多,this为多的一方,sourceId者为少的一方,否则为NULL; + */ + K getSourceId(); + + void setIdentifierGenerator(IIdentifierGenerator generator); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/IBeanFactory.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IBeanFactory.java new file mode 100644 index 0000000..3d7c065 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IBeanFactory.java @@ -0,0 +1,32 @@ +package org.code.modules.plugins.service; + + +public interface IBeanFactory { + + /** + * 获得Spring容器中的对象 + * @param beanName + * beanName + * @return Object + */ + abstract Object getBean(String beanName); + + abstract boolean containsBean(String beanName); + + void injectBean(Object obj); + + void injectBean(Object obj, String version); + + /** + * 自动装配一个Bean对象 + * autowireComponent + * @param bean + * bean + */ + abstract void autowireComponent(Object bean); + + T getBean(String beanName, Class beanClass); + + T getBean(String beanName, String version, Class beanClass); + +} \ No newline at end of file diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginMetaBackup.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginMetaBackup.java new file mode 100644 index 0000000..b571bb3 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginMetaBackup.java @@ -0,0 +1,22 @@ +package org.code.modules.plugins.service; + + +import org.code.modules.plugins.meta.BackupMeta; +import org.code.modules.plugins.meta.PluginMeta; + +public interface IPluginMetaBackup { + + /** + * 备份对应插件所关联的元库信息或者其他信息 + * 如果没有这些信息只需空实现即可 + * @param pluginMeta 备份对象 + * @return 备份对象 + */ + T dataBackup(M pluginMeta); + + /** + * 获取备份对象 + * @param backupMeta backupMeta + */ + void recover(T backupMeta); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginMetaRegisterService.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginMetaRegisterService.java new file mode 100644 index 0000000..49e22b8 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginMetaRegisterService.java @@ -0,0 +1,11 @@ +package org.code.modules.plugins.service; + +/** + * 插件元数据信息 + */ +public interface IPluginMetaRegisterService { + + void resetPluginMeta(Class pluginBeanMeta); + + T _savePluginMeta(Class pluginBeanMeta); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginRegistMethod.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginRegistMethod.java new file mode 100644 index 0000000..247ae74 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginRegistMethod.java @@ -0,0 +1,27 @@ +package org.code.modules.plugins.service; + + +import org.code.modules.plugins.loader.PluginClassLoader; +import org.code.modules.plugins.model.PluginBeanMeta; + +public interface IPluginRegistMethod { + + /** + * 需要注册的类 + * + * @return + */ + Class[] typeFilters(); + + boolean filter(Class clazz); + + + /** + * 对class文件进行信息封装 + * + * @param clazz + * @return + */ + PluginBeanMeta regist(PluginClassLoader loader, Class clazz); + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginRegistry.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginRegistry.java new file mode 100644 index 0000000..dccb65b --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IPluginRegistry.java @@ -0,0 +1,21 @@ +package org.code.modules.plugins.service; + +import org.code.modules.plugins.loader.PluginClassLoader; + +public interface IPluginRegistry { + + void init(); + + boolean containsPluginBean(String beanName); + + PluginClassLoader getClassLoader(String code, String version); + + Object instancePluginBean(String beanName); + + T instancePluginBean(String beanName, Class classType); + + void clear(); + + T instancePluginBean(String beanName, String version, Class classType); + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/IllegalPluginException.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IllegalPluginException.java new file mode 100644 index 0000000..494c9b5 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/IllegalPluginException.java @@ -0,0 +1,22 @@ +package org.code.modules.plugins.service; + + +public class IllegalPluginException extends RuntimeException{ + + public IllegalPluginException() { + super(); + } + + public IllegalPluginException(String message, Throwable cause) { + super(message, cause); + } + + public IllegalPluginException(String message) { + super(message); + } + + public IllegalPluginException(Throwable cause) { + super(cause); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/DefPluginRegistry.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/DefPluginRegistry.java new file mode 100644 index 0000000..78cd17a --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/DefPluginRegistry.java @@ -0,0 +1,538 @@ +package org.code.modules.plugins.service.impl; + + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.luqj.util.FileSystemUtil; +import com.luqj.util.StringUtils; +import com.luqj.util.Validator; +import com.luqj.util.assertion.Assert; +import org.code.modules.plugins.loader.PluginClassLoader; +import org.code.modules.plugins.model.PluginBeanMeta; +import org.code.modules.plugins.service.IPluginRegistMethod; +import org.code.modules.plugins.service.IPluginRegistry; +import org.code.modules.plugins.service.IllegalPluginException; +import org.apache.commons.io.FileUtils; +import com.luqj.util.reflect.ClassUtils; +import com.luqj.util.reflect.JarUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.*; + +@Service("defPluginRegistry") +public class DefPluginRegistry implements IPluginRegistry { + private static final String PLUGIN_HOME = "PLUGIN_HOME"; + + private static final Logger LOGGER = LoggerFactory.getLogger(DefPluginRegistry.class); + /** + * 添加支持通过环境变量配置 plugin home [插件目录] + */ + private static final String BASE_DIR = System.getenv(PLUGIN_HOME); + + private Set registMethods = Sets.newHashSet(); + @Autowired + private PluginBeanRegister pluginRegistMethod; + @Autowired + private FuncBeanRegister funcBeanRegister; + @Autowired + private TypeMappingBeanRegister typeMappingBeanRegister; + + @Value("${plugin.base.dir:D://luqj-plugins}") + private String baseDir; + + private String pageDir; + + @PostConstruct + public void initBean() { + registMethods.add(typeMappingBeanRegister); + registMethods.add(pluginRegistMethod); + registMethods.add(funcBeanRegister); + } + + /** + * 加载器集合【插件code,version,loader】 + */ + private Map> classLoaderMap = Maps.newHashMap(); + + /** + * 【插件code,version,loader】pluginBean集合 + */ + private Map> pluginBeans = Maps.newHashMap(); + + + private Set allClassLoaders = Sets.newHashSet(); + + private Set analysisJar = Sets.newHashSet(); + + // 为什么要用 apache common 的 HashedMap? + private Map thirdPluginMap = Maps.newHashMap(); + + private void addPluginBeanMeta(String beanName, PluginBeanMeta pluginBeanMeta) { + if (this.pluginBeans.containsKey(beanName)) { + this.pluginBeans.get(beanName).put(pluginBeanMeta.getVersion(), pluginBeanMeta); + } else { + Map versions = Maps.newHashMap(); + versions.put("def", pluginBeanMeta); + LOGGER.trace("新增插件对象:{} V def", beanName); + versions.put(pluginBeanMeta.getVersion(), pluginBeanMeta); + LOGGER.trace("新增插件对象:{} V {}", beanName, pluginBeanMeta.getVersion()); + this.pluginBeans.put(beanName, versions); + } + + } + + public Object instancePluginBean(String beanName) { + return instancePluginBean(beanName, Object.class); + } + + @Deprecated + public Object instancePluginBean(String beanName, String version) { + return instancePluginBean(beanName, Object.class); + } + + public boolean containsPluginBean(String beanName) { + return this.pluginBeans.containsKey(beanName); + } + + public T instancePluginBean(String beanName, String version, Class classType) { + try { + if (!Validator.hasText(version)) { + version = "def"; + } + if (this.pluginBeans.containsKey(beanName)) { + PluginBeanMeta beanMeta = this.pluginBeans.get(beanName).get(version); + + LOGGER.trace("初始化实例[{}],版本[{}]", beanName, version); + return (T) beanMeta.getClassLoader().loadClass(beanMeta.getClassName()).newInstance(); + } + } catch (Exception e) { + //如果插件bean里有包含,初始化实例出错打出报错信息 + if (this.pluginBeans.containsKey(beanName)) { + LOGGER.error("初始化实例[{}],版本[{}]异常,异常信息{}", beanName, version, e); + } + //忽略 + LOGGER.trace("pluginBean集合找不到类" + beanName); + } + + // 如果已经设置了加载器,先从本身线程的加载器里找 + if (Thread.currentThread().getContextClassLoader() instanceof PluginClassLoader) { + PluginClassLoader loader = (PluginClassLoader) Thread.currentThread().getContextClassLoader(); + try { + T obj = (T) loader.loadClassFromThis(beanName, false).newInstance(); + if (classType.isInstance(obj)) { + return obj; + } else { + Assert.fail("[" + beanName + "]类加载器不一致,[" + obj.getClass().getClassLoader() + " != " + classType.getClassLoader() + "]"); + return null; + } + } catch (InstantiationException | IllegalAccessException e) { + throw new IllegalPluginException(beanName + "实例化异常,异常消息[" + e.getMessage() + "]", e); + } catch (ClassNotFoundException e) { + LOGGER.trace("当前类加载器{}找不到{}", loader, beanName); + } catch (Throwable e) { + LOGGER.trace(e.getMessage(), loader, beanName); + } + } + T defClassLoader = null; + for (PluginClassLoader loader : allClassLoaders) { + try { + T obj = (T) loader.loadClassFromThis(beanName, false).newInstance(); + + if (classType.isInstance(obj)) { + return obj; + } else { + Assert.fail("[" + beanName + "]类加载器不一致,[" + obj.getClass().getClassLoader() + " != " + classType.getClassLoader() + "]"); + } + defClassLoader = obj; + if (!"def".equals(version) && loader.getVersion().equals(version)) { + return obj; + } + if ("def".equals(version)) { + return obj; + } + } catch (InstantiationException | IllegalAccessException e) { + throw new IllegalPluginException(beanName + "实例化异常,异常消息[" + e.getMessage() + "]", e); + } catch (ClassNotFoundException e) { + LOGGER.trace("类加载器{}找不到{}", loader, beanName); + } catch (Throwable e) { + LOGGER.trace(e.getMessage(), loader, beanName); + } + } + if (null != defClassLoader) { + return defClassLoader; + } + try { + T obj = (T) Thread.currentThread().getContextClassLoader().loadClass(beanName).newInstance(); + return obj; + } catch (Exception ignore) { + LOGGER.trace(ignore.getMessage(), beanName); + } + LOGGER.debug("加载器也找不到类{}", beanName); + return null; + } + + public T instancePluginBean(String beanName, Class classType) { + try { + if (this.pluginBeans.containsKey(beanName)) { + PluginBeanMeta beanMeta = this.pluginBeans.get(beanName).get("def"); + return (T) beanMeta.getClassLoader().loadClass(beanMeta.getClassName()).newInstance(); + } + } catch (Exception e) { + //忽略 + LOGGER.trace("pluginBean集合找不到类:{}", beanName); + } + for (PluginClassLoader loader : allClassLoaders) { + try { + return (T) loader.loadClassFromThis(beanName, false).newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + throw new IllegalPluginException(beanName + "实例化异常,异常消息[" + e.getMessage() + "]", e); + } catch (ClassNotFoundException e) { + LOGGER.trace("{} 找不到 {}", loader, beanName); + } + } + try { + return (T) Thread.currentThread().getContextClassLoader().loadClass(beanName).newInstance(); + } catch (Exception e) { + //忽略 + } + LOGGER.warn("加载器也找不到类:{}", beanName); + return null; + } + + @Override + public void clear() { + + } + public void init() { + if (!Validator.hasText(this.baseDir)) { + this.baseDir = BASE_DIR; + } + final String TARGET = "target/classes/"; + final String WEB_INF = "WEB-INF/classes/"; + final String TEST_TARGET = "target/test-classes/"; + if (!Validator.hasText(this.pageDir)) { + String classDir = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + if (classDir.endsWith(TARGET)) { + this.pageDir = classDir.substring(0, classDir.length() - TARGET.length()) + "target" + File.separator + "mistWebTmp" + File.separator; + } else if (classDir.endsWith(TEST_TARGET)) { + this.pageDir = classDir.substring(0, classDir.length() - TEST_TARGET.length()) + "target/classes/META-INF/resources/"; + } else { + if(classDir.length() > WEB_INF.length()) { + this.pageDir = classDir.substring(0, classDir.length() - WEB_INF.length()); + }else{ + this.pageDir = classDir; + } + } + } + + //获取到软件表中的所有软件信息 plugin下的一级子目录[软件目录] + File[] codeFiles = new File(baseDir).listFiles(pluginFileFilter); + if (codeFiles == null || codeFiles.length == 0) { + LOGGER.error("插件目录:[" + baseDir + "]为空!"); + return; + } + for (File codeFile : codeFiles) { + // plugin下的二级子目录[版本目录] + File[] versionFiles = codeFile.listFiles(pluginFileFilter); + if (versionFiles == null || versionFiles.length == 0) { + continue; + } + for (File versionFile : versionFiles) { + registPlugin(codeFile.getName(), versionFile.getName()); + } + } + //第三方开发平台使用 + addDevPlugin(); + } + + + /** + * 添加开发平台插件 + */ + private void addDevPlugin() { + for (String packageName : thirdPluginMap.keySet()) { + String code = packageName.substring(packageName.lastIndexOf(".") + 1); + String version = thirdPluginMap.get(packageName); + Map pluginMap = Maps.newHashMap(); + try { + String pluginDir = code + File.separator + version; + PluginClassLoader pluginClassLoader = new PluginClassLoader( + getClassURL(baseDir, pluginDir), + Thread.currentThread().getContextClassLoader()); + pluginClassLoader.setName(code); + pluginClassLoader.setVersion(version); + List classNames = ClassUtils.getClasssFromPackage(packageName); + addPluginInit(classNames, version, pluginClassLoader); + pluginMap.put(version, pluginClassLoader); + classLoaderMap.put(code, pluginMap); + allClassLoaders.add(pluginClassLoader); + } catch (Exception e) { + LOGGER.warn(e.getMessage(), e); + } + } + } + + private final static FileFilter pluginFileFilter = new FileFilter() { + @Override + public boolean accept(File file) { + return file.isDirectory() && !file.isHidden(); + } + }; + + public PluginClassLoader getClassLoader(String code, String version) { + Assert.logic(classLoaderMap.containsKey(code), "容器找不到指定插件名称[" + code + "]的类"); + return classLoaderMap.get(code).get(version); + } + + public void registPlugin(String code, String version) { + try { + //已经加载过 + if (classLoaderMap.containsKey(code)) { + PluginClassLoader loader = createClassLoader(code, version); + classLoaderMap.get(code).put(version, loader); + allClassLoaders.add(loader); + } else { + Map pluginMap = Maps.newHashMap(); + PluginClassLoader loader = createClassLoader(code, version); + pluginMap.put(version, loader); + classLoaderMap.put(code, pluginMap); + allClassLoaders.add(loader); + } + LOGGER.debug("插件[{}.{}]加载成功!", code, version); + } catch (Exception e) { + LOGGER.error("插件注册出现异常,异常消息[{}]", e.getMessage(), e); + throw new IllegalPluginException("插件注册出现异常,异常消息[" + e.getMessage() + "]", e); + } + } + + + private PluginClassLoader createClassLoader(String code, String version) throws Exception { + String pluginDir = code + File.separator + version; + PluginClassLoader pluginClassLoader = new PluginClassLoader( + getClassURL(baseDir, pluginDir), + Thread.currentThread().getContextClassLoader()); + String path = "file:" + baseDir + File.separator + pluginDir + "/**/*.jar"; + ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(pluginClassLoader); + pluginClassLoader.setName(code); + pluginClassLoader.setVersion(version); + LOGGER.debug("{}开始加载。。。", code); + loadPath(code, version, resourcePatternResolver, path); + return pluginClassLoader; + } + + + /** + * 将符合条件的Bean以Class集合的形式返回 + * + * @throws IOException + * @throws ClassNotFoundException + */ + private void loadPath( + String code, + String version, + ResourcePatternResolver resourcePatternResolver, + String classPattern) throws IOException, ClassNotFoundException { + Resource[] resources = resourcePatternResolver.getResources(classPattern); + PluginClassLoader pcl = (PluginClassLoader) resourcePatternResolver.getClassLoader(); + String configPath = baseDir + File.separator + code + File.separator + version + File.separator + "config.properties"; + getAnalysisJar(configPath); + try { + for (Resource resource : resources) { + if (resource.isReadable() && analysisJar(resource.getFilename())) { + LOGGER.trace("解析JAR:{}", resource.getURL().getPath()); + Collection classNames = JarUtils.getAllClassInfo(resource.getURL().getPath()); + addPluginInit(classNames, version, pcl); + if (version.toUpperCase().equals("PAGE")) { + loadPage(resource.getURL().getPath(), pcl); + } + } + } + } catch (Throwable throwable) { + LOGGER.error("加载{}${}时候出错!", code, version, throwable); + } + } + + private void loadPage(String resourcePath, PluginClassLoader pcl) { + if (!Validator.hasText(this.pageDir)) { + Assert.fail("PageDir为空无法对【" + resourcePath + "】进行copy"); + } + Collection resources = JarUtils.getResources(resourcePath, "META-INF/resources"); + for (String r : resources) { + String urlPath = "jar:file:" + File.separator + resourcePath + "!" + File.separator + r; + File file = new File(this.pageDir + r.substring("META-INF/resources/".length(), r.length())); + if (file.exists()) { + file.delete(); + } + try { + URL url = pcl.getResource(r); + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + FileUtils.copyInputStreamToFile(url.openStream(), file); + } catch (MalformedURLException e) { + LOGGER.error("获取:{}出现异常", urlPath, e); + } catch (IOException e) { + + LOGGER.error("无法将[" + urlPath + "]copy到[" + file.getPath() + "]", e); + } + + } + } + + private void addPluginInit(Collection classNames, String version, PluginClassLoader pcl) throws ClassNotFoundException { + for (String cn : classNames) { + LOGGER.trace("解析类:{}", cn); + Class clazz = pcl.loadClass(cn); + for (IPluginRegistMethod filter : this.registMethods) { + if (filter.filter(clazz)) { + PluginBeanMeta beanMeta = filter.regist(pcl, clazz); + if (beanMeta != null) { + beanMeta.setVersion(version); + addPluginBeanMeta(beanMeta.getBeanName(), beanMeta); + } + } + } + } + } + + /** + * 判断是否需要加载 + * + * @param fileName + * @return + */ + private boolean analysisJar(String fileName) { + for (String analysis : analysisJar) { + String regex = analysis.replace("*", ".*"); + if (fileName.matches(regex)) { + return true; + } + } + return false; + } + + private void getAnalysisJar(String config) { + if (StringUtils.isBlank(config)) { + return; + } + File file = new File(config); + if (!file.isFile()) { + return; + } + Properties properties = null; + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + properties = new Properties(); + properties.load(fis); + String jarName = properties.getProperty("jarName"); + Boolean flag = Boolean.valueOf(properties.getProperty(getStringRemoveMess(properties, "isLoad"), "false")); + if (StringUtils.isNotBlank(jarName) && flag) { + String[] jarNames = jarName.split(","); + Collections.addAll(analysisJar, jarNames); + } + } catch (IOException e) { + LOGGER.warn("配置文件[{}]读取失败.", config, e); + } finally { + if (fis != null) { + try { + fis.close(); + } catch (IOException e) { + LOGGER.warn(e.getMessage(), e); + } + } + } + } + + /** + * 防止windowns生成的config文件首行乱码 + * + * @param properties + * @param key + * @return + */ + private String getStringRemoveMess(Properties properties, String key) { + Set propertyset = properties.keySet(); + for (Object o : propertyset) { + if (o.toString().endsWith("isLoad")) { + key = o.toString(); + } + } + return key; + } + + private static URL[] getClassURL(String baseDir, String pluginDir) throws Exception { + List result = Lists.newArrayList(); + File path = new File(baseDir + File.separator + pluginDir); + if (path.exists()) { + List files = FileSystemUtil.getAllFiles(path, false, null); + for (File file : files) { + result.add(file.toURI().toURL()); + LOGGER.trace("准备加载JAR:{}", file.toURI().toURL()); + } + } else { + LOGGER.warn("找不到指定路径{}", baseDir + File.separator + pluginDir); + } + return result.toArray(new URL[result.size()]); + } + + public String getBaseDir() { + return baseDir; + } + + public void setBaseDir(String baseDir) { + this.baseDir = baseDir; + } + + public static void main(String[] args) throws IOException, SecurityException, NoSuchMethodException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { + JarUtils.loadClass("C:\\plugin\\ORACLE\\11g\\etl-rdb-0.0.1-SNAPSHOT.jar", Thread.currentThread().getContextClassLoader()); + } + + public Set getAnalysisJar() { + return analysisJar; + } + + public void setAnalysisJar(Set analysisJar) { + this.analysisJar = analysisJar; + } + + public Set getRegistMethods() { + return registMethods; + } + + public void setRegistMethods(Set registMethods) { + this.registMethods = registMethods; + } + + public Map getThirdPluginMap() { + return thirdPluginMap; + } + + public void setThirdPluginMap(Map thirdPluginMap) { + this.thirdPluginMap = thirdPluginMap; + } + + public String getPageDir() { + return pageDir; + } + + public void setPageDir(String pageDir) { + this.pageDir = pageDir; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/FuncBeanRegister.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/FuncBeanRegister.java new file mode 100644 index 0000000..6170dbe --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/FuncBeanRegister.java @@ -0,0 +1,506 @@ +package org.code.modules.plugins.service.impl; + + +import com.google.common.collect.Lists; +import org.code.modules.plugins.function.annotation.FuncBean; +import org.code.modules.plugins.function.annotation.FuncMethod; +import org.code.modules.plugins.function.annotation.FuncParam; +import org.code.modules.plugins.function.annotation.FuncTypeEnum; +import org.code.modules.plugins.loader.PluginClassLoader; +import org.code.modules.plugins.model.PluginBeanMeta; +import org.code.modules.plugins.service.IPluginRegistMethod; +import org.code.modules.plugins.service.impl.function.FuncExample; +import org.code.modules.plugins.service.impl.function.FuncMeta; +import org.code.modules.plugins.service.impl.function.FuncParamMeta; +import org.code.modules.plugins.types.*; +import org.apache.commons.lang.StringUtils; +import com.luqj.util.Validator; +import com.luqj.util.reflect.ClassUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.util.Assert; + +import java.lang.reflect.Method; +import java.util.*; + +/** + * 函数元数据注册 + * Created by chenzm on 2017/11/23. + */ +@Service +public class FuncBeanRegister implements IPluginRegistMethod { + private Map> funcTree = new LinkedHashMap<>(); + private static final Logger logger = LoggerFactory.getLogger(FuncBeanRegister.class); + private Map funcMetas = new HashMap<>(); + private volatile boolean hasInitialized = false; + + @Override + public Class[] typeFilters() { + return new Class[]{FuncBean.class}; + } + + @Override + public boolean filter(Class clazz) { + FuncBean b = clazz.getAnnotation(FuncBean.class); + return b != null; + } + + @Override + public PluginBeanMeta regist(PluginClassLoader loader, Class clazz) { + FuncBean pb = (FuncBean) clazz.getAnnotation(FuncBean.class); + String beanName = Validator.hasText(pb.code()) ? pb.code() : ClassUtils.getDefBeanName(clazz); + try { + registerFuncMeta(clazz); + } catch (Exception e) { + + logger.error("函数元数据[" + clazz.getName() + "]注册失败", e); + } + return new PluginBeanMeta(beanName, clazz.getName(), loader); + } + + private FuncExample buildExamples(String input, String output, String memo) { + return new FuncExample("", input, memo, output); + } + + private FuncParamMeta buildParamMeta(Type type, String... args) { + FuncParamMeta param = new FuncParamMeta(); + param.setCode(args.length > 0 ? args[0] : "arg"); + param.setName(args.length > 1 ? args[1] : "参数"); + if (args.length > 2 && StringUtils.isNotBlank(args[2])) { + param.setMemo(args[2]); + } + if (args.length > 3 && StringUtils.isNotBlank(args[3])) { + param.setAny(Boolean.valueOf(args[3])); + } + if (args.length > 4 && StringUtils.isNotBlank(args[4])) { + param.setDefVal(args[4]); + } + param.setValType(type.getCode()); + param.setPrecision(type.getPrecsn()); + param.setLength(type.getLength()); + + return param; + } + + /** + * 注册函数元数据信息 + * + * @param clazz + * @param + */ + public void registerFuncMeta(Class clazz) { + if (logger.isDebugEnabled()) { + logger.debug(String.format("开始注册函数%s", clazz.getName())); + } + Assert.notNull(clazz, "函数元数据信息对象不能为空!"); + FuncBean funcBean = clazz.getAnnotation(FuncBean.class); + Assert.notNull(funcBean, String.format("%s必须要FuncBean注解", clazz.getName())); + for (Method method : clazz.getDeclaredMethods()) { + FuncMethod funcMethod = method.getAnnotation(FuncMethod.class); + if (funcMethod != null) { + FuncParamMeta outputParam = buildParamMeta(StdTypes.getStandardTypeByName("std." + funcMethod.outputParam().valType().name())); + FuncParamMeta[] inputParams = new FuncParamMeta[funcMethod.inputParams().length]; + String inputParamStr = ""; + for (int i = 0; i < funcMethod.inputParams().length; i++) { + FuncParam param = funcMethod.inputParams()[i]; + inputParams[i] = buildParamMeta( + StdTypes.getStandardTypeByName("std." + param.valType().name()), + param.code(), param.name(), param.name(), + String.valueOf(param.isAny()), param.defVal() + ); + inputParamStr = inputParamStr + ",[" + param.code() + "]"; + } + if (!funcMetas.containsKey(funcBean.code())) { + FuncMeta funcMeta = buildFuncMeta(funcBean.code(), + funcBean.name(), funcBean.clazz(), + funcBean.funcType(), funcBean.memo(), + null, null + ); + for (org.code.modules.plugins.function.annotation.FuncExample example : funcBean.examples()) { + if (StringUtils.isNotBlank(example.input())) { + funcMeta.addExample(new FuncExample(example.name(), example.input(), example.memo(), example.result())); + } + + } + funcMeta.setFuncMethodExample(funcMeta.getCode() + "(" + inputParamStr.replaceFirst(",", "") + ")"); + this.addFunc(funcBean.classifyDir(), funcMeta); + this.funcMetas.put(funcBean.code(), funcMeta); + } + this.funcMetas.get(funcBean.code()).setOutputParam(method.getName(), outputParam); + this.funcMetas.get(funcBean.code()).setInputParam(method.getName(), Arrays.asList(inputParams)); + } + } + } + + private void addFunc(String classifyDir, FuncMeta funcMeta) { + if (!this.funcTree.containsKey(classifyDir)) { + this.funcTree.put(classifyDir, new ArrayList()); + } + this.funcTree.get(classifyDir).add(funcMeta); + logger.debug(String.format("[code=%s, name=%s, class=%s]函数元数据信息注册成功", + funcMeta.getCode(), funcMeta.getName(), funcMeta.getClazz()) + ); + } + + private FuncMeta buildFuncMeta(String funcCode, String funcName, String clazz, FuncTypeEnum funcType, String memo, + FuncExample funcExample, FuncParamMeta outputParam, FuncParamMeta... inputParams) { + FuncMeta meta = new FuncMeta(); + meta.setCode(funcCode); + meta.setName(funcName); + meta.setClazz(clazz); + meta.setFuncType(funcType.getCode()); + meta.setMemo(memo); + if (outputParam != null) { + meta.setOutputParam(funcName, outputParam); + } + String inputParamStr = ""; + if (inputParams != null && inputParams.length > 0) { + for (int i = 0; i < inputParams.length; i++) { + inputParams[i].setArgPos(i); + inputParamStr = inputParamStr + ",[" + inputParams[i].getCode() + "]"; + } + meta.setInputParam(funcName, Arrays.asList(inputParams)); + } + if (funcExample != null) { + meta.addExample(funcExample); + } + + meta.setFuncMethodExample(funcCode + "(" + inputParamStr.replaceFirst(",", "") + ")"); + return meta; + } + + public synchronized Map> getFuncTree() { + if (hasInitialized) { + return this.funcTree; + } + + Map> typeMap = funcInitInfo(); + for (String classifyDir : typeMap.keySet()) { + for (FuncMeta funcMeta : typeMap.get(classifyDir)) { + this.addFunc(classifyDir, funcMeta); + } + } + hasInitialized = true; + return this.funcTree; + } + + /** + * 函数初始化信息 + * + * @return + */ + private Map> funcInitInfo() { + Map> typeMap = new LinkedHashMap>(); + List funcs = new ArrayList(); + + funcs.add(buildFuncMeta("REVERSE_LONG_TO_DATE", "时间戳转化为日期时间对象", "com.code.std.function.method.datetime.ReverseLongToDateFunc", FuncTypeEnum.NORMAL, "LONG>MAX-LONG的时间戳转化为日期时间对象", + buildExamples("REVERSE_LONG_TO_DATE(1511775486481,0)", "java.util.Date", "1511775486481转换为java.util.Date"), + buildParamMeta(ObjType.BASE), buildParamMeta(StringType.BASE, "datestr", "Long Long类型时间戳,如:1511775486481"), + buildParamMeta(StringType.BASE, "outputType", "输出类型,0:java.util.Date 1:java.sql.Date 2:java.sql.Timestamp 3:java.sql.Time") + )); + funcs.add(buildFuncMeta("CHAR_TO_DATE", "字符串转时间对象", "com.code.std.function.method.datetime.ToDateFunc", FuncTypeEnum.NORMAL, "根据inFmt的样式,日期时间字符串转化为日期时间对象", + buildExamples("CHAR_TO_DATE(20041001,yyyyMMdd)", "java.util.Date(2004-10-01)", "将日期时间字符串20041001转化成时间对象2004-10-01"), + buildParamMeta(ObjType.BASE), buildParamMeta(StringType.BASE, "datestr", "String 日期时间字符串,如:20041001、2004年10月01日 15:03"), + buildParamMeta(StringType.BASE, "inFmt", "String 对datestr参数格式说明,参照类说明,如yyyyMMdd、yyyy年MM月dd日 HH:mm"), + buildParamMeta(StringType.BASE, "dateType", "String 输出日期的格式,'0': 正常日期格式(如Thu Feb 22 00:00:00 GMT+08:00 2018);'1':SQL_Date格式(yyyy-MM-dd);'2':SQL_TIMESTAMP格式(yyyy-MM-dd HH:mm:ss.0格式,'3':SQL_TIME格式(HH:mm:ss);该参数可不填,不填默认'1'") + )); + funcs.add(buildFuncMeta("DATE_TO_CHAR", "时间对象转成字符串", "com.code.std.function.method.datetime.ToCharFunc", FuncTypeEnum.NORMAL, "时间对象转成字符串", + buildExamples("DATE_TO_CHAR(2018年08月10日 15:53:22,yyyy-MM-dd HH:mm:ss,1900-12-30 01:01:01)", "2018年08月10日 15:53:22", "将时间对象2018年08月10日 15:53:22转成字符串,当参数为空的情况下输出默认值1900-12-30 01:01:01"), + buildParamMeta(StringType.BASE), buildParamMeta(DateType.BASE, "date", "时间对象 java.util.Date,java.sql.Date,java.sql.Timestamp,java.sql.Time"), + buildParamMeta(StringType.BASE, "outFmt", "时间字符串输出的格式,如yyyyMMdd、yyyy年MM月dd日 HH:mm"), + buildParamMeta(StringType.BASE, "defVal", "date 参数为空的情况下输出的默认值") + )); + funcs.add(buildFuncMeta("MILLISECONDS", "获取毫秒数", "com.code.std.function.method.datetime.MilliSeconds", FuncTypeEnum.NORMAL, "获取毫秒数,当前时间的毫秒值加上间隔时间所获取到的毫秒值", + buildExamples("MILLISECONDS(0,DAY_OF_YEAR)", "1533887484139", "获取当前时间的毫秒值加上间隔为0天所获取到的毫秒值的和返回"), + buildParamMeta(LongType.BASE), + buildParamMeta(StringType.BASE, "intervalTime", "间隔时间值"), + buildParamMeta(StringType.BASE, "unit", "时间单位 YEAR MONTH DAY_OF_YEAR") + )); + funcs.add(buildFuncMeta("SYS_TIME", "获取系统时间", "com.code.std.function.method.datetime.SysTimeFunc", FuncTypeEnum.NORMAL, "获取系统时间,通过毫秒数转成指定格式的时间", + buildExamples("SYS_TIME(MILLISECONDS(0,DAY_OF_YEAR),yyyyMMdd)", "20180819", "将传入的时间的毫秒数转成指定格式yyyyMMdd的时间"), + buildParamMeta(StringType.BASE), + buildParamMeta(LongType.BASE, "milliseconds", "间隔时间值"), + buildParamMeta(StringType.BASE, "outFmt", "outFmt参数格式说明,如yyyyMMddHHmmss,yyyyMMdd, yyyy年MM月dd日 HH:mm") + )); + funcs.add(buildFuncMeta("DATE_WINDOW_EXPAND", "时间窗函数", "com.code.std.function.method.reduce.DateWindowExpandFunc", FuncTypeEnum.NORMAL, "时间窗函数(无法调试执行,需在实际环境中使用)", + buildExamples("DATE_WINDOW_EXPAND(3,yyyyMMdd,true,SFZH,CZS)", "返回List集合", "根据输入的间隔时间值和时间参数格式yyyyMMdd,设置时间扩展将需往下流的字段SFZH、CZS封装到以时间为键值的数组中返回"), + buildParamMeta(ListType.BASE, "OUTPUT_KEY", "返回的类型"), + buildParamMeta(IntegerType.BASE, "param1", "间隔时间值(int),比如设置(20170102)为3天,取的范围为(20170101,20170102,20170103)"), + buildParamMeta(StringType.BASE, "param2", "时间参数(varchar),格式yyyyMMdd"), + buildParamMeta(StringType.BASE, "param3", "是否设置时间扩展(true or false)"), + buildParamMeta(StringType.BASE, "param4 ...", "需往下流的字段,支持多个") + )); + funcs.add(buildFuncMeta("DATE_ADD", "添加时间跨度函数", "com.code.std.function.method.date.AddDayFunc", FuncTypeEnum.NORMAL, "添加时间跨度函数(无法调试执行,需在实际环境中使用)", + buildExamples("DATE_ADD(2018-01-01 11:12:12,12,hour)", "2018-01-01 23:12:12", "根据输入的时间2018-01-01 11:12:12增加12小时得到新的时间返回"), + buildParamMeta(DateType.BASE, "返回指定类型", "返回DATE类型,入参必须是date类型"), + buildParamMeta(DateType.BASE, "date", "指定时间点(java.util DATE类型)"), + buildParamMeta(IntegerType.BASE, "num", "添加时间跨度"), + buildParamMeta(StringType.BASE, "format", "时间类型,目前支持:YEAR,MONTH,DAY,HOUR,MINUTE,SECOND") + )); + typeMap.put("date", funcs); + + /*funcs = new ArrayList(); + funcs.add(buildFuncMeta("MAX", "com.code.std.function.method.mathematical.MaxFunc", FuncTypeEnum.NORMAL, "从一组数字中返回最大值", + buildParamMeta(NumberType.BASE), buildParamMeta(AnyType.createAnyType(NumberType.BASE)) + )); + funcs.add(buildFuncMeta("MIN", "com.code.std.function.method.mathematical.MinFunc", FuncTypeEnum.NORMAL, "从一组数字中返回最小值", + buildParamMeta(NumberType.BASE), buildParamMeta(AnyType.createAnyType(NumberType.BASE)) + )); + funcs.add(buildFuncMeta("AVG", "com.code.std.function.method.mathematical.AvgFunc", FuncTypeEnum.NORMAL, "从一组数字获取平均值", + buildParamMeta(NumberType.BASE), buildParamMeta(AnyType.createAnyType(NumberType.BASE)) + )); + funcs.add(buildFuncMeta("SUM", "com.code.std.function.method.mathematical.SumFunc", FuncTypeEnum.NORMAL, "一组数字的总和", + buildParamMeta(NumberType.BASE), buildParamMeta(AnyType.createAnyType(NumberType.BASE)) + )); + funcs.add(buildFuncMeta("RMAX", "com.code.std.function.method.mathematical.dataset.RMaxFunc", FuncTypeEnum.AGGREGATION, "数据集间求最大值", + buildParamMeta(ObjType.BASE), buildParamMeta(ObjType.BASE) + )); + funcs.add(buildFuncMeta("RMIN", "com.code.std.function.method.mathematical.dataset.RMinFunc", FuncTypeEnum.AGGREGATION, "数据集间求最小值", + buildParamMeta(ObjType.BASE), buildParamMeta(ObjType.BASE) + )); + funcs.add(buildFuncMeta("RAVG", "com.code.std.function.method.mathematical.dataset.RAvgFunc", FuncTypeEnum.AGGREGATION, "数据集间求平均值", + buildParamMeta(ObjType.BASE), buildParamMeta(ObjType.BASE) + )); + funcs.add(buildFuncMeta("RSUM", "com.code.std.function.method.mathematical.dataset.RSumFunc", FuncTypeEnum.AGGREGATION, "数据集间求和", + buildParamMeta(ObjType.BASE), buildParamMeta(ObjType.BASE) + )); + typeMap.put("mathematical", funcs);*/ + + funcs = new ArrayList(); + funcs.add(buildFuncMeta("TRUE", "返回常数true值", "com.code.std.function.method.logical.TrueFunc", FuncTypeEnum.NORMAL, "返回常数true值", + buildExamples("TRUE()", "true", "返回常数true值"), + buildParamMeta(BooleanType.BASE) + )); + + funcs.add(buildFuncMeta("OR", "逻辑或", "com.code.std.function.method.logical.OrFunc", FuncTypeEnum.NORMAL, "计算一组布尔参数的逻辑或", + buildExamples("OR(0,0,0,0)", "false", "逻辑或,全部为false才为false,如果OR(0,0,0,1)则返回true"), + buildParamMeta(BooleanType.BASE), buildParamMeta(AnyType.createAnyType(BooleanType.BASE), "flag...", "布尔值,可以传入多个,例如:OR(flag1,flag2,...,flag100)") + )); + funcs.add(buildFuncMeta("AND", "逻辑与", "com.code.std.function.method.logical.AndFunc", FuncTypeEnum.NORMAL, "计算一组布尔参数的逻辑与", + buildExamples("AND(0,0,1,1)", "false", "逻辑与,全部为true才为true,例如AND(1,1,1,1)则返回true"), + buildParamMeta(BooleanType.BASE), buildParamMeta(AnyType.createAnyType(BooleanType.BASE), "flag...", "布尔值,可以传入多个,例如:AND(flag1,flag2,...,flag100)") + )); + + funcs.add(buildFuncMeta("IF", "if判断", "com.code.std.function.method.logical.IfFunc", FuncTypeEnum.NORMAL, "根据条件返回两个值中的一个", + buildExamples("IF(true,是,否)", "是", "第一参数为判断条件,满足则输出第二个参数,不满足输出第三个参数"), + buildParamMeta(ObjType.BASE), buildParamMeta(BooleanType.BASE, "boolean", "判断条件"), buildParamMeta(ObjType.BASE, "res1", "返回值1"), + buildParamMeta(ObjType.BASE, "res2", "返回值2") + )); + funcs.add(buildFuncMeta("EQ", "两个数值参数间的逻辑比较是否相等", "com.code.std.function.method.logical.EqFunc", FuncTypeEnum.NORMAL, "两个数值参数间的逻辑比较是否相等", + buildExamples("EQ(44,44)", "true", "比较44和44两个数值参数间的逻辑比较是否相等"), + buildParamMeta(BooleanType.BASE), buildParamMeta(ObjType.BASE), buildParamMeta(ObjType.BASE))); + funcs.add(buildFuncMeta("GT", "两个数值逻辑比较是否大于", "com.code.std.function.method.logical.GtFunc", FuncTypeEnum.NORMAL, "两个数值参数间的逻辑比较是否大于", + buildExamples("GT(49,44)", "true", "比较49和44两个数值参数间的逻辑比较是否大于"), + buildParamMeta(BooleanType.BASE), buildParamMeta(NumberType.BASE, "num1", "数值1"), buildParamMeta(NumberType.BASE, "num2", "数值2") + )); + funcs.add(buildFuncMeta("GTE", "两个数值逻辑比较是否大于等于", "com.code.std.function.method.logical.GteFunc", FuncTypeEnum.NORMAL, "两个数值参数间的逻辑比较是否大于等于", + buildExamples("GTE(44,44)", "true", "比较44和44两个数值参数间的逻辑比较是否大于等于"), + buildParamMeta(BooleanType.BASE), buildParamMeta(NumberType.BASE, "num1", "数值1"), buildParamMeta(NumberType.BASE, "num2", "数值2") + )); + funcs.add(buildFuncMeta("LT", "两个数值逻辑比较是否小于", "com.code.std.function.method.logical.LtFunc", FuncTypeEnum.NORMAL, "两个数值参数间的逻辑比较是否小于", + buildExamples("LT(42,44)", "true", "比较42和44两个数值参数间的逻辑比较是否小于"), + buildParamMeta(BooleanType.BASE), buildParamMeta(NumberType.BASE, "num1", "数值1"), buildParamMeta(NumberType.BASE, "num2", "数值2") + )); + funcs.add(buildFuncMeta("LTE", "两个数值逻辑比较是否小于等于", "com.code.std.function.method.logical.LteFunc", FuncTypeEnum.NORMAL, "两个数值参数间的逻辑比较是否小于等于", + buildExamples("LTE(42,44)", "true", "比较42和44两个数值参数间的逻辑比较是否小于等于"), + buildParamMeta(BooleanType.BASE), buildParamMeta(NumberType.BASE, "num1", "数值1"), buildParamMeta(NumberType.BASE, "num2", "数值2") + )); + funcs.add(buildFuncMeta("NOT", "计算逻辑非", "com.code.std.function.method.logical.NotFunc", FuncTypeEnum.NORMAL, "计算逻辑非", + buildExamples("NOT(true)", "false", "计算true的逻辑非为false"), + buildParamMeta(BooleanType.BASE), buildParamMeta(BooleanType.BASE, "boolean", "布尔值") + )); + funcs.add(buildFuncMeta("XOR", "计算逻辑XOR", "com.code.std.function.method.logical.XorFunc", FuncTypeEnum.NORMAL, "输入的布尔值全部一样返回false,有一个不一样返回true", + buildExamples("XOR(true,true,true)", "false", "输入的布尔值全部一样返回false,如果为XOR(true,true,false)则返回true"), + buildParamMeta(BooleanType.BASE), buildParamMeta(BooleanType.BASE, "booleans...", "输入的布尔值,可以输入多个,XOR(boolean1,boolean2,...,boolean100)") + )); + funcs.add(buildFuncMeta("MATCH", "逻辑匹配", "com.code.std.function.method.logical.MatchFunc", FuncTypeEnum.NORMAL, "逻辑匹配", + buildExamples("MATCH(CHAR_TO_NUMBER(125)<=130,'偏高')", "偏高", "判断前一个参数的逻辑值是否满足条件,满足则输出后一个参数的值"), + buildParamMeta(ObjType.BASE), buildParamMeta(BooleanType.BASE, "logic", "逻辑值 true false"), + buildParamMeta(ObjType.BASE), buildParamMeta(AnyType.BASE, "any", "前一个参数是逻辑值,后一个参数是要输出的值") + )); + typeMap.put("logical", funcs); + + funcs = new ArrayList(); + funcs.add(buildFuncMeta("CHOOSE", "使用索引从值的列表返回一个值", "com.code.std.function.method.information.ChooseFunc", FuncTypeEnum.NORMAL, "使用索引从值的列表返回一个值", + buildExamples("CHOOSE(1,aa,bb)", "aa", "索引1的参数值为aa"), + buildParamMeta(ObjType.BASE), buildParamMeta(NumberType.BASE, "indexCode", "索引列值", "索引值从1开始"), + buildParamMeta(AnyType.BASE, "obj...", "索引值上的实际值,可输入多个,例如CHOOSE(indexCode,obj1,obj2,...,obj100,...)") + )); + funcs.add(buildFuncMeta("ISBLANK", "参数值为空判断", "com.code.std.function.method.information.IsBlankFunc", FuncTypeEnum.NORMAL, "如果参数值为空返回TRUE,否则返回FALSE", + buildExamples("ISBLANK('')", "true", "参数值为空或空字符串返回TRUE"), + buildParamMeta(BooleanType.BASE), buildParamMeta(StringType.BASE, "str", "字符串") + )); + funcs.add(buildFuncMeta("ISNUMBER", "参数值类型为数字判断", "com.code.std.function.method.information.IsNumberFunc", FuncTypeEnum.NORMAL, + "如果参数值类型为数字返回TRUE,否则返回FALSE,由于调试页面输入会被当做String类型,所以调试页面不准确,即使输入纯数字也会返回false", + buildExamples("ISNUMBER(INTEGER)", "true", "参数值类型为数字返回TRUE"), + buildParamMeta(BooleanType.BASE), buildParamMeta(ObjType.BASE, "obj", "输入对象") + )); + funcs.add(buildFuncMeta("ISTEXT", "参数值类型为字符串判断", "com.code.std.function.method.information.IsTextFunc", FuncTypeEnum.NORMAL, + "如果参数值为文本返回TRUE,否则返回FALSE,由于调试页面输入会被当做String类型,所以调试页面无法测试其他类型,需要实际配方案执行测试", + buildExamples("ISTEXT(adfdf)", "true", "参数值类型为字符串返回true"), + buildParamMeta(BooleanType.BASE), buildParamMeta(ObjType.BASE, "obj", "输入对象") + )); + typeMap.put("information", funcs); + + funcs = new ArrayList(); + funcs.add(buildFuncMeta("TEXT", "对象转换为字符串", "com.code.std.function.method.text.TextFunc", FuncTypeEnum.NORMAL, "返回转换为文本的值", + buildExamples("TEXT(456)", "'456'", "数字456被转成字符串'456'"), + buildParamMeta(StringType.BASE), buildParamMeta(ObjType.BASE, "obj", "需要转换为字符串的对象") + )); + funcs.add(buildFuncMeta("TRIM", "文本去空", "com.code.std.function.method.text.TrimFunc", FuncTypeEnum.NORMAL, "返回文本去空后的值", + buildExamples("TRIM( abcde )", "abcde", "文本左右的空格被去掉"), + buildParamMeta(StringType.BASE), buildParamMeta(StringType.BASE, "str", "需要去空的字符串") + )); + /*funcs.add(buildFuncMeta("UPPER", "com.code.std.function.method.text.UpperFunc", FuncTypeEnum.NORMAL, "小写字母转换为大写字母", + buildParamMeta(StringType.BASE), buildParamMeta(StringType.BASE) + ));*/ + funcs.add(buildFuncMeta("LEN", "文本长度统计", "com.code.std.function.method.text.LenFunc", FuncTypeEnum.NORMAL, "返回文本的长度", + buildExamples("LEN(abcd)", "4", "abcd文本字符串的长度为4"), + buildParamMeta(IntegerType.BASE), buildParamMeta(StringType.BASE, "str", "字符串") + )); + /*funcs.add(buildFuncMeta("LOWER", "com.code.std.function.method.text.LowerFunc", FuncTypeEnum.NORMAL, "大写字母转换为小写字母", + buildParamMeta(StringType.BASE), buildParamMeta(StringType.BASE) + ));*/ + funcs.add(buildFuncMeta("SUBSTRING", "文本截取", "com.code.std.function.method.text.SubstringFunc", FuncTypeEnum.NORMAL, "文本截取函数", + buildExamples("SUBSTRING(abcd,1,2)", "b", "abcd截取的结果为b"), + buildParamMeta(StringType.BASE), buildParamMeta(StringType.BASE, "str", "截取前的原始字符串"), + buildParamMeta(NumberType.BASE, "start", "开始位置,索引值从0开始,截取时包含开始位置的值"), + buildParamMeta(NumberType.BASE, "end", "结束位置,截取时不包含结束位置的值") + )); + /*funcs.add(buildFuncMeta("REPLACE", "com.code.std.function.method.text.ReplaceFunc", FuncTypeEnum.NORMAL, "文本替换函数", + buildParamMeta(StringType.BASE), buildParamMeta(StringType.BASE, "sourceText"), buildParamMeta(StringType.BASE, "regex", "正则表达式"), + buildParamMeta(StringType.BASE, "replacement", "替换值"), buildParamMeta(NumberType.BASE, "methodCode", "方法代码", "0:replaceAll 1:replace 2:replaceFirst") + ));*/ + funcs.add(buildFuncMeta("EXACT", "字符串比较", "com.code.std.function.method.text.ExactFunc", FuncTypeEnum.NORMAL, "比较两个字符串是否一致,一致返回true,不一致返回false", + buildExamples("EXACT(aa,aa)", "true", "一致返回true"), + buildParamMeta(BooleanType.BASE), buildParamMeta(StringType.BASE, "str1", "字符串1"), + buildParamMeta(StringType.BASE, "str2", "字符串2") + )); + + funcs.add(buildFuncMeta("FIND", "字符在字符串中的位置", "com.code.std.function.method.text.FindFunc", FuncTypeEnum.NORMAL, "查找字符在字符串的位置,字符串的索引值从0开始,返回第一个匹配到的字符串位置,匹配不到返回-1", + buildExamples("FIND(bbbaabbbb, a)", "3", "返回第一个匹配到的字符位置的索引值"), + buildParamMeta(IntegerType.BASE), buildParamMeta(StringType.BASE, "text", "文本"), buildParamMeta(StringType.BASE, "searchValue", "查找值") + )); + + /*funcs.add(buildFuncMeta("CONCAT", "com.code.std.function.method.text.ConcatFunc", FuncTypeEnum.NORMAL, "字符串拼接函数", + buildParamMeta(StringType.BASE), buildParamMeta(AnyType.createAnyType(StringType.BASE), "strs", "任意的字符串") + ));*/ + funcs.add(buildFuncMeta("CONCAT_MULTI", "字符串拼接", "com.code.std.function.method.text.ConcatMultiFunc", FuncTypeEnum.NORMAL, "字符串拼接,可传入多个参数", + buildExamples("CONCAT_MULTI(aa,bb,cc,dd)", "aabbccdd", "将输入的字符串拼接成一个字符串"), + buildParamMeta(StringType.BASE), + buildParamMeta(StringType.BASE, "args...", "需要拼接起来的字符串串,可传入多值;(值1,值2,...值n)") + )); + funcs.add(buildFuncMeta("SPLITROW", "一行拆分成多行", "com.code.std.function.method.text.SplitIntoMultiRows", FuncTypeEnum.NORMAL, "一行拆分成多行(弃用)", + buildExamples("弃用", "", ""), + buildParamMeta(MapType.BASE), buildParamMeta(StringType.BASE, "outputFields", "输出的字段集合"), buildParamMeta(AnyType.BASE, "inputFields", "组前缀 + 字段名") + )); + funcs.add(buildFuncMeta("JSONPARSE", "JSON解析", "com.code.std.function.method.text.JsonParseFunc", FuncTypeEnum.NORMAL, "解析JSON字符串,获取json中的字段值", + buildExamples("JSONPARSE({id:'123', person={name:'jack',age:10}},id,person.name)", "MAP(id:123, person.name:jack)", "调试需将json字符串中的单引号改为双引号"), + buildParamMeta(MapType.BASE), buildParamMeta(StringType.BASE, "jsonStr", "json字符串"), buildParamMeta(AnyType.createAnyType(StringType.BASE), "fields...", + "字段名,可传入多值,例如:JSONPARSE([jsonStr],[field1],[field2],...,[field100])") + )); + funcs.add(buildFuncMeta("SPLIT", "文本分割", "com.code.std.function.method.text.SplitFunc", FuncTypeEnum.NORMAL, "文本分割", + buildExamples("SPLIT('a,b,c,d',',',R,1)", "List(Map(R:b),Map(R:c),Map(R:d))", "如果模式为C,则切成一列,返回值则为List(Map(C1:a,C2:b,C3:c))"), + buildParamMeta(ListType.BASE), buildParamMeta(StringType.BASE, "str", "文本"), buildParamMeta(StringType.BASE, "regx", "分割符"), + buildParamMeta(StringType.BASE, "model", "模式 C:表示切成列 R:表示切成多行"), + buildParamMeta(IntegerType.BASE, "startPos", "起始位置,非必填,不填默认从0开始") + )); + funcs.add(buildFuncMeta("DECODE", "DECODE解析", "com.code.std.function.method.text.DecodeFunc", FuncTypeEnum.NORMAL, "DECODE解析", + buildExamples("DECODE(1,1,A,2,B,C)", "A", "将查询出来的结果中的1翻译成A"), + buildParamMeta(StringType.BASE), buildParamMeta(StringType.BASE, "field", "需要翻译的值"), buildParamMeta(StringType.BASE, "key", "用于匹配需要翻译的值"), + buildParamMeta(StringType.BASE, "value", "翻译后的值,与key配对使用,可以填入多个key-value,例如:(field,key1,value1,key2,value2,...keyn,valuen,缺省值)"), + buildParamMeta(StringType.BASE, "default", "缺省值,匹配不到返回该值") + )); + funcs.add(buildFuncMeta("NUMBER_TO_CHAR", "数字转字符函数", "com.code.std.function.method.text.NumberToCharFunc", FuncTypeEnum.NORMAL, "数字转字符函数", + buildExamples("NUMBER_TO_CHAR(182324.33,1,666)", "182324.3", "将数字182324.33转化为数字精度为1位的字符串,参数为空的情况下输出的默认值位666"), + buildParamMeta(StringType.BASE), buildParamMeta(StringType.BASE, "numberValue", "值"), buildParamMeta(IntegerType.BASE, "precision", "数字精度"), + buildParamMeta(StringType.BASE, "defVal", "参数为空的情况下输出的默认值") + )); + typeMap.put("text", funcs); + + funcs = new ArrayList(); + funcs.add(buildFuncMeta("DATA_COMPARISON", "数据比对", "", FuncTypeEnum.NORMAL, "数据比对(弃用),建议使用redis操作插件,性能更佳", + buildExamples("DATA_COMPARISON(SFZH,192.168.21.15,CZRK,8)", "TRUE", "与redis中key对应的值,返回true"), + buildParamMeta(BooleanType.BASE), + buildParamMeta(StringType.BASE, "identity", "redis key,值需要唯一!"), + buildParamMeta(StringType.BASE, "redisIp", "redis数据库IP地址"), + buildParamMeta(StringType.BASE, "redisKeyPre", "redis key前缀标识"), + buildParamMeta(StringType.BASE, "redisPartition", "redis数据存储区域") + )); + funcs.add(buildFuncMeta("REDIS_DELETE", "redis数据删除", "", FuncTypeEnum.NORMAL, "redis数据删除", + buildExamples("REDIS_DELETE(SFZH,192.168.21.15,8001,CZRK,8)", "True", "删除成功"), + buildParamMeta(BooleanType.BASE), + buildParamMeta(StringType.BASE, "identity", "redis key,值需要唯一!"), + buildParamMeta(StringType.BASE, "redisIp", "redis数据库IP地址"), + buildParamMeta(StringType.BASE, "redisIpPort", "redis数据库IP的端口"), + buildParamMeta(StringType.BASE, "redisKeyPre", "redis key前缀标识"), + buildParamMeta(StringType.BASE, "redisPartition", "redis数据存储区域") + )); + funcs.add(buildFuncMeta("REDIS_VALUES", "redis取值", "", FuncTypeEnum.NORMAL, "redis取值(弃用,建议使用redis操作插件,性能更佳),eg REDIS_VALUE([columnName],'ip','port','redisKeyPre','redisPartition','redisValuesCode')", + buildExamples("REDIS_DELETE(LXDH,192.168.21.15,8001,CZRK,8,SJ)", "1234", "redis中的值为1234"), + buildParamMeta(MapType.BASE), + buildParamMeta(StringType.BASE, "reidsKey", "redis key,值需要唯一!"), + buildParamMeta(StringType.BASE, "redisIp", "redis数据库IP地址"), + buildParamMeta(StringType.BASE, "redisIpPort", "redis数据库IP的端口"), + buildParamMeta(StringType.BASE, "redisKeyPre", "redis key前缀标识"), + buildParamMeta(StringType.BASE, "redisPartition", "redis数据存储区域"), + buildParamMeta(StringType.BASE, "redisValuesCode", "redis数据valuesCode 多个值就以&隔开") + )); + funcs.add(buildFuncMeta("CACHING_APPLY", "获取缓存中的值并做相应的计算", "", FuncTypeEnum.NORMAL, "获取缓存中的值并做相应的计算(无法调试执行,需在实际环境中使用)", + buildExamples("CACHING_APPLY('CACHING_NAME',PEOPLE,'NL','[B] + [A] + 1',[B]", "23", "获取缓存名为CACHING_NAME的map对应主键为PEOPLE、属性名为NL的值,与传入的扩展表达式参数[B]执行表达式[B]+[A]+1得到结果返回"), + buildParamMeta(DoubleType.BASE), + buildParamMeta(StringType.BASE, "CACHE_NAME", "缓存名称,缓存必须存map"), + buildParamMeta(StringType.BASE, "KEY", "key,值需要唯一!"), + buildParamMeta(StringType.BASE, "FIELD", "属性名"), + buildParamMeta(StringType.BASE, "EXP", "表达式"), + buildParamMeta(AnyType.BASE, "EXP_PARAMS...", "扩展表达式参数") + )); + typeMap.put("thirdParty", funcs); + + funcs = Lists.newArrayList(); + funcs.add(buildFuncMeta("BIZ_IDCARD_GENDER", "身份证查询性别函数", "com.code.std.function.method.biz.IdCardGenderFunc", FuncTypeEnum.NORMAL, "身份证查询性别函数 返回结果 1:性别男 2:性别女 0:输入参数不合法", + buildExamples("BIZ_IDCARD_GENDER(642101197002122752)", "1", "求身份证号为“642101197002122752”的性别"), + buildParamMeta(StringType.BASE), buildParamMeta(StringType.BASE, "idCard", "身份证号 ") + )); + funcs.add(buildFuncMeta("BIZ_IDCARD_BIRTH", "身份证查询出生日期", "com.code.std.function.method.biz.IdCardBirthDay", FuncTypeEnum.NORMAL, "身份证查询出生日期", + buildExamples("BIZ_IDCARD_BIRTH(642101197002122752)", "19700212", "求身份证号为“642101197002122752”的出生日期"), + buildParamMeta(StringType.BASE), buildParamMeta(StringType.BASE, "idCard", "返回8为身份证号") + )); + funcs.add(buildFuncMeta("MERGE_VALUE", "REDUCE插件合并数据的回调函数", "com.code.std.function.method.reduce.MergeValFunc", FuncTypeEnum.NORMAL, "REDUCE插件合并数据的回调函数", + buildExamples("A:A.NAME(值为:List(NAME:33) B.NAME(值为:List(XB:1)))", "MERGE_VALUE([A],[B])", "将输入数据A与结果集合B合并数据并返回"), + buildParamMeta(MapType.BASE), buildParamMeta(ListType.BASE, "resultData", "结果集合"), + buildParamMeta(ListType.BASE, "inputData", "输入数据") + )); + typeMap.put("biz", funcs); + + funcs = new ArrayList(); + funcs.add(buildFuncMeta("BERNOULLI_SAMPLER", "伯努利数据抽样", "", FuncTypeEnum.NORMAL, "伯努利数据抽样, eg: BERNOULLI_SAMPLER(0.5) 返回值 0代表不需要该数据 1表示需要改数据", + buildExamples("BERNOULLI_SAMPLER(0.5)", "0", "表示抽50%的数据"), + buildParamMeta(BooleanType.BASE), + buildParamMeta(StringType.BASE, "rate", "比率值,rate为0.5表示抽50%的数据") + )); + funcs.add(buildFuncMeta("RESERVOIR_SAMPLER", "水塘抽样", "", FuncTypeEnum.NORMAL, "水塘抽样 返回值index 如果是-1表示不需要设置,否则即为数组的第{index}个需要被流过来的数据覆盖", + buildExamples("RESERVOIR_SAMPLER(1000)", "23", "对于1000个需要抽取的数据流进行随机采样"), + buildParamMeta(IntegerType.BASE), + buildParamMeta(StringType.BASE, "k", "需要抽取的个数") + )); + typeMap.put("sample", funcs); + + funcs = new ArrayList(); + funcs.add(buildFuncMeta("TRY_CATCH", "异常处理函数", "com.code.std.function.method.exception.TryCatchFunc", FuncTypeEnum.NORMAL, "异常处理函数,如果发生异常返回{defaultVal},defaultVal默认为false。 {defaultVal}可以根据需要进行设置,eg:try_catch(SUBSTRING([A],0, 3), 'SUBSTRING函数发生错误')", + buildExamples("TRY_CATCH(match(CHAR_TO_NUMBER(null<=130,'130'),'false')", "false", "异常处理函数,由于传入空值导致发生异常返回false"), + buildParamMeta(ObjType.BASE), buildParamMeta(ObjType.BASE, "logicHandler", "逻辑处理"), + buildParamMeta(ObjType.BASE, "defaultVal", "默认值") + )); + funcs.add(buildFuncMeta( + "BAG", "包函数", "org.code.modules.plugins.function.method.BagFunc", FuncTypeEnum.NORMAL, + "包函数对参数不进行任何的计算直接返回参数 (系统级函数,NULL-OBJECT模式)", + buildExamples("BAG(23)", "23", "返回传入的参数对象23"), + buildParamMeta(ObjType.BASE), + buildParamMeta(ObjType.BASE) + )); + typeMap.put("system", funcs); + return typeMap; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/PluginBeanRegister.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/PluginBeanRegister.java new file mode 100644 index 0000000..add8e4f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/PluginBeanRegister.java @@ -0,0 +1,56 @@ +package org.code.modules.plugins.service.impl; + + +import org.code.modules.plugins.annotation.PluginBean; +import org.code.modules.plugins.annotation.PluginType; +import org.code.modules.plugins.loader.PluginClassLoader; +import org.code.modules.plugins.model.PluginBeanMeta; +import org.code.modules.plugins.service.IPluginMetaRegisterService; +import org.code.modules.plugins.service.IPluginRegistMethod; +import com.luqj.util.Validator; +import com.luqj.util.reflect.ClassUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class PluginBeanRegister implements IPluginRegistMethod { + private static Logger logger = LoggerFactory.getLogger(PluginBeanRegister.class); + @Autowired + private IPluginMetaRegisterService pluginMetaRegisterService; + + @Override + public PluginBeanMeta regist(PluginClassLoader loader, Class clazz) { + PluginBean pb = (PluginBean) clazz.getAnnotation(PluginBean.class); + String beanName = Validator.hasText(pb.name()) ? pb.name() : ClassUtils.getDefBeanName(clazz); + if(pb.beanType() == PluginType.ETL_TRANS_META) { + try { + pluginMetaRegisterService.resetPluginMeta(clazz); + } catch (Exception e) { + + logger.error("插件模型[" + clazz.getName() + "]注册失败", e); + } + } + return new PluginBeanMeta(beanName, clazz.getName(), loader); + } + + @Override + public boolean filter(Class clazz) { + PluginBean b = clazz.getAnnotation(PluginBean.class); + return b != null; + } + + @Override + public Class[] typeFilters() { + return new Class[]{PluginBean.class}; + } + + public IPluginMetaRegisterService getPluginMetaRegisterService() { + return pluginMetaRegisterService; + } + + public void setPluginMetaRegisterService(IPluginMetaRegisterService pluginMetaRegisterService) { + this.pluginMetaRegisterService = pluginMetaRegisterService; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/PluginMetaRegisterServiceImpl.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/PluginMetaRegisterServiceImpl.java new file mode 100644 index 0000000..5e3c18d --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/PluginMetaRegisterServiceImpl.java @@ -0,0 +1,23 @@ +package org.code.modules.plugins.service.impl; + +import org.code.modules.plugins.service.IPluginMetaRegisterService; +import org.springframework.stereotype.Service; + +/** + * 插件元数据注册 + * Created by chenzm on 2016/12/28. + */ +@Service +public class PluginMetaRegisterServiceImpl implements IPluginMetaRegisterService { + + @Override + public void resetPluginMeta(Class pluginBeanMeta) { + + } + + @Override + public String _savePluginMeta(Class pluginBeanMeta) { + return null; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/TypeMappingBeanRegister.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/TypeMappingBeanRegister.java new file mode 100644 index 0000000..1ddf18b --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/TypeMappingBeanRegister.java @@ -0,0 +1,37 @@ +package org.code.modules.plugins.service.impl; + + +import org.code.modules.plugins.annotation.DBTypeMapping; +import org.code.modules.plugins.loader.PluginClassLoader; +import org.code.modules.plugins.model.PluginBeanMeta; +import org.code.modules.plugins.service.IPluginRegistMethod; +import com.luqj.util.Validator; +import com.luqj.util.reflect.ClassUtils; +import org.springframework.stereotype.Service; + +@Service("typeMappingBeanRegister") +public class TypeMappingBeanRegister implements IPluginRegistMethod { + + @Override + public Class[] typeFilters() { + return new Class[]{DBTypeMapping.class}; + } + + @Override + public boolean filter(Class clazz) { + DBTypeMapping b = clazz.getAnnotation(DBTypeMapping.class); + return b != null; + } + + @Override + public PluginBeanMeta regist(PluginClassLoader loader, Class clazz) { + DBTypeMapping pb = (DBTypeMapping) clazz.getAnnotation(DBTypeMapping.class); + if(Validator.hasText(pb.name())){ + return new PluginBeanMeta(pb.name(), clazz.getCanonicalName(), loader); + }else{ + String name = ClassUtils.getDefBeanName(clazz); + return new PluginBeanMeta(name,clazz.getCanonicalName(), loader); + } + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/ExtendMeta.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/ExtendMeta.java new file mode 100644 index 0000000..781ed46 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/ExtendMeta.java @@ -0,0 +1,82 @@ +package org.code.modules.plugins.service.impl.function; +import org.code.modules.plugins.annotation.function.Feature; + +import java.io.Serializable; + +public class ExtendMeta implements Serializable { + @Feature( + handler = Feature.HandlerType.IGNORE + ) + protected String id; + @Feature( + handler = Feature.HandlerType.IGNORE + ) + protected String name; + @Feature( + handler = Feature.HandlerType.IGNORE + ) + protected Integer version; + @Feature( + handler = Feature.HandlerType.IGNORE + ) + protected String type; + @Feature( + handler = Feature.HandlerType.IGNORE + ) + protected String memo; + @Feature( + handler = Feature.HandlerType.IGNORE + ) + protected String code; + + public ExtendMeta() { + } + + public String getId() { + return this.id; + } + + public String getName() { + return this.name; + } + + public Integer getVersion() { + return this.version; + } + + public String getType() { + return this.type; + } + + public String getMemo() { + return this.memo; + } + + public String getCode() { + return this.code; + } + + public void setId(String id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public void setType(String type) { + this.type = type; + } + + public void setMemo(String memo) { + this.memo = memo; + } + + public void setCode(String code) { + this.code = code; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncClassify.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncClassify.java new file mode 100644 index 0000000..efd393f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncClassify.java @@ -0,0 +1,5 @@ +package org.code.modules.plugins.service.impl.function; + +public class FuncClassify extends ExtendMeta{ + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncExample.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncExample.java new file mode 100644 index 0000000..74f7b08 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncExample.java @@ -0,0 +1,36 @@ +package org.code.modules.plugins.service.impl.function; + +/** + * Created by chenzm on 2017/12/4. + */ +public class FuncExample extends ExtendMeta { + private String input; + + private String result; + + public FuncExample() { + } + + public FuncExample(String name, String input, String memo, String result) { + this.name = name; + this.memo = memo; + this.input = input; + this.result = result; + } + + public String getInput() { + return input; + } + + public void setInput(String input) { + this.input = input; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncMeta.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncMeta.java new file mode 100644 index 0000000..54818f6 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncMeta.java @@ -0,0 +1,174 @@ +package org.code.modules.plugins.service.impl.function; + +import org.code.modules.plugins.function.annotation.FuncTypeEnum; + +import java.io.Serializable; +import java.util.*; + +public class FuncMeta extends ExtendMeta { + /** + * 类的全路径 eg:com.code.abc + */ + private String clazz; + + /** + * 函数类型 + */ + private String funcType; + + /** + * 函数分类 + */ + private FuncClassify funcClassify; + + /** + * 函数方法样例 + */ + public String funcMethodExample; + + + public String getFuncMethodExample() { + return funcMethodExample; + } + + public void setFuncMethodExample(String funcMethodExample) { + this.funcMethodExample = funcMethodExample; + } + + /** + * 函数例子 + */ + private List examples = new ArrayList<>(); + + private Map methods = new LinkedHashMap<>(); + + public static class Method implements Serializable { + /** + * 输出参数 + */ + FuncParamMeta outputParam; + + /** + * 输入参数 + */ + List inputParams = new ArrayList<>(); + + public FuncParamMeta getInputParam(int index) { + return this.getInputParams().get(index); + } + + public FuncParamMeta getOutputParam() { + return outputParam; + } + + public void setOutputParam(FuncParamMeta outputParam) { + this.outputParam = outputParam; + } + + public List getInputParams() { + return inputParams; + } + + public void setInputParams(List inputParams) { + for(int i = 0 ; i < inputParams.size(); i++) { + inputParams.get(i).setArgPos(i); + } + this.inputParams = inputParams; + } + } + + public void setOutputParam(String methodCode, FuncParamMeta outputParam) { + if(!this.methods.containsKey(methodCode)) { + this.methods.put(methodCode, new Method()); + } + this.methods.get(methodCode).setOutputParam(outputParam); + } + + public void setInputParam(String methodCode, List inputParams) { + if(!this.methods.containsKey(methodCode)) { + this.methods.put(methodCode, new Method()); + } + this.methods.get(methodCode).setInputParams(inputParams); + } + + public FuncParamMeta getOutputParam() { + if(this.methods.size() == 0) { + return null; + } + for(String key : this.methods.keySet()) { + if(isDefMethod(key)) { + continue; + } + return this.methods.get(key).getOutputParam(); + } + throw new IllegalArgumentException(String.format("%s找不到输出参数", this.code)); + } + + private boolean isDefMethod(String key) { + return FuncTypeEnum.valueOf(this.funcType) == FuncTypeEnum.AGGREGATION && (key.equals("reset") || key.equals("merge")); + } + + public List getInputParams() { + if(this.methods.size() == 0) { + return Collections.emptyList(); + } + for(String key : this.methods.keySet()) { + if(isDefMethod(key)) { + continue; + } + return this.methods.get(key).getInputParams(); + } + throw new IllegalArgumentException(String.format("%s找不到执行的方法", this.code)); + } + + public List getInputParams(String methodCode) { + if(!this.methods.containsKey(methodCode)) { + throw new IllegalArgumentException(String.format("不存在方法%s", methodCode)); + } + return this.methods.get(methodCode).getInputParams(); + } + + public FuncParamMeta getOutputParam(String methodCode) { + if(!this.methods.containsKey(methodCode)) { + throw new IllegalArgumentException(String.format("不存在方法%s", methodCode)); + } + return this.methods.get(methodCode).getOutputParam(); + } + + public String getClazz() { + return clazz; + } + + public void setClazz(String clazz) { + this.clazz = clazz; + } + + + public FuncClassify getFuncClassify() { + return funcClassify; + } + + public void setFuncClassify(FuncClassify funcClassify) { + this.funcClassify = funcClassify; + } + + public String getFuncType() { + return funcType; + } + + public void setFuncType(String funcType) { + this.funcType = funcType; + } + + public List getExamples() { + return examples; + } + + public void setExamples(List examples) { + this.examples = examples; + } + + public void addExample(FuncExample funcExample) { + this.examples.add(funcExample); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncParamMeta.java b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncParamMeta.java new file mode 100644 index 0000000..b000d87 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/service/impl/function/FuncParamMeta.java @@ -0,0 +1,63 @@ +package org.code.modules.plugins.service.impl.function; + +public class FuncParamMeta extends ExtendMeta{ + private String valType; + + private Integer precision; + + private Integer length; + + private Integer argPos; + + private String defVal; + + private boolean isAny = false; + + public Integer getPrecision() { + return precision; + } + + public void setPrecision(Integer precision) { + this.precision = precision; + } + + public Integer getLength() { + return length; + } + + public void setLength(Integer length) { + this.length = length; + } + + public String getValType() { + return valType; + } + + public void setValType(String valType) { + this.valType = valType; + } + + public Integer getArgPos() { + return argPos; + } + + public void setArgPos(Integer argPos) { + this.argPos = argPos; + } + + public boolean isAny() { + return isAny; + } + + public void setAny(boolean any) { + isAny = any; + } + + public String getDefVal() { + return defVal; + } + + public void setDefVal(String defVal) { + this.defVal = defVal; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/AbstractType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/AbstractType.java new file mode 100644 index 0000000..edb72ea --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/AbstractType.java @@ -0,0 +1,54 @@ +package org.code.modules.plugins.types; + + + +public abstract class AbstractType implements Type{ + + protected String name; + + protected String code; + + /**长度*/ + protected int length; + + /**精度*/ + protected int precsn; + + + public AbstractType(String name, String code) { + super(); + this.name = name; + this.code = code; + } + + public AbstractType(String name, String code,int length, int precsn) { + this(name,code); + this.length = length; + this.precsn = precsn; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getCode() { + return code; + } + + @Override + public int getLength() { + return length; + } + + @Override + public int getPrecsn() { + return precsn; + } + + + + +} + diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/AnyType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/AnyType.java new file mode 100644 index 0000000..8b913e3 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/AnyType.java @@ -0,0 +1,44 @@ +package org.code.modules.plugins.types; +/** + * 任意类型 只是用来标记 + * Type ...types + * @author chenzm + */ +public class AnyType implements Type { + + public static AnyType BASE = new AnyType(); + + private Type type; + + public AnyType() { + this.type = new ObjType(); + } + + public AnyType(Type type) { + this.type = type; + } + + public static AnyType createAnyType(Type type) { + return new AnyType(type); + } + + @Override + public int getPrecsn() { + return 0; + } + + @Override + public int getLength() { + return 0; + } + + @Override + public String getCode() { + return "Any." + type.getCode(); + } + + @Override + public String getName() { + return "Any." + type.getCode(); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/BigDecimalType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/BigDecimalType.java new file mode 100644 index 0000000..2651344 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/BigDecimalType.java @@ -0,0 +1,46 @@ +package org.code.modules.plugins.types; + + +import com.luqj.util.NumFormat; + +import java.math.BigDecimal; +import java.sql.Types; + +public class BigDecimalType extends AbstractType implements StandardType{ + + public static final StandardType BASE = new BigDecimalType(); + + private BigDecimalType() { + super("std.BigDecimal", "BigDecimal"); + } + + public BigDecimalType(int length,int precsn) { + super("std.BigDecimal", "BigDecimal", length, precsn); + } + + @Override + public Class getReturnedClass() { + return BigDecimal.class; + } + + @Override + public int typeCode() { + return Types.NUMERIC; + } + + @Override + public Object fromStringValue(String xml) { + return new BigDecimal(xml); + } + + @Override + public String format(Object obj) { + return NumFormat.toString((BigDecimal)obj); + } + + @Override + public boolean isNull(Object obj) { + return obj == null || ((BigDecimal)obj).longValue() == 0; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/BigIntegerType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/BigIntegerType.java new file mode 100644 index 0000000..a8049b5 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/BigIntegerType.java @@ -0,0 +1,45 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.NumFormat; + +import java.math.BigInteger; +import java.sql.Types; + +public class BigIntegerType extends AbstractType implements StandardType{ + + public static final StandardType BASE = new BigIntegerType(); + + private BigIntegerType() { + super("std.BigInteger", "BigInteger"); + } + + public BigIntegerType(int length) { + super("std.BigInteger", "BigInteger",length, 0); + } + + @Override + public Class getReturnedClass() { + return BigInteger.class; + } + + @Override + public int typeCode() { + return Types.NUMERIC; + } + + @Override + public Object fromStringValue(String xml) { + return new BigInteger(xml); + } + + @Override + public String format(Object obj) { + return NumFormat.toString((BigInteger)obj); + } + + @Override + public boolean isNull(Object obj) { + return obj == null || ((BigInteger)obj).longValue() == 0; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/BlobType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/BlobType.java new file mode 100644 index 0000000..dc944e7 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/BlobType.java @@ -0,0 +1,42 @@ +package org.code.modules.plugins.types; + + + +import com.luqj.util.NumFormat; + +import java.sql.Blob; + +public class BlobType extends AbstractType implements StandardType{ + + public static final StandardType BASE = new BlobType(Integer.MAX_VALUE); + + public BlobType(int length) { + super("std.Blob", "Blob",length, 0); + } + + @Override + public Class getReturnedClass() { + return Blob.class; + } + + @Override + public int typeCode() { + return TypesCode.BLOB; + } + + @Override + public String format(Object obj) { + return new String((byte[])obj); + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return NumFormat.$Byte(xml); + } + + @Override + public boolean isNull(Object obj) { + return obj == null ; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/BooleanType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/BooleanType.java new file mode 100644 index 0000000..10a54e61 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/BooleanType.java @@ -0,0 +1,50 @@ +package org.code.modules.plugins.types; + +import java.io.Serializable; + +public class BooleanType extends PrimitiveType implements StandardType{ + + + public static final StandardType BASE = new BooleanType(); + + public BooleanType() { + super("std.Boolean", "Boolean", 1, 0); + } + + @Override + public Class getReturnedClass() { + return Boolean.class; + } + + @Override + public int typeCode() { + return 0; + } + + @Override + public Class getPrimitiveClass() { + return boolean.class; + } + + @Override + public Serializable getDefaultValue() { + return null; + } + + @Override + public String format(Object obj) { + return Boolean.toString((Boolean) obj); + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return Boolean.parseBoolean(xml); + } + + @Override + public boolean isNull(Object obj) { + return obj == null ; + } + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/ByteType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/ByteType.java new file mode 100644 index 0000000..826869f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/ByteType.java @@ -0,0 +1,56 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.NumFormat; + +import java.io.Serializable; +import java.sql.Types; + + +public class ByteType extends PrimitiveType implements StandardType{ + + private static final Byte ZERO = new Byte( (byte) 0 ); + + public static final StandardType BASE = new ByteType(); + + public ByteType() { + super("std.Byte", "Byte",1,0); + } + + @Override + public Class getReturnedClass() { + return Byte.class; + } + + @Override + public int typeCode() { + return Types.TINYINT; + } + + @Override + public Class getPrimitiveClass() { + return byte.class; + } + + @Override + public Serializable getDefaultValue() { + return ZERO; + } + + @Override + public String format(Object obj) { + return NumFormat.toString((Byte)obj); + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return NumFormat.$Byte(xml); + } + + @Override + public boolean isNull(Object obj) { + return obj == null || ((Byte)obj) == 0; + } + + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/DateType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/DateType.java new file mode 100644 index 0000000..32af059 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/DateType.java @@ -0,0 +1,43 @@ +package org.code.modules.plugins.types; + + +import com.luqj.util.date.DateUtils; + +import java.util.Date; + + +public class DateType extends AbstractType implements StandardType{ + + + public static final StandardType BASE = new DateType(); + + public DateType() { + super("std.Date", "Date",0, 0); + } + + @Override + public Class getReturnedClass() { + return Date.class; + } + + @Override + public int typeCode() { + return TypesCode.DATE; + } + + @Override + public String format(Object obj) { + return DateUtils.getDateFormat((Date) obj); + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return DateUtils.getDate(xml, ""); + } + + @Override + public boolean isNull(Object obj) { + return obj == null; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/DoubleType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/DoubleType.java new file mode 100644 index 0000000..c2305fa --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/DoubleType.java @@ -0,0 +1,54 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.NumFormat; + +import java.io.Serializable; + +public class DoubleType extends PrimitiveType implements StandardType{ + + public static final StandardType BASE = new DoubleType(); + + private DoubleType() { + super("std.Double", "Double"); + } + + public DoubleType(int length, int precsn) { + super("std.Double", "Double",length, precsn); + } + + @Override + public Class getReturnedClass() { + return Double.class; + } + + @Override + public int typeCode() { + return TypesCode.DOUBLE; + } + + @Override + public Class getPrimitiveClass() { + return double.class; + } + + @Override + public Serializable getDefaultValue() { + return new Double(0.0); + } + + @Override + public String format(Object obj) { + return NumFormat.toString((Double)obj); + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return NumFormat.$Double(xml); + } + + @Override + public boolean isNull(Object obj) { + return obj == null; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/FloatType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/FloatType.java new file mode 100644 index 0000000..633b70e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/FloatType.java @@ -0,0 +1,57 @@ +package org.code.modules.plugins.types; + + + +import com.luqj.util.NumFormat; + +import java.io.Serializable; + +public class FloatType extends PrimitiveType implements StandardType{ + + + public static final StandardType BASE = new FloatType(); + + private FloatType() { + super("std.Float", "Float"); + } + + public FloatType(int length, int precsn) { + super("std.Float", "Float",length, precsn); + } + + @Override + public Class getReturnedClass() { + return Float.class; + } + + @Override + public int typeCode() { + return TypesCode.FLOAT; + } + + @Override + public Class getPrimitiveClass() { + return float.class; + } + + @Override + public Serializable getDefaultValue() { + return new Float(0.0); + } + + @Override + public String format(Object obj) { + return NumFormat.toString((Float)obj); + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return NumFormat.$Float(xml); + } + + @Override + public boolean isNull(Object obj) { + return obj == null; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/HashMapType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/HashMapType.java new file mode 100644 index 0000000..31d733c --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/HashMapType.java @@ -0,0 +1,95 @@ +package org.code.modules.plugins.types; + + + +import com.luqj.util.assertion.Assert; +import com.luqj.util.reflect.ClassUtils; + +import java.lang.reflect.Field; +import java.util.*; + +public class HashMapType extends AbstractType implements StandardMutlValType{ + + public static final StandardMutlValType BASE = new HashMapType(); + + private Class specificType; + + private HashMapType() { + super("std.HashMap", "HashMap"); + } + + + public HashMapType(Class specificType) { + super("std.HashMap", "HashMap"); + this.specificType = specificType; + } + + + + @Override + public Object fromEntityValue(Collection entitys) + throws Exception { + Assert.notNull(entitys); + HashMap value = new HashMap(); + if(StdTypes.isSimpleType(specificType)){ + StandardType vType = StdTypes.transToStandardType(specificType); + for (ValEntity valEntity : entitys) { + value.put(valEntity.keyName, vType.format(valEntity.value)); + } + }else{ + for (ValEntity valEntity : entitys) { + value.put(valEntity.keyName, valEntity.value); + } + } + + return value; + } + + @Override + public Class getReturnedClass() { + return HashMap.class; + } + + @Override + public int typeCode() { + return 0; + } + + @Override + public Class getSpecific() { + return this.specificType; + } + + + + @Override + public Collection format(Object obj) { + List values = new ArrayList(); + Map vObj = (Map) obj; + int i = 0; + for (String key : vObj.keySet()) { + StandardType vType = StdTypes.transToStandardType(specificType); + values.add(new ValEntity(key,i++,vType.format(vObj.get(key)))); + } + return values; + } + + + @Override + public StandardMutlValType instanceType(Field f) { + return new HashMapType((Class) ClassUtils.getMapFieldGenericity(f)[1]); + } + + + @Override + public StandardMutlValType instanceType(Class sType) { + return new HashMapType(sType); + } + + + @Override + public boolean isNull(Object obj) { + return obj == null || ((Map)obj).isEmpty(); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/HashSetType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/HashSetType.java new file mode 100644 index 0000000..f5ab92c --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/HashSetType.java @@ -0,0 +1,92 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.assertion.Assert; +import com.luqj.util.reflect.ClassUtils; + +import java.lang.reflect.Field; +import java.util.*; + +public class HashSetType extends AbstractType implements StandardMutlValType{ + + public static final StandardMutlValType BASE = new HashSetType(); + + private Class specificType; + + private HashSetType() { + super("std.HashSet", "HashSet"); + } + + + public HashSetType(Class specificType) { + super("std.HashSet", "HashSet"); + this.specificType = specificType; + } + + + + @Override + public Object fromEntityValue(Collection entitys) + throws Exception { + Assert.notNull(entitys); + HashSet value = new HashSet(); + if(StdTypes.isSimpleType(specificType)){ + StandardType vType = StdTypes.transToStandardType(specificType); + for (ValEntity valEntity : entitys) { + value.add(vType.format(valEntity.value)); + } + }else{ + for (ValEntity valEntity : entitys) { + value.add(valEntity.value); + } + } + + return value; + } + + @Override + public Class getReturnedClass() { + return HashSet.class; + } + + @Override + public int typeCode() { + return 0; + } + + @Override + public Class getSpecific() { + return this.specificType; + } + + + + @Override + public Collection format(Object obj) { + List values = new ArrayList(); + Set vObj = (Set) obj; + int i = 0; + for (Object val : vObj) { + StandardType vType = StdTypes.transToStandardType(specificType); + values.add(new ValEntity(i++,vType.format(val))); + } + return values; + } + + + @Override + public StandardMutlValType instanceType(Class sType) { + return new HashSetType(sType); + } + + + @Override + public StandardMutlValType instanceType(Field f) { + return new HashSetType((Class) ClassUtils.getSetFieldGenericity(f)); + } + + @Override + public boolean isNull(Object obj) { + return obj == null || ((HashSet)obj).isEmpty(); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/IntegerType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/IntegerType.java new file mode 100644 index 0000000..ff86338 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/IntegerType.java @@ -0,0 +1,55 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.NumFormat; + +import java.io.Serializable; + +public class IntegerType extends PrimitiveType implements StandardType{ + + + public static final StandardType BASE = new IntegerType(); + + public IntegerType() { + super("std.Integer", "Integer", 4, 0); + } + + private static final Integer ZERO = new Integer(0); + + @Override + public Class getReturnedClass() { + return Integer.class; + } + + @Override + public Class getPrimitiveClass() { + return int.class; + } + + @Override + public Serializable getDefaultValue() { + return ZERO; + } + + @Override + public int typeCode() { + return TypesCode.INTEGER; + } + + @Override + public String format(Object obj) { + return NumFormat.toString((Integer)obj); + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return NumFormat.$Intger(xml); + } + + @Override + public boolean isNull(Object obj) { + return obj == null; + } + + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/ListType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/ListType.java new file mode 100644 index 0000000..c81bec0 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/ListType.java @@ -0,0 +1,111 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.assertion.Assert; +import com.luqj.util.reflect.ClassUtils; +import net.sf.json.JSONArray; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class ListType extends AbstractType implements StandardMutlValType{ + + public static final StandardMutlValType BASE = new ListType(); + + private Class specificType; + + public ListType() { + super("std.List", "List"); + } + + + @Override + public boolean isNull(Object obj) { + return obj == null || ((List)obj).isEmpty(); + } + + public ListType(Class specificType) { + super("std.List", "List"); + this.specificType = specificType; + } + + + + public List fromString(String strVal,Class clazz){ + // 转换方法1 + JSONArray array = JSONArray.fromObject(strVal); + return JSONArray.toList(array, clazz); + } + + public String toString(List strVal){ + return String.valueOf(JSONArray.fromObject(strVal)); + } + + + + @Override + public Object fromEntityValue(Collection entitys) + throws Exception { + Assert.notNull(entitys); + ArrayList value = new ArrayList(entitys.size()); + if(StdTypes.isSimpleType(specificType)){ + StandardType vType = StdTypes.transToStandardType(specificType); + for (ValEntity valEntity : entitys) { + value.add(valEntity.index,vType.format(valEntity.value)); + } + }else{ + for (ValEntity valEntity : entitys) { + value.add(valEntity.index,valEntity.value); + } + } + + return value; + } + + @Override + public Class getReturnedClass() { + return List.class; + } + + @Override + public int typeCode() { + return 0; + } + + @Override + public Class getSpecific() { + return this.specificType; + } + + + + @Override + public Collection format(Object obj) { + List values = new ArrayList(); + List vObj = (List) obj; + int i = 0; + for (Object val : vObj) { + if(StdTypes.isSimpleType(specificType)){ + StandardType vType = StdTypes.transToStandardType(specificType); + values.add(new ValEntity(i++,vType.format(val))); + }else{ + values.add(new ValEntity(i++,val)); + } + } + return values; + } + + + @Override + public StandardMutlValType instanceType(Class sType) { + return new ListType(sType); + } + + + @Override + public StandardMutlValType instanceType(Field f) { + return new ListType((Class) ClassUtils.getListGenericity(f)); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/LongType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/LongType.java new file mode 100644 index 0000000..020654f --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/LongType.java @@ -0,0 +1,52 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.NumFormat; + +import java.io.Serializable; + +public class LongType extends PrimitiveType implements StandardType{ + + private static final Long ZERO = new Long(0); + + public static final StandardType BASE = new LongType(); + + public LongType() { + super("std.Long", "Long",8, 0); + } + + @Override + public Class getReturnedClass() { + return Long.class; + } + + @Override + public int typeCode() { + return TypesCode.BIGINT; + } + + @Override + public Class getPrimitiveClass() { + return long.class; + } + + @Override + public Serializable getDefaultValue() { + return ZERO; + } + + @Override + public String format(Object obj) { + return NumFormat.toString((Long)obj); + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return NumFormat.$Long(xml); + } + + @Override + public boolean isNull(Object obj) { + return obj == null; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/MapType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/MapType.java new file mode 100644 index 0000000..378886e --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/MapType.java @@ -0,0 +1,92 @@ +package org.code.modules.plugins.types; + + +import com.luqj.util.assertion.Assert; +import com.luqj.util.reflect.ClassUtils; + +import java.lang.reflect.Field; +import java.util.*; + +public class MapType extends AbstractType implements StandardMutlValType{ + + public static final StandardMutlValType BASE = new MapType(); + + private Class specificType; + + private MapType() { + super("std.Map", "Map"); + } + + @Override + public boolean isNull(Object obj) { + return obj == null || ((Map)obj).isEmpty(); + } + + public MapType(Class specificType) { + super("std.Map", "Map"); + this.specificType = specificType; + } + + + + @Override + public Object fromEntityValue(Collection entitys) + throws Exception { + Assert.notNull(entitys); + HashMap value = new HashMap(); + if(StdTypes.isSimpleType(specificType)){ + StandardType vType = StdTypes.transToStandardType(specificType); + for (ValEntity valEntity : entitys) { + value.put(valEntity.keyName, vType.format(valEntity.value)); + } + }else{ + for (ValEntity valEntity : entitys) { + value.put(valEntity.keyName, valEntity.value); + } + } + return value; + } + + @Override + public Class getReturnedClass() { + return Map.class; + } + + @Override + public int typeCode() { + return 0; + } + + @Override + public Class getSpecific() { + return this.specificType; + } + + + + @Override + public Collection format(Object obj) { + List values = new ArrayList(); + Map vObj = (Map) obj; + int i = 0; + for (String key : vObj.keySet()) { + StandardType vType = StdTypes.transToStandardType(specificType); + values.add(new ValEntity(key,i++,vType.format(vObj.get(key)))); + } + return values; + } + + + @Override + public StandardMutlValType instanceType(Field f) { + Class type = (Class) ClassUtils.getMapFieldGenericity(f)[1]; + return new MapType(type); + } + + + @Override + public StandardMutlValType instanceType(Class sType) { + return new MapType(sType); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/NonStandardType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/NonStandardType.java new file mode 100644 index 0000000..6a72be8 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/NonStandardType.java @@ -0,0 +1,11 @@ +package org.code.modules.plugins.types; + + +public class NonStandardType extends AbstractType{ + + public NonStandardType(String name, String code, int length, int precsn) { + super(name, code, length, precsn); + } + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/NumberType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/NumberType.java new file mode 100644 index 0000000..f1c9332 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/NumberType.java @@ -0,0 +1,42 @@ +package org.code.modules.plugins.types; + + +public class NumberType extends AbstractType implements StandardType{ + + + public static final StandardType BASE = new NumberType(0); + + public NumberType(int length) { + super("std.Number", "Number",length, 0); + } + + @Override + public Class getReturnedClass() { + return Number.class; + } + + @Override + public int typeCode() { + return TypesCode.VARCHAR; + } + + @Override + public String format(Object obj) { + return obj != null ? obj.toString(): ""; + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return xml; + } + + @Override + public boolean isNull(Object obj) { + return null == obj; + } + + + + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/ObjType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/ObjType.java new file mode 100644 index 0000000..43ac3cb --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/ObjType.java @@ -0,0 +1,52 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.NumFormat; + + +public class ObjType extends AbstractType implements StandardType{ + + public static final StandardType BASE = new ObjType(); + + private Class specificType; + + public ObjType() { + super("std.Object", "Object",32, 0); + } + + public ObjType(Class specificType) { + super("std.Object", "Object",32, 0); + this.specificType = specificType; + } + + @Override + public Class getReturnedClass() { + return Object.class; + } + + @Override + public int typeCode() { + return 0; + } + + @Override + public String format(Object obj) { + return obj.toString(); + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return NumFormat.$Long(xml); + } + + public Class getSpecificType() { + return specificType; + } + + @Override + public boolean isNull(Object obj) { + return obj == null; + } + + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/PrimitiveType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/PrimitiveType.java new file mode 100644 index 0000000..8c90679 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/PrimitiveType.java @@ -0,0 +1,22 @@ +package org.code.modules.plugins.types; + +import java.io.Serializable; + +public abstract class PrimitiveType extends AbstractType{ + + public PrimitiveType(String name, String code,int length, int precsn) { + super(name, code,length, precsn); + } + + protected PrimitiveType(String name, String code) { + super(name, code); + } + + public abstract Class getPrimitiveClass(); + + public String toString(Object value) { + return value.toString(); + } + + public abstract Serializable getDefaultValue(); +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/SetType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/SetType.java new file mode 100644 index 0000000..38d1d71 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/SetType.java @@ -0,0 +1,95 @@ +package org.code.modules.plugins.types; + + +import com.luqj.util.assertion.Assert; +import com.luqj.util.reflect.ClassUtils; + +import java.lang.reflect.Field; +import java.util.*; + +public class SetType extends AbstractType implements StandardMutlValType{ + + public static final StandardMutlValType BASE = new SetType(); + + private Class specificType; + + private SetType() { + super("std.Set", "Set"); + } + + + public SetType(Class specificType) { + super("std.Set", "Set"); + this.specificType = specificType; + } + + + + @Override + public Object fromEntityValue(Collection entitys) + throws Exception { + Assert.notNull(entitys); + Set value = new HashSet(); + if(StdTypes.isSimpleType(specificType)){ + StandardType vType = StdTypes.transToStandardType(specificType); + for (ValEntity valEntity : entitys) { + value.add(vType.format(valEntity.value)); + } + }else{ + for (ValEntity valEntity : entitys) { + value.add(valEntity.value); + } + } + + return value; + } + + @Override + public Class getReturnedClass() { + return Set.class; + } + + @Override + public int typeCode() { + return 0; + } + + @Override + public Class getSpecific() { + return this.specificType; + } + + + + @Override + public Collection format(Object obj) { + List values = new ArrayList(); + Set vObj = (Set) obj; + int i = 0; + for (Object val : vObj) { + if(StdTypes.isSimpleType(specificType)){ + StandardType vType = StdTypes.transToStandardType(specificType); + values.add(new ValEntity(i++,vType.format(val))); + }else{ + values.add(new ValEntity(i++,val)); + } + } + return values; + } + @Override + public boolean isNull(Object obj) { + return obj == null || ((Set)obj).isEmpty(); + } + + @Override + public StandardMutlValType instanceType(Class sType) { + return new SetType(sType); + } + + + @Override + public StandardMutlValType instanceType(Field f) { + return new SetType((Class) ClassUtils.getSetFieldGenericity(f)); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/ShortType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/ShortType.java new file mode 100644 index 0000000..bacad3a --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/ShortType.java @@ -0,0 +1,57 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.NumFormat; + +import java.io.Serializable; + +public class ShortType extends PrimitiveType implements StandardType{ + + private static final Short ZERO = new Short( (short) 0 ); + + public static final StandardType BASE = new ShortType(); + + public ShortType() { + super("std.Short", "Short",2, 0); + } + + + @Override + public Class getReturnedClass() { + return Short.class; + } + + @Override + public int typeCode() { + return TypesCode.SMALLINT; + } + + @Override + public Class getPrimitiveClass() { + return short.class; + } + + @Override + public Serializable getDefaultValue() { + return ZERO; + } + + + @Override + public Object fromStringValue(String xml) throws Exception { + // TODO Auto-generated method stub + return NumFormat.$Short(xml); + } + + + @Override + public String format(Object obj) { + return NumFormat.toString((Short)obj); + } + + + @Override + public boolean isNull(Object obj) { + return obj == null || ((Short)obj) == 0; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/StandardMutlValType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StandardMutlValType.java new file mode 100644 index 0000000..8517d2c --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StandardMutlValType.java @@ -0,0 +1,48 @@ +package org.code.modules.plugins.types; + +import java.lang.reflect.Field; +import java.util.Collection; + +public interface StandardMutlValType extends Type{ + + + StandardMutlValType instanceType(Class sType); + + StandardMutlValType instanceType(Field field); + + Collection format(Object obj); + + public Object fromEntityValue(Collection entitys) throws Exception; + + public Class getSpecific(); + + public boolean isNull(Object obj); + /** + * 返回类型 + * @return + */ + public Class getReturnedClass(); + + public int typeCode(); + + public static class ValEntity{ + public String keyName; + public int index; + public Object value; + public ValEntity(String keyName, int index, Object value) { + super(); + this.keyName = keyName; + this.index = index; + this.value = value; + } + public ValEntity(int index, Object value) { + super(); + this.index = index; + this.value = value; + } + + + } + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/StandardType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StandardType.java new file mode 100644 index 0000000..e625daa --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StandardType.java @@ -0,0 +1,20 @@ +package org.code.modules.plugins.types; + + +public interface StandardType extends Type{ + + String format(Object obj); + + boolean isNull(Object obj); + + public Object fromStringValue(String xml) throws Exception; + + /** + * 返回类型 + * @return + */ + public Class getReturnedClass(); + + public int typeCode(); + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/StandardTypeFactory.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StandardTypeFactory.java new file mode 100644 index 0000000..5a9b486 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StandardTypeFactory.java @@ -0,0 +1,58 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.assertion.Assert; + +public class StandardTypeFactory { + + + public static StandardMutlValType createType(String name,int length){ + if("List".equalsIgnoreCase(name)){ + return new ListType(); + }else{ + Assert.fail("找不到指定的标准型["+name+"]"); + return null; + } + } + + + public static StandardType createType(String name,int length,int precsn){ + if("Boolean".equalsIgnoreCase(name)){ + return new BooleanType(); + }else if("Byte".equalsIgnoreCase(name)){ + return new ByteType(); + }else if("Short".equalsIgnoreCase(name)){ + return new ShortType(); + }else if("Integer".equalsIgnoreCase(name)){ + return new IntegerType(); + }else if("Long".equalsIgnoreCase(name)){ + return new LongType(); + }else if("BigInteger".equalsIgnoreCase(name)){ + return new BigIntegerType(length); + }else if("Float".equalsIgnoreCase(name)){ + return new FloatType(length,precsn); + }else if("Double".equalsIgnoreCase(name)){ + return new DoubleType(length,precsn); + }else if("BigDecimal".equalsIgnoreCase(name)){ + return new BigDecimalType(length,precsn); + }else if("Blob".equalsIgnoreCase(name)){ + return new BlobType(length); + }else if("String".equalsIgnoreCase(name)){ + return new StringType(length); + }else if("Text".equalsIgnoreCase(name)){ + return new TextType(length); + }else if("Time".equalsIgnoreCase(name)){ + return new TimeType(); + }else if("Timestamp".equalsIgnoreCase(name)){ + return new TimestampType(); + }else if("Date".equalsIgnoreCase(name)){ + return new DateType(); + }else if("Object".equals(name) || "LinkedList".equals(name) || "ArrayList".equals(name)){ + return new ObjType(); + }else if("byte[]".equals(name)){ + return new BlobType(length); + }else{ + Assert.fail("找不到指定的标准型["+name+"]"); + return null; + } + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/StdTypes.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StdTypes.java new file mode 100644 index 0000000..0857dcd --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StdTypes.java @@ -0,0 +1,152 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.assertion.Assert; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +public class StdTypes { + + public static HashMap, StandardType> _stdSimpleTypes = new HashMap, StandardType>(); + static{ + _stdSimpleTypes.put(BigDecimalType.BASE.getReturnedClass(), BigDecimalType.BASE); + _stdSimpleTypes.put(BigIntegerType.BASE.getReturnedClass(), BigIntegerType.BASE); + _stdSimpleTypes.put(BooleanType.BASE.getReturnedClass(), BooleanType.BASE); + _stdSimpleTypes.put(boolean.class, BooleanType.BASE); + _stdSimpleTypes.put(ByteType.BASE.getReturnedClass(), ByteType.BASE); + _stdSimpleTypes.put(byte.class, ByteType.BASE); + _stdSimpleTypes.put(DateType.BASE.getReturnedClass(), DateType.BASE); + _stdSimpleTypes.put(DoubleType.BASE.getReturnedClass(), DoubleType.BASE); + _stdSimpleTypes.put(double.class, DoubleType.BASE); + _stdSimpleTypes.put(FloatType.BASE.getReturnedClass(), FloatType.BASE); + _stdSimpleTypes.put(float.class, FloatType.BASE); + _stdSimpleTypes.put(IntegerType.BASE.getReturnedClass(), IntegerType.BASE); + _stdSimpleTypes.put(int.class, IntegerType.BASE); + _stdSimpleTypes.put(LongType.BASE.getReturnedClass(), LongType.BASE); + _stdSimpleTypes.put(long.class, LongType.BASE); + _stdSimpleTypes.put(ShortType.BASE.getReturnedClass(), ShortType.BASE); + _stdSimpleTypes.put(Short.class, ShortType.BASE); + _stdSimpleTypes.put(StringType.BASE.getReturnedClass(), StringType.BASE); + _stdSimpleTypes.put(TimestampType.BASE.getReturnedClass(), TimestampType.BASE); + _stdSimpleTypes.put(TimeType.BASE.getReturnedClass(), TimeType.BASE); + _stdSimpleTypes.put(ObjType.BASE.getReturnedClass(), ObjType.BASE); + _stdSimpleTypes.put(BlobType.BASE.getReturnedClass(), BlobType.BASE); + } + + + public static HashMap, StandardMutlValType> _stdMapValTypes = new HashMap, StandardMutlValType>(); + static{ + _stdMapValTypes.put(HashMapType.BASE.getReturnedClass(), HashMapType.BASE); + _stdMapValTypes.put(TreeMapType.BASE.getReturnedClass(), TreeMapType.BASE); + _stdMapValTypes.put(MapType.BASE.getReturnedClass(), MapType.BASE); + } + + public static HashMap, StandardMutlValType> _stdSetValTypes = new HashMap, StandardMutlValType>(); + static{ + _stdSetValTypes.put(SetType.BASE.getReturnedClass(), SetType.BASE); + _stdSetValTypes.put(HashSetType.BASE.getReturnedClass(), HashSetType.BASE); + _stdSetValTypes.put(TreeSetType.BASE.getReturnedClass(), TreeSetType.BASE); + } + + public static HashMap, StandardMutlValType> _stdListValTypes = new HashMap, StandardMutlValType>(); + static{ + _stdListValTypes.put(ListType.BASE.getReturnedClass(), ListType.BASE); + } + + + public static HashMap, StandardMutlValType> _stdMultValTypes = new HashMap, StandardMutlValType>(); + static{ + _stdMultValTypes.putAll(_stdMapValTypes); + _stdMultValTypes.putAll(_stdSetValTypes); + _stdMultValTypes.putAll(_stdListValTypes); + } + + + + + + + + private static Set> NUMBER_TYPES = new HashSet>(); + static{ + NUMBER_TYPES.add(Double.class); + NUMBER_TYPES.add(Long.class); + NUMBER_TYPES.add(Integer.class); + NUMBER_TYPES.add(Short.class); + NUMBER_TYPES.add(Byte.class); + + NUMBER_TYPES.add(double.class); + NUMBER_TYPES.add(long.class); + NUMBER_TYPES.add(int.class); + NUMBER_TYPES.add(short.class); + NUMBER_TYPES.add(byte.class); + } + + + private static Set> SIMPLE_TYPES = new HashSet>(); + static{ + SIMPLE_TYPES.add(String.class); + SIMPLE_TYPES.add(Character.class); + SIMPLE_TYPES.addAll(NUMBER_TYPES); + } + + + public static StandardType transToStandardType(Class t){ + Assert.logic(_stdSimpleTypes.containsKey(t),"只能转换基本类型,但类型为["+t+"]"); + return _stdSimpleTypes.get(t); + } + + public static StandardMutlValType getStandardMultTypeByName(String name){ + Assert.hasLength(name,"类型名不允许为空"); + for (StandardMutlValType type : _stdMultValTypes.values()) { + if(type.getName().equals(name)){ + return type; + } + } + Assert.fail("找不到名称["+name+"]的标准类型"); + return null; + } + + public static StandardType getStandardTypeByName(String name){ + Assert.hasLength(name,"类型名不允许为空"); + for (StandardType type : _stdSimpleTypes.values()) { + if(type.getName().equals(name)){ + return type; + } + } + Assert.fail("找不到名称["+name+"]的标准类型"); + return null; + } + + + public static StandardMutlValType transToStandardMutlValType(Class t){ + Assert.logic(_stdMultValTypes.containsKey(t),"类型为["+t+"],无法找到相应的标准型"); + return _stdMultValTypes.get(t); + } + + public static boolean isMutlType (Class t){ + return _stdMultValTypes.containsKey(t); + } + + public static boolean isMapType(Class t){ + return _stdMapValTypes.containsKey(t); + } + + public static boolean isSetType(Class t){ + return _stdSetValTypes.containsKey(t); + } + + public static boolean isListType(Class t){ + return _stdListValTypes.containsKey(t); + } + + + public static boolean isSimpleType(Class t){ + return _stdSimpleTypes.containsKey(t); + } + + public static boolean isNumberType(Class t){ + return NUMBER_TYPES.contains(t); + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/StringType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StringType.java new file mode 100644 index 0000000..c8d9dfd --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/StringType.java @@ -0,0 +1,41 @@ +package org.code.modules.plugins.types; + +public class StringType extends AbstractType implements StandardType{ + + + public static final StandardType BASE = new StringType(0); + + public StringType(int length) { + super("std.String", "String",length, 0); + } + + @Override + public Class getReturnedClass() { + return String.class; + } + + @Override + public int typeCode() { + return TypesCode.VARCHAR; + } + + @Override + public String format(Object obj) { + return obj != null ? obj.toString(): ""; + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return xml; + } + + @Override + public boolean isNull(Object obj) { + return null == obj; + } + + + + + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/TextType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TextType.java new file mode 100644 index 0000000..d350173 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TextType.java @@ -0,0 +1,38 @@ +package org.code.modules.plugins.types; + + +import com.luqj.util.StringUtils; + +public class TextType extends AbstractType implements StandardType{ + public static final StandardType BASE = new TextType(15000); + + public TextType(int length) { + super("std.Text", "Text",length, 0); + } + + @Override + public Class getReturnedClass() { + return String.class; + } + + @Override + public int typeCode() { + return TypesCode.CLOB; + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return xml; + } + + @Override + public String format(Object obj) { + return null; + } + + @Override + public boolean isNull(Object obj) { + return StringUtils.isBlank((String) obj); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/TimeType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TimeType.java new file mode 100644 index 0000000..8d52ba4 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TimeType.java @@ -0,0 +1,48 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.NumFormat; + +import java.sql.Time; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class TimeType extends AbstractType implements StandardType{ + + private static final String TIME_FORMAT = "HH:mm:ss"; + + public static final StandardType BASE = new TimeType(); + + public TimeType() { + super("std.Time", "Time",6, 0); + } + + @Override + public Class getReturnedClass() { + return Time.class; + } + + @Override + public int typeCode() { + return TypesCode.TIME; + } + + @Override + public Object fromStringValue(String string) throws Exception { + try { + return new SimpleDateFormat(TIME_FORMAT).parse(string); + }catch (ParseException pe) { + throw pe; + } + } + + @Override + public String format(Object obj) { + return obj != null ? NumFormat.toString(((Time)obj).getTime()) : ""; + } + + @Override + public boolean isNull(Object obj) { + return obj == null; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/TimestampType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TimestampType.java new file mode 100644 index 0000000..05d2d17 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TimestampType.java @@ -0,0 +1,44 @@ +package org.code.modules.plugins.types; + + +import com.luqj.util.NumFormat; + +import java.sql.Timestamp; + + +public class TimestampType extends AbstractType implements StandardType{ + + private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + public static final StandardType BASE = new TimestampType(); + + public TimestampType() { + super("std.Timestamp", "Timestamp",14, 0); + } + + @Override + public Class getReturnedClass() { + return Timestamp.class; + } + + @Override + public int typeCode() { + return TypesCode.TIMESTAMP; + } + + @Override + public String format(Object obj) { + return obj != null ? NumFormat.toString(((Timestamp)obj).getTime()) : ""; + } + + @Override + public Object fromStringValue(String xml) throws Exception { + return NumFormat.$Long(xml); + } + + @Override + public boolean isNull(Object obj) { + return obj == null; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/TreeMapType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TreeMapType.java new file mode 100644 index 0000000..6580dc8 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TreeMapType.java @@ -0,0 +1,90 @@ +package org.code.modules.plugins.types; + +import com.luqj.util.assertion.Assert; +import com.luqj.util.reflect.ClassUtils; + +import java.lang.reflect.Field; +import java.util.*; + +public class TreeMapType extends AbstractType implements StandardMutlValType{ + + public static final StandardMutlValType BASE = new TreeMapType(); + + private Class specificType; + + private TreeMapType() { + super("std.TreeMap", "TreeMap"); + } + + @Override + public boolean isNull(Object obj) { + return obj == null || ((TreeMap)obj).isEmpty(); + } + public TreeMapType(Class specificType) { + super("std.TreeMap", "TreeMap"); + this.specificType = specificType; + } + + + + @Override + public Class getReturnedClass() { + return TreeMap.class; + } + + @Override + public int typeCode() { + return 0; + } + + @Override + public Class getSpecific() { + return this.specificType; + } + + + + @Override + public Collection format(Object obj) { + List values = new ArrayList(); + Map vObj = (Map) obj; + int i = 0; + StandardType vType = StdTypes.transToStandardType(specificType); + for (String key : vObj.keySet()) { + values.add(new ValEntity(key,i++,vType.format(vObj.get(key)))); + } + return values; + } + + + @Override + public StandardMutlValType instanceType(Class sType) { + return new TreeMapType(sType); + } + + + @Override + public StandardMutlValType instanceType(Field f) { + return new TreeMapType((Class) ClassUtils.getMapFieldGenericity(f)[1]); + } + + @Override + public Object fromEntityValue(Collection entitys) + throws Exception { + Assert.notNull(entitys); + TreeMap value = new TreeMap(); + if(StdTypes.isSimpleType(specificType)){ + StandardType vType = StdTypes.transToStandardType(specificType); + for (ValEntity valEntity : entitys) { + value.put(valEntity.keyName, vType.format(valEntity.value)); + } + }else{ + for (ValEntity valEntity : entitys) { + value.put(valEntity.keyName, valEntity.value); + } + } + + return value; + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/TreeSetType.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TreeSetType.java new file mode 100644 index 0000000..e31b72c --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TreeSetType.java @@ -0,0 +1,92 @@ +package org.code.modules.plugins.types; + + +import com.luqj.util.assertion.Assert; +import com.luqj.util.reflect.ClassUtils; + +import java.lang.reflect.Field; +import java.util.*; + +public class TreeSetType extends AbstractType implements StandardMutlValType{ + + public static final StandardMutlValType BASE = new TreeSetType(); + + private Class specificType; + + private TreeSetType() { + super("std.TreeSet", "TreeSet"); + } + + + public TreeSetType(Class specificType) { + super("std.TreeSet", "TreeSet"); + this.specificType = specificType; + } + + + + @Override + public Object fromEntityValue(Collection entitys) + throws Exception { + Assert.notNull(entitys); + TreeSet value = new TreeSet(); + if(StdTypes.isSimpleType(specificType)){ + StandardType vType = StdTypes.transToStandardType(specificType); + for (ValEntity valEntity : entitys) { + value.add(vType.format(valEntity.value)); + } + }else{ + for (ValEntity valEntity : entitys) { + value.add(valEntity.value); + } + } + + return value; + } + + @Override + public Class getReturnedClass() { + return TreeSet.class; + } + + @Override + public boolean isNull(Object obj) { + return obj == null || ((TreeSet)obj).isEmpty(); + } + @Override + public int typeCode() { + return 0; + } + + @Override + public Class getSpecific() { + return this.specificType; + } + + + + @Override + public Collection format(Object obj) { + List values = new ArrayList(); + Set vObj = (Set) obj; + int i = 0; + for (Object val : vObj) { + StandardType vType = StdTypes.transToStandardType(specificType); + values.add(new ValEntity(i++,vType.format(val))); + } + return values; + } + + + @Override + public StandardMutlValType instanceType(Class sType) { + return new TreeSetType(sType); + } + + + @Override + public StandardMutlValType instanceType(Field f) { + return new TreeSetType((Class) ClassUtils.getSetFieldGenericity(f)); + } + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/Type.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/Type.java new file mode 100644 index 0000000..82c9c27 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/Type.java @@ -0,0 +1,16 @@ +package org.code.modules.plugins.types; + +import java.io.Serializable; + + +public interface Type extends Serializable{ + + public int getPrecsn(); + + public int getLength(); + + public String getCode(); + + public String getName(); + +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/TypeEnum.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TypeEnum.java new file mode 100644 index 0000000..5c0904d --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TypeEnum.java @@ -0,0 +1,67 @@ +package org.code.modules.plugins.types; + + +public enum TypeEnum { + + Boolean(BooleanType.class, 0, "布尔型"), + + Byte(ByteType.class, 1, "数值"), + + Short(ShortType.class, 2, "数值"), + + Integer(IntegerType.class, 3, "数值"), + + Long(LongType.class, 4, "数值"), + + BigInteger(BigIntegerType.class, 5, "数值"), + + Float(FloatType.class, 6, "数值"), + + Double(DoubleType.class, 7, "数值"), + + BigDecimal(BigDecimalType.class, 8, "数值"), + + + + Blob(BlobType.class, 9, "字符"), + + String(StringType.class, 10, "字符"), + + Text(TextType.class, 11, "字符"), + + + + Time(TimeType.class, 12, "时间"), + + Timestamp(TimestampType.class, 13, "时间"), + + Date(DateType.class, 14, "时间"), + + Object(ObjType.class, 15, "其他"); + + + + private TypeEnum(Class type, int priority, String zhName) { + this.type = type; + this.zhName = zhName; + } + + private Class type; + + /**优先级**/ + private int priority; + + private String zhName; + + public Class getType() { + return type; + } + + public int getPriority() { + return priority; + } + + public java.lang.String getZhName() { + return zhName; + } +} diff --git a/luqj-plugin/src/main/java/org/code/modules/plugins/types/TypesCode.java b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TypesCode.java new file mode 100644 index 0000000..08959e2 --- /dev/null +++ b/luqj-plugin/src/main/java/org/code/modules/plugins/types/TypesCode.java @@ -0,0 +1,282 @@ +package org.code.modules.plugins.types; + +import java.sql.Types; + +public class TypesCode{ + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * BIT. + */ + public final static int BIT = Types.BIT; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * TINYINT. + */ + public final static int TINYINT = Types.TINYINT; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * SMALLINT. + */ + public final static int SMALLINT = Types.SMALLINT; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * INTEGER. + */ + public final static int INTEGER = Types.INTEGER; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * BIGINT. + */ + public final static int BIGINT = -5; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * FLOAT. + */ + public final static int FLOAT = 6; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * REAL. + */ + public final static int REAL = 7; + + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * DOUBLE. + */ + public final static int DOUBLE = 8; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * NUMERIC. + */ + public final static int NUMERIC = 2; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * DECIMAL. + */ + public final static int DECIMAL = 3; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * CHAR. + */ + public final static int CHAR = 1; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * VARCHAR. + */ + public final static int VARCHAR = 12; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * LONGVARCHAR. + */ + public final static int LONGVARCHAR = -1; + + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * DATE. + */ + public final static int DATE = 91; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * TIME. + */ + public final static int TIME = 92; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * TIMESTAMP. + */ + public final static int TIMESTAMP = 93; + + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * BINARY. + */ + public final static int BINARY = -2; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * VARBINARY. + */ + public final static int VARBINARY = -3; + +/** + *

The constant in the Java programming language, sometimes referred + * to as a type code, that identifies the generic SQL type + * LONGVARBINARY. + */ + public final static int LONGVARBINARY = -4; + +/** + *

The constant in the Java programming language + * that identifies the generic SQL value + * DEFAULT. + */ + public final static int NULL = 0; + + /** + * The constant in the Java programming language that indicates + * that the SQL type is database-specific and + * gets mapped to a Java object that can be accessed via + * the methods getObject and setObject. + */ + public final static int OTHER = 1111; + + + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type + * JAVA_OBJECT. + * @since 1.2 + */ + public final static int JAVA_OBJECT = 2000; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type + * DISTINCT. + * @since 1.2 + */ + public final static int DISTINCT = 2001; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type + * STRUCT. + * @since 1.2 + */ + public final static int STRUCT = 2002; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type + * ARRAY. + * @since 1.2 + */ + public final static int ARRAY = 2003; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type + * BLOB. + * @since 1.2 + */ + public final static int BLOB = 2004; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type + * CLOB. + * @since 1.2 + */ + public final static int CLOB = 2005; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type + * REF. + * @since 1.2 + */ + public final static int REF = 2006; + + /** + * The constant in the Java programming language, somtimes referred to + * as a type code, that identifies the generic SQL type DATALINK. + * + * @since 1.4 + */ + public final static int DATALINK = 70; + + /** + * The constant in the Java programming language, somtimes referred to + * as a type code, that identifies the generic SQL type BOOLEAN. + * + * @since 1.4 + */ + public final static int BOOLEAN = 16; + + //------------------------- JDBC 4.0 ----------------------------------- + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type ROWID + * + * @since 1.6 + * + */ + public final static int ROWID = -8; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type NCHAR + * + * @since 1.6 + */ + public static final int NCHAR = -15; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type NVARCHAR. + * + * @since 1.6 + */ + public static final int NVARCHAR = -9; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type LONGNVARCHAR. + * + * @since 1.6 + */ + public static final int LONGNVARCHAR = -16; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type NCLOB. + * + * @since 1.6 + */ + public static final int NCLOB = 2011; + + /** + * The constant in the Java programming language, sometimes referred to + * as a type code, that identifies the generic SQL type XML. + * + * @since 1.6 + */ + public static final int SQLXML = 2009; +} diff --git a/pom.xml b/pom.xml index b4ec09d..b08f0d9 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,6 @@ ruoyi http://www.ruoyi.vip susdt管理系统 - 3.4.0 UTF-8 @@ -231,6 +230,11 @@ luqj-thymeleaf luqj-opencv luqj-baidu-ai + luqj-plugin + luqj-plugin-interface + luqj-plugin-demo + luqj-djl + luqj-ec pom diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index 865c915..26e8458 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -14,13 +14,47 @@ web服务入口 - + + + + com.google.protobuf + protobuf-java + 3.25.5 + + + + + com.ruoyi + luqj-djl + 3.4.0 + + + com.ruoyi + luqj-ec + 3.4.0 + + + com.ruoyi + luqj-plugin + 3.4.0 + com.belerweb pinyin4j 2.5.1 + + + com.madgag.spongycastle + prov + 1.58.0.0 + + + com.google.protobuf + protobuf-java + 3.25.5 + com.hankcs hanlp diff --git a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java index c7065ea..f418532 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java @@ -13,7 +13,7 @@ import org.springframework.context.annotation.Bean; * @author ruoyi */ @SpringBootApplication(scanBasePackages = { - "com.ruoyi", "com.luqj"}, exclude = {DataSourceAutoConfiguration.class}) + "com.ruoyi", "com.luqj","org.code.modules.plugins",}, exclude = {DataSourceAutoConfiguration.class}) @MapperScan({ "com.luqj.*.mapper", "com.ruoyi.*.mapper" diff --git a/ruoyi-admin/src/main/java/com/ruoyi/task/AggregationTask.java b/ruoyi-admin/src/main/java/com/ruoyi/task/AggregationTask.java new file mode 100644 index 0000000..3d7ef83 --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/task/AggregationTask.java @@ -0,0 +1,130 @@ +package com.ruoyi.task; + +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.*; +import com.ruoyi.system.service.*; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.tron.trident.core.ApiWrapper; + +import java.math.BigDecimal; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +@Slf4j +@Component("AggregationTask") +public class AggregationTask { + @Autowired + private IUsdtAggregationTaskService usdtAggregationTaskService; + @Autowired + private IUsdtAggregationTaskItemService usdtAggregationTaskItemService; + @Autowired + private ITronService tronService; + @Autowired + private IUsdtFundFlowService usdtFundFlowService; + @Autowired + private IWalletAddressService walletAddressService; + @Autowired + private IWeb3WalletService web3WalletService; + + @Scheduled(cron = "0 */10 * * * ?") +// @Scheduled(cron = "0/10 * * * * ?") + public void execute() { + List taskPluses = this.usdtAggregationTaskService.getListByStatusAndLtExeTime(0, new Date()); + for (UsdtAggregationTaskPlus taskPlus : taskPluses) { + Web3WalletPlus web3Wallet = this.web3WalletService.getById(taskPlus.getUserId()); + if (web3Wallet == null) { + web3Wallet = new Web3WalletPlus(); + web3Wallet.setId(taskPlus.getUserId()); + web3Wallet.setPassword(UUID.randomUUID().toString()); + web3Wallet.setEthBalance(new BigDecimal(0)); + web3Wallet.setTrxBalance(new BigDecimal(0)); + web3Wallet.setUsdtBalance(new BigDecimal(0)); + web3Wallet.setCreatedAt(new Date()); + web3Wallet.setUpdatedAt(new Date()); + this.web3WalletService.save(web3Wallet); + } + List itemPluses = this.usdtAggregationTaskItemService.getListByStatusAndParentId(0, taskPlus.getId()); + int success = 0; + for (UsdtAggregationTaskItemPlus itemPlus : itemPluses) { + WalletAddressPlus walletAddressPlus = walletAddressService.getByTokenAndAppId(itemPlus.getTokenAddress(), itemPlus.getAppId()); + if(walletAddressPlus.getUpdatedAt().getTime()< itemPlus.getCreatedAt().getTime()){ + itemPlus.setStatus(0); + itemPlus.setRemark("等待钱包更新"); + usdtAggregationTaskItemService.updateById(itemPlus); + continue; + } + ApiWrapper api = tronService.buildApiWrapper(walletAddressPlus.getTokenKey()); + try { + if(walletAddressPlus.getEnergyNum() < tronService.defaultEstimateEnergy()){ + itemPlus.setStatus(0); + itemPlus.setRemark("能量不足,需要手续费"); + usdtAggregationTaskItemService.updateById(itemPlus); + continue; + } + long bandwidth = tronService.defaultEstimateBandwidth(); + if(bandwidth > walletAddressPlus.getBandwidthNum()){ + itemPlus.setStatus(0); + itemPlus.setRemark("带宽不足需要手续费"); + usdtAggregationTaskItemService.updateById(itemPlus); + continue; + } + if(bandwidth > walletAddressPlus.getBandwidthStakedNum() + && bandwidth > (walletAddressPlus.getBandwidthNum()-walletAddressPlus.getBandwidthStakedNum())){ + itemPlus.setStatus(0); + itemPlus.setRemark("代理|免费带宽不足需要手续费"); + usdtAggregationTaskItemService.updateById(itemPlus); + continue; + } + if(walletAddressPlus.getWithdrawUsdtBalance().subtract(itemPlus.getOpeAmount()).doubleValue() < 0){ + itemPlus.setStatus(2); + itemPlus.setRemark("超额或者重复提现,请排查"); + usdtAggregationTaskItemService.updateById(itemPlus); + continue; + } + String result = this.tronService.usdtTrans(api, itemPlus.getTokenAddress(), itemPlus.getDistTokenAddress(), itemPlus.getOpeAmount().toString()); + //验证是否成功 TODO + if (StringUtils.isNotEmpty(result)) { + itemPlus.setStatus(1); + itemPlus.setRemark(result); + walletAddressPlus.setWithdrawUsdtBalance(walletAddressPlus.getWithdrawUsdtBalance().subtract(itemPlus.getOpeAmount())); + web3Wallet.setUsdtBalance(web3Wallet.getUsdtBalance().subtract(itemPlus.getOpeAmount())); + + UsdtFundFlowPlus shFlow = new UsdtFundFlowPlus(); + shFlow.setAppId(itemPlus.getAppId()); + shFlow.setAmount(itemPlus.getOpeAmount()); + shFlow.setOrderId(itemPlus.getId()); + shFlow.setOpType(2); + shFlow.setUserId(itemPlus.getUserId()); + shFlow.setToken(itemPlus.getTokenAddress()); + shFlow.setRemark("归集成功"); + shFlow.setCreatedAt(new Date()); + shFlow.setUpdatedAt(new Date()); + this.usdtFundFlowService.save(shFlow); + + this.web3WalletService.updateById(web3Wallet); + this.walletAddressService.updateById(walletAddressPlus); + success++; + } else { + itemPlus.setStatus(0); + itemPlus.setRemark("归集失败"); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + itemPlus.setStatus(0); + itemPlus.setRemark(e.getMessage()); + } + itemPlus.setUpdatedAt(new Date()); + this.usdtAggregationTaskItemService.updateById(itemPlus); + api.close(); + } + if(success == itemPluses.size() && itemPluses.size() > 0){ + taskPlus.setStatus(1); + this.usdtAggregationTaskService.updateById(taskPlus); + } + } + } +} diff --git a/ruoyi-admin/src/main/java/com/ruoyi/task/SplitAccountsTask.java b/ruoyi-admin/src/main/java/com/ruoyi/task/SplitAccountsTask.java index 33cb8dc..8539634 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/task/SplitAccountsTask.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/task/SplitAccountsTask.java @@ -1,20 +1,13 @@ package com.ruoyi.task; -import com.ruoyi.system.domain.UsdtFundFlow; -import com.ruoyi.system.domain.UsdtFundFlowPlus; -import com.ruoyi.system.domain.UsdtOrdersPlus; -import com.ruoyi.system.domain.UsdtUserSettlementConfigurationPlus; -import com.ruoyi.system.service.IUsdtFundFlowService; -import com.ruoyi.system.service.IUsdtOrdersService; -import com.ruoyi.system.service.IUsdtUserSettlementConfigurationService; +import com.ruoyi.system.domain.*; +import com.ruoyi.system.service.*; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; @Component("splitAccountsTask") public class SplitAccountsTask { @@ -24,14 +17,26 @@ public class SplitAccountsTask { private IUsdtUserSettlementConfigurationService usdtUserSettlementConfigurationService; @Autowired private IUsdtFundFlowService usdtFundFlowService; + @Autowired + private IWalletAddressService walletAddressService; + @Autowired + private IWeb3WalletService web3WalletService; +// @Scheduled(cron = "0/10 * * * * ?") + @Scheduled(cron = "0 */10 * * * ?") public void execute() { List list = usdtOrdersService.getWillSettlement(1000); Map configMap = new HashMap(); List fundFlows = new ArrayList(); List ids = new ArrayList<>(); + Map web3WalletMap = new HashMap<>(); for (UsdtOrdersPlus usdtOrdersPlus : list) { + WalletAddressPlus walletAddressPlus = walletAddressService.getByTokenAndAppId(usdtOrdersPlus.getToken(),usdtOrdersPlus.getAppId() + ,WalletAddressPlus::getId,WalletAddressPlus::getWithdrawUsdtBalance); + if(walletAddressPlus.getWithdrawUsdtBalance() == null){ + walletAddressPlus.setWithdrawUsdtBalance(new BigDecimal(0)); + } UsdtUserSettlementConfigurationPlus config = configMap.getOrDefault(usdtOrdersPlus.getUserId(), usdtUserSettlementConfigurationService.getByUserId(usdtOrdersPlus.getUserId())); - BigDecimal yj = usdtOrdersPlus.getActualAmount().multiply(config.getCommissionRate()); + BigDecimal yj = usdtOrdersPlus.getActualAmount().multiply(config.getCommissionRate()); UsdtFundFlowPlus yjFlow = new UsdtFundFlowPlus(); yjFlow.setAppId(usdtOrdersPlus.getAppId()); yjFlow.setAmount(yj); @@ -40,6 +45,23 @@ public class SplitAccountsTask { yjFlow.setUserId(usdtOrdersPlus.getUserId()); yjFlow.setToken(usdtOrdersPlus.getToken()); + Web3WalletPlus web3Wallet = web3WalletMap.get(usdtOrdersPlus.getUserId()); + if (web3Wallet == null) { + web3Wallet = new Web3WalletPlus(); + web3Wallet.setId(usdtOrdersPlus.getUserId()); + web3Wallet.setPassword(UUID.randomUUID().toString()); + web3Wallet.setEthBalance(new BigDecimal(0)); + web3Wallet.setTrxBalance(new BigDecimal(0)); + web3Wallet.setUsdtBalance(new BigDecimal(0)); + web3Wallet.setCreatedAt(new Date()); + web3Wallet.setUpdatedAt(new Date()); + this.web3WalletService.save(web3Wallet); + } else { + web3Wallet.setUpdatedAt(new Date()); + } + web3Wallet.setUsdtBalance(web3Wallet.getUsdtBalance().add(usdtOrdersPlus.getActualAmount().subtract(yj))); + web3WalletMap.put(usdtOrdersPlus.getUserId(), web3Wallet); + UsdtFundFlowPlus shFlow = new UsdtFundFlowPlus(); shFlow.setAppId(usdtOrdersPlus.getAppId()); shFlow.setAmount(usdtOrdersPlus.getActualAmount().subtract(yj)); @@ -47,16 +69,25 @@ public class SplitAccountsTask { shFlow.setOpType(0); shFlow.setUserId(usdtOrdersPlus.getUserId()); shFlow.setToken(usdtOrdersPlus.getToken()); - + walletAddressPlus.setWithdrawUsdtBalance(walletAddressPlus.getWithdrawUsdtBalance().add(shFlow.getAmount())); fundFlows.add(yjFlow); fundFlows.add(shFlow); ids.add(usdtOrdersPlus.getId()); + this.walletAddressService.updateWithdrawUsdtBalanceById(walletAddressPlus.getId(),walletAddressPlus.getWithdrawUsdtBalance()); } - if(!fundFlows.isEmpty()){ + Iterator> iterator = web3WalletMap.entrySet().iterator(); + List updates = new ArrayList<>(); + while (iterator.hasNext()) { + updates.add(iterator.next().getValue()); + } + if (!updates.isEmpty()) { + web3WalletService.updateBatchById(updates); + } + if (!fundFlows.isEmpty()) { usdtFundFlowService.saveBatch(fundFlows); } - if(ids.isEmpty()){ - this.usdtOrdersService.updateSettlementStatusByIds(ids,1); + if (!ids.isEmpty()) { + this.usdtOrdersService.updateSettlementStatusByIds(ids, 1); } } } diff --git a/ruoyi-admin/src/main/java/com/ruoyi/task/WalletAddressTask.java b/ruoyi-admin/src/main/java/com/ruoyi/task/WalletAddressTask.java new file mode 100644 index 0000000..58a286c --- /dev/null +++ b/ruoyi-admin/src/main/java/com/ruoyi/task/WalletAddressTask.java @@ -0,0 +1,74 @@ +package com.ruoyi.task; + +import com.ruoyi.system.domain.WalletAddressPlus; +import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; +import com.ruoyi.system.service.ITronService; +import com.ruoyi.system.service.IWalletAddressService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.tron.trident.core.ApiWrapper; + +import java.math.BigDecimal; +import java.util.Date; +import java.util.List; +@Slf4j +@Component("WalletAddressTask") +public class WalletAddressTask { + @Autowired + private ITronService tronService; + @Autowired + private IWalletAddressService walletAddressService; +// @Scheduled(cron = "0/5 * * * * ?") +@Scheduled(cron = "0 */10 * * * ?") + public void execute() { + List walletAddressPluses = walletAddressService.list(); + for (WalletAddressPlus walletAddressPlus : walletAddressPluses) { + ApiWrapper api = tronService.buildApiWrapper(walletAddressPlus.getTokenKey()); + BigDecimal amout = tronService.getUsdtBalance(api,walletAddressPlus.getToken()); + walletAddressPlus.setUsdtBalance(amout); + amout = tronService.getTRxBalance(api,walletAddressPlus.getToken()); + walletAddressPlus.setTrxBalance(amout); + EnergyAndBandwidthVo energyAndBandwidthVo = tronService.energyAndBandwidth(walletAddressPlus.getToken()); + walletAddressPlus.setEnergyNum(energyAndBandwidthVo.getEnergy().longValue()); + walletAddressPlus.setBandwidthNum(energyAndBandwidthVo.getBandwidth().longValue()); + amout = tronService.votedBalance(api,walletAddressPlus.getToken()); + walletAddressPlus.setVotedNum(amout.longValue()); + amout = tronService.stakedTrxBalance(api,walletAddressPlus.getToken(),1); + walletAddressPlus.setEnergyStakedTrxNum(amout.longValue()); + amout = tronService.stakedTrxBalance(api,walletAddressPlus.getToken(),0); + walletAddressPlus.setBandwidthStakedTrxNum(amout.longValue()); + energyAndBandwidthVo = tronService.allDelegatedDnergyAndBandwidth(walletAddressPlus.getToken()); + walletAddressPlus.setAcquiredDelegatedBandwidthValue(energyAndBandwidthVo.getAcquiredBandwidth()); + walletAddressPlus.setAcquiredDelegatedEnergyValue(energyAndBandwidthVo.getAcquiredEnergy()); + walletAddressPlus.setDelegatedBandwidthValue(energyAndBandwidthVo.getDelegateBandwidth()); + walletAddressPlus.setDelegatedEnergyValue(energyAndBandwidthVo.getDelegateEnergy()); + walletAddressPlus.setBandwidthStakedNum(energyAndBandwidthVo.getBandwidthStakedNum()); + + amout = tronService.delegatedStakedTrxBalance(api,walletAddressPlus.getToken(),1); + walletAddressPlus.setDelegatedEnergyTrxNum(amout.longValue()); + amout = tronService.delegatedStakedTrxBalance(api,walletAddressPlus.getToken(),0); + walletAddressPlus.setDelegatedBandwidthTrxNum(amout.longValue()); + + amout = tronService.acquiredDelegatedStakedTrxBalance(api,walletAddressPlus.getToken(),1); + walletAddressPlus.setAcquiredDelegatedEnergyTrxNum(amout.longValue()); + amout = tronService.acquiredDelegatedStakedTrxBalance(api,walletAddressPlus.getToken(),0); + walletAddressPlus.setAcquiredDelegatedBandwidthTrxNum(amout.longValue()); + + amout = tronService.voteBalance(api,walletAddressPlus.getToken()); + walletAddressPlus.setVoteNum(amout.longValue()+walletAddressPlus.getDelegatedBandwidthTrxNum()+ walletAddressPlus.getDelegatedEnergyTrxNum()); + + walletAddressPlus.setStakedTrxNum(walletAddressPlus.getVoteNum()); + + if(walletAddressPlus.getStakedTrxNum() != energyAndBandwidthVo.getStakedTrxNum().longValue()){ + log.error("please check stakedTrxNum is true"); + walletAddressPlus.setStakedTrxNum(energyAndBandwidthVo.getStakedTrxNum()); + walletAddressPlus.setVoteNum(walletAddressPlus.getStakedTrxNum()); + } + walletAddressPlus.setUpdatedAt(new Date()); + walletAddressService.updateById(walletAddressPlus); + api.close(); + } + } +} diff --git a/ruoyi-admin/src/main/resources/application-local.yml b/ruoyi-admin/src/main/resources/application-local.yml index 8313311..14e2b1d 100644 --- a/ruoyi-admin/src/main/resources/application-local.yml +++ b/ruoyi-admin/src/main/resources/application-local.yml @@ -11,9 +11,9 @@ spring: # 主库数据源 master: #url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 - url: jdbc:mysql://192.168.3.243:3306/epusdt?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + url: jdbc:mysql://gitlab.chatshop.com.cn:3309/epusdt?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root - password: Lqj7667213.520 + password: lqj7667213 # 从库数据源 slave: # 从数据源开关/默认关闭 diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml index 130382f..983a9c8 100644 --- a/ruoyi-admin/src/main/resources/application.yml +++ b/ruoyi-admin/src/main/resources/application.yml @@ -3,6 +3,7 @@ ruoyi: whiteList: - /demo/index - /system/demoUsdt/** + - /system/test/testPlugin # 名称 name: RuoYi # 版本 @@ -18,6 +19,11 @@ ruoyi: # 验证码类型 math 数组计算 char 字符验证 captchaType: math +simcse: + path: D:/voice-room/simcse +plugin: + base: + dir: D:/luqj-plugins # 开发环境配置 server: # 服务器的HTTP端口,默认为8080 @@ -42,6 +48,9 @@ logging: com.ruoyi: debug org.springframework: warn +tron: + env: + type: nile # Spring配置 spring: resources: @@ -80,7 +89,7 @@ spring: redis: # 地址 #host: localhost - host: 192.168.3.243 + host: gitlab.chatshop.com.cn # 端口,默认为6379 port: 16379 # 数据库索引 diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java index 1600733..a81a901 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/StringUtils.java @@ -1,11 +1,7 @@ package com.ruoyi.common.utils; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; + import com.ruoyi.common.core.text.StrFormatter; /** @@ -20,7 +16,9 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils /** 下划线 */ private static final char SEPARATOR = '_'; - + public static String uuid(){ + return UUID.randomUUID().toString().replaceAll("-", ""); + } /** * 获取参数不为空值 * diff --git a/ruoyi-generator/src/main/resources/vm/vue/userIndex.vue.vm b/ruoyi-generator/src/main/resources/vm/vue/userIndex.vue.vm index 4467bc4..9c3daef 100644 --- a/ruoyi-generator/src/main/resources/vm/vue/userIndex.vue.vm +++ b/ruoyi-generator/src/main/resources/vm/vue/userIndex.vue.vm @@ -83,7 +83,7 @@ icon="el-icon-plus" size="mini" @click="handleAdd" - v-hasPermi="['${moduleName}:${businessName}:add']" + v-hasPermi="['${moduleName}:${businessName}:user-add']" >新增 @@ -94,7 +94,7 @@ size="mini" :disabled="single" @click="handleUpdate" - v-hasPermi="['${moduleName}:${businessName}:edit']" + v-hasPermi="['${moduleName}:${businessName}:user-edit']" >修改 @@ -105,7 +105,7 @@ size="mini" :disabled="multiple" @click="handleDelete" - v-hasPermi="['${moduleName}:${businessName}:remove']" + v-hasPermi="['${moduleName}:${businessName}:user-remove']" >删除 @@ -142,14 +142,14 @@ type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" - v-hasPermi="['${moduleName}:${businessName}:edit']" + v-hasPermi="['${moduleName}:${businessName}:user-edit']" >修改 删除 diff --git a/ruoyi-system/pom.xml b/ruoyi-system/pom.xml index f54b0fb..d75c31d 100644 --- a/ruoyi-system/pom.xml +++ b/ruoyi-system/pom.xml @@ -14,8 +14,74 @@ system系统模块 - + + + + com.google.protobuf + protobuf-java + 3.25.5 + + + + + com.github.tronprotocol + tron-wallet-cli + 1.2.0 + + + + io.grpc + grpc-stub + 1.60.0 + + + + + io.grpc + grpc-protobuf + 1.60.0 + + + + + io.grpc + grpc-netty + 1.60.0 + + + io.github.tronprotocol + trident + 0.10.0 + + + + com.madgag.spongycastle + prov + 1.58.0.0 + + + + + org.bitcoinj + bitcoinj-core + 0.17 + + + com.squareup.okhttp + okhttp + + + com.google.protobuf + protobuf-java + + + + + com.github.tronprotocol + tron-protobuf + 1.0 + com.github.binarywang weixin-java-miniapp @@ -31,6 +97,17 @@ com.ruoyi ruoyi-common + + com.ruoyi + luqj-plugin + 3.4.0 + + + org.adminframework.boot + luqj-plugin-interface + 2.3.0 + compile + diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/TestPluginController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/TestPluginController.java new file mode 100644 index 0000000..ff14725 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/TestPluginController.java @@ -0,0 +1,23 @@ +package com.ruoyi.system.controller; + +import com.ruoyi.common.core.domain.AjaxResult; +import org.code.modules.plugins.PluginBeanFactory; +import org.code.modules.plugins.service.IPluginTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/system/test") +public class TestPluginController { + @Autowired + private PluginBeanFactory pluginBeanFactory; + + @GetMapping(value = "/testPlugin") + public AjaxResult testPlugin() { + IPluginTest pluginTest = pluginBeanFactory.getBean("pluginDemo", "1.0.0", IPluginTest.class); + System.out.println(pluginTest.funcExec("dd")); + return AjaxResult.success(pluginTest.funcExec("dd")); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/UsdtAggregationTaskController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/UsdtAggregationTaskController.java new file mode 100644 index 0000000..c340bdc --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/UsdtAggregationTaskController.java @@ -0,0 +1,168 @@ +package com.ruoyi.system.controller; + +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.select.Ids; +import com.ruoyi.common.select.SelectItem; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.system.domain.UsdtAggregationTask; +import com.ruoyi.system.domain.UsdtAggregationTaskPlus; +import com.ruoyi.system.service.IUsdtAggregationTaskService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 归集任务Controller + * + * @author luqj + * @date 2026-01-01 + */ +@RestController +@RequestMapping("/system/usdtTask") +public class UsdtAggregationTaskController extends BaseController { + @Autowired + private IUsdtAggregationTaskService usdtAggregationTaskService; + + @PreAuthorize("@ss.hasPermi('system:usdtTask:getByIds')") + @PostMapping("/getByIds") + public AjaxResult getByIds(@RequestBody Ids ids) { + List list = usdtAggregationTaskService.getByIds(ids.getLongIds(), false, UsdtAggregationTaskPlus::getTaskName, UsdtAggregationTaskPlus::getId); + return AjaxResult.success(list); + } + + @PreAuthorize("@ss.hasPermi('system:usdtTask:user-getByIds')") + @PostMapping("/user/getByIds") + public AjaxResult userGetByIds(@RequestBody Ids ids) { + List list = usdtAggregationTaskService.getByIds(ids.getLongIds(), true, UsdtAggregationTaskPlus::getUserId, UsdtAggregationTaskPlus::getTaskName, UsdtAggregationTaskPlus::getId); + return AjaxResult.success(list); + } + + @PreAuthorize("@ss.hasPermi('system:usdtTask:select')") + @GetMapping("/select") + public AjaxResult select(String keyword) { + List list = usdtAggregationTaskService.select(keyword, false); + return AjaxResult.success(list); + } + + @PreAuthorize("@ss.hasPermi('system:usdtTask:user-select')") + @GetMapping("/user/select") + public AjaxResult userSelect(String keyword) { + List list = usdtAggregationTaskService.select(keyword, true); + return AjaxResult.success(list); + } + + /** + * 查询归集任务列表 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:list')") + @GetMapping("/list") + public TableDataInfo list(UsdtAggregationTask usdtAggregationTask) { + startPage(); + List list = usdtAggregationTaskService.selectUsdtAggregationTaskList(usdtAggregationTask, false); + return getDataTable(list); + } + + /** + * 查询归集任务列表 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:user-list')") + @GetMapping("/user/list") + public TableDataInfo userList(UsdtAggregationTask usdtAggregationTask) { + startPage(); + List list = usdtAggregationTaskService.selectUsdtAggregationTaskList(usdtAggregationTask, true); + return getDataTable(list); + } + + /** + * 导出归集任务列表 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:export')") + @Log(title = "归集任务", businessType = BusinessType.EXPORT) + @GetMapping("/export") + public AjaxResult export(UsdtAggregationTask usdtAggregationTask) { + List list = usdtAggregationTaskService.selectUsdtAggregationTaskList(usdtAggregationTask, false); + ExcelUtil util = new ExcelUtil(UsdtAggregationTask.class); + return util.exportExcel(list, "usdtTask"); + } + + /** + * 获取归集任务详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(usdtAggregationTaskService.selectUsdtAggregationTaskById(id, false)); + } + + /** + * 获取归集任务详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:user-query')") + @GetMapping(value = "/user/{id}") + public AjaxResult userGetInfo(@PathVariable("id") Long id) { + return AjaxResult.success(usdtAggregationTaskService.selectUsdtAggregationTaskById(id, true)); + } + + /** + * 新增归集任务 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:add')") + @Log(title = "归集任务", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody UsdtAggregationTask usdtAggregationTask) { + return toAjax(usdtAggregationTaskService.insertUsdtAggregationTask(usdtAggregationTask, false)); + } + + /** + * 新增归集任务 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:user-add')") + @Log(title = "归集任务", businessType = BusinessType.INSERT) + @PostMapping("/user") + public AjaxResult userAdd(@RequestBody UsdtAggregationTask usdtAggregationTask) { + return toAjax(usdtAggregationTaskService.insertUsdtAggregationTask(usdtAggregationTask, true)); + } + + /** + * 修改归集任务 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:edit')") + @Log(title = "归集任务", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody UsdtAggregationTask usdtAggregationTask) { + return toAjax(usdtAggregationTaskService.updateUsdtAggregationTask(usdtAggregationTask, false)); + } + + @PreAuthorize("@ss.hasPermi('system:usdtTask:user-edit')") + @Log(title = "归集任务", businessType = BusinessType.UPDATE) + @PutMapping("/user") + public AjaxResult userEdit(@RequestBody UsdtAggregationTask usdtAggregationTask) { + return toAjax(usdtAggregationTaskService.updateUsdtAggregationTask(usdtAggregationTask, true)); + } + + /** + * 删除归集任务 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:remove')") + @Log(title = "归集任务", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(usdtAggregationTaskService.deleteUsdtAggregationTaskByIds(ids, false)); + } + + /** + * 删除归集任务 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTask:user-remove')") + @Log(title = "归集任务", businessType = BusinessType.DELETE) + @DeleteMapping("/user/{ids}") + public AjaxResult userRemove(@PathVariable Long[] ids) { + return toAjax(usdtAggregationTaskService.deleteUsdtAggregationTaskByIds(ids, true)); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/UsdtAggregationTaskItemController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/UsdtAggregationTaskItemController.java new file mode 100644 index 0000000..da6ec82 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/UsdtAggregationTaskItemController.java @@ -0,0 +1,170 @@ +package com.ruoyi.system.controller; + +import com.ruoyi.common.annotation.Log; +import com.ruoyi.common.core.controller.BaseController; +import com.ruoyi.common.core.domain.AjaxResult; +import com.ruoyi.common.core.page.TableDataInfo; +import com.ruoyi.common.enums.BusinessType; +import com.ruoyi.common.select.Ids; +import com.ruoyi.common.select.SelectItem; +import com.ruoyi.common.utils.poi.ExcelUtil; +import com.ruoyi.system.domain.UsdtAggregationTaskItem; +import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus; +import com.ruoyi.system.service.IUsdtAggregationTaskItemService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 归集任务明细Controller + * + * @author luqj + * @date 2026-01-01 + */ +@RestController +@RequestMapping("/system/usdtTaskItem") +public class UsdtAggregationTaskItemController extends BaseController +{ + @Autowired + private IUsdtAggregationTaskItemService usdtAggregationTaskItemService; + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:getByIds')") + @PostMapping("/getByIds") + public AjaxResult getByIds(@RequestBody Ids ids) + { + List list = usdtAggregationTaskItemService.getByIds(ids.getLongIds(),false,UsdtAggregationTaskItemPlus::getRemark,UsdtAggregationTaskItemPlus::getId); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-getByIds')") + @PostMapping("/user/getByIds") + public AjaxResult userGetByIds(@RequestBody Ids ids) + { + List list = usdtAggregationTaskItemService.getByIds(ids.getLongIds(),true,UsdtAggregationTaskItemPlus::getUserId,UsdtAggregationTaskItemPlus::getRemark,UsdtAggregationTaskItemPlus::getId); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:select')") + @GetMapping("/select") + public AjaxResult select(String keyword) + { + List list = usdtAggregationTaskItemService.select(keyword,false); + return AjaxResult.success(list); + } + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-select')") + @GetMapping("/user/select") + public AjaxResult userSelect(String keyword) + { + List list = usdtAggregationTaskItemService.select(keyword,true); + return AjaxResult.success(list); + } + /** + * 查询归集任务明细列表 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:list')") + @GetMapping("/list") + public TableDataInfo list(UsdtAggregationTaskItem usdtAggregationTaskItem) + { + startPage(); + List list = usdtAggregationTaskItemService.selectUsdtAggregationTaskItemList(usdtAggregationTaskItem,false); + return getDataTable(list); + } +/** + * 查询归集任务明细列表 + */ +@PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-list')") +@GetMapping("/user/list") + public TableDataInfo userList(UsdtAggregationTaskItem usdtAggregationTaskItem) + { + startPage(); + List list = usdtAggregationTaskItemService.selectUsdtAggregationTaskItemList(usdtAggregationTaskItem,true); + return getDataTable(list); + } + /** + * 导出归集任务明细列表 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:export')") + @Log(title = "归集任务明细", businessType = BusinessType.EXPORT) + @GetMapping("/export") + public AjaxResult export(UsdtAggregationTaskItem usdtAggregationTaskItem) + { + List list = usdtAggregationTaskItemService.selectUsdtAggregationTaskItemList(usdtAggregationTaskItem,false); + ExcelUtil util = new ExcelUtil(UsdtAggregationTaskItem.class); + return util.exportExcel(list, "usdtTaskItem"); + } + + /** + * 获取归集任务明细详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) + { + return AjaxResult.success(usdtAggregationTaskItemService.selectUsdtAggregationTaskItemById(id,false)); + } + /** + * 获取归集任务明细详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-query')") + @GetMapping(value = "/user/{id}") + public AjaxResult userGetInfo(@PathVariable("id") Long id) + { + return AjaxResult.success(usdtAggregationTaskItemService.selectUsdtAggregationTaskItemById(id,true)); + } + /** + * 新增归集任务明细 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:add')") + @Log(title = "归集任务明细", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem) + { + return toAjax(usdtAggregationTaskItemService.insertUsdtAggregationTaskItem(usdtAggregationTaskItem,false)); + } + /** + * 新增归集任务明细 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-add')") + @Log(title = "归集任务明细", businessType = BusinessType.INSERT) + @PostMapping("/user") + public AjaxResult userAdd(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem) + { + return toAjax(usdtAggregationTaskItemService.insertUsdtAggregationTaskItem(usdtAggregationTaskItem,true)); + } + /** + * 修改归集任务明细 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:edit')") + @Log(title = "归集任务明细", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem) + { + return toAjax(usdtAggregationTaskItemService.updateUsdtAggregationTaskItem(usdtAggregationTaskItem,false)); + } + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-edit')") + @Log(title = "归集任务明细", businessType = BusinessType.UPDATE) + @PutMapping("/user") + public AjaxResult userEdit(@RequestBody UsdtAggregationTaskItem usdtAggregationTaskItem) + { + return toAjax(usdtAggregationTaskItemService.updateUsdtAggregationTaskItem(usdtAggregationTaskItem,true)); + } + /** + * 删除归集任务明细 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:remove')") + @Log(title = "归集任务明细", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) + { + return toAjax(usdtAggregationTaskItemService.deleteUsdtAggregationTaskItemByIds(ids,false)); + } + /** + * 删除归集任务明细 + */ + @PreAuthorize("@ss.hasPermi('system:usdtTaskItem:user-remove')") + @Log(title = "归集任务明细", businessType = BusinessType.DELETE) + @DeleteMapping("/user/{ids}") + public AjaxResult userRemove(@PathVariable Long[] ids) + { + return toAjax(usdtAggregationTaskItemService.deleteUsdtAggregationTaskItemByIds(ids,true)); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeysPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeysPlus.java index c32abf8..e7448fe 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeysPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppApiKeysPlus.java @@ -1,6 +1,9 @@ package com.ruoyi.system.domain; import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -21,6 +24,7 @@ public class AppApiKeysPlus implements Serializable private static final long serialVersionUID = 1L; /** 主键 */ + @TableId(type = IdType.INPUT) private Long id; /** 应用ID */ @Excel(name = "应用ID") diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/Apps.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/Apps.java index fa4f34d..b33a7f4 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/Apps.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/Apps.java @@ -23,7 +23,8 @@ public class Apps extends BaseEntity /** 用户 */ @Excel(name = "用户") private Long userId; - + @Excel(name = "归集地址") + private String distTokenAddress; /** 名称 */ @Excel(name = "名称") private String name; @@ -90,7 +91,15 @@ public class Apps extends BaseEntity this.status = status; } - public Integer getStatus() + public String getDistTokenAddress() { + return distTokenAddress; + } + + public void setDistTokenAddress(String distTokenAddress) { + this.distTokenAddress = distTokenAddress; + } + + public Integer getStatus() { return status; } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppsPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppsPlus.java index 5b2a01b..02d6884 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppsPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/AppsPlus.java @@ -1,6 +1,9 @@ package com.ruoyi.system.domain; import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -21,6 +24,7 @@ public class AppsPlus implements Serializable private static final long serialVersionUID = 1L; /** 主键 */ + @TableId(type = IdType.INPUT) private Long id; /** 用户 */ @Excel(name = "用户") @@ -34,6 +38,9 @@ public class AppsPlus implements Serializable /** 状态 */ @Excel(name = "状态") private Integer status; + + @Excel(name = "归集地址") + private String distTokenAddress; /** 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd") @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") @@ -117,6 +124,14 @@ public class AppsPlus implements Serializable return deletedAt; } + public String getDistTokenAddress() { + return distTokenAddress; + } + + public void setDistTokenAddress(String distTokenAddress) { + this.distTokenAddress = distTokenAddress; + } + @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTask.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTask.java new file mode 100644 index 0000000..32d83ef --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTask.java @@ -0,0 +1,197 @@ +package com.ruoyi.system.domain; + +import java.math.BigDecimal; +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +/** + * 归集任务对象 usdt_aggregation_task + * + * @author luqj + * @date 2026-01-01 + */ +public class UsdtAggregationTask extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + + /** 任务名称 */ + @Excel(name = "任务名称") + private String taskName; + + /** 应用 */ + @Excel(name = "应用") + private Long appId; + + /** 用户 */ + @Excel(name = "用户") + private Long userId; + + /** 状态 */ + @Excel(name = "状态") + private Integer status; + + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + + /** 更新时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + + /** 删除时间 */ + private Date deletedAt; + + /** 提现总金额 */ + @Excel(name = "提现总金额") + private BigDecimal totalAmount; + + /** 执行时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "执行时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date exeTime; + + /** 审核状态 */ + @Excel(name = "审核状态") + private Integer verifyStatus; + + /** 归集地址 */ + @Excel(name = "归集地址") + private String distTokenAddress; + + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTaskName(String taskName) + { + this.taskName = taskName; + } + + public String getTaskName() + { + return taskName; + } + public void setAppId(Long appId) + { + this.appId = appId; + } + + public Long getAppId() + { + return appId; + } + public void setUserId(Long userId) + { + this.userId = userId; + } + + public Long getUserId() + { + return userId; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + public void setDeletedAt(Date deletedAt) + { + this.deletedAt = deletedAt; + } + + public Date getDeletedAt() + { + return deletedAt; + } + public void setTotalAmount(BigDecimal totalAmount) + { + this.totalAmount = totalAmount; + } + + public BigDecimal getTotalAmount() + { + return totalAmount; + } + public void setExeTime(Date exeTime) + { + this.exeTime = exeTime; + } + + public Date getExeTime() + { + return exeTime; + } + public void setVerifyStatus(Integer verifyStatus) + { + this.verifyStatus = verifyStatus; + } + + public Integer getVerifyStatus() + { + return verifyStatus; + } + public void setDistTokenAddress(String distTokenAddress) + { + this.distTokenAddress = distTokenAddress; + } + + public String getDistTokenAddress() + { + return distTokenAddress; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("taskName", getTaskName()) + .append("appId", getAppId()) + .append("userId", getUserId()) + .append("remark", getRemark()) + .append("status", getStatus()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .append("deletedAt", getDeletedAt()) + .append("totalAmount", getTotalAmount()) + .append("exeTime", getExeTime()) + .append("verifyStatus", getVerifyStatus()) + .append("distTokenAddress", getDistTokenAddress()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTaskItem.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTaskItem.java new file mode 100644 index 0000000..4db138d --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTaskItem.java @@ -0,0 +1,182 @@ +package com.ruoyi.system.domain; + +import java.math.BigDecimal; +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +/** + * 归集任务明细对象 usdt_aggregation_task_item + * + * @author luqj + * @date 2026-01-01 + */ +public class UsdtAggregationTaskItem extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + private Long id; + + /** 钱包地址 */ + @Excel(name = "钱包地址") + private String tokenAddress; + + /** 状态0 待执行 1 执行 2 执行失败 */ + @Excel(name = "状态0 待执行 1 执行 2 执行失败") + private Integer status; + + /** 金额 */ + @Excel(name = "金额") + private BigDecimal opeAmount; + + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + + /** 更新时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + + /** 删除时间 */ + private Date deletedAt; + + /** 用户 */ + @Excel(name = "用户") + private Long userId; + + /** 应用 */ + @Excel(name = "应用") + private Long appId; + + /** 父任务 */ + @Excel(name = "父任务") + private Long parentId; + + /** 归集地址 */ + @Excel(name = "归集地址") + private String distTokenAddress; + + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTokenAddress(String tokenAddress) + { + this.tokenAddress = tokenAddress; + } + + public String getTokenAddress() + { + return tokenAddress; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setOpeAmount(BigDecimal opeAmount) + { + this.opeAmount = opeAmount; + } + + public BigDecimal getOpeAmount() + { + return opeAmount; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + public void setDeletedAt(Date deletedAt) + { + this.deletedAt = deletedAt; + } + + public Date getDeletedAt() + { + return deletedAt; + } + public void setUserId(Long userId) + { + this.userId = userId; + } + + public Long getUserId() + { + return userId; + } + public void setAppId(Long appId) + { + this.appId = appId; + } + + public Long getAppId() + { + return appId; + } + public void setParentId(Long parentId) + { + this.parentId = parentId; + } + + public Long getParentId() + { + return parentId; + } + public void setDistTokenAddress(String distTokenAddress) + { + this.distTokenAddress = distTokenAddress; + } + + public String getDistTokenAddress() + { + return distTokenAddress; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("tokenAddress", getTokenAddress()) + .append("status", getStatus()) + .append("remark", getRemark()) + .append("opeAmount", getOpeAmount()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .append("deletedAt", getDeletedAt()) + .append("userId", getUserId()) + .append("appId", getAppId()) + .append("parentId", getParentId()) + .append("distTokenAddress", getDistTokenAddress()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTaskItemPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTaskItemPlus.java new file mode 100644 index 0000000..de7486b --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTaskItemPlus.java @@ -0,0 +1,190 @@ +package com.ruoyi.system.domain; + +import java.math.BigDecimal; +import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +import java.util.Date; +import com.baomidou.mybatisplus.annotation.TableName; +/** + * 归集任务明细对象 usdt_aggregation_task_item + * + * @author luqj + * @date 2026-01-01 + */ +@TableName(value = "usdt_aggregation_task_item") +public class UsdtAggregationTaskItemPlus implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + @TableId(type = IdType.INPUT) + private Long id; + /** 钱包地址 */ + @Excel(name = "钱包地址") + private String tokenAddress; + /** 状态0 待执行 1 执行 2 执行失败 */ + @Excel(name = "状态0 待执行 1 执行 2 执行失败") + private Integer status; + /** 备注 */ + @Excel(name = "备注") + private String remark; + /** 金额 */ + @Excel(name = "金额") + private BigDecimal opeAmount; + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + /** 更新时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + /** 删除时间 */ + private Date deletedAt; + /** 用户 */ + @Excel(name = "用户") + private Long userId; + /** 应用 */ + @Excel(name = "应用") + private Long appId; + /** 父任务 */ + @Excel(name = "父任务") + private Long parentId; + /** 归集地址 */ + @Excel(name = "归集地址") + private String distTokenAddress; + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTokenAddress(String tokenAddress) + { + this.tokenAddress = tokenAddress; + } + + public String getTokenAddress() + { + return tokenAddress; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setRemark(String remark) + { + this.remark = remark; + } + + public String getRemark() + { + return remark; + } + public void setOpeAmount(BigDecimal opeAmount) + { + this.opeAmount = opeAmount; + } + + public BigDecimal getOpeAmount() + { + return opeAmount; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + public void setDeletedAt(Date deletedAt) + { + this.deletedAt = deletedAt; + } + + public Date getDeletedAt() + { + return deletedAt; + } + public void setUserId(Long userId) + { + this.userId = userId; + } + + public Long getUserId() + { + return userId; + } + public void setAppId(Long appId) + { + this.appId = appId; + } + + public Long getAppId() + { + return appId; + } + public void setParentId(Long parentId) + { + this.parentId = parentId; + } + + public Long getParentId() + { + return parentId; + } + public void setDistTokenAddress(String distTokenAddress) + { + this.distTokenAddress = distTokenAddress; + } + + public String getDistTokenAddress() + { + return distTokenAddress; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("tokenAddress", getTokenAddress()) + .append("status", getStatus()) + .append("remark", getRemark()) + .append("opeAmount", getOpeAmount()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .append("deletedAt", getDeletedAt()) + .append("userId", getUserId()) + .append("appId", getAppId()) + .append("parentId", getParentId()) + .append("distTokenAddress", getDistTokenAddress()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTaskPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTaskPlus.java new file mode 100644 index 0000000..cd9979c --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtAggregationTaskPlus.java @@ -0,0 +1,204 @@ +package com.ruoyi.system.domain; + +import java.math.BigDecimal; +import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.fasterxml.jackson.annotation.JsonFormat; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import com.ruoyi.common.annotation.Excel; +import com.ruoyi.common.core.domain.BaseEntity; +import java.io.Serializable; +import java.util.Date; +import com.baomidou.mybatisplus.annotation.TableName; +/** + * 归集任务对象 usdt_aggregation_task + * + * @author luqj + * @date 2026-01-01 + */ +@TableName(value = "usdt_aggregation_task") +public class UsdtAggregationTaskPlus implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 主键 */ + @TableId(type = IdType.INPUT) + private Long id; + /** 任务名称 */ + @Excel(name = "任务名称") + private String taskName; + /** 应用 */ + @Excel(name = "应用") + private Long appId; + /** 用户 */ + @Excel(name = "用户") + private Long userId; + /** 备注 */ + @Excel(name = "备注") + private String remark; + /** 状态 */ + @Excel(name = "状态") + private Integer status; + /** 创建时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date createdAt; + /** 更新时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date updatedAt; + /** 删除时间 */ + private Date deletedAt; + /** 提现总金额 */ + @Excel(name = "提现总金额") + private BigDecimal totalAmount; + /** 执行时间 */ + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "执行时间", width = 30, dateFormat = "yyyy-MM-dd") + private Date exeTime; + /** 审核状态 */ + @Excel(name = "审核状态") + private Integer verifyStatus; + /** 归集地址 */ + @Excel(name = "归集地址") + private String distTokenAddress; + public void setId(Long id) + { + this.id = id; + } + + public Long getId() + { + return id; + } + public void setTaskName(String taskName) + { + this.taskName = taskName; + } + + public String getTaskName() + { + return taskName; + } + public void setAppId(Long appId) + { + this.appId = appId; + } + + public Long getAppId() + { + return appId; + } + public void setUserId(Long userId) + { + this.userId = userId; + } + + public Long getUserId() + { + return userId; + } + public void setRemark(String remark) + { + this.remark = remark; + } + + public String getRemark() + { + return remark; + } + public void setStatus(Integer status) + { + this.status = status; + } + + public Integer getStatus() + { + return status; + } + public void setCreatedAt(Date createdAt) + { + this.createdAt = createdAt; + } + + public Date getCreatedAt() + { + return createdAt; + } + public void setUpdatedAt(Date updatedAt) + { + this.updatedAt = updatedAt; + } + + public Date getUpdatedAt() + { + return updatedAt; + } + public void setDeletedAt(Date deletedAt) + { + this.deletedAt = deletedAt; + } + + public Date getDeletedAt() + { + return deletedAt; + } + public void setTotalAmount(BigDecimal totalAmount) + { + this.totalAmount = totalAmount; + } + + public BigDecimal getTotalAmount() + { + return totalAmount; + } + public void setExeTime(Date exeTime) + { + this.exeTime = exeTime; + } + + public Date getExeTime() + { + return exeTime; + } + public void setVerifyStatus(Integer verifyStatus) + { + this.verifyStatus = verifyStatus; + } + + public Integer getVerifyStatus() + { + return verifyStatus; + } + public void setDistTokenAddress(String distTokenAddress) + { + this.distTokenAddress = distTokenAddress; + } + + public String getDistTokenAddress() + { + return distTokenAddress; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("id", getId()) + .append("taskName", getTaskName()) + .append("appId", getAppId()) + .append("userId", getUserId()) + .append("remark", getRemark()) + .append("status", getStatus()) + .append("createdAt", getCreatedAt()) + .append("updatedAt", getUpdatedAt()) + .append("deletedAt", getDeletedAt()) + .append("totalAmount", getTotalAmount()) + .append("exeTime", getExeTime()) + .append("verifyStatus", getVerifyStatus()) + .append("distTokenAddress", getDistTokenAddress()) + .toString(); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtFundFlowPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtFundFlowPlus.java index 9c485a4..cff4e6e 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtFundFlowPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtFundFlowPlus.java @@ -2,6 +2,9 @@ package com.ruoyi.system.domain; import java.math.BigDecimal; import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -22,6 +25,7 @@ public class UsdtFundFlowPlus implements Serializable private static final long serialVersionUID = 1L; /** 主键 */ + @TableId(type = IdType.INPUT) private Long id; /** 订单ID */ @Excel(name = "订单ID") @@ -46,7 +50,7 @@ public class UsdtFundFlowPlus implements Serializable @Excel(name = "操作金额") private BigDecimal amount; /** 操作类型 */ - @Excel(name = "操作类型") + @Excel(name = "操作类型 操作类型 0 商户收入 1 平台抽佣 2 商户归集提现金额") private Integer opType; /** Token地址 */ @Excel(name = "Token地址") diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtOrdersPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtOrdersPlus.java index b2628bb..8fd287b 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtOrdersPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtOrdersPlus.java @@ -2,6 +2,9 @@ package com.ruoyi.system.domain; import java.math.BigDecimal; import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -22,6 +25,7 @@ public class UsdtOrdersPlus implements Serializable private static final long serialVersionUID = 1L; /** 主键 */ + @TableId(type = IdType.INPUT) private Long id; /** 订单号 */ @Excel(name = "订单号") @@ -42,7 +46,7 @@ public class UsdtOrdersPlus implements Serializable @Excel(name = "钱包地址") private String token; /** 状态 */ - @Excel(name = "状态") + @Excel(name = "状态 状态1:等待支付,2:支付成功,3:已过期") private Long status; /** 异步地址 */ @Excel(name = "异步地址") diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtUserSettlementConfigurationPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtUserSettlementConfigurationPlus.java index a6b69c6..608d18d 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtUserSettlementConfigurationPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UsdtUserSettlementConfigurationPlus.java @@ -2,6 +2,9 @@ package com.ruoyi.system.domain; import java.math.BigDecimal; import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -22,6 +25,7 @@ public class UsdtUserSettlementConfigurationPlus implements Serializable private static final long serialVersionUID = 1L; /** 主键 */ + @TableId(type = IdType.INPUT) private Long id; /** 用户id */ @Excel(name = "用户id") diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UserAuthPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UserAuthPlus.java index 4b3197f..3dbc211 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/UserAuthPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/UserAuthPlus.java @@ -1,6 +1,9 @@ package com.ruoyi.system.domain; import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -21,6 +24,7 @@ public class UserAuthPlus implements Serializable private static final long serialVersionUID = 1L; /** 主键ID */ + @TableId(type = IdType.INPUT) private Long id; /** 用户 */ @Excel(name = "用户") diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/WalletAddress.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/WalletAddress.java index ead5620..fd7153a 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/WalletAddress.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/WalletAddress.java @@ -1,5 +1,6 @@ package com.ruoyi.system.domain; +import java.math.BigDecimal; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; @@ -11,7 +12,7 @@ import java.io.Serializable; * token管理对象 wallet_address * * @author luqj - * @date 2025-11-25 + * @date 2025-12-30 */ public class WalletAddress extends BaseEntity { @@ -50,6 +51,83 @@ public class WalletAddress extends BaseEntity @Excel(name = "用户") private Long userId; + /** 密钥 */ + @Excel(name = "密钥") + private String tokenKey; + @Excel(name = "质押还剩能用的带宽") + private Long bandwidthStakedNum; + /** usdt余额 */ + @Excel(name = "usdt余额") + private BigDecimal usdtBalance; + + /** trx余额 */ + @Excel(name = "trx余额") + private BigDecimal trxBalance; + + /** 能量-可用 */ + @Excel(name = "能量-可用") + private Long energyNum; + + /** 带宽-可用 */ + @Excel(name = "带宽-可用") + private Long bandwidthNum; + + /** 可以提现usdt金额 */ + @Excel(name = "可以提现usdt金额") + private BigDecimal withdrawUsdtBalance; + + /** 代理给别人能量的trx数量 */ + @Excel(name = "代理给别人能量的trx数量") + private Long delegatedEnergyTrxNum; + + /** 代理给别人的能量 */ + @Excel(name = "代理给别人的能量") + private BigDecimal delegatedEnergyValue; + + /** 别人代理给我能量的trx数量 */ + @Excel(name = "别人代理给我能量的trx数量") + private Long acquiredDelegatedEnergyTrxNum; + + /** 别人代理给我的能量 */ + @Excel(name = "别人代理给我的能量") + private BigDecimal acquiredDelegatedEnergyValue; + + /** 代理给别人的带宽trx数量 */ + @Excel(name = "代理给别人的带宽trx数量") + private Long delegatedBandwidthTrxNum; + + /** 代理给别人的带宽 */ + @Excel(name = "代理给别人的带宽") + private BigDecimal delegatedBandwidthValue; + + /** 别人代理给我带宽的trx数量 */ + @Excel(name = "别人代理给我带宽的trx数量") + private Long acquiredDelegatedBandwidthTrxNum; + + /** 别人代理给我的带宽 */ + @Excel(name = "别人代理给我的带宽") + private BigDecimal acquiredDelegatedBandwidthValue; + + /** 质押的trx数量-不含代理 */ + @Excel(name = "质押的trx数量-不含代理") + private Long stakedTrxNum; + + /** 能量质押的trx数量-不含代理 */ + @Excel(name = "能量质押的trx数量-不含代理") + private Long energyStakedTrxNum; + + /** 带宽质押的trx数量-不含代理 */ + @Excel(name = "带宽质押的trx数量-不含代理") + private Long bandwidthStakedTrxNum; + + /** 可投票数 */ + @Excel(name = "可投票数") + private Long voteNum; + + /** 已经投票数量 */ + @Excel(name = "已经投票数量") + private Long votedNum; + public void setId(Long id) { this.id = id; @@ -64,7 +142,15 @@ public class WalletAddress extends BaseEntity this.token = token; } - public String getToken() + public Long getBandwidthStakedNum() { + return bandwidthStakedNum; + } + + public void setBandwidthStakedNum(Long bandwidthStakedNum) { + this.bandwidthStakedNum = bandwidthStakedNum; + } + + public String getToken() { return token; } @@ -122,6 +208,177 @@ public class WalletAddress extends BaseEntity { return userId; } + public void setTokenKey(String key) + { + this.tokenKey = key; + } + + public String getTokenKey() + { + return tokenKey; + } + public void setUsdtBalance(BigDecimal usdtBalance) + { + this.usdtBalance = usdtBalance; + } + + public BigDecimal getUsdtBalance() + { + return usdtBalance; + } + public void setTrxBalance(BigDecimal trxBalance) + { + this.trxBalance = trxBalance; + } + + public BigDecimal getTrxBalance() + { + return trxBalance; + } + public void setEnergyNum(Long energyNum) + { + this.energyNum = energyNum; + } + + public Long getEnergyNum() + { + return energyNum; + } + public void setBandwidthNum(Long bandwidthNum) + { + this.bandwidthNum = bandwidthNum; + } + + public Long getBandwidthNum() + { + return bandwidthNum; + } + public void setWithdrawUsdtBalance(BigDecimal withdrawUsdtBalance) + { + this.withdrawUsdtBalance = withdrawUsdtBalance; + } + + public BigDecimal getWithdrawUsdtBalance() + { + return withdrawUsdtBalance; + } + public void setDelegatedEnergyTrxNum(Long delegatedEnergyTrxNum) + { + this.delegatedEnergyTrxNum = delegatedEnergyTrxNum; + } + + public Long getDelegatedEnergyTrxNum() + { + return delegatedEnergyTrxNum; + } + public void setDelegatedEnergyValue(BigDecimal delegatedEnergyValue) + { + this.delegatedEnergyValue = delegatedEnergyValue; + } + + public BigDecimal getDelegatedEnergyValue() + { + return delegatedEnergyValue; + } + public void setAcquiredDelegatedEnergyTrxNum(Long acquiredDelegatedEnergyTrxNum) + { + this.acquiredDelegatedEnergyTrxNum = acquiredDelegatedEnergyTrxNum; + } + + public Long getAcquiredDelegatedEnergyTrxNum() + { + return acquiredDelegatedEnergyTrxNum; + } + public void setAcquiredDelegatedEnergyValue(BigDecimal acquiredDelegatedEnergyValue) + { + this.acquiredDelegatedEnergyValue = acquiredDelegatedEnergyValue; + } + + public BigDecimal getAcquiredDelegatedEnergyValue() + { + return acquiredDelegatedEnergyValue; + } + public void setDelegatedBandwidthTrxNum(Long delegatedBandwidthTrxNum) + { + this.delegatedBandwidthTrxNum = delegatedBandwidthTrxNum; + } + + public Long getDelegatedBandwidthTrxNum() + { + return delegatedBandwidthTrxNum; + } + public void setDelegatedBandwidthValue(BigDecimal delegatedBandwidthValue) + { + this.delegatedBandwidthValue = delegatedBandwidthValue; + } + + public BigDecimal getDelegatedBandwidthValue() + { + return delegatedBandwidthValue; + } + public void setAcquiredDelegatedBandwidthTrxNum(Long acquiredDelegatedBandwidthTrxNum) + { + this.acquiredDelegatedBandwidthTrxNum = acquiredDelegatedBandwidthTrxNum; + } + + public Long getAcquiredDelegatedBandwidthTrxNum() + { + return acquiredDelegatedBandwidthTrxNum; + } + public void setAcquiredDelegatedBandwidthValue(BigDecimal acquiredDelegatedBandwidthValue) + { + this.acquiredDelegatedBandwidthValue = acquiredDelegatedBandwidthValue; + } + + public BigDecimal getAcquiredDelegatedBandwidthValue() + { + return acquiredDelegatedBandwidthValue; + } + public void setStakedTrxNum(Long stakedTrxNum) + { + this.stakedTrxNum = stakedTrxNum; + } + + public Long getStakedTrxNum() + { + return stakedTrxNum; + } + public void setEnergyStakedTrxNum(Long energyStakedTrxNum) + { + this.energyStakedTrxNum = energyStakedTrxNum; + } + + public Long getEnergyStakedTrxNum() + { + return energyStakedTrxNum; + } + public void setBandwidthStakedTrxNum(Long bandwidthStakedTrxNum) + { + this.bandwidthStakedTrxNum = bandwidthStakedTrxNum; + } + + public Long getBandwidthStakedTrxNum() + { + return bandwidthStakedTrxNum; + } + public void setVoteNum(Long voteNum) + { + this.voteNum = voteNum; + } + + public Long getVoteNum() + { + return voteNum; + } + public void setVotedNum(Long votedNum) + { + this.votedNum = votedNum; + } + + public Long getVotedNum() + { + return votedNum; + } @Override public String toString() { @@ -134,6 +391,25 @@ public class WalletAddress extends BaseEntity .append("deletedAt", getDeletedAt()) .append("appId", getAppId()) .append("userId", getUserId()) + .append("tokenKey", getTokenKey()) + .append("usdtBalance", getUsdtBalance()) + .append("trxBalance", getTrxBalance()) + .append("energyNum", getEnergyNum()) + .append("bandwidthNum", getBandwidthNum()) + .append("withdrawUsdtBalance", getWithdrawUsdtBalance()) + .append("delegatedEnergyTrxNum", getDelegatedEnergyTrxNum()) + .append("delegatedEnergyValue", getDelegatedEnergyValue()) + .append("acquiredDelegatedEnergyTrxNum", getAcquiredDelegatedEnergyTrxNum()) + .append("acquiredDelegatedEnergyValue", getAcquiredDelegatedEnergyValue()) + .append("delegatedBandwidthTrxNum", getDelegatedBandwidthTrxNum()) + .append("delegatedBandwidthValue", getDelegatedBandwidthValue()) + .append("acquiredDelegatedBandwidthTrxNum", getAcquiredDelegatedBandwidthTrxNum()) + .append("acquiredDelegatedBandwidthValue", getAcquiredDelegatedBandwidthValue()) + .append("stakedTrxNum", getStakedTrxNum()) + .append("energyStakedTrxNum", getEnergyStakedTrxNum()) + .append("bandwidthStakedTrxNum", getBandwidthStakedTrxNum()) + .append("voteNum", getVoteNum()) + .append("votedNum", getVotedNum()) .toString(); } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/WalletAddressPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/WalletAddressPlus.java index 12d2df5..88c3ff9 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/WalletAddressPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/WalletAddressPlus.java @@ -2,6 +2,9 @@ package com.ruoyi.system.domain; import java.math.BigDecimal; import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -14,7 +17,7 @@ import com.baomidou.mybatisplus.annotation.TableName; * token管理对象 wallet_address * * @author luqj - * @date 2025-11-25 + * @date 2025-12-30 */ @TableName(value = "wallet_address") public class WalletAddressPlus implements Serializable @@ -22,6 +25,7 @@ public class WalletAddressPlus implements Serializable private static final long serialVersionUID = 1L; /** 主键 */ + @TableId(type = IdType.INPUT) @Excel(name = "主键") private Long id; /** Token */ @@ -46,30 +50,66 @@ public class WalletAddressPlus implements Serializable /** 用户 */ @Excel(name = "用户") private Long userId; - + /** 密钥 */ + @Excel(name = "密钥") + private String tokenKey; + /** usdt余额 */ @Excel(name = "usdt余额") private BigDecimal usdtBalance; - + /** trx余额 */ @Excel(name = "trx余额") private BigDecimal trxBalance; - - public BigDecimal getTrxBalance() { - return trxBalance; - } - - public void setTrxBalance(BigDecimal trxBalance) { - this.trxBalance = trxBalance; - } - - public BigDecimal getUsdtBalance() { - return usdtBalance; - } - - public void setUsdtBalance(BigDecimal usdtBalance) { - this.usdtBalance = usdtBalance; - } - - public void setId(Long id) + /** 能量-可用 */ + @Excel(name = "能量-可用") + private Long energyNum; + @Excel(name = "质押还剩能用的带宽") + private Long bandwidthStakedNum; + /** 带宽-可用 */ + @Excel(name = "带宽-可用") + private Long bandwidthNum; + /** 可以提现usdt金额 */ + @Excel(name = "可以提现usdt金额") + private BigDecimal withdrawUsdtBalance; + /** 代理给别人能量的trx数量 */ + @Excel(name = "代理给别人能量的trx数量") + private Long delegatedEnergyTrxNum; + /** 代理给别人的能量 */ + @Excel(name = "代理给别人的能量") + private BigDecimal delegatedEnergyValue; + /** 别人代理给我能量的trx数量 */ + @Excel(name = "别人代理给我能量的trx数量") + private Long acquiredDelegatedEnergyTrxNum; + /** 别人代理给我的能量 */ + @Excel(name = "别人代理给我的能量") + private BigDecimal acquiredDelegatedEnergyValue; + /** 代理给别人的带宽trx数量 */ + @Excel(name = "代理给别人的带宽trx数量") + private Long delegatedBandwidthTrxNum; + /** 代理给别人的带宽 */ + @Excel(name = "代理给别人的带宽") + private BigDecimal delegatedBandwidthValue; + /** 别人代理给我带宽的trx数量 */ + @Excel(name = "别人代理给我带宽的trx数量") + private Long acquiredDelegatedBandwidthTrxNum; + /** 别人代理给我的带宽 */ + @Excel(name = "别人代理给我的带宽") + private BigDecimal acquiredDelegatedBandwidthValue; + /** 质押的trx数量-不含代理 */ + @Excel(name = "质押的trx数量-不含代理") + private Long stakedTrxNum; + /** 能量质押的trx数量-不含代理 */ + @Excel(name = "能量质押的trx数量-不含代理") + private Long energyStakedTrxNum; + /** 带宽质押的trx数量-不含代理 */ + @Excel(name = "带宽质押的trx数量-不含代理") + private Long bandwidthStakedTrxNum; + /** 可投票数 */ + @Excel(name = "可投票数") + private Long voteNum; + /** 已经投票数量 */ + @Excel(name = "已经投票数量") + private Long votedNum; + public void setId(Long id) { this.id = id; } @@ -101,7 +141,15 @@ public class WalletAddressPlus implements Serializable this.createdAt = createdAt; } - public Date getCreatedAt() + public Long getBandwidthStakedNum() { + return bandwidthStakedNum; + } + + public void setBandwidthStakedNum(Long bandwidthStakedNum) { + this.bandwidthStakedNum = bandwidthStakedNum; + } + + public Date getCreatedAt() { return createdAt; } @@ -141,6 +189,177 @@ public class WalletAddressPlus implements Serializable { return userId; } + public void setTokenKey(String key) + { + this.tokenKey = key; + } + + public String getTokenKey() + { + return tokenKey; + } + public void setUsdtBalance(BigDecimal usdtBalance) + { + this.usdtBalance = usdtBalance; + } + + public BigDecimal getUsdtBalance() + { + return usdtBalance; + } + public void setTrxBalance(BigDecimal trxBalance) + { + this.trxBalance = trxBalance; + } + + public BigDecimal getTrxBalance() + { + return trxBalance; + } + public void setEnergyNum(Long energyNum) + { + this.energyNum = energyNum; + } + + public Long getEnergyNum() + { + return energyNum; + } + public void setBandwidthNum(Long bandwidthNum) + { + this.bandwidthNum = bandwidthNum; + } + + public Long getBandwidthNum() + { + return bandwidthNum; + } + public void setWithdrawUsdtBalance(BigDecimal withdrawUsdtBalance) + { + this.withdrawUsdtBalance = withdrawUsdtBalance; + } + + public BigDecimal getWithdrawUsdtBalance() + { + return withdrawUsdtBalance; + } + public void setDelegatedEnergyTrxNum(Long delegatedEnergyTrxNum) + { + this.delegatedEnergyTrxNum = delegatedEnergyTrxNum; + } + + public Long getDelegatedEnergyTrxNum() + { + return delegatedEnergyTrxNum; + } + public void setDelegatedEnergyValue(BigDecimal delegatedEnergyValue) + { + this.delegatedEnergyValue = delegatedEnergyValue; + } + + public BigDecimal getDelegatedEnergyValue() + { + return delegatedEnergyValue; + } + public void setAcquiredDelegatedEnergyTrxNum(Long acquiredDelegatedEnergyTrxNum) + { + this.acquiredDelegatedEnergyTrxNum = acquiredDelegatedEnergyTrxNum; + } + + public Long getAcquiredDelegatedEnergyTrxNum() + { + return acquiredDelegatedEnergyTrxNum; + } + public void setAcquiredDelegatedEnergyValue(BigDecimal acquiredDelegatedEnergyValue) + { + this.acquiredDelegatedEnergyValue = acquiredDelegatedEnergyValue; + } + + public BigDecimal getAcquiredDelegatedEnergyValue() + { + return acquiredDelegatedEnergyValue; + } + public void setDelegatedBandwidthTrxNum(Long delegatedBandwidthTrxNum) + { + this.delegatedBandwidthTrxNum = delegatedBandwidthTrxNum; + } + + public Long getDelegatedBandwidthTrxNum() + { + return delegatedBandwidthTrxNum; + } + public void setDelegatedBandwidthValue(BigDecimal delegatedBandwidthValue) + { + this.delegatedBandwidthValue = delegatedBandwidthValue; + } + + public BigDecimal getDelegatedBandwidthValue() + { + return delegatedBandwidthValue; + } + public void setAcquiredDelegatedBandwidthTrxNum(Long acquiredDelegatedBandwidthTrxNum) + { + this.acquiredDelegatedBandwidthTrxNum = acquiredDelegatedBandwidthTrxNum; + } + + public Long getAcquiredDelegatedBandwidthTrxNum() + { + return acquiredDelegatedBandwidthTrxNum; + } + public void setAcquiredDelegatedBandwidthValue(BigDecimal acquiredDelegatedBandwidthValue) + { + this.acquiredDelegatedBandwidthValue = acquiredDelegatedBandwidthValue; + } + + public BigDecimal getAcquiredDelegatedBandwidthValue() + { + return acquiredDelegatedBandwidthValue; + } + public void setStakedTrxNum(Long stakedTrxNum) + { + this.stakedTrxNum = stakedTrxNum; + } + + public Long getStakedTrxNum() + { + return stakedTrxNum; + } + public void setEnergyStakedTrxNum(Long energyStakedTrxNum) + { + this.energyStakedTrxNum = energyStakedTrxNum; + } + + public Long getEnergyStakedTrxNum() + { + return energyStakedTrxNum; + } + public void setBandwidthStakedTrxNum(Long bandwidthStakedTrxNum) + { + this.bandwidthStakedTrxNum = bandwidthStakedTrxNum; + } + + public Long getBandwidthStakedTrxNum() + { + return bandwidthStakedTrxNum; + } + public void setVoteNum(Long voteNum) + { + this.voteNum = voteNum; + } + + public Long getVoteNum() + { + return voteNum; + } + public void setVotedNum(Long votedNum) + { + this.votedNum = votedNum; + } + + public Long getVotedNum() + { + return votedNum; + } @Override public String toString() { @@ -153,6 +372,25 @@ public class WalletAddressPlus implements Serializable .append("deletedAt", getDeletedAt()) .append("appId", getAppId()) .append("userId", getUserId()) + .append("tokenKey", getTokenKey()) + .append("usdtBalance", getUsdtBalance()) + .append("trxBalance", getTrxBalance()) + .append("energyNum", getEnergyNum()) + .append("bandwidthNum", getBandwidthNum()) + .append("withdrawUsdtBalance", getWithdrawUsdtBalance()) + .append("delegatedEnergyTrxNum", getDelegatedEnergyTrxNum()) + .append("delegatedEnergyValue", getDelegatedEnergyValue()) + .append("acquiredDelegatedEnergyTrxNum", getAcquiredDelegatedEnergyTrxNum()) + .append("acquiredDelegatedEnergyValue", getAcquiredDelegatedEnergyValue()) + .append("delegatedBandwidthTrxNum", getDelegatedBandwidthTrxNum()) + .append("delegatedBandwidthValue", getDelegatedBandwidthValue()) + .append("acquiredDelegatedBandwidthTrxNum", getAcquiredDelegatedBandwidthTrxNum()) + .append("acquiredDelegatedBandwidthValue", getAcquiredDelegatedBandwidthValue()) + .append("stakedTrxNum", getStakedTrxNum()) + .append("energyStakedTrxNum", getEnergyStakedTrxNum()) + .append("bandwidthStakedTrxNum", getBandwidthStakedTrxNum()) + .append("voteNum", getVoteNum()) + .append("votedNum", getVotedNum()) .toString(); } } diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/Web3WalletPlus.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/Web3WalletPlus.java index 40acb23..5630a11 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/domain/Web3WalletPlus.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/Web3WalletPlus.java @@ -2,6 +2,9 @@ package com.ruoyi.system.domain; import java.math.BigDecimal; import java.util.Date; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -22,6 +25,7 @@ public class Web3WalletPlus implements Serializable private static final long serialVersionUID = 1L; /** 用户 */ + @TableId(type = IdType.INPUT) private Long id; /** usdt */ @Excel(name = "usdt") diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AccountResource.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AccountResource.java new file mode 100644 index 0000000..3860968 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/AccountResource.java @@ -0,0 +1,11 @@ +package com.ruoyi.system.domain.vo; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.Map; +@Data +public class AccountResource { + + @JsonProperty("frozen_balance_for_energy") + private Map frozenBalanceForEnergy; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Bandwidth.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Bandwidth.java new file mode 100644 index 0000000..ab0964f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Bandwidth.java @@ -0,0 +1,72 @@ +package com.ruoyi.system.domain.vo; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.Map; +@Data +public class Bandwidth { + + @JsonProperty("energyRemaining") + private long energyRemaining; + + @JsonProperty("energyLimit") + private long energyLimit; + + @JsonProperty("totalEnergyLimit") + private long totalEnergyLimit; + + @JsonProperty("totalEnergyWeight") + private long totalEnergyWeight; + + @JsonProperty("energyUsed") + private long energyUsed; + + @JsonProperty("netUsed") + private long netUsed; + + @JsonProperty("netLimit") + private long netLimit; + + @JsonProperty("netRemaining") + private long netRemaining; + + @JsonProperty("freeNetLimit") + private long freeNetLimit; + + @JsonProperty("freeNetUsed") + private long freeNetUsed; + + @JsonProperty("freeNetRemaining") + private long freeNetRemaining; + + @JsonProperty("totalNetLimit") + private long totalNetLimit; + + @JsonProperty("totalNetWeight") + private long totalNetWeight; + + @JsonProperty("netPercentage") + private BigDecimal netPercentage; + + @JsonProperty("freeNetPercentage") + private BigDecimal freeNetPercentage; + + @JsonProperty("energyPercentage") + private BigDecimal energyPercentage; + + @JsonProperty("storageLimit") + private long storageLimit; + + @JsonProperty("storageUsed") + private long storageUsed; + + @JsonProperty("storageRemaining") + private long storageRemaining; + + @JsonProperty("storagePercentage") + private BigDecimal storagePercentage; + + @JsonProperty("assets") + private Map assets; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/EnergyAndBandwidthVo.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/EnergyAndBandwidthVo.java new file mode 100644 index 0000000..030d96a --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/EnergyAndBandwidthVo.java @@ -0,0 +1,24 @@ +package com.ruoyi.system.domain.vo; + +import com.ruoyi.common.annotation.Excel; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +@Data +public class EnergyAndBandwidthVo implements Serializable { + private BigDecimal delegateBandwidth; + private BigDecimal delegateEnergy; + + private Long stakedTrxNum; + + @Excel(name = "质押还剩能用的带宽") + private Long bandwidthStakedNum; + + private BigDecimal bandwidth; + private BigDecimal energy; + + private BigDecimal acquiredBandwidth; + private BigDecimal acquiredEnergy; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Frozen.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Frozen.java new file mode 100644 index 0000000..496c866 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Frozen.java @@ -0,0 +1,15 @@ +package com.ruoyi.system.domain.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; +@Data +public class Frozen { + + @JsonProperty("total") + private long total; + + @JsonProperty("balances") + private List balances; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Permission.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Permission.java new file mode 100644 index 0000000..d5aae31 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Permission.java @@ -0,0 +1,26 @@ +package com.ruoyi.system.domain.vo; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; +@Data +public class Permission { + + @JsonProperty("id") + private int id; + + @JsonProperty("type") + private String type; + + @JsonProperty("permission_name") + private String permissionName; + + @JsonProperty("threshold") + private int threshold; + + @JsonProperty("operations") + private String operations; + + @JsonProperty("keys") + private List keys; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/PermissionKey.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/PermissionKey.java new file mode 100644 index 0000000..4427e61 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/PermissionKey.java @@ -0,0 +1,13 @@ +package com.ruoyi.system.domain.vo; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +@Data +public class PermissionKey { + + @JsonProperty("address") + private String address; + + @JsonProperty("weight") + private int weight; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Representative.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Representative.java new file mode 100644 index 0000000..0fe4cd8 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/Representative.java @@ -0,0 +1,20 @@ +package com.ruoyi.system.domain.vo; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +@Data +public class Representative { + + @JsonProperty("lastWithDrawTime") + private long lastWithDrawTime; + + @JsonProperty("allowance") + private long allowance; + + @JsonProperty("enabled") + private boolean enabled; + + @JsonProperty("url") + private String url; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TokenBalance.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TokenBalance.java new file mode 100644 index 0000000..aa6b29f --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TokenBalance.java @@ -0,0 +1,47 @@ +package com.ruoyi.system.domain.vo; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.math.BigDecimal; +@Data +public class TokenBalance { + + @JsonProperty("tokenId") + private String tokenId; + + @JsonProperty("tokenName") + private String tokenName; + + @JsonProperty("tokenAbbr") + private String tokenAbbr; + + @JsonProperty("tokenDecimal") + private int tokenDecimal; + + @JsonProperty("tokenType") + private String tokenType; + + @JsonProperty("balance") + private String balance; + + @JsonProperty("amount") + private BigDecimal amount; + + @JsonProperty("tokenPriceInTrx") + private BigDecimal tokenPriceInTrx; + + @JsonProperty("vip") + private boolean vip; + + @JsonProperty("tokenCanShow") + private int tokenCanShow; + + @JsonProperty("tokenLogo") + private String tokenLogo; + + @JsonProperty("transferCount") + private long transferCount; + + @JsonProperty("nrOfTokenHolders") + private long nrOfTokenHolders; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TronAccount.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TronAccount.java new file mode 100644 index 0000000..c640b5a --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TronAccount.java @@ -0,0 +1,18 @@ +package com.ruoyi.system.domain.vo; + +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * TRON 钱包信息实体 + */ +@Data +public class TronAccount implements Serializable { + + private static final long serialVersionUID = 1L; + + private List items; + private String phrase; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TronAccountItem.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TronAccountItem.java new file mode 100644 index 0000000..af3f53b --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TronAccountItem.java @@ -0,0 +1,63 @@ +package com.ruoyi.system.domain.vo; + +import lombok.Data; + +import java.io.Serializable; + +/** + * TRON 钱包信息实体 + */ +@Data +public class TronAccountItem implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * Base58 地址(T 开头) + * 示例:TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW + */ + private String address; + + private String pubKeyCompressed; + + + private String pubKeyUnCompressed; + + /** + * 私钥(Hex) + * 示例:xxxx + */ + private String privateKey; + + private String path; + + /** + * Hex 地址(41 开头) + * 示例:41xxx + */ + private String hexAddress; + + /** + * Base58 私钥 + * 示例:xxx + */ + private String privateKeyBase58; + + public TronAccountItem() { + } + + public TronAccountItem(String address, String privateKey, String hexAddress, String privateKeyBase58) { + this.address = address; + this.privateKey = privateKey; + this.hexAddress = hexAddress; + this.privateKeyBase58 = privateKeyBase58; + } + + @Override + public String toString() { + return "TronAccount{" + + "address='" + address + '\'' + + ", hexAddress='" + hexAddress + '\'' + + '}'; + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TronAccountResp.java b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TronAccountResp.java new file mode 100644 index 0000000..0e43154 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/domain/vo/TronAccountResp.java @@ -0,0 +1,254 @@ +package com.ruoyi.system.domain.vo; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class TronAccountResp { + + @JsonProperty("totalFrozenV2") + private long totalFrozenV2; + + @JsonProperty("transactions_out") + private int transactionsOut; + + @JsonProperty("frozenForEnergyV2") + private long frozenForEnergyV2; + + @JsonProperty("totalEnergy") + private long totalEnergy; + + @JsonProperty("rewardNum") + private int rewardNum; + /** + * 我代理给别人的 2.0 带宽trx + */ + @JsonProperty("delegatedFrozenV2BalanceForBandwidth") + private long delegatedFrozenV2BalanceForBandwidth; + + @JsonProperty("ownerPermission") + private Permission ownerPermission; + + @JsonProperty("redTag") + private String redTag; + + @JsonProperty("delegateFrozenForEnergy") + private long delegateFrozenForEnergy; + + @JsonProperty("totalEnergyRemaining") + private long totalEnergyRemaining; + + @JsonProperty("balance") + private long balance; + + @JsonProperty("frozenForBandWidthV2") + private long frozenForBandWidthV2; + + @JsonProperty("canWithdrawAmountV2") + private long canWithdrawAmountV2; + + @JsonProperty("netRemainingCal") + private long netRemainingCal; + + @JsonProperty("delegated") + private Map delegated; + + @JsonProperty("transactions_in") + private int transactionsIn; + + @JsonProperty("totalTransactionCount") + private int totalTransactionCount; + + @JsonProperty("frozenForEnergyV2Value") + private long frozenForEnergyV2Value; + + @JsonProperty("representative") + private Representative representative; + /** + * 别人代理给我 1.0 我获得的带宽值 + */ + @JsonProperty("acquiredDelegatedFrozenBalanceForBandwidthValue") + private BigDecimal acquiredDelegatedFrozenBalanceForBandwidthValue; + + @JsonProperty("announcement") + private String announcement; + + @JsonProperty("allowExchange") + private List allowExchange; + + @JsonProperty("accountType") + private int accountType; + + @JsonProperty("totalFrozenBandwidthValue") + private long totalFrozenBandwidthValue; + + @JsonProperty("frozen") + private Frozen frozen; + + @JsonProperty("balanceStr") + private String balanceStr; + + @JsonProperty("transactions") + private int transactions; + /** + *我代理給別人的2.0 trx + */ + @JsonProperty("delegatedFrozenV2BalanceForEnergy") + private long delegatedFrozenV2BalanceForEnergy; + + @JsonProperty("totalFrozenEnergyV2Value") + private long totalFrozenEnergyV2Value; + + @JsonProperty("name") + private String name; + + @JsonProperty("totalFrozenEnergyValue") + private long totalFrozenEnergyValue; + + @JsonProperty("frozenForEnergy") + private long frozenForEnergy; + + @JsonProperty("energyCost") + private BigDecimal energyCost; + + @JsonProperty("activePermissions") + private List activePermissions; + /** + * 別人代理給我的 2.0 trx + */ + @JsonProperty("acquiredDelegatedFrozenV2BalanceForBandwidth") + private long acquiredDelegatedFrozenV2BalanceForBandwidth; + + @JsonProperty("netCost") + private BigDecimal netCost; + /** + * 别人代理给我的 1.0 trx + */ + @JsonProperty("acquiredDelegateFrozenForBandWidth") + private long acquiredDelegateFrozenForBandWidth; + + @JsonProperty("frozenForBandwidthValue") + private long frozenForBandwidthValue; + + @JsonProperty("greyTag") + private String greyTag; + /** + * 我代理给别人的 2.0 能量值 + */ + @JsonProperty("delegatedFrozenV2BalanceForEnergyValue") + private BigDecimal delegatedFrozenV2BalanceForEnergyValue; + + @JsonProperty("withPriceTokens") + private List withPriceTokens; + /** + * 别人代理给我 我获得的 Stake 2.0 能量值 + */ + @JsonProperty("acquiredDelegatedFrozenV2BalanceForEnergyValue") + private BigDecimal acquiredDelegatedFrozenV2BalanceForEnergyValue; + + @JsonProperty("unfreezeV2") + private long unfreezeV2; + /** + * 我代理给别人的 2.0 带宽值 + */ + @JsonProperty("delegatedFrozenV2BalanceForBandwidthValue") + private BigDecimal delegatedFrozenV2BalanceForBandwidthValue; + + @JsonProperty("feedbackRisk") + private boolean feedbackRisk; + + @JsonProperty("voteTotal") + private long voteTotal; + + @JsonProperty("totalFrozen") + private long totalFrozen; + + @JsonProperty("totalFrozenBandwidthV2Value") + private long totalFrozenBandwidthV2Value; + + @JsonProperty("latest_operation_time") + private long latestOperationTime; + + @JsonProperty("totalNetRemaining") + private long totalNetRemaining; + + @JsonProperty("frozenForBandWidth") + private long frozenForBandWidth; + + @JsonProperty("reward") + private int reward; + + @JsonProperty("frozenForEnergyV2ValueSum") + private BigDecimal frozenForEnergyV2ValueSum; + + @JsonProperty("addressTagLogo") + private String addressTagLogo; + + @JsonProperty("address") + private String address; + + @JsonProperty("frozen_supply") + private List frozenSupply; + + @JsonProperty("bandwidth") + private Bandwidth bandwidth; + + @JsonProperty("date_created") + private long dateCreated; + /** + * 别人代理给我 我获得的 Stake 2.0 Trx + */ + @JsonProperty("acquiredDelegatedFrozenV2BalanceForEnergy") + private long acquiredDelegatedFrozenV2BalanceForEnergy; + + @JsonProperty("frozenForBandwidthV2Value") + private long frozenForBandwidthV2Value; + + @JsonProperty("frozenForBandwidthV2ValueSum") + private BigDecimal frozenForBandwidthV2ValueSum; + + @JsonProperty("accountResource") + private AccountResource accountResource; + + @JsonProperty("totalNet") + private long totalNet; + + @JsonProperty("blueTag") + private String blueTag; + /** + * 别人代理给我 我获得的 Stake 2.0 带宽值 + */ + @JsonProperty("acquiredDelegatedFrozenV2BalanceForBandwidthValue") + private BigDecimal acquiredDelegatedFrozenV2BalanceForBandwidthValue; + + @JsonProperty("witness") + private int witness; + + @JsonProperty("frozenForEnergyValue") + private long frozenForEnergyValue; + + @JsonProperty("freezing") + private long freezing; + /** + * 我代理给别人的带宽trx 1.0 + */ + @JsonProperty("delegateFrozenForBandWidth") + private long delegateFrozenForBandWidth; + /** + * 别人代理给我 能量 我获得的 Stake 1.0 能量值 + */ + @JsonProperty("acquiredDelegatedFrozenBalanceForEnergyValue") + private BigDecimal acquiredDelegatedFrozenBalanceForEnergyValue; + + @JsonProperty("activated") + private boolean activated; + /** + * 别人代理给我的 1.0 能量trx + */ + @JsonProperty("acquiredDelegateFrozenForEnergy") + private long acquiredDelegateFrozenForEnergy; +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/UsdtAggregationTaskItemMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/UsdtAggregationTaskItemMapper.java new file mode 100644 index 0000000..fb76ef2 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/UsdtAggregationTaskItemMapper.java @@ -0,0 +1,65 @@ +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import com.ruoyi.system.domain.UsdtAggregationTaskItem; +import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus; + +/** + * 归集任务明细Mapper接口 + * + * @author luqj + * @date 2026-01-01 + */ +public interface UsdtAggregationTaskItemMapper extends BaseMapper +{ + /** + * 查询归集任务明细 + * + * @param id 归集任务明细ID + * @return 归集任务明细 + */ + public UsdtAggregationTaskItem selectUsdtAggregationTaskItemById(Long id); + + /** + * 查询归集任务明细列表 + * + * @param usdtAggregationTaskItem 归集任务明细 + * @return 归集任务明细集合 + */ + public List selectUsdtAggregationTaskItemList(UsdtAggregationTaskItem usdtAggregationTaskItem); + + /** + * 新增归集任务明细 + * + * @param usdtAggregationTaskItem 归集任务明细 + * @return 结果 + */ + public int insertUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem); + + /** + * 修改归集任务明细 + * + * @param usdtAggregationTaskItem 归集任务明细 + * @return 结果 + */ + public int updateUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem); + + /** + * 删除归集任务明细 + * + * @param id 归集任务明细ID + * @return 结果 + */ + public int deleteUsdtAggregationTaskItemById(Long id); + + /** + * 批量删除归集任务明细 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteUsdtAggregationTaskItemByIds(Long[] ids); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/mapper/UsdtAggregationTaskMapper.java b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/UsdtAggregationTaskMapper.java new file mode 100644 index 0000000..40f56a0 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/mapper/UsdtAggregationTaskMapper.java @@ -0,0 +1,65 @@ +package com.ruoyi.system.mapper; + +import java.util.List; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Param; +import com.ruoyi.system.domain.UsdtAggregationTask; +import com.ruoyi.system.domain.UsdtAggregationTaskPlus; + +/** + * 归集任务Mapper接口 + * + * @author luqj + * @date 2026-01-01 + */ +public interface UsdtAggregationTaskMapper extends BaseMapper +{ + /** + * 查询归集任务 + * + * @param id 归集任务ID + * @return 归集任务 + */ + public UsdtAggregationTask selectUsdtAggregationTaskById(Long id); + + /** + * 查询归集任务列表 + * + * @param usdtAggregationTask 归集任务 + * @return 归集任务集合 + */ + public List selectUsdtAggregationTaskList(UsdtAggregationTask usdtAggregationTask); + + /** + * 新增归集任务 + * + * @param usdtAggregationTask 归集任务 + * @return 结果 + */ + public int insertUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask); + + /** + * 修改归集任务 + * + * @param usdtAggregationTask 归集任务 + * @return 结果 + */ + public int updateUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask); + + /** + * 删除归集任务 + * + * @param id 归集任务ID + * @return 结果 + */ + public int deleteUsdtAggregationTaskById(Long id); + + /** + * 批量删除归集任务 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteUsdtAggregationTaskByIds(Long[] ids); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/ITronService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/ITronService.java new file mode 100644 index 0000000..b004b4b --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/ITronService.java @@ -0,0 +1,258 @@ +package com.ruoyi.system.service; + +import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; +import com.ruoyi.system.domain.vo.TronAccount; +import com.ruoyi.system.domain.vo.TronAccountItem; +import org.tron.trident.core.ApiWrapper; +import org.tron.trident.core.exceptions.IllegalException; + +import java.math.BigDecimal; + +public interface ITronService { + Integer grpcPort(); + String grpcUrl(); + String type(); + ApiWrapper buildApiWrapper(String privateKey); + + String contractAddress(); + + String tronscanApiUrl(); + + String tronscanApiKey(); + + String usdtTrans(ApiWrapper api,String fromAddress, String toAddress, String amount); + + + String trxTrans(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount); + /** + * 不包含质押的数量 + * @param api + * @param address + * @return + */ + BigDecimal getTRxBalance(ApiWrapper api,String address); + + BigDecimal getUsdtBalance(ApiWrapper api,String address); + + /** + * 所有的可用的 包括別人代理給你的值 + * @param ownerAddr + * @return + */ + EnergyAndBandwidthVo energyAndBandwidth(String ownerAddr); + + /** + * 別人代理給我的的能量和带宽值 + * @param ownerAddr + * @return + */ + EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr); + + /** + * 一天后生效,一天内可以cancle + * @param api + * @param ownerAddr + * @param balance + * @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze | + * | -------------- | ----- | ----------- | -------- | ----------- | + * | BANDWIDTH | 0 | 带宽 | ✅ | ✅ | + * | ENERGY | 1 | 能量 | ✅ | ✅ | + * | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ | + * | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ | + * @return + */ + boolean unstakeTrxBalance(ApiWrapper api,String ownerAddr, BigDecimal balance, int resourceCode); + + /** + * 取消 unstakeTrxBalance + * @param api + * @param ownerAddr + * @return + */ + boolean cancleUnstakeTrxBalance(ApiWrapper api,String ownerAddr); + + /** + * 質押trx-获取带宽或者能量 + * 调用会消耗能量或者带宽-不足是会消耗TRX-所以不能一次性质押TXT,最好要预留一个trx-1 + * @param api + * @param ownerAddr + * @param balance + * @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze | + * | -------------- | ----- | ----------- | -------- | ----------- | + * | BANDWIDTH | 0 | 带宽 | ✅ | ✅ | + * | ENERGY | 1 | 能量 | ✅ | ✅ | + * | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ | + * | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ | + */ + boolean stakeTrxBalance(ApiWrapper api,String ownerAddr, BigDecimal balance, int resourceCode); + + /** + * 获取质押trx的数量-不包含代理的 + * @param ownerAddr + * @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze | + * | -------------- | ----- | ----------- | -------- | ----------- | + * | BANDWIDTH | 0 | 带宽 | ✅ | ✅ | + * | ENERGY | 1 | 能量 | ✅ | ✅ | + * | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ | + * | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ | + * @return + */ + BigDecimal stakedTrxBalance(ApiWrapper api,String ownerAddr, int resourceCode); + + /** + * 获取别人质押的trx的数量-代理的 + * @param ownerAddr + * @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze | + * | -------------- | ----- | ----------- | -------- | ----------- | + * | BANDWIDTH | 0 | 带宽 | ✅ | ✅ | + * | ENERGY | 1 | 能量 | ✅ | ✅ | + * | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ | + * | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ | + * @return + */ + BigDecimal acquiredDelegatedStakedTrxBalance(ApiWrapper api,String ownerAddr, int resourceCode); + + + /** + * 我质押的trx的数量-代理的给别人的 + * @param ownerAddr + * @param resourceCode | 枚举 | code | 链上含义 | 能否 stake | 能否 unfreeze | + * | -------------- | ----- | ----------- | -------- | ----------- | + * | BANDWIDTH | 0 | 带宽 | ✅ | ✅ | + * | ENERGY | 1 | 能量 | ✅ | ✅ | + * | **TRON_POWER** | **2** | **投票权(TP)** | ❌ | ❌ | + * | UNRECOGNIZED | -1 | protobuf 占位 | ❌ | ❌ | + * @return + */ + BigDecimal delegatedStakedTrxBalance(ApiWrapper api,String ownerAddr, int resourceCode); + + /** + * 取消质押账户金额 - 在unstakeTrxBalance操作后会有值 + * @param api + * @param ownerAddr + * @param resourceCode + * @return + */ + BigDecimal cancleStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode); + + /** + * 获取可投票的数量 + * @param ownerAddr + * @return + */ + BigDecimal voteBalance(ApiWrapper api,String ownerAddr); + + + /** + * 已经投票的数量 + * @param ownerAddr + * @return + */ + BigDecimal votedBalance(ApiWrapper api,String ownerAddr); + + /** + * 自动投票到top前size的地址上 + * @param api + * @param ownerAddress + * @param size + * @return + */ + boolean autoVoteTop(ApiWrapper api,String ownerAddress,int size) throws IllegalException; + + /** + * 自动领取TRX奖励 + * @param api + * @param ownerAddr + * @throws IllegalException + */ + boolean autoGetReward(ApiWrapper api,String ownerAddr) throws IllegalException; + + /** + * 给某个sender 授权usdt 额度-是做覆盖操作 + * @param api ownerAddr的api + * @param ownerAddr 账户所有者地址 + * @param sender - 被授权的钱包地址 + * @param amount + * @return + */ + Boolean approve(ApiWrapper api,String ownerAddr,String sender, BigDecimal amount); + + + BigDecimal getAllowance(ApiWrapper api,String ownerAddress, String spenderAddress); + /** + * usdt 转账 + * @param api 被授权(approve)的账号生成的api + * @param sender approve 被授权的钱包地址 + * @param fromAddress + * @param toAddress + * @param amount + * @return + */ + Boolean usdtTransferFrom(ApiWrapper api,String sender,String fromAddress, String toAddress, BigDecimal amount); + + /** + * 创建钱包 + * @return + */ + TronAccountItem createTronAddress(); + + /** + * 由助记词生成 + * @return + */ + TronAccount createTronWallet(Integer site); + /** + * 默认不使用 + * Estimate the energy required for the successful execution of smart contract transactions + * This API is closed by default in tron node. + * To open this interface, the two configuration items vm.estimateEnergy and vm.supportConstant + * must be enabled in the node configuration file at the same time. + * @param api + * @param fromAddress + * @param toAddress + * @param amount + * @return + */ + long estimateEnergy(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount); + + /** + * 默认消耗的energy + * @return + */ + long defaultEstimateEnergy(); + + + long defaultEstimateBandwidth(); + /** + * 获取transfer消耗的带宽 + * @param api + * @param fromAddress + * @param toAddress + * @param amount + * @return + */ + long estimateBandwidth(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount); + + /** + * 把质押的TRX 代理给其他账号获取 带宽或者能量 + * @param api + * @param fromAddress + * @param toAddress + * @param amount + * @param resourceCode + * @return + */ + String delegateResourceV2(ApiWrapper api,String fromAddress, String toAddress,BigDecimal amount ,int resourceCode); + + + /** + * 取消把质押的TRX 代理给其他账号 + * @param api + * @param fromAddress + * @param toAddress + * @param amount + * @param resourceCode + * @return + */ + String unDelegateResourceV2(ApiWrapper api,String fromAddress, String toAddress,BigDecimal amount ,int resourceCode); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/IUsdtAggregationTaskItemService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/IUsdtAggregationTaskItemService.java new file mode 100644 index 0000000..a9db767 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/IUsdtAggregationTaskItemService.java @@ -0,0 +1,93 @@ +package com.ruoyi.system.service; + +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.baomidou.mybatisplus.extension.service.IService; +import com.ruoyi.common.select.SelectItem; +import com.ruoyi.system.domain.UsdtAggregationTaskItem; +import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus; + +import java.util.List; +import java.util.Map; +/** + * 归集任务明细Service接口 + * + * @author luqj + * @date 2026-01-01 + */ +public interface IUsdtAggregationTaskItemService extends IService +{ + + List select(String keyword,boolean isUser); + /** + * 查询归集任务明细 + * + * @param id 归集任务明细ID + * @return 归集任务明细 + */ + public UsdtAggregationTaskItem selectUsdtAggregationTaskItemById(Long id,boolean isUser); + + /** + * 查询归集任务明细列表 + * + * @param usdtAggregationTaskItem 归集任务明细 + * @return 归集任务明细集合 + */ + public List selectUsdtAggregationTaskItemList(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser); + + /** + * 新增归集任务明细 + * + * @param usdtAggregationTaskItem 归集任务明细 + * @return 结果 + */ + public int insertUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser); + + /** + * 修改归集任务明细 + * + * @param usdtAggregationTaskItem 归集任务明细 + * @return 结果 + */ + public int updateUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser); + + /** + * 批量删除归集任务明细 + * + * @param ids 需要删除的归集任务明细ID + * @return 结果 + */ + public int deleteUsdtAggregationTaskItemByIds(Long[] ids,boolean isUser); + + /** + * 删除归集任务明细信息 + * + * @param id 归集任务明细ID + * @return 结果 + */ + public int deleteUsdtAggregationTaskItemById(Long id,boolean isUser); + + List getByIds(List ids,boolean isUser, SFunction... columns); + + UsdtAggregationTaskItemPlus getById(Long id, SFunction... columns); + + Map getMapByIds(List ids, SFunction... columns); + + List getListByStatusAndParentId(Integer status,Long parentId); + + List getByIds(List ids); + + Map getMapByIds(List ids); + + /** + * @param field sum 字段 + * @param where 条件 + * @param tClass 返回类型 + * @param + * @return + */ + T sum(String field, String where, Class tClass); + + Long count(String where); + + List countByGroupBy(String select, String where, String groupby, Class tClass); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/IUsdtAggregationTaskService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/IUsdtAggregationTaskService.java new file mode 100644 index 0000000..97f4eea --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/IUsdtAggregationTaskService.java @@ -0,0 +1,94 @@ +package com.ruoyi.system.service; + +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.baomidou.mybatisplus.extension.service.IService; +import com.ruoyi.common.select.SelectItem; +import com.ruoyi.system.domain.UsdtAggregationTask; +import com.ruoyi.system.domain.UsdtAggregationTaskPlus; + +import java.util.Date; +import java.util.List; +import java.util.Map; +/** + * 归集任务Service接口 + * + * @author luqj + * @date 2026-01-01 + */ +public interface IUsdtAggregationTaskService extends IService +{ + + List select(String keyword,boolean isUser); + + List getListByStatusAndLtExeTime(Integer status, Date gtExeTime); + /** + * 查询归集任务 + * + * @param id 归集任务ID + * @return 归集任务 + */ + public UsdtAggregationTask selectUsdtAggregationTaskById(Long id,boolean isUser); + + /** + * 查询归集任务列表 + * + * @param usdtAggregationTask 归集任务 + * @return 归集任务集合 + */ + public List selectUsdtAggregationTaskList(UsdtAggregationTask usdtAggregationTask,boolean isUser); + + /** + * 新增归集任务 + * + * @param usdtAggregationTask 归集任务 + * @return 结果 + */ + public int insertUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask,boolean isUser); + + /** + * 修改归集任务 + * + * @param usdtAggregationTask 归集任务 + * @return 结果 + */ + public int updateUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask,boolean isUser); + + /** + * 批量删除归集任务 + * + * @param ids 需要删除的归集任务ID + * @return 结果 + */ + public int deleteUsdtAggregationTaskByIds(Long[] ids,boolean isUser); + + /** + * 删除归集任务信息 + * + * @param id 归集任务ID + * @return 结果 + */ + public int deleteUsdtAggregationTaskById(Long id,boolean isUser); + + List getByIds(List ids,boolean isUser, SFunction... columns); + + UsdtAggregationTaskPlus getById(Long id, SFunction... columns); + + Map getMapByIds(List ids, SFunction... columns); + + List getByIds(List ids); + + Map getMapByIds(List ids); + + /** + * @param field sum 字段 + * @param where 条件 + * @param tClass 返回类型 + * @param + * @return + */ + T sum(String field, String where, Class tClass); + + Long count(String where); + + List countByGroupBy(String select, String where, String groupby, Class tClass); +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/IWalletAddressService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/IWalletAddressService.java index 86c7754..f95be54 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/IWalletAddressService.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/IWalletAddressService.java @@ -1,4 +1,5 @@ package com.ruoyi.system.service; +import java.math.BigDecimal; import java.util.Map; import java.util.List; import com.ruoyi.system.domain.WalletAddress; @@ -15,6 +16,8 @@ import com.ruoyi.common.select.SelectItem; public interface IWalletAddressService extends IService { + boolean updateTronInfo(WalletAddressPlus walletAddress); + List select(String keyword,boolean isUser); /** * 查询token管理 @@ -24,6 +27,10 @@ public interface IWalletAddressService extends IService */ public WalletAddress selectWalletAddressById(Long id,boolean isUser); + + WalletAddressPlus getByTokenAndAppId(String token,Long appId, SFunction... columns); + + List getListByAppId(Long appId, SFunction... columns); /** * 查询token管理列表 * @@ -70,6 +77,8 @@ public interface IWalletAddressService extends IService Map getMapByIds(List ids, SFunction... columns); + boolean updateWithdrawUsdtBalanceById(Long id, BigDecimal withdrawUsdtBalance); + List getByIds(List ids); Map getMapByIds(List ids); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java new file mode 100644 index 0000000..7401e22 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronNileServiceImpl.java @@ -0,0 +1,852 @@ +package com.ruoyi.system.service.impl; + +import com.google.protobuf.ByteString; +import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; +import com.ruoyi.system.domain.vo.TronAccount; +import com.ruoyi.system.domain.vo.TronAccountItem; +import com.ruoyi.system.domain.vo.TronAccountResp; +import com.ruoyi.system.service.ITronService; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import lombok.extern.slf4j.Slf4j; +import org.bitcoinj.crypto.ChildNumber; +import org.bitcoinj.crypto.DeterministicKey; +import org.bitcoinj.crypto.HDPath; +import org.bitcoinj.crypto.MnemonicCode; +import org.bitcoinj.wallet.DeterministicKeyChain; +import org.bitcoinj.wallet.DeterministicSeed; +import org.bouncycastle.crypto.digests.SM3Digest; +import org.bouncycastle.jcajce.provider.digest.Keccak; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.encoders.Hex; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.crypto.ECKey; +import org.tron.common.utils.Base58; +import org.tron.common.utils.ByteArray; +import org.tron.protos.Protocol; +import org.tron.trident.abi.FunctionEncoder; +import org.tron.trident.abi.datatypes.Address; +import org.tron.trident.abi.datatypes.Function; +import org.tron.trident.abi.datatypes.generated.Uint256; +import org.tron.trident.core.ApiWrapper; +import org.tron.trident.core.NodeType; +import org.tron.trident.core.contract.Contract; +import org.tron.trident.core.contract.Trc20Contract; +import org.tron.trident.core.exceptions.IllegalException; +import org.tron.trident.proto.Chain; +import org.tron.trident.proto.Common; +import org.tron.trident.proto.Response; +import org.tron.trident.utils.Base58Check; +import org.tron.trident.utils.Convert; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.*; +import java.util.stream.Collectors; + +@Slf4j +@ConditionalOnProperty(prefix = "tron.env", name = "type", havingValue = "nile") +@Service +public class TronNileServiceImpl implements ITronService { + // 能量和带宽限制 + public static final long FEE_LIMIT = 10_000_000L; // 10 TRX + private static SecureRandom random = new SecureRandom(); + private static final BigInteger BASE = BigInteger.valueOf(58); + private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); + private RestTemplate restTemplate = new RestTemplate(); + @Override + public Integer grpcPort() { + return 50051; + } + + @Override + public String grpcUrl() { + return "grpc.nile.trongrid.io"; + } + + @Override + public String type() { + return "nile"; + } + + @Override + public ApiWrapper buildApiWrapper(String privateKey) { + ApiWrapper apiWrapper = ApiWrapper.ofNile(privateKey); + return apiWrapper; + } + + @Override + public String contractAddress() { + return "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf"; + } + + @Override + public String tronscanApiUrl() { + return "https://nileapi.tronscan.org"; + } + + @Override + public String tronscanApiKey() { + return ""; + } + + @Override + public String usdtTrans(ApiWrapper api, String fromAddress, String toAddress, String amount) { + try { + // 获取合约地址信息 + Contract contract = api.getContract(contractAddress()); + Trc20Contract token = new Trc20Contract(contract, fromAddress, api); + String transfer; + // 获取转账账户的TRX余额 + BigInteger trc20Value = token.balanceOf(fromAddress); + // 获取想要转账的数额 + BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger(); + // 进行比较 + if (trc20Value.compareTo(sunAmountValue) >= 0) { + // 设置最大矿工费用 + long feeLimit = Convert.toSun("2", Convert.Unit.TRX).longValue(); + //转账 + transfer = token.transfer(toAddress, sunAmountValue.longValue(), 0, "", feeLimit); + } else { + return null; + } + if (transfer == null || transfer.isEmpty()) { + return null; + } + return transfer; + } catch (Exception ex) { + log.error(ex.getMessage(),ex); + throw new RuntimeException(ex.getMessage()); + } + } + + @Override + public String trxTrans(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) { + try { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + // 创建交易 + Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount); + // 签名交易 + Chain.Transaction signTransaction = api.signTransaction(transaction); + // 计算交易所需要的宽带 + long byteSize = api.estimateBandwidth(signTransaction); +// long byteSize = api.estimateEnergy(signTransaction); + // 广播交易 + String hashTx = api.broadcastTransaction(signTransaction); + return hashTx; + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + @Override + public BigDecimal getTRxBalance(ApiWrapper api, String address) { + Long balance = api.getAccountBalance(address); + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(balance).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + @Override + public BigDecimal getUsdtBalance(ApiWrapper api, String address) { + Contract contract = api.getContract(contractAddress()); + Trc20Contract token = new Trc20Contract(contract, address, api); + BigInteger balanceOf = token.balanceOf(address); + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(balanceOf).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + @Override + public EnergyAndBandwidthVo energyAndBandwidth(String ownerAddr) { + ManagedChannel channel = ManagedChannelBuilder +// .forAddress("grpc.trongrid.io", 50051) + .forAddress(this.grpcUrl(), this.grpcPort()) + .usePlaintext() + .build(); + WalletGrpc.WalletBlockingStub stub = + WalletGrpc.newBlockingStub(channel); + byte[] address = Base58Check.base58ToBytes(ownerAddr); + Protocol.Account account = Protocol.Account.newBuilder() + .setAddress(ByteString.copyFrom(address)) + .build(); + GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account); + long bandwidth = + (res.getFreeNetLimit() - res.getFreeNetUsed()) + + (res.getNetLimit() - res.getNetUsed()); + long energy = + res.getEnergyLimit() - res.getEnergyUsed(); + EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo(); + energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth)); + energyAndBandwidthVo.setEnergy(new BigDecimal(energy)); + channel.shutdown(); + return energyAndBandwidthVo; + } + + @Override + public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) { + HttpHeaders headers = new HttpHeaders(); + headers.set("TRON-PRO-API-KEY", "your_api_key"); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + + HttpEntity entity = new HttpEntity<>(headers); + ResponseEntity result = restTemplate.exchange(tronscanApiUrl()+"/api/accountv2?address="+ownerAddr, HttpMethod.GET,entity, TronAccountResp.class); + EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo(); + if(null != result.getBody()){ + energyAndBandwidthVo.setAcquiredEnergy(result.getBody().getAcquiredDelegatedFrozenV2BalanceForEnergyValue()); + energyAndBandwidthVo.setAcquiredBandwidth(result.getBody().getAcquiredDelegatedFrozenV2BalanceForBandwidthValue()); + energyAndBandwidthVo.setDelegateEnergy(result.getBody().getDelegatedFrozenV2BalanceForEnergyValue()); + energyAndBandwidthVo.setDelegateBandwidth(result.getBody().getDelegatedFrozenV2BalanceForBandwidthValue()); + energyAndBandwidthVo.setStakedTrxNum(result.getBody().getTotalFrozenV2()); + energyAndBandwidthVo.setBandwidthStakedNum(result.getBody().getBandwidth().getNetRemaining()); + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(energyAndBandwidthVo.getStakedTrxNum()).divide(divisor, 4, RoundingMode.HALF_UP); + energyAndBandwidthVo.setStakedTrxNum(divide.longValue()); + }else{ + energyAndBandwidthVo.setDelegateBandwidth(new BigDecimal(0)); + energyAndBandwidthVo.setDelegateEnergy(new BigDecimal(0)); + energyAndBandwidthVo.setAcquiredBandwidth(new BigDecimal(0)); + energyAndBandwidthVo.setAcquiredEnergy(new BigDecimal(0)); + energyAndBandwidthVo.setStakedTrxNum(0L); + } + return energyAndBandwidthVo; + } + + @Override + public boolean unstakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Response.TransactionExtention tx = null; + try { + tx = api.unfreezeBalanceV2(ownerAddr, + balance.multiply(divisor).longValue(), + resourceCode + ); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public boolean cancleUnstakeTrxBalance(ApiWrapper api, String ownerAddr) { + Response.TransactionExtention tx = null; + try { + tx = api.cancelAllUnfreezeV2(ownerAddr); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public boolean stakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Response.TransactionExtention tx = null; + try { + tx = api.freezeBalanceV2(ownerAddr, + balance.multiply(divisor).longValue(), + resourceCode + ); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public BigDecimal stakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + Response.Account account = api.getAccount(ownerAddr); + long totalStakedSun = 0; + // ===== FrozenV2(当前主流质押方式)===== + for (Response.Account.FreezeV2 frozenV2 : account.getFrozenV2List()) { + if (frozenV2.getType().getNumber() == resourceCode) { + totalStakedSun += frozenV2.getAmount(); + } + } + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + @Override + public BigDecimal acquiredDelegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + try { + Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr); + List list = resourceAccountIndex.getFromAccountsList(); + BigDecimal result = new BigDecimal(0); + for (ByteString byteString : list) { + String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray()); + String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress)); + Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(address, ownerAddr); + int count = delegatedResourceList.getDelegatedResourceCount(); + for (int i = 0; i < count; i++) { + Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i); + String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray()); + String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress)); + String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray()); + String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress)); + if (resourceCode == 0) { + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } else if (resourceCode == 1) { + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } + } + } + return result; + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new RuntimeException(e); + } + } + @Override + public BigDecimal delegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + try { + Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr); + List list = resourceAccountIndex.getToAccountsList(); + BigDecimal result = new BigDecimal(0); + for (ByteString byteString : list) { + String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray()); + String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress)); + Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(ownerAddr,address); + int count = delegatedResourceList.getDelegatedResourceCount(); + for (int i = 0; i < count; i++) { + Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i); + String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray()); + String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress)); + String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray()); + String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress)); + if (resourceCode == 0) { + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } else if (resourceCode == 1) { + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } + } + } + return result; + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new RuntimeException(e); + } + } + public BigDecimal cancleStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + Response.Account account = api.getAccount(ownerAddr); + long totalStakedSun = 0; + // ===== FrozenV2(当前主流质押方式)===== + for (Response.Account.UnFreezeV2 frozenV2 : account.getUnfrozenV2List()) { + if (frozenV2.getType().getNumber() == resourceCode) { + totalStakedSun += frozenV2.getUnfreezeAmount(); + } + } + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP); + System.out.println(divide); + return divide; + } + + @Override + public BigDecimal voteBalance(ApiWrapper api, String ownerAddr) { + Response.Account account = api.getAccount(ownerAddr); + long totalVotes = account.getFrozenV2List().stream() + .mapToLong(Response.Account.FreezeV2::getAmount) + .sum() / 1_000_000; + return new BigDecimal(totalVotes); + } + + @Override + public BigDecimal votedBalance(ApiWrapper api, String ownerAddr) { + Response.Account account = api.getAccount(ownerAddr); + Map currentVotes = account.getVotesList().stream() + .collect(Collectors.toMap( + v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()), + Common.Vote::getVoteCount + )); + Iterator> iterator = currentVotes.entrySet().iterator(); + BigDecimal bigDecimal = new BigDecimal(0); + while (iterator.hasNext()) { + bigDecimal = bigDecimal.add(new BigDecimal(iterator.next().getValue())); + } + return bigDecimal; + } + + @Override + public boolean autoVoteTop(ApiWrapper api, String ownerAddress, int size) throws IllegalException { + // 1. 当前账户 + Response.Account account = api.getAccount(ownerAddress); + long totalVotes = account.getFrozenV2List().stream() + .mapToLong(Response.Account.FreezeV2::getAmount) + .sum() / 1_000_000; + if (totalVotes <= 0) { + log.error("没有投票的vote"); + return false; + } + Map currentVotes = account.getVotesList().stream() + .collect(Collectors.toMap( + v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()), + Common.Vote::getVoteCount + )); + // 2. Top27 SR + Response.WitnessList witnesses = api.listWitnesses(); + Set top27 = witnesses.getWitnessesList().stream() + .sorted(Comparator.comparingLong(w -> -w.getVoteCount())) + .limit(size + 1) + .map(w -> Base58Check.bytesToBase58(w.getAddress().toByteArray())) + .collect(Collectors.toSet()); + + // 3. 找出掉出 Top27 的 SR + boolean needRevote = currentVotes.keySet().stream() + .anyMatch(sr -> !top27.contains(sr)); + Iterator iterator = currentVotes.keySet().iterator(); + org.tron.protos.Contract.VoteWitnessContract.Builder builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder() + .setOwnerAddress(ApiWrapper.parseAddress(ownerAddress)); + boolean cancle = false; + while (iterator.hasNext()) { + String address = iterator.next(); + if (!top27.contains(address)) { + builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(address)) + .setVoteCount(1)); + cancle = true; + } + } + if (cancle) { + org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build(); + Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract, + Chain.Transaction.Contract.ContractType.VoteWitnessContract); + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + } + if (!needRevote) { + log.info("All SRs still in Top27."); + return true; + } + // 4. 总投票权 + List backupSRs = new ArrayList<>(); + // 5. 构建新投票(平均投到备用 SR) + backupSRs.addAll(top27.stream().sorted().collect(Collectors.toList()).subList(0, size)); + long perSRVotes = totalVotes / backupSRs.size(); + builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder() + .setOwnerAddress(ApiWrapper.parseAddress(ownerAddress)); + for (String sr : backupSRs) { + builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(sr)).setVoteCount(perSRVotes)); + } + org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build(); + Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract, + Chain.Transaction.Contract.ContractType.VoteWitnessContract); + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public boolean autoGetReward(ApiWrapper api, String ownerAddr) throws IllegalException { + org.tron.trident.api.GrpcAPI.NumberMessage reward = api.getRewardInfo(ownerAddr, NodeType.FULL_NODE); + log.info("Unclaimed reward: " + reward.getNum() / 1_000_000.0 + " TRX"); + Response.TransactionExtention tx = api.withdrawBalance(ownerAddr); + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public Boolean approve(ApiWrapper api, String ownerAddr, String spenderAddress, BigDecimal amount) { + try { + BigInteger amountInSun = + amount + .multiply(BigDecimal.valueOf(1_000_000)) + .toBigInteger(); + Function function = new Function( + "approve", + Arrays.asList( + new Address(spenderAddress), + new Uint256(amountInSun) + ), + Collections.emptyList() + ); + Chain.Transaction txnExtension = api.triggerCall( + ownerAddr, + ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())), + function + ).setFeeLimit(FEE_LIMIT).build(); + Chain.Transaction signedTxn = api.signTransaction(txnExtension); + Response.TransactionReturn ret = api.blockingStub.broadcastTransaction(signedTxn); + return ret.getResult(); + } catch (Exception e) { + log.error("授权异常: " + e.getMessage(), e); + return null; + } + } + + @Override + public BigDecimal getAllowance(ApiWrapper api, String ownerAddress, String spenderAddress) { + // Trc20合约地址 + Contract contract = api.getContract(contractAddress()); + Trc20Contract token = new Trc20Contract(contract, ownerAddress, api); + try { + // 查询授权额度 + BigInteger allowance = token.allowance(ownerAddress, spenderAddress); + + // 如果是USDT等6位小数代币 + double allowanceInToken = allowance.doubleValue() / 1_000_000.0; + return new BigDecimal(allowanceInToken); + } catch (Exception e) { + e.printStackTrace(); + } + return new BigDecimal(0); + } + + @Override + public Boolean usdtTransferFrom(ApiWrapper api, String sender, String fromAddress, String toAddress, BigDecimal amount) { + try { + // 转换金额为 USDT 最小单位 (6位小数) + BigInteger amountInSun = + amount + .multiply(BigDecimal.valueOf(1_000_000)) + .toBigInteger(); + // 构建 transferFrom 函数 + Function function = new Function( + "transferFrom", + Arrays.asList( + new Address(fromAddress), // 转出地址 + new Address(toAddress), // 接收地址 + new Uint256(amountInSun) // 转账金额 + ), + Collections.emptyList() + ); + + + String encodedFunction = FunctionEncoder.encode(function); + System.out.println("编码后的函数: " + encodedFunction); + + // 触发智能合约调用 + Chain.Transaction txnExtension = api.triggerCall( + ApiWrapper.toHex(ApiWrapper.parseAddress(sender)), // 调用者地址 + ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())), + function + ).setFeeLimit(FEE_LIMIT).build(); + // 签名交易 + Chain.Transaction signedTxn = api.signTransaction(txnExtension); + // 广播交易 + String ret = api.broadcastTransaction(signedTxn); + log.info(ret); + return true; + } catch (Exception e) { + log.error("transferFrom 异常: " + e.getMessage(), e); + return false; + } + } + + @Override + public TronAccountItem createTronAddress() { + ECKey eCkey = new ECKey(random); + String privateKey = ByteArray.toHexString(eCkey.getPrivKeyBytes()); + byte[] addressBytes = eCkey.getAddress(); + String hexAddress = ByteArray.toHexString(addressBytes); + TronAccountItem tronAccount = new TronAccountItem(); + tronAccount.setAddress(toViewAddress(hexAddress)); + tronAccount.setHexAddress(hexAddress); + tronAccount.setPrivateKey(privateKey); + //String privateKeyBase58 = org.spongycastle.util.encoders.Hex.e(base58Str); + String privateKeyBase58 = encode58Check(eCkey.getPrivKeyBytes()); + tronAccount.setPrivateKeyBase58(privateKeyBase58); + return tronAccount; + } + + private static byte[] keccak256(byte[] input) { + Keccak.Digest256 digest = new Keccak.Digest256(); + return digest.digest(input); + } + + private String formatHDPath(HDPath path) { + StringBuilder sb = new StringBuilder("m"); + for (ChildNumber cn : path) { + sb.append("/"); + sb.append(cn.isHardened() ? cn.num() + "'" : cn.num()); + } + return sb.toString(); + } + + private String base58CheckEncode(byte[] input) throws NoSuchAlgorithmException { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash1 = digest.digest(input); + byte[] hash2 = digest.digest(hash1); + + byte[] checksum = Arrays.copyOfRange(hash2, 0, 4); + + byte[] result = new byte[input.length + 4]; + System.arraycopy(input, 0, result, 0, input.length); + System.arraycopy(checksum, 0, result, input.length, 4); + + return encode(result); + } + + public String encode(byte[] input) { + BigInteger bi = new BigInteger(1, input); + StringBuilder sb = new StringBuilder(); + while (bi.compareTo(BigInteger.ZERO) > 0) { + BigInteger[] div = bi.divideAndRemainder(BASE); + sb.append(ALPHABET[div[1].intValue()]); + bi = div[0]; + } + for (byte b : input) { + if (b == 0) { + sb.append(ALPHABET[0]); + } else { + break; + } + } + return sb.reverse().toString(); + } + + @Override + public TronAccount createTronWallet(Integer site) { + TronAccount result = new TronAccount(); + // 1. 生成随机助记词(12个) + SecureRandom random = new SecureRandom(); + byte[] entropy = new byte[16]; // 128-bit entropy + random.nextBytes(entropy); + List mnemonicWords = MnemonicCode.INSTANCE.toMnemonic(entropy); + + // 可以使用助记词恢复公私钥和钱包地址 + /*String mnemonicStr = "elder trend clay accuse joke pizza extend holiday spread apple dress mercy"; + List mnemonicWords = Arrays.stream(mnemonicStr.split(" ")).collect(Collectors.toList());*/ + + String mnemonic = String.join(" ", mnemonicWords); + result.setPhrase(mnemonic); + // 2. 创建 DeterministicSeed 和 KeyChain + DeterministicSeed seed = DeterministicSeed.ofMnemonic(mnemonicWords, ""); + DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build(); + + // 3. 使用 TRON 路径 m/44'/195'/0'/0/i + HDPath basePath = HDPath.M().extend( + new ChildNumber(44, true), + new ChildNumber(195, true), + new ChildNumber(0, true), + ChildNumber.ZERO + ); + + List list = new ArrayList<>(); + for (int i = 0; i < site; i++) { + HDPath path = basePath.extend(new ChildNumber(i, false)); + DeterministicKey key = keyChain.getKeyByPath(path, true); + byte[] privateKey = key.getPrivKeyBytes(); + byte[] pubKeyCompressed = key.getPubKey(); // 压缩公钥(33字节) + ECPoint pubKeyPoint = key.getPubKeyPoint(); + byte[] pubKeyUnCompressed = pubKeyPoint.getEncoded(false); // 非压缩公钥(65字节) + byte[] pubKeyWithoutPrefix = Arrays.copyOfRange(pubKeyUnCompressed, 1, pubKeyUnCompressed.length); + byte[] keccakHash = keccak256(pubKeyWithoutPrefix); + byte[] addressBytes = new byte[21]; + addressBytes[0] = (byte) 0x41; + System.arraycopy(keccakHash, 12, addressBytes, 1, 20); + String base58Address = null; + try { + base58Address = base58CheckEncode(addressBytes); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + String pathStr = formatHDPath(path); + TronAccountItem item = new TronAccountItem(); + item.setAddress(base58Address); + item.setPrivateKey(Hex.toHexString(privateKey)); + item.setPubKeyCompressed(Hex.toHexString(pubKeyCompressed)); + item.setPubKeyUnCompressed(Hex.toHexString(pubKeyUnCompressed)); + item.setPath(pathStr); + String hexAddress = ByteArray.toHexString(addressBytes); + item.setHexAddress(hexAddress); + String privateKeyBase58 = encode58Check(privateKey); + item.setPrivateKeyBase58(privateKeyBase58); + + list.add(item); + } + result.setItems(list); + return result; + } + + /** + * Estimate the energy required for the successful execution of smart contract transactions + * This API is closed by default in tron node. + * To open this interface, the two configuration items vm.estimateEnergy and vm.supportConstant + * must be enabled in the node configuration file at the same time. + * + * @param api + * @param owner + * @param toAddress + * @param amount + * @return + */ + @Override + public long estimateEnergy(ApiWrapper api, String owner, String toAddress, BigDecimal amount) { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + Function function = new Function( + "transfer(address,uint256)", + Arrays.asList( + new Address(toAddress), // 接收地址 + new Uint256(rechangeAmount) // 转账金额 + ), + Collections.emptyList() + ); + String callData = FunctionEncoder.encode(function); + + Response.EstimateEnergyMessage estimate = api.estimateEnergy( + owner, callData, callData, 0, 0, null + ); + return estimate.getEnergyRequired(); + } + + @Override + public long defaultEstimateEnergy() { + return 20000L; + } + + @Override + public long defaultEstimateBandwidth() { + return 365; + } + + @Override + public long estimateBandwidth(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) { + try { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + // 创建交易 + Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount); + // 签名交易 + Chain.Transaction signTransaction = api.signTransaction(transaction); + // 计算交易所需要的宽带 + return api.estimateBandwidth(signTransaction); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return 0; + } + + @Override + public String delegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + Response.TransactionExtention transactionExtention = null; + try { + transactionExtention = api.delegateResourceV2(fromAddress,rechangeAmount,resourceCode,toAddress,true,86400); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signTransaction = api.signTransaction(transactionExtention); + String hashTx = api.broadcastTransaction(signTransaction); + return hashTx; + } + + @Override + public String unDelegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + Response.TransactionExtention transactionExtention = null; + try { + transactionExtention = api.undelegateResource(fromAddress,rechangeAmount,resourceCode,toAddress); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signTransaction = api.signTransaction(transactionExtention); + String hashTx = api.broadcastTransaction(signTransaction); + return hashTx; + } + + /** + * 转换成T开头的地址 + * + * @param hexAddress + * @return + */ + private String toViewAddress(String hexAddress) { + return encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress)); + } + + /** + * Calculates the SHA-256 hash of the given bytes. + * + * @param input the bytes to hash + * @return the hash (in big-endian order) + */ + public byte[] hash(boolean isSha256, byte[] input) throws NoSuchAlgorithmException { + return hash(isSha256, input, 0, input.length); + } + + /** + * Calculates the SHA-256 hash of the given byte range. + * + * @param input the array containing the bytes to hash + * @param offset the offset within the array of the bytes to hash + * @param length the number of bytes to hash + * @return the hash (in big-endian order) + */ + public byte[] hash(boolean isSha256, byte[] input, int offset, int length) throws NoSuchAlgorithmException { + if (isSha256) { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + digest.update(input, offset, length); + return digest.digest(); + } else { + SM3Digest digest = new SM3Digest(); + digest.update(input, offset, length); + byte[] eHash = new byte[digest.getDigestSize()]; + digest.doFinal(eHash, 0); + return eHash; + } + } + + private String encode58Check(byte[] input) { + try { + byte[] hash0 = hash(true, input); + byte[] hash1 = hash(true, hash0); + byte[] inputCheck = new byte[input.length + 4]; + System.arraycopy(input, 0, inputCheck, 0, input.length); + System.arraycopy(hash1, 0, inputCheck, input.length, 4); + return Base58.encode(inputCheck); + } catch (Throwable t) { + log.error(String.format("data error:%s", Hex.toHexString(input)), t); + } + return null; + } + + public static void main(String[] args) { + ITronService tronService = new TronNileServiceImpl(); +// tronService.energyAndBandwidth("TULphDUxnr4VBrKJr4C6YVetses1PSx8B4"); + ApiWrapper api = tronService.buildApiWrapper("34d200bcf5693a7ffc000edbb85fe0a7f84e7c87d894ef8638f516c07994a989"); + tronService.delegateResourceV2(api,"TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW","TULphDUxnr4VBrKJr4C6YVetses1PSx8B4",new BigDecimal("20"),0); +// BigDecimal balance = tronService.getUsdtBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW"); +// System.out.println(balance); +// balance = tronService.getTRxBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW"); +// System.out.println(balance); +// tronService.energyAndBandwidth("TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW"); +// System.out.println(tronService.stakedTrxBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW", 0)); +// System.out.println(tronService.stakedTrxBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW", 1)); +// System.out.println(tronService.delegatedStakedTrxBalance(api, "TULphDUxnr4VBrKJr4C6YVetses1PSx8B4", 1)); +// System.out.println(tronService.delegatedStakedTrxBalance(api, "TULphDUxnr4VBrKJr4C6YVetses1PSx8B4", 0)); +//// tronService.trxTrans(api,"TULphDUxnr4VBrKJr4C6YVetses1PSx8B4","TXTJKCikqtLZHK7moDdmxdaTNWbjdCM1H9",new BigDecimal(200)); +//// TronAccount tronAccount = tronService.createTronWallet(2); +//// System.out.println(JSONObject.toJSONString(tronAccount)); +// tronService.allDelegatedDnergyAndBandwidth("TULphDUxnr4VBrKJr4C6YVetses1PSx8B4"); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java new file mode 100644 index 0000000..5121e3c --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronProServiceImpl.java @@ -0,0 +1,834 @@ +package com.ruoyi.system.service.impl; + +import com.google.protobuf.ByteString; +import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; +import com.ruoyi.system.domain.vo.TronAccount; +import com.ruoyi.system.domain.vo.TronAccountItem; +import com.ruoyi.system.domain.vo.TronAccountResp; +import com.ruoyi.system.service.ITronService; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import lombok.extern.slf4j.Slf4j; +import org.bitcoinj.crypto.ChildNumber; +import org.bitcoinj.crypto.DeterministicKey; +import org.bitcoinj.crypto.HDPath; +import org.bitcoinj.crypto.MnemonicCode; +import org.bitcoinj.wallet.DeterministicKeyChain; +import org.bitcoinj.wallet.DeterministicSeed; +import org.bouncycastle.crypto.digests.SM3Digest; +import org.bouncycastle.jcajce.provider.digest.Keccak; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.encoders.Hex; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.crypto.ECKey; +import org.tron.common.utils.Base58; +import org.tron.common.utils.ByteArray; +import org.tron.protos.Protocol; +import org.tron.trident.abi.FunctionEncoder; +import org.tron.trident.abi.datatypes.Address; +import org.tron.trident.abi.datatypes.Function; +import org.tron.trident.abi.datatypes.generated.Uint256; +import org.tron.trident.core.ApiWrapper; +import org.tron.trident.core.NodeType; +import org.tron.trident.core.contract.Contract; +import org.tron.trident.core.contract.Trc20Contract; +import org.tron.trident.core.exceptions.IllegalException; +import org.tron.trident.proto.Chain; +import org.tron.trident.proto.Common; +import org.tron.trident.proto.Response; +import org.tron.trident.utils.Base58Check; +import org.tron.trident.utils.Convert; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.*; +import java.util.stream.Collectors; + +@Slf4j +@ConditionalOnProperty(prefix = "tron.env", name = "type", havingValue = "pro") +@Service +public class TronProServiceImpl implements ITronService { + private static final BigInteger BASE = BigInteger.valueOf(58); + + private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); + private RestTemplate restTemplate = new RestTemplate(); + // 能量和带宽限制 + public static final long FEE_LIMIT = 10_000_000L; // 10 TRX + private static SecureRandom random = new SecureRandom(); + + @Override + public Integer grpcPort() { + return 50051; + } + + @Override + public String grpcUrl() { + return "grpc.trongrid.io"; + } + + @Override + public String type() { + return "pro"; + } + + @Override + public ApiWrapper buildApiWrapper(String privateKey) { + return ApiWrapper.ofMainnet(privateKey, "719b2ba2-dedd-48ad-99a6-df1caa6f08ae"); + } + + private static byte[] keccak256(byte[] input) { + Keccak.Digest256 digest = new Keccak.Digest256(); + return digest.digest(input); + } + + private String formatHDPath(HDPath path) { + StringBuilder sb = new StringBuilder("m"); + for (ChildNumber cn : path) { + sb.append("/"); + sb.append(cn.isHardened() ? cn.num() + "'" : cn.num()); + } + return sb.toString(); + } + + private String base58CheckEncode(byte[] input) throws NoSuchAlgorithmException { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash1 = digest.digest(input); + byte[] hash2 = digest.digest(hash1); + + byte[] checksum = Arrays.copyOfRange(hash2, 0, 4); + + byte[] result = new byte[input.length + 4]; + System.arraycopy(input, 0, result, 0, input.length); + System.arraycopy(checksum, 0, result, input.length, 4); + + return encode(result); + } + + public String encode(byte[] input) { + BigInteger bi = new BigInteger(1, input); + StringBuilder sb = new StringBuilder(); + while (bi.compareTo(BigInteger.ZERO) > 0) { + BigInteger[] div = bi.divideAndRemainder(BASE); + sb.append(ALPHABET[div[1].intValue()]); + bi = div[0]; + } + for (byte b : input) { + if (b == 0) { + sb.append(ALPHABET[0]); + } else { + break; + } + } + return sb.reverse().toString(); + } + + @Override + public String contractAddress() { + return "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"; + } + + @Override + public String tronscanApiUrl() { + return "https://api.tronscan.org"; + } + + @Override + public String tronscanApiKey() { + return "47fae50b-b5e8-4d1b-8329-501a422a3169"; + } + + @Override + public String usdtTrans(ApiWrapper api, String fromAddress, String toAddress, String amount) { + try { + // 获取合约地址信息 + Contract contract = api.getContract(contractAddress()); + Trc20Contract token = new Trc20Contract(contract, fromAddress, api); + String transfer; + // 获取转账账户的TRX余额 + BigInteger trc20Value = token.balanceOf(fromAddress); + // 获取想要转账的数额 + BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger(); + // 进行比较 + if (trc20Value.compareTo(sunAmountValue) >= 0) { + // 设置最大矿工费用 + long feeLimit = Convert.toSun("2", Convert.Unit.TRX).longValue(); + //转账 + transfer = token.transfer(toAddress, sunAmountValue.longValue(), 0, "", feeLimit); + } else { + return "error_error"; + } + if (transfer == null || transfer.equals("")) { + return "error_error"; + } + return transfer; + } catch (Exception ex) { + String message = ex.getMessage(); + return "error_" + message; + } + } + + @Override + public String trxTrans(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) { + try { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + // 创建交易 + Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount); + // 签名交易 + Chain.Transaction signTransaction = api.signTransaction(transaction); + // 计算交易所需要的宽带 + long byteSize = api.estimateBandwidth(signTransaction); +// long byteSize = api.estimateEnergy(signTransaction); + // 广播交易 + String hashTx = api.broadcastTransaction(signTransaction); + return hashTx; + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + @Override + public BigDecimal getTRxBalance(ApiWrapper api, String address) { + Long balance = api.getAccountBalance(address); + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(balance).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + @Override + public BigDecimal getUsdtBalance(ApiWrapper api, String address) { + Contract contract = api.getContract(contractAddress()); + Trc20Contract token = new Trc20Contract(contract, address, api); + BigInteger balanceOf = token.balanceOf(address); + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(balanceOf).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + @Override + public EnergyAndBandwidthVo energyAndBandwidth(String ownerAddr) { + ManagedChannel channel = ManagedChannelBuilder +// .forAddress("grpc.trongrid.io", 50051) + .forAddress(this.grpcUrl(), this.grpcPort()) + .usePlaintext() + .build(); + WalletGrpc.WalletBlockingStub stub = + WalletGrpc.newBlockingStub(channel); + byte[] address = Base58Check.base58ToBytes(ownerAddr); + Protocol.Account account = Protocol.Account.newBuilder() + .setAddress(ByteString.copyFrom(address)) + .build(); + GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account); + long bandwidth = + (res.getFreeNetLimit() - res.getFreeNetUsed()) + + (res.getNetLimit() - res.getNetUsed()); + long energy = + res.getEnergyLimit() - res.getEnergyUsed(); + EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo(); + energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth)); + energyAndBandwidthVo.setEnergy(new BigDecimal(energy)); + return energyAndBandwidthVo; + } + @Override + public String unDelegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + Response.TransactionExtention transactionExtention = null; + try { + transactionExtention = api.undelegateResource(fromAddress,rechangeAmount,resourceCode,toAddress); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signTransaction = api.signTransaction(transactionExtention); + String hashTx = api.broadcastTransaction(signTransaction); + return hashTx; + } + @Override + public String delegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + Response.TransactionExtention transactionExtention = null; + try { + transactionExtention = api.delegateResourceV2(fromAddress,rechangeAmount,resourceCode,toAddress,true,86400); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signTransaction = api.signTransaction(transactionExtention); + String hashTx = api.broadcastTransaction(signTransaction); + return hashTx; + } + @Override + public long defaultEstimateBandwidth() { + return 365; + } + @Override + public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) { + HttpHeaders headers = new HttpHeaders(); + headers.set("TRON-PRO-API-KEY", "your_api_key"); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + + HttpEntity entity = new HttpEntity<>(headers); + ResponseEntity result = restTemplate.exchange(tronscanApiUrl()+"/api/accountv2?address="+ownerAddr, HttpMethod.GET,entity, TronAccountResp.class); + EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo(); + if(null != result.getBody()){ + energyAndBandwidthVo.setAcquiredEnergy(result.getBody().getAcquiredDelegatedFrozenV2BalanceForEnergyValue()); + energyAndBandwidthVo.setAcquiredBandwidth(result.getBody().getAcquiredDelegatedFrozenV2BalanceForBandwidthValue()); + energyAndBandwidthVo.setDelegateEnergy(result.getBody().getDelegatedFrozenV2BalanceForEnergyValue()); + energyAndBandwidthVo.setDelegateBandwidth(result.getBody().getDelegatedFrozenV2BalanceForBandwidthValue()); + energyAndBandwidthVo.setStakedTrxNum(result.getBody().getTotalFrozenV2()); + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(energyAndBandwidthVo.getStakedTrxNum()).divide(divisor, 4, RoundingMode.HALF_UP); + energyAndBandwidthVo.setStakedTrxNum(divide.longValue()); + }else{ + energyAndBandwidthVo.setDelegateBandwidth(new BigDecimal(0)); + energyAndBandwidthVo.setDelegateEnergy(new BigDecimal(0)); + energyAndBandwidthVo.setAcquiredBandwidth(new BigDecimal(0)); + energyAndBandwidthVo.setAcquiredEnergy(new BigDecimal(0)); + energyAndBandwidthVo.setStakedTrxNum(0L); + } + return energyAndBandwidthVo; + } + + @Override + public boolean unstakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Response.TransactionExtention tx = null; + try { + tx = api.unfreezeBalanceV2(ownerAddr, + balance.multiply(divisor).longValue(), + resourceCode + ); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + @Override + public BigDecimal votedBalance(ApiWrapper api, String ownerAddr) { + Response.Account account = api.getAccount(ownerAddr); + Map currentVotes = account.getVotesList().stream() + .collect(Collectors.toMap( + v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()), + Common.Vote::getVoteCount + )); + Iterator> iterator = currentVotes.entrySet().iterator(); + BigDecimal bigDecimal = new BigDecimal(0); + while (iterator.hasNext()) { + bigDecimal = bigDecimal.add(new BigDecimal(iterator.next().getValue())); + } + return bigDecimal; + } + @Override + public BigDecimal delegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + try { + Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr); + List list = resourceAccountIndex.getToAccountsList(); + BigDecimal result = new BigDecimal(0); + for (ByteString byteString : list) { + String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray()); + String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress)); + Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(ownerAddr,address); + int count = delegatedResourceList.getDelegatedResourceCount(); + for (int i = 0; i < count; i++) { + Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i); + String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray()); + String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress)); + String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray()); + String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress)); + if (resourceCode == 0) { + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } else if (resourceCode == 1) { + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } + } + } + return result; + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new RuntimeException(e); + } + } + @Override + public BigDecimal acquiredDelegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + try { + Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr); + List list = resourceAccountIndex.getFromAccountsList(); + BigDecimal result = new BigDecimal(0); + for (ByteString byteString : list) { + String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray()); + String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress)); + Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(address, ownerAddr); + int count = delegatedResourceList.getDelegatedResourceCount(); + for (int i = 0; i < count; i++) { + Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i); + String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray()); + String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress)); + String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray()); + String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress)); + if(resourceCode == 0){ + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + }else if(resourceCode == 1){ + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } + } + } + return result; + }catch (Exception e){ + log.error(e.getMessage(),e); + throw new RuntimeException(e); + } + } + @Override + public boolean cancleUnstakeTrxBalance(ApiWrapper api, String ownerAddr) { + Response.TransactionExtention tx = null; + try { + tx = api.cancelAllUnfreezeV2(ownerAddr); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public boolean stakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Response.TransactionExtention tx = null; + try { + tx = api.freezeBalanceV2(ownerAddr, + balance.multiply(divisor).longValue(), + resourceCode + ); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public BigDecimal stakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + Response.Account account = api.getAccount(ownerAddr); + long totalStakedSun = 0; + // ===== FrozenV2(当前主流质押方式)===== + for (Response.Account.FreezeV2 frozenV2 : account.getFrozenV2List()) { + if (frozenV2.getType().getNumber() == resourceCode) { + totalStakedSun += frozenV2.getAmount(); + } + } + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + public BigDecimal cancleStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + Response.Account account = api.getAccount(ownerAddr); + long totalStakedSun = 0; + // ===== FrozenV2(当前主流质押方式)===== + for (Response.Account.UnFreezeV2 frozenV2 : account.getUnfrozenV2List()) { + if (frozenV2.getType().getNumber() == resourceCode) { + totalStakedSun += frozenV2.getUnfreezeAmount(); + } + } + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP); + System.out.println(divide); + return divide; + } + + @Override + public BigDecimal voteBalance(ApiWrapper api, String ownerAddr) { + Response.Account account = api.getAccount(ownerAddr); + long totalStakedSun = 0; + // ===== FrozenV2(当前主流质押方式)===== + for (Common.Vote vote : account.getVotesList()) { + totalStakedSun += vote.getVoteCount(); + } + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + @Override + public boolean autoVoteTop(ApiWrapper api, String ownerAddress, int size) throws IllegalException { + // 1. 当前账户 + Response.Account account = api.getAccount(ownerAddress); + long totalVotes = account.getFrozenV2List().stream() + .mapToLong(Response.Account.FreezeV2::getAmount) + .sum() / 1_000_000; + if (totalVotes <= 0) { + log.error("没有投票的vote"); + return false; + } + Map currentVotes = account.getVotesList().stream() + .collect(Collectors.toMap( + v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()), + Common.Vote::getVoteCount + )); + // 2. Top27 SR + Response.WitnessList witnesses = api.listWitnesses(); + Set top27 = witnesses.getWitnessesList().stream() + .sorted(Comparator.comparingLong(w -> -w.getVoteCount())) + .limit(size + 1) + .map(w -> Base58Check.bytesToBase58(w.getAddress().toByteArray())) + .collect(Collectors.toSet()); + + // 3. 找出掉出 Top27 的 SR + boolean needRevote = currentVotes.keySet().stream() + .anyMatch(sr -> !top27.contains(sr)); + Iterator iterator = currentVotes.keySet().iterator(); + org.tron.protos.Contract.VoteWitnessContract.Builder builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder() + .setOwnerAddress(ApiWrapper.parseAddress(ownerAddress)); + boolean cancle = false; + while (iterator.hasNext()) { + String address = iterator.next(); + if (!top27.contains(address)) { + builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(address)) + .setVoteCount(1)); + cancle = true; + } + } + if (cancle) { + org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build(); + Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract, + Chain.Transaction.Contract.ContractType.VoteWitnessContract); + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + } + if (!needRevote) { + log.info("All SRs still in Top27."); + return true; + } + // 4. 总投票权 + List backupSRs = new ArrayList<>(); + // 5. 构建新投票(平均投到备用 SR) + backupSRs.addAll(top27.stream().sorted().collect(Collectors.toList()).subList(0, size)); + long perSRVotes = totalVotes / backupSRs.size(); + builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder() + .setOwnerAddress(ApiWrapper.parseAddress(ownerAddress)); + for (String sr : backupSRs) { + builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(sr)).setVoteCount(perSRVotes)); + } + org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build(); + Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract, + Chain.Transaction.Contract.ContractType.VoteWitnessContract); + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public boolean autoGetReward(ApiWrapper api, String ownerAddr) throws IllegalException { + org.tron.trident.api.GrpcAPI.NumberMessage reward = api.getRewardInfo(ownerAddr, NodeType.FULL_NODE); + log.info("Unclaimed reward: " + reward.getNum() / 1_000_000.0 + " TRX"); + Response.TransactionExtention tx = api.withdrawBalance(ownerAddr); + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public Boolean approve(ApiWrapper api, String ownerAddr, String spenderAddress, BigDecimal amount) { + try { + BigInteger amountInSun = + amount + .multiply(BigDecimal.valueOf(1_000_000)) + .toBigInteger(); + Function function = new Function( + "approve", + Arrays.asList( + new Address(spenderAddress), + new Uint256(amountInSun) + ), + Collections.emptyList() + ); + Chain.Transaction txnExtension = api.triggerCall( + ownerAddr, + ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())), + function + ).setFeeLimit(FEE_LIMIT).build(); + Chain.Transaction signedTxn = api.signTransaction(txnExtension); + Response.TransactionReturn ret = api.blockingStub.broadcastTransaction(signedTxn); + return ret.getResult(); + } catch (Exception e) { + log.error("授权异常: " + e.getMessage(), e); + return null; + } + } + + @Override + public BigDecimal getAllowance(ApiWrapper api, String ownerAddress, String spenderAddress) { + // Trc20合约地址 + Contract contract = api.getContract(contractAddress()); + Trc20Contract token = new Trc20Contract(contract, ownerAddress, api); + try { + // 查询授权额度 + BigInteger allowance = token.allowance(ownerAddress, spenderAddress); + + // 如果是USDT等6位小数代币 + double allowanceInToken = allowance.doubleValue() / 1_000_000.0; + return new BigDecimal(allowanceInToken); + } catch (Exception e) { + e.printStackTrace(); + } + return new BigDecimal(0); + } + + @Override + public Boolean usdtTransferFrom(ApiWrapper api, String sender, String fromAddress, String toAddress, BigDecimal amount) { + try { + // 转换金额为 USDT 最小单位 (6位小数) + BigInteger amountInSun = + amount + .multiply(BigDecimal.valueOf(1_000_000)) + .toBigInteger(); + // 构建 transferFrom 函数 + Function function = new Function( + "transferFrom", + Arrays.asList( + new Address(fromAddress), // 转出地址 + new Address(toAddress), // 接收地址 + new Uint256(amountInSun) // 转账金额 + ), + Collections.emptyList() + ); + + + String encodedFunction = FunctionEncoder.encode(function); + System.out.println("编码后的函数: " + encodedFunction); + + // 触发智能合约调用 + Chain.Transaction txnExtension = api.triggerCall( + ApiWrapper.toHex(ApiWrapper.parseAddress(sender)), // 调用者地址 + ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())), + function + ).setFeeLimit(FEE_LIMIT).build(); + // 签名交易 + Chain.Transaction signedTxn = api.signTransaction(txnExtension); + // 广播交易 + String ret = api.broadcastTransaction(signedTxn); + log.info(ret); + return true; + } catch (Exception e) { + log.error("transferFrom 异常: " + e.getMessage(), e); + return false; + } + } + + @Override + public TronAccountItem createTronAddress() { + ECKey eCkey = new ECKey(random); + String privateKey = ByteArray.toHexString(eCkey.getPrivKeyBytes()); + byte[] addressBytes = eCkey.getAddress(); + String hexAddress = ByteArray.toHexString(addressBytes); + TronAccountItem tronAccount = new TronAccountItem(); + tronAccount.setAddress(toViewAddress(hexAddress)); + tronAccount.setHexAddress(hexAddress); + tronAccount.setPrivateKey(privateKey); + //String privateKeyBase58 = org.spongycastle.util.encoders.Hex.e(base58Str); + String privateKeyBase58 = encode58Check(eCkey.getPrivKeyBytes()); + tronAccount.setPrivateKeyBase58(privateKeyBase58); + return tronAccount; + } + + @Override + public TronAccount createTronWallet(Integer site) { + TronAccount result = new TronAccount(); + // 1. 生成随机助记词(12个) + SecureRandom random = new SecureRandom(); + byte[] entropy = new byte[16]; // 128-bit entropy + random.nextBytes(entropy); + List mnemonicWords = MnemonicCode.INSTANCE.toMnemonic(entropy); + + // 可以使用助记词恢复公私钥和钱包地址 + /*String mnemonicStr = "elder trend clay accuse joke pizza extend holiday spread apple dress mercy"; + List mnemonicWords = Arrays.stream(mnemonicStr.split(" ")).collect(Collectors.toList());*/ + + String mnemonic = String.join(" ", mnemonicWords); + result.setPhrase(mnemonic); + // 2. 创建 DeterministicSeed 和 KeyChain + DeterministicSeed seed = DeterministicSeed.ofMnemonic(mnemonicWords, ""); + DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build(); + + // 3. 使用 TRON 路径 m/44'/195'/0'/0/i + HDPath basePath = HDPath.M().extend( + new ChildNumber(44, true), + new ChildNumber(195, true), + new ChildNumber(0, true), + ChildNumber.ZERO + ); + + List list = new ArrayList<>(); + for (int i = 0; i < site; i++) { + HDPath path = basePath.extend(new ChildNumber(i, false)); + DeterministicKey key = keyChain.getKeyByPath(path, true); + byte[] privateKey = key.getPrivKeyBytes(); + byte[] pubKeyCompressed = key.getPubKey(); // 压缩公钥(33字节) + ECPoint pubKeyPoint = key.getPubKeyPoint(); + byte[] pubKeyUnCompressed = pubKeyPoint.getEncoded(false); // 非压缩公钥(65字节) + byte[] pubKeyWithoutPrefix = Arrays.copyOfRange(pubKeyUnCompressed, 1, pubKeyUnCompressed.length); + byte[] keccakHash = keccak256(pubKeyWithoutPrefix); + byte[] addressBytes = new byte[21]; + addressBytes[0] = (byte) 0x41; + System.arraycopy(keccakHash, 12, addressBytes, 1, 20); + String base58Address = null; + try { + base58Address = base58CheckEncode(addressBytes); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + String pathStr = formatHDPath(path); + TronAccountItem item = new TronAccountItem(); + item.setAddress(base58Address); + item.setPrivateKey(Hex.toHexString(privateKey)); + item.setPubKeyCompressed(Hex.toHexString(pubKeyCompressed)); + item.setPubKeyUnCompressed(Hex.toHexString(pubKeyUnCompressed)); + item.setPath(pathStr); + list.add(item); + } + result.setItems(list); + return result; + } + + /** + * Estimate the energy required for the successful execution of smart contract transactions + * This API is closed by default in tron node. + * To open this interface, the two configuration items vm.estimateEnergy and vm.supportConstant + * must be enabled in the node configuration file at the same time. + * + * @param api + * @param owner + * @param toAddress + * @param amount + * @return + */ + @Override + public long estimateEnergy(ApiWrapper api, String owner, String toAddress, BigDecimal amount) { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + Function function = new Function( + "transfer(address,uint256)", + Arrays.asList( + new Address(toAddress), // 接收地址 + new Uint256(rechangeAmount) // 转账金额 + ), + Collections.emptyList() + ); + String callData = FunctionEncoder.encode(function); + + Response.EstimateEnergyMessage estimate = api.estimateEnergy( + owner, callData, callData, 0, 0, null + ); + return estimate.getEnergyRequired(); + } + + @Override + public long defaultEstimateEnergy() { + return 20000L; + } + + @Override + public long estimateBandwidth(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) { + try { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + // 创建交易 + Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount); + // 签名交易 + Chain.Transaction signTransaction = api.signTransaction(transaction); + // 计算交易所需要的宽带 + return api.estimateBandwidth(signTransaction); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return 0; + } + + /** + * 转换成T开头的地址 + * + * @param hexAddress + * @return + */ + private String toViewAddress(String hexAddress) { + return encode58Check(ByteArray.fromHexString(hexAddress)); + } + + /** + * Calculates the SHA-256 hash of the given bytes. + * + * @param input the bytes to hash + * @return the hash (in big-endian order) + */ + public byte[] hash(boolean isSha256, byte[] input) throws NoSuchAlgorithmException { + return hash(isSha256, input, 0, input.length); + } + + /** + * Calculates the SHA-256 hash of the given byte range. + * + * @param input the array containing the bytes to hash + * @param offset the offset within the array of the bytes to hash + * @param length the number of bytes to hash + * @return the hash (in big-endian order) + */ + public byte[] hash(boolean isSha256, byte[] input, int offset, int length) throws NoSuchAlgorithmException { + if (isSha256) { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + digest.update(input, offset, length); + return digest.digest(); + } else { + SM3Digest digest = new SM3Digest(); + digest.update(input, offset, length); + byte[] eHash = new byte[digest.getDigestSize()]; + digest.doFinal(eHash, 0); + return eHash; + } + } + + private String encode58Check(byte[] input) { + try { + byte[] hash0 = hash(true, input); + byte[] hash1 = hash(true, hash0); + byte[] inputCheck = new byte[input.length + 4]; + System.arraycopy(input, 0, inputCheck, 0, input.length); + System.arraycopy(hash1, 0, inputCheck, input.length, 4); + return Base58.encode(inputCheck); + } catch (Throwable t) { + log.error(String.format("data error:%s", Hex.toHexString(input)), t); + } + return null; + } + + public static void main(String[] args) { + ITronService tronService = new TronProServiceImpl(); + tronService.energyAndBandwidth("TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW"); + ApiWrapper api = tronService.buildApiWrapper("34d200bcf5693a7ffc000edbb85fe0a7f84e7c87d894ef8638f516c07994a989"); + BigDecimal balance = tronService.getUsdtBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW"); + System.out.println(balance); + balance = tronService.getTRxBalance(api, "TDYsiHd9Jac9Hs2wFBySrbAgx548ahXuQW"); + System.out.println(balance); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronShastaServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronShastaServiceImpl.java new file mode 100644 index 0000000..b5995d7 --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/TronShastaServiceImpl.java @@ -0,0 +1,838 @@ +package com.ruoyi.system.service.impl; + +import com.google.protobuf.ByteString; +import com.ruoyi.common.utils.http.HttpHelper; +import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; +import com.ruoyi.system.domain.vo.TronAccount; +import com.ruoyi.system.domain.vo.TronAccountItem; +import com.ruoyi.system.domain.vo.TronAccountResp; +import com.ruoyi.system.service.ITronService; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import lombok.extern.slf4j.Slf4j; +import org.bitcoinj.crypto.ChildNumber; +import org.bitcoinj.crypto.DeterministicKey; +import org.bitcoinj.crypto.HDPath; +import org.bitcoinj.crypto.MnemonicCode; +import org.bitcoinj.wallet.DeterministicKeyChain; +import org.bitcoinj.wallet.DeterministicSeed; +import org.bouncycastle.crypto.digests.SM3Digest; +import org.bouncycastle.jcajce.provider.digest.Keccak; +import org.bouncycastle.math.ec.ECPoint; +import org.bouncycastle.util.encoders.Hex; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.crypto.ECKey; +import org.tron.common.utils.Base58; +import org.tron.common.utils.ByteArray; +import org.tron.protos.Protocol; +import org.tron.trident.abi.FunctionEncoder; +import org.tron.trident.abi.datatypes.Address; +import org.tron.trident.abi.datatypes.Function; +import org.tron.trident.abi.datatypes.generated.Uint256; +import org.tron.trident.core.ApiWrapper; +import org.tron.trident.core.NodeType; +import org.tron.trident.core.contract.Contract; +import org.tron.trident.core.contract.Trc20Contract; +import org.tron.trident.core.exceptions.IllegalException; +import org.tron.trident.proto.Chain; +import org.tron.trident.proto.Common; +import org.tron.trident.proto.Response; +import org.tron.trident.utils.Base58Check; +import org.tron.trident.utils.Convert; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.*; +import java.util.stream.Collectors; + +@Slf4j +@ConditionalOnProperty(prefix = "tron.env", name = "type", havingValue = "shasta") +@Service +public class TronShastaServiceImpl implements ITronService { + // 能量和带宽限制 + public static final long FEE_LIMIT = 10_000_000L; // 10 TRX + private static SecureRandom random = new SecureRandom(); + private static final BigInteger BASE = BigInteger.valueOf(58); + private static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray(); + private RestTemplate restTemplate = new RestTemplate(); + @Override + public Integer grpcPort() { + return 50051; + } + + @Override + public String grpcUrl() { + return "grpc.shasta.trongrid.io"; + } + + @Override + public String type() { + return "shasta"; + } + @Override + public BigDecimal votedBalance(ApiWrapper api, String ownerAddr) { + Response.Account account = api.getAccount(ownerAddr); + Map currentVotes = account.getVotesList().stream() + .collect(Collectors.toMap( + v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()), + Common.Vote::getVoteCount + )); + Iterator> iterator = currentVotes.entrySet().iterator(); + BigDecimal bigDecimal = new BigDecimal(0); + while (iterator.hasNext()) { + bigDecimal = bigDecimal.add(new BigDecimal(iterator.next().getValue())); + } + return bigDecimal; + } + @Override + public BigDecimal delegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + try { + Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr); + List list = resourceAccountIndex.getToAccountsList(); + BigDecimal result = new BigDecimal(0); + for (ByteString byteString : list) { + String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray()); + String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress)); + Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(ownerAddr,address); + int count = delegatedResourceList.getDelegatedResourceCount(); + for (int i = 0; i < count; i++) { + Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i); + String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray()); + String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress)); + String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray()); + String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress)); + if (resourceCode == 0) { + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } else if (resourceCode == 1) { + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } + } + } + return result; + } catch (Exception e) { + log.error(e.getMessage(), e); + throw new RuntimeException(e); + } + } + @Override + public BigDecimal acquiredDelegatedStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + try { + Response.DelegatedResourceAccountIndex resourceAccountIndex = api.getDelegatedResourceAccountIndexV2(ownerAddr); + List list = resourceAccountIndex.getFromAccountsList(); + BigDecimal result = new BigDecimal(0); + for (ByteString byteString : list) { + String hexAddress = org.spongycastle.util.encoders.Hex.toHexString(byteString.toByteArray()); + String address = encode58Check(org.tron.common.utils.ByteArray.fromHexString(hexAddress)); + Response.DelegatedResourceList delegatedResourceList = api.getDelegatedResourceV2(address, ownerAddr); + int count = delegatedResourceList.getDelegatedResourceCount(); + for (int i = 0; i < count; i++) { + Response.DelegatedResource delegatedResource = delegatedResourceList.getDelegatedResource(i); + String fromHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getFrom().toByteArray()); + String fromAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(fromHexAddress)); + String toHexAddress = org.spongycastle.util.encoders.Hex.toHexString(delegatedResource.getTo().toByteArray()); + String toAddress = encode58Check(org.tron.common.utils.ByteArray.fromHexString(toHexAddress)); + if(resourceCode == 0){ + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForBandwidth()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + }else if(resourceCode == 1){ + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(delegatedResource.getFrozenBalanceForEnergy()).divide(divisor, 4, RoundingMode.HALF_UP); + result = result.add(divide); + } + } + } + return result; + }catch (Exception e){ + log.error(e.getMessage(),e); + throw new RuntimeException(e); + } + } + @Override + public ApiWrapper buildApiWrapper(String privateKey) { + ApiWrapper apiWrapper = ApiWrapper.ofShasta(privateKey); + return apiWrapper; + } + + @Override + public String contractAddress() { + return "TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs"; + } + + @Override + public String tronscanApiUrl() { + return "https://shastapi.tronscan.org"; + } + + @Override + public String tronscanApiKey() { + return ""; + } + + @Override + public String usdtTrans(ApiWrapper api, String fromAddress, String toAddress, String amount) { + try { + // 获取合约地址信息 + Contract contract = api.getContract(contractAddress()); + Trc20Contract token = new Trc20Contract(contract, fromAddress, api); + String transfer; + // 获取转账账户的TRX余额 + BigInteger trc20Value = token.balanceOf(fromAddress); + // 获取想要转账的数额 + BigInteger sunAmountValue = Convert.toSun(amount, Convert.Unit.TRX).toBigInteger(); + // 进行比较 + if (trc20Value.compareTo(sunAmountValue) >= 0) { + // 设置最大矿工费用 + long feeLimit = Convert.toSun("2", Convert.Unit.TRX).longValue(); + //转账 + transfer = token.transfer(toAddress, sunAmountValue.longValue(), 0, "", feeLimit); + } else { + return "error_error"; + } + if (transfer == null || transfer.equals("")) { + return "error_error"; + } + return transfer; + } catch (Exception ex) { + String message = ex.getMessage(); + return "error_" + message; + } + } + + @Override + public String trxTrans(ApiWrapper api,String fromAddress, String toAddress, BigDecimal amount) { + try { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + // 创建交易 + Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount); + // 签名交易 + Chain.Transaction signTransaction = api.signTransaction(transaction); + // 计算交易所需要的宽带 + long byteSize = api.estimateBandwidth(signTransaction); +// long byteSize = api.estimateEnergy(signTransaction); + // 广播交易 + String hashTx = api.broadcastTransaction(signTransaction); + return hashTx; + } catch (Exception e) { + e.printStackTrace(); + } + return ""; + } + + @Override + public BigDecimal getTRxBalance(ApiWrapper api, String address) { + Long balance = api.getAccountBalance(address); + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(balance).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + @Override + public BigDecimal getUsdtBalance(ApiWrapper api, String address) { + Contract contract = api.getContract(contractAddress()); + Trc20Contract token = new Trc20Contract(contract, address, api); + BigInteger balanceOf = token.balanceOf(address); + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(balanceOf).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + @Override + public EnergyAndBandwidthVo energyAndBandwidth(String ownerAddr) { + ManagedChannel channel = ManagedChannelBuilder +// .forAddress("grpc.trongrid.io", 50051) + .forAddress(this.grpcUrl(), this.grpcPort()) + .usePlaintext() + .build(); + WalletGrpc.WalletBlockingStub stub = + WalletGrpc.newBlockingStub(channel); + byte[] address = Base58Check.base58ToBytes(ownerAddr); + Protocol.Account account = Protocol.Account.newBuilder() + .setAddress(ByteString.copyFrom(address)) + .build(); + GrpcAPI.AccountResourceMessage res = stub.getAccountResource(account); + long bandwidth = + (res.getFreeNetLimit() - res.getFreeNetUsed()) + + (res.getNetLimit() - res.getNetUsed()); + long energy = + res.getEnergyLimit() - res.getEnergyUsed(); + EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo(); + energyAndBandwidthVo.setBandwidth(new BigDecimal(bandwidth)); + energyAndBandwidthVo.setEnergy(new BigDecimal(energy)); + return energyAndBandwidthVo; + } + @Override + public String delegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + Response.TransactionExtention transactionExtention = null; + try { + transactionExtention = api.delegateResourceV2(fromAddress,rechangeAmount,resourceCode,toAddress,true,86400); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signTransaction = api.signTransaction(transactionExtention); + String hashTx = api.broadcastTransaction(signTransaction); + return hashTx; + } + @Override + public String unDelegateResourceV2(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + Response.TransactionExtention transactionExtention = null; + try { + transactionExtention = api.undelegateResource(fromAddress,rechangeAmount,resourceCode,toAddress); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signTransaction = api.signTransaction(transactionExtention); + String hashTx = api.broadcastTransaction(signTransaction); + return hashTx; + } + @Override + public EnergyAndBandwidthVo allDelegatedDnergyAndBandwidth(String ownerAddr) { + HttpHeaders headers = new HttpHeaders(); + headers.set("TRON-PRO-API-KEY", "your_api_key"); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + + HttpEntity entity = new HttpEntity<>(headers); + ResponseEntity result = restTemplate.exchange(tronscanApiUrl()+"/api/accountv2?address="+ownerAddr, HttpMethod.GET,entity, TronAccountResp.class); + EnergyAndBandwidthVo energyAndBandwidthVo = new EnergyAndBandwidthVo(); + if(null != result.getBody()){ + energyAndBandwidthVo.setAcquiredEnergy(result.getBody().getAcquiredDelegatedFrozenV2BalanceForEnergyValue()); + energyAndBandwidthVo.setAcquiredBandwidth(result.getBody().getAcquiredDelegatedFrozenV2BalanceForBandwidthValue()); + energyAndBandwidthVo.setDelegateEnergy(result.getBody().getDelegatedFrozenV2BalanceForEnergyValue()); + energyAndBandwidthVo.setDelegateBandwidth(result.getBody().getDelegatedFrozenV2BalanceForBandwidthValue()); + energyAndBandwidthVo.setStakedTrxNum(result.getBody().getTotalFrozenV2()); + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(energyAndBandwidthVo.getStakedTrxNum()).divide(divisor, 4, RoundingMode.HALF_UP); + energyAndBandwidthVo.setStakedTrxNum(divide.longValue()); + }else{ + energyAndBandwidthVo.setDelegateBandwidth(new BigDecimal(0)); + energyAndBandwidthVo.setDelegateEnergy(new BigDecimal(0)); + energyAndBandwidthVo.setAcquiredBandwidth(new BigDecimal(0)); + energyAndBandwidthVo.setAcquiredEnergy(new BigDecimal(0)); + energyAndBandwidthVo.setStakedTrxNum(0L); + } + return energyAndBandwidthVo; + } + @Override + public long defaultEstimateBandwidth() { + return 365; + } + @Override + public boolean unstakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Response.TransactionExtention tx = null; + try { + tx = api.unfreezeBalanceV2(ownerAddr, + balance.multiply(divisor).longValue(), + resourceCode + ); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public boolean cancleUnstakeTrxBalance(ApiWrapper api, String ownerAddr) { + Response.TransactionExtention tx = null; + try { + tx = api.cancelAllUnfreezeV2(ownerAddr); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public boolean stakeTrxBalance(ApiWrapper api, String ownerAddr, BigDecimal balance, int resourceCode) { + BigDecimal divisor = new BigDecimal("1000000"); + Response.TransactionExtention tx = null; + try { + tx = api.freezeBalanceV2(ownerAddr, + balance.multiply(divisor).longValue(), + resourceCode + ); + } catch (IllegalException e) { + throw new RuntimeException(e); + } + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public BigDecimal stakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + Response.Account account = api.getAccount(ownerAddr); + long totalStakedSun = 0; + // ===== FrozenV2(当前主流质押方式)===== + for (Response.Account.FreezeV2 frozenV2 : account.getFrozenV2List()) { + if (frozenV2.getType().getNumber() == resourceCode) { + totalStakedSun += frozenV2.getAmount(); + } + } + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + public BigDecimal cancleStakedTrxBalance(ApiWrapper api, String ownerAddr, int resourceCode) { + Response.Account account = api.getAccount(ownerAddr); + long totalStakedSun = 0; + // ===== FrozenV2(当前主流质押方式)===== + for (Response.Account.UnFreezeV2 frozenV2 : account.getUnfrozenV2List()) { + if (frozenV2.getType().getNumber() == resourceCode) { + totalStakedSun += frozenV2.getUnfreezeAmount(); + } + } + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP); + System.out.println(divide); + return divide; + } + + @Override + public BigDecimal voteBalance(ApiWrapper api, String ownerAddr) { + Response.Account account = api.getAccount(ownerAddr); + long totalStakedSun = 0; + // ===== FrozenV2(当前主流质押方式)===== + for (Common.Vote vote : account.getVotesList()) { + totalStakedSun += vote.getVoteCount(); + } + BigDecimal divisor = new BigDecimal("1000000"); + BigDecimal divide = new BigDecimal(totalStakedSun).divide(divisor, 4, RoundingMode.HALF_UP); + return divide; + } + + @Override + public boolean autoVoteTop(ApiWrapper api, String ownerAddress, int size) throws IllegalException { + // 1. 当前账户 + Response.Account account = api.getAccount(ownerAddress); + long totalVotes = account.getFrozenV2List().stream() + .mapToLong(Response.Account.FreezeV2::getAmount) + .sum() / 1_000_000; + if (totalVotes <= 0) { + log.error("没有投票的vote"); + return false; + } + Map currentVotes = account.getVotesList().stream() + .collect(Collectors.toMap( + v -> Base58Check.bytesToBase58(v.getVoteAddress().toByteArray()), + Common.Vote::getVoteCount + )); + // 2. Top27 SR + Response.WitnessList witnesses = api.listWitnesses(); + Set top27 = witnesses.getWitnessesList().stream() + .sorted(Comparator.comparingLong(w -> -w.getVoteCount())) + .limit(size + 1) + .map(w -> Base58Check.bytesToBase58(w.getAddress().toByteArray())) + .collect(Collectors.toSet()); + + // 3. 找出掉出 Top27 的 SR + boolean needRevote = currentVotes.keySet().stream() + .anyMatch(sr -> !top27.contains(sr)); + Iterator iterator = currentVotes.keySet().iterator(); + org.tron.protos.Contract.VoteWitnessContract.Builder builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder() + .setOwnerAddress(ApiWrapper.parseAddress(ownerAddress)); + boolean cancle = false; + while (iterator.hasNext()) { + String address = iterator.next(); + if (!top27.contains(address)) { + builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(address)) + .setVoteCount(1)); + cancle = true; + } + } + if (cancle) { + org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build(); + Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract, + Chain.Transaction.Contract.ContractType.VoteWitnessContract); + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + } + if (!needRevote) { + log.info("All SRs still in Top27."); + return true; + } + // 4. 总投票权 + List backupSRs = new ArrayList<>(); + // 5. 构建新投票(平均投到备用 SR) + backupSRs.addAll(top27.stream().sorted().collect(Collectors.toList()).subList(0, size)); + long perSRVotes = totalVotes / backupSRs.size(); + builder = org.tron.protos.Contract.VoteWitnessContract.newBuilder() + .setOwnerAddress(ApiWrapper.parseAddress(ownerAddress)); + for (String sr : backupSRs) { + builder.addVotes(org.tron.protos.Contract.VoteWitnessContract.Vote.newBuilder().setVoteAddress(ApiWrapper.parseAddress(sr)).setVoteCount(perSRVotes)); + } + org.tron.protos.Contract.VoteWitnessContract voteWitnessContract = builder.build(); + Response.TransactionExtention tx = api.createTransactionExtention(voteWitnessContract, + Chain.Transaction.Contract.ContractType.VoteWitnessContract); + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public boolean autoGetReward(ApiWrapper api, String ownerAddr) throws IllegalException { + org.tron.trident.api.GrpcAPI.NumberMessage reward = api.getRewardInfo(ownerAddr, NodeType.FULL_NODE); + log.info("Unclaimed reward: " + reward.getNum() / 1_000_000.0 + " TRX"); + Response.TransactionExtention tx = api.withdrawBalance(ownerAddr); + Chain.Transaction signedTx = api.signTransaction(tx); + api.broadcastTransaction(signedTx); + return true; + } + + @Override + public Boolean approve(ApiWrapper api, String ownerAddr, String spenderAddress, BigDecimal amount) { + try { + BigInteger amountInSun = + amount + .multiply(BigDecimal.valueOf(1_000_000)) + .toBigInteger(); + Function function = new Function( + "approve", + Arrays.asList( + new Address(spenderAddress), + new Uint256(amountInSun) + ), + Collections.emptyList() + ); + Chain.Transaction txnExtension = api.triggerCall( + ownerAddr, + ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())), + function + ).setFeeLimit(FEE_LIMIT).build(); + Chain.Transaction signedTxn = api.signTransaction(txnExtension); + Response.TransactionReturn ret = api.blockingStub.broadcastTransaction(signedTxn); + return ret.getResult(); + } catch (Exception e) { + log.error("授权异常: " + e.getMessage(), e); + return null; + } + } + + @Override + public BigDecimal getAllowance(ApiWrapper api, String ownerAddress, String spenderAddress) { + // Trc20合约地址 + Contract contract = api.getContract(contractAddress()); + Trc20Contract token = new Trc20Contract(contract, ownerAddress, api); + try { + // 查询授权额度 + BigInteger allowance = token.allowance(ownerAddress, spenderAddress); + + // 如果是USDT等6位小数代币 + double allowanceInToken = allowance.doubleValue() / 1_000_000.0; + return new BigDecimal(allowanceInToken); + } catch (Exception e) { + e.printStackTrace(); + } + return new BigDecimal(0); + } + + @Override + public Boolean usdtTransferFrom(ApiWrapper api, String sender, String fromAddress, String toAddress, BigDecimal amount) { + try { + // 转换金额为 USDT 最小单位 (6位小数) + BigInteger amountInSun = + amount + .multiply(BigDecimal.valueOf(1_000_000)) + .toBigInteger(); + // 构建 transferFrom 函数 + Function function = new Function( + "transferFrom", + Arrays.asList( + new Address(fromAddress), // 转出地址 + new Address(toAddress), // 接收地址 + new Uint256(amountInSun) // 转账金额 + ), + Collections.emptyList() + ); + + + String encodedFunction = FunctionEncoder.encode(function); + System.out.println("编码后的函数: " + encodedFunction); + + // 触发智能合约调用 + Chain.Transaction txnExtension = api.triggerCall( + ApiWrapper.toHex(ApiWrapper.parseAddress(sender)), // 调用者地址 + ApiWrapper.toHex(ApiWrapper.parseAddress(contractAddress())), + function + ).setFeeLimit(FEE_LIMIT).build(); + // 签名交易 + Chain.Transaction signedTxn = api.signTransaction(txnExtension); + // 广播交易 + String ret = api.broadcastTransaction(signedTxn); + log.info(ret); + return true; + } catch (Exception e) { + log.error("transferFrom 异常: " + e.getMessage(), e); + return false; + } + } + + @Override + public TronAccountItem createTronAddress() { + ECKey eCkey = new ECKey(random); + String privateKey = ByteArray.toHexString(eCkey.getPrivKeyBytes()); + byte[] addressBytes = eCkey.getAddress(); + String hexAddress = ByteArray.toHexString(addressBytes); + TronAccountItem tronAccount = new TronAccountItem(); + tronAccount.setAddress(toViewAddress(hexAddress)); + tronAccount.setHexAddress(hexAddress); + tronAccount.setPrivateKey(privateKey); + //String privateKeyBase58 = org.spongycastle.util.encoders.Hex.e(base58Str); + String privateKeyBase58 = encode58Check(eCkey.getPrivKeyBytes()); + tronAccount.setPrivateKeyBase58(privateKeyBase58); + return tronAccount; + } + private static byte[] keccak256(byte[] input) { + Keccak.Digest256 digest = new Keccak.Digest256(); + return digest.digest(input); + } + + private String formatHDPath(HDPath path) { + StringBuilder sb = new StringBuilder("m"); + for (ChildNumber cn : path) { + sb.append("/"); + sb.append(cn.isHardened() ? cn.num() + "'" : cn.num()); + } + return sb.toString(); + } + + private String base58CheckEncode(byte[] input) throws NoSuchAlgorithmException { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] hash1 = digest.digest(input); + byte[] hash2 = digest.digest(hash1); + + byte[] checksum = Arrays.copyOfRange(hash2, 0, 4); + + byte[] result = new byte[input.length + 4]; + System.arraycopy(input, 0, result, 0, input.length); + System.arraycopy(checksum, 0, result, input.length, 4); + + return encode(result); + } + + public String encode(byte[] input) { + BigInteger bi = new BigInteger(1, input); + StringBuilder sb = new StringBuilder(); + while (bi.compareTo(BigInteger.ZERO) > 0) { + BigInteger[] div = bi.divideAndRemainder(BASE); + sb.append(ALPHABET[div[1].intValue()]); + bi = div[0]; + } + for (byte b : input) { + if (b == 0) { + sb.append(ALPHABET[0]); + } else { + break; + } + } + return sb.reverse().toString(); + } + @Override + public TronAccount createTronWallet(Integer site) { + TronAccount result = new TronAccount(); + // 1. 生成随机助记词(12个) + SecureRandom random = new SecureRandom(); + byte[] entropy = new byte[16]; // 128-bit entropy + random.nextBytes(entropy); + List mnemonicWords = MnemonicCode.INSTANCE.toMnemonic(entropy); + + // 可以使用助记词恢复公私钥和钱包地址 + /*String mnemonicStr = "elder trend clay accuse joke pizza extend holiday spread apple dress mercy"; + List mnemonicWords = Arrays.stream(mnemonicStr.split(" ")).collect(Collectors.toList());*/ + + String mnemonic = String.join(" ", mnemonicWords); + result.setPhrase(mnemonic); + // 2. 创建 DeterministicSeed 和 KeyChain + DeterministicSeed seed = DeterministicSeed.ofMnemonic(mnemonicWords, ""); + DeterministicKeyChain keyChain = DeterministicKeyChain.builder().seed(seed).build(); + + // 3. 使用 TRON 路径 m/44'/195'/0'/0/i + HDPath basePath = HDPath.M().extend( + new ChildNumber(44, true), + new ChildNumber(195, true), + new ChildNumber(0, true), + ChildNumber.ZERO + ); + + List list = new ArrayList<>(); + for (int i = 0; i < site; i++) { + HDPath path = basePath.extend(new ChildNumber(i, false)); + DeterministicKey key = keyChain.getKeyByPath(path, true); + byte[] privateKey = key.getPrivKeyBytes(); + byte[] pubKeyCompressed = key.getPubKey(); // 压缩公钥(33字节) + ECPoint pubKeyPoint = key.getPubKeyPoint(); + byte[] pubKeyUnCompressed = pubKeyPoint.getEncoded(false); // 非压缩公钥(65字节) + byte[] pubKeyWithoutPrefix = Arrays.copyOfRange(pubKeyUnCompressed, 1, pubKeyUnCompressed.length); + byte[] keccakHash = keccak256(pubKeyWithoutPrefix); + byte[] addressBytes = new byte[21]; + addressBytes[0] = (byte) 0x41; + System.arraycopy(keccakHash, 12, addressBytes, 1, 20); + String base58Address = null; + try { + base58Address = base58CheckEncode(addressBytes); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + String pathStr = formatHDPath(path); + TronAccountItem item = new TronAccountItem(); + item.setAddress(base58Address); + item.setPrivateKey(Hex.toHexString(privateKey)); + item.setPubKeyCompressed(Hex.toHexString(pubKeyCompressed)); + item.setPubKeyUnCompressed(Hex.toHexString(pubKeyUnCompressed)); + item.setPath(pathStr); + String hexAddress = ByteArray.toHexString(addressBytes); + item.setHexAddress(hexAddress); + String privateKeyBase58 = encode58Check(privateKey); + item.setPrivateKeyBase58(privateKeyBase58); + + list.add(item); + } + result.setItems(list); + return result; + } + + /** + * Estimate the energy required for the successful execution of smart contract transactions + * This API is closed by default in tron node. + * To open this interface, the two configuration items vm.estimateEnergy and vm.supportConstant + * must be enabled in the node configuration file at the same time. + * @param api + * @param owner + * @param toAddress + * @param amount + * @return + */ + @Override + public long estimateEnergy(ApiWrapper api, String owner, String toAddress, BigDecimal amount) { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + Function function = new Function( + "transfer(address,uint256)", + Arrays.asList( + new Address(toAddress), // 接收地址 + new Uint256(rechangeAmount) // 转账金额 + ), + Collections.emptyList() + ); + String callData = FunctionEncoder.encode(function); + + Response.EstimateEnergyMessage estimate = api.estimateEnergy( + owner, callData, callData, 0, 0, null + ); + return estimate.getEnergyRequired(); + } + + @Override + public long defaultEstimateEnergy() { + return 20000L; + } + + @Override + public long estimateBandwidth(ApiWrapper api, String fromAddress, String toAddress, BigDecimal amount) { + try { + BigDecimal divisor = new BigDecimal("1000000"); + Long rechangeAmount = new BigDecimal(String.valueOf(amount)).multiply(divisor).longValue(); + // 创建交易 + Response.TransactionExtention transaction = api.transfer(fromAddress, toAddress, rechangeAmount); + // 签名交易 + Chain.Transaction signTransaction = api.signTransaction(transaction); + // 计算交易所需要的宽带 + return api.estimateBandwidth(signTransaction); + } catch (Exception e) { + log.error(e.getMessage(),e); + } + return 0; + } + + /** + * 转换成T开头的地址 + * + * @param hexAddress + * @return + */ + private String toViewAddress(String hexAddress) { + return encode58Check(ByteArray.fromHexString(hexAddress)); + } + + /** + * Calculates the SHA-256 hash of the given bytes. + * + * @param input the bytes to hash + * @return the hash (in big-endian order) + */ + public byte[] hash(boolean isSha256, byte[] input) throws NoSuchAlgorithmException { + return hash(isSha256, input, 0, input.length); + } + + /** + * Calculates the SHA-256 hash of the given byte range. + * + * @param input the array containing the bytes to hash + * @param offset the offset within the array of the bytes to hash + * @param length the number of bytes to hash + * @return the hash (in big-endian order) + */ + public byte[] hash(boolean isSha256, byte[] input, int offset, int length) throws NoSuchAlgorithmException { + if (isSha256) { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + digest.update(input, offset, length); + return digest.digest(); + } else { + SM3Digest digest = new SM3Digest(); + digest.update(input, offset, length); + byte[] eHash = new byte[digest.getDigestSize()]; + digest.doFinal(eHash, 0); + return eHash; + } + } + + private String encode58Check(byte[] input) { + try { + byte[] hash0 = hash(true, input); + byte[] hash1 = hash(true, hash0); + byte[] inputCheck = new byte[input.length + 4]; + System.arraycopy(input, 0, inputCheck, 0, input.length); + System.arraycopy(hash1, 0, inputCheck, input.length, 4); + return Base58.encode(inputCheck); + } catch (Throwable t) { + log.error(String.format("data error:%s", Hex.toHexString(input)), t); + } + return null; + } + + public static void main(String[] args) { + ITronService tronService = new TronShastaServiceImpl(); + tronService.energyAndBandwidth("TULphDUxnr4VBrKJr4C6YVetses1PSx8B4"); + ApiWrapper api = tronService.buildApiWrapper("7a1b41106df333ec8eb53fed529a957b57478a919d39b3d961a02753a95de506"); + BigDecimal balance = tronService.getUsdtBalance(api, "TULphDUxnr4VBrKJr4C6YVetses1PSx8B4"); + System.out.println(balance); + balance = tronService.getTRxBalance(api, "TULphDUxnr4VBrKJr4C6YVetses1PSx8B4"); + System.out.println(balance); + tronService.trxTrans(api,"TULphDUxnr4VBrKJr4C6YVetses1PSx8B4","TXTJKCikqtLZHK7moDdmxdaTNWbjdCM1H9",new BigDecimal(200)); +// TronAccount tronAccount = tronService.createTronWallet(2); +// System.out.println(JSONObject.toJSONString(tronAccount)); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/UsdtAggregationTaskItemServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/UsdtAggregationTaskItemServiceImpl.java new file mode 100644 index 0000000..eaaa33e --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/UsdtAggregationTaskItemServiceImpl.java @@ -0,0 +1,278 @@ +package com.ruoyi.system.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.ruoyi.common.select.SelectItem; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.common.utils.SecurityUtils; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.UsdtAggregationTaskItem; +import com.ruoyi.system.domain.UsdtAggregationTaskItemPlus; +import com.ruoyi.system.mapper.UsdtAggregationTaskItemMapper; +import com.ruoyi.system.service.IUsdtAggregationTaskItemService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import java.util.*; +/** + * 归集任务明细Service业务层处理 + * + * @author luqj + * @date 2026-01-01 + */ +@Service +public class UsdtAggregationTaskItemServiceImpl extends ServiceImpl implements IUsdtAggregationTaskItemService +{ + @Autowired + private UsdtAggregationTaskItemMapper usdtAggregationTaskItemMapper; + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public List getByIds(List ids ,boolean isUser, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).in(UsdtAggregationTaskItemPlus::getId, ids); + if(isUser){ + lambdaQueryWrapper.eq(UsdtAggregationTaskItemPlus::getUserId, SecurityUtils.getUserId()); + } + List list = this.list(lambdaQueryWrapper); + if(isUser){ + checkUserPlus(list); + } + return list; + } + private void checkUserPlus(List list) { + for (UsdtAggregationTaskItemPlus item : list){ + if(null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()){ + throw new RuntimeException("无权限"); + } + } + } + private void checkUser(List list) { + for (UsdtAggregationTaskItem item : list){ + if(null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()){ + throw new RuntimeException("无权限"); + } + } + } + private void checkUser(UsdtAggregationTaskItemPlus item) { + if(null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()){ + throw new RuntimeException("无权限"); + } + } + private void checkUser(UsdtAggregationTaskItem item) { + if(null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()){ + throw new RuntimeException("无权限"); + } + } + @Override + public List select(String keyword,boolean isUser) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(UsdtAggregationTaskItemPlus::getId,UsdtAggregationTaskItemPlus::getUserId, UsdtAggregationTaskItemPlus::getRemark) + .like(UsdtAggregationTaskItemPlus::getRemark, keyword); + if(isUser){ + lambdaQueryWrapper.eq(UsdtAggregationTaskItemPlus::getUserId, SecurityUtils.getUserId()); + } + List list = this.list(lambdaQueryWrapper); + if(isUser){ + checkUserPlus(list); + } + List result =new ArrayList<>(); + for (UsdtAggregationTaskItemPlus item : list){ + SelectItem selectItem = new SelectItem(); + selectItem.setName(item.getRemark()); + selectItem.setId(item.getId()); + result.add(selectItem); + } + return result; + } + @Override + public UsdtAggregationTaskItemPlus getById(Long id, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).eq(UsdtAggregationTaskItemPlus::getId, id); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids, SFunction... columns) { + List list = this.getByIds(ids,false, columns); + Map map = new HashMap<>(); + for (UsdtAggregationTaskItemPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getListByStatusAndParentId(Integer status, Long parentId) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .eq(UsdtAggregationTaskItemPlus::getStatus, status) + .eq(UsdtAggregationTaskItemPlus::getParentId, parentId); + return list(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids) { + List list = this.getByIds(ids); + Map map = new HashMap<>(); + for (UsdtAggregationTaskItemPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getByIds(List ids) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper().in(UsdtAggregationTaskItemPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + public T sum(String field, String where, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" sum(" + field + ") as total "); + stringBuffer.append(" from usdt_aggregation_task_item "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass); + return result; + } + + public Long count(String where) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" count(1)"); + stringBuffer.append(" from "); + stringBuffer.append(" usdt_aggregation_task_item "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class); + return result; + } + + public List countByGroupBy(String select, String where, String groupby, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(select); + stringBuffer.append(" from "); + stringBuffer.append(" usdt_aggregation_task_item "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + stringBuffer.append(" group by "); + stringBuffer.append(groupby); + List result = jdbcTemplate.queryForList(stringBuffer.toString()); + List tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass); + return tList; + } + /** + * 查询归集任务明细 + * + * @param id 归集任务明细ID + * @return 归集任务明细 + */ + @Override + public UsdtAggregationTaskItem selectUsdtAggregationTaskItemById(Long id,boolean isUser) + { + UsdtAggregationTaskItem vo = usdtAggregationTaskItemMapper.selectUsdtAggregationTaskItemById(id); + if(isUser){ + checkUser(vo); + } + return vo; + } + + /** + * 查询归集任务明细列表 + * + * @param usdtAggregationTaskItem 归集任务明细 + * @return 归集任务明细 + */ + @Override + public List selectUsdtAggregationTaskItemList(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser) + { + if(usdtAggregationTaskItem == null){ + usdtAggregationTaskItem = new UsdtAggregationTaskItem(); + } + if(isUser){ + usdtAggregationTaskItem.setUserId(SecurityUtils.getUserId()); + } + List list = usdtAggregationTaskItemMapper.selectUsdtAggregationTaskItemList(usdtAggregationTaskItem); + if(isUser){ + checkUser(list); + } + return list; + } + + /** + * 新增归集任务明细 + * + * @param usdtAggregationTaskItem 归集任务明细 + * @return 结果 + */ + @Override + public int insertUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser) + { + usdtAggregationTaskItem.setCreatedAt(DateUtils.getNowDate()); + usdtAggregationTaskItem.setUpdatedAt(DateUtils.getNowDate()); + if(isUser){ + usdtAggregationTaskItem.setUserId(SecurityUtils.getUserId()); + } + return usdtAggregationTaskItemMapper.insertUsdtAggregationTaskItem(usdtAggregationTaskItem); + } + + /** + * 修改归集任务明细 + * + * @param usdtAggregationTaskItem 归集任务明细 + * @return 结果 + */ + @Override + public int updateUsdtAggregationTaskItem(UsdtAggregationTaskItem usdtAggregationTaskItem,boolean isUser) + { + usdtAggregationTaskItem.setUpdatedAt(DateUtils.getNowDate()); + if(isUser){ + checkUser(usdtAggregationTaskItem); + } + return usdtAggregationTaskItemMapper.updateUsdtAggregationTaskItem(usdtAggregationTaskItem); + } + + /** + * 批量删除归集任务明细 + * + * @param ids 需要删除的归集任务明细ID + * @return 结果 + */ + @Override + public int deleteUsdtAggregationTaskItemByIds(Long[] ids,boolean isUser) + { + if(isUser){ + List list= getByIds(Arrays.asList(ids),false,UsdtAggregationTaskItemPlus::getUserId,UsdtAggregationTaskItemPlus::getId); + checkUserPlus(list); + } + return usdtAggregationTaskItemMapper.deleteUsdtAggregationTaskItemByIds(ids); + } + + /** + * 删除归集任务明细信息 + * + * @param id 归集任务明细ID + * @return 结果 + */ + @Override + public int deleteUsdtAggregationTaskItemById(Long id,boolean isUser) + { + if(isUser){ + UsdtAggregationTaskItemPlus vo = getById(id,UsdtAggregationTaskItemPlus::getUserId,UsdtAggregationTaskItemPlus::getId); + checkUser(vo); + } + return usdtAggregationTaskItemMapper.deleteUsdtAggregationTaskItemById(id); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/UsdtAggregationTaskServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/UsdtAggregationTaskServiceImpl.java new file mode 100644 index 0000000..d9afc5a --- /dev/null +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/UsdtAggregationTaskServiceImpl.java @@ -0,0 +1,412 @@ +package com.ruoyi.system.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.support.SFunction; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.ruoyi.common.select.SelectItem; +import com.ruoyi.common.utils.DateUtils; +import com.ruoyi.common.utils.SecurityUtils; +import com.ruoyi.common.utils.StringUtils; +import com.ruoyi.system.domain.*; +import com.ruoyi.system.mapper.UsdtAggregationTaskMapper; +import com.ruoyi.system.service.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.tron.trident.core.ApiWrapper; + +import java.math.BigDecimal; +import java.util.*; + +/** + * 归集任务Service业务层处理 + * + * @author luqj + * @date 2026-01-01 + */ +@Service +public class UsdtAggregationTaskServiceImpl extends ServiceImpl implements IUsdtAggregationTaskService { + @Autowired + private UsdtAggregationTaskMapper usdtAggregationTaskMapper; + @Autowired + private ITronService tronService; + @Autowired + private IUsdtAggregationTaskItemService usdtAggregationTaskItemService; + @Autowired + private IAppsService appsService; + @Autowired + private JdbcTemplate jdbcTemplate; + @Autowired + private IWeb3WalletService web3WalletService; + @Autowired + private IWalletAddressService walletAddressService; + + @Override + public List getByIds(List ids, boolean isUser, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).in(UsdtAggregationTaskPlus::getId, ids); + if (isUser) { + lambdaQueryWrapper.eq(UsdtAggregationTaskPlus::getUserId, SecurityUtils.getUserId()); + } + List list = this.list(lambdaQueryWrapper); + if (isUser) { + checkUserPlus(list); + } + return list; + } + + private void checkUserPlus(List list) { + for (UsdtAggregationTaskPlus item : list) { + if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) { + throw new RuntimeException("无权限"); + } + } + } + + private void checkUser(List list) { + for (UsdtAggregationTask item : list) { + if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) { + throw new RuntimeException("无权限"); + } + } + } + + private void checkUser(UsdtAggregationTaskPlus item) { + if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) { + throw new RuntimeException("无权限"); + } + } + + private void checkUser(UsdtAggregationTask item) { + if (null != SecurityUtils.getUserId() && item.getUserId().longValue() != SecurityUtils.getUserId()) { + throw new RuntimeException("无权限"); + } + } + + @Override + public List select(String keyword, boolean isUser) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(UsdtAggregationTaskPlus::getId, UsdtAggregationTaskPlus::getUserId, UsdtAggregationTaskPlus::getTaskName) + .like(UsdtAggregationTaskPlus::getTaskName, keyword); + if (isUser) { + lambdaQueryWrapper.eq(UsdtAggregationTaskPlus::getUserId, SecurityUtils.getUserId()); + } + List list = this.list(lambdaQueryWrapper); + if (isUser) { + checkUserPlus(list); + } + List result = new ArrayList<>(); + for (UsdtAggregationTaskPlus item : list) { + SelectItem selectItem = new SelectItem(); + selectItem.setName(item.getTaskName()); + selectItem.setId(item.getId()); + result.add(selectItem); + } + return result; + } + + @Override + public List getListByStatusAndLtExeTime(Integer status, Date gtExeTime) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .eq(UsdtAggregationTaskPlus::getStatus, status).lt(UsdtAggregationTaskPlus::getExeTime, gtExeTime); + return list(lambdaQueryWrapper); + } + + @Override + public UsdtAggregationTaskPlus getById(Long id, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .select(columns).eq(UsdtAggregationTaskPlus::getId, id); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public Map getMapByIds(List ids, SFunction... columns) { + List list = this.getByIds(ids, false, columns); + Map map = new HashMap<>(); + for (UsdtAggregationTaskPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public Map getMapByIds(List ids) { + List list = this.getByIds(ids); + Map map = new HashMap<>(); + for (UsdtAggregationTaskPlus item : list) { + map.put(item.getId(), item); + } + return map; + } + + @Override + public List getByIds(List ids) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper().in(UsdtAggregationTaskPlus::getId, ids); + return this.list(lambdaQueryWrapper); + } + + public T sum(String field, String where, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" sum(" + field + ") as total "); + stringBuffer.append(" from usdt_aggregation_task "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass); + return result; + } + + public Long count(String where) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(" count(1)"); + stringBuffer.append(" from "); + stringBuffer.append(" usdt_aggregation_task "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class); + return result; + } + + public List countByGroupBy(String select, String where, String groupby, Class tClass) { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("select "); + stringBuffer.append(select); + stringBuffer.append(" from "); + stringBuffer.append(" usdt_aggregation_task "); + if (StringUtils.isNotBlank(where)) { + stringBuffer.append(" where "); + stringBuffer.append(where); + } + stringBuffer.append(" group by "); + stringBuffer.append(groupby); + List result = jdbcTemplate.queryForList(stringBuffer.toString()); + List tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass); + return tList; + } + + /** + * 查询归集任务 + * + * @param id 归集任务ID + * @return 归集任务 + */ + @Override + public UsdtAggregationTask selectUsdtAggregationTaskById(Long id, boolean isUser) { + UsdtAggregationTask vo = usdtAggregationTaskMapper.selectUsdtAggregationTaskById(id); + if (isUser) { + checkUser(vo); + } + return vo; + } + + /** + * 查询归集任务列表 + * + * @param usdtAggregationTask 归集任务 + * @return 归集任务 + */ + @Override + public List selectUsdtAggregationTaskList(UsdtAggregationTask usdtAggregationTask, boolean isUser) { + if (usdtAggregationTask == null) { + usdtAggregationTask = new UsdtAggregationTask(); + } + if (isUser) { + usdtAggregationTask.setUserId(SecurityUtils.getUserId()); + } + List list = usdtAggregationTaskMapper.selectUsdtAggregationTaskList(usdtAggregationTask); + if (isUser) { + checkUser(list); + } + return list; + } + + /** + * 新增归集任务 + * + * @param usdtAggregationTask 归集任务 + * @return 结果 + */ + @Transactional + @Override + public int insertUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask, boolean isUser) { + usdtAggregationTask.setCreatedAt(DateUtils.getNowDate()); + usdtAggregationTask.setUpdatedAt(DateUtils.getNowDate()); + if (isUser) { + usdtAggregationTask.setUserId(SecurityUtils.getUserId()); + if (usdtAggregationTask.getAppId() == null) { + throw new RuntimeException("AppId为空"); + } + AppsPlus apps = this.appsService.getById(usdtAggregationTask.getAppId()); + if (apps == null) { + throw new RuntimeException("App为空"); + } + if (SecurityUtils.getUserId() == null) { + throw new RuntimeException("没有登入"); + } + if (usdtAggregationTask.getExeTime() == null) { + throw new RuntimeException("执行时间为空"); + } + if (apps.getUserId().longValue() != SecurityUtils.getUserId()) { + throw new RuntimeException("没有权限"); + } + Web3WalletPlus web3WalletPlus = web3WalletService.getById(SecurityUtils.getUserId()); + if (web3WalletPlus.getUsdtBalance().subtract(usdtAggregationTask.getTotalAmount()).longValue() < 0) { + throw new RuntimeException("超过账户金额"); + } + if (usdtAggregationTask.getTaskName() == null) { + throw new RuntimeException("任务名称为空"); + } + if (usdtAggregationTask.getTotalAmount() == null || usdtAggregationTask.getTotalAmount().longValue() <= 0) { + throw new RuntimeException("归集金额为空"); + } + if (usdtAggregationTask.getExeTime() == null) { + usdtAggregationTask.setExeTime(DateUtils.getNowDate()); + } + usdtAggregationTask.setUserId(SecurityUtils.getUserId()); + usdtAggregationTask.setDistTokenAddress(apps.getDistTokenAddress()); + usdtAggregationTask.setVerifyStatus(1); + usdtAggregationTask.setStatus(0); + List list = walletAddressService.getListByAppId(usdtAggregationTask.getAppId()); + list.sort(new Comparator() { + @Override + public int compare(WalletAddressPlus p1, WalletAddressPlus p2) { + return Double.compare(p2.getWithdrawUsdtBalance().doubleValue(), p1.getWithdrawUsdtBalance().doubleValue()); // 倒序排序 + } + }); + String willTxAmount = this.sum("total_amount","status = 0 and verify_status=1 and user_id="+usdtAggregationTask.getUserId(),String.class); + if(willTxAmount == null){ + willTxAmount ="0.00"; + } + if(new BigDecimal(willTxAmount).add(usdtAggregationTask.getTotalAmount()) + .subtract(web3WalletPlus.getUsdtBalance()).doubleValue()>0){ + throw new RuntimeException("待提现金额超过账户金额"); + } + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() + .eq(UsdtAggregationTaskPlus::getAppId, usdtAggregationTask.getAppId()) + .eq(UsdtAggregationTaskPlus::getUserId,usdtAggregationTask.getUserId()) + .eq(UsdtAggregationTaskPlus::getStatus,0); + if(count(lambdaQueryWrapper) > 0){ + throw new RuntimeException("存在正在提现的记录"); + } + + this.usdtAggregationTaskMapper.insertUsdtAggregationTask(usdtAggregationTask); + BigDecimal totalAmount = usdtAggregationTask.getTotalAmount(); + List usdtAggregationTaskItems = new ArrayList<>(); + BigDecimal hasTxItem = new BigDecimal(0); + for (WalletAddressPlus item : list) { + if (item.getWithdrawUsdtBalance() == null) { + item.setWithdrawUsdtBalance(new BigDecimal(0)); + } + UsdtAggregationTaskItemPlus usdtAggregationTaskItem = new UsdtAggregationTaskItemPlus(); + usdtAggregationTaskItem.setUserId(SecurityUtils.getUserId()); + usdtAggregationTaskItem.setAppId(usdtAggregationTask.getAppId()); + usdtAggregationTaskItem.setCreatedAt(new Date()); + usdtAggregationTaskItem.setUpdatedAt(new Date()); + usdtAggregationTaskItem.setStatus(0); + usdtAggregationTaskItem.setDistTokenAddress(usdtAggregationTask.getDistTokenAddress()); + usdtAggregationTaskItem.setParentId(usdtAggregationTask.getId()); + usdtAggregationTaskItem.setTokenAddress(item.getToken()); + + if (item.getEnergyNum() < tronService.defaultEstimateEnergy()) { + log.error(item.getToken()+"能量不足,需要手续费"); + continue; + } + long bandwidth = tronService.defaultEstimateBandwidth(); + if (bandwidth > item.getBandwidthNum()) { + log.error(item.getToken()+"带宽不足需要手续费"); + continue; + } + if(bandwidth > item.getBandwidthStakedNum() + && bandwidth > (item.getBandwidthNum()-item.getBandwidthStakedNum())){ + log.error("代理|免费带宽不足需要手续费"); + continue; + } + + String tempAmount = usdtAggregationTaskItemService.sum("ope_amount","status = 0 and token_address ='"+item.getToken()+"'",String.class); + if(tempAmount ==null){ + tempAmount = "0.00"; + } + if (item.getWithdrawUsdtBalance().subtract(totalAmount).longValue() > 0) { + usdtAggregationTaskItem.setOpeAmount(totalAmount); + usdtAggregationTaskItems.add(usdtAggregationTaskItem); + hasTxItem = hasTxItem.add(item.getWithdrawUsdtBalance().subtract(new BigDecimal(tempAmount)) + .subtract(totalAmount)); + totalAmount = new BigDecimal(0); + break; + } else { + usdtAggregationTaskItem.setOpeAmount(item.getWithdrawUsdtBalance()); + totalAmount = totalAmount.subtract(item.getWithdrawUsdtBalance()); + usdtAggregationTaskItems.add(usdtAggregationTaskItem); + hasTxItem = hasTxItem.add(item.getWithdrawUsdtBalance().subtract(new BigDecimal(tempAmount)) + .subtract(item.getWithdrawUsdtBalance())); + } + } + if (hasTxItem.doubleValue() < 0) { + throw new RuntimeException("app下的地址可提现金额不足,amount=" + hasTxItem.toString()); + } + if (totalAmount.longValue() > 0) { + throw new RuntimeException("app下的地址可提现金额不足,amount=" + totalAmount.toString()); + } + if (!usdtAggregationTaskItems.isEmpty()) { + this.usdtAggregationTaskItemService.saveBatch(usdtAggregationTaskItems); + }else{ + throw new RuntimeException("没有可以免费提现的地址"); + } + return 1; + } else { + return usdtAggregationTaskMapper.insertUsdtAggregationTask(usdtAggregationTask); + } + } + + /** + * 修改归集任务 + * + * @param usdtAggregationTask 归集任务 + * @return 结果 + */ + @Override + public int updateUsdtAggregationTask(UsdtAggregationTask usdtAggregationTask, boolean isUser) { + usdtAggregationTask.setUpdatedAt(DateUtils.getNowDate()); + if (isUser) { + checkUser(usdtAggregationTask); + } + return usdtAggregationTaskMapper.updateUsdtAggregationTask(usdtAggregationTask); + } + + /** + * 批量删除归集任务 + * + * @param ids 需要删除的归集任务ID + * @return 结果 + */ + @Override + public int deleteUsdtAggregationTaskByIds(Long[] ids, boolean isUser) { + if (isUser) { + List list = getByIds(Arrays.asList(ids), false, UsdtAggregationTaskPlus::getUserId, UsdtAggregationTaskPlus::getId); + checkUserPlus(list); + } + return usdtAggregationTaskMapper.deleteUsdtAggregationTaskByIds(ids); + } + + /** + * 删除归集任务信息 + * + * @param id 归集任务ID + * @return 结果 + */ + @Override + public int deleteUsdtAggregationTaskById(Long id, boolean isUser) { + if (isUser) { + UsdtAggregationTaskPlus vo = getById(id, UsdtAggregationTaskPlus::getUserId, UsdtAggregationTaskPlus::getId); + checkUser(vo); + } + return usdtAggregationTaskMapper.deleteUsdtAggregationTaskById(id); + } +} diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/WalletAddressServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/WalletAddressServiceImpl.java index 5d80659..5a1ffe9 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/WalletAddressServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/WalletAddressServiceImpl.java @@ -10,12 +10,16 @@ import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.WalletAddress; import com.ruoyi.system.domain.WalletAddressPlus; +import com.ruoyi.system.domain.vo.EnergyAndBandwidthVo; import com.ruoyi.system.mapper.WalletAddressMapper; +import com.ruoyi.system.service.ITronService; import com.ruoyi.system.service.IWalletAddressService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; +import org.tron.trident.core.ApiWrapper; +import java.math.BigDecimal; import java.util.*; /** @@ -30,7 +34,8 @@ public class WalletAddressServiceImpl extends ServiceImpl getByIds(List ids, boolean isUser, SFunction... columns) { LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() @@ -73,6 +78,54 @@ public class WalletAddressServiceImpl extends ServiceImpl select(String keyword, boolean isUser) { LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper() @@ -101,6 +154,25 @@ public class WalletAddressServiceImpl extends ServiceImpl... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper(); + if(null != columns || columns.length > 0){ + lambdaQueryWrapper.select(columns); + } + lambdaQueryWrapper.eq(WalletAddressPlus::getToken, token).eq(WalletAddressPlus::getAppId, appId); + return baseMapper.selectOne(lambdaQueryWrapper); + } + + @Override + public List getListByAppId(Long appId, SFunction... columns) { + LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper(); + if(null != columns || columns.length > 0){ + lambdaQueryWrapper.select(columns); + } + lambdaQueryWrapper.eq(WalletAddressPlus::getAppId, appId); + return baseMapper.selectList(lambdaQueryWrapper); + } @Override public Map getMapByIds(List ids, SFunction... columns) { @@ -111,7 +183,14 @@ public class WalletAddressServiceImpl extends ServiceImpl lambdaQueryWrapper = new LambdaQueryWrapper(); + lambdaQueryWrapper.eq(WalletAddressPlus::getId, id); + return this.update(walletAddressPlus,lambdaQueryWrapper); + } @Override public Map getMapByIds(List ids) { List list = this.getByIds(ids); diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/Web3WalletServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/Web3WalletServiceImpl.java index bd318cf..418a5de 100644 --- a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/Web3WalletServiceImpl.java +++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/Web3WalletServiceImpl.java @@ -15,10 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.math.BigDecimal; +import java.util.*; /** * 钱包管理Service业务层处理 @@ -178,6 +176,21 @@ public class Web3WalletServiceImpl extends ServiceImpl selectWeb3WalletList(Web3Wallet web3Wallet, boolean isUser) { + if (isUser) { + Web3WalletPlus myWallet = this.getById(SecurityUtils.getUserId()); + if(myWallet == null){ + myWallet = new Web3WalletPlus(); + myWallet.setId(SecurityUtils.getUserId()); + myWallet.setPassword(UUID.randomUUID().toString()); + myWallet.setEthBalance(new BigDecimal(0)); + myWallet.setTrxBalance(new BigDecimal(0)); + myWallet.setUsdtBalance(new BigDecimal(0)); + myWallet.setCreatedAt(new Date()); + myWallet.setUpdatedAt(new Date()); + this.save(myWallet); + } + web3Wallet.setId(SecurityUtils.getUserId()); + } List list = web3WalletMapper.selectWeb3WalletList(web3Wallet); if (isUser) { checkUser(list); diff --git a/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml b/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml index d100b18..57504b2 100644 --- a/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/AppsMapper.xml @@ -13,10 +13,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + - select id, user_id, name, description, status, created_at, updated_at, deleted_at from apps + select id, user_id, name, dist_token_address,description, status, created_at, updated_at, deleted_at from apps @@ -47,6 +49,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" created_at, updated_at, deleted_at, + dist_token_address, #{userId}, @@ -56,6 +59,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" #{createdAt}, #{updatedAt}, #{deletedAt}, + #{distTokenAddress}, @@ -69,6 +73,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" created_at = #{createdAt}, updated_at = #{updatedAt}, deleted_at = #{deletedAt}, + dist_token_address = #{distTokenAddress}, where id = #{id} diff --git a/ruoyi-system/src/main/resources/mapper/system/UsdtAggregationTaskItemMapper.xml b/ruoyi-system/src/main/resources/mapper/system/UsdtAggregationTaskItemMapper.xml new file mode 100644 index 0000000..feba9d2 --- /dev/null +++ b/ruoyi-system/src/main/resources/mapper/system/UsdtAggregationTaskItemMapper.xml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + select id, token_address, status, remark, ope_amount, created_at, updated_at, deleted_at, user_id, app_id, parent_id, dist_token_address from usdt_aggregation_task_item + + + + + + + + insert into usdt_aggregation_task_item + + token_address, + status, + remark, + ope_amount, + created_at, + updated_at, + deleted_at, + user_id, + app_id, + parent_id, + dist_token_address, + + + #{tokenAddress}, + #{status}, + #{remark}, + #{opeAmount}, + #{createdAt}, + #{updatedAt}, + #{deletedAt}, + #{userId}, + #{appId}, + #{parentId}, + #{distTokenAddress}, + + + + + update usdt_aggregation_task_item + + token_address = #{tokenAddress}, + status = #{status}, + remark = #{remark}, + ope_amount = #{opeAmount}, + created_at = #{createdAt}, + updated_at = #{updatedAt}, + deleted_at = #{deletedAt}, + user_id = #{userId}, + app_id = #{appId}, + parent_id = #{parentId}, + dist_token_address = #{distTokenAddress}, + + where id = #{id} + + + + delete from usdt_aggregation_task_item where id = #{id} + + + + delete from usdt_aggregation_task_item where id in + + #{id} + + + \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/UsdtAggregationTaskMapper.xml b/ruoyi-system/src/main/resources/mapper/system/UsdtAggregationTaskMapper.xml new file mode 100644 index 0000000..67fb6c6 --- /dev/null +++ b/ruoyi-system/src/main/resources/mapper/system/UsdtAggregationTaskMapper.xml @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + select id, task_name, app_id, user_id, remark, status, created_at, updated_at, deleted_at, total_amount, exe_time, verify_status, dist_token_address from usdt_aggregation_task + + + + + + + + insert into usdt_aggregation_task + + task_name, + app_id, + user_id, + remark, + status, + created_at, + updated_at, + deleted_at, + total_amount, + exe_time, + verify_status, + dist_token_address, + + + #{taskName}, + #{appId}, + #{userId}, + #{remark}, + #{status}, + #{createdAt}, + #{updatedAt}, + #{deletedAt}, + #{totalAmount}, + #{exeTime}, + #{verifyStatus}, + #{distTokenAddress}, + + + + + update usdt_aggregation_task + + task_name = #{taskName}, + app_id = #{appId}, + user_id = #{userId}, + remark = #{remark}, + status = #{status}, + created_at = #{createdAt}, + updated_at = #{updatedAt}, + deleted_at = #{deletedAt}, + total_amount = #{totalAmount}, + exe_time = #{exeTime}, + verify_status = #{verifyStatus}, + dist_token_address = #{distTokenAddress}, + + where id = #{id} + + + + delete from usdt_aggregation_task where id = #{id} + + + + delete from usdt_aggregation_task where id in + + #{id} + + + \ No newline at end of file diff --git a/ruoyi-system/src/main/resources/mapper/system/WalletAddressMapper.xml b/ruoyi-system/src/main/resources/mapper/system/WalletAddressMapper.xml index 4c41e53..2f0210b 100644 --- a/ruoyi-system/src/main/resources/mapper/system/WalletAddressMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/WalletAddressMapper.xml @@ -13,12 +13,30 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + + + + + + + + + + + + + + + + + + - select id, token, status, created_at, updated_at, deleted_at, app_id, user_id,usdt_balance,trx_balance from wallet_address + select id, token, status, created_at, updated_at,bandwidth_staked_num, deleted_at, app_id, user_id, token_key, usdt_balance, trx_balance, energy_num, bandwidth_num, withdraw_usdt_balance, delegated_energy_trx_num, delegated_energy_value, acquired_delegated_energy_trx_num, acquired_delegated_energy_value, delegated_bandwidth_trx_num, delegated_bandwidth_value, acquired_delegated_bandwidth_trx_num, acquired_delegated_bandwidth_value, staked_trx_num, energy_staked_trx_num, bandwidth_staked_trx_num, vote_num, voted_num from wallet_address @@ -49,8 +83,26 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" deleted_at, app_id, user_id, + token_key, usdt_balance, trx_balance, + energy_num, + bandwidth_num, + withdraw_usdt_balance, + delegated_energy_trx_num, + delegated_energy_value, + acquired_delegated_energy_trx_num, + acquired_delegated_energy_value, + delegated_bandwidth_trx_num, + delegated_bandwidth_value, + acquired_delegated_bandwidth_trx_num, + acquired_delegated_bandwidth_value, + staked_trx_num, + energy_staked_trx_num, + bandwidth_staked_trx_num, + vote_num, + voted_num, + bandwidth_staked_num, #{token}, @@ -60,8 +112,26 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" #{deletedAt}, #{appId}, #{userId}, + #{tokenKey}, #{usdtBalance}, #{trxBalance}, + #{energyNum}, + #{bandwidthNum}, + #{withdrawUsdtBalance}, + #{delegatedEnergyTrxNum}, + #{delegatedEnergyValue}, + #{acquiredDelegatedEnergyTrxNum}, + #{acquiredDelegatedEnergyValue}, + #{delegatedBandwidthTrxNum}, + #{delegatedBandwidthValue}, + #{acquiredDelegatedBandwidthTrxNum}, + #{acquiredDelegatedBandwidthValue}, + #{stakedTrxNum}, + #{energyStakedTrxNum}, + #{bandwidthStakedTrxNum}, + #{voteNum}, + #{votedNum}, + #{bandwidthStakedNum}, @@ -75,8 +145,26 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" deleted_at = #{deletedAt}, app_id = #{appId}, user_id = #{userId}, + token_key = #{tokenKey}, usdt_balance = #{usdtBalance}, trx_balance = #{trxBalance}, + energy_num = #{energyNum}, + bandwidth_num = #{bandwidthNum}, + withdraw_usdt_balance = #{withdrawUsdtBalance}, + delegated_energy_trx_num = #{delegatedEnergyTrxNum}, + delegated_energy_value = #{delegatedEnergyValue}, + acquired_delegated_energy_trx_num = #{acquiredDelegatedEnergyTrxNum}, + acquired_delegated_energy_value = #{acquiredDelegatedEnergyValue}, + delegated_bandwidth_trx_num = #{delegatedBandwidthTrxNum}, + delegated_bandwidth_value = #{delegatedBandwidthValue}, + acquired_delegated_bandwidth_trx_num = #{acquiredDelegatedBandwidthTrxNum}, + acquired_delegated_bandwidth_value = #{acquiredDelegatedBandwidthValue}, + staked_trx_num = #{stakedTrxNum}, + energy_staked_trx_num = #{energyStakedTrxNum}, + bandwidth_staked_trx_num = #{bandwidthStakedTrxNum}, + vote_num = #{voteNum}, + voted_num = #{votedNum}, + bandwidth_staked_num = #{bandwidthStakedNum}, where id = #{id} diff --git a/ruoyi-system/src/main/resources/mapper/system/Web3WalletMapper.xml b/ruoyi-system/src/main/resources/mapper/system/Web3WalletMapper.xml index 0dfa987..859e5a9 100644 --- a/ruoyi-system/src/main/resources/mapper/system/Web3WalletMapper.xml +++ b/ruoyi-system/src/main/resources/mapper/system/Web3WalletMapper.xml @@ -29,6 +29,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" and trx_balance = #{trxBalance} and eth_balance = #{ethBalance} and password = #{password} + and id = #{id}