file_id
stringlengths
5
9
content
stringlengths
128
32.8k
repo
stringlengths
9
63
path
stringlengths
8
125
token_length
int64
36
8.14k
original_comment
stringlengths
5
1.83k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
111
32.8k
excluded
float64
0
1
27720_17
package chess.pieces; import chess.panels.PanelBase; import chess.style.Style; import chess.util.Constants; import com.sun.istack.internal.NotNull; import javax.swing.*; import java.awt.*; import java.io.File; /** * 国际象棋抽象类<p> * KING: 国王<p> * QUEEN: 皇后<p> * ROOK: 战车,和中国象棋一样<p> * BISHOP: 主教,对应象,写法上和中国象棋基本一致,需要去掉不能过河这个判断<p> * KNIGHT: 骑士,对应马<p> * PAWN: 兵 * * * </p> * 除了棋子的一般着法外,国际象棋中存在下面三种特殊着法:<p> * 吃过路兵:如果对方的兵第一次行棋且直进两格,刚好形成本方有兵与其横向紧贴并列,则本方的兵可以立即斜进,把对方的兵吃掉,并视为一步棋。这个动作必须立刻进行,缓着后无效。记录时记为 “en passant” 或 “en pt”, 法语中表示 “路过”。 * <p> * 兵升变:本方任何一个兵直进达到对方底线时,即可升变为除“王”和“兵”以外的任何一种棋子,可升变为“后”、“车”、“马”、“象”,不能不变。这被视为一步棋。升变后按新棋子的规则走棋。 * <p> * 王车易位:每局棋中,双方各有一次机会,让王朝车的方向移动两格,然后车越过王,放在与王紧邻的一格上,作为王执行的一步棋。王车易位根据左右分为"长易位"(后翼易位,记谱记为0-0-0)和"短易位"(王翼易位,记谱记为0-0)。王车易位是国际象棋中较为重要的一种战略,它涉及王、车两种棋子,是关键时刻扭转局势或解杀还杀的手段。 * <p> * 王车易位有较为严格的规则限制,当且仅当以下6个条件同时成立时,方可进行王车易位: * 1.王与用来易位的车均从未被移动过(即王和车处在棋局开始的原始位置,王在e1或e8,车在a1、a8、h1或h8。但如果王或用来易位的车之前曾经移动过,后来又返回了原始位置,则不能进行“王车易位”,因为不符合“从未被移动过”); * 2.王与用来易位的车之间没有其他棋子阻隔; * 3.王不能正被对方“将军”(即“王车易位”不能作为“应将”的手段); * 4.王所经过的格子不能在对方棋子的攻击范围之内; * 5.王所到达的格子不能被对方“将军”(即王不可以送吃); * 6.王和对应的车必须处在同一横行(即通过兵的升变得到的车不能用来进行“王车易位”)。【注:此项规则为国际棋联在1972年所添加,目的是为防备这种情况:设想一局棋,假定白方的王从开局起一直未移动过,处在e1位置,那么白方若将一个兵成功走至对方底线的e8位置并且升变为车(见兵的升变规则),与王处在同一直行,且就满足以上1~5的条件,此时也可进行王车易位(因为规则1规定为对应的车未被移动过,而升变后的车确实没有移动,之前做的走动为兵在执行)。Max Pam发现这一走法,而且被棋手在比赛中采用过。为了防止这种不被习惯赞同但确实符合规定的走法出现,国际棋联添加了此规则。】 * <p> * 对于王车易位的规则有一些误解,特此说明,一切以上述6点为准,在符合上述规则且有下列情况出现时,是允许王车易位的: * 1.王未正被“将军”,但之前被“将军”过; * 2.用来易位的车正受对方攻击; * 3.在长易位中,车所经过的格子在对方的攻击范围之内。 * <p> * 上述三点不影响王车易位的进行。【注意:在比赛走子时,必须先移动王,再移动车,否则被判为车的一步棋,王车易位失效。】 */ public abstract class Chess { public final static String KING = "king", ROOK = "rook", QUEEN = "queen", KNIGHT = "knight", BISHOP = "bishop", PAWN = "pawn"; public static Style style = Style.DEFAULT; public final static String[] PIECES = { KING, ROOK, QUEEN, KNIGHT, BISHOP, PAWN}; public static final int FIRST_COLOR = 1, LATER_COLOR = -1; //棋子大小 public static final int SIZE = 60; //棋子距边缘距离 public static final int MARGIN = 20; //棋子间距 public static final int SPACE = 60; //棋子名称 protected String name; public String path; //棋子颜色、实际坐标、下标 private static int IDBase = 0; public static void setIDBase(int var){ IDBase = var; } protected int color, x, y, ID; public boolean moved, changed; //棋子的网格坐标 protected Point point, initPoint; public String getName() { return this.name; } public int getID() { return this.ID; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public void setName(String name) { this.name = name; this.path = Constants.STYLE_PATH + File.separator + Style.getStyle(style) + File.separator + name + color+".png"; } public void setID(int ID){ this.ID = ID; } public void setPoint(Point point) { this.point = (Point) point.clone(); if (initPoint == null) { initPoint = this.point; } calculatePosition(); } public Chess(String name, Point point, int player) { this.name = name; this.color = player; this.path = Constants.STYLE_PATH + File.separator +Style.getStyle(style) + File.separator + name + color + ".png"; System.out.println(path); this.point = new Point(point); this.initPoint = new Point(point); this.calculatePosition(); this.ID = ++IDBase; } public void setPoint(int x, int y) { if (x >= 0 && x < 8 && y > -1 && y < 8) { this.point.x = x; this.point.y = y; calculatePosition(); } } public Point getPoint() { return this.point; } /** * 绘制棋子的方法 * * @param g 棋子画笔 * @param panel 棋盘所在的panel */ public void draw(Graphics g, PanelBase panel) { g.drawImage(Toolkit.getDefaultToolkit().getImage(path), MARGIN+SPACE * point.x, MARGIN+SPACE * point.y, SIZE, SIZE, panel); } public void drawSelectedChess(Graphics g) { g.drawRect(this.x, this.y, SIZE, SIZE); } public void calculatePosition() { // this.x = MARGIN - SIZE / 2 + SPACE * (point.x); // this.y = MARGIN - SIZE / 2 + SPACE * (point.y); this.x=MARGIN+SPACE * point.x; this.y=MARGIN+SPACE * point.y; } /** * 根据x,y坐标计算网格坐标 * * @param x * @param y */ public static Point getNewPoint(int x, int y) { //todo: 添加判定方法!判断x,y是否合法。 // x = (x - MARGIN + SIZE / 2) / SPACE; // y = (y - MARGIN + SIZE / 2) / SPACE; x = (x-MARGIN)/SPACE; y = (y-MARGIN)/SPACE; return new Point(x, y); } public void reverse() { point.y = 7 - point.y; initPoint = point; calculatePosition(); } /* 下棋逻辑判断部分。 */ /** * 是否蹩脚。国际象棋里没有用。 * * @param point * @param gamePanel * @return boolean */ @Deprecated public boolean isPrevented(Point point, PanelBase gamePanel) { Point center = new Point(); if (Chess.BISHOP.equals(name)) { center.x = (point.x + this.point.x) / 2; center.y = (point.y + this.point.y) / 2; return gamePanel.getChessFromPoint(center) != null; } else if (Chess.KNIGHT.equals(name)) { int line = whichLine(point); if (line == -2) { //x轴日字蹩脚: center.x = (point.x + this.point.x) / 2; center.y = this.point.y; } else if (line == -3) { //y轴日字蹩脚 center.x = this.point.x; center.y = (point.y + this.point.y)/2; } return gamePanel.getChessFromPoint(center) != null; } return false; } /** * 判断棋子最初在河对岸还是我方。例如,y < 5, 在棋盘上方。 * * @return */ public boolean isUp() { return initPoint.y < 5; } /** * @param point 坐标 * @return 3:沿x方向直线<p> * 2:沿着y方向直线<p> * 1:45°斜线<p> * -1:都不是<p> * -2: x轴日<p> * -3:y轴日 */ public int whichLine(Point point) { if (point.y == this.point.y) return 3; else if (point.x == this.point.x) return 2; else if (Math.abs(point.x - this.point.x) == Math.abs(point.y - this.point.y)) return 1; else if (Math.abs(this.point.x - point.x) == 2 && Math.abs(this.point.y - point.y) == 1) return -2; else if (Math.abs(this.point.y - point.y) == 2 && Math.abs(this.point.x - point.x) == 1) return -3; else return -1; } /** * 走的直角边数, 例如,马任走一次会走3个直角边,车从(2,1)走到(4,1)会走过2个直角边。 * * @param point 目标点位置 * @return 经过的小方格边数。 * */ public int getStep(Point point) { // int line = whichLine(point); // if (line == 3) return Math.abs(point.x - this.point.x); // else if (line == 2 || line == 1) return Math.abs(point.y - this.point.y); // else return line; return getStep(point, whichLine(point)); } public int getStep(Point point, int line) { if (line == 3) return Math.abs(point.x - this.point.x); else if (line == 2 || line == 1) return Math.abs(point.y - this.point.y); else return line; } /** * 计算起点到终点之间的直线上有多少棋子。<b>不包括起点、终点</b>。 * @param point 目标坐标 * @return 棋子数量 */ @SuppressWarnings("can be update") public int pieceCount(Point point, PanelBase gamePanel){ return pieceCount(whichLine(point), point, gamePanel); } /** * 计算起点到终点之间的直线上有多少棋子。<b>不包括起点、终点</b>。这个方法可以被精简。 * @param line 走棋方向,如果不是直线或者对角线,会直接返回line值。 * @param point 目标坐标 * @param gamePanel 游戏面板 * @return int */ @SuppressWarnings("can be update") public int pieceCount(int line, Point point, PanelBase gamePanel){ int start, end, cou = 0; Point tempP = new Point(); if(line == 2){//沿y tempP.x = this.point.x; start = Math.min(point.y, this.point.y)+1; end = Math.max(point.y, this.point.y); for(int i = start ; i < end; i++){ tempP.y = i; if(gamePanel.getChessFromPoint(tempP) != null) cou++; } }else if(line == 3){//沿x tempP.y = this.point.y; start = Math.min(point.x, this.point.x)+1; end = Math.max(point.x, this.point.x); for(int i = start ; i < end; i++){ tempP.x = i; if(gamePanel.getChessFromPoint(tempP) != null) cou++; } }else if(line == 1){ //todo: 完成象中途不能被挡住 int startX = point.x, startY = point.y, endX = this.point.x; int deltaX = startX < endX? 1:-1, deltaY = startY < this.point.y? 1:-1; for(startX += deltaX, startY+=deltaY; startX != endX; startX+=deltaX, startY+=deltaY){ tempP.x = startX; tempP.y = startY; if(gamePanel.getChessFromPoint(tempP) != null) { cou++; } } } return cou; } /** * 判断是否前进 * @param point 目标坐标 * @return 是否前进 */ public boolean isForward(Point point){ if(isUp()){//如果本身在上面,那么只能往下走 return point.y > this.point.y; }else{ return point.y < this.point.y; } } /** * 判断王车换位能否成立。 * @return 能为真,不能为假 */ @Deprecated public boolean canWangCheYiWei(){ //todo: 判断王车易位能否成立 return false; } /** * 兵的特殊走法:能否换成新的棋子。例如走到对方的皇位置,变成皇后。 * @return */ @Deprecated public boolean canUpdatePawn(){ return false; } @Override public String toString() { return String.format("棋子名称:%s, ID:%d, 横坐标:%d, 纵坐标:%d, \n属于【%d】阵营。", name, this.ID, point.x, point.y, color); } public boolean equals(Chess chess){ return chess.getID() == this.ID; }//这不是equal方法。 public void moveProcess(PanelBase panel){ Point tp = new Point(0,0); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) {//遍历棋盘每一个点 tp.x = i; tp.y = j; if(canMove(tp, panel) ) {//如果可以走,就绘制提示。 if(panel.getChessFromPoint(tp) != null && panel.getChessFromPoint(tp).getColor() == color) continue; panel.drawHint(tp); System.out.println(i + " " + j + "可以走"); } } } } @Deprecated public void shengWei(Point point){} public void shengWei(String name){} public boolean isAttacked(PanelBase panel){ return false; } public void refactor(String s){} /** * 判断能否移动到Point处 * * @param point 想要移动到的点位 * @return 能否移动 */ public abstract boolean canMove(Point point, PanelBase panel); public void resetPath(){ this.path = Constants.STYLE_PATH + File.separator + Style.getStyle(style) + File.separator + name + color + ".png"; } @Deprecated public static boolean canMove(Point oldPoint, Point targetPoint, PanelBase panel){ return false; }; public boolean isDoubleMove(){ return false; } public void setDoubleMove(boolean flag){ } }
Ethylene9160/Chess
src/chess/pieces/Chess.java
4,418
//y轴日字蹩脚
line_comment
zh-cn
package chess.pieces; import chess.panels.PanelBase; import chess.style.Style; import chess.util.Constants; import com.sun.istack.internal.NotNull; import javax.swing.*; import java.awt.*; import java.io.File; /** * 国际象棋抽象类<p> * KING: 国王<p> * QUEEN: 皇后<p> * ROOK: 战车,和中国象棋一样<p> * BISHOP: 主教,对应象,写法上和中国象棋基本一致,需要去掉不能过河这个判断<p> * KNIGHT: 骑士,对应马<p> * PAWN: 兵 * * * </p> * 除了棋子的一般着法外,国际象棋中存在下面三种特殊着法:<p> * 吃过路兵:如果对方的兵第一次行棋且直进两格,刚好形成本方有兵与其横向紧贴并列,则本方的兵可以立即斜进,把对方的兵吃掉,并视为一步棋。这个动作必须立刻进行,缓着后无效。记录时记为 “en passant” 或 “en pt”, 法语中表示 “路过”。 * <p> * 兵升变:本方任何一个兵直进达到对方底线时,即可升变为除“王”和“兵”以外的任何一种棋子,可升变为“后”、“车”、“马”、“象”,不能不变。这被视为一步棋。升变后按新棋子的规则走棋。 * <p> * 王车易位:每局棋中,双方各有一次机会,让王朝车的方向移动两格,然后车越过王,放在与王紧邻的一格上,作为王执行的一步棋。王车易位根据左右分为"长易位"(后翼易位,记谱记为0-0-0)和"短易位"(王翼易位,记谱记为0-0)。王车易位是国际象棋中较为重要的一种战略,它涉及王、车两种棋子,是关键时刻扭转局势或解杀还杀的手段。 * <p> * 王车易位有较为严格的规则限制,当且仅当以下6个条件同时成立时,方可进行王车易位: * 1.王与用来易位的车均从未被移动过(即王和车处在棋局开始的原始位置,王在e1或e8,车在a1、a8、h1或h8。但如果王或用来易位的车之前曾经移动过,后来又返回了原始位置,则不能进行“王车易位”,因为不符合“从未被移动过”); * 2.王与用来易位的车之间没有其他棋子阻隔; * 3.王不能正被对方“将军”(即“王车易位”不能作为“应将”的手段); * 4.王所经过的格子不能在对方棋子的攻击范围之内; * 5.王所到达的格子不能被对方“将军”(即王不可以送吃); * 6.王和对应的车必须处在同一横行(即通过兵的升变得到的车不能用来进行“王车易位”)。【注:此项规则为国际棋联在1972年所添加,目的是为防备这种情况:设想一局棋,假定白方的王从开局起一直未移动过,处在e1位置,那么白方若将一个兵成功走至对方底线的e8位置并且升变为车(见兵的升变规则),与王处在同一直行,且就满足以上1~5的条件,此时也可进行王车易位(因为规则1规定为对应的车未被移动过,而升变后的车确实没有移动,之前做的走动为兵在执行)。Max Pam发现这一走法,而且被棋手在比赛中采用过。为了防止这种不被习惯赞同但确实符合规定的走法出现,国际棋联添加了此规则。】 * <p> * 对于王车易位的规则有一些误解,特此说明,一切以上述6点为准,在符合上述规则且有下列情况出现时,是允许王车易位的: * 1.王未正被“将军”,但之前被“将军”过; * 2.用来易位的车正受对方攻击; * 3.在长易位中,车所经过的格子在对方的攻击范围之内。 * <p> * 上述三点不影响王车易位的进行。【注意:在比赛走子时,必须先移动王,再移动车,否则被判为车的一步棋,王车易位失效。】 */ public abstract class Chess { public final static String KING = "king", ROOK = "rook", QUEEN = "queen", KNIGHT = "knight", BISHOP = "bishop", PAWN = "pawn"; public static Style style = Style.DEFAULT; public final static String[] PIECES = { KING, ROOK, QUEEN, KNIGHT, BISHOP, PAWN}; public static final int FIRST_COLOR = 1, LATER_COLOR = -1; //棋子大小 public static final int SIZE = 60; //棋子距边缘距离 public static final int MARGIN = 20; //棋子间距 public static final int SPACE = 60; //棋子名称 protected String name; public String path; //棋子颜色、实际坐标、下标 private static int IDBase = 0; public static void setIDBase(int var){ IDBase = var; } protected int color, x, y, ID; public boolean moved, changed; //棋子的网格坐标 protected Point point, initPoint; public String getName() { return this.name; } public int getID() { return this.ID; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public void setName(String name) { this.name = name; this.path = Constants.STYLE_PATH + File.separator + Style.getStyle(style) + File.separator + name + color+".png"; } public void setID(int ID){ this.ID = ID; } public void setPoint(Point point) { this.point = (Point) point.clone(); if (initPoint == null) { initPoint = this.point; } calculatePosition(); } public Chess(String name, Point point, int player) { this.name = name; this.color = player; this.path = Constants.STYLE_PATH + File.separator +Style.getStyle(style) + File.separator + name + color + ".png"; System.out.println(path); this.point = new Point(point); this.initPoint = new Point(point); this.calculatePosition(); this.ID = ++IDBase; } public void setPoint(int x, int y) { if (x >= 0 && x < 8 && y > -1 && y < 8) { this.point.x = x; this.point.y = y; calculatePosition(); } } public Point getPoint() { return this.point; } /** * 绘制棋子的方法 * * @param g 棋子画笔 * @param panel 棋盘所在的panel */ public void draw(Graphics g, PanelBase panel) { g.drawImage(Toolkit.getDefaultToolkit().getImage(path), MARGIN+SPACE * point.x, MARGIN+SPACE * point.y, SIZE, SIZE, panel); } public void drawSelectedChess(Graphics g) { g.drawRect(this.x, this.y, SIZE, SIZE); } public void calculatePosition() { // this.x = MARGIN - SIZE / 2 + SPACE * (point.x); // this.y = MARGIN - SIZE / 2 + SPACE * (point.y); this.x=MARGIN+SPACE * point.x; this.y=MARGIN+SPACE * point.y; } /** * 根据x,y坐标计算网格坐标 * * @param x * @param y */ public static Point getNewPoint(int x, int y) { //todo: 添加判定方法!判断x,y是否合法。 // x = (x - MARGIN + SIZE / 2) / SPACE; // y = (y - MARGIN + SIZE / 2) / SPACE; x = (x-MARGIN)/SPACE; y = (y-MARGIN)/SPACE; return new Point(x, y); } public void reverse() { point.y = 7 - point.y; initPoint = point; calculatePosition(); } /* 下棋逻辑判断部分。 */ /** * 是否蹩脚。国际象棋里没有用。 * * @param point * @param gamePanel * @return boolean */ @Deprecated public boolean isPrevented(Point point, PanelBase gamePanel) { Point center = new Point(); if (Chess.BISHOP.equals(name)) { center.x = (point.x + this.point.x) / 2; center.y = (point.y + this.point.y) / 2; return gamePanel.getChessFromPoint(center) != null; } else if (Chess.KNIGHT.equals(name)) { int line = whichLine(point); if (line == -2) { //x轴日字蹩脚: center.x = (point.x + this.point.x) / 2; center.y = this.point.y; } else if (line == -3) { //y轴 <SUF> center.x = this.point.x; center.y = (point.y + this.point.y)/2; } return gamePanel.getChessFromPoint(center) != null; } return false; } /** * 判断棋子最初在河对岸还是我方。例如,y < 5, 在棋盘上方。 * * @return */ public boolean isUp() { return initPoint.y < 5; } /** * @param point 坐标 * @return 3:沿x方向直线<p> * 2:沿着y方向直线<p> * 1:45°斜线<p> * -1:都不是<p> * -2: x轴日<p> * -3:y轴日 */ public int whichLine(Point point) { if (point.y == this.point.y) return 3; else if (point.x == this.point.x) return 2; else if (Math.abs(point.x - this.point.x) == Math.abs(point.y - this.point.y)) return 1; else if (Math.abs(this.point.x - point.x) == 2 && Math.abs(this.point.y - point.y) == 1) return -2; else if (Math.abs(this.point.y - point.y) == 2 && Math.abs(this.point.x - point.x) == 1) return -3; else return -1; } /** * 走的直角边数, 例如,马任走一次会走3个直角边,车从(2,1)走到(4,1)会走过2个直角边。 * * @param point 目标点位置 * @return 经过的小方格边数。 * */ public int getStep(Point point) { // int line = whichLine(point); // if (line == 3) return Math.abs(point.x - this.point.x); // else if (line == 2 || line == 1) return Math.abs(point.y - this.point.y); // else return line; return getStep(point, whichLine(point)); } public int getStep(Point point, int line) { if (line == 3) return Math.abs(point.x - this.point.x); else if (line == 2 || line == 1) return Math.abs(point.y - this.point.y); else return line; } /** * 计算起点到终点之间的直线上有多少棋子。<b>不包括起点、终点</b>。 * @param point 目标坐标 * @return 棋子数量 */ @SuppressWarnings("can be update") public int pieceCount(Point point, PanelBase gamePanel){ return pieceCount(whichLine(point), point, gamePanel); } /** * 计算起点到终点之间的直线上有多少棋子。<b>不包括起点、终点</b>。这个方法可以被精简。 * @param line 走棋方向,如果不是直线或者对角线,会直接返回line值。 * @param point 目标坐标 * @param gamePanel 游戏面板 * @return int */ @SuppressWarnings("can be update") public int pieceCount(int line, Point point, PanelBase gamePanel){ int start, end, cou = 0; Point tempP = new Point(); if(line == 2){//沿y tempP.x = this.point.x; start = Math.min(point.y, this.point.y)+1; end = Math.max(point.y, this.point.y); for(int i = start ; i < end; i++){ tempP.y = i; if(gamePanel.getChessFromPoint(tempP) != null) cou++; } }else if(line == 3){//沿x tempP.y = this.point.y; start = Math.min(point.x, this.point.x)+1; end = Math.max(point.x, this.point.x); for(int i = start ; i < end; i++){ tempP.x = i; if(gamePanel.getChessFromPoint(tempP) != null) cou++; } }else if(line == 1){ //todo: 完成象中途不能被挡住 int startX = point.x, startY = point.y, endX = this.point.x; int deltaX = startX < endX? 1:-1, deltaY = startY < this.point.y? 1:-1; for(startX += deltaX, startY+=deltaY; startX != endX; startX+=deltaX, startY+=deltaY){ tempP.x = startX; tempP.y = startY; if(gamePanel.getChessFromPoint(tempP) != null) { cou++; } } } return cou; } /** * 判断是否前进 * @param point 目标坐标 * @return 是否前进 */ public boolean isForward(Point point){ if(isUp()){//如果本身在上面,那么只能往下走 return point.y > this.point.y; }else{ return point.y < this.point.y; } } /** * 判断王车换位能否成立。 * @return 能为真,不能为假 */ @Deprecated public boolean canWangCheYiWei(){ //todo: 判断王车易位能否成立 return false; } /** * 兵的特殊走法:能否换成新的棋子。例如走到对方的皇位置,变成皇后。 * @return */ @Deprecated public boolean canUpdatePawn(){ return false; } @Override public String toString() { return String.format("棋子名称:%s, ID:%d, 横坐标:%d, 纵坐标:%d, \n属于【%d】阵营。", name, this.ID, point.x, point.y, color); } public boolean equals(Chess chess){ return chess.getID() == this.ID; }//这不是equal方法。 public void moveProcess(PanelBase panel){ Point tp = new Point(0,0); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) {//遍历棋盘每一个点 tp.x = i; tp.y = j; if(canMove(tp, panel) ) {//如果可以走,就绘制提示。 if(panel.getChessFromPoint(tp) != null && panel.getChessFromPoint(tp).getColor() == color) continue; panel.drawHint(tp); System.out.println(i + " " + j + "可以走"); } } } } @Deprecated public void shengWei(Point point){} public void shengWei(String name){} public boolean isAttacked(PanelBase panel){ return false; } public void refactor(String s){} /** * 判断能否移动到Point处 * * @param point 想要移动到的点位 * @return 能否移动 */ public abstract boolean canMove(Point point, PanelBase panel); public void resetPath(){ this.path = Constants.STYLE_PATH + File.separator + Style.getStyle(style) + File.separator + name + color + ".png"; } @Deprecated public static boolean canMove(Point oldPoint, Point targetPoint, PanelBase panel){ return false; }; public boolean isDoubleMove(){ return false; } public void setDoubleMove(boolean flag){ } }
0
46976_0
package web; import my_music.*; import java.util.ArrayList; import java.util.List; public class Constants { public static MusicDemo ErGe = new MusicDemo("快乐儿歌","无","佚名",0,0); public final static MusicDemo Jiangjunling = new MusicDemo("将军令","五月天", "YOUR LEGEND ~燃烧的生命~", 0,0); private static final User u1 = new User("Spark", "12121", "000", 0); private static final User u2 = new User("降临者", "12121", "000", 0); public static List<MusicDemo> musicLists = getMusicLists(); public static List<MusicDemo> getMusicLists(){ ArrayList<MusicDemo> musicDemos = new ArrayList<>(); Comments comments = new Comments(); //一些例子 comments.put(new SingleComment(u1, "太打动我了这首曲子!", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(u2, "一个小评论!", new MyDate(2023,4,30,0,16,52))); comments.put(new SingleComment(u1, "这是一个评论", new MyDate(2023,1,30,14,23,12))); comments.put(new SingleComment(u1, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2022,11,6,13,11,52))); comments.put(new SingleComment(u1, "这是依然一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(u2, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(new User("Knight", "16121", "000", 0), "好听", new MyDate(2023,4,30,0,11,52))); musicDemos.add(ErGe); Jiangjunling.setComments(comments); musicDemos.add(Jiangjunling); MusicDemo demo = new MusicDemo("转眼", "五月天", "自传", 0, 0); demo.setComments(new Comments(new SingleComment(u1, "泪目", new MyDate(2022,10,14,16,29,4)))); musicDemos.add(demo); musicDemos.add(new MusicDemo("兄弟","五月天","自传", 0,0)); musicDemos.add(new MusicDemo("顽固","五月天","自传", 0,0)); musicDemos.add(new MusicDemo("派对动物","五月天","自传",0,0)); musicDemos.add(new MusicDemo("干杯","五月天","第二人生-明日版",0,0)); return musicDemos; } }
Ethylene9160/SUSTC_EE317_Android_applications
musicPlayer/src_server/web/Constants.java
814
//一些例子
line_comment
zh-cn
package web; import my_music.*; import java.util.ArrayList; import java.util.List; public class Constants { public static MusicDemo ErGe = new MusicDemo("快乐儿歌","无","佚名",0,0); public final static MusicDemo Jiangjunling = new MusicDemo("将军令","五月天", "YOUR LEGEND ~燃烧的生命~", 0,0); private static final User u1 = new User("Spark", "12121", "000", 0); private static final User u2 = new User("降临者", "12121", "000", 0); public static List<MusicDemo> musicLists = getMusicLists(); public static List<MusicDemo> getMusicLists(){ ArrayList<MusicDemo> musicDemos = new ArrayList<>(); Comments comments = new Comments(); //一些 <SUF> comments.put(new SingleComment(u1, "太打动我了这首曲子!", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(u2, "一个小评论!", new MyDate(2023,4,30,0,16,52))); comments.put(new SingleComment(u1, "这是一个评论", new MyDate(2023,1,30,14,23,12))); comments.put(new SingleComment(u1, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2022,11,6,13,11,52))); comments.put(new SingleComment(u1, "这是依然一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(u2, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(new User("Knight", "16121", "000", 0), "好听", new MyDate(2023,4,30,0,11,52))); musicDemos.add(ErGe); Jiangjunling.setComments(comments); musicDemos.add(Jiangjunling); MusicDemo demo = new MusicDemo("转眼", "五月天", "自传", 0, 0); demo.setComments(new Comments(new SingleComment(u1, "泪目", new MyDate(2022,10,14,16,29,4)))); musicDemos.add(demo); musicDemos.add(new MusicDemo("兄弟","五月天","自传", 0,0)); musicDemos.add(new MusicDemo("顽固","五月天","自传", 0,0)); musicDemos.add(new MusicDemo("派对动物","五月天","自传",0,0)); musicDemos.add(new MusicDemo("干杯","五月天","第二人生-明日版",0,0)); return musicDemos; } }
0
45491_6
package com.rookie.stack.ai.domain.chat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; import lombok.extern.slf4j.Slf4j; import java.io.Serializable; import java.util.List; import java.util.Map; /** * @author eumenides * @description * @date 2023/11/28 */ @Data @Builder @Slf4j @JsonInclude(JsonInclude.Include.NON_NULL) @NoArgsConstructor @AllArgsConstructor public class ChatCompletionRequest implements Serializable { /** 默认模型 */ private String model = Model.GPT_3_5_TURBO.getCode(); /** 问题描述 */ private List<Message> messages; /** 控制温度【随机性】;0到2之间。较高的值(如0.8)将使输出更加随机,而较低的值(如0.2)将使输出更加集中和确定 */ private double temperature = 0.2; /** 多样性控制;使用温度采样的替代方法称为核心采样,其中模型考虑具有top_p概率质量的令牌的结果。因此,0.1 意味着只考虑包含前 10% 概率质量的代币 */ @JsonProperty("top_p") private Double topP = 1d; /** 为每个提示生成的完成次数 */ private Integer n = 1; /** 是否为流式输出;就是一蹦一蹦的,出来结果 */ private boolean stream = false; /** 停止输出标识 */ private List<String> stop; /** 输出字符串限制;0 ~ 4096 */ @JsonProperty("max_tokens") private Integer maxTokens = 2048; /** 频率惩罚;降低模型重复同一行的可能性 */ @JsonProperty("frequency_penalty") private double frequencyPenalty = 0; /** 存在惩罚;增强模型谈论新话题的可能性 */ @JsonProperty("presence_penalty") private double presencePenalty = 0; /** 生成多个调用结果,只显示最佳的。这样会更多的消耗你的 api token */ @JsonProperty("logit_bias") private Map logitBias; /** 调用标识,避免重复调用 */ private String user; @Getter @AllArgsConstructor public enum Model { /** gpt-3.5-turbo */ GPT_3_5_TURBO("gpt-3.5-turbo"), /** GPT4.0 */ GPT_4("gpt-4"), /** GPT4.0 超长上下文 */ GPT_4_32K("gpt-4-32k"), ; private String code; } }
Eumenides1/rookie-gpt-sdk-java
src/main/java/com/rookie/stack/ai/domain/chat/ChatCompletionRequest.java
678
/** 是否为流式输出;就是一蹦一蹦的,出来结果 */
block_comment
zh-cn
package com.rookie.stack.ai.domain.chat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; import lombok.extern.slf4j.Slf4j; import java.io.Serializable; import java.util.List; import java.util.Map; /** * @author eumenides * @description * @date 2023/11/28 */ @Data @Builder @Slf4j @JsonInclude(JsonInclude.Include.NON_NULL) @NoArgsConstructor @AllArgsConstructor public class ChatCompletionRequest implements Serializable { /** 默认模型 */ private String model = Model.GPT_3_5_TURBO.getCode(); /** 问题描述 */ private List<Message> messages; /** 控制温度【随机性】;0到2之间。较高的值(如0.8)将使输出更加随机,而较低的值(如0.2)将使输出更加集中和确定 */ private double temperature = 0.2; /** 多样性控制;使用温度采样的替代方法称为核心采样,其中模型考虑具有top_p概率质量的令牌的结果。因此,0.1 意味着只考虑包含前 10% 概率质量的代币 */ @JsonProperty("top_p") private Double topP = 1d; /** 为每个提示生成的完成次数 */ private Integer n = 1; /** 是否为 <SUF>*/ private boolean stream = false; /** 停止输出标识 */ private List<String> stop; /** 输出字符串限制;0 ~ 4096 */ @JsonProperty("max_tokens") private Integer maxTokens = 2048; /** 频率惩罚;降低模型重复同一行的可能性 */ @JsonProperty("frequency_penalty") private double frequencyPenalty = 0; /** 存在惩罚;增强模型谈论新话题的可能性 */ @JsonProperty("presence_penalty") private double presencePenalty = 0; /** 生成多个调用结果,只显示最佳的。这样会更多的消耗你的 api token */ @JsonProperty("logit_bias") private Map logitBias; /** 调用标识,避免重复调用 */ private String user; @Getter @AllArgsConstructor public enum Model { /** gpt-3.5-turbo */ GPT_3_5_TURBO("gpt-3.5-turbo"), /** GPT4.0 */ GPT_4("gpt-4"), /** GPT4.0 超长上下文 */ GPT_4_32K("gpt-4-32k"), ; private String code; } }
0
29042_0
public class RealSubject implements Subject{ @Override public void eat() {//吃饭 System.out.println("eating"); } }
Euraxluo/ProjectPractice
java/DesignPatternInJAVA/Proxy/src/RealSubject.java
36
//吃饭
line_comment
zh-cn
public class RealSubject implements Subject{ @Override public void eat() {//吃饭 <SUF> System.out.println("eating"); } }
0
56716_0
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList){ if (beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() == 0 || beginWord.length() != endWord.length()) return 0; // 此题关键是去重,还有去除和beginWord,相同的单词 Set<String> set = new HashSet<String>(wordList); if (set.contains(beginWord)) set.remove(beginWord); Queue<String> wordQueue = new LinkedList<String>(); int level = 1; // the start string already count for 1 int curnum = 1;// the candidate num on current level int nextnum = 0;// counter for next level // 或者使用map记录层数 // Map<String, Integer> map = new HashMap<String, Integer>(); // map.put(beginWord, 1); wordQueue.add(beginWord); while (!wordQueue.isEmpty()) { String word = wordQueue.poll(); curnum--; // int curLevel = map.get(word); for (int i = 0; i < word.length(); i++) { char[] wordunit = word.toCharArray(); for (char j = 'a'; j <= 'z'; j++) { wordunit[i] = j; String temp = new String(wordunit); if (set.contains(temp)) { if (temp.equals(endWord)) // return curLevel + 1; return level + 1; // map.put(temp, curLevel + 1); nextnum++; wordQueue.add(temp); set.remove(temp); } } } if (curnum == 0) { curnum = nextnum; nextnum = 0; level++; } } return 0; } }
Eurus-Holmes/LCED
Word Ladder.java
490
// 此题关键是去重,还有去除和beginWord,相同的单词
line_comment
zh-cn
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList){ if (beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() == 0 || beginWord.length() != endWord.length()) return 0; // 此题 <SUF> Set<String> set = new HashSet<String>(wordList); if (set.contains(beginWord)) set.remove(beginWord); Queue<String> wordQueue = new LinkedList<String>(); int level = 1; // the start string already count for 1 int curnum = 1;// the candidate num on current level int nextnum = 0;// counter for next level // 或者使用map记录层数 // Map<String, Integer> map = new HashMap<String, Integer>(); // map.put(beginWord, 1); wordQueue.add(beginWord); while (!wordQueue.isEmpty()) { String word = wordQueue.poll(); curnum--; // int curLevel = map.get(word); for (int i = 0; i < word.length(); i++) { char[] wordunit = word.toCharArray(); for (char j = 'a'; j <= 'z'; j++) { wordunit[i] = j; String temp = new String(wordunit); if (set.contains(temp)) { if (temp.equals(endWord)) // return curLevel + 1; return level + 1; // map.put(temp, curLevel + 1); nextnum++; wordQueue.add(temp); set.remove(temp); } } } if (curnum == 0) { curnum = nextnum; nextnum = 0; level++; } } return 0; } }
0
31939_10
package client.data; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.Scanner; /** * */ public class Txt2Excel { public void txt2excel1() { File file = new File("D:\\学习\\Slime's fighting\\account.txt");// 将读取的txt文件 File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.xls");// 将生成的excel表格 if (file.exists() && file.isFile()) { InputStreamReader read = null; BufferedReader input = null; WritableWorkbook wbook = null; WritableSheet sheet; try { read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); input = new BufferedReader(read); Scanner scanner = new Scanner(read); wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件 sheet = wbook.createSheet("first", 0);// 新标签页 try { Label sName = new Label(0, 0, "");// 如下皆为列名 sheet.addCell(sName); Label account = new Label(0, 0, "用户名");// 如下皆为列名 sheet.addCell(account); Label pass = new Label(1, 0, "密码"); sheet.addCell(pass); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } int m = 1;// excel行数 int n = 0;// excel列数 int count = 0; Label t; while ((scanner.hasNext())) { String word = scanner.next(); t = new Label(n, m, word.trim()); sheet.addCell(t); n++; count++; if (count == 2) { n = 0;// 回到列头部 m++;// 向下移动一行 count = 0; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { wbook.write(); wbook.close(); input.close(); read.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } System.out.println("over!"); } else { System.out.println("file is not exists or not a file"); } } public void txt2excel2() { File file = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.txt");// 将读取的txt文件 File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\game_data.xls");// 将生成的excel表格 if (file.exists() && file.isFile()) { InputStreamReader read = null; BufferedReader input = null; WritableWorkbook wbook = null; WritableSheet sheet; try { read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); input = new BufferedReader(read); Scanner scanner = new Scanner(read); wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件 sheet = wbook.createSheet("first", 0);// 新标签页 try { Label sName = new Label(0, 0, "");// 如下皆为列名 sheet.addCell(sName); Label account = new Label(0, 0, "用户名");// 如下皆为列名 sheet.addCell(account); Label team = new Label(1, 0, "队伍(0绿1蓝)"); sheet.addCell(team); Label blood = new Label(2, 0, "剩余血量"); sheet.addCell(blood); Label time = new Label(3, 0, "在线时长"); sheet.addCell(time); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } int m = 1;// excel行数 int n = 0;// excel列数 int count = 0; Label t; scanner.next(); scanner.next(); scanner.next(); scanner.next(); while ((scanner.hasNext())) { String word = scanner.next(); t = new Label(n, m, word.trim()); sheet.addCell(t); n++; count++; if (count == 4) { n = 0;// 回到列头部 m++;// 向下移动一行 count = 0; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { wbook.write(); wbook.close(); input.close(); read.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } System.out.println("over!"); } else { System.out.println("file is not exists or not a file"); } } }
Evelynn1014/BJTU-cxd-Slime-java-project
client/data/Txt2Excel.java
1,373
// 将读取的txt文件
line_comment
zh-cn
package client.data; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.Scanner; /** * */ public class Txt2Excel { public void txt2excel1() { File file = new File("D:\\学习\\Slime's fighting\\account.txt");// 将读取的txt文件 File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.xls");// 将生成的excel表格 if (file.exists() && file.isFile()) { InputStreamReader read = null; BufferedReader input = null; WritableWorkbook wbook = null; WritableSheet sheet; try { read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); input = new BufferedReader(read); Scanner scanner = new Scanner(read); wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件 sheet = wbook.createSheet("first", 0);// 新标签页 try { Label sName = new Label(0, 0, "");// 如下皆为列名 sheet.addCell(sName); Label account = new Label(0, 0, "用户名");// 如下皆为列名 sheet.addCell(account); Label pass = new Label(1, 0, "密码"); sheet.addCell(pass); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } int m = 1;// excel行数 int n = 0;// excel列数 int count = 0; Label t; while ((scanner.hasNext())) { String word = scanner.next(); t = new Label(n, m, word.trim()); sheet.addCell(t); n++; count++; if (count == 2) { n = 0;// 回到列头部 m++;// 向下移动一行 count = 0; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { wbook.write(); wbook.close(); input.close(); read.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } System.out.println("over!"); } else { System.out.println("file is not exists or not a file"); } } public void txt2excel2() { File file = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.txt");// 将读 <SUF> File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\game_data.xls");// 将生成的excel表格 if (file.exists() && file.isFile()) { InputStreamReader read = null; BufferedReader input = null; WritableWorkbook wbook = null; WritableSheet sheet; try { read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); input = new BufferedReader(read); Scanner scanner = new Scanner(read); wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件 sheet = wbook.createSheet("first", 0);// 新标签页 try { Label sName = new Label(0, 0, "");// 如下皆为列名 sheet.addCell(sName); Label account = new Label(0, 0, "用户名");// 如下皆为列名 sheet.addCell(account); Label team = new Label(1, 0, "队伍(0绿1蓝)"); sheet.addCell(team); Label blood = new Label(2, 0, "剩余血量"); sheet.addCell(blood); Label time = new Label(3, 0, "在线时长"); sheet.addCell(time); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } int m = 1;// excel行数 int n = 0;// excel列数 int count = 0; Label t; scanner.next(); scanner.next(); scanner.next(); scanner.next(); while ((scanner.hasNext())) { String word = scanner.next(); t = new Label(n, m, word.trim()); sheet.addCell(t); n++; count++; if (count == 4) { n = 0;// 回到列头部 m++;// 向下移动一行 count = 0; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { wbook.write(); wbook.close(); input.close(); read.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } System.out.println("over!"); } else { System.out.println("file is not exists or not a file"); } } }
0
48204_5
package com.ygkj.river.model; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.Date; import java.util.List; /** * @author xq * @description 河长/湖长基础信息表 * @date 2021-08-04 */ @Data @ApiModel("河长/湖长基础信息表") public class AttRivLkChiefBase implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @ApiModelProperty("id") private String id; /** * 真实姓名 */ @ApiModelProperty("真实姓名") private String realName; /** * 手机号 */ @ApiModelProperty("手机号") private String phone; /** * 职务 */ @ApiModelProperty("职务") private String post; /** * 等级2:省级;3:市级;4:县级;5:镇级;6:村级 */ @ApiModelProperty("等级2:省级;3:市级;4:县级;5:镇级;6:村级") private Integer level; /** * type=1时,身份1:河长;2:督察;5:警长 * type=2时,类型[1:库长;2:湖长;3:督察长] */ @ApiModelProperty("type=1时,身份1:河长;2:督察;5:警长" + "/type=2时,类型[1:库长;2:湖长;3:督察长]") private Integer rpost; /** * 所属地区 */ @ApiModelProperty("所属地区") private String pathStr; /** * 所管河段 */ @ApiModelProperty("所管河段") private String riverName; /** * 管理湖库信息 */ @ApiModelProperty("管理湖库信息") private String reservoirName; /** * 创建时间 */ @ApiModelProperty("创建时间") private Date createTime; /** * 创建人 */ @ApiModelProperty("创建人") private String createId; /** * 修改时间 */ @ApiModelProperty("修改时间") private Date updateTime; /** * 修改人 */ @ApiModelProperty("修改人") private String updateId; /** * 是否删除 0-未删除 1-已删除 */ @ApiModelProperty("是否删除 0-未删除 1-已删除") private Integer delFlag; /** * 1,河长/警长 信息;2,湖/库长信息 */ @ApiModelProperty("1,河长/警长 信息;2,湖/库长信息") private Integer type; public AttRivLkChiefBase() { } }
EvilIrving/all-of-demo
ygkj/Lucheng_Comprehensive_Digital_Management/service/api/river-api/src/main/java/com/ygkj/river/model/AttRivLkChiefBase.java
692
/** * 等级2:省级;3:市级;4:县级;5:镇级;6:村级 */
block_comment
zh-cn
package com.ygkj.river.model; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.Date; import java.util.List; /** * @author xq * @description 河长/湖长基础信息表 * @date 2021-08-04 */ @Data @ApiModel("河长/湖长基础信息表") public class AttRivLkChiefBase implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @ApiModelProperty("id") private String id; /** * 真实姓名 */ @ApiModelProperty("真实姓名") private String realName; /** * 手机号 */ @ApiModelProperty("手机号") private String phone; /** * 职务 */ @ApiModelProperty("职务") private String post; /** * 等级2 <SUF>*/ @ApiModelProperty("等级2:省级;3:市级;4:县级;5:镇级;6:村级") private Integer level; /** * type=1时,身份1:河长;2:督察;5:警长 * type=2时,类型[1:库长;2:湖长;3:督察长] */ @ApiModelProperty("type=1时,身份1:河长;2:督察;5:警长" + "/type=2时,类型[1:库长;2:湖长;3:督察长]") private Integer rpost; /** * 所属地区 */ @ApiModelProperty("所属地区") private String pathStr; /** * 所管河段 */ @ApiModelProperty("所管河段") private String riverName; /** * 管理湖库信息 */ @ApiModelProperty("管理湖库信息") private String reservoirName; /** * 创建时间 */ @ApiModelProperty("创建时间") private Date createTime; /** * 创建人 */ @ApiModelProperty("创建人") private String createId; /** * 修改时间 */ @ApiModelProperty("修改时间") private Date updateTime; /** * 修改人 */ @ApiModelProperty("修改人") private String updateId; /** * 是否删除 0-未删除 1-已删除 */ @ApiModelProperty("是否删除 0-未删除 1-已删除") private Integer delFlag; /** * 1,河长/警长 信息;2,湖/库长信息 */ @ApiModelProperty("1,河长/警长 信息;2,湖/库长信息") private Integer type; public AttRivLkChiefBase() { } }
1
16451_1
package db.log.sim; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.telephony.TelephonyManager; import lombok.Data; /** * @Author : YangFan * @Date : 2020年11月19日 10:10 * @effect : 获取sim卡、手机号 */ @Data public class Phone { private Context context; private TelephonyManager telephonyManager; public Phone(Context context) { this.context = context; telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); } /** * READ_PHONE_STATE * @return 是否有读取手机状态的权限 * 电话 READ_PHONE_STATE 危险 允许对电话状态进行只读访问,包括设备的电话号码,当前蜂窝网络信息,任何正在进行的呼叫的状态以及设备上注册的任何PhoneAccounts列表 * 电话 CALL_PHONE 危险 允许应用程序在不通过拨号器用户界面的情况下发起电话呼叫,以便用户确认呼叫 * 电话 READ_CALL_LOG 危险 允许应用程序读取用户的通话记录 * 电话 WRITE_CALL_LOG 危险 允许应用程序写入(但不读取)用户的呼叫日志数据 * 电话 ADD_VOICEMAIL 危险 允许应用程序将语音邮件添加到系统中 * 电话 USE_SIP 危险 允许应用程序使用SIP服务 * 电话 PROCESS_OUTGOING_CALLS 危险 允许应用程序查看拨出呼叫期间拨打的号码,并选择将呼叫重定向到其他号码或完全中止呼叫 * 耗时3ms左右 */ //获取SIM卡iccid public String getIccid() { String iccid = "N/A"; iccid = telephonyManager.getSimSerialNumber(); return iccid; } //获取电话号码 public String getNativePhoneNumber() { String nativePhoneNumber = "N/A"; if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return nativePhoneNumber; } nativePhoneNumber = telephonyManager.getLine1Number(); return nativePhoneNumber; } }
EvolvedHumans/EdgeAgent
CPE1/app/src/main/java/db/log/sim/Phone.java
736
/** * READ_PHONE_STATE * @return 是否有读取手机状态的权限 * 电话 READ_PHONE_STATE 危险 允许对电话状态进行只读访问,包括设备的电话号码,当前蜂窝网络信息,任何正在进行的呼叫的状态以及设备上注册的任何PhoneAccounts列表 * 电话 CALL_PHONE 危险 允许应用程序在不通过拨号器用户界面的情况下发起电话呼叫,以便用户确认呼叫 * 电话 READ_CALL_LOG 危险 允许应用程序读取用户的通话记录 * 电话 WRITE_CALL_LOG 危险 允许应用程序写入(但不读取)用户的呼叫日志数据 * 电话 ADD_VOICEMAIL 危险 允许应用程序将语音邮件添加到系统中 * 电话 USE_SIP 危险 允许应用程序使用SIP服务 * 电话 PROCESS_OUTGOING_CALLS 危险 允许应用程序查看拨出呼叫期间拨打的号码,并选择将呼叫重定向到其他号码或完全中止呼叫 * 耗时3ms左右 */
block_comment
zh-cn
package db.log.sim; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.telephony.TelephonyManager; import lombok.Data; /** * @Author : YangFan * @Date : 2020年11月19日 10:10 * @effect : 获取sim卡、手机号 */ @Data public class Phone { private Context context; private TelephonyManager telephonyManager; public Phone(Context context) { this.context = context; telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); } /** * REA <SUF>*/ //获取SIM卡iccid public String getIccid() { String iccid = "N/A"; iccid = telephonyManager.getSimSerialNumber(); return iccid; } //获取电话号码 public String getNativePhoneNumber() { String nativePhoneNumber = "N/A"; if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return nativePhoneNumber; } nativePhoneNumber = telephonyManager.getLine1Number(); return nativePhoneNumber; } }
0
39788_37
package com.ranni.naming; import javax.naming.*; import javax.naming.directory.*; import java.io.*; import java.net.URI; import java.util.*; /** * Title: HttpServer * Description: * 文件资源容器 * JNDI中的context * * @Author 2Executioner * @Email 1205878539@qq.com * @Date 2022-04-06 19:06 */ public class FileDirContext extends BaseDirContext { protected static final int BUFFER_SIZE = 2048; // 缓冲区大小 protected File base; // 文件夹根目录 protected String absoluteBase; // 文档根目录的绝对路径 protected boolean caseSensitive = true; // 是否检查绝对路径的规范性 protected boolean allowLinking = false; // 是否允许连接 public FileDirContext() { } public FileDirContext(Hashtable env) { super(env); } /** * 释放资源 */ public void release() { caseSensitive = true; allowLinking = false; absoluteBase = null; base = null; } /** * 设置文档根目录的绝对路径 * * @param docBase */ @Override public void setDocBase(String docBase) { if (docBase == null) throw new IllegalArgumentException("文件夹路径不能为空!"); base = new File(docBase); try { // 取得规范文件,即将".", "..", "./"这种表示方法解析后返回以绝对路径表示形式的文件 base = base.getCanonicalFile(); } catch (IOException e) { e.printStackTrace(); } // 文件不存在、不是目录、不能读,这些情况将抛出异常 if (!base.exists() || !base.isDirectory() || !base.canRead()) throw new IllegalArgumentException("文件目录异常 " + docBase); this.absoluteBase = base.getAbsolutePath(); super.setDocBase(docBase); } /** * 先取得资源,再取得资源属性 * 此方法返回的也是得到的文件的新的属性,故不存在文件被修改了,但是程序不知道的情况 * * @param name * @param attrIds * @return * @throws NamingException */ @Override public Attributes getAttributes(String name, String[] attrIds) throws NamingException { File file = file(name); if (file == null) throw new NamingException("资源未找到! name:" + name); return new FileResourceAttributes(file); } /** * 取得文件 * 每次返回的都是一个新的文件对象,所以此方法不存在文件被修改了,但是程序还不知道的情况 * * @see {@link File#getCanonicalPath()} 关于此方法的说明如下: * 假设有个index.html文件的绝对路径为 E:\JavaProject\project\HttpServer\processor\index.html * 在E:\JavaProject\project\HttpServer下有个Test类想访问此index.html文件 * Test类使用相对路径 File file = new File("./processor/index.html"); 来取得该文件 * file.getAbsolutePath(); 的结果为 E:\JavaProject\project\HttpServer\.\processor\index.html * file.getCanonicalPath(); 的结果为 E:\JavaProject\project\HttpServer\processor\index.html * 可以看到 getCanonicalPath() 方法会把相对路径中的 "." 去掉(查看该方法的说明 ".." 也能去掉)然后得到 * 规范路径名(规范路径名同时也是绝对路径名,但是绝对路径名不一定是规范路径名)。 * * @param name * @return */ protected File file(String name) { File file = new File(base, name); if (file.exists() && file.canRead()) { // 取得规范路径 String canPath = null; try { canPath = file.getCanonicalPath(); } catch (IOException e) { ; } if (canPath == null) return null; // 如果不允许连接且路径不是以绝对基本路径开头那将返回null if (!allowLinking && !canPath.startsWith(absoluteBase)) return null; // 检查绝对路径是否是规范路径 if (caseSensitive) { String absPath = file.getAbsolutePath(); if (absPath.endsWith(".")) absPath += "/"; absPath = normalize(absPath); canPath = normalize(canPath); if (canPath == null || absPath == null) return null; if (absoluteBase.length() < absPath.length() && absoluteBase.length() < canPath.length()) { absPath = absPath.substring(absoluteBase.length() + 1); canPath = canPath.substring(absoluteBase.length() + 1); if ("".equals(absPath)) absPath = "/"; if ("".equals(canPath)) canPath = "/"; if (!canPath.equals(absPath)) return null; } } } else { return null; } return file; } /** * 规范化文件路径,开头必须有个/ * \ => / * 连续/ => / * /./ => / * /../ => 向上返回一级之后变成/ * * 例子:\root//a/../b/./c\\\e///a/d//v * 规范化后:/root/b/c/e/a/d/v * * 用栈优化原本的字符串拼接 * * @param path * @return */ protected String normalize(String path) { char[] chars = path.toCharArray(); Deque<Character> deque = new LinkedList<>(); for (int i = 0; i < chars.length; i++) { char ch = chars[i]; if (ch == '\\') { if (!deque.isEmpty() && deque.peekLast() != '/') { deque.addLast('/'); } } else if (ch == '.') { // 检索后面两位 if (i < chars.length - 1) { if (chars[i + 1] == '/') { i++; } else if (chars[i + 1] == '.') { if (i < chars.length - 2 && chars[i + 2] == '/') { // 弹出一个目录 deque.pollLast(); // 弹出之前压入的 / while (!deque.isEmpty() && deque.peekLast() != '/') deque.pollLast(); } i += 2; } } } else if (ch == '/') { if (deque.peekLast() != null && deque.peekLast() != '/') deque.addLast('/'); } else { deque.addLast(ch); } } if (deque.isEmpty()) return null; StringBuilder sb = new StringBuilder(deque.size() + 1); // 预留一个开头 / 的空间 if (deque.getFirst() != '/') sb.append('/'); for (char ch : deque) sb.append(ch); return sb.toString(); } /** * 暂不支持该操作 * * @param name * @param mod_op * @param attrs * @throws NamingException */ @Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param mods * @throws NamingException */ @Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); } /** * 绑定资源 * * @param name * @param obj * @param attrs * @throws NamingException */ @Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException("资源已绑定! " + name); rebind(name, obj, attrs); } /** * 正儿八经开始绑定资源 * 此实现类的该方法不支持自定义属性,所以attrs参数无用 * 如果需要绑定的对象是个目录,那么就删除原来name对应的资源并创建一个名字为变量name的空文件夹 * XXX 这个鸡儿卵方法是个狗屎,后面一定要改 * * @param name 资源名 * @param obj 需要绑定的对象 * @param attrs 自定义属性,但在该方法中无用 * @throws NamingException */ @Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { File file = new File(base, name); InputStream is = null; if (obj instanceof Resource) { try { is = ((Resource) obj).streamContent(); } catch (IOException e) { ; } } else if (obj instanceof InputStream) { is = (InputStream) obj; } else if (obj instanceof DirContext) { // 如果需要绑定的对象是个目录 // 那么就删除原来name对应的资源并创建一个名字为变量name的空文件夹 if (file.exists()) { if (!file.delete()) throw new NamingException("资源绑定失败(资源已存在且删除失败)! " + name); } if (!file.mkdir()) throw new NamingException("资源绑定失败(文件夹创建失败)! " + name); } if (is == null) throw new NamingException("资源绑定失败(未取得输入流) " + name); // 将obj中的内容写入到file中 byte[] buffer = new byte[BUFFER_SIZE]; int len = -1; try (FileOutputStream os = new FileOutputStream(file)) { while (true) { len = is.read(buffer); if (len < 0) break; os.write(buffer,0, len); } } catch (IOException e) { throw new NamingException("资源绑定失败! " + e); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 创建子容器 * * @param name * @param attrs 不支持自定义属性,此参数无用 * @return * @throws NamingException */ @Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException("资源已存在! " + name); if (!file.mkdir()) throw new NamingException("资源创建失败! " + name); return (DirContext) lookup(name); } /** * 暂不支持该操作 * * @param name * @return * @throws NamingException */ @Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @return * @throws NamingException */ @Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param matchingAttributes * @param attributesToReturn * @return * @throws NamingException */ @Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param matchingAttributes * @return * @throws NamingException */ @Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param filter * @param cons * @return * @throws NamingException */ @Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param filterExpr * @param filterArgs * @param cons * @return * @throws NamingException */ @Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); } /** * 检索并创建对象 * * @param name * @return * @throws NamingException */ @Override public Object lookup(String name) throws NamingException { Object res = null; File file = file(name); // 取得文件 if (file == null) throw new NamingException("资源不存在! " + name); if (file.isDirectory()) { // 如果是目录,则作为FileDirContext返回 FileDirContext fileDirContext = new FileDirContext(env); fileDirContext.setDocBase(file.getPath()); res = fileDirContext; } else { // 不是目录,作为文件资源返回 res = new FileResource(file); } return res; } /** * 解绑 * 就是文件存在就删除文件,不存在就抛出异常 * * @param name * @throws NamingException */ @Override public void unbind(String name) throws NamingException { File file = file(name); if (file == null) throw new NamingException("资源不存在! " + name); if (!file.delete()) throw new NamingException("资源删除失败! " + name); } /** * 重命名 * * @param oldName * @param newName * @throws NamingException */ @Override public void rename(String oldName, String newName) throws NamingException { File file = file(oldName); if (file == null) throw new NamingException("资源不存在! " + oldName); File newFile = new File(base, newName); file.renameTo(newFile); // 重命名资源 } /** * 得到传入的File文件夹中的资源 * 如果该资源是个目录,则将该资源封装成FileDirContext对象后存入集合 * 如果该资源是个文件,则将该资源封装成FileResource对象后存入集合 * * @param file * @return 返回一个线程安全的集合 {@link Collections#synchronizedList(List)} */ protected List<NamingEntry> list(File file) { // 取得一个线程安全的集合 List<NamingEntry> list = Collections.synchronizedList(new ArrayList<>()); if (!file.isDirectory()) return list; String[] names = file.list(); Arrays.sort(names); if (names == null) return list; NamingEntry entry = null; Object o = null; for (int i = 0; i < names.length; i++) { File currentFile = new File(file, names[i]); if (currentFile.isDirectory()) { // 当前文件是个目录,那就生成一个目录容器 FileDirContext fileDirContext = new FileDirContext(env); fileDirContext.setDocBase(currentFile.getPath()); o = fileDirContext; } else { o = new FileResource(currentFile); } entry = new NamingEntry(names[i], o, NamingEntry.ENTRY); list.add(entry); } return list; } /** * 返回文件夹中文件集合的迭代器 * 迭代器中的元素是{@link NameClassPair}包装类 * * @param name * @return * @throws NamingException */ @Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { File file = file(name); if (file == null) throw new NamingException("资源不存在! " + name); List<NamingEntry> list = list(file); return new NamingContextEnumeration<>(list); } /** * 返回绑定的资源集合的迭代器 * 迭代器中的元素是{@link Binding}包装类 * 同 {@link FileDirContext#list(String)} 类似 * * @param name * @return * @throws NamingException */ @Override public NamingEnumeration<Binding> listBindings(String name) throws NamingException { File file = file(name); if (file == null) throw new NamingException("资源不存在! " + name); List<NamingEntry> list = list(file); return new NamingContextEnumeration<>(list); } /** * 销毁子容器,直接就是解绑 * * @param name * @throws NamingException */ @Override public void destroySubcontext(String name) throws NamingException { unbind(name); } /** * 创建子容器 * * @param name * @return * @throws NamingException */ @Override public Context createSubcontext(String name) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException("资源已存在! " + name); if (!file.mkdir()) throw new NamingException("资源创建失败! " + name); return (Context) lookup(name); } /** * 不支持连接,这里直接调用{@link FileDirContext#lookup(String)} * * @param name * @return * @throws NamingException */ @Override public Object lookupLink(String name) throws NamingException { return lookup(name); } /** * 返回文件夹根目录 * * @return * @throws NamingException */ @Override public String getNameInNamespace() throws NamingException { return this.docBase; } /** * 返回文件根目录 * * @return */ public File getBase() { return base; } /** * 文件资源属性内部类 */ protected class FileResourceAttributes extends ResourceAttributes { protected File file; // 资源文件 protected boolean accessed; // 是否访问过子资源 public FileResourceAttributes(File file) { this.file = file; } /** * 是否是目录。 * 如果是目录,则将accessed标志位置为true * * @return */ @Override public boolean isCollection() { if (!accessed) { collection = file.isDirectory(); accessed = true; } return super.isCollection(); } /** * 获取内容长度 * * @return */ @Override public long getContentLength() { if (contentLength != -1L) return contentLength; contentLength = file.length(); return contentLength; } /** * 取得文件的创建时间 * * @return */ @Override public long getCreation() { if (creation != -1L) return creation; creation = file.lastModified(); return creation; } /** * 取得文件的创建日期 * * @return */ @Override public Date getCreationDate() { if (creation == -1L) creation = file.lastModified(); return super.getCreationDate(); } /** * 取得最后一次修改的时间 * * @return */ @Override public long getLastModified() { if (lastModified != -1L) return lastModified; lastModified = file.lastModified(); return lastModified; } /** * 取得最后一次修改的日期 * * @return */ @Override public Date getLastModifiedDate() { if (lastModified == -1L) lastModified = file.lastModified(); return super.getLastModifiedDate(); } /** * 取得名字 * * @return */ @Override public String getName() { if (name == null) name = file.getName(); return name; } /** * 取得资源类型 * * @return */ public String getResourceType() { if (!accessed) { collection = file.isDirectory(); accessed = true; } return super.getResourceType(); } } /** * 文件的包装类,以FileDirContext的内部类存在 */ public class FileResource extends Resource { protected File file; public FileResource(File file) { this.file = file; } /** * @return 返回URI */ public URI getURI() { return file.toURI(); } /** * 取得输入流 * 如果binaryContent为null,则说明没有把文件内容存入到数组中 * 那么即使inputStream不为null,也很可能这个流已经被用过并关闭掉了 * 所以只要没有把文件内容缓存下来,每次外部请求取得文件的输入流时就要新创建一个输入流对象 * * @return * @throws IOException */ @Override public InputStream streamContent() throws IOException { if (binaryContent == null) return new FileInputStream(file); return super.streamContent(); } } }
Executioner2/http-server
src/main/java/com/ranni/naming/FileDirContext.java
4,966
// 不是目录,作为文件资源返回
line_comment
zh-cn
package com.ranni.naming; import javax.naming.*; import javax.naming.directory.*; import java.io.*; import java.net.URI; import java.util.*; /** * Title: HttpServer * Description: * 文件资源容器 * JNDI中的context * * @Author 2Executioner * @Email 1205878539@qq.com * @Date 2022-04-06 19:06 */ public class FileDirContext extends BaseDirContext { protected static final int BUFFER_SIZE = 2048; // 缓冲区大小 protected File base; // 文件夹根目录 protected String absoluteBase; // 文档根目录的绝对路径 protected boolean caseSensitive = true; // 是否检查绝对路径的规范性 protected boolean allowLinking = false; // 是否允许连接 public FileDirContext() { } public FileDirContext(Hashtable env) { super(env); } /** * 释放资源 */ public void release() { caseSensitive = true; allowLinking = false; absoluteBase = null; base = null; } /** * 设置文档根目录的绝对路径 * * @param docBase */ @Override public void setDocBase(String docBase) { if (docBase == null) throw new IllegalArgumentException("文件夹路径不能为空!"); base = new File(docBase); try { // 取得规范文件,即将".", "..", "./"这种表示方法解析后返回以绝对路径表示形式的文件 base = base.getCanonicalFile(); } catch (IOException e) { e.printStackTrace(); } // 文件不存在、不是目录、不能读,这些情况将抛出异常 if (!base.exists() || !base.isDirectory() || !base.canRead()) throw new IllegalArgumentException("文件目录异常 " + docBase); this.absoluteBase = base.getAbsolutePath(); super.setDocBase(docBase); } /** * 先取得资源,再取得资源属性 * 此方法返回的也是得到的文件的新的属性,故不存在文件被修改了,但是程序不知道的情况 * * @param name * @param attrIds * @return * @throws NamingException */ @Override public Attributes getAttributes(String name, String[] attrIds) throws NamingException { File file = file(name); if (file == null) throw new NamingException("资源未找到! name:" + name); return new FileResourceAttributes(file); } /** * 取得文件 * 每次返回的都是一个新的文件对象,所以此方法不存在文件被修改了,但是程序还不知道的情况 * * @see {@link File#getCanonicalPath()} 关于此方法的说明如下: * 假设有个index.html文件的绝对路径为 E:\JavaProject\project\HttpServer\processor\index.html * 在E:\JavaProject\project\HttpServer下有个Test类想访问此index.html文件 * Test类使用相对路径 File file = new File("./processor/index.html"); 来取得该文件 * file.getAbsolutePath(); 的结果为 E:\JavaProject\project\HttpServer\.\processor\index.html * file.getCanonicalPath(); 的结果为 E:\JavaProject\project\HttpServer\processor\index.html * 可以看到 getCanonicalPath() 方法会把相对路径中的 "." 去掉(查看该方法的说明 ".." 也能去掉)然后得到 * 规范路径名(规范路径名同时也是绝对路径名,但是绝对路径名不一定是规范路径名)。 * * @param name * @return */ protected File file(String name) { File file = new File(base, name); if (file.exists() && file.canRead()) { // 取得规范路径 String canPath = null; try { canPath = file.getCanonicalPath(); } catch (IOException e) { ; } if (canPath == null) return null; // 如果不允许连接且路径不是以绝对基本路径开头那将返回null if (!allowLinking && !canPath.startsWith(absoluteBase)) return null; // 检查绝对路径是否是规范路径 if (caseSensitive) { String absPath = file.getAbsolutePath(); if (absPath.endsWith(".")) absPath += "/"; absPath = normalize(absPath); canPath = normalize(canPath); if (canPath == null || absPath == null) return null; if (absoluteBase.length() < absPath.length() && absoluteBase.length() < canPath.length()) { absPath = absPath.substring(absoluteBase.length() + 1); canPath = canPath.substring(absoluteBase.length() + 1); if ("".equals(absPath)) absPath = "/"; if ("".equals(canPath)) canPath = "/"; if (!canPath.equals(absPath)) return null; } } } else { return null; } return file; } /** * 规范化文件路径,开头必须有个/ * \ => / * 连续/ => / * /./ => / * /../ => 向上返回一级之后变成/ * * 例子:\root//a/../b/./c\\\e///a/d//v * 规范化后:/root/b/c/e/a/d/v * * 用栈优化原本的字符串拼接 * * @param path * @return */ protected String normalize(String path) { char[] chars = path.toCharArray(); Deque<Character> deque = new LinkedList<>(); for (int i = 0; i < chars.length; i++) { char ch = chars[i]; if (ch == '\\') { if (!deque.isEmpty() && deque.peekLast() != '/') { deque.addLast('/'); } } else if (ch == '.') { // 检索后面两位 if (i < chars.length - 1) { if (chars[i + 1] == '/') { i++; } else if (chars[i + 1] == '.') { if (i < chars.length - 2 && chars[i + 2] == '/') { // 弹出一个目录 deque.pollLast(); // 弹出之前压入的 / while (!deque.isEmpty() && deque.peekLast() != '/') deque.pollLast(); } i += 2; } } } else if (ch == '/') { if (deque.peekLast() != null && deque.peekLast() != '/') deque.addLast('/'); } else { deque.addLast(ch); } } if (deque.isEmpty()) return null; StringBuilder sb = new StringBuilder(deque.size() + 1); // 预留一个开头 / 的空间 if (deque.getFirst() != '/') sb.append('/'); for (char ch : deque) sb.append(ch); return sb.toString(); } /** * 暂不支持该操作 * * @param name * @param mod_op * @param attrs * @throws NamingException */ @Override public void modifyAttributes(String name, int mod_op, Attributes attrs) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param mods * @throws NamingException */ @Override public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new OperationNotSupportedException(); } /** * 绑定资源 * * @param name * @param obj * @param attrs * @throws NamingException */ @Override public void bind(String name, Object obj, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException("资源已绑定! " + name); rebind(name, obj, attrs); } /** * 正儿八经开始绑定资源 * 此实现类的该方法不支持自定义属性,所以attrs参数无用 * 如果需要绑定的对象是个目录,那么就删除原来name对应的资源并创建一个名字为变量name的空文件夹 * XXX 这个鸡儿卵方法是个狗屎,后面一定要改 * * @param name 资源名 * @param obj 需要绑定的对象 * @param attrs 自定义属性,但在该方法中无用 * @throws NamingException */ @Override public void rebind(String name, Object obj, Attributes attrs) throws NamingException { File file = new File(base, name); InputStream is = null; if (obj instanceof Resource) { try { is = ((Resource) obj).streamContent(); } catch (IOException e) { ; } } else if (obj instanceof InputStream) { is = (InputStream) obj; } else if (obj instanceof DirContext) { // 如果需要绑定的对象是个目录 // 那么就删除原来name对应的资源并创建一个名字为变量name的空文件夹 if (file.exists()) { if (!file.delete()) throw new NamingException("资源绑定失败(资源已存在且删除失败)! " + name); } if (!file.mkdir()) throw new NamingException("资源绑定失败(文件夹创建失败)! " + name); } if (is == null) throw new NamingException("资源绑定失败(未取得输入流) " + name); // 将obj中的内容写入到file中 byte[] buffer = new byte[BUFFER_SIZE]; int len = -1; try (FileOutputStream os = new FileOutputStream(file)) { while (true) { len = is.read(buffer); if (len < 0) break; os.write(buffer,0, len); } } catch (IOException e) { throw new NamingException("资源绑定失败! " + e); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 创建子容器 * * @param name * @param attrs 不支持自定义属性,此参数无用 * @return * @throws NamingException */ @Override public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException("资源已存在! " + name); if (!file.mkdir()) throw new NamingException("资源创建失败! " + name); return (DirContext) lookup(name); } /** * 暂不支持该操作 * * @param name * @return * @throws NamingException */ @Override public DirContext getSchema(String name) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @return * @throws NamingException */ @Override public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param matchingAttributes * @param attributesToReturn * @return * @throws NamingException */ @Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param matchingAttributes * @return * @throws NamingException */ @Override public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param filter * @param cons * @return * @throws NamingException */ @Override public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); } /** * 暂不支持该操作 * * @param name * @param filterExpr * @param filterArgs * @param cons * @return * @throws NamingException */ @Override public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new OperationNotSupportedException(); } /** * 检索并创建对象 * * @param name * @return * @throws NamingException */ @Override public Object lookup(String name) throws NamingException { Object res = null; File file = file(name); // 取得文件 if (file == null) throw new NamingException("资源不存在! " + name); if (file.isDirectory()) { // 如果是目录,则作为FileDirContext返回 FileDirContext fileDirContext = new FileDirContext(env); fileDirContext.setDocBase(file.getPath()); res = fileDirContext; } else { // 不是 <SUF> res = new FileResource(file); } return res; } /** * 解绑 * 就是文件存在就删除文件,不存在就抛出异常 * * @param name * @throws NamingException */ @Override public void unbind(String name) throws NamingException { File file = file(name); if (file == null) throw new NamingException("资源不存在! " + name); if (!file.delete()) throw new NamingException("资源删除失败! " + name); } /** * 重命名 * * @param oldName * @param newName * @throws NamingException */ @Override public void rename(String oldName, String newName) throws NamingException { File file = file(oldName); if (file == null) throw new NamingException("资源不存在! " + oldName); File newFile = new File(base, newName); file.renameTo(newFile); // 重命名资源 } /** * 得到传入的File文件夹中的资源 * 如果该资源是个目录,则将该资源封装成FileDirContext对象后存入集合 * 如果该资源是个文件,则将该资源封装成FileResource对象后存入集合 * * @param file * @return 返回一个线程安全的集合 {@link Collections#synchronizedList(List)} */ protected List<NamingEntry> list(File file) { // 取得一个线程安全的集合 List<NamingEntry> list = Collections.synchronizedList(new ArrayList<>()); if (!file.isDirectory()) return list; String[] names = file.list(); Arrays.sort(names); if (names == null) return list; NamingEntry entry = null; Object o = null; for (int i = 0; i < names.length; i++) { File currentFile = new File(file, names[i]); if (currentFile.isDirectory()) { // 当前文件是个目录,那就生成一个目录容器 FileDirContext fileDirContext = new FileDirContext(env); fileDirContext.setDocBase(currentFile.getPath()); o = fileDirContext; } else { o = new FileResource(currentFile); } entry = new NamingEntry(names[i], o, NamingEntry.ENTRY); list.add(entry); } return list; } /** * 返回文件夹中文件集合的迭代器 * 迭代器中的元素是{@link NameClassPair}包装类 * * @param name * @return * @throws NamingException */ @Override public NamingEnumeration<NameClassPair> list(String name) throws NamingException { File file = file(name); if (file == null) throw new NamingException("资源不存在! " + name); List<NamingEntry> list = list(file); return new NamingContextEnumeration<>(list); } /** * 返回绑定的资源集合的迭代器 * 迭代器中的元素是{@link Binding}包装类 * 同 {@link FileDirContext#list(String)} 类似 * * @param name * @return * @throws NamingException */ @Override public NamingEnumeration<Binding> listBindings(String name) throws NamingException { File file = file(name); if (file == null) throw new NamingException("资源不存在! " + name); List<NamingEntry> list = list(file); return new NamingContextEnumeration<>(list); } /** * 销毁子容器,直接就是解绑 * * @param name * @throws NamingException */ @Override public void destroySubcontext(String name) throws NamingException { unbind(name); } /** * 创建子容器 * * @param name * @return * @throws NamingException */ @Override public Context createSubcontext(String name) throws NamingException { File file = new File(base, name); if (file.exists()) throw new NameAlreadyBoundException("资源已存在! " + name); if (!file.mkdir()) throw new NamingException("资源创建失败! " + name); return (Context) lookup(name); } /** * 不支持连接,这里直接调用{@link FileDirContext#lookup(String)} * * @param name * @return * @throws NamingException */ @Override public Object lookupLink(String name) throws NamingException { return lookup(name); } /** * 返回文件夹根目录 * * @return * @throws NamingException */ @Override public String getNameInNamespace() throws NamingException { return this.docBase; } /** * 返回文件根目录 * * @return */ public File getBase() { return base; } /** * 文件资源属性内部类 */ protected class FileResourceAttributes extends ResourceAttributes { protected File file; // 资源文件 protected boolean accessed; // 是否访问过子资源 public FileResourceAttributes(File file) { this.file = file; } /** * 是否是目录。 * 如果是目录,则将accessed标志位置为true * * @return */ @Override public boolean isCollection() { if (!accessed) { collection = file.isDirectory(); accessed = true; } return super.isCollection(); } /** * 获取内容长度 * * @return */ @Override public long getContentLength() { if (contentLength != -1L) return contentLength; contentLength = file.length(); return contentLength; } /** * 取得文件的创建时间 * * @return */ @Override public long getCreation() { if (creation != -1L) return creation; creation = file.lastModified(); return creation; } /** * 取得文件的创建日期 * * @return */ @Override public Date getCreationDate() { if (creation == -1L) creation = file.lastModified(); return super.getCreationDate(); } /** * 取得最后一次修改的时间 * * @return */ @Override public long getLastModified() { if (lastModified != -1L) return lastModified; lastModified = file.lastModified(); return lastModified; } /** * 取得最后一次修改的日期 * * @return */ @Override public Date getLastModifiedDate() { if (lastModified == -1L) lastModified = file.lastModified(); return super.getLastModifiedDate(); } /** * 取得名字 * * @return */ @Override public String getName() { if (name == null) name = file.getName(); return name; } /** * 取得资源类型 * * @return */ public String getResourceType() { if (!accessed) { collection = file.isDirectory(); accessed = true; } return super.getResourceType(); } } /** * 文件的包装类,以FileDirContext的内部类存在 */ public class FileResource extends Resource { protected File file; public FileResource(File file) { this.file = file; } /** * @return 返回URI */ public URI getURI() { return file.toURI(); } /** * 取得输入流 * 如果binaryContent为null,则说明没有把文件内容存入到数组中 * 那么即使inputStream不为null,也很可能这个流已经被用过并关闭掉了 * 所以只要没有把文件内容缓存下来,每次外部请求取得文件的输入流时就要新创建一个输入流对象 * * @return * @throws IOException */ @Override public InputStream streamContent() throws IOException { if (binaryContent == null) return new FileInputStream(file); return super.streamContent(); } } }
1
31182_7
/* * SHANGHAI SUNNY EDUCATION, INC. CONFIDENTIAL * * Copyright 2011-2017 Shanghai Sunny Education, Inc. All Rights Reserved. * * NOTICE: All information contained herein is, and remains the property of * Shanghai Sunny Education, Inc. and its suppliers, if any. The intellectual * and technical concepts contained herein are proprietary to Shanghai Sunny * Education, Inc. and its suppliers and may be covered by patents, patents * in process, and are protected by trade secret or copyright law. Dissemination * of this information or reproduction of this material is strictly forbidden * unless prior written permission is obtained from Shanghai Sunny Education, Inc. */ package com.voxlearning.utopia.admin.controller.crm; import com.voxlearning.alps.annotation.meta.AuthenticationState; import com.voxlearning.alps.annotation.meta.ClazzLevel; import com.voxlearning.alps.annotation.meta.SchoolLevel; import com.voxlearning.alps.annotation.meta.SchoolType; import com.voxlearning.alps.annotation.remote.ImportService; import com.voxlearning.alps.calendar.DateUtils; import com.voxlearning.alps.core.util.CollectionUtils; import com.voxlearning.alps.core.util.MapUtils; import com.voxlearning.alps.core.util.StringUtils; import com.voxlearning.alps.lang.convert.SafeConverter; import com.voxlearning.alps.lang.util.MapMessage; import com.voxlearning.alps.runtime.RuntimeMode; import com.voxlearning.raikou.system.api.RaikouSystem; import com.voxlearning.utopia.admin.auth.AuthCurrentAdminUser; import com.voxlearning.utopia.admin.service.crm.CrmSchoolClueService; import com.voxlearning.utopia.admin.service.crm.CrmWorkRecordService; import com.voxlearning.utopia.admin.viewdata.SchoolCheckDetailView; import com.voxlearning.utopia.admin.viewdata.SchoolClueDetailView; import com.voxlearning.utopia.admin.viewdata.SchoolClueView; import com.voxlearning.utopia.api.constant.CrmSchoolClueStatus; import com.voxlearning.utopia.api.constant.EduSystemType; import com.voxlearning.utopia.core.helper.AmapMapApi; import com.voxlearning.utopia.entity.crm.CrmSchoolClue; import com.voxlearning.utopia.service.config.api.CRMConfigService; import com.voxlearning.utopia.service.config.api.constant.ConfigCategory; import com.voxlearning.utopia.service.crm.api.entities.agent.CrmWorkRecord; import com.voxlearning.utopia.service.region.api.entities.extension.ExRegion; import com.voxlearning.utopia.service.school.client.SchoolExtServiceClient; import com.voxlearning.utopia.service.user.api.entities.School; import com.voxlearning.utopia.service.user.api.entities.SchoolExtInfo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.inject.Inject; import java.util.*; import java.util.stream.Collectors; /** * @author Jia HuanYin * @since 2015/11/9 */ @Controller @RequestMapping("/crm/school_clue") public class CrmSchoolClueController extends CrmAbstractController { private static final String SCHOOL_AUTH_OPERATORS = "school_auth_operators"; private static final String SCHOOL_INFO_OPERATORS = "school_info_operators"; private static final String OP_AUTH = "op_auth"; private static final String OP_INFO = "op_info"; private static final String OP_CRITICAL = "op_critical"; private static final String OP_SIGN_IN = "op_sign_in"; private static final Integer PAGE_SIZE = 50; private static final List<Integer> AUTHENTICATE_LIST; static { AUTHENTICATE_LIST = new ArrayList<>(); AUTHENTICATE_LIST.add(1); AUTHENTICATE_LIST.add(4); AUTHENTICATE_LIST.add(5); } @Inject private RaikouSystem raikouSystem; @Inject CrmSchoolClueService crmSchoolClueService; @Inject CrmWorkRecordService crmWorkRecordService; @ImportService(interfaceClass = CRMConfigService.class) private CRMConfigService crmConfigService; @Inject private SchoolExtServiceClient schoolExtServiceClient; @RequestMapping(value = "clue_list.vpage") public String clueList(Model model) { AuthCurrentAdminUser user = getCurrentAdminUser(); // 判断用户是否有学校鉴定权限 boolean schoolAuthOperate = false; String authOperators = crmConfigService.$loadCommonConfigValue(ConfigCategory.PRIMARY_PLATFORM_GENERAL.getType(), SCHOOL_AUTH_OPERATORS); if (authOperators.contains(user.getAdminUserName())) { schoolAuthOperate = true; } // 判断用户是否有信息完善权限 boolean schoolInfoOperate = false; String infoOperators = crmConfigService.$loadCommonConfigValue(ConfigCategory.PRIMARY_PLATFORM_GENERAL.getType(), SCHOOL_INFO_OPERATORS); if (infoOperators.contains(user.getAdminUserName())) { schoolInfoOperate = true; } if (RuntimeMode.isDevelopment()) { schoolAuthOperate = schoolInfoOperate = true; } model.addAttribute("schoolAuthOperate", schoolAuthOperate); model.addAttribute("schoolInfoOperate", schoolInfoOperate); // 没有鉴定,也没有信息完善权限的人走开 if (!schoolAuthOperate && !schoolInfoOperate) { return "crm/school_clue/clue_list"; } // 查询条件 String querySchoolName = getRequestString("schoolName"); // 学校名 Integer checkStatus = getRequestInt("check_status", 1); // 审核状态 Integer authStatus = getRequestInt("auth_status", 1); String updateStart = getRequestString("updateStart"); String updateEnd = getRequestString("updateEnd"); Date updateStartTime = null; if (StringUtils.isNotBlank(updateStart)) { updateStartTime = DateUtils.stringToDate(updateStart + " 00:00:00"); } Date updateEndTime = null; if (StringUtils.isNotBlank(updateEnd)) { updateEndTime = DateUtils.stringToDate(updateEnd + " 23:59:59"); } List<CrmSchoolClue> schoolClues = crmSchoolClueService.loadLocationSchoolClues(querySchoolName, updateStartTime, updateEndTime, checkStatus); Map<Long, List<CrmSchoolClue>> schoolClueMap = schoolClues.stream().collect(Collectors.groupingBy(CrmSchoolClue::getSchoolId, Collectors.toList())); Set<Long> schoolIds = schoolClues.stream().map(CrmSchoolClue::getSchoolId).collect(Collectors.toSet()); List<School> allSchool = new ArrayList<>(); if (authStatus == 1) { allSchool = raikouSystem.loadSchools(schoolIds) .values() .stream() .filter(p -> p.getSchoolAuthenticationState() == AuthenticationState.WAITING) .collect(Collectors.toList()); } if (authStatus == 2) { allSchool = raikouSystem.loadSchools(schoolIds) .values() .stream() .filter(p -> p.getSchoolAuthenticationState() == AuthenticationState.SUCCESS) .collect(Collectors.toList()); } List<SchoolClueView> views = allSchool .stream() .map(p -> createView(p, schoolClueMap.get(p.getId()))) .filter(Objects::nonNull) .collect(Collectors.toList()); model.addAttribute("querySchoolName", querySchoolName); model.addAttribute("authStatus", authStatus); model.addAttribute("checkStatus", checkStatus); model.addAttribute("queryUpdateTimeStart", updateStart); model.addAttribute("queryUpdateTimeEnd", updateEnd); if (CollectionUtils.isNotEmpty(views)) { views.sort((o1, o2) -> (o1.getSchoolUpdateTime().compareTo(o2.getSchoolUpdateTime()))); int pageSize = PAGE_SIZE; int totalPage; if (views.size() % pageSize == 0) { totalPage = views.size() / pageSize; } else { totalPage = views.size() / pageSize + 1; } int number = getRequestInt("PAGE") >= 0 ? getRequestInt("PAGE") : 0; if (number > totalPage - 1) { number = totalPage - 1; } int totalCount = views.size(); int endIndex = (number + 1) * pageSize; if (endIndex > totalCount) { endIndex = totalCount; } List<SchoolClueView> retSchoolClues = views.subList(number * pageSize, endIndex); model.addAttribute("schoolClues", retSchoolClues); Map<String, Integer> pager = new HashMap<>(); pager.put("number", number); pager.put("totalPages", totalPage); pager.put("totalElements", totalCount); model.addAttribute("pager", pager); } return "crm/school_clue/clue_list"; } private SchoolClueView createView(School school, List<CrmSchoolClue> clues) { if (school == null || CollectionUtils.isEmpty(clues)) { return null; } SchoolClueView result = new SchoolClueView(); result.setCmainName(school.getCmainName()); result.setSchoolPhase(SchoolLevel.safeParse(school.getLevel()).getDescription()); result.setShortName(school.getShortName()); result.setSchoolDistrict(school.getSchoolDistrict()); result.setSchoolCreateTime(school.getCreateTime()); result.setId(school.getId()); ExRegion region = raikouSystem.loadRegion(school.getRegionCode()); if (region != null) { result.setProvinceName(region.getProvinceName()); result.setCityName(region.getCityName()); result.setCountyName(region.getCountyName()); } result.setAuthenticationState(school.getSchoolAuthenticationState().getDescription()); clues.sort((o1, o2) -> (o1.getUpdateTime().compareTo(o2.getUpdateTime()))); CrmSchoolClue clue = clues.get(0); result.setSchoolUpdateTime(clue.getUpdateTime()); return result; } @RequestMapping(value = "review_detail.vpage") @ResponseBody public Map<String, Object> reviewDetail() { Long schoolId = getRequestLong("schoolId"); School school = raikouSystem.loadSchool(schoolId); if (school == null) { return MapMessage.errorMessage("学校信息未找到"); } SchoolCheckDetailView view = createSchoolCheckDetailView(school); List<CrmSchoolClue> clues = crmSchoolClueService.loadSchoolByIdIncludeDisabled(schoolId).stream() .filter(p -> !SafeConverter.toBoolean(p.getDisabled())) .filter(p -> AUTHENTICATE_LIST.contains(p.getAuthenticateType())) .collect(Collectors.toList()); view.setClues(clues.stream().map(this::createSchoolClueDetailView).filter(Objects::nonNull).collect(Collectors.toList())); return MapMessage.successMessage().add("view", view); } private SchoolCheckDetailView createSchoolCheckDetailView(School school) { SchoolCheckDetailView view = new SchoolCheckDetailView(); view.setFullName(school.loadSchoolFullName()); view.setSchoolPhase(SchoolLevel.safeParse(school.getLevel()).getDescription()); view.setShortName(school.getShortName()); view.setSchoolCreateDate(school.getCreateTime()); view.setSchoolId(school.getId()); ExRegion region = raikouSystem.loadRegion(school.getRegionCode()); if (region != null) { view.setProvinceName(region.getProvinceName()); view.setCityName(region.getCityName()); view.setCountyName(region.getCountyName()); } view.setAuthenticationState(school.getSchoolAuthenticationState().getDescription()); SchoolExtInfo schoolExtInfo = schoolExtServiceClient.getSchoolExtService().loadSchoolExtInfo(school.getId()).getUninterruptibly(); if (schoolExtInfo != null) { view.setAddress(schoolExtInfo.getAddress()); //view.setEnglishStartGrade(); EduSystemType eduSystemType = schoolExtInfo.fetchEduSystem(); view.setSchoolLength(eduSystemType == null ? "" : eduSystemType.getDescription()); view.setEnglishStartGrade(schoolExtInfo.getEnglishStartGrade() == null ? "" : ClazzLevel.getDescription(schoolExtInfo.getEnglishStartGrade())); view.setSchoolSize(schoolExtInfo.getSchoolSize()); } return view; } private SchoolClueDetailView createSchoolClueDetailView(CrmSchoolClue clue) { if (clue.getAuthenticateType() == null) { return null; } SchoolClueDetailView view = new SchoolClueDetailView(); view.setClueId(clue.getId()); view.setCreateApplyTime(DateUtils.dateToString(clue.getCreateTime())); if (clue.getAuthenticateType() != 2) { view.setCheckStatus(CrmSchoolClueStatus.codeOf(clue.getStatus()) == null ? "" : CrmSchoolClueStatus.codeOf(clue.getStatus()).toString()); } else { view.setCheckStatus(CrmSchoolClueStatus.codeOf(clue.getInfoStatus()) == null ? "" : CrmSchoolClueStatus.codeOf(clue.getInfoStatus()).toString()); } view.setRecorderName(clue.getRecorderName()); view.setRecorderPhone(clue.getRecorderPhone()); view.setPhotoUrl(clue.getPhotoUrl()); view.setLatitude(clue.getLatitude()); view.setLongitude(clue.getLongitude()); view.setDateTime(clue.getDateTime()); view.setAddress(clue.getAddress()); view.setReviewerName(clue.getReviewerName()); view.setReviewTime(clue.getReviewTime() != null ? DateUtils.dateToString(clue.getReviewTime()) : ""); view.setReviewNote(clue.getReviewNote()); view.setUpdateTime(clue.getUpdateTime() != null ? clue.getUpdateTime().getTime() : 0L); return view; } @RequestMapping(value = "review_clue.vpage") @ResponseBody public MapMessage reviewClue() { String id = requestString("id"); Long time = requestLong("updateTime"); CrmSchoolClueStatus reviewStatus = CrmSchoolClueStatus.codeOf(requestInteger("reviewStatus")); String reviewNote = requestString("reviewNote"); String longitude = requestString("longitude"); String latitude = requestString("latitude"); String address = requestString("address"); return crmSchoolClueService.reviewSchoolClue(id, time, reviewStatus, reviewNote, getCurrentAdminUser(), longitude, latitude, address); } // @RequestMapping(value = "clue_list.vpage") public String clueListBak(Model model) { AuthCurrentAdminUser user = getCurrentAdminUser(); // 判断用户是否有学校鉴定权限 boolean schoolAuthOperate = false; String authOperators = crmConfigService.$loadCommonConfigValue(ConfigCategory.PRIMARY_PLATFORM_GENERAL.getType(), SCHOOL_AUTH_OPERATORS); if (authOperators.contains(user.getAdminUserName())) { schoolAuthOperate = true; } // 判断用户是否有信息完善权限 boolean schoolInfoOperate = false; String infoOperators = crmConfigService.$loadCommonConfigValue(ConfigCategory.PRIMARY_PLATFORM_GENERAL.getType(), SCHOOL_INFO_OPERATORS); if (infoOperators.contains(user.getAdminUserName())) { schoolInfoOperate = true; } if (RuntimeMode.isDevelopment()) { schoolAuthOperate = schoolInfoOperate = true; } model.addAttribute("schoolAuthOperate", schoolAuthOperate); model.addAttribute("schoolInfoOperate", schoolInfoOperate); // 没有鉴定,也没有信息完善权限的人走开 if (!schoolAuthOperate && !schoolInfoOperate) { return "crm/school_clue/clue_list"; } // 查询条件 String querySchoolName = getRequestString("schoolName"); // 学校名 String queryCategory = getRequestString("category"); // 类别 Integer queryStatus = getRequestInt("status", 1); // 审核状态 String provinceName = getRequestString("provinceName"); // 省名称 String cityName = getRequestString("cityName"); // 市名城 String recorderName = getRequestString("recorderName"); // 申请人 String createStart = getRequestString("createStart"); String createEnd = getRequestString("createEnd"); String reviewerName = getRequestString("reviewerName"); Date createStartTime = null; if (StringUtils.isNotBlank(createStart)) { createStartTime = DateUtils.stringToDate(createStart + " 00:00:00"); } Date createEndTime = null; if (StringUtils.isNotBlank(createEnd)) { createEndTime = DateUtils.stringToDate(createEnd + " 23:59:59"); } // 检查类别是否正常 if (StringUtils.isNoneBlank(queryCategory) && !OP_AUTH.equals(queryCategory) && !OP_INFO.equals(queryCategory) && !OP_CRITICAL.equals(queryCategory) && !OP_SIGN_IN.equals(queryCategory)) { return "crm/school_clue/clue_list"; } else if ((OP_AUTH.equals(queryCategory) && !schoolAuthOperate) || (OP_INFO.equals(queryCategory) && !schoolInfoOperate) || (OP_CRITICAL.equals(queryCategory) && !schoolAuthOperate) || (OP_SIGN_IN.equals(queryCategory) && !schoolInfoOperate)) { return "crm/school_clue/clue_list"; } List<CrmSchoolClue> retSchoolClues = new ArrayList<>(); int totalCount = 0; List<CrmSchoolClue> schoolClues = new ArrayList<>(); if (schoolAuthOperate && (StringUtils.isBlank(queryCategory) || OP_AUTH.equals(queryCategory))) { // 学校鉴定队列 queryCategory = OP_AUTH; schoolClues = crmSchoolClueService.loadAuthSchoolClues(queryStatus, querySchoolName, provinceName, cityName, recorderName, createStartTime, createEndTime, reviewerName); } else if (schoolAuthOperate && (StringUtils.isBlank(queryCategory) || OP_CRITICAL.equals(queryCategory))) { queryCategory = OP_CRITICAL; schoolClues = crmSchoolClueService.loadCriticalSchoolClues(queryStatus, querySchoolName, provinceName, cityName, recorderName, createStartTime, createEndTime, reviewerName); } else if (schoolInfoOperate && (OP_SIGN_IN.equals(queryCategory))) { queryCategory = OP_SIGN_IN; schoolClues = crmSchoolClueService.loadSignInSchoolClues(queryStatus, querySchoolName, provinceName, cityName, recorderName, createStartTime, createEndTime, reviewerName); } else { // 信息审核队列 queryCategory = OP_INFO; schoolClues = crmSchoolClueService.loadInfoSchoolClues(queryStatus, querySchoolName, provinceName, cityName, recorderName, createStartTime, createEndTime, reviewerName); } if (CollectionUtils.isNotEmpty(schoolClues)) { totalCount = schoolClues.size(); Collections.sort(schoolClues, (o1, o2) -> (o1.getUpdateTime().compareTo(o2.getUpdateTime()))); retSchoolClues.addAll(schoolClues.stream().limit(50).collect(Collectors.toList())); } Set<Long> schoolIdSet = retSchoolClues.stream().map(CrmSchoolClue::getSchoolId).filter(Objects::nonNull).collect(Collectors.toSet()); Map<Long, School> schoolMap = raikouSystem.loadSchools(schoolIdSet); retSchoolClues.forEach(p -> { p.setShowPhase(SchoolLevel.safeParse(p.getSchoolPhase())); p.setShowType(SchoolType.safeParse(p.getSchoolType())); //修改成学校的创建时间 if (p.getSchoolId() != null && schoolMap.get(p.getSchoolId()) != null) { p.setCreateTime(schoolMap.get(p.getSchoolId()).getCreateTime()); } else { p.setCreateTime(null); } }); model.addAttribute("schoolClues", retSchoolClues); model.addAttribute("totalCount", totalCount); model.addAttribute("queryStatus", queryStatus); model.addAttribute("queryCategory", queryCategory); model.addAttribute("querySchoolName", querySchoolName); model.addAttribute("queryProvinceName", provinceName); model.addAttribute("queryCityName", cityName); model.addAttribute("queryRecorderName", recorderName); model.addAttribute("queryReviewerName", reviewerName); model.addAttribute("queryCreateStart", createStart); model.addAttribute("queryCreateEnd", createEnd); return "crm/school_clue/clue_list"; } @RequestMapping(value = "save_base_clue.vpage") @ResponseBody public MapMessage saveBaseClue() { String id = requestString("id"); Integer regionCode = requestInteger("regionCode"); String cmainName = requestString("cmainName"); String schoolDistrict = requestString("schoolDistrict"); Integer schoolPhase = requestInteger("schoolPhase"); String address = requestString("address"); Long time = requestLong("updateTime"); if (StringUtils.isBlank(id) || regionCode == null || StringUtils.isBlank(cmainName) || schoolPhase == null) { return MapMessage.errorMessage("请求参数有误"); } CrmSchoolClue schoolClue = crmSchoolClueService.load(id); if (schoolClue == null) { return MapMessage.errorMessage("学校线索记录不存在"); } if (!isTimeEqual(time, schoolClue.getUpdateTime())) { return MapMessage.errorMessage("学校线索已被修改,请刷新页面后再操作"); } crmSchoolClueService.updateBaseClue(id, regionCode, cmainName, schoolDistrict, address, schoolPhase); return MapMessage.successMessage(); } @RequestMapping(value = "base_clue.vpage") @ResponseBody public CrmSchoolClue baseClue() { String id = requestString("id"); return crmSchoolClueService.load(id); } /* @RequestMapping(value = "review_detail.vpage") @ResponseBody*/ public Map<String, Object> reviewDetailBak() { Map<String, Object> reviewDetail = new HashMap<>(); String id = requestString("id"); CrmSchoolClue schoolClue = crmSchoolClueService.load(id); if (schoolClue != null) { Long schoolId = schoolClue.getSchoolId(); //schoolClue.setSchoolSize(CrmSchoolClueService.countSchoolSize(schoolClue)); schoolClue.setBranchSchoolNames(loadBranchSchoolNames(schoolClue.getBranchSchoolIds())); School school = raikouSystem.loadSchool(schoolClue.getSchoolId()); reviewDetail.put("school", school); if (school != null) { ExRegion region = raikouSystem.loadRegion(school.getRegionCode()); reviewDetail.put("schoolRegion", region); SchoolExtInfo schoolExtInfo = schoolExtServiceClient.getSchoolExtService() .loadSchoolExtInfo(school.getId()) .getUninterruptibly(); if (schoolExtInfo != null) { schoolExtInfo.setBranchSchoolNames(loadBranchSchoolNames(schoolExtInfo.getBranchSchoolIds())); } reviewDetail.put("schoolExtInfo", schoolExtInfo); List<CrmWorkRecord> records = crmWorkRecordService.loadCrmWorkRecordBySchoolId(school.getId()); reviewDetail.put("signPoints", createSignPoint(records)); } Map<String, String> photoMeta = getPhotoMeta(schoolClue); reviewDetail.put("photoMeta", photoMeta); List<CrmSchoolClue> schoolClues = crmSchoolClueService.loadSchoolByIdIncludeDisabled(schoolId).stream() .filter(p -> !Objects.equals(p.getId(), id)) .filter(CrmSchoolClue::isApproved) .filter(p -> StringUtils.isNotBlank(p.getPhotoUrl())).collect(Collectors.toList()); if (schoolClues.size() > 4) { schoolClues = schoolClues.subList(0, 4); } reviewDetail.put("photoList", createPhotoList(schoolClues)); } updateSchoolClueLocationInfoByCoordinateType(schoolClue); reviewDetail.put("schoolClue", schoolClue); return reviewDetail; } private void updateSchoolClueLocationInfoByCoordinateType(CrmSchoolClue schoolClue) { if (Objects.equals(schoolClue.getCoordinateType(), "autonavi")) { return; } MapMessage msg = AmapMapApi.coordinateConvert(schoolClue.getLongitude(), schoolClue.getLatitude(), schoolClue.getCoordinateType()); if (!msg.isSuccess()) { return; } schoolClue.setLongitude(SafeConverter.toString(msg.get("longitude"))); schoolClue.setLatitude(SafeConverter.toString(msg.get("latitude"))); schoolClue.setCoordinateType("autonavi"); } private List<Map<String, String>> createSignPoint(List<CrmWorkRecord> records) { List<Map<String, String>> result = new ArrayList<>(); records.forEach(p -> { if (StringUtils.isNotBlank(p.getLongitude()) && StringUtils.isNotBlank(p.getLatitude())) { Map<String, String> signPoint = new HashMap<>(); signPoint.put("longitude", p.getLongitude()); // 经度 signPoint.put("latitude", p.getLatitude()); // 纬度 signPoint.put("coordinateType", p.getCoordinateType()); // GPS 类型 signPoint.put("createTime", DateUtils.dateToString(p.getCreateTime())); // 时间 result.add(signPoint); } }); coordinatesConvertByCoordinate(result, "wgs84ll"); coordinatesConvertByCoordinate(result, "bd09ll"); return result; } private List<Map<String, String>> createPhotoList(List<CrmSchoolClue> schoolClues) { List<Map<String, String>> result = new ArrayList<>(); schoolClues.forEach(p -> { Map<String, String> photoInfo = new HashMap<>(); photoInfo.put("photoUrl", p.getPhotoUrl()); photoInfo.put("updateTime", DateUtils.dateToString(p.getUpdateTime())); photoInfo.put("longitude", p.getLongitude()); // 经度 photoInfo.put("latitude", p.getLatitude()); // 纬度 photoInfo.put("coordinateType", p.getCoordinateType()); // GPS 类型 result.add(photoInfo); }); coordinatesConvertByCoordinate(result, "wgs84ll"); coordinatesConvertByCoordinate(result, "bd09ll"); return result; } private void coordinatesConvertByCoordinate(List<Map<String, String>> coordinates, String coordinateType) { List<Map<String, String>> points = coordinates.stream().filter(p -> Objects.equals(p.get("coordinateType"), coordinateType)).collect(Collectors.toList()); MapMessage msg = AmapMapApi.coordinatesConvert(AmapMapApi.createCoordinateCollection(points, "longitude", "latitude"), coordinateType); if (!msg.isSuccess()) { return; } List<List<String>> locations = (List<List<String>>) msg.get("locations"); if (CollectionUtils.isEmpty(locations)) { return; } if (points.size() != locations.size()) { return; } for (int i = 0; i < locations.size(); i++) { List<String> locationInfo = locations.get(i); Map<String, String> pointInfo = points.get(i); pointInfo.put("longitude", locationInfo.get(0)); pointInfo.put("latitude", locationInfo.get(1)); } } private Set<String> loadBranchSchoolNames(Set<Long> schoolIds) { if (CollectionUtils.isEmpty(schoolIds)) { return Collections.emptySet(); } Map<Long, School> longSchoolMap = raikouSystem.loadSchools(schoolIds); if (MapUtils.isEmpty(longSchoolMap)) { return Collections.emptySet(); } Collection<School> schools = longSchoolMap.values(); if (CollectionUtils.isEmpty(schools)) { return Collections.emptySet(); } return schools.stream().map(School::getCname).collect(Collectors.toSet()); } private Map<String, String> getPhotoMeta(CrmSchoolClue schoolClue) { Map<String, String> photoMeta = new HashMap<>(); photoMeta.put("Make", ""); photoMeta.put("Model", ""); photoMeta.put("Date/Time", ""); if (schoolClue == null) { return photoMeta; } if (StringUtils.isNotBlank(schoolClue.getMake())) { photoMeta.put("Make", schoolClue.getMake()); photoMeta.put("Model", schoolClue.getModel()); photoMeta.put("Date/Time", schoolClue.getDateTime()); return photoMeta; } photoMeta = crmSchoolClueService.photoMeta(schoolClue.getPhotoUrl()); return photoMeta; } private boolean isTimeEqual(long timestamp, Date targetTime) { return targetTime != null && timestamp == targetTime.getTime(); } }
Explorer1092/vox
utopia-admin/utopia-admin-core/src/main/java/com/voxlearning/utopia/admin/controller/crm/CrmSchoolClueController.java
7,242
// 审核状态
line_comment
zh-cn
/* * SHANGHAI SUNNY EDUCATION, INC. CONFIDENTIAL * * Copyright 2011-2017 Shanghai Sunny Education, Inc. All Rights Reserved. * * NOTICE: All information contained herein is, and remains the property of * Shanghai Sunny Education, Inc. and its suppliers, if any. The intellectual * and technical concepts contained herein are proprietary to Shanghai Sunny * Education, Inc. and its suppliers and may be covered by patents, patents * in process, and are protected by trade secret or copyright law. Dissemination * of this information or reproduction of this material is strictly forbidden * unless prior written permission is obtained from Shanghai Sunny Education, Inc. */ package com.voxlearning.utopia.admin.controller.crm; import com.voxlearning.alps.annotation.meta.AuthenticationState; import com.voxlearning.alps.annotation.meta.ClazzLevel; import com.voxlearning.alps.annotation.meta.SchoolLevel; import com.voxlearning.alps.annotation.meta.SchoolType; import com.voxlearning.alps.annotation.remote.ImportService; import com.voxlearning.alps.calendar.DateUtils; import com.voxlearning.alps.core.util.CollectionUtils; import com.voxlearning.alps.core.util.MapUtils; import com.voxlearning.alps.core.util.StringUtils; import com.voxlearning.alps.lang.convert.SafeConverter; import com.voxlearning.alps.lang.util.MapMessage; import com.voxlearning.alps.runtime.RuntimeMode; import com.voxlearning.raikou.system.api.RaikouSystem; import com.voxlearning.utopia.admin.auth.AuthCurrentAdminUser; import com.voxlearning.utopia.admin.service.crm.CrmSchoolClueService; import com.voxlearning.utopia.admin.service.crm.CrmWorkRecordService; import com.voxlearning.utopia.admin.viewdata.SchoolCheckDetailView; import com.voxlearning.utopia.admin.viewdata.SchoolClueDetailView; import com.voxlearning.utopia.admin.viewdata.SchoolClueView; import com.voxlearning.utopia.api.constant.CrmSchoolClueStatus; import com.voxlearning.utopia.api.constant.EduSystemType; import com.voxlearning.utopia.core.helper.AmapMapApi; import com.voxlearning.utopia.entity.crm.CrmSchoolClue; import com.voxlearning.utopia.service.config.api.CRMConfigService; import com.voxlearning.utopia.service.config.api.constant.ConfigCategory; import com.voxlearning.utopia.service.crm.api.entities.agent.CrmWorkRecord; import com.voxlearning.utopia.service.region.api.entities.extension.ExRegion; import com.voxlearning.utopia.service.school.client.SchoolExtServiceClient; import com.voxlearning.utopia.service.user.api.entities.School; import com.voxlearning.utopia.service.user.api.entities.SchoolExtInfo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.inject.Inject; import java.util.*; import java.util.stream.Collectors; /** * @author Jia HuanYin * @since 2015/11/9 */ @Controller @RequestMapping("/crm/school_clue") public class CrmSchoolClueController extends CrmAbstractController { private static final String SCHOOL_AUTH_OPERATORS = "school_auth_operators"; private static final String SCHOOL_INFO_OPERATORS = "school_info_operators"; private static final String OP_AUTH = "op_auth"; private static final String OP_INFO = "op_info"; private static final String OP_CRITICAL = "op_critical"; private static final String OP_SIGN_IN = "op_sign_in"; private static final Integer PAGE_SIZE = 50; private static final List<Integer> AUTHENTICATE_LIST; static { AUTHENTICATE_LIST = new ArrayList<>(); AUTHENTICATE_LIST.add(1); AUTHENTICATE_LIST.add(4); AUTHENTICATE_LIST.add(5); } @Inject private RaikouSystem raikouSystem; @Inject CrmSchoolClueService crmSchoolClueService; @Inject CrmWorkRecordService crmWorkRecordService; @ImportService(interfaceClass = CRMConfigService.class) private CRMConfigService crmConfigService; @Inject private SchoolExtServiceClient schoolExtServiceClient; @RequestMapping(value = "clue_list.vpage") public String clueList(Model model) { AuthCurrentAdminUser user = getCurrentAdminUser(); // 判断用户是否有学校鉴定权限 boolean schoolAuthOperate = false; String authOperators = crmConfigService.$loadCommonConfigValue(ConfigCategory.PRIMARY_PLATFORM_GENERAL.getType(), SCHOOL_AUTH_OPERATORS); if (authOperators.contains(user.getAdminUserName())) { schoolAuthOperate = true; } // 判断用户是否有信息完善权限 boolean schoolInfoOperate = false; String infoOperators = crmConfigService.$loadCommonConfigValue(ConfigCategory.PRIMARY_PLATFORM_GENERAL.getType(), SCHOOL_INFO_OPERATORS); if (infoOperators.contains(user.getAdminUserName())) { schoolInfoOperate = true; } if (RuntimeMode.isDevelopment()) { schoolAuthOperate = schoolInfoOperate = true; } model.addAttribute("schoolAuthOperate", schoolAuthOperate); model.addAttribute("schoolInfoOperate", schoolInfoOperate); // 没有鉴定,也没有信息完善权限的人走开 if (!schoolAuthOperate && !schoolInfoOperate) { return "crm/school_clue/clue_list"; } // 查询条件 String querySchoolName = getRequestString("schoolName"); // 学校名 Integer checkStatus = getRequestInt("check_status", 1); // 审核 <SUF> Integer authStatus = getRequestInt("auth_status", 1); String updateStart = getRequestString("updateStart"); String updateEnd = getRequestString("updateEnd"); Date updateStartTime = null; if (StringUtils.isNotBlank(updateStart)) { updateStartTime = DateUtils.stringToDate(updateStart + " 00:00:00"); } Date updateEndTime = null; if (StringUtils.isNotBlank(updateEnd)) { updateEndTime = DateUtils.stringToDate(updateEnd + " 23:59:59"); } List<CrmSchoolClue> schoolClues = crmSchoolClueService.loadLocationSchoolClues(querySchoolName, updateStartTime, updateEndTime, checkStatus); Map<Long, List<CrmSchoolClue>> schoolClueMap = schoolClues.stream().collect(Collectors.groupingBy(CrmSchoolClue::getSchoolId, Collectors.toList())); Set<Long> schoolIds = schoolClues.stream().map(CrmSchoolClue::getSchoolId).collect(Collectors.toSet()); List<School> allSchool = new ArrayList<>(); if (authStatus == 1) { allSchool = raikouSystem.loadSchools(schoolIds) .values() .stream() .filter(p -> p.getSchoolAuthenticationState() == AuthenticationState.WAITING) .collect(Collectors.toList()); } if (authStatus == 2) { allSchool = raikouSystem.loadSchools(schoolIds) .values() .stream() .filter(p -> p.getSchoolAuthenticationState() == AuthenticationState.SUCCESS) .collect(Collectors.toList()); } List<SchoolClueView> views = allSchool .stream() .map(p -> createView(p, schoolClueMap.get(p.getId()))) .filter(Objects::nonNull) .collect(Collectors.toList()); model.addAttribute("querySchoolName", querySchoolName); model.addAttribute("authStatus", authStatus); model.addAttribute("checkStatus", checkStatus); model.addAttribute("queryUpdateTimeStart", updateStart); model.addAttribute("queryUpdateTimeEnd", updateEnd); if (CollectionUtils.isNotEmpty(views)) { views.sort((o1, o2) -> (o1.getSchoolUpdateTime().compareTo(o2.getSchoolUpdateTime()))); int pageSize = PAGE_SIZE; int totalPage; if (views.size() % pageSize == 0) { totalPage = views.size() / pageSize; } else { totalPage = views.size() / pageSize + 1; } int number = getRequestInt("PAGE") >= 0 ? getRequestInt("PAGE") : 0; if (number > totalPage - 1) { number = totalPage - 1; } int totalCount = views.size(); int endIndex = (number + 1) * pageSize; if (endIndex > totalCount) { endIndex = totalCount; } List<SchoolClueView> retSchoolClues = views.subList(number * pageSize, endIndex); model.addAttribute("schoolClues", retSchoolClues); Map<String, Integer> pager = new HashMap<>(); pager.put("number", number); pager.put("totalPages", totalPage); pager.put("totalElements", totalCount); model.addAttribute("pager", pager); } return "crm/school_clue/clue_list"; } private SchoolClueView createView(School school, List<CrmSchoolClue> clues) { if (school == null || CollectionUtils.isEmpty(clues)) { return null; } SchoolClueView result = new SchoolClueView(); result.setCmainName(school.getCmainName()); result.setSchoolPhase(SchoolLevel.safeParse(school.getLevel()).getDescription()); result.setShortName(school.getShortName()); result.setSchoolDistrict(school.getSchoolDistrict()); result.setSchoolCreateTime(school.getCreateTime()); result.setId(school.getId()); ExRegion region = raikouSystem.loadRegion(school.getRegionCode()); if (region != null) { result.setProvinceName(region.getProvinceName()); result.setCityName(region.getCityName()); result.setCountyName(region.getCountyName()); } result.setAuthenticationState(school.getSchoolAuthenticationState().getDescription()); clues.sort((o1, o2) -> (o1.getUpdateTime().compareTo(o2.getUpdateTime()))); CrmSchoolClue clue = clues.get(0); result.setSchoolUpdateTime(clue.getUpdateTime()); return result; } @RequestMapping(value = "review_detail.vpage") @ResponseBody public Map<String, Object> reviewDetail() { Long schoolId = getRequestLong("schoolId"); School school = raikouSystem.loadSchool(schoolId); if (school == null) { return MapMessage.errorMessage("学校信息未找到"); } SchoolCheckDetailView view = createSchoolCheckDetailView(school); List<CrmSchoolClue> clues = crmSchoolClueService.loadSchoolByIdIncludeDisabled(schoolId).stream() .filter(p -> !SafeConverter.toBoolean(p.getDisabled())) .filter(p -> AUTHENTICATE_LIST.contains(p.getAuthenticateType())) .collect(Collectors.toList()); view.setClues(clues.stream().map(this::createSchoolClueDetailView).filter(Objects::nonNull).collect(Collectors.toList())); return MapMessage.successMessage().add("view", view); } private SchoolCheckDetailView createSchoolCheckDetailView(School school) { SchoolCheckDetailView view = new SchoolCheckDetailView(); view.setFullName(school.loadSchoolFullName()); view.setSchoolPhase(SchoolLevel.safeParse(school.getLevel()).getDescription()); view.setShortName(school.getShortName()); view.setSchoolCreateDate(school.getCreateTime()); view.setSchoolId(school.getId()); ExRegion region = raikouSystem.loadRegion(school.getRegionCode()); if (region != null) { view.setProvinceName(region.getProvinceName()); view.setCityName(region.getCityName()); view.setCountyName(region.getCountyName()); } view.setAuthenticationState(school.getSchoolAuthenticationState().getDescription()); SchoolExtInfo schoolExtInfo = schoolExtServiceClient.getSchoolExtService().loadSchoolExtInfo(school.getId()).getUninterruptibly(); if (schoolExtInfo != null) { view.setAddress(schoolExtInfo.getAddress()); //view.setEnglishStartGrade(); EduSystemType eduSystemType = schoolExtInfo.fetchEduSystem(); view.setSchoolLength(eduSystemType == null ? "" : eduSystemType.getDescription()); view.setEnglishStartGrade(schoolExtInfo.getEnglishStartGrade() == null ? "" : ClazzLevel.getDescription(schoolExtInfo.getEnglishStartGrade())); view.setSchoolSize(schoolExtInfo.getSchoolSize()); } return view; } private SchoolClueDetailView createSchoolClueDetailView(CrmSchoolClue clue) { if (clue.getAuthenticateType() == null) { return null; } SchoolClueDetailView view = new SchoolClueDetailView(); view.setClueId(clue.getId()); view.setCreateApplyTime(DateUtils.dateToString(clue.getCreateTime())); if (clue.getAuthenticateType() != 2) { view.setCheckStatus(CrmSchoolClueStatus.codeOf(clue.getStatus()) == null ? "" : CrmSchoolClueStatus.codeOf(clue.getStatus()).toString()); } else { view.setCheckStatus(CrmSchoolClueStatus.codeOf(clue.getInfoStatus()) == null ? "" : CrmSchoolClueStatus.codeOf(clue.getInfoStatus()).toString()); } view.setRecorderName(clue.getRecorderName()); view.setRecorderPhone(clue.getRecorderPhone()); view.setPhotoUrl(clue.getPhotoUrl()); view.setLatitude(clue.getLatitude()); view.setLongitude(clue.getLongitude()); view.setDateTime(clue.getDateTime()); view.setAddress(clue.getAddress()); view.setReviewerName(clue.getReviewerName()); view.setReviewTime(clue.getReviewTime() != null ? DateUtils.dateToString(clue.getReviewTime()) : ""); view.setReviewNote(clue.getReviewNote()); view.setUpdateTime(clue.getUpdateTime() != null ? clue.getUpdateTime().getTime() : 0L); return view; } @RequestMapping(value = "review_clue.vpage") @ResponseBody public MapMessage reviewClue() { String id = requestString("id"); Long time = requestLong("updateTime"); CrmSchoolClueStatus reviewStatus = CrmSchoolClueStatus.codeOf(requestInteger("reviewStatus")); String reviewNote = requestString("reviewNote"); String longitude = requestString("longitude"); String latitude = requestString("latitude"); String address = requestString("address"); return crmSchoolClueService.reviewSchoolClue(id, time, reviewStatus, reviewNote, getCurrentAdminUser(), longitude, latitude, address); } // @RequestMapping(value = "clue_list.vpage") public String clueListBak(Model model) { AuthCurrentAdminUser user = getCurrentAdminUser(); // 判断用户是否有学校鉴定权限 boolean schoolAuthOperate = false; String authOperators = crmConfigService.$loadCommonConfigValue(ConfigCategory.PRIMARY_PLATFORM_GENERAL.getType(), SCHOOL_AUTH_OPERATORS); if (authOperators.contains(user.getAdminUserName())) { schoolAuthOperate = true; } // 判断用户是否有信息完善权限 boolean schoolInfoOperate = false; String infoOperators = crmConfigService.$loadCommonConfigValue(ConfigCategory.PRIMARY_PLATFORM_GENERAL.getType(), SCHOOL_INFO_OPERATORS); if (infoOperators.contains(user.getAdminUserName())) { schoolInfoOperate = true; } if (RuntimeMode.isDevelopment()) { schoolAuthOperate = schoolInfoOperate = true; } model.addAttribute("schoolAuthOperate", schoolAuthOperate); model.addAttribute("schoolInfoOperate", schoolInfoOperate); // 没有鉴定,也没有信息完善权限的人走开 if (!schoolAuthOperate && !schoolInfoOperate) { return "crm/school_clue/clue_list"; } // 查询条件 String querySchoolName = getRequestString("schoolName"); // 学校名 String queryCategory = getRequestString("category"); // 类别 Integer queryStatus = getRequestInt("status", 1); // 审核状态 String provinceName = getRequestString("provinceName"); // 省名称 String cityName = getRequestString("cityName"); // 市名城 String recorderName = getRequestString("recorderName"); // 申请人 String createStart = getRequestString("createStart"); String createEnd = getRequestString("createEnd"); String reviewerName = getRequestString("reviewerName"); Date createStartTime = null; if (StringUtils.isNotBlank(createStart)) { createStartTime = DateUtils.stringToDate(createStart + " 00:00:00"); } Date createEndTime = null; if (StringUtils.isNotBlank(createEnd)) { createEndTime = DateUtils.stringToDate(createEnd + " 23:59:59"); } // 检查类别是否正常 if (StringUtils.isNoneBlank(queryCategory) && !OP_AUTH.equals(queryCategory) && !OP_INFO.equals(queryCategory) && !OP_CRITICAL.equals(queryCategory) && !OP_SIGN_IN.equals(queryCategory)) { return "crm/school_clue/clue_list"; } else if ((OP_AUTH.equals(queryCategory) && !schoolAuthOperate) || (OP_INFO.equals(queryCategory) && !schoolInfoOperate) || (OP_CRITICAL.equals(queryCategory) && !schoolAuthOperate) || (OP_SIGN_IN.equals(queryCategory) && !schoolInfoOperate)) { return "crm/school_clue/clue_list"; } List<CrmSchoolClue> retSchoolClues = new ArrayList<>(); int totalCount = 0; List<CrmSchoolClue> schoolClues = new ArrayList<>(); if (schoolAuthOperate && (StringUtils.isBlank(queryCategory) || OP_AUTH.equals(queryCategory))) { // 学校鉴定队列 queryCategory = OP_AUTH; schoolClues = crmSchoolClueService.loadAuthSchoolClues(queryStatus, querySchoolName, provinceName, cityName, recorderName, createStartTime, createEndTime, reviewerName); } else if (schoolAuthOperate && (StringUtils.isBlank(queryCategory) || OP_CRITICAL.equals(queryCategory))) { queryCategory = OP_CRITICAL; schoolClues = crmSchoolClueService.loadCriticalSchoolClues(queryStatus, querySchoolName, provinceName, cityName, recorderName, createStartTime, createEndTime, reviewerName); } else if (schoolInfoOperate && (OP_SIGN_IN.equals(queryCategory))) { queryCategory = OP_SIGN_IN; schoolClues = crmSchoolClueService.loadSignInSchoolClues(queryStatus, querySchoolName, provinceName, cityName, recorderName, createStartTime, createEndTime, reviewerName); } else { // 信息审核队列 queryCategory = OP_INFO; schoolClues = crmSchoolClueService.loadInfoSchoolClues(queryStatus, querySchoolName, provinceName, cityName, recorderName, createStartTime, createEndTime, reviewerName); } if (CollectionUtils.isNotEmpty(schoolClues)) { totalCount = schoolClues.size(); Collections.sort(schoolClues, (o1, o2) -> (o1.getUpdateTime().compareTo(o2.getUpdateTime()))); retSchoolClues.addAll(schoolClues.stream().limit(50).collect(Collectors.toList())); } Set<Long> schoolIdSet = retSchoolClues.stream().map(CrmSchoolClue::getSchoolId).filter(Objects::nonNull).collect(Collectors.toSet()); Map<Long, School> schoolMap = raikouSystem.loadSchools(schoolIdSet); retSchoolClues.forEach(p -> { p.setShowPhase(SchoolLevel.safeParse(p.getSchoolPhase())); p.setShowType(SchoolType.safeParse(p.getSchoolType())); //修改成学校的创建时间 if (p.getSchoolId() != null && schoolMap.get(p.getSchoolId()) != null) { p.setCreateTime(schoolMap.get(p.getSchoolId()).getCreateTime()); } else { p.setCreateTime(null); } }); model.addAttribute("schoolClues", retSchoolClues); model.addAttribute("totalCount", totalCount); model.addAttribute("queryStatus", queryStatus); model.addAttribute("queryCategory", queryCategory); model.addAttribute("querySchoolName", querySchoolName); model.addAttribute("queryProvinceName", provinceName); model.addAttribute("queryCityName", cityName); model.addAttribute("queryRecorderName", recorderName); model.addAttribute("queryReviewerName", reviewerName); model.addAttribute("queryCreateStart", createStart); model.addAttribute("queryCreateEnd", createEnd); return "crm/school_clue/clue_list"; } @RequestMapping(value = "save_base_clue.vpage") @ResponseBody public MapMessage saveBaseClue() { String id = requestString("id"); Integer regionCode = requestInteger("regionCode"); String cmainName = requestString("cmainName"); String schoolDistrict = requestString("schoolDistrict"); Integer schoolPhase = requestInteger("schoolPhase"); String address = requestString("address"); Long time = requestLong("updateTime"); if (StringUtils.isBlank(id) || regionCode == null || StringUtils.isBlank(cmainName) || schoolPhase == null) { return MapMessage.errorMessage("请求参数有误"); } CrmSchoolClue schoolClue = crmSchoolClueService.load(id); if (schoolClue == null) { return MapMessage.errorMessage("学校线索记录不存在"); } if (!isTimeEqual(time, schoolClue.getUpdateTime())) { return MapMessage.errorMessage("学校线索已被修改,请刷新页面后再操作"); } crmSchoolClueService.updateBaseClue(id, regionCode, cmainName, schoolDistrict, address, schoolPhase); return MapMessage.successMessage(); } @RequestMapping(value = "base_clue.vpage") @ResponseBody public CrmSchoolClue baseClue() { String id = requestString("id"); return crmSchoolClueService.load(id); } /* @RequestMapping(value = "review_detail.vpage") @ResponseBody*/ public Map<String, Object> reviewDetailBak() { Map<String, Object> reviewDetail = new HashMap<>(); String id = requestString("id"); CrmSchoolClue schoolClue = crmSchoolClueService.load(id); if (schoolClue != null) { Long schoolId = schoolClue.getSchoolId(); //schoolClue.setSchoolSize(CrmSchoolClueService.countSchoolSize(schoolClue)); schoolClue.setBranchSchoolNames(loadBranchSchoolNames(schoolClue.getBranchSchoolIds())); School school = raikouSystem.loadSchool(schoolClue.getSchoolId()); reviewDetail.put("school", school); if (school != null) { ExRegion region = raikouSystem.loadRegion(school.getRegionCode()); reviewDetail.put("schoolRegion", region); SchoolExtInfo schoolExtInfo = schoolExtServiceClient.getSchoolExtService() .loadSchoolExtInfo(school.getId()) .getUninterruptibly(); if (schoolExtInfo != null) { schoolExtInfo.setBranchSchoolNames(loadBranchSchoolNames(schoolExtInfo.getBranchSchoolIds())); } reviewDetail.put("schoolExtInfo", schoolExtInfo); List<CrmWorkRecord> records = crmWorkRecordService.loadCrmWorkRecordBySchoolId(school.getId()); reviewDetail.put("signPoints", createSignPoint(records)); } Map<String, String> photoMeta = getPhotoMeta(schoolClue); reviewDetail.put("photoMeta", photoMeta); List<CrmSchoolClue> schoolClues = crmSchoolClueService.loadSchoolByIdIncludeDisabled(schoolId).stream() .filter(p -> !Objects.equals(p.getId(), id)) .filter(CrmSchoolClue::isApproved) .filter(p -> StringUtils.isNotBlank(p.getPhotoUrl())).collect(Collectors.toList()); if (schoolClues.size() > 4) { schoolClues = schoolClues.subList(0, 4); } reviewDetail.put("photoList", createPhotoList(schoolClues)); } updateSchoolClueLocationInfoByCoordinateType(schoolClue); reviewDetail.put("schoolClue", schoolClue); return reviewDetail; } private void updateSchoolClueLocationInfoByCoordinateType(CrmSchoolClue schoolClue) { if (Objects.equals(schoolClue.getCoordinateType(), "autonavi")) { return; } MapMessage msg = AmapMapApi.coordinateConvert(schoolClue.getLongitude(), schoolClue.getLatitude(), schoolClue.getCoordinateType()); if (!msg.isSuccess()) { return; } schoolClue.setLongitude(SafeConverter.toString(msg.get("longitude"))); schoolClue.setLatitude(SafeConverter.toString(msg.get("latitude"))); schoolClue.setCoordinateType("autonavi"); } private List<Map<String, String>> createSignPoint(List<CrmWorkRecord> records) { List<Map<String, String>> result = new ArrayList<>(); records.forEach(p -> { if (StringUtils.isNotBlank(p.getLongitude()) && StringUtils.isNotBlank(p.getLatitude())) { Map<String, String> signPoint = new HashMap<>(); signPoint.put("longitude", p.getLongitude()); // 经度 signPoint.put("latitude", p.getLatitude()); // 纬度 signPoint.put("coordinateType", p.getCoordinateType()); // GPS 类型 signPoint.put("createTime", DateUtils.dateToString(p.getCreateTime())); // 时间 result.add(signPoint); } }); coordinatesConvertByCoordinate(result, "wgs84ll"); coordinatesConvertByCoordinate(result, "bd09ll"); return result; } private List<Map<String, String>> createPhotoList(List<CrmSchoolClue> schoolClues) { List<Map<String, String>> result = new ArrayList<>(); schoolClues.forEach(p -> { Map<String, String> photoInfo = new HashMap<>(); photoInfo.put("photoUrl", p.getPhotoUrl()); photoInfo.put("updateTime", DateUtils.dateToString(p.getUpdateTime())); photoInfo.put("longitude", p.getLongitude()); // 经度 photoInfo.put("latitude", p.getLatitude()); // 纬度 photoInfo.put("coordinateType", p.getCoordinateType()); // GPS 类型 result.add(photoInfo); }); coordinatesConvertByCoordinate(result, "wgs84ll"); coordinatesConvertByCoordinate(result, "bd09ll"); return result; } private void coordinatesConvertByCoordinate(List<Map<String, String>> coordinates, String coordinateType) { List<Map<String, String>> points = coordinates.stream().filter(p -> Objects.equals(p.get("coordinateType"), coordinateType)).collect(Collectors.toList()); MapMessage msg = AmapMapApi.coordinatesConvert(AmapMapApi.createCoordinateCollection(points, "longitude", "latitude"), coordinateType); if (!msg.isSuccess()) { return; } List<List<String>> locations = (List<List<String>>) msg.get("locations"); if (CollectionUtils.isEmpty(locations)) { return; } if (points.size() != locations.size()) { return; } for (int i = 0; i < locations.size(); i++) { List<String> locationInfo = locations.get(i); Map<String, String> pointInfo = points.get(i); pointInfo.put("longitude", locationInfo.get(0)); pointInfo.put("latitude", locationInfo.get(1)); } } private Set<String> loadBranchSchoolNames(Set<Long> schoolIds) { if (CollectionUtils.isEmpty(schoolIds)) { return Collections.emptySet(); } Map<Long, School> longSchoolMap = raikouSystem.loadSchools(schoolIds); if (MapUtils.isEmpty(longSchoolMap)) { return Collections.emptySet(); } Collection<School> schools = longSchoolMap.values(); if (CollectionUtils.isEmpty(schools)) { return Collections.emptySet(); } return schools.stream().map(School::getCname).collect(Collectors.toSet()); } private Map<String, String> getPhotoMeta(CrmSchoolClue schoolClue) { Map<String, String> photoMeta = new HashMap<>(); photoMeta.put("Make", ""); photoMeta.put("Model", ""); photoMeta.put("Date/Time", ""); if (schoolClue == null) { return photoMeta; } if (StringUtils.isNotBlank(schoolClue.getMake())) { photoMeta.put("Make", schoolClue.getMake()); photoMeta.put("Model", schoolClue.getModel()); photoMeta.put("Date/Time", schoolClue.getDateTime()); return photoMeta; } photoMeta = crmSchoolClueService.photoMeta(schoolClue.getPhotoUrl()); return photoMeta; } private boolean isTimeEqual(long timestamp, Date targetTime) { return targetTime != null && timestamp == targetTime.getTime(); } }
1
3166_29
package cn.exrick.xboot.common.utils; import cn.exrick.xboot.common.exception.CaptchaException; import cn.hutool.core.util.StrUtil; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.security.SecureRandom; /** * 随机字符验证码生成工具类 * @author Exrickx */ public class CreateVerifyCode { /** * 随机字符 */ public static final String STRING = "ABCDEFGHJKMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz1234567890"; /** * 图片的宽度 */ private int width = 160; /** * 图片的高度 */ private int height = 40; /** * 验证码字符个数 */ private int codeCount = 4; /** * 验证码干扰线数 */ private int lineCount = 20; /** * 验证码 */ private String code = null; /** * 验证码图片Buffer */ private BufferedImage buffImg = null; SecureRandom random = new SecureRandom(); public CreateVerifyCode() { creatImage(); } public CreateVerifyCode(int width, int height) { this.width = width; this.height = height; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount) { this.width = width; this.height = height; this.codeCount = codeCount; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount, int lineCount) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount, int lineCount, String code) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; creatImage(code); } /** * 生成图片 */ private void creatImage() { // 字体的宽度 int fontWidth = width / codeCount; // 字体的高度 int fontHeight = height - 5; int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); //Graphics2D g = buffImg.createGraphics(); // 设置背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设置字体 // Font font1 = getFont(fontHeight); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); // 设置干扰线 for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width); int ye = ys + random.nextInt(height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // 添加噪点 噪声率 float yawpRate = 0.01f; int area = (int) (yawpRate * width * height); for (int i = 0; i < area; i++) { int x = random.nextInt(width); int y = random.nextInt(height); buffImg.setRGB(x, y, random.nextInt(255)); } // 得到随机字符 String str1 = randomStr(codeCount); this.code = str1; for (int i = 0; i < codeCount; i++) { String strRand = str1.substring(i, i + 1); g.setColor(getRandColor(1, 255)); // g.drawString(a,x,y); // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, i * fontWidth + 3, codeY); } } /** * 生成指定字符图片 */ private void creatImage(String code) { if (StrUtil.isBlank(code)) { throw new CaptchaException("验证码为空或已过期,请重新获取"); } // 字体的宽度 int fontWidth = width / codeCount; // 字体的高度 int fontHeight = height - 5; int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); //Graphics2D g = buffImg.createGraphics(); // 设置背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设置字体 //Font font1 = getFont(fontHeight); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); // 设置干扰线 for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width); int ye = ys + random.nextInt(height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // 添加噪点 噪声率 float yawpRate = 0.01f; int area = (int) (yawpRate * width * height); for (int i = 0; i < area; i++) { int x = random.nextInt(width); int y = random.nextInt(height); buffImg.setRGB(x, y, random.nextInt(255)); } this.code = code; for (int i = 0; i < code.length(); i++) { String strRand = code.substring(i, i + 1); g.setColor(getRandColor(1, 255)); // g.drawString(a,x,y); // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, i * fontWidth + 3, codeY); } } /** * 得到随机字符 * @param n * @return */ public String randomStr(int n) { String str = ""; int len = STRING.length() - 1; double r; for (int i = 0; i < n; i++) { r = random.nextDouble() * len; str = str + STRING.charAt((int) r); } return str; } /** * 得到随机颜色 * @param fc * @param bc * @return */ private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色 if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * 产生随机字体 */ private Font getFont(int size) { Font[] font = new Font[5]; font[0] = new Font("Ravie", Font.PLAIN, size); font[1] = new Font("Antique Olive Compact", Font.PLAIN, size); font[2] = new Font("Fixedsys", Font.PLAIN, size); font[3] = new Font("Wide Latin", Font.PLAIN, size); font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size); return font[random.nextInt(5)]; } // 扭曲方法 private void shear(Graphics g, int w1, int h1, Color color) { shearX(g, w1, h1, color); shearY(g, w1, h1, color); } private void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) { g.setColor(color); g.drawLine((int) d, i, 0, i); g.drawLine((int) d + w1, i, w1, i); } } } private void shearY(Graphics g, int w1, int h1, Color color) { // 50 int period = random.nextInt(40) + 10; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } } public void write(OutputStream sos) throws IOException { ImageIO.write(buffImg, "png", sos); sos.close(); } public BufferedImage getBuffImg() { return buffImg; } public String getCode() { return code.toLowerCase(); } }
Exrick/xboot
xboot-fast/src/main/java/cn/exrick/xboot/common/utils/CreateVerifyCode.java
2,567
// 设置干扰线
line_comment
zh-cn
package cn.exrick.xboot.common.utils; import cn.exrick.xboot.common.exception.CaptchaException; import cn.hutool.core.util.StrUtil; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.security.SecureRandom; /** * 随机字符验证码生成工具类 * @author Exrickx */ public class CreateVerifyCode { /** * 随机字符 */ public static final String STRING = "ABCDEFGHJKMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz1234567890"; /** * 图片的宽度 */ private int width = 160; /** * 图片的高度 */ private int height = 40; /** * 验证码字符个数 */ private int codeCount = 4; /** * 验证码干扰线数 */ private int lineCount = 20; /** * 验证码 */ private String code = null; /** * 验证码图片Buffer */ private BufferedImage buffImg = null; SecureRandom random = new SecureRandom(); public CreateVerifyCode() { creatImage(); } public CreateVerifyCode(int width, int height) { this.width = width; this.height = height; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount) { this.width = width; this.height = height; this.codeCount = codeCount; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount, int lineCount) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount, int lineCount, String code) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; creatImage(code); } /** * 生成图片 */ private void creatImage() { // 字体的宽度 int fontWidth = width / codeCount; // 字体的高度 int fontHeight = height - 5; int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); //Graphics2D g = buffImg.createGraphics(); // 设置背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设置字体 // Font font1 = getFont(fontHeight); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); // 设置干扰线 for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width); int ye = ys + random.nextInt(height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // 添加噪点 噪声率 float yawpRate = 0.01f; int area = (int) (yawpRate * width * height); for (int i = 0; i < area; i++) { int x = random.nextInt(width); int y = random.nextInt(height); buffImg.setRGB(x, y, random.nextInt(255)); } // 得到随机字符 String str1 = randomStr(codeCount); this.code = str1; for (int i = 0; i < codeCount; i++) { String strRand = str1.substring(i, i + 1); g.setColor(getRandColor(1, 255)); // g.drawString(a,x,y); // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, i * fontWidth + 3, codeY); } } /** * 生成指定字符图片 */ private void creatImage(String code) { if (StrUtil.isBlank(code)) { throw new CaptchaException("验证码为空或已过期,请重新获取"); } // 字体的宽度 int fontWidth = width / codeCount; // 字体的高度 int fontHeight = height - 5; int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); //Graphics2D g = buffImg.createGraphics(); // 设置背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设置字体 //Font font1 = getFont(fontHeight); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); // 设置 <SUF> for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width); int ye = ys + random.nextInt(height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // 添加噪点 噪声率 float yawpRate = 0.01f; int area = (int) (yawpRate * width * height); for (int i = 0; i < area; i++) { int x = random.nextInt(width); int y = random.nextInt(height); buffImg.setRGB(x, y, random.nextInt(255)); } this.code = code; for (int i = 0; i < code.length(); i++) { String strRand = code.substring(i, i + 1); g.setColor(getRandColor(1, 255)); // g.drawString(a,x,y); // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, i * fontWidth + 3, codeY); } } /** * 得到随机字符 * @param n * @return */ public String randomStr(int n) { String str = ""; int len = STRING.length() - 1; double r; for (int i = 0; i < n; i++) { r = random.nextDouble() * len; str = str + STRING.charAt((int) r); } return str; } /** * 得到随机颜色 * @param fc * @param bc * @return */ private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色 if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * 产生随机字体 */ private Font getFont(int size) { Font[] font = new Font[5]; font[0] = new Font("Ravie", Font.PLAIN, size); font[1] = new Font("Antique Olive Compact", Font.PLAIN, size); font[2] = new Font("Fixedsys", Font.PLAIN, size); font[3] = new Font("Wide Latin", Font.PLAIN, size); font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size); return font[random.nextInt(5)]; } // 扭曲方法 private void shear(Graphics g, int w1, int h1, Color color) { shearX(g, w1, h1, color); shearY(g, w1, h1, color); } private void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) { g.setColor(color); g.drawLine((int) d, i, 0, i); g.drawLine((int) d + w1, i, w1, i); } } } private void shearY(Graphics g, int w1, int h1, Color color) { // 50 int period = random.nextInt(40) + 10; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } } public void write(OutputStream sos) throws IOException { ImageIO.write(buffImg, "png", sos); sos.close(); } public BufferedImage getBuffImg() { return buffImg; } public String getCode() { return code.toLowerCase(); } }
0
13028_4
package cn.exrick.front.limit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.Transaction; import redis.clients.jedis.ZParams; import java.util.List; import java.util.UUID; /** * @author wangiegie@gmail.com https://gitee.com/boding1/pig-cloud */ @Component public class RedisRaterLimiter { final static Logger log= LoggerFactory.getLogger(RedisRaterLimiter.class); @Autowired private JedisPool jedisPool; private static final String BUCKET = "BUCKET_"; private static final String BUCKET_COUNT = "BUCKET_COUNT"; private static final String BUCKET_MONITOR = "BUCKET_MONITOR_"; public String acquireTokenFromBucket(String point, int limit, long timeout) { Jedis jedis = jedisPool.getResource(); try{ //UUID令牌 String token = UUID.randomUUID().toString(); long now = System.currentTimeMillis(); //开启事务 Transaction transaction = jedis.multi(); //删除信号量 移除有序集中指定区间(score)内的所有成员 ZREMRANGEBYSCORE key min max transaction.zremrangeByScore((BUCKET_MONITOR + point).getBytes(), "-inf".getBytes(), String.valueOf(now - timeout).getBytes()); //为每个有序集分别指定一个乘法因子(默认设置为 1) 每个成员的score值在传递给聚合函数之前都要先乘以该因子 ZParams params = new ZParams(); params.weightsByDouble(1.0, 0.0); //计算给定的一个或多个有序集的交集 transaction.zinterstore(BUCKET + point, params, BUCKET + point, BUCKET_MONITOR + point); //计数器自增 transaction.incr(BUCKET_COUNT); List<Object> results = transaction.exec(); long counter = (Long) results.get(results.size() - 1); transaction = jedis.multi(); //Zadd 将一个或多个成员元素及其分数值(score)加入到有序集当中 transaction.zadd(BUCKET_MONITOR + point, now, token); transaction.zadd(BUCKET + point, counter, token); transaction.zrank(BUCKET + point, token); results = transaction.exec(); //获取排名,判断请求是否取得了信号量 long rank = (Long) results.get(results.size() - 1); if (rank < limit) { return token; } else { //没有获取到信号量,清理之前放入redis中垃圾数据 transaction = jedis.multi(); //Zrem移除有序集中的一个或多个成员 transaction.zrem(BUCKET_MONITOR + point, token); transaction.zrem(BUCKET + point, token); transaction.exec(); } }catch (Exception e){ log.error("限流出错"+e.toString()); }finally { if(jedis!=null){ jedis.close(); } } return null; } }
Exrick/xmall
xmall-front-web/src/main/java/cn/exrick/front/limit/RedisRaterLimiter.java
773
//为每个有序集分别指定一个乘法因子(默认设置为 1) 每个成员的score值在传递给聚合函数之前都要先乘以该因子
line_comment
zh-cn
package cn.exrick.front.limit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.Transaction; import redis.clients.jedis.ZParams; import java.util.List; import java.util.UUID; /** * @author wangiegie@gmail.com https://gitee.com/boding1/pig-cloud */ @Component public class RedisRaterLimiter { final static Logger log= LoggerFactory.getLogger(RedisRaterLimiter.class); @Autowired private JedisPool jedisPool; private static final String BUCKET = "BUCKET_"; private static final String BUCKET_COUNT = "BUCKET_COUNT"; private static final String BUCKET_MONITOR = "BUCKET_MONITOR_"; public String acquireTokenFromBucket(String point, int limit, long timeout) { Jedis jedis = jedisPool.getResource(); try{ //UUID令牌 String token = UUID.randomUUID().toString(); long now = System.currentTimeMillis(); //开启事务 Transaction transaction = jedis.multi(); //删除信号量 移除有序集中指定区间(score)内的所有成员 ZREMRANGEBYSCORE key min max transaction.zremrangeByScore((BUCKET_MONITOR + point).getBytes(), "-inf".getBytes(), String.valueOf(now - timeout).getBytes()); //为每 <SUF> ZParams params = new ZParams(); params.weightsByDouble(1.0, 0.0); //计算给定的一个或多个有序集的交集 transaction.zinterstore(BUCKET + point, params, BUCKET + point, BUCKET_MONITOR + point); //计数器自增 transaction.incr(BUCKET_COUNT); List<Object> results = transaction.exec(); long counter = (Long) results.get(results.size() - 1); transaction = jedis.multi(); //Zadd 将一个或多个成员元素及其分数值(score)加入到有序集当中 transaction.zadd(BUCKET_MONITOR + point, now, token); transaction.zadd(BUCKET + point, counter, token); transaction.zrank(BUCKET + point, token); results = transaction.exec(); //获取排名,判断请求是否取得了信号量 long rank = (Long) results.get(results.size() - 1); if (rank < limit) { return token; } else { //没有获取到信号量,清理之前放入redis中垃圾数据 transaction = jedis.multi(); //Zrem移除有序集中的一个或多个成员 transaction.zrem(BUCKET_MONITOR + point, token); transaction.zrem(BUCKET + point, token); transaction.exec(); } }catch (Exception e){ log.error("限流出错"+e.toString()); }finally { if(jedis!=null){ jedis.close(); } } return null; } }
1
4963_1
package cn.exrick.service.impl; import cn.exrick.bean.Pay; import cn.exrick.bean.dto.Count; import cn.exrick.common.utils.DateUtils; import cn.exrick.common.utils.StringUtils; import cn.exrick.dao.PayDao; import cn.exrick.service.PayService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; /** * @author Exrickx */ @Service public class PayServiceImpl implements PayService { private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class); @Autowired private PayDao payDao; @Override public Page<Pay> getPayListByPage(Integer state, String key, Pageable pageable) { return payDao.findAll(new Specification<Pay>() { @Override public Predicate toPredicate(Root<Pay> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { Path<String> nickNameField = root.get("nickName"); Path<String> infoField = root.get("info"); Path<String> payTypeField=root.get("payType"); Path<Integer> stateField=root.get("state"); List<Predicate> list = new ArrayList<Predicate>(); //模糊搜素 if(StringUtils.isNotBlank(key)){ Predicate p1 = cb.like(nickNameField,'%'+key+'%'); Predicate p3 = cb.like(infoField,'%'+key+'%'); Predicate p4 = cb.like(payTypeField,'%'+key+'%'); list.add(cb.or(p1,p3,p4)); } //状态 if(state!=null){ list.add(cb.equal(stateField, state)); } Predicate[] arr = new Predicate[list.size()]; cq.where(list.toArray(arr)); return null; } }, pageable); } @Override public List<Pay> getPayList(Integer state) { List<Pay> list=payDao.getByStateIs(state); for(Pay pay:list){ //屏蔽隐私数据 pay.setId(""); pay.setEmail(""); pay.setTestEmail(""); pay.setPayNum(null); pay.setMobile(null); pay.setCustom(null); pay.setDevice(null); } return list; } @Override public Pay getPay(String id) { Pay pay=payDao.findOne(id); pay.setTime(StringUtils.getTimeStamp(pay.getCreateTime())); return pay; } @Override public int addPay(Pay pay) { pay.setId(UUID.randomUUID().toString()); pay.setCreateTime(new Date()); pay.setState(0); payDao.save(pay); return 1; } @Override public int updatePay(Pay pay) { pay.setUpdateTime(new Date()); payDao.saveAndFlush(pay); return 1; } @Override public int changePayState(String id, Integer state) { Pay pay=getPay(id); pay.setState(state); pay.setUpdateTime(new Date()); payDao.saveAndFlush(pay); return 1; } @Override public int delPay(String id) { payDao.delete(id); return 1; } @Override public Count statistic(Integer type, String start, String end) { Count count=new Count(); if(type==-1){ // 总 count.setAmount(payDao.countAllMoney()); count.setAlipay(payDao.countAllMoneyByType("Alipay")); count.setWechat(payDao.countAllMoneyByType("Wechat")); count.setQq(payDao.countAllMoneyByType("QQ")); count.setUnion(payDao.countAllMoneyByType("UnionPay")); count.setDiandan(payDao.countAllMoneyByType("Diandan")); return count; } Date startDate=null,endDate=null; if(type==0){ // 今天 startDate = DateUtils.getDayBegin(); endDate = DateUtils.getDayEnd(); }if(type==6){ // 昨天 startDate = DateUtils.getBeginDayOfYesterday(); endDate = DateUtils.getEndDayOfYesterDay(); }else if(type==1){ // 本周 startDate = DateUtils.getBeginDayOfWeek(); endDate = DateUtils.getEndDayOfWeek(); }else if(type==2){ // 本月 startDate = DateUtils.getBeginDayOfMonth(); endDate = DateUtils.getEndDayOfMonth(); }else if(type==3){ // 本年 startDate = DateUtils.getBeginDayOfYear(); endDate = DateUtils.getEndDayOfYear(); }else if(type==4){ // 上周 startDate = DateUtils.getBeginDayOfLastWeek(); endDate = DateUtils.getEndDayOfLastWeek(); }else if(type==5){ // 上个月 startDate = DateUtils.getBeginDayOfLastMonth(); endDate = DateUtils.getEndDayOfLastMonth(); }else if(type==-2){ // 自定义 startDate = DateUtils.parseStartDate(start); endDate = DateUtils.parseEndDate(end); } count.setAmount(payDao.countMoney(startDate, endDate)); count.setAlipay(payDao.countMoneyByType("Alipay", startDate, endDate)); count.setWechat(payDao.countMoneyByType("Wechat", startDate, endDate)); count.setQq(payDao.countMoneyByType("QQ", startDate, endDate)); count.setUnion(payDao.countMoneyByType("UnionPay", startDate, endDate)); count.setDiandan(payDao.countMoneyByType("Diandan", startDate, endDate)); return count; } }
Exrick/xpay
xpay-code/src/main/java/cn/exrick/service/impl/PayServiceImpl.java
1,487
//模糊搜素
line_comment
zh-cn
package cn.exrick.service.impl; import cn.exrick.bean.Pay; import cn.exrick.bean.dto.Count; import cn.exrick.common.utils.DateUtils; import cn.exrick.common.utils.StringUtils; import cn.exrick.dao.PayDao; import cn.exrick.service.PayService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; /** * @author Exrickx */ @Service public class PayServiceImpl implements PayService { private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class); @Autowired private PayDao payDao; @Override public Page<Pay> getPayListByPage(Integer state, String key, Pageable pageable) { return payDao.findAll(new Specification<Pay>() { @Override public Predicate toPredicate(Root<Pay> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { Path<String> nickNameField = root.get("nickName"); Path<String> infoField = root.get("info"); Path<String> payTypeField=root.get("payType"); Path<Integer> stateField=root.get("state"); List<Predicate> list = new ArrayList<Predicate>(); //模糊 <SUF> if(StringUtils.isNotBlank(key)){ Predicate p1 = cb.like(nickNameField,'%'+key+'%'); Predicate p3 = cb.like(infoField,'%'+key+'%'); Predicate p4 = cb.like(payTypeField,'%'+key+'%'); list.add(cb.or(p1,p3,p4)); } //状态 if(state!=null){ list.add(cb.equal(stateField, state)); } Predicate[] arr = new Predicate[list.size()]; cq.where(list.toArray(arr)); return null; } }, pageable); } @Override public List<Pay> getPayList(Integer state) { List<Pay> list=payDao.getByStateIs(state); for(Pay pay:list){ //屏蔽隐私数据 pay.setId(""); pay.setEmail(""); pay.setTestEmail(""); pay.setPayNum(null); pay.setMobile(null); pay.setCustom(null); pay.setDevice(null); } return list; } @Override public Pay getPay(String id) { Pay pay=payDao.findOne(id); pay.setTime(StringUtils.getTimeStamp(pay.getCreateTime())); return pay; } @Override public int addPay(Pay pay) { pay.setId(UUID.randomUUID().toString()); pay.setCreateTime(new Date()); pay.setState(0); payDao.save(pay); return 1; } @Override public int updatePay(Pay pay) { pay.setUpdateTime(new Date()); payDao.saveAndFlush(pay); return 1; } @Override public int changePayState(String id, Integer state) { Pay pay=getPay(id); pay.setState(state); pay.setUpdateTime(new Date()); payDao.saveAndFlush(pay); return 1; } @Override public int delPay(String id) { payDao.delete(id); return 1; } @Override public Count statistic(Integer type, String start, String end) { Count count=new Count(); if(type==-1){ // 总 count.setAmount(payDao.countAllMoney()); count.setAlipay(payDao.countAllMoneyByType("Alipay")); count.setWechat(payDao.countAllMoneyByType("Wechat")); count.setQq(payDao.countAllMoneyByType("QQ")); count.setUnion(payDao.countAllMoneyByType("UnionPay")); count.setDiandan(payDao.countAllMoneyByType("Diandan")); return count; } Date startDate=null,endDate=null; if(type==0){ // 今天 startDate = DateUtils.getDayBegin(); endDate = DateUtils.getDayEnd(); }if(type==6){ // 昨天 startDate = DateUtils.getBeginDayOfYesterday(); endDate = DateUtils.getEndDayOfYesterDay(); }else if(type==1){ // 本周 startDate = DateUtils.getBeginDayOfWeek(); endDate = DateUtils.getEndDayOfWeek(); }else if(type==2){ // 本月 startDate = DateUtils.getBeginDayOfMonth(); endDate = DateUtils.getEndDayOfMonth(); }else if(type==3){ // 本年 startDate = DateUtils.getBeginDayOfYear(); endDate = DateUtils.getEndDayOfYear(); }else if(type==4){ // 上周 startDate = DateUtils.getBeginDayOfLastWeek(); endDate = DateUtils.getEndDayOfLastWeek(); }else if(type==5){ // 上个月 startDate = DateUtils.getBeginDayOfLastMonth(); endDate = DateUtils.getEndDayOfLastMonth(); }else if(type==-2){ // 自定义 startDate = DateUtils.parseStartDate(start); endDate = DateUtils.parseEndDate(end); } count.setAmount(payDao.countMoney(startDate, endDate)); count.setAlipay(payDao.countMoneyByType("Alipay", startDate, endDate)); count.setWechat(payDao.countMoneyByType("Wechat", startDate, endDate)); count.setQq(payDao.countMoneyByType("QQ", startDate, endDate)); count.setUnion(payDao.countMoneyByType("UnionPay", startDate, endDate)); count.setDiandan(payDao.countMoneyByType("Diandan", startDate, endDate)); return count; } }
0
59342_2
package com.track.ui.adapter; import java.text.SimpleDateFormat; import java.util.List; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.track.app.user.R; import com.track.misc.model.TransHistory; import com.track.net.IDataAdapter; public class TransHistoryAdapter extends ArrayAdapter<TransHistory> implements IDataAdapter<List<TransHistory>> { private List<TransHistory> itemList; private Context context; public TransHistoryAdapter(List<TransHistory> itemList, Context ctx) { super(ctx, R.layout.transhistory_list_item, itemList); this.itemList = itemList; this.context = ctx; } @Override public int getCount() { if (itemList != null) return itemList.size(); return 0; } @Override public TransHistory getItem(int position) { if (itemList != null) return itemList.get(position); return null; } public void setItem(TransHistory th, int position) { if (itemList != null) itemList.set(position, th); } @Override public long getItemId(int position) { if (itemList != null) return itemList.get(position).hashCode(); return 0; } @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; hold h = null; if (v == null) { h = new hold(); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(R.layout.transhistory_list_item, null); h.timeDay = (TextView) v.findViewById(R.id.time_tv1); h.timeHour = (TextView) v.findViewById(R.id.time_tv2); h.img = (ImageView) v.findViewById(R.id.transhistory_iv); h.textNode = (TextView) v.findViewById(R.id.his_node); // h.textNode2 = (TextView) v.findViewById(R.id.his_node2); h.textOpe = (TextView) v.findViewById(R.id.his_ope1); h.textUser = (TextView) v.findViewById(R.id.his_user1); h.textUserTp = (TextView) v.findViewById(R.id.user); } TransHistory his = itemList.get(position); SimpleDateFormat myFmtDay = new SimpleDateFormat("yyyy.MM.dd"); SimpleDateFormat myFmtHour = new SimpleDateFormat("HH:mm"); Log.e("his", his.toString()); if (his.getActtime() != null && myFmtDay != null && h != null) { h.timeDay.setText(myFmtDay.format(his.getActtime())); h.timeHour.setText(myFmtHour.format(his.getActtime())); } if (h != null) { switch (position) { case 0: h.textNode.setText("快件"); h.textOpe.setText("已揽收"); h.textNode.setTextSize(16); h.textNode.setTextColor(Color.BLACK); h.textOpe.setTextSize(16); h.textOpe.setTextColor(Color.BLACK); h.textUserTp.setText("快递员:"); h.textUser.setText(his.getUserFrom().getUname() + " 电话: " + his.getUserFrom().getTelcode()); h.textUserTp.setTextSize(16); h.textUserTp.setTextColor(Color.BLACK); h.textUser.setTextSize(16); h.textUser.setTextColor(Color.BLACK); h.timeDay.setTextColor(Color.BLACK); break; case 1: if (his.getPackageid().getTargetTransNode() != null) { h.textNode.setText(his.getPackageid().getTargetTransNode() .getNodename()); } h.textUserTp.setText("管理员:"); h.textOpe.setText("已拆包"); h.textUser.setText(his.getUserTo().getUname()); break; default: if (his.getUserTo() != null) { // 当快件交给管理员,且uidfrom和uidto相等 if (his.getUidfrom() == his.getUidto() && his.getUserTo().getRole() == 1) { h.textNode.setText(his.getPackageid() .getSourceTransNode().getNodename()); h.textOpe.setText("已打包,将发往" + his.getPackageid().getTargetTransNode() .getNodename()); h.textUserTp.setText("管理员:"); h.textUser.setText(his.getUserFrom().getUname()); // 当快件交给管理员 } else if (his.getUidfrom() != his.getUidto() && his.getUserTo().getRole() == 1) { h.textNode.setText("快件到达" + his.getPackageid().getTargetTransNode() .getNodename()); h.textOpe.setText(""); h.textUserTp.setText("管理员:"); h.textUser.setText(his.getUserTo().getUname()); // 当快件交给司机 } else if (his.getUserTo().getRole() == 2) { h.textNode.setText("快件已离开" + his.getPackageid().getSourceTransNode() .getNodename()); h.textOpe.setText(""); h.textUserTp.setText("司机:"); h.textUser.setText(his.getUserTo().getUname()); // 当快件交给快递员 } else if (his.getUserTo().getRole() == 0) { h.textNode.setText("快件"); h.textOpe.setText("正在派送,请保持手机畅通"); h.textUserTp.setText("快递员:"); h.textUser.setText(his.getUserTo().getUname() + " 电话: " + his.getUserTo().getTelcode()); } } else if (his.getUidto() == 0) { h.textNode.setText("快件"); h.textOpe.setText("已签收"); h.textUserTp.setText("快递员:"); h.textUser.setText(his.getUserFrom().getUname()); h.img.setImageResource(R.drawable.icon_ok); h.textNode.setTextSize(18); h.textNode.setTextColor(Color.BLUE); h.textOpe.setTextSize(18); h.textOpe.setTextColor(Color.BLUE); h.timeDay.setTextColor(Color.BLUE); h.timeHour.setTextColor(Color.BLUE); } break; } } // 将position传进去 // text.setTag(position); return v; } @Override public List<TransHistory> getData() { return itemList; } @Override public void setData(List<TransHistory> data) { this.itemList = data; } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); } private class hold { TextView timeDay; TextView timeHour; ImageView img; TextView textOpe; TextView textUser; TextView textNode; TextView textUserTp; TextView textNode2; } }
Extrace/Extrace_UserApp
src/com/track/ui/adapter/TransHistoryAdapter.java
2,021
// 当快件交给管理员
line_comment
zh-cn
package com.track.ui.adapter; import java.text.SimpleDateFormat; import java.util.List; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Color; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.track.app.user.R; import com.track.misc.model.TransHistory; import com.track.net.IDataAdapter; public class TransHistoryAdapter extends ArrayAdapter<TransHistory> implements IDataAdapter<List<TransHistory>> { private List<TransHistory> itemList; private Context context; public TransHistoryAdapter(List<TransHistory> itemList, Context ctx) { super(ctx, R.layout.transhistory_list_item, itemList); this.itemList = itemList; this.context = ctx; } @Override public int getCount() { if (itemList != null) return itemList.size(); return 0; } @Override public TransHistory getItem(int position) { if (itemList != null) return itemList.get(position); return null; } public void setItem(TransHistory th, int position) { if (itemList != null) itemList.set(position, th); } @Override public long getItemId(int position) { if (itemList != null) return itemList.get(position).hashCode(); return 0; } @SuppressLint("InflateParams") @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; hold h = null; if (v == null) { h = new hold(); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(R.layout.transhistory_list_item, null); h.timeDay = (TextView) v.findViewById(R.id.time_tv1); h.timeHour = (TextView) v.findViewById(R.id.time_tv2); h.img = (ImageView) v.findViewById(R.id.transhistory_iv); h.textNode = (TextView) v.findViewById(R.id.his_node); // h.textNode2 = (TextView) v.findViewById(R.id.his_node2); h.textOpe = (TextView) v.findViewById(R.id.his_ope1); h.textUser = (TextView) v.findViewById(R.id.his_user1); h.textUserTp = (TextView) v.findViewById(R.id.user); } TransHistory his = itemList.get(position); SimpleDateFormat myFmtDay = new SimpleDateFormat("yyyy.MM.dd"); SimpleDateFormat myFmtHour = new SimpleDateFormat("HH:mm"); Log.e("his", his.toString()); if (his.getActtime() != null && myFmtDay != null && h != null) { h.timeDay.setText(myFmtDay.format(his.getActtime())); h.timeHour.setText(myFmtHour.format(his.getActtime())); } if (h != null) { switch (position) { case 0: h.textNode.setText("快件"); h.textOpe.setText("已揽收"); h.textNode.setTextSize(16); h.textNode.setTextColor(Color.BLACK); h.textOpe.setTextSize(16); h.textOpe.setTextColor(Color.BLACK); h.textUserTp.setText("快递员:"); h.textUser.setText(his.getUserFrom().getUname() + " 电话: " + his.getUserFrom().getTelcode()); h.textUserTp.setTextSize(16); h.textUserTp.setTextColor(Color.BLACK); h.textUser.setTextSize(16); h.textUser.setTextColor(Color.BLACK); h.timeDay.setTextColor(Color.BLACK); break; case 1: if (his.getPackageid().getTargetTransNode() != null) { h.textNode.setText(his.getPackageid().getTargetTransNode() .getNodename()); } h.textUserTp.setText("管理员:"); h.textOpe.setText("已拆包"); h.textUser.setText(his.getUserTo().getUname()); break; default: if (his.getUserTo() != null) { // 当快件交给管理员,且uidfrom和uidto相等 if (his.getUidfrom() == his.getUidto() && his.getUserTo().getRole() == 1) { h.textNode.setText(his.getPackageid() .getSourceTransNode().getNodename()); h.textOpe.setText("已打包,将发往" + his.getPackageid().getTargetTransNode() .getNodename()); h.textUserTp.setText("管理员:"); h.textUser.setText(his.getUserFrom().getUname()); // 当快 <SUF> } else if (his.getUidfrom() != his.getUidto() && his.getUserTo().getRole() == 1) { h.textNode.setText("快件到达" + his.getPackageid().getTargetTransNode() .getNodename()); h.textOpe.setText(""); h.textUserTp.setText("管理员:"); h.textUser.setText(his.getUserTo().getUname()); // 当快件交给司机 } else if (his.getUserTo().getRole() == 2) { h.textNode.setText("快件已离开" + his.getPackageid().getSourceTransNode() .getNodename()); h.textOpe.setText(""); h.textUserTp.setText("司机:"); h.textUser.setText(his.getUserTo().getUname()); // 当快件交给快递员 } else if (his.getUserTo().getRole() == 0) { h.textNode.setText("快件"); h.textOpe.setText("正在派送,请保持手机畅通"); h.textUserTp.setText("快递员:"); h.textUser.setText(his.getUserTo().getUname() + " 电话: " + his.getUserTo().getTelcode()); } } else if (his.getUidto() == 0) { h.textNode.setText("快件"); h.textOpe.setText("已签收"); h.textUserTp.setText("快递员:"); h.textUser.setText(his.getUserFrom().getUname()); h.img.setImageResource(R.drawable.icon_ok); h.textNode.setTextSize(18); h.textNode.setTextColor(Color.BLUE); h.textOpe.setTextSize(18); h.textOpe.setTextColor(Color.BLUE); h.timeDay.setTextColor(Color.BLUE); h.timeHour.setTextColor(Color.BLUE); } break; } } // 将position传进去 // text.setTag(position); return v; } @Override public List<TransHistory> getData() { return itemList; } @Override public void setData(List<TransHistory> data) { this.itemList = data; } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); } private class hold { TextView timeDay; TextView timeHour; ImageView img; TextView textOpe; TextView textUser; TextView textNode; TextView textUserTp; TextView textNode2; } }
1
23265_29
// 排序算法 import java.util.Arrays; public class Sort { //插入排序 public static void insertSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; ++i) { // 记录有序序列最后一个元素的下标 int end = i; // 待插入的元素 int tem = arr[end + 1]; // 单趟排 while (end >= 0) { // 比插入的数大就向后移 if (tem < arr[end]) { arr[end + 1] = arr[end]; end--; } // 比插入的数小,跳出循环 else { break; } } // tem放到比插入的数小的数的后面 arr[end + 1] = tem; // 代码执行到此位置有两种情况: // 1. 待插入元素找到应插入位置(break跳出循环到此) // 2. 待插入元素比当前有序序列中的所有元素都小(while循环结束后到此) } } //希尔排序 public static void shellSort(int[] arr) { int n = arr.length; int gap = n; while (gap > 1) { //每次对gap折半操作 gap = gap / 2; //单趟排序 for (int i = 0; i < n - gap; ++i) { int end = i; int tem = arr[end + gap]; while (end >= 0) { if (tem < arr[end]) { arr[end + gap] = arr[end]; end -= gap; } else { break; } } arr[end + gap] = tem; } } } //选择排序 // public static void selectionSort(int[] arr) { // int n = arr.length; // for (int i = 0; i < n - 1; i++) { // int minIndex = i; // for (int j = i + 1; j < n; j++) { // if (arr[j] < arr[minIndex]) { // minIndex = j; // } // } // int temp = arr[minIndex]; // arr[minIndex] = arr[i]; // arr[i] = temp; // } // } public static void selectionSort(int[] arr) { int n = arr.length; int begin = 0; int end = n - 1; while (begin < end) { int min = begin; int max = begin; for (int i = begin; i <= end; ++i) { if (arr[i] < arr[min]) { min = i; } if (arr[i] > arr[max]) { max = i; } } int temp1 = arr[min]; int temp2 = arr[max]; arr[min] = arr[begin]; arr[begin] = temp1; if (begin == max) { max = min; } arr[max] = arr[end]; arr[end] = temp2; ++begin; --end; } } //冒泡排序 public static void bubbleSort(int[] arr) { int end = arr.length; while (end>0) { int flag = 0; for (int i = 1; i < end; ++i) { if (arr[i - 1] > arr[i]) { int tem = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = tem; flag = 1; } } if (flag == 0) { break; } --end; } } //堆排序 //快速排序 public static void quickSort(int[] array, int low, int high){ int i,j,pivot; //结束条件 if (low >= high) { return; } i = low; j = high; //选择的节点,这里选择的数组的第一数作为节点 pivot = array[low]; while (i < j){ //从右往左找比节点小的数,循环结束要么找到了,要么i=j while (array[j] >= pivot && i < j){ j--; } //从左往右找比节点大的数,循环结束要么找到了,要么i=j while (array[i] <= pivot && i < j){ i++; } //如果i!=j说明都找到了,就交换这两个数 if (i < j){ int temp = array[i]; array[i] = array[j]; array[j] = temp; } } //i==j一轮循环结束,交换节点的数和相遇点的数 array[low] = array[i]; array[i] = pivot; //数组“分两半”,再重复上面的操作 quickSort(array,low,i - 1); quickSort(array,i + 1,high); } //归并排序 public static int[] mergeSort(int[] nums) { int len = nums.length; int[] temp = new int[len]; mSort(nums,0,len-1,temp); return nums; } /** * 递归函数对nums[left...right]进行归并排序 * @param nums 原数组 * @param left 左边的索引 * @param right 右边记录索引位置 * @param temp */ public static void mSort(int[] nums, int left, int right, int[] temp) { if (left == right){//当拆分到数组当中只要一个值的时候,结束递归 return; } int mid = (left+right)/2; //找到下次要拆分的中间值 mSort(nums,left,mid,temp);//记录树左边的 mSort(nums,mid+1,right,temp);//记录树右边的 //合并两个区间 for (int i = left; i <= right; i++) { temp[i] = nums[i]; //temp就是辅助列表,新列表的需要排序的值就是从辅助列表中拿到的 } int i = left; //给辅助数组里面的值标点 int j = mid +1; for (int k = left; k <= right ; k++) {//k 就为当前要插入的位置 if (i == mid + 1){ nums[k] = temp[j]; j++; }else if (j == right+1){ nums[k] = temp[i]; i++; } else if (temp[i] <= temp[j]){ nums[k] = temp[i]; i++; }else { nums[k] = temp[j]; j++; } } } //计数排序 public static void countSort(int[] arr) { int max = 0; int min = 0; for(int i = 0; i < arr.length; i++){ if(arr[i] < min) min = arr[i]; if(arr[i] > max) max = arr[i]; } } public static void main(String[] args) { int[] nums1 = new int[]{8,9,1,7,2,3,5,5,6,4,3}; // insertSort(nums1); // shellSort(nums1); // selectionSort(nums1); // bubbleSort(nums1); // quickSort(nums1, 0, nums1.length-1); mergeSort(nums1); System.out.println(Arrays.toString(nums1)); } }
Eye-Wuppertal/Question
Sort.java
1,861
//选择的节点,这里选择的数组的第一数作为节点
line_comment
zh-cn
// 排序算法 import java.util.Arrays; public class Sort { //插入排序 public static void insertSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; ++i) { // 记录有序序列最后一个元素的下标 int end = i; // 待插入的元素 int tem = arr[end + 1]; // 单趟排 while (end >= 0) { // 比插入的数大就向后移 if (tem < arr[end]) { arr[end + 1] = arr[end]; end--; } // 比插入的数小,跳出循环 else { break; } } // tem放到比插入的数小的数的后面 arr[end + 1] = tem; // 代码执行到此位置有两种情况: // 1. 待插入元素找到应插入位置(break跳出循环到此) // 2. 待插入元素比当前有序序列中的所有元素都小(while循环结束后到此) } } //希尔排序 public static void shellSort(int[] arr) { int n = arr.length; int gap = n; while (gap > 1) { //每次对gap折半操作 gap = gap / 2; //单趟排序 for (int i = 0; i < n - gap; ++i) { int end = i; int tem = arr[end + gap]; while (end >= 0) { if (tem < arr[end]) { arr[end + gap] = arr[end]; end -= gap; } else { break; } } arr[end + gap] = tem; } } } //选择排序 // public static void selectionSort(int[] arr) { // int n = arr.length; // for (int i = 0; i < n - 1; i++) { // int minIndex = i; // for (int j = i + 1; j < n; j++) { // if (arr[j] < arr[minIndex]) { // minIndex = j; // } // } // int temp = arr[minIndex]; // arr[minIndex] = arr[i]; // arr[i] = temp; // } // } public static void selectionSort(int[] arr) { int n = arr.length; int begin = 0; int end = n - 1; while (begin < end) { int min = begin; int max = begin; for (int i = begin; i <= end; ++i) { if (arr[i] < arr[min]) { min = i; } if (arr[i] > arr[max]) { max = i; } } int temp1 = arr[min]; int temp2 = arr[max]; arr[min] = arr[begin]; arr[begin] = temp1; if (begin == max) { max = min; } arr[max] = arr[end]; arr[end] = temp2; ++begin; --end; } } //冒泡排序 public static void bubbleSort(int[] arr) { int end = arr.length; while (end>0) { int flag = 0; for (int i = 1; i < end; ++i) { if (arr[i - 1] > arr[i]) { int tem = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = tem; flag = 1; } } if (flag == 0) { break; } --end; } } //堆排序 //快速排序 public static void quickSort(int[] array, int low, int high){ int i,j,pivot; //结束条件 if (low >= high) { return; } i = low; j = high; //选择 <SUF> pivot = array[low]; while (i < j){ //从右往左找比节点小的数,循环结束要么找到了,要么i=j while (array[j] >= pivot && i < j){ j--; } //从左往右找比节点大的数,循环结束要么找到了,要么i=j while (array[i] <= pivot && i < j){ i++; } //如果i!=j说明都找到了,就交换这两个数 if (i < j){ int temp = array[i]; array[i] = array[j]; array[j] = temp; } } //i==j一轮循环结束,交换节点的数和相遇点的数 array[low] = array[i]; array[i] = pivot; //数组“分两半”,再重复上面的操作 quickSort(array,low,i - 1); quickSort(array,i + 1,high); } //归并排序 public static int[] mergeSort(int[] nums) { int len = nums.length; int[] temp = new int[len]; mSort(nums,0,len-1,temp); return nums; } /** * 递归函数对nums[left...right]进行归并排序 * @param nums 原数组 * @param left 左边的索引 * @param right 右边记录索引位置 * @param temp */ public static void mSort(int[] nums, int left, int right, int[] temp) { if (left == right){//当拆分到数组当中只要一个值的时候,结束递归 return; } int mid = (left+right)/2; //找到下次要拆分的中间值 mSort(nums,left,mid,temp);//记录树左边的 mSort(nums,mid+1,right,temp);//记录树右边的 //合并两个区间 for (int i = left; i <= right; i++) { temp[i] = nums[i]; //temp就是辅助列表,新列表的需要排序的值就是从辅助列表中拿到的 } int i = left; //给辅助数组里面的值标点 int j = mid +1; for (int k = left; k <= right ; k++) {//k 就为当前要插入的位置 if (i == mid + 1){ nums[k] = temp[j]; j++; }else if (j == right+1){ nums[k] = temp[i]; i++; } else if (temp[i] <= temp[j]){ nums[k] = temp[i]; i++; }else { nums[k] = temp[j]; j++; } } } //计数排序 public static void countSort(int[] arr) { int max = 0; int min = 0; for(int i = 0; i < arr.length; i++){ if(arr[i] < min) min = arr[i]; if(arr[i] > max) max = arr[i]; } } public static void main(String[] args) { int[] nums1 = new int[]{8,9,1,7,2,3,5,5,6,4,3}; // insertSort(nums1); // shellSort(nums1); // selectionSort(nums1); // bubbleSort(nums1); // quickSort(nums1, 0, nums1.length-1); mergeSort(nums1); System.out.println(Arrays.toString(nums1)); } }
1
52668_1
package com.atguigu.practiceNo2.juc; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class SemaphoreDemo { public static void main(String[] args) { //6辆汽车停三个停车位 Semaphore semaphore = new Semaphore(3); for (int i = 0; i <= 6; i++) { new Thread(() -> { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "停车"); //随机停车时间 TimeUnit.SECONDS.sleep(new Random().nextInt(5)); System.out.println(Thread.currentThread().getName() + "离开"); } catch (Exception e) { e.printStackTrace(); } finally { //释放 semaphore.release(); } }, "线程" + i).start(); } } }
Ezrabin/juc_atguigu
src/com/atguigu/practiceNo2/juc/SemaphoreDemo.java
217
//随机停车时间
line_comment
zh-cn
package com.atguigu.practiceNo2.juc; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class SemaphoreDemo { public static void main(String[] args) { //6辆汽车停三个停车位 Semaphore semaphore = new Semaphore(3); for (int i = 0; i <= 6; i++) { new Thread(() -> { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "停车"); //随机 <SUF> TimeUnit.SECONDS.sleep(new Random().nextInt(5)); System.out.println(Thread.currentThread().getName() + "离开"); } catch (Exception e) { e.printStackTrace(); } finally { //释放 semaphore.release(); } }, "线程" + i).start(); } } }
0
58892_37
package com.videogo.ui.login; import java.util.ArrayList; import java.util.List; /** * 开放平台服务端在分为海外和国内,海外又分为5个大区 * (北美、南美、新加坡(亚洲)、俄罗斯、欧洲) * 必须根据当前使用的AppKey对应大区切换到所在大区的服务器 * 否则EZOpenSDK的接口调用将会出现异常 */ public enum ServerAreasEnum { /** * 国内 */ ASIA_CHINA(0,"Asia-China", "https://open.ys7.com", "https://openauth.ys7.com", "26810f3acd794862b608b6cfbc32a6b8"), /** * 海外:俄罗斯 */ ASIA_Russia(5, "Asia-Russia", "https://irusopen.ezvizru.com", "https://irusopenauth.ezvizru.com", true), /** * 海外:亚洲 * (服务亚洲的所有国家,但不包括中国和俄罗斯) */ ASIA(10, "Asia", "https://isgpopen.ezvizlife.com", "https://isgpopenauth.ezvizlife.com", true), /** * 海外:北美洲 */ NORTH_AMERICA(15,"North America", "https://iusopen.ezvizlife.com", "https://iusopenauth.ezvizlife.com", true), /** * 海外:南美洲 */ SOUTH_AMERICA(20, "South America", "https://isaopen.ezvizlife.com", "https://isaopenauth.ezvizlife.com", true), /** * 海外:欧洲 */ EUROPE(25, "Europe", "https://ieuopen.ezvizlife.com", "https://ieuopenauth.ezvizlife.com", "5cadedf5478d11e7ae26fa163e8bac01", true), OTHER(26, "Other", "", "", "1111"), OTHER_GLOBAL(27, "Other Global", "", "", "1111", true), /*线上平台的id范围为0到99,测试平台的id范围为100+*/ /** * 测试平台:test12 */ TEST12(110, "test12", "https://test12open.ys7.com", "https://test12openauth.ys7.com", "b22035492c7949bca95286382ed90b01"), /** * 测试平台:testcn */ TEST_CN(115, "testcn", "https://testcnopen.ezvizlife.com", "https://testcnopenauth.ezvizlife.com", true), /** * 测试平台:testus */ TEST_US(120, "testus", "https://testusopen.ezvizlife.com", "https://testusopenauth.ezvizlife.com", true), /** * 测试平台:testeu */ // TEST_EU(125, "testeu", "https://testeuopen.ezvizlife.com", // "https://testeuopenauth.ezvizlife.com", true), TEST_EU(125, "testeu", "https://ys-open.wens.com.cn", "https://test2auth.ys7.com:8643", true), /** * 温氏 */ WENSHI(126, "WenShi", "https://ezcpcloudopen.wens.com.cn", "https://ezcpcloudopenauth.wens.com.cn", false), /** * 华住 */ HUAZHU(127, "HuaZhu", "https://ezcpatctestopen.ys7.com", "https://ezcpatctestopenauth.ys7.com", false); // TEST_NEW(130,"testnew", "https://ys-open.wens.com.cn", // "https://test2auth.ys7.com:8643", true); public int id; public String areaName; public String openApiServer; public String openAuthApiServer; // 预置的用于测试h5登录的appKey(该appKey的bundleId已绑定到ezviz.opensdk) public String defaultOpenAuthAppKey; // 是否正在海外域名,海外域名需要使用GlobalEZOpenSDK,反之使用EZOpenSDK public boolean usingGlobalSDK; ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer){ this(id, areaName, openApiServer, openAuthApiServer, null, false); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey){ this(id, areaName, openApiServer, openAuthApiServer, defaultOpenAuthAppKey, false); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, boolean usingGlobalSDK){ this(id, areaName, openApiServer, openAuthApiServer, null, usingGlobalSDK); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey, boolean usingGlobalSDK){ this.id = id; this.areaName = areaName; this.openApiServer = openApiServer; this.openAuthApiServer = openAuthApiServer; this.defaultOpenAuthAppKey = defaultOpenAuthAppKey; this.usingGlobalSDK = usingGlobalSDK; } public static List<ServerAreasEnum> getAllServers(){ List<ServerAreasEnum> serversList = new ArrayList<>(); for (ServerAreasEnum server : values()) { boolean isTestServer = server.id >= 100; // 线上demo不展示测试平台 if (!com.videogo.openapi.BuildConfig.DEBUG && isTestServer) { continue; } serversList.add(server); } return serversList; } @Override public String toString() { return "id: " + id + ", " + "areaName: " + areaName + ", " + "openApiServer: " + openApiServer + ", " + "openAuthApiServer: " + openAuthApiServer; } }
Ezviz-Open/EzvizSDK-Android
app/src/main/java/com/videogo/ui/login/ServerAreasEnum.java
1,598
/** * 华住 */
block_comment
zh-cn
package com.videogo.ui.login; import java.util.ArrayList; import java.util.List; /** * 开放平台服务端在分为海外和国内,海外又分为5个大区 * (北美、南美、新加坡(亚洲)、俄罗斯、欧洲) * 必须根据当前使用的AppKey对应大区切换到所在大区的服务器 * 否则EZOpenSDK的接口调用将会出现异常 */ public enum ServerAreasEnum { /** * 国内 */ ASIA_CHINA(0,"Asia-China", "https://open.ys7.com", "https://openauth.ys7.com", "26810f3acd794862b608b6cfbc32a6b8"), /** * 海外:俄罗斯 */ ASIA_Russia(5, "Asia-Russia", "https://irusopen.ezvizru.com", "https://irusopenauth.ezvizru.com", true), /** * 海外:亚洲 * (服务亚洲的所有国家,但不包括中国和俄罗斯) */ ASIA(10, "Asia", "https://isgpopen.ezvizlife.com", "https://isgpopenauth.ezvizlife.com", true), /** * 海外:北美洲 */ NORTH_AMERICA(15,"North America", "https://iusopen.ezvizlife.com", "https://iusopenauth.ezvizlife.com", true), /** * 海外:南美洲 */ SOUTH_AMERICA(20, "South America", "https://isaopen.ezvizlife.com", "https://isaopenauth.ezvizlife.com", true), /** * 海外:欧洲 */ EUROPE(25, "Europe", "https://ieuopen.ezvizlife.com", "https://ieuopenauth.ezvizlife.com", "5cadedf5478d11e7ae26fa163e8bac01", true), OTHER(26, "Other", "", "", "1111"), OTHER_GLOBAL(27, "Other Global", "", "", "1111", true), /*线上平台的id范围为0到99,测试平台的id范围为100+*/ /** * 测试平台:test12 */ TEST12(110, "test12", "https://test12open.ys7.com", "https://test12openauth.ys7.com", "b22035492c7949bca95286382ed90b01"), /** * 测试平台:testcn */ TEST_CN(115, "testcn", "https://testcnopen.ezvizlife.com", "https://testcnopenauth.ezvizlife.com", true), /** * 测试平台:testus */ TEST_US(120, "testus", "https://testusopen.ezvizlife.com", "https://testusopenauth.ezvizlife.com", true), /** * 测试平台:testeu */ // TEST_EU(125, "testeu", "https://testeuopen.ezvizlife.com", // "https://testeuopenauth.ezvizlife.com", true), TEST_EU(125, "testeu", "https://ys-open.wens.com.cn", "https://test2auth.ys7.com:8643", true), /** * 温氏 */ WENSHI(126, "WenShi", "https://ezcpcloudopen.wens.com.cn", "https://ezcpcloudopenauth.wens.com.cn", false), /** * 华住 <SUF>*/ HUAZHU(127, "HuaZhu", "https://ezcpatctestopen.ys7.com", "https://ezcpatctestopenauth.ys7.com", false); // TEST_NEW(130,"testnew", "https://ys-open.wens.com.cn", // "https://test2auth.ys7.com:8643", true); public int id; public String areaName; public String openApiServer; public String openAuthApiServer; // 预置的用于测试h5登录的appKey(该appKey的bundleId已绑定到ezviz.opensdk) public String defaultOpenAuthAppKey; // 是否正在海外域名,海外域名需要使用GlobalEZOpenSDK,反之使用EZOpenSDK public boolean usingGlobalSDK; ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer){ this(id, areaName, openApiServer, openAuthApiServer, null, false); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey){ this(id, areaName, openApiServer, openAuthApiServer, defaultOpenAuthAppKey, false); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, boolean usingGlobalSDK){ this(id, areaName, openApiServer, openAuthApiServer, null, usingGlobalSDK); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey, boolean usingGlobalSDK){ this.id = id; this.areaName = areaName; this.openApiServer = openApiServer; this.openAuthApiServer = openAuthApiServer; this.defaultOpenAuthAppKey = defaultOpenAuthAppKey; this.usingGlobalSDK = usingGlobalSDK; } public static List<ServerAreasEnum> getAllServers(){ List<ServerAreasEnum> serversList = new ArrayList<>(); for (ServerAreasEnum server : values()) { boolean isTestServer = server.id >= 100; // 线上demo不展示测试平台 if (!com.videogo.openapi.BuildConfig.DEBUG && isTestServer) { continue; } serversList.add(server); } return serversList; } @Override public String toString() { return "id: " + id + ", " + "areaName: " + areaName + ", " + "openApiServer: " + openApiServer + ", " + "openAuthApiServer: " + openAuthApiServer; } }
0
34734_3
package com.ezviz.open.model; import com.ezviz.open.utils.CameraCaptureCache; import com.videogo.openapi.bean.EZCameraInfo; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Description:通道信息类 * Created by dingwei3 * * @date : 2016/12/5 */ public class EZOpenCameraInfo extends RealmObject{ /** * 设备序列号加camerNo组成主键存储 */ @PrimaryKey private String deviceSerial_cameraNo; /** * camera对应的设备数字序列号 */ private String deviceSerial = null; /** * camera在对应设备上的通道号,若为IPC设备,该字段始终为1 */ private int cameraNo = 0; /** * camera名称,若为IPC设备,和EZDeviceInfo中deviceName会保持一致 */ private String cameraName = null; /** * 分享状态 * 1-分享所有者,0-未分享,2-分享接受者(表示此摄像头是别人分享给我的) */ private int isShared = 0; /** * 封面url */ private String cameraCover = null; /** * 清晰度 * 0-流畅,1-均衡,2-高清,3-超清 */ private int videoLevel = 0; /** * 在线状态,1-在线,2-不在线 */ private int status = 1; /** * 设备布防状态 * A1设备:0-睡眠 8-在家 16-外出 * 非A1设备如IPC:0-撤防 1-布防 */ private int defence = 0; /** * 设备型号 */ private String deviceType; /** * 设备大类 */ private String category = null; /** * 是否支持布撤防 */ private boolean isSupportDefence; /** * 支持的清晰度信息 */ private RealmList<EZOpenVideoQualityInfo> mEZOpenVideoQualityInfos; public String getDeviceSerial() { return deviceSerial; } public void setDeviceSerial(String deviceSerial) { this.deviceSerial = deviceSerial; } public int getCameraNo() { return cameraNo; } public void setCameraNo(int cameraNo) { this.cameraNo = cameraNo; } public String getCameraName() { return cameraName; } public void setCameraName(String cameraName) { this.cameraName = cameraName; } public int getIsShared() { return isShared; } public void setIsShared(int isShared) { this.isShared = isShared; } public String getCameraCover() { return cameraCover; } public void setCameraCover(String cameraCover) { this.cameraCover = cameraCover; } public int getVideoLevel() { return videoLevel; } public void setVideoLevel(int videoLevel) { this.videoLevel = videoLevel; } public String getDeviceSerial_cameraNo() { return deviceSerial_cameraNo; } public void setDeviceSerial_cameraNo(String deviceSerial_cameraNo) { this.deviceSerial_cameraNo = deviceSerial_cameraNo; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public int getDefence() { return defence; } public void setDefence(int defence) { this.defence = defence; } public boolean isSupportDefence() { return isSupportDefence; } public void setSupportDefence(boolean supportDefence) { isSupportDefence = supportDefence; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public RealmList<EZOpenVideoQualityInfo> getEZOpenVideoQualityInfos() { return mEZOpenVideoQualityInfos; } public void setEZOpenVideoQualityInfos(RealmList<EZOpenVideoQualityInfo> EZOpenVideoQualityInfos) { mEZOpenVideoQualityInfos = EZOpenVideoQualityInfos; } public void copy(EZCameraInfo cameraInfo){ setCameraCover(cameraInfo.getCameraCover()); setCameraName(cameraInfo.getCameraName()); setCameraNo(cameraInfo.getCameraNo()); setDeviceSerial(cameraInfo.getDeviceSerial()); setIsShared(cameraInfo.getIsShared()); setVideoLevel(cameraInfo.getCurrentVideoLevel().getVideoLevel()); CameraCaptureCache.getInstance().addCoverRefresh(cameraInfo.getDeviceSerial(),cameraInfo.getCameraNo(),true); } }
Ezviz-OpenBiz/EZOpenAPP-Lite-Android
example/EZOpenAPP-Lite-Android/app/src/main/java/com/ezviz/open/model/EZOpenCameraInfo.java
1,178
/** * camera在对应设备上的通道号,若为IPC设备,该字段始终为1 */
block_comment
zh-cn
package com.ezviz.open.model; import com.ezviz.open.utils.CameraCaptureCache; import com.videogo.openapi.bean.EZCameraInfo; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Description:通道信息类 * Created by dingwei3 * * @date : 2016/12/5 */ public class EZOpenCameraInfo extends RealmObject{ /** * 设备序列号加camerNo组成主键存储 */ @PrimaryKey private String deviceSerial_cameraNo; /** * camera对应的设备数字序列号 */ private String deviceSerial = null; /** * cam <SUF>*/ private int cameraNo = 0; /** * camera名称,若为IPC设备,和EZDeviceInfo中deviceName会保持一致 */ private String cameraName = null; /** * 分享状态 * 1-分享所有者,0-未分享,2-分享接受者(表示此摄像头是别人分享给我的) */ private int isShared = 0; /** * 封面url */ private String cameraCover = null; /** * 清晰度 * 0-流畅,1-均衡,2-高清,3-超清 */ private int videoLevel = 0; /** * 在线状态,1-在线,2-不在线 */ private int status = 1; /** * 设备布防状态 * A1设备:0-睡眠 8-在家 16-外出 * 非A1设备如IPC:0-撤防 1-布防 */ private int defence = 0; /** * 设备型号 */ private String deviceType; /** * 设备大类 */ private String category = null; /** * 是否支持布撤防 */ private boolean isSupportDefence; /** * 支持的清晰度信息 */ private RealmList<EZOpenVideoQualityInfo> mEZOpenVideoQualityInfos; public String getDeviceSerial() { return deviceSerial; } public void setDeviceSerial(String deviceSerial) { this.deviceSerial = deviceSerial; } public int getCameraNo() { return cameraNo; } public void setCameraNo(int cameraNo) { this.cameraNo = cameraNo; } public String getCameraName() { return cameraName; } public void setCameraName(String cameraName) { this.cameraName = cameraName; } public int getIsShared() { return isShared; } public void setIsShared(int isShared) { this.isShared = isShared; } public String getCameraCover() { return cameraCover; } public void setCameraCover(String cameraCover) { this.cameraCover = cameraCover; } public int getVideoLevel() { return videoLevel; } public void setVideoLevel(int videoLevel) { this.videoLevel = videoLevel; } public String getDeviceSerial_cameraNo() { return deviceSerial_cameraNo; } public void setDeviceSerial_cameraNo(String deviceSerial_cameraNo) { this.deviceSerial_cameraNo = deviceSerial_cameraNo; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public int getDefence() { return defence; } public void setDefence(int defence) { this.defence = defence; } public boolean isSupportDefence() { return isSupportDefence; } public void setSupportDefence(boolean supportDefence) { isSupportDefence = supportDefence; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public RealmList<EZOpenVideoQualityInfo> getEZOpenVideoQualityInfos() { return mEZOpenVideoQualityInfos; } public void setEZOpenVideoQualityInfos(RealmList<EZOpenVideoQualityInfo> EZOpenVideoQualityInfos) { mEZOpenVideoQualityInfos = EZOpenVideoQualityInfos; } public void copy(EZCameraInfo cameraInfo){ setCameraCover(cameraInfo.getCameraCover()); setCameraName(cameraInfo.getCameraName()); setCameraNo(cameraInfo.getCameraNo()); setDeviceSerial(cameraInfo.getDeviceSerial()); setIsShared(cameraInfo.getIsShared()); setVideoLevel(cameraInfo.getCurrentVideoLevel().getVideoLevel()); CameraCaptureCache.getInstance().addCoverRefresh(cameraInfo.getDeviceSerial(),cameraInfo.getCameraNo(),true); } }
1
61834_50
package burp; import yaml.YamlUtil; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.List; import java.util.Map; public class Config { private JPanel one; private JTextField txtfield1; public String yaml_path = BurpExtender.Yaml_Path; public JSpinner spinner1; private BurpExtender burp; public JTabbedPane ruleTabbedPane; public TabTitleEditListener ruleSwitch; protected static JPopupMenu tabMenu = new JPopupMenu(); private JMenuItem closeTabMenuItem = new JMenuItem("Delete"); private static int RulesInt = 0; public static String new_Rules() { RulesInt += 1; return "New " + RulesInt; } public void newTab() { Object[][] data = new Object[][]{{false, "New Name", "(New Regex)", "gray", "any", "nfa", false}}; insertTab(ruleTabbedPane, Config.new_Rules(), data); } public void insertTab(JTabbedPane pane, String title, Object[][] data) { pane.addTab(title, new JLabel()); pane.remove(pane.getSelectedIndex()); pane.addTab("...", new JLabel()); } public void closeTabActionPerformed(ActionEvent e) { if (ruleTabbedPane.getTabCount() > 2) { Dialog frame = new JDialog();//构造一个新的JFrame,作为新窗口。 frame.setBounds( new Rectangle( // 让新窗口与SwingTest窗口示例错开50像素。 620, 300, // 窗口总大小-500像素 200, 100 ) ); JPanel xin = new JPanel(); xin.setLayout(null); JLabel Tips = new JLabel("Are you sure you want to delete"); Tips.setBounds(20, 10, 200, 20); xin.add(Tips); // Ok JButton Ok_button = new JButton("Yes"); Ok_button.setBounds(120, 40, 60, 20); xin.add(Ok_button); Ok_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String type = ruleTabbedPane.getTitleAt(ruleTabbedPane.getSelectedIndex()); View Remove_view = burp.views.get(type); if (Remove_view != null) { for (View.LogEntry l : Remove_view.log) { YamlUtil.removeYaml(l.id, BurpExtender.Yaml_Path); } } ruleTabbedPane.remove(ruleTabbedPane.getSelectedIndex()); frame.dispose(); } }); // no JButton No_button = new JButton("NO"); No_button.setBounds(30, 40, 60, 20); xin.add(No_button); No_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.dispose(); } }); ((JDialog) frame).getContentPane().add(xin); frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 设置模式类型。 frame.setVisible(true); } } public Config(BurpExtender burp) { tabMenu.add(closeTabMenuItem); closeTabMenuItem.addActionListener(e -> closeTabActionPerformed(e)); this.burp = burp; } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { one = new JPanel(); one.setLayout(null); one.setBounds(0, 0, 1180, 500); // Yaml File Path 文本展示框 JLabel yaml_Path = new JLabel("Yaml File Path:"); yaml_Path.setBounds(5, 20, 100, 50); // 展示路径 txtfield1 = new JTextField(); //创建文本框 txtfield1.setText(yaml_path); //设置文本框的内容 txtfield1.setEditable(false); txtfield1.setBounds(110, 35, 772, 20); // Online Update按钮 JButton Online_Update_button = new JButton("Update"); Online_Update_button.setBounds(886, 34, 87, 23); Online_Update_Yaml(Online_Update_button); // load 按钮 JButton load_button = new JButton("Load Yaml"); load_button.setBounds(980, 34, 87, 23); load_button_Yaml(load_button); // 线程选择 JLabel thread_num = new JLabel("Thread Numbers:"); thread_num.setBounds(1074, 20, 100, 50); SpinnerNumberModel model1 = new SpinnerNumberModel(10, 1, 500, 3); this.spinner1 = new JSpinner(model1); ((JSpinner.DefaultEditor) this.spinner1.getEditor()).getTextField().setEditable(false); this.spinner1.setBounds(1168, 34, 100, 23); // add按钮 JButton add_button = new JButton("Add"); add_button.setBounds(5, 75, 70, 23); Add_Button_Yaml(add_button, yaml_path); // Edit按钮 JButton edit_button = new JButton("Edit"); edit_button.setBounds(5, 100, 70, 23); // Edit_Button_Yaml(edit_button,yaml_path,view_class,log); Edit_Button_Yaml(edit_button, yaml_path); // Del按钮 JButton remove_button = new JButton("Del"); remove_button.setBounds(5, 125, 70, 23); Del_Button_Yaml(remove_button, yaml_path); // 展示界面容器 ruleTabbedPane = new JTabbedPane(); this.ruleSwitch = new TabTitleEditListener(ruleTabbedPane, this.burp); ruleTabbedPane.setBounds(80, 60, 1185, 740); Bfunc.show_yaml(burp); ruleTabbedPane.addMouseListener(ruleSwitch); // // Switch 文本展示框 // JLabel Expansion_switch = new JLabel("Extend Switch:"); // Expansion_switch.setBounds(5, -10, 100, 50); // 开启按钮 // JButton on_off_button = new JButton("Stop"); JButton on_off_button = new JButton("Start"); on_off_button.setBounds(20, 5, 70, 23); Color Primary = on_off_button.getBackground(); // on_off_button.setBackground(Color.green); on_off_Button_action(on_off_button, Primary); // // Switch 文本展示框 // JLabel Carry_head = new JLabel("Carry Head:"); // Carry_head.setBounds(224, -10, 100, 50); // 携带head按钮 JButton carry_head_button = new JButton("Head_On"); carry_head_button.setBounds(150, 5, 90, 23); carry_head_Button_action(carry_head_button, Primary); // DomainScan按钮 JButton DomainScan_button = new JButton("DomainScan_On"); DomainScan_button.setBounds(300, 5, 90, 23); DomainScan_Button_action(DomainScan_button, DomainScan_button.getBackground()); // bypass按钮 JButton bypass_button = new JButton("Bypass_On"); bypass_button.setBounds(450, 5, 90, 23); bypass_Button_action(bypass_button, bypass_button.getBackground()); // Filter_Host 文本展示框 JLabel Filter_Host = new JLabel("Filter_Host:"); Filter_Host.setBounds(623, -10, 100, 50); // Host 输入框 JTextField Host_txtfield = new JTextField(); //创建文本框 Host_txtfield.setText("*"); //设置文本框的内容 Host_txtfield.setBounds(698, 5, 572, 20); burp.Host_txtfield = Host_txtfield; // 添加到主面板 one.add(yaml_Path); one.add(txtfield1); one.add(Online_Update_button); one.add(load_button); one.add(DomainScan_button); one.add(bypass_button); one.add(add_button); one.add(edit_button); one.add(remove_button); one.add(ruleTabbedPane); one.add(thread_num); one.add(spinner1); // one.add(Expansion_switch); one.add(on_off_button); // one.add(Carry_head); one.add(carry_head_button); one.add(Filter_Host); one.add(Host_txtfield); } private void carry_head_Button_action(JButton Button_one, Color Primary) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (burp.Carry_head) { burp.Carry_head = false; Button_one.setText("Head_On"); Button_one.setBackground(Primary); } else { burp.Carry_head = true; Button_one.setText("Head_Off"); Button_one.setBackground(Color.green); } } }); } private void on_off_Button_action(JButton Button_one, Color Primary) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (burp.on_off) { burp.on_off = false; Button_one.setText("Start"); Button_one.setBackground(Primary); } else { burp.on_off = true; Button_one.setText("Stop"); Button_one.setBackground(Color.green); } } }); } private void bypass_Button_action(JButton Button_one, Color Primary) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (burp.Bypass) { burp.Bypass = false; Button_one.setText("Bypass_On"); Button_one.setBackground(Primary); } else { burp.Bypass = true; Button_one.setText("Bypass_Off"); Button_one.setBackground(Color.green); } } }); } private void DomainScan_Button_action(JButton Button_one, Color Primary) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (burp.DomainScan) { burp.DomainScan = false; Button_one.setText("DomainScan_On"); Button_one.setBackground(Primary); } else { burp.DomainScan = true; Button_one.setText("DomainScan_Off"); Button_one.setBackground(Color.green); } } }); } private void Online_Update_Yaml(JButton Button_one) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { YamlUtil.init_Yaml(burp, one); } }); } private void Edit_Button_Yaml(JButton Button_one, String yaml_path1) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialog frame = new JDialog();//构造一个新的JFrame,作为新窗口。 frame.setBounds( new Rectangle( // 让新窗口与SwingTest窗口示例错开50像素。 620, 300, // 窗口总大小-500像素 300, 300 ) ); String type = ruleTabbedPane.getTitleAt(ruleTabbedPane.getSelectedIndex()); View view_class = burp.views.get(type); JPanel xin = new JPanel(); xin.setLayout(null); // Name JLabel Name_field = new JLabel("Name :"); JTextField Name_text = new JTextField(); Name_text.setText(view_class.Choice.name); Name_field.setBounds(10, 5, 40, 20); Name_text.setBounds(65, 5, 200, 20); xin.add(Name_field); xin.add(Name_text); // Method JLabel Method_field = new JLabel("Method :"); // JTextField Method_text = new JTextField(); JComboBox Method_text = new JComboBox(); //创建JComboBox Method_text.addItem("GET"); //向下拉列表中添加一项 Method_text.addItem("POST"); //向下拉列表中添加一项 Method_text.setSelectedItem(view_class.Choice.method); Method_field.setBounds(10, 45, 40, 20); Method_text.setBounds(65, 45, 200, 20); xin.add(Method_field); xin.add(Method_text); // Url JLabel Url_field = new JLabel("Url :"); JTextField Url_text = new JTextField(); Url_text.setText(view_class.Choice.url); Url_field.setBounds(10, 85, 40, 20); Url_text.setBounds(65, 85, 200, 20); xin.add(Url_field); xin.add(Url_text); // Re JLabel Re_field = new JLabel("Re :"); JTextField Re_text = new JTextField(); Re_text.setText(view_class.Choice.re); Re_field.setBounds(10, 125, 40, 20); Re_text.setBounds(65, 125, 200, 20); xin.add(Re_field); xin.add(Re_text); // Info JLabel Info_field = new JLabel("Info :"); JTextField Info_text = new JTextField(); Info_text.setText(view_class.Choice.info); Info_field.setBounds(10, 165, 40, 20); Info_text.setBounds(65, 165, 200, 20); xin.add(Info_field); xin.add(Info_text); // state JLabel State_field = new JLabel("state :"); JTextField State_text = new JTextField(); State_text.setText(view_class.Choice.state); State_field.setBounds(10, 205, 40, 20); State_text.setBounds(65, 205, 200, 20); xin.add(State_field); xin.add(State_text); // Ok JButton Ok_button = new JButton("OK"); Ok_button.setBounds(200, 245, 60, 20); xin.add(Ok_button); Ok_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String name = Name_text.getText(); String url = Url_text.getText(); String method = (String) Method_text.getSelectedItem(); String re = Re_text.getText(); String info = Info_text.getText(); String state = State_text.getText(); Map<String, Object> add_map = new HashMap<String, Object>(); add_map.put("id", Integer.parseInt(view_class.Choice.id)); add_map.put("type", type); add_map.put("loaded", view_class.Choice.loaded); add_map.put("name", name); add_map.put("method", method); add_map.put("url", url); add_map.put("re", re); add_map.put("info", info); add_map.put("state", state); YamlUtil.updateYaml(add_map, yaml_path1); // burp.views = Bfunc.Get_Views(); // Bfunc.show_yaml(burp); Bfunc.show_yaml_view(burp, view_class, type); frame.dispose(); } }); // no JButton No_button = new JButton("NO"); No_button.setBounds(130, 245, 60, 20); xin.add(No_button); No_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.dispose(); } }); frame.getContentPane().add(xin); frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 设置模式类型。 frame.setVisible(true); } }); } private void Del_Button_Yaml(JButton Button_one, String yaml_path1) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String type = ruleTabbedPane.getTitleAt(ruleTabbedPane.getSelectedIndex()); View view_class = burp.views.get(type); if (view_class.Choice != null) { JDialog frame = new JDialog();//构造一个新的JFrame,作为新窗口。 frame.setBounds( new Rectangle( // 让新窗口与SwingTest窗口示例错开50像素。 620, 300, // 窗口总大小-500像素 200, 100 ) ); JPanel xin = new JPanel(); xin.setLayout(null); JLabel Tips = new JLabel("Are you sure you want to delete"); Tips.setBounds(20, 10, 200, 20); xin.add(Tips); // Ok JButton Ok_button = new JButton("Yes"); Ok_button.setBounds(120, 40, 60, 20); xin.add(Ok_button); Ok_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { YamlUtil.removeYaml(view_class.Choice.id, yaml_path1); // burp.views = Bfunc.Get_Views(); Bfunc.show_yaml_view(burp, view_class, type); frame.dispose(); } }); // no JButton No_button = new JButton("NO"); No_button.setBounds(30, 40, 60, 20); xin.add(No_button); No_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.dispose(); } }); frame.getContentPane().add(xin); frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 设置模式类型。 frame.setVisible(true); } } }); } private void Add_Button_Yaml(JButton Button_one, String yaml_path1) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // burp.call.printOutput(ruleSwitch.ruleEditTextField.getText().trim()); JDialog frame = new JDialog();//构造一个新的JFrame,作为新窗口。 frame.setBounds( new Rectangle( // 让新窗口与SwingTest窗口示例错开50像素。 620, 300, // 窗口总大小-500像素 300, 300 ) ); String type = ruleTabbedPane.getTitleAt(ruleTabbedPane.getSelectedIndex()); JPanel xin = new JPanel(); xin.setLayout(null); // Name JLabel Name_field = new JLabel("Name :"); JTextField Name_text = new JTextField(); Name_field.setBounds(10, 5, 40, 20); Name_text.setBounds(65, 5, 200, 20); xin.add(Name_field); xin.add(Name_text); // Method JLabel Method_field = new JLabel("Method :"); JComboBox Method_text = new JComboBox(); //创建JComboBox Method_text.addItem("GET"); //向下拉列表中添加一项 Method_text.addItem("POST"); //向下拉列表中添加一项 Method_field.setBounds(10, 45, 40, 20); Method_text.setBounds(65, 45, 200, 20); xin.add(Method_field); xin.add(Method_text); // Url JLabel Url_field = new JLabel("Url :"); JTextField Url_text = new JTextField(); Url_field.setBounds(10, 85, 40, 20); Url_text.setBounds(65, 85, 200, 20); xin.add(Url_field); xin.add(Url_text); // Re JLabel Re_field = new JLabel("Re :"); JTextField Re_text = new JTextField(); Re_field.setBounds(10, 125, 40, 20); Re_text.setBounds(65, 125, 200, 20); xin.add(Re_field); xin.add(Re_text); // Info JLabel Info_field = new JLabel("Info :"); JTextField Info_text = new JTextField(); Info_field.setBounds(10, 165, 40, 20); Info_text.setBounds(65, 165, 200, 20); xin.add(Info_field); xin.add(Info_text); // State JLabel State_field = new JLabel("State :"); JTextField State_text = new JTextField(); State_field.setBounds(10, 205, 40, 20); State_text.setBounds(65, 205, 200, 20); xin.add(State_field); xin.add(State_text); // Ok JButton Ok_button = new JButton("OK"); Ok_button.setBounds(200, 245, 60, 20); xin.add(Ok_button); Ok_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = 0; Map<String, Object> Yaml_Map = YamlUtil.readYaml(yaml_path1); List<Map<String, Object>> List1 = (List<Map<String, Object>>) Yaml_Map.get("Load_List"); for (Map<String, Object> zidian : List1) { if ((int) zidian.get("id") > id) { id = (int) zidian.get("id"); } } id += 1; String name = Name_text.getText(); String url = Url_text.getText(); String method = (String) Method_text.getSelectedItem(); String re = Re_text.getText(); String info = Info_text.getText(); String state = State_text.getText(); Map<String, Object> add_map = new HashMap<String, Object>(); add_map.put("type", type); add_map.put("id", id); add_map.put("loaded", true); add_map.put("name", name); add_map.put("method", method); add_map.put("url", url); add_map.put("re", re); add_map.put("info", info); add_map.put("state", state); YamlUtil.addYaml(add_map, yaml_path1); Bfunc.show_yaml_view(burp, burp.views.get(type), type); frame.dispose(); } }); // no JButton No_button = new JButton("NO"); No_button.setBounds(130, 245, 60, 20); xin.add(No_button); No_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.dispose(); } }); frame.getContentPane().add(xin); frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 设置模式类型。 frame.setVisible(true); } }); } private void load_button_Yaml(JButton Button_one) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Bfunc.show_yaml(burp); } }); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { $$$setupUI$$$(); return one; } }
F6JO/RouteVulScan
src/main/java/burp/Config.java
6,017
// 设置模式类型。
line_comment
zh-cn
package burp; import yaml.YamlUtil; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.List; import java.util.Map; public class Config { private JPanel one; private JTextField txtfield1; public String yaml_path = BurpExtender.Yaml_Path; public JSpinner spinner1; private BurpExtender burp; public JTabbedPane ruleTabbedPane; public TabTitleEditListener ruleSwitch; protected static JPopupMenu tabMenu = new JPopupMenu(); private JMenuItem closeTabMenuItem = new JMenuItem("Delete"); private static int RulesInt = 0; public static String new_Rules() { RulesInt += 1; return "New " + RulesInt; } public void newTab() { Object[][] data = new Object[][]{{false, "New Name", "(New Regex)", "gray", "any", "nfa", false}}; insertTab(ruleTabbedPane, Config.new_Rules(), data); } public void insertTab(JTabbedPane pane, String title, Object[][] data) { pane.addTab(title, new JLabel()); pane.remove(pane.getSelectedIndex()); pane.addTab("...", new JLabel()); } public void closeTabActionPerformed(ActionEvent e) { if (ruleTabbedPane.getTabCount() > 2) { Dialog frame = new JDialog();//构造一个新的JFrame,作为新窗口。 frame.setBounds( new Rectangle( // 让新窗口与SwingTest窗口示例错开50像素。 620, 300, // 窗口总大小-500像素 200, 100 ) ); JPanel xin = new JPanel(); xin.setLayout(null); JLabel Tips = new JLabel("Are you sure you want to delete"); Tips.setBounds(20, 10, 200, 20); xin.add(Tips); // Ok JButton Ok_button = new JButton("Yes"); Ok_button.setBounds(120, 40, 60, 20); xin.add(Ok_button); Ok_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String type = ruleTabbedPane.getTitleAt(ruleTabbedPane.getSelectedIndex()); View Remove_view = burp.views.get(type); if (Remove_view != null) { for (View.LogEntry l : Remove_view.log) { YamlUtil.removeYaml(l.id, BurpExtender.Yaml_Path); } } ruleTabbedPane.remove(ruleTabbedPane.getSelectedIndex()); frame.dispose(); } }); // no JButton No_button = new JButton("NO"); No_button.setBounds(30, 40, 60, 20); xin.add(No_button); No_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.dispose(); } }); ((JDialog) frame).getContentPane().add(xin); frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 设置模式类型。 frame.setVisible(true); } } public Config(BurpExtender burp) { tabMenu.add(closeTabMenuItem); closeTabMenuItem.addActionListener(e -> closeTabActionPerformed(e)); this.burp = burp; } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { one = new JPanel(); one.setLayout(null); one.setBounds(0, 0, 1180, 500); // Yaml File Path 文本展示框 JLabel yaml_Path = new JLabel("Yaml File Path:"); yaml_Path.setBounds(5, 20, 100, 50); // 展示路径 txtfield1 = new JTextField(); //创建文本框 txtfield1.setText(yaml_path); //设置文本框的内容 txtfield1.setEditable(false); txtfield1.setBounds(110, 35, 772, 20); // Online Update按钮 JButton Online_Update_button = new JButton("Update"); Online_Update_button.setBounds(886, 34, 87, 23); Online_Update_Yaml(Online_Update_button); // load 按钮 JButton load_button = new JButton("Load Yaml"); load_button.setBounds(980, 34, 87, 23); load_button_Yaml(load_button); // 线程选择 JLabel thread_num = new JLabel("Thread Numbers:"); thread_num.setBounds(1074, 20, 100, 50); SpinnerNumberModel model1 = new SpinnerNumberModel(10, 1, 500, 3); this.spinner1 = new JSpinner(model1); ((JSpinner.DefaultEditor) this.spinner1.getEditor()).getTextField().setEditable(false); this.spinner1.setBounds(1168, 34, 100, 23); // add按钮 JButton add_button = new JButton("Add"); add_button.setBounds(5, 75, 70, 23); Add_Button_Yaml(add_button, yaml_path); // Edit按钮 JButton edit_button = new JButton("Edit"); edit_button.setBounds(5, 100, 70, 23); // Edit_Button_Yaml(edit_button,yaml_path,view_class,log); Edit_Button_Yaml(edit_button, yaml_path); // Del按钮 JButton remove_button = new JButton("Del"); remove_button.setBounds(5, 125, 70, 23); Del_Button_Yaml(remove_button, yaml_path); // 展示界面容器 ruleTabbedPane = new JTabbedPane(); this.ruleSwitch = new TabTitleEditListener(ruleTabbedPane, this.burp); ruleTabbedPane.setBounds(80, 60, 1185, 740); Bfunc.show_yaml(burp); ruleTabbedPane.addMouseListener(ruleSwitch); // // Switch 文本展示框 // JLabel Expansion_switch = new JLabel("Extend Switch:"); // Expansion_switch.setBounds(5, -10, 100, 50); // 开启按钮 // JButton on_off_button = new JButton("Stop"); JButton on_off_button = new JButton("Start"); on_off_button.setBounds(20, 5, 70, 23); Color Primary = on_off_button.getBackground(); // on_off_button.setBackground(Color.green); on_off_Button_action(on_off_button, Primary); // // Switch 文本展示框 // JLabel Carry_head = new JLabel("Carry Head:"); // Carry_head.setBounds(224, -10, 100, 50); // 携带head按钮 JButton carry_head_button = new JButton("Head_On"); carry_head_button.setBounds(150, 5, 90, 23); carry_head_Button_action(carry_head_button, Primary); // DomainScan按钮 JButton DomainScan_button = new JButton("DomainScan_On"); DomainScan_button.setBounds(300, 5, 90, 23); DomainScan_Button_action(DomainScan_button, DomainScan_button.getBackground()); // bypass按钮 JButton bypass_button = new JButton("Bypass_On"); bypass_button.setBounds(450, 5, 90, 23); bypass_Button_action(bypass_button, bypass_button.getBackground()); // Filter_Host 文本展示框 JLabel Filter_Host = new JLabel("Filter_Host:"); Filter_Host.setBounds(623, -10, 100, 50); // Host 输入框 JTextField Host_txtfield = new JTextField(); //创建文本框 Host_txtfield.setText("*"); //设置文本框的内容 Host_txtfield.setBounds(698, 5, 572, 20); burp.Host_txtfield = Host_txtfield; // 添加到主面板 one.add(yaml_Path); one.add(txtfield1); one.add(Online_Update_button); one.add(load_button); one.add(DomainScan_button); one.add(bypass_button); one.add(add_button); one.add(edit_button); one.add(remove_button); one.add(ruleTabbedPane); one.add(thread_num); one.add(spinner1); // one.add(Expansion_switch); one.add(on_off_button); // one.add(Carry_head); one.add(carry_head_button); one.add(Filter_Host); one.add(Host_txtfield); } private void carry_head_Button_action(JButton Button_one, Color Primary) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (burp.Carry_head) { burp.Carry_head = false; Button_one.setText("Head_On"); Button_one.setBackground(Primary); } else { burp.Carry_head = true; Button_one.setText("Head_Off"); Button_one.setBackground(Color.green); } } }); } private void on_off_Button_action(JButton Button_one, Color Primary) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (burp.on_off) { burp.on_off = false; Button_one.setText("Start"); Button_one.setBackground(Primary); } else { burp.on_off = true; Button_one.setText("Stop"); Button_one.setBackground(Color.green); } } }); } private void bypass_Button_action(JButton Button_one, Color Primary) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (burp.Bypass) { burp.Bypass = false; Button_one.setText("Bypass_On"); Button_one.setBackground(Primary); } else { burp.Bypass = true; Button_one.setText("Bypass_Off"); Button_one.setBackground(Color.green); } } }); } private void DomainScan_Button_action(JButton Button_one, Color Primary) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (burp.DomainScan) { burp.DomainScan = false; Button_one.setText("DomainScan_On"); Button_one.setBackground(Primary); } else { burp.DomainScan = true; Button_one.setText("DomainScan_Off"); Button_one.setBackground(Color.green); } } }); } private void Online_Update_Yaml(JButton Button_one) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { YamlUtil.init_Yaml(burp, one); } }); } private void Edit_Button_Yaml(JButton Button_one, String yaml_path1) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialog frame = new JDialog();//构造一个新的JFrame,作为新窗口。 frame.setBounds( new Rectangle( // 让新窗口与SwingTest窗口示例错开50像素。 620, 300, // 窗口总大小-500像素 300, 300 ) ); String type = ruleTabbedPane.getTitleAt(ruleTabbedPane.getSelectedIndex()); View view_class = burp.views.get(type); JPanel xin = new JPanel(); xin.setLayout(null); // Name JLabel Name_field = new JLabel("Name :"); JTextField Name_text = new JTextField(); Name_text.setText(view_class.Choice.name); Name_field.setBounds(10, 5, 40, 20); Name_text.setBounds(65, 5, 200, 20); xin.add(Name_field); xin.add(Name_text); // Method JLabel Method_field = new JLabel("Method :"); // JTextField Method_text = new JTextField(); JComboBox Method_text = new JComboBox(); //创建JComboBox Method_text.addItem("GET"); //向下拉列表中添加一项 Method_text.addItem("POST"); //向下拉列表中添加一项 Method_text.setSelectedItem(view_class.Choice.method); Method_field.setBounds(10, 45, 40, 20); Method_text.setBounds(65, 45, 200, 20); xin.add(Method_field); xin.add(Method_text); // Url JLabel Url_field = new JLabel("Url :"); JTextField Url_text = new JTextField(); Url_text.setText(view_class.Choice.url); Url_field.setBounds(10, 85, 40, 20); Url_text.setBounds(65, 85, 200, 20); xin.add(Url_field); xin.add(Url_text); // Re JLabel Re_field = new JLabel("Re :"); JTextField Re_text = new JTextField(); Re_text.setText(view_class.Choice.re); Re_field.setBounds(10, 125, 40, 20); Re_text.setBounds(65, 125, 200, 20); xin.add(Re_field); xin.add(Re_text); // Info JLabel Info_field = new JLabel("Info :"); JTextField Info_text = new JTextField(); Info_text.setText(view_class.Choice.info); Info_field.setBounds(10, 165, 40, 20); Info_text.setBounds(65, 165, 200, 20); xin.add(Info_field); xin.add(Info_text); // state JLabel State_field = new JLabel("state :"); JTextField State_text = new JTextField(); State_text.setText(view_class.Choice.state); State_field.setBounds(10, 205, 40, 20); State_text.setBounds(65, 205, 200, 20); xin.add(State_field); xin.add(State_text); // Ok JButton Ok_button = new JButton("OK"); Ok_button.setBounds(200, 245, 60, 20); xin.add(Ok_button); Ok_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String name = Name_text.getText(); String url = Url_text.getText(); String method = (String) Method_text.getSelectedItem(); String re = Re_text.getText(); String info = Info_text.getText(); String state = State_text.getText(); Map<String, Object> add_map = new HashMap<String, Object>(); add_map.put("id", Integer.parseInt(view_class.Choice.id)); add_map.put("type", type); add_map.put("loaded", view_class.Choice.loaded); add_map.put("name", name); add_map.put("method", method); add_map.put("url", url); add_map.put("re", re); add_map.put("info", info); add_map.put("state", state); YamlUtil.updateYaml(add_map, yaml_path1); // burp.views = Bfunc.Get_Views(); // Bfunc.show_yaml(burp); Bfunc.show_yaml_view(burp, view_class, type); frame.dispose(); } }); // no JButton No_button = new JButton("NO"); No_button.setBounds(130, 245, 60, 20); xin.add(No_button); No_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.dispose(); } }); frame.getContentPane().add(xin); frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 设置 <SUF> frame.setVisible(true); } }); } private void Del_Button_Yaml(JButton Button_one, String yaml_path1) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String type = ruleTabbedPane.getTitleAt(ruleTabbedPane.getSelectedIndex()); View view_class = burp.views.get(type); if (view_class.Choice != null) { JDialog frame = new JDialog();//构造一个新的JFrame,作为新窗口。 frame.setBounds( new Rectangle( // 让新窗口与SwingTest窗口示例错开50像素。 620, 300, // 窗口总大小-500像素 200, 100 ) ); JPanel xin = new JPanel(); xin.setLayout(null); JLabel Tips = new JLabel("Are you sure you want to delete"); Tips.setBounds(20, 10, 200, 20); xin.add(Tips); // Ok JButton Ok_button = new JButton("Yes"); Ok_button.setBounds(120, 40, 60, 20); xin.add(Ok_button); Ok_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { YamlUtil.removeYaml(view_class.Choice.id, yaml_path1); // burp.views = Bfunc.Get_Views(); Bfunc.show_yaml_view(burp, view_class, type); frame.dispose(); } }); // no JButton No_button = new JButton("NO"); No_button.setBounds(30, 40, 60, 20); xin.add(No_button); No_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.dispose(); } }); frame.getContentPane().add(xin); frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 设置模式类型。 frame.setVisible(true); } } }); } private void Add_Button_Yaml(JButton Button_one, String yaml_path1) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // burp.call.printOutput(ruleSwitch.ruleEditTextField.getText().trim()); JDialog frame = new JDialog();//构造一个新的JFrame,作为新窗口。 frame.setBounds( new Rectangle( // 让新窗口与SwingTest窗口示例错开50像素。 620, 300, // 窗口总大小-500像素 300, 300 ) ); String type = ruleTabbedPane.getTitleAt(ruleTabbedPane.getSelectedIndex()); JPanel xin = new JPanel(); xin.setLayout(null); // Name JLabel Name_field = new JLabel("Name :"); JTextField Name_text = new JTextField(); Name_field.setBounds(10, 5, 40, 20); Name_text.setBounds(65, 5, 200, 20); xin.add(Name_field); xin.add(Name_text); // Method JLabel Method_field = new JLabel("Method :"); JComboBox Method_text = new JComboBox(); //创建JComboBox Method_text.addItem("GET"); //向下拉列表中添加一项 Method_text.addItem("POST"); //向下拉列表中添加一项 Method_field.setBounds(10, 45, 40, 20); Method_text.setBounds(65, 45, 200, 20); xin.add(Method_field); xin.add(Method_text); // Url JLabel Url_field = new JLabel("Url :"); JTextField Url_text = new JTextField(); Url_field.setBounds(10, 85, 40, 20); Url_text.setBounds(65, 85, 200, 20); xin.add(Url_field); xin.add(Url_text); // Re JLabel Re_field = new JLabel("Re :"); JTextField Re_text = new JTextField(); Re_field.setBounds(10, 125, 40, 20); Re_text.setBounds(65, 125, 200, 20); xin.add(Re_field); xin.add(Re_text); // Info JLabel Info_field = new JLabel("Info :"); JTextField Info_text = new JTextField(); Info_field.setBounds(10, 165, 40, 20); Info_text.setBounds(65, 165, 200, 20); xin.add(Info_field); xin.add(Info_text); // State JLabel State_field = new JLabel("State :"); JTextField State_text = new JTextField(); State_field.setBounds(10, 205, 40, 20); State_text.setBounds(65, 205, 200, 20); xin.add(State_field); xin.add(State_text); // Ok JButton Ok_button = new JButton("OK"); Ok_button.setBounds(200, 245, 60, 20); xin.add(Ok_button); Ok_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = 0; Map<String, Object> Yaml_Map = YamlUtil.readYaml(yaml_path1); List<Map<String, Object>> List1 = (List<Map<String, Object>>) Yaml_Map.get("Load_List"); for (Map<String, Object> zidian : List1) { if ((int) zidian.get("id") > id) { id = (int) zidian.get("id"); } } id += 1; String name = Name_text.getText(); String url = Url_text.getText(); String method = (String) Method_text.getSelectedItem(); String re = Re_text.getText(); String info = Info_text.getText(); String state = State_text.getText(); Map<String, Object> add_map = new HashMap<String, Object>(); add_map.put("type", type); add_map.put("id", id); add_map.put("loaded", true); add_map.put("name", name); add_map.put("method", method); add_map.put("url", url); add_map.put("re", re); add_map.put("info", info); add_map.put("state", state); YamlUtil.addYaml(add_map, yaml_path1); Bfunc.show_yaml_view(burp, burp.views.get(type), type); frame.dispose(); } }); // no JButton No_button = new JButton("NO"); No_button.setBounds(130, 245, 60, 20); xin.add(No_button); No_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.dispose(); } }); frame.getContentPane().add(xin); frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 设置模式类型。 frame.setVisible(true); } }); } private void load_button_Yaml(JButton Button_one) { Button_one.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Bfunc.show_yaml(burp); } }); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { $$$setupUI$$$(); return one; } }
1
28234_3
package top.dyw.pat.simple; import java.util.Scanner; /** * 1014 福尔摩斯的约会 (20分) * * @author: ChangSheng * @date: 2019年12月15日 下午3:32:17 */ public class P1014福尔摩斯的约会 { public static void main(String[] args) { Scanner s = new Scanner(System.in); String[] weeks = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"}; String line01 = s.nextLine(); String line02 = s.nextLine(); String line03 = s.nextLine(); String line04 = s.nextLine(); // 1.找出周几和第几钟头 boolean isFindWeek = false; // boolean isFindHour = false; for (int i = 0; i < line01.length() && i < line02.length(); i++) { char ch1 = line01.charAt(i); char ch2 = line02.charAt(i); if (ch1 == ch2) { if (!isFindWeek && ch2 >= 'A' && ch2 <= 'G') { System.out.print(weeks[ch2 - 'A'] + " "); isFindWeek = true; continue; //跳过当前循环 防止下面查找小时遇到重复计算 } if (isFindWeek) {//找到了周几 现在找小时 if (ch2 >= '0' && ch2 <= '9') { System.out.printf("%02d:", (ch2 - '0')); break; } else if (ch2 >= 'A' && ch2 <= 'N') { System.out.print((ch2-55)+":"); break; } } } } // 2.找出分钟 for (int i = 0; i < line03.length() && i < line04.length(); i++) { char ch = line03.charAt(i); char ch2 = line04.charAt(i); if (ch==ch2){ if ((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')){ System.out.printf("%02d",i); return; } } } } }
FANGDEI/leetcode
java-devildyw/src/main/java/top/dyw/pat/simple/P1014福尔摩斯的约会.java
579
//跳过当前循环 防止下面查找小时遇到重复计算
line_comment
zh-cn
package top.dyw.pat.simple; import java.util.Scanner; /** * 1014 福尔摩斯的约会 (20分) * * @author: ChangSheng * @date: 2019年12月15日 下午3:32:17 */ public class P1014福尔摩斯的约会 { public static void main(String[] args) { Scanner s = new Scanner(System.in); String[] weeks = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"}; String line01 = s.nextLine(); String line02 = s.nextLine(); String line03 = s.nextLine(); String line04 = s.nextLine(); // 1.找出周几和第几钟头 boolean isFindWeek = false; // boolean isFindHour = false; for (int i = 0; i < line01.length() && i < line02.length(); i++) { char ch1 = line01.charAt(i); char ch2 = line02.charAt(i); if (ch1 == ch2) { if (!isFindWeek && ch2 >= 'A' && ch2 <= 'G') { System.out.print(weeks[ch2 - 'A'] + " "); isFindWeek = true; continue; //跳过 <SUF> } if (isFindWeek) {//找到了周几 现在找小时 if (ch2 >= '0' && ch2 <= '9') { System.out.printf("%02d:", (ch2 - '0')); break; } else if (ch2 >= 'A' && ch2 <= 'N') { System.out.print((ch2-55)+":"); break; } } } } // 2.找出分钟 for (int i = 0; i < line03.length() && i < line04.length(); i++) { char ch = line03.charAt(i); char ch2 = line04.charAt(i); if (ch==ch2){ if ((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')){ System.out.printf("%02d",i); return; } } } } }
1
21896_5
import java.io.IOException; import java.io.PrintWriter; import java.net.Inet4Address; import java.net.ServerSocket; import java.net.Socket; import java.util.Random; /** * 命令传输线程+ */ public class ControlLinkHandler implements Runnable { private static Random random;//随机器 private ServerSocket controlServerSocket;//控制socket private PrintWriter writer; static { random = new Random(); } /** * @param port 初始化端口号 * @throws IOException */ public ControlLinkHandler(int port) throws IOException { controlServerSocket = new ServerSocket(port,10,Inet4Address.getLocalHost()); //本地启动一个socket,第二个参数是最大正在连接数(并不是最大连接数) System.out.println("控制连接已经在 " + controlServerSocket.getInetAddress() + " 端口: " + controlServerSocket.getLocalPort()+"开启"); } @Override public void run() { //无限循环去接收客户端的消息 while(true) { Socket socket; try { socket = controlServerSocket.accept();//接收客户端连接,该方法会堵塞 System.out.println("控制连接 接收到 来自 客户端" + socket.getInetAddress() + " 端口: " + socket.getPort()+"的连接请求"); socket.setSoTimeout(5000); //read timeout writer = new PrintWriter(socket.getOutputStream(),true); Object[] objects=new Object[2]; if(IPManger.canConnect(socket,objects)){ //如果可以连接 Long connectionId = random.nextLong();//生成客户端ID识别码 writer.println(true); writer.println(connectionId.toString()); IPManger.connetingMap.put(connectionId, socket); }else { writer.println(false); writer.println(objects[0]);//返回给客户端的错误信息 System.out.printf(objects[1].toString()); socket.close(); } } catch (IOException e) { throw new IllegalStateException("客户端连接时出现IO错误:" + e); } } } }
FENG-MASTER/FTP
src/ControlLinkHandler.java
536
//无限循环去接收客户端的消息
line_comment
zh-cn
import java.io.IOException; import java.io.PrintWriter; import java.net.Inet4Address; import java.net.ServerSocket; import java.net.Socket; import java.util.Random; /** * 命令传输线程+ */ public class ControlLinkHandler implements Runnable { private static Random random;//随机器 private ServerSocket controlServerSocket;//控制socket private PrintWriter writer; static { random = new Random(); } /** * @param port 初始化端口号 * @throws IOException */ public ControlLinkHandler(int port) throws IOException { controlServerSocket = new ServerSocket(port,10,Inet4Address.getLocalHost()); //本地启动一个socket,第二个参数是最大正在连接数(并不是最大连接数) System.out.println("控制连接已经在 " + controlServerSocket.getInetAddress() + " 端口: " + controlServerSocket.getLocalPort()+"开启"); } @Override public void run() { //无限 <SUF> while(true) { Socket socket; try { socket = controlServerSocket.accept();//接收客户端连接,该方法会堵塞 System.out.println("控制连接 接收到 来自 客户端" + socket.getInetAddress() + " 端口: " + socket.getPort()+"的连接请求"); socket.setSoTimeout(5000); //read timeout writer = new PrintWriter(socket.getOutputStream(),true); Object[] objects=new Object[2]; if(IPManger.canConnect(socket,objects)){ //如果可以连接 Long connectionId = random.nextLong();//生成客户端ID识别码 writer.println(true); writer.println(connectionId.toString()); IPManger.connetingMap.put(connectionId, socket); }else { writer.println(false); writer.println(objects[0]);//返回给客户端的错误信息 System.out.printf(objects[1].toString()); socket.close(); } } catch (IOException e) { throw new IllegalStateException("客户端连接时出现IO错误:" + e); } } } }
null