file_id
int64 1
66.7k
| content
stringlengths 14
343k
| repo
stringlengths 6
92
| path
stringlengths 5
169
|
---|---|---|---|
1,332 | /*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
This source code is licensed under the Apache License Version 2.0.*/
package apijson.orm;
/**对请求 JSON 的操作
* @author Lemon
*/
public enum Operation {
/**
* 必须传的字段,结构是
* "key0,key1,key2..."
*/
MUST,
/**
* 不允许传的字段,结构是
* "key0,key1,key2..."
*/
REFUSE,
/**TODO 是否应该把数组类型写成 BOOLEANS, NUMBERS 等复数单词,以便抽取 enum ?扩展用 VERIFY 或 INSERT/UPDATE 远程函数等
* 验证是否符合预设的类型:
* BOOLEAN, NUMBER, DECIMAL, STRING, URL, DATE, TIME, DATETIME, OBJECT, ARRAY
* 或它们的数组
* BOOLEAN[], NUMBER[], DECIMAL[], STRING[], URL[], DATE[], TIME[], DATETIME[], OBJECT[], ARRAY[]
* 结构是
* {
* key0: value0,
* key1: value1,
* key2: value2
* ...
* }
* 例如
* {
* "id": "NUMBER", //id 类型必须为 NUMBER
* "pictureList": "URL[]", //pictureList 类型必须为 URL[]
* }
* @see {@link AbstractVerifier#verifyType(String, String, Object, boolean)}
*/
TYPE,
/**
* 验证是否符合预设的条件,结构是
* {
* key0: value0,
* key1: value1,
* key2: value2
* ...
* }
* 例如
* {
* "phone~": "PHONE", //phone 必须满足 PHONE 的格式,配置见 {@link AbstractVerifier#COMPILE_MAP}
* "status{}": [1,2,3], //status 必须在给出的范围内
* "content{L}": ">0,<=255", //content的长度 必须在给出的范围内
* "balance&{}":">0,<=10000" //必须满足 balance>0 & balance<=10000
* }
*/
VERIFY,
/**
* 验证是否存在,结构是
* "key0,key1,key2..."
* 多个字段用逗号隔开,联合校验
*/
EXIST,
/**
* 验证是否不存在,除了本身的记录,结构是
* "key0,key1,key2..."
* 多个字段用逗号隔开,联合校验
*/
UNIQUE,
/**
* 添加,当要被添加的对象不存在时,结构是
* {
* key0: value0,
* key1: value1,
* key2: value2
* ...
* }
*/
INSERT,
/**
* 强行放入,不存在时就添加,存在时就修改,结构是
* {
* key0: value0,
* key1: value1,
* key2: value2
* ...
* }
*/
UPDATE,
/**
* 替换,当要被替换的对象存在时,结构是
* {
* key0: value0,
* key1: value1,
* key2: value2
* ...
* }
*/
REPLACE,
/**
* 移除,当要被移除的对象存在时,结构是
* "key0,key1,key2..."
*/
REMOVE,
/**
* 监听事件,用于同步到其它表,结构是
* "key0": {}
* 例如 "name": { "UPDATE": { "Comment": { "userName@": "/name" } } }
* 当 User.name 被修改时,同步修改 Comment.userName
*
* 例如 "sex != 0 && sex != 1": "throw new Error('sex 必须在 [0, 1] 内!')"
* 自定义代码,当满足条件是执行后面的代码
*
* 还有
* "ELSE": ""
* 自定义代码,不处理,和不传一样
*/
IF,
// /** 直接用 IF 替代
// * 自定义代码,结构是 "code",例如
// * "var a = 1;
// * var b = a + 2;
// * if (b % 2 == 0) {
// * throw new Error('b % 2 == 0 !');
// * }
// * "
// *
// * 或 { "code": "JS", "code2": "LUA" }
// */
// CODE,
/**
* 允许批量增删改部分失败,结构是
* "Table[],key[],key:alias[]"
* 自动 ALLOW_PARTIAL_UPDATE_FAILED_TABLE_MAP.put,结构是 Boolean,例如 true
*/
ALLOW_PARTIAL_UPDATE_FAIL,
/**
* 强制要求必须有 id/id{}/id{}@ 条件,结构是 Boolean,例如 true
*/
IS_ID_CONDITION_MUST;
}
| Tencent/APIJSON | APIJSONORM/src/main/java/apijson/orm/Operation.java |
1,333 | package com.example.gsyvideoplayer;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.media3.exoplayer.SeekParameters;
import com.example.gsyvideoplayer.databinding.ActivityDetailAudioPlayerBinding;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import java.util.HashMap;
import java.util.Map;
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager;
public class AudioDetailPlayer extends AppCompatActivity {
private boolean isPlay;
private boolean isPause;
private OrientationUtils orientationUtils;
ActivityDetailAudioPlayerBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityDetailAudioPlayerBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
String url = getUrl();
resolveNormalVideoUI();
//外部辅助的旋转,帮助全屏
orientationUtils = new OrientationUtils(this, binding.detailPlayer);
//初始化不打开外部的旋转
orientationUtils.setEnable(false);
binding.detailPlayer.loadCoverImage("", R.drawable.lololo);
Map<String, String> header = new HashMap<>();
header.put("ee", "33");
header.put("allowCrossProtocolRedirects", "true");
GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder();
gsyVideoOption
.setIsTouchWiget(true)
.setRotateViewAuto(false)
.setLockLand(false)
.setAutoFullWithSize(false)
.setShowFullAnimation(false)
.setNeedLockFull(true)
.setUrl(url)
.setMapHeadData(header)
.setCacheWithPlay(false)
.setVideoTitle("测试视频")
.setVideoAllCallBack(new GSYSampleCallBack() {
@Override
public void onPrepared(String url, Object... objects) {
Debuger.printfError("***** onPrepared **** " + objects[0]);
Debuger.printfError("***** onPrepared **** " + objects[1]);
super.onPrepared(url, objects);
//开始播放了才能旋转和全屏
orientationUtils.setEnable(binding.detailPlayer.isRotateWithSystem());
isPlay = true;
//设置 seek 的临近帧。
if (binding.detailPlayer.getGSYVideoManager().getPlayer() instanceof Exo2PlayerManager) {
((Exo2PlayerManager) binding.detailPlayer.getGSYVideoManager().getPlayer()).setSeekParameter(SeekParameters.NEXT_SYNC);
Debuger.printfError("***** setSeekParameter **** ");
}
}
@Override
public void onEnterFullscreen(String url, Object... objects) {
super.onEnterFullscreen(url, objects);
Debuger.printfError("***** onEnterFullscreen **** " + objects[0]);//title
Debuger.printfError("***** onEnterFullscreen **** " + objects[1]);//当前全屏player
}
@Override
public void onAutoComplete(String url, Object... objects) {
super.onAutoComplete(url, objects);
}
@Override
public void onClickStartError(String url, Object... objects) {
super.onClickStartError(url, objects);
}
@Override
public void onQuitFullscreen(String url, Object... objects) {
super.onQuitFullscreen(url, objects);
Debuger.printfError("***** onQuitFullscreen **** " + objects[0]);//title
Debuger.printfError("***** onQuitFullscreen **** " + objects[1]);//当前非全屏player
// ------- !!!如果不需要旋转屏幕,可以不调用!!!-------
// 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false)
if (orientationUtils != null) {
orientationUtils.backToProtVideo();
}
}
})
.setLockClickListener(new LockClickListener() {
@Override
public void onClick(View view, boolean lock) {
if (orientationUtils != null) {
//配合下方的onConfigurationChanged
orientationUtils.setEnable(!lock);
}
}
})
.setGSYVideoProgressListener(new GSYVideoProgressListener() {
@Override
public void onProgress(long progress, long secProgress, long currentPosition, long duration) {
Debuger.printfLog(" progress " + progress + " secProgress " + secProgress + " currentPosition " + currentPosition + " duration " + duration);
}
})
.build(binding.detailPlayer);
binding.detailPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//直接横屏
// ------- !!!如果不需要旋转屏幕,可以不调用!!!-------
// 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false)
orientationUtils.resolveByClick();
//第一个true是否需要隐藏actionbar,第二个true是否需要隐藏statusbar
binding.detailPlayer.startWindowFullscreen(AudioDetailPlayer.this, true, true);
}
});
}
@Override
public void onBackPressed() {
// ------- !!!如果不需要旋转屏幕,可以不调用!!!-------
// 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false)
if (orientationUtils != null) {
orientationUtils.backToProtVideo();
}
if (GSYVideoManager.backFromWindowFull(this)) {
return;
}
super.onBackPressed();
}
@Override
protected void onPause() {
getCurPlay().onVideoPause();
super.onPause();
isPause = true;
}
@Override
protected void onResume() {
getCurPlay().onVideoResume(false);
super.onResume();
isPause = false;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (isPlay) {
getCurPlay().release();
}
//GSYPreViewManager.instance().releaseMediaPlayer();
if (orientationUtils != null)
orientationUtils.releaseListener();
}
/**
* orientationUtils 和 detailPlayer.onConfigurationChanged 方法是用于触发屏幕旋转的
*/
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//如果旋转了就全屏
if (isPlay && !isPause) {
binding.detailPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
}
}
private void resolveNormalVideoUI() {
//增加title
binding.detailPlayer.getTitleTextView().setVisibility(View.GONE);
binding.detailPlayer.getBackButton().setVisibility(View.GONE);
}
private GSYVideoPlayer getCurPlay() {
if (binding.detailPlayer.getFullWindowPlayer() != null) {
return binding.detailPlayer.getFullWindowPlayer();
}
return binding.detailPlayer;
}
private String getUrl() {
String url = "android.resource://" + getPackageName() + "/" + R.raw.test3;
//注意,用ijk模式播放raw视频,这个必须打开
GSYVideoManager.instance().enableRawPlay(getApplicationContext());
///exo raw 支持
//String url = RawResourceDataSource.buildRawResourceUri(R.raw.test).toString();
//return "https://oss.nbs.cn/M00/22/E4/wKhkDmPZ1uSAJWFwAlYRLUW4gK0892.mp3";
return url;
}
}
| CarGuo/GSYVideoPlayer | app/src/main/java/com/example/gsyvideoplayer/AudioDetailPlayer.java |
1,336 | package org.nlpcn.es4sql;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr;
import com.alibaba.druid.sql.ast.expr.SQLInListExpr;
import com.alibaba.druid.sql.ast.expr.SQLIntervalExpr;
import com.alibaba.druid.sql.ast.expr.SQLNumericLiteralExpr;
import com.alibaba.druid.sql.ast.expr.SQLPropertyExpr;
import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr;
import com.alibaba.druid.util.StringUtils;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.elasticsearch.core.Tuple;
import org.nlpcn.es4sql.domain.KVValue;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
/**
* Created by allwefantasy on 8/19/16.
*/
public class SQLFunctions {
//Groovy Built In Functions
public final static Set<String> buildInFunctions = Sets.newHashSet(
"exp", "log", "log2", "log10", "log10", "sqrt", "cbrt", "ceil", "floor", "rint", "pow", "round",
"random", "abs", //nummber operator
"split", "concat_ws", "substring", "trim",//string operator
"add", "multiply", "divide", "subtract", "modulus",//binary operator
"field", "date_format", "if",//if判断目前支持多个二元操作符
"max_bw", "min_bw", //added by xzb 取两个数的最大/小值
"coalesce", //added by xzb 取两个值中间有值的那个
"case_new",//added by xzb 支持多个判断条件
//支持正则表达式抽取原字段后赋给新字段,注意必须指定一个group。如 parse(hobby,(?<type>\S+)球, defaultValue)
"parse",//此函数需要在elasticsearch.yml中设置 script.painless.regex.enabled : true
"now", "date", "date_add", "from_unixtime"
);
//added by xzb 增加二元操作运算符
public static Set<String> binaryOperators = Sets.newHashSet("=" ,"!=", ">", ">=", "<", "<=");
//modified by xzb 增加 binaryOperatorName,即 if、case条件中的判断
public static Tuple<String, String> function(String methodName, List<KVValue> paramers, String name, boolean returnValue , String binaryOperatorName, List<String> binaryOperatorNames) throws Exception {
//added by xzb ,默认二元操作符为 ==
if (binaryOperatorName == null || binaryOperatorName.equals("=")) {
binaryOperatorName = " == ";
}
Tuple<String, String> functionStr = null;
switch (methodName.toLowerCase()) {
case "if":
String nameIF = "";
String caseString = "";
if(paramers.get(0).value instanceof SQLInListExpr){
nameIF += methodName+"("+((SQLInListExpr) paramers.get(0).value).getExpr()+" in (";
String left = "doc['"+((SQLInListExpr) paramers.get(0).value).getExpr().toString()+"'].value";
List<SQLExpr> targetList = ((SQLInListExpr) paramers.get(0).value).getTargetList();
for(SQLExpr a:targetList){
caseString += left + " == '" + a.toString() + "' ||";
nameIF += a.toString()+",";
}
caseString = caseString.substring(0,caseString.length()-2);
nameIF = nameIF.substring(0,nameIF.length()-1)+"),";
}else{
String key =paramers.get(0).key;
String left = "doc['"+key+"'].value";
String value = paramers.get(0).value.toString();
//xzb 支持更多的表达式,如 > 、<、>=、<=、!= 等
caseString += left + binaryOperatorName + value;
nameIF = methodName+"("+ key + binaryOperatorName + value +",";
}
nameIF += paramers.get(1).value+","+paramers.get(2).value+")";
functionStr = new Tuple<>(nameIF,"if(("+caseString+")){"+paramers.get(1).value+"} else {"+paramers.get(2).value+"}");
break;
case "split":
if (paramers.size() == 3) {
functionStr = split(Util.expr2Object((SQLExpr) paramers.get(0).value).toString(),
Util.expr2Object((SQLExpr) paramers.get(1).value).toString(),
Integer.parseInt(Util.expr2Object((SQLExpr) paramers.get(2).value).toString()), name);
} else {
functionStr = split(paramers.get(0).value.toString(),
paramers.get(1).value.toString(),
name);
}
break;
case "concat_ws":
List<SQLExpr> result = Lists.newArrayList();
for (int i = 1; i < paramers.size(); i++) {
result.add((SQLExpr) paramers.get(i).value);
}
functionStr = concat_ws(paramers.get(0).value.toString(), result, name);
break;
case "date_format":
functionStr = date_format(
Util.expr2Object((SQLExpr) paramers.get(0).value).toString(),
Util.expr2Object((SQLExpr) paramers.get(1).value).toString(),
2 < paramers.size() ? Util.expr2Object((SQLExpr) paramers.get(2).value).toString() : null,
name);
break;
case "from_unixtime":
functionStr = from_unixtime(
Util.expr2Object((SQLExpr) paramers.get(0).value).toString(),
1 < paramers.size() ? Util.expr2Object((SQLExpr) paramers.get(1).value).toString() : null,
2 < paramers.size() ? Util.expr2Object((SQLExpr) paramers.get(2).value).toString() : null,
name);
break;
case "abs":
case "round":
case "max_bw":
case "min_bw":
case "coalesce":
case "parse":
case "case_new":
case "floor":
//zhongshu-comment es的round()默认是保留到个位,这里给round()函数加上精确到小数点后第几位的功能
//modify by xzb 增加两个函数 min_bw 和 max_bw
if (paramers.size() >= 2) {//coalesce函数的参数可以是2个以上
if (methodName.equals("round")){
int decimalPrecision = Integer.parseInt(paramers.get(1).value.toString());
functionStr = mathRoundTemplate("Math."+methodName,methodName,Util.expr2Object((SQLExpr) paramers.get(0).value).toString(), name, decimalPrecision);
break;
} else if (methodName.equals("max_bw")) {
functionStr = mathBetweenTemplate("Math.max", methodName, paramers, name);
break;
} else if (methodName.equals("min_bw")) {
functionStr = mathBetweenTemplate("Math.min", methodName, paramers, name);
break;
} else if (methodName.equals("coalesce")) {
functionStr = coalesceTemplate(methodName, paramers);
break;
}else if (methodName.equals("case_new")) {
functionStr = caseNewTemplate(methodName, paramers, binaryOperatorNames);
break;
}else if (methodName.equals("parse")) {
functionStr = parseTemplate(methodName, paramers);
break;
}
}
case "ceil":
case "cbrt":
case "rint":
case "exp":
case "sqrt":
functionStr = mathSingleValueTemplate("Math."+methodName,methodName,Util.expr2Object((SQLExpr) paramers.get(0).value).toString(), name);
break;
case "pow":
functionStr = mathDoubleValueTemplate("Math."+methodName, methodName, Util.expr2Object((SQLExpr) paramers.get(0).value).toString(), Util.expr2Object((SQLExpr) paramers.get(1).value).toString(), name);
break;
case "substring":
functionStr = substring(Util.expr2Object((SQLExpr) paramers.get(0).value).toString(),
Integer.parseInt(Util.expr2Object((SQLExpr) paramers.get(1).value).toString()),
Integer.parseInt(Util.expr2Object((SQLExpr) paramers.get(2).value).toString())
, name);
break;
case "trim":
functionStr = trim(Util.expr2Object((SQLExpr) paramers.get(0).value).toString(), name);
break;
case "add":
functionStr = add((SQLExpr) paramers.get(0).value, (SQLExpr) paramers.get(1).value);
break;
case "subtract":
functionStr = subtract((SQLExpr) paramers.get(0).value, (SQLExpr) paramers.get(1).value);
break;
case "divide":
functionStr = divide((SQLExpr) paramers.get(0).value, (SQLExpr) paramers.get(1).value);
break;
case "multiply":
functionStr = multiply((SQLExpr) paramers.get(0).value, (SQLExpr) paramers.get(1).value);
break;
case "modulus":
functionStr = modulus((SQLExpr) paramers.get(0).value, (SQLExpr) paramers.get(1).value);
break;
case "field":
functionStr = field(Util.expr2Object((SQLExpr) paramers.get(0).value).toString());
break;
case "log2":
functionStr = log(SQLUtils.toSQLExpr("2"), (SQLExpr) paramers.get(0).value, name);
break;
case "log10":
functionStr = log(SQLUtils.toSQLExpr("10"), (SQLExpr) paramers.get(0).value, name);
break;
case "log":
List<SQLExpr> logs = Lists.newArrayList();
for (int i = 0; i < paramers.size(); i++) {
logs.add((SQLExpr) paramers.get(0).value);
}
if (logs.size() > 1) {
functionStr = log(logs.get(0), logs.get(1), name);
} else {
functionStr = log(SQLUtils.toSQLExpr("Math.E"), logs.get(0), name);
}
break;
case "now":
functionStr = now();
break;
case "date":
functionStr = date(Util.expr2Object((SQLExpr) paramers.get(0).value).toString(), name);
break;
case "date_add":
functionStr = date_add(
Util.expr2Object((SQLExpr) paramers.get(0).value).toString(),
(SQLIntervalExpr) paramers.get(1).value,
name);
break;
default:
}
//added by xzb 以下几种情况的脚本,script中均不需要return语句
if(returnValue && !methodName.equalsIgnoreCase("if") &&
!methodName.equalsIgnoreCase("coalesce") &&
!methodName.equalsIgnoreCase("parse") &&
!methodName.equalsIgnoreCase("case_new") &&
buildInFunctions.contains(methodName)){
String generatedFieldName = functionStr.v1();
String returnCommand = ";return " + generatedFieldName +";" ;
String newScript = functionStr.v2() + returnCommand;
functionStr = new Tuple<>(generatedFieldName, newScript);
}
return functionStr;
}
public static String random() {
return Math.abs(ThreadLocalRandom.current().nextInt()) + "";
}
private static Tuple<String, String> concat_ws(String split, List<SQLExpr> columns, String valueName) {
String name = "concat_ws_" + random();
List<String> result = Lists.newArrayList();
for (SQLExpr column : columns) {
String strColumn = Util.expr2Object(column).toString();
if (strColumn.startsWith("def ")) {
result.add(strColumn);
} else if (isProperty(column)) {
result.add("doc['" + strColumn + "'].value");
} else {
result.add("'" + strColumn + "'");
}
}
return new Tuple<>(name, "def " + name + " =" + Joiner.on("+ " + split + " +").join(result));
}
//split(Column str, java.lang.String pattern)
public static Tuple<String, String> split(String strColumn, String pattern, int index, String valueName) {
String name = "split_" + random();
String script = "";
if (valueName == null) {
script = "def " + name + " = doc['" + strColumn + "'].value.split('" + pattern + "')[" + index + "]";
} else {
script = "; def " + name + " = " + valueName + ".split('" + pattern + "')[" + index + "]";
}
return new Tuple<>(name, script);
}
private static Tuple<String, String> date_format(String strColumn, String pattern, String zoneId, String valueName) {
String name = "date_format_" + random();
if (valueName == null) {
return new Tuple<>(name, "def " + name + " = DateTimeFormatter.ofPattern('" + pattern + "').withZone(" +
(zoneId != null ? "ZoneId.of('" + zoneId + "')" : "ZoneId.systemDefault()") +
").format(Instant.ofEpochMilli(doc['" + strColumn + "'].value.getMillis()))");
} else {
return new Tuple<>(name, strColumn + "; def " + name + " = new SimpleDateFormat('" + pattern + "').format(new Date(" + valueName + " - 8*1000*60*60))");
}
}
private static Tuple<String, String> from_unixtime(String strColumn, String pattern, String zoneId, String valueName) {
String name = "from_unixtime_" + random();
if (Objects.isNull(pattern)) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
zoneId = Objects.isNull(zoneId) ? "ZoneId.systemDefault()" : "ZoneId.of('" + zoneId + "')";
if (valueName == null) {
return new Tuple<>(name, "def " + name + " = DateTimeFormatter.ofPattern('" + pattern + "').withZone(" +
zoneId +
").format(Instant.ofEpochSecond(doc['" + strColumn + "'].value))");
} else {
return new Tuple<>(name, strColumn + "; def " + name + " = DateTimeFormatter.ofPattern('" + pattern + "').withZone(" +
zoneId +
").format(Instant.ofEpochSecond(" + valueName + "))");
}
}
public static Tuple<String, String> add(SQLExpr a, SQLExpr b) {
return binaryOpertator("add", "+", a, b);
}
private static Tuple<String, String> modulus(SQLExpr a, SQLExpr b) {
return binaryOpertator("modulus", "%", a, b);
}
public static Tuple<String, String> field(String a) {
String name = "field_" + random();
return new Tuple<>(name, "def " + name + " = " + "doc['" + a + "'].value");
}
private static Tuple<String, String> subtract(SQLExpr a, SQLExpr b) {
return binaryOpertator("subtract", "-", a, b);
}
private static Tuple<String, String> multiply(SQLExpr a, SQLExpr b) {
return binaryOpertator("multiply", "*", a, b);
}
private static Tuple<String, String> divide(SQLExpr a, SQLExpr b) {
return binaryOpertator("divide", "/", a, b);
}
private static Tuple<String, String> binaryOpertator(String methodName, String operator, SQLExpr a, SQLExpr b) {
String name = methodName + "_" + random();
return new Tuple<>(name,
scriptDeclare(a) + scriptDeclare(b) +
convertType(a) + convertType(b) +
" def " + name + " = " + extractName(a) + " " + operator + " " + extractName(b) ) ;
}
private static boolean isProperty(SQLExpr expr) {
return (expr instanceof SQLIdentifierExpr || expr instanceof SQLPropertyExpr || expr instanceof SQLVariantRefExpr);
}
private static String scriptDeclare(SQLExpr a) {
if (isProperty(a) || a instanceof SQLNumericLiteralExpr)
return "";
else return Util.expr2Object(a).toString() + ";";
}
private static String extractName(SQLExpr script) {
if (isProperty(script)) return "doc['" + script + "'].value";
String scriptStr = Util.expr2Object(script).toString();
String[] variance = scriptStr.split(";");
String newScript = variance[variance.length - 1];
if (newScript.trim().startsWith("def ")) {
//for now ,if variant is string,then change to double.
return newScript.trim().substring(4).split("=")[0].trim();
} else return scriptStr;
}
//cast(year as int)
private static String convertType(SQLExpr script) {
String[] variance = Util.expr2Object(script).toString().split(";");
String newScript = variance[variance.length - 1];
if (newScript.trim().startsWith("def ")) {
//for now ,if variant is string,then change to double.
String temp = newScript.trim().substring(4).split("=")[0].trim();
return " if( " + temp + " instanceof String) " + temp + "= Double.parseDouble(" + temp.trim() + "); ";
} else return "";
}
public static Tuple<String, String> log(String strColumn, String valueName) {
return mathSingleValueTemplate("log", strColumn, valueName);
}
public static Tuple<String, String> log10(String strColumn, String valueName) {
return mathSingleValueTemplate("log10", strColumn, valueName);
}
public static Tuple<String, String> log(SQLExpr base, SQLExpr strColumn, String valueName) {
String name = "log_" + random();
String result;
if (valueName == null) {
if (isProperty(strColumn)) {
result = "def " + name + " = Math.log(doc['" + Util.expr2Object(strColumn).toString() + "'].value)/Math.log("+Util.expr2Object(base).toString()+")";
} else {
result = "def " + name + " = Math.log(" + Util.expr2Object(strColumn).toString() + ")/Math.log("+Util.expr2Object(base).toString()+")";
}
} else {
result = Util.expr2Object(strColumn).toString()+";def "+name+" = Math.log("+valueName+")/Math.log("+Util.expr2Object(base).toString()+")";
}
return new Tuple(name, result);
}
public static Tuple<String, String> sqrt(String strColumn, String valueName) {
return mathSingleValueTemplate("Math.sqrt", "sqrt", strColumn, valueName);
}
public static Tuple<String, String> round(String strColumn, String valueName) {
return mathSingleValueTemplate("Math.round","round", strColumn, valueName);
}
public static Tuple<String, String> trim(String strColumn, String valueName) {
return strSingleValueTemplate("trim", strColumn, valueName);
}
private static Tuple<String, String> mathDoubleValueTemplate(String methodName, String fieldName, String val1, String val2, String valueName) {
String name = fieldName + "_" + random();
if (valueName == null) {
return new Tuple(name, "def "+name+" = "+methodName+"(doc['"+val1+"'].value, "+val2+")");
} else {
return new Tuple(name, val1 + ";def "+name+" = "+methodName+"("+valueName+", "+val2+")");
}
}
private static Tuple<String, String> mathSingleValueTemplate(String methodName, String strColumn, String valueName) {
return mathSingleValueTemplate(methodName,methodName, strColumn,valueName);
}
private static Tuple<String, String> mathSingleValueTemplate(String methodName, String fieldName, String strColumn, String valueName) {
String name = fieldName + "_" + random();
if (valueName == null) {
return new Tuple<>(name, "def " + name + " = " + methodName + "(doc['" + strColumn + "'].value)");
} else {
return new Tuple<>(name, strColumn + ";def " + name + " = " + methodName + "(" + valueName + ")");
}
}
private static Tuple<String, String> mathRoundTemplate(String methodName, String fieldName, String strColumn, String valueName, int decimalPrecision) {
StringBuilder sb = new StringBuilder("1");
for (int i = 0; i < decimalPrecision; i++) {
sb.append("0");
}
double num = Double.parseDouble(sb.toString());
String name = fieldName + "_" + random();
if (valueName == null) {
return new Tuple<>(name, "def " + name + " = " + methodName + "((doc['" + strColumn + "'].value) * " + num + ")/" + num);
} else {
return new Tuple<>(name, strColumn + ";def " + name + " = " + methodName + "((" + valueName + ") * " + num + ")/" + num);
}
}
//求两个值中最大值,如 def abs_775880898 = Math.max(doc['age1'].value, doc['age2'].value);return abs_775880898;
private static Tuple<String, String> mathBetweenTemplate(String methodName, String fieldName, List<KVValue> paramer, String valueName) {
//获取 max_bw/min_bw 函数的两个字段
String name = fieldName + "_" + random();
StringBuffer sb = new StringBuffer();
sb.append("def " + name + " = " + methodName + "(");
int i = 0;
for (KVValue kv : paramer) {
String field = kv.value.toString();
if (i > 0) {
sb.append(", ");
}
sb.append("doc['" + field + "'].value");
i++;
}
sb.append(")");
return new Tuple<>(name, sb.toString());
}
//实现coalesce(field1, field2, ...)功能,只要任意一个不为空即可
private static Tuple<String, String> coalesceTemplate(String fieldName, List<KVValue> paramer) {
//if((doc['age2'].value != null)){doc['age2'].value} else if((doc['age1'].value != null)){doc['age1'].value}
String name = fieldName + "_" + random();
StringBuffer sb = new StringBuffer();
int i = 0;
//sb.append("def " + name + " = ");
for (KVValue kv : paramer) {
String field = kv.value.toString();
if (i > 0) {
sb.append(" else ");
}
sb.append("if(doc['" + field + "'].value != null){doc['" + field + "'].value}");
i++;
}
return new Tuple<>(name, sb.toString());
}
//实现正则表达式抽取原字段后赋给新字段,注意必须指定一个group。如 parse(hobby,(?<type>\S+)球, defaultValue)
//"SELECT parse(hobby, '(?<type>\\\\S+)球', 'NOT_MATCH') AS ballType, COUNT(_index) FROM bank GROUP BY ballType"
private static Tuple<String, String> parseTemplate(String fieldName, List<KVValue> params) {
// def m = /(?<type>\S+)球/.matcher(doc['hobby'].value); if(m.matches()) { return m.group(1) } else { return \"no_match\" }
String name = fieldName + "_" + random();
StringBuffer sb = new StringBuffer();
if (null == params || params.size()!= 3) {
throw new IllegalArgumentException("parse 函数必须包含三个参数,第一个是原字段,第二个是带有group的正则表达式, 第三个是抽取不成功的默认值");
}
String srcField = params.get(0).value.toString();
String regexStr = params.get(1).value.toString();
//需要去除自动添加的单引号
regexStr = regexStr.substring(1, regexStr.length() - 1);
String defaultValue = params.get(2).value.toString();
sb.append("def m = /" + regexStr + "/.matcher(doc['" + srcField + "'].value); if(m.matches()) { return m.group(1) } else { return " + defaultValue +" }");
return new Tuple<>(name, sb.toString());
}
//实现 case_new(gender='m', '男', gender='f', '女', default, '无') as myGender 功能
private static Tuple<String, String> caseNewTemplate(String fieldName, List<KVValue> paramer, List<String> binaryOperatorNames) {
if (paramer.size() % 2 != 0) {//如果参数不是偶数个,则抛异常
throw new IllegalArgumentException("请检查参数数量,必须是偶数个!");
}
//1.找出所有字段及其对应的值存入到Map中,如果有default,则将其移除
String defaultVal = null;
List<String> fieldList = new ArrayList<>();
List<Object> valueList = new ArrayList<>();
List<Object> defaultList = new ArrayList<>();
for (int i = 0; i < paramer.size(); i = i + 2) {
String _default = paramer.get(i + 1).value.toString();
//记录默认值
if (paramer.get(i).value.toString().equalsIgnoreCase("default")) {
defaultVal = _default;
} else {
fieldList.add(paramer.get(i).key);
valueList.add(paramer.get(i).value.toString());
defaultList.add(_default);
}
}
// if((doc['gender'].value == 'm')) '男' else if((doc['gender'].value == 'f')) '女' else ''无
String name = fieldName + "_" + random();
StringBuffer sb = new StringBuffer();
int i = 0;
//sb.append("def " + name + " = ");
for (int j = 0; j < fieldList.size(); j++) {
String field = fieldList.get(j);
if (i > 0) {
sb.append(" else ");
}
//added by xzb 此处有问题,还需要支持除 == 外的其他二元操作符
// sb.append("if(doc['" + field + "'].value == " + valueList.get(i) + ") { " + defaultList.get(i) + " }");
String binaryOperatorName = binaryOperatorNames.get(j);
if ("=".equals(binaryOperatorName)) {// SQL中只有 = 符号,但script中必须使用 ==
binaryOperatorName = "==";
}
sb.append("if(doc['" + field + "'].value " + binaryOperatorName + " " + valueList.get(i) + ") { " + defaultList.get(i) + " }");
i++;
}
if (!StringUtils.isEmpty(defaultVal)) {
sb.append(" else " + defaultVal);
}
return new Tuple<>(name, sb.toString());
}
public static Tuple<String, String> strSingleValueTemplate(String methodName, String strColumn, String valueName) {
String name = methodName + "_" + random();
if (valueName == null) {
return new Tuple(name, "def " + name + " = doc['" + strColumn + "'].value." + methodName + "()" );
} else {
return new Tuple(name, strColumn + "; def " + name + " = " + valueName + "." + methodName + "()");
}
}
public static Tuple<String, String> floor(String strColumn, String valueName) {
return mathSingleValueTemplate("Math.floor", "floor",strColumn, valueName);
}
//substring(Column str, int pos, int len)
public static Tuple<String, String> substring(String strColumn, int pos, int len, String valueName) {
String name = "substring_" + random();
if (valueName == null) {
return new Tuple(name, "def " + name + " = doc['" + strColumn + "'].value.substring(" + pos + "," + len + ")");
} else {
return new Tuple(name, strColumn + ";def " + name + " = " + valueName + ".substring(" + pos + "," + len + ")");
}
}
//split(Column str, java.lang.String pattern)
public static Tuple<String, String> split(String strColumn, String pattern, String valueName) {
String name = "split_" + random();
if (valueName == null) {
return new Tuple(name, "def " + name + " = doc['" + strColumn + "'].value.split('" + pattern + "')" );
} else {
return new Tuple(name, strColumn + "; def " + name + " = " + valueName + ".split('" + pattern + "')");
}
}
private static Tuple<String, String> now() {
String name = "now_" + random();
return new Tuple<>(name, "def " + name + " = " + "Instant.ofEpochMilli(System.currentTimeMillis()).atZone(ZoneId.systemDefault())");
}
private static Tuple<String, String> date(String strColumn, String valueName) {
String name = "date_" + random();
if (valueName == null) {
return new Tuple<>(name, "def " + name + " = doc['" + strColumn + "'].value.truncatedTo(ChronoUnit.DAYS)");
} else {
return new Tuple<>(name, strColumn + "; def " + name + " = " + valueName + ".truncatedTo(ChronoUnit.DAYS)");
}
}
private static Tuple<String, String> date_add(String strColumn, SQLIntervalExpr intervalExpr, String valueName) {
String unit;
switch (intervalExpr.getUnit()) {
case MICROSECOND:
unit = "ChronoUnit.MICROS";
break;
case SECOND:
unit = "ChronoUnit.SECONDS";
break;
case MINUTE:
unit = "ChronoUnit.MINUTES";
break;
case HOUR:
unit = "ChronoUnit.HOURS";
break;
case DAY:
unit = "ChronoUnit.DAYS";
break;
case WEEK:
unit = "ChronoUnit.WEEKS";
break;
case MONTH:
unit = "ChronoUnit.MONTHS";
break;
case YEAR:
unit = "ChronoUnit.YEARS";
break;
default:
throw new IllegalArgumentException("not supported unit: " + intervalExpr.getUnit());
}
Object amountToAdd = Util.expr2Object(intervalExpr.getValue());
String name = "date_add_" + random();
if (valueName == null) {
return new Tuple<>(name, "def " + name + " = doc['" + strColumn + "'].value.plus(" + amountToAdd + "," + unit + ")");
} else {
return new Tuple<>(name, strColumn + "; def " + name + " = " + valueName + ".plus(" + amountToAdd + "," + unit + ")");
}
}
}
| NLPchina/elasticsearch-sql | src/main/java/org/nlpcn/es4sql/SQLFunctions.java |
1,337 | /**
* File: merge_sort.java
* Created Time: 2022-11-25
* Author: krahets ([email protected])
*/
package chapter_sorting;
import java.util.*;
public class merge_sort {
/* 合并左子数组和右子数组 */
static void merge(int[] nums, int left, int mid, int right) {
// 左子数组区间为 [left, mid], 右子数组区间为 [mid+1, right]
// 创建一个临时数组 tmp ,用于存放合并后的结果
int[] tmp = new int[right - left + 1];
// 初始化左子数组和右子数组的起始索引
int i = left, j = mid + 1, k = 0;
// 当左右子数组都还有元素时,进行比较并将较小的元素复制到临时数组中
while (i <= mid && j <= right) {
if (nums[i] <= nums[j])
tmp[k++] = nums[i++];
else
tmp[k++] = nums[j++];
}
// 将左子数组和右子数组的剩余元素复制到临时数组中
while (i <= mid) {
tmp[k++] = nums[i++];
}
while (j <= right) {
tmp[k++] = nums[j++];
}
// 将临时数组 tmp 中的元素复制回原数组 nums 的对应区间
for (k = 0; k < tmp.length; k++) {
nums[left + k] = tmp[k];
}
}
/* 归并排序 */
static void mergeSort(int[] nums, int left, int right) {
// 终止条件
if (left >= right)
return; // 当子数组长度为 1 时终止递归
// 划分阶段
int mid = left + (right - left) / 2; // 计算中点
mergeSort(nums, left, mid); // 递归左子数组
mergeSort(nums, mid + 1, right); // 递归右子数组
// 合并阶段
merge(nums, left, mid, right);
}
public static void main(String[] args) {
/* 归并排序 */
int[] nums = { 7, 3, 2, 6, 0, 1, 5, 4 };
mergeSort(nums, 0, nums.length - 1);
System.out.println("归并排序完成后 nums = " + Arrays.toString(nums));
}
}
| krahets/hello-algo | codes/java/chapter_sorting/merge_sort.java |
1,343 | package com.macro.mall.security.util;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* JwtToken生成的工具类
* JWT token的格式:header.payload.signature
* header的格式(算法、token的类型):
* {"alg": "HS512","typ": "JWT"}
* payload的格式(用户名、创建时间、生成时间):
* {"sub":"wang","created":1489079981393,"exp":1489684781}
* signature的生成算法:
* HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
* Created by macro on 2018/4/26.
*/
public class JwtTokenUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);
private static final String CLAIM_KEY_USERNAME = "sub";
private static final String CLAIM_KEY_CREATED = "created";
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
@Value("${jwt.tokenHead}")
private String tokenHead;
/**
* 根据负责生成JWT的token
*/
private String generateToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
/**
* 从token中获取JWT中的负载
*/
private Claims getClaimsFromToken(String token) {
Claims claims = null;
try {
claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
} catch (Exception e) {
LOGGER.info("JWT格式验证失败:{}", token);
}
return claims;
}
/**
* 生成token的过期时间
*/
private Date generateExpirationDate() {
return new Date(System.currentTimeMillis() + expiration * 1000);
}
/**
* 从token中获取登录用户名
*/
public String getUserNameFromToken(String token) {
String username;
try {
Claims claims = getClaimsFromToken(token);
username = claims.getSubject();
} catch (Exception e) {
username = null;
}
return username;
}
/**
* 验证token是否还有效
*
* @param token 客户端传入的token
* @param userDetails 从数据库中查询出来的用户信息
*/
public boolean validateToken(String token, UserDetails userDetails) {
String username = getUserNameFromToken(token);
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
/**
* 判断token是否已经失效
*/
private boolean isTokenExpired(String token) {
Date expiredDate = getExpiredDateFromToken(token);
return expiredDate.before(new Date());
}
/**
* 从token中获取过期时间
*/
private Date getExpiredDateFromToken(String token) {
Claims claims = getClaimsFromToken(token);
return claims.getExpiration();
}
/**
* 根据用户信息生成token
*/
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
/**
* 当原来的token没过期时是可以刷新的
*
* @param oldToken 带tokenHead的token
*/
public String refreshHeadToken(String oldToken) {
if(StrUtil.isEmpty(oldToken)){
return null;
}
String token = oldToken.substring(tokenHead.length());
if(StrUtil.isEmpty(token)){
return null;
}
//token校验不通过
Claims claims = getClaimsFromToken(token);
if(claims==null){
return null;
}
//如果token已经过期,不支持刷新
if(isTokenExpired(token)){
return null;
}
//如果token在30分钟之内刚刷新过,返回原token
if(tokenRefreshJustBefore(token,30*60)){
return token;
}else{
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
}
/**
* 判断token在指定时间内是否刚刚刷新过
* @param token 原token
* @param time 指定时间(秒)
*/
private boolean tokenRefreshJustBefore(String token, int time) {
Claims claims = getClaimsFromToken(token);
Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
Date refreshDate = new Date();
//刷新时间在创建时间的指定时间内
if(refreshDate.after(created)&&refreshDate.before(DateUtil.offsetSecond(created,time))){
return true;
}
return false;
}
}
| macrozheng/mall | mall-security/src/main/java/com/macro/mall/security/util/JwtTokenUtil.java |
1,346 | package com.macro.mall.portal.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.component.CancelOrderSender;
import com.macro.mall.portal.dao.PortalOrderDao;
import com.macro.mall.portal.dao.PortalOrderItemDao;
import com.macro.mall.portal.dao.SmsCouponHistoryDao;
import com.macro.mall.portal.domain.*;
import com.macro.mall.portal.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* 前台订单管理Service
* Created by macro on 2018/8/30.
*/
@Slf4j
@Service
public class OmsPortalOrderServiceImpl implements OmsPortalOrderService {
@Autowired
private UmsMemberService memberService;
@Autowired
private OmsCartItemService cartItemService;
@Autowired
private UmsMemberReceiveAddressService memberReceiveAddressService;
@Autowired
private UmsMemberCouponService memberCouponService;
@Autowired
private UmsIntegrationConsumeSettingMapper integrationConsumeSettingMapper;
@Autowired
private PmsSkuStockMapper skuStockMapper;
@Autowired
private SmsCouponHistoryDao couponHistoryDao;
@Autowired
private OmsOrderMapper orderMapper;
@Autowired
private PortalOrderItemDao orderItemDao;
@Autowired
private SmsCouponHistoryMapper couponHistoryMapper;
@Autowired
private RedisService redisService;
@Value("${redis.key.orderId}")
private String REDIS_KEY_ORDER_ID;
@Value("${redis.database}")
private String REDIS_DATABASE;
@Autowired
private PortalOrderDao portalOrderDao;
@Autowired
private OmsOrderSettingMapper orderSettingMapper;
@Autowired
private OmsOrderItemMapper orderItemMapper;
@Autowired
private CancelOrderSender cancelOrderSender;
@Override
public ConfirmOrderResult generateConfirmOrder(List<Long> cartIds) {
ConfirmOrderResult result = new ConfirmOrderResult();
//获取购物车信息
UmsMember currentMember = memberService.getCurrentMember();
List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(),cartIds);
result.setCartPromotionItemList(cartPromotionItemList);
//获取用户收货地址列表
List<UmsMemberReceiveAddress> memberReceiveAddressList = memberReceiveAddressService.list();
result.setMemberReceiveAddressList(memberReceiveAddressList);
//获取用户可用优惠券列表
List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1);
result.setCouponHistoryDetailList(couponHistoryDetailList);
//获取用户积分
result.setMemberIntegration(currentMember.getIntegration());
//获取积分使用规则
UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
result.setIntegrationConsumeSetting(integrationConsumeSetting);
//计算总金额、活动优惠、应付金额
ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(cartPromotionItemList);
result.setCalcAmount(calcAmount);
return result;
}
@Override
public Map<String, Object> generateOrder(OrderParam orderParam) {
List<OmsOrderItem> orderItemList = new ArrayList<>();
//校验收货地址
if(orderParam.getMemberReceiveAddressId()==null){
Asserts.fail("请选择收货地址!");
}
//获取购物车及优惠信息
UmsMember currentMember = memberService.getCurrentMember();
List<CartPromotionItem> cartPromotionItemList = cartItemService.listPromotion(currentMember.getId(), orderParam.getCartIds());
for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
//生成下单商品信息
OmsOrderItem orderItem = new OmsOrderItem();
orderItem.setProductId(cartPromotionItem.getProductId());
orderItem.setProductName(cartPromotionItem.getProductName());
orderItem.setProductPic(cartPromotionItem.getProductPic());
orderItem.setProductAttr(cartPromotionItem.getProductAttr());
orderItem.setProductBrand(cartPromotionItem.getProductBrand());
orderItem.setProductSn(cartPromotionItem.getProductSn());
orderItem.setProductPrice(cartPromotionItem.getPrice());
orderItem.setProductQuantity(cartPromotionItem.getQuantity());
orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
orderItem.setGiftIntegration(cartPromotionItem.getIntegration());
orderItem.setGiftGrowth(cartPromotionItem.getGrowth());
orderItemList.add(orderItem);
}
//判断购物车中商品是否都有库存
if (!hasStock(cartPromotionItemList)) {
Asserts.fail("库存不足,无法下单");
}
//判断使用使用了优惠券
if (orderParam.getCouponId() == null) {
//不用优惠券
for (OmsOrderItem orderItem : orderItemList) {
orderItem.setCouponAmount(new BigDecimal(0));
}
} else {
//使用优惠券
SmsCouponHistoryDetail couponHistoryDetail = getUseCoupon(cartPromotionItemList, orderParam.getCouponId());
if (couponHistoryDetail == null) {
Asserts.fail("该优惠券不可用");
}
//对下单商品的优惠券进行处理
handleCouponAmount(orderItemList, couponHistoryDetail);
}
//判断是否使用积分
if (orderParam.getUseIntegration() == null||orderParam.getUseIntegration().equals(0)) {
//不使用积分
for (OmsOrderItem orderItem : orderItemList) {
orderItem.setIntegrationAmount(new BigDecimal(0));
}
} else {
//使用积分
BigDecimal totalAmount = calcTotalAmount(orderItemList);
BigDecimal integrationAmount = getUseIntegrationAmount(orderParam.getUseIntegration(), totalAmount, currentMember, orderParam.getCouponId() != null);
if (integrationAmount.compareTo(new BigDecimal(0)) == 0) {
Asserts.fail("积分不可用");
} else {
//可用情况下分摊到可用商品中
for (OmsOrderItem orderItem : orderItemList) {
BigDecimal perAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(integrationAmount);
orderItem.setIntegrationAmount(perAmount);
}
}
}
//计算order_item的实付金额
handleRealAmount(orderItemList);
//进行库存锁定
lockStock(cartPromotionItemList);
//根据商品合计、运费、活动优惠、优惠券、积分计算应付金额
OmsOrder order = new OmsOrder();
order.setDiscountAmount(new BigDecimal(0));
order.setTotalAmount(calcTotalAmount(orderItemList));
order.setFreightAmount(new BigDecimal(0));
order.setPromotionAmount(calcPromotionAmount(orderItemList));
order.setPromotionInfo(getOrderPromotionInfo(orderItemList));
if (orderParam.getCouponId() == null) {
order.setCouponAmount(new BigDecimal(0));
} else {
order.setCouponId(orderParam.getCouponId());
order.setCouponAmount(calcCouponAmount(orderItemList));
}
if (orderParam.getUseIntegration() == null) {
order.setIntegration(0);
order.setIntegrationAmount(new BigDecimal(0));
} else {
order.setIntegration(orderParam.getUseIntegration());
order.setIntegrationAmount(calcIntegrationAmount(orderItemList));
}
order.setPayAmount(calcPayAmount(order));
//转化为订单信息并插入数据库
order.setMemberId(currentMember.getId());
order.setCreateTime(new Date());
order.setMemberUsername(currentMember.getUsername());
//支付方式:0->未支付;1->支付宝;2->微信
order.setPayType(orderParam.getPayType());
//订单来源:0->PC订单;1->app订单
order.setSourceType(1);
//订单状态:0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭;5->无效订单
order.setStatus(0);
//订单类型:0->正常订单;1->秒杀订单
order.setOrderType(0);
//收货人信息:姓名、电话、邮编、地址
UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(orderParam.getMemberReceiveAddressId());
order.setReceiverName(address.getName());
order.setReceiverPhone(address.getPhoneNumber());
order.setReceiverPostCode(address.getPostCode());
order.setReceiverProvince(address.getProvince());
order.setReceiverCity(address.getCity());
order.setReceiverRegion(address.getRegion());
order.setReceiverDetailAddress(address.getDetailAddress());
//0->未确认;1->已确认
order.setConfirmStatus(0);
order.setDeleteStatus(0);
//计算赠送积分
order.setIntegration(calcGifIntegration(orderItemList));
//计算赠送成长值
order.setGrowth(calcGiftGrowth(orderItemList));
//生成订单号
order.setOrderSn(generateOrderSn(order));
//设置自动收货天数
List<OmsOrderSetting> orderSettings = orderSettingMapper.selectByExample(new OmsOrderSettingExample());
if(CollUtil.isNotEmpty(orderSettings)){
order.setAutoConfirmDay(orderSettings.get(0).getConfirmOvertime());
}
// TODO: 2018/9/3 bill_*,delivery_*
//插入order表和order_item表
orderMapper.insert(order);
for (OmsOrderItem orderItem : orderItemList) {
orderItem.setOrderId(order.getId());
orderItem.setOrderSn(order.getOrderSn());
}
orderItemDao.insertList(orderItemList);
//如使用优惠券更新优惠券使用状态
if (orderParam.getCouponId() != null) {
updateCouponStatus(orderParam.getCouponId(), currentMember.getId(), 1);
}
//如使用积分需要扣除积分
if (orderParam.getUseIntegration() != null) {
order.setUseIntegration(orderParam.getUseIntegration());
if(currentMember.getIntegration()==null){
currentMember.setIntegration(0);
}
memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration() - orderParam.getUseIntegration());
}
//删除购物车中的下单商品
deleteCartItemList(cartPromotionItemList, currentMember);
//发送延迟消息取消订单
sendDelayMessageCancelOrder(order.getId());
Map<String, Object> result = new HashMap<>();
result.put("order", order);
result.put("orderItemList", orderItemList);
return result;
}
@Override
public Integer paySuccess(Long orderId, Integer payType) {
//修改订单支付状态
OmsOrder order = new OmsOrder();
order.setId(orderId);
order.setStatus(1);
order.setPaymentTime(new Date());
order.setPayType(payType);
OmsOrderExample orderExample = new OmsOrderExample();
orderExample.createCriteria()
.andIdEqualTo(order.getId())
.andDeleteStatusEqualTo(0)
.andStatusEqualTo(0);
//只修改未付款状态的订单
int updateCount = orderMapper.updateByExampleSelective(order, orderExample);
if(updateCount==0){
Asserts.fail("订单不存在或订单状态不是未支付!");
}
//恢复所有下单商品的锁定库存,扣减真实库存
OmsOrderDetail orderDetail = portalOrderDao.getDetail(orderId);
int totalCount = 0;
for (OmsOrderItem orderItem : orderDetail.getOrderItemList()) {
int count = portalOrderDao.reduceSkuStock(orderItem.getProductSkuId(),orderItem.getProductQuantity());
if(count==0){
Asserts.fail("库存不足,无法扣减!");
}
totalCount+=count;
}
return totalCount;
}
@Override
public Integer cancelTimeOutOrder() {
Integer count=0;
OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
//查询超时、未支付的订单及订单详情
List<OmsOrderDetail> timeOutOrders = portalOrderDao.getTimeOutOrders(orderSetting.getNormalOrderOvertime());
if (CollectionUtils.isEmpty(timeOutOrders)) {
return count;
}
//修改订单状态为交易取消
List<Long> ids = new ArrayList<>();
for (OmsOrderDetail timeOutOrder : timeOutOrders) {
ids.add(timeOutOrder.getId());
}
portalOrderDao.updateOrderStatus(ids, 4);
for (OmsOrderDetail timeOutOrder : timeOutOrders) {
//解除订单商品库存锁定
portalOrderDao.releaseSkuStockLock(timeOutOrder.getOrderItemList());
//修改优惠券使用状态
updateCouponStatus(timeOutOrder.getCouponId(), timeOutOrder.getMemberId(), 0);
//返还使用积分
if (timeOutOrder.getUseIntegration() != null) {
UmsMember member = memberService.getById(timeOutOrder.getMemberId());
memberService.updateIntegration(timeOutOrder.getMemberId(), member.getIntegration() + timeOutOrder.getUseIntegration());
}
}
return timeOutOrders.size();
}
@Override
public void cancelOrder(Long orderId) {
//查询未付款的取消订单
OmsOrderExample example = new OmsOrderExample();
example.createCriteria().andIdEqualTo(orderId).andStatusEqualTo(0).andDeleteStatusEqualTo(0);
List<OmsOrder> cancelOrderList = orderMapper.selectByExample(example);
if (CollectionUtils.isEmpty(cancelOrderList)) {
return;
}
OmsOrder cancelOrder = cancelOrderList.get(0);
if (cancelOrder != null) {
//修改订单状态为取消
cancelOrder.setStatus(4);
orderMapper.updateByPrimaryKeySelective(cancelOrder);
OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
orderItemExample.createCriteria().andOrderIdEqualTo(orderId);
List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
//解除订单商品库存锁定
if (!CollectionUtils.isEmpty(orderItemList)) {
for (OmsOrderItem orderItem : orderItemList) {
int count = portalOrderDao.releaseStockBySkuId(orderItem.getProductSkuId(),orderItem.getProductQuantity());
if(count==0){
Asserts.fail("库存不足,无法释放!");
}
}
}
//修改优惠券使用状态
updateCouponStatus(cancelOrder.getCouponId(), cancelOrder.getMemberId(), 0);
//返还使用积分
if (cancelOrder.getUseIntegration() != null) {
UmsMember member = memberService.getById(cancelOrder.getMemberId());
memberService.updateIntegration(cancelOrder.getMemberId(), member.getIntegration() + cancelOrder.getUseIntegration());
}
}
}
@Override
public void sendDelayMessageCancelOrder(Long orderId) {
//获取订单超时时间
OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
long delayTimes = orderSetting.getNormalOrderOvertime() * 60 * 1000;
//发送延迟消息
cancelOrderSender.sendMessage(orderId, delayTimes);
}
@Override
public void confirmReceiveOrder(Long orderId) {
UmsMember member = memberService.getCurrentMember();
OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
if(!member.getId().equals(order.getMemberId())){
Asserts.fail("不能确认他人订单!");
}
if(order.getStatus()!=2){
Asserts.fail("该订单还未发货!");
}
order.setStatus(3);
order.setConfirmStatus(1);
order.setReceiveTime(new Date());
orderMapper.updateByPrimaryKey(order);
}
@Override
public CommonPage<OmsOrderDetail> list(Integer status, Integer pageNum, Integer pageSize) {
if(status==-1){
status = null;
}
UmsMember member = memberService.getCurrentMember();
PageHelper.startPage(pageNum,pageSize);
OmsOrderExample orderExample = new OmsOrderExample();
OmsOrderExample.Criteria criteria = orderExample.createCriteria();
criteria.andDeleteStatusEqualTo(0)
.andMemberIdEqualTo(member.getId());
if(status!=null){
criteria.andStatusEqualTo(status);
}
orderExample.setOrderByClause("create_time desc");
List<OmsOrder> orderList = orderMapper.selectByExample(orderExample);
CommonPage<OmsOrder> orderPage = CommonPage.restPage(orderList);
//设置分页信息
CommonPage<OmsOrderDetail> resultPage = new CommonPage<>();
resultPage.setPageNum(orderPage.getPageNum());
resultPage.setPageSize(orderPage.getPageSize());
resultPage.setTotal(orderPage.getTotal());
resultPage.setTotalPage(orderPage.getTotalPage());
if(CollUtil.isEmpty(orderList)){
return resultPage;
}
//设置数据信息
List<Long> orderIds = orderList.stream().map(OmsOrder::getId).collect(Collectors.toList());
OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
orderItemExample.createCriteria().andOrderIdIn(orderIds);
List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
List<OmsOrderDetail> orderDetailList = new ArrayList<>();
for (OmsOrder omsOrder : orderList) {
OmsOrderDetail orderDetail = new OmsOrderDetail();
BeanUtil.copyProperties(omsOrder,orderDetail);
List<OmsOrderItem> relatedItemList = orderItemList.stream().filter(item -> item.getOrderId().equals(orderDetail.getId())).collect(Collectors.toList());
orderDetail.setOrderItemList(relatedItemList);
orderDetailList.add(orderDetail);
}
resultPage.setList(orderDetailList);
return resultPage;
}
@Override
public OmsOrderDetail detail(Long orderId) {
OmsOrder omsOrder = orderMapper.selectByPrimaryKey(orderId);
OmsOrderItemExample example = new OmsOrderItemExample();
example.createCriteria().andOrderIdEqualTo(orderId);
List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(example);
OmsOrderDetail orderDetail = new OmsOrderDetail();
BeanUtil.copyProperties(omsOrder,orderDetail);
orderDetail.setOrderItemList(orderItemList);
return orderDetail;
}
@Override
public void deleteOrder(Long orderId) {
UmsMember member = memberService.getCurrentMember();
OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
if(!member.getId().equals(order.getMemberId())){
Asserts.fail("不能删除他人订单!");
}
if(order.getStatus()==3||order.getStatus()==4){
order.setDeleteStatus(1);
orderMapper.updateByPrimaryKey(order);
}else{
Asserts.fail("只能删除已完成或已关闭的订单!");
}
}
@Override
public void paySuccessByOrderSn(String orderSn, Integer payType) {
OmsOrderExample example = new OmsOrderExample();
example.createCriteria()
.andOrderSnEqualTo(orderSn)
.andStatusEqualTo(0)
.andDeleteStatusEqualTo(0);
List<OmsOrder> orderList = orderMapper.selectByExample(example);
if(CollUtil.isNotEmpty(orderList)){
OmsOrder order = orderList.get(0);
paySuccess(order.getId(),payType);
}
}
/**
* 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
*/
private String generateOrderSn(OmsOrder order) {
StringBuilder sb = new StringBuilder();
String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
String key = REDIS_DATABASE+":"+ REDIS_KEY_ORDER_ID + date;
Long increment = redisService.incr(key, 1);
sb.append(date);
sb.append(String.format("%02d", order.getSourceType()));
sb.append(String.format("%02d", order.getPayType()));
String incrementStr = increment.toString();
if (incrementStr.length() <= 6) {
sb.append(String.format("%06d", increment));
} else {
sb.append(incrementStr);
}
return sb.toString();
}
/**
* 删除下单商品的购物车信息
*/
private void deleteCartItemList(List<CartPromotionItem> cartPromotionItemList, UmsMember currentMember) {
List<Long> ids = new ArrayList<>();
for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
ids.add(cartPromotionItem.getId());
}
cartItemService.delete(currentMember.getId(), ids);
}
/**
* 计算该订单赠送的成长值
*/
private Integer calcGiftGrowth(List<OmsOrderItem> orderItemList) {
Integer sum = 0;
for (OmsOrderItem orderItem : orderItemList) {
sum = sum + orderItem.getGiftGrowth() * orderItem.getProductQuantity();
}
return sum;
}
/**
* 计算该订单赠送的积分
*/
private Integer calcGifIntegration(List<OmsOrderItem> orderItemList) {
int sum = 0;
for (OmsOrderItem orderItem : orderItemList) {
sum += orderItem.getGiftIntegration() * orderItem.getProductQuantity();
}
return sum;
}
/**
* 将优惠券信息更改为指定状态
*
* @param couponId 优惠券id
* @param memberId 会员id
* @param useStatus 0->未使用;1->已使用
*/
private void updateCouponStatus(Long couponId, Long memberId, Integer useStatus) {
if (couponId == null) return;
//查询第一张优惠券
SmsCouponHistoryExample example = new SmsCouponHistoryExample();
example.createCriteria().andMemberIdEqualTo(memberId)
.andCouponIdEqualTo(couponId).andUseStatusEqualTo(useStatus == 0 ? 1 : 0);
List<SmsCouponHistory> couponHistoryList = couponHistoryMapper.selectByExample(example);
if (!CollectionUtils.isEmpty(couponHistoryList)) {
SmsCouponHistory couponHistory = couponHistoryList.get(0);
couponHistory.setUseTime(new Date());
couponHistory.setUseStatus(useStatus);
couponHistoryMapper.updateByPrimaryKeySelective(couponHistory);
}
}
private void handleRealAmount(List<OmsOrderItem> orderItemList) {
for (OmsOrderItem orderItem : orderItemList) {
//原价-促销优惠-优惠券抵扣-积分抵扣
BigDecimal realAmount = orderItem.getProductPrice()
.subtract(orderItem.getPromotionAmount())
.subtract(orderItem.getCouponAmount())
.subtract(orderItem.getIntegrationAmount());
orderItem.setRealAmount(realAmount);
}
}
/**
* 获取订单促销信息
*/
private String getOrderPromotionInfo(List<OmsOrderItem> orderItemList) {
StringBuilder sb = new StringBuilder();
for (OmsOrderItem orderItem : orderItemList) {
sb.append(orderItem.getPromotionName());
sb.append(";");
}
String result = sb.toString();
if (result.endsWith(";")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* 计算订单应付金额
*/
private BigDecimal calcPayAmount(OmsOrder order) {
//总金额+运费-促销优惠-优惠券优惠-积分抵扣
BigDecimal payAmount = order.getTotalAmount()
.add(order.getFreightAmount())
.subtract(order.getPromotionAmount())
.subtract(order.getCouponAmount())
.subtract(order.getIntegrationAmount());
return payAmount;
}
/**
* 计算订单优惠券金额
*/
private BigDecimal calcIntegrationAmount(List<OmsOrderItem> orderItemList) {
BigDecimal integrationAmount = new BigDecimal(0);
for (OmsOrderItem orderItem : orderItemList) {
if (orderItem.getIntegrationAmount() != null) {
integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
}
}
return integrationAmount;
}
/**
* 计算订单优惠券金额
*/
private BigDecimal calcCouponAmount(List<OmsOrderItem> orderItemList) {
BigDecimal couponAmount = new BigDecimal(0);
for (OmsOrderItem orderItem : orderItemList) {
if (orderItem.getCouponAmount() != null) {
couponAmount = couponAmount.add(orderItem.getCouponAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
}
}
return couponAmount;
}
/**
* 计算订单活动优惠
*/
private BigDecimal calcPromotionAmount(List<OmsOrderItem> orderItemList) {
BigDecimal promotionAmount = new BigDecimal(0);
for (OmsOrderItem orderItem : orderItemList) {
if (orderItem.getPromotionAmount() != null) {
promotionAmount = promotionAmount.add(orderItem.getPromotionAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
}
}
return promotionAmount;
}
/**
* 获取可用积分抵扣金额
*
* @param useIntegration 使用的积分数量
* @param totalAmount 订单总金额
* @param currentMember 使用的用户
* @param hasCoupon 是否已经使用优惠券
*/
private BigDecimal getUseIntegrationAmount(Integer useIntegration, BigDecimal totalAmount, UmsMember currentMember, boolean hasCoupon) {
BigDecimal zeroAmount = new BigDecimal(0);
//判断用户是否有这么多积分
if (useIntegration.compareTo(currentMember.getIntegration()) > 0) {
return zeroAmount;
}
//根据积分使用规则判断是否可用
//是否可与优惠券共用
UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(1L);
if (hasCoupon && integrationConsumeSetting.getCouponStatus().equals(0)) {
//不可与优惠券共用
return zeroAmount;
}
//是否达到最低使用积分门槛
if (useIntegration.compareTo(integrationConsumeSetting.getUseUnit()) < 0) {
return zeroAmount;
}
//是否超过订单抵用最高百分比
BigDecimal integrationAmount = new BigDecimal(useIntegration).divide(new BigDecimal(integrationConsumeSetting.getUseUnit()), 2, RoundingMode.HALF_EVEN);
BigDecimal maxPercent = new BigDecimal(integrationConsumeSetting.getMaxPercentPerOrder()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
if (integrationAmount.compareTo(totalAmount.multiply(maxPercent)) > 0) {
return zeroAmount;
}
return integrationAmount;
}
/**
* 对优惠券优惠进行处理
*
* @param orderItemList order_item列表
* @param couponHistoryDetail 可用优惠券详情
*/
private void handleCouponAmount(List<OmsOrderItem> orderItemList, SmsCouponHistoryDetail couponHistoryDetail) {
SmsCoupon coupon = couponHistoryDetail.getCoupon();
if (coupon.getUseType().equals(0)) {
//全场通用
calcPerCouponAmount(orderItemList, coupon);
} else if (coupon.getUseType().equals(1)) {
//指定分类
List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 0);
calcPerCouponAmount(couponOrderItemList, coupon);
} else if (coupon.getUseType().equals(2)) {
//指定商品
List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 1);
calcPerCouponAmount(couponOrderItemList, coupon);
}
}
/**
* 对每个下单商品进行优惠券金额分摊的计算
*
* @param orderItemList 可用优惠券的下单商品商品
*/
private void calcPerCouponAmount(List<OmsOrderItem> orderItemList, SmsCoupon coupon) {
BigDecimal totalAmount = calcTotalAmount(orderItemList);
for (OmsOrderItem orderItem : orderItemList) {
//(商品价格/可用商品总价)*优惠券面额
BigDecimal couponAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(coupon.getAmount());
orderItem.setCouponAmount(couponAmount);
}
}
/**
* 获取与优惠券有关系的下单商品
*
* @param couponHistoryDetail 优惠券详情
* @param orderItemList 下单商品
* @param type 使用关系类型:0->相关分类;1->指定商品
*/
private List<OmsOrderItem> getCouponOrderItemByRelation(SmsCouponHistoryDetail couponHistoryDetail, List<OmsOrderItem> orderItemList, int type) {
List<OmsOrderItem> result = new ArrayList<>();
if (type == 0) {
List<Long> categoryIdList = new ArrayList<>();
for (SmsCouponProductCategoryRelation productCategoryRelation : couponHistoryDetail.getCategoryRelationList()) {
categoryIdList.add(productCategoryRelation.getProductCategoryId());
}
for (OmsOrderItem orderItem : orderItemList) {
if (categoryIdList.contains(orderItem.getProductCategoryId())) {
result.add(orderItem);
} else {
orderItem.setCouponAmount(new BigDecimal(0));
}
}
} else if (type == 1) {
List<Long> productIdList = new ArrayList<>();
for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
productIdList.add(productRelation.getProductId());
}
for (OmsOrderItem orderItem : orderItemList) {
if (productIdList.contains(orderItem.getProductId())) {
result.add(orderItem);
} else {
orderItem.setCouponAmount(new BigDecimal(0));
}
}
}
return result;
}
/**
* 获取该用户可以使用的优惠券
*
* @param cartPromotionItemList 购物车优惠列表
* @param couponId 使用优惠券id
*/
private SmsCouponHistoryDetail getUseCoupon(List<CartPromotionItem> cartPromotionItemList, Long couponId) {
List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1);
for (SmsCouponHistoryDetail couponHistoryDetail : couponHistoryDetailList) {
if (couponHistoryDetail.getCoupon().getId().equals(couponId)) {
return couponHistoryDetail;
}
}
return null;
}
/**
* 计算总金额
*/
private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
BigDecimal totalAmount = new BigDecimal("0");
for (OmsOrderItem item : orderItemList) {
totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
}
return totalAmount;
}
/**
* 锁定下单商品的所有库存
*/
private void lockStock(List<CartPromotionItem> cartPromotionItemList) {
for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(cartPromotionItem.getProductSkuId());
skuStock.setLockStock(skuStock.getLockStock() + cartPromotionItem.getQuantity());
int count = portalOrderDao.lockStockBySkuId(cartPromotionItem.getProductSkuId(),cartPromotionItem.getQuantity());
if(count==0){
Asserts.fail("库存不足,无法下单");
}
}
}
/**
* 判断下单商品是否都有库存
*/
private boolean hasStock(List<CartPromotionItem> cartPromotionItemList) {
for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
if (cartPromotionItem.getRealStock()==null //判断真实库存是否为空
||cartPromotionItem.getRealStock() <= 0 //判断真实库存是否小于0
|| cartPromotionItem.getRealStock() < cartPromotionItem.getQuantity()) //判断真实库存是否小于下单的数量
{
return false;
}
}
return true;
}
/**
* 计算购物车中商品的价格
*/
private ConfirmOrderResult.CalcAmount calcCartAmount(List<CartPromotionItem> cartPromotionItemList) {
ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
calcAmount.setFreightAmount(new BigDecimal(0));
BigDecimal totalAmount = new BigDecimal("0");
BigDecimal promotionAmount = new BigDecimal("0");
for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
}
calcAmount.setTotalAmount(totalAmount);
calcAmount.setPromotionAmount(promotionAmount);
calcAmount.setPayAmount(totalAmount.subtract(promotionAmount));
return calcAmount;
}
}
| macrozheng/mall | mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java |
1,347 | package com.macro.mall.portal.service.impl;
import cn.hutool.core.collection.CollUtil;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.dao.SmsCouponHistoryDao;
import com.macro.mall.portal.domain.CartPromotionItem;
import com.macro.mall.portal.domain.SmsCouponHistoryDetail;
import com.macro.mall.portal.service.UmsMemberCouponService;
import com.macro.mall.portal.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
/**
* 会员优惠券管理Service实现类
* Created by macro on 2018/8/29.
*/
@Service
public class UmsMemberCouponServiceImpl implements UmsMemberCouponService {
@Autowired
private UmsMemberService memberService;
@Autowired
private SmsCouponMapper couponMapper;
@Autowired
private SmsCouponHistoryMapper couponHistoryMapper;
@Autowired
private SmsCouponHistoryDao couponHistoryDao;
@Autowired
private SmsCouponProductRelationMapper couponProductRelationMapper;
@Autowired
private SmsCouponProductCategoryRelationMapper couponProductCategoryRelationMapper;
@Autowired
private PmsProductMapper productMapper;
@Override
public void add(Long couponId) {
UmsMember currentMember = memberService.getCurrentMember();
//获取优惠券信息,判断数量
SmsCoupon coupon = couponMapper.selectByPrimaryKey(couponId);
if(coupon==null){
Asserts.fail("优惠券不存在");
}
if(coupon.getCount()<=0){
Asserts.fail("优惠券已经领完了");
}
Date now = new Date();
if(now.before(coupon.getEnableTime())){
Asserts.fail("优惠券还没到领取时间");
}
//判断用户领取的优惠券数量是否超过限制
SmsCouponHistoryExample couponHistoryExample = new SmsCouponHistoryExample();
couponHistoryExample.createCriteria().andCouponIdEqualTo(couponId).andMemberIdEqualTo(currentMember.getId());
long count = couponHistoryMapper.countByExample(couponHistoryExample);
if(count>=coupon.getPerLimit()){
Asserts.fail("您已经领取过该优惠券");
}
//生成领取优惠券历史
SmsCouponHistory couponHistory = new SmsCouponHistory();
couponHistory.setCouponId(couponId);
couponHistory.setCouponCode(generateCouponCode(currentMember.getId()));
couponHistory.setCreateTime(now);
couponHistory.setMemberId(currentMember.getId());
couponHistory.setMemberNickname(currentMember.getNickname());
//主动领取
couponHistory.setGetType(1);
//未使用
couponHistory.setUseStatus(0);
couponHistoryMapper.insert(couponHistory);
//修改优惠券表的数量、领取数量
coupon.setCount(coupon.getCount()-1);
coupon.setReceiveCount(coupon.getReceiveCount()==null?1:coupon.getReceiveCount()+1);
couponMapper.updateByPrimaryKey(coupon);
}
/**
* 16位优惠码生成:时间戳后8位+4位随机数+用户id后4位
*/
private String generateCouponCode(Long memberId) {
StringBuilder sb = new StringBuilder();
Long currentTimeMillis = System.currentTimeMillis();
String timeMillisStr = currentTimeMillis.toString();
sb.append(timeMillisStr.substring(timeMillisStr.length() - 8));
for (int i = 0; i < 4; i++) {
sb.append(new Random().nextInt(10));
}
String memberIdStr = memberId.toString();
if (memberIdStr.length() <= 4) {
sb.append(String.format("%04d", memberId));
} else {
sb.append(memberIdStr.substring(memberIdStr.length()-4));
}
return sb.toString();
}
@Override
public List<SmsCouponHistory> listHistory(Integer useStatus) {
UmsMember currentMember = memberService.getCurrentMember();
SmsCouponHistoryExample couponHistoryExample=new SmsCouponHistoryExample();
SmsCouponHistoryExample.Criteria criteria = couponHistoryExample.createCriteria();
criteria.andMemberIdEqualTo(currentMember.getId());
if(useStatus!=null){
criteria.andUseStatusEqualTo(useStatus);
}
return couponHistoryMapper.selectByExample(couponHistoryExample);
}
@Override
public List<SmsCouponHistoryDetail> listCart(List<CartPromotionItem> cartItemList, Integer type) {
UmsMember currentMember = memberService.getCurrentMember();
Date now = new Date();
//获取该用户所有优惠券
List<SmsCouponHistoryDetail> allList = couponHistoryDao.getDetailList(currentMember.getId());
//根据优惠券使用类型来判断优惠券是否可用
List<SmsCouponHistoryDetail> enableList = new ArrayList<>();
List<SmsCouponHistoryDetail> disableList = new ArrayList<>();
for (SmsCouponHistoryDetail couponHistoryDetail : allList) {
Integer useType = couponHistoryDetail.getCoupon().getUseType();
BigDecimal minPoint = couponHistoryDetail.getCoupon().getMinPoint();
Date endTime = couponHistoryDetail.getCoupon().getEndTime();
if(useType.equals(0)){
//0->全场通用
//判断是否满足优惠起点
//计算购物车商品的总价
BigDecimal totalAmount = calcTotalAmount(cartItemList);
if(now.before(endTime)&&totalAmount.subtract(minPoint).intValue()>=0){
enableList.add(couponHistoryDetail);
}else{
disableList.add(couponHistoryDetail);
}
}else if(useType.equals(1)){
//1->指定分类
//计算指定分类商品的总价
List<Long> productCategoryIds = new ArrayList<>();
for (SmsCouponProductCategoryRelation categoryRelation : couponHistoryDetail.getCategoryRelationList()) {
productCategoryIds.add(categoryRelation.getProductCategoryId());
}
BigDecimal totalAmount = calcTotalAmountByproductCategoryId(cartItemList,productCategoryIds);
if(now.before(endTime)&&totalAmount.intValue()>0&&totalAmount.subtract(minPoint).intValue()>=0){
enableList.add(couponHistoryDetail);
}else{
disableList.add(couponHistoryDetail);
}
}else if(useType.equals(2)){
//2->指定商品
//计算指定商品的总价
List<Long> productIds = new ArrayList<>();
for (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) {
productIds.add(productRelation.getProductId());
}
BigDecimal totalAmount = calcTotalAmountByProductId(cartItemList,productIds);
if(now.before(endTime)&&totalAmount.intValue()>0&&totalAmount.subtract(minPoint).intValue()>=0){
enableList.add(couponHistoryDetail);
}else{
disableList.add(couponHistoryDetail);
}
}
}
if(type.equals(1)){
return enableList;
}else{
return disableList;
}
}
@Override
public List<SmsCoupon> listByProduct(Long productId) {
List<Long> allCouponIds = new ArrayList<>();
//获取指定商品优惠券
SmsCouponProductRelationExample cprExample = new SmsCouponProductRelationExample();
cprExample.createCriteria().andProductIdEqualTo(productId);
List<SmsCouponProductRelation> cprList = couponProductRelationMapper.selectByExample(cprExample);
if(CollUtil.isNotEmpty(cprList)){
List<Long> couponIds = cprList.stream().map(SmsCouponProductRelation::getCouponId).collect(Collectors.toList());
allCouponIds.addAll(couponIds);
}
//获取指定分类优惠券
PmsProduct product = productMapper.selectByPrimaryKey(productId);
SmsCouponProductCategoryRelationExample cpcrExample = new SmsCouponProductCategoryRelationExample();
cpcrExample.createCriteria().andProductCategoryIdEqualTo(product.getProductCategoryId());
List<SmsCouponProductCategoryRelation> cpcrList = couponProductCategoryRelationMapper.selectByExample(cpcrExample);
if(CollUtil.isNotEmpty(cpcrList)){
List<Long> couponIds = cpcrList.stream().map(SmsCouponProductCategoryRelation::getCouponId).collect(Collectors.toList());
allCouponIds.addAll(couponIds);
}
//所有优惠券
SmsCouponExample couponExample = new SmsCouponExample();
couponExample.createCriteria().andEndTimeGreaterThan(new Date())
.andStartTimeLessThan(new Date())
.andUseTypeEqualTo(0);
if(CollUtil.isNotEmpty(allCouponIds)){
couponExample.or(couponExample.createCriteria()
.andEndTimeGreaterThan(new Date())
.andStartTimeLessThan(new Date())
.andUseTypeNotEqualTo(0)
.andIdIn(allCouponIds));
}
return couponMapper.selectByExample(couponExample);
}
@Override
public List<SmsCoupon> list(Integer useStatus) {
UmsMember member = memberService.getCurrentMember();
return couponHistoryDao.getCouponList(member.getId(),useStatus);
}
private BigDecimal calcTotalAmount(List<CartPromotionItem> cartItemList) {
BigDecimal total = new BigDecimal("0");
for (CartPromotionItem item : cartItemList) {
BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity())));
}
return total;
}
private BigDecimal calcTotalAmountByproductCategoryId(List<CartPromotionItem> cartItemList,List<Long> productCategoryIds) {
BigDecimal total = new BigDecimal("0");
for (CartPromotionItem item : cartItemList) {
if(productCategoryIds.contains(item.getProductCategoryId())){
BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity())));
}
}
return total;
}
private BigDecimal calcTotalAmountByProductId(List<CartPromotionItem> cartItemList,List<Long> productIds) {
BigDecimal total = new BigDecimal("0");
for (CartPromotionItem item : cartItemList) {
if(productIds.contains(item.getProductId())){
BigDecimal realPrice = item.getPrice().subtract(item.getReduceAmount());
total=total.add(realPrice.multiply(new BigDecimal(item.getQuantity())));
}
}
return total;
}
}
| macrozheng/mall | mall-portal/src/main/java/com/macro/mall/portal/service/impl/UmsMemberCouponServiceImpl.java |
1,348 | package com.blankj.utildebug.base.view;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import com.blankj.utilcode.util.SizeUtils;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.Nullable;
/**
* <pre>
* author: blankj
* blog : http://blankj.com
* time : 2019/09/10
* desc :
* </pre>
*/
public class SwipeRightMenu extends LinearLayout {
private static final AccelerateInterpolator OPEN_INTERPOLATOR = new AccelerateInterpolator(0.5f);
private static final DecelerateInterpolator CLOSE_INTERPOLATOR = new DecelerateInterpolator(0.5f);
private static boolean isTouching;
private static WeakReference<SwipeRightMenu> swipeMenuOpened;
private View mContentView;
private List<MenuBean> mMenus = new ArrayList<>();
private int mMenusWidth = 0;
public SwipeRightMenu(Context context) {
this(context, null);
}
public SwipeRightMenu(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setOrientation(HORIZONTAL);
post(new Runnable() {
@Override
public void run() {
initView();
}
});
}
private void initView() {
int childCount = getChildCount();
if (childCount <= 1) {
throw new IllegalArgumentException("no menus");
}
mContentView = getChildAt(0);
for (int i = 1; i < childCount; i++) {
MenuBean bean = new MenuBean(getChildAt(i));
mMenus.add(bean);
if (i == 1) {
bean.setCloseMargin(0);
} else {
bean.setCloseMargin(-mMenus.get(i - 2).getWidth());
}
mMenusWidth += bean.getWidth();
}
for (int i = 0; i < mMenus.size(); i++) {
mMenus.get(i).setOpenMargin(0);
}
}
private static final int STATE_DOWN = 0;
private static final int STATE_MOVE = 1;
private static final int STATE_STOP = 2;
private static final int SLIDE_INIT = 0;
private static final int SLIDE_HORIZONTAL = 1;
private static final int SLIDE_VERTICAL = 2;
private static final int MIN_DISTANCE_MOVE = SizeUtils.dp2px(4);
private static final int THRESHOLD_DISTANCE = SizeUtils.dp2px(20);
private static final int ANIM_TIMING = 350;
private int mState;
private int mDownX;
private int mDownY;
private int mLastX;
private int mLastY;
private int slideDirection;
private boolean isTouchPointInView(View view, int x, int y) {
if (view == null) {
return false;
}
int[] location = new int[2];
view.getLocationOnScreen(location);
int left = location[0];
int top = location[1];
int right = left + view.getMeasuredWidth();
int bottom = top + view.getMeasuredHeight();
return y >= top && y <= bottom && x >= left && x <= right;
}
public boolean isOpen() {
return swipeMenuOpened != null;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int x = (int) event.getRawX();
int y = (int) event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (isTouching) {
return false;
}
isTouching = true;
close(this);
mDownX = x;
mDownY = y;
mLastX = x;
mLastY = y;
mState = STATE_DOWN;
slideDirection = SLIDE_INIT;
super.dispatchTouchEvent(event);
break;
case MotionEvent.ACTION_MOVE:
if (mState == STATE_DOWN
&& Math.abs(x - mDownX) < MIN_DISTANCE_MOVE
&& Math.abs(y - mDownY) < MIN_DISTANCE_MOVE) {
break;
}
if (slideDirection == SLIDE_INIT) {
if (Math.abs(x - mDownX) > Math.abs(y - mDownY)) {
slideDirection = SLIDE_HORIZONTAL;
cancelChildViewTouch();
requestDisallowInterceptTouchEvent(true);// 让父 view 不要拦截
} else {
slideDirection = SLIDE_VERTICAL;
}
}
if (slideDirection == SLIDE_VERTICAL) {
return super.dispatchTouchEvent(event);
}
scrollTo(Math.max(Math.min(getScrollX() - x + mLastX, mMenusWidth), 0), 0);
float percent = getScrollX() / (float) mMenusWidth;
updateLeftMarginByPercent(percent);
mLastX = x;
mLastY = y;
mState = STATE_MOVE;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
try {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mState == STATE_DOWN) {
if (isOpen()) {
if (isTouchPointInView(mContentView, x, y)) {
close(true);
final long now = SystemClock.elapsedRealtime();
final MotionEvent cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
super.dispatchTouchEvent(cancelEvent);
return true;
}
}
super.dispatchTouchEvent(event);
close(true);
return true;
}
} else {
super.dispatchTouchEvent(event);
}
if (swipeMenuOpened != null && swipeMenuOpened.get() == this) {// 如果之前是展开状态
if (getScrollX() < mMenusWidth - THRESHOLD_DISTANCE) {// 超过阈值则关闭
close(true);
} else {// 否则还是打开
open(true);
}
} else {
if (getScrollX() > THRESHOLD_DISTANCE) {// 如果是关闭
open(true);// 超过阈值则打开
} else {
close(true);// 否则还是关闭
}
}
} finally {
isTouching = false;
mState = STATE_STOP;
}
break;
default:
break;
}
return true;
}
private void updateLeftMarginByPercent(float percent) {
for (MenuBean menu : mMenus) {
menu.getParams().leftMargin = (int) (menu.getCloseMargin() + percent * (menu.getOpenMargin() - menu.getCloseMargin()));
menu.getView().requestLayout();
}
}
private void close(boolean isAnim) {
swipeMenuOpened = null;
if (isAnim) {
ValueAnimator anim = ValueAnimator.ofInt(getScrollX(), 0);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
scrollTo((int) animation.getAnimatedValue(), 0);
}
});
anim.setInterpolator(CLOSE_INTERPOLATOR);
anim.setDuration(ANIM_TIMING).start();
for (final MenuBean menu : mMenus) {
ValueAnimator menuAnim = ValueAnimator.ofInt(menu.getParams().leftMargin, menu.getCloseMargin());
menuAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
menu.getParams().leftMargin = (int) animation.getAnimatedValue();
menu.getView().requestLayout();
}
});
menuAnim.setInterpolator(CLOSE_INTERPOLATOR);
menuAnim.setDuration(ANIM_TIMING).start();
}
} else {
scrollTo(0, 0);
for (final MenuBean menu : mMenus) {
menu.getParams().leftMargin = menu.getCloseMargin();
menu.getView().requestLayout();
}
}
}
private void open(boolean isAnim) {
swipeMenuOpened = new WeakReference<>(this);
if (isAnim) {
ValueAnimator anim = ValueAnimator.ofInt(getScrollX(), mMenusWidth);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
scrollTo((int) animation.getAnimatedValue(), 0);
}
});
anim.setInterpolator(OPEN_INTERPOLATOR);
anim.setDuration(ANIM_TIMING).start();
for (final MenuBean menu : mMenus) {
ValueAnimator menuAnim = ValueAnimator.ofInt(menu.getParams().leftMargin, menu.getOpenMargin());
menuAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
menu.getParams().leftMargin = (int) animation.getAnimatedValue();
menu.getView().requestLayout();
}
});
menuAnim.setInterpolator(OPEN_INTERPOLATOR);
menuAnim.setDuration(ANIM_TIMING).start();
}
} else {
scrollTo(mMenusWidth, 0);
for (final MenuBean menu : mMenus) {
menu.getParams().leftMargin = menu.getOpenMargin();
menu.getView().requestLayout();
}
}
}
public void close(SwipeRightMenu exclude) {
if (swipeMenuOpened != null) {
final SwipeRightMenu swipeMenu = swipeMenuOpened.get();
if (swipeMenu != exclude) {
swipeMenu.close(true);
}
}
}
private void cancelChildViewTouch() {
final long now = SystemClock.elapsedRealtime();
final MotionEvent cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
getChildAt(i).dispatchTouchEvent(cancelEvent);
}
cancelEvent.recycle();
}
private static class MenuBean {
private View mView;
private LinearLayout.LayoutParams mParams;
private int mWidth;
private int mCloseMargin;
private int mOpenMargin;
public MenuBean(View view) {
mView = view;
mParams = (LayoutParams) view.getLayoutParams();
mWidth = view.getWidth();
}
public View getView() {
return mView;
}
public LayoutParams getParams() {
return mParams;
}
public int getWidth() {
return mWidth;
}
public int getCloseMargin() {
return mCloseMargin;
}
public int getOpenMargin() {
return mOpenMargin;
}
public void setCloseMargin(int closeMargin) {
mCloseMargin = closeMargin;
}
public void setOpenMargin(int openMargin) {
mOpenMargin = openMargin;
}
}
} | Blankj/AndroidUtilCode | lib/utildebug/src/main/java/com/blankj/utildebug/base/view/SwipeRightMenu.java |
1,352 | package com.macro.mall.model;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
public class UmsIntegrationConsumeSetting implements Serializable {
private Long id;
@ApiModelProperty(value = "每一元需要抵扣的积分数量")
private Integer deductionPerAmount;
@ApiModelProperty(value = "每笔订单最高抵用百分比")
private Integer maxPercentPerOrder;
@ApiModelProperty(value = "每次使用积分最小单位100")
private Integer useUnit;
@ApiModelProperty(value = "是否可以和优惠券同用;0->不可以;1->可以")
private Integer couponStatus;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getDeductionPerAmount() {
return deductionPerAmount;
}
public void setDeductionPerAmount(Integer deductionPerAmount) {
this.deductionPerAmount = deductionPerAmount;
}
public Integer getMaxPercentPerOrder() {
return maxPercentPerOrder;
}
public void setMaxPercentPerOrder(Integer maxPercentPerOrder) {
this.maxPercentPerOrder = maxPercentPerOrder;
}
public Integer getUseUnit() {
return useUnit;
}
public void setUseUnit(Integer useUnit) {
this.useUnit = useUnit;
}
public Integer getCouponStatus() {
return couponStatus;
}
public void setCouponStatus(Integer couponStatus) {
this.couponStatus = couponStatus;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", deductionPerAmount=").append(deductionPerAmount);
sb.append(", maxPercentPerOrder=").append(maxPercentPerOrder);
sb.append(", useUnit=").append(useUnit);
sb.append(", couponStatus=").append(couponStatus);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | macrozheng/mall | mall-mbg/src/main/java/com/macro/mall/model/UmsIntegrationConsumeSetting.java |
1,354 | package cn.hutool.core.thread;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Consumer;
/**
* 当任务队列过长时处于阻塞状态,直到添加到队列中
* 如果阻塞过程中被中断,就会抛出{@link InterruptedException}异常<br>
* 有时候在线程池内访问第三方接口,只希望固定并发数去访问,并且不希望丢弃任务时使用此策略,队列满的时候会处于阻塞状态(例如刷库的场景)
*
* @author luozongle
* @since 5.8.0
*/
public class BlockPolicy implements RejectedExecutionHandler {
/**
* 线程池关闭时,为避免任务丢失,留下处理方法
* 如果需要由调用方来运行,可以{@code new BlockPolicy(Runnable::run)}
*/
private final Consumer<Runnable> handlerwhenshutdown;
/**
* 构造
*
* @param handlerwhenshutdown 线程池关闭后的执行策略
*/
public BlockPolicy(final Consumer<Runnable> handlerwhenshutdown) {
this.handlerwhenshutdown = handlerwhenshutdown;
}
/**
* 构造
*/
public BlockPolicy() {
this(null);
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
// 线程池未关闭时,阻塞等待
if (false == e.isShutdown()) {
try {
e.getQueue().put(r);
} catch (InterruptedException ex) {
throw new RejectedExecutionException("Task " + r + " rejected from " + e);
}
} else if (null != handlerwhenshutdown) {
// 当设置了关闭时候的处理
handlerwhenshutdown.accept(r);
}
// 线程池关闭后,丢弃任务
}
}
| dromara/hutool | hutool-core/src/main/java/cn/hutool/core/thread/BlockPolicy.java |
1,356 | H
1533539906
tags: BFS
给Walls and Gates很像, 不同的是, 这道题要选一个 coordinate, having shortest sum distance to all buildings (marked as 1).
#### BFS
- BFS 可以 mark shortest distance from bulding -> any possible spot.
- Try each building (marked as 1) -> BFS cover all 0.
- time: O(n^2) * # of building; use new visited[][] to mark visited for each building.
- O(n^2) find smallest point/aggregation value.
- 注意, 这道题我们update grid[][] sum up with shortest path value from building.
- 最后找个min value 就好了, 甚至不用return coordinate.
- 分析过, 还没有写.
```
/*
You want to build a house on an empty land which reaches all buildings
in the shortest amount of distance. You can only move up, down, left and right.
You are given a 2D grid of values 0, 1 or 2, where:
Each 0 marks an empty land which you can pass by freely.
Each 1 marks a building which you cannot pass through.
Each 2 marks an obstacle which you cannot pass through.
Example:
Input: [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
1 - 0 - 2 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0
Output: 7
Explanation: Given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2),
the point (1,2) is an ideal empty land to build a house, as the total
travel distance of 3+3+1=7 is minimal. So return 7.
Note:
There will be at least one building.
If it is not possible to build such house according to the above rules, return -1.
*/
``` | awangdev/leet-code | Java/Shortest Distance from All Buildings.java |
1,359 | /**
* File: radix_sort.java
* Created Time: 2023-01-17
* Author: krahets ([email protected])
*/
package chapter_sorting;
import java.util.*;
public class radix_sort {
/* 获取元素 num 的第 k 位,其中 exp = 10^(k-1) */
static int digit(int num, int exp) {
// 传入 exp 而非 k 可以避免在此重复执行昂贵的次方计算
return (num / exp) % 10;
}
/* 计数排序(根据 nums 第 k 位排序) */
static void countingSortDigit(int[] nums, int exp) {
// 十进制的位范围为 0~9 ,因此需要长度为 10 的桶数组
int[] counter = new int[10];
int n = nums.length;
// 统计 0~9 各数字的出现次数
for (int i = 0; i < n; i++) {
int d = digit(nums[i], exp); // 获取 nums[i] 第 k 位,记为 d
counter[d]++; // 统计数字 d 的出现次数
}
// 求前缀和,将“出现个数”转换为“数组索引”
for (int i = 1; i < 10; i++) {
counter[i] += counter[i - 1];
}
// 倒序遍历,根据桶内统计结果,将各元素填入 res
int[] res = new int[n];
for (int i = n - 1; i >= 0; i--) {
int d = digit(nums[i], exp);
int j = counter[d] - 1; // 获取 d 在数组中的索引 j
res[j] = nums[i]; // 将当前元素填入索引 j
counter[d]--; // 将 d 的数量减 1
}
// 使用结果覆盖原数组 nums
for (int i = 0; i < n; i++)
nums[i] = res[i];
}
/* 基数排序 */
static void radixSort(int[] nums) {
// 获取数组的最大元素,用于判断最大位数
int m = Integer.MIN_VALUE;
for (int num : nums)
if (num > m)
m = num;
// 按照从低位到高位的顺序遍历
for (int exp = 1; exp <= m; exp *= 10) {
// 对数组元素的第 k 位执行计数排序
// k = 1 -> exp = 1
// k = 2 -> exp = 10
// 即 exp = 10^(k-1)
countingSortDigit(nums, exp);
}
}
public static void main(String[] args) {
// 基数排序
int[] nums = { 10546151, 35663510, 42865989, 34862445, 81883077,
88906420, 72429244, 30524779, 82060337, 63832996 };
radixSort(nums);
System.out.println("基数排序完成后 nums = " + Arrays.toString(nums));
}
}
| krahets/hello-algo | codes/java/chapter_sorting/radix_sort.java |
1,363 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014-2023 [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.pagehelper;
/**
* 抽象类,自己的查询类可以继承该类,可以更直接的控制分页参数
*/
public class PageParam implements IPage {
private Integer pageNum;
private Integer pageSize;
private String orderBy;
public PageParam() {
}
public PageParam(Integer pageNum, Integer pageSize) {
this.pageNum = pageNum;
this.pageSize = pageSize;
}
public PageParam(Integer pageNum, Integer pageSize, String orderBy) {
this.pageNum = pageNum;
this.pageSize = pageSize;
this.orderBy = orderBy;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
@Override
public Integer getPageNum() {
return pageNum;
}
@Override
public Integer getPageSize() {
return pageSize;
}
@Override
public String getOrderBy() {
return orderBy;
}
}
| pagehelper/Mybatis-PageHelper | src/main/java/com/github/pagehelper/PageParam.java |
1,364 | package com.xkcoding.task.xxl.job.task;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* <p>
* 测试定时任务
* </p>
*
* @author yangkai.shen
* @date Created in 2019-08-07 10:15
*/
@Slf4j
@Component
@JobHandler("demoTask")
public class DemoTask extends IJobHandler {
/**
* execute handler, invoked when executor receives a scheduling request
*
* @param param 定时任务参数
* @return 执行状态
* @throws Exception 任务异常
*/
@Override
public ReturnT<String> execute(String param) throws Exception {
// 可以动态获取传递过来的参数,根据参数不同,当前调度的任务不同
log.info("【param】= {}", param);
XxlJobLogger.log("demo task run at : {}", DateUtil.now());
return RandomUtil.randomInt(1, 11) % 2 == 0 ? SUCCESS : FAIL;
}
}
| xkcoding/spring-boot-demo | demo-task-xxl-job/src/main/java/com/xkcoding/task/xxl/job/task/DemoTask.java |
1,367 | package decaf.machdesc;
import decaf.tac.Label;
import decaf.type.BaseType;
public final class Intrinsic {
/**
* 分配内存,如果失败则自动退出程序<br>
* 参数: 为要分配的内存块大小(单位为字节)<br>
* 返回: 该内存块的首地址<br>
* 返回类型: 指针,需要用VarDecl的changeTypeTo()函数更改类型
*/
public static final Intrinsic ALLOCATE = new Intrinsic("_Alloc", 1,
BaseType.INT);
/**
* 读取一行字符串(最大63个字符)<br>
* 返回: 读到的字符串首地址<br>
* 返回类型: string
*/
public static final Intrinsic READ_LINE = new Intrinsic("_ReadLine", 0,
BaseType.STRING);
/**
* 读取一个整数<br>
* 返回: 读到的整数<br>
* 返回类型: int
*/
public static final Intrinsic READ_INT = new Intrinsic("_ReadInteger", 0,
BaseType.INT);
/**
* 比较两个字符串<br>
* 参数: 要比较的两个字符串的首地址<br>
* 返回: 若相等则返回true,否则返回false<br>
* 返回类型: bool
*/
public static final Intrinsic STRING_EQUAL = new Intrinsic("_StringEqual",
2, BaseType.BOOL);
/**
* 打印一个整数<br>
* 参数: 要打印的数字
*/
public static final Intrinsic PRINT_INT = new Intrinsic("_PrintInt", 1,
BaseType.VOID);
/**
* 打印一个字符串<br>
* 参数: 要打印的字符串
*/
public static final Intrinsic PRINT_STRING = new Intrinsic("_PrintString",
1, BaseType.VOID);
/**
* 打印一个布尔值<br>
* 参数: 要打印的布尔变量
*/
public static final Intrinsic PRINT_BOOL = new Intrinsic("_PrintBool", 1,
BaseType.VOID);
/**
* 结束程序<br>
* 可以作为子程序调用,也可以直接Goto
*/
public static final Intrinsic HALT = new Intrinsic("_Halt", 0,
BaseType.VOID);
/**
* 函数名字
*/
public final Label label;
/**
* 函数的参数个数
*/
public final int numArgs;
/**
* 函数返回值类型
*/
public final BaseType type;
/**
* 构造一个预定义函数的信息
*
* @param name
* 函数名字
* @param argc
* 参数个数
* @param type
* 返回类型
*/
private Intrinsic(String name, int numArgs, BaseType type) {
this.label = Label.createLabel(name, false);
this.numArgs = numArgs;
this.type = type;
}
}
| PKUanonym/REKCARC-TSC-UHT | 大三上/编译原理/hw/2015_刘智峰_PA/PA3/src/decaf/machdesc/Intrinsic.java |
1,371 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.demo.callback;
import com.google.gson.stream.JsonReader;
import com.lzy.demo.model.LzyResponse;
import com.lzy.demo.model.SimpleResponse;
import com.lzy.demo.utils.Convert;
import com.lzy.okgo.convert.Converter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class JsonConvert<T> implements Converter<T> {
private Type type;
private Class<T> clazz;
public JsonConvert() {
}
public JsonConvert(Type type) {
this.type = type;
}
public JsonConvert(Class<T> clazz) {
this.clazz = clazz;
}
/**
* 该方法是子线程处理,不能做ui相关的工作
* 主要作用是解析网络返回的 response 对象,生成onSuccess回调中需要的数据对象
* 这里的解析工作不同的业务逻辑基本都不一样,所以需要自己实现,以下给出的时模板代码,实际使用根据需要修改
*/
@Override
public T convertResponse(Response response) throws Throwable {
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 重要的事情说三遍,不同的业务,这里的代码逻辑都不一样,如果你不修改,那么基本不可用
// 如果你对这里的代码原理不清楚,可以看这里的详细原理说明: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
// 如果你对这里的代码原理不清楚,可以看这里的详细原理说明: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
// 如果你对这里的代码原理不清楚,可以看这里的详细原理说明: https://github.com/jeasonlzy/okhttp-OkGo/wiki/JsonCallback
if (type == null) {
if (clazz == null) {
// 如果没有通过构造函数传进来,就自动解析父类泛型的真实类型(有局限性,继承后就无法解析到)
Type genType = getClass().getGenericSuperclass();
type = ((ParameterizedType) genType).getActualTypeArguments()[0];
} else {
return parseClass(response, clazz);
}
}
if (type instanceof ParameterizedType) {
return parseParameterizedType(response, (ParameterizedType) type);
} else if (type instanceof Class) {
return parseClass(response, (Class<?>) type);
} else {
return parseType(response, type);
}
}
private T parseClass(Response response, Class<?> rawType) throws Exception {
if (rawType == null) return null;
ResponseBody body = response.body();
if (body == null) return null;
JsonReader jsonReader = new JsonReader(body.charStream());
if (rawType == String.class) {
//noinspection unchecked
return (T) body.string();
} else if (rawType == JSONObject.class) {
//noinspection unchecked
return (T) new JSONObject(body.string());
} else if (rawType == JSONArray.class) {
//noinspection unchecked
return (T) new JSONArray(body.string());
} else {
T t = Convert.fromJson(jsonReader, rawType);
response.close();
return t;
}
}
private T parseType(Response response, Type type) throws Exception {
if (type == null) return null;
ResponseBody body = response.body();
if (body == null) return null;
JsonReader jsonReader = new JsonReader(body.charStream());
// 泛型格式如下: new JsonCallback<任意JavaBean>(this)
T t = Convert.fromJson(jsonReader, type);
response.close();
return t;
}
private T parseParameterizedType(Response response, ParameterizedType type) throws Exception {
if (type == null) return null;
ResponseBody body = response.body();
if (body == null) return null;
JsonReader jsonReader = new JsonReader(body.charStream());
Type rawType = type.getRawType(); // 泛型的实际类型
Type typeArgument = type.getActualTypeArguments()[0]; // 泛型的参数
if (rawType != LzyResponse.class) {
// 泛型格式如下: new JsonCallback<外层BaseBean<内层JavaBean>>(this)
T t = Convert.fromJson(jsonReader, type);
response.close();
return t;
} else {
if (typeArgument == Void.class) {
// 泛型格式如下: new JsonCallback<LzyResponse<Void>>(this)
SimpleResponse simpleResponse = Convert.fromJson(jsonReader, SimpleResponse.class);
response.close();
//noinspection unchecked
return (T) simpleResponse.toLzyResponse();
} else {
// 泛型格式如下: new JsonCallback<LzyResponse<内层JavaBean>>(this)
LzyResponse lzyResponse = Convert.fromJson(jsonReader, type);
response.close();
int code = lzyResponse.code;
//这里的0是以下意思
//一般来说服务器会和客户端约定一个数表示成功,其余的表示失败,这里根据实际情况修改
if (code == 0) {
//noinspection unchecked
return (T) lzyResponse;
} else if (code == 104) {
throw new IllegalStateException("用户授权信息无效");
} else if (code == 105) {
throw new IllegalStateException("用户收取信息已过期");
} else {
//直接将服务端的错误信息抛出,onError中可以获取
throw new IllegalStateException("错误代码:" + code + ",错误信息:" + lzyResponse.msg);
}
}
}
}
}
| jeasonlzy/okhttp-OkGo | demo/src/main/java/com/lzy/demo/callback/JsonConvert.java |
1,372 | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.base;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.jess.arms.base.delegate.IFragment;
import com.jess.arms.integration.cache.Cache;
import com.jess.arms.integration.cache.CacheType;
import com.jess.arms.integration.lifecycle.FragmentLifecycleable;
import com.jess.arms.mvp.IPresenter;
import com.jess.arms.utils.ArmsUtils;
import com.trello.rxlifecycle2.android.FragmentEvent;
import javax.inject.Inject;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.Subject;
/**
* ================================================
* 因为 Java 只能单继承, 所以如果要用到需要继承特定 @{@link Fragment} 的三方库, 那你就需要自己自定义 @{@link Fragment}
* 继承于这个特定的 @{@link Fragment}, 然后再按照 {@link BaseFragment} 的格式, 将代码复制过去, 记住一定要实现{@link IFragment}
*
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki">请配合官方 Wiki 文档学习本框架</a>
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki/UpdateLog">更新日志, 升级必看!</a>
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki/Issues">常见 Issues, 踩坑必看!</a>
* @see <a href="https://github.com/JessYanCoding/ArmsComponent/wiki">MVPArms 官方组件化方案 ArmsComponent, 进阶指南!</a>
* Created by JessYan on 22/03/2016
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public abstract class BaseFragment<P extends IPresenter> extends Fragment implements IFragment, FragmentLifecycleable {
protected final String TAG = this.getClass().getSimpleName();
private final BehaviorSubject<FragmentEvent> mLifecycleSubject = BehaviorSubject.create();
protected Context mContext;
@Inject
@Nullable
protected P mPresenter;//如果当前页面逻辑简单, Presenter 可以为 null
private Cache<String, Object> mCache;
@NonNull
@Override
public synchronized Cache<String, Object> provideCache() {
if (mCache == null) {
//noinspection unchecked
mCache = ArmsUtils.obtainAppComponentFromContext(getActivity()).cacheFactory().build(CacheType.FRAGMENT_CACHE);
}
return mCache;
}
@NonNull
@Override
public final Subject<FragmentEvent> provideLifecycleSubject() {
return mLifecycleSubject;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return initView(inflater, container, savedInstanceState);
}
@Override
public void onDestroy() {
super.onDestroy();
if (mPresenter != null) {
mPresenter.onDestroy();//释放资源
}
this.mPresenter = null;
}
@Override
public void onDetach() {
super.onDetach();
mContext = null;
}
/**
* 是否使用 EventBus
* Arms 核心库现在并不会依赖某个 EventBus, 要想使用 EventBus, 还请在项目中自行依赖对应的 EventBus
* 现在支持两种 EventBus, greenrobot 的 EventBus 和畅销书 《Android源码设计模式解析与实战》的作者 何红辉 所作的 AndroidEventBus
* 确保依赖后, 将此方法返回 true, Arms 会自动检测您依赖的 EventBus, 并自动注册
* 这种做法可以让使用者有自行选择三方库的权利, 并且还可以减轻 Arms 的体积
*
* @return 返回 {@code true} (默认为 {@code true}), Arms 会自动注册 EventBus
*/
@Override
public boolean useEventBus() {
return true;
}
}
| JessYanCoding/MVPArms | arms/src/main/java/com/jess/arms/base/BaseFragment.java |
1,373 | package com.example.gsyvideoplayer.simple;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import com.example.gsyvideoplayer.R;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
/**
* 横屏不旋转的 Demo
*/
public class SimplePlayer extends AppCompatActivity {
StandardGSYVideoPlayer videoPlayer;
OrientationUtils orientationUtils;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_play);
init();
}
private void init() {
videoPlayer = (StandardGSYVideoPlayer)findViewById(R.id.video_player);
String source1 = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
videoPlayer.setUp(source1, true, "测试视频");
//增加封面
ImageView imageView = new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(R.mipmap.xxx1);
videoPlayer.setThumbImageView(imageView);
//增加title
videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);
//设置返回键
videoPlayer.getBackButton().setVisibility(View.VISIBLE);
//设置旋转
orientationUtils = new OrientationUtils(this, videoPlayer);
//设置全屏按键功能,这是使用的是选择屏幕,而不是全屏
videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ------- !!!如果不需要旋转屏幕,可以不调用!!!-------
// 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false)
//orientationUtils.resolveByClick();
finish();
}
});
//是否可以滑动调整
videoPlayer.setIsTouchWiget(true);
//设置返回按键功能
videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
///不需要屏幕旋转
videoPlayer.setNeedOrientationUtils(false);
videoPlayer.startPlayLogic();
}
@Override
protected void onPause() {
super.onPause();
videoPlayer.onVideoPause();
}
@Override
protected void onResume() {
super.onResume();
videoPlayer.onVideoResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
GSYVideoManager.releaseAllVideos();
if (orientationUtils != null)
orientationUtils.releaseListener();
}
@Override
public void onBackPressed() {
/// 不需要回归竖屏
// if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
// videoPlayer.getFullscreenButton().performClick();
// return;
// }
//释放所有
videoPlayer.setVideoAllCallBack(null);
super.onBackPressed();
}
}
| CarGuo/GSYVideoPlayer | app/src/main/java/com/example/gsyvideoplayer/simple/SimplePlayer.java |
1,375 | package tk.mybatis.mapper.genid;
/**
* 不提供具体的实现,这里提供一个思路。<br/>
* <p>
* 在 Spring 集成环境中,可以通过配置静态方式获取 Spring 的 context 对象。<br/>
* <p>
* 如果使用 vesta(https://gitee.com/free/vesta-id-generator) 来生成 ID,假设已经提供了 vesta 的 idService。<br/>
* <p>
* 那么可以在实现中获取该类,然后生成 Id 返回,示例代码如下:
*
* <pre>
* public class VestaGenId implement GenId<Long> {
* public Long genId(String table, String column){
* //ApplicationUtil.getBean 需要自己实现
* IdService idService = ApplicationUtil.getBean(IdService.class);
* return idService.genId();
* }
* }
* </pre>
*
* @author liuzh
*/
public interface GenId<T> {
T genId(String table, String column);
class NULL implements GenId {
@Override
public Object genId(String table, String column) {
throw new UnsupportedOperationException();
}
}
}
| abel533/Mapper | core/src/main/java/tk/mybatis/mapper/genid/GenId.java |
1,376 | /*
* Tencent is pleased to support the open source community by making QMUI_Android available.
*
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the MIT License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://opensource.org/licenses/MIT
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qmuiteam.qmui.span;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.style.ReplacementSpan;
import androidx.annotation.NonNull;
/**
* 支持调整字体大小的 span。{@link android.text.style.AbsoluteSizeSpan} 可以调整字体大小,但在中英文混排下由于 decent 的不同,
* 无法根据具体需求进行底部对齐或者顶部对齐。而 QMUITextSizeSpan 则可以多传一个参数,让你可以根据具体情况来决定偏移值。
*
* @author cginechen
* @date 2016-12-02
*/
public class QMUITextSizeSpan extends ReplacementSpan {
private int mTextSize;
private int mVerticalOffset;
private Paint mPaint;
private Typeface mTypeface;
public QMUITextSizeSpan(int textSize, int verticalOffset){
this(textSize, verticalOffset, null);
}
public QMUITextSizeSpan(int textSize, int verticalOffset, Typeface typeface){
mTextSize = textSize;
mVerticalOffset = verticalOffset;
mTypeface = typeface;
mPaint = new Paint();
mPaint.setTextSize(mTextSize);
mPaint.setTypeface(mTypeface);
}
@Override
public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
if(mTextSize > paint.getTextSize() && fm != null){
Paint.FontMetricsInt newFm = mPaint.getFontMetricsInt();
fm.descent = newFm.descent;
fm.ascent = newFm.ascent;
fm.top = newFm.top;
fm.bottom = newFm.bottom;
}
return (int) mPaint.measureText(text, start, end);
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top,
int y, int bottom, @NonNull Paint paint) {
mPaint.setColor(paint.getColor());
mPaint.setStyle(paint.getStyle());
mPaint.setAntiAlias(paint.isAntiAlias());
int baseline = y + mVerticalOffset;
canvas.drawText(text, start, end, x, baseline, mPaint);
}
}
| Tencent/QMUI_Android | qmui/src/main/java/com/qmuiteam/qmui/span/QMUITextSizeSpan.java |
1,377 | package practice;
import java.util.Arrays;
/**
* @program: leetcode
* @description:
* @author: [email protected]
* @create: 2022-06-30 22:33
**/
public class L1464 {
public int maxProduct(int[] nums) {
int max = -1;
int second = -1;
Arrays.sort(nums);
for(int i=0;i<nums.length;i++) {
// 注意,这里要用大于等于,如此以来,最大值出现两次的时候,可以保证max和second都是最大值
if (nums[i]>=max) {
// 如果max已经赋值过,那么可以把曾经的max让给second
if (max>-1) {
second = max;
}
max = nums[i];
} else if (second<nums[i]) {
// max看不上的数字,要给second试试
second = nums[i];
}
}
return (max-1)*(second-1);
}
public static void main(String[] args) {
System.out.println(new L1464().maxProduct(new int[] {3,4,5,2})); // 12
System.out.println(new L1464().maxProduct(new int[] {1,5,4,5})); // 16
System.out.println(new L1464().maxProduct(new int[] {3,7})); // 12
System.out.println(new L1464().maxProduct(new int[] {7,3})); // 12
System.out.println(new L1464().maxProduct(new int[] {10,2,5,2})); // 36
}
}
| zq2599/blog_demos | leetcode/src/practice/L1464.java |
1,378 | package practice;
/**
* @program: leetcode
* @description:
* @author: [email protected]
* @create: 2022-06-30 22:33
**/
public class L0045 {
private int findFartestOneStep(int[] nums, int start) {
int range = nums[start];
// 如果是0,表示从start位置无法移动,返回的距离只能是自己的位置
if (0==range) {
return start;
}
int maxDistance = start+range;
int bestPosition = start;
for(int i=start+1;i<=start+range;i++) {
if (nums[i]!=0 && i+nums[i]>maxDistance) {
bestPosition = i;
maxDistance = i+nums[i];
}
// 如果最远距离可以到达队尾,就不用再往后找了,直接范围当前位置
if (maxDistance>=(nums.length-1)) {
return i;
}
}
return bestPosition;
}
public int jump(int[] nums) {
if (1==nums.length) {
return 0;
} else if (2==nums.length) {
// 注意审题:假设你总是可以到达数组的最后一个位置,所以数组等于2的时候,一定是一步结束
return 1;
}
// if (nums[0]>=nums.length-1) {
// return 1;
// }
int currentPostion = 0;
int step = 0;
int nextPosition = 0;
while (true) {
// 从当前位置起步,如果一步就到达队尾,那么可以直接返回了(注意要把这一步加上)
if ((currentPostion+nums[currentPostion])>= (nums.length-1)) {
return step+1;
}
nextPosition = findFartestOneStep(nums, currentPostion);
// System.out.println("从当前位置[" + currentPostion + "]探查,发现去[" + nextPosition + "]可以到达最远距离[" + (nextPosition+nums[nextPosition]) + "]");
//走了一步
currentPostion = nextPosition;
step++;
}
}
public static void main(String[] args) {
// 2
System.out.println(new L0045().jump(new int[] {2,3,1,1,4}));
// // 2
System.out.println(new L0045().jump(new int[] {2,3,0,1,4}));
// // 1
System.out.println(new L0045().jump(new int[] {3,2,1}));
// // 2
System.out.println(new L0045().jump(new int[] {7,0,9,6,9,6,1,7,9,0,1,2,9,0,3}));
// 4
System.out.println(new L0045().jump(new int[] {1,1,1,1,1}));
}
}
| zq2599/blog_demos | leetcode/src/practice/L0045.java |
1,379 | package practice;
import java.util.Arrays;
/**
* @program: leetcode
* @description:
* @author: [email protected]
* @create: 2022-06-30 22:33
**/
public class L0283 {
public void moveZeroes(int[] nums) {
// 处理异常情况
if(nums.length<1) {
return;
}
// insertOffset表示从后往前移动非零数据时,可以写入的位置
int insertOffset = -1;
// 第一个可以写入的位置,是0第一次出现的位置
for (int i=0;i<nums.length;i++) {
if(nums[i]==0) {
insertOffset = i;
break;
}
}
// 如果insertOffset还等于-1,就表示整个数组都没有0
// 如果此时insertOffset指向队伍末尾,就表示数组最后一个元素是0,前面都不是0,此时就没必要操作了
if(insertOffset==-1 || insertOffset==nums.length-1) {
return;
}
for (int i=insertOffset+1;i<nums.length;i++) {
// 遇到0,继续往后走,insertOffset不变,就是最靠左的可以写入的位置
if (nums[i]==0) {
continue;
}
nums[insertOffset] = nums[i];
// 移动完毕后,此位置设为为0,这是题目要求
nums[i] = 0;
// 假设insertOffset是2,那么上一步将非零数字写入到2位置之后,接下来能写入的位置肯定是3,
// 因为此刻的3位置的值,如果是0就能写入,如果非零上一步已经将其值写入到2位置的了,此3位置的内容就没用了,可以用于下一次写入
insertOffset++;
}
}
public static void main( String[] args ) {
int[] nums = {0,1,0,3,12};
new L0283().moveZeroes(nums);
System.out.println(Arrays.toString(nums) );
}
}
| zq2599/blog_demos | leetcode/src/practice/L0283.java |
1,380 | package practice;
import java.util.ArrayList;
import java.util.List;
/**
* @program: leetcode
* @description:
* @author: [email protected]
* @create: 2022-06-30 22:33
**/
public class L0306 {
boolean res = false;
private static boolean check(String num, int pos0, int pos1, int pos2, int pos3) {
// 加数长度大于和是不可能的
if ((pos1-pos0)>(pos3-pos2)) {
return false;
}
if ((pos2-pos1)>(pos3-pos2)) {
return false;
}
String add1Str = num.substring(pos0, pos1);
String add2Str = num.substring(pos1, pos2);
StringBuilder sb = new StringBuilder();
int i = add1Str.length() - 1, j = add2Str.length() - 1;
int upper = 0;
while (i >= 0 || j >= 0) {
int a = 0, b = 0;
if (i >= 0) a = add1Str.charAt(i) - '0';
if (j >= 0) b = add2Str.charAt(j) - '0';
int sum = a + b + upper;
upper = sum / 10;
sb.append(sum % 10);
i--;
j--;
}
if (upper != 0) {
sb.append(upper);
}
String addRlt = sb.reverse().toString();
return addRlt.equals(num.substring(pos2, pos3));
}
private static boolean isZeroStart(String num, int start, int end) {
String lastPart = num.substring(start, end);
return (lastPart.length()>1 && '0'==lastPart.charAt(0));
}
private void dfs(String num, int startIndex, ArrayList<Integer> path) {
int size = path.size();
if(2==size) {
if (!isZeroStart(num, path.get(1), num.length())
&& check(num, 0, path.get(0), path.get(1), num.length())) {
res = true;
return;
}
}
else if(size>2) {
int pos0 = size>3 ? path.get(size-4) : 0;
int pos1 = path.get(size-3);
int pos2 = path.get(size-2);
int pos3 = path.get(size-1);
// 如果不符合规则,就终止接下来的递归
if (!check(num, pos0, pos1, pos2, pos3)) {
return;
}
// 剩下的所有内容作为结果,验证一下是否满足需求
// 满足的话,就表示整串都满足了,可以返回,因为题目要求返回true或者false
// 不允许出现以0开头的多位数字,所以,剩下的部分如果是以0开头的多位数字,就不需要转成数字了(还要继续分割)
if (!isZeroStart(num, pos3, num.length())
&& check(num, pos1, pos2, pos3, num.length())) {
res = true;
return;
}
/*
System.out.println("path : " + path);
int rlt = Integer.valueOf(num.substring(path.get(size-2), path.get(size-1)));
int add2 = Integer.valueOf(num.substring(path.get(size-3), path.get(size-2)));
int start = size>3 ? path.get(size-4) : 0;
int add1 = Integer.valueOf(num.substring(start, path.get(size-3)));
System.out.println("add1 [" + add1 + "], add2 [" + add2 + "], rlt [" + rlt + "]");
if(rlt!=(add1+add2)) {
return;
}
// 用剩下的内容做一下检查,看看如果相等,就可以提前结束了
int last = Integer.valueOf(num.substring(path.get(size-1), num.length()));
System.out.println("last [" + last + "]");
if (last==(rlt+add2)) {
res = true;
return;
}
*/
}
for(int i=startIndex;i<num.length();i++) {
// System.out.println("i : [" + i + "], val : " + num.charAt(i));
// if('0'==num.charAt(i)) {
// continue;
// }
size = path.size();
String sub = "";
if (size>0) {
sub = num.substring(path.get(size-1), i);
} else {
sub = num.substring(0,i);
}
if (sub.length()>1 && '0'==sub.charAt(0)) {
// System.out.println(sub);
continue;
}
path.add(i);
dfs(num, i+1, path);
// 已经匹配成功,就可以提前返回了
if (res) {
return;
}
path.remove(path.size()-1);
}
}
public boolean isAdditiveNumber(String num) {
dfs(num, 1, new ArrayList<>());
return res;
}
public static void main(String[] args) {
// System.out.println((new L0306().isAdditiveNumber("112358")));
// System.out.println((new L0306().isAdditiveNumber("199100199")));
// System.out.println((new L0306().isAdditiveNumber("1023")));
// 预期是true
System.out.println((new L0306().isAdditiveNumber("101")));
// 预期 false
System.out.println((new L0306().isAdditiveNumber("1203")));
// System.out.println((new L0306().isAdditiveNumber("198019823962")));
// 预期 true
System.out.println((new L0306().isAdditiveNumber("121474836472147483648")));
// System.out.println("1234".substring(0,1));
// System.out.println("1234".substring(1,2));
// System.out.println("1234".substring(2,3));
}
}
| zq2599/blog_demos | leetcode/src/practice/L0306.java |
1,381 | /*
* Copyright 2018 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.http.log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.jess.arms.di.module.GlobalConfigModule;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.Request;
/**
* ================================================
* 对 OkHttp 的请求和响应信息进行更规范和清晰的打印, 开发者可更根据自己的需求自行扩展打印格式
*
* @see DefaultFormatPrinter
* @see GlobalConfigModule.Builder#formatPrinter(FormatPrinter)
* Created by JessYan on 31/01/2018 17:36
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public interface FormatPrinter {
/**
* 打印网络请求信息, 当网络请求时 {{@link okhttp3.RequestBody}} 可以解析的情况
*
* @param request
* @param bodyString 发送给服务器的请求体中的数据(已解析)
*/
void printJsonRequest(@NonNull Request request, @NonNull String bodyString);
/**
* 打印网络请求信息, 当网络请求时 {{@link okhttp3.RequestBody}} 为 {@code null} 或不可解析的情况
*
* @param request
*/
void printFileRequest(@NonNull Request request);
/**
* 打印网络响应信息, 当网络响应时 {{@link okhttp3.ResponseBody}} 可以解析的情况
*
* @param chainMs 服务器响应耗时(单位毫秒)
* @param isSuccessful 请求是否成功
* @param code 响应码
* @param headers 请求头
* @param contentType 服务器返回数据的数据类型
* @param bodyString 服务器返回的数据(已解析)
* @param segments 域名后面的资源地址
* @param message 响应信息
* @param responseUrl 请求地址
*/
void printJsonResponse(long chainMs, boolean isSuccessful, int code, @NonNull String headers, @Nullable MediaType contentType,
@Nullable String bodyString, @NonNull List<String> segments, @NonNull String message, @NonNull String responseUrl);
/**
* 打印网络响应信息, 当网络响应时 {{@link okhttp3.ResponseBody}} 为 {@code null} 或不可解析的情况
*
* @param chainMs 服务器响应耗时(单位毫秒)
* @param isSuccessful 请求是否成功
* @param code 响应码
* @param headers 请求头
* @param segments 域名后面的资源地址
* @param message 响应信息
* @param responseUrl 请求地址
*/
void printFileResponse(long chainMs, boolean isSuccessful, int code, @NonNull String headers,
@NonNull List<String> segments, @NonNull String message, @NonNull String responseUrl);
}
| JessYanCoding/MVPArms | arms/src/main/java/com/jess/arms/http/log/FormatPrinter.java |
1,415 | M
1527833857
tags: Math
LeetCode: 判断数字是否是ugly number. (definition: factor only have 2, 3, 5)
#### Math
- 看是否可以整除.
- 看整除最终结果是否== 1
LintCode: 找kth ugly number, 应该与 Ugly Number II是一样的
- 方法1: PriorityQueue排序。用ArrayList check 新的ugly Number是否出现过。
- 方法1-1:(解释不通,不可取)用PriorityQueue排序。神奇的3,5,7走位:按照题目答案的出发,定了3,5,7以什么规律出现。但是题目并没有特殊表明。
- 方法2: DP . Not Done yet.
```
/*
LeetCode
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example 1:
Input: 6
Output: true
Explanation: 6 = 2 × 3
Example 2:
Input: 8
Output: true
Explanation: 8 = 2 × 2 × 2
Example 3:
Input: 14
Output: false
Explanation: 14 is not ugly since it includes another prime factor 7.
Note:
1 is typically treated as an ugly number.
Input is within the 32-bit signed integer range: [−2^31, 2^31 − 1].
*/
class Solution {
public boolean isUgly(int num) {
if (num == 0) {
return false;
}
while (num % 2 == 0) num /= 2;
while (num % 3 == 0) num /= 3;
while (num % 5 == 0) num /= 5;
return num == 1;
}
}
/*
LintCode
Ugly number is a number that only have factors 3, 5 and 7.
Design an algorithm to find the Kth ugly number. The first 5 ugly numbers are 3, 5, 7, 9, 15 ...
Example
If K=4, return 9.
Challenge
O(K log K) or O(K) time.
Tags Expand
LintCode Copyright Priority Queue
*/
/*
Thoughts:
Every level it's like:
3 5 7
3 3,5 3,5,7
Use a priority queue to keep track.
Use a for loop to keep calculating the target number, and return it at the end
Note:
Why not offer 3,5, 7 in first if statement? (Which is my original thought). Maybe, we want to limit the number of offers in 3's case, in case some 3's cases becomes bigger than 5's case. That, will accidentally prevent the program to check on 5's.
Therefore, leave 3,5,7 cases till 7's .
*/
class Solution {
/**
* @param k: The number k.
* @return: The kth prime number as description.
*/
public long kthPrimeNumber(int k) {
if (k == 0) {
return 0;
}
PriorityQueue<Long> queue = new PriorityQueue<Long>();
queue.offer((long)3);
queue.offer((long)5);
queue.offer((long)7);
long num = 0;
for (int i = 0; i < k; i++) {
num = queue.poll();
if (num % 3 == 0) {
queue.offer(num * 3);
} else if (num % 5 == 0) {
queue.offer(num * 3);
queue.offer(num * 5);
} else if (num % 7 == 0) {
queue.offer(num * 3);
queue.offer(num * 5);
queue.offer(num * 7);
}
}
return num;
}
};
//Ignore the sequence of 3, 5, 7. Use arraylist to check for duplicates
class Solution {
/**
* @param k: The number k.
* @return: The kth prime number as description.
*/
public long kthPrimeNumber(int k) {
if (k == 0) {
return 0;
}
ArrayList<Long> set = new ArrayList<Long>();
PriorityQueue<Long> queue = new PriorityQueue<Long>();
queue.offer((long)3);
queue.offer((long)5);
queue.offer((long)7);
set.add((long)3);
set.add((long)5);
set.add((long)7);
long num = 0;
for (int i = 0; i < k; i++) {
num = queue.poll();
if (!set.contains(num * 3)) {
queue.offer(num * 3);
set.add(num * 3);
}
if (!set.contains(num * 5)) {
queue.offer(num * 5);
set.add(num * 5);
}
if (!set.contains(num * 7)) {
queue.offer(num * 7);
set.add(num * 7);
}
}
return num;
}
};
/*
Can use DP as well:http://blog.welkinlan.com/2015/07/28/ugly-number-lintcode-java/
*/
``` | awangdev/leet-code | Java/Ugly Number.java |
1,416 | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.base;
import androidx.annotation.NonNull;
import com.jess.arms.di.component.AppComponent;
/**
* ================================================
* 框架要求框架中的每个 {@link android.app.Application} 都需要实现此类, 以满足规范
*
* @see BaseApplication
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki">请配合官方 Wiki 文档学习本框架</a>
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki/UpdateLog">更新日志, 升级必看!</a>
* @see <a href="https://github.com/JessYanCoding/MVPArms/wiki/Issues">常见 Issues, 踩坑必看!</a>
* @see <a href="https://github.com/JessYanCoding/ArmsComponent/wiki">MVPArms 官方组件化方案 ArmsComponent, 进阶指南!</a>
* Created by JessYan on 25/04/2017 14:54
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public interface App {
@NonNull
AppComponent getAppComponent();
}
| JessYanCoding/MVPArms | arms/src/main/java/com/jess/arms/base/App.java |
1,418 | package org.nlpcn.es4sql.domain;
public class KVValue implements Cloneable {
public String key;
public Object value;
//zhongshu-comment 看样子,应该存在只有value没有key的情况
public KVValue(Object value) {
this.value = value;
}
public KVValue(String key, Object value) {
if (key != null) {
this.key = key.replace("'", "");
}
this.value = value;
}
@Override
public String toString() {
//zhongshu-comment 看样子,应该存在只有value没有key的情况
if (key == null) {
return value.toString();
} else {
return key + "=" + value;
}
}
}
| NLPchina/elasticsearch-sql | src/main/java/org/nlpcn/es4sql/domain/KVValue.java |
1,419 | /*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
This source code is licensed under the Apache License Version 2.0.*/
package apijson;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.JSONReader;
import java.util.List;
/**阿里FastJSON封装类 防止解析时异常
* @author Lemon
*/
public class JSON {
private static final String TAG = "JSON";
/**判断json格式是否正确
* @param s
* @return
*/
public static boolean isJsonCorrect(String s) {
//太长 Log.i(TAG, "isJsonCorrect <<<< " + s + " >>>>>>>");
if (s == null
// || s.equals("[]")
// || s.equals("{}")
|| s.equals("")
|| s.equals("[null]")
|| s.equals("{null}")
|| s.equals("null")) {
return false;
}
return true;
}
/**获取有效的json
* @param s
* @return
*/
public static String getCorrectJson(String s) {
return getCorrectJson(s, false);
}
/**获取有效的json
* @param s
* @param isArray
* @return
*/
public static String getCorrectJson(String s, boolean isArray) {
s = StringUtil.getTrimedString(s);
// if (isArray) {
// while (s.startsWith("\"")) {
// s = s.substring(1);
// }
// while (s.endsWith("\"")) {
// s = s.substring(0, s.length() - 1);
// }
// }
return s;//isJsonCorrect(s) ? s : null;
}
/**
* @param json
* @return
*/
private static final Feature[] DEFAULT_FASTJSON_FEATURES = {Feature.OrderedField, Feature.UseBigDecimal};
public static Object parse(Object obj) {
try {
return com.alibaba.fastjson.JSON.parse(obj instanceof String ? (String) obj : toJSONString(obj), DEFAULT_FASTJSON_FEATURES);
} catch (Exception e) {
Log.i(TAG, "parse catch \n" + e.getMessage());
}
return null;
}
/**obj转JSONObject
* @param obj
* @return
*/
public static JSONObject parseObject(Object obj) {
if (obj instanceof JSONObject) {
return (JSONObject) obj;
}
return parseObject(toJSONString(obj));
}
/**json转JSONObject
* @param json
* @return
*/
public static JSONObject parseObject(String json) {
return parseObject(json, JSONObject.class);
}
/**json转实体类
* @param json
* @param clazz
* @return
*/
public static <T> T parseObject(String json, Class<T> clazz) {
if (clazz == null || StringUtil.isEmpty(json, true)) {
Log.e(TAG, "parseObject clazz == null || StringUtil.isEmpty(json, true) >> return null;");
} else {
try {
return com.alibaba.fastjson.JSON.parseObject(getCorrectJson(json), clazz, DEFAULT_FASTJSON_FEATURES);
} catch (Exception e) {
Log.i(TAG, "parseObject catch \n" + e.getMessage());
}
}
return null;
}
/**list转JSONArray
* @param list
* @return
*/
public static JSONArray parseArray(List<Object> list) {
return new JSONArray(list);
}
/**obj转JSONArray
* @param obj
* @return
*/
public static JSONArray parseArray(Object obj) {
if (obj instanceof JSONArray) {
return (JSONArray) obj;
}
return parseArray(toJSONString(obj));
}
/**json转JSONArray
* @param json
* @return
*/
public static JSONArray parseArray(String json) {
if (StringUtil.isEmpty(json, true)) {
Log.e(TAG, "parseArray StringUtil.isEmpty(json, true) >> return null;");
} else {
try {
return com.alibaba.fastjson.JSON.parseArray(getCorrectJson(json, true));
} catch (Exception e) {
Log.i(TAG, "parseArray catch \n" + e.getMessage());
}
}
return null;
}
/**JSONArray转实体类列表
* @param array
* @param clazz
* @return
*/
public static <T> List<T> parseArray(JSONArray array, Class<T> clazz) {
return parseArray(toJSONString(array), clazz);
}
/**json转实体类列表
* @param json
* @param clazz
* @return
*/
public static <T> List<T> parseArray(String json, Class<T> clazz) {
if (clazz == null || StringUtil.isEmpty(json, true)) {
Log.e(TAG, "parseArray clazz == null || StringUtil.isEmpty(json, true) >> return null;");
} else {
try {
return com.alibaba.fastjson.JSON.parseArray(getCorrectJson(json, true), clazz);
} catch (Exception e) {
Log.i(TAG, "parseArray catch \n" + e.getMessage());
}
}
return null;
}
/**实体类转json
* @param obj
* @return
*/
public static String toJSONString(Object obj) {
if (obj == null) {
return null;
}
if (obj instanceof String) {
return (String) obj;
}
try {
return com.alibaba.fastjson.JSON.toJSONString(obj);
} catch (Exception e) {
Log.e(TAG, "toJSONString catch \n" + e.getMessage());
}
return null;
}
/**实体类转json
* @param obj
* @param features
* @return
*/
public static String toJSONString(Object obj, SerializerFeature... features) {
if (obj == null) {
return null;
}
if (obj instanceof String) {
return (String) obj;
}
try {
return com.alibaba.fastjson.JSON.toJSONString(obj, features);
} catch (Exception e) {
Log.e(TAG, "parseArray catch \n" + e.getMessage());
}
return null;
}
/**格式化,显示更好看
* @param json
* @return
*/
public static String format(String json) {
return format(parse(json));
}
/**格式化,显示更好看
* @param object
* @return
*/
public static String format(Object object) {
return toJSONString(object, SerializerFeature.PrettyFormat);
}
/**判断是否为JSONObject
* @param obj instanceof String ? parseObject
* @return
*/
public static boolean isJSONObject(Object obj) {
if (obj instanceof JSONObject) {
return true;
}
if (obj instanceof String) {
try {
JSONObject json = parseObject((String) obj);
return json != null && json.isEmpty() == false;
} catch (Exception e) {
Log.e(TAG, "isJSONObject catch \n" + e.getMessage());
}
}
return false;
}
/**判断是否为JSONArray
* @param obj instanceof String ? parseArray
* @return
*/
public static boolean isJSONArray(Object obj) {
if (obj instanceof JSONArray) {
return true;
}
if (obj instanceof String) {
try {
JSONArray json = parseArray((String) obj);
return json != null && json.isEmpty() == false;
} catch (Exception e) {
Log.e(TAG, "isJSONArray catch \n" + e.getMessage());
}
}
return false;
}
/**判断是否为 Boolean,Number,String 中的一种
* @param obj
* @return
*/
public static boolean isBooleanOrNumberOrString(Object obj) {
return obj instanceof Boolean || obj instanceof Number || obj instanceof String;
}
}
| Tencent/APIJSON | APIJSONORM/src/main/java/apijson/JSON.java |
1,420 | package me.zhyd.oauth.enums.scope;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Gitee 平台 OAuth 授权范围
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0.0
* @since 1.0.0
*/
@Getter
@AllArgsConstructor
public enum AuthGiteeScope implements AuthScope {
/**
* {@code scope} 含义,以{@code description} 为准
*/
USER_INFO("user_info", "访问用户的个人信息、最新动态等", true),
PROJECTS("projects", "查看、创建、更新用户的项目", false),
PULL_REQUESTS("pull_requests", "查看、发布、更新用户的 Pull Request", false),
ISSUES("issues", "查看、发布、更新用户的 Issue", false),
NOTES("notes", "查看、发布、管理用户在项目、代码片段中的评论", false),
KEYS("keys", "查看、部署、删除用户的公钥", false),
HOOK("hook", "查看、部署、更新用户的 Webhook", false),
GROUPS("groups", "查看、管理用户的组织以及成员", false),
GISTS("gists", "查看、删除、更新用户的代码片段", false),
ENTERPRISES("enterprises", "查看、管理用户的企业以及成员", false),
EMAILS("emails", "查看用户的个人邮箱信息", false);
private final String scope;
private final String description;
private final boolean isDefault;
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/enums/scope/AuthGiteeScope.java |
1,422 | package cn.hutool.core.util;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.PatternPool;
import cn.hutool.core.lang.Validator;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* 身份证相关工具类<br>
* see <a href="https://www.oschina.net/code/snippet_1611_2881">https://www.oschina.net/code/snippet_1611_2881</a>
*
* <p>
* 本工具并没有对行政区划代码做校验,如有需求,请参阅(2018年10月):
* <a href="http://www.mca.gov.cn/article/sj/xzqh/2018/201804-12/20181011221630.html">http://www.mca.gov.cn/article/sj/xzqh/2018/201804-12/20181011221630.html</a>
* </p>
*
* @author Looly
* @since 3.0.4
*/
public class IdcardUtil {
/**
* 中国公民身份证号码最小长度。
*/
private static final int CHINA_ID_MIN_LENGTH = 15;
/**
* 中国公民身份证号码最大长度。
*/
private static final int CHINA_ID_MAX_LENGTH = 18;
/**
* 每位加权因子
*/
private static final int[] POWER = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
/**
* 省市代码表
*/
private static final Map<String, String> CITY_CODES = new HashMap<>();
/**
* 台湾身份首字母对应数字
*/
private static final Map<Character, Integer> TW_FIRST_CODE = new HashMap<>();
static {
CITY_CODES.put("11", "北京");
CITY_CODES.put("12", "天津");
CITY_CODES.put("13", "河北");
CITY_CODES.put("14", "山西");
CITY_CODES.put("15", "内蒙古");
CITY_CODES.put("21", "辽宁");
CITY_CODES.put("22", "吉林");
CITY_CODES.put("23", "黑龙江");
CITY_CODES.put("31", "上海");
CITY_CODES.put("32", "江苏");
CITY_CODES.put("33", "浙江");
CITY_CODES.put("34", "安徽");
CITY_CODES.put("35", "福建");
CITY_CODES.put("36", "江西");
CITY_CODES.put("37", "山东");
CITY_CODES.put("41", "河南");
CITY_CODES.put("42", "湖北");
CITY_CODES.put("43", "湖南");
CITY_CODES.put("44", "广东");
CITY_CODES.put("45", "广西");
CITY_CODES.put("46", "海南");
CITY_CODES.put("50", "重庆");
CITY_CODES.put("51", "四川");
CITY_CODES.put("52", "贵州");
CITY_CODES.put("53", "云南");
CITY_CODES.put("54", "西藏");
CITY_CODES.put("61", "陕西");
CITY_CODES.put("62", "甘肃");
CITY_CODES.put("63", "青海");
CITY_CODES.put("64", "宁夏");
CITY_CODES.put("65", "新疆");
CITY_CODES.put("71", "台湾");
CITY_CODES.put("81", "香港");
CITY_CODES.put("82", "澳门");
//issue#1277,台湾身份证号码以83开头,但是行政区划为71
CITY_CODES.put("83", "台湾");
CITY_CODES.put("91", "国外");
TW_FIRST_CODE.put('A', 10);
TW_FIRST_CODE.put('B', 11);
TW_FIRST_CODE.put('C', 12);
TW_FIRST_CODE.put('D', 13);
TW_FIRST_CODE.put('E', 14);
TW_FIRST_CODE.put('F', 15);
TW_FIRST_CODE.put('G', 16);
TW_FIRST_CODE.put('H', 17);
TW_FIRST_CODE.put('J', 18);
TW_FIRST_CODE.put('K', 19);
TW_FIRST_CODE.put('L', 20);
TW_FIRST_CODE.put('M', 21);
TW_FIRST_CODE.put('N', 22);
TW_FIRST_CODE.put('P', 23);
TW_FIRST_CODE.put('Q', 24);
TW_FIRST_CODE.put('R', 25);
TW_FIRST_CODE.put('S', 26);
TW_FIRST_CODE.put('T', 27);
TW_FIRST_CODE.put('U', 28);
TW_FIRST_CODE.put('V', 29);
TW_FIRST_CODE.put('X', 30);
TW_FIRST_CODE.put('Y', 31);
TW_FIRST_CODE.put('W', 32);
TW_FIRST_CODE.put('Z', 33);
TW_FIRST_CODE.put('I', 34);
TW_FIRST_CODE.put('O', 35);
}
/**
* 将15位身份证号码转换为18位
*
* @param idCard 15位身份编码
* @return 18位身份编码
*/
public static String convert15To18(String idCard) {
StringBuilder idCard18;
if (idCard.length() != CHINA_ID_MIN_LENGTH) {
return null;
}
if (ReUtil.isMatch(PatternPool.NUMBERS, idCard)) {
// 获取出生年月日
String birthday = idCard.substring(6, 12);
Date birthDate = DateUtil.parse(birthday, "yyMMdd");
// 获取出生年(完全表现形式,如:2010)
int sYear = DateUtil.year(birthDate);
if (sYear > 2000) {
// 2000年之后不存在15位身份证号,此处用于修复此问题的判断
sYear -= 100;
}
idCard18 = StrUtil.builder().append(idCard, 0, 6).append(sYear).append(idCard.substring(8));
// 获取校验位
char sVal = getCheckCode18(idCard18.toString());
idCard18.append(sVal);
} else {
return null;
}
return idCard18.toString();
}
/**
* 将18位身份证号码转换为15位
*
* @param idCard 18位身份编码
* @return 15位身份编码
*/
public static String convert18To15(String idCard) {
if (StrUtil.isNotBlank(idCard) && IdcardUtil.isValidCard18(idCard)) {
return idCard.substring(0, 6) + idCard.substring(8, idCard.length() - 1);
}
return idCard;
}
/**
* 是否有效身份证号,忽略X的大小写<br>
* 如果身份证号码中含有空格始终返回{@code false}
*
* @param idCard 身份证号,支持18位、15位和港澳台的10位
* @return 是否有效
*/
public static boolean isValidCard(String idCard) {
if (StrUtil.isBlank(idCard)) {
return false;
}
//idCard = idCard.trim();
int length = idCard.length();
switch (length) {
case 18:// 18位身份证
return isValidCard18(idCard);
case 15:// 15位身份证
return isValidCard15(idCard);
case 10: {// 10位身份证,港澳台地区
String[] cardVal = isValidCard10(idCard);
return null != cardVal && "true".equals(cardVal[2]);
}
default:
return false;
}
}
/**
* <p>
* 判断18位身份证的合法性
* </p>
* 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。<br>
* 排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。
* <p>
* 顺序码: 表示在同一地址码所标识的区域范围内,对同年、同月、同 日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配 给女性。
* </p>
* <ol>
* <li>第1、2位数字表示:所在省份的代码</li>
* <li>第3、4位数字表示:所在城市的代码</li>
* <li>第5、6位数字表示:所在区县的代码</li>
* <li>第7~14位数字表示:出生年、月、日</li>
* <li>第15、16位数字表示:所在地的派出所的代码</li>
* <li>第17位数字表示性别:奇数表示男性,偶数表示女性</li>
* <li>第18位数字是校检码,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示</li>
* </ol>
* <p>
* 第十八位数字(校验码)的计算方法为:
* <ol>
* <li>将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2</li>
* <li>将这17位数字和系数相乘的结果相加</li>
* <li>用加出来和除以11,看余数是多少</li>
* <li>余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3 2</li>
* <li>通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2</li>
* </ol>
* <ol>
* <li>香港人在大陆的身份证,【810000】开头;同样可以直接获取到 性别、出生日期</li>
* <li>81000019980902013X: 文绎循 男 1998-09-02</li>
* <li>810000201011210153: 辛烨 男 2010-11-21</li>
* </ol>
* <ol>
* <li>澳门人在大陆的身份证,【820000】开头;同样可以直接获取到 性别、出生日期</li>
* <li>820000200009100032: 黄敬杰 男 2000-09-10</li>
* </ol>
* <ol>
* <li>台湾人在大陆的身份证,【830000】开头;同样可以直接获取到 性别、出生日期</li>
* <li>830000200209060065: 王宜妃 女 2002-09-06</li>
* <li>830000194609150010: 苏建文 男 1946-09-14</li>
* <li>83000019810715006X: 刁婉琇 女 1981-07-15</li>
* </ol>
*
* @param idcard 待验证的身份证
* @return 是否有效的18位身份证,忽略x的大小写
*/
public static boolean isValidCard18(String idcard) {
return isValidCard18(idcard, true);
}
/**
* <p>
* 判断18位身份证的合法性
* </p>
* 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。<br>
* 排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。
* <p>
* 顺序码: 表示在同一地址码所标识的区域范围内,对同年、同月、同 日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配 给女性。
* </p>
* <ol>
* <li>第1、2位数字表示:所在省份的代码</li>
* <li>第3、4位数字表示:所在城市的代码</li>
* <li>第5、6位数字表示:所在区县的代码</li>
* <li>第7~14位数字表示:出生年、月、日</li>
* <li>第15、16位数字表示:所在地的派出所的代码</li>
* <li>第17位数字表示性别:奇数表示男性,偶数表示女性</li>
* <li>第18位数字是校检码,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示</li>
* </ol>
* <p>
* 第十八位数字(校验码)的计算方法为:
* <ol>
* <li>将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2</li>
* <li>将这17位数字和系数相乘的结果相加</li>
* <li>用加出来和除以11,看余数是多少</li>
* <li>余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3 2</li>
* <li>通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2</li>
* </ol>
*
* @param idcard 待验证的身份证
* @param ignoreCase 是否忽略大小写。{@code true}则忽略X大小写,否则严格匹配大写。
* @return 是否有效的18位身份证
* @since 5.5.7
*/
public static boolean isValidCard18(String idcard, boolean ignoreCase) {
if (idcard == null) {
return false;
}
if (CHINA_ID_MAX_LENGTH != idcard.length()) {
return false;
}
// 截取省份代码。新版外国人永久居留身份证以9开头,第二三位是受理地代码
final String proCode = idcard.startsWith("9") ? idcard.substring(1, 3): idcard.substring(0, 2);
if (null == CITY_CODES.get(proCode)) {
return false;
}
//校验生日
if (false == Validator.isBirthday(idcard.substring(6, 14))) {
return false;
}
// 前17位
final String code17 = idcard.substring(0, 17);
if (ReUtil.isMatch(PatternPool.NUMBERS, code17)) {
// 获取校验位
char val = getCheckCode18(code17);
// 第18位
return CharUtil.equals(val, idcard.charAt(17), ignoreCase);
}
return false;
}
/**
* 验证15位身份编码是否合法
*
* @param idcard 身份编码
* @return 是否合法
*/
public static boolean isValidCard15(String idcard) {
if (idcard == null) {
return false;
}
if (CHINA_ID_MIN_LENGTH != idcard.length()) {
return false;
}
if (ReUtil.isMatch(PatternPool.NUMBERS, idcard)) {
// 省份
String proCode = idcard.substring(0, 2);
if (null == CITY_CODES.get(proCode)) {
return false;
}
//校验生日(两位年份,补充为19XX)
return false != Validator.isBirthday("19" + idcard.substring(6, 12));
} else {
return false;
}
}
/**
* 验证10位身份编码是否合法
*
* @param idcard 身份编码
* @return 身份证信息数组
* <p>
* [0] - 台湾、澳门、香港 [1] - 性别(男M,女F,未知N) [2] - 是否合法(合法true,不合法false) 若不是身份证件号码则返回null
* </p>
*/
public static String[] isValidCard10(String idcard) {
if (StrUtil.isBlank(idcard)) {
return null;
}
String[] info = new String[3];
String card = idcard.replaceAll("[()]", "");
if (card.length() != 8 && card.length() != 9 && idcard.length() != 10) {
return null;
}
if (idcard.matches("^[a-zA-Z][0-9]{9}$")) { // 台湾
info[0] = "台湾";
char char2 = idcard.charAt(1);
if ('1' == char2) {
info[1] = "M";
} else if ('2' == char2) {
info[1] = "F";
} else {
info[1] = "N";
info[2] = "false";
return info;
}
info[2] = isValidTWCard(idcard) ? "true" : "false";
} else if (idcard.matches("^[157][0-9]{6}\\(?[0-9A-Z]\\)?$")) { // 澳门
info[0] = "澳门";
info[1] = "N";
info[2] = "true";
} else if (idcard.matches("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")) { // 香港
info[0] = "香港";
info[1] = "N";
info[2] = isValidHKCard(idcard) ? "true" : "false";
} else {
return null;
}
return info;
}
/**
* 验证台湾身份证号码
*
* @param idcard 身份证号码
* @return 验证码是否符合
*/
public static boolean isValidTWCard(String idcard) {
if (null == idcard || idcard.length() != 10) {
return false;
}
final Integer iStart = TW_FIRST_CODE.get(idcard.charAt(0));
if (null == iStart) {
return false;
}
int sum = iStart / 10 + (iStart % 10) * 9;
final String mid = idcard.substring(1, 9);
final char[] chars = mid.toCharArray();
int iflag = 8;
for (char c : chars) {
sum += Integer.parseInt(String.valueOf(c)) * iflag;
iflag--;
}
final String end = idcard.substring(9, 10);
return (sum % 10 == 0 ? 0 : (10 - sum % 10)) == Integer.parseInt(end);
}
/**
* 验证香港身份证号码(存在Bug,部份特殊身份证无法检查)
* <p>
* 身份证前2位为英文字符,如果只出现一个英文字符则表示第一位是空格,对应数字58 前2位英文字符A-Z分别对应数字10-35 最后一位校验码为0-9的数字加上字符"A","A"代表10
* </p>
* <p>
* 将身份证号码全部转换为数字,分别对应乘9-1相加的总和,整除11则证件号码有效
* </p>
*
* @param idcard 身份证号码
* @return 验证码是否符合
*/
public static boolean isValidHKCard(String idcard) {
String card = idcard.replaceAll("[()]", "");
int sum;
if (card.length() == 9) {
sum = (Character.toUpperCase(card.charAt(0)) - 55) * 9 + (Character.toUpperCase(card.charAt(1)) - 55) * 8;
card = card.substring(1, 9);
} else {
sum = 522 + (Character.toUpperCase(card.charAt(0)) - 55) * 8;
}
// 首字母A-Z,A表示1,以此类推
String mid = card.substring(1, 7);
String end = card.substring(7, 8);
char[] chars = mid.toCharArray();
int iflag = 7;
for (char c : chars) {
sum = sum + Integer.parseInt(String.valueOf(c)) * iflag;
iflag--;
}
if ("A".equalsIgnoreCase(end)) {
sum += 10;
} else {
sum += Integer.parseInt(end);
}
return sum % 11 == 0;
}
/**
* 根据身份编号获取生日,只支持15或18位身份证号码
*
* @param idcard 身份编号
* @return 生日(yyyyMMdd)
* @see #getBirth(String)
*/
public static String getBirthByIdCard(String idcard) {
return getBirth(idcard);
}
/**
* 根据身份编号获取生日,只支持15或18位身份证号码
*
* @param idCard 身份编号
* @return 生日(yyyyMMdd)
*/
public static String getBirth(String idCard) {
Assert.notBlank(idCard, "id card must be not blank!");
final int len = idCard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idCard = convert15To18(idCard);
}
return Objects.requireNonNull(idCard).substring(6, 14);
}
/**
* 从身份证号码中获取生日日期,只支持15或18位身份证号码
*
* @param idCard 身份证号码
* @return 日期
*/
public static DateTime getBirthDate(String idCard) {
final String birthByIdCard = getBirthByIdCard(idCard);
return null == birthByIdCard ? null : DateUtil.parse(birthByIdCard, DatePattern.PURE_DATE_FORMAT);
}
/**
* 根据身份编号获取年龄,只支持15或18位身份证号码
*
* @param idcard 身份编号
* @return 年龄
*/
public static int getAgeByIdCard(String idcard) {
return getAgeByIdCard(idcard, DateUtil.date());
}
/**
* 根据身份编号获取指定日期当时的年龄年龄,只支持15或18位身份证号码
*
* @param idcard 身份编号
* @param dateToCompare 以此日期为界,计算年龄。
* @return 年龄
*/
public static int getAgeByIdCard(String idcard, Date dateToCompare) {
String birth = getBirthByIdCard(idcard);
return DateUtil.age(DateUtil.parse(birth, "yyyyMMdd"), dateToCompare);
}
/**
* 根据身份编号获取生日年,只支持15或18位身份证号码
*
* @param idcard 身份编号
* @return 生日(yyyy)
*/
public static Short getYearByIdCard(String idcard) {
final int len = idcard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idcard = convert15To18(idcard);
}
return Short.valueOf(Objects.requireNonNull(idcard).substring(6, 10));
}
/**
* 根据身份编号获取生日月,只支持15或18位身份证号码
*
* @param idcard 身份编号
* @return 生日(MM)
*/
public static Short getMonthByIdCard(String idcard) {
final int len = idcard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idcard = convert15To18(idcard);
}
return Short.valueOf(Objects.requireNonNull(idcard).substring(10, 12));
}
/**
* 根据身份编号获取生日天,只支持15或18位身份证号码
*
* @param idcard 身份编号
* @return 生日(dd)
*/
public static Short getDayByIdCard(String idcard) {
final int len = idcard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idcard = convert15To18(idcard);
}
return Short.valueOf(Objects.requireNonNull(idcard).substring(12, 14));
}
/**
* 根据身份编号获取性别,只支持15或18位身份证号码
*
* @param idcard 身份编号
* @return 性别(1 : 男 , 0 : 女)
*/
public static int getGenderByIdCard(String idcard) {
Assert.notBlank(idcard);
final int len = idcard.length();
if (!(len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH)) {
throw new IllegalArgumentException("ID Card length must be 15 or 18");
}
if (len == CHINA_ID_MIN_LENGTH) {
idcard = convert15To18(idcard);
}
char sCardChar = Objects.requireNonNull(idcard).charAt(16);
return (sCardChar % 2 != 0) ? 1 : 0;
}
/**
* 根据身份编号获取户籍省份编码,只支持15或18位身份证号码
*
* @param idcard 身份编码
* @return 省份编码
* @since 5.7.2
*/
public static String getProvinceCodeByIdCard(String idcard) {
int len = idcard.length();
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
return idcard.substring(0, 2);
}
return null;
}
/**
* 根据身份编号获取户籍省份,只支持15或18位身份证号码
*
* @param idcard 身份编码
* @return 省份名称。
*/
public static String getProvinceByIdCard(String idcard) {
final String code = getProvinceCodeByIdCard(idcard);
if (StrUtil.isNotBlank(code)) {
return CITY_CODES.get(code);
}
return null;
}
/**
* 根据身份编号获取地市级编码,只支持15或18位身份证号码<br>
* 获取编码为4位
*
* @param idcard 身份编码
* @return 地市级编码
*/
public static String getCityCodeByIdCard(String idcard) {
int len = idcard.length();
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
return idcard.substring(0, 4);
}
return null;
}
/**
* 根据身份编号获取区县级编码,只支持15或18位身份证号码<br>
* 获取编码为6位
*
* @param idcard 身份编码
* @return 地市级编码
* @since 5.8.0
*/
public static String getDistrictCodeByIdCard(String idcard) {
int len = idcard.length();
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
return idcard.substring(0, 6);
}
return null;
}
/**
* 隐藏指定位置的几个身份证号数字为“*”
*
* @param idcard 身份证号
* @param startInclude 开始位置(包含)
* @param endExclude 结束位置(不包含)
* @return 隐藏后的身份证号码
* @see StrUtil#hide(CharSequence, int, int)
* @since 3.2.2
*/
public static String hide(String idcard, int startInclude, int endExclude) {
return StrUtil.hide(idcard, startInclude, endExclude);
}
/**
* 获取身份证信息,包括身份、城市代码、生日、性别等
*
* @param idcard 15或18位身份证
* @return {@link Idcard}
* @since 5.4.3
*/
public static Idcard getIdcardInfo(String idcard) {
return new Idcard(idcard);
}
// ----------------------------------------------------------------------------------- Private method start
/**
* 获得18位身份证校验码
*
* @param code17 18位身份证号中的前17位
* @return 第18位
*/
private static char getCheckCode18(String code17) {
int sum = getPowerSum(code17.toCharArray());
return getCheckCode18(sum);
}
/**
* 将power和值与11取模获得余数进行校验码判断
*
* @param iSum 加权和
* @return 校验位
*/
private static char getCheckCode18(int iSum) {
switch (iSum % 11) {
case 10:
return '2';
case 9:
return '3';
case 8:
return '4';
case 7:
return '5';
case 6:
return '6';
case 5:
return '7';
case 4:
return '8';
case 3:
return '9';
case 2:
return 'X';
case 1:
return '0';
case 0:
return '1';
default:
return StrUtil.C_SPACE;
}
}
/**
* 将身份证的每位和对应位的加权因子相乘之后,再得到和值
*
* @param iArr 身份证号码的数组
* @return 身份证编码
*/
private static int getPowerSum(char[] iArr) {
int iSum = 0;
if (POWER.length == iArr.length) {
for (int i = 0; i < iArr.length; i++) {
iSum += Integer.parseInt(String.valueOf(iArr[i])) * POWER[i];
}
}
return iSum;
}
// ----------------------------------------------------------------------------------- Private method end
/**
* 身份证信息,包括身份、城市代码、生日、性别等
*
* @author looly
* @since 5.4.3
*/
public static class Idcard implements Serializable {
private static final long serialVersionUID = 1L;
private final String provinceCode;
private final String cityCode;
private final DateTime birthDate;
private final Integer gender;
private final int age;
/**
* 构造
*
* @param idcard 身份证号码
*/
public Idcard(String idcard) {
this.provinceCode = IdcardUtil.getProvinceCodeByIdCard(idcard);
this.cityCode = IdcardUtil.getCityCodeByIdCard(idcard);
this.birthDate = IdcardUtil.getBirthDate(idcard);
this.gender = IdcardUtil.getGenderByIdCard(idcard);
this.age = IdcardUtil.getAgeByIdCard(idcard);
}
/**
* 获取省份代码
*
* @return 省份代码
*/
public String getProvinceCode() {
return this.provinceCode;
}
/**
* 获取省份名称
*
* @return 省份代码
*/
public String getProvince() {
return CITY_CODES.get(this.provinceCode);
}
/**
* 获取市级编码
*
* @return 市级编码
*/
public String getCityCode() {
return this.cityCode;
}
/**
* 获得生日日期
*
* @return 生日日期
*/
public DateTime getBirthDate() {
return this.birthDate;
}
/**
* 获取性别代号,性别(1 : 男 , 0 : 女)
*
* @return 性别(1 : 男 , 0 : 女)
*/
public Integer getGender() {
return this.gender;
}
/**
* 获取年龄
*
* @return 年龄
*/
public int getAge() {
return age;
}
@Override
public String toString() {
return "Idcard{" +
"provinceCode='" + provinceCode + '\'' +
", cityCode='" + cityCode + '\'' +
", birthDate=" + birthDate +
", gender=" + gender +
", age=" + age +
'}';
}
}
}
| dromara/hutool | hutool-core/src/main/java/cn/hutool/core/util/IdcardUtil.java |
1,423 | package org.nutz.trans;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.log.Log;
import org.nutz.log.Logs;
/**
* 用模板的方式操作事务
*
* @author zozoh([email protected])
* @author wendal([email protected])
*/
public abstract class Trans {
private static final Log log = Logs.get();
private static Class<? extends Transaction> implClass;
/**
* 这个类提供的均为静态方法.
*/
Trans() {}
static ThreadLocal<Transaction> trans = new ThreadLocal<Transaction>();
static ThreadLocal<Integer> count = new ThreadLocal<Integer>();
/**
* 事务debug开关
*/
public static boolean DEBUG = false;
/**
* @return 当前线程的事务,如果没有事务,返回 null
*/
public static Transaction get() {
return trans.get();
}
/**
* 这个函数允许你扩展默认的 Nutz 事务实现方式
*
* @param classOfTransaction
* 你的事务实现
*/
public static void setup(Class<? extends Transaction> classOfTransaction) {
implClass = classOfTransaction;
}
static void _begain(int level) throws Exception {
Transaction tn = trans.get();
if (null == tn) {
tn = New();
tn.setLevel(level);
trans.set(tn);
count.set(0);
if (DEBUG)
log.debugf("Start New Transaction id=%d, level=%d", tn.getId(), level);
} else {
if (DEBUG)
log.debugf("Attach Transaction id=%d, level=%d", tn.getId(), level);
}
int tCount = count.get() + 1;
count.set(tCount);
//if (DEBUG)
// log.debugf("trans_begain: %d", tCount);
}
static void _commit() throws Exception {
count.set(count.get() - 1);
Transaction tn = trans.get();
if (count.get() == 0) {
if (DEBUG)
log.debug("Transaction Commit id="+tn.getId());
tn.commit();
} else {
if (DEBUG)
log.debugf("Transaction delay Commit id=%d, count=%d", tn.getId(), count.get());
}
}
static void _depose() {
if (count.get() == 0)
try {
if (DEBUG)
log.debugf("Transaction depose id=%d, count=%s", trans.get().getId(), count.get());
trans.get().close();
}
catch (Throwable e) {
throw Lang.wrapThrow(e);
}
finally {
trans.set(null);
}
}
static void _rollback(Integer num) {
count.set(num);
if (count.get() == 0) {
if (DEBUG)
log.debugf("Transaction rollback id=%s, count=%s", trans.get().getId(), num);
trans.get().rollback();
} else {
if (DEBUG)
log.debugf("Transaction delay rollback id=%s, count=%s", trans.get().getId(), num);
}
}
/**
* 是否在事务中
* @return 真,如果在不事务中
*/
public static boolean isTransactionNone() {
Transaction t = trans.get();
return null == t || t.getLevel() == Connection.TRANSACTION_NONE;
}
/**
* 执行一组原子操作,默认的事务级别为: TRANSACTION_READ_COMMITTED。详细请看 exec(int level,
* Atom... atoms) 函数的说明
*
* @param atoms
* 原子操作对象
*/
public static void exec(Atom... atoms) {
exec(Connection.TRANSACTION_READ_COMMITTED, atoms);
}
/**
* 执行一组原子操作,并指定事务级别。
* <p>
* 这里需要注意的是,Nutz 支持事务模板的无限层级嵌套。 这里,如果每一层嵌套,指定的事务级别有所不同,不同的数据库,可能引发不可预知的错误。
* <p>
* 所以,嵌套的事务模板的事务,将以最顶层的事务为级别为标准。就是说,如果最顶层的事务级别为
* 'TRANSACTION_READ_COMMITTED',那么下面所包含的所有事务,无论你指定什么样的事务级别,都是
* 'TRANSACTION_READ_COMMITTED', 这一点,由抽象类 Transaction 来保证。其 setLevel
* 当被设置了一个大于 0 的整数以后,将不再 接受任何其他的值。
* <p>
* 你可以通过继承 Transaction 来修改这个默认的行为,当然,这个行为修改一般是没有必要的。
* <p>
* 另外,你还可能需要知道,通过 Trans.setup 方法,能让整个虚拟机的 Nutz 事务操作都使用你的 Transaction 实现
*
* @param level
* 事务的级别。
* <p>
* 你可以设置的事务级别是:
* <ul>
* <li>java.sql.Connection.TRANSACTION_NONE
* <li>java.sql.Connection.TRANSACTION_READ_UNCOMMITTED
* <li>java.sql.Connection.TRANSACTION_READ_COMMITTED
* <li>java.sql.Connection.TRANSACTION_REPEATABLE_READ
* <li>java.sql.Connection.TRANSACTION_SERIALIZABLE
* </ul>
* 不同的数据库,对于 JDBC 事务级别的规范,支持的力度不同。请参看相应数据库的文档,已
* 确定你设置的数据库事务级别是否被支持。
* @param atoms
* 原子操作对象
* @see org.nutz.trans.Transaction
* @see java.sql.Connection
*/
public static void exec(int level, Atom... atoms) {
if (null == atoms)
return;
int num = count.get() == null ? 0 : count.get();
try {
_begain(level);
for (Atom atom : atoms)
atom.run();
_commit();
}
catch (Throwable e) {
_rollback(num);
throw Lang.wrapThrow(e);
}
finally {
_depose();
}
}
/**
* 执行一个分子,并给出返回值
*
* @param <T>
* @param molecule
* 分子
* @return 分子返回值
*/
public static <T> T exec(Molecule<T> molecule) {
Trans.exec((Atom) molecule);
return molecule.getObj();
}
/* ===========================下面暴露几个方法给喜欢 try...catch...finally 的人 ===== */
/**
* 开始一个事务,级别为 TRANSACTION_READ_COMMITTED
* <p>
* 你需要手工用 try...catch...finally 来保证你提交和关闭这个事务
*
* @throws Exception
*/
public static void begin() throws Exception {
Trans._begain(Connection.TRANSACTION_READ_COMMITTED);
}
/**
* 开始一个指定事务
* <p>
* 你需要手工用 try...catch...finally 来保证你提交和关闭这个事务
*
* @param level
* 指定级别
*
* @throws Exception
*/
public static void begin(int level) throws Exception {
Trans._begain(level);
}
/**
* 提交事务,执行它前,你必需保证你已经手工开始了一个事务
*
* @throws Exception
*/
public static void commit() throws Exception {
Trans._commit();
}
/**
* 回滚事务,执行它前,你必需保证你已经手工开始了一个事务
*
* @throws Exception
*/
public static void rollback() throws Exception {
Integer c = Trans.count.get();
if (c == null)
c = Integer.valueOf(0);
else if (c > 0)
c--;
Trans._rollback(c);
}
/**
* 关闭事务,执行它前,你必需保证你已经手工开始了一个事务
*
* @throws Exception
*/
public static void close() throws Exception {
Trans._depose();
}
/**
* 如果在事务中,则返回事务的连接,否则直接从数据源取一个新的连接
*/
public static Connection getConnectionAuto(DataSource ds) throws SQLException {
if (get() == null)
return ds.getConnection();
else
return get().getConnection(ds);
}
/**
* 自动判断是否关闭当前连接
* @param conn 数据库连接
*/
public static void closeConnectionAuto(Connection conn) {
if (get() == null && null != conn) {
try {
conn.close();
}
catch (SQLException e) {
throw Lang.wrapThrow(e);
}
}
}
/**
* 强制清理事务上下文
* @param rollbackOrCommit 检测到未闭合的事务时回滚还是提交,true为回滚,false为提交。
*/
public static void clear(boolean rollbackOrCommit) {
Integer c = Trans.count.get();
if (c == null)
return;
if (c > 0) {
for (int i = 0; i < c; i++) {
try {
if (rollbackOrCommit)
Trans.rollback();
else
Trans.commit();
Trans.close();
}
catch (Exception e) {
}
}
}
Trans.count.set(null);
Transaction t = get();
if (t != null)
t.close();
Trans.trans.set(null);
}
public static void set(Transaction t) {
Trans.trans.set(t);
}
public static Transaction New() {
return null == implClass ? new NutTransaction() : Mirror.me(implClass).born();
}
}
| nutzam/nutz | src/org/nutz/trans/Trans.java |
1,427 | package com.macro.mall.portal.service;
import com.macro.mall.portal.domain.MemberProductCollection;
import org.springframework.data.domain.Page;
/**
* 会员商品收藏管理Service
* Created by macro on 2018/8/2.
*/
public interface MemberCollectionService {
/**
* 添加收藏
*/
int add(MemberProductCollection productCollection);
/**
* 删除收藏
*/
int delete(Long productId);
/**
* 分页查询收藏
*/
Page<MemberProductCollection> list(Integer pageNum, Integer pageSize);
/**
* 查看收藏详情
*/
MemberProductCollection detail(Long productId);
/**
* 清空收藏
*/
void clear();
}
| macrozheng/mall | mall-portal/src/main/java/com/macro/mall/portal/service/MemberCollectionService.java |
1,429 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.weex;
import android.content.res.AssetFileDescriptor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.taobao.weex.IWXRenderListener;
import com.taobao.weex.WXSDKEngine;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.common.WXException;
import com.taobao.weex.common.WXModule;
import com.taobao.weex.common.WXRenderStrategy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SliceTestActivity extends AppCompatActivity {
private static final String LOG_TAG = "SliceTestActivity";
private RecyclerView mRecyclerView;
private TextView mReportTextView;
private final List<String> mData = new ArrayList<>();
private WXInstanceAdapter mAdapter;
private final Set<WXSDKInstance> mInstances = new HashSet<>();
public static class SearchModule extends WXModule {
@JSMethod(uiThread = true)
public void search(JSONObject options) {
Log.e("TestModuel", options.toJSONString());
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
WXSDKEngine.registerModule("searchEvent", SearchModule.class);
} catch (WXException e) {
e.printStackTrace();
}
setContentView(R.layout.activity_slice_test);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mReportTextView = (TextView) findViewById(R.id.report_text);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
mAdapter = new WXInstanceAdapter();
mRecyclerView.setAdapter(mAdapter);
}
static int i = 0;
public void addCellClick(View view) {
//rax case.js
if (i++ % 2 == 0) {
mData.add("{\"model\":{\"tips\":[{\"show\":\"雪纺\",\"q\":\"连衣裙 雪纺\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%221%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]},{\"show\":\"中长款\",\"q\":\"连衣裙 中长款\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%222%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]},{\"show\":\"假两件\",\"q\":\"连衣裙 假两件\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%223%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]},{\"show\":\"A字款\",\"q\":\"连衣裙 A字款\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%224%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]},{\"show\":\"气质淑女\",\"q\":\"连衣裙 气质淑女\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%225%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]}],\"pos\":\"3\",\"src\":\"graph\",\"topic\":\"细选"+i+"\",\"type\":\"1\",\"tItemType\":\"wx_text\",\"tShowTmpl\":\"wx_text\",\"rl\":\"query_type-1|tip_show_type-1|tip_show_page-2\"},\"status\":{\"layoutStyle\":0}}");
} else {
mData.add("{\"model\":{\"tips\":[{\"show\":\"雪纺\",\"q\":\"连衣裙 雪纺\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%221%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]},{\"show\":\"中长款\",\"q\":\"连衣裙 中长款\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%222%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]},{\"show\":\"假两件\",\"q\":\"连衣裙 假两件\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%223%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]},{\"show\":\"A字款\",\"q\":\"连衣裙 A字款\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%224%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]},{\"show\":\"气质淑女\",\"q\":\"连衣裙 气质淑女\",\"params\":[{\"key\":\"from\",\"value\":\"tips_1\"},{\"key\":\"vClickTrace\",\"value\":\"%7B%22tips_oriq%22%3A%22%E8%BF%9E%E8%A1%A3%E8%A3%99%22%2C%22tips_srppage%22%3A%222%22%2C%22tips_type%22%3A%221%22%2C%22tips_pos%22%3A%225%22%2C%22pre_rn%22%3A%220189c4d06e11f32262fa896f5f364f76%22%7D\"}]}],\"pos\":\"3\",\"src\":\"graph\",\"topic\":\"细选"+i+"\",\"type\":\"1\",\"tItemType\":\"wx_text\",\"tShowTmpl\":\"wx_text\",\"rl\":\"query_type-1|tip_show_type-1|tip_show_page-2\"},\"status\":{\"layoutStyle\":1}}");
}
//card.wasm
if (false) {
if (i++ % 2 == 0) {
mData.add("{\n" +
" \"model\": {\n" +
" \"src\": \"tmall_rec\",\n" +
" \"pos\": 3,\n" +
" \"topic\": \"你可能想看"+i+"\",\n" +
" \"type\": \"tmall_rec\",\n" +
" \"tShowTmpl\": \"wx_tmall_discovery\",\n" +
" \"tItemType\": \"wx_tmall_discovery\",\n" +
" \"tips\": [\n" +
" {\n" +
" \"picUrl\": \"https://img.alicdn.com/imgextra/i1/2985924572/TB2EL5XnDnI8KJjy0FfXXcdoVXa_!!2985924572.jpg\",\n" +
" \"show\": \"职场范儿\",\n" +
" \"params\": [\n" +
" {\n" +
" \"value\": \"tmall_rec\",\n" +
" \"key\": \"from\"\n" +
" },\n" +
" {\n" +
" \"value\": \"%7B%22tips_oriq%22%3A%22%E7%BE%BD%E7%BB%92%E6%9C%8D%22%2C%22tips_srppage%22%3A%221%22%2C%22tips_type%22%3A%22mall1%22%2C%22tips_pos%22%3A%220%22%2C%22pre_rn%22%3A%22767d9f52662b4883b2dfcff69f12edce%22%7D\",\n" +
" \"key\": \"vClickTrace\"\n" +
" },\n" +
" {\n" +
" \"value\": \"1001\",\n" +
" \"key\": \"tag_id\"\n" +
" },\n" +
" {\n" +
" \"value\": \"767d9f52662b4883b2dfcff69f12edce\",\n" +
" \"key\": \"sessionid\"\n" +
" },\n" +
" {\n" +
" \"value\": \"tmallRecCard\",\n" +
" \"key\": \"m\"\n" +
" },\n" +
" {\n" +
" \"value\": \"羽绒服\",\n" +
" \"key\": \"q\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"picUrl\": \"https://img.alicdn.com/tfs/TB1.3ctnvDH8KJjy1XcXXcpdXXa-1125-390.png\",\n" +
" \"show\": \"国际大牌\",\n" +
" \"params\": [\n" +
" {\n" +
" \"value\": \"tmall_rec\",\n" +
" \"key\": \"from\"\n" +
" },\n" +
" {\n" +
" \"value\": \"%7B%22tips_oriq%22%3A%22%E7%BE%BD%E7%BB%92%E6%9C%8D%22%2C%22tips_srppage%22%3A%221%22%2C%22tips_type%22%3A%22mall1%22%2C%22tips_pos%22%3A%221%22%2C%22pre_rn%22%3A%22767d9f52662b4883b2dfcff69f12edce%22%7D\",\n" +
" \"key\": \"vClickTrace\"\n" +
" },\n" +
" {\n" +
" \"value\": \"1007\",\n" +
" \"key\": \"tag_id\"\n" +
" },\n" +
" {\n" +
" \"value\": \"767d9f52662b4883b2dfcff69f12edce\",\n" +
" \"key\": \"sessionid\"\n" +
" },\n" +
" {\n" +
" \"value\": \"tmallRecCard\",\n" +
" \"key\": \"m\"\n" +
" },\n" +
" {\n" +
" \"value\": \"羽绒服\",\n" +
" \"key\": \"q\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"picUrl\": \"https://img.alicdn.com/imgextra/i2/263817957/TB2STDSnwLD8KJjSszeXXaGRpXa-263817957.jpg\",\n" +
" \"show\": \"优雅淑女\",\n" +
" \"params\": [\n" +
" {\n" +
" \"value\": \"tmall_rec\",\n" +
" \"key\": \"from\"\n" +
" },\n" +
" {\n" +
" \"value\": \"%7B%22tips_oriq%22%3A%22%E7%BE%BD%E7%BB%92%E6%9C%8D%22%2C%22tips_srppage%22%3A%221%22%2C%22tips_type%22%3A%22mall1%22%2C%22tips_pos%22%3A%222%22%2C%22pre_rn%22%3A%22767d9f52662b4883b2dfcff69f12edce%22%7D\",\n" +
" \"key\": \"vClickTrace\"\n" +
" },\n" +
" {\n" +
" \"value\": \"1002\",\n" +
" \"key\": \"tag_id\"\n" +
" },\n" +
" {\n" +
" \"value\": \"767d9f52662b4883b2dfcff69f12edce\",\n" +
" \"key\": \"sessionid\"\n" +
" },\n" +
" {\n" +
" \"value\": \"tmallRecCard\",\n" +
" \"key\": \"m\"\n" +
" },\n" +
" {\n" +
" \"value\": \"羽绒服\",\n" +
" \"key\": \"q\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"picUrl\": \"https://img.alicdn.com/imgextra/i2/263817957/TB2_JnCnBHH8KJjy0FbXXcqlpXa-263817957.jpg\",\n" +
" \"show\": \"活力少女\",\n" +
" \"params\": [\n" +
" {\n" +
" \"value\": \"tmall_rec\",\n" +
" \"key\": \"from\"\n" +
" },\n" +
" {\n" +
" \"value\": \"%7B%22tips_oriq%22%3A%22%E7%BE%BD%E7%BB%92%E6%9C%8D%22%2C%22tips_srppage%22%3A%221%22%2C%22tips_type%22%3A%22mall1%22%2C%22tips_pos%22%3A%223%22%2C%22pre_rn%22%3A%22767d9f52662b4883b2dfcff69f12edce%22%7D\",\n" +
" \"key\": \"vClickTrace\"\n" +
" },\n" +
" {\n" +
" \"value\": \"1005\",\n" +
" \"key\": \"tag_id\"\n" +
" },\n" +
" {\n" +
" \"value\": \"767d9f52662b4883b2dfcff69f12edce\",\n" +
" \"key\": \"sessionid\"\n" +
" },\n" +
" {\n" +
" \"value\": \"tmallRecCard\",\n" +
" \"key\": \"m\"\n" +
" },\n" +
" {\n" +
" \"value\": \"羽绒服\",\n" +
" \"key\": \"q\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"status\": {\n" +
" \"layoutStyle\": 0\n" +
" }\n" +
" }");
} else {
mData.add("{\n" +
" \"model\": {\n" +
" \"src\": \"tmall_rec\",\n" +
" \"pos\": 3,\n" +
" \"topic\": \"你可能不想看\",\n" +
" \"type\": \"tmall_rec\",\n" +
" \"tShowTmpl\": \"wx_tmall_discovery\",\n" +
" \"tItemType\": \"wx_tmall_discovery\",\n" +
" \"tips\": [\n" +
" {\n" +
" \"picUrl\": \"https://img.alicdn.com/imgextra/i1/2985924572/TB2EL5XnDnI8KJjy0FfXXcdoVXa_!!2985924572.jpg\",\n" +
" \"show\": \"职场范儿\",\n" +
" \"params\": [\n" +
" {\n" +
" \"value\": \"tmall_rec\",\n" +
" \"key\": \"from\"\n" +
" },\n" +
" {\n" +
" \"value\": \"%7B%22tips_oriq%22%3A%22%E7%BE%BD%E7%BB%92%E6%9C%8D%22%2C%22tips_srppage%22%3A%221%22%2C%22tips_type%22%3A%22mall1%22%2C%22tips_pos%22%3A%220%22%2C%22pre_rn%22%3A%22767d9f52662b4883b2dfcff69f12edce%22%7D\",\n" +
" \"key\": \"vClickTrace\"\n" +
" },\n" +
" {\n" +
" \"value\": \"1001\",\n" +
" \"key\": \"tag_id\"\n" +
" },\n" +
" {\n" +
" \"value\": \"767d9f52662b4883b2dfcff69f12edce\",\n" +
" \"key\": \"sessionid\"\n" +
" },\n" +
" {\n" +
" \"value\": \"tmallRecCard\",\n" +
" \"key\": \"m\"\n" +
" },\n" +
" {\n" +
" \"value\": \"羽绒服\",\n" +
" \"key\": \"q\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"picUrl\": \"https://img.alicdn.com/tfs/TB1.3ctnvDH8KJjy1XcXXcpdXXa-1125-390.png\",\n" +
" \"show\": \"国际大牌\",\n" +
" \"params\": [\n" +
" {\n" +
" \"value\": \"tmall_rec\",\n" +
" \"key\": \"from\"\n" +
" },\n" +
" {\n" +
" \"value\": \"%7B%22tips_oriq%22%3A%22%E7%BE%BD%E7%BB%92%E6%9C%8D%22%2C%22tips_srppage%22%3A%221%22%2C%22tips_type%22%3A%22mall1%22%2C%22tips_pos%22%3A%221%22%2C%22pre_rn%22%3A%22767d9f52662b4883b2dfcff69f12edce%22%7D\",\n" +
" \"key\": \"vClickTrace\"\n" +
" },\n" +
" {\n" +
" \"value\": \"1007\",\n" +
" \"key\": \"tag_id\"\n" +
" },\n" +
" {\n" +
" \"value\": \"767d9f52662b4883b2dfcff69f12edce\",\n" +
" \"key\": \"sessionid\"\n" +
" },\n" +
" {\n" +
" \"value\": \"tmallRecCard\",\n" +
" \"key\": \"m\"\n" +
" },\n" +
" {\n" +
" \"value\": \"羽绒服\",\n" +
" \"key\": \"q\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"picUrl\": \"https://img.alicdn.com/imgextra/i2/263817957/TB2STDSnwLD8KJjSszeXXaGRpXa-263817957.jpg\",\n" +
" \"show\": \"优雅淑女\",\n" +
" \"params\": [\n" +
" {\n" +
" \"value\": \"tmall_rec\",\n" +
" \"key\": \"from\"\n" +
" },\n" +
" {\n" +
" \"value\": \"%7B%22tips_oriq%22%3A%22%E7%BE%BD%E7%BB%92%E6%9C%8D%22%2C%22tips_srppage%22%3A%221%22%2C%22tips_type%22%3A%22mall1%22%2C%22tips_pos%22%3A%222%22%2C%22pre_rn%22%3A%22767d9f52662b4883b2dfcff69f12edce%22%7D\",\n" +
" \"key\": \"vClickTrace\"\n" +
" },\n" +
" {\n" +
" \"value\": \"1002\",\n" +
" \"key\": \"tag_id\"\n" +
" },\n" +
" {\n" +
" \"value\": \"767d9f52662b4883b2dfcff69f12edce\",\n" +
" \"key\": \"sessionid\"\n" +
" },\n" +
" {\n" +
" \"value\": \"tmallRecCard\",\n" +
" \"key\": \"m\"\n" +
" },\n" +
" {\n" +
" \"value\": \"羽绒服\",\n" +
" \"key\": \"q\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"picUrl\": \"https://img.alicdn.com/imgextra/i2/263817957/TB2_JnCnBHH8KJjy0FbXXcqlpXa-263817957.jpg\",\n" +
" \"show\": \"活力少女\",\n" +
" \"params\": [\n" +
" {\n" +
" \"value\": \"tmall_rec\",\n" +
" \"key\": \"from\"\n" +
" },\n" +
" {\n" +
" \"value\": \"%7B%22tips_oriq%22%3A%22%E7%BE%BD%E7%BB%92%E6%9C%8D%22%2C%22tips_srppage%22%3A%221%22%2C%22tips_type%22%3A%22mall1%22%2C%22tips_pos%22%3A%223%22%2C%22pre_rn%22%3A%22767d9f52662b4883b2dfcff69f12edce%22%7D\",\n" +
" \"key\": \"vClickTrace\"\n" +
" },\n" +
" {\n" +
" \"value\": \"1005\",\n" +
" \"key\": \"tag_id\"\n" +
" },\n" +
" {\n" +
" \"value\": \"767d9f52662b4883b2dfcff69f12edce\",\n" +
" \"key\": \"sessionid\"\n" +
" },\n" +
" {\n" +
" \"value\": \"tmallRecCard\",\n" +
" \"key\": \"m\"\n" +
" },\n" +
" {\n" +
" \"value\": \"羽绒服\",\n" +
" \"key\": \"q\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"status\": {\n" +
" \"layoutStyle\": 1\n" +
" }\n" +
" }");
}
}
mAdapter.notifyItemInserted(mData.size() - 1);
// mAdapter.notifyDataSetChanged();
}
private class WXInstanceAdapter extends RecyclerView.Adapter<WXViewHolder> {
@Override
public WXViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(LOG_TAG, "onCreateViewHolder");
FrameLayout itemView = new FrameLayout(SliceTestActivity.this);
itemView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
return new WXViewHolder(itemView);
}
@Override
public void onBindViewHolder(WXViewHolder holder, int position) {
String data = mData.get(position);
if (!holder.isRendered()) {
Log.d(LOG_TAG, "render onBindViewHolder " + position);
holder.render(data, position);
} else {
Log.d(LOG_TAG, "refresh onBindViewHolder " + position);
holder.refresh(data, position);
}
}
@Override
public int getItemCount() {
return mData.size();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
for (WXSDKInstance instance : mInstances) {
instance.destroy();
}
mInstances.clear();
}
private class WXViewHolder extends RecyclerView.ViewHolder implements IWXRenderListener {
private WXSDKInstance mInstance;
private boolean mRendered;
private TextView mTextView;
public WXViewHolder(View itemView) {
super(itemView);
mInstance = new WXSDKInstance(SliceTestActivity.this);
mInstance.registerRenderListener(this);
mInstances.add(mInstance);
mTextView = new TextView(SliceTestActivity.this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
((ViewGroup) itemView).addView(mTextView, params);
}
public void render(String initData, int position) {
//
if (true) {
mInstance.render(
"testPage",
loadAssets(),
null,
initData,
WXRenderStrategy.DATA_RENDER
);
} else {
//
mInstance.render(
"testPage",
loadBytes(),
null,
initData
);
}
mTextView.setText(String.valueOf(position));
mRendered = true;
}
public boolean isRendered() {
return mRendered;
}
public void refresh(String initData, int position) {
mInstance.refreshInstance(initData);
mTextView.setText(String.valueOf(position));
}
@Override
public void onViewCreated(WXSDKInstance instance, View view) {
((ViewGroup) itemView).addView(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public void onRenderSuccess(WXSDKInstance instance, int width, int height) {
}
@Override
public void onRefreshSuccess(WXSDKInstance instance, int width, int height) {
}
@Override
public void onException(WXSDKInstance instance, String errCode, String msg) {
}
}
@NonNull
private String loadAssets() {
StringBuilder buf = new StringBuilder();
try {
InputStream json = getAssets().open("lite_template/case.js");
BufferedReader in =
new BufferedReader(new InputStreamReader(json, "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
buf.append(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return buf.toString();
}
private byte[] loadBytes() {
try {
AssetFileDescriptor assetFileDescriptor = getAssets().openFd("lite_template/card.wasm");
long len = assetFileDescriptor.getDeclaredLength();
ByteBuffer buf = ByteBuffer.allocate((int) len);
InputStream json = assetFileDescriptor.createInputStream();
json.read(buf.array());
json.close();
return buf.array();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| alibaba/weex | playground/android/playground/src/main/java/org/apache/weex/SliceTestActivity.java |
1,431 | package run.halo.app.notification;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.concurrent.atomic.AtomicReference;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.util.Pair;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import run.halo.app.core.extension.notification.Subscription;
import run.halo.app.infra.utils.JsonUtils;
import run.halo.app.notification.EmailSenderHelper.EmailSenderConfig;
/**
* <p>A notifier that can send email.</p>
*
* @author guqing
* @see ReactiveNotifier
* @see JavaMailSenderImpl
* @since 2.10.0
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class EmailNotifier implements ReactiveNotifier {
private final SubscriberEmailResolver subscriberEmailResolver;
private final NotificationTemplateRender notificationTemplateRender;
private final EmailSenderHelper emailSenderHelper;
private final AtomicReference<Pair<EmailSenderConfig, JavaMailSender>>
emailSenderConfigPairRef = new AtomicReference<>();
@Override
public Mono<Void> notify(NotificationContext context) {
JsonNode senderConfig = context.getSenderConfig();
var emailSenderConfig =
JsonUtils.DEFAULT_JSON_MAPPER.convertValue(senderConfig, EmailSenderConfig.class);
if (!emailSenderConfig.isEnable()) {
log.debug("Email notifier is disabled, skip sending email.");
return Mono.empty();
}
JavaMailSender javaMailSender = getJavaMailSender(emailSenderConfig);
String recipient = context.getMessage().getRecipient();
var subscriber = new Subscription.Subscriber();
subscriber.setName(recipient);
var payload = context.getMessage().getPayload();
return subscriberEmailResolver.resolve(subscriber)
.flatMap(toEmail -> {
if (StringUtils.isBlank(toEmail)) {
log.debug("Cannot resolve email for subscriber: [{}], skip sending email.",
subscriber);
return Mono.empty();
}
var htmlMono = appendHtmlBodyFooter(payload.getAttributes())
.doOnNext(footer -> {
if (StringUtils.isNotBlank(payload.getHtmlBody())) {
payload.setHtmlBody(payload.getHtmlBody() + "\n" + footer);
}
});
var rawMono = appendRawBodyFooter(payload.getAttributes())
.doOnNext(footer -> {
if (StringUtils.isNotBlank(payload.getRawBody())) {
payload.setRawBody(payload.getRawBody() + "\n" + footer);
}
});
return Mono.when(htmlMono, rawMono)
.thenReturn(toEmail);
})
.map(toEmail -> getMimeMessagePreparator(toEmail, emailSenderConfig, payload))
.publishOn(Schedulers.boundedElastic())
.doOnNext(javaMailSender::send)
.then();
}
@NonNull
private MimeMessagePreparator getMimeMessagePreparator(String toEmail,
EmailSenderConfig emailSenderConfig, NotificationContext.MessagePayload payload) {
return emailSenderHelper.createMimeMessagePreparator(emailSenderConfig, toEmail,
payload.getTitle(),
payload.getRawBody(), payload.getHtmlBody());
}
JavaMailSender getJavaMailSender(EmailSenderConfig emailSenderConfig) {
return emailSenderConfigPairRef.updateAndGet(pair -> {
if (pair != null && pair.getFirst().equals(emailSenderConfig)) {
return pair;
}
return Pair.of(emailSenderConfig,
emailSenderHelper.createJavaMailSender(emailSenderConfig));
}).getSecond();
}
Mono<String> appendRawBodyFooter(ReasonAttributes attributes) {
return notificationTemplateRender.render("""
---
如果您不想再收到此类通知,点击链接退订: [(${unsubscribeUrl})]
[(${site.title})]
""", attributes);
}
Mono<String> appendHtmlBodyFooter(ReasonAttributes attributes) {
return notificationTemplateRender.render("""
<div class="footer" style="font-size: 12px; color: #666;">
<a th:href="${site.url}" th:text="${site.title}"></a>
<p class="unsubscribe">
—<br />请勿直接回复此邮件,
<a th:href="|${site.url}/uc/notifications|">查看通知</a>
或
<a th:href="${unsubscribeUrl}">取消订阅</a>。
</p>
</div>
""", attributes);
}
}
| halo-dev/halo | application/src/main/java/run/halo/app/notification/EmailNotifier.java |
1,433 | M
1528247314
tags: Array
给一串sorted list, 中间有缺数字, return 所有数字的range string (example 看题目)
#### Basic implementation
- 用一个list as the buffer to store candidates
- when: 1. end of nums; 2. not continuous integer => convert list to result
```
/*
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
Tags: Array
Similar Problems: (M) Missing Ranges
*/
/*
Thoughts: basic implementation, use a arraylist to catch candidates.
Detect condition, and return results.
*/
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> rst = new ArrayList<>();
if (nums == null || nums.length == 0) {
return rst;
}
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
list.add(nums[i]);
if (i + 1 == nums.length || nums[i] + 1 != nums[i + 1]) {
if (list.size() == 1) {
rst.add(list.get(0) + "");
} else {
rst.add(list.get(0) + "->" + list.get(list.size() - 1));
}
list = new ArrayList<Integer>();
}
}
return rst;
}
}
//O(n)
``` | awangdev/leet-code | Java/Summary Ranges.java |
1,434 | M
1518159874
tags: Math, DP, BFS, Partition DP
给一个数字n, 找到这个数字 最少能用多少个 平方数组成.
平方数比如: 1, 4, 9, 16 ... etc
#### Partition DP
- 遇到最值, 想到DP.
- 看到分割字眼, 想到分割型 DP.
- 思考, 如果 j * j = 9, 那么 j = 3 就是最少的一步; 但是如果是10呢? 就会分割成1 + 9 = 1 + j * j
- 考虑最后的数字: 要是12割个1出来, 剩下11怎么考虑? 割个4出来,剩下8怎么考虑?
- partion的方式: 在考虑dp[i - x]的时候, x 不是1, 而是 x = j*j.
- 就变成了dp = Min{dp[i - j^2] + 1}
#### 时间复杂度
- 乍一看是O(n*sqrt(n)). 实际也是. 但如何推导?
- 考虑上限: 把小的数字变成大的 推导上限; 考虑下限: 把数字整合归小, 找到下限.
- 考虑sqrt(1) + sqrt(2) + ....sqrt(n):找这个的upper bound and lower bound.
- 最后发现它的两边是 A*n*sqrt(n) <= actual time complexity <= B*n*sqrt(n)
- 那么就是O(n*sqrt(n))啦
#### BFS
- minus all possible (i*i) and calculate the remain
- if the remain is new, add to queue (use a hashset to mark calculated item)
- find shortest path / lowest level number
#### Previous Notes
- 一开始没clue.看了一下提示
- 1. 第一步想到了,从数学角度,可能是从最大的perfect square number开始算起。
- 2. 然后想法到了dp, 假设最后一步用了最大的maxSqrNum, 那么就在剩下的 dp[i - maxSqrNum^2] +1 不就好了?
- 3. 做了,发现有个问题...最后一步选不选maxSqrNum? 比如12就是个例子。
- 然后就根据提示,想到BFS。顺的。 把1~maxSqrNum 都试一试。找个最小的。
- 看我把12拆分的那个example. 那很形象的就是BFS了。
- 面试时候,如果拆分到这个阶段不确定,那跟面试官陶瓷一下,说不定也就提示BFS了。
```
/*
Given a positive integer n, find the least number of perfect square numbers
(for example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4;
given n = 13, return 2 because 13 = 4 + 9.
*/
/*
Thoughts: DP
dp[i] : min # of perfect square numbers with integer i
*/
class Solution {
public int numSquares(int n) {
if (n <= 1) {
return 1;
}
int[] dp = new int[n + 1]; // need to calculate dp[n]
dp[0] = 0;
for (int i = 1; i <= n; i++) {
dp[i] = Integer.MAX_VALUE;
for (int j = 1; j <= i; j++) {
if (i >= j * j) {
dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
} else {
break; // if (i - j * j) < 0, there is no point to j++
}
}
}
return dp[n];
}
}
// Same
class Solution {
public int numSquares(int n) {
if (n <= 1) {
return 1;
}
int[] dp = new int[n + 1]; // need to calculate dp[n]
dp[0] = 0;
for (int i = 1; i <= n; i++) {
dp[i] = Integer.MAX_VALUE;
for (int j = 1; j <= i && j * j <= i; j++) {
dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
}
}
return dp[n];
}
}
/*
BFS:
- count level, add input number n into queue
- consume num from queue, try out all integers [1, num)
- add remains (num - x^2) back to queue
- if any remain == 0, that's end of search, return level + 1
*/
class Solution {
public int numSquares(int n) {
// check input
if (n <= 0) {
return 0;
}
// build queue, add n
Queue<Integer> queue = new LinkedList<>();
Set<Integer> set = new HashSet<>(); // save remain, skip the ones already added
queue.offer(n);
// consume queue, count level
int level = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int x = 0; x < size; x++) {
int num = queue.poll();
for (int i = 1; i <= num; i++) {
int remain = num - i * i;
if (remain == 0) {
return level;
} else if (remain > 0 && !set.contains(remain)) {
queue.offer(remain);
set.add(remain);
} else if (remain < 0) {
break;
}
}
}
level++;
}
return level;
}
}
/*
Previous notes
Thoughts:
Take the 12 example: to start with can be break down to (1, 11), (4, 8), (9, 3).
Then we need to find minNumSquares for 11, or for 8, or for 3,
where we can verify that 11 and 3 does not have a perfect square root,
so we need to go with (4, 8) -> (4, 4, 4) or (4, 1, 7) => (4, 4, 4)
let's say dp[i]: # of perfect square at i = Min{dp[i - j^2] + 1}, where 1<=j<=i
We are not sure what last number we could pick, so loop over 1<=j<=i to try all
O(n*sqrt(n))
*/
/*
Thoughts:
Math:
num =13. sqrt(13) = 3.xxx. Floor() = 3. count++;//1
num = 13 - 9 = 4. sqrt(4) = 2. No remaining. count++;//2
DP:
state
dp[i]: min # of perfect square till i.
dp[0] = 0;
dp[1] = 1;
dp[2] = 1 + 1 = 2;
dp[3] = 1,1,1;//3
dp[4] = 2^2;//1
dp[5] = dp[5 - floor(sqrt(5))^2] + 1;
fn: //Pick the largest perfect square possible, then added on what's remaining's dp. Do a BFS on all possiblilities
maxFlorNum = Math.floor(Math.sqrt(i))
12
-3^2 = 3 -2^2 = 8 -1^2 = 11
1 + dp[3] 1 + dp[8] 1 + dp[11]
for (j = 0 ~ i)
dp[i] = min(min, dp[i - j ^ 2] + 1)
init:
dp[0] = 0;
dp[1] = 1;
return dp[n];
*/
public class Solution {
public int numSquares(int n) {
if (n <= 0) {
return 0;
}
int[] dp = new int[n + 1];
dp[0] = 0;
for (int i = 1; i <= n; i++) {
int maxSqrNum = (int)Math.floor(Math.sqrt(i));
int min = Integer.MAX_VALUE;
for (int j = 1; j <= maxSqrNum; j++) {
min = Math.min(min, dp[i - j * j] + 1);
}
dp[i] = min;
}
return dp[n];
}
}
/*
//Test Cases
dp[2] =2;
dp[4] = 1
dp[5] = 2;
dp[6] = 2 + 1 =3;
dp[7] = 3 + 1 = 4;
dp[8] = dp[4] + 1 = 1 = 1 = 2;
dp[9] = 1
dp[10] = 1 + 1 = 2;
dp[11] = 2 + 1 = 3
dp[12] = dp[12 - 9] + 3
*/
``` | awangdev/leet-code | Java/Perfect Squares.java |
1,435 | E
和Permutation Sequence相反的题目。思想类似。
题目为Easy,琢磨很久,分析:
每个数位的数字,都是跳过了小于这数字开头的多种可能。
举例【6,5,2】吧。我们找6,5,2是permudation里面的第几个。
正常排序,也就是permutation的第一个,应该是【2,5,6】
如果要从首位,2,变成6,要跨过多少可能性呢?
很简单,就是问:小于6的数字有多少个呢?(2,5).每个数字变成head,都有各自的一套变化,都有(n-1)!种可能。
本题做法:每个(n-1)!加起来。 Note:(n-1) means, 开头的数字(2,5)各带出多少种排列,也就是不就是(n-1)!嘛。
这一步,计算数量很简单: (有几个小于6的数字) ×(除去head剩下有多少个数字)!
以上 ,都是为了把6推上皇位,而牺牲的条数。
那么把6推上去以后,还有接下去的呢。
接下去要看5,2.
6确定,后面permudation可变的情况有可能是【6,5,2】,那还可能是【6,2,5】呢。
Same process, 看given 数组的第二位5,算它接下去:
1. 有几个数字小于5呢?
2. 除去5,还有几个数字可以 factorial呢?
3. 一样的。第一步就结果乘以第二步。
最后接下去要看最后一个元素2了。
6,5,2全看过了以后,加起来。
就是【6,5,2】上位,所踏过的所有小命啊!
我这解释太生动了。因为耗费了好长时间思考...
```
/*
Given a permutation which contains no repeated number, find its index in all the permutations of these numbers,
which are ordered in lexicographical order. The index begins at 1.
Example
Given [1,2,4], return 1.
*/
/*
Thoughts:
Given some thoughts online:
Take one example 4,2,1 (totally reversed, worse case)
Assume array length = n
1. If sorted, it should be 1,2,4. In permutation, when does 4 appear? It appears after 1xx,2xx. That is, it appears after all of the smaller ones show up.
2. For each number smaller than 4 in later indexes, each of them all have (n-1)! mutations. n -1 is actaully: current 0-based index of 4.
Therefore, for head number 4, there are:
#ofSmallerNumber * (curr 0-base index)!
3. For loop on each num, calculate
SUM {#ofSmallerNumber * (index i)!}
4. To store #ofSmallerNum, put hashmap<num, index>. For example, for number 4, with index 2: There are 2 numbers smaller than 4, which are 1 and 2.
O(n^2)
*/
public class Solution {
public long permutationIndex(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int n = A.length;
long rst = 0;
//O(n^2)
//Count: in A, after A[i], how many smaller nums are left behind.
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = i + 1; j < n; j++) {
if (A[j] < A[i]) {
count++;
}
}
map.put(A[i], count);
}
//O(n^2)
for (int i = 0; i < n; i++) {
long fact = 1;
for (int j = (n - i - 1); j >= 1; j--) {
fact *= j;
}
rst += map.get(A[i]) * fact;
}
return rst + 1;
}
}
``` | awangdev/leet-code | Java/Permutation Index.java |
1,436 | E
tags: Tree, DFS, BFS
time: O(n)
space: O(logn)
给两个 binary tree, 看两个tree是否identical.
#### Method1: DFS
- DFS. 确定leaf条件, && with all dfs(sub1, sub2).
- 这里无论如何都要走过所有的node, 所以dfs更加合适, 好写.
#### Method2: BFS with 2 queues
- 两个queue存每个tree的所有current level node. Check equality, check queue size.
- Populate next level by nodes at current level.
```
/*
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical
and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
Method1: DFS
Use the function itself with dfs.
Check p == q, p.left==q.left, p.right==q.right
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) return p == null && q == null;
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
// Method2: BFS
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Queue<TreeNode> pp = new LinkedList<>();
Queue<TreeNode> qq = new LinkedList<>();
pp.offer(p);
qq.offer(q);
while (!pp.isEmpty() && !qq.isEmpty()) {
p = pp.poll();
q = qq.poll();
if (p == null && q == null) continue;
if (p == null ^ q == null) return false;
if (p.val != q.val) return false;
offer(p, pp);
offer(q, qq);
}
return true;
}
private void offer(TreeNode node, Queue<TreeNode> queue) {
queue.offer(node.left);
queue.offer(node.right);
}
}
``` | awangdev/leet-code | Java/100. Same Tree.java |
1,440 | E
1532126087
tags: Greedy, Array, DP, Sequence DP, Subarray
time: O(m)
space: O(1)
给一串数组, unsorted, can have negative/positive num. 找数组中间 subarray 数字之和的最小值
#### DP
- 看到 min value, 至少考虑dp:
- Consider last num: min sum will be (preMinSum + curr, or curr)
- Use preMinSum to cache previouly calcualted min sum, also compare with +curr.
- Have a global min to track: because the preMinSum can be dis-continuous.
- 也可以写成 dp[i] 但是没什么必要
```
/*
Given an array of integers, find the subarray with smallest sum.
Return the sum of the subarray.
Example
For [1, -1, -2, 1], return -3
Note
The subarray should contain at least one integer.
Tags Expand
Greedy LintCode Copyright Subarray Array
*/
/*
DP, Sequence DP
Consider last num: min sum will be (preMinSum + curr, or curr)
Use preMinSum to cache previouly calcualted min sum, also compare with +curr.
Have a global min to track: because the preMinSum can be dis-continuous.
*/
public class Solution {
public int minSubArray(List<Integer> nums) {
if (nums == null || nums.size() == 0) return Integer.MAX_VALUE;
int preMinSum = 0, min = Integer.MAX_VALUE;
for (int num : nums) {
preMinSum = Math.min(num, preMinSum + num);
min = Math.min(min, preMinSum);
}
return min;
}
}
/*
Thoughts:
Note: sub-array has order. It's not sub-set
1. On each index: decide to add with nums.get(i), to use the new lowest value nums.get(i). That means:
If the new value is negative (it has decresing impact on sum) and the sum is larger than new value, just use the new value.
In another case, if sum has been nagative, so sum + new value will be even smaller, then use sum.
2. Every time compare the currMin with the overall minimum value, call it minRst.
Note: remember to pre-set init value for curMin, minRst.
*/
public class Solution {
/**
* @param nums: a list of integers
* @return: A integer indicate the sum of minimum subarray
*/
public int minSubArray(ArrayList<Integer> nums) {
if (nums == null || nums.size() == 0) {
return 0;
}
int curMin = nums.get(0);
int minRst = nums.get(0);
for (int i = 1; i < nums.size(); i++) {
curMin = Math.min(nums.get(i), curMin + nums.get(i));
minRst = Math.min(curMin, minRst);
}
return minRst;
}
}
``` | awangdev/leet-code | Java/Minimum Subarray.java |
1,441 | E
tags: String
给两个String, 看A rotate之后 能不能变成B
#### LeetCode
- Basics
- StringBuffer.deleteCharAt(xx), StringBuffer.append(xx)
- O(n)
#### LintCode
- Different problem: 给一个char[], 要rotate offset times.
- *三步rotate*
- 有个坑:offset可能很长,那么要%length,才能得到真正需要rotate的部分。
- Note: rotate 一个 full length之后,是string 不变
```
/*
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position.
For example, if A = 'abcde', then it will be 'bcdea' after one shift on A.
Return True if and only if A can become B after some number of shifts on A.
Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true
Example 2:
Input: A = 'abcde', B = 'abced'
Output: false
Note:
A and B will have length at most 100.
*/
class Solution {
public boolean rotateString(String A, String B) {
// check edge condition
if (A == null || B == null || A.length() != B.length()) {
return false;
}
if (A.equals(B)) {
return true;
}
// move characters, one at a time, and compare
StringBuffer sb = new StringBuffer(A);
for (char c : A.toCharArray()) {
sb.deleteCharAt(0);
sb.append(c);
if (sb.toString().equals(B)) {
return true;
}
}
return false;
}
}
/*
17% Accepted
Given a string and an offset, rotate string by offset. (rotate from left to right)
Example
Given "abcdefg"
for offset=0, return "abcdefg"
for offset=1, return "gabcdef"
for offset=2, return "fgabcde"
for offset=3, return "efgabcd"
...
Tags Expand
String
*/
public class Solution {
/*
* param A: A string
* param offset: Rotate string with offset.
* return: Rotated string.
*/
public char[] rotateString(char[] A, int offset) {
if (A == null || A.length == 0) return A;
offset = offset % (A.length);
reverse(A, 0, A.length - offset - 1);
reverse(A, A.length - offset, A.length - 1);
reverse(A, 0, A.length - 1);
return A;
}
//Helper function: reverse certain range of array
public void reverse(char[] A, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
char temp = A[j];
A[j] = A[i];
A[i] = temp;
}
}
};
``` | awangdev/leet-code | Java/796. Rotate String.java |
1,442 | package edu.stanford.nlp.pipeline;
import java.util.List;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import edu.stanford.nlp.ling.CoreAnnotations.TokensAnnotation;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.util.StringUtils;
public class ChineseSegmenterAnnotatorITest {
private StanfordCoreNLP pipeline; // = null
@Before
public void setUp() throws Exception {
if (pipeline != null) {
return;
}
Properties props = new Properties();
props.setProperty("annotators", "cseg");
props.setProperty("customAnnotatorClass.cseg", "edu.stanford.nlp.pipeline.ChineseSegmenterAnnotator");
props.setProperty("cseg.model", "edu/stanford/nlp/models/segmenter/chinese/ctb.gz");
props.setProperty("cseg.sighanCorporaDict", "edu/stanford/nlp/models/segmenter/chinese");
props.setProperty("cseg.serDictionary", "edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz");
props.setProperty("cseg.sighanPostProcessing", "true");
pipeline = new StanfordCoreNLP(props);
}
@Test
public void testPipeline() {
testOne("你马上回来北京吗?",
new String[]{"你", "马上", "回来", "北京", "吗", "?"},
new int[]{0, 1, 3, 5, 7, 8},
new int[]{1, 3, 5, 7, 8, 9});
// test that it does something reasonable with spaces
testOne("我在 加州 工作 ",
new String[]{"我", "在", "加州", "工作"},
new int[]{0, 1, 3, 6},
new int[]{1, 2, 5, 8});
// test that it does something reasonable with NBSP
testOne("我在 加州 工作 ",
new String[]{"我", "在", "加州", "工作"},
new int[]{0, 1, 3, 6},
new int[]{1, 2, 5, 8});
// All of the tools should now produce () instead of -LRB- -RRB-
testOne("你马上回来(北京)吗?",
new String[]{"你", "马上", "回来", "(", "北京", ")", "吗", "?"},
new int[]{0, 1, 3, 5, 6, 8, 9, 10},
new int[]{1, 3, 5, 6, 8, 9, 10, 11});
// Properly handle XML tags
testOne("<post id=\"something\" anything>这是一个测试</post>",
new String[]{"<post id=\"something\" anything>", "这", "是", "一", "个", "测试", "</post>"},
new int[]{0, 30, 31, 32, 33, 34, 36},
new int[]{30, 31, 32, 33, 34, 36, 43});
// KBP corpus examples, containing newlines and spaces
// The segmenter should be able to keep spaces within the xml tags, but skip those out of xml tags
testOne("<post author=\"拖垮美帝\" datetime=\"2011-12-06T22:36:00\" id=\"p3\">\n" +
"这个很难回答。\n" +
"</post>",
new String[]{"<post author=\"拖垮美帝\" datetime=\"2011-12-06T22:36:00\" id=\"p3\">", "这个", "很", "难", "回答", "。", "</post>"},
new int[]{0, 60, 62, 63, 64, 66, 68},
new int[]{59, 62, 63, 64, 66, 67, 75});
testOne("这里有一个图片。<img src=\"http://bbsfile.ifeng.com/bbsfile/images/smilies/default/lol.gif\"/> 希望你们都能看看。",
new String[]{"这里", "有", "一", "个", "图片", "。", "<img src=\"http://bbsfile.ifeng.com/bbsfile/images/smilies/default/lol.gif\"/>",
"希望", "你们", "都", "能", "看看", "。"},
new int[]{0, 2, 3, 4, 5, 7, 8, 86, 88, 90, 91, 92, 94},
new int[]{2, 3, 4, 5, 7, 8, 84, 88, 90, 91, 92, 94, 95});
// Check still works with non-BMP chars
testOne("买点咖啡\uD83D\uDE0A",
new String[] { "买", "点", "咖啡", "\uD83D\uDE0A" },
new int[] { 0, 1, 2, 4 },
new int[] { 1, 2, 4, 6});
}
private void testOne(String query, String[] expectedWords, int[] expectedBeginPositions, int[] expectedEndPositions) {
Annotation annotation = new Annotation(query);
pipeline.annotate(annotation);
List<CoreLabel> tokens = annotation.get(TokensAnnotation.class);
if (expectedWords.length != tokens.size()) {
System.err.println("Expected: " + StringUtils.join(expectedWords, " "));
System.err.println("Got: " + StringUtils.joinWords(tokens, " "));
}
Assert.assertEquals(expectedWords.length, tokens.size());
for (int i = 0; i < expectedWords.length; ++i) {
Assert.assertEquals(expectedWords[i], tokens.get(i).word());
Assert.assertEquals(expectedBeginPositions[i], tokens.get(i).beginPosition());
Assert.assertEquals(expectedEndPositions[i], tokens.get(i).endPosition());
}
}
}
| stanfordnlp/CoreNLP | itest/src/edu/stanford/nlp/pipeline/ChineseSegmenterAnnotatorITest.java |
1,443 | package org.ansj.dic.impl;
import org.ansj.dic.DicReader;
import org.ansj.dic.PathToStream;
import org.ansj.exception.LibraryException;
import java.io.InputStream;
/**
* 从系统jar包中读取文件,你们不能用,只有我能用 jar://org.ansj.dic.DicReader|/crf.model
*
* @author ansj
*
*/
public class Jar2Stream extends PathToStream {
@Override
public InputStream toStream(String path) {
if (path.contains("|")) {
String[] split = path.split("\\|");
try {
return Class.forName(split[0].substring(6)).getResourceAsStream(split[1].trim());
} catch (ClassNotFoundException e) {
throw new LibraryException(e);
}
} else {
return DicReader.getInputStream(path.substring(6));
}
}
}
| NLPchina/ansj_seg | src/main/java/org/ansj/dic/impl/Jar2Stream.java |
1,446 | package topic_model;
import Utils.TrieTree;
import Utils.WordNode;
import java.util.ArrayList;
/**
* Created by Jayvee on 2014/8/13.
*/
public class testTrieTree {
public static void main(String[] args) {
TrieTree tt = new TrieTree();
tt.addWord("我们工人有力量!");
tt.addWord("我们");
tt.addWord("你们");
tt.addWord("你们");
tt.addWord("你们");
tt.addWord("我们");
ArrayList<WordNode> al = tt.getSortedList(TrieTree.downSortor);
for (WordNode wn : al) {
System.out.println(wn);
}
}
}
| JayveeHe/TextClassifier-SVM | src/topic_model/testTrieTree.java |
1,447 | /**
* This file is part of FNLP (formerly FudanNLP).
*
* FNLP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FNLP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FudanNLP. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2009-2014 www.fnlp.org. All rights reserved.
*/
package org.fnlp.nlp.duplicate;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.fnlp.nlp.pipe.NGram;
/**
* 创建指纹
* @author xpqiu
*
*/
public class FingerPrint {
public static enum Type {Print,Char,NGram,WhiteSpace};
public static void main(String[] args) {
System.out.println(print("心 把那些挫折好好分析下 让自己的心态能更好 以后遇到事情也不会这么难受 别自己和自己过不去 那叫没事找事儿… 快睡吧"));
System.out.println(print("明天我问他。你们早点睡觉。明天场地呢"));//这种情况fa提取不出
System.out.println(print("自己的心态"));
}
private static Pattern p = Pattern.compile(".(\\pP|\\pS| | |\\s|的|把|和|也)+.");
public static TreeSet<String> print(String s) {
Matcher matcher = p.matcher(s);
TreeSet<String> set = new TreeSet<String>();
while(matcher.find()) {
String m = matcher.group();
set.add(m);
}
return set;
}
public static String ngram(String ss,int n) {
List l = NGram.ngramOnCharacter2List(ss, new int[]{n});
StringBuilder sb = new StringBuilder();
for(int i=0;i<l.size();i++){
sb.append(l.get(i));
sb.append(" ");
}
return sb.toString();
}
public static Set<String> ngramSet(String ss,int n) {
return NGram.ngramOnCharacter2Set(ss, new int[]{n});
}
public static String feature(String s, Type t) {
if(t==Type.WhiteSpace){
return whitespace(s);
}else if(t==Type.NGram){
return ngram(s,2);
}else if(t==Type.Char){
return ngram(s,1);
}
return null;
}
private static String whitespace(String s) {
return s;
}
public static Set<String> featureset(String s, Type t) {
if(t==Type.WhiteSpace){
return whitespaceSet(s);
}else if(t==Type.NGram){
return ngramSet(s,2);
}else if(t==Type.Char){
return ngramSet(s,1);
}
return null;
}
private static Set<String> whitespaceSet(String s) {
String[] toks = s.split("\\s+");
Set<String> set = new HashSet<String>();
for(int i=0;i<toks.length;i++)
set.add(toks[i]);
return set;
}
} | FudanNLP/fnlp | fnlp-core/src/main/java/org/fnlp/nlp/duplicate/FingerPrint.java |
1,449 | package zzz.study.foundations.string;
public class OutputFormat {
public static void main(String[] args) {
System.out.format("%-6s %-5s %-5s %-3s\n", "我", "是", "重要", "的");
System.out.format("%-6s %-5s %-5s %-3s\n", "你们", "是", "我的", "朋友");
System.out.format("%-6s %-5s %-5s %-3s\n", "他们", "很", "讨厌", "令人");
System.out.println("******************************* ");
System.out.format("%-6s %-5s %-5.5s %-3s\n", "I", "am", "important", "indeed");
System.out.format("%-6s %-5s %-5.5s %-3s\n", "you", "are", "my", "friends");
System.out.format("%-6s %-5s %-5.5s %-3s\n", "they", "are", "very", "noisy");
System.out.println("******************************* ");
System.out.format("%s\n", "这是中文字符");
System.out.format("%s\n", "These are English Characters");
System.out.format("%s\n", "一个汉字和一个英文字符都被认为是一个字符,但字符宽度却不一样");
System.out.format("%s\n", "format 只能根据字符个数进行对齐,而不能根据字符宽度对齐。");
System.out.format("%-6.6s %-5s %-5.5s %-3.5s\n", "中文字符宽度", "是", "1.5-2", "英文字符宽度");
System.out.println("******************************* ");
System.out.printf("%f %5.2f %7.3f\n", Math.PI, Math.PI, Math.PI);
System.out.printf("%f %5.2f %7.3f\n", Math.E, Math.E, Math.E);
System.out.printf("%f %5.2f %7.3f\n", 2.50, 2.50, 2.50);
}
}
| shuqin/ALLIN | src/main/java/zzz/study/foundations/string/OutputFormat.java |
1,450 | package com.hxy.shiro.filter;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* 类的功能描述.
*
* @Auther hxy
* @Date 2017/5/17
*/
public class RememberAuthenticationFilter extends FormAuthenticationFilter{
/**
* 这个方法决定了是否能让用户登录
*/
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
Subject subject = getSubject(request, response);
//如果 isAuthenticated 为 false 证明不是登录过的,同时 isRememberd 为true 证明是没登陆直接通过记住我功能进来的
if(!subject.isAuthenticated() && subject.isRemembered()){
//获取session看看是不是空的
Session session = subject.getSession();
//随便拿session的一个属性来看session当前是否是空的,我用userId,你们的项目可以自行发挥
if(session.getAttribute("user") == null){
//如果是空的才初始化,否则每次都要初始化,项目得慢死
//这边根据前面的前提假设,拿到的是username
// UserEntity userEntity = (UserEntity) subject.getPrincipal();
// session.setAttribute("user",userEntity);
//在这个方法里面做初始化用户上下文的事情,比如通过查询数据库来设置session值,你们自己发挥
//globalUserService.initUserContext(username, subject);
}
}
//这个方法本来只返回 subject.isAuthenticated() 现在我们加上 subject.isRemembered() 让它同时也兼容remember这种情况
return subject.isAuthenticated() || subject.isRemembered();
}
}
| huangxianyuan/hxyFrame | frame-shiro/src/main/java/com/hxy/shiro/filter/RememberAuthenticationFilter.java |
1,451 | /*
* MIT License
*
* Copyright (c) 2019 Perol_Notsfsssf
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE
*/
package com.perol.asdpl.pixivez.responses;
import java.io.Serializable;
public class IllustDetailResponse implements Serializable {
/**
* illust : {"id":67261030,"title":"吃狗粮的日子到了","type":"illust","image_urls":{"square_medium":"https://i.pximg.net/c/360x360_70/img-master/img/2018/02/14/01/02/59/67261030_p0_square1200.jpg","medium":"https://i.pximg.net/c/540x540_70/img-master/img/2018/02/14/01/02/59/67261030_p0_master1200.jpg","large":"https://i.pximg.net/c/600x1200_90/img-master/img/2018/02/14/01/02/59/67261030_p0_master1200.jpg"},"caption":"你们快乐,我继续肝崩崩崩","restrict":0,"user":{"id":24087148,"name":"脸黑の零氪渣","account":"zeng_yu","profile_image_urls":{"medium":"https://i.pximg.net/user-profile/img/2017/08/04/20/04/06/12978904_75e510554696aaa9f228cf94736b57e9_170.gif"},"is_followed":true},"tags":[{"name":"崩坏3"},{"name":"崩坏3rd"},{"name":"德莉莎"},{"name":"情人节"},{"name":"崩壊3rd"}],"tools":["SAI"],"create_date":"2018-02-14T01:02:59+09:00","page_count":1,"width":1200,"height":1600,"sanity_level":2,"series":null,"meta_single_page":{"original_image_url":"https://i.pximg.net/img-original/img/2018/02/14/01/02/59/67261030_p0.jpg"},"meta_pages":[],"total_view":884,"total_bookmarks":91,"is_bookmarked":false,"visible":true,"is_muted":false,"total_comments":3}
*/
private Illust illust;
public Illust getIllust() {
return illust;
}
public void setIllust(Illust illust) {
this.illust = illust;
}
}
| Notsfsssf/Pix-EzViewer | app/src/main/java/com/perol/asdpl/pixivez/responses/IllustDetailResponse.java |
1,452 | import java.util.Scanner;
/**
* @Description 智能AI客服服务系统
* @Author saltfish
* @Date 15:35 2019/6/22
*/
public class AICustomerServiceSystem {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str;
// 待优化
while (true) {
str = sc.next();
// 测试环境,正式环境从数据库中获取
str = str.replace("吗", "");
str = str.replace("?", "!");
str = str.replace("?", "!");
str = str.replace("不", "很");
str = str.replace("你们", "我们");
str = str.replace("有", "没有");
System.out.println(str);
}
// test
// 在吗?
// 在!
// 你好!
// 你好!
// 产品有问题啊
// 产品没有问题啊
// 你们的服务态度不好
// 我们的服务态度很好
}
} | xumuyao/gitee-bullshit-codes | java/AICustomerServiceSystem.java |
1,453 | /*
* Copyright (c) 2020 WildFireChat. All rights reserved.
*/
package cn.wildfirechat.message.notification;
import android.os.Parcel;
import cn.wildfirechat.message.Message;
import cn.wildfirechat.message.core.ContentTag;
import cn.wildfirechat.message.core.MessagePayload;
import cn.wildfirechat.message.core.PersistFlag;
import static cn.wildfirechat.message.core.MessageContentType.ContentType_Friend_Added;
import static cn.wildfirechat.message.core.MessageContentType.ContentType_Friend_Greeting;
/**
* Created by heavyrainlee on 20/12/2017.
*/
@ContentTag(type = ContentType_Friend_Added, flag = PersistFlag.Persist)
public class FriendAddedMessageContent extends NotificationMessageContent {
public FriendAddedMessageContent() {
}
@Override
public String formatNotification(Message message) {
return "你们已经是好友了,可以开始聊天了。";
}
@Override
public MessagePayload encode() {
MessagePayload payload = super.encode();
return payload;
}
@Override
public void decode(MessagePayload payload) {
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
}
protected FriendAddedMessageContent(Parcel in) {
super(in);
}
public static final Creator<FriendAddedMessageContent> CREATOR = new Creator<FriendAddedMessageContent>() {
@Override
public FriendAddedMessageContent createFromParcel(Parcel source) {
return new FriendAddedMessageContent(source);
}
@Override
public FriendAddedMessageContent[] newArray(int size) {
return new FriendAddedMessageContent[size];
}
};
}
| wildfirechat/android-chat | client/src/main/java/cn/wildfirechat/message/notification/FriendAddedMessageContent.java |
1,454 | import java.text.SimpleDateFormat;
import java.util.Date;
public class A {
/*
* 第一个Java程序
* 它将输出字符串 Hello World
*/
public static void main(String[] args) {
// 数组类型[] 数组名=new {"小白","小明"};
/*
* int[] age = { 1, 2, 9, 3, 4, 5, 6, 7, 8 };
* String[] name = { "小明", "小白" };
* System.out.println(age[0]);
* System.out.println(name[0]);
*/
/*
* StringBuilder sb = new StringBuilder();
* sb.append("我是");
* sb.append("你们");
* sb.append("管理员");
* System.out.println(sb);
*/
Date date = new Date();
SimpleDateFormat sp = new SimpleDateFormat("y-M-d h:m:s ");
System.out.println(date.toString());
System.out.println(sp.format(date));
}
} | 1990569689/JavaLearn | A.java |
1,456 | package com.xu.drools.rule.complexProblem;
import com.xu.drools.bean.Student;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
/**
* 使用kmodule的方式调用drools
* /resources/META-INF/kmodule.xml
* 猜对错问题
*/
public class WorldProblem {
/**
* 在一次数学竞赛中,获得前三名的同学是A,B,C. 老师对他们说:“祝贺你们,请你们猜一猜名次。”
* 甲:“A是第二,C是第三.”
* 乙:“A是第一,B是第三.”
* 丙:“B是第二,A是第三.”
* 感觉有更好的方法,但是写不出规则来0.0
*/
public static void main(final String[] args) {
KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();
System.out.println(kc.verify().getMessages().toString());
execute(kc);
}
private static void execute(KieContainer kc) {
KieSession ksession = kc.newKieSession("worldKS");
String[] names = new String[]{"jia", "yi", "bing"};
String[] word1 = new String[]{"A", "B", "C"};
String[] word2 = new String[]{"A", "B", "C"};
int[] desc1 = new int[]{1, 2, 3};
int[] desc2 = new int[]{1, 2, 3};
for (String n : names) {
for (String w1 : word1) {
for (String w2 : word2) {
for (int d1 : desc1) {
for (int d2 : desc2) {
Student student = new Student(n, w1, w2, d1, d2);
ksession.insert(student);
}
}
}
}
}
ksession.fireAllRules();
ksession.dispose();
}
}
| MyHerux/drools-springboot | src/main/java/com/xu/drools/rule/complexProblem/WorldProblem.java |
1,457 | package spark;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Milo on 2017/8/9.
*/
public class TestPattern {
private static final Pattern pattern = Pattern
.compile("(http://|ftp://|https://|www){0,1}[^\u4e00-\u9fa5\\s]*?\\.(com|net|cn|me|tw|fr)[^\u4e00-\u9fa5\\s]*");
public static void main(String[] args) {
String comment = "你们 91flba.com 91flba.com 别 www.baidu.com www.xxxxxbbs.com";
Matcher matcher =pattern.matcher(comment);
List<String> replaceList = Lists.newArrayList();
while (matcher.find()){
boolean result = ReplaceURLInCommentUtil.doWhile(matcher.group(0));
System.out.println(result);
if(result){
replaceList.add(matcher.group(0));
}
}
System.out.println(replaceList.size());
System.out.println(replaceList);
for (String str : replaceList){
comment = comment.replace(str,"");
}
System.out.println(comment);
}
}
| xupengju/myjava | src/spark/TestPattern.java |
1,458 | package com.example.newbiechen.ireader.model.bean;
/**
* Created by newbiechen on 17-5-10.
*/
public class ChapterInfoBean {
/**
* title : 第一章 他叫白小纯
* body : 帽儿山,位于东林山脉中,山下有一个村子,民风淳朴,以耕田为生,与世隔绝。
清晨,村庄的大门前,整个村子里的乡亲,正为一个十五六岁少年送别,这少年瘦弱,但却白白净净,看起来很是乖巧,衣着尽管是寻常的青衫,可却洗的泛白,穿在这少年的身上,与他目中的纯净搭配在一起,透出一股子灵动。
他叫白小纯。
“父老乡亲们,我要去修仙了,可我舍不得你们啊。”少年满脸不舍,原本就乖巧的样子,此刻看起来更为纯朴。
四周的乡亲,面面相觑,顿时摆出难舍之色。
“小纯,你爹娘走的早,你是个……好孩子!!难道你不想长生了么,成为仙人就可以长生,能活的很久很久,走吧,雏鹰长大,总有飞出去的那一天。”人群内走出一个头发花白的老者,说道好孩子三个字时,他顿了一下。
“在外面遇到任何事情,都要坚持下去,走出村子,就不要回来,因为你的路在前方!”老人神色慈祥,拍了拍少年的肩膀。
“长生……”白小纯身体一震,目中慢慢坚定起来,在老者以及四周乡亲鼓励的目光下,他重重的点了点头,深深的看了一眼四周的乡亲,转身迈着大步,渐渐走出了村子。
眼看少年的身影远去,村中的众人,一个个都激动起来,目中的难舍刹那就被喜悦代替,那之前满脸慈祥的老者,此刻也在颤抖,眼中流下泪水。
“苍天有眼,这白鼠狼,他终于……终于走了,是谁告诉他在附近看到仙人的,你为村子立下了大功!”
“这白鼠狼终于肯离开了,可怜我家的几只鸡,就因为这白鼠狼怕鸡打鸣,不知用了什么方法,唆使一群孩子吃鸡肉,把全村的鸡都给吃的干干净净……”
“今天过年了!”欢呼之声,立刻在这不大的村子里,沸腾而起,甚至有人拿出了锣鼓,高兴的敲打起来。
村子外,白小纯还没等走远,他就听到了身后村子内,传出了敲锣打鼓的声音,还夹着欢呼。
白小纯脚步一顿,神色有些古怪,干咳一声,伴随着耳边传来的锣鼓,白小纯顺着山路,走上了帽儿山。
这帽儿山虽不高,却灌木杂多,虽是清晨,可看起来也是黑压压一片,很是安静。
“听二狗说,他前几天在这里被一头野猪追赶时,看到天上有仙人飞过……”白小纯走在山路上,心脏怦怦跳动时,忽然一旁的灌林中传来阵阵哗哗声,似野猪一样,这声音来的突然,让本就紧张的白小纯,顿时背后发凉。
“谁,谁在那里!”白小纯右手快速从行囊中拿出四把斧头,六把柴刀,还觉得不放心,又从怀里取出了一小根黑色的香,死死的抓住。
“别出来,千万别出来,我有斧头,有柴刀,手里的香还可以召唤天雷,能引仙人降临,你敢出来,就劈死你!”白小纯哆嗦的大喊,连滚带爬的夹着那些武器,赶紧顺着山路跑去,沿途叮当乱响,斧头柴刀掉了一地。
或许是真的被他给吓住了,很快的哗哗声就消失,没有什么野兽跑出来,白小纯面色苍白,擦了擦冷汗,有心放弃继续上山,可一想到手中这根香是他爹娘去世前留给他的,据说是祖上曾偶然的救下一个落魄的仙人,那仙人离去时留下这根香作为报答,曾言会收下白家血脉一人为弟子,只要点燃,仙人就会到来。
可至今为止,这根香他点过十多次,始终不见仙人到来,让白小纯开始怀疑仙人是不是真的会来,这一次之所以下定决心,一方面是香所剩不多,另一方面是他听村子里人说,头几天在这看到有仙人从天上飞过。
所以他这才到来,想着距离仙人近一些,或许仙人就察觉到了也说不定。
踌躇一番,白小纯咬牙继续,好在此山不高,不久他气喘吁吁的到了山顶,站在那里,他遥望山下的村庄,神色颇为感慨,又低头看着手中的只有指甲盖大小的黑香,此香似乎被燃烧了好多次,所剩不多。
“三年了,爹娘保佑我,这次一定要成功!”白小纯深吸口气,小心的将香点燃,立刻四周狂风顿起,天空更是眨眼间乌云密布,一道道闪电划过,还有震耳欲聋的雷鸣在白小纯耳边直接炸开。
声音之大,气势之强,让白小纯身体哆嗦,有种随时会被雷劈死的感觉,下意识的就想要吐口唾沫将那根香灭掉,但却挣扎忍住。
“三年了,我点这根香点了十二次,这是第十三次,这次一定要忍住,小纯不怕,应该不会被劈死……”白小纯想起了这三年的经历,不算这次,点了十二次,每次都是这样的雷鸣闪电,仙人也没有到来,吓的本就怕死的他每次都吐口唾沫将其熄灭,说来也怪,这根香看似不凡,可实际上一样是浇水就灭。
在白小纯这里心惊肉跳,艰难的于那雷声中等待时,距离这里不远处的天空上,有一道长虹正急速的呼啸而来。
长虹内是一个中年男子,这男子衣着华丽,仙风道骨,可偏偏风尘仆仆,甚至仔细去看,可以看到他神色内深深的疲惫。
“我倒要看看,到底是个什么样的人,竟然点根香点了三年!”
一想到自己这三年的经历,中年男子就气恼,三年前他察觉有人点燃自己还是凝气时送出的香药,想起了当年在凡俗中的一段人情。
这才飞出寻来,原本按照他的打算,很快就会回来,可没成想,刚寻着香气过去,还没等多远,那气息就瞬间消失,断了联系。若是一次也就罢了,这三年,气息出现了十多次。
使得他这里,多次在寻找时中断,就这样来来回回,折腾了三年……
此刻他遥遥的看到了帽儿山,看到了山顶上白小纯,气不打一处来,一瞬飞出,直接就站在了山顶,大手一挥,那根所剩不多的香,直接熄灭。
雷声刹那消失,白小纯愣了一下,抬头一看,看到了自己的身边多了一个中年男子。
“仙人?”白小纯小心翼翼的开口,有些拿不准,背后偷偷捡起一把斧头。
“本座李青候,你是白家后人?”中年修士目光如电,无视白小纯身后的斧子,打量了白小纯一番,觉得眼前此子眉清目秀,依稀与当年的故人相似,资质也不错,心底的恼意,也不由缓了一些。
“晚辈正是白家后人,白小纯。”白小纯眨了眨眼,小声说道,虽然心中有些畏惧,但还是挺了挺腰板。
“我问你,点一根香,为什么点了三年!”中年修士淡淡开口,问出了他这三年里,最想要知道的问题。
白小纯听到这个问题,脑筋飞速转动,然后脸上摆出惆怅,遥望山下的村庄。
“晚辈是一个重情重义的人,舍不得那些乡亲们,每一次我点燃香,他们也都不舍得我离去,如今山下的他们,还在因为我的离去而悲伤呢。”
中年修士一愣,这个缘由,是他之前没想到的,目中的恼色又少了一些,单单从话语上看,此子的本性还是不错的。
可当他的目光落在山下的村子时,他的神识随之扫过,听到了村子里的敲锣打鼓以及那一句句欢呼白鼠狼离去的话语,面色立刻难看起来,有些头疼,看着眼前这个外表乖巧纯朴,人畜无害的白小纯,已心底明朗对方实际上一肚子坏水。
“说实话!”中年修士一瞪眼,声音如同雷声一样,白小纯吓得一个哆嗦。
“这不怨我啊,你那什么破香啊,每次点燃都会打雷,好几次都差点劈死我,我躲过了十三次,已经很不容易了。”白小纯可怜兮兮的说道。
中年修士看着白小纯,半晌无语。
“既然你这么害怕,为什么还要强行去点香十多次?”中年修士缓缓开口。
“我怕死啊,修仙不是能长生么,我想长生啊。”白小纯委屈的说道。
中年修士再次无语,不过觉得此子总算执念可嘉,扔到门派里磨炼一番,或可在性子上改变一二。
于是略一思索,大袖一甩卷着白小纯化作一道长虹,直奔天边而去。
“跟我走吧。”
“去哪?这也太高了吧……”白小纯看到自己在天上飞,下面是万丈深渊,立刻脸色苍白,斧头一扔,死死的抱住仙人的大腿。
中年修士看了眼自己的腿,无奈开口。
“灵溪宗。”
兄弟姐妹们,阔别2个月,你们想不想我啊,我非常想你们!
这本书,我做了详细的大纲,每次回顾大纲里的情节,都很兴奋,有种燃烧的感觉,我非常满意,明天,正式更新,依旧是中午一章,晚上一章!
很兴奋,我们已沉寂了数月,如今归来,要……再战起点!
新书期,兄弟姐妹,别忘了收藏与推荐啊,收藏与推荐至关重要!
求收藏!!求推荐!!
让众人知晓,我们……归来了!
我们的目标,依旧是……点击榜,推荐榜,第一!
*/
private String title;
private String body;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
| newbiechen1024/NovelReader | app/src/main/java/com/example/newbiechen/ireader/model/bean/ChapterInfoBean.java |
1,459 | /*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is "Simplenlg".
*
* The Initial Developer of the Original Code is Ehud Reiter, Albert Gatt and Dave Westwater.
* Portions created by Ehud Reiter, Albert Gatt and Dave Westwater are Copyright (C) 2010-11 The University of Aberdeen. All Rights Reserved.
*
* Contributor(s): Ehud Reiter, Albert Gatt, Dave Wewstwater, Roman Kutlak, Margaret Mitchell.
*/
package simplenlg.framework;
import java.util.Arrays;
import java.util.List;
import simplenlg.features.Feature;
import simplenlg.features.Gender;
import simplenlg.features.InternalFeature;
import simplenlg.features.LexicalFeature;
import simplenlg.features.NumberAgreement;
import simplenlg.features.Person;
import simplenlg.lexicon.Lexicon;
import simplenlg.phrasespec.AdjPhraseSpec;
import simplenlg.phrasespec.AdvPhraseSpec;
import simplenlg.phrasespec.NPPhraseSpec;
import simplenlg.phrasespec.PPPhraseSpec;
import simplenlg.phrasespec.SPhraseSpec;
import simplenlg.phrasespec.VPPhraseSpec;
/**
* <p>
* This class contains methods for creating syntactic phrases. These methods
* should be used instead of directly invoking new on SPhraseSpec, etc.
*
* The phrase factory should be linked to s lexicon if possible (although it
* will work without one)
* </p>
*
*
* @author D. Westwater, University of Aberdeen.
* @version 4.0
*
*/
public class NLGFactory {
/***
* CODING COMMENTS The original version of phraseFactory created a crude
* realisation of the phrase in the BASE_FORM feature. This was just for
* debugging purposes (note BASE_FORM on a WordElement is meaningful), I've
* zapped this as it was makig things too complex
*
* This version of phraseFactory replicates WordElements (instead of reusing
* them). I think this is because elemente are linked to their parent
* phrases, via the parent data member. May be good to check if this is
* actually necessary
*
* The explicit list of pronouns below should be replaced by a reference to
* the lexicon
*
* Things to sort out at some point..
*
*/
/** The lexicon to be used with this factory. */
private Lexicon lexicon;
/** The list of Chinese pronouns.
* Changes:
* 1. discard accusative forms, the word such as "咱们" will not be considered;
* 2. discard the case that "自己" appears itself;
* 3. discard the word "there" in English, since there is no such pronoun in
* Chinese
* 4. for plural cases, chinese also has different form for different gender
*/
@SuppressWarnings("nls")
private static final List<String> PRONOUNS = Arrays.asList("我",
"你",
"他",
"她",
"它",
"我 自己",
"你 自己",
"他 自己",
"她 自己",
"它 自己",
"我 的",
"你 的",
"他 的",
"她 的",
"它 的",
"我们",
"你们",
"他们",
"她们",
"它们",
"我们 自己",
"你们 自己",
"它们 自己",
"他们 自己",
"她们 自己",
"我们 的",
"你们 的",
"她们 的",
"它们 的",
"他们 的");
/** The list of first-person Chinese pronouns. */
@SuppressWarnings("nls")
private static final List<String> FIRST_PRONOUNS = Arrays.asList("我",
"我 自己",
"我们",
"我们 自己",
"我们 的",
"我 的");
/** The list of second person English pronouns. */
@SuppressWarnings("nls")
private static final List<String> SECOND_PRONOUNS = Arrays.asList("你",
"你 自己",
"你们 自己",
"你们 的",
"你 的");
/** The list of reflexive English pronouns. */
@SuppressWarnings("nls")
private static final List<String> REFLEXIVE_PRONOUNS = Arrays.asList("我 自己",
"你 自己",
"他 自己",
"她 自己",
"它 自己",
"我们 自己",
"你们 自己",
"它们 自己",
"她们 自己",
"他们 自己");
/** The list of masculine Chinese pronouns. */
@SuppressWarnings("nls")
private static final List<String> MASCULINE_PRONOUNS = Arrays.asList("他", "他 自己", "他 的", "他们 自己", "他们 的");
/** The list of feminine English pronouns. */
@SuppressWarnings("nls")
private static final List<String> FEMININE_PRONOUNS = Arrays.asList("她", "她 自己", "她 的", "她们 自己", "她们 的");
/** The list of possessive English pronouns. */
@SuppressWarnings("nls")
private static final List<String> POSSESSIVE_PRONOUNS = Arrays.asList("我 的",
"我们 的",
"你 的",
"你们 的",
"他 的",
"她 的",
"它 的",
"它们 的",
"他们 的",
"她们 的");
/** The list of plural English pronouns. */
@SuppressWarnings("nls")
private static final List<String> PLURAL_PRONOUNS = Arrays.asList("我们 的",
"你们 的",
"它们 的",
"他们 的",
"我们 自己",
"你们 自己",
"它们 自己",
"她们 自己",
"他们 自己");
/** The list of English pronouns that can be singular or plural. */
private static final List<String> EITHER_NUMBER_PRONOUNS = Arrays.asList("there");
/** The list of expletive English pronouns. */
private static final List<String> EXPLETIVE_PRONOUNS = Arrays.asList("there");
/** regex for determining if a string is a single word or not **/
private static final String WORD_REGEX = "\\w*";
/**
* Creates a new phrase factory with no associated lexicon.
*/
public NLGFactory() {
this(null);
}
/**
* Creates a new phrase factory with the associated lexicon.
*
* @param newLexicon
* the <code>Lexicon</code> to be used with this factory.
*/
public NLGFactory(Lexicon newLexicon) {
setLexicon(newLexicon);
}
/**
* Sets the lexicon to be used by this factory. Passing a parameter of
* <code>null</code> will remove any existing lexicon from the factory.
*
* @param newLexicon
* the new <code>Lexicon</code> to be used.
*/
public void setLexicon(Lexicon newLexicon) {
this.lexicon = newLexicon;
}
/**
* Creates a new element representing a word. If the word passed is already
* an <code>NLGElement</code> then that is returned unchanged. If a
* <code>String</code> is passed as the word then the factory will look up
* the <code>Lexicon</code> if one exists and use the details found to
* create a new <code>WordElement</code>.
*
* @param word
* the base word for the new element. This can be a
* <code>NLGElement</code>, which is returned unchanged, or a
* <code>String</code>, which is used to construct a new
* <code>WordElement</code>.
* @param category
* the <code>LexicalCategory</code> for the word.
*
* @return an <code>NLGElement</code> representing the word.
*/
public NLGElement createWord(Object word, LexicalCategory category) {
NLGElement wordElement = null;
if(word instanceof NLGElement) {
wordElement = (NLGElement) word;
} else if(word instanceof String && this.lexicon != null) {
wordElement = lexicon.lookupWord((String) word, category);
if(PRONOUNS.contains(word)) {
setPronounFeatures(wordElement, (String) word);
}
}
return wordElement;
}
/**
* Create an inflected word element. InflectedWordElement represents a word
* that already specifies the morphological and other features that it
* should exhibit in a realisation. While normally, phrases are constructed
* using <code>WordElement</code>s, and features are set on phrases, it is
* sometimes desirable to set features directly on words (for example, when
* one wants to elide a specific word, but not its parent phrase).
*
* <P>
* If the object passed is already a <code>WordElement</code>, then a new
*
* <code>InflectedWordElement<code> is returned which wraps this <code>WordElement</code>
* . If the object is a <code>String</code>, then the
* <code>WordElement</code> representing this <code>String</code> is looked
* up, and a new
* <code>InflectedWordElement<code> wrapping this is returned. If no such <code>WordElement</code>
* is found, the element returned is an <code>InflectedWordElement</code>
* with the supplied string as baseform and no base <code>WordElement</code>
* . If an <code>NLGElement</code> is passed, this is returned unchanged.
*
* @param word
* the word
* @param category
* the category
* @return an <code>InflectedWordElement</code>, or the original supplied
* object if it is an <code>NLGElement</code>.
*/
public NLGElement createInflectedWord(Object word, LexicalCategory category) {
// first get the word element
NLGElement inflElement = null;
if(word instanceof WordElement) {
inflElement = new InflectedWordElement((WordElement) word);
} else if(word instanceof String) {
NLGElement baseword = createWord((String) word, category);
if(baseword != null && baseword instanceof WordElement) {
inflElement = new InflectedWordElement((WordElement) baseword);
} else {
inflElement = new InflectedWordElement((String) word, category);
}
} else if(word instanceof NLGElement) {
inflElement = (NLGElement) word;
}
return inflElement;
}
/**
* A helper method to set the features on newly created pronoun words.
* Adaptation not finished, currently only work for pronominalisation
*
* @param wordElement
* the created element representing the pronoun.
* @param word
* the base word for the pronoun.
*/
private void setPronounFeatures(NLGElement wordElement, String word) {
wordElement.setCategory(LexicalCategory.PRONOUN);
if(FIRST_PRONOUNS.contains(word)) {
wordElement.setFeature(Feature.PERSON, Person.FIRST);
} else if(SECOND_PRONOUNS.contains(word)) {
wordElement.setFeature(Feature.PERSON, Person.SECOND);
} else {
wordElement.setFeature(Feature.PERSON, Person.THIRD);
}
if(REFLEXIVE_PRONOUNS.contains(word)) {
wordElement.setFeature(LexicalFeature.REFLEXIVE, true);
} else {
wordElement.setFeature(LexicalFeature.REFLEXIVE, false);
}
if(MASCULINE_PRONOUNS.contains(word)) {// The mixed gender cases will be considered when processing mophemes
wordElement.setFeature(LexicalFeature.GENDER, Gender.MASCULINE);
} else if(FEMININE_PRONOUNS.contains(word)) {
wordElement.setFeature(LexicalFeature.GENDER, Gender.FEMININE);
} else {
wordElement.setFeature(LexicalFeature.GENDER, Gender.NEUTER);
}
if(POSSESSIVE_PRONOUNS.contains(word)) {
wordElement.setFeature(Feature.POSSESSIVE, true);
} else {
wordElement.setFeature(Feature.POSSESSIVE, false);
}
if(PLURAL_PRONOUNS.contains(word)) {
wordElement.setPlural(true);
} else {
wordElement.setPlural(false);
}
if(EXPLETIVE_PRONOUNS.contains(word)) {
wordElement.setFeature(InternalFeature.NON_MORPH, true);
wordElement.setFeature(LexicalFeature.EXPLETIVE_SUBJECT, true);
}
}
/**
* Creates a blank preposition phrase with no preposition or complements.
*
* @return a <code>PPPhraseSpec</code> representing this phrase.
*/
public PPPhraseSpec createPrepositionPhrase() {
return createPrepositionPhrase(null, null);
}
/**
* Creates a preposition phrase with the given preposition.
*
* @param preposition
* the preposition to be used.
* @return a <code>PPPhraseSpec</code> representing this phrase.
*/
public PPPhraseSpec createPrepositionPhrase(Object preposition) {
return createPrepositionPhrase(preposition, null);
}
/**
* Creates a preposition phrase with the given preposition and complement.
* An <code>NLGElement</code> representing the preposition is added as the
* head feature of this phrase while the complement is added as a normal
* phrase complement.
*
* @param preposition
* the preposition to be used.
* @param complement
* the complement of the phrase.
* @return a <code>PPPhraseSpec</code> representing this phrase.
*/
public PPPhraseSpec createPrepositionPhrase(Object preposition, Object complement) {
PPPhraseSpec phraseElement = new PPPhraseSpec(this);
NLGElement prepositionalElement = createNLGElement(preposition, LexicalCategory.PREPOSITION);
setPhraseHead(phraseElement, prepositionalElement);
if(complement != null) {
setComplement(phraseElement, complement);
}
return phraseElement;
}
/**
* A helper method for setting the complement of a phrase.
*
* @param phraseElement
* the created element representing this phrase.
* @param complement
* the complement to be added.
*/
private void setComplement(PhraseElement phraseElement, Object complement) {
NLGElement complementElement = createNLGElement(complement);
phraseElement.addComplement(complementElement);
}
/**
* this method creates an NLGElement from an object If object is null,
* return null If the object is already an NLGElement, it is returned
* unchanged Exception: if it is an InflectedWordElement, return underlying
* WordElement If it is a String which matches a lexicon entry or pronoun,
* the relevant WordElement is returned If it is a different String, a
* wordElement is created if the string is a single word Otherwise a
* StringElement is returned Otherwise throw an exception
*
* @param element
* - object to look up
* @param category
* - default lexical category of object
* @return NLGelement
*/
public NLGElement createNLGElement(Object element, LexicalCategory category) {
if(element == null)
return null;
// InflectedWordElement - return underlying word
else if(element instanceof InflectedWordElement)
return ((InflectedWordElement) element).getBaseWord();
// StringElement - look up in lexicon if it is a word
// otherwise return element
else if(element instanceof StringElement) {
if(stringIsWord(((StringElement) element).getRealisation(), category))
return createWord(((StringElement) element).getRealisation(), category);
else
return (StringElement) element;
}
// other NLGElement - return element
else if(element instanceof NLGElement)
return (NLGElement) element;
// String - look up in lexicon if a word, otherwise return StringElement
else if(element instanceof String) {
if(stringIsWord((String) element, category))
return createWord(element, category);
else
return new StringElement((String) element);
}
throw new IllegalArgumentException(element.toString() + " is not a valid type");
}
/**
* return true if string is a word
*
* @param string
* @param category
* @return
*/
private boolean stringIsWord(String string, LexicalCategory category) {
return lexicon != null
&& (lexicon.hasWord(string, category) || PRONOUNS.contains(string) || (string.matches(WORD_REGEX)));
}
/**
* create an NLGElement from the element, no default lexical category
*
* @param element
* @return NLGelement
*/
public NLGElement createNLGElement(Object element) {
return createNLGElement(element, LexicalCategory.ANY);
}
/**
* Creates a blank noun phrase with no subject or specifier.
*
* @return a <code>NPPhraseSpec</code> representing this phrase.
*/
public NPPhraseSpec createNounPhrase() {
return createNounPhrase(null, null, null);
}
/**
* Creates a noun phrase with the given subject but no specifier.
*
* @param noun
* the subject of the phrase.
* @return a <code>NPPhraseSpec</code> representing this phrase.
*/
public NPPhraseSpec createNounPhrase(Object noun) {
if(noun instanceof NPPhraseSpec)
return (NPPhraseSpec) noun;
else
return createNounPhrase(null, null, noun);
}
/**
* Creates a noun phrase with the given specifier and subject.
*
* @param specifier
* the specifier or determiner for the noun phrase.
* @param noun
* the subject of the phrase.
* @return a <code>NPPhraseSpec</code> representing this phrase.
*/
public NPPhraseSpec createNounPhrase(Object specifier, Object noun) {
if(noun instanceof NPPhraseSpec)
return (NPPhraseSpec) noun;
NPPhraseSpec phraseElement = new NPPhraseSpec(this);
NLGElement nounElement = createNLGElement(noun, LexicalCategory.NOUN);
setPhraseHead(phraseElement, nounElement);
if(specifier != null)
phraseElement.setSpecifier(specifier);
return phraseElement;
}
/**
* Creates a noun phrase in the format of [number+classifier+noun],
* which is actually a number phrase. It is equivalent to the
* [(definite/indefinite article)+(singular/plural noun)] in
* English.
*
* Adapation for Chinese has been done. Changes:
* 1. replace the specifier with the head of number phrases
* 2. leave the work of adding determiner for other structure
*
* @param numeral
* the number for the noun phrase
* @param classifier
* the classifier for the noun phrase.
* @param noun
* the subject of the phrase.
* @return a <code>NPPhraseSpec</code> representing this phrase.
*/
public NPPhraseSpec createNounPhrase(Object numeral, Object classifier, Object noun) {
if(noun instanceof NPPhraseSpec)
return (NPPhraseSpec) noun;
NPPhraseSpec phraseElement = new NPPhraseSpec(this);
NLGElement nounElement = createNLGElement(noun, LexicalCategory.NOUN);
setPhraseHead(phraseElement, nounElement);
if (numeral instanceof NLGElement) {
((NLGElement) numeral).setCategory(LexicalCategory.NUMERAL);
phraseElement.addSpecifier((NLGElement) numeral);
} else {
NLGElement numeralElement = createWord(numeral, LexicalCategory.NUMERAL);
phraseElement.addSpecifier(numeralElement);
}
if (classifier instanceof NLGElement) {
((NLGElement) classifier).setCategory(LexicalCategory.CLASSIFIER);
phraseElement.addSpecifier((NLGElement) numeral);
} else {
NLGElement classifierElement = createWord(classifier, LexicalCategory.CLASSIFIER);
phraseElement.addSpecifier(classifierElement);
}
return phraseElement;
}
/**
* A helper method to set the head feature of the phrase.
*
* @param phraseElement
* the phrase element.
* @param headElement
* the head element.
*/
private void setPhraseHead(PhraseElement phraseElement, NLGElement headElement) {
if(headElement != null) {
phraseElement.setHead(headElement);
headElement.setParent(phraseElement);
} else {
phraseElement.setFeature(Feature.ADJECTIVE_ORDERING, true);
phraseElement.setFeature(Feature.SPECIFIER_ORDERING, true);
}
}
/**
* Creates a blank adjective phrase with no base adjective set.
*
* @return a <code>AdjPhraseSpec</code> representing this phrase.
*/
public AdjPhraseSpec createAdjectivePhrase() {
return createAdjectivePhrase(null);
}
/**
* Creates an adjective phrase wrapping the given adjective.
*
* @param adjective
* the main adjective for this phrase.
* @return a <code>AdjPhraseSpec</code> representing this phrase.
*/
public AdjPhraseSpec createAdjectivePhrase(Object adjective) {
AdjPhraseSpec phraseElement = new AdjPhraseSpec(this);
NLGElement adjectiveElement = createNLGElement(adjective, LexicalCategory.ADJECTIVE);
setPhraseHead(phraseElement, adjectiveElement);
return phraseElement;
}
/**
* Creates a blank verb phrase with no main verb.
*
* @return a <code>VPPhraseSpec</code> representing this phrase.
*/
public VPPhraseSpec createVerbPhrase() {
return createVerbPhrase(null);
}
/**
* Creates a verb phrase wrapping the main verb given. If a
* <code>String</code> is passed in then some parsing is done to see if the
* verb contains a particle, for example <em>fall down</em>. The first word
* is taken to be the verb while all other words are assumed to form the
* particle.
*
* @param verb
* the verb to be wrapped.
* @return a <code>VPPhraseSpec</code> representing this phrase.
*/
public VPPhraseSpec createVerbPhrase(Object verb) {
VPPhraseSpec phraseElement = new VPPhraseSpec(this);
phraseElement.setVerb(verb);
setPhraseHead(phraseElement, phraseElement.getVerb());
return phraseElement;
}
/**
* Creates a blank adverb phrase that has no adverb.
*
* @return a <code>AdvPhraseSpec</code> representing this phrase.
*/
public AdvPhraseSpec createAdverbPhrase() {
return createAdverbPhrase(null);
}
/**
* Creates an adverb phrase wrapping the given adverb.
*
* @param adverb
* the adverb for this phrase.
* @return a <code>AdvPhraseSpec</code> representing this phrase.
*/
public AdvPhraseSpec createAdverbPhrase(String adverb) {
AdvPhraseSpec phraseElement = new AdvPhraseSpec(this);
NLGElement adverbElement = createNLGElement(adverb, LexicalCategory.ADVERB);
setPhraseHead(phraseElement, adverbElement);
return phraseElement;
}
/**
* Creates a blank clause with no subject, verb or objects.
*
* @return a <code>SPhraseSpec</code> representing this phrase.
*/
public SPhraseSpec createClause() {
return createClause(null, null, null);
}
/**
* Creates a clause with the given subject and verb but no objects.
*
* @param subject
* the subject for the clause as a <code>NLGElement</code> or
* <code>String</code>. This forms a noun phrase.
* @param phrase
* the verb for the clause as a <code>NLGElement</code> or
* <code>String</code>. This forms a verb phrase.
* @return a <code>SPhraseSpec</code> representing this phrase.
*/
public SPhraseSpec createClause(Object subject, Object phrase) {
if (((NLGElement) phrase).isA(LexicalCategory.VERB) || ((NLGElement) phrase).isA(PhraseCategory.VERB_PHRASE)) {
return createClause(subject, phrase, null);
} else {
return createClause(subject, null, phrase);
}
}
/**
* Creates a clause with the given subject, verb or verb phrase and direct
* object but no indirect object.
*
* @param subject
* the subject for the clause as a <code>NLGElement</code> or
* <code>String</code>. This forms a noun phrase.
* @param verb
* the verb for the clause as a <code>NLGElement</code> or
* <code>String</code>. This forms a verb phrase.
* @param directObject
* the direct object for the clause as a <code>NLGElement</code>
* or <code>String</code>. This forms a complement for the
* clause.
* @return a <code>SPhraseSpec</code> representing this phrase.
*/
public SPhraseSpec createClause(Object subject, Object verb, Object directObject) {
SPhraseSpec phraseElement = new SPhraseSpec(this);
if(verb != null) {
// AG: fix here: check if "verb" is a VPPhraseSpec or a Verb
if(verb instanceof PhraseElement) {
phraseElement.setVerbPhrase((PhraseElement) verb);
} else {
phraseElement.setVerb(verb);
}
}
if(subject != null)
phraseElement.setSubject(subject);
if(directObject != null) {
phraseElement.setObject(directObject);
}
return phraseElement;
}
/* *//**
* A helper method to set the verb phrase for a clause.
*
* @param baseForm
* the base form of the clause.
* @param verbPhrase
* the verb phrase to be used in the clause.
* @param phraseElement
* the current representation of the clause.
*/
/*
* private void setVerbPhrase(StringBuffer baseForm, NLGElement verbPhrase,
* PhraseElement phraseElement) { if (baseForm.length() > 0) {
* baseForm.append(' '); }
* baseForm.append(verbPhrase.getFeatureAsString(Feature.BASE_FORM));
* phraseElement.setFeature(Feature.VERB_PHRASE, verbPhrase);
* verbPhrase.setParent(phraseElement);
* verbPhrase.setFeature(Feature.DISCOURSE_FUNCTION,
* DiscourseFunction.VERB_PHRASE); if
* (phraseElement.hasFeature(Feature.GENDER)) {
* verbPhrase.setFeature(Feature.GENDER, phraseElement
* .getFeature(Feature.GENDER)); } if
* (phraseElement.hasFeature(Feature.NUMBER)) {
* verbPhrase.setFeature(Feature.NUMBER, phraseElement
* .getFeature(Feature.NUMBER)); } if
* (phraseElement.hasFeature(Feature.PERSON)) {
* verbPhrase.setFeature(Feature.PERSON, phraseElement
* .getFeature(Feature.PERSON)); } }
*//**
* A helper method to add the direct object to the clause.
*
* @param baseForm
* the base form for the clause.
* @param directObject
* the direct object to be added.
* @param phraseElement
* the current representation of this clause.
* @param function
* the discourse function for this object.
*/
/*
* private void setObject(StringBuffer baseForm, Object object,
* PhraseElement phraseElement, DiscourseFunction function) { if
* (baseForm.length() > 0) { baseForm.append(' '); } if (object instanceof
* NLGElement) { phraseElement.addComplement((NLGElement) object);
* baseForm.append(((NLGElement) object)
* .getFeatureAsString(Feature.BASE_FORM));
*
* ((NLGElement) object).setFeature(Feature.DISCOURSE_FUNCTION, function);
*
* if (((NLGElement) object).hasFeature(Feature.NUMBER)) {
* phraseElement.setFeature(Feature.NUMBER, ((NLGElement) object)
* .getFeature(Feature.NUMBER)); } } else if (object instanceof String) {
* NLGElement complementElement = createNounPhrase(object);
* phraseElement.addComplement(complementElement);
* complementElement.setFeature(Feature.DISCOURSE_FUNCTION, function);
* baseForm.append((String) object); } }
*/
/* *//**
* A helper method that sets the subjects on a clause.
*
* @param phraseElement
* the element representing the clause.
* @param subjectPhrase
* the subject phrase for the clause.
* @param baseForm
* the base form for the clause.
*/
/*
* private void setPhraseSubjects(PhraseElement phraseElement, NLGElement
* subjectPhrase, StringBuffer baseForm) {
* subjectPhrase.setParent(phraseElement); List<NLGElement> allSubjects =
* new ArrayList<NLGElement>(); allSubjects.add(subjectPhrase);
* phraseElement.setFeature(Feature.SUBJECTS, allSubjects);
* baseForm.append(subjectPhrase.getFeatureAsString(Feature.BASE_FORM));
* subjectPhrase.setFeature(Feature.DISCOURSE_FUNCTION,
* DiscourseFunction.SUBJECT);
*
* if (subjectPhrase.hasFeature(Feature.GENDER)) {
* phraseElement.setFeature(Feature.GENDER, subjectPhrase
* .getFeature(Feature.GENDER)); } if
* (subjectPhrase.hasFeature(Feature.NUMBER)) {
* phraseElement.setFeature(Feature.NUMBER, subjectPhrase
* .getFeature(Feature.NUMBER));
*
* } if (subjectPhrase.hasFeature(Feature.PERSON)) {
* phraseElement.setFeature(Feature.PERSON, subjectPhrase
* .getFeature(Feature.PERSON)); } }
*/
/**
* Creates a blank canned text phrase with no text.
*
* @return a <code>PhraseElement</code> representing this phrase.
*/
public NLGElement createStringElement() {
return createStringElement(null);
}
/**
* Creates a canned text phrase with the given text.
*
* @param text
* the canned text.
* @return a <code>PhraseElement</code> representing this phrase.
*/
public NLGElement createStringElement(String text) {
return new StringElement(text);
}
/**
* Creates a new (empty) coordinated phrase
*
* @return empty <code>CoordinatedPhraseElement</code>
*/
public CoordinatedPhraseElement createCoordinatedPhrase() {
return new CoordinatedPhraseElement();
}
/**
* Creates a new coordinated phrase with two elements (initially)
*
* @param coord1
* - first phrase to be coordinated
* @param coord2
* = second phrase to be coordinated
* @return <code>CoordinatedPhraseElement</code> for the two given elements
*/
public CoordinatedPhraseElement createCoordinatedPhrase(Object coord1, Object coord2) {
return new CoordinatedPhraseElement(coord1, coord2);
}
/***********************************************************************************
* Document level stuff
***********************************************************************************/
/**
* Creates a new document element with no title.
*
* @return a <code>DocumentElement</code>
*/
public DocumentElement createDocument() {
return createDocument(null);
}
/**
* Creates a new document element with the given title.
*
* @param title
* the title for this element.
* @return a <code>DocumentElement</code>.
*/
public DocumentElement createDocument(String title) {
return new DocumentElement(DocumentCategory.DOCUMENT, title);
}
/**
* Creates a new document element with the given title and adds all of the
* given components in the list
*
* @param title
* the title of this element.
* @param components
* a <code>List</code> of <code>NLGElement</code>s that form the
* components of this element.
* @return a <code>DocumentElement</code>
*/
public DocumentElement createDocument(String title, List<DocumentElement> components) {
DocumentElement document = new DocumentElement(DocumentCategory.DOCUMENT, title);
if(components != null) {
document.addComponents(components);
}
return document;
}
/**
* Creates a new document element with the given title and adds the given
* component.
*
* @param title
* the title for this element.
* @param component
* an <code>NLGElement</code> that becomes the first component of
* this document element.
* @return a <code>DocumentElement</code>
*/
public DocumentElement createDocument(String title, NLGElement component) {
DocumentElement element = new DocumentElement(DocumentCategory.DOCUMENT, title);
if(component != null) {
element.addComponent(component);
}
return element;
}
/**
* Creates a new list element with no components.
*
* @return a <code>DocumentElement</code> representing the list.
*/
public DocumentElement createList() {
return new DocumentElement(DocumentCategory.LIST, null);
}
/**
* Creates a new list element and adds all of the given components in the
* list
*
* @param textComponents
* a <code>List</code> of <code>NLGElement</code>s that form the
* components of this element.
* @return a <code>DocumentElement</code> representing the list.
*/
public DocumentElement createList(List<DocumentElement> textComponents) {
DocumentElement list = new DocumentElement(DocumentCategory.LIST, null);
list.addComponents(textComponents);
return list;
}
/**
* Creates a new section element with the given title and adds the given
* component.
*
* @param component
* an <code>NLGElement</code> that becomes the first component of
* this document element.
* @return a <code>DocumentElement</code> representing the section.
*/
public DocumentElement createList(NLGElement component) {
DocumentElement list = new DocumentElement(DocumentCategory.LIST, null);
list.addComponent(component);
return list;
}
/**
* Creates a new enumerated list element with no components.
*
* @return a <code>DocumentElement</code> representing the list.
* @author Rodrigo de Oliveira - Data2Text Ltd
*/
public DocumentElement createEnumeratedList() {
return new DocumentElement(DocumentCategory.ENUMERATED_LIST, null);
}
/**
* Creates a new enumerated list element and adds all of the given components in the
* list
*
* @param textComponents
* a <code>List</code> of <code>NLGElement</code>s that form the
* components of this element.
* @return a <code>DocumentElement</code> representing the list.
* @author Rodrigo de Oliveira - Data2Text Ltd
*/
public DocumentElement createEnumeratedList(List<DocumentElement> textComponents) {
DocumentElement list = new DocumentElement(DocumentCategory.ENUMERATED_LIST, null);
list.addComponents(textComponents);
return list;
}
/**
* Creates a new section element with the given title and adds the given
* component.
*
* @param component
* an <code>NLGElement</code> that becomes the first component of
* this document element.
* @return a <code>DocumentElement</code> representing the section.
* @author Rodrigo de Oliveira - Data2Text Ltd
*/
public DocumentElement createEnumeratedList(NLGElement component) {
DocumentElement list = new DocumentElement(DocumentCategory.ENUMERATED_LIST, null);
list.addComponent(component);
return list;
}
/**
* Creates a list item for adding to a list element.
*
* @return a <code>DocumentElement</code> representing the list item.
*/
public DocumentElement createListItem() {
return new DocumentElement(DocumentCategory.LIST_ITEM, null);
}
/**
* Creates a list item for adding to a list element. The list item has the
* given component.
*
* @return a <code>DocumentElement</code> representing the list item.
*/
public DocumentElement createListItem(NLGElement component) {
DocumentElement listItem = new DocumentElement(DocumentCategory.LIST_ITEM, null);
listItem.addComponent(component);
return listItem;
}
/**
* Creates a new paragraph element with no components.
*
* @return a <code>DocumentElement</code> representing this paragraph
*/
public DocumentElement createParagraph() {
return new DocumentElement(DocumentCategory.PARAGRAPH, null);
}
/**
* Creates a new paragraph element and adds all of the given components in
* the list
*
* @param components
* a <code>List</code> of <code>NLGElement</code>s that form the
* components of this element.
* @return a <code>DocumentElement</code> representing this paragraph
*/
public DocumentElement createParagraph(List<DocumentElement> components) {
DocumentElement paragraph = new DocumentElement(DocumentCategory.PARAGRAPH, null);
if(components != null) {
paragraph.addComponents(components);
}
return paragraph;
}
/**
* Creates a new paragraph element and adds the given component
*
* @param component
* an <code>NLGElement</code> that becomes the first component of
* this document element.
* @return a <code>DocumentElement</code> representing this paragraph
*/
public DocumentElement createParagraph(NLGElement component) {
DocumentElement paragraph = new DocumentElement(DocumentCategory.PARAGRAPH, null);
if(component != null) {
paragraph.addComponent(component);
}
return paragraph;
}
/**
* Creates a new section element.
*
* @return a <code>DocumentElement</code> representing the section.
*/
public DocumentElement createSection() {
return new DocumentElement(DocumentCategory.SECTION, null);
}
/**
* Creates a new section element with the given title.
*
* @param title
* the title of the section.
* @return a <code>DocumentElement</code> representing the section.
*/
public DocumentElement createSection(String title) {
return new DocumentElement(DocumentCategory.SECTION, title);
}
/**
* Creates a new section element with the given title and adds all of the
* given components in the list
*
* @param title
* the title of this element.
* @param components
* a <code>List</code> of <code>NLGElement</code>s that form the
* components of this element.
* @return a <code>DocumentElement</code> representing the section.
*/
public DocumentElement createSection(String title, List<DocumentElement> components) {
DocumentElement section = new DocumentElement(DocumentCategory.SECTION, title);
if(components != null) {
section.addComponents(components);
}
return section;
}
/**
* Creates a new section element with the given title and adds the given
* component.
*
* @param title
* the title for this element.
* @param component
* an <code>NLGElement</code> that becomes the first component of
* this document element.
* @return a <code>DocumentElement</code> representing the section.
*/
public DocumentElement createSection(String title, NLGElement component) {
DocumentElement section = new DocumentElement(DocumentCategory.SECTION, title);
if(component != null) {
section.addComponent(component);
}
return section;
}
/**
* Creates a new sentence element with no components.
*
* @return a <code>DocumentElement</code> representing this sentence
*/
public DocumentElement createSentence() {
return new DocumentElement(DocumentCategory.SENTENCE, null);
}
/**
* Creates a new sentence element and adds all of the given components.
*
* @param components
* a <code>List</code> of <code>NLGElement</code>s that form the
* components of this element.
* @return a <code>DocumentElement</code> representing this sentence
*/
public DocumentElement createSentence(List<NLGElement> components) {
DocumentElement sentence = new DocumentElement(DocumentCategory.SENTENCE, null);
sentence.addComponents(components);
return sentence;
}
/**
* Creates a new sentence element
*
* @param components
* an <code>NLGElement</code> that becomes the first component of
* this document element.
* @return a <code>DocumentElement</code> representing this sentence
*/
public DocumentElement createSentence(NLGElement components) {
DocumentElement sentence = new DocumentElement(DocumentCategory.SENTENCE, null);
sentence.addComponent(components);
return sentence;
}
/**
* Creates a sentence with the given subject and verb. The phrase factory is
* used to construct a clause that then forms the components of the
* sentence.
*
* @param subject
* the subject of the sentence.
* @param verb
* the verb of the sentence.
* @return a <code>DocumentElement</code> representing this sentence
*/
public DocumentElement createSentence(Object subject, Object verb) {
return createSentence(subject, verb, null);
}
/**
* Creates a sentence with the given subject, verb and direct object. The
* phrase factory is used to construct a clause that then forms the
* components of the sentence.
*
* @param subject
* the subject of the sentence.
* @param verb
* the verb of the sentence.
* @param complement
* the object of the sentence.
* @return a <code>DocumentElement</code> representing this sentence
*/
public DocumentElement createSentence(Object subject, Object verb, Object complement) {
DocumentElement sentence = new DocumentElement(DocumentCategory.SENTENCE, null);
sentence.addComponent(createClause(subject, verb, complement));
return sentence;
}
/**
* Creates a new sentence with the given canned text. The canned text is
* used to form a canned phrase (from the phrase factory) which is then
* added as the component to sentence element.
*
* @param cannedSentence
* the canned text as a <code>String</code>.
* @return a <code>DocumentElement</code> representing this sentence
*/
public DocumentElement createSentence(String cannedSentence) {
DocumentElement sentence = new DocumentElement(DocumentCategory.SENTENCE, null);
if(cannedSentence != null) {
sentence.addComponent(createStringElement(cannedSentence));
}
return sentence;
}
}
| a-quei/simplenlg-zh | main/simplenlg/framework/NLGFactory.java |
1,460 | import java.nio.ByteBuffer;
import java.util.TreeMap;
/**
* 线程不安全: ----> 有负数
*
*
*/
public class unsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station, "我").start();
new Thread(station,"你们").start();
new Thread(station, "黄牛").start();
}
}
class BuyTicket implements Runnable{
private int ticketNums = 10;
boolean flag = true; // 外部停止方式
@Override
public void run() {
// buy ticket
while (flag) {
try {
Thread.sleep(1000);
buy();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
// private void buy() throws InterruptedException { // 不安全线程
// 同步方法
// 锁的是this
private synchronized void buy() throws InterruptedException { // 修改为安全线程
// 判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
// 模拟延时
// Thread.sleep(100000);
// 买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
} | DonkeyBoy001/java-thread- | unsafeBuyTicket.java |
1,462 | package com.jhl.admin.service;
import com.jhl.admin.VO.UserVO;
import com.jhl.admin.cache.DefendBruteForceAttackUser;
import com.jhl.admin.model.Account;
import com.jhl.admin.model.User;
import com.jhl.admin.repository.UserRepository;
import com.jhl.admin.util.Validator;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
@Autowired
AccountService accountService;
@Autowired
EmailService emailService;
@Autowired
StatService StatService;
@Autowired
DefendBruteForceAttackUser defendBruteForceAttackUser;
public void reg(User user) {
Validator.isNotNull(user);
if (!emailService.verifyCode(user.getEmail(), user.getVCode())) {
throw new IllegalArgumentException("验证码错误");
}
adminReg(user);
}
public void adminReg(User user) {
User exist = userRepository.findOne(Example.of(User.builder().email(user.getEmail()).build())).orElse(null);
if (exist != null) {
throw new RuntimeException("已经存在账号,如忘记密码请找回");
}
create(user);
Account account = Account.builder().userId(user.getId()).build();
accountService.create(account);
StatService.createOrGetStat(account);
}
public void changePassword(User user) {
Validator.isNotNull(user);
if (!emailService.verifyCode(user.getEmail(), user.getVCode())) {
throw new IllegalArgumentException("验证码错误");
}
User dbUser = userRepository.findOne(Example.of(User.builder().email(user.getEmail()).build())).orElse(null);
Validator.isNotNull(user.getPassword());
if (dbUser == null) {
throw new NullPointerException("用户不存在");
}
User newUser = User.builder().password(encodePassword(user.getPassword()))
.build();
newUser.setId(dbUser.getId());
userRepository.save(newUser);
//删除访问限制
defendBruteForceAttackUser.rmCache(user.getEmail());
}
/**
* @param userId
* @param oldPw 旧密码
* @param newPw 新你们
*/
public void changePassword(Integer userId, String oldPw, String newPw) {
Validator.isNotNull(userId);
Validator.isNotNull(oldPw);
Validator.isNotNull(newPw);
User user = userRepository.findById(userId).orElse(null);
if (user == null) {
throw new NullPointerException("用户不存在");
}
String password = user.getPassword();
if (!encodePassword(oldPw).equals(password)) throw new RuntimeException("旧密码不正确");
user.setPassword(encodePassword(newPw));
userRepository.save(user);
}
public void create(User user) {
String password = user.getPassword();
String digestPW = DigestUtils.md5Hex(password);
user.setPassword(digestPW);
if (user.getStatus() == null) user.setStatus(1);
userRepository.save(user);
}
public User login(UserVO user) {
Validator.isNotNull(user);
String email = user.getEmail();
Validator.isNotNull(email, "email为空");
String password = user.getPassword();
Validator.isNotNull(password, "密码为空");
AtomicInteger tryCount = defendBruteForceAttackUser.getCache(email);
if (tryCount != null && tryCount.get() > 4) throw new RuntimeException("为了你的安全,账号已经被锁定,请在一个小时后重试/或者修改密码");
Example<User> userExample = Example.of(User.builder().email(StringUtils.trim(email))
.password(StringUtils.trim(password)).build());
User dbUser = userRepository.findOne(userExample).orElse(null);
if (dbUser == null || dbUser.getId() == null) {
if (tryCount == null) {
tryCount = new AtomicInteger(1);
defendBruteForceAttackUser.setCache(email, tryCount);
} else {
tryCount.addAndGet(1);
}
throw new IllegalArgumentException("账号/密码错误");
}
if (dbUser.getStatus() != 1) throw new RuntimeException("账号已经禁用");
dbUser.setPassword(null);
defendBruteForceAttackUser.rmCache(email);
return dbUser;
}
public User get(Integer id) {
return userRepository.findById(id).orElse(null);
}
public Map<Integer, User> getUserMapBy(Iterable<Integer> ids) {
Map<Integer, User> userMap = new HashMap<>();
if (ids == null) return userMap;
final List<User> regUsers = userRepository.findAllById(ids);
regUsers.forEach(user1 -> userMap.put(user1.getId(), user1));
return userMap;
}
public UserVO getOne(User user) {
user.setStatus(1);
Optional<User> one = userRepository.findOne(Example.of(user));
if (!one.isPresent()) return null;
UserVO userVO = one.get().toVO(UserVO.class);
userVO.setPassword(null);
return userVO;
}
public User getOneByAdmin(User user) {
user.setStatus(1);
Optional<User> one = userRepository.findOne(Example.of(user));
return one.orElse(null);
}
public User getUserButRemovePW(
Integer id) {
User user = get(id);
if (user != null)
user.setPassword(null);
return user;
}
public void addRemark(Integer userId, String remark) {
User user = new User();
user.setId(userId);
user.setRemark(remark);
userRepository.save(user);
}
public String encodePassword(String pw) {
return DigestUtils.md5Hex(pw);
}
}
| master-coder-ll/v2ray-web-manager | vpn-admin/src/main/java/com/jhl/admin/service/UserService.java |
1,463 | package com.meiji.toutiao.bean.wenda;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
/**
* Created by Meiji on 2017/5/22.
*/
public class WendaContentBean {
/**
* show_format : {"show_module":1,"font_size":"18","answer_full_context_color":0}
* err_tips :
* err_no : 0
* offset : 10
* candidate_invite_user : []
* module_list : [{"day_icon_url":"http://p3.pstatp.com/origin/1bf50001abbc1c7f8dba","text":"更多问答","icon_type":2,"night_icon_url":"http://p3.pstatp.com/origin/1bf40001abebc0717135","schema":"sslocal://feed?category=question_and_answer&concern_id=6260258266329123329&type=4&name=%E9%97%AE%E7%AD%94&api_param=%7B%22source%22%3A%22question_brow%22%2C%22origin_from%22%3Anull%2C%22enter_from%22%3Anull%7D"}]
* has_more : true
* channel_data : {"open_url":"sslocal://webview?url=https%3A%2F%2Fic.snssdk.com%2Fwenda%2Fv1%2Fwaphome%2Fbrow%2F%3Frecommend_from%3Drecommend_question_brow&title=%E5%A4%B4%E6%9D%A1%E9%97%AE%E7%AD%94","text":"关注问答频道,聊天更有谈资!","pos":3,"button_text":"进入","recommend_image":{"url":"https://p.pstatp.com/origin/159f000460df3e3f850c","url_list":[{"url":"http://p3.pstatp.com/list/r90/13530005a010f7ce835d"},{"url":"http://pb9.pstatp.com/list/r90/13530005a010f7ce835d"},{"url":"http://pb3.pstatp.com/list/r90/13530005a010f7ce835d"}],"uri":"list/r90/13530005a010f7ce835d","height":90,"width":90,"type":1},"type":1}
* question : {"concern_tag_list":[{"concern_id":"6213182495320443393","name":"火车","schema":"sslocal://concern?tab_sname=wenda&api_param=%7B%22wenda_api_param%22%3A%7B%22scope%22%3A%22toutiao_wenda%22%2C%22origin_from%22%3A%22click_headline%22%2C%22parent_enter_from%22%3A%22click_headline%22%2C%22enter_from%22%3A%22question%22%7D%7D&cid=6213182495320443393"}],"can_delete":false,"post_answer_url":"sslocal://wenda_post?qid=6420544946419269889&gd_ext_json=%7B%22enter_type%22%3A%22question_and_answer%22%2C%22ansid%22%3A6422088403512197378%7D&qTitle=%E5%8D%B0%E5%BA%A6%E6%9C%80%E5%BF%AB%E7%9A%84%E5%88%97%E8%BD%A6%E6%97%B6%E9%80%9F160%EF%BC%8C%E5%BD%93%E5%9C%B0%E4%BA%BA%E9%97%AE%E2%80%9C%E4%B8%AD%E5%9B%BD%E7%81%AB%E8%BD%A6%E6%9C%89%E8%BF%99%E4%B9%88%E5%BF%AB%E5%90%97%E2%80%9D%EF%BC%8C%E6%80%8E%E4%B9%88%E5%9B%9E%E7%AD%94%EF%BC%9F","is_follow":false,"nice_ans_count":73,"create_time":1494899612,"normal_ans_count":851,"user":{"user_intro":"","uname":"yuejiao19926","avatar_url":"http://p0.pstatp.com/origin/3795/3033762272","user_id":"6796383301","is_verify":0},"share_data":{"content":"非常推荐!","image_url":"http://p0.pstatp.com/medium/6399/2275149767","share_url":"https://wenda.toutiao.com/m/wapshare/question/brow/?qid=6420544946419269889&","title":"头条问答-印度最快的列车时速160,当地人问\u201c中国火车有这么快吗\u201d,怎么回答?(924个回答)"},"can_edit":false,"show_delete":false,"title":"印度最快的列车时速160,当地人问\u201c中国火车有这么快吗\u201d,怎么回答?","follow_count":497,"content":{"text":"\n","thumb_image_list":[{"url":"http://p9.pstatp.com/list/r640/1dcd000e3ba14e6e61f8","url_list":[{"url":"http://p9.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"},{"url":"http://pb1.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"},{"url":"http://pb3.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"}],"uri":"1dcd000e3ba14e6e61f8","height":379,"width":640,"type":1}],"large_image_list":[{"url":"http://p9.pstatp.com/large/1dcd000e3ba14e6e61f8","url_list":[{"url":"http://p9.pstatp.com/large/1dcd000e3ba14e6e61f8"},{"url":"http://pb1.pstatp.com/large/1dcd000e3ba14e6e61f8"},{"url":"http://pb3.pstatp.com/large/1dcd000e3ba14e6e61f8"}],"uri":"1dcd000e3ba14e6e61f8","height":379,"width":640,"type":1}]},"show_edit":false,"qid":"6420544946419269889","fold_reason":{"open_url":"sslocal://detail?groupid=6293724675596402946","title":"为什么折叠?"}}
* module_count : 1
* question_type : 0
* api_param : {"origin_from": null, "enter_from": null}
* question_header_content_fold_max_count : 1
*/
private ShowFormatBean show_format;
private String err_tips;
private int err_no;
private int offset;
private boolean has_more;
private ChannelDataBean channel_data;
private QuestionBean question;
private int module_count;
private int question_type;
private String api_param;
private int question_header_content_fold_max_count;
private List<?> candidate_invite_user;
private List<ModuleListBean> module_list;
private List<AnsListBean> ans_list;
public ShowFormatBean getShow_format() {
return show_format;
}
public void setShow_format(ShowFormatBean show_format) {
this.show_format = show_format;
}
public String getErr_tips() {
return err_tips;
}
public void setErr_tips(String err_tips) {
this.err_tips = err_tips;
}
public int getErr_no() {
return err_no;
}
public void setErr_no(int err_no) {
this.err_no = err_no;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public boolean isHas_more() {
return has_more;
}
public void setHas_more(boolean has_more) {
this.has_more = has_more;
}
public ChannelDataBean getChannel_data() {
return channel_data;
}
public void setChannel_data(ChannelDataBean channel_data) {
this.channel_data = channel_data;
}
public QuestionBean getQuestion() {
return question;
}
public void setQuestion(QuestionBean question) {
this.question = question;
}
public int getModule_count() {
return module_count;
}
public void setModule_count(int module_count) {
this.module_count = module_count;
}
public int getQuestion_type() {
return question_type;
}
public void setQuestion_type(int question_type) {
this.question_type = question_type;
}
public String getApi_param() {
return api_param;
}
public void setApi_param(String api_param) {
this.api_param = api_param;
}
public int getQuestion_header_content_fold_max_count() {
return question_header_content_fold_max_count;
}
public void setQuestion_header_content_fold_max_count(int question_header_content_fold_max_count) {
this.question_header_content_fold_max_count = question_header_content_fold_max_count;
}
public List<?> getCandidate_invite_user() {
return candidate_invite_user;
}
public void setCandidate_invite_user(List<?> candidate_invite_user) {
this.candidate_invite_user = candidate_invite_user;
}
public List<ModuleListBean> getModule_list() {
return module_list;
}
public void setModule_list(List<ModuleListBean> module_list) {
this.module_list = module_list;
}
public List<AnsListBean> getAns_list() {
return ans_list;
}
public void setAns_list(List<AnsListBean> ans_list) {
this.ans_list = ans_list;
}
public static class ShowFormatBean {
/**
* show_module : 1
* font_size : 18
* answer_full_context_color : 0
*/
private int show_module;
private String font_size;
private int answer_full_context_color;
public int getShow_module() {
return show_module;
}
public void setShow_module(int show_module) {
this.show_module = show_module;
}
public String getFont_size() {
return font_size;
}
public void setFont_size(String font_size) {
this.font_size = font_size;
}
public int getAnswer_full_context_color() {
return answer_full_context_color;
}
public void setAnswer_full_context_color(int answer_full_context_color) {
this.answer_full_context_color = answer_full_context_color;
}
}
public static class ChannelDataBean {
/**
* open_url : sslocal://webview?url=https%3A%2F%2Fic.snssdk.com%2Fwenda%2Fv1%2Fwaphome%2Fbrow%2F%3Frecommend_from%3Drecommend_question_brow&title=%E5%A4%B4%E6%9D%A1%E9%97%AE%E7%AD%94
* text : 关注问答频道,聊天更有谈资!
* pos : 3
* button_text : 进入
* recommend_image : {"url":"https://p.pstatp.com/origin/159f000460df3e3f850c","url_list":[{"url":"http://p3.pstatp.com/list/r90/13530005a010f7ce835d"},{"url":"http://pb9.pstatp.com/list/r90/13530005a010f7ce835d"},{"url":"http://pb3.pstatp.com/list/r90/13530005a010f7ce835d"}],"uri":"list/r90/13530005a010f7ce835d","height":90,"width":90,"type":1}
* type : 1
*/
private String open_url;
private String text;
private int pos;
private String button_text;
private RecommendImageBean recommend_image;
private int type;
public String getOpen_url() {
return open_url;
}
public void setOpen_url(String open_url) {
this.open_url = open_url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getPos() {
return pos;
}
public void setPos(int pos) {
this.pos = pos;
}
public String getButton_text() {
return button_text;
}
public void setButton_text(String button_text) {
this.button_text = button_text;
}
public RecommendImageBean getRecommend_image() {
return recommend_image;
}
public void setRecommend_image(RecommendImageBean recommend_image) {
this.recommend_image = recommend_image;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public static class RecommendImageBean {
/**
* url : https://p.pstatp.com/origin/159f000460df3e3f850c
* url_list : [{"url":"http://p3.pstatp.com/list/r90/13530005a010f7ce835d"},{"url":"http://pb9.pstatp.com/list/r90/13530005a010f7ce835d"},{"url":"http://pb3.pstatp.com/list/r90/13530005a010f7ce835d"}]
* uri : list/r90/13530005a010f7ce835d
* height : 90
* width : 90
* type : 1
*/
private String url;
private String uri;
private int height;
private int width;
private int type;
private List<UrlListBean> url_list;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<UrlListBean> getUrl_list() {
return url_list;
}
public void setUrl_list(List<UrlListBean> url_list) {
this.url_list = url_list;
}
public static class UrlListBean {
/**
* url : http://p3.pstatp.com/list/r90/13530005a010f7ce835d
*/
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
}
public static class QuestionBean {
/**
* concern_tag_list : [{"concern_id":"6213182495320443393","name":"火车","schema":"sslocal://concern?tab_sname=wenda&api_param=%7B%22wenda_api_param%22%3A%7B%22scope%22%3A%22toutiao_wenda%22%2C%22origin_from%22%3A%22click_headline%22%2C%22parent_enter_from%22%3A%22click_headline%22%2C%22enter_from%22%3A%22question%22%7D%7D&cid=6213182495320443393"}]
* can_delete : false
* post_answer_url : sslocal://wenda_post?qid=6420544946419269889&gd_ext_json=%7B%22enter_type%22%3A%22question_and_answer%22%2C%22ansid%22%3A6422088403512197378%7D&qTitle=%E5%8D%B0%E5%BA%A6%E6%9C%80%E5%BF%AB%E7%9A%84%E5%88%97%E8%BD%A6%E6%97%B6%E9%80%9F160%EF%BC%8C%E5%BD%93%E5%9C%B0%E4%BA%BA%E9%97%AE%E2%80%9C%E4%B8%AD%E5%9B%BD%E7%81%AB%E8%BD%A6%E6%9C%89%E8%BF%99%E4%B9%88%E5%BF%AB%E5%90%97%E2%80%9D%EF%BC%8C%E6%80%8E%E4%B9%88%E5%9B%9E%E7%AD%94%EF%BC%9F
* is_follow : false
* nice_ans_count : 73
* create_time : 1494899612
* normal_ans_count : 851
* user : {"user_intro":"","uname":"yuejiao19926","avatar_url":"http://p0.pstatp.com/origin/3795/3033762272","user_id":"6796383301","is_verify":0}
* share_data : {"content":"非常推荐!","image_url":"http://p0.pstatp.com/medium/6399/2275149767","share_url":"https://wenda.toutiao.com/m/wapshare/question/brow/?qid=6420544946419269889&","title":"头条问答-印度最快的列车时速160,当地人问\u201c中国火车有这么快吗\u201d,怎么回答?(924个回答)"}
* can_edit : false
* show_delete : false
* title : 印度最快的列车时速160,当地人问“中国火车有这么快吗”,怎么回答?
* follow_count : 497
* content : {"text":"\n","thumb_image_list":[{"url":"http://p9.pstatp.com/list/r640/1dcd000e3ba14e6e61f8","url_list":[{"url":"http://p9.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"},{"url":"http://pb1.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"},{"url":"http://pb3.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"}],"uri":"1dcd000e3ba14e6e61f8","height":379,"width":640,"type":1}],"large_image_list":[{"url":"http://p9.pstatp.com/large/1dcd000e3ba14e6e61f8","url_list":[{"url":"http://p9.pstatp.com/large/1dcd000e3ba14e6e61f8"},{"url":"http://pb1.pstatp.com/large/1dcd000e3ba14e6e61f8"},{"url":"http://pb3.pstatp.com/large/1dcd000e3ba14e6e61f8"}],"uri":"1dcd000e3ba14e6e61f8","height":379,"width":640,"type":1}]}
* show_edit : false
* qid : 6420544946419269889
* fold_reason : {"open_url":"sslocal://detail?groupid=6293724675596402946","title":"为什么折叠?"}
*/
private boolean can_delete;
private String post_answer_url;
private boolean is_follow;
private int nice_ans_count;
private int create_time;
private int normal_ans_count;
private UserBean user;
private ShareDataBean share_data;
private boolean can_edit;
private boolean show_delete;
private String title;
private int follow_count;
private ContentBean content;
private boolean show_edit;
private String qid;
private FoldReasonBean fold_reason;
private List<ConcernTagListBean> concern_tag_list;
public boolean isCan_delete() {
return can_delete;
}
public void setCan_delete(boolean can_delete) {
this.can_delete = can_delete;
}
public String getPost_answer_url() {
return post_answer_url;
}
public void setPost_answer_url(String post_answer_url) {
this.post_answer_url = post_answer_url;
}
public boolean isIs_follow() {
return is_follow;
}
public void setIs_follow(boolean is_follow) {
this.is_follow = is_follow;
}
public int getNice_ans_count() {
return nice_ans_count;
}
public void setNice_ans_count(int nice_ans_count) {
this.nice_ans_count = nice_ans_count;
}
public int getCreate_time() {
return create_time;
}
public void setCreate_time(int create_time) {
this.create_time = create_time;
}
public int getNormal_ans_count() {
return normal_ans_count;
}
public void setNormal_ans_count(int normal_ans_count) {
this.normal_ans_count = normal_ans_count;
}
public UserBean getUser() {
return user;
}
public void setUser(UserBean user) {
this.user = user;
}
public ShareDataBean getShare_data() {
return share_data;
}
public void setShare_data(ShareDataBean share_data) {
this.share_data = share_data;
}
public boolean isCan_edit() {
return can_edit;
}
public void setCan_edit(boolean can_edit) {
this.can_edit = can_edit;
}
public boolean isShow_delete() {
return show_delete;
}
public void setShow_delete(boolean show_delete) {
this.show_delete = show_delete;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getFollow_count() {
return follow_count;
}
public void setFollow_count(int follow_count) {
this.follow_count = follow_count;
}
public ContentBean getContent() {
return content;
}
public void setContent(ContentBean content) {
this.content = content;
}
public boolean isShow_edit() {
return show_edit;
}
public void setShow_edit(boolean show_edit) {
this.show_edit = show_edit;
}
public String getQid() {
return qid;
}
public void setQid(String qid) {
this.qid = qid;
}
public FoldReasonBean getFold_reason() {
return fold_reason;
}
public void setFold_reason(FoldReasonBean fold_reason) {
this.fold_reason = fold_reason;
}
public List<ConcernTagListBean> getConcern_tag_list() {
return concern_tag_list;
}
public void setConcern_tag_list(List<ConcernTagListBean> concern_tag_list) {
this.concern_tag_list = concern_tag_list;
}
public static class UserBean {
/**
* user_intro :
* uname : yuejiao19926
* avatar_url : http://p0.pstatp.com/origin/3795/3033762272
* user_id : 6796383301
* is_verify : 0
*/
private String user_intro;
private String uname;
private String avatar_url;
private String user_id;
private int is_verify;
public String getUser_intro() {
return user_intro;
}
public void setUser_intro(String user_intro) {
this.user_intro = user_intro;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getAvatar_url() {
return avatar_url;
}
public void setAvatar_url(String avatar_url) {
this.avatar_url = avatar_url;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public int getIs_verify() {
return is_verify;
}
public void setIs_verify(int is_verify) {
this.is_verify = is_verify;
}
}
public static class ShareDataBean {
/**
* content : 非常推荐!
* image_url : http://p0.pstatp.com/medium/6399/2275149767
* share_url : https://wenda.toutiao.com/m/wapshare/question/brow/?qid=6420544946419269889&
* title : 头条问答-印度最快的列车时速160,当地人问“中国火车有这么快吗”,怎么回答?(924个回答)
*/
private String content;
private String image_url;
private String share_url;
private String title;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public String getShare_url() {
return share_url;
}
public void setShare_url(String share_url) {
this.share_url = share_url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public static class ContentBean {
/**
* text :
* <p>
* thumb_image_list : [{"url":"http://p9.pstatp.com/list/r640/1dcd000e3ba14e6e61f8","url_list":[{"url":"http://p9.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"},{"url":"http://pb1.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"},{"url":"http://pb3.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"}],"uri":"1dcd000e3ba14e6e61f8","height":379,"width":640,"type":1}]
* large_image_list : [{"url":"http://p9.pstatp.com/large/1dcd000e3ba14e6e61f8","url_list":[{"url":"http://p9.pstatp.com/large/1dcd000e3ba14e6e61f8"},{"url":"http://pb1.pstatp.com/large/1dcd000e3ba14e6e61f8"},{"url":"http://pb3.pstatp.com/large/1dcd000e3ba14e6e61f8"}],"uri":"1dcd000e3ba14e6e61f8","height":379,"width":640,"type":1}]
*/
private String text;
private List<ThumbImageListBean> thumb_image_list;
private List<LargeImageListBean> large_image_list;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<ThumbImageListBean> getThumb_image_list() {
return thumb_image_list;
}
public void setThumb_image_list(List<ThumbImageListBean> thumb_image_list) {
this.thumb_image_list = thumb_image_list;
}
public List<LargeImageListBean> getLarge_image_list() {
return large_image_list;
}
public void setLarge_image_list(List<LargeImageListBean> large_image_list) {
this.large_image_list = large_image_list;
}
public static class ThumbImageListBean {
/**
* url : http://p9.pstatp.com/list/r640/1dcd000e3ba14e6e61f8
* url_list : [{"url":"http://p9.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"},{"url":"http://pb1.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"},{"url":"http://pb3.pstatp.com/list/r640/1dcd000e3ba14e6e61f8"}]
* uri : 1dcd000e3ba14e6e61f8
* height : 379
* width : 640
* type : 1
*/
private String url;
private String uri;
private int height;
private int width;
private int type;
private List<UrlListBeanX> url_list;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<UrlListBeanX> getUrl_list() {
return url_list;
}
public void setUrl_list(List<UrlListBeanX> url_list) {
this.url_list = url_list;
}
public static class UrlListBeanX {
/**
* url : http://p9.pstatp.com/list/r640/1dcd000e3ba14e6e61f8
*/
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
public static class LargeImageListBean {
/**
* url : http://p9.pstatp.com/large/1dcd000e3ba14e6e61f8
* url_list : [{"url":"http://p9.pstatp.com/large/1dcd000e3ba14e6e61f8"},{"url":"http://pb1.pstatp.com/large/1dcd000e3ba14e6e61f8"},{"url":"http://pb3.pstatp.com/large/1dcd000e3ba14e6e61f8"}]
* uri : 1dcd000e3ba14e6e61f8
* height : 379
* width : 640
* type : 1
*/
private String url;
private String uri;
private int height;
private int width;
private int type;
private List<UrlListBeanXX> url_list;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<UrlListBeanXX> getUrl_list() {
return url_list;
}
public void setUrl_list(List<UrlListBeanXX> url_list) {
this.url_list = url_list;
}
public static class UrlListBeanXX {
/**
* url : http://p9.pstatp.com/large/1dcd000e3ba14e6e61f8
*/
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
}
public static class FoldReasonBean {
/**
* open_url : sslocal://detail?groupid=6293724675596402946
* title : 为什么折叠?
*/
private String open_url;
private String title;
public String getOpen_url() {
return open_url;
}
public void setOpen_url(String open_url) {
this.open_url = open_url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public static class ConcernTagListBean {
/**
* concern_id : 6213182495320443393
* name : 火车
* schema : sslocal://concern?tab_sname=wenda&api_param=%7B%22wenda_api_param%22%3A%7B%22scope%22%3A%22toutiao_wenda%22%2C%22origin_from%22%3A%22click_headline%22%2C%22parent_enter_from%22%3A%22click_headline%22%2C%22enter_from%22%3A%22question%22%7D%7D&cid=6213182495320443393
*/
private String concern_id;
private String name;
private String schema;
public String getConcern_id() {
return concern_id;
}
public void setConcern_id(String concern_id) {
this.concern_id = concern_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
}
}
public static class ModuleListBean {
/**
* day_icon_url : http://p3.pstatp.com/origin/1bf50001abbc1c7f8dba
* text : 更多问答
* icon_type : 2
* night_icon_url : http://p3.pstatp.com/origin/1bf40001abebc0717135
* schema : sslocal://feed?category=question_and_answer&concern_id=6260258266329123329&type=4&name=%E9%97%AE%E7%AD%94&api_param=%7B%22source%22%3A%22question_brow%22%2C%22origin_from%22%3Anull%2C%22enter_from%22%3Anull%7D
*/
private String day_icon_url;
private String text;
private int icon_type;
private String night_icon_url;
private String schema;
public String getDay_icon_url() {
return day_icon_url;
}
public void setDay_icon_url(String day_icon_url) {
this.day_icon_url = day_icon_url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getIcon_type() {
return icon_type;
}
public void setIcon_type(int icon_type) {
this.icon_type = icon_type;
}
public String getNight_icon_url() {
return night_icon_url;
}
public void setNight_icon_url(String night_icon_url) {
this.night_icon_url = night_icon_url;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
}
public static class AnsListBean implements Parcelable {
public static final Creator<AnsListBean> CREATOR = new Creator<AnsListBean>() {
@Override
public AnsListBean createFromParcel(Parcel in) {
return new AnsListBean(in);
}
@Override
public AnsListBean[] newArray(int size) {
return new AnsListBean[size];
}
};
/**
* content_abstract : {"text":"我去过印度,觉得印度人有时也太可爱了,在他们眼里,印度几乎就是唯一的,他们接受新事物的能力似乎非常的有限。但真心是想不到,印度居然还是IT大国。去过印度的人通常都会从导游那里知道:从新德里出发到阿格拉的泰姬陵之间的一趟列车,时速最高的时候达到了160公里/每小时,被印度人称为当地最快的火车。因为印度人非常的热情,看到中国游客就会用蹩脚的汉语跟中国人搭讪,甚至会问:\u201c中国有没有这样快的火车呀?\u201d,这让人尴尬不已,不知道如何回答是好。我在想如下回答,如何?----对不起,中国没有时速160的火车,只有时速360的动车。----我们中国的火车坐的人少,拉轻,印度的火车超载了,跑不快,所以中国的火车要快一点。----你们印度人是坐在车外面的,所以感觉很快,我们的高铁是坐里面的,所以感觉不到快。","thumb_image_list":[{"url":"http://p1.pstatp.com/list/r498/216d000c29349bc2648f","url_list":[{"url":"http://p1.pstatp.com/list/r498/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/list/r498/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/list/r498/216d000c29349bc2648f"}],"uri":"list/r498/216d000c29349bc2648f","height":350,"width":498,"type":1}],"large_image_list":[{"url":"http://p1.pstatp.com/large/216d000c29349bc2648f","url_list":[{"url":"http://p1.pstatp.com/large/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/large/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/large/216d000c29349bc2648f"}],"uri":"large/216d000c29349bc2648f","height":350,"width":498,"type":1}],"video_list":[]}
* create_time : 1494936653
* user : {"uname":"媒体人杨壮波的落脚地","avatar_url":"http://p9.pstatp.com/thumb/1787/4062932054","user_id":"3747947486","is_verify":0,"create_time":1419220894,"user_intro":"","user_auth_info":"","schema":"sslocal://profile?uid=3747947486&refer=wenda"}
* share_data : {"content":"我去过印度,觉得印度人有时也太可爱了,在他们眼里,印度几乎就是唯一的,他们接受新事物的能力似乎非常的有限。但真心是想不到,印度居然还是IT大国。去过印度的人通常都会从导游那里知道:从新德里出发到阿格拉的泰姬陵之间的一趟列车,时速最高的时候达到了160公里/每小时,被印度人称为当地最快的火车。因为印度人非常的热情,看到中国游客就会用蹩脚的汉语跟中国人搭讪,甚至会问:\u201c中国有没有这样快的火车呀?\u201d,这让人尴尬不已,不知道如何回答是好。我在想如下回答,如何?----对不起,中国没有时速160的火车,只有时速360的动车。----我们中国的火车坐的人少,拉轻,印度的火车超载了,跑不快,所以中国的火车要快一点。----你们印度人是坐在车外面的,所以感觉很快,我们的高铁是坐里面的,所以感觉不到快。","image_url":"http://p1.pstatp.com/list/r498/216d000c29349bc2648f","share_url":"https://wenda.toutiao.com/m/wapshare/answer/brow/?ansid=6420704033253622018&","title":"头条问答-印度最快的列车时速160,当地人问\u201c中国火车有这么快吗\u201d,怎么回答?"}
* ans_url : https://ic.snssdk.com/wenda/v1/wapanswer/content/?ansid=6420704033253622018
* ansid : 6420704033253622018
* is_show_bury : true
* is_buryed : false
* bury_count : 34
* title :
* digg_count : 566
* is_digg : false
* schema : sslocal://wenda_detail?gd_ext_json=%7B%22ansid%22%3A6420704033253622018%7D&ansid=6420704033253622018&api_param=%7B%22in_offset%22%3A0%2C%22has_more%22%3Atrue%2C%22next_offset%22%3A10%2C%22answer_list%22%3A%5B6420704033253622018%2C6420545734315081985%2C6420999813550047490%2C6420564644980588801%2C6420722026490626306%2C6420724394624041217%2C6420874208393298177%2C6420766146428928258%2C6420914953204531457%2C6422088403512197378%5D%2C%22answer_type%22%3A%22nice_answer%22%7D
*/
private ContentAbstractBean content_abstract;
private int create_time;
private UserBeanX user;
private ShareDataBeanX share_data;
private String ans_url;
private String ansid;
private String qid;
private boolean is_show_bury;
private boolean is_buryed;
private int bury_count;
private String title;
private int digg_count;
private boolean is_digg;
private String schema;
public AnsListBean(Parcel in) {
create_time = in.readInt();
user = in.readParcelable(UserBeanX.class.getClassLoader());
share_data = in.readParcelable(ShareDataBeanX.class.getClassLoader());
ans_url = in.readString();
ansid = in.readString();
qid = in.readString();
is_show_bury = in.readByte() != 0;
is_buryed = in.readByte() != 0;
bury_count = in.readInt();
title = in.readString();
digg_count = in.readInt();
is_digg = in.readByte() != 0;
schema = in.readString();
}
public AnsListBean() {
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
AnsListBean that = (AnsListBean) o;
if (!ans_url.equals(that.ans_url))
return false;
return ansid.equals(that.ansid);
}
@Override
public int hashCode() {
int result = ans_url.hashCode();
result = 31 * result + ansid.hashCode();
return result;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(create_time);
dest.writeParcelable(user, flags);
dest.writeParcelable(share_data, flags);
dest.writeString(ans_url);
dest.writeString(ansid);
dest.writeString(qid);
dest.writeByte((byte) (is_show_bury ? 1 : 0));
dest.writeByte((byte) (is_buryed ? 1 : 0));
dest.writeInt(bury_count);
dest.writeString(title);
dest.writeInt(digg_count);
dest.writeByte((byte) (is_digg ? 1 : 0));
dest.writeString(schema);
}
@Override
public int describeContents() {
return 0;
}
public ContentAbstractBean getContent_abstract() {
return content_abstract;
}
public void setContent_abstract(ContentAbstractBean content_abstract) {
this.content_abstract = content_abstract;
}
public String getQid() {
return qid;
}
public void setQid(String qid) {
this.qid = qid;
}
public int getCreate_time() {
return create_time;
}
public void setCreate_time(int create_time) {
this.create_time = create_time;
}
public UserBeanX getUser() {
return user;
}
public void setUser(UserBeanX user) {
this.user = user;
}
public ShareDataBeanX getShare_data() {
return share_data;
}
public void setShare_data(ShareDataBeanX share_data) {
this.share_data = share_data;
}
public String getAns_url() {
return ans_url;
}
public void setAns_url(String ans_url) {
this.ans_url = ans_url;
}
public String getAnsid() {
return ansid;
}
public void setAnsid(String ansid) {
this.ansid = ansid;
}
public boolean isIs_show_bury() {
return is_show_bury;
}
public void setIs_show_bury(boolean is_show_bury) {
this.is_show_bury = is_show_bury;
}
public boolean isIs_buryed() {
return is_buryed;
}
public void setIs_buryed(boolean is_buryed) {
this.is_buryed = is_buryed;
}
public int getBury_count() {
return bury_count;
}
public void setBury_count(int bury_count) {
this.bury_count = bury_count;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getDigg_count() {
return digg_count;
}
public void setDigg_count(int digg_count) {
this.digg_count = digg_count;
}
public boolean isIs_digg() {
return is_digg;
}
public void setIs_digg(boolean is_digg) {
this.is_digg = is_digg;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public static class ContentAbstractBean {
/**
* text : 我去过印度,觉得印度人有时也太可爱了,在他们眼里,印度几乎就是唯一的,他们接受新事物的能力似乎非常的有限。但真心是想不到,印度居然还是IT大国。去过印度的人通常都会从导游那里知道:从新德里出发到阿格拉的泰姬陵之间的一趟列车,时速最高的时候达到了160公里/每小时,被印度人称为当地最快的火车。因为印度人非常的热情,看到中国游客就会用蹩脚的汉语跟中国人搭讪,甚至会问:“中国有没有这样快的火车呀?”,这让人尴尬不已,不知道如何回答是好。我在想如下回答,如何?----对不起,中国没有时速160的火车,只有时速360的动车。----我们中国的火车坐的人少,拉轻,印度的火车超载了,跑不快,所以中国的火车要快一点。----你们印度人是坐在车外面的,所以感觉很快,我们的高铁是坐里面的,所以感觉不到快。
* thumb_image_list : [{"url":"http://p1.pstatp.com/list/r498/216d000c29349bc2648f","url_list":[{"url":"http://p1.pstatp.com/list/r498/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/list/r498/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/list/r498/216d000c29349bc2648f"}],"uri":"list/r498/216d000c29349bc2648f","height":350,"width":498,"type":1}]
* large_image_list : [{"url":"http://p1.pstatp.com/large/216d000c29349bc2648f","url_list":[{"url":"http://p1.pstatp.com/large/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/large/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/large/216d000c29349bc2648f"}],"uri":"large/216d000c29349bc2648f","height":350,"width":498,"type":1}]
* video_list : []
*/
private String text;
private List<ThumbImageListBeanX> thumb_image_list;
private List<LargeImageListBeanX> large_image_list;
private List<?> video_list;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<ThumbImageListBeanX> getThumb_image_list() {
return thumb_image_list;
}
public void setThumb_image_list(List<ThumbImageListBeanX> thumb_image_list) {
this.thumb_image_list = thumb_image_list;
}
public List<LargeImageListBeanX> getLarge_image_list() {
return large_image_list;
}
public void setLarge_image_list(List<LargeImageListBeanX> large_image_list) {
this.large_image_list = large_image_list;
}
public List<?> getVideo_list() {
return video_list;
}
public void setVideo_list(List<?> video_list) {
this.video_list = video_list;
}
public static class ThumbImageListBeanX {
/**
* url : http://p1.pstatp.com/list/r498/216d000c29349bc2648f
* url_list : [{"url":"http://p1.pstatp.com/list/r498/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/list/r498/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/list/r498/216d000c29349bc2648f"}]
* uri : list/r498/216d000c29349bc2648f
* height : 350
* width : 498
* type : 1
*/
private String url;
private String uri;
private int height;
private int width;
private int type;
private List<UrlListBeanXXX> url_list;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<UrlListBeanXXX> getUrl_list() {
return url_list;
}
public void setUrl_list(List<UrlListBeanXXX> url_list) {
this.url_list = url_list;
}
public static class UrlListBeanXXX {
/**
* url : http://p1.pstatp.com/list/r498/216d000c29349bc2648f
*/
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
public static class LargeImageListBeanX {
/**
* url : http://p1.pstatp.com/large/216d000c29349bc2648f
* url_list : [{"url":"http://p1.pstatp.com/large/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/large/216d000c29349bc2648f"},{"url":"http://pb3.pstatp.com/large/216d000c29349bc2648f"}]
* uri : large/216d000c29349bc2648f
* height : 350
* width : 498
* type : 1
*/
private String url;
private String uri;
private int height;
private int width;
private int type;
private List<UrlListBeanXXXX> url_list;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<UrlListBeanXXXX> getUrl_list() {
return url_list;
}
public void setUrl_list(List<UrlListBeanXXXX> url_list) {
this.url_list = url_list;
}
public static class UrlListBeanXXXX {
/**
* url : http://p1.pstatp.com/large/216d000c29349bc2648f
*/
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
}
public static class UserBeanX implements Parcelable {
public static final Creator<UserBeanX> CREATOR = new Creator<UserBeanX>() {
@Override
public UserBeanX createFromParcel(Parcel in) {
return new UserBeanX(in);
}
@Override
public UserBeanX[] newArray(int size) {
return new UserBeanX[size];
}
};
/**
* uname : 媒体人杨壮波的落脚地
* avatar_url : http://p9.pstatp.com/thumb/1787/4062932054
* user_id : 3747947486
* is_verify : 0
* create_time : 1419220894
* user_intro :
* user_auth_info :
* schema : sslocal://profile?uid=3747947486&refer=wenda
*/
private String uname;
private String avatar_url;
private String user_id;
private int is_verify;
private int create_time;
private String user_intro;
private String user_auth_info;
private String schema;
public UserBeanX(Parcel in) {
uname = in.readString();
avatar_url = in.readString();
user_id = in.readString();
is_verify = in.readInt();
create_time = in.readInt();
user_intro = in.readString();
user_auth_info = in.readString();
schema = in.readString();
}
public UserBeanX() {
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(uname);
dest.writeString(avatar_url);
dest.writeString(user_id);
dest.writeInt(is_verify);
dest.writeInt(create_time);
dest.writeString(user_intro);
dest.writeString(user_auth_info);
dest.writeString(schema);
}
@Override
public int describeContents() {
return 0;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getAvatar_url() {
return avatar_url;
}
public void setAvatar_url(String avatar_url) {
this.avatar_url = avatar_url;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public int getIs_verify() {
return is_verify;
}
public void setIs_verify(int is_verify) {
this.is_verify = is_verify;
}
public int getCreate_time() {
return create_time;
}
public void setCreate_time(int create_time) {
this.create_time = create_time;
}
public String getUser_intro() {
return user_intro;
}
public void setUser_intro(String user_intro) {
this.user_intro = user_intro;
}
public String getUser_auth_info() {
return user_auth_info;
}
public void setUser_auth_info(String user_auth_info) {
this.user_auth_info = user_auth_info;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
}
public static class ShareDataBeanX implements Parcelable {
public static final Creator<ShareDataBeanX> CREATOR = new Creator<ShareDataBeanX>() {
@Override
public ShareDataBeanX createFromParcel(Parcel in) {
return new ShareDataBeanX(in);
}
@Override
public ShareDataBeanX[] newArray(int size) {
return new ShareDataBeanX[size];
}
};
/**
* content : 我去过印度,觉得印度人有时也太可爱了,在他们眼里,印度几乎就是唯一的,他们接受新事物的能力似乎非常的有限。但真心是想不到,印度居然还是IT大国。去过印度的人通常都会从导游那里知道:从新德里出发到阿格拉的泰姬陵之间的一趟列车,时速最高的时候达到了160公里/每小时,被印度人称为当地最快的火车。因为印度人非常的热情,看到中国游客就会用蹩脚的汉语跟中国人搭讪,甚至会问:“中国有没有这样快的火车呀?”,这让人尴尬不已,不知道如何回答是好。我在想如下回答,如何?----对不起,中国没有时速160的火车,只有时速360的动车。----我们中国的火车坐的人少,拉轻,印度的火车超载了,跑不快,所以中国的火车要快一点。----你们印度人是坐在车外面的,所以感觉很快,我们的高铁是坐里面的,所以感觉不到快。
* image_url : http://p1.pstatp.com/list/r498/216d000c29349bc2648f
* share_url : https://wenda.toutiao.com/m/wapshare/answer/brow/?ansid=6420704033253622018&
* title : 头条问答-印度最快的列车时速160,当地人问“中国火车有这么快吗”,怎么回答?
*/
private String content;
private String image_url;
private String share_url;
private String title;
public ShareDataBeanX(Parcel in) {
content = in.readString();
image_url = in.readString();
share_url = in.readString();
title = in.readString();
}
public ShareDataBeanX() {
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(content);
dest.writeString(image_url);
dest.writeString(share_url);
dest.writeString(title);
}
@Override
public int describeContents() {
return 0;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public String getShare_url() {
return share_url;
}
public void setShare_url(String share_url) {
this.share_url = share_url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}
}
| iMeiji/Toutiao | app/src/main/java/com/meiji/toutiao/bean/wenda/WendaContentBean.java |
1,464 | package com.meiji.toutiao.bean.wenda;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by Meiji on 2017/5/21.
*/
public class WendaArticleDataBean {
/**
* cell_type : 36
* extra : {"wenda_video":[],"show_answer":false,"video_large_card":false,"label_style":{"color_type":0,"name":""},"show_video":false,"video_source_name":"","wenda_image":{"three_image_list":[{"url":"http:\/\/p3.pstatp.com\/list\/300x196\/18a2000bcefb11e51664","url_list":[{"url":"http:\/\/p3.pstatp.com\/list\/300x196\/18a2000bcefb11e51664"},{"url":"http:\/\/pb9.pstatp.com\/list\/300x196\/18a2000bcefb11e51664"},{"url":"http:\/\/pb3.pstatp.com\/list\/300x196\/18a2000bcefb11e51664"}],"uri":"list\/300x196\/18a2000bcefb11e51664","height":576,"width":768,"type":1},{"url":"http:\/\/p3.pstatp.com\/list\/300x196\/e580008f01daabc4b83","url_list":[{"url":"http:\/\/p3.pstatp.com\/list\/300x196\/e580008f01daabc4b83"},{"url":"http:\/\/pb9.pstatp.com\/list\/300x196\/e580008f01daabc4b83"},{"url":"http:\/\/pb3.pstatp.com\/list\/300x196\/e580008f01daabc4b83"}],"uri":"list\/300x196\/e580008f01daabc4b83","height":295,"width":440,"type":1},{"url":"http:\/\/p9.pstatp.com\/list\/300x196\/12320005f73e2f519d5c","url_list":[{"url":"http:\/\/p9.pstatp.com\/list\/300x196\/12320005f73e2f519d5c"},{"url":"http:\/\/pb1.pstatp.com\/list\/300x196\/12320005f73e2f519d5c"},{"url":"http:\/\/pb3.pstatp.com\/list\/300x196\/12320005f73e2f519d5c"}],"uri":"list\/300x196\/12320005f73e2f519d5c","height":768,"width":431,"type":1}],"small_image_list":[],"large_image_list":[],"medium_image_list":[]},"schema":"sslocal:\/\/wenda_list?qid=6333792867344974082&gd_ext_json=%7B%22qid%22%3A%226333792867344974082%22%2C%22ansid%22%3A%226334054392425087233%22%2C%22enter_from%22%3A%22click_answer_hot%22%7D&video_auto_play=0&api_param=%7B%22scope%22%3A%22toutiao_wenda%22%2C%22origin_from%22%3A%22native_wenda_home%22%2C%22enter_ansid%22%3A%226334054392425087233%22%2C%22enter_from%22%3A%22answer_hot%22%7D"}
* question : {"status":1,"op_status":0,"qid":6333792867344974082,"nice_ans_count":336,"uname":"","create_time":1474701070,"normal_ans_count":1227,"item_id":0,"user_id":5547793806,"title":"\u4f60\u4eec\u5f53\u5730\u90a3\u4e9b\u6df7\u9ed1\u793e\u4f1a\u7684\u4eba\u73b0\u5728\u90fd\u600e\u4e48\u6837\u4e86\uff1f","content":{"text":"\u6211\u77e5\u9053\u7684\u90fd\u51fa\u53bb\u6253\u5de5\u4e86\uff0c\u6709\u4e9b\u751a\u81f3\u8e72\u8fc7\u51e0\u5e74\u7262\uff0c\u603b\u4e4b\u5c31\u662f\u6ca1\u4ee5\u524d\u90a3\u4e48\u56a3\u5f20\u5f97\u610f\uff0c\u4f60\u4eec\u77e5\u9053\u7684\u5462\uff1f","pic_uri_list":[],"thumb_image_list":[],"large_image_list":[]},"group_id":null}
* behot_time : 1495245397
* cursor : 0
* filter_words : [{"is_selected":false,"id":"8:0","show_dislike":true,"name":"重复、旧闻"},{"is_selected":false,"id":"9:1","show_dislike":true,"name":"内容质量差"},{"is_selected":false,"id":"3:306457840","show_dislike":true,"name":"黑社会"},{"is_selected":false,"id":"6:47778225","show_dislike":true,"name":"打黑除恶"}]
* answer : {"status":1,"qid":6333792867344974082,"abstract":"\u8fd9\u4e2a\u4eba\u7269\u662f\u6211\u540c\u5b66\u7684\u8205\u8205\uff0c\u9053\u4e0a\u90fd\u53eb\u4ed6\u8363\u54e5\uff0c\u4e1c\u5317\u9ed1\u9053\u7684\uff0c\u66fe\u7ecf\u548c\u9ed1\u8001\u5927\u5218\u52c7\u6df7\u7684\uff0c\u73b0\u5728\u5feb60\u5de6\u53f3\u4e86\uff0c\u4e09\u756a\u4e94\u6b21\u8fdb\u5bab\uff0c\u7d2f\u8ba1\u5728\u76d1\u72f1\u5446\u4e86\u5c0f30\u5e74\uff0c2013\u5e74\u51fa\u6765\u4e00\u6b21\uff0c\u56e0\u4e3a\u624b\u4e0b\u4e00\u4e2a\u5c0f\u5f1f\u62ff\u67aa\u5931\u624b\u628a\u5bf9\u65b9\u6253\u6b7b\u4e86\uff0c\u5f53\u65f6\u8fd9\u5c0f\u5f1f\u5f00\u9762\u5305\u8f66\u53bb\u7684\uff0c\u628a\u4eba\u6253\u6b7b\u540e\u6ca1\u6765\u5f97\u53ca\u5f00\u8f66\u8d70\uff0c\u8363\u54e5\u77e5\u9053\u540e\u5927\u9a82\u4ed6\u4e00\u987f\uff0c\u544a\u8bc9\u4ed6\uff0c\u8f66\u4e0d\u80fd\u8981\u4e86\uff0c\u5c0f\u5f1f\u5fc3\u75bc\u8f66\uff0c\u4e8b\u53d1\u540e\u5341\u5929\uff0c\u770b\u6ca1\u5565\u4e8b\uff0c\u5c0f\u5f1f\u6df1\u591c\u53bb\u53d6\u8f66\uff0c\u88ab\u8b66\u5bdf\u5f53\u573a\u62ff\u4e0b\uff0c\u5c0f\u5f1f\u88ab\u6293\uff0c\u67aa\u662f\u8363\u54e5\u7684\uff0c\u6240\u4ee5\u8363\u54e5\u4e5f\u8fdb\u53bb\u4e86\uff0c\u8363\u54e5\u5224\u4e86\u4e0d\u5c11\u5e74\uff0c\u6700\u540e\u51cf\u52117\u5e74\u51fa\u6765\u4e86\uff0c\u9053\u4e0a\u670b\u53cb\u63a5\u98ce\u8bbe\u5bb4\u5f88\u8bb2\u7a76\uff0c\u6bcf\u4e2a\u4eba\u515c\u91cc\u90fd\u6709\u67aa\uff0c\u51fa\u6765\u4e00\u4e2a\u6708\u540e\u53c8\u56e0\u4e3a\u8d29\u6bd2\u8fdb\u53bb\u4e86\uff0c\u4e03\u514b\u6bd2\u54c1\uff0c\u542c\u8bf4\u8d85\u8fc7\u4e03\u514b\u7f6a\u8fc7\u5c31\u5927\u4e86\u3002\u8363\u54e5\u8bf4\uff0c\u4ed6\u8fd9\u7ea7\u522b\u7684\u72af\u4eba\u5728\u7262\u91cc\u6bd4\u5916\u9762\u81ea\u5728\uff0c\u5728\u7262\u91cc\u4e00\u6837\u6709\u5927\u7b14\u751f\u610f\u505a\uff0c\u4e00\u5e74\u4e5f\u80fd20\u6765\u4e07\uff0c\u73b0\u5728\u5f88\u591a\u5f53\u5e74\u8fd8\u4e0d\u9519\u7684\u5927\u54e5\u90fd\u5728\u7262\u91cc\u505a\u751f\u610f\uff0c\u51fa\u6765\u4e86\u4e5f\u60f3\u529e\u6cd5\u518d\u8fdb\u53bb\u3002","uname":"\u67cf\u94ed\u4e00","create_time":1474761961,"ansid":6334054392425087233,"user_id":6029773522,"bury_count":809,"display_status":2,"digg_count":2100,"can_comment":1}
* id : 6334054392425087000
*/
private int cell_type;
private String extra;
private String question;
private String behot_time;
private int cursor;
private String answer;
private long id;
private ExtraBean extraBean;
private QuestionBean questionBean;
private AnswerBean answerBean;
public AnswerBean getAnswerBean() {
return answerBean;
}
public void setAnswerBean(AnswerBean answerBean) {
this.answerBean = answerBean;
}
public ExtraBean getExtraBean() {
return extraBean;
}
public void setExtraBean(ExtraBean extraBean) {
this.extraBean = extraBean;
}
public QuestionBean getQuestionBean() {
return questionBean;
}
public void setQuestionBean(QuestionBean questionBean) {
this.questionBean = questionBean;
}
public int getCell_type() {
return cell_type;
}
public void setCell_type(int cell_type) {
this.cell_type = cell_type;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getBehot_time() {
return behot_time;
}
public void setBehot_time(String behot_time) {
this.behot_time = behot_time;
}
public int getCursor() {
return cursor;
}
public void setCursor(int cursor) {
this.cursor = cursor;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public static class ExtraBean {
/**
* wenda_video : []
* show_answer : false
* video_large_card : false
* label_style : {"color_type":0,"name":""}
* show_video : false
* video_source_name :
* wenda_image : {"three_image_list":[{"url":"http://p3.pstatp.com/list/300x196/18a2000bcefb11e51664","url_list":[{"url":"http://p3.pstatp.com/list/300x196/18a2000bcefb11e51664"},{"url":"http://pb9.pstatp.com/list/300x196/18a2000bcefb11e51664"},{"url":"http://pb3.pstatp.com/list/300x196/18a2000bcefb11e51664"}],"uri":"list/300x196/18a2000bcefb11e51664","height":576,"width":768,"type":1},{"url":"http://p3.pstatp.com/list/300x196/e580008f01daabc4b83","url_list":[{"url":"http://p3.pstatp.com/list/300x196/e580008f01daabc4b83"},{"url":"http://pb9.pstatp.com/list/300x196/e580008f01daabc4b83"},{"url":"http://pb3.pstatp.com/list/300x196/e580008f01daabc4b83"}],"uri":"list/300x196/e580008f01daabc4b83","height":295,"width":440,"type":1},{"url":"http://p9.pstatp.com/list/300x196/12320005f73e2f519d5c","url_list":[{"url":"http://p9.pstatp.com/list/300x196/12320005f73e2f519d5c"},{"url":"http://pb1.pstatp.com/list/300x196/12320005f73e2f519d5c"},{"url":"http://pb3.pstatp.com/list/300x196/12320005f73e2f519d5c"}],"uri":"list/300x196/12320005f73e2f519d5c","height":768,"width":431,"type":1}],"small_image_list":[],"large_image_list":[],"medium_image_list":[]}
* schema : sslocal://wenda_list?qid=6333792867344974082&gd_ext_json=%7B%22qid%22%3A%226333792867344974082%22%2C%22ansid%22%3A%226334054392425087233%22%2C%22enter_from%22%3A%22click_answer_hot%22%7D&video_auto_play=0&api_param=%7B%22scope%22%3A%22toutiao_wenda%22%2C%22origin_from%22%3A%22native_wenda_home%22%2C%22enter_ansid%22%3A%226334054392425087233%22%2C%22enter_from%22%3A%22answer_hot%22%7D
*/
private boolean show_answer;
private boolean video_large_card;
private LabelStyleBean label_style;
private boolean show_video;
private String video_source_name;
private WendaImageBean wenda_image;
private String schema;
private List<?> wenda_video;
public boolean isShow_answer() {
return show_answer;
}
public void setShow_answer(boolean show_answer) {
this.show_answer = show_answer;
}
public boolean isVideo_large_card() {
return video_large_card;
}
public void setVideo_large_card(boolean video_large_card) {
this.video_large_card = video_large_card;
}
public LabelStyleBean getLabel_style() {
return label_style;
}
public void setLabel_style(LabelStyleBean label_style) {
this.label_style = label_style;
}
public boolean isShow_video() {
return show_video;
}
public void setShow_video(boolean show_video) {
this.show_video = show_video;
}
public String getVideo_source_name() {
return video_source_name;
}
public void setVideo_source_name(String video_source_name) {
this.video_source_name = video_source_name;
}
public WendaImageBean getWenda_image() {
return wenda_image;
}
public void setWenda_image(WendaImageBean wenda_image) {
this.wenda_image = wenda_image;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public List<?> getWenda_video() {
return wenda_video;
}
public void setWenda_video(List<?> wenda_video) {
this.wenda_video = wenda_video;
}
public static class LabelStyleBean {
/**
* color_type : 0
* name :
*/
private int color_type;
private String name;
public int getColor_type() {
return color_type;
}
public void setColor_type(int color_type) {
this.color_type = color_type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class WendaImageBean {
private List<ThreeImageListBean> three_image_list;
private List<?> small_image_list;
private List<LargeImageList> large_image_list;
private List<?> medium_image_list;
public List<ThreeImageListBean> getThree_image_list() {
return three_image_list;
}
public void setThree_image_list(List<ThreeImageListBean> three_image_list) {
this.three_image_list = three_image_list;
}
public List<?> getSmall_image_list() {
return small_image_list;
}
public void setSmall_image_list(List<?> small_image_list) {
this.small_image_list = small_image_list;
}
public List<LargeImageList> getLarge_image_list() {
return large_image_list;
}
public void setLarge_image_list(List<LargeImageList> large_image_list) {
this.large_image_list = large_image_list;
}
public List<?> getMedium_image_list() {
return medium_image_list;
}
public void setMedium_image_list(List<?> medium_image_list) {
this.medium_image_list = medium_image_list;
}
public static class ThreeImageListBean {
/**
* url : http://p3.pstatp.com/list/300x196/18a2000bcefb11e51664
* url_list : [{"url":"http://p3.pstatp.com/list/300x196/18a2000bcefb11e51664"},{"url":"http://pb9.pstatp.com/list/300x196/18a2000bcefb11e51664"},{"url":"http://pb3.pstatp.com/list/300x196/18a2000bcefb11e51664"}]
* uri : list/300x196/18a2000bcefb11e51664
* height : 576
* width : 768
* type : 1
*/
private String url;
private String uri;
private int height;
private int width;
private int type;
private List<UrlListBean> url_list;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<UrlListBean> getUrl_list() {
return url_list;
}
public void setUrl_list(List<UrlListBean> url_list) {
this.url_list = url_list;
}
public static class UrlListBean {
/**
* url : http://p3.pstatp.com/list/300x196/18a2000bcefb11e51664
*/
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
public static class LargeImageList {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
}
public static class QuestionBean {
/**
* status : 1
* op_status : 0
* qid : 6333792867344974000
* nice_ans_count : 336
* uname :
* create_time : 1474701070
* normal_ans_count : 1227
* item_id : 0
* user_id : 5547793806
* title : 你们当地那些混黑社会的人现在都怎么样了?
* content : {"text":"我知道的都出去打工了,有些甚至蹲过几年牢,总之就是没以前那么嚣张得意,你们知道的呢?","pic_uri_list":[],"thumb_image_list":[],"large_image_list":[]}
* group_id : null
*/
private int status;
private int op_status;
private long qid;
private int nice_ans_count;
private String uname;
private int create_time;
private int normal_ans_count;
private int item_id;
private long user_id;
private String title;
private ContentBean content;
private Object group_id;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
QuestionBean that = (QuestionBean) o;
if (!title.equals(that.title))
return false;
return content.equals(that.content);
}
@Override
public int hashCode() {
int result = title.hashCode();
result = 31 * result + content.hashCode();
return result;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getOp_status() {
return op_status;
}
public void setOp_status(int op_status) {
this.op_status = op_status;
}
public long getQid() {
return qid;
}
public void setQid(long qid) {
this.qid = qid;
}
public int getNice_ans_count() {
return nice_ans_count;
}
public void setNice_ans_count(int nice_ans_count) {
this.nice_ans_count = nice_ans_count;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getCreate_time() {
return create_time;
}
public void setCreate_time(int create_time) {
this.create_time = create_time;
}
public int getNormal_ans_count() {
return normal_ans_count;
}
public void setNormal_ans_count(int normal_ans_count) {
this.normal_ans_count = normal_ans_count;
}
public int getItem_id() {
return item_id;
}
public void setItem_id(int item_id) {
this.item_id = item_id;
}
public long getUser_id() {
return user_id;
}
public void setUser_id(long user_id) {
this.user_id = user_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public ContentBean getContent() {
return content;
}
public void setContent(ContentBean content) {
this.content = content;
}
public Object getGroup_id() {
return group_id;
}
public void setGroup_id(Object group_id) {
this.group_id = group_id;
}
public static class ContentBean {
/**
* text : 我知道的都出去打工了,有些甚至蹲过几年牢,总之就是没以前那么嚣张得意,你们知道的呢?
* pic_uri_list : []
* thumb_image_list : []
* large_image_list : []
*/
private String text;
private List<?> pic_uri_list;
private List<?> thumb_image_list;
private List<?> large_image_list;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<?> getPic_uri_list() {
return pic_uri_list;
}
public void setPic_uri_list(List<?> pic_uri_list) {
this.pic_uri_list = pic_uri_list;
}
public List<?> getThumb_image_list() {
return thumb_image_list;
}
public void setThumb_image_list(List<?> thumb_image_list) {
this.thumb_image_list = thumb_image_list;
}
public List<?> getLarge_image_list() {
return large_image_list;
}
public void setLarge_image_list(List<?> large_image_list) {
this.large_image_list = large_image_list;
}
}
}
public static class AnswerBean {
/**
* status : 1
* qid : 6355230839860625000
* abstract : 很多人喜欢在院子里种树,但有些树适合在院子里种,有些树不适合。那么,院子里中出的风水有什么禁忌呢?哪些树可以种,哪些不可以呢?下面和大家一起看看。院子里种树的风水有什么禁忌种树也有风水讲究你知道院子里不能种什么树吗院子中央不宜放植栽院子中心不宜种树,树种树风水院子里种树风水知识植物有阴阳属性。喜阳的植物,如植(置)于阴湿的环境,则体弱,无花,无果或死亡。如:白兰、玫瑰、茉莉、梅花、牡丹、芍药、杜鹃、菊花等。这类植物,须得一千八百个勒克斯光照度,才能正常发能。而文竹,龟背竹、万年青、绿萝、蓬莱松、巴西铁等,在一百个勒克斯光照度条件下,亦能正常生长。此类植物可长期置于室内或阴暗处。属于阴性植物。院子里种树风水注意事项风水树知识根据古代风水理论,中式风格的别墅院子前院可以栽种桂亦主桃花、多生女儿,此时可在向上施以遮形、通气之法。艮方有山而形恶者相同 。植物作为一种活物,其本身存在的风水能量就要比一些摆件或者装饰之类的死物更强,因此,在进行庭院绿化的过程中必须要关注下各种不同植物的风水问题。庭院绿化过程中要注意植物的风水禁忌在这里我们要为各位介绍的就是关于植物的风水禁忌问题,在庭院绿化的过程中,一定要尽可能的避免触犯这些风水禁忌。1、任何植物不可与门相对,因为大门乃是住宅的纳气口,所以庭院大门和住宅大门必须相通,中间不可以有任何阻碍,如果中间出现了什么植物挡住了从大门进入的气场,必然会对住宅的气场环境带来一定不利影响,所以这一点大家必须重视。2、庭院中心位置不可有植物,因为在风水学中认为中心的位置乃是风水气运最强的地方,所以最好将自己的住宅放在庭院的中心,这样对于住宅的气运才会有所帮助。如果在中心位置有植物,特别是大树,将会严重破坏住宅的风水气场,所以最好是在庭院中心处建造一个水池、喷泉之类与水有关的事物,这样可以旺盛财运。3、带有尖刺的植物不宜种植,在庭院绿化的过程中种植的植物一定要谨慎选择,由于风水学中比较忌讳带有尖刺的事物,所以植物如果有尖刺,最好也不要种在庭院里,那样对于住宅的风水气场会带来不利影响。此外,如果植物的相貌丑恶,最好也不要种。这些就是庭院绿化过程中,大家必须注意的与植物相关的风水禁忌问题。一个家宅中,除了大厅、卧室,庭院是每个人的必经之处,所以庭院的风水布局也是住宅最重要的部分之一,合理的布置庭院,不仅能让庭院看起来美观大方,还能形成良好的气场。我们可以通过庭院绿化来做好庭院布局。有关庭院布局,大家可以看看下面的讲解。庭院绿化时需要注意的一些风水布局问题不宜种植易斜的树:庭院绿化最重要的是绿化植物的选择,选择绿化植物的时候尽量选择树干笔直、生命力旺盛的植物,这样会旺子孙,一定不要选择难成活、遇风雨容易倾斜的植物,这样的植物不利于房屋气场的通行,影响家人的身体健康。庭院不要铺很多碎石:泥土是很多植物的最佳种植方式,但是近年来,有人不断追求新潮,喜欢用碎石来种植植物,以增加庭院的韵味,但是庭院绿化很忌讳道路铺碎石。另外,庭院道路上铺碎石,不方便人行走,走的时候容易发生磕磕绊绊,尤其是家中有老人的,老人摔跤严重时会有生命危险。设计假山、喷泉,风水更佳:所谓风水布局,有风来,七亨通;有水到,水到渠成。庭院绿化的时候,房主可考虑修建一些假山或喷泉,利用绿化、水体造型,不仅能让庭院更美观,水气加湿空气湿度,让家人身体健康。庭院绿化的布置,与家人的运势息息相关,这里提醒大家,在开工前一定要先充分了解庭院绿化风水的有关知识,否则破坏原有的风水就不好了。家里不能种石榴树,这要看你石榴的大小了,石榴本来有多子多福的寓意,土栽盆栽都有。既美化了环境,又可以吃到美味的果实,一举两得。但是如果种植位置不对,或者树形大小不合适,如此情况是不建议在家种植的。但是如果说不能在家种植,似乎有些武断了!看看哪些情况下不适合在家种:风水禁忌院子或客厅中央不宜放。首先在院子中间种植石榴树,树形较大,容易挡光,不利于采光。另外,如果是落叶树经常掉叶,难于清扫,也有碍美观和卫生。另外,认为家中不能种植石榴树的人,大多是因为“石榴裙下死”这个故事的传说,容易对家庭造成不和谐。大家都生活在现代社会,所谓的这些故事传说,并不能得到验证,没有说服力。如果你对植物家居风水深信不疑,那还是不要在家种石榴!养护环境的差异许多人在家种石榴盆栽,但只开花不结果,不是什么风水问题,是家里的环境有关,还有品种,以及种植方法不恰当的影响。1.品种石榴品种很多,主要分二大类,即花石榴和果石榴(果石榴多单瓣花),如果选择的仅供赏花的花石榴,就可能只开花不结果,即使结果,也只能结直径仅2—3厘米的小果实,不能食用,也就是看看而已。现有一种红花重瓣石榴,花艳而结果,既能赏花又能食果。2.环境要求种植石榴的土壤要求疏松、肥沃、排水良好;光照应充足,生长期要求全日照,并且光照越充足,花越多越鲜艳,光照不足时,可能只长叶不开花;适宜生长温度15-20℃。而家庭种最大的问题就是光照,除非是庭院,无遮挡阳光充足,否则很难达到石榴开花结果的要求。3.日常管理浇水、施肥、适度剪枝、病虫害防治也很重要,充分注意才能花好果丰。家里是可以种石榴的,在风水上还是有一定好处的:石榴花的风水价值石榴花花朵表面光滑,颜色鲜红艳丽,象征着富贵,成熟的美丽。如果石榴花摆放位置不同那么它所代表的风水也不同首先因为石榴花的果实鲜美肥硕,而且色彩鲜艳光亮,所以表示了喜庆,如果把石榴花放在客厅、阳台、院子里,则会让家庭多子多孙,多福寿。其次石榴花的果子香甜口口,常被人们代表为繁荣、昌盛、团圆、和睦,是人们喜爱的一种吉祥之果,在民间人们会把石榴花的果实切开,会出来丰满饱实的果粒,则用来表示多多生子,以及农家丰收满满。最后石榴也会作为一种中秋佳节赠送的礼品,象征吉祥,又因为石榴花带一个榴字,可以谐音为留,所以也表示了留下之意,“送榴传谊”就延伸出来了。石榴花的价值当你把石榴花摆在家里的阳台上或者卧室里时,不仅可以带来吉祥美好的祝福,也会祝福你多子多孙多福寿,而且石榴花的价值也不少呢石榴花摆在室内美化空间,等石榴花的果实成熟以后,也可以食用,药用。石榴花的果实可以炒菜,作为一道美味的小菜入口,甜润爽口。石榴花的果实也可以入药,治疗腹泻、杀早、止咳等。所以石榴花不仅风水好,它的价值也不容易小觑,不妨你试试,绝对让你赞不绝口,会想一直种植石榴花呢!石榴呢,在书上一般记载为落叶灌木或小乔木。石榴树树冠丛状自然圆头形。树干呈灰褐色,上面有丑丑的瘤状突起,树根是黄褐色。石榴树高可达4-5米以上,但是也有分矮生石榴,长成的石榴树只有1米左右。石榴的叶子是针状枝,叶呈长倒卵形或长椭圆形。石榴花是朱红色的,花期是5、6月份。石榴是一个圆圆的小红果,到9月10月的时候就会像一个个红彤彤的小灯笼一样,挂在树上。石榴作为一种常见的水果,也是常见的观赏植物。可谓全身是宝,果皮、根、花皆可入药。石榴晶莹剔透,如红宝石般的果粒,是很多女性都会喜欢的。但是很多人不喜欢石榴外表黑红,有些丑丑的果皮,千万不要小看了石榴的果皮哦,其果皮中含有苹果酸、鞣质、生物碱等成分。所以说,石榴可是实力和内在兼具的水果。
* uname : 用户58700537490
* create_time : 1490869217
* ansid : 6403234528361447000
* user_id : 58700537490
* bury_count : 39
* display_status : 2
* digg_count : 998
* can_comment : 1
*/
private int status;
private long qid;
@SerializedName("abstract")
private String abstractX;
private String uname;
private int create_time;
private long ansid;
private long user_id;
private int bury_count;
private int display_status;
private int digg_count;
private int can_comment;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public long getQid() {
return qid;
}
public void setQid(long qid) {
this.qid = qid;
}
public String getAbstractX() {
return abstractX;
}
public void setAbstractX(String abstractX) {
this.abstractX = abstractX;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getCreate_time() {
return create_time;
}
public void setCreate_time(int create_time) {
this.create_time = create_time;
}
public long getAnsid() {
return ansid;
}
public void setAnsid(long ansid) {
this.ansid = ansid;
}
public long getUser_id() {
return user_id;
}
public void setUser_id(long user_id) {
this.user_id = user_id;
}
public int getBury_count() {
return bury_count;
}
public void setBury_count(int bury_count) {
this.bury_count = bury_count;
}
public int getDisplay_status() {
return display_status;
}
public void setDisplay_status(int display_status) {
this.display_status = display_status;
}
public int getDigg_count() {
return digg_count;
}
public void setDigg_count(int digg_count) {
this.digg_count = digg_count;
}
public int getCan_comment() {
return can_comment;
}
public void setCan_comment(int can_comment) {
this.can_comment = can_comment;
}
}
}
| iMeiji/Toutiao | app/src/main/java/com/meiji/toutiao/bean/wenda/WendaArticleDataBean.java |
1,465 | package class19;
public class Code02_ConvertToLetterString {
// str只含有数字字符0~9
// 返回多少种转化方案
public static int number(String str) {
if (str == null || str.length() == 0) {
return 0;
}
return process(str.toCharArray(), 0);
}
// str[0..i-1]转化无需过问
// str[i.....]去转化,返回有多少种转化方法
public static int process(char[] str, int i) {
if (i == str.length) {
return 1;
}
// i没到最后,说明有字符
if (str[i] == '0') { // 之前的决定有问题
return 0;
}
// str[i] != '0'
// 可能性一,i单转
int ways = process(str, i + 1);
if (i + 1 < str.length && (str[i] - '0') * 10 + str[i + 1] - '0' < 27) {
ways += process(str, i + 2);
}
return ways;
}
// 从右往左的动态规划
// 就是上面方法的动态规划版本
// dp[i]表示:str[i...]有多少种转化方式
public static int dp1(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] str = s.toCharArray();
int N = str.length;
int[] dp = new int[N + 1];
dp[N] = 1;
for (int i = N - 1; i >= 0; i--) {
if (str[i] != '0') {
int ways = dp[i + 1];
if (i + 1 < str.length && (str[i] - '0') * 10 + str[i + 1] - '0' < 27) {
ways += dp[i + 2];
}
dp[i] = ways;
}
}
return dp[0];
}
// 从左往右的动态规划
// dp[i]表示:str[0...i]有多少种转化方式
public static int dp2(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] str = s.toCharArray();
int N = str.length;
if (str[0] == '0') {
return 0;
}
int[] dp = new int[N];
dp[0] = 1;
for (int i = 1; i < N; i++) {
if (str[i] == '0') {
// 如果此时str[i]=='0',那么他是一定要拉前一个字符(i-1的字符)一起拼的,
// 那么就要求前一个字符,不能也是‘0’,否则拼不了。
// 前一个字符不是‘0’就够了嘛?不够,还得要求拼完了要么是10,要么是20,如果更大的话,拼不了。
// 这就够了嘛?还不够,你们拼完了,还得要求str[0...i-2]真的可以被分解!
// 如果str[0...i-2]都不存在分解方案,那i和i-1拼成了也不行,因为之前的搞定不了。
if (str[i - 1] == '0' || str[i - 1] > '2' || (i - 2 >= 0 && dp[i - 2] == 0)) {
return 0;
} else {
dp[i] = i - 2 >= 0 ? dp[i - 2] : 1;
}
} else {
dp[i] = dp[i - 1];
if (str[i - 1] != '0' && (str[i - 1] - '0') * 10 + str[i] - '0' <= 26) {
dp[i] += i - 2 >= 0 ? dp[i - 2] : 1;
}
}
}
return dp[N - 1];
}
// 为了测试
public static String randomString(int len) {
char[] str = new char[len];
for (int i = 0; i < len; i++) {
str[i] = (char) ((int) (Math.random() * 10) + '0');
}
return String.valueOf(str);
}
// 为了测试
public static void main(String[] args) {
int N = 30;
int testTime = 1000000;
System.out.println("测试开始");
for (int i = 0; i < testTime; i++) {
int len = (int) (Math.random() * N);
String s = randomString(len);
int ans0 = number(s);
int ans1 = dp1(s);
int ans2 = dp2(s);
if (ans0 != ans1 || ans0 != ans2) {
System.out.println(s);
System.out.println(ans0);
System.out.println(ans1);
System.out.println(ans2);
System.out.println("Oops!");
break;
}
}
System.out.println("测试结束");
}
}
| algorithmzuo/algorithmbasic2020 | src/class19/Code02_ConvertToLetterString.java |
1,466 | package com.abin.mallchat.common.chatai.handler;
import cn.hutool.http.HttpResponse;
import com.abin.mallchat.common.chat.domain.entity.Message;
import com.abin.mallchat.common.chat.domain.entity.msg.MessageExtra;
import com.abin.mallchat.common.chatai.dto.GPTRequestDTO;
import com.abin.mallchat.common.chatai.properties.ChatGLM2Properties;
import com.abin.mallchat.common.chatai.utils.ChatGLM2Utils;
import com.abin.mallchat.common.common.constant.RedisKey;
import com.abin.mallchat.common.common.domain.dto.FrequencyControlDTO;
import com.abin.mallchat.common.common.exception.FrequencyControlException;
import com.abin.mallchat.common.common.service.frequencycontrol.FrequencyControlUtil;
import com.abin.mallchat.common.common.utils.RedisUtils;
import com.abin.mallchat.common.user.domain.vo.response.user.UserInfoResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static com.abin.mallchat.common.common.constant.RedisKey.USER_GLM2_TIME_LAST;
import static com.abin.mallchat.common.common.service.frequencycontrol.FrequencyControlStrategyFactory.TOTAL_COUNT_WITH_IN_FIX_TIME_FREQUENCY_CONTROLLER;
@Slf4j
@Component
public class ChatGLM2Handler extends AbstractChatAIHandler {
/**
* ChatGLM2Handler限流前缀
*/
private static final String CHAT_GLM2_FREQUENCY_PREFIX = "ChatGLM2Handler";
private static final List<String> ERROR_MSG = Arrays.asList(
"还摸鱼呢?你不下班我还要下班呢。。。。",
"没给钱,矿工了。。。。",
"服务器被你们玩儿坏了。。。。",
"你们这群人,我都不想理你们了。。。。",
"艾特我那是另外的价钱。。。。",
"得加钱");
private static final Random RANDOM = new Random();
private static String AI_NAME;
@Autowired
private ChatGLM2Properties glm2Properties;
@Override
protected void init() {
super.init();
if (isUse()) {
UserInfoResp userInfo = userService.getUserInfo(glm2Properties.getAIUserId());
if (userInfo == null) {
log.error("根据AIUserId:{} 找不到用户信息", glm2Properties.getAIUserId());
throw new RuntimeException("根据AIUserId找不到用户信息");
}
if (StringUtils.isBlank(userInfo.getName())) {
log.warn("根据AIUserId:{} 找到的用户信息没有name", glm2Properties.getAIUserId());
throw new RuntimeException("根据AIUserId: " + glm2Properties.getAIUserId() + " 找到的用户没有名字");
}
AI_NAME = userInfo.getName();
}
}
@Override
protected boolean isUse() {
return glm2Properties.isUse();
}
@Override
public Long getChatAIUserId() {
return glm2Properties.getAIUserId();
}
@Override
protected String doChat(Message message) {
String content = message.getContent().replace("@" + AI_NAME, "").trim();
Long uid = message.getFromUid();
try {
FrequencyControlDTO frequencyControlDTO = new FrequencyControlDTO();
frequencyControlDTO.setKey(CHAT_GLM2_FREQUENCY_PREFIX + ":" + uid);
frequencyControlDTO.setUnit(TimeUnit.MINUTES);
frequencyControlDTO.setCount(1);
frequencyControlDTO.setTime(glm2Properties.getMinute().intValue());
return FrequencyControlUtil.executeWithFrequencyControl(TOTAL_COUNT_WITH_IN_FIX_TIME_FREQUENCY_CONTROLLER, frequencyControlDTO, () -> sendRequestToGPT(new GPTRequestDTO(content, uid)));
} catch (FrequencyControlException e) {
return "你太快了亲爱的~过一会再来找人家~";
} catch (Throwable e) {
return "系统开小差啦~~";
}
}
/**
* TODO
*
* @param gptRequestDTO
* @return
*/
@Nullable
private String sendRequestToGPT(GPTRequestDTO gptRequestDTO) {
String content = gptRequestDTO.getContent();
String text;
HttpResponse response = null;
try {
response = ChatGLM2Utils
.create()
.url(glm2Properties.getUrl())
.prompt(content)
.timeout(glm2Properties.getTimeout())
.send();
text = ChatGLM2Utils.parseText(response);
} catch (Exception e) {
log.warn("glm2 doChat warn:", e);
return getErrorText();
}
return text;
}
private static String getErrorText() {
int index = RANDOM.nextInt(ERROR_MSG.size());
return ERROR_MSG.get(index);
}
/**
* 用户多少分钟后才能再次聊天
*
* @param uid
* @return
*/
private Long userMinutesLater(Long uid) {
// 获取用户最后聊天时间
Date lastChatTime = RedisUtils.get(RedisKey.getKey(USER_GLM2_TIME_LAST, uid), Date.class);
if (lastChatTime == null) {
// 如果没有聊天记录,则可以立即聊天
return 0L;
}
// 计算当前时间和上次聊天时间之间的时间差
long now = System.currentTimeMillis();
long lastChatTimeMillis = lastChatTime.getTime();
long durationMillis = now - lastChatTimeMillis;
long minutes = TimeUnit.MILLISECONDS.toMinutes(durationMillis);
// 计算剩余等待时间
long remainingMinutes = glm2Properties.getMinute() - minutes;
return remainingMinutes > 0 ? remainingMinutes : 0L;
}
@Override
protected boolean supports(Message message) {
if (!glm2Properties.isUse()) {
return false;
}
/* 前端传@信息后取消注释 */
MessageExtra extra = message.getExtra();
if (extra == null) {
return false;
}
if (CollectionUtils.isEmpty(extra.getAtUidList())) {
return false;
}
if (!extra.getAtUidList().contains(glm2Properties.getAIUserId())) {
return false;
}
if (StringUtils.isBlank(message.getContent())) {
return false;
}
return StringUtils.contains(message.getContent(), "@" + AI_NAME)
&& StringUtils.isNotBlank(message.getContent().replace(AI_NAME, "").trim());
}
}
| zongzibinbin/MallChat | mallchat-chat-server/src/main/java/com/abin/mallchat/common/chatai/handler/ChatGLM2Handler.java |
1,467 | package name.gudong.translate.mvp.model.entity.dayline;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by GuDong on 10/7/16 12:57.
* Contact with [email protected].
*/
public class JinshanDayLineEntity implements IDayLine{
/**
* sid : 2363
* tts : http://news.iciba.com/admin/tts/2016-10-07-day.mp3
* content : Always let your conscience be your guide. —Pinocchio
* note : 要凭着你的良心做事。 —《木偶奇遇记》
* love : 936
* translation : 词霸小编:这句话让小编想起前一阵的电信诈骗案,不管家庭如何困难,有手有脚就应该靠自己去打拼赚钱,而不是通过诈骗或其他不法手段获取利益哦!小伙伴们,你们是不是也跟小编一样想的呢~~
* picture : http://cdn.iciba.com/news/word/20161007.jpg
* picture2 : http://cdn.iciba.com/news/word/big_20161007b.jpg
* caption : 词霸每日一句
* dateline : 2016-10-07
* s_pv : 0
* sp_pv : 0
* tags : [{"id":"10","name":"正能量"},{"id":"33","name":"人生感悟"}]
* fenxiang_img : http://cdn.iciba.com/web/news/longweibo/imag/2016-10-07.jpg
*/
public String sid;
public String tts;
public String content;
public String note;
public String love;
public String translation;
public String picture;
public String picture2;
public String caption;
public String dateline;
public String s_pv;
public String sp_pv;
public String fenxiang_img;
/**
* id : 10
* name : 正能量
*/
public List<TagsEntity> tags;
@Override
public String tts() {
return tts;
}
@Override
public String content() {
return content;
}
@Override
public String note() {
return note;
}
@Override
public String imageThumb() {
return picture;
}
@Override
public String imageHigh() {
return picture2;
}
@Override
public String caption() {
return caption;
}
@Override
public Date date() {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(dateline);
} catch (ParseException e) {
e.printStackTrace();
return new Date(System.currentTimeMillis());
}
}
@Override
public String shareImage() {
return fenxiang_img;
}
public static class TagsEntity {
public String id;
public String name;
@Override
public String toString() {
return "TagsEntity{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
@Override
public String toString() {
return "JinshanDayLineEntity{" +
"caption='" + caption + '\'' +
", sid='" + sid + '\'' +
", tts='" + tts + '\'' +
", content='" + content + '\'' +
", note='" + note + '\'' +
", love='" + love + '\'' +
", translation='" + translation + '\'' +
", picture='" + picture + '\'' +
", picture2='" + picture2 + '\'' +
", dateline='" + dateline + '\'' +
", s_pv='" + s_pv + '\'' +
", sp_pv='" + sp_pv + '\'' +
", fenxiang_img='" + fenxiang_img + '\'' +
", tags=" + tags +
'}';
}
}
| maoruibin/TranslateApp | app/src/main/java/name/gudong/translate/mvp/model/entity/dayline/JinshanDayLineEntity.java |
1,468 | package com.hlsp.video.bean;
/**
* Created by hackest on 2018/4/27.
*/
public class AuthorVideo {
/**
* video_name : 你们看到的是什么?
* video_coverURL : http://p3.pstatp.com/large/6e0e0001f838e80b2285.jpeg
* period : 14600
* law : null
* video_author_name : 陈立农的小仙女
* Bitrate : 100083
* video_pubtime : null
* video_like_count : 1151646
* video_count_share : 181995
* video_show_mode : 1
* video_playURL : http://youqu-video.oss-cn-shenzhen.aliyuncs.com/5acc6e835e14d41440e1b885?Expires=1524829935&OSSAccessKeyId=LTAI0KtApRo67
* video_author_id : douyin_61222759089
* video_count_play : 50830057
* height_width : height:1024,width576
* video_source : dingyue
* video_count_comment : 65329
* ratio : 720p
* video_id : 5acc6e835e14d41440e1b885
* video_desc : 你们看到的是什么?
*/
private String video_name;
private String video_coverURL;
private String period;
private String law;
private String video_author_name;
private String Bitrate;
private String video_pubtime;
private String video_like_count;
private String video_count_share;
private String video_show_mode;
private String video_playURL;
private String video_author_id;
private String video_count_play;
private String height_width;
private String video_source;
private String video_count_comment;
private String ratio;
private String video_id;
private String video_desc;
public String getVideo_name() {
return video_name;
}
public String getVideo_coverURL() {
return video_coverURL;
}
public String getPeriod() {
return period;
}
public String getLaw() {
return law;
}
public String getVideo_author_name() {
return video_author_name;
}
public String getBitrate() {
return Bitrate;
}
public String getVideo_pubtime() {
return video_pubtime;
}
public String getVideo_like_count() {
return video_like_count;
}
public String getVideo_count_share() {
return video_count_share;
}
public String getVideo_show_mode() {
return video_show_mode;
}
public String getVideo_playURL() {
return video_playURL;
}
public String getVideo_author_id() {
return video_author_id;
}
public String getVideo_count_play() {
return video_count_play;
}
public String getHeight_width() {
return height_width;
}
public String getVideo_source() {
return video_source;
}
public String getVideo_count_comment() {
return video_count_comment;
}
public String getRatio() {
return ratio;
}
public String getVideo_id() {
return video_id;
}
public String getVideo_desc() {
return video_desc;
}
}
| MIkeeJY/honglou | app/src/main/java/com/hlsp/video/bean/AuthorVideo.java |
1,469 | package com.sjk.tpay.request;
import android.support.annotation.Nullable;
import com.alibaba.fastjson.JSONException;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.sjk.tpay.po.Configer;
import com.sjk.tpay.utils.StrEncode;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
/**
* @ Created by Dlg
* @ <p>TiTle: StringRequestGet</p>
* @ <p>Description: 有时候HTTP请求可能不是和自己服务器交流,用这个吧
* @ 统一设置好超时和重试次数,这里的token我没有去掉,一般不影响,你们也可以删除完全不影响</p>
* @ date: 2018/9/30
* @ QQ群:524901982
*/
public class StringRequestGet extends JsonRequest<String> {
private Map<String, String> headers = new HashMap<>();
public StringRequestGet(String url, Response.Listener<String> listener, @Nullable Response.ErrorListener errorListener) {
super(Method.GET, url, null, listener, errorListener);
setRetryPolicy(new DefaultRetryPolicy(5000, 0, 0));
}
public StringRequestGet addHeaders(String key, String value) {
headers.put(key, value);
return this;
}
/**
* 这个方法可以不用继承修改的哈
*
* @return
* @throws AuthFailureError
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
addHeaders("token", StrEncode
.encoderByDES(System.currentTimeMillis() + "|" + getUrl()
, Configer.getInstance().getToken()));
headers.putAll(super.getHeaders());
return headers;
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
| itmad/Tpay | app/src/main/java/com/sjk/tpay/request/StringRequestGet.java |
1,470 | package com.lugeek.schoolevents.officeevents.bean;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lugeek on 2015/8/9.
*/
public class Events {
private static Events instance;
private List<Event> events;
public static Events getInstance(){
if (instance == null){
instance = new Events();
instance.events = new ArrayList<Event>();
}
return instance;
}
public List<Event> getEvents(){
return events;
}
public void setEvents(List<Event> events) {
this.events = events;
}
public List<Event> setTestEvents(){
events.removeAll(events);
Event event1 = new Event();
event1.setImageUrl("http://7xiq48.com1.z0.glb.clouddn.com/article/drjh.jpg");
event1.setTitle("活动1");
event1.setOrganizer("主办方:杭州电子科技大学");
event1.setTime("时间:8月10日13:00");
event1.setAddress("地点:杭州电子科技大学6教201");
event1.setParticipants(10);
event1.setAllNum(100);
event1.setFans(20);
event1.setNeedSignup(true);
event1.setDescribe("如果你热爱音乐,需要舞台; \n" +
"如果想认识新伙伴,擦出创作的火花; \n" +
"如果你有想法,做些关于音乐的交流活动。 \n" +
"欢迎,你们。");
events.add(event1);
Event event2 = new Event();
event2.setImageUrl("http://7xiq48.com1.z0.glb.clouddn.com/article/drjh.jpg");
event2.setTitle("活动2");
event2.setOrganizer("主办方:通信学院");
event2.setTime("时间:8月15日13:00");
event2.setAddress("地点:科技馆");
event2.setParticipants(16);
event2.setAllNum(200);
event2.setFans(52);
event2.setNeedSignup(false);
event2.setDescribe("针对于浙江大学法学硕士在职研究生课程班级" +
"的开班,还有针对于各个专业的咨询情况。法学硕士将于9月12日" +
"开班。其他课程开班具体情况做出简短的解答,针对于现阶段法学硕士" +
"能够使用的范围,上课的课程内容,都可以到校做咨询。");
events.add(event2);
events.add(event1);
events.add(event2);
events.add(event1);
events.add(event2);
events.add(event1);
events.add(event2);
return events;
}
public List<Event> addList(List<Event> newEvents){
events.addAll(0, newEvents);
return events;
}
}
| HDU2014/SchoolActivities | app/src/main/java/com/lugeek/schoolevents/officeevents/bean/Events.java |
1,471 | package cn.afterturn.easypoi.test.excel.template;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Workbook;
import org.junit.Before;
import org.junit.Test;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelStyleType;
import cn.afterturn.easypoi.test.entity.CourseEntity;
import cn.afterturn.easypoi.test.entity.StudentEntity;
import cn.afterturn.easypoi.test.entity.TeacherEntity;
/**
* 多sheet导出
*
* @author JueYue 2015年8月15日 下午10:39:21
*/
public class TemplateExcelManySheet
{
List<CourseEntity> list = new ArrayList<CourseEntity>();
CourseEntity courseEntity;
@Test
public void manyMap()
throws Exception
{
TemplateExportParams params = new TemplateExportParams("doc/exportTemp.xls", 0, 1);
params.setHeadingRows(2);
params.setHeadingStartRow(2);
params.setStyle(ExcelStyleType.BORDER.getClazz());
Map<Integer, Map<String, Object>> sheetMap = new HashMap<Integer, Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
// sheet 1
map.put("year", "2013");
map.put("sunCourses", list.size());
Map<String, Object> obj = new HashMap<String, Object>();
map.put("obj", obj);
obj.put("n" + "ame", list.size());
// sheet 2
map.put("month", 10);
// 第一个sheet Map的值put进去
sheetMap.put(0, map);
map = new HashMap<String, Object>();
Map<String, Object> temp;
for (int i = 1; i < 8; i++)
{
temp = new HashMap<String, Object>();
temp.put("per", i * 10);
temp.put("mon", i * 1000);
temp.put("summon", i * 10000);
map.put("i" + i, temp);
}
// 第二个sheet Map的值put进去
sheetMap.put(1, map);
Workbook book = ExcelExportUtil.exportExcel(sheetMap, params);
File savefile = new File("D:/home/excel/");
if (!savefile.exists())
{
savefile.mkdirs();
}
FileOutputStream fos = new FileOutputStream("D:/home/excel/exportTemp3.xls");
book.write(fos);
fos.close();
}
@Before
public void testBefore()
{
courseEntity = new CourseEntity();
courseEntity.setId("1131");
courseEntity.setName("小白");
TeacherEntity teacherEntity = new TeacherEntity();
teacherEntity.setId("12131231");
teacherEntity.setName("你们");
courseEntity.setChineseTeacher(teacherEntity);
teacherEntity = new TeacherEntity();
teacherEntity.setId("121312314312421131");
teacherEntity.setName("老王");
courseEntity.setMathTeacher(teacherEntity);
StudentEntity studentEntity = new StudentEntity();
studentEntity.setId("11231");
studentEntity.setName("撒旦法司法局");
studentEntity.setBirthday(new Date());
studentEntity.setSex(1);
List<StudentEntity> studentList = new ArrayList<StudentEntity>();
studentList.add(studentEntity);
studentList.add(studentEntity);
courseEntity.setStudents(studentList);
for (int i = 0; i < 3; i++)
{
list.add(courseEntity);
}
}
}
| adminers/Undercurrent | un-simulation/com.qiaweidata.com/TemplateExcelManySheet.java |
1,475 | package cn.hutool.db;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.func.Func0;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.SqlUtil;
import java.nio.charset.Charset;
import java.sql.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Set;
/**
* 数据实体对象<br>
* 数据实体类充当两个角色:<br>
* 1. 数据的载体,一个Entity对应数据库中的一个row<br>
* 2. SQL条件,Entity中的每一个字段对应一个条件,字段值对应条件的值
*
* @author loolly
*/
public class Entity extends Dict {
private static final long serialVersionUID = -1951012511464327448L;
// --------------------------------------------------------------- Static method start
/**
* 创建Entity
*
* @return Entity
*/
public static Entity create() {
return new Entity();
}
/**
* 创建Entity
*
* @param tableName 表名
* @return Entity
*/
public static Entity create(String tableName) {
return new Entity(tableName);
}
/**
* 将PO对象转为Entity
*
* @param <T> Bean对象类型
* @param bean Bean对象
* @return Entity
*/
public static <T> Entity parse(T bean) {
return create(null).parseBean(bean);
}
/**
* 将PO对象转为Entity
*
* @param <T> Bean对象类型
* @param bean Bean对象
* @param isToUnderlineCase 是否转换为下划线模式
* @param ignoreNullValue 是否忽略值为空的字段
* @return Entity
*/
public static <T> Entity parse(T bean, boolean isToUnderlineCase, boolean ignoreNullValue) {
return create(null).parseBean(bean, isToUnderlineCase, ignoreNullValue);
}
/**
* 将PO对象转为Entity,并采用下划线法转换字段
*
* @param <T> Bean对象类型
* @param bean Bean对象
* @return Entity
*/
public static <T> Entity parseWithUnderlineCase(T bean) {
return create(null).parseBean(bean, true, true);
}
// --------------------------------------------------------------- Static method end
/* 表名 */
private String tableName;
/* 字段名列表,用于限制加入的字段的值 */
private Set<String> fieldNames;
// --------------------------------------------------------------- Constructor start
public Entity() {
}
/**
* 构造
*
* @param tableName 数据表名
*/
public Entity(String tableName) {
this.tableName = tableName;
}
/**
* 构造
*
* @param tableName 数据表名
* @param caseInsensitive 是否大小写不敏感
* @since 4.5.16
*/
public Entity(String tableName, boolean caseInsensitive) {
super(caseInsensitive);
this.tableName = tableName;
}
// --------------------------------------------------------------- Constructor end
// --------------------------------------------------------------- Getters and Setters start
/**
* @return 获得表名
*/
public String getTableName() {
return tableName;
}
/**
* 设置表名
*
* @param tableName 表名
* @return 本身
*/
public Entity setTableName(String tableName) {
this.tableName = tableName;
return this;
}
/**
* @return 字段集合
*/
public Set<String> getFieldNames() {
return this.fieldNames;
}
/**
* 设置字段列表,用于限制加入的字段的值
*
* @param fieldNames 字段列表
* @return 自身
*/
public Entity setFieldNames(Collection<String> fieldNames) {
if (CollectionUtil.isNotEmpty(fieldNames)) {
this.fieldNames = CollectionUtil.newHashSet(true, fieldNames);
}
return this;
}
/**
* 设置字段列表,用于限制加入的字段的值
*
* @param fieldNames 字段列表
* @return 自身
*/
public Entity setFieldNames(String... fieldNames) {
if (ArrayUtil.isNotEmpty(fieldNames)) {
this.fieldNames = CollectionUtil.newLinkedHashSet(fieldNames);
}
return this;
}
/**
* 通过lambda批量设置值
* @param fields lambda,不能为空
* @return this
*/
@Override
public Entity setFields(Func0<?>... fields) {
return (Entity) super.setFields(fields);
}
/**
* 添加字段列表
*
* @param fieldNames 字段列表
* @return 自身
*/
public Entity addFieldNames(String... fieldNames) {
if (ArrayUtil.isNotEmpty(fieldNames)) {
if (null == this.fieldNames) {
return setFieldNames(fieldNames);
} else {
Collections.addAll(this.fieldNames, fieldNames);
}
}
return this;
}
// --------------------------------------------------------------- Getters and Setters end
/**
* 将值对象转换为Entity<br>
* 类名会被当作表名,小写第一个字母
*
* @param <T> Bean对象类型
* @param bean Bean对象
* @return 自己
*/
@Override
public <T> Entity parseBean(T bean) {
if (StrUtil.isBlank(this.tableName)) {
this.setTableName(StrUtil.lowerFirst(bean.getClass().getSimpleName()));
}
return (Entity) super.parseBean(bean);
}
/**
* 将值对象转换为Entity<br>
* 类名会被当作表名,小写第一个字母
*
* @param <T> Bean对象类型
* @param bean Bean对象
* @param isToUnderlineCase 是否转换为下划线模式
* @param ignoreNullValue 是否忽略值为空的字段
* @return 自己
*/
@Override
public <T> Entity parseBean(T bean, boolean isToUnderlineCase, boolean ignoreNullValue) {
if (StrUtil.isBlank(this.tableName)) {
String simpleName = bean.getClass().getSimpleName();
this.setTableName(isToUnderlineCase ? StrUtil.toUnderlineCase(simpleName) : StrUtil.lowerFirst(simpleName));
}
return (Entity) super.parseBean(bean, isToUnderlineCase, ignoreNullValue);
}
/**
* 过滤Map保留指定键值对,如果键不存在跳过
*
* @param keys 键列表
* @return Dict 结果
* @since 4.0.10
*/
@Override
public Entity filter(String... keys) {
final Entity result = new Entity(this.tableName);
result.setFieldNames(this.fieldNames);
for (String key : keys) {
if (this.containsKey(key)) {
result.put(key, this.get(key));
}
}
return result;
}
/**
* 过滤Map去除指定键值对,如果键不存在跳过
*
* @param keys 键列表
* @return Dict 结果
* @since 5.8.19
*/
public Entity removeNew(final String... keys) {
return (Entity) MapUtil.removeAny(this.clone(), keys);
}
// -------------------------------------------------------------------- Put and Set start
@Override
public Entity set(String field, Object value) {
return (Entity) super.set(field, value);
}
@Override
public Entity setIgnoreNull(String field, Object value) {
return (Entity) super.setIgnoreNull(field, value);
}
// -------------------------------------------------------------------- Put and Set end
// -------------------------------------------------------------------- Get start
/**
* 获得Clob类型结果
*
* @param field 参数
* @return Clob
*/
public Clob getClob(String field) {
return get(field, null);
}
/**
* 获得Blob类型结果
*
* @param field 参数
* @return Blob
* @since 3.0.6
*/
public Blob getBlob(String field) {
return get(field, null);
}
@Override
public Time getTime(String field) {
Object obj = get(field);
Time result = null;
if (null != obj) {
try {
result = (Time) obj;
} catch (Exception e) {
// try oracle.sql.TIMESTAMP
result = ReflectUtil.invoke(obj, "timeValue");
}
}
return result;
}
@Override
public Date getDate(String field) {
Object obj = get(field);
Date result = null;
if (null != obj) {
try {
result = (Date) obj;
} catch (Exception e) {
// try oracle.sql.TIMESTAMP
result = ReflectUtil.invoke(obj, "dateValue");
}
}
return result;
}
@Override
public Timestamp getTimestamp(String field) {
Object obj = get(field);
Timestamp result = null;
if (null != obj) {
try {
result = (Timestamp) obj;
} catch (Exception e) {
// try oracle.sql.TIMESTAMP
result = ReflectUtil.invoke(obj, "timestampValue");
}
}
return result;
}
@Override
public String getStr(String field) {
return getStr(field, CharsetUtil.CHARSET_UTF_8);
}
/**
* 获得字符串值<br>
* 支持Clob、Blob、RowId
*
* @param field 字段名
* @param charset 编码
* @return 字段对应值
* @since 3.0.6
*/
public String getStr(String field, Charset charset) {
final Object obj = get(field);
if (obj instanceof Clob) {
return SqlUtil.clobToStr((Clob) obj);
} else if (obj instanceof Blob) {
return SqlUtil.blobToStr((Blob) obj, charset);
} else if (obj instanceof RowId) {
final RowId rowId = (RowId) obj;
return StrUtil.str(rowId.getBytes(), charset);
}
return super.getStr(field);
}
/**
* 获得rowid
*
* @return RowId
*/
public RowId getRowId() {
return getRowId("ROWID");
}
/**
* 获得rowid
*
* @param field rowid属性名
* @return RowId
*/
public RowId getRowId(String field) {
Object obj = this.get(field);
if (null == obj) {
return null;
}
if (obj instanceof RowId) {
return (RowId) obj;
}
throw new DbRuntimeException("Value of field [{}] is not a rowid!", field);
}
// -------------------------------------------------------------------- Get end
// -------------------------------------------------------------------- 特殊方法 start
@Override
public Entity clone() {
return (Entity) super.clone();
}
// -------------------------------------------------------------------- 特殊方法 end
@Override
public String toString() {
return "Entity {tableName=" + tableName + ", fieldNames=" + fieldNames + ", fields=" + super.toString() + "}";
}
}
| dromara/hutool | hutool-db/src/main/java/cn/hutool/db/Entity.java |
1,480 | package org.ansj.util;
import org.ansj.domain.Nature;
import org.ansj.domain.Term;
import org.ansj.domain.TermNatures;
import org.ansj.library.DATDictionary;
import org.ansj.library.NatureLibrary;
import java.util.ArrayList;
import java.util.List;
/**
* term的操作类
*
* @author ansj
*
*/
public class TermUtil {
/**
* 将两个term合并为一个全新的term
*
* @param termNatures
* @return
*/
public static Term makeNewTermNum(Term from, Term to, TermNatures termNatures) {
Term term = new Term(from.getName() + to.getName(), from.getOffe(), termNatures);
term.termNatures().numAttr = from.termNatures().numAttr;
TermUtil.termLink(term, to.to());
TermUtil.termLink(term.from(), term);
return term;
}
public static void termLink(Term from, Term to) {
if (from == null || to == null) {
return;
}
from.setTo(to);
to.setFrom(from);
}
public static enum InsertTermType{
/**
* 跳过 0
*/
SKIP,
/**
* 替换 1
*/
REPLACE,
/**
* 累积分值 保证顺序,由大到小 2
*/
SCORE_ADD_SORT
}
/**
* 将一个term插入到链表中的对应位置中, 如果这个term已经存在参照type type 0.跳过 1. 替换 2.累积分值 保证顺序,由大到小
*
* @param terms
* @param term
*/
public static void insertTerm(Term[] terms, Term term, InsertTermType type) {
Term self = terms[term.getOffe()];
if (self == null) {
terms[term.getOffe()] = term;
return;
}
int len = term.getName().length();
// 如果是第一位置
if (self.getName().length() == len) {
if (type == InsertTermType.REPLACE) {
term.setNext(self.next());
terms[term.getOffe()] = term;
} else if (type == InsertTermType.SCORE_ADD_SORT) {
self.score(self.score() + term.score());
self.selfScore(self.selfScore() + term.selfScore());
}
return;
}
if(self.getName().length() > len){
term.setNext(self) ;
terms[term.getOffe()] = term;
return;
}
Term next = self;
Term before = self;
while ((next = before.next()) != null) {
if (next.getName().length() == len) {
if (type == InsertTermType.REPLACE) {
term.setNext(next.next());
before.setNext(term);
} else if (type == InsertTermType.SCORE_ADD_SORT) {
next.score(next.score() + term.score());
next.selfScore(next.selfScore() + term.selfScore());
}
return;
} else if (next.getName().length() > len) {
before.setNext(term);
term.setNext(next);
return;
}
before = next;
}
before.setNext(term); // 如果都没有命中
}
public static void insertTermNum(Term[] terms, Term term) {
terms[term.getOffe()] = term;
}
public static void insertTerm(Term[] terms, List<Term> tempList, TermNatures tns) {
StringBuilder sb = new StringBuilder();
for (Term term : tempList) {
sb.append(term.getName());
terms[term.getOffe()] = null;
}
Term term = new Term(sb.toString(), tempList.get(0).getOffe(), tns);
termLink(tempList.get(0).from(), term);
termLink(term,tempList.get(tempList.size()-1).to());
insertTermNum(terms, term);
}
protected static Term setToAndfrom(Term to, Term from) {
from.setTo(to);
to.setFrom(from);
return from;
}
/**
* 得到细颗粒度的分词,并且确定词性
*
* @return 返回是null说明已经是最细颗粒度
*/
public static void parseNature(Term term) {
if (!Nature.NW.equals(term.natrue())) {
return;
}
String name = term.getName();
if (name.length() <= 3) {
return;
}
// 是否是外国人名
if (DATDictionary.foreign(term)) {
term.setNature(NatureLibrary.getNature("nrf"));
return;
}
List<Term> subTerm = term.getSubTerm();
// TODO:判断是否是机构名
}
/**
* 从from到to生成subterm
*
* @param from
* @param to
* @return
*/
public static List<Term> getSubTerm(Term from, Term to) {
List<Term> subTerm = new ArrayList<Term>(3);
while ((from = from.to()) != to) {
subTerm.add(from);
}
return subTerm;
}
}
| NLPchina/ansj_seg | src/main/java/org/ansj/util/TermUtil.java |
1,483 | /*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
This source code is licensed under the Apache License Version 2.0.*/
package apijson.orm;
import com.alibaba.fastjson.JSONObject;
import apijson.NotNull;
import apijson.RequestMethod;
/**校验器(权限、请求参数、返回结果等)
* @author Lemon
*/
public interface Verifier<T> {
/**验证权限是否通过
* @param config
* @return
* @throws Exception
*/
boolean verifyAccess(SQLConfig config) throws Exception;
/**校验请求使用的角色,角色不好判断,让访问者发过来角色名,OWNER,CONTACT,ADMIN等
* @param config
* @param table
* @param method
* @param role
* @return
* @throws Exception
* @see {@link apijson.JSONObject#KEY_ROLE}
*/
void verifyRole(SQLConfig config, String table, RequestMethod method, String role) throws Exception;
/**登录校验
* @throws Exception
*/
void verifyLogin() throws Exception;
/**管理员角色校验
* @throws Exception
*/
void verifyAdmin() throws Exception;
/**验证是否重复
* @param table
* @param key
* @param value
* @throws Exception
*/
void verifyRepeat(String table, String key, Object value) throws Exception;
/**验证是否重复
* @param table
* @param key
* @param value
* @param exceptId 不包含id
* @throws Exception
*/
void verifyRepeat(String table, String key, Object value, long exceptId) throws Exception;
/**验证请求参数的数据和结构
* @param method
* @param name
* @param target
* @param request
* @param maxUpdateCount
* @param globalDatabase
* @param globalSchema
* @param creator
* @return
* @throws Exception
*/
JSONObject verifyRequest(RequestMethod method, String name, JSONObject target, JSONObject request,
int maxUpdateCount, String globalDatabase, String globalSchema, SQLCreator creator) throws Exception;
/**验证返回结果的数据和结构
* @param method
* @param name
* @param target
* @param response
* @param database
* @param schema
* @param creator
* @param callback
* @return
* @throws Exception
*/
JSONObject verifyResponse(
RequestMethod method, String name, JSONObject target, JSONObject response,
String database, String schema, SQLCreator creator, OnParseCallback callback
) throws Exception;
@NotNull
Parser<T> createParser();
@NotNull
Visitor<T> getVisitor();
Verifier<T> setVisitor(@NotNull Visitor<T> visitor);
String getVisitorIdKey(SQLConfig config);
}
| Tencent/APIJSON | APIJSONORM/src/main/java/apijson/orm/Verifier.java |
1,487 | package io.mycat.statistic.stat;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import io.mycat.MycatServer;
import io.mycat.server.parser.ServerParse;
import io.mycat.statistic.SQLRecord;
import io.mycat.statistic.SQLRecorder;
/**
* 用户状态
*
* @author Ben
*/
public class UserStat {
private long SQL_SLOW_TIME = 100;
private String user;
/**
* 最大的并发
*/
private final AtomicInteger runningCount = new AtomicInteger();
private final AtomicInteger concurrentMax = new AtomicInteger();
/**
* SQL 大集合插入、返回记录
*/
private UserSqlLargeStat sqlLargeStat = null;
/**
* SQL 执行记录
*/
private UserSqlLastStat sqlLastStat = null;
/**
* CURD 执行分布
*/
private UserSqlRWStat sqlRwStat = null;
/**
* 用户高频SQL分析
*/
private UserSqlHighStat sqlHighStat = null;
/**
* 慢查询记录器 TOP 10
*/
private SQLRecorder sqlRecorder;
/**
* 大结果集记录
*/
private SqlResultSizeRecorder sqlResultSizeRecorder = null;
/**
* 读写锁
*/
// private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public UserStat(String user) {
super();
int size = MycatServer.getInstance().getConfig().getSystem().getSqlRecordCount();
this.user = user;
this.sqlRwStat = new UserSqlRWStat();
this.sqlLastStat = new UserSqlLastStat(50);
this.sqlLargeStat = new UserSqlLargeStat(10);
this.sqlHighStat = new UserSqlHighStat();
this.sqlRecorder = new SQLRecorder( size );
this.sqlResultSizeRecorder = new SqlResultSizeRecorder();
}
public String getUser() {
return user;
}
public SQLRecorder getSqlRecorder() {
return sqlRecorder;
}
public UserSqlRWStat getRWStat() {
return sqlRwStat;
}
public UserSqlLastStat getSqlLastStat() {
return this.sqlLastStat;
}
public UserSqlLargeStat getSqlLargeRowStat() {
return this.sqlLargeStat;
}
public UserSqlHighStat getSqlHigh(){
return this.sqlHighStat;
}
public SqlResultSizeRecorder getSqlResultSizeRecorder() {
return this.sqlResultSizeRecorder;
}
public void setSlowTime(long time) {
this.SQL_SLOW_TIME = time;
this.sqlRecorder.clear();
}
public void clearSql() {
this.sqlLastStat.reset();
}
public void clearSqlslow() {
this.sqlRecorder.clear();
}
public void clearRwStat() {
this.sqlRwStat.reset();
}
public void reset() {
this.sqlRecorder.clear();
this.sqlResultSizeRecorder.clearSqlResultSet();
this.sqlRwStat.reset();
this.sqlLastStat.reset();
this.runningCount.set(0);
this.concurrentMax.set(0);
}
/**
* 更新状态
*
* @param sqlType
* @param sql
* @param startTime
*/
public void update(String schema, int sqlType, String sql, long sqlRows,
long netInBytes, long netOutBytes, long startTime, long endTime ,int rseultSetSize,String host) {
//before 计算最大并发数
//-----------------------------------------------------
int invoking = runningCount.incrementAndGet();
for (;;) {
int max = concurrentMax.get();
if (invoking > max) {
if (concurrentMax.compareAndSet(max, invoking)) {
break;
}
} else {
break;
}
}
//-----------------------------------------------------
// this.lock.writeLock().lock();
// try {
//慢查询记录
long executeTime = endTime - startTime;
if ( executeTime >= SQL_SLOW_TIME ){
SQLRecord record = new SQLRecord();
record.executeTime = executeTime;
record.statement = sql;
record.startTime = startTime;
record.host = host;
record.schema = schema;
this.sqlRecorder.add(record);
}
//执行状态记录
this.sqlRwStat.setConcurrentMax( concurrentMax.get() );
this.sqlRwStat.add(sqlType, sql, executeTime, netInBytes, netOutBytes, startTime, endTime);
//记录最新执行的SQL
this.sqlLastStat.add(sql, executeTime, startTime, endTime ,host);
//记录高频SQL
this.sqlHighStat.addSql(sql, executeTime, startTime, endTime,host);
//记录SQL Select 返回超过 10000 行的 大结果集
if ( sqlType == ServerParse.SELECT && sqlRows > 10000 ) {
this.sqlLargeStat.add(sql, sqlRows, executeTime, startTime, endTime,host);
}
//记录超过阈值的大结果集sql
if(rseultSetSize>=MycatServer.getInstance().getConfig().getSystem().getMaxResultSet()){
this.sqlResultSizeRecorder.addSql(sql, rseultSetSize);
}
// } finally {
// this.lock.writeLock().unlock();
// }
//after
//-----------------------------------------------------
runningCount.decrementAndGet();
}
} | MyCATApache/Mycat-Server | src/main/java/io/mycat/statistic/stat/UserStat.java |
1,490 | class Solution {
private int[] dirs = {-1, 0, 1, 0, -1};
public int shortestPathAllKeys(String[] grid) {
int m = grid.length, n = grid[0].length();
int k = 0;
int si = 0, sj = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
char c = grid[i].charAt(j);
if (Character.isLowerCase(c)) {
// 累加钥匙数量
++k;
} else if (c == '@') {
// 起点
si = i;
sj = j;
}
}
}
Deque<int[]> q = new ArrayDeque<>();
q.offer(new int[] {si, sj, 0});
boolean[][][] vis = new boolean[m][n][1 << k];
vis[si][sj][0] = true;
int ans = 0;
while (!q.isEmpty()) {
for (int t = q.size(); t > 0; --t) {
var p = q.poll();
int i = p[0], j = p[1], state = p[2];
// 找到所有钥匙,返回当前步数
if (state == (1 << k) - 1) {
return ans;
}
// 往四个方向搜索
for (int h = 0; h < 4; ++h) {
int x = i + dirs[h], y = j + dirs[h + 1];
// 在边界范围内
if (x >= 0 && x < m && y >= 0 && y < n) {
char c = grid[x].charAt(y);
// 是墙,或者是锁,但此时没有对应的钥匙,无法通过
if (c == '#'
|| (Character.isUpperCase(c) && ((state >> (c - 'A')) & 1) == 0)) {
continue;
}
int nxt = state;
// 是钥匙
if (Character.isLowerCase(c)) {
// 更新状态
nxt |= 1 << (c - 'a');
}
// 此状态未访问过,入队
if (!vis[x][y][nxt]) {
vis[x][y][nxt] = true;
q.offer(new int[] {x, y, nxt});
}
}
}
}
// 步数加一
++ans;
}
return -1;
}
} | doocs/leetcode | solution/0800-0899/0864.Shortest Path to Get All Keys/Solution.java |
1,491 | package org.nutz.lang;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Enumeration;
import java.util.regex.Matcher;
import javax.servlet.http.HttpServletRequest;
import org.nutz.lang.stream.StringOutputStream;
/**
* 显示对象的信息,为日志以及调试提供帮助的函数集
*
* @author zozoh([email protected])
* @author wendal([email protected])
* @author bonyfish([email protected])
*/
public abstract class Dumps {
/**
* 显示 Matcher 的详细信息
*
* @param m
* Matcher 对象,必须未执行过 find
* @return 信息
*/
public static String matcher(Matcher m) {
if (m.find())
return matcherFound(m);
return "No found!";
}
/**
* 显示 Matcher 的详细信息
*
* @param m
* Matcher 对象,必须执行过 find
* @return 信息
*/
public static String matcherFound(Matcher m) {
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d/%d Regin:%d/%d\n",
m.start(),
m.end(),
m.regionStart(),
m.regionEnd()));
for (int i = 0; i <= m.groupCount(); i++)
sb.append(String.format("%2d:[%3d,%3d) `%s`\n", i, m.start(i), m.end(i), m.group(i)));
return sb.toString();
}
/**
* 显示一个对象所有个 getter 函数返回,以及 public 的 Field 的值
*
* @param obj
* 对象
* @return 信息
*/
public static String obj(Object obj) {
if (null == obj)
return "null";
StringBuilder sb = new StringBuilder(obj.getClass().getName() + "\n\n[Fields:]");
Mirror<?> mirror = Mirror.me(obj.getClass());
for (Field f : mirror.getType().getFields())
if (Modifier.isPublic(f.getModifiers()))
try {
sb.append(String.format("\n\t%10s : %s", f.getName(), f.get(obj)));
}
catch (Exception e1) {
sb.append(String.format("\n\t%10s : %s", f.getName(), e1.getMessage()));
}
sb.append("\n\n[Methods:]");
for (Method m : mirror.getType().getMethods())
if (Modifier.isPublic(m.getModifiers()))
if (m.getName().startsWith("get"))
if (m.getParameterTypes().length == 0)
try {
sb.append(String.format("\n\t%10s : %s", m.getName(), m.invoke(obj)));
}
catch (Exception e) {
sb.append(String.format("\n\t%10s : %s", m.getName(), e.getMessage()));
}
return sb.toString();
}
/**
* 显示 HTTP 内容的名称空间
*/
public static class HTTP {
public static enum MODE {
ALL, HEADER_ONLY, BODY_ONLY
}
/**
* 详细显示一个 HTTP 请求的全部内容
*
* @param req
* 请求对象
* @param ops
* 内容的输出流
* @param mode
* 显示 HTTP 头信息的模式: MODE.ALL or MODE.HEADER_ONLY
*/
public static void http(HttpServletRequest req, OutputStream ops, MODE mode) {
InputStream ins;
int b;
try {
/*
* Header
*/
if (MODE.ALL == mode || MODE.HEADER_ONLY == mode) {
StringBuilder sb = new StringBuilder();
Enumeration<?> ens = req.getHeaderNames();
while (ens.hasMoreElements()) {
String name = ens.nextElement().toString();
sb.append(name).append(": ").append(req.getHeader(name)).append("\r\n");
}
sb.append("\r\n");
ins = Lang.ins(sb);
while (-1 != (b = ins.read()))
ops.write(b);
}
/*
* Body
*/
if (MODE.ALL == mode || MODE.BODY_ONLY == mode) {
ins = req.getInputStream();
while (-1 != (b = ins.read()))
ops.write(b);
ins.close();
}
ops.flush();
ops.close();
}
catch (IOException e) {
throw Lang.wrapThrow(e);
}
}
/**
* 详细显示一个 HTTP 请求的全部内容
*
* @param req
* 请求对象
* @param mode
* 显示 HTTP 头信息的模式: MODE.ALL or MODE.HEADER_ONLY
* @return 一个文本字符串表示 HTTP 的全部内容
*/
public static String http(HttpServletRequest req, MODE mode) {
StringBuilder sb = new StringBuilder();
OutputStream ops = new StringOutputStream(sb, req.getCharacterEncoding());
http(req, ops, mode);
return sb.toString();
}
public static void body(HttpServletRequest req, OutputStream ops) {
http(req, ops, MODE.BODY_ONLY);
}
public static String body(HttpServletRequest req) {
return http(req, MODE.BODY_ONLY);
}
public static void header(HttpServletRequest req, OutputStream ops) {
http(req, ops, MODE.HEADER_ONLY);
}
public static String header(HttpServletRequest req) {
return http(req, MODE.HEADER_ONLY);
}
public static void all(HttpServletRequest req, OutputStream ops) {
http(req, ops, MODE.ALL);
}
public static String all(HttpServletRequest req) {
return http(req, MODE.ALL);
}
}
}
| nutzam/nutz | src/org/nutz/lang/Dumps.java |
1,492 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.sys.utils;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.method.HandlerMethod;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.Exceptions;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.dao.LogDao;
import com.thinkgem.jeesite.modules.sys.dao.MenuDao;
import com.thinkgem.jeesite.modules.sys.entity.Log;
import com.thinkgem.jeesite.modules.sys.entity.Menu;
import com.thinkgem.jeesite.modules.sys.entity.User;
/**
* 日志工具类
* @author ThinkGem
* @version 2014-11-7
*/
public class LogUtils {
public static final String CACHE_MENU_NAME_PATH_MAP = "menuNamePathMap";
private static LogDao logDao = SpringContextHolder.getBean(LogDao.class);
private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
/**
* 保存日志
*/
public static void saveLog(HttpServletRequest request, String title){
saveLog(request, null, null, title);
}
/**
* 保存日志
*/
public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title){
User user = UserUtils.getUser();
if (user != null && user.getId() != null){
Log log = new Log();
log.setTitle(title);
log.setType(ex == null ? Log.TYPE_ACCESS : Log.TYPE_EXCEPTION);
log.setRemoteAddr(StringUtils.getRemoteAddr(request));
log.setUserAgent(request.getHeader("user-agent"));
log.setRequestUri(request.getRequestURI());
log.setParams(request.getParameterMap());
log.setMethod(request.getMethod());
log.preInsert();
// 异步保存日志
new SaveLogThread(log, handler, ex).start();
}
}
/**
* 保存日志线程
*/
public static class SaveLogThread extends Thread{
private Log log;
private Object handler;
private Exception ex;
public SaveLogThread(Log log, Object handler, Exception ex){
super(SaveLogThread.class.getSimpleName());
this.log = log;
this.handler = handler;
this.ex = ex;
}
@Override
public void run() {
// 获取日志标题
if (StringUtils.isBlank(log.getTitle())){
String permission = "";
if (handler instanceof HandlerMethod){
Method m = ((HandlerMethod)handler).getMethod();
RequiresPermissions rp = m.getAnnotation(RequiresPermissions.class);
permission = (rp != null ? StringUtils.join(rp.value(), ",") : "");
}
log.setTitle(getMenuNamePath(log.getRequestUri(), permission));
}
// 如果有异常,设置异常信息
log.setException(Exceptions.getStackTraceAsString(ex));
// 如果无标题并无异常日志,则不保存信息
if (StringUtils.isBlank(log.getTitle()) && StringUtils.isBlank(log.getException())){
return;
}
// 保存日志信息
logDao.insert(log);
}
}
/**
* 获取菜单名称路径(如:系统设置-机构用户-用户管理-编辑)
*/
public static String getMenuNamePath(String requestUri, String permission){
String href = StringUtils.substringAfter(requestUri, Global.getAdminPath());
@SuppressWarnings("unchecked")
Map<String, String> menuMap = (Map<String, String>)CacheUtils.get(CACHE_MENU_NAME_PATH_MAP);
if (menuMap == null){
menuMap = Maps.newHashMap();
List<Menu> menuList = menuDao.findAllList(new Menu());
for (Menu menu : menuList){
// 获取菜单名称路径(如:系统设置-机构用户-用户管理-编辑)
String namePath = "";
if (menu.getParentIds() != null){
List<String> namePathList = Lists.newArrayList();
for (String id : StringUtils.split(menu.getParentIds(), ",")){
if (Menu.getRootId().equals(id)){
continue; // 过滤跟节点
}
for (Menu m : menuList){
if (m.getId().equals(id)){
namePathList.add(m.getName());
break;
}
}
}
namePathList.add(menu.getName());
namePath = StringUtils.join(namePathList, "-");
}
// 设置菜单名称路径
if (StringUtils.isNotBlank(menu.getHref())){
menuMap.put(menu.getHref(), namePath);
}else if (StringUtils.isNotBlank(menu.getPermission())){
for (String p : StringUtils.split(menu.getPermission())){
menuMap.put(p, namePath);
}
}
}
CacheUtils.put(CACHE_MENU_NAME_PATH_MAP, menuMap);
}
String menuNamePath = menuMap.get(href);
if (menuNamePath == null){
for (String p : StringUtils.split(permission)){
menuNamePath = menuMap.get(p);
if (StringUtils.isNotBlank(menuNamePath)){
break;
}
}
if (menuNamePath == null){
return "";
}
}
return menuNamePath;
}
}
| thinkgem/jeesite | src/main/java/com/thinkgem/jeesite/modules/sys/utils/LogUtils.java |
1,495 | package com.example.gsyvideoplayer;
import android.annotation.TargetApi;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.transition.Transition;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;
import com.example.gsyvideoplayer.databinding.ActivityPlayBinding;
import com.example.gsyvideoplayer.databinding.ActivityPlayTvBinding;
import com.example.gsyvideoplayer.listener.OnTransitionListener;
import com.example.gsyvideoplayer.model.SwitchVideoModel;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 单独的视频播放页面
* Created by Bill on 2023/7/25.
*/
public class PlayTVActivity extends AppCompatActivity {
public final static String IMG_TRANSITION = "IMG_TRANSITION";
public final static String TRANSITION = "TRANSITION";
OrientationUtils orientationUtils;
private boolean isTransition;
private Transition transition;
private ActivityPlayTvBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityPlayTvBinding.inflate(getLayoutInflater());
View rootView = binding.getRoot();
setContentView(rootView);
isTransition = getIntent().getBooleanExtra(TRANSITION, false);
init();
}
private void init() {
String url = "https://res.exexm.com/cw_145225549855002";
//String url = "http://7xse1z.com1.z0.glb.clouddn.com/1491813192";
//需要路径的
//videoPlayer.setUp(url, true, new File(FileUtils.getPath()), "");
//借用了jjdxm_ijkplayer的URL
String source1 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear1/prog_index.m3u8";
String name = "普通";
SwitchVideoModel switchVideoModel = new SwitchVideoModel(name, source1);
String source2 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear3/prog_index.m3u8";
String name2 = "清晰";
SwitchVideoModel switchVideoModel2 = new SwitchVideoModel(name2, source2);
List<SwitchVideoModel> list = new ArrayList<>();
list.add(switchVideoModel);
list.add(switchVideoModel2);
binding.videoPlayerTv.setUp(list.get(0).getUrl(), false, "测试视频");
//增加封面
ImageView imageView = new ImageView(this);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(R.mipmap.xxx1);
binding.videoPlayerTv.setThumbImageView(imageView);
//增加title
binding.videoPlayerTv.getTitleTextView().setVisibility(View.VISIBLE);
//videoPlayer.setShowPauseCover(false);
//videoPlayer.setSpeed(2f);
//设置返回键
binding.videoPlayerTv.getBackButton().setVisibility(View.VISIBLE);
//设置旋转
orientationUtils = new OrientationUtils(this, binding.videoPlayerTv);
//设置全屏按键功能,这是使用的是选择屏幕,而不是全屏
binding.videoPlayerTv.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ------- !!!如果不需要旋转屏幕,可以不调用!!!-------
// 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false)
orientationUtils.resolveByClick();
}
});
//videoPlayer.setBottomProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_progress));
//videoPlayer.setDialogVolumeProgressBar(getResources().getDrawable(R.drawable.video_new_volume_progress_bg));
//videoPlayer.setDialogProgressBar(getResources().getDrawable(R.drawable.video_new_progress));
//videoPlayer.setBottomShowProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_seekbar_progress),
//getResources().getDrawable(R.drawable.video_new_seekbar_thumb));
//videoPlayer.setDialogProgressColor(getResources().getColor(R.color.colorAccent), -11);
//是否可以滑动调整
binding.videoPlayerTv.setIsTouchWiget(true);
//设置返回按键功能
binding.videoPlayerTv.getBackButton().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
//过渡动画
initTransition();
}
@Override
protected void onPause() {
super.onPause();
binding.videoPlayerTv.onVideoPause();
}
@Override
protected void onResume() {
super.onResume();
binding.videoPlayerTv.onVideoResume();
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onDestroy() {
super.onDestroy();
if (orientationUtils != null)
orientationUtils.releaseListener();
}
@Override
public void onBackPressed() {
//先返回正常状态
if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
binding.videoPlayerTv.getFullscreenButton().performClick();
return;
}
//释放所有
binding.videoPlayerTv.setVideoAllCallBack(null);
GSYVideoManager.releaseAllVideos();
if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
super.onBackPressed();
} else {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
overridePendingTransition(androidx.appcompat.R.anim.abc_fade_in, androidx.appcompat.R.anim.abc_fade_out);
}
}, 500);
}
}
private void initTransition() {
if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
postponeEnterTransition();
ViewCompat.setTransitionName(binding.videoPlayerTv, IMG_TRANSITION);
addTransitionListener();
startPostponedEnterTransition();
} else {
binding.videoPlayerTv.startPlayLogic();
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean addTransitionListener() {
transition = getWindow().getSharedElementEnterTransition();
if (transition != null) {
transition.addListener(new OnTransitionListener() {
@Override
public void onTransitionEnd(Transition transition) {
super.onTransitionEnd(transition);
binding.videoPlayerTv.startPlayLogic();
transition.removeListener(this);
}
});
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
binding.videoPlayerTv.onKeyDown(keyCode,event);
return super.onKeyDown(keyCode, event);
}
}
| CarGuo/GSYVideoPlayer | app/src/main/java/com/example/gsyvideoplayer/PlayTVActivity.java |
1,496 | package com.xxl.job.admin.controller;
import com.xxl.job.admin.core.complete.XxlJobCompleter;
import com.xxl.job.admin.core.exception.XxlJobException;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import com.xxl.job.admin.core.scheduler.XxlJobScheduler;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.dao.XxlJobGroupDao;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import com.xxl.job.admin.dao.XxlJobLogDao;
import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.model.KillParam;
import com.xxl.job.core.biz.model.LogParam;
import com.xxl.job.core.biz.model.LogResult;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* index controller
* @author xuxueli 2015-12-19 16:13:16
*/
@Controller
@RequestMapping("/joblog")
public class JobLogController {
private static Logger logger = LoggerFactory.getLogger(JobLogController.class);
@Resource
private XxlJobGroupDao xxlJobGroupDao;
@Resource
public XxlJobInfoDao xxlJobInfoDao;
@Resource
public XxlJobLogDao xxlJobLogDao;
@RequestMapping
public String index(HttpServletRequest request, Model model, @RequestParam(required = false, defaultValue = "0") Integer jobId) {
// 执行器列表
List<XxlJobGroup> jobGroupList_all = xxlJobGroupDao.findAll();
// filter group
List<XxlJobGroup> jobGroupList = JobInfoController.filterJobGroupByRole(request, jobGroupList_all);
if (jobGroupList==null || jobGroupList.size()==0) {
throw new XxlJobException(I18nUtil.getString("jobgroup_empty"));
}
model.addAttribute("JobGroupList", jobGroupList);
// 任务
if (jobId > 0) {
XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId);
if (jobInfo == null) {
throw new RuntimeException(I18nUtil.getString("jobinfo_field_id") + I18nUtil.getString("system_unvalid"));
}
model.addAttribute("jobInfo", jobInfo);
// valid permission
JobInfoController.validPermission(request, jobInfo.getJobGroup());
}
return "joblog/joblog.index";
}
@RequestMapping("/getJobsByGroup")
@ResponseBody
public ReturnT<List<XxlJobInfo>> getJobsByGroup(int jobGroup){
List<XxlJobInfo> list = xxlJobInfoDao.getJobsByGroup(jobGroup);
return new ReturnT<List<XxlJobInfo>>(list);
}
@RequestMapping("/pageList")
@ResponseBody
public Map<String, Object> pageList(HttpServletRequest request,
@RequestParam(required = false, defaultValue = "0") int start,
@RequestParam(required = false, defaultValue = "10") int length,
int jobGroup, int jobId, int logStatus, String filterTime) {
// valid permission
JobInfoController.validPermission(request, jobGroup); // 仅管理员支持查询全部;普通用户仅支持查询有权限的 jobGroup
// parse param
Date triggerTimeStart = null;
Date triggerTimeEnd = null;
if (filterTime!=null && filterTime.trim().length()>0) {
String[] temp = filterTime.split(" - ");
if (temp.length == 2) {
triggerTimeStart = DateUtil.parseDateTime(temp[0]);
triggerTimeEnd = DateUtil.parseDateTime(temp[1]);
}
}
// page query
List<XxlJobLog> list = xxlJobLogDao.pageList(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
int list_count = xxlJobLogDao.pageListCount(start, length, jobGroup, jobId, triggerTimeStart, triggerTimeEnd, logStatus);
// package result
Map<String, Object> maps = new HashMap<String, Object>();
maps.put("recordsTotal", list_count); // 总记录数
maps.put("recordsFiltered", list_count); // 过滤后的总记录数
maps.put("data", list); // 分页列表
return maps;
}
@RequestMapping("/logDetailPage")
public String logDetailPage(int id, Model model){
// base check
ReturnT<String> logStatue = ReturnT.SUCCESS;
XxlJobLog jobLog = xxlJobLogDao.load(id);
if (jobLog == null) {
throw new RuntimeException(I18nUtil.getString("joblog_logid_unvalid"));
}
model.addAttribute("triggerCode", jobLog.getTriggerCode());
model.addAttribute("handleCode", jobLog.getHandleCode());
model.addAttribute("logId", jobLog.getId());
return "joblog/joblog.detail";
}
@RequestMapping("/logDetailCat")
@ResponseBody
public ReturnT<LogResult> logDetailCat(long logId, int fromLineNum){
try {
// valid
XxlJobLog jobLog = xxlJobLogDao.load(logId); // todo, need to improve performance
if (jobLog == null) {
return new ReturnT<LogResult>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_logid_unvalid"));
}
// log cat
ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(jobLog.getExecutorAddress());
ReturnT<LogResult> logResult = executorBiz.log(new LogParam(jobLog.getTriggerTime().getTime(), logId, fromLineNum));
// is end
if (logResult.getContent()!=null && logResult.getContent().getFromLineNum() > logResult.getContent().getToLineNum()) {
if (jobLog.getHandleCode() > 0) {
logResult.getContent().setEnd(true);
}
}
// fix xss
if (logResult.getContent()!=null && StringUtils.hasText(logResult.getContent().getLogContent())) {
String newLogContent = logResult.getContent().getLogContent();
newLogContent = HtmlUtils.htmlEscape(newLogContent, "UTF-8");
logResult.getContent().setLogContent(newLogContent);
}
return logResult;
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<LogResult>(ReturnT.FAIL_CODE, e.getMessage());
}
}
@RequestMapping("/logKill")
@ResponseBody
public ReturnT<String> logKill(int id){
// base check
XxlJobLog log = xxlJobLogDao.load(id);
XxlJobInfo jobInfo = xxlJobInfoDao.loadById(log.getJobId());
if (jobInfo==null) {
return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_jobid_unvalid"));
}
if (ReturnT.SUCCESS_CODE != log.getTriggerCode()) {
return new ReturnT<String>(500, I18nUtil.getString("joblog_kill_log_limit"));
}
// request of kill
ReturnT<String> runResult = null;
try {
ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(log.getExecutorAddress());
runResult = executorBiz.kill(new KillParam(jobInfo.getId()));
} catch (Exception e) {
logger.error(e.getMessage(), e);
runResult = new ReturnT<String>(500, e.getMessage());
}
if (ReturnT.SUCCESS_CODE == runResult.getCode()) {
log.setHandleCode(ReturnT.FAIL_CODE);
log.setHandleMsg( I18nUtil.getString("joblog_kill_log_byman")+":" + (runResult.getMsg()!=null?runResult.getMsg():""));
log.setHandleTime(new Date());
XxlJobCompleter.updateHandleInfoAndFinish(log);
return new ReturnT<String>(runResult.getMsg());
} else {
return new ReturnT<String>(500, runResult.getMsg());
}
}
@RequestMapping("/clearLog")
@ResponseBody
public ReturnT<String> clearLog(int jobGroup, int jobId, int type){
Date clearBeforeTime = null;
int clearBeforeNum = 0;
if (type == 1) {
clearBeforeTime = DateUtil.addMonths(new Date(), -1); // 清理一个月之前日志数据
} else if (type == 2) {
clearBeforeTime = DateUtil.addMonths(new Date(), -3); // 清理三个月之前日志数据
} else if (type == 3) {
clearBeforeTime = DateUtil.addMonths(new Date(), -6); // 清理六个月之前日志数据
} else if (type == 4) {
clearBeforeTime = DateUtil.addYears(new Date(), -1); // 清理一年之前日志数据
} else if (type == 5) {
clearBeforeNum = 1000; // 清理一千条以前日志数据
} else if (type == 6) {
clearBeforeNum = 10000; // 清理一万条以前日志数据
} else if (type == 7) {
clearBeforeNum = 30000; // 清理三万条以前日志数据
} else if (type == 8) {
clearBeforeNum = 100000; // 清理十万条以前日志数据
} else if (type == 9) {
clearBeforeNum = 0; // 清理所有日志数据
} else {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_clean_type_unvalid"));
}
List<Long> logIds = null;
do {
logIds = xxlJobLogDao.findClearLogIds(jobGroup, jobId, clearBeforeTime, clearBeforeNum, 1000);
if (logIds!=null && logIds.size()>0) {
xxlJobLogDao.clearLog(logIds);
}
} while (logIds!=null && logIds.size()>0);
return ReturnT.SUCCESS;
}
}
| xuxueli/xxl-job | xxl-job-admin/src/main/java/com/xxl/job/admin/controller/JobLogController.java |
1,497 | package com.xxl.job.admin.service.impl;
import com.xxl.job.admin.core.cron.CronExpression;
import com.xxl.job.admin.core.model.XxlJobGroup;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLogReport;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.core.route.ExecutorRouteStrategyEnum;
import com.xxl.job.admin.core.scheduler.MisfireStrategyEnum;
import com.xxl.job.admin.core.scheduler.ScheduleTypeEnum;
import com.xxl.job.admin.core.thread.JobScheduleHelper;
import com.xxl.job.admin.core.thread.JobTriggerPoolHelper;
import com.xxl.job.admin.core.trigger.TriggerTypeEnum;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.dao.*;
import com.xxl.job.admin.service.XxlJobService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import com.xxl.job.core.glue.GlueTypeEnum;
import com.xxl.job.core.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;
/**
* core job action for xxl-job
* @author xuxueli 2016-5-28 15:30:33
*/
@Service
public class XxlJobServiceImpl implements XxlJobService {
private static Logger logger = LoggerFactory.getLogger(XxlJobServiceImpl.class);
@Resource
private XxlJobGroupDao xxlJobGroupDao;
@Resource
private XxlJobInfoDao xxlJobInfoDao;
@Resource
public XxlJobLogDao xxlJobLogDao;
@Resource
private XxlJobLogGlueDao xxlJobLogGlueDao;
@Resource
private XxlJobLogReportDao xxlJobLogReportDao;
@Override
public Map<String, Object> pageList(int start, int length, int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) {
// page list
List<XxlJobInfo> list = xxlJobInfoDao.pageList(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author);
int list_count = xxlJobInfoDao.pageListCount(start, length, jobGroup, triggerStatus, jobDesc, executorHandler, author);
// package result
Map<String, Object> maps = new HashMap<String, Object>();
maps.put("recordsTotal", list_count); // 总记录数
maps.put("recordsFiltered", list_count); // 过滤后的总记录数
maps.put("data", list); // 分页列表
return maps;
}
@Override
public ReturnT<String> add(XxlJobInfo jobInfo) {
// valid base
XxlJobGroup group = xxlJobGroupDao.load(jobInfo.getJobGroup());
if (group == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_choose")+I18nUtil.getString("jobinfo_field_jobgroup")) );
}
if (jobInfo.getJobDesc()==null || jobInfo.getJobDesc().trim().length()==0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_jobdesc")) );
}
if (jobInfo.getAuthor()==null || jobInfo.getAuthor().trim().length()==0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_author")) );
}
// valid trigger
ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(jobInfo.getScheduleType(), null);
if (scheduleTypeEnum == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
if (scheduleTypeEnum == ScheduleTypeEnum.CRON) {
if (jobInfo.getScheduleConf()==null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron"+I18nUtil.getString("system_unvalid"));
}
} else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE/* || scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/) {
if (jobInfo.getScheduleConf() == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")) );
}
try {
int fixSecond = Integer.valueOf(jobInfo.getScheduleConf());
if (fixSecond < 1) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
} catch (Exception e) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
}
// valid job
if (GlueTypeEnum.match(jobInfo.getGlueType()) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_gluetype")+I18nUtil.getString("system_unvalid")) );
}
if (GlueTypeEnum.BEAN==GlueTypeEnum.match(jobInfo.getGlueType()) && (jobInfo.getExecutorHandler()==null || jobInfo.getExecutorHandler().trim().length()==0) ) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+"JobHandler") );
}
// 》fix "\r" in shell
if (GlueTypeEnum.GLUE_SHELL==GlueTypeEnum.match(jobInfo.getGlueType()) && jobInfo.getGlueSource()!=null) {
jobInfo.setGlueSource(jobInfo.getGlueSource().replaceAll("\r", ""));
}
// valid advanced
if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorRouteStrategy")+I18nUtil.getString("system_unvalid")) );
}
if (MisfireStrategyEnum.match(jobInfo.getMisfireStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("misfire_strategy")+I18nUtil.getString("system_unvalid")) );
}
if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorBlockStrategy")+I18nUtil.getString("system_unvalid")) );
}
// 》ChildJobId valid
if (jobInfo.getChildJobId()!=null && jobInfo.getChildJobId().trim().length()>0) {
String[] childJobIds = jobInfo.getChildJobId().split(",");
for (String childJobIdItem: childJobIds) {
if (childJobIdItem!=null && childJobIdItem.trim().length()>0 && isNumeric(childJobIdItem)) {
XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.parseInt(childJobIdItem));
if (childJobInfo==null) {
return new ReturnT<String>(ReturnT.FAIL_CODE,
MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_not_found")), childJobIdItem));
}
} else {
return new ReturnT<String>(ReturnT.FAIL_CODE,
MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_unvalid")), childJobIdItem));
}
}
// join , avoid "xxx,,"
String temp = "";
for (String item:childJobIds) {
temp += item + ",";
}
temp = temp.substring(0, temp.length()-1);
jobInfo.setChildJobId(temp);
}
// add in db
jobInfo.setAddTime(new Date());
jobInfo.setUpdateTime(new Date());
jobInfo.setGlueUpdatetime(new Date());
xxlJobInfoDao.save(jobInfo);
if (jobInfo.getId() < 1) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_add")+I18nUtil.getString("system_fail")) );
}
return new ReturnT<String>(String.valueOf(jobInfo.getId()));
}
private boolean isNumeric(String str){
try {
int result = Integer.valueOf(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public ReturnT<String> update(XxlJobInfo jobInfo) {
// valid base
if (jobInfo.getJobDesc()==null || jobInfo.getJobDesc().trim().length()==0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_jobdesc")) );
}
if (jobInfo.getAuthor()==null || jobInfo.getAuthor().trim().length()==0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("system_please_input")+I18nUtil.getString("jobinfo_field_author")) );
}
// valid trigger
ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(jobInfo.getScheduleType(), null);
if (scheduleTypeEnum == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
if (scheduleTypeEnum == ScheduleTypeEnum.CRON) {
if (jobInfo.getScheduleConf()==null || !CronExpression.isValidExpression(jobInfo.getScheduleConf())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Cron"+I18nUtil.getString("system_unvalid") );
}
} else if (scheduleTypeEnum == ScheduleTypeEnum.FIX_RATE /*|| scheduleTypeEnum == ScheduleTypeEnum.FIX_DELAY*/) {
if (jobInfo.getScheduleConf() == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
try {
int fixSecond = Integer.valueOf(jobInfo.getScheduleConf());
if (fixSecond < 1) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
} catch (Exception e) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
}
// valid advanced
if (ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorRouteStrategy")+I18nUtil.getString("system_unvalid")) );
}
if (MisfireStrategyEnum.match(jobInfo.getMisfireStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("misfire_strategy")+I18nUtil.getString("system_unvalid")) );
}
if (ExecutorBlockStrategyEnum.match(jobInfo.getExecutorBlockStrategy(), null) == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_executorBlockStrategy")+I18nUtil.getString("system_unvalid")) );
}
// 》ChildJobId valid
if (jobInfo.getChildJobId()!=null && jobInfo.getChildJobId().trim().length()>0) {
String[] childJobIds = jobInfo.getChildJobId().split(",");
for (String childJobIdItem: childJobIds) {
if (childJobIdItem!=null && childJobIdItem.trim().length()>0 && isNumeric(childJobIdItem)) {
XxlJobInfo childJobInfo = xxlJobInfoDao.loadById(Integer.parseInt(childJobIdItem));
if (childJobInfo==null) {
return new ReturnT<String>(ReturnT.FAIL_CODE,
MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_not_found")), childJobIdItem));
}
} else {
return new ReturnT<String>(ReturnT.FAIL_CODE,
MessageFormat.format((I18nUtil.getString("jobinfo_field_childJobId")+"({0})"+I18nUtil.getString("system_unvalid")), childJobIdItem));
}
}
// join , avoid "xxx,,"
String temp = "";
for (String item:childJobIds) {
temp += item + ",";
}
temp = temp.substring(0, temp.length()-1);
jobInfo.setChildJobId(temp);
}
// group valid
XxlJobGroup jobGroup = xxlJobGroupDao.load(jobInfo.getJobGroup());
if (jobGroup == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_jobgroup")+I18nUtil.getString("system_unvalid")) );
}
// stage job info
XxlJobInfo exists_jobInfo = xxlJobInfoDao.loadById(jobInfo.getId());
if (exists_jobInfo == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_id")+I18nUtil.getString("system_not_found")) );
}
// next trigger time (5s后生效,避开预读周期)
long nextTriggerTime = exists_jobInfo.getTriggerNextTime();
boolean scheduleDataNotChanged = jobInfo.getScheduleType().equals(exists_jobInfo.getScheduleType()) && jobInfo.getScheduleConf().equals(exists_jobInfo.getScheduleConf());
if (exists_jobInfo.getTriggerStatus() == 1 && !scheduleDataNotChanged) {
try {
Date nextValidTime = JobScheduleHelper.generateNextValidTime(jobInfo, new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS));
if (nextValidTime == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
nextTriggerTime = nextValidTime.getTime();
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
}
exists_jobInfo.setJobGroup(jobInfo.getJobGroup());
exists_jobInfo.setJobDesc(jobInfo.getJobDesc());
exists_jobInfo.setAuthor(jobInfo.getAuthor());
exists_jobInfo.setAlarmEmail(jobInfo.getAlarmEmail());
exists_jobInfo.setScheduleType(jobInfo.getScheduleType());
exists_jobInfo.setScheduleConf(jobInfo.getScheduleConf());
exists_jobInfo.setMisfireStrategy(jobInfo.getMisfireStrategy());
exists_jobInfo.setExecutorRouteStrategy(jobInfo.getExecutorRouteStrategy());
exists_jobInfo.setExecutorHandler(jobInfo.getExecutorHandler());
exists_jobInfo.setExecutorParam(jobInfo.getExecutorParam());
exists_jobInfo.setExecutorBlockStrategy(jobInfo.getExecutorBlockStrategy());
exists_jobInfo.setExecutorTimeout(jobInfo.getExecutorTimeout());
exists_jobInfo.setExecutorFailRetryCount(jobInfo.getExecutorFailRetryCount());
exists_jobInfo.setChildJobId(jobInfo.getChildJobId());
exists_jobInfo.setTriggerNextTime(nextTriggerTime);
exists_jobInfo.setUpdateTime(new Date());
xxlJobInfoDao.update(exists_jobInfo);
return ReturnT.SUCCESS;
}
@Override
public ReturnT<String> remove(int id) {
XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id);
if (xxlJobInfo == null) {
return ReturnT.SUCCESS;
}
xxlJobInfoDao.delete(id);
xxlJobLogDao.delete(id);
xxlJobLogGlueDao.deleteByJobId(id);
return ReturnT.SUCCESS;
}
@Override
public ReturnT<String> start(int id) {
XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id);
// valid
ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(xxlJobInfo.getScheduleType(), ScheduleTypeEnum.NONE);
if (ScheduleTypeEnum.NONE == scheduleTypeEnum) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type_none_limit_start")) );
}
// next trigger time (5s后生效,避开预读周期)
long nextTriggerTime = 0;
try {
Date nextValidTime = JobScheduleHelper.generateNextValidTime(xxlJobInfo, new Date(System.currentTimeMillis() + JobScheduleHelper.PRE_READ_MS));
if (nextValidTime == null) {
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
nextTriggerTime = nextValidTime.getTime();
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("schedule_type")+I18nUtil.getString("system_unvalid")) );
}
xxlJobInfo.setTriggerStatus(1);
xxlJobInfo.setTriggerLastTime(0);
xxlJobInfo.setTriggerNextTime(nextTriggerTime);
xxlJobInfo.setUpdateTime(new Date());
xxlJobInfoDao.update(xxlJobInfo);
return ReturnT.SUCCESS;
}
@Override
public ReturnT<String> stop(int id) {
XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(id);
xxlJobInfo.setTriggerStatus(0);
xxlJobInfo.setTriggerLastTime(0);
xxlJobInfo.setTriggerNextTime(0);
xxlJobInfo.setUpdateTime(new Date());
xxlJobInfoDao.update(xxlJobInfo);
return ReturnT.SUCCESS;
}
@Override
public ReturnT<String> trigger(XxlJobUser loginUser, int jobId, String executorParam, String addressList) {
// permission
if (loginUser == null) {
return new ReturnT<String>(ReturnT.FAIL.getCode(), I18nUtil.getString("system_permission_limit"));
}
XxlJobInfo xxlJobInfo = xxlJobInfoDao.loadById(jobId);
if (xxlJobInfo == null) {
return new ReturnT<String>(ReturnT.FAIL.getCode(), I18nUtil.getString("jobinfo_glue_jobid_unvalid"));
}
if (!hasPermission(loginUser, xxlJobInfo.getJobGroup())) {
return new ReturnT<String>(ReturnT.FAIL.getCode(), I18nUtil.getString("system_permission_limit"));
}
// force cover job param
if (executorParam == null) {
executorParam = "";
}
JobTriggerPoolHelper.trigger(jobId, TriggerTypeEnum.MANUAL, -1, null, executorParam, addressList);
return ReturnT.SUCCESS;
}
private boolean hasPermission(XxlJobUser loginUser, int jobGroup){
if (loginUser.getRole() == 1) {
return true;
}
List<String> groupIdStrs = new ArrayList<>();
if (loginUser.getPermission()!=null && loginUser.getPermission().trim().length()>0) {
groupIdStrs = Arrays.asList(loginUser.getPermission().trim().split(","));
}
return groupIdStrs.contains(String.valueOf(jobGroup));
}
@Override
public Map<String, Object> dashboardInfo() {
int jobInfoCount = xxlJobInfoDao.findAllCount();
int jobLogCount = 0;
int jobLogSuccessCount = 0;
XxlJobLogReport xxlJobLogReport = xxlJobLogReportDao.queryLogReportTotal();
if (xxlJobLogReport != null) {
jobLogCount = xxlJobLogReport.getRunningCount() + xxlJobLogReport.getSucCount() + xxlJobLogReport.getFailCount();
jobLogSuccessCount = xxlJobLogReport.getSucCount();
}
// executor count
Set<String> executorAddressSet = new HashSet<String>();
List<XxlJobGroup> groupList = xxlJobGroupDao.findAll();
if (groupList!=null && !groupList.isEmpty()) {
for (XxlJobGroup group: groupList) {
if (group.getRegistryList()!=null && !group.getRegistryList().isEmpty()) {
executorAddressSet.addAll(group.getRegistryList());
}
}
}
int executorCount = executorAddressSet.size();
Map<String, Object> dashboardMap = new HashMap<String, Object>();
dashboardMap.put("jobInfoCount", jobInfoCount);
dashboardMap.put("jobLogCount", jobLogCount);
dashboardMap.put("jobLogSuccessCount", jobLogSuccessCount);
dashboardMap.put("executorCount", executorCount);
return dashboardMap;
}
@Override
public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate) {
// process
List<String> triggerDayList = new ArrayList<String>();
List<Integer> triggerDayCountRunningList = new ArrayList<Integer>();
List<Integer> triggerDayCountSucList = new ArrayList<Integer>();
List<Integer> triggerDayCountFailList = new ArrayList<Integer>();
int triggerCountRunningTotal = 0;
int triggerCountSucTotal = 0;
int triggerCountFailTotal = 0;
List<XxlJobLogReport> logReportList = xxlJobLogReportDao.queryLogReport(startDate, endDate);
if (logReportList!=null && logReportList.size()>0) {
for (XxlJobLogReport item: logReportList) {
String day = DateUtil.formatDate(item.getTriggerDay());
int triggerDayCountRunning = item.getRunningCount();
int triggerDayCountSuc = item.getSucCount();
int triggerDayCountFail = item.getFailCount();
triggerDayList.add(day);
triggerDayCountRunningList.add(triggerDayCountRunning);
triggerDayCountSucList.add(triggerDayCountSuc);
triggerDayCountFailList.add(triggerDayCountFail);
triggerCountRunningTotal += triggerDayCountRunning;
triggerCountSucTotal += triggerDayCountSuc;
triggerCountFailTotal += triggerDayCountFail;
}
} else {
for (int i = -6; i <= 0; i++) {
triggerDayList.add(DateUtil.formatDate(DateUtil.addDays(new Date(), i)));
triggerDayCountRunningList.add(0);
triggerDayCountSucList.add(0);
triggerDayCountFailList.add(0);
}
}
Map<String, Object> result = new HashMap<String, Object>();
result.put("triggerDayList", triggerDayList);
result.put("triggerDayCountRunningList", triggerDayCountRunningList);
result.put("triggerDayCountSucList", triggerDayCountSucList);
result.put("triggerDayCountFailList", triggerDayCountFailList);
result.put("triggerCountRunningTotal", triggerCountRunningTotal);
result.put("triggerCountSucTotal", triggerCountSucTotal);
result.put("triggerCountFailTotal", triggerCountFailTotal);
return new ReturnT<Map<String, Object>>(result);
}
}
| xuxueli/xxl-job | xxl-job-admin/src/main/java/com/xxl/job/admin/service/impl/XxlJobServiceImpl.java |
1,506 | /**
* POI封装实现<br>
* Java针对MS Office的操作的库屈指可数,比较有名的就是Apache的POI库。<br>
* 这个库异常强大,但是使用起来也并不容易。Hutool针对POI封装一些常用工具,使Java操作Excel等文件变得异常简单。
*
* @author looly
*
*/
package cn.hutool.poi; | dromara/hutool | hutool-poi/src/main/java/cn/hutool/poi/package-info.java |
1,509 | package org.nlpcn.es4sql.domain;
import java.util.LinkedList;
public class Where implements Cloneable{
public enum CONN {
AND, OR;
public CONN negative() {
return this == AND ? OR : AND;
}
}
public static Where newInstance() {
return new Where(CONN.AND);
}
//zhongshu-comment 只有wheres和conn这两个属性
private LinkedList<Where> wheres = new LinkedList<>();//zhongshu-comment 不会被子类Condition继承,但是子类可以通过get() set()方法访问吧?
protected CONN conn;
public Where(String connStr) {
this.conn = CONN.valueOf(connStr.toUpperCase());
}
public Where(CONN conn) {
this.conn = conn;
}
public void addWhere(Where where) {
wheres.add(where);
}
public CONN getConn() {
return this.conn;
}
public void setConn(CONN conn) {
this.conn = conn;
}
public LinkedList<Where> getWheres() {
return wheres;
}
@Override
public String toString(){
if(wheres.size()>0){
String whereStr = wheres.toString() ;
return this.conn + " ( "+whereStr.substring(1,whereStr.length()-1)+" ) " ;
}else{
return "" ;
}
}
@Override
public Object clone() throws CloneNotSupportedException {
Where clonedWhere = new Where(this.getConn());
for (Where innerWhere : this.getWheres()){
clonedWhere.addWhere((Where)innerWhere.clone());
}
return clonedWhere;
}
}
| NLPchina/elasticsearch-sql | src/main/java/org/nlpcn/es4sql/domain/Where.java |
1,511 | package me.zhyd.oauth.enums.scope;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 百度平台 OAuth 授权范围
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0.0
* @since 1.0.0
*/
@Getter
@AllArgsConstructor
public enum AuthBaiduScope implements AuthScope {
/**
* {@code scope} 含义,以{@code description} 为准
*/
BASIC("basic", "用户基本权限,可以获取用户的基本信息 。", true),
SUPER_MSG("super_msg", "往用户的百度首页上发送消息提醒,相关API任何应用都能使用,但要想将消息提醒在百度首页显示,需要第三方在注册应用时额外填写相关信息。", false),
NETDISK("netdisk", "获取用户在个人云存储中存放的数据。", false),
PUBLIC("public", "可以访问公共的开放API。", false),
HAO123("hao123", "可以访问Hao123 提供的开放API接口。该权限需要申请开通,请将具体的理由和用途发邮件给[email protected]。", false);
private final String scope;
private final String description;
private final boolean isDefault;
}
| justauth/JustAuth | src/main/java/me/zhyd/oauth/enums/scope/AuthBaiduScope.java |
1,517 | /**
* IK 中文分词 版本 5.0
* IK Analyzer release 5.0
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 源代码由林良益([email protected])提供
* 版权声明 2012,乌龙茶工作室
* provided by Linliangyi and copyright 2012 by Oolong studio
*
*/
package org.wltea.analyzer.core;
import java.util.Arrays;
/**
*
* 英文字符及阿拉伯数字子分词器
*/
class LetterSegmenter implements ISegmenter {
//子分词器标签
static final String SEGMENTER_NAME = "LETTER_SEGMENTER";
//链接符号
private static final char[] Letter_Connector = new char[]{'#' , '&' , '+' , '-' , '.' , '@' , '_'};
//数字符号
private static final char[] Num_Connector = new char[]{',' , '.'};
/*
* 词元的开始位置,
* 同时作为子分词器状态标识
* 当start > -1 时,标识当前的分词器正在处理字符
*/
private int start;
/*
* 记录词元结束位置
* end记录的是在词元中最后一个出现的Letter但非Sign_Connector的字符的位置
*/
private int end;
/*
* 字母起始位置
*/
private int englishStart;
/*
* 字母结束位置
*/
private int englishEnd;
/*
* 阿拉伯数字起始位置
*/
private int arabicStart;
/*
* 阿拉伯数字结束位置
*/
private int arabicEnd;
LetterSegmenter(){
Arrays.sort(Letter_Connector);
Arrays.sort(Num_Connector);
this.start = -1;
this.end = -1;
this.englishStart = -1;
this.englishEnd = -1;
this.arabicStart = -1;
this.arabicEnd = -1;
}
/* (non-Javadoc)
* @see org.wltea.analyzer.core.ISegmenter#analyze(org.wltea.analyzer.core.AnalyzeContext)
*/
public void analyze(AnalyzeContext context) {
boolean bufferLockFlag = false;
//处理英文字母
bufferLockFlag = this.processEnglishLetter(context) || bufferLockFlag;
//处理阿拉伯字母
bufferLockFlag = this.processArabicLetter(context) || bufferLockFlag;
//处理混合字母(这个要放最后处理,可以通过QuickSortSet排除重复)
bufferLockFlag = this.processMixLetter(context) || bufferLockFlag;
//判断是否锁定缓冲区
if(bufferLockFlag){
context.lockBuffer(SEGMENTER_NAME);
}else{
//对缓冲区解锁
context.unlockBuffer(SEGMENTER_NAME);
}
}
/* (non-Javadoc)
* @see org.wltea.analyzer.core.ISegmenter#reset()
*/
public void reset() {
this.start = -1;
this.end = -1;
this.englishStart = -1;
this.englishEnd = -1;
this.arabicStart = -1;
this.arabicEnd = -1;
}
/**
* 处理数字字母混合输出
* 如:windos2000 | [email protected]
// * @param input
* @param context
* @return
*/
private boolean processMixLetter(AnalyzeContext context){
boolean needLock = false;
if(this.start == -1){//当前的分词器尚未开始处理字符
if(CharacterUtil.CHAR_ARABIC == context.getCurrentCharType()
|| CharacterUtil.CHAR_ENGLISH == context.getCurrentCharType()){
//记录起始指针的位置,标明分词器进入处理状态
this.start = context.getCursor();
this.end = start;
}
}else{//当前的分词器正在处理字符
if(CharacterUtil.CHAR_ARABIC == context.getCurrentCharType()
|| CharacterUtil.CHAR_ENGLISH == context.getCurrentCharType()){
//记录下可能的结束位置
this.end = context.getCursor();
}else if(CharacterUtil.CHAR_USELESS == context.getCurrentCharType()
&& this.isLetterConnector(context.getCurrentChar())){
//记录下可能的结束位置
this.end = context.getCursor();
}else{
//遇到非Letter字符,输出词元
Lexeme newLexeme = new Lexeme(context.getBufferOffset() , this.start , this.end - this.start + 1 , Lexeme.TYPE_LETTER);
context.addLexeme(newLexeme);
this.start = -1;
this.end = -1;
}
}
//判断缓冲区是否已经读完
if(context.isBufferConsumed() && (this.start != -1 && this.end != -1)){
//缓冲以读完,输出词元
Lexeme newLexeme = new Lexeme(context.getBufferOffset() , this.start , this.end - this.start + 1 , Lexeme.TYPE_LETTER);
context.addLexeme(newLexeme);
this.start = -1;
this.end = -1;
}
//判断是否锁定缓冲区
if(this.start == -1 && this.end == -1){
//对缓冲区解锁
needLock = false;
}else{
needLock = true;
}
return needLock;
}
/**
* 处理纯英文字母输出
* @param context
* @return
*/
private boolean processEnglishLetter(AnalyzeContext context){
boolean needLock = false;
if(this.englishStart == -1){//当前的分词器尚未开始处理英文字符
if(CharacterUtil.CHAR_ENGLISH == context.getCurrentCharType()){
//记录起始指针的位置,标明分词器进入处理状态
this.englishStart = context.getCursor();
this.englishEnd = this.englishStart;
}
}else {//当前的分词器正在处理英文字符
if(CharacterUtil.CHAR_ENGLISH == context.getCurrentCharType()){
//记录当前指针位置为结束位置
this.englishEnd = context.getCursor();
}else{
//遇到非English字符,输出词元
Lexeme newLexeme = new Lexeme(context.getBufferOffset() , this.englishStart , this.englishEnd - this.englishStart + 1 , Lexeme.TYPE_ENGLISH);
context.addLexeme(newLexeme);
this.englishStart = -1;
this.englishEnd= -1;
}
}
//判断缓冲区是否已经读完
if(context.isBufferConsumed() && (this.englishStart != -1 && this.englishEnd != -1)){
//缓冲以读完,输出词元
Lexeme newLexeme = new Lexeme(context.getBufferOffset() , this.englishStart , this.englishEnd - this.englishStart + 1 , Lexeme.TYPE_ENGLISH);
context.addLexeme(newLexeme);
this.englishStart = -1;
this.englishEnd= -1;
}
//判断是否锁定缓冲区
if(this.englishStart == -1 && this.englishEnd == -1){
//对缓冲区解锁
needLock = false;
}else{
needLock = true;
}
return needLock;
}
/**
* 处理阿拉伯数字输出
* @param context
* @return
*/
private boolean processArabicLetter(AnalyzeContext context){
boolean needLock = false;
if(this.arabicStart == -1){//当前的分词器尚未开始处理数字字符
if(CharacterUtil.CHAR_ARABIC == context.getCurrentCharType()){
//记录起始指针的位置,标明分词器进入处理状态
this.arabicStart = context.getCursor();
this.arabicEnd = this.arabicStart;
}
}else {//当前的分词器正在处理数字字符
if(CharacterUtil.CHAR_ARABIC == context.getCurrentCharType()){
//记录当前指针位置为结束位置
this.arabicEnd = context.getCursor();
}else if(CharacterUtil.CHAR_USELESS == context.getCurrentCharType()
&& this.isNumConnector(context.getCurrentChar())){
//不输出数字,但不标记结束
}else{
////遇到非Arabic字符,输出词元
Lexeme newLexeme = new Lexeme(context.getBufferOffset() , this.arabicStart , this.arabicEnd - this.arabicStart + 1 , Lexeme.TYPE_ARABIC);
context.addLexeme(newLexeme);
this.arabicStart = -1;
this.arabicEnd = -1;
}
}
//判断缓冲区是否已经读完
if(context.isBufferConsumed() && (this.arabicStart != -1 && this.arabicEnd != -1)){
//生成已切分的词元
Lexeme newLexeme = new Lexeme(context.getBufferOffset() , this.arabicStart , this.arabicEnd - this.arabicStart + 1 , Lexeme.TYPE_ARABIC);
context.addLexeme(newLexeme);
this.arabicStart = -1;
this.arabicEnd = -1;
}
//判断是否锁定缓冲区
if(this.arabicStart == -1 && this.arabicEnd == -1){
//对缓冲区解锁
needLock = false;
}else{
needLock = true;
}
return needLock;
}
/**
* 判断是否是字母连接符号
* @param input
* @return
*/
private boolean isLetterConnector(char input){
int index = Arrays.binarySearch(Letter_Connector, input);
return index >= 0;
}
/**
* 判断是否是数字连接符号
* @param input
* @return
*/
private boolean isNumConnector(char input){
int index = Arrays.binarySearch(Num_Connector, input);
return index >= 0;
}
}
| infinilabs/analysis-ik | core/src/main/java/org/wltea/analyzer/core/LetterSegmenter.java |
1,522 | /*
* Copyright 2016 jeasonlzy(廖子尧)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lzy.demo.okgo;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import com.lzy.demo.R;
import com.lzy.demo.base.BaseDetailActivity;
import com.lzy.demo.callback.DialogCallback;
import com.lzy.demo.model.LzyResponse;
import com.lzy.demo.model.ServerModel;
import com.lzy.demo.utils.Urls;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.db.CacheManager;
import com.lzy.okgo.model.Response;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
/**
* ================================================
* 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy
* 版 本:1.0
* 创建日期:16/9/11
* 描 述:
* 修订历史:
* ================================================
*/
public class CacheActivity extends BaseDetailActivity {
@Override
protected void onActivityCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_cache);
ButterKnife.bind(this);
setTitle("网络缓存基本用法");
}
@Override
protected void onDestroy() {
super.onDestroy();
//Activity销毁时,取消网络请求
OkGo.getInstance().cancelTag(this);
}
@SuppressWarnings("unchecked")
@OnClick(R.id.getAll)
public void getAll(View view) {
// 获取所有的缓存,但是一般每个缓存的泛型都不一样,所以缓存的泛型使用 ?
List<CacheEntity<?>> all = CacheManager.getInstance().getAll();
StringBuilder sb = new StringBuilder();
sb.append("共" + all.size() + "条缓存:").append("\n\n");
for (int i = 0; i < all.size(); i++) {
CacheEntity<?> cacheEntity = all.get(i);
sb.append("第" + (i + 1) + "条缓存:").append("\n").append(cacheEntity).append("\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("所有缓存显示").setMessage(sb.toString()).show();
}
@OnClick(R.id.clear)
public void clear(View view) {
boolean clear = CacheManager.getInstance().clear();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("清除缓存").setMessage("是否清除成功:" + clear).show();
}
@OnClick(R.id.no_cache)
public void no_cache(View view) {
OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
.tag(this)//
.cacheMode(CacheMode.NO_CACHE)//
.cacheKey("no_cache") //对于无缓存模式,该参数无效
.cacheTime(5000) //对于无缓存模式,该时间无效
.headers("header1", "headerValue1")//
.params("param1", "paramValue1")//
.execute(new CacheCallBack(this));
}
@OnClick(R.id.cache_default)
public void cache_default(View view) {
OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
.tag(this)//
.cacheMode(CacheMode.DEFAULT)//
.cacheKey("cache_default")//
.cacheTime(5000)//对于默认的缓存模式,该时间无效,依靠的是服务端对304缓存的控制
.headers("header1", "headerValue1")//
.params("param1", "paramValue1")//
.execute(new CacheCallBack(this));
}
@OnClick(R.id.request_failed_read_cache)
public void request_failed_read_cache(View view) {
OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
.tag(this)//
.cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)//
.cacheKey("request_failed_read_cache")//
.cacheTime(5000) // 单位毫秒.5秒后过期
.headers("header1", "headerValue1")//
.params("param1", "paramValue1")//
.execute(new CacheCallBack(this));
}
@OnClick(R.id.if_none_cache_request)
public void if_none_cache_request(View view) {
OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
.tag(this)//
.cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)//
.cacheKey("if_none_cache_request")//
.cacheTime(5000) // 单位毫秒.5秒后过期
.headers("header1", "headerValue1")//
.params("param1", "paramValue1")//
.execute(new CacheCallBack(this));
}
@OnClick(R.id.first_cache_then_request)
public void first_cache_then_request(View view) {
OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
.tag(this)//
.cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)//
.cacheKey("first_cache_then_request")//
.cacheTime(5000) // 单位毫秒.5秒后过期
.headers("header1", "headerValue1")//
.params("param1", "paramValue1")//
.execute(new CacheCallBack(this));
}
private class CacheCallBack extends DialogCallback<LzyResponse<ServerModel>> {
CacheCallBack(Activity activity) {
super(activity);
}
@Override
public void onSuccess(Response<LzyResponse<ServerModel>> response) {
handleResponse(response);
Call call = response.getRawCall();
requestState.setText("请求成功 是否来自缓存:false 请求方式:" + call.request().method() + "\n" + "url:" + call.request().url());
}
@Override
public void onCacheSuccess(Response<LzyResponse<ServerModel>> response) {
handleResponse(response);
Call call = response.getRawCall();
requestState.setText("请求成功 是否来自缓存:true 请求方式:" + call.request().method() + "\n" + "url:" + call.request().url());
}
@Override
public void onError(Response<LzyResponse<ServerModel>> response) {
handleError(response);
Call call = response.getRawCall();
requestState.setText("请求失败 是否来自缓存:false 请求方式:" + call.request().method() + "\n" + "url:" + call.request().url());
}
}
}
| jeasonlzy/okhttp-OkGo | demo/src/main/java/com/lzy/demo/okgo/CacheActivity.java |
1,524 | /*
* Copyright 1999-2017 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fastjson.util;
import java.util.Arrays;
/**
* for concurrent IdentityHashMap
*
* @author wenshao[[email protected]]
*/
@SuppressWarnings("unchecked")
public class IdentityHashMap<K, V> {
private final Entry<K, V>[] buckets;
private final int indexMask;
public final static int DEFAULT_SIZE = 8192;
public IdentityHashMap(){
this(DEFAULT_SIZE);
}
public IdentityHashMap(int tableSize){
this.indexMask = tableSize - 1;
this.buckets = new Entry[tableSize];
}
public final V get(K key) {
final int hash = System.identityHashCode(key);
final int bucket = hash & indexMask;
for (Entry<K, V> entry = buckets[bucket]; entry != null; entry = entry.next) {
if (key == entry.key) {
return (V) entry.value;
}
}
return null;
}
public Class findClass(String keyString) {
for (int i = 0; i < buckets.length; i++) {
Entry bucket = buckets[i];
if (bucket == null) {
continue;
}
for (Entry<K, V> entry = bucket; entry != null; entry = entry.next) {
Object key = bucket.key;
if (key instanceof Class) {
Class clazz = ((Class) key);
String className = clazz.getName();
if (className.equals(keyString)) {
return clazz;
}
}
}
}
return null;
}
public boolean put(K key, V value) {
final int hash = System.identityHashCode(key);
final int bucket = hash & indexMask;
for (Entry<K, V> entry = buckets[bucket]; entry != null; entry = entry.next) {
if (key == entry.key) {
entry.value = value;
return true;
}
}
Entry<K, V> entry = new Entry<K, V>(key, value, hash, buckets[bucket]);
buckets[bucket] = entry; // 并发是处理时会可能导致缓存丢失,但不影响正确性
return false;
}
protected static final class Entry<K, V> {
public final int hashCode;
public final K key;
public V value;
public final Entry<K, V> next;
public Entry(K key, V value, int hash, Entry<K, V> next){
this.key = key;
this.value = value;
this.next = next;
this.hashCode = hash;
}
}
public void clear() {
Arrays.fill(this.buckets, null);
}
public int size() {
int count = 0;
for (Entry<K, V> bucket : this.buckets) {
for (; bucket != null; bucket = bucket.next) {
count++;
}
}
return count;
}
}
| alibaba/fastjson | src/main/java/com/alibaba/fastjson/util/IdentityHashMap.java |
1,526 | /*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.sql.parser;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.util.FnvHash;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class InsertColumnsCache {
public static InsertColumnsCache global;
static {
global = new InsertColumnsCache(8192);
}
public ConcurrentMap<Long, Entry> cache = new ConcurrentHashMap<Long, Entry>();
private final Entry[] buckets;
private final int indexMask;
public InsertColumnsCache(int tableSize) {
this.indexMask = tableSize - 1;
this.buckets = new Entry[tableSize];
}
public final Entry get(long hashCode64) {
final int bucket = ((int) hashCode64) & indexMask;
for (Entry entry = buckets[bucket]; entry != null; entry = entry.next) {
if (hashCode64 == entry.hashCode64) {
return entry;
}
}
return null;
}
public boolean put(long hashCode64, String columnsString, String columnsFormattedString, List<SQLExpr> columns) {
final int bucket = ((int) hashCode64) & indexMask;
for (Entry entry = buckets[bucket]; entry != null; entry = entry.next) {
if (hashCode64 == entry.hashCode64) {
return true;
}
}
Entry entry = new Entry(hashCode64, columnsString, columnsFormattedString, columns, buckets[bucket]);
buckets[bucket] = entry; // 并发是处理时会可能导致缓存丢失,但不影响正确性
return false;
}
public static final class Entry {
public final long hashCode64;
public final String columnsString;
public final String columnsFormattedString;
public final long columnsFormattedStringHash;
public final List<SQLExpr> columns;
public final Entry next;
public Entry(long hashCode64,
String columnsString,
String columnsFormattedString,
List<SQLExpr> columns,
Entry next) {
this.hashCode64 = hashCode64;
this.columnsString = columnsString;
this.columnsFormattedString = columnsFormattedString;
this.columnsFormattedStringHash = FnvHash.fnv1a_64_lower(columnsFormattedString);
this.columns = columns;
this.next = next;
}
}
}
| alibaba/druid | core/src/main/java/com/alibaba/druid/sql/parser/InsertColumnsCache.java |
1,527 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.stat;
import com.alibaba.druid.proxy.DruidDriver;
import com.alibaba.druid.proxy.jdbc.StatementExecuteType;
import com.alibaba.druid.util.JMXUtils;
import com.alibaba.druid.util.Utils;
import javax.management.JMException;
import javax.management.openmbean.*;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import static com.alibaba.druid.util.JdbcSqlStatUtils.get;
public final class JdbcSqlStat implements JdbcSqlStatMBean, Comparable<JdbcSqlStat> {
private final String sql;
private long sqlHash;
private long id;
private String dataSource;
private long executeLastStartTime;
private volatile long executeBatchSizeTotal;
private volatile int executeBatchSizeMax;
private volatile long executeSuccessCount;
private volatile long executeSpanNanoTotal;
private volatile long executeSpanNanoMax;
private volatile int runningCount;
private volatile int concurrentMax;
private volatile long resultSetHoldTimeNano;
private volatile long executeAndResultSetHoldTime;
static final AtomicLongFieldUpdater<JdbcSqlStat> executeBatchSizeTotalUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeBatchSizeTotal");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> executeBatchSizeMaxUpdater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeBatchSizeMax");
static final AtomicLongFieldUpdater<JdbcSqlStat> executeSuccessCountUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeSuccessCount");
static final AtomicLongFieldUpdater<JdbcSqlStat> executeSpanNanoTotalUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeSpanNanoTotal");
static final AtomicLongFieldUpdater<JdbcSqlStat> executeSpanNanoMaxUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeSpanNanoMax");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> runningCountUpdater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"runningCount");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> concurrentMaxUpdater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"concurrentMax");
static final AtomicLongFieldUpdater<JdbcSqlStat> resultSetHoldTimeNanoUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"resultSetHoldTimeNano");
static final AtomicLongFieldUpdater<JdbcSqlStat> executeAndResultSetHoldTimeUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeAndResultSetHoldTime");
private String name;
private String file;
private String dbType;
private volatile long executeNanoSpanMaxOccurTime;
private volatile long executeErrorCount;
private volatile Throwable executeErrorLast;
private volatile long executeErrorLastTime;
private volatile long updateCount;
private volatile long updateCountMax;
private volatile long fetchRowCount;
private volatile long fetchRowCountMax;
private volatile long inTransactionCount;
private volatile String lastSlowParameters;
private boolean removed;
private volatile long clobOpenCount;
private volatile long blobOpenCount;
private volatile long readStringLength;
private volatile long readBytesLength;
private volatile long inputStreamOpenCount;
private volatile long readerOpenCount;
static final AtomicLongFieldUpdater<JdbcSqlStat> executeErrorCountUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeErrorCount");
static final AtomicLongFieldUpdater<JdbcSqlStat> updateCountUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"updateCount");
static final AtomicLongFieldUpdater<JdbcSqlStat> updateCountMaxUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"updateCountMax");
static final AtomicLongFieldUpdater<JdbcSqlStat> fetchRowCountUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"fetchRowCount");
static final AtomicLongFieldUpdater<JdbcSqlStat> fetchRowCountMaxUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"fetchRowCountMax");
static final AtomicLongFieldUpdater<JdbcSqlStat> inTransactionCountUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"inTransactionCount");
static final AtomicLongFieldUpdater<JdbcSqlStat> clobOpenCountUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"clobOpenCount");
static final AtomicLongFieldUpdater<JdbcSqlStat> blobOpenCountUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"blobOpenCount");
static final AtomicLongFieldUpdater<JdbcSqlStat> readStringLengthUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"readStringLength");
static final AtomicLongFieldUpdater<JdbcSqlStat> readBytesLengthUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"readBytesLength");
static final AtomicLongFieldUpdater<JdbcSqlStat> inputStreamOpenCountUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"inputStreamOpenCount");
static final AtomicLongFieldUpdater<JdbcSqlStat> readerOpenCountUpdater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"readerOpenCount");
private volatile long histogram_0_1;
private volatile long histogram_1_10;
private volatile int histogram_10_100;
private volatile int histogram_100_1000;
private volatile int histogram_1000_10000;
private volatile int histogram_10000_100000;
private volatile int histogram_100000_1000000;
private volatile int histogram_1000000_more;
static final AtomicLongFieldUpdater<JdbcSqlStat> histogram_0_1_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"histogram_0_1");
static final AtomicLongFieldUpdater<JdbcSqlStat> histogram_1_10_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"histogram_1_10");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> histogram_10_100_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"histogram_10_100");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> histogram_100_1000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"histogram_100_1000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> histogram_1000_10000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"histogram_1000_10000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> histogram_10000_100000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"histogram_10000_100000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> histogram_100000_1000000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"histogram_100000_1000000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> histogram_1000000_more_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"histogram_1000000_more");
private volatile long executeAndResultHoldTime_0_1;
private volatile long executeAndResultHoldTime_1_10;
private volatile int executeAndResultHoldTime_10_100;
private volatile int executeAndResultHoldTime_100_1000;
private volatile int executeAndResultHoldTime_1000_10000;
private volatile int executeAndResultHoldTime_10000_100000;
private volatile int executeAndResultHoldTime_100000_1000000;
private volatile int executeAndResultHoldTime_1000000_more;
static final AtomicLongFieldUpdater<JdbcSqlStat> executeAndResultHoldTime_0_1_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeAndResultHoldTime_0_1");
static final AtomicLongFieldUpdater<JdbcSqlStat> executeAndResultHoldTime_1_10_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeAndResultHoldTime_1_10");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> executeAndResultHoldTime_10_100_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeAndResultHoldTime_10_100");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> executeAndResultHoldTime_100_1000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeAndResultHoldTime_100_1000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> executeAndResultHoldTime_1000_10000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeAndResultHoldTime_1000_10000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> executeAndResultHoldTime_10000_100000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeAndResultHoldTime_10000_100000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> executeAndResultHoldTime_100000_1000000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeAndResultHoldTime_100000_1000000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> executeAndResultHoldTime_1000000_more_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"executeAndResultHoldTime_1000000_more");
private volatile long fetchRowCount_0_1;
private volatile long fetchRowCount_1_10;
private volatile long fetchRowCount_10_100;
private volatile int fetchRowCount_100_1000;
private volatile int fetchRowCount_1000_10000;
private volatile int fetchRowCount_10000_more;
static final AtomicLongFieldUpdater<JdbcSqlStat> fetchRowCount_0_1_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"fetchRowCount_0_1");
static final AtomicLongFieldUpdater<JdbcSqlStat> fetchRowCount_1_10_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"fetchRowCount_1_10");
static final AtomicLongFieldUpdater<JdbcSqlStat> fetchRowCount_10_100_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"fetchRowCount_10_100");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> fetchRowCount_100_1000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"fetchRowCount_100_1000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> fetchRowCount_1000_10000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"fetchRowCount_1000_10000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> fetchRowCount_10000_more_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"fetchRowCount_10000_more");
private volatile long updateCount_0_1;
private volatile long updateCount_1_10;
private volatile long updateCount_10_100;
private volatile int updateCount_100_1000;
private volatile int updateCount_1000_10000;
private volatile int updateCount_10000_more;
static final AtomicLongFieldUpdater<JdbcSqlStat> updateCount_0_1_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"updateCount_0_1");
static final AtomicLongFieldUpdater<JdbcSqlStat> updateCount_1_10_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"updateCount_1_10");
static final AtomicLongFieldUpdater<JdbcSqlStat> updateCount_10_100_Updater = AtomicLongFieldUpdater.newUpdater(JdbcSqlStat.class,
"updateCount_10_100");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> updateCount_100_1000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"updateCount_100_1000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> updateCount_1000_10000_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"updateCount_1000_10000");
static final AtomicIntegerFieldUpdater<JdbcSqlStat> updateCount_10000_more_Updater = AtomicIntegerFieldUpdater.newUpdater(JdbcSqlStat.class,
"updateCount_10000_more");
public JdbcSqlStat(String sql) {
this.sql = sql;
this.id = DruidDriver.createSqlStatId();
}
public String getLastSlowParameters() {
return lastSlowParameters;
}
public void setLastSlowParameters(String lastSlowParameters) {
this.lastSlowParameters = lastSlowParameters;
}
public String getDbType() {
return dbType;
}
public void setDbType(String dbType) {
this.dbType = dbType;
}
public String getDataSource() {
return dataSource;
}
public void setDataSource(String dataSource) {
this.dataSource = dataSource;
}
public static final String getContextSqlName() {
JdbcStatContext context = JdbcStatManager.getInstance().getStatContext();
if (context == null) {
return null;
}
return context.getName();
}
public static final void setContextSqlName(String val) {
JdbcStatContext context = JdbcStatManager.getInstance().getStatContext();
if (context == null) {
context = JdbcStatManager.getInstance().createStatContext();
JdbcStatManager.getInstance().setStatContext(context);
}
context.setName(val);
}
public static final String getContextSqlFile() {
JdbcStatContext context = JdbcStatManager.getInstance().getStatContext();
if (context == null) {
return null;
}
return context.getFile();
}
public static final void setContextSqlFile(String val) {
JdbcStatContext context = JdbcStatManager.getInstance().getStatContext();
if (context == null) {
context = JdbcStatManager.getInstance().createStatContext();
JdbcStatManager.getInstance().setStatContext(context);
}
context.setFile(val);
}
public static final void setContextSql(String val) {
JdbcStatContext context = JdbcStatManager.getInstance().getStatContext();
if (context == null) {
context = JdbcStatManager.getInstance().createStatContext();
JdbcStatManager.getInstance().setStatContext(context);
}
context.setSql(val);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public void reset() {
executeLastStartTime = 0;
executeBatchSizeTotalUpdater.set(this, 0);
executeBatchSizeMaxUpdater.set(this, 0);
executeSuccessCountUpdater.set(this, 0);
executeSpanNanoTotalUpdater.set(this, 0);
executeSpanNanoMaxUpdater.set(this, 0);
executeNanoSpanMaxOccurTime = 0;
concurrentMaxUpdater.set(this, 0);
executeErrorCountUpdater.set(this, 0);
executeErrorLast = null;
executeErrorLastTime = 0;
updateCountUpdater.set(this, 0);
updateCountMaxUpdater.set(this, 0);
fetchRowCountUpdater.set(this, 0);
fetchRowCountMaxUpdater.set(this, 0);
histogram_0_1_Updater.set(this, 0);
histogram_1_10_Updater.set(this, 0);
histogram_10_100_Updater.set(this, 0);
histogram_100_1000_Updater.set(this, 0);
histogram_1000_10000_Updater.set(this, 0);
histogram_10000_100000_Updater.set(this, 0);
histogram_100000_1000000_Updater.set(this, 0);
histogram_1000000_more_Updater.set(this, 0);
this.lastSlowParameters = null;
inTransactionCountUpdater.set(this, 0);
resultSetHoldTimeNanoUpdater.set(this, 0);
executeAndResultSetHoldTimeUpdater.set(this, 0);
fetchRowCount_0_1_Updater.set(this, 0);
fetchRowCount_1_10_Updater.set(this, 0);
fetchRowCount_10_100_Updater.set(this, 0);
fetchRowCount_100_1000_Updater.set(this, 0);
fetchRowCount_1000_10000_Updater.set(this, 0);
fetchRowCount_10000_more_Updater.set(this, 0);
updateCount_0_1_Updater.set(this, 0);
updateCount_1_10_Updater.set(this, 0);
updateCount_10_100_Updater.set(this, 0);
updateCount_100_1000_Updater.set(this, 0);
updateCount_1000_10000_Updater.set(this, 0);
updateCount_10000_more_Updater.set(this, 0);
executeAndResultHoldTime_0_1_Updater.set(this, 0);
executeAndResultHoldTime_1_10_Updater.set(this, 0);
executeAndResultHoldTime_10_100_Updater.set(this, 0);
executeAndResultHoldTime_100_1000_Updater.set(this, 0);
executeAndResultHoldTime_1000_10000_Updater.set(this, 0);
executeAndResultHoldTime_10000_100000_Updater.set(this, 0);
executeAndResultHoldTime_100000_1000000_Updater.set(this, 0);
executeAndResultHoldTime_1000000_more_Updater.set(this, 0);
blobOpenCountUpdater.set(this, 0);
clobOpenCountUpdater.set(this, 0);
readStringLengthUpdater.set(this, 0);
readBytesLengthUpdater.set(this, 0);
inputStreamOpenCountUpdater.set(this, 0);
readerOpenCountUpdater.set(this, 0);
}
public JdbcSqlStatValue getValueAndReset() {
return getValue(true);
}
public JdbcSqlStatValue getValue(boolean reset) {
JdbcSqlStatValue val = new JdbcSqlStatValue();
val.setDbType(dbType);
val.setSql(sql);
val.setSqlHash(getSqlHash());
val.setId(id);
val.setName(name);
val.setFile(file);
val.setExecuteLastStartTime(executeLastStartTime);
if (reset) {
executeLastStartTime = 0;
}
val.setExecuteBatchSizeTotal(get(this, executeBatchSizeTotalUpdater, reset));
val.setExecuteBatchSizeMax(get(this, executeBatchSizeMaxUpdater, reset));
val.setExecuteSuccessCount(get(this, executeSuccessCountUpdater, reset));
val.setExecuteSpanNanoTotal(get(this, executeSpanNanoTotalUpdater, reset));
val.setExecuteSpanNanoMax(get(this, executeSpanNanoMaxUpdater, reset));
val.setExecuteNanoSpanMaxOccurTime(executeNanoSpanMaxOccurTime);
if (reset) {
executeNanoSpanMaxOccurTime = 0;
}
val.setRunningCount(this.runningCount);
val.setConcurrentMax(get(this, concurrentMaxUpdater, reset));
val.setExecuteErrorCount(get(this, executeErrorCountUpdater, reset));
val.setExecuteErrorLast(executeErrorLast);
if (reset) {
executeErrorLast = null;
}
val.setExecuteErrorLastTime(executeErrorLastTime);
if (reset) {
executeErrorLastTime = 0;
}
val.setUpdateCount(get(this, updateCountUpdater, reset));
val.setUpdateCountMax(get(this, updateCountMaxUpdater, reset));
val.setFetchRowCount(get(this, fetchRowCountUpdater, reset));
val.setFetchRowCountMax(get(this, fetchRowCountMaxUpdater, reset));
val.histogram_0_1 = get(this, histogram_0_1_Updater, reset);
val.histogram_1_10 = get(this, histogram_1_10_Updater, reset);
val.histogram_10_100 = get(this, histogram_10_100_Updater, reset);
val.histogram_100_1000 = get(this, histogram_100_1000_Updater, reset);
val.histogram_1000_10000 = get(this, histogram_1000_10000_Updater, reset);
val.histogram_10000_100000 = get(this, histogram_10000_100000_Updater, reset);
val.histogram_100000_1000000 = get(this, histogram_100000_1000000_Updater, reset);
val.histogram_1000000_more = get(this, histogram_1000000_more_Updater, reset);
val.setLastSlowParameters(lastSlowParameters);
if (reset) {
lastSlowParameters = null;
}
val.setInTransactionCount(get(this, inTransactionCountUpdater, reset));
val.setResultSetHoldTimeNano(get(this, resultSetHoldTimeNanoUpdater, reset));
val.setExecuteAndResultSetHoldTime(get(this, executeAndResultSetHoldTimeUpdater, reset));
val.fetchRowCount_0_1 = get(this, fetchRowCount_0_1_Updater, reset);
val.fetchRowCount_1_10 = get(this, fetchRowCount_1_10_Updater, reset);
val.fetchRowCount_10_100 = get(this, fetchRowCount_10_100_Updater, reset);
val.fetchRowCount_100_1000 = get(this, fetchRowCount_100_1000_Updater, reset);
val.fetchRowCount_1000_10000 = get(this, fetchRowCount_1000_10000_Updater, reset);
val.fetchRowCount_10000_more = get(this, fetchRowCount_10000_more_Updater, reset);
val.updateCount_0_1 = get(this, updateCount_0_1_Updater, reset);
val.updateCount_1_10 = get(this, updateCount_1_10_Updater, reset);
val.updateCount_10_100 = get(this, updateCount_10_100_Updater, reset);
val.updateCount_100_1000 = get(this, updateCount_100_1000_Updater, reset);
val.updateCount_1000_10000 = get(this, updateCount_1000_10000_Updater, reset);
val.updateCount_10000_more = get(this, updateCount_10000_more_Updater, reset);
val.executeAndResultHoldTime_0_1 = get(this, executeAndResultHoldTime_0_1_Updater, reset);
val.executeAndResultHoldTime_1_10 = get(this, executeAndResultHoldTime_1_10_Updater, reset);
val.executeAndResultHoldTime_10_100 = get(this, executeAndResultHoldTime_10_100_Updater, reset);
val.executeAndResultHoldTime_100_1000 = get(this, executeAndResultHoldTime_100_1000_Updater, reset);
val.executeAndResultHoldTime_1000_10000 = get(this, executeAndResultHoldTime_1000_10000_Updater, reset);
val.executeAndResultHoldTime_10000_100000 = get(this, executeAndResultHoldTime_10000_100000_Updater, reset);
val.executeAndResultHoldTime_100000_1000000 = get(this, executeAndResultHoldTime_100000_1000000_Updater, reset);
val.executeAndResultHoldTime_1000000_more = get(this, executeAndResultHoldTime_1000000_more_Updater, reset);
val.setBlobOpenCount(get(this, blobOpenCountUpdater, reset));
val.setClobOpenCount(get(this, clobOpenCountUpdater, reset));
val.setReadStringLength(get(this, readStringLengthUpdater, reset));
val.setReadBytesLength(get(this, readBytesLengthUpdater, reset));
val.setInputStreamOpenCount(get(this, inputStreamOpenCountUpdater, reset));
val.setReaderOpenCount(get(this, readerOpenCountUpdater, reset));
return val;
}
public long getConcurrentMax() {
return concurrentMax;
}
public long getRunningCount() {
return runningCount;
}
public void addUpdateCount(int delta) {
if (delta > 0) {
updateCountUpdater.addAndGet(this, delta);
}
for (; ; ) {
long max = updateCountMaxUpdater.get(this);
if (delta <= max) {
break;
}
if (updateCountMaxUpdater.compareAndSet(this, max, delta)) {
break;
}
}
if (delta < 1) {
updateCount_0_1_Updater.incrementAndGet(this);
} else if (delta < 10) {
updateCount_1_10_Updater.incrementAndGet(this);
} else if (delta < 100) {
updateCount_10_100_Updater.incrementAndGet(this);
} else if (delta < 1000) {
updateCount_100_1000_Updater.incrementAndGet(this);
} else if (delta < 10000) {
updateCount_1000_10000_Updater.incrementAndGet(this);
} else {
updateCount_10000_more_Updater.incrementAndGet(this);
}
}
public long getUpdateCount() {
return updateCount;
}
public long getUpdateCountMax() {
return updateCountMax;
}
public long getFetchRowCount() {
return fetchRowCount;
}
public long getFetchRowCountMax() {
return fetchRowCountMax;
}
public long getClobOpenCount() {
return clobOpenCount;
}
public void incrementClobOpenCount() {
clobOpenCountUpdater.incrementAndGet(this);
}
public long getBlobOpenCount() {
return blobOpenCount;
}
public void incrementBlobOpenCount() {
blobOpenCountUpdater.incrementAndGet(this);
}
public long getReadStringLength() {
return readStringLength;
}
public void addStringReadLength(long length) {
readStringLengthUpdater.addAndGet(this, length);
}
public long getReadBytesLength() {
return readBytesLength;
}
public void addReadBytesLength(long length) {
readBytesLengthUpdater.addAndGet(this, length);
}
public long getReaderOpenCount() {
return readerOpenCount;
}
public void addReaderOpenCount(int count) {
readerOpenCountUpdater.addAndGet(this, count);
}
public long getInputStreamOpenCount() {
return inputStreamOpenCount;
}
public void addInputStreamOpenCount(int count) {
inputStreamOpenCountUpdater.addAndGet(this, count);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSql() {
return sql;
}
public long getSqlHash() {
if (sqlHash == 0) {
sqlHash = Utils.fnv_64(sql);
}
return sqlHash;
}
public Date getExecuteLastStartTime() {
if (executeLastStartTime <= 0) {
return null;
}
return new Date(executeLastStartTime);
}
public void setExecuteLastStartTime(long executeLastStartTime) {
this.executeLastStartTime = executeLastStartTime;
}
public Date getExecuteNanoSpanMaxOccurTime() {
if (executeNanoSpanMaxOccurTime <= 0) {
return null;
}
return new Date(executeNanoSpanMaxOccurTime);
}
public Date getExecuteErrorLastTime() {
if (executeErrorLastTime <= 0) {
return null;
}
return new Date(executeErrorLastTime);
}
public void addFetchRowCount(long delta) {
fetchRowCountUpdater.addAndGet(this, delta);
for (; ; ) {
long max = fetchRowCountMaxUpdater.get(this);
if (delta <= max) {
break;
}
if (fetchRowCountMaxUpdater.compareAndSet(this, max, delta)) {
break;
}
}
if (delta < 1) {
fetchRowCount_0_1_Updater.incrementAndGet(this);
} else if (delta < 10) {
fetchRowCount_1_10_Updater.incrementAndGet(this);
} else if (delta < 100) {
fetchRowCount_10_100_Updater.incrementAndGet(this);
} else if (delta < 1000) {
fetchRowCount_100_1000_Updater.incrementAndGet(this);
} else if (delta < 10000) {
fetchRowCount_1000_10000_Updater.incrementAndGet(this);
} else {
fetchRowCount_10000_more_Updater.incrementAndGet(this);
}
}
public void addExecuteBatchCount(long batchSize) {
executeBatchSizeTotalUpdater.addAndGet(this, batchSize);
// executeBatchSizeMax
for (; ; ) {
int current = executeBatchSizeMaxUpdater.get(this);
if (current >= batchSize) {
break;
}
if (executeBatchSizeMaxUpdater.compareAndSet(this, current, (int) batchSize)) {
break;
}
}
}
public long getExecuteBatchSizeTotal() {
return executeBatchSizeTotal;
}
public void incrementExecuteSuccessCount() {
executeSuccessCountUpdater.incrementAndGet(this);
}
public void incrementRunningCount() {
int val = runningCountUpdater.incrementAndGet(this);
for (; ; ) {
int max = concurrentMaxUpdater.get(this);
if (val <= max) {
break;
}
if (concurrentMaxUpdater.compareAndSet(this, max, val)) {
break;
}
}
}
public void decrementRunningCount() {
runningCountUpdater.decrementAndGet(this);
}
public void decrementExecutingCount() {
runningCountUpdater.decrementAndGet(this);
}
public long getExecuteSuccessCount() {
return executeSuccessCount;
}
public void addExecuteTime(StatementExecuteType executeType, boolean firstResultSet, long nanoSpan) {
addExecuteTime(nanoSpan);
if (StatementExecuteType.ExecuteQuery != executeType && !firstResultSet) {
executeAndResultHoldTimeHistogramRecord(nanoSpan);
}
}
private void executeAndResultHoldTimeHistogramRecord(long nanoSpan) {
long millis = nanoSpan / 1000 / 1000;
if (millis < 1) {
executeAndResultHoldTime_0_1_Updater.incrementAndGet(this);
} else if (millis < 10) {
executeAndResultHoldTime_1_10_Updater.incrementAndGet(this);
} else if (millis < 100) {
executeAndResultHoldTime_10_100_Updater.incrementAndGet(this);
} else if (millis < 1000) {
executeAndResultHoldTime_100_1000_Updater.incrementAndGet(this);
} else if (millis < 10000) {
executeAndResultHoldTime_1000_10000_Updater.incrementAndGet(this);
} else if (millis < 100000) {
executeAndResultHoldTime_10000_100000_Updater.incrementAndGet(this);
} else if (millis < 1000000) {
executeAndResultHoldTime_100000_1000000_Updater.incrementAndGet(this);
} else {
executeAndResultHoldTime_1000000_more_Updater.incrementAndGet(this);
}
}
private void histogramRecord(long nanoSpan) {
long millis = nanoSpan / 1000 / 1000;
if (millis < 1) {
histogram_0_1_Updater.incrementAndGet(this);
} else if (millis < 10) {
histogram_1_10_Updater.incrementAndGet(this);
} else if (millis < 100) {
histogram_10_100_Updater.incrementAndGet(this);
} else if (millis < 1000) {
histogram_100_1000_Updater.incrementAndGet(this);
} else if (millis < 10000) {
histogram_1000_10000_Updater.incrementAndGet(this);
} else if (millis < 100000) {
histogram_10000_100000_Updater.incrementAndGet(this);
} else if (millis < 1000000) {
histogram_100000_1000000_Updater.incrementAndGet(this);
} else {
histogram_1000000_more_Updater.incrementAndGet(this);
}
}
public void addExecuteTime(long nanoSpan) {
executeSpanNanoTotalUpdater.addAndGet(this, nanoSpan);
for (; ; ) {
long current = executeSpanNanoMaxUpdater.get(this);
if (current >= nanoSpan) {
break;
}
if (executeSpanNanoMaxUpdater.compareAndSet(this, current, nanoSpan)) {
// 可能不准确,但是绝大多数情况下都会正确,性能换取一致性
executeNanoSpanMaxOccurTime = System.currentTimeMillis();
break;
}
}
histogramRecord(nanoSpan);
}
public long getExecuteMillisTotal() {
return executeSpanNanoTotal / (1000 * 1000);
}
public long getExecuteMillisMax() {
return executeSpanNanoMax / (1000 * 1000);
}
public long getErrorCount() {
return executeErrorCount;
}
@Override
public long getExecuteBatchSizeMax() {
return executeBatchSizeMax;
}
public long getInTransactionCount() {
return inTransactionCount;
}
public void incrementInTransactionCount() {
inTransactionCountUpdater.incrementAndGet(this);
}
private static CompositeType COMPOSITE_TYPE;
public static CompositeType getCompositeType() throws JMException {
if (COMPOSITE_TYPE != null) {
return COMPOSITE_TYPE;
}
OpenType<?>[] indexTypes = new OpenType<?>[]{
// 0 - 4
SimpleType.LONG, //
SimpleType.STRING, //
SimpleType.STRING, //
SimpleType.LONG, //
SimpleType.LONG, //
// 5 - 9
SimpleType.LONG, //
SimpleType.DATE, //
SimpleType.LONG, //
JMXUtils.getThrowableCompositeType(), //
SimpleType.LONG, //
//
// 10 - 14
SimpleType.LONG, //
SimpleType.DATE, //
SimpleType.LONG, //
SimpleType.LONG, //
SimpleType.LONG, //
//
// 15 - 19
SimpleType.LONG, //
SimpleType.STRING, //
SimpleType.STRING, //
SimpleType.STRING, //
SimpleType.STRING, //
//
// 20 - 24
SimpleType.STRING, //
SimpleType.DATE, //
SimpleType.STRING, //
SimpleType.LONG, //
SimpleType.STRING, //
// 25 - 29
new ArrayType<Long>(SimpleType.LONG, true), //
SimpleType.STRING, //
SimpleType.LONG, //
SimpleType.LONG, //
new ArrayType<Long>(SimpleType.LONG, true), //
// 30 - 34
new ArrayType<Long>(SimpleType.LONG, true), //
new ArrayType<Long>(SimpleType.LONG, true), //
SimpleType.LONG, //
SimpleType.LONG, //
SimpleType.LONG, //
// 35 - 39
SimpleType.LONG, //
SimpleType.LONG, //
SimpleType.LONG, //
SimpleType.LONG, //
SimpleType.LONG, //
// 40 -
SimpleType.LONG, //
};
String[] indexNames = {
// 0 - 4
"ID", //
"DataSource", //
"SQL", //
"ExecuteCount", //
"ErrorCount", //
// 5 - 9
"TotalTime", //
"LastTime", //
"MaxTimespan", //
"LastError", //
"EffectedRowCount", //
// 10 - 14
"FetchRowCount", //
"MaxTimespanOccurTime", //
"BatchSizeMax", //
"BatchSizeTotal", //
"ConcurrentMax", //
// 15 - 19
"RunningCount", //
"Name", //
"File", //
"LastErrorMessage", //
"LastErrorClass", //
// 20 - 24
"LastErrorStackTrace", //
"LastErrorTime", //
"DbType", //
"InTransactionCount", //
"URL", //
// 25 - 29
"Histogram", //
"LastSlowParameters", //
"ResultSetHoldTime", //
"ExecuteAndResultSetHoldTime", //
"FetchRowCountHistogram", //
// 30 - 34
"EffectedRowCountHistogram", //
"ExecuteAndResultHoldTimeHistogram", //
"EffectedRowCountMax", //
"FetchRowCountMax", //
"ClobOpenCount",
// 35 -
"BlobOpenCount", //
"ReadStringLength", //
"ReadBytesLength", //
"InputStreamOpenCount", //
"ReaderOpenCount", //
// 40
"HASH", //
//
};
String[] indexDescriptions = indexNames;
COMPOSITE_TYPE = new CompositeType("SqlStatistic", "Sql Statistic", indexNames, indexDescriptions, indexTypes);
return COMPOSITE_TYPE;
}
public long getExecuteCount() {
return getErrorCount() + getExecuteSuccessCount();
}
public Map<String, Object> getData() throws JMException {
return getValue(false).getData();
}
public long[] getHistogramValues() {
return new long[]{
//
histogram_0_1, //
histogram_1_10, //
histogram_10_100, //
histogram_100_1000, //
histogram_1000_10000, //
histogram_10000_100000, //
histogram_100000_1000000, //
histogram_1000000_more //
};
}
public long getHistogramSum() {
long[] values = this.getHistogramValues();
long sum = 0;
for (int i = 0; i < values.length; ++i) {
sum += values[i];
}
return sum;
}
public CompositeDataSupport getCompositeData() throws JMException {
return new CompositeDataSupport(getCompositeType(), getData());
}
public Throwable getExecuteErrorLast() {
return executeErrorLast;
}
public void error(Throwable error) {
executeErrorCountUpdater.incrementAndGet(this);
executeErrorLastTime = System.currentTimeMillis();
executeErrorLast = error;
}
public long getResultSetHoldTimeMilis() {
return getResultSetHoldTimeNano() / (1000 * 1000);
}
public long getExecuteAndResultSetHoldTimeMilis() {
return getExecuteAndResultSetHoldTimeNano() / (1000 * 1000);
}
public long[] getFetchRowCountHistogramValues() {
return new long[]{
//
fetchRowCount_0_1, //
fetchRowCount_1_10, //
fetchRowCount_10_100, //
fetchRowCount_100_1000, //
fetchRowCount_1000_10000, //
fetchRowCount_10000_more //
};
}
public long[] getUpdateCountHistogramValues() {
return new long[]{
//
updateCount_0_1, //
updateCount_1_10, //
updateCount_10_100, //
updateCount_100_1000, //
updateCount_1000_10000, //
updateCount_10000_more //
};
}
public long[] getExecuteAndResultHoldTimeHistogramValues() {
return new long[]{
//
executeAndResultHoldTime_0_1, //
executeAndResultHoldTime_1_10, //
executeAndResultHoldTime_10_100, //
executeAndResultHoldTime_100_1000, //
executeAndResultHoldTime_1000_10000, //
executeAndResultHoldTime_10000_100000, //
executeAndResultHoldTime_100000_1000000, //
executeAndResultHoldTime_1000000_more //
};
}
public long getExecuteAndResultHoldTimeHistogramSum() {
long[] values = this.getExecuteAndResultHoldTimeHistogramValues();
long sum = 0;
for (int i = 0; i < values.length; ++i) {
sum += values[i];
}
return sum;
}
public long getResultSetHoldTimeNano() {
return resultSetHoldTimeNano;
}
public long getExecuteAndResultSetHoldTimeNano() {
return executeAndResultSetHoldTime;
}
public void addResultSetHoldTimeNano(long nano) {
resultSetHoldTimeNanoUpdater.addAndGet(this, nano);
}
public void addResultSetHoldTimeNano(long statementExecuteNano, long resultHoldTimeNano) {
resultSetHoldTimeNanoUpdater.addAndGet(this, resultHoldTimeNano);
executeAndResultSetHoldTimeUpdater.addAndGet(this, statementExecuteNano + resultHoldTimeNano);
executeAndResultHoldTimeHistogramRecord(statementExecuteNano + resultHoldTimeNano);
updateCount_0_1_Updater.incrementAndGet(this);
}
public boolean isRemoved() {
return removed;
}
public void setRemoved(boolean removed) {
this.removed = removed;
}
@Override
public int compareTo(JdbcSqlStat o) {
if (o.sqlHash == this.sqlHash) {
return 0;
}
return this.id < o.id ? -1 : 1;
}
}
| alibaba/druid | core/src/main/java/com/alibaba/druid/stat/JdbcSqlStat.java |
1,528 | /*
* Copyright 1999-2017 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fastjson.parser;
import java.io.*;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.AccessControlException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import com.alibaba.fastjson.*;
import com.alibaba.fastjson.annotation.JSONCreator;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.asm.ClassReader;
import com.alibaba.fastjson.asm.TypeCollector;
import com.alibaba.fastjson.parser.deserializer.*;
import com.alibaba.fastjson.serializer.*;
import com.alibaba.fastjson.spi.Module;
import com.alibaba.fastjson.support.moneta.MonetaCodec;
import com.alibaba.fastjson.util.*;
import com.alibaba.fastjson.util.IdentityHashMap;
import com.alibaba.fastjson.util.ServiceLoader;
import javax.xml.datatype.XMLGregorianCalendar;
import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_hashcode;
import static com.alibaba.fastjson.util.TypeUtils.fnv1a_64_magic_prime;
/**
* @author wenshao[[email protected]]
*/
public class ParserConfig {
public static final String DENY_PROPERTY_INTERNAL = "fastjson.parser.deny.internal";
public static final String DENY_PROPERTY = "fastjson.parser.deny";
public static final String AUTOTYPE_ACCEPT = "fastjson.parser.autoTypeAccept";
public static final String AUTOTYPE_SUPPORT_PROPERTY = "fastjson.parser.autoTypeSupport";
public static final String SAFE_MODE_PROPERTY = "fastjson.parser.safeMode";
public static final String[] DENYS_INTERNAL;
public static final String[] DENYS;
private static final String[] AUTO_TYPE_ACCEPT_LIST;
public static final boolean AUTO_SUPPORT;
public static final boolean SAFE_MODE;
private static final long[] INTERNAL_WHITELIST_HASHCODES;
static {
{
String property = IOUtils.getStringProperty(DENY_PROPERTY_INTERNAL);
DENYS_INTERNAL = splitItemsFormProperty(property);
}
{
String property = IOUtils.getStringProperty(DENY_PROPERTY);
DENYS = splitItemsFormProperty(property);
}
{
String property = IOUtils.getStringProperty(AUTOTYPE_SUPPORT_PROPERTY);
AUTO_SUPPORT = "true".equals(property);
}
{
String property = IOUtils.getStringProperty(SAFE_MODE_PROPERTY);
SAFE_MODE = "true".equals(property);
}
{
String property = IOUtils.getStringProperty(AUTOTYPE_ACCEPT);
String[] items = splitItemsFormProperty(property);
if (items == null) {
items = new String[0];
}
AUTO_TYPE_ACCEPT_LIST = items;
}
INTERNAL_WHITELIST_HASHCODES = new long[] {
0x9F2E20FB6049A371L,
0xA8AAA929446FFCE4L,
0xD45D6F8C9017FAL,
0x64DC636F343516DCL
};
}
public static ParserConfig getGlobalInstance() {
return global;
}
public static ParserConfig global = new ParserConfig();
private final IdentityHashMap<Type, ObjectDeserializer> deserializers = new IdentityHashMap<Type, ObjectDeserializer>();
private final IdentityHashMap<Type, IdentityHashMap<Type, ObjectDeserializer>> mixInDeserializers = new IdentityHashMap<Type, IdentityHashMap<Type, ObjectDeserializer>>(16);
private final ConcurrentMap<String,Class<?>> typeMapping = new ConcurrentHashMap<String,Class<?>>(16, 0.75f, 1);
private boolean asmEnable = !ASMUtils.IS_ANDROID;
public final SymbolTable symbolTable = new SymbolTable(4096);
public PropertyNamingStrategy propertyNamingStrategy;
protected ClassLoader defaultClassLoader;
protected ASMDeserializerFactory asmFactory;
private static boolean awtError = false;
private static boolean jdk8Error = false;
private static boolean jodaError = false;
private static boolean guavaError = false;
private boolean autoTypeSupport = AUTO_SUPPORT;
private long[] internalDenyHashCodes;
private long[] denyHashCodes;
private long[] acceptHashCodes;
public final boolean fieldBased;
private boolean jacksonCompatible = false;
public boolean compatibleWithJavaBean = TypeUtils.compatibleWithJavaBean;
private List<Module> modules = new ArrayList<Module>();
private volatile List<AutoTypeCheckHandler> autoTypeCheckHandlers;
private boolean safeMode = SAFE_MODE;
{
denyHashCodes = new long[]{
0x80D0C70BCC2FEA02L,
0x868385095A22725FL,
0x86FC2BF9BEAF7AEFL,
0x87F52A1B07EA33A6L,
0x8872F29FD0B0B7A7L,
0x8BAAEE8F9BF77FA7L,
0x8EADD40CB2A94443L,
0x8F75F9FA0DF03F80L,
0x9172A53F157930AFL,
0x92122D710E364FB8L,
0x941866E73BEFF4C9L,
0x94305C26580F73C5L,
0x9437792831DF7D3FL,
0xA123A62F93178B20L,
0xA85882CE1044C450L,
0xAA3DAFFDB10C4937L,
0xAAA9E6B7C1E1C6A7L,
0xAAAA0826487A3737L,
0xAB82562F53E6E48FL,
0xAC6262F52C98AA39L,
0xAD937A449831E8A0L,
0xAE50DA1FAD60A096L,
0xAFF6FF23388E225AL,
0xAFFF4C95B99A334DL,
0xB40F341C746EC94FL,
0xB7E8ED757F5D13A2L,
0xB98B6B5396932FE9L,
0xBCDD9DC12766F0CEL,
0xBCE0DEE34E726499L,
0xBE4F13E96A6796D0L,
0xBEBA72FB1CCBA426L,
0xC00BE1DEBAF2808BL,
0xC1086AFAE32E6258L,
0xC2664D0958ECFE4CL,
0xC41FF7C9C87C7C05L,
0xC664B363BACA050AL,
0xC7599EBFE3E72406L,
0xC8D49E5601E661A9L,
0xC8F04B3A28909935L,
0xC963695082FD728EL,
0xCBF29CE484222325L,
0xD1EFCDF4B3316D34L,
0xD54B91CC77B239EDL,
0xD59EE91F0B09EA01L,
0xD66F68AB92E7FEF5L,
0xD8CA3D595E982BACL,
0xDCD8D615A6449E3EL,
0xDE23A0809A8B9BD6L,
0xDEFC208F237D4104L,
0xDF2DDFF310CDB375L,
0xE09AE4604842582FL,
0xE1919804D5BF468FL,
0xE2EB3AC7E56C467EL,
0xE603D6A51FAD692BL,
0xE704FD19052B2A34L,
0xE9184BE55B1D962AL,
0xE9F20BAD25F60807L,
0xED13653CB45C4BEDL,
0xF2983D099D29B477L,
0xF3702A4A5490B8E8L,
0xF474E44518F26736L,
0xF4D93F4FB3E3D991L,
0xF5D77DCF8E4D71E6L,
0xF6C0340E73A36A69L,
0xF7E96E74DFA58DBCL,
0xFC773AE20C827691L,
0xFCF3E78644B98BD8L,
0xFD5BFC610056D720L,
0xFFA15BF021F1E37CL,
0xFFDD1A80F1ED3405L,
0x10E067CD55C5E5L,
0x761619136CC13EL,
0x22BAA234C5BFB8AL,
0x3085068CB7201B8L,
0x45B11BC78A3ABA3L,
0x55CFCA0F2281C07L,
0xA555C74FE3A5155L,
0xB6E292FA5955ADEL,
0xBEF8514D0B79293L,
0xEE6511B66FD5EF0L,
0x100150A253996624L,
0x10B2BDCA849D9B3EL,
0x10DBC48446E0DAE5L,
0x119B5B1F10210AFCL,
0x144277B467723158L,
0x14DB2E6FEAD04AF0L,
0x154B6CB22D294CFAL,
0x17924CCA5227622AL,
0x193B2697EAAED41AL,
0x1CD6F11C6A358BB7L,
0x1E0A8C3358FF3DAEL,
0x24652CE717E713BBL,
0x24D2F6048FEF4E49L,
0x24EC99D5E7DC5571L,
0x25E962F1C28F71A2L,
0x275D0732B877AF29L,
0x28AC82E44E933606L,
0x2A71CE2CC40A710CL,
0x2AD1CE3A112F015DL,
0x2ADFEFBBFE29D931L,
0x2B3A37467A344CDFL,
0x2B6DD8B3229D6837L,
0x2D308DBBC851B0D8L,
0x2FE950D3EA52AE0DL,
0x313BB4ABD8D4554CL,
0x327C8ED7C8706905L,
0x332F0B5369A18310L,
0x339A3E0B6BEEBEE9L,
0x33C64B921F523F2FL,
0x33E7F3E02571B153L,
0x34A81EE78429FDF1L,
0x37317698DCFCE894L,
0x378307CB0111E878L,
0x3826F4B2380C8B9BL,
0x398F942E01920CF0L,
0x3A31412DBB05C7FFL,
0x3A7EE0635EB2BC33L,
0x3ADBA40367F73264L,
0x3B0B51ECBF6DB221L,
0x3BF14094A524F0E2L,
0x42D11A560FC9FBA9L,
0x43320DC9D2AE0892L,
0x440E89208F445FB9L,
0x46C808A4B5841F57L,
0x470FD3A18BB39414L,
0x49312BDAFB0077D9L,
0x4A3797B30328202CL,
0x4BA3E254E758D70DL,
0x4BF881E49D37F530L,
0x4CF54EEC05E3E818L,
0x4DA972745FEB30C1L,
0x4EF08C90FF16C675L,
0x4FD10DDC6D13821FL,
0x521B4F573376DF4AL,
0x527DB6B46CE3BCBCL,
0x535E552D6F9700C1L,
0x54855E265FE1DAD5L,
0x5728504A6D454FFCL,
0x599B5C1213A099ACL,
0x5A5BD85C072E5EFEL,
0x5AB0CB3071AB40D1L,
0x5B6149820275EA42L,
0x5D74D3E5B9370476L,
0x5D92E6DDDE40ED84L,
0x5E61093EF8CDDDBBL,
0x5F215622FB630753L,
0x61C5BDD721385107L,
0x62DB241274397C34L,
0x636ECCA2A131B235L,
0x63A220E60A17C7B9L,
0x647AB0224E149EBEL,
0x65F81B84C1D920CDL,
0x665C53C311193973L,
0x6749835432E0F0D2L,
0x69B6E0175084B377L,
0x6A47501EBB2AFDB2L,
0x6FCABF6FA54CAFFFL,
0x6FE92D83FC0A4628L,
0x746BD4A53EC195FBL,
0x74B50BB9260E31FFL,
0x75CC60F5871D0FD3L,
0x767A586A5107FEEFL,
0x78E5935826671397L,
0x793ADDDED7A967F5L,
0x7AA7EE3627A19CF3L,
0x7AFA070241B8CC4BL,
0x7ED9311D28BF1A65L,
0x7ED9481D28BF417AL,
0x7EE6C477DA20BBE3L
};
long[] hashCodes = new long[AUTO_TYPE_ACCEPT_LIST.length];
for (int i = 0; i < AUTO_TYPE_ACCEPT_LIST.length; i++) {
hashCodes[i] = TypeUtils.fnv1a_64(AUTO_TYPE_ACCEPT_LIST[i]);
}
Arrays.sort(hashCodes);
acceptHashCodes = hashCodes;
}
public ParserConfig(){
this(false);
}
public ParserConfig(boolean fieldBase){
this(null, null, fieldBase);
}
public ParserConfig(ClassLoader parentClassLoader){
this(null, parentClassLoader, false);
}
public ParserConfig(ASMDeserializerFactory asmFactory){
this(asmFactory, null, false);
}
private ParserConfig(ASMDeserializerFactory asmFactory, ClassLoader parentClassLoader, boolean fieldBased){
this.fieldBased = fieldBased;
if (asmFactory == null && !ASMUtils.IS_ANDROID) {
try {
if (parentClassLoader == null) {
asmFactory = new ASMDeserializerFactory(new ASMClassLoader());
} else {
asmFactory = new ASMDeserializerFactory(parentClassLoader);
}
} catch (ExceptionInInitializerError error) {
// skip
} catch (AccessControlException error) {
// skip
} catch (NoClassDefFoundError error) {
// skip
}
}
this.asmFactory = asmFactory;
if (asmFactory == null) {
asmEnable = false;
}
initDeserializers();
addItemsToDeny(DENYS);
addItemsToDeny0(DENYS_INTERNAL);
addItemsToAccept(AUTO_TYPE_ACCEPT_LIST);
}
private final Callable<Void> initDeserializersWithJavaSql = new Callable<Void>() {
public Void call() {
deserializers.put(java.sql.Timestamp.class, SqlDateDeserializer.instance_timestamp);
deserializers.put(java.sql.Date.class, SqlDateDeserializer.instance);
deserializers.put(java.sql.Time.class, TimeDeserializer.instance);
deserializers.put(java.util.Date.class, DateCodec.instance);
return null;
}
};
private void initDeserializers() {
deserializers.put(SimpleDateFormat.class, MiscCodec.instance);
deserializers.put(Calendar.class, CalendarCodec.instance);
deserializers.put(XMLGregorianCalendar.class, CalendarCodec.instance);
deserializers.put(JSONObject.class, MapDeserializer.instance);
deserializers.put(JSONArray.class, CollectionCodec.instance);
deserializers.put(Map.class, MapDeserializer.instance);
deserializers.put(HashMap.class, MapDeserializer.instance);
deserializers.put(LinkedHashMap.class, MapDeserializer.instance);
deserializers.put(TreeMap.class, MapDeserializer.instance);
deserializers.put(ConcurrentMap.class, MapDeserializer.instance);
deserializers.put(ConcurrentHashMap.class, MapDeserializer.instance);
deserializers.put(Collection.class, CollectionCodec.instance);
deserializers.put(List.class, CollectionCodec.instance);
deserializers.put(ArrayList.class, CollectionCodec.instance);
deserializers.put(Object.class, JavaObjectDeserializer.instance);
deserializers.put(String.class, StringCodec.instance);
deserializers.put(StringBuffer.class, StringCodec.instance);
deserializers.put(StringBuilder.class, StringCodec.instance);
deserializers.put(char.class, CharacterCodec.instance);
deserializers.put(Character.class, CharacterCodec.instance);
deserializers.put(byte.class, NumberDeserializer.instance);
deserializers.put(Byte.class, NumberDeserializer.instance);
deserializers.put(short.class, NumberDeserializer.instance);
deserializers.put(Short.class, NumberDeserializer.instance);
deserializers.put(int.class, IntegerCodec.instance);
deserializers.put(Integer.class, IntegerCodec.instance);
deserializers.put(long.class, LongCodec.instance);
deserializers.put(Long.class, LongCodec.instance);
deserializers.put(BigInteger.class, BigIntegerCodec.instance);
deserializers.put(BigDecimal.class, BigDecimalCodec.instance);
deserializers.put(float.class, FloatCodec.instance);
deserializers.put(Float.class, FloatCodec.instance);
deserializers.put(double.class, NumberDeserializer.instance);
deserializers.put(Double.class, NumberDeserializer.instance);
deserializers.put(boolean.class, BooleanCodec.instance);
deserializers.put(Boolean.class, BooleanCodec.instance);
deserializers.put(Class.class, MiscCodec.instance);
deserializers.put(char[].class, new CharArrayCodec());
deserializers.put(AtomicBoolean.class, BooleanCodec.instance);
deserializers.put(AtomicInteger.class, IntegerCodec.instance);
deserializers.put(AtomicLong.class, LongCodec.instance);
deserializers.put(AtomicReference.class, ReferenceCodec.instance);
deserializers.put(WeakReference.class, ReferenceCodec.instance);
deserializers.put(SoftReference.class, ReferenceCodec.instance);
deserializers.put(UUID.class, MiscCodec.instance);
deserializers.put(TimeZone.class, MiscCodec.instance);
deserializers.put(Locale.class, MiscCodec.instance);
deserializers.put(Currency.class, MiscCodec.instance);
deserializers.put(Inet4Address.class, MiscCodec.instance);
deserializers.put(Inet6Address.class, MiscCodec.instance);
deserializers.put(InetSocketAddress.class, MiscCodec.instance);
deserializers.put(File.class, MiscCodec.instance);
deserializers.put(URI.class, MiscCodec.instance);
deserializers.put(URL.class, MiscCodec.instance);
deserializers.put(Pattern.class, MiscCodec.instance);
deserializers.put(Charset.class, MiscCodec.instance);
deserializers.put(JSONPath.class, MiscCodec.instance);
deserializers.put(Number.class, NumberDeserializer.instance);
deserializers.put(AtomicIntegerArray.class, AtomicCodec.instance);
deserializers.put(AtomicLongArray.class, AtomicCodec.instance);
deserializers.put(StackTraceElement.class, StackTraceElementDeserializer.instance);
deserializers.put(Serializable.class, JavaObjectDeserializer.instance);
deserializers.put(Cloneable.class, JavaObjectDeserializer.instance);
deserializers.put(Comparable.class, JavaObjectDeserializer.instance);
deserializers.put(Closeable.class, JavaObjectDeserializer.instance);
deserializers.put(JSONPObject.class, new JSONPDeserializer());
ModuleUtil.callWhenHasJavaSql(initDeserializersWithJavaSql);
}
private static String[] splitItemsFormProperty(final String property ){
if (property != null && property.length() > 0) {
return property.split(",");
}
return null;
}
public void configFromPropety(Properties properties) {
{
String property = properties.getProperty(DENY_PROPERTY);
String[] items = splitItemsFormProperty(property);
addItemsToDeny(items);
}
{
String property = properties.getProperty(AUTOTYPE_ACCEPT);
String[] items = splitItemsFormProperty(property);
addItemsToAccept(items);
}
{
String property = properties.getProperty(AUTOTYPE_SUPPORT_PROPERTY);
if ("true".equals(property)) {
this.autoTypeSupport = true;
} else if ("false".equals(property)) {
this.autoTypeSupport = false;
}
}
}
private void addItemsToDeny0(final String[] items){
if (items == null){
return;
}
for (int i = 0; i < items.length; ++i) {
String item = items[i];
this.addDenyInternal(item);
}
}
private void addItemsToDeny(final String[] items){
if (items == null){
return;
}
for (int i = 0; i < items.length; ++i) {
String item = items[i];
this.addDeny(item);
}
}
private void addItemsToAccept(final String[] items){
if (items == null){
return;
}
for (int i = 0; i < items.length; ++i) {
String item = items[i];
this.addAccept(item);
}
}
/**
* @since 1.2.68
*/
public boolean isSafeMode() {
return safeMode;
}
/**
* @since 1.2.68
*/
public void setSafeMode(boolean safeMode) {
this.safeMode = safeMode;
}
public boolean isAutoTypeSupport() {
return autoTypeSupport;
}
public void setAutoTypeSupport(boolean autoTypeSupport) {
this.autoTypeSupport = autoTypeSupport;
}
public boolean isAsmEnable() {
return asmEnable;
}
public void setAsmEnable(boolean asmEnable) {
this.asmEnable = asmEnable;
}
/**
* @deprecated
*/
public IdentityHashMap<Type, ObjectDeserializer> getDerializers() {
return deserializers;
}
public IdentityHashMap<Type, ObjectDeserializer> getDeserializers() {
return deserializers;
}
public ObjectDeserializer getDeserializer(Type type) {
ObjectDeserializer deserializer = get(type);
if (deserializer != null) {
return deserializer;
}
if (type instanceof Class<?>) {
return getDeserializer((Class<?>) type, type);
}
if (type instanceof ParameterizedType) {
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType instanceof Class<?>) {
return getDeserializer((Class<?>) rawType, type);
} else {
return getDeserializer(rawType);
}
}
if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
Type[] upperBounds = wildcardType.getUpperBounds();
if (upperBounds.length == 1) {
Type upperBoundType = upperBounds[0];
return getDeserializer(upperBoundType);
}
}
return JavaObjectDeserializer.instance;
}
public ObjectDeserializer getDeserializer(Class<?> clazz, Type type) {
ObjectDeserializer deserializer = get(type);
if (deserializer == null && type instanceof ParameterizedTypeImpl) {
Type innerType = TypeReference.intern((ParameterizedTypeImpl) type);
deserializer = get(innerType);
}
if (deserializer != null) {
return deserializer;
}
if (type == null) {
type = clazz;
}
deserializer = get(type);
if (deserializer != null) {
return deserializer;
}
{
JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class);
if (annotation != null) {
Class<?> mappingTo = annotation.mappingTo();
if (mappingTo != Void.class) {
return getDeserializer(mappingTo, mappingTo);
}
}
}
if (type instanceof WildcardType || type instanceof TypeVariable || type instanceof ParameterizedType) {
deserializer = get(clazz);
}
if (deserializer != null) {
return deserializer;
}
for (Module module : modules) {
deserializer = module.createDeserializer(this, clazz);
if (deserializer != null) {
putDeserializer(type, deserializer);
return deserializer;
}
}
String className = clazz.getName();
className = className.replace('$', '.');
if (className.startsWith("java.awt.") //
&& AwtCodec.support(clazz)) {
if (!awtError) {
String[] names = new String[] {
"java.awt.Point",
"java.awt.Font",
"java.awt.Rectangle",
"java.awt.Color"
};
try {
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = AwtCodec.instance);
return deserializer;
}
}
} catch (Throwable e) {
// skip
awtError = true;
}
deserializer = AwtCodec.instance;
}
}
if (!jdk8Error) {
try {
if (className.startsWith("java.time.")) {
String[] names = new String[] {
"java.time.LocalDateTime",
"java.time.LocalDate",
"java.time.LocalTime",
"java.time.ZonedDateTime",
"java.time.OffsetDateTime",
"java.time.OffsetTime",
"java.time.ZoneOffset",
"java.time.ZoneRegion",
"java.time.ZoneId",
"java.time.Period",
"java.time.Duration",
"java.time.Instant"
};
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = Jdk8DateCodec.instance);
return deserializer;
}
}
} else if (className.startsWith("java.util.Optional")) {
String[] names = new String[] {
"java.util.Optional",
"java.util.OptionalDouble",
"java.util.OptionalInt",
"java.util.OptionalLong"
};
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = OptionalCodec.instance);
return deserializer;
}
}
}
} catch (Throwable e) {
// skip
jdk8Error = true;
}
}
if (!jodaError) {
try {
if (className.startsWith("org.joda.time.")) {
String[] names = new String[] {
"org.joda.time.DateTime",
"org.joda.time.LocalDate",
"org.joda.time.LocalDateTime",
"org.joda.time.LocalTime",
"org.joda.time.Instant",
"org.joda.time.Period",
"org.joda.time.Duration",
"org.joda.time.DateTimeZone",
"org.joda.time.format.DateTimeFormatter"
};
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = JodaCodec.instance);
return deserializer;
}
}
}
} catch (Throwable e) {
// skip
jodaError = true;
}
}
if ((!guavaError) //
&& className.startsWith("com.google.common.collect.")) {
try {
String[] names = new String[] {
"com.google.common.collect.HashMultimap",
"com.google.common.collect.LinkedListMultimap",
"com.google.common.collect.LinkedHashMultimap",
"com.google.common.collect.ArrayListMultimap",
"com.google.common.collect.TreeMultimap"
};
for (String name : names) {
if (name.equals(className)) {
putDeserializer(Class.forName(name), deserializer = GuavaCodec.instance);
return deserializer;
}
}
} catch (ClassNotFoundException e) {
// skip
guavaError = true;
}
}
if (className.equals("java.nio.ByteBuffer")) {
putDeserializer(clazz, deserializer = ByteBufferCodec.instance);
}
if (className.equals("java.nio.file.Path")) {
putDeserializer(clazz, deserializer = MiscCodec.instance);
}
if (clazz == Map.Entry.class) {
putDeserializer(clazz, deserializer = MiscCodec.instance);
}
if (className.equals("org.javamoney.moneta.Money")) {
putDeserializer(clazz, deserializer = MonetaCodec.instance);
}
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
for (AutowiredObjectDeserializer autowired : ServiceLoader.load(AutowiredObjectDeserializer.class,
classLoader)) {
for (Type forType : autowired.getAutowiredFor()) {
putDeserializer(forType, autowired);
}
}
} catch (Exception ex) {
// skip
}
if (deserializer == null) {
deserializer = get(type);
}
if (deserializer != null) {
return deserializer;
}
if (clazz.isEnum()) {
if (jacksonCompatible) {
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (TypeUtils.isJacksonCreator(method)) {
deserializer = createJavaBeanDeserializer(clazz, type);
putDeserializer(type, deserializer);
return deserializer;
}
}
}
Class mixInType = (Class) JSON.getMixInAnnotations(clazz);
Class<?> deserClass = null;
JSONType jsonType = TypeUtils.getAnnotation(mixInType != null ? mixInType : clazz, JSONType.class);
if (jsonType != null) {
deserClass = jsonType.deserializer();
try {
deserializer = (ObjectDeserializer) deserClass.newInstance();
putDeserializer(clazz, deserializer);
return deserializer;
} catch (Throwable error) {
// skip
}
}
Method jsonCreatorMethod = null;
if (mixInType != null) {
Method mixedCreator = getEnumCreator(mixInType, clazz);
if (mixedCreator != null) {
try {
jsonCreatorMethod = clazz.getMethod(mixedCreator.getName(), mixedCreator.getParameterTypes());
} catch (Exception e) {
// skip
}
}
} else {
jsonCreatorMethod = getEnumCreator(clazz, clazz);
}
if (jsonCreatorMethod != null) {
deserializer = new EnumCreatorDeserializer(jsonCreatorMethod);
putDeserializer(clazz, deserializer);
return deserializer;
}
deserializer = getEnumDeserializer(clazz);
} else if (clazz.isArray()) {
deserializer = ObjectArrayCodec.instance;
} else if (clazz == Set.class || clazz == HashSet.class || clazz == Collection.class || clazz == List.class
|| clazz == ArrayList.class) {
deserializer = CollectionCodec.instance;
} else if (Collection.class.isAssignableFrom(clazz)) {
deserializer = CollectionCodec.instance;
} else if (Map.class.isAssignableFrom(clazz)) {
deserializer = MapDeserializer.instance;
} else if (Throwable.class.isAssignableFrom(clazz)) {
deserializer = new ThrowableDeserializer(this, clazz);
} else if (PropertyProcessable.class.isAssignableFrom(clazz)) {
deserializer = new PropertyProcessableDeserializer((Class<PropertyProcessable>) clazz);
} else if (clazz == InetAddress.class) {
deserializer = MiscCodec.instance;
} else {
deserializer = createJavaBeanDeserializer(clazz, type);
}
putDeserializer(type, deserializer);
return deserializer;
}
private static Method getEnumCreator(Class clazz, Class enumClass) {
Method[] methods = clazz.getMethods();
Method jsonCreatorMethod = null;
for (Method method : methods) {
if (Modifier.isStatic(method.getModifiers())
&& method.getReturnType() == enumClass
&& method.getParameterTypes().length == 1
) {
JSONCreator jsonCreator = method.getAnnotation(JSONCreator.class);
if (jsonCreator != null) {
jsonCreatorMethod = method;
break;
}
}
}
return jsonCreatorMethod;
}
/**
* 可以通过重写这个方法,定义自己的枚举反序列化实现
* @param clazz 转换的类型
* @return 返回一个枚举的反序列化实现
* @author zhu.xiaojie
* @time 2020-4-5
*/
protected ObjectDeserializer getEnumDeserializer(Class<?> clazz){
return new EnumDeserializer(clazz);
}
/**
*
* @since 1.2.25
*/
public void initJavaBeanDeserializers(Class<?>... classes) {
if (classes == null) {
return;
}
for (Class<?> type : classes) {
if (type == null) {
continue;
}
ObjectDeserializer deserializer = createJavaBeanDeserializer(type, type);
putDeserializer(type, deserializer);
}
}
public ObjectDeserializer createJavaBeanDeserializer(Class<?> clazz, Type type) {
boolean asmEnable = this.asmEnable & !this.fieldBased;
if (asmEnable) {
JSONType jsonType = TypeUtils.getAnnotation(clazz,JSONType.class);
if (jsonType != null) {
Class<?> deserializerClass = jsonType.deserializer();
if (deserializerClass != Void.class) {
try {
Object deseralizer = deserializerClass.newInstance();
if (deseralizer instanceof ObjectDeserializer) {
return (ObjectDeserializer) deseralizer;
}
} catch (Throwable e) {
// skip
}
}
asmEnable = jsonType.asm()
&& jsonType.parseFeatures().length == 0;
}
if (asmEnable) {
Class<?> superClass = JavaBeanInfo.getBuilderClass(clazz, jsonType);
if (superClass == null) {
superClass = clazz;
}
for (;;) {
if (!Modifier.isPublic(superClass.getModifiers())) {
asmEnable = false;
break;
}
superClass = superClass.getSuperclass();
if (superClass == Object.class || superClass == null) {
break;
}
}
}
}
if (clazz.getTypeParameters().length != 0) {
asmEnable = false;
}
if (asmEnable && asmFactory != null && asmFactory.classLoader.isExternalClass(clazz)) {
asmEnable = false;
}
if (asmEnable) {
asmEnable = ASMUtils.checkName(clazz.getSimpleName());
}
if (asmEnable) {
if (clazz.isInterface()) {
asmEnable = false;
}
JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz
, type
, propertyNamingStrategy
,false
, TypeUtils.compatibleWithJavaBean
, jacksonCompatible
);
if (asmEnable && beanInfo.fields.length > 200) {
asmEnable = false;
}
Constructor<?> defaultConstructor = beanInfo.defaultConstructor;
if (asmEnable && defaultConstructor == null && !clazz.isInterface()) {
asmEnable = false;
}
for (FieldInfo fieldInfo : beanInfo.fields) {
if (fieldInfo.getOnly) {
asmEnable = false;
break;
}
Class<?> fieldClass = fieldInfo.fieldClass;
if (!Modifier.isPublic(fieldClass.getModifiers())) {
asmEnable = false;
break;
}
if (fieldClass.isMemberClass() && !Modifier.isStatic(fieldClass.getModifiers())) {
asmEnable = false;
break;
}
if (fieldInfo.getMember() != null //
&& !ASMUtils.checkName(fieldInfo.getMember().getName())) {
asmEnable = false;
break;
}
JSONField annotation = fieldInfo.getAnnotation();
if (annotation != null //
&& ((!ASMUtils.checkName(annotation.name())) //
|| annotation.format().length() != 0 //
|| annotation.deserializeUsing() != Void.class //
|| annotation.parseFeatures().length != 0 //
|| annotation.unwrapped())
|| (fieldInfo.method != null && fieldInfo.method.getParameterTypes().length > 1)) {
asmEnable = false;
break;
}
if (fieldClass.isEnum()) { // EnumDeserializer
ObjectDeserializer fieldDeser = this.getDeserializer(fieldClass);
if (!(fieldDeser instanceof EnumDeserializer)) {
asmEnable = false;
break;
}
}
}
}
if (asmEnable) {
if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) {
asmEnable = false;
}
}
if (asmEnable) {
if (TypeUtils.isXmlField(clazz)) {
asmEnable = false;
}
}
if (!asmEnable) {
return new JavaBeanDeserializer(this, clazz, type);
}
JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy);
try {
return asmFactory.createJavaBeanDeserializer(this, beanInfo);
// } catch (VerifyError e) {
// e.printStackTrace();
// return new JavaBeanDeserializer(this, clazz, type);
} catch (NoSuchMethodException ex) {
return new JavaBeanDeserializer(this, clazz, type);
} catch (JSONException asmError) {
return new JavaBeanDeserializer(this, beanInfo);
} catch (Exception e) {
throw new JSONException("create asm deserializer error, " + clazz.getName(), e);
}
}
public FieldDeserializer createFieldDeserializer(ParserConfig mapping, //
JavaBeanInfo beanInfo, //
FieldInfo fieldInfo) {
Class<?> clazz = beanInfo.clazz;
Class<?> fieldClass = fieldInfo.fieldClass;
Class<?> deserializeUsing = null;
JSONField annotation = fieldInfo.getAnnotation();
if (annotation != null) {
deserializeUsing = annotation.deserializeUsing();
if (deserializeUsing == Void.class) {
deserializeUsing = null;
}
}
if (deserializeUsing == null && (fieldClass == List.class || fieldClass == ArrayList.class)) {
return new ArrayListTypeFieldDeserializer(mapping, clazz, fieldInfo);
}
return new DefaultFieldDeserializer(mapping, clazz, fieldInfo);
}
public void putDeserializer(Type type, ObjectDeserializer deserializer) {
Type mixin = JSON.getMixInAnnotations(type);
if (mixin != null) {
IdentityHashMap<Type, ObjectDeserializer> mixInClasses = this.mixInDeserializers.get(type);
if (mixInClasses == null) {
//多线程下可能会重复创建,但不影响正确性
mixInClasses = new IdentityHashMap<Type, ObjectDeserializer>(4);
this.mixInDeserializers.put(type, mixInClasses);
}
mixInClasses.put(mixin, deserializer);
} else {
this.deserializers.put(type, deserializer);
}
}
public ObjectDeserializer get(Type type) {
Type mixin = JSON.getMixInAnnotations(type);
if (null == mixin) {
return this.deserializers.get(type);
}
IdentityHashMap<Type, ObjectDeserializer> mixInClasses = this.mixInDeserializers.get(type);
if (mixInClasses == null) {
return null;
}
return mixInClasses.get(mixin);
}
public ObjectDeserializer getDeserializer(FieldInfo fieldInfo) {
return getDeserializer(fieldInfo.fieldClass, fieldInfo.fieldType);
}
/**
* @deprecated internal method, dont call
*/
public boolean isPrimitive(Class<?> clazz) {
return isPrimitive2(clazz);
}
private static Function<Class<?>, Boolean> isPrimitiveFuncation = new Function<Class<?>, Boolean>() {
public Boolean apply(Class<?> clazz) {
return clazz == java.sql.Date.class //
|| clazz == java.sql.Time.class //
|| clazz == java.sql.Timestamp.class;
}
};
/**
* @deprecated internal method, dont call
*/
public static boolean isPrimitive2(final Class<?> clazz) {
Boolean primitive = clazz.isPrimitive() //
|| clazz == Boolean.class //
|| clazz == Character.class //
|| clazz == Byte.class //
|| clazz == Short.class //
|| clazz == Integer.class //
|| clazz == Long.class //
|| clazz == Float.class //
|| clazz == Double.class //
|| clazz == BigInteger.class //
|| clazz == BigDecimal.class //
|| clazz == String.class //
|| clazz == java.util.Date.class //
|| clazz.isEnum() //
;
if (!primitive) {
primitive = ModuleUtil.callWhenHasJavaSql(isPrimitiveFuncation, clazz);
}
return primitive != null ? primitive : false;
}
/**
* fieldName,field ,先生成fieldName的快照,减少之后的findField的轮询
*
* @param clazz
* @param fieldCacheMap :map<fieldName ,Field>
*/
public static void parserAllFieldToCache(Class<?> clazz,Map</**fieldName*/String , Field> fieldCacheMap){
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String fieldName = field.getName();
if (!fieldCacheMap.containsKey(fieldName)) {
fieldCacheMap.put(fieldName, field);
}
}
if (clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class) {
parserAllFieldToCache(clazz.getSuperclass(), fieldCacheMap);
}
}
public static Field getFieldFromCache(String fieldName, Map<String, Field> fieldCacheMap) {
Field field = fieldCacheMap.get(fieldName);
if (field == null) {
field = fieldCacheMap.get("_" + fieldName);
}
if (field == null) {
field = fieldCacheMap.get("m_" + fieldName);
}
if (field == null) {
char c0 = fieldName.charAt(0);
if (c0 >= 'a' && c0 <= 'z') {
char[] chars = fieldName.toCharArray();
chars[0] -= 32; // lower
String fieldNameX = new String(chars);
field = fieldCacheMap.get(fieldNameX);
}
if (fieldName.length() > 2) {
char c1 = fieldName.charAt(1);
if (c0 >= 'a' && c0 <= 'z'
&& c1 >= 'A' && c1 <= 'Z') {
for (Map.Entry<String, Field> entry : fieldCacheMap.entrySet()) {
if (fieldName.equalsIgnoreCase(entry.getKey())) {
field = entry.getValue();
break;
}
}
}
}
}
return field;
}
public ClassLoader getDefaultClassLoader() {
return defaultClassLoader;
}
public void setDefaultClassLoader(ClassLoader defaultClassLoader) {
this.defaultClassLoader = defaultClassLoader;
}
public void addDenyInternal(String name) {
if (name == null || name.length() == 0) {
return;
}
long hash = TypeUtils.fnv1a_64(name);
if (internalDenyHashCodes == null) {
this.internalDenyHashCodes = new long[] {hash};
return;
}
if (Arrays.binarySearch(this.internalDenyHashCodes, hash) >= 0) {
return;
}
long[] hashCodes = new long[this.internalDenyHashCodes.length + 1];
hashCodes[hashCodes.length - 1] = hash;
System.arraycopy(this.internalDenyHashCodes, 0, hashCodes, 0, this.internalDenyHashCodes.length);
Arrays.sort(hashCodes);
this.internalDenyHashCodes = hashCodes;
}
public void addDeny(String name) {
if (name == null || name.length() == 0) {
return;
}
long hash = TypeUtils.fnv1a_64(name);
if (Arrays.binarySearch(this.denyHashCodes, hash) >= 0) {
return;
}
long[] hashCodes = new long[this.denyHashCodes.length + 1];
hashCodes[hashCodes.length - 1] = hash;
System.arraycopy(this.denyHashCodes, 0, hashCodes, 0, this.denyHashCodes.length);
Arrays.sort(hashCodes);
this.denyHashCodes = hashCodes;
}
public void addAccept(String name) {
if (name == null || name.length() == 0) {
return;
}
long hash = TypeUtils.fnv1a_64(name);
if (Arrays.binarySearch(this.acceptHashCodes, hash) >= 0) {
return;
}
long[] hashCodes = new long[this.acceptHashCodes.length + 1];
hashCodes[hashCodes.length - 1] = hash;
System.arraycopy(this.acceptHashCodes, 0, hashCodes, 0, this.acceptHashCodes.length);
Arrays.sort(hashCodes);
this.acceptHashCodes = hashCodes;
}
public Class<?> checkAutoType(Class type) {
if (get(type) != null) {
return type;
}
return checkAutoType(type.getName(), null, JSON.DEFAULT_PARSER_FEATURE);
}
public Class<?> checkAutoType(String typeName, Class<?> expectClass) {
return checkAutoType(typeName, expectClass, JSON.DEFAULT_PARSER_FEATURE);
}
public Class<?> checkAutoType(String typeName, Class<?> expectClass, int features) {
if (typeName == null) {
return null;
}
if (autoTypeCheckHandlers != null) {
for (AutoTypeCheckHandler h : autoTypeCheckHandlers) {
Class<?> type = h.handler(typeName, expectClass, features);
if (type != null) {
return type;
}
}
}
final int safeModeMask = Feature.SafeMode.mask;
boolean safeMode = this.safeMode
|| (features & safeModeMask) != 0
|| (JSON.DEFAULT_PARSER_FEATURE & safeModeMask) != 0;
if (safeMode) {
throw new JSONException("safeMode not support autoType : " + typeName);
}
final int mask = Feature.SupportAutoType.mask;
boolean autoTypeSupport = this.autoTypeSupport
|| (features & mask) != 0
|| (JSON.DEFAULT_PARSER_FEATURE & mask) != 0;
if (typeName.length() >= 192 || typeName.length() < 3) {
throw new JSONException("autoType is not support. " + typeName);
}
final boolean expectClassFlag;
if (expectClass == null) {
expectClassFlag = false;
} else {
long expectHash = TypeUtils.fnv1a_64(expectClass.getName());
if (expectHash == 0x90a25f5baa21529eL
|| expectHash == 0x2d10a5801b9d6136L
|| expectHash == 0xaf586a571e302c6bL
|| expectHash == 0xed007300a7b227c6L
|| expectHash == 0x295c4605fd1eaa95L
|| expectHash == 0x47ef269aadc650b4L
|| expectHash == 0x6439c4dff712ae8bL
|| expectHash == 0xe3dd9875a2dc5283L
|| expectHash == 0xe2a8ddba03e69e0dL
|| expectHash == 0xd734ceb4c3e9d1daL
) {
expectClassFlag = false;
} else {
expectClassFlag = true;
}
}
String className = typeName.replace('$', '.');
Class<?> clazz;
final long h1 = (fnv1a_64_magic_hashcode ^ className.charAt(0)) * fnv1a_64_magic_prime;
if (h1 == 0xaf64164c86024f1aL) { // [
throw new JSONException("autoType is not support. " + typeName);
}
if ((h1 ^ className.charAt(className.length() - 1)) * fnv1a_64_magic_prime == 0x9198507b5af98f0L) {
throw new JSONException("autoType is not support. " + typeName);
}
final long h3 = (((((fnv1a_64_magic_hashcode ^ className.charAt(0))
* fnv1a_64_magic_prime)
^ className.charAt(1))
* fnv1a_64_magic_prime)
^ className.charAt(2))
* fnv1a_64_magic_prime;
long fullHash = TypeUtils.fnv1a_64(className);
boolean internalWhite = Arrays.binarySearch(INTERNAL_WHITELIST_HASHCODES, fullHash) >= 0;
if (internalDenyHashCodes != null) {
long hash = h3;
for (int i = 3; i < className.length(); ++i) {
hash ^= className.charAt(i);
hash *= fnv1a_64_magic_prime;
if (Arrays.binarySearch(internalDenyHashCodes, hash) >= 0) {
throw new JSONException("autoType is not support. " + typeName);
}
}
}
if ((!internalWhite) && (autoTypeSupport || expectClassFlag)) {
long hash = h3;
for (int i = 3; i < className.length(); ++i) {
hash ^= className.charAt(i);
hash *= fnv1a_64_magic_prime;
if (Arrays.binarySearch(acceptHashCodes, hash) >= 0) {
clazz = TypeUtils.loadClass(typeName, defaultClassLoader, true);
if (clazz != null) {
return clazz;
}
}
if (Arrays.binarySearch(denyHashCodes, hash) >= 0 && TypeUtils.getClassFromMapping(typeName) == null) {
if (Arrays.binarySearch(acceptHashCodes, fullHash) >= 0) {
continue;
}
throw new JSONException("autoType is not support. " + typeName);
}
}
}
clazz = TypeUtils.getClassFromMapping(typeName);
if (clazz == null) {
clazz = deserializers.findClass(typeName);
}
if (expectClass == null && clazz != null && Throwable.class.isAssignableFrom(clazz) && !autoTypeSupport) {
clazz = null;
}
if (clazz == null) {
clazz = typeMapping.get(typeName);
}
if (internalWhite) {
clazz = TypeUtils.loadClass(typeName, defaultClassLoader, true);
}
if (clazz != null) {
if (expectClass != null
&& clazz != java.util.HashMap.class
&& clazz != java.util.LinkedHashMap.class
&& !expectClass.isAssignableFrom(clazz)) {
throw new JSONException("type not match. " + typeName + " -> " + expectClass.getName());
}
return clazz;
}
if (!autoTypeSupport) {
long hash = h3;
for (int i = 3; i < className.length(); ++i) {
char c = className.charAt(i);
hash ^= c;
hash *= fnv1a_64_magic_prime;
if (Arrays.binarySearch(denyHashCodes, hash) >= 0) {
if (typeName.endsWith("Exception") || typeName.endsWith("Error")) {
return null;
}
throw new JSONException("autoType is not support. " + typeName);
}
// white list
if (Arrays.binarySearch(acceptHashCodes, hash) >= 0) {
clazz = TypeUtils.loadClass(typeName, defaultClassLoader, true);
if (clazz == null) {
return expectClass;
}
if (expectClass != null && expectClass.isAssignableFrom(clazz)) {
throw new JSONException("type not match. " + typeName + " -> " + expectClass.getName());
}
return clazz;
}
}
}
boolean jsonType = false;
InputStream is = null;
try {
String resource = typeName.replace('.', '/') + ".class";
if (defaultClassLoader != null) {
is = defaultClassLoader.getResourceAsStream(resource);
} else {
is = ParserConfig.class.getClassLoader().getResourceAsStream(resource);
}
if (is != null) {
ClassReader classReader = new ClassReader(is, true);
TypeCollector visitor = new TypeCollector("<clinit>", new Class[0]);
classReader.accept(visitor);
jsonType = visitor.hasJsonType();
}
} catch (Exception e) {
// skip
} finally {
IOUtils.close(is);
}
if (autoTypeSupport || jsonType || expectClassFlag) {
boolean cacheClass = autoTypeSupport || jsonType;
clazz = TypeUtils.loadClass(typeName, defaultClassLoader, cacheClass);
}
if (clazz != null) {
if (jsonType) {
if (autoTypeSupport) {
TypeUtils.addMapping(typeName, clazz);
}
return clazz;
}
if (ClassLoader.class.isAssignableFrom(clazz) // classloader is danger
|| javax.sql.DataSource.class.isAssignableFrom(clazz) // dataSource can load jdbc driver
|| javax.sql.RowSet.class.isAssignableFrom(clazz) //
) {
throw new JSONException("autoType is not support. " + typeName);
}
if (expectClass != null) {
if (expectClass.isAssignableFrom(clazz)) {
if (autoTypeSupport) {
TypeUtils.addMapping(typeName, clazz);
}
return clazz;
} else {
throw new JSONException("type not match. " + typeName + " -> " + expectClass.getName());
}
}
JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, clazz, propertyNamingStrategy);
if (beanInfo.creatorConstructor != null && autoTypeSupport) {
throw new JSONException("autoType is not support. " + typeName);
}
}
if (!autoTypeSupport) {
if (typeName.endsWith("Exception") || typeName.endsWith("Error")) {
return null;
}
throw new JSONException("autoType is not support. " + typeName);
}
if (clazz != null) {
if (autoTypeSupport) {
TypeUtils.addMapping(typeName, clazz);
}
}
return clazz;
}
public void clearDeserializers() {
this.deserializers.clear();
this.initDeserializers();
}
public boolean isJacksonCompatible() {
return jacksonCompatible;
}
public void setJacksonCompatible(boolean jacksonCompatible) {
this.jacksonCompatible = jacksonCompatible;
}
public void register(String typeName, Class type) {
typeMapping.putIfAbsent(typeName, type);
}
public void register(Module module) {
this.modules.add(module);
}
public void addAutoTypeCheckHandler(AutoTypeCheckHandler h) {
List<AutoTypeCheckHandler> autoTypeCheckHandlers = this.autoTypeCheckHandlers;
if (autoTypeCheckHandlers == null) {
this.autoTypeCheckHandlers
= autoTypeCheckHandlers
= new CopyOnWriteArrayList();
}
autoTypeCheckHandlers.add(h);
}
/**
* @since 1.2.68
*/
public interface AutoTypeCheckHandler {
Class<?> handler(String typeName, Class<?> expectClass, int features);
}
}
| alibaba/fastjson | src/main/java/com/alibaba/fastjson/parser/ParserConfig.java |
1,530 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.support.http.stat;
import com.alibaba.druid.support.profile.ProfileStat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import static com.alibaba.druid.util.JdbcSqlStatUtils.get;
public class WebURIStat {
private final String uri;
private volatile int runningCount;
private volatile int concurrentMax;
private volatile long requestCount;
private volatile long requestTimeNano;
private volatile long requestTimeNanoMax;
private volatile long requestTimeNanoMaxOccurTime;
static final AtomicIntegerFieldUpdater<WebURIStat> runningCountUpdater = AtomicIntegerFieldUpdater.newUpdater(WebURIStat.class,
"runningCount");
static final AtomicIntegerFieldUpdater<WebURIStat> concurrentMaxUpdater = AtomicIntegerFieldUpdater.newUpdater(WebURIStat.class,
"concurrentMax");
static final AtomicLongFieldUpdater<WebURIStat> requestCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"requestCount");
static final AtomicLongFieldUpdater<WebURIStat> requestTimeNanoUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"requestTimeNano");
static final AtomicLongFieldUpdater<WebURIStat> requestTimeNanoMaxUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"requestTimeNanoMax");
static final AtomicLongFieldUpdater<WebURIStat> requestTimeNanoMaxOccurTimeUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"requestTimeNanoMaxOccurTime");
private volatile long jdbcFetchRowCount;
private volatile long jdbcFetchRowPeak; // 单次请求读取行数的峰值
static final AtomicLongFieldUpdater<WebURIStat> jdbcFetchRowCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcFetchRowCount");
static final AtomicLongFieldUpdater<WebURIStat> jdbcFetchRowPeakUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcFetchRowPeak");
private volatile long jdbcUpdateCount;
private volatile long jdbcUpdatePeak; // 单次请求更新行数的峰值
static final AtomicLongFieldUpdater<WebURIStat> jdbcUpdateCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcUpdateCount");
static final AtomicLongFieldUpdater<WebURIStat> jdbcUpdatePeakUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcUpdatePeak");
private volatile long jdbcExecuteCount;
private volatile long jdbcExecuteErrorCount;
private volatile long jdbcExecutePeak; // 单次请求执行SQL次数的峰值
private volatile long jdbcExecuteTimeNano;
static final AtomicLongFieldUpdater<WebURIStat> jdbcExecuteCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcExecuteCount");
static final AtomicLongFieldUpdater<WebURIStat> jdbcExecuteErrorCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcExecuteErrorCount");
static final AtomicLongFieldUpdater<WebURIStat> jdbcExecutePeakUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcExecutePeak");
static final AtomicLongFieldUpdater<WebURIStat> jdbcExecuteTimeNanoUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcExecuteTimeNano");
private volatile long jdbcCommitCount;
private volatile long jdbcRollbackCount;
static final AtomicLongFieldUpdater<WebURIStat> jdbcCommitCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcCommitCount");
static final AtomicLongFieldUpdater<WebURIStat> jdbcRollbackCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcRollbackCount");
private volatile long jdbcPoolConnectionOpenCount;
private volatile long jdbcPoolConnectionCloseCount;
static final AtomicLongFieldUpdater<WebURIStat> jdbcPoolConnectionOpenCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcPoolConnectionOpenCount");
static final AtomicLongFieldUpdater<WebURIStat> jdbcPoolConnectionCloseCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcPoolConnectionCloseCount");
private volatile long jdbcResultSetOpenCount;
private volatile long jdbcResultSetCloseCount;
private volatile long errorCount;
private volatile long lastAccessTimeMillis = -1L;
private volatile ProfileStat profiletat = new ProfileStat();
static final AtomicLongFieldUpdater<WebURIStat> jdbcResultSetOpenCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcResultSetOpenCount");
static final AtomicLongFieldUpdater<WebURIStat> jdbcResultSetCloseCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"jdbcResultSetCloseCount");
static final AtomicLongFieldUpdater<WebURIStat> errorCountUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"errorCount");
static final AtomicLongFieldUpdater<WebURIStat> lastAccessTimeMillisUpdater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"lastAccessTimeMillis");
private static final ThreadLocal<WebURIStat> currentLocal = new ThreadLocal<WebURIStat>();
private volatile long histogram_0_1;
private volatile long histogram_1_10;
private volatile long histogram_10_100;
private volatile long histogram_100_1000;
private volatile int histogram_1000_10000;
private volatile int histogram_10000_100000;
private volatile int histogram_100000_1000000;
private volatile int histogram_1000000_more;
static final AtomicLongFieldUpdater<WebURIStat> histogram_0_1_Updater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"histogram_0_1");
static final AtomicLongFieldUpdater<WebURIStat> histogram_1_10_Updater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"histogram_1_10");
static final AtomicLongFieldUpdater<WebURIStat> histogram_10_100_Updater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"histogram_10_100");
static final AtomicLongFieldUpdater<WebURIStat> histogram_100_1000_Updater = AtomicLongFieldUpdater.newUpdater(WebURIStat.class,
"histogram_100_1000");
static final AtomicIntegerFieldUpdater<WebURIStat> histogram_1000_10000_Updater = AtomicIntegerFieldUpdater.newUpdater(WebURIStat.class,
"histogram_1000_10000");
static final AtomicIntegerFieldUpdater<WebURIStat> histogram_10000_100000_Updater = AtomicIntegerFieldUpdater.newUpdater(WebURIStat.class,
"histogram_10000_100000");
static final AtomicIntegerFieldUpdater<WebURIStat> histogram_100000_1000000_Updater = AtomicIntegerFieldUpdater.newUpdater(WebURIStat.class,
"histogram_100000_1000000");
static final AtomicIntegerFieldUpdater<WebURIStat> histogram_1000000_more_Updater = AtomicIntegerFieldUpdater.newUpdater(WebURIStat.class,
"histogram_1000000_more");
public WebURIStat(String uri) {
super();
this.uri = uri;
}
public static WebURIStat current() {
return currentLocal.get();
}
public String getUri() {
return uri;
}
public void beforeInvoke() {
currentLocal.set(this);
int running = runningCountUpdater.incrementAndGet(this);
for (; ; ) {
int max = concurrentMaxUpdater.get(this);
if (running > max) {
if (concurrentMaxUpdater.compareAndSet(this, max, running)) {
break;
}
} else {
break;
}
}
requestCountUpdater.incrementAndGet(this);
WebRequestStat requestStat = WebRequestStat.current();
if (requestStat != null) {
this.setLastAccessTimeMillis(requestStat.getStartMillis());
}
}
public void afterInvoke(Throwable error, long nanos) {
runningCountUpdater.decrementAndGet(this);
requestTimeNanoUpdater.addAndGet(this, nanos);
for (; ; ) {
long current = requestTimeNanoMaxUpdater.get(this);
if (current < nanos) {
if (requestTimeNanoMaxUpdater.compareAndSet(this, current, nanos)) {
// 可能不准确,但是绝大多数情况下都会正确,性能换取一致性
requestTimeNanoMaxOccurTime = System.currentTimeMillis();
break;
} else {
continue;
}
} else {
break;
}
}
histogramRecord(nanos);
if (error != null) {
errorCountUpdater.incrementAndGet(this);
}
{
WebRequestStat localStat = WebRequestStat.current();
if (localStat != null) {
{
long fetchRowCount = localStat.getJdbcFetchRowCount();
this.addJdbcFetchRowCount(fetchRowCount);
for (; ; ) {
long peak = jdbcFetchRowPeakUpdater.get(this);
if (fetchRowCount <= peak) {
break;
}
if (jdbcFetchRowPeakUpdater.compareAndSet(this, peak, fetchRowCount)) {
break;
}
}
}
{
long executeCount = localStat.getJdbcExecuteCount();
this.addJdbcExecuteCount(executeCount);
for (; ; ) {
long peak = jdbcExecutePeakUpdater.get(this);
if (executeCount <= peak) {
break;
}
if (jdbcExecutePeakUpdater.compareAndSet(this, peak, executeCount)) {
break;
}
}
}
{
long updateCount = localStat.getJdbcUpdateCount();
this.addJdbcUpdateCount(updateCount);
for (; ; ) {
long peak = jdbcUpdatePeakUpdater.get(this);
if (updateCount <= peak) {
break;
}
if (jdbcUpdatePeakUpdater.compareAndSet(this, peak, updateCount)) {
break;
}
}
}
jdbcExecuteErrorCountUpdater.addAndGet(this, localStat.getJdbcExecuteErrorCount());
jdbcExecuteTimeNanoUpdater.addAndGet(this, localStat.getJdbcExecuteTimeNano());
this.addJdbcPoolConnectionOpenCount(localStat.getJdbcPoolConnectionOpenCount());
this.addJdbcPoolConnectionCloseCount(localStat.getJdbcPoolConnectionCloseCount());
this.addJdbcResultSetOpenCount(localStat.getJdbcResultSetOpenCount());
this.addJdbcResultSetCloseCount(localStat.getJdbcResultSetCloseCount());
}
}
currentLocal.set(null);
}
private void histogramRecord(long nanos) {
final long millis = nanos / 1000 / 1000;
if (millis < 1) {
histogram_0_1_Updater.incrementAndGet(this);
} else if (millis < 10) {
histogram_1_10_Updater.incrementAndGet(this);
} else if (millis < 100) {
histogram_10_100_Updater.incrementAndGet(this);
} else if (millis < 1000) {
histogram_100_1000_Updater.incrementAndGet(this);
} else if (millis < 10000) {
histogram_1000_10000_Updater.incrementAndGet(this);
} else if (millis < 100000) {
histogram_10000_100000_Updater.incrementAndGet(this);
} else if (millis < 1000000) {
histogram_100000_1000000_Updater.incrementAndGet(this);
} else {
histogram_1000000_more_Updater.incrementAndGet(this);
}
}
public int getRunningCount() {
return this.runningCount;
}
public long getConcurrentMax() {
return concurrentMax;
}
public long getRequestCount() {
return requestCount;
}
public long getRequestTimeNano() {
return requestTimeNano;
}
public long getRequestTimeMillis() {
return getRequestTimeNano() / (1000 * 1000);
}
public void addJdbcFetchRowCount(long delta) {
jdbcFetchRowCountUpdater.addAndGet(this, delta);
}
public long getJdbcFetchRowCount() {
return jdbcFetchRowCount;
}
public long getJdbcFetchRowPeak() {
return jdbcFetchRowPeak;
}
public void addJdbcUpdateCount(long updateCount) {
jdbcUpdateCountUpdater.addAndGet(this, updateCount);
}
public long getJdbcUpdateCount() {
return jdbcUpdateCount;
}
public long getJdbcUpdatePeak() {
return jdbcUpdatePeak;
}
public void incrementJdbcExecuteCount() {
jdbcExecuteCountUpdater.incrementAndGet(this);
}
public void addJdbcExecuteCount(long executeCount) {
jdbcExecuteCountUpdater.addAndGet(this, executeCount);
}
public long getJdbcExecuteCount() {
return jdbcExecuteCount;
}
public long getJdbcExecuteErrorCount() {
return jdbcExecuteErrorCount;
}
public long getJdbcExecutePeak() {
return jdbcExecutePeak;
}
public long getJdbcExecuteTimeMillis() {
return getJdbcExecuteTimeNano() / (1000 * 1000);
}
public long getJdbcExecuteTimeNano() {
return jdbcExecuteTimeNano;
}
public void incrementJdbcCommitCount() {
jdbcCommitCountUpdater.incrementAndGet(this);
}
public long getJdbcCommitCount() {
return jdbcCommitCount;
}
public void incrementJdbcRollbackCount() {
jdbcRollbackCountUpdater.incrementAndGet(this);
}
public long getJdbcRollbackCount() {
return jdbcRollbackCount;
}
public void setLastAccessTimeMillis(long lastAccessTimeMillis) {
this.lastAccessTimeMillis = lastAccessTimeMillis;
}
public Date getLastAccessTime() {
if (lastAccessTimeMillis < 0L) {
return null;
}
return new Date(lastAccessTimeMillis);
}
public long getLastAccessTimeMillis() {
return lastAccessTimeMillis;
}
public long getErrorCount() {
return errorCount;
}
public long getJdbcPoolConnectionOpenCount() {
return jdbcPoolConnectionOpenCount;
}
public void addJdbcPoolConnectionOpenCount(long delta) {
jdbcPoolConnectionOpenCountUpdater.addAndGet(this, delta);
}
public void incrementJdbcPoolConnectionOpenCount() {
jdbcPoolConnectionOpenCountUpdater.incrementAndGet(this);
}
public long getJdbcPoolConnectionCloseCount() {
return jdbcPoolConnectionCloseCount;
}
public void addJdbcPoolConnectionCloseCount(long delta) {
jdbcPoolConnectionCloseCountUpdater.addAndGet(this, delta);
}
public void incrementJdbcPoolConnectionCloseCount() {
jdbcPoolConnectionCloseCountUpdater.incrementAndGet(this);
}
public long getJdbcResultSetOpenCount() {
return jdbcResultSetOpenCount;
}
public void addJdbcResultSetOpenCount(long delta) {
jdbcResultSetOpenCountUpdater.addAndGet(this, delta);
}
public long getJdbcResultSetCloseCount() {
return jdbcResultSetCloseCount;
}
public void addJdbcResultSetCloseCount(long delta) {
jdbcResultSetCloseCountUpdater.addAndGet(this, delta);
}
public ProfileStat getProfiletat() {
return profiletat;
}
public long[] getHistogramValues() {
return new long[]{
//
histogram_0_1, //
histogram_1_10, //
histogram_10_100, //
histogram_100_1000, //
histogram_1000_10000, //
histogram_10000_100000, //
histogram_100000_1000000, //
histogram_1000000_more //
};
}
public WebURIStatValue getValue(boolean reset) {
WebURIStatValue val = new WebURIStatValue();
val.setUri(uri);
val.setRunningCount(runningCount);
val.setConcurrentMax(get(this, concurrentMaxUpdater, reset));
val.setRequestCount(get(this, requestCountUpdater, reset));
val.setRequestTimeNano(get(this, requestTimeNanoUpdater, reset));
val.setRequestTimeNanoMax(get(this, requestTimeNanoMaxUpdater, reset));
val.setRequestTimeNanoMaxOccurTime(get(this, requestTimeNanoMaxOccurTimeUpdater, reset));
val.setJdbcFetchRowCount(get(this, jdbcFetchRowCountUpdater, reset));
val.setJdbcFetchRowPeak(get(this, jdbcFetchRowPeakUpdater, reset));
val.setJdbcUpdateCount(get(this, jdbcUpdateCountUpdater, reset));
val.setJdbcUpdatePeak(get(this, jdbcUpdatePeakUpdater, reset));
val.setJdbcExecuteCount(get(this, jdbcExecuteCountUpdater, reset));
val.setJdbcExecuteErrorCount(get(this, jdbcExecuteErrorCountUpdater, reset));
val.setJdbcExecutePeak(get(this, jdbcExecutePeakUpdater, reset));
val.setJdbcExecuteTimeNano(get(this, jdbcExecuteTimeNanoUpdater, reset));
val.setJdbcCommitCount(get(this, jdbcCommitCountUpdater, reset));
val.setJdbcRollbackCount(get(this, jdbcRollbackCountUpdater, reset));
val.setJdbcPoolConnectionOpenCount(get(this, jdbcPoolConnectionOpenCountUpdater, reset));
val.setJdbcPoolConnectionCloseCount(get(this, jdbcPoolConnectionCloseCountUpdater, reset));
val.setJdbcResultSetOpenCount(get(this, jdbcResultSetOpenCountUpdater, reset));
val.setJdbcResultSetCloseCount(get(this, jdbcResultSetCloseCountUpdater, reset));
val.setErrorCount(get(this, errorCountUpdater, reset));
val.setLastAccessTimeMillis(get(this, lastAccessTimeMillisUpdater, reset));
val.setProfileEntryStatValueList(this.getProfiletat().getStatValue(reset));
val.histogram_0_1 = get(this, histogram_0_1_Updater, reset);
val.histogram_1_10 = get(this, histogram_1_10_Updater, reset);
val.histogram_10_100 = get(this, histogram_10_100_Updater, reset);
val.histogram_100_1000 = get(this, histogram_100_1000_Updater, reset);
val.histogram_1000_10000 = get(this, histogram_1000_10000_Updater, reset);
val.histogram_10000_100000 = get(this, histogram_10000_100000_Updater, reset);
val.histogram_100000_1000000 = get(this, histogram_100000_1000000_Updater, reset);
val.histogram_1000000_more = get(this, histogram_1000000_more_Updater, reset);
return val;
}
public Map<String, Object> getStatData() {
return getValue(false).getStatData();
}
}
| alibaba/druid | core/src/main/java/com/alibaba/druid/support/http/stat/WebURIStat.java |
1,531 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.naming.utils;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.SystemPropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.NoneSelector;
import com.alibaba.nacos.api.selector.SelectorType;
import com.alibaba.nacos.client.env.NacosClientProperties;
import com.alibaba.nacos.client.env.SourceType;
import com.alibaba.nacos.client.utils.ContextPathUtil;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.TemplateUtils;
import com.alibaba.nacos.client.utils.TenantUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
/**
* Init utils.
*
* @author liaochuntao
* @author deshao
*/
public class InitUtils {
private static final String DEFAULT_END_POINT_PORT = "8080";
/**
* Add a difference to the name naming. This method simply initializes the namespace for Naming. Config
* initialization is not the same, so it cannot be reused directly.
*
* @param properties properties
* @return namespace
*/
public static String initNamespaceForNaming(NacosClientProperties properties) {
String tmpNamespace = null;
String isUseCloudNamespaceParsing = properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
properties.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
String.valueOf(Constants.DEFAULT_USE_CLOUD_NAMESPACE_PARSING)));
if (Boolean.parseBoolean(isUseCloudNamespaceParsing)) {
tmpNamespace = TenantUtil.getUserTenantForAns();
LogUtils.NAMING_LOGGER.info("initializer namespace from ans.namespace attribute : {}", tmpNamespace);
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> {
String namespace = properties.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from ALIBABA_ALIWARE_NAMESPACE attribute :" + namespace);
return namespace;
});
}
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> {
String namespace = properties.getPropertyFrom(SourceType.JVM, PropertyKeyConst.NAMESPACE);
LogUtils.NAMING_LOGGER.info("initializer namespace from namespace attribute :" + namespace);
return namespace;
});
if (StringUtils.isEmpty(tmpNamespace)) {
tmpNamespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
}
tmpNamespace = TemplateUtils.stringEmptyAndThenExecute(tmpNamespace, () -> UtilAndComs.DEFAULT_NAMESPACE_ID);
return tmpNamespace;
}
/**
* Init web root context.
*
* @param properties properties
* @since 1.4.1
*/
public static void initWebRootContext(NacosClientProperties properties) {
final String webContext = properties.getProperty(PropertyKeyConst.CONTEXT_PATH);
TemplateUtils.stringNotEmptyAndThenExecute(webContext, () -> {
UtilAndComs.webContext = ContextPathUtil.normalizeContextPath(webContext);
UtilAndComs.nacosUrlBase = UtilAndComs.webContext + "/v1/ns";
UtilAndComs.nacosUrlInstance = UtilAndComs.nacosUrlBase + "/instance";
});
}
/**
* Init end point.
*
* @param properties properties
* @return end point
*/
public static String initEndpoint(final NacosClientProperties properties) {
if (properties == null) {
return "";
}
// Whether to enable domain name resolution rules
String isUseEndpointRuleParsing = properties.getProperty(PropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE,
properties.getProperty(SystemPropertyKeyConst.IS_USE_ENDPOINT_PARSING_RULE,
String.valueOf(ParamUtil.USE_ENDPOINT_PARSING_RULE_DEFAULT_VALUE)));
boolean isUseEndpointParsingRule = Boolean.parseBoolean(isUseEndpointRuleParsing);
String endpointUrl;
if (isUseEndpointParsingRule) {
// Get the set domain name information
endpointUrl = ParamUtil.parsingEndpointRule(properties.getProperty(PropertyKeyConst.ENDPOINT));
if (StringUtils.isBlank(endpointUrl)) {
return "";
}
} else {
endpointUrl = properties.getProperty(PropertyKeyConst.ENDPOINT);
}
if (StringUtils.isBlank(endpointUrl)) {
return "";
}
String endpointPort = TemplateUtils
.stringEmptyAndThenExecute(properties.getProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_PORT),
() -> properties.getProperty(PropertyKeyConst.ENDPOINT_PORT));
endpointPort = TemplateUtils.stringEmptyAndThenExecute(endpointPort, () -> DEFAULT_END_POINT_PORT);
return endpointUrl + ":" + endpointPort;
}
/**
* Register subType for serialization.
*
* <p>
* Now these subType implementation class has registered in static code. But there are some problem for classloader.
* The implementation class will be loaded when they are used, which will make deserialize before register.
* </p>
*
* <p>
* 子类实现类中的静态代码串中已经向Jackson进行了注册,但是由于classloader的原因,只有当 该子类被使用的时候,才会加载该类。这可能会导致Jackson先进性反序列化,再注册子类,从而导致 反序列化失败。
* </p>
*/
public static void initSerialization() {
// TODO register in implementation class or remove subType
JacksonUtils.registerSubtype(NoneSelector.class, SelectorType.none.name());
JacksonUtils.registerSubtype(ExpressionSelector.class, SelectorType.label.name());
}
}
| alibaba/nacos | client/src/main/java/com/alibaba/nacos/client/naming/utils/InitUtils.java |
1,532 | package com.macro.mall.dto;
import com.macro.mall.validator.FlagValidator;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
/**
* 品牌请求参数
* Created by macro on 2018/4/26.
*/
@Data
@EqualsAndHashCode
public class PmsBrandParam {
@NotEmpty
@ApiModelProperty(value = "品牌名称",required = true)
private String name;
@ApiModelProperty(value = "品牌首字母")
private String firstLetter;
@Min(value = 0)
@ApiModelProperty(value = "排序字段")
private Integer sort;
@FlagValidator(value = {"0","1"}, message = "厂家状态不正确")
@ApiModelProperty(value = "是否为厂家制造商")
private Integer factoryStatus;
@FlagValidator(value = {"0","1"}, message = "显示状态不正确")
@ApiModelProperty(value = "是否进行显示")
private Integer showStatus;
@NotEmpty
@ApiModelProperty(value = "品牌logo",required = true)
private String logo;
@ApiModelProperty(value = "品牌大图")
private String bigPic;
@ApiModelProperty(value = "品牌故事")
private String brandStory;
}
| macrozheng/mall | mall-admin/src/main/java/com/macro/mall/dto/PmsBrandParam.java |
1,534 | package cn.hutool.db;
import cn.hutool.core.lang.func.VoidFunc1;
import cn.hutool.db.dialect.Dialect;
import cn.hutool.db.dialect.DialectFactory;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.sql.Wrapper;
import cn.hutool.db.transaction.TransactionLevel;
import cn.hutool.log.StaticLog;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 数据库操作类<br>
* 通过给定的数据源执行给定SQL或者给定数据源和方言,执行相应的CRUD操作<br>
*
* @author Looly
* @since 4.1.2
*/
public class Db extends AbstractDb {
private static final long serialVersionUID = -3378415769645309514L;
/**
* 创建Db<br>
* 使用默认数据源,自动探测数据库连接池
*
* @return Db
*/
public static Db use() {
return use(DSFactory.get());
}
/**
* 创建Db<br>
* 使用默认数据源,自动探测数据库连接池
*
* @param group 数据源分组
* @return Db
*/
public static Db use(String group) {
return use(DSFactory.get(group));
}
/**
* 创建Db<br>
* 会根据数据源连接的元信息识别目标数据库类型,进而使用合适的数据源
*
* @param ds 数据源
* @return Db
*/
public static Db use(DataSource ds) {
return ds == null ? null : new Db(ds);
}
/**
* 创建Db
*
* @param ds 数据源
* @param dialect 方言
* @return Db
*/
public static Db use(DataSource ds, Dialect dialect) {
return new Db(ds, dialect);
}
/**
* 创建Db
*
* @param ds 数据源
* @param driverClassName 数据库连接驱动类名
* @return Db
*/
public static Db use(DataSource ds, String driverClassName) {
return new Db(ds, DialectFactory.newDialect(driverClassName));
}
// ---------------------------------------------------------------------------- Constructor start
/**
* 构造,从DataSource中识别方言
*
* @param ds 数据源
*/
public Db(DataSource ds) {
this(ds, DialectFactory.getDialect(ds));
}
/**
* 构造
*
* @param ds 数据源
* @param driverClassName 数据库连接驱动类名,用于识别方言
*/
public Db(DataSource ds, String driverClassName) {
this(ds, DialectFactory.newDialect(driverClassName));
}
/**
* 构造
*
* @param ds 数据源
* @param dialect 方言
*/
public Db(DataSource ds, Dialect dialect) {
super(ds, dialect);
}
// ---------------------------------------------------------------------------- Constructor end
// ---------------------------------------------------------------------------- Getters and Setters start
@Override
public Db setWrapper(Character wrapperChar) {
return (Db) super.setWrapper(wrapperChar);
}
@Override
public Db setWrapper(Wrapper wrapper) {
return (Db) super.setWrapper(wrapper);
}
@Override
public Db disableWrapper() {
return (Db)super.disableWrapper();
}
// ---------------------------------------------------------------------------- Getters and Setters end
@Override
public Connection getConnection() throws SQLException {
return ThreadLocalConnection.INSTANCE.get(this.ds);
}
@Override
public void closeConnection(Connection conn) {
try {
if (conn != null && false == conn.getAutoCommit()) {
// 事务中的Session忽略关闭事件
return;
}
} catch (SQLException e) {
// ignore
}
ThreadLocalConnection.INSTANCE.close(this.ds);
}
/**
* 执行事务,使用默认的事务级别<br>
* 在同一事务中,所有对数据库操作都是原子的,同时提交或者同时回滚
*
* @param func 事务函数,所有操作应在同一函数下执行,确保在同一事务中
* @return this
* @throws SQLException SQL异常
*/
public Db tx(VoidFunc1<Db> func) throws SQLException {
return tx(null, func);
}
/**
* 执行事务<br>
* 在同一事务中,所有对数据库操作都是原子的,同时提交或者同时回滚
*
* @param transactionLevel 事务级别枚举,null表示使用JDBC默认事务
* @param func 事务函数,所有操作应在同一函数下执行,确保在同一事务中
* @return this
* @throws SQLException SQL异常
*/
public Db tx(TransactionLevel transactionLevel, VoidFunc1<Db> func) throws SQLException {
final Connection conn = getConnection();
// 检查是否支持事务
checkTransactionSupported(conn);
// 设置事务级别
if (null != transactionLevel) {
final int level = transactionLevel.getLevel();
if (conn.getTransactionIsolation() < level) {
// 用户定义的事务级别如果比默认级别更严格,则按照严格的级别进行
//noinspection MagicConstant
conn.setTransactionIsolation(level);
}
}
// 开始事务
boolean autoCommit = conn.getAutoCommit();
if (autoCommit) {
conn.setAutoCommit(false);
}
// 执行事务
try {
func.call(this);
// 提交
conn.commit();
} catch (Throwable e) {
quietRollback(conn);
throw (e instanceof SQLException) ? (SQLException) e : new SQLException(e);
} finally {
// 还原事务状态
quietSetAutoCommit(conn, autoCommit);
// 关闭连接或将连接归还连接池
closeConnection(conn);
}
return this;
}
// ---------------------------------------------------------------------------- Private method start
/**
* 静默回滚事务
*
* @param conn Connection
*/
private void quietRollback(Connection conn) {
if (null != conn) {
try {
conn.rollback();
} catch (Exception e) {
StaticLog.error(e);
}
}
}
/**
* 静默设置自动提交
*
* @param conn Connection
* @param autoCommit 是否自动提交
*/
private void quietSetAutoCommit(Connection conn, Boolean autoCommit) {
if (null != conn && null != autoCommit) {
try {
conn.setAutoCommit(autoCommit);
} catch (Exception e) {
StaticLog.error(e);
}
}
}
// ---------------------------------------------------------------------------- Private method end
}
| dromara/hutool | hutool-db/src/main/java/cn/hutool/db/Db.java |
1,535 | /*
* Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.server;
import java.io.IOException;
import java.nio.channels.NetworkChannel;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.mycat.MycatServer;
import io.mycat.backend.mysql.listener.DefaultSqlExecuteStageListener;
import io.mycat.backend.mysql.listener.SqlExecuteStageListener;
import io.mycat.config.ErrorCode;
import io.mycat.config.model.SchemaConfig;
import io.mycat.config.model.SystemConfig;
import io.mycat.net.FrontendConnection;
import io.mycat.route.RouteResultset;
import io.mycat.server.handler.MysqlProcHandler;
import io.mycat.server.parser.ServerParse;
import io.mycat.server.response.Heartbeat;
import io.mycat.server.response.InformationSchemaProfiling;
import io.mycat.server.response.InformationSchemaProfilingSqlyog;
import io.mycat.server.response.Ping;
import io.mycat.server.util.SchemaUtil;
import io.mycat.util.SplitUtil;
import io.mycat.util.TimeUtil;
/**
* @author mycat
*/
public class ServerConnection extends FrontendConnection {
private static final Logger LOGGER = LoggerFactory
.getLogger(ServerConnection.class);
private long authTimeout = SystemConfig.DEFAULT_AUTH_TIMEOUT;
/** 保存SET SQL_SELECT_LIMIT的值, default 解析为-1. */
private volatile int sqlSelectLimit = -1;
private volatile boolean txReadonly;
private volatile int txIsolation;
private volatile boolean autocommit;
private volatile boolean preAcStates; //上一个ac状态,默认为true
private volatile boolean txInterrupted;
private volatile String txInterrputMsg = "";
private long lastInsertId;
private NonBlockingSession session;
/**
* 标志是否执行了lock tables语句,并处于lock状态
*/
private volatile boolean isLocked = false;
private Queue<SqlEntry> executeSqlQueue;
private SqlExecuteStageListener listener;
public ServerConnection(NetworkChannel channel)
throws IOException {
super(channel);
this.txInterrupted = false;
this.autocommit = true;
this.preAcStates = true;
this.txReadonly = false;
this.executeSqlQueue = new LinkedBlockingQueue<>();
this.listener = new DefaultSqlExecuteStageListener(this);
}
@Override
public boolean isIdleTimeout() {
if (isAuthenticated) {
return super.isIdleTimeout();
} else {
return TimeUtil.currentTimeMillis() > Math.max(lastWriteTime, lastReadTime) + this.authTimeout;
}
}
public long getAuthTimeout() {
return authTimeout;
}
public void setAuthTimeout(long authTimeout) {
this.authTimeout = authTimeout;
}
public int getTxIsolation() {
return txIsolation;
}
public void setTxIsolation(int txIsolation) {
this.txIsolation = txIsolation;
}
public boolean isAutocommit() {
return autocommit;
}
public void setAutocommit(boolean autocommit) {
this.autocommit = autocommit;
}
public boolean isTxReadonly() {
return txReadonly;
}
public void setTxReadonly(boolean txReadonly) {
this.txReadonly = txReadonly;
}
public int getSqlSelectLimit() {
return sqlSelectLimit;
}
public void setSqlSelectLimit(int sqlSelectLimit) {
this.sqlSelectLimit = sqlSelectLimit;
}
public long getLastInsertId() {
return lastInsertId;
}
public void setLastInsertId(long lastInsertId) {
this.lastInsertId = lastInsertId;
}
/**
* 设置是否需要中断当前事务
*/
public void setTxInterrupt(String txInterrputMsg) {
if (!autocommit && !txInterrupted) {
txInterrupted = true;
this.txInterrputMsg = txInterrputMsg;
}
}
/**
*
* 清空食事务中断
* */
public void clearTxInterrupt() {
if (!autocommit && txInterrupted) {
txInterrupted = false;
this.txInterrputMsg = "";
}
}
public boolean isTxInterrupted()
{
return txInterrupted;
}
public NonBlockingSession getSession2() {
return session;
}
public void setSession2(NonBlockingSession session2) {
this.session = session2;
}
public boolean isLocked() {
return isLocked;
}
public void setLocked(boolean isLocked) {
this.isLocked = isLocked;
}
@Override
public void ping() {
Ping.response(this);
}
@Override
public void heartbeat(byte[] data) {
Heartbeat.response(this, data);
}
public void execute(String sql, int type) {
//连接状态检查
if (this.isClosed()) {
LOGGER.warn("ignore execute ,server connection is closed " + this);
return;
}
// 事务状态检查
if (txInterrupted) {
writeErrMessage(ErrorCode.ER_YES,
"Transaction error, need to rollback." + txInterrputMsg);
return;
}
// 检查当前使用的DB
String db = this.schema;
boolean isDefault = true;
if (db == null) {
db = SchemaUtil.detectDefaultDb(sql, type);
if (db == null) {
db = MycatServer.getInstance().getConfig().getUsers().get(user).getDefaultSchema();
if (db == null) {
writeErrMessage(ErrorCode.ERR_BAD_LOGICDB,
"No MyCAT Database selected");
return ;
}
}
isDefault = false;
}
// 兼容PhpAdmin's, 支持对MySQL元数据的模拟返回
//// TODO: 2016/5/20 支持更多information_schema特性
// if (ServerParse.SELECT == type
// && db.equalsIgnoreCase("information_schema") ) {
// MysqlInformationSchemaHandler.handle(sql, this);
// return;
// }
if (ServerParse.SELECT == type
&& sql.contains("mysql")
&& sql.contains("proc")) {
SchemaUtil.SchemaInfo schemaInfo = SchemaUtil.parseSchema(sql);
if (schemaInfo != null
&& "mysql".equalsIgnoreCase(schemaInfo.schema)
&& "proc".equalsIgnoreCase(schemaInfo.table)) {
// 兼容MySQLWorkbench
MysqlProcHandler.handle(sql, this);
return;
}
}
SchemaConfig schema = MycatServer.getInstance().getConfig().getSchemas().get(db);
if (schema == null) {
writeErrMessage(ErrorCode.ERR_BAD_LOGICDB,
"Unknown MyCAT Database '" + db + "'");
return;
}
//fix navicat SELECT STATE AS `State`, ROUND(SUM(DURATION),7) AS `Duration`, CONCAT(ROUND(SUM(DURATION)/*100,3), '%') AS `Percentage` FROM INFORMATION_SCHEMA.PROFILING WHERE QUERY_ID= GROUP BY STATE ORDER BY SEQ
if(ServerParse.SELECT == type &&sql.contains(" INFORMATION_SCHEMA.PROFILING ")&&sql.contains("CONCAT(ROUND(SUM(DURATION)/"))
{
InformationSchemaProfiling.response(this);
return;
}
//fix sqlyog select state, round(sum(duration),5) as `duration (summed) in sec` from information_schema.profiling where query_id = 0 group by state order by `duration (summed) in sec` desc
if(ServerParse.SELECT == type &&sql.contains(" information_schema.profiling ")&&sql.contains("duration (summed) in sec"))
{
InformationSchemaProfilingSqlyog.response(this);
return;
}
/* 当已经设置默认schema时,可以通过在sql中指定其它schema的方式执行
* 相关sql,已经在mysql客户端中验证。
* 所以在此处增加关于sql中指定Schema方式的支持。
*/
if (isDefault && schema.isCheckSQLSchema() && isNormalSql(type)) {
SchemaUtil.SchemaInfo schemaInfo = SchemaUtil.parseSchema(sql);
if (schemaInfo != null && schemaInfo.schema != null && !schemaInfo.schema.equals(db)) {
SchemaConfig schemaConfig = MycatServer.getInstance().getConfig().getSchemas().get(schemaInfo.schema);
if (schemaConfig != null)
schema = schemaConfig;
}
}
routeEndExecuteSQL(sql, type, schema);
}
private boolean isNormalSql(int type) {
return ServerParse.SELECT==type||ServerParse.INSERT==type||ServerParse.UPDATE==type||ServerParse.DELETE==type||ServerParse.DDL==type;
}
public RouteResultset routeSQL(String sql, int type) {
// 检查当前使用的DB
String db = this.schema;
if (db == null) {
db = SchemaUtil.detectDefaultDb(sql, type);
if (db == null){
db = MycatServer.getInstance().getConfig().getUsers().get(user).getDefaultSchema();
if (db == null) {
writeErrMessage(ErrorCode.ERR_BAD_LOGICDB,
"No MyCAT Database selected");
return null;
}
}
}
SchemaConfig schema = MycatServer.getInstance().getConfig()
.getSchemas().get(db);
if (schema == null) {
writeErrMessage(ErrorCode.ERR_BAD_LOGICDB,
"Unknown MyCAT Database '" + db + "'");
return null;
}
// 路由计算
RouteResultset rrs = null;
try {
rrs = MycatServer
.getInstance()
.getRouterservice()
.route(MycatServer.getInstance().getConfig().getSystem(),
schema, type, sql, this.charset, this);
} catch (Exception e) {
StringBuilder s = new StringBuilder();
LOGGER.warn(s.append(this).append(sql).toString() + " err:" + e.toString(),e);
String msg = e.getMessage();
writeErrMessage(ErrorCode.ER_PARSE_ERROR, msg == null ? e.getClass().getSimpleName() : msg);
return null;
}
return rrs;
}
public void routeEndExecuteSQL(String sql, final int type, final SchemaConfig schema) {
// 路由计算
RouteResultset rrs = null;
try {
rrs = MycatServer
.getInstance()
.getRouterservice()
.route(MycatServer.getInstance().getConfig().getSystem(),
schema, type, sql, this.charset, this);
} catch (Exception e) {
StringBuilder s = new StringBuilder();
LOGGER.warn(s.append(this).append(sql).toString() + " err:" + e.toString(),e);
String msg = e.getMessage();
writeErrMessage(ErrorCode.ER_PARSE_ERROR, msg == null ? e.getClass().getSimpleName() : msg);
return;
}
if (rrs != null) {
// #支持mariadb驱动useBatchMultiSend=true,连续接收到的sql先放入队列,等待前面处理完成后再继续处理。
// 参考https://mariadb.com/kb/en/option-batchmultisend-description/
boolean executeNow = false;
synchronized (this.executeSqlQueue) {
executeNow = this.executeSqlQueue.isEmpty();
this.executeSqlQueue.add(new SqlEntry(sql, type, rrs));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("add queue,executeSqlQueue size {}", executeSqlQueue.size());
}
}
if (executeNow) {
this.executeSqlId++;
session.execute(rrs, rrs.isSelectForUpdate() ? ServerParse.UPDATE : type);
}
}
}
/**
* 提交事务
*/
public void commit() {
if (txInterrupted) {
LOGGER.warn("receive commit ,but found err message in Transaction {}",this);
this.rollback();
// writeErrMessage(ErrorCode.ER_YES,
// "Transaction error, need to rollback.");
} else {
session.commit();
}
}
/**
* 回滚事务
*/
public void rollback() {
// 状态检查
if (txInterrupted) {
txInterrupted = false;
}
// 执行回滚
session.rollback();
}
/**
* 执行lock tables语句方法
* @param sql
*/
public void lockTable(String sql) {
// 事务中不允许执行lock table语句
if (!autocommit) {
writeErrMessage(ErrorCode.ER_YES, "can't lock table in transaction!");
return;
}
// 已经执行了lock table且未执行unlock table之前的连接不能再次执行lock table命令
if (isLocked) {
writeErrMessage(ErrorCode.ER_YES, "can't lock multi-table");
return;
}
RouteResultset rrs = routeSQL(sql, ServerParse.LOCK);
if (rrs != null) {
session.lockTable(rrs);
}
}
/**
* 执行unlock tables语句方法
* @param sql
*/
public void unLockTable(String sql) {
sql = sql.replaceAll("\n", " ").replaceAll("\t", " ");
String[] words = SplitUtil.split(sql, ' ', true);
if (words.length==2 && ("table".equalsIgnoreCase(words[1]) || "tables".equalsIgnoreCase(words[1]))) {
isLocked = false;
session.unLockTable(sql);
} else {
writeErrMessage(ErrorCode.ER_UNKNOWN_COM_ERROR, "Unknown command");
}
}
/**
* 撤销执行中的语句
*
* @param sponsor
* 发起者为null表示是自己
*/
public void cancel(final FrontendConnection sponsor) {
processor.getExecutor().execute(new Runnable() {
@Override
public void run() {
session.cancel(sponsor);
}
});
}
@Override
public void close(String reason) {
super.close(reason);
session.terminate();
if(getLoadDataInfileHandler()!=null)
{
getLoadDataInfileHandler().clear();
}
}
/**
* add huangyiming 检测字符串中某字符串出现次数
* @param srcText
* @param findText
* @return
*/
public static int appearNumber(String srcText, String findText) {
int count = 0;
Pattern p = Pattern.compile(findText);
Matcher m = p.matcher(srcText);
while (m.find()) {
count++;
}
return count;
}
@Override
public String toString() {
return "ServerConnection [id=" + id + ", schema=" + schema + ", host="
+ host + ", user=" + user + ",txIsolation=" + txIsolation
+ ", autocommit=" + autocommit + ", schema=" + schema+ ", executeSql=" + executeSql + "]" +
this.getSession2();
}
public boolean isPreAcStates() {
return preAcStates;
}
public void setPreAcStates(boolean preAcStates) {
this.preAcStates = preAcStates;
}
public SqlExecuteStageListener getListener() {
return listener;
}
public void setListener(SqlExecuteStageListener listener) {
this.listener = listener;
}
@Override
public void checkQueueFlow() {
RouteResultset rrs = session.getRrs();
if (rrs != null && rrs.getNodes().length > 1 && session.getRrs().needMerge()) {
// 多节点合并结果集语句需要拉取所有数据,无法流控
return;
} else {
// 非合并结果集语句进行流量控制检查。
flowController.check(session.getTargetMap());
}
}
@Override
public void resetConnection() {
// 1 简单点直接关闭后端连接。若按照mysql官方的提交事务或回滚事务,mycat都会回包给应用,引发包乱序。
session.closeAndClearResources("receive com_reset_connection");
// 2 重置用户变量
this.txInterrupted = false;
this.autocommit = true;
this.preAcStates = true;
this.txReadonly = false;
this.lastInsertId = 0;
super.resetConnection();
}
/**
* sql执行完成后回调函数
*/
public void onEventSqlCompleted() {
SqlEntry sqlEntry = null;
synchronized (this.executeSqlQueue) {
this.executeSqlQueue.poll();// 弹出已经执行成功的
sqlEntry = this.executeSqlQueue.peek();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("poll queue,executeSqlQueue size {}", this.executeSqlQueue.size());
}
}
if (sqlEntry != null) {
this.executeSqlId++;
session.execute(sqlEntry.rrs, sqlEntry.rrs.isSelectForUpdate() ? ServerParse.UPDATE : sqlEntry.type);
}
}
private class SqlEntry {
public String sql;
public int type;
public RouteResultset rrs;
public SqlEntry(String sql, int type, RouteResultset rrs) {
this.sql = sql;
this.type = type;
this.rrs = rrs;
}
}
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/server/ServerConnection.java |
1,538 | package base.transaction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* 测试事务.
*
* @author skywalker
*/
@Component
public class TransactionBean {
public NestedBean getNestedBean() {
return nestedBean;
}
public void setNestedBean(NestedBean nestedBean) {
this.nestedBean = nestedBean;
}
private NestedBean nestedBean;
@Transactional(propagation = Propagation.REQUIRED)
public void process() {
System.out.println("事务执行");
nestedBean.nest();
}
}
| seaswalker/spring-analysis | src/main/java/base/transaction/TransactionBean.java |
1,539 | package com.xkcoding.websocket.socketio.config;
/**
* <p>
* 事件常量
* </p>
*
* @author yangkai.shen
* @date Created in 2018-12-18 19:36
*/
public interface Event {
/**
* 聊天事件
*/
String CHAT = "chat";
/**
* 广播消息
*/
String BROADCAST = "broadcast";
/**
* 群聊
*/
String GROUP = "group";
/**
* 加入群聊
*/
String JOIN = "join";
}
| xkcoding/spring-boot-demo | demo-websocket-socketio/src/main/java/com/xkcoding/websocket/socketio/config/Event.java |
1,540 | M
1523330238
tags: Tree, DFS, DP, Status DP
Houses被arrange成了binary tree, 规则还是一样, 连续相连的房子不能同时抄.
求Binary Tree neighbor max 能抄多少.
#### DFS
- 判断当下的node是否被采用,用一个boolean来表示.
- 如果curr node被采用,那么下面的child一定不能被采用.
- 如果curr node不被采用,那么下面的children有可能被采用,但也可能略过,所以这里用Math.max() 比较一下两种可能有的dfs结果。
- dfs重复计算:每个root都有4种dive in的可能性, 假设level高度是h, 那么时间O(4^(h)), where h = logN, 也就是O(n^2)
#### DP, DFS
- 并不是单纯的DP, 是在发现DFS很费劲后, 想能不能代替一些重复计算?
- 基本思想是dfs解法一致: 取root找最大值, 或者不取root找最大值
- 在root上DFS, 不在dfs进入前分叉; 每一个level按照状态来存相应的值: dp[0] root not picked, dp[1] root picked.
- Optimization: DP里面, 一口气找leftDP[]会dfs到最底层, 然后自下向上做计算
- 这个过程里面, 因为没有在外面给dfs()分叉, 计算就不会重叠, 再也不用回去visit most-left-leaf了, 算过一遍就完事.
- 然而, 普通没有dp的dfs, 在算完visited的情况下的dfs, 还要重新dfs一遍!visited的情况.
- Space O(h), time O(n), 或者说是O(2^h), where h = log(n)
#### DP 特点
- 不为状态而分叉dfs
- 把不同状态model成dp
- 每一个dfs都return一个based on status的 dp array.
- 等于一次性dfs计算到底, 然后back track, 计算顶部的每一层.
- DP 并不一定要是以n为base的. 也可以是局部的去memorize状态->value.
```
/*
The thief has found himself a new place for his thievery again.
There is only one entrance to this area, called the "root."
Besides the root, each house has one and only one parent house.
After a tour, the smart thief realized that "all houses in this place forms a binary tree".
It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
Subscribe to see which companies asked this question
Tree Depth-first Search
Hide Similar Problems (E) House Robber (M) House Robber II
*/
/*
Thoughts:
There are lots of redundant calculations in this particular dfs.
Let:
- dp[0] represent: max value when you do not pick up root i.
- dp[1] represent: max value when you do pick up root i.
The logic break down should be the same as in DFS.
This is different from regular DP, where we have a global dp[][].
Here we still have to do dp, combine with dfs.
*/
class Solution {
public int rob(TreeNode root) {
int[] dp = dfs(root);
return Math.max(dp[0], dp[1]);
}
public int[] dfs(TreeNode root) {
int[] dp = new int[2]; // {0, 0}
if (root == null) {
return dp;
}
int[] leftDP = dfs(root.left);
int[] rightDP = dfs(root.right);
dp[0] = Math.max(leftDP[0], leftDP[1]) + Math.max(rightDP[0], rightDP[1]); // do not pick root
dp[1] = root.val + leftDP[0] + rightDP[0]; // do pick root
return dp;
}
}
/*
Thoughts:
DFS. Always deal with the 3 ndoes: root, left, and right.
Either of them can be picked or not picked: overeall 6 possibilities: a bit of redundant calculation
Right/Left are independent to create combination cases.
*/
class Solution {
public int rob(TreeNode root) {
return Math.max(dfs(root, true), dfs(root, false));
}
public int dfs(TreeNode root, boolean visited) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return visited ? root.val : 0;
}
int leftMaxValue = 0;
int rightMaxValue = 0;
if (visited) { // If root visited, we can't use left/right children
leftMaxValue = dfs(root.left, !visited);
rightMaxValue = dfs(root.right, !visited);
return root.val + leftMaxValue + rightMaxValue;
} else {
leftMaxValue = Math.max(dfs(root.left, visited), dfs(root.left, !visited));
rightMaxValue = Math.max(dfs(root.right, visited), dfs(root.right, !visited));
return leftMaxValue + rightMaxValue;
}
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
3.24.2016
Thought: dfs should be able to handle this.
*/
public class Solution {
public int rob(TreeNode root) {
if (root == null) {
return 0;
} else if (root.left == null && root.right == null) {
return root.val;
}
return Math.max(dfs(root,true), dfs(root, false));
}
public int dfs (TreeNode node, boolean visit) {
if (node.left == null && node.right == null) {
if (visit){
return node.val;
} else {
return 0;
}
}
int left = 0;
int right = 0;
if (visit) {
if (node.left != null) {
left = dfs(node.left, !visit);
}
if (node.right != null) {
right = dfs(node.right, !visit);
}
return node.val + left + right;
} else {
if (node.left != null) {
left = Math.max(dfs(node.left, !visit), dfs(node.left, visit));
}
if (node.right != null) {
right = Math.max(dfs(node.right, !visit), dfs(node.right, visit));
}
return left + right;
}
}
}
``` | awangdev/leet-code | Java/House Robber III.java |
1,543 | /*
* Copyright 2017 JessYan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jess.arms.base;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.jess.arms.utils.ThirdViewUtil;
import com.zhy.autolayout.utils.AutoUtils;
/**
* ================================================
* 基类 {@link RecyclerView.ViewHolder}
* <p>
* Created by JessYan on 2015/11/24.
* <a href="mailto:[email protected]">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* ================================================
*/
public abstract class BaseHolder<T> extends RecyclerView.ViewHolder implements View.OnClickListener {
protected final String TAG = this.getClass().getSimpleName();
protected OnViewClickListener mOnViewClickListener = null;
public BaseHolder(View itemView) {
super(itemView);
//点击事件
itemView.setOnClickListener(this);
//屏幕适配
if (ThirdViewUtil.isUseAutolayout()) {
AutoUtils.autoSize(itemView);
}
//绑定 ButterKnife
ThirdViewUtil.bindTarget(this, itemView);
}
/**
* 设置数据
*
* @param data 数据
* @param position 在 RecyclerView 中的位置
*/
public abstract void setData(@NonNull T data, int position);
/**
* 在 Activity 的 onDestroy 中使用 {@link DefaultAdapter#releaseAllHolder(RecyclerView)} 方法 (super.onDestroy() 之前)
* {@link BaseHolder#onRelease()} 才会被调用, 可以在此方法中释放一些资源
*/
protected void onRelease() {
}
@Override
public void onClick(View view) {
if (mOnViewClickListener != null) {
mOnViewClickListener.onViewClick(view, this.getPosition());
}
}
public void setOnItemClickListener(OnViewClickListener listener) {
this.mOnViewClickListener = listener;
}
/**
* item 点击事件
*/
public interface OnViewClickListener {
/**
* item 被点击
*
* @param view 被点击的 {@link View}
* @param position 在 RecyclerView 中的位置
*/
void onViewClick(View view, int position);
}
} | JessYanCoding/MVPArms | arms/src/main/java/com/jess/arms/base/BaseHolder.java |
1,544 | package com.zheng.common.listener;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import java.lang.reflect.Method;
import java.util.Map;
/**
* spring容器初始化完成事件
* Created by shuzheng on 2017/1/7.
*/
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextListener.class);
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
// root application context
if(null == contextRefreshedEvent.getApplicationContext().getParent()) {
LOGGER.debug(">>>>> spring初始化完毕 <<<<<");
// spring初始化完毕后,通过反射调用所有使用BaseService注解的initMapper方法
Map<String, Object> baseServices = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(BaseService.class);
for(Object service : baseServices.values()) {
LOGGER.debug(">>>>> {}.initMapper()", service.getClass().getName());
try {
Method initMapper = service.getClass().getMethod("initMapper");
initMapper.invoke(service);
} catch (Exception e) {
LOGGER.error("初始化BaseService的initMapper方法异常", e);
e.printStackTrace();
}
}
// 系统入口初始化
Map<String, BaseInterface> baseInterfaceBeans = contextRefreshedEvent.getApplicationContext().getBeansOfType(BaseInterface.class);
for(Object service : baseInterfaceBeans.values()) {
LOGGER.debug(">>>>> {}.init()", service.getClass().getName());
try {
Method init = service.getClass().getMethod("init");
init.invoke(service);
} catch (Exception e) {
LOGGER.error("初始化BaseInterface的init方法异常", e);
e.printStackTrace();
}
}
}
}
}
| shuzheng/zheng | zheng-common/src/main/java/com/zheng/common/listener/ApplicationContextListener.java |
1,549 | package com.tamsiree.rxui.view;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import com.tamsiree.rxkit.RxImageTool;
import com.tamsiree.rxui.R;
/**
* @author tamsiree
*/
public class RxSeekBar extends View {
private static final float DEFAULT_RADIUS = 0.5f;
//default seekbar's padding left and right
private int defaultPaddingLeftAndRight;
private int defaultPaddingTop;
//进度提示的背景 The background of the progress
private int mProgressHintBGId;
// 按钮的背景 The background of the Drag button
private int mThumbResId;
//刻度模式:number根据数字实际比例排列;other 均分排列
//Scale mode:
// number according to the actual proportion of the number of arranged;
// other equally arranged
private int mCellMode;
//single是Seekbar模式,range是RxSeekBar
//single is Seekbar mode, range is angeSeekbar
//single = 1; range = 2
private int mSeekBarMode;
//默认为1,当大于1时自动切回刻度模式
//The default is 1, and when it is greater than 1,
// it will automatically switch back to the scale mode
private int cellsCount = 1;
//刻度与进度条间的间距
//The spacing between the scale and the progress bar
private int textPadding;
//进度提示背景与按钮之间的距离
//The progress indicates the distance between the background and the button
private int mHintBGPadding;
private int mSeekBarHeight;
private int mThumbSize;
//两个按钮之间的最小距离
//The minimum distance between two buttons
private int reserveCount;
private int mCursorTextHeight;
private int mPartLength;
private int heightNeeded;
private int lineCorners;
private int lineWidth;
//选择过的进度条颜色
// the color of the selected progress bar
private int colorLineSelected;
//未选则的进度条颜色
// the color of the unselected progress bar
private int colorLineEdge;
//The foreground color of progress bar and thumb button.
private int colorPrimary;
//The background color of progress bar and thumb button.
private int colorSecondary;
//刻度文字与提示文字的大小
//Scale text and prompt text size
private int mTextSize;
private int lineTop, lineBottom, lineLeft, lineRight;
//进度提示背景的高度,宽度如果是0的话会自适应调整
//Progress prompted the background height, width,
// if it is 0, then adaptively adjust
private float mHintBGHeight;
private float mHintBGWith;
private float offsetValue;
private float cellsPercent;
private float reserveValue;
private float reservePercent;
private float maxValue, minValue;
//真实的最大值和最小值
//True maximum and minimum values
private float mMin, mMax;
private boolean isEnable = true;
private boolean mHideProgressHint;
//刻度上显示的文字
//The texts displayed on the scale
private CharSequence[] mTextArray;
private Bitmap mProgressHintBG;
private Paint mMainPaint = new Paint();
private Paint mCursorPaint = new Paint();
private Paint mProgressPaint;
private RectF line = new RectF();
private SeekBar leftSB;
private SeekBar rightSB;
private SeekBar currTouch;
private OnRangeChangedListener callback;
public boolean isHintHolder() {
return mIsHintHolder;
}
public void setHintHolder(boolean hintHolder) {
mIsHintHolder = hintHolder;
}
private boolean mIsHintHolder;
public RxSeekBar(Context context) {
this(context, null);
}
public RxSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context, attrs);
}
public RxSeekBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context, attrs);
}
@TargetApi(21)
public RxSeekBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initView(context, attrs);
}
private void initView(Context context, AttributeSet attrs) {
TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.RxSeekBar);
cellsCount = t.getInt(R.styleable.RxSeekBar_cells, 1);
reserveValue = t.getFloat(R.styleable.RxSeekBar_reserve, 0);
mMin = t.getFloat(R.styleable.RxSeekBar_minProgress, 0);
mMax = t.getFloat(R.styleable.RxSeekBar_maxProgress, 100);
mThumbResId = t.getResourceId(R.styleable.RxSeekBar_seekBarResId, R.drawable.seekbar_thumb);
mProgressHintBGId = t.getResourceId(R.styleable.RxSeekBar_progressHintResId, 0);
colorLineSelected = t.getColor(R.styleable.RxSeekBar_lineColorSelected, 0xFF4BD962);
colorLineEdge = t.getColor(R.styleable.RxSeekBar_lineColorEdge, 0xFFD7D7D7);
colorPrimary = t.getColor(R.styleable.RxSeekBar_thumbPrimaryColor, 0);
colorSecondary = t.getColor(R.styleable.RxSeekBar_thumbSecondaryColor, 0);
mTextArray = t.getTextArray(R.styleable.RxSeekBar_markTextArray);
mHideProgressHint = t.getBoolean(R.styleable.RxSeekBar_hideProgressHint, false);
mIsHintHolder = t.getBoolean(R.styleable.RxSeekBar_isHintHolder, false);
textPadding = (int) t.getDimension(R.styleable.RxSeekBar_textPadding, RxImageTool.dp2px(context, 7f));
mTextSize = (int) t.getDimension(R.styleable.RxSeekBar_textSize2, RxImageTool.dp2px(context, 12f));
mHintBGHeight = t.getDimension(R.styleable.RxSeekBar_hintBGHeight, 0);
mHintBGWith = t.getDimension(R.styleable.RxSeekBar_hintBGWith, 0);
mSeekBarHeight = (int) t.getDimension(R.styleable.RxSeekBar_seekBarHeight, RxImageTool.dp2px(context, 2f));
mHintBGPadding = (int) t.getDimension(R.styleable.RxSeekBar_hintBGPadding, 0);
mThumbSize = (int) t.getDimension(R.styleable.RxSeekBar_thumbSize, RxImageTool.dp2px(context, 26f));
mCellMode = t.getInt(R.styleable.RxSeekBar_cellMode, 0);
mSeekBarMode = t.getInt(R.styleable.RxSeekBar_seekBarMode, 2);
if (mSeekBarMode == 2) {
leftSB = new SeekBar(-1);
rightSB = new SeekBar(1);
} else {
leftSB = new SeekBar(-1);
}
// if you don't set the mHintBGWith or the mHintBGWith < default value, if will use default value
if (mHintBGWith == 0) {
defaultPaddingLeftAndRight = RxImageTool.dp2px(context, 25f);
} else {
defaultPaddingLeftAndRight = Math.max((int) (mHintBGWith / 2 + RxImageTool.dp2px(context, 5f)), RxImageTool.dp2px(context, 25f));
}
setRules(mMin, mMax, reserveValue, cellsCount);
initPaint();
initBitmap();
t.recycle();
defaultPaddingTop = mSeekBarHeight / 2;
mHintBGHeight = mHintBGHeight == 0 ? (mCursorPaint.measureText("国") * 3) : mHintBGHeight;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
heightNeeded = 2 * (lineTop) + mSeekBarHeight;
/**
* onMeasure传入的widthMeasureSpec和heightMeasureSpec不是一般的尺寸数值,而是将模式和尺寸组合在一起的数值
* MeasureSpec.EXACTLY 是精确尺寸
* MeasureSpec.AT_MOST 是最大尺寸
* MeasureSpec.UNSPECIFIED 是未指定尺寸
*/
if (heightMode == MeasureSpec.EXACTLY) {
heightSize = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
} else if (heightMode == MeasureSpec.AT_MOST) {
heightSize = MeasureSpec.makeMeasureSpec(
heightSize < heightNeeded ? heightSize : heightNeeded, MeasureSpec.EXACTLY);
} else {
heightSize = MeasureSpec.makeMeasureSpec(
heightNeeded, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightSize);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
//计算进度条的位置,并根据它初始化两个按钮的位置
// Calculates the position of the progress bar and initializes the positions of
// the two buttons based on it
lineLeft = defaultPaddingLeftAndRight + getPaddingLeft();
lineRight = w - lineLeft - getPaddingRight();
lineTop = (int) mHintBGHeight + mThumbSize / 2 - mSeekBarHeight / 2;
lineBottom = lineTop + mSeekBarHeight;
lineWidth = lineRight - lineLeft;
line.set(lineLeft, lineTop, lineRight, lineBottom);
lineCorners = (int) ((lineBottom - lineTop) * 0.45f);
leftSB.onSizeChanged(lineLeft, lineBottom, mThumbSize, lineWidth, cellsCount > 1, mThumbResId, getContext());
if (mSeekBarMode == 2) {
rightSB.onSizeChanged(lineLeft, lineBottom, mThumbSize, lineWidth, cellsCount > 1, mThumbResId, getContext());
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//绘制刻度,并且根据当前位置是否在刻度范围内设置不同的颜色显示
// Draw the scales, and according to the current position is set within
// the scale range of different color display
if (mTextArray != null) {
mPartLength = lineWidth / (mTextArray.length - 1);
for (int i = 0; i < mTextArray.length; i++) {
final String text2Draw = mTextArray[i].toString();
float x;
//平分显示
if (mCellMode == 1) {
mCursorPaint.setColor(colorLineEdge);
x = lineLeft + i * mPartLength - mCursorPaint.measureText(text2Draw) / 2;
} else {
float num = Float.parseFloat(text2Draw);
float[] result = getCurrentRange();
if (compareFloat(num, result[0]) != -1 && compareFloat(num, result[1]) != 1 && mSeekBarMode == 2) {
mCursorPaint.setColor(ContextCompat.getColor(getContext(), R.color.green));
} else {
mCursorPaint.setColor(colorLineEdge);
}
//按实际比例显示
x = lineLeft + lineWidth * (num - mMin) / (mMax - mMin)
- mCursorPaint.measureText(text2Draw) / 2;
}
float y = lineTop - textPadding;
canvas.drawText(text2Draw, x, y, mCursorPaint);
}
}
//绘制进度条
// draw the progress bar
mMainPaint.setColor(colorLineEdge);
canvas.drawRoundRect(line, lineCorners, lineCorners, mMainPaint);
mMainPaint.setColor(colorLineSelected);
if (mSeekBarMode == 2) {
canvas.drawRect(leftSB.left + leftSB.widthSize / 2 + leftSB.lineWidth * leftSB.currPercent, lineTop,
rightSB.left + rightSB.widthSize / 2 + rightSB.lineWidth * rightSB.currPercent, lineBottom, mMainPaint);
} else {
canvas.drawRect(leftSB.left + leftSB.widthSize / 2, lineTop,
leftSB.left + leftSB.widthSize / 2 + leftSB.lineWidth * leftSB.currPercent, lineBottom, mMainPaint);
}
leftSB.draw(canvas);
if (mSeekBarMode == 2) {
rightSB.draw(canvas);
}
}
/**
* 初始化画笔
* init the paints
*/
private void initPaint() {
mMainPaint.setStyle(Paint.Style.FILL);
mMainPaint.setColor(colorLineEdge);
mCursorPaint.setStyle(Paint.Style.FILL);
mCursorPaint.setColor(colorLineEdge);
mCursorPaint.setTextSize(mTextSize);
mProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mProgressPaint.setTypeface(Typeface.DEFAULT);
//计算文字的高度
//Calculate the height of the text
Paint.FontMetrics fm = mCursorPaint.getFontMetrics();
mCursorTextHeight = (int) (Math.ceil(fm.descent - fm.ascent) + 2);
}
/**
* 初始化进度提示的背景
*/
private void initBitmap() {
if (mProgressHintBGId != 0) {
mProgressHintBG = BitmapFactory.decodeResource(getResources(), mProgressHintBGId);
} else {
mProgressHintBG = BitmapFactory.decodeResource(getResources(), R.drawable.progress_hint_bg);
}
}
//*********************************** SeekBar ***********************************//
private class SeekBar {
private int lineWidth;
private int widthSize, heightSize;
private int left, right, top, bottom;
private float currPercent;
private float material = 0;
public boolean isShowingHint;
private boolean isLeft;
private Bitmap bmp;
private ValueAnimator anim;
private RadialGradient shadowGradient;
private Paint defaultPaint;
private String mHintText2Draw;
private Boolean isPrimary = true;
public SeekBar(int position) {
isLeft = position < 0;
}
/**
* 计算每个按钮的位置和尺寸
* Calculates the position and size of each button
*
* @param x 在屏幕上的X的位置
* @param y 在屏幕上的Y的位置
* @param hSize 高度大小
* @param parentLineWidth 父类线宽度
* @param cellsMode
* @param bmpResId
* @param context
*/
protected void onSizeChanged(int x, int y, int hSize, int parentLineWidth, boolean cellsMode, int bmpResId, Context context) {
heightSize = hSize;
widthSize = heightSize;
left = x - widthSize / 2;
right = x + widthSize / 2;
top = y - heightSize / 2;
bottom = y + heightSize / 2;
if (cellsMode) {
lineWidth = parentLineWidth;
} else {
lineWidth = parentLineWidth;
}
if (bmpResId > 0) {
Bitmap original = BitmapFactory.decodeResource(context.getResources(), bmpResId);
if (original != null) {
Matrix matrix = new Matrix();
float scaleHeight = mThumbSize * 1.0f / original.getHeight();
float scaleWidth = scaleHeight;
matrix.postScale(scaleWidth, scaleHeight);
if (!isInEditMode()) {
bmp = Bitmap.createBitmap(original, 0, 0, original.getWidth(), original.getHeight(), matrix, true);
}
}
} else {
defaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
int radius = (int) (widthSize * DEFAULT_RADIUS);
int barShadowRadius = (int) (radius * 0.95f);
int mShadowCenterX = widthSize / 2;
int mShadowCenterY = heightSize / 2;
shadowGradient = new RadialGradient(mShadowCenterX, mShadowCenterY, barShadowRadius, Color.BLACK, Color.TRANSPARENT, Shader.TileMode.CLAMP);
}
}
/**
* 绘制按钮和提示背景和文字
* Draw buttons and tips for background and text
*
* @param canvas
*/
protected void draw(Canvas canvas) {
int offset = (int) (lineWidth * currPercent);
canvas.save();
canvas.translate(offset, 0);
String text2Draw = "";
int hintW = 0, hintH = 0;
float[] result = getCurrentRange();
if (mHideProgressHint) {
isShowingHint = false;
} else {
if (isLeft) {
if (mHintText2Draw == null) {
text2Draw = (int) result[0] + "";
} else {
text2Draw = mHintText2Draw;
}
// if is the start,change the thumb color
isPrimary = (compareFloat(result[0], mMin) == 0);
} else {
if (mHintText2Draw == null) {
text2Draw = (int) result[1] + "";
} else {
text2Draw = mHintText2Draw;
}
isPrimary = (compareFloat(result[1], mMax) == 0);
}
hintH = (int) mHintBGHeight;
hintW = (int) (mHintBGWith == 0 ? (mCursorPaint.measureText(text2Draw) + defaultPaddingLeftAndRight)
: mHintBGWith);
if (hintW < 1.5f * hintH) {
hintW = (int) (1.5f * hintH);
}
}
if (bmp != null) {
canvas.drawBitmap(bmp, left, lineTop - bmp.getHeight() / 2, null);
if (isShowingHint) {
Rect rect = new Rect();
rect.left = left - (hintW / 2 - bmp.getWidth() / 2);
rect.top = bottom - hintH - bmp.getHeight();
rect.right = rect.left + hintW;
rect.bottom = rect.top + hintH;
RxImageTool.drawNinePath(canvas, mProgressHintBG, rect);
mCursorPaint.setColor(Color.WHITE);
int x = (int) (left + (bmp.getWidth() / 2) - mCursorPaint.measureText(text2Draw) / 2);
int y = bottom - hintH - bmp.getHeight() + hintH / 2;
canvas.drawText(text2Draw, x, y, mCursorPaint);
}
} else {
canvas.translate(left, 0);
if (isShowingHint) {
Rect rect = new Rect();
rect.left = widthSize / 2 - hintW / 2;
rect.top = defaultPaddingTop;
rect.right = rect.left + hintW;
rect.bottom = rect.top + hintH;
RxImageTool.drawNinePath(canvas, mProgressHintBG, rect);
mCursorPaint.setColor(Color.WHITE);
int x = (int) (widthSize / 2 - mCursorPaint.measureText(text2Draw) / 2);
// TODO: 2017/2/6
//这里和背景形状有关,暂时根据本图形状比例计算
//Here and the background shape, temporarily based on the shape of this figure ratio calculation
int y = hintH / 3 + defaultPaddingTop + mCursorTextHeight / 2;
canvas.drawText(text2Draw, x, y, mCursorPaint);
}
drawDefault(canvas);
}
canvas.restore();
}
/**
* 如果没有图片资源,则绘制默认按钮
* <p>
* If there is no image resource, draw the default button
*
* @param canvas
*/
private void drawDefault(Canvas canvas) {
int centerX = widthSize / 2;
int centerY = lineBottom - mSeekBarHeight / 2;
int radius = (int) (widthSize * DEFAULT_RADIUS);
// draw shadow
if (defaultPaint == null) {
defaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
defaultPaint.setStyle(Paint.Style.FILL);
canvas.save();
canvas.translate(0, radius * 0.25f);
canvas.scale(1 + (0.1f * material), 1 + (0.1f * material), centerX, centerY);
defaultPaint.setShader(shadowGradient);
canvas.drawCircle(centerX, centerY, radius, defaultPaint);
defaultPaint.setShader(null);
canvas.restore();
// draw body
defaultPaint.setStyle(Paint.Style.FILL);
if (isPrimary) {
//if not set the color,it will use default color
if (colorPrimary == 0) {
defaultPaint.setColor(te.evaluate(material, 0xFFFFFFFF, 0xFFE7E7E7));
} else {
defaultPaint.setColor(colorPrimary);
}
} else {
if (colorSecondary == 0) {
defaultPaint.setColor(te.evaluate(material, 0xFFFFFFFF, 0xFFE7E7E7));
} else {
defaultPaint.setColor(colorSecondary);
}
}
canvas.drawCircle(centerX, centerY, radius, defaultPaint);
// draw border
defaultPaint.setStyle(Paint.Style.STROKE);
defaultPaint.setColor(0xFFD7D7D7);
canvas.drawCircle(centerX, centerY, radius, defaultPaint);
}
final TypeEvaluator<Integer> te = new TypeEvaluator<Integer>() {
@Override
public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
int alpha = (int) (Color.alpha(startValue) + fraction * (Color.alpha(endValue) - Color.alpha(startValue)));
int red = (int) (Color.red(startValue) + fraction * (Color.red(endValue) - Color.red(startValue)));
int green = (int) (Color.green(startValue) + fraction * (Color.green(endValue) - Color.green(startValue)));
int blue = (int) (Color.blue(startValue) + fraction * (Color.blue(endValue) - Color.blue(startValue)));
return Color.argb(alpha, red, green, blue);
}
};
/**
* 拖动检测
*
* @param event 拖动事件
* @return
*/
protected boolean collide(MotionEvent event) {
float x = event.getX();
float y = event.getY();
int offset = (int) (lineWidth * currPercent);
return x > left + offset && x < right + offset && y > top && y < bottom;
}
private void slide(float percent) {
if (percent < 0) {
percent = 0;
} else if (percent > 1) {
percent = 1;
}
currPercent = percent;
}
private void materialRestore() {
if (anim != null) {
anim.cancel();
}
anim = ValueAnimator.ofFloat(material, 0);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
material = (float) animation.getAnimatedValue();
invalidate();
}
});
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
material = 0;
invalidate();
}
});
anim.start();
}
public void setProgressHint(String hint) {
mHintText2Draw = hint;
}
}
//*********************************** SeekBar ***********************************//
public interface OnRangeChangedListener {
void onRangeChanged(RxSeekBar view, float min, float max, boolean isFromUser);
}
public void setOnRangeChangedListener(OnRangeChangedListener listener) {
callback = listener;
}
public void setValue(float min, float max) {
min = min + offsetValue;
max = max + offsetValue;
if (min < minValue) {
throw new IllegalArgumentException("setValue() min < (preset min - offsetValue) . #min:" + min + " #preset min:" + minValue + " #offsetValue:" + offsetValue);
}
if (max > maxValue) {
throw new IllegalArgumentException("setValue() max > (preset max - offsetValue) . #max:" + max + " #preset max:" + maxValue + " #offsetValue:" + offsetValue);
}
if (reserveCount > 1) {
if ((min - minValue) % reserveCount != 0) {
throw new IllegalArgumentException("setValue() (min - preset min) % reserveCount != 0 . #min:" + min + " #preset min:" + minValue + "#reserveCount:" + reserveCount + "#reserve:" + reserveValue);
}
if ((max - minValue) % reserveCount != 0) {
throw new IllegalArgumentException("setValue() (max - preset min) % reserveCount != 0 . #max:" + max + " #preset min:" + minValue + "#reserveCount:" + reserveCount + "#reserve:" + reserveValue);
}
leftSB.currPercent = (min - minValue) / reserveCount * cellsPercent;
if (mSeekBarMode == 2) {
rightSB.currPercent = (max - minValue) / reserveCount * cellsPercent;
}
} else {
leftSB.currPercent = (min - minValue) / (maxValue - minValue);
if (mSeekBarMode == 2) {
rightSB.currPercent = (max - minValue) / (maxValue - minValue);
}
}
if (callback != null) {
if (mSeekBarMode == 2) {
callback.onRangeChanged(this, leftSB.currPercent, rightSB.currPercent, false);
} else {
callback.onRangeChanged(this, leftSB.currPercent, leftSB.currPercent, false);
}
}
invalidate();
}
public void setValue(float value) {
setValue(value, mMax);
}
public void setRange(float min, float max) {
setRules(min, max, reserveCount, cellsCount);
}
public void setRules(float min, float max, float reserve, int cells) {
if (max <= min) {
throw new IllegalArgumentException("setRules() max must be greater than min ! #max:" + max + " #min:" + min);
}
mMax = max;
mMin = min;
if (min < 0) {
offsetValue = 0 - min;
min = min + offsetValue;
max = max + offsetValue;
}
minValue = min;
maxValue = max;
if (reserve < 0) {
throw new IllegalArgumentException("setRules() reserve must be greater than zero ! #reserve:" + reserve);
}
if (reserve >= max - min) {
throw new IllegalArgumentException("setRules() reserve must be less than (max - min) ! #reserve:" + reserve + " #max - min:" + (max - min));
}
if (cells < 1) {
throw new IllegalArgumentException("setRules() cells must be greater than 1 ! #cells:" + cells);
}
cellsCount = cells;
cellsPercent = 1f / cellsCount;
reserveValue = reserve;
reservePercent = reserve / (max - min);
reserveCount = (int) (reservePercent / cellsPercent + (reservePercent % cellsPercent != 0 ? 1 : 0));
if (cellsCount > 1) {
if (mSeekBarMode == 2) {
if (leftSB.currPercent + cellsPercent * reserveCount <= 1 && leftSB.currPercent + cellsPercent * reserveCount > rightSB.currPercent) {
rightSB.currPercent = leftSB.currPercent + cellsPercent * reserveCount;
} else if (rightSB.currPercent - cellsPercent * reserveCount >= 0 && rightSB.currPercent - cellsPercent * reserveCount < leftSB.currPercent) {
leftSB.currPercent = rightSB.currPercent - cellsPercent * reserveCount;
}
} else {
if (1 - cellsPercent * reserveCount >= 0 && 1 - cellsPercent * reserveCount < leftSB.currPercent) {
leftSB.currPercent = 1 - cellsPercent * reserveCount;
}
}
} else {
if (mSeekBarMode == 2) {
if (leftSB.currPercent + reservePercent <= 1 && leftSB.currPercent + reservePercent > rightSB.currPercent) {
rightSB.currPercent = leftSB.currPercent + reservePercent;
} else if (rightSB.currPercent - reservePercent >= 0 && rightSB.currPercent - reservePercent < leftSB.currPercent) {
leftSB.currPercent = rightSB.currPercent - reservePercent;
}
} else {
if (1 - reservePercent >= 0 && 1 - reservePercent < leftSB.currPercent) {
leftSB.currPercent = 1 - reservePercent;
}
}
}
invalidate();
}
public float getMax() {
return mMax;
}
public float getMin() {
return mMin;
}
public float[] getCurrentRange() {
float range = maxValue - minValue;
if (mSeekBarMode == 2) {
return new float[]{-offsetValue + minValue + range * leftSB.currPercent,
-offsetValue + minValue + range * rightSB.currPercent};
} else {
return new float[]{-offsetValue + minValue + range * leftSB.currPercent,
-offsetValue + minValue + range * 1.0f};
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
this.isEnable = enabled;
}
public void setProgressDescription(String progress) {
if (leftSB != null) {
leftSB.setProgressHint(progress);
}
if (rightSB != null) {
rightSB.setProgressHint(progress);
}
}
public void setLeftProgressDescription(String progress) {
if (leftSB != null) {
leftSB.setProgressHint(progress);
}
}
public void setRightProgressDescription(String progress) {
if (rightSB != null) {
rightSB.setProgressHint(progress);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnable) return true;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
boolean touchResult = false;
if (rightSB != null && rightSB.currPercent >= 1 && leftSB.collide(event)) {
currTouch = leftSB;
touchResult = true;
} else if (rightSB != null && rightSB.collide(event)) {
currTouch = rightSB;
touchResult = true;
} else if (leftSB.collide(event)) {
currTouch = leftSB;
touchResult = true;
}
//Intercept parent TouchEvent
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
return touchResult;
case MotionEvent.ACTION_MOVE:
float percent;
float x = event.getX();
currTouch.material = currTouch.material >= 1 ? 1 : currTouch.material + 0.1f;
if (currTouch == leftSB) {
if (cellsCount > 1) {
if (x < lineLeft) {
percent = 0;
} else {
percent = (x - lineLeft) * 1f / (lineWidth);
}
int touchLeftCellsValue = Math.round(percent / cellsPercent);
int currRightCellsValue;
if (mSeekBarMode == 2) {
currRightCellsValue = Math.round(rightSB.currPercent / cellsPercent);
} else {
currRightCellsValue = Math.round(1.0f / cellsPercent);
}
percent = touchLeftCellsValue * cellsPercent;
while (touchLeftCellsValue > currRightCellsValue - reserveCount) {
touchLeftCellsValue--;
if (touchLeftCellsValue < 0) {
break;
}
percent = touchLeftCellsValue * cellsPercent;
}
} else {
if (x < lineLeft) {
percent = 0;
} else {
percent = (x - lineLeft) * 1f / (lineWidth);
}
if (mSeekBarMode == 2) {
if (percent > rightSB.currPercent - reservePercent) {
percent = rightSB.currPercent - reservePercent;
}
} else {
if (percent > 1.0f - reservePercent) {
percent = 1.0f - reservePercent;
}
}
}
leftSB.slide(percent);
leftSB.isShowingHint = true;
//Intercept parent TouchEvent
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
} else if (currTouch == rightSB) {
if (cellsCount > 1) {
if (x > lineRight) {
percent = 1;
} else {
percent = (x - lineLeft) * 1f / (lineWidth);
}
int touchRightCellsValue = Math.round(percent / cellsPercent);
int currLeftCellsValue = Math.round(leftSB.currPercent / cellsPercent);
percent = touchRightCellsValue * cellsPercent;
while (touchRightCellsValue < currLeftCellsValue + reserveCount) {
touchRightCellsValue++;
if (touchRightCellsValue > maxValue - minValue) {
break;
}
percent = touchRightCellsValue * cellsPercent;
}
} else {
if (x > lineRight) {
percent = 1;
} else {
percent = (x - lineLeft) * 1f / (lineWidth);
}
if (percent < leftSB.currPercent + reservePercent) {
percent = leftSB.currPercent + reservePercent;
}
}
rightSB.slide(percent);
rightSB.isShowingHint = true;
}
if (callback != null) {
float[] result = getCurrentRange();
callback.onRangeChanged(this, result[0], result[1], true);
}
invalidate();
//Intercept parent TouchEvent
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsHintHolder) {
if (mSeekBarMode == 2) {
rightSB.isShowingHint = false;
}
leftSB.isShowingHint = false;
}
if (callback != null) {
float[] result = getCurrentRange();
callback.onRangeChanged(this, result[0], result[1], false);
}
//Intercept parent TouchEvent
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
break;
case MotionEvent.ACTION_UP:
if (mIsHintHolder) {
if (mSeekBarMode == 2) {
rightSB.isShowingHint = false;
}
leftSB.isShowingHint = false;
}
currTouch.materialRestore();
if (callback != null) {
float[] result = getCurrentRange();
callback.onRangeChanged(this, result[0], result[1], false);
}
//Intercept parent TouchEvent
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(true);
}
break;
default:
break;
}
return super.onTouchEvent(event);
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.minValue = minValue - offsetValue;
ss.maxValue = maxValue - offsetValue;
ss.reserveValue = reserveValue;
ss.cellsCount = cellsCount;
float[] results = getCurrentRange();
ss.currSelectedMin = results[0];
ss.currSelectedMax = results[1];
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
float min = ss.minValue;
float max = ss.maxValue;
float reserve = ss.reserveValue;
int cells = ss.cellsCount;
setRules(min, max, reserve, cells);
float currSelectedMin = ss.currSelectedMin;
float currSelectedMax = ss.currSelectedMax;
setValue(currSelectedMin, currSelectedMax);
}
private class SavedState extends BaseSavedState {
private float minValue;
private float maxValue;
private float reserveValue;
private int cellsCount;
private float currSelectedMin;
private float currSelectedMax;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
minValue = in.readFloat();
maxValue = in.readFloat();
reserveValue = in.readFloat();
cellsCount = in.readInt();
currSelectedMin = in.readFloat();
currSelectedMax = in.readFloat();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeFloat(minValue);
out.writeFloat(maxValue);
out.writeFloat(reserveValue);
out.writeInt(cellsCount);
out.writeFloat(currSelectedMin);
out.writeFloat(currSelectedMax);
}
}
/**
* Compare the size of two floating point numbers
*
* @param a
* @param b
* @return 1 is a > b
* -1 is a < b
* 0 is a == b
*/
private int compareFloat(float a, float b) {
int ta = Math.round(a * 1000);
int tb = Math.round(b * 1000);
if (ta > tb) {
return 1;
} else if (ta < tb) {
return -1;
} else {
return 0;
}
}
}
| Tamsiree/RxTool | RxUI/src/main/java/com/tamsiree/rxui/view/RxSeekBar.java |
1,554 | package com.alibaba.otter.canal.example;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import com.alibaba.otter.canal.protocol.CanalEntry.*;
import com.google.protobuf.InvalidProtocolBufferException;
public class BaseCanalClientTest {
protected final static Logger logger = LoggerFactory
.getLogger(AbstractCanalClientTest.class);
protected static final String SEP = SystemUtils.LINE_SEPARATOR;
protected static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
protected volatile boolean running = false;
protected Thread.UncaughtExceptionHandler handler = (t, e) -> logger.error("parse events has an error",
e);
protected Thread thread = null;
protected CanalConnector connector;
protected static String context_format = null;
protected static String row_format = null;
protected static String transaction_format = null;
protected String destination;
static {
context_format = SEP + "****************************************************" + SEP;
context_format += "* Batch Id: [{}] ,count : [{}] , memsize : [{}] , Time : {}" + SEP;
context_format += "* Start : [{}] " + SEP;
context_format += "* End : [{}] " + SEP;
context_format += "****************************************************" + SEP;
row_format = SEP
+ "----------------> binlog[{}:{}] , name[{},{}] , eventType : {} , executeTime : {}({}) , gtid : ({}) , delay : {} ms"
+ SEP;
transaction_format = SEP + "================> binlog[{}:{}] , executeTime : {}({}) , gtid : ({}) , delay : {}ms"
+ SEP;
}
protected void printSummary(Message message, long batchId, int size) {
long memsize = 0;
for (Entry entry : message.getEntries()) {
memsize += entry.getHeader().getEventLength();
}
String startPosition = null;
String endPosition = null;
if (!CollectionUtils.isEmpty(message.getEntries())) {
startPosition = buildPositionForDump(message.getEntries().get(0));
endPosition = buildPositionForDump(message.getEntries().get(message.getEntries().size() - 1));
}
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
logger.info(context_format,
new Object[] { batchId, size, memsize, format.format(new Date()), startPosition, endPosition });
}
protected String buildPositionForDump(Entry entry) {
long time = entry.getHeader().getExecuteTime();
Date date = new Date(time);
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
String position = entry.getHeader().getLogfileName() + ":" + entry.getHeader().getLogfileOffset() + ":"
+ entry.getHeader().getExecuteTime() + "(" + format.format(date) + ")";
if (StringUtils.isNotEmpty(entry.getHeader().getGtid())) {
position += " gtid(" + entry.getHeader().getGtid() + ")";
}
return position;
}
protected void printEntry(List<Entry> entrys) {
for (Entry entry : entrys) {
long executeTime = entry.getHeader().getExecuteTime();
long delayTime = new Date().getTime() - executeTime;
Date date = new Date(entry.getHeader().getExecuteTime());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN
|| entry.getEntryType() == EntryType.TRANSACTIONEND) {
if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN) {
TransactionBegin begin = null;
try {
begin = TransactionBegin.parseFrom(entry.getStoreValue());
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException("parse event has an error , data:" + entry.toString(), e);
}
// 打印事务头信息,执行的线程id,事务耗时
logger.info(transaction_format,
new Object[] { entry.getHeader().getLogfileName(),
String.valueOf(entry.getHeader().getLogfileOffset()),
String.valueOf(entry.getHeader().getExecuteTime()),
simpleDateFormat.format(date), entry.getHeader().getGtid(),
String.valueOf(delayTime) });
logger.info(" BEGIN ----> Thread id: {}", begin.getThreadId());
printXAInfo(begin.getPropsList());
} else if (entry.getEntryType() == EntryType.TRANSACTIONEND) {
TransactionEnd end = null;
try {
end = TransactionEnd.parseFrom(entry.getStoreValue());
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException("parse event has an error , data:" + entry.toString(), e);
}
// 打印事务提交信息,事务id
logger.info("----------------\n");
logger.info(" END ----> transaction id: {}", end.getTransactionId());
printXAInfo(end.getPropsList());
logger.info(transaction_format,
new Object[] { entry.getHeader().getLogfileName(),
String.valueOf(entry.getHeader().getLogfileOffset()),
String.valueOf(entry.getHeader().getExecuteTime()),
simpleDateFormat.format(date), entry.getHeader().getGtid(),
String.valueOf(delayTime) });
}
continue;
}
if (entry.getEntryType() == EntryType.ROWDATA) {
RowChange rowChange = null;
try {
rowChange = RowChange.parseFrom(entry.getStoreValue());
} catch (Exception e) {
throw new RuntimeException("parse event has an error , data:" + entry.toString(), e);
}
EventType eventType = rowChange.getEventType();
logger.info(row_format,
new Object[] { entry.getHeader().getLogfileName(),
String.valueOf(entry.getHeader().getLogfileOffset()),
entry.getHeader().getSchemaName(), entry.getHeader().getTableName(), eventType,
String.valueOf(entry.getHeader().getExecuteTime()), simpleDateFormat.format(date),
entry.getHeader().getGtid(), String.valueOf(delayTime) });
if (eventType == EventType.QUERY || rowChange.getIsDdl()) {
logger.info("ddl : " + rowChange.getIsDdl() + " , sql ----> " + rowChange.getSql() + SEP);
continue;
}
printXAInfo(rowChange.getPropsList());
for (RowData rowData : rowChange.getRowDatasList()) {
if (eventType == EventType.DELETE) {
printColumn(rowData.getBeforeColumnsList());
} else if (eventType == EventType.INSERT) {
printColumn(rowData.getAfterColumnsList());
} else {
printColumn(rowData.getAfterColumnsList());
}
}
}
}
}
protected void printColumn(List<Column> columns) {
for (Column column : columns) {
StringBuilder builder = new StringBuilder();
try {
if (StringUtils.containsIgnoreCase(column.getMysqlType(), "BLOB")
|| StringUtils.containsIgnoreCase(column.getMysqlType(), "BINARY")) {
// get value bytes
builder.append(
column.getName() + " : " + new String(column.getValue().getBytes("ISO-8859-1"), "UTF-8"));
} else {
builder.append(column.getName() + " : " + column.getValue());
}
} catch (UnsupportedEncodingException e) {
}
builder.append(" type=" + column.getMysqlType());
if (column.getUpdated()) {
builder.append(" update=" + column.getUpdated());
}
builder.append(SEP);
logger.info(builder.toString());
}
}
protected void printXAInfo(List<Pair> pairs) {
if (pairs == null) {
return;
}
String xaType = null;
String xaXid = null;
for (Pair pair : pairs) {
String key = pair.getKey();
if (StringUtils.endsWithIgnoreCase(key, "XA_TYPE")) {
xaType = pair.getValue();
} else if (StringUtils.endsWithIgnoreCase(key, "XA_XID")) {
xaXid = pair.getValue();
}
}
if (xaType != null && xaXid != null) {
logger.info(" ------> " + xaType + " " + xaXid);
}
}
public void setConnector(CanalConnector connector) {
this.connector = connector;
}
/**
* 获取当前Entry的 GTID信息示例
*
* @param header
* @return
*/
public static String getCurrentGtid(CanalEntry.Header header) {
List<CanalEntry.Pair> props = header.getPropsList();
if (props != null && props.size() > 0) {
for (CanalEntry.Pair pair : props) {
if ("curtGtid".equals(pair.getKey())) {
return pair.getValue();
}
}
}
return "";
}
/**
* 获取当前Entry的 GTID Sequence No信息示例
*
* @param header
* @return
*/
public static String getCurrentGtidSn(CanalEntry.Header header) {
List<CanalEntry.Pair> props = header.getPropsList();
if (props != null && props.size() > 0) {
for (CanalEntry.Pair pair : props) {
if ("curtGtidSn".equals(pair.getKey())) {
return pair.getValue();
}
}
}
return "";
}
/**
* 获取当前Entry的 GTID Last Committed信息示例
*
* @param header
* @return
*/
public static String getCurrentGtidLct(CanalEntry.Header header) {
List<CanalEntry.Pair> props = header.getPropsList();
if (props != null && props.size() > 0) {
for (CanalEntry.Pair pair : props) {
if ("curtGtidLct".equals(pair.getKey())) {
return pair.getValue();
}
}
}
return "";
}
}
| alibaba/canal | example/src/main/java/com/alibaba/otter/canal/example/BaseCanalClientTest.java |
1,555 | /*
* Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat.server;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.mycat.MycatServer;
import io.mycat.backend.BackendConnection;
import io.mycat.backend.datasource.PhysicalDBNode;
import io.mycat.backend.mysql.listener.SqlExecuteStage;
import io.mycat.backend.mysql.nio.handler.CommitNodeHandler;
import io.mycat.backend.mysql.nio.handler.KillConnectionHandler;
import io.mycat.backend.mysql.nio.handler.LockTablesHandler;
import io.mycat.backend.mysql.nio.handler.MiddlerResultHandler;
import io.mycat.backend.mysql.nio.handler.MultiNodeCoordinator;
import io.mycat.backend.mysql.nio.handler.MultiNodeQueryHandler;
import io.mycat.backend.mysql.nio.handler.RollbackNodeHandler;
import io.mycat.backend.mysql.nio.handler.RollbackReleaseHandler;
import io.mycat.backend.mysql.nio.handler.SingleNodeHandler;
import io.mycat.backend.mysql.nio.handler.UnLockTablesHandler;
import io.mycat.config.ErrorCode;
import io.mycat.config.MycatConfig;
import io.mycat.net.FrontendConnection;
import io.mycat.net.mysql.OkPacket;
import io.mycat.route.RouteResultset;
import io.mycat.route.RouteResultsetNode;
import io.mycat.server.parser.ServerParse;
import io.mycat.server.sqlcmd.SQLCmdConstant;
/**
* @author mycat
* @author mycat
*/
public class NonBlockingSession implements Session {
public static final Logger LOGGER = LoggerFactory.getLogger(NonBlockingSession.class);
private final ServerConnection source;
//huangyiming add 避免出现jdk版本冲突
private final ConcurrentMap<RouteResultsetNode, BackendConnection> target;
// life-cycle: each sql execution
private volatile SingleNodeHandler singleNodeHandler;
private volatile MultiNodeQueryHandler multiNodeHandler;
private volatile RollbackNodeHandler rollbackHandler;
private final MultiNodeCoordinator multiNodeCoordinator;
private final CommitNodeHandler commitHandler;
private volatile String xaTXID;
//huangyiming
private volatile boolean canClose = true;
private volatile MiddlerResultHandler middlerResultHandler;
private boolean prepared;
private RouteResultset rrs;
public NonBlockingSession(ServerConnection source) {
this.source = source;
this.target = new ConcurrentHashMap<RouteResultsetNode, BackendConnection>(2, 0.75f);
multiNodeCoordinator = new MultiNodeCoordinator(this);
commitHandler = new CommitNodeHandler(this);
}
@Override
public ServerConnection getSource() {
return source;
}
@Override
public int getTargetCount() {
return target.size();
}
public Set<RouteResultsetNode> getTargetKeys() {
return target.keySet();
}
public BackendConnection getTarget(RouteResultsetNode key) {
return target.get(key);
}
public Map<RouteResultsetNode, BackendConnection> getTargetMap() {
return this.target;
}
public BackendConnection removeTarget(RouteResultsetNode key) {
return target.remove(key);
}
@Override
public void execute(RouteResultset rrs, int type) {
this.rrs = rrs;
// clear prev execute resources
clearHandlesResources();
if (LOGGER.isDebugEnabled()) {
StringBuilder s = new StringBuilder();
LOGGER.debug(s.append(source).append(rrs).toString() + " rrs ");
}
// 检查路由结果是否为空
RouteResultsetNode[] nodes = rrs.getNodes();
if (nodes == null || nodes.length == 0 || nodes[0].getName() == null || nodes[0].getName().equals("")) {
source.writeErrMessage(ErrorCode.ER_NO_DB_ERROR,
"No dataNode found ,please check tables defined in schema:" + source.getSchema());
source.getListener().fireEvent(SqlExecuteStage.END);
return;
}
boolean autocommit = source.isAutocommit();
final int initCount = target.size();
if (nodes.length == 1) {
singleNodeHandler = new SingleNodeHandler(rrs, this);
if (this.isPrepared()) {
singleNodeHandler.setPrepared(true);
}
try {
if(initCount > 1){
checkDistriTransaxAndExecute(rrs,1,autocommit);
}else{
singleNodeHandler.execute();
}
} catch (Exception e) {
LOGGER.warn(new StringBuilder().append(source).append(rrs).toString(), e);
source.writeErrMessage(ErrorCode.ERR_HANDLE_DATA, e.toString());
source.getListener().fireEvent(SqlExecuteStage.END);
}
} else {
multiNodeHandler = new MultiNodeQueryHandler(type, rrs, autocommit, this);
if (this.isPrepared()) {
multiNodeHandler.setPrepared(true);
}
try {
if(((type == ServerParse.DELETE || type == ServerParse.INSERT || type == ServerParse.UPDATE) && !rrs.isGlobalTable() && nodes.length > 1)||initCount > 1) {
checkDistriTransaxAndExecute(rrs,2,autocommit);
} else {
multiNodeHandler.execute();
}
} catch (Exception e) {
LOGGER.warn(new StringBuilder().append(source).append(rrs).toString(), e);
source.writeErrMessage(ErrorCode.ERR_HANDLE_DATA, e.toString());
source.getListener().fireEvent(SqlExecuteStage.END);
}
}
if (this.isPrepared()) {
this.setPrepared(false);
}
}
private void checkDistriTransaxAndExecute(RouteResultset rrs, int type,boolean autocommit) throws Exception {
switch(MycatServer.getInstance().getConfig().getSystem().getHandleDistributedTransactions()) {
case 1:
source.writeErrMessage(ErrorCode.ER_NOT_ALLOWED_COMMAND, "Distributed transaction is disabled!");
if(!autocommit){
source.setTxInterrupt("Distributed transaction is disabled!");
}
break;
case 2:
LOGGER.warn("Distributed transaction detected! RRS:" + rrs);
if(type == 1){
singleNodeHandler.execute();
}
else{
multiNodeHandler.execute();
}
break;
default:
if(type == 1){
singleNodeHandler.execute();
}
else{
multiNodeHandler.execute();
}
}
}
private void checkDistriTransaxAndExecute() {
if(!isALLGlobal()){
switch(MycatServer.getInstance().getConfig().getSystem().getHandleDistributedTransactions()) {
case 1:
source.writeErrMessage(ErrorCode.ER_NOT_ALLOWED_COMMAND, "Distributed transaction is disabled!Please rollback!");
source.setTxInterrupt("Distributed transaction is disabled!");
break;
case 2:
multiNodeCoordinator.executeBatchNodeCmd(SQLCmdConstant.COMMIT_CMD);
LOGGER.warn("Distributed transaction detected! Targets:" + target);
break;
default:
multiNodeCoordinator.executeBatchNodeCmd(SQLCmdConstant.COMMIT_CMD);
}
} else {
multiNodeCoordinator.executeBatchNodeCmd(SQLCmdConstant.COMMIT_CMD);
}
}
public void commit() {
final int initCount = target.size();
if (initCount <= 0) {
ByteBuffer buffer = source.allocate();
buffer = source.writeToBuffer(OkPacket.OK, buffer);
source.write(buffer);
/* 1. 如果开启了 xa 事务 */
if(getXaTXID()!=null){
setXATXEnabled(false);
}
/* 2. preAcStates 为true,事务结束后,需要设置为true。preAcStates 为ac上一个状态 */
if(source.isPreAcStates()&&!source.isAutocommit()){
source.setAutocommit(true);
}
return;
} else if (initCount == 1) {
//huangyiming add 避免出现jdk版本冲突
// BackendConnection con = target.values().iterator().next();
commitHandler.commit();
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("multi node commit to send ,total " + initCount);
}
checkDistriTransaxAndExecute();
}
}
private boolean isALLGlobal(){
for(RouteResultsetNode routeResultsetNode:target.keySet()){
if(routeResultsetNode.getSource()==null){
return false;
}
else if(!routeResultsetNode.getSource().isGlobalTable()){
return false;
}
}
return true;
}
public void rollback() {
final int initCount = target.size();
if (initCount <= 0) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("no session bound connections found ,no need send rollback cmd ");
}
ByteBuffer buffer = source.allocate();
buffer = source.writeToBuffer(OkPacket.OK, buffer);
source.write(buffer);
/* 1. 如果开启了 xa 事务 */
if(getXaTXID()!=null){
setXATXEnabled(false);
}
/* 2. preAcStates 为true,事务结束后,需要设置为true。preAcStates 为ac上一个状态 */
if(source.isPreAcStates()&&!source.isAutocommit()){
source.setAutocommit(true);
}
return;
}
rollbackHandler = new RollbackNodeHandler(this);
rollbackHandler.rollback();
}
/**
* 执行lock tables语句方法
* @author songdabin
* @date 2016-7-9
* @param rrs
*/
public void lockTable(RouteResultset rrs) {
// 检查路由结果是否为空
RouteResultsetNode[] nodes = rrs.getNodes();
if (nodes == null || nodes.length == 0 || nodes[0].getName() == null
|| nodes[0].getName().equals("")) {
source.writeErrMessage(ErrorCode.ER_NO_DB_ERROR,
"No dataNode found ,please check tables defined in schema:"
+ source.getSchema());
return;
}
LockTablesHandler handler = new LockTablesHandler(this, rrs);
source.setLocked(true);
try {
handler.execute();
} catch (Exception e) {
LOGGER.warn(new StringBuilder().append(source).append(rrs).toString(), e);
source.writeErrMessage(ErrorCode.ERR_HANDLE_DATA, e.toString());
}
}
/**
* 执行unlock tables语句方法
* @author songdabin
* @date 2016-7-9
* @param sql
*/
public void unLockTable(String sql) {
UnLockTablesHandler handler = new UnLockTablesHandler(this, this.source.isAutocommit(), sql);
handler.execute();
}
@Override
public void cancel(FrontendConnection sponsor) {
}
/**
* {@link ServerConnection#isClosed()} must be true before invoking this
*/
public void terminate() {
for (BackendConnection node : target.values()) {
node.close("client closed ");
}
target.clear();
clearHandlesResources();
}
public void closeAndClearResources(String reason) {
for (BackendConnection node : target.values()) {
node.closeWithoutRsp(reason);
}
target.clear();
clearHandlesResources();
}
public void closeConnection(BackendConnection con, String reason) {
Iterator<Entry<RouteResultsetNode, BackendConnection>> itor = target.entrySet().iterator();
while (itor.hasNext()) {
BackendConnection theCon = itor.next().getValue();
if (theCon == con) {
itor.remove();
con.close(reason);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("realse connection " + con);
}
break;
}
}
}
public void releaseConnectionIfSafe(BackendConnection conn, boolean debug,
boolean needRollback) {
RouteResultsetNode node = (RouteResultsetNode) conn.getAttachment();
if (node != null) {
/* 分表 在
* 1. 没有开启事务
* 2. 读取走的从节点
* 3. 没有执行过更新sql
* 也需要释放连接
*/
// if (node.isDisctTable()) {
// return;
// }
if (MycatServer.getInstance().getConfig().getSystem().isStrictTxIsolation()) {
// 如果是严格隔离级别模式的话,不考虑是否已经执行了modifiedSql,直接不释放连接
if ((!this.source.isAutocommit() && !conn.isFromSlaveDB()) || this.source.isLocked()) {
return;
}
}
if ((this.source.isAutocommit() || conn.isFromSlaveDB()
|| !conn.isModifiedSQLExecuted()) && !this.source.isLocked()) {
releaseConnection((RouteResultsetNode) conn.getAttachment(), LOGGER.isDebugEnabled(),
needRollback);
}
}
}
public void releaseConnection(RouteResultsetNode rrn, boolean debug,
final boolean needRollback) {
BackendConnection c = target.remove(rrn);
if (c != null) {
if (debug) {
//LOGGER.debug("release connection " + c);
String sql = rrn.getStatement();
if(sql!=null){
sql = sql.replaceAll("[\r\n]+", "");
}
LOGGER.debug("releaseConnection Connection@{} [id={}] for node={}, sql={}",
new Object[]{c.hashCode(), c.getId(), rrn.getName(), sql});
}
if (c.getAttachment() != null) {
c.setAttachment(null);
}
if (!c.isClosedOrQuit()) {
if (c.isAutocommit()) {
c.release();
} else
//if (needRollback)
{
c.setResponseHandler(new RollbackReleaseHandler());
c.rollback();
}
//else {
// c.release();
//}
}
}
}
public void releaseConnections(final boolean needRollback) {
boolean debug = LOGGER.isDebugEnabled();
for (RouteResultsetNode rrn : target.keySet()) {
releaseConnection(rrn, debug, needRollback);
}
}
public void releaseConnection(BackendConnection con) {
Iterator<Entry<RouteResultsetNode, BackendConnection>> itor = target
.entrySet().iterator();
while (itor.hasNext()) {
BackendConnection theCon = itor.next().getValue();
if (theCon == con) {
itor.remove();
con.release();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("realse connection " + con);
}
break;
}
}
}
/**
* @return previous bound connection
*/
public BackendConnection bindConnection(RouteResultsetNode key,
BackendConnection conn) {
// System.out.println("bind connection "+conn+
// " to key "+key.getName()+" on sesion "+this);
if(LOGGER.isDebugEnabled()){
String sql = key.getStatement();
if(sql!=null){
sql = sql.replaceAll("[\r\n]+", "");
}
LOGGER.debug("bindConnection Connection@{} [id={}] for node={}, sql={}",
new Object[]{conn.hashCode(), conn.getId(), key.getName(), sql});
}
return target.put(key, conn);
}
public boolean tryExistsCon(final BackendConnection conn, RouteResultsetNode node) {
if (conn == null) {
return false;
}
boolean canReUse = false;
// conn 是 slave db 的,并且 路由结果显示,本次sql可以重用该 conn
if (conn.isFromSlaveDB() && (node.canRunnINReadDB(getSource().isAutocommit())
&& (node.getRunOnSlave() == null || node.getRunOnSlave()))) {
canReUse = true;
}
// conn 是 master db 的,并且路由结果显示,本次sql可以重用该conn
if (!conn.isFromSlaveDB() && (node.getRunOnSlave() == null || !node.getRunOnSlave())) {
canReUse = true;
}
if (canReUse) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("found connections in session to use " + conn
+ " for " + node);
}
conn.setAttachment(node);
return true;
} else {
// Previous connection and can't use anymore ,release it
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Release previous connection,can't be used in trasaction "
+ conn + " for " + node);
}
releaseConnection(node, LOGGER.isDebugEnabled(), false);
}
return false;
}
// public boolean tryExistsCon(final BackendConnection conn,
// RouteResultsetNode node) {
//
// if (conn == null) {
// return false;
// }
// if (!conn.isFromSlaveDB()
// || node.canRunnINReadDB(getSource().isAutocommit())) {
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("found connections in session to use " + conn
// + " for " + node);
// }
// conn.setAttachment(node);
// return true;
// } else {
// // slavedb connection and can't use anymore ,release it
// if (LOGGER.isDebugEnabled()) {
// LOGGER.debug("release slave connection,can't be used in trasaction "
// + conn + " for " + node);
// }
// releaseConnection(node, LOGGER.isDebugEnabled(), false);
// }
// return false;
// }
protected void kill() {
boolean hooked = false;
AtomicInteger count = null;
Map<RouteResultsetNode, BackendConnection> killees = null;
for (RouteResultsetNode node : target.keySet()) {
BackendConnection c = target.get(node);
if (c != null) {
if (!hooked) {
hooked = true;
killees = new HashMap<RouteResultsetNode, BackendConnection>();
count = new AtomicInteger(0);
}
killees.put(node, c);
count.incrementAndGet();
}
}
if (hooked) {
for (Entry<RouteResultsetNode, BackendConnection> en : killees
.entrySet()) {
KillConnectionHandler kill = new KillConnectionHandler(
en.getValue(), this);
MycatConfig conf = MycatServer.getInstance().getConfig();
PhysicalDBNode dn = conf.getDataNodes().get(
en.getKey().getName());
try {
dn.getConnectionFromSameSource(null, true, en.getValue(),
kill, en.getKey());
} catch (Exception e) {
LOGGER.error(
"get killer connection failed for " + en.getKey(),
e);
kill.connectionError(e, null);
}
}
}
}
private void clearHandlesResources() {
SingleNodeHandler singleHander = singleNodeHandler;
if (singleHander != null) {
singleHander.clearResources();
singleNodeHandler = null;
}
MultiNodeQueryHandler multiHandler = multiNodeHandler;
if (multiHandler != null) {
multiHandler.clearResources();
multiNodeHandler = null;
}
}
public void clearResources(final boolean needRollback) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("clear session resources " + this);
}
this.releaseConnections(needRollback);
clearHandlesResources();
}
public boolean closed() {
return source.isClosed();
}
private String genXATXID() {
return MycatServer.getInstance().getXATXIDGLOBAL();
}
public void setXATXEnabled(boolean xaTXEnabled) {
if (xaTXEnabled) {
LOGGER.info("XA Transaction enabled ,con " + this.getSource());
if(this.xaTXID == null){
xaTXID = genXATXID();
}
}else{
LOGGER.info("XA Transaction disabled ,con " + this.getSource());
this.xaTXID = null;
}
}
public String getXaTXID() {
return xaTXID;
}
public boolean isPrepared() {
return prepared;
}
public void setPrepared(boolean prepared) {
this.prepared = prepared;
}
public boolean isCanClose() {
return canClose;
}
public void setCanClose(boolean canClose) {
this.canClose = canClose;
}
public MiddlerResultHandler getMiddlerResultHandler() {
return middlerResultHandler;
}
public void setMiddlerResultHandler(MiddlerResultHandler middlerResultHandler) {
this.middlerResultHandler = middlerResultHandler;
}
public void setAutoCommitStatus() {
/* 1. 事务结束后,xa事务结束 */
if(this.getXaTXID()!=null){
this.setXATXEnabled(false);
}
/* 2. preAcStates 为true,事务结束后,需要设置为true。preAcStates 为ac上一个状态 */
if(this.getSource().isPreAcStates()&&!this.getSource().isAutocommit()){
this.getSource().setAutocommit(true);
}
this.getSource().clearTxInterrupt();
}
@Override
public String toString() {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
for (BackendConnection backCon : target.values()) {
sb.append(backCon).append("\r\n");
}
return sb.toString();
}
public RouteResultset getRrs() {
return rrs;
}
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/server/NonBlockingSession.java |
1,557 | /*
* Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package io.mycat;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.AsynchronousChannelGroup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.Files;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import io.mycat.backend.BackendConnection;
import io.mycat.backend.datasource.PhysicalDBNode;
import io.mycat.backend.datasource.PhysicalDBPool;
import io.mycat.backend.datasource.PhysicalDatasource;
import io.mycat.backend.heartbeat.zkprocess.MycatLeaderLatch;
import io.mycat.backend.mysql.nio.handler.MultiNodeCoordinator;
import io.mycat.backend.mysql.xa.CoordinatorLogEntry;
import io.mycat.backend.mysql.xa.ParticipantLogEntry;
import io.mycat.backend.mysql.xa.TxState;
import io.mycat.backend.mysql.xa.XACommitCallback;
import io.mycat.backend.mysql.xa.XARollbackCallback;
import io.mycat.backend.mysql.xa.recovery.Repository;
import io.mycat.backend.mysql.xa.recovery.impl.FileSystemRepository;
import io.mycat.buffer.BufferPool;
import io.mycat.buffer.DirectByteBufferPool;
import io.mycat.buffer.NettyBufferPool;
import io.mycat.cache.CacheService;
import io.mycat.config.MycatConfig;
import io.mycat.config.classloader.DynaClassLoader;
import io.mycat.config.loader.zkprocess.comm.ZkConfig;
import io.mycat.config.loader.zkprocess.comm.ZkParamCfg;
import io.mycat.config.model.SchemaConfig;
import io.mycat.config.model.SystemConfig;
import io.mycat.config.model.TableConfig;
import io.mycat.config.table.structure.MySQLTableStructureDetector;
import io.mycat.manager.ManagerConnectionFactory;
import io.mycat.memory.MyCatMemory;
import io.mycat.net.AIOAcceptor;
import io.mycat.net.AIOConnector;
import io.mycat.net.NIOAcceptor;
import io.mycat.net.NIOConnector;
import io.mycat.net.NIOProcessor;
import io.mycat.net.NIOReactorPool;
import io.mycat.net.SocketAcceptor;
import io.mycat.net.SocketConnector;
import io.mycat.route.MyCATSequnceProcessor;
import io.mycat.route.RouteService;
import io.mycat.route.factory.RouteStrategyFactory;
import io.mycat.route.sequence.handler.SequenceHandler;
import io.mycat.server.ServerConnectionFactory;
import io.mycat.server.interceptor.SQLInterceptor;
import io.mycat.server.interceptor.impl.GlobalTableUtil;
import io.mycat.sqlengine.OneRawSQLQueryResultHandler;
import io.mycat.sqlengine.SQLJob;
import io.mycat.statistic.SQLRecorder;
import io.mycat.statistic.stat.SqlResultSizeRecorder;
import io.mycat.statistic.stat.UserStat;
import io.mycat.statistic.stat.UserStatAnalyzer;
import io.mycat.util.ExecutorUtil;
import io.mycat.util.NameableExecutor;
import io.mycat.util.TimeUtil;
import io.mycat.util.ZKUtils;
/**
* @author mycat
*/
public class MycatServer {
public static final String NAME = "MyCat";
private static final long LOG_WATCH_DELAY = 60000L;
private static final long TIME_UPDATE_PERIOD = 20L;
private static final long DEFAULT_SQL_STAT_RECYCLE_PERIOD = 5 * 1000L;
private static final long DEFAULT_OLD_CONNECTION_CLEAR_PERIOD = 5 * 1000L;
private static final long DEFAULT_DATANODE_CALC_ACTIVECOUNT = 1000L;
private static final MycatServer INSTANCE = new MycatServer();
private static final Logger LOGGER = LoggerFactory.getLogger("MycatServer");
private static final Repository fileRepository = new FileSystemRepository();
private final RouteService routerService;
private final CacheService cacheService;
private Properties dnIndexProperties;
//AIO连接群组
private AsynchronousChannelGroup[] asyncChannelGroups;
private volatile int channelIndex = 0;
//全局序列号
// private final MyCATSequnceProcessor sequnceProcessor = new MyCATSequnceProcessor();
private final DynaClassLoader catletClassLoader;
private final SQLInterceptor sqlInterceptor;
private volatile int nextProcessor;
// System Buffer Pool Instance
private BufferPool bufferPool;
private boolean aio = false;
//XA事务全局ID生成
private final AtomicLong xaIDInc = new AtomicLong();
//sequence处理对象
private SequenceHandler sequenceHandler;
/**
* Mycat 内存管理类
*/
private MyCatMemory myCatMemory = null;
public static final MycatServer getInstance() {
return INSTANCE;
}
private final MycatConfig config;
private final ScheduledExecutorService scheduler;
private final ScheduledExecutorService heartbeatScheduler;
private final SQLRecorder sqlRecorder;
private final AtomicBoolean isOnline;
private final long startupTime;
private NIOProcessor[] processors;
private SocketConnector connector;
private NameableExecutor businessExecutor;
private NameableExecutor sequenceExecutor;
private NameableExecutor timerExecutor;
private ListeningExecutorService listeningExecutorService;
private InterProcessMutex dnindexLock;
private long totalNetWorkBufferSize = 0;
private volatile MycatLeaderLatch leaderLatch;
private final AtomicBoolean startup = new AtomicBoolean(false);
private ScheduledFuture<?> recycleSqlStatFuture = null;
private MycatServer() {
//读取文件配置
this.config = new MycatConfig();
//定时线程池,单线程线程池
scheduler = Executors.newSingleThreadScheduledExecutor();
//心跳调度独立出来,避免被其他任务影响
heartbeatScheduler = Executors.newSingleThreadScheduledExecutor();
//SQL记录器
this.sqlRecorder = new SQLRecorder(config.getSystem().getSqlRecordCount());
/**
* 是否在线,MyCat manager中有命令控制
* | offline | Change MyCat status to OFF |
* | online | Change MyCat status to ON |
*/
this.isOnline = new AtomicBoolean(true);
//缓存服务初始化
cacheService = new CacheService();
//路由计算初始化
routerService = new RouteService(cacheService);
// load datanode active index from properties
dnIndexProperties = loadDnIndexProps();
try {
//SQL解析器
sqlInterceptor = (SQLInterceptor) Class.forName(
config.getSystem().getSqlInterceptor()).newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
//catlet加载器
catletClassLoader = new DynaClassLoader(SystemConfig.getHomePath()
+ File.separator + "catlet", config.getSystem().getCatletClassCheckSeconds());
//记录启动时间
this.startupTime = TimeUtil.currentTimeMillis();
if (isUseZkSwitch()) {
String path = ZKUtils.getZKBasePath() + "lock/dnindex.lock";
dnindexLock = new InterProcessMutex(ZKUtils.getConnection(), path);
}
}
public AtomicBoolean getStartup() {
return startup;
}
public long getTotalNetWorkBufferSize() {
return totalNetWorkBufferSize;
}
public BufferPool getBufferPool() {
return bufferPool;
}
public NameableExecutor getTimerExecutor() {
return timerExecutor;
}
public DynaClassLoader getCatletClassLoader() {
return catletClassLoader;
}
public MyCATSequnceProcessor getSequnceProcessor() {
return MyCATSequnceProcessor.getInstance();
}
public SQLInterceptor getSqlInterceptor() {
return sqlInterceptor;
}
public ScheduledExecutorService getScheduler() {
return scheduler;
}
public String genXATXID() {
long seq = this.xaIDInc.incrementAndGet();
if (seq < 0) {
synchronized (xaIDInc) {
if (xaIDInc.get() < 0) {
xaIDInc.set(0);
}
seq = xaIDInc.incrementAndGet();
}
}
return "'Mycat." + this.getConfig().getSystem().getMycatNodeId() + "." + seq + "'";
}
public String getXATXIDGLOBAL() {
return "'" + getUUID() + "'";
}
public static String getUUID() {
String s = UUID.randomUUID().toString();
//去掉“-”符号
return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
}
public MyCatMemory getMyCatMemory() {
return myCatMemory;
}
/**
* get next AsynchronousChannel ,first is exclude if multi
* AsynchronousChannelGroups
*
* @return
*/
public AsynchronousChannelGroup getNextAsyncChannelGroup() {
if (asyncChannelGroups.length == 1) {
return asyncChannelGroups[0];
} else {
int index = (++channelIndex) % asyncChannelGroups.length;
if (index == 0) {
++channelIndex;
return asyncChannelGroups[1];
} else {
return asyncChannelGroups[index];
}
}
}
public MycatConfig getConfig() {
return config;
}
public void beforeStart() {
String home = SystemConfig.getHomePath();
//ZkConfig.instance().initZk();
}
public void startup() throws IOException {
SystemConfig system = config.getSystem();
int processorCount = system.getProcessors();
//init RouteStrategyFactory first
RouteStrategyFactory.init();
// server startup
LOGGER.info(NAME + " is ready to startup ...");
String inf = "Startup processors ...,total processors:"
+ system.getProcessors() + ",aio thread pool size:"
+ system.getProcessorExecutor()
+ " \r\n each process allocated socket buffer pool "
+ " bytes ,a page size:"
+ system.getBufferPoolPageSize()
+ " a page's chunk number(PageSize/ChunkSize) is:"
+ (system.getBufferPoolPageSize()
/ system.getBufferPoolChunkSize())
+ " buffer page's number is:"
+ system.getBufferPoolPageNumber();
LOGGER.info(inf);
LOGGER.info("sysconfig params:" + system.toString());
// startup manager
ManagerConnectionFactory mf = new ManagerConnectionFactory();
ServerConnectionFactory sf = new ServerConnectionFactory();
SocketAcceptor manager = null;
SocketAcceptor server = null;
aio = (system.getUsingAIO() == 1);
// startup processors
int threadPoolSize = system.getProcessorExecutor();
processors = new NIOProcessor[processorCount];
// a page size
int bufferPoolPageSize = system.getBufferPoolPageSize();
// total page number
short bufferPoolPageNumber = system.getBufferPoolPageNumber();
//minimum allocation unit
short bufferPoolChunkSize = system.getBufferPoolChunkSize();
int socketBufferLocalPercent = system.getProcessorBufferLocalPercent();
int bufferPoolType = system.getProcessorBufferPoolType();
switch (bufferPoolType) {
case 0:
bufferPool = new DirectByteBufferPool(bufferPoolPageSize, bufferPoolChunkSize,
bufferPoolPageNumber, system.getFrontSocketSoRcvbuf());
totalNetWorkBufferSize = bufferPoolPageSize * bufferPoolPageNumber;
break;
case 1:
/**
* todo 对应权威指南修改:
*
* bytebufferarena由6个bytebufferlist组成,这六个list有减少内存碎片的机制
* 每个bytebufferlist由多个bytebufferchunk组成,每个list也有减少内存碎片的机制
* 每个bytebufferchunk由多个page组成,平衡二叉树管理内存使用状态,计算灵活
* 设置的pagesize对应bytebufferarena里面的每个bytebufferlist的每个bytebufferchunk的buffer长度
* bufferPoolChunkSize对应每个bytebufferchunk的每个page的长度
* bufferPoolPageNumber对应每个bytebufferlist有多少个bytebufferchunk
*/
totalNetWorkBufferSize = 6 * bufferPoolPageSize * bufferPoolPageNumber;
break;
case 2:
bufferPool = new NettyBufferPool(bufferPoolChunkSize);
LOGGER.info("Use Netty Buffer Pool");
break;
default:
bufferPool = new DirectByteBufferPool(bufferPoolPageSize, bufferPoolChunkSize,
bufferPoolPageNumber, system.getFrontSocketSoRcvbuf());
;
totalNetWorkBufferSize = bufferPoolPageSize * bufferPoolPageNumber;
}
/**
* Off Heap For Merge/Order/Group/Limit 初始化
*/
if (system.getUseOffHeapForMerge() == 1) {
try {
myCatMemory = new MyCatMemory(system, totalNetWorkBufferSize);
} catch (NoSuchFieldException e) {
LOGGER.error("NoSuchFieldException", e);
} catch (IllegalAccessException e) {
LOGGER.error("Error", e);
}
}
businessExecutor = ExecutorUtil.create("BusinessExecutor",
threadPoolSize);
sequenceExecutor = ExecutorUtil.create("SequenceExecutor", threadPoolSize);
timerExecutor = ExecutorUtil.create("Timer", system.getTimerExecutor());
listeningExecutorService = MoreExecutors.listeningDecorator(businessExecutor);
for (int i = 0; i < processors.length; i++) {
processors[i] = new NIOProcessor("Processor" + i, bufferPool,
businessExecutor);
}
if (aio) {
LOGGER.info("using aio network handler ");
asyncChannelGroups = new AsynchronousChannelGroup[processorCount];
// startup connector
connector = new AIOConnector();
for (int i = 0; i < processors.length; i++) {
asyncChannelGroups[i] = AsynchronousChannelGroup.withFixedThreadPool(processorCount,
new ThreadFactory() {
private int inx = 1;
@Override
public Thread newThread(Runnable r) {
Thread th = new Thread(r);
//TODO
th.setName(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "AIO" + (inx++));
LOGGER.info("created new AIO thread " + th.getName());
return th;
}
}
);
}
manager = new AIOAcceptor(NAME + "Manager", system.getBindIp(),
system.getManagerPort(), system.getServerBacklog(), mf, this.asyncChannelGroups[0]);
// startup server
server = new AIOAcceptor(NAME + "Server", system.getBindIp(),
system.getServerPort(), system.getServerBacklog(), sf, this.asyncChannelGroups[0]);
} else {
LOGGER.info("using nio network handler ");
NIOReactorPool reactorPool = new NIOReactorPool(
DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "NIOREACTOR",
processors.length);
connector = new NIOConnector(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "NIOConnector", reactorPool);
((NIOConnector) connector).start();
manager = new NIOAcceptor(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + NAME
+ "Manager", system.getBindIp(), system.getManagerPort(), system.getServerBacklog(), mf, reactorPool);
server = new NIOAcceptor(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + NAME
+ "Server", system.getBindIp(), system.getServerPort(), system.getServerBacklog(), sf, reactorPool);
}
// manager start
manager.start();
LOGGER.info(manager.getName() + " is started and listening on " + manager.getPort());
server.start();
// server started
LOGGER.info(server.getName() + " is started and listening on " + server.getPort());
LOGGER.info("===============================================");
// init datahost
Map<String, PhysicalDBPool> dataHosts = config.getDataHosts();
LOGGER.info("Initialize dataHost ...");
for (PhysicalDBPool node : dataHosts.values()) {
String index = dnIndexProperties.getProperty(node.getHostName(), "0");
if (!"0".equals(index)) {
LOGGER.info("init datahost: " + node.getHostName() + " to use datasource index:" + index);
}
node.init(Integer.parseInt(index));
node.startHeartbeat();
}
long dataNodeIldeCheckPeriod = system.getDataNodeIdleCheckPeriod();
heartbeatScheduler.scheduleAtFixedRate(updateTime(), 0L, TIME_UPDATE_PERIOD, TimeUnit.MILLISECONDS);
heartbeatScheduler.scheduleAtFixedRate(processorCheck(), 0L, system.getProcessorCheckPeriod(), TimeUnit.MILLISECONDS);
heartbeatScheduler.scheduleAtFixedRate(dataNodeConHeartBeatCheck(dataNodeIldeCheckPeriod), 0L, dataNodeIldeCheckPeriod, TimeUnit.MILLISECONDS);
heartbeatScheduler.scheduleAtFixedRate(dataNodeHeartbeat(), 0L, system.getDataNodeHeartbeatPeriod(), TimeUnit.MILLISECONDS);
heartbeatScheduler.scheduleAtFixedRate(dataSourceOldConsClear(), 0L, DEFAULT_OLD_CONNECTION_CLEAR_PERIOD, TimeUnit.MILLISECONDS);
heartbeatScheduler.scheduleAtFixedRate(dataNodeCalcActiveCons(), 0L, DEFAULT_DATANODE_CALC_ACTIVECOUNT, TimeUnit.MILLISECONDS);
//
scheduler.schedule(catletClassClear(), 30000, TimeUnit.MILLISECONDS);
if (system.getCheckTableConsistency() == 1) {
scheduler.scheduleAtFixedRate(tableStructureCheck(), 0L, system.getCheckTableConsistencyPeriod(), TimeUnit.MILLISECONDS);
}
ensureSqlstatRecycleFuture();
if (system.getUseGlobleTableCheck() == 1) { // 全局表一致性检测是否开启
// scheduler.scheduleAtFixedRate(glableTableConsistencyCheck(), 0L, system.getGlableTableCheckPeriod(), TimeUnit.MILLISECONDS);
}
//定期清理结果集排行榜,控制拒绝策略
scheduler.scheduleAtFixedRate(resultSetMapClear(), 0L, system.getClearBigSqLResultSetMapMs(), TimeUnit.MILLISECONDS);
//xa 事务定时检查 是否全部提交 或者部分提交 部分回滚, 进行补充提交补充回滚.
scheduler.scheduleAtFixedRate(xaTaskCheck(), 0L, 10 * 1000, TimeUnit.MILLISECONDS);
// new Thread(tableStructureCheck()).start();
//XA Init recovery Log
LOGGER.info("===============================================");
LOGGER.info("Perform XA recovery log ...");
CoordinatorLogEntry[] coordinatorLogEntries = getCoordinatorLogEntries();
putXARecoveryLogToMemory(coordinatorLogEntries);
performXARecoveryLog(coordinatorLogEntries);
LOGGER.info("Perform XA recovery log end...");
if (isUseZkSwitch()) {
//首次启动如果发现zk上dnindex为空,则将本地初始化上zk
initZkDnindex();
leaderLatch = new MycatLeaderLatch("heartbeat/leader");
try {
leaderLatch.start();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
e.printStackTrace();
}
}
initRuleData();
startup.set(true);
}
public void ensureSqlstatRecycleFuture() {
if (config.getSystem().getUseSqlStat() == 1) {
if(recycleSqlStatFuture == null){
recycleSqlStatFuture = scheduler
.scheduleAtFixedRate(recycleSqlStat(), 0L, DEFAULT_SQL_STAT_RECYCLE_PERIOD, TimeUnit.MILLISECONDS);
}
} else {
if (recycleSqlStatFuture != null) {
recycleSqlStatFuture.cancel(false);
recycleSqlStatFuture = null;
}
}
}
public void initRuleData() {
if (!isUseZk()) return;
InterProcessMutex ruleDataLock = null;
try {
File file = new File(SystemConfig.getHomePath(), "conf" + File.separator + "ruledata");
if (!file.exists()) {
file.mkdir();
}
String path = ZKUtils.getZKBasePath() + "lock/ruledata.lock";
ruleDataLock = new InterProcessMutex(ZKUtils.getConnection(), path);
ruleDataLock.acquire(30, TimeUnit.SECONDS);
File[] childFiles = file.listFiles();
if (childFiles != null && childFiles.length > 0) {
String basePath = ZKUtils.getZKBasePath() + "ruledata/";
for (File childFile : childFiles) {
CuratorFramework zk = ZKUtils.getConnection();
if (zk.checkExists().forPath(basePath + childFile.getName()) == null) {
zk.create().creatingParentsIfNeeded().forPath(basePath + childFile.getName(), Files.toByteArray(childFile));
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (ruleDataLock != null)
ruleDataLock.release();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private void initZkDnindex() {
try {
File file = new File(SystemConfig.getHomePath(), "conf" + File.separator + "dnindex.properties");
dnindexLock.acquire(30, TimeUnit.SECONDS);
String path = ZKUtils.getZKBasePath() + "bindata/dnindex.properties";
CuratorFramework zk = ZKUtils.getConnection();
if (zk.checkExists().forPath(path) == null) {
zk.create().creatingParentsIfNeeded().forPath(path, Files.toByteArray(file));
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
dnindexLock.release();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public void reloadDnIndex() {
if (MycatServer.getInstance().getProcessors() == null) return;
// load datanode active index from properties
dnIndexProperties = loadDnIndexProps();
// init datahost
Map<String, PhysicalDBPool> dataHosts = config.getDataHosts();
LOGGER.info("reInitialize dataHost ...");
for (PhysicalDBPool node : dataHosts.values()) {
String index = dnIndexProperties.getProperty(node.getHostName(), "0");
if (!"0".equals(index)) {
LOGGER.info("reinit datahost: " + node.getHostName() + " to use datasource index:" + index);
}
node.switchSource(Integer.parseInt(index), true, "reload dnindex");
}
}
private Runnable catletClassClear() {
return new Runnable() {
@Override
public void run() {
try {
catletClassLoader.clearUnUsedClass();
} catch (Exception e) {
LOGGER.warn("catletClassClear err " + e);
}
}
;
};
}
/**
* 清理 reload @@config_all 后,老的 connection 连接
*
* @return
*/
private Runnable dataSourceOldConsClear() {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
long sqlTimeout = MycatServer.getInstance().getConfig().getSystem().getSqlExecuteTimeout() * 1000L;
//根据 lastTime 确认事务的执行, 超过 sqlExecuteTimeout 阀值 close connection
long currentTime = TimeUtil.currentTimeMillis();
Iterator<BackendConnection> iter = NIOProcessor.backends_old.iterator();
while (iter.hasNext()) {
BackendConnection con = iter.next();
long lastTime = con.getLastTime();
if (currentTime - lastTime > sqlTimeout) {
con.close("clear old backend connection ...");
iter.remove();
}
}
}
});
}
;
};
}
/**
* 在bufferpool使用率大于使用率阈值时不清理
* 在bufferpool使用率小于使用率阈值时清理大结果集清单内容
*/
private Runnable resultSetMapClear() {
return new Runnable() {
@Override
public void run() {
try {
BufferPool bufferPool = getBufferPool();
long bufferSize = bufferPool.size();
long bufferCapacity = bufferPool.capacity();
long bufferUsagePercent = (bufferCapacity - bufferSize) * 100 / bufferCapacity;
if (bufferUsagePercent < config.getSystem().getBufferUsagePercent()) {
Map<String, UserStat> map = UserStatAnalyzer.getInstance().getUserStatMap();
Set<String> userSet = config.getUsers().keySet();
for (String user : userSet) {
UserStat userStat = map.get(user);
if (userStat != null) {
SqlResultSizeRecorder recorder = userStat.getSqlResultSizeRecorder();
//System.out.println(recorder.getSqlResultSet().size());
recorder.clearSqlResultSet();
}
}
}
} catch (Exception e) {
LOGGER.warn("resultSetMapClear err " + e);
}
}
;
};
}
private Properties loadDnIndexProps() {
Properties prop = new Properties();
File file = new File(SystemConfig.getHomePath(), "conf" + File.separator + "dnindex.properties");
if (!file.exists()) {
return prop;
}
FileInputStream filein = null;
try {
filein = new FileInputStream(file);
prop.load(filein);
} catch (Exception e) {
LOGGER.warn("load DataNodeIndex err:" + e);
} finally {
if (filein != null) {
try {
filein.close();
} catch (IOException e) {
}
}
}
return prop;
}
public synchronized boolean saveDataHostIndexToZk(String dataHost, int curIndex) {
boolean result = false;
try {
try {
dnindexLock.acquire(30, TimeUnit.SECONDS);
String path = ZKUtils.getZKBasePath() + "bindata/dnindex.properties";
Map<String, String> propertyMap = new HashMap<>();
propertyMap.put(dataHost, String.valueOf(curIndex));
result = ZKUtils.writeProperty(path, propertyMap);
} finally {
dnindexLock.release();
}
} catch (Exception e) {
LOGGER.warn("saveDataHostIndexToZk err:", e);
}
return result;
}
/**
* save cur datanode index to properties file
*
* @param
* @param curIndex
*/
public synchronized void saveDataHostIndex(String dataHost, int curIndex) {
File file = new File(SystemConfig.getHomePath(), "conf" + File.separator + "dnindex.properties");
FileOutputStream fileOut = null;
try {
String oldIndex = dnIndexProperties.getProperty(dataHost);
String newIndex = String.valueOf(curIndex);
if (newIndex.equals(oldIndex)) {
return;
}
dnIndexProperties.setProperty(dataHost, newIndex);
LOGGER.info("save DataHost index " + dataHost + " cur index " + curIndex);
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
fileOut = new FileOutputStream(file);
dnIndexProperties.store(fileOut, "update");
// if(isUseZkSwitch()) {
// // save to zk
// try {
// dnindexLock.acquire(30,TimeUnit.SECONDS) ;
// String path = ZKUtils.getZKBasePath() + "bindata/dnindex.properties";
// CuratorFramework zk = ZKUtils.getConnection();
// if(zk.checkExists().forPath(path)==null) {
// zk.create().creatingParentsIfNeeded().forPath(path, Files.toByteArray(file));
// } else{
// byte[] data= zk.getData().forPath(path);
// ByteArrayOutputStream out=new ByteArrayOutputStream();
// Properties properties=new Properties();
// properties.load(new ByteArrayInputStream(data));
// if(!String.valueOf(curIndex).equals(properties.getProperty(dataHost))) {
// properties.setProperty(dataHost, String.valueOf(curIndex));
// properties.store(out, "update");
// zk.setData().forPath(path, out.toByteArray());
// }
// }
//
// }finally {
// dnindexLock.release();
// }
// }
} catch (Exception e) {
LOGGER.warn("saveDataNodeIndex err:", e);
} finally {
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
}
}
}
}
private boolean isUseZk() {
String loadZk = ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_FLAG);
return "true".equalsIgnoreCase(loadZk);
}
public boolean isUseZkSwitch() {
MycatConfig mycatConfig = config;
boolean isUseZkSwitch = mycatConfig.getSystem().isUseZKSwitch();
String loadZk = ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_FLAG);
return (isUseZkSwitch && "true".equalsIgnoreCase(loadZk));
}
public RouteService getRouterService() {
return routerService;
}
public CacheService getCacheService() {
return cacheService;
}
public NameableExecutor getBusinessExecutor() {
return businessExecutor;
}
public RouteService getRouterservice() {
return routerService;
}
public NIOProcessor nextProcessor() {
int i = ++nextProcessor;
if (i >= processors.length) {
i = nextProcessor = 0;
}
return processors[i];
}
public NIOProcessor[] getProcessors() {
return processors;
}
public SocketConnector getConnector() {
return connector;
}
public SQLRecorder getSqlRecorder() {
return sqlRecorder;
}
public long getStartupTime() {
return startupTime;
}
public boolean isOnline() {
return isOnline.get();
}
public void offline() {
isOnline.set(false);
}
public void online() {
isOnline.set(true);
}
// 系统时间定时更新任务
private Runnable updateTime() {
return new Runnable() {
@Override
public void run() {
TimeUtil.update();
}
};
}
// 处理器定时检查任务
private Runnable processorCheck() {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
try {
for (NIOProcessor p : processors) {
p.checkBackendCons();
}
} catch (Exception e) {
LOGGER.warn("checkBackendCons caught err:" + e);
}
}
});
timerExecutor.execute(new Runnable() {
@Override
public void run() {
try {
for (NIOProcessor p : processors) {
p.checkFrontCons();
}
} catch (Exception e) {
LOGGER.warn("checkFrontCons caught err:" + e);
}
}
});
}
};
}
// 数据节点定时连接空闲超时检查任务
private Runnable dataNodeConHeartBeatCheck(final long heartPeriod) {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
Map<String, PhysicalDBPool> nodes = config.getDataHosts();
for (PhysicalDBPool node : nodes.values()) {
node.heartbeatCheck(heartPeriod);
}
/*
Map<String, PhysicalDBPool> _nodes = config.getBackupDataHosts();
if (_nodes != null) {
for (PhysicalDBPool node : _nodes.values()) {
node.heartbeatCheck(heartPeriod);
}
}*/
}
});
}
};
}
// 数据节点定时心跳任务
private Runnable dataNodeHeartbeat() {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
Map<String, PhysicalDBPool> nodes = config.getDataHosts();
for (PhysicalDBPool node : nodes.values()) {
node.doHeartbeat();
}
}
});
}
};
}
//by kaiz : 定时计算datanode active connection
private Runnable dataNodeCalcActiveCons() {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
Map<String, PhysicalDBPool> nodes = config.getDataHosts();
for (PhysicalDBPool node : nodes.values()) {
Collection<PhysicalDatasource> dataSources = node.getAllDataSources();
for(PhysicalDatasource ds : dataSources) {
ds.calcTotalCount();
}
}
}
});
}
};
}
//定时清理保存SqlStat中的数据
private Runnable recycleSqlStat() {
return new Runnable() {
@Override
public void run() {
Map<String, UserStat> statMap = UserStatAnalyzer.getInstance().getUserStatMap();
for (UserStat userStat : statMap.values()) {
userStat.getSqlLastStat().recycle();
userStat.getSqlRecorder().recycle();
userStat.getSqlHigh().recycle();
userStat.getSqlLargeRowStat().recycle();
}
}
};
}
//定时清理xa任务 对超过阈值的xa任务回滚或者提交
private Runnable xaTaskCheck() {
return new Runnable() {
@Override
public void run() {
Collection<CoordinatorLogEntry> coordinatorLogEntries = MultiNodeCoordinator.inMemoryRepository.getAllCoordinatorLogEntries();
long sqlTimeout = MycatServer.getInstance().getConfig().getSystem().getSqlExecuteTimeout() * 1000L;
List<CoordinatorLogEntry> CoordinatorLogEntryList = null;
long currentTime = TimeUtil.currentTimeMillis();
for(CoordinatorLogEntry coordinatorLogEntry : coordinatorLogEntries) {
//超过执行时间20秒 进行重试
if(currentTime > sqlTimeout + 20 * 1000 + coordinatorLogEntry.createTime){
if(CoordinatorLogEntryList == null) {
CoordinatorLogEntryList = new ArrayList<CoordinatorLogEntry>();
}
CoordinatorLogEntryList.add(coordinatorLogEntry);
}
}
if(CoordinatorLogEntryList != null) {
performXARecoveryLog((CoordinatorLogEntry[])CoordinatorLogEntryList.toArray());
}
}
};
}
//定时检查不同分片表结构一致性
private Runnable tableStructureCheck() {
return new MySQLTableStructureDetector();
}
// 全局表一致性检查任务
private Runnable glableTableConsistencyCheck() {
return new Runnable() {
@Override
public void run() {
timerExecutor.execute(new Runnable() {
@Override
public void run() {
GlobalTableUtil.consistencyCheck();
}
});
}
};
}
private void putXARecoveryLogToMemory(CoordinatorLogEntry[] coordinatorLogEntries) {
//init into in memory cached
for (int i = 0; i < coordinatorLogEntries.length; i++) {
MultiNodeCoordinator.inMemoryRepository.put(coordinatorLogEntries[i].id, coordinatorLogEntries[i]);
//discard the recovery log
MultiNodeCoordinator.fileRepository.writeCheckpoint(coordinatorLogEntries[i].id, MultiNodeCoordinator.inMemoryRepository.getAllCoordinatorLogEntries());
}
}
//XA recovery log check
private void performXARecoveryLog(CoordinatorLogEntry[] coordinatorLogEntries) {
//fetch the recovery log
for (int i = 0; i < coordinatorLogEntries.length; i++) {
CoordinatorLogEntry coordinatorLogEntry = coordinatorLogEntries[i];
boolean needRollback = false;
boolean hasCommit = false;
//检查xa事务是否完成 ,处于部分commit 或者部分prepare中
for (int j = 0; j < coordinatorLogEntry.participants.length; j++) {
ParticipantLogEntry participantLogEntry = coordinatorLogEntry.participants[j];
if (participantLogEntry.txState == TxState.TX_PREPARED_STATE || participantLogEntry.txState == TxState.TX_STARTED_STATE) {
needRollback = true;
}
if (participantLogEntry.txState == TxState.TX_COMMITED_STATE) {
hasCommit = true;
}
}
//补充提交 prepare 状态的提交, xa commit or xa rollback
if (needRollback) {
//1 can rollback
if(!hasCommit) {
for (int j = 0; j < coordinatorLogEntry.participants.length; j++) {
ParticipantLogEntry participantLogEntry = coordinatorLogEntry.participants[j];
if (participantLogEntry.txState == TxState.TX_COMMITED_STATE || participantLogEntry.txState == TxState.TX_ROLLBACKED_STATE) {
continue;
} //XA rollback
String xacmd = "XA ROLLBACK " + coordinatorLogEntry.id +",'"+ participantLogEntry.resourceName+"'" + ';';
LOGGER.debug("send xaCmd : {}", xacmd);
OneRawSQLQueryResultHandler resultHandler = new OneRawSQLQueryResultHandler(new String[0], new XARollbackCallback(coordinatorLogEntry.id,
participantLogEntry
));
//xa cmd send
sendXaCmd(participantLogEntry, xacmd, resultHandler);
}
} else {
LOGGER.debug( "some has commit in {}",coordinatorLogEntry);
for (int j = 0; j < coordinatorLogEntry.participants.length; j++) {
ParticipantLogEntry participantLogEntry = coordinatorLogEntry.participants[j];
if (participantLogEntry.txState == TxState.TX_COMMITED_STATE || participantLogEntry.txState == TxState.TX_ROLLBACKED_STATE) {
continue;
}
//XA commit
String xacmd = "XA COMMIT " + coordinatorLogEntry.id +",'"+ participantLogEntry.resourceName+"'" + ';';
LOGGER.debug("send xaCmd : {}", xacmd);
OneRawSQLQueryResultHandler resultHandler = new OneRawSQLQueryResultHandler(new String[0], new XACommitCallback(coordinatorLogEntry.id,
participantLogEntry
));
//xa cmd send
sendXaCmd(participantLogEntry, xacmd, resultHandler);
}
}
}
}
}
private void sendXaCmd(ParticipantLogEntry participantLogEntry, String xacmd,
OneRawSQLQueryResultHandler resultHandler) {
for (SchemaConfig schema : MycatServer.getInstance().getConfig().getSchemas().values()) {
for (TableConfig table : schema.getTables().values()) {
for (String dataNode : table.getDataNodes()) {
PhysicalDBNode dn = MycatServer.getInstance().getConfig().getDataNodes().get(dataNode);
if (dn.getDbPool().getSource().getConfig().getIp().equals(participantLogEntry.uri)
&& dn.getDatabase().equals(participantLogEntry.resourceName)) {
//XA STATE ROLLBACK
SQLJob sqlJob = new SQLJob(xacmd, dn.getDatabase(), resultHandler, dn.getDbPool().getSource());
sqlJob.run();
LOGGER.debug(String.format("[XA cmd] [%s] Host:[%s] schema:[%s]", xacmd, dn.getName(), dn.getDatabase()));
// break outloop;
return;
}
}
}
}
}
/**
* covert the collection to array
**/
private CoordinatorLogEntry[] getCoordinatorLogEntries() {
Collection<CoordinatorLogEntry> allCoordinatorLogEntries = fileRepository.getAllCoordinatorLogEntries();
if (allCoordinatorLogEntries == null) {
return new CoordinatorLogEntry[0];
}
if (allCoordinatorLogEntries.size() == 0) {
return new CoordinatorLogEntry[0];
}
return allCoordinatorLogEntries.toArray(new CoordinatorLogEntry[allCoordinatorLogEntries.size()]);
}
public NameableExecutor getSequenceExecutor() {
return sequenceExecutor;
}
//huangyiming add
public DirectByteBufferPool getDirectByteBufferPool() {
return (DirectByteBufferPool) bufferPool;
}
public boolean isAIO() {
return aio;
}
public ListeningExecutorService getListeningExecutorService() {
return listeningExecutorService;
}
public ScheduledExecutorService getHeartbeatScheduler() {
return heartbeatScheduler;
}
public MycatLeaderLatch getLeaderLatch() {
return leaderLatch;
}
public static void main(String[] args) throws Exception {
String path = ZKUtils.getZKBasePath() + "bindata";
CuratorFramework zk = ZKUtils.getConnection();
if (zk.checkExists().forPath(path) == null) ;
byte[] data = zk.getData().forPath(path);
System.out.println(data.length);
}
}
| MyCATApache/Mycat-Server | src/main/java/io/mycat/MycatServer.java |
1,560 | package me.chanjar.weixin.common.api;
/**
* <pre>
* 消息重复检查器.
* 微信服务器在五秒内收不到响应会断掉连接,并且重新发起请求,总共重试三次
* </pre>
*
* @author Daniel Qian
*/
public interface WxMessageDuplicateChecker {
/**
* 判断消息是否重复.
* <h2>公众号的排重方式</h2>
*
* <p>普通消息:关于重试的消息排重,推荐使用msgid排重。<a href="http://mp.weixin.qq.com/wiki/10/79502792eef98d6e0c6e1739da387346.html">文档参考</a>。</p>
* <p>事件消息:关于重试的消息排重,推荐使用FromUserName + CreateTime 排重。<a href="http://mp.weixin.qq.com/wiki/2/5baf56ce4947d35003b86a9805634b1e.html">文档参考</a></p>
*
* <h2>企业号的排重方式</h2>
* <p>官方文档完全没有写,参照公众号的方式排重。</p>
* <p>或者可以采取更简单的方式,如果有MsgId就用MsgId排重,如果没有就用FromUserName+CreateTime排重</p>
*
* @param messageId messageId需要根据上面讲的方式构造
* @return 如果是重复消息,返回true,否则返回false
*/
boolean isDuplicate(String messageId);
}
| 723580451/Wechat-Group-WxJava | weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageDuplicateChecker.java |