file_id
stringlengths
5
9
content
stringlengths
128
32.8k
repo
stringlengths
9
63
path
stringlengths
8
120
token_length
int64
52
8.14k
original_comment
stringlengths
5
1.83k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
111
32.8k
excluded
float64
0
1
15935_1
package com.liuliuzhu.autojs; import android.app.Application; import android.util.Log; import com.liuliuzhu.autojs.utils.HookUtils; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage; /** * @author 溜溜猪 * @date 2020/05/23 * @desc 微信公众号:AI小子 */ public class Hook extends Application implements IXposedHookLoadPackage, Config { @Override public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { final Class<?> clazz = XposedHelpers.findClass( "com.stardust.autojs.engine.encryption.ScriptEncryption", loadPackageParam.classLoader); XposedHelpers.findAndHookMethod( clazz, "decrypt", byte[].class, int.class, int.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { // 拿到的解密数据 String str = HookUtils.bytesToString((byte[]) param.getResult()); HookUtils.strToFile(str, FILEPATH); } }); } }
66pig/Autojs_tools
app/src/main/java/com/liuliuzhu/autojs/Hook.java
347
// 拿到的解密数据
line_comment
zh-cn
package com.liuliuzhu.autojs; import android.app.Application; import android.util.Log; import com.liuliuzhu.autojs.utils.HookUtils; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage; /** * @author 溜溜猪 * @date 2020/05/23 * @desc 微信公众号:AI小子 */ public class Hook extends Application implements IXposedHookLoadPackage, Config { @Override public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { final Class<?> clazz = XposedHelpers.findClass( "com.stardust.autojs.engine.encryption.ScriptEncryption", loadPackageParam.classLoader); XposedHelpers.findAndHookMethod( clazz, "decrypt", byte[].class, int.class, int.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { // 拿到 <SUF> String str = HookUtils.bytesToString((byte[]) param.getResult()); HookUtils.strToFile(str, FILEPATH); } }); } }
0
7799_39
package com.dou361.jjdxm_ijkplayer.videomonitoring; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.os.CountDownTimer; import android.os.PowerManager; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.Toast; import androidx.annotation.NonNull; import com.alibaba.fastjson.JSON; import com.bumptech.glide.Glide; import com.dou361.jjdxm_ijkplayer.R; import com.dou361.jjdxm_ijkplayer.videomonitoring.utlis.MediaUtils; import com.videogo.exception.BaseException; import com.videogo.openapi.EZOpenSDK; import com.videogo.openapi.EZPlayer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import butterknife.ButterKnife; import butterknife.OnClick; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static android.content.ContentValues.TAG; public class VideoEZplayer extends Activity implements View.OnClickListener , MyRadioGroup.OnCheckedChangeListener ,SurfaceHolder.Callback{ EZPlayer mEZPlayer1; private int count = 0; public String hostURL="http://vehicleroadcloud.faw.cn:60443/backend/appBackend/"; private String testURL= // "ezopen://open.ys7.com/C78957921/1.live"; "ezopen://open.ys7.com/231236707/1.live"; public CountDownTimer countDownTimer; public VideoRequest videoRequest; public VideoReply videoReply,videoReply2; public String videoResponseString,mergeVideoString;//视频Post请求返回数据 private Context mContext; private PowerManager.WakeLock wakeLock; View rootView; private Integer videoPlayingNum=5; private MyRadioGroup videoRatioGroup; private RadioButton buttonFront, buttonBack, buttonLeft, buttonRight, channelGodPerspective; private HashMap<String, RadioButton> channels = new HashMap<>(5); private ImageButton lightControllerButton; @SuppressLint("InvalidWakeLockTag") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hcplay); Log.d(TAG, "onCreate: EZplayer Creating"); mEZPlayer1 = EZOpenSDK.getInstance().createPlayerWithUrl("https://hls01open.ys7.com/openlive/6e0b2be040a943489ef0b9bb344b96b8.hd.m3u8"); // SurfaceView mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview); // SurfaceHolder mSurfaceHolder1 = mSurfaceView1.getHolder(); // Log.d(TAG, "playViaDevSerial: 播放器绑定界面"+mEZPlayer1.setSurfaceHold(mSurfaceHolder1)); // mSurfaceHolder1.addCallback(this); // mEZPlayer=EZOpenSDK.getInstance().createPlayer("E40958484",1); // mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview); // mSurfaceHolder2 = mSurfaceView2.getHolder(); // mEZPlayer2.setSurfaceHold(mSurfaceHolder2); // mSurfaceHolder2.addCallback(this); /* mSurfaceView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (count++%2 == 0){ Log.d(TAG, "onClick: count"+count); mEZPlayer.stopRealPlay(); }else{ mEZPlayer.startRealPlay(); } } });*/ this.mContext = this; // rootView = getLayoutInflater().from(this).inflate(R.layout.activity_hcplay, null); // setContentView(rootView); // setContentView(R.layout.activity_main); ButterKnife.bind(this); // lightControllerButton=(ImageButton) findViewById(R.id.light); // lightControllerButton.setOnClickListener(this); buttonFront = (RadioButton) findViewById(R.id.front_Click); buttonBack = (RadioButton)findViewById(R.id.back_Click); buttonLeft = (RadioButton)findViewById(R.id.left_Click); buttonRight = (RadioButton)findViewById(R.id.right_Click); channelGodPerspective = (RadioButton)findViewById(R.id.god_perspective_Click); buttonFront.setOnClickListener(this); buttonBack.setOnClickListener(this); buttonLeft.setOnClickListener(this); buttonRight.setOnClickListener(this); channelGodPerspective.setOnClickListener(this); channels.put("Channel_Front",buttonFront); channels.put("Channel_Back",buttonBack); channels.put("Channel_Left",buttonLeft); channels.put("Channel_Right",buttonRight); channels.put("Channel_God_Perspective", channelGodPerspective); // // replyTextView=findViewById(R.id.replyTextView); // requestTextView=findViewById(R.id.requestTextView); /**常亮*/ PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG"); wakeLock.acquire(); // for(int i=1;i<7;i++){//for循環打開所有視頻流 // postVideoRequest(i,1);} videoRatioGroup = (MyRadioGroup)findViewById(R.id.radiogroup); videoRatioGroup.setOnCheckedChangeListener(new MyRadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(MyRadioGroup group, int checkedId) { switch (checkedId){ case R.id.left_Click: Log.d(TAG, "onCheckedChanged: 左视角"); playVideo(3); // try2play(3); break; case R.id.right_Click: playVideo(4); // try2play(4); break; case R.id.front_Click: playVideo(1); // try2play(0); break; case R.id.back_Click: playVideo(2); // try2play(2); break; case R.id.god_perspective_Click: playVideo(5); // try2play(5); break; default: Toast defualt =Toast.makeText(VideoEZplayer.this, "上帝", Toast.LENGTH_SHORT); new ShowMyToast().showMyToast(defualt,100); break; } } }); } /** * Post video request string * * @param videoNum video num 视频类型 * @param serviceType service type 1表示打开,0表示关闭 * @return the string */ public String postVideoRequest(final int videoNum, int serviceType){ videoRequest = new VideoRequest(); videoRequest.setUserId("6D"); videoRequest.setVin("test"); videoRequest.setVideo_type(Integer.toString(videoNum)); videoRequest.setServicetype(Integer.toString(serviceType)); final String videoRequestJson = JSON.toJSONString(videoRequest);//序列化 new Thread(new Runnable() { @Override public void run() { try { Log.d(TAG, "postVideoRequest: "+videoRequestJson); OkHttpClient videoClient=new OkHttpClient(); Request videoRequest= new Request.Builder() .url(hostURL+"videoRequest") .post(RequestBody.create(MediaType.parse("application/json"),videoRequestJson)) .build();//创造HTTP请求 //执行发送的指令 Response videoResponse = videoClient.newCall(videoRequest).execute(); Log.d(TAG, "run: 到了videoResponse"); if(videoNum!=6){ videoResponseString=videoResponse.body().string(); Log.d(TAG, "run: videoResponseString:"+videoResponseString); } else { mergeVideoString = videoResponse.body().string(); Log.d(TAG, "run: Merge"); } Log.d(TAG, "run: 返回结果"+videoNum+"路视频:\n"+videoResponseString+"\n"+mergeVideoString); }catch (Exception e){ e.printStackTrace(); Log.d("POST失敗", "onClick: "+e.toString()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(VideoEZplayer.this,"請求視頻失败!",Toast.LENGTH_LONG).show(); } }); } } }).start(); Log.d(TAG, "run: 返回结果"+videoNum+"路视频:\n"+videoResponseString); if (videoNum!=6){ return videoResponseString;} else { return mergeVideoString; } } public void playVideo(int videoNum){ if(videoPlayingNum==videoNum) { return; } switch (videoNum){ //E40958484 E40958558 E40958703 E40958817 右左前后序列号 case 0: break; case 1: //只播原始視頻 Log.d(TAG, "playVideo: 前视角"); // playViaDevSerial(testURL); playViaDevSerial("E40958703"); // playViaDevSerial("E40958703",mSurfaceHolder); // mEZPlayer1.stopRealPlay(); break; case 2: //后视角 playViaDevSerial("E40958817"); // surfaceCreated(mSurfaceHolder); break; case 3: //左视角 playViaDevSerial("D30723108"); // mEZPlayer1=EZOpenSDK.getInstance().createPlayer("E40958484",1); // mEZPlayer1.startRealPlay(); break; case 4: //右视角 playViaDevSerial("E40958484"); break; case 5: //上帝视角 // playViaDevSerial("231236707"); playViaDevSerial(testURL); // mEZPlayer1=EZOpenSDK.getInstance().createPlayerWithUrl("ezopen://open.ys7.com/C78957921/1.live"); break; case 6: //只有融合視頻 break; default: break; } videoPlayingNum=videoNum; } public void playViaDevSerial(final String deviceSerial){ SurfaceView mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview); SurfaceHolder mSurfaceHolder1 = mSurfaceView1.getHolder(); mEZPlayer1.release(); if(testURL.equals(deviceSerial)){ mEZPlayer1=EZOpenSDK.getInstance().createPlayerWithUrl(testURL);} else{ mEZPlayer1 = EZOpenSDK.getInstance().createPlayer(deviceSerial, 1); } Log.d(TAG, "playViaDevSerial: 播放器绑定界面"+mEZPlayer1.setSurfaceHold(mSurfaceHolder1)); mSurfaceHolder1.addCallback(this); Log.d(TAG, "playViaDevSerial: 播放器设备"+deviceSerial); // mEZPlayer1.setSurfaceHold(holder); // mEZPlayer.setHandler(mHandler); // holder.addCallback(this); Log.d(TAG, "playViaDevSerial: 播放成功?"+mEZPlayer1.startRealPlay()); } @Override protected void onPause() { super.onPause(); /**demo的内容,恢复系统其它媒体的状态*/ MediaUtils.muteAudioFocus(mContext, true); } @Override protected void onResume() { super.onResume(); /**demo的内容,暂停系统其它媒体的状态*/ MediaUtils.muteAudioFocus(mContext, false); /**demo的内容,激活设备常亮状态*/ if (wakeLock != null) { wakeLock.acquire(); } } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override public void onBackPressed() { super.onBackPressed(); /**demo的内容,恢复设备亮度状态*/ if (wakeLock != null) { wakeLock.release(); } } @Override public void onCheckedChanged(MyRadioGroup group, int checkedId) { } @Override public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "surfaceCreated: 播放器创建"); /*// mSurfaceHolder = holder; // Intent intent = getIntent(); // mEZPlayer1=EZOpenSDK.getInstance().createPlayer("231236707",1); // mEZPlayer=EZOpenSDK.getInstance().createPlayer("E40958484",1); mEZPlayer1.setSurfaceHold(holder); // mEZPlayer.setHandler(mHandler); mEZPlayer1.startRealPlay();*/ // mEZPlayer1.startRealPlay(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void onClick(View view) { } }
6D1996/zz_ijkplayer-master
app/src/main/java/com/dou361/jjdxm_ijkplayer/videomonitoring/VideoEZplayer.java
3,379
//后视角
line_comment
zh-cn
package com.dou361.jjdxm_ijkplayer.videomonitoring; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.os.CountDownTimer; import android.os.PowerManager; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.Toast; import androidx.annotation.NonNull; import com.alibaba.fastjson.JSON; import com.bumptech.glide.Glide; import com.dou361.jjdxm_ijkplayer.R; import com.dou361.jjdxm_ijkplayer.videomonitoring.utlis.MediaUtils; import com.videogo.exception.BaseException; import com.videogo.openapi.EZOpenSDK; import com.videogo.openapi.EZPlayer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import butterknife.ButterKnife; import butterknife.OnClick; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static android.content.ContentValues.TAG; public class VideoEZplayer extends Activity implements View.OnClickListener , MyRadioGroup.OnCheckedChangeListener ,SurfaceHolder.Callback{ EZPlayer mEZPlayer1; private int count = 0; public String hostURL="http://vehicleroadcloud.faw.cn:60443/backend/appBackend/"; private String testURL= // "ezopen://open.ys7.com/C78957921/1.live"; "ezopen://open.ys7.com/231236707/1.live"; public CountDownTimer countDownTimer; public VideoRequest videoRequest; public VideoReply videoReply,videoReply2; public String videoResponseString,mergeVideoString;//视频Post请求返回数据 private Context mContext; private PowerManager.WakeLock wakeLock; View rootView; private Integer videoPlayingNum=5; private MyRadioGroup videoRatioGroup; private RadioButton buttonFront, buttonBack, buttonLeft, buttonRight, channelGodPerspective; private HashMap<String, RadioButton> channels = new HashMap<>(5); private ImageButton lightControllerButton; @SuppressLint("InvalidWakeLockTag") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hcplay); Log.d(TAG, "onCreate: EZplayer Creating"); mEZPlayer1 = EZOpenSDK.getInstance().createPlayerWithUrl("https://hls01open.ys7.com/openlive/6e0b2be040a943489ef0b9bb344b96b8.hd.m3u8"); // SurfaceView mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview); // SurfaceHolder mSurfaceHolder1 = mSurfaceView1.getHolder(); // Log.d(TAG, "playViaDevSerial: 播放器绑定界面"+mEZPlayer1.setSurfaceHold(mSurfaceHolder1)); // mSurfaceHolder1.addCallback(this); // mEZPlayer=EZOpenSDK.getInstance().createPlayer("E40958484",1); // mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview); // mSurfaceHolder2 = mSurfaceView2.getHolder(); // mEZPlayer2.setSurfaceHold(mSurfaceHolder2); // mSurfaceHolder2.addCallback(this); /* mSurfaceView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (count++%2 == 0){ Log.d(TAG, "onClick: count"+count); mEZPlayer.stopRealPlay(); }else{ mEZPlayer.startRealPlay(); } } });*/ this.mContext = this; // rootView = getLayoutInflater().from(this).inflate(R.layout.activity_hcplay, null); // setContentView(rootView); // setContentView(R.layout.activity_main); ButterKnife.bind(this); // lightControllerButton=(ImageButton) findViewById(R.id.light); // lightControllerButton.setOnClickListener(this); buttonFront = (RadioButton) findViewById(R.id.front_Click); buttonBack = (RadioButton)findViewById(R.id.back_Click); buttonLeft = (RadioButton)findViewById(R.id.left_Click); buttonRight = (RadioButton)findViewById(R.id.right_Click); channelGodPerspective = (RadioButton)findViewById(R.id.god_perspective_Click); buttonFront.setOnClickListener(this); buttonBack.setOnClickListener(this); buttonLeft.setOnClickListener(this); buttonRight.setOnClickListener(this); channelGodPerspective.setOnClickListener(this); channels.put("Channel_Front",buttonFront); channels.put("Channel_Back",buttonBack); channels.put("Channel_Left",buttonLeft); channels.put("Channel_Right",buttonRight); channels.put("Channel_God_Perspective", channelGodPerspective); // // replyTextView=findViewById(R.id.replyTextView); // requestTextView=findViewById(R.id.requestTextView); /**常亮*/ PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG"); wakeLock.acquire(); // for(int i=1;i<7;i++){//for循環打開所有視頻流 // postVideoRequest(i,1);} videoRatioGroup = (MyRadioGroup)findViewById(R.id.radiogroup); videoRatioGroup.setOnCheckedChangeListener(new MyRadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(MyRadioGroup group, int checkedId) { switch (checkedId){ case R.id.left_Click: Log.d(TAG, "onCheckedChanged: 左视角"); playVideo(3); // try2play(3); break; case R.id.right_Click: playVideo(4); // try2play(4); break; case R.id.front_Click: playVideo(1); // try2play(0); break; case R.id.back_Click: playVideo(2); // try2play(2); break; case R.id.god_perspective_Click: playVideo(5); // try2play(5); break; default: Toast defualt =Toast.makeText(VideoEZplayer.this, "上帝", Toast.LENGTH_SHORT); new ShowMyToast().showMyToast(defualt,100); break; } } }); } /** * Post video request string * * @param videoNum video num 视频类型 * @param serviceType service type 1表示打开,0表示关闭 * @return the string */ public String postVideoRequest(final int videoNum, int serviceType){ videoRequest = new VideoRequest(); videoRequest.setUserId("6D"); videoRequest.setVin("test"); videoRequest.setVideo_type(Integer.toString(videoNum)); videoRequest.setServicetype(Integer.toString(serviceType)); final String videoRequestJson = JSON.toJSONString(videoRequest);//序列化 new Thread(new Runnable() { @Override public void run() { try { Log.d(TAG, "postVideoRequest: "+videoRequestJson); OkHttpClient videoClient=new OkHttpClient(); Request videoRequest= new Request.Builder() .url(hostURL+"videoRequest") .post(RequestBody.create(MediaType.parse("application/json"),videoRequestJson)) .build();//创造HTTP请求 //执行发送的指令 Response videoResponse = videoClient.newCall(videoRequest).execute(); Log.d(TAG, "run: 到了videoResponse"); if(videoNum!=6){ videoResponseString=videoResponse.body().string(); Log.d(TAG, "run: videoResponseString:"+videoResponseString); } else { mergeVideoString = videoResponse.body().string(); Log.d(TAG, "run: Merge"); } Log.d(TAG, "run: 返回结果"+videoNum+"路视频:\n"+videoResponseString+"\n"+mergeVideoString); }catch (Exception e){ e.printStackTrace(); Log.d("POST失敗", "onClick: "+e.toString()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(VideoEZplayer.this,"請求視頻失败!",Toast.LENGTH_LONG).show(); } }); } } }).start(); Log.d(TAG, "run: 返回结果"+videoNum+"路视频:\n"+videoResponseString); if (videoNum!=6){ return videoResponseString;} else { return mergeVideoString; } } public void playVideo(int videoNum){ if(videoPlayingNum==videoNum) { return; } switch (videoNum){ //E40958484 E40958558 E40958703 E40958817 右左前后序列号 case 0: break; case 1: //只播原始視頻 Log.d(TAG, "playVideo: 前视角"); // playViaDevSerial(testURL); playViaDevSerial("E40958703"); // playViaDevSerial("E40958703",mSurfaceHolder); // mEZPlayer1.stopRealPlay(); break; case 2: //后视 <SUF> playViaDevSerial("E40958817"); // surfaceCreated(mSurfaceHolder); break; case 3: //左视角 playViaDevSerial("D30723108"); // mEZPlayer1=EZOpenSDK.getInstance().createPlayer("E40958484",1); // mEZPlayer1.startRealPlay(); break; case 4: //右视角 playViaDevSerial("E40958484"); break; case 5: //上帝视角 // playViaDevSerial("231236707"); playViaDevSerial(testURL); // mEZPlayer1=EZOpenSDK.getInstance().createPlayerWithUrl("ezopen://open.ys7.com/C78957921/1.live"); break; case 6: //只有融合視頻 break; default: break; } videoPlayingNum=videoNum; } public void playViaDevSerial(final String deviceSerial){ SurfaceView mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview); SurfaceHolder mSurfaceHolder1 = mSurfaceView1.getHolder(); mEZPlayer1.release(); if(testURL.equals(deviceSerial)){ mEZPlayer1=EZOpenSDK.getInstance().createPlayerWithUrl(testURL);} else{ mEZPlayer1 = EZOpenSDK.getInstance().createPlayer(deviceSerial, 1); } Log.d(TAG, "playViaDevSerial: 播放器绑定界面"+mEZPlayer1.setSurfaceHold(mSurfaceHolder1)); mSurfaceHolder1.addCallback(this); Log.d(TAG, "playViaDevSerial: 播放器设备"+deviceSerial); // mEZPlayer1.setSurfaceHold(holder); // mEZPlayer.setHandler(mHandler); // holder.addCallback(this); Log.d(TAG, "playViaDevSerial: 播放成功?"+mEZPlayer1.startRealPlay()); } @Override protected void onPause() { super.onPause(); /**demo的内容,恢复系统其它媒体的状态*/ MediaUtils.muteAudioFocus(mContext, true); } @Override protected void onResume() { super.onResume(); /**demo的内容,暂停系统其它媒体的状态*/ MediaUtils.muteAudioFocus(mContext, false); /**demo的内容,激活设备常亮状态*/ if (wakeLock != null) { wakeLock.acquire(); } } @Override protected void onDestroy() { super.onDestroy(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override public void onBackPressed() { super.onBackPressed(); /**demo的内容,恢复设备亮度状态*/ if (wakeLock != null) { wakeLock.release(); } } @Override public void onCheckedChanged(MyRadioGroup group, int checkedId) { } @Override public void surfaceCreated(SurfaceHolder holder) { Log.d(TAG, "surfaceCreated: 播放器创建"); /*// mSurfaceHolder = holder; // Intent intent = getIntent(); // mEZPlayer1=EZOpenSDK.getInstance().createPlayer("231236707",1); // mEZPlayer=EZOpenSDK.getInstance().createPlayer("E40958484",1); mEZPlayer1.setSurfaceHold(holder); // mEZPlayer.setHandler(mHandler); mEZPlayer1.startRealPlay();*/ // mEZPlayer1.startRealPlay(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void onClick(View view) { } }
0
40213_5
package com.liefox.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class SignInfo { private int userid;//用户唯一id private int signid;//表单唯一id private int schoolid;//来自哪个学校 private String username;//用户名 private String temperature;//体温 private String address;//地址 private String date;//时间 private String qr_code_color;//健康码颜色 private String is_to_dongguan;//是否去过中高风险地区,之前写的是东莞,懒得改数据库了 }
6DDUU6/HealthCheck
src/main/java/com/liefox/pojo/SignInfo.java
149
//是否去过中高风险地区,之前写的是东莞,懒得改数据库了
line_comment
zh-cn
package com.liefox.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class SignInfo { private int userid;//用户唯一id private int signid;//表单唯一id private int schoolid;//来自哪个学校 private String username;//用户名 private String temperature;//体温 private String address;//地址 private String date;//时间 private String qr_code_color;//健康码颜色 private String is_to_dongguan;//是否 <SUF> }
0
64382_2
package com.kefu.netty.server; import com.kefu.netty.config.NettyProperties; import com.kefu.netty.initializer.TcpServerInitializer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; /** * 引导Netty服务器 * * @author feng * @date 2019-04-20 */ @Component public class TcpChatServer { private int port; public TcpChatServer(NettyProperties nettyProperties) { this.port = nettyProperties.getTcp().getPort(); } /** * 开始引导服务器 * 注意:不带 child 的是设置服务端的 Channel,带 child 的方法是设置每一条连接 */ public void start() { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap // 指定线程模型,这里是主从线程模型 .group(bossGroup, workerGroup) // 指定服务端的 Channel 的 I/O 模型 .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) // 指定处理新连接数据的读写处理逻辑:每次有新连接到来,都会去执行ChannelInitializer.initChannel(),并new一大堆handler。所以如果handler中无成员变量,则可写成单例 .childHandler(new TcpServerInitializer()); serverBootstrap.bind(port).addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { System.out.println("tcp端口绑定成功 port = " + port); } else { System.out.println("tcp端口绑定失败"); } }); } }
6ag/im-demo-netty-tcp-websocket
src/main/java/com/kefu/netty/server/TcpChatServer.java
507
// 指定线程模型,这里是主从线程模型
line_comment
zh-cn
package com.kefu.netty.server; import com.kefu.netty.config.NettyProperties; import com.kefu.netty.initializer.TcpServerInitializer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; /** * 引导Netty服务器 * * @author feng * @date 2019-04-20 */ @Component public class TcpChatServer { private int port; public TcpChatServer(NettyProperties nettyProperties) { this.port = nettyProperties.getTcp().getPort(); } /** * 开始引导服务器 * 注意:不带 child 的是设置服务端的 Channel,带 child 的方法是设置每一条连接 */ public void start() { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap // 指定 <SUF> .group(bossGroup, workerGroup) // 指定服务端的 Channel 的 I/O 模型 .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) // 指定处理新连接数据的读写处理逻辑:每次有新连接到来,都会去执行ChannelInitializer.initChannel(),并new一大堆handler。所以如果handler中无成员变量,则可写成单例 .childHandler(new TcpServerInitializer()); serverBootstrap.bind(port).addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { System.out.println("tcp端口绑定成功 port = " + port); } else { System.out.println("tcp端口绑定失败"); } }); } }
0
46823_5
package com.nlf.calendar; import com.nlf.calendar.util.LunarUtil; import com.nlf.calendar.util.ShouXingUtil; import java.util.ArrayList; import java.util.List; /** * 农历年 * * @author 6tail */ public class LunarYear { /** * 元 */ private static final String[] YUAN = {"下", "上", "中"}; /** * 运 */ private static final String[] YUN = {"七", "八", "九", "一", "二", "三", "四", "五", "六"}; /** * 闰冬月年份 */ private static final int[] LEAP_11 = {75, 94, 170, 265, 322, 398, 469, 553, 583, 610, 678, 735, 754, 773, 849, 887, 936, 1050, 1069, 1126, 1145, 1164, 1183, 1259, 1278, 1308, 1373, 1403, 1441, 1460, 1498, 1555, 1593, 1612, 1631, 1642, 2033, 2128, 2147, 2242, 2614, 2728, 2910, 3062, 3244, 3339, 3616, 3711, 3730, 3825, 4007, 4159, 4197, 4322, 4341, 4379, 4417, 4531, 4599, 4694, 4713, 4789, 4808, 4971, 5085, 5104, 5161, 5180, 5199, 5294, 5305, 5476, 5677, 5696, 5772, 5791, 5848, 5886, 6049, 6068, 6144, 6163, 6258, 6402, 6440, 6497, 6516, 6630, 6641, 6660, 6679, 6736, 6774, 6850, 6869, 6899, 6918, 6994, 7013, 7032, 7051, 7070, 7089, 7108, 7127, 7146, 7222, 7271, 7290, 7309, 7366, 7385, 7404, 7442, 7461, 7480, 7491, 7499, 7594, 7624, 7643, 7662, 7681, 7719, 7738, 7814, 7863, 7882, 7901, 7939, 7958, 7977, 7996, 8034, 8053, 8072, 8091, 8121, 8159, 8186, 8216, 8235, 8254, 8273, 8311, 8330, 8341, 8349, 8368, 8444, 8463, 8474, 8493, 8531, 8569, 8588, 8626, 8664, 8683, 8694, 8702, 8713, 8721, 8751, 8789, 8808, 8816, 8827, 8846, 8884, 8903, 8922, 8941, 8971, 9036, 9066, 9085, 9104, 9123, 9142, 9161, 9180, 9199, 9218, 9256, 9294, 9313, 9324, 9343, 9362, 9381, 9419, 9438, 9476, 9514, 9533, 9544, 9552, 9563, 9571, 9582, 9601, 9639, 9658, 9666, 9677, 9696, 9734, 9753, 9772, 9791, 9802, 9821, 9886, 9897, 9916, 9935, 9954, 9973, 9992}; /** * 闰腊月年份 */ private static final int[] LEAP_12 = {37, 56, 113, 132, 151, 189, 208, 227, 246, 284, 303, 341, 360, 379, 417, 436, 458, 477, 496, 515, 534, 572, 591, 629, 648, 667, 697, 716, 792, 811, 830, 868, 906, 925, 944, 963, 982, 1001, 1020, 1039, 1058, 1088, 1153, 1202, 1221, 1240, 1297, 1335, 1392, 1411, 1422, 1430, 1517, 1525, 1536, 1574, 3358, 3472, 3806, 3988, 4751, 4941, 5066, 5123, 5275, 5343, 5438, 5457, 5495, 5533, 5552, 5715, 5810, 5829, 5905, 5924, 6421, 6535, 6793, 6812, 6888, 6907, 7002, 7184, 7260, 7279, 7374, 7556, 7746, 7757, 7776, 7833, 7852, 7871, 7966, 8015, 8110, 8129, 8148, 8224, 8243, 8338, 8406, 8425, 8482, 8501, 8520, 8558, 8596, 8607, 8615, 8645, 8740, 8778, 8835, 8865, 8930, 8960, 8979, 8998, 9017, 9055, 9074, 9093, 9112, 9150, 9188, 9237, 9275, 9332, 9351, 9370, 9408, 9427, 9446, 9457, 9465, 9495, 9560, 9590, 9628, 9647, 9685, 9715, 9742, 9780, 9810, 9818, 9829, 9848, 9867, 9905, 9924, 9943, 9962, 10000}; private static final int[] YMC = {11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; private static LunarYear CACHE_YEAR = null; /** * 农历年 */ private final int year; /** * 天干下标 */ private final int ganIndex; /** * 地支下标 */ private final int zhiIndex; /** * 农历月们 */ private final List<LunarMonth> months = new ArrayList<LunarMonth>(); /** * 节气儒略日们 */ private final List<Double> jieQiJulianDays = new ArrayList<Double>(); /** * 初始化 * * @param lunarYear 农历年 */ public LunarYear(int lunarYear) { this.year = lunarYear; int offset = lunarYear - 4; int yearGanIndex = offset % 10; int yearZhiIndex = offset % 12; if (yearGanIndex < 0) { yearGanIndex += 10; } if (yearZhiIndex < 0) { yearZhiIndex += 12; } this.ganIndex = yearGanIndex; this.zhiIndex = yearZhiIndex; compute(); } private static boolean contains(int[] arr, int n) { for (int o : arr) { if (n == o) { return true; } } return false; } /** * 通过农历年初始化 * * @param lunarYear 农历年 * @return 农历年 */ public synchronized static LunarYear fromYear(int lunarYear) { LunarYear y; if (null == LunarYear.CACHE_YEAR || LunarYear.CACHE_YEAR.getYear() != lunarYear) { y = new LunarYear(lunarYear); LunarYear.CACHE_YEAR = y; } else { y = LunarYear.CACHE_YEAR; } return y; } private void compute() { // 节气 double[] jq = new double[27]; // 合朔,即每月初一 double[] hs = new double[16]; // 每月天数 int[] dayCounts = new int[15]; int[] months = new int[15]; int currentYear = this.year; double jd = Math.floor((currentYear - 2000) * 365.2422 + 180); // 355是2000.12冬至,得到较靠近jd的冬至估计值 double w = Math.floor((jd - 355 + 183) / 365.2422) * 365.2422 + 355; if (ShouXingUtil.calcQi(w) > jd) { w -= 365.2422; } // 25个节气时刻(北京时间),从冬至开始到下一个冬至以后 for (int i = 0; i < 26; i++) { jq[i] = ShouXingUtil.calcQi(w + 15.2184 * i); } // 从上年的大雪到下年的立春 for (int i = 0, j = Lunar.JIE_QI_IN_USE.length; i < j; i++) { if (i == 0) { jd = ShouXingUtil.qiAccurate2(jq[0] - 15.2184); } else if (i <= 26) { jd = ShouXingUtil.qiAccurate2(jq[i - 1]); } else { jd = ShouXingUtil.qiAccurate2(jq[25] + 15.2184 * (i - 26)); } jieQiJulianDays.add(jd + Solar.J2000); } // 冬至前的初一,今年"首朔"的日月黄经差w w = ShouXingUtil.calcShuo(jq[0]); if (w > jq[0]) { w -= 29.53; } // 递推每月初一 for (int i = 0; i < 16; i++) { hs[i] = ShouXingUtil.calcShuo(w + 29.5306 * i); } // 每月 for (int i = 0; i < 15; i++) { dayCounts[i] = (int)(hs[i + 1] - hs[i]); months[i] = i; } int prevYear = currentYear - 1; int leapIndex = 16; if (contains(LEAP_11, currentYear)) { leapIndex = 13; } else if (contains(LEAP_12, currentYear)) { leapIndex = 14; } else if (hs[13] <= jq[24]) { int i = 1; while (hs[i + 1] > jq[2 * i] && i < 13) { i++; } leapIndex = i; } for (int i = leapIndex; i < 15; i++) { months[i] -= 1; } int fm = -1; int index = -1; int y = prevYear; for (int i = 0; i < 15; i++) { double dm = hs[i] + Solar.J2000; int v2 = months[i]; int mc = YMC[v2 % 12]; if (1724360 <= dm && dm < 1729794) { mc = YMC[(v2 + 1) % 12]; } else if (1807724 <= dm && dm < 1808699) { mc = YMC[(v2 + 1) % 12]; } else if (dm == 1729794 || dm == 1808699) { mc = 12; } if (fm == -1) { fm = mc; index = mc; } if (mc < fm) { y += 1; index = 1; } fm = mc; if (i == leapIndex) { mc = -mc; } else if (dm == 1729794 || dm == 1808699) { mc = -11; } this.months.add(new LunarMonth(y, mc, dayCounts[i], hs[i] + Solar.J2000, index)); index++; } } /** * 获取农历年 * * @return 农历年 */ public int getYear() { return year; } /** * 获取总天数 * @return 天数 */ public int getDayCount() { int n = 0; for (LunarMonth m : months) { if (m.getYear() == year) { n += m.getDayCount(); } } return n; } /** * 获取当年的农历月们 * * @return 农历月们 */ public List<LunarMonth> getMonthsInYear() { List<LunarMonth> l = new ArrayList<LunarMonth>(); for (LunarMonth m : months) { if (m.getYear() == year) { l.add(m); } } return l; } /** * 获取农历月们 * * @return 农历月们 */ public List<LunarMonth> getMonths() { return months; } /** * 获取节气儒略日们 * * @return 节气儒略日们 */ public List<Double> getJieQiJulianDays() { return jieQiJulianDays; } /** * 获取天干序号,从0开始 * * @return 序号 */ public int getGanIndex() { return ganIndex; } /** * 获取地支序号,从0开始 * * @return 序号 */ public int getZhiIndex() { return zhiIndex; } /** * 获取天干 * * @return 天干 */ public String getGan() { return LunarUtil.GAN[ganIndex + 1]; } /** * 获取地支 * * @return 地支 */ public String getZhi() { return LunarUtil.ZHI[zhiIndex + 1]; } /** * 获取干支 * * @return 干支 */ public String getGanZhi() { return getGan() + getZhi(); } /** * 获取农历月 * * @param lunarMonth 月,1-12,闰月为负数,如闰2月为-2 * @return 农历月 */ public LunarMonth getMonth(int lunarMonth) { for (LunarMonth m : months) { if (m.getYear() == year && m.getMonth() == lunarMonth) { return m; } } return null; } /** * 获取闰月 * * @return 闰月数字,1代表闰1月,0代表无闰月 */ public int getLeapMonth() { for (LunarMonth m : months) { if (m.getYear() == year && m.isLeap()) { return Math.abs(m.getMonth()); } } return 0; } protected String getZaoByGan(int index, String name) { int offset = index - Solar.fromJulianDay(getMonth(1).getFirstJulianDay()).getLunar().getDayGanIndex(); if (offset < 0) { offset += 10; } return name.replaceFirst("几", LunarUtil.NUMBER[offset + 1]); } protected String getZaoByZhi(int index, String name) { int offset = index - Solar.fromJulianDay(getMonth(1).getFirstJulianDay()).getLunar().getDayZhiIndex(); if (offset < 0) { offset += 12; } return name.replaceFirst("几", LunarUtil.NUMBER[offset + 1]); } /** * 获取几鼠偷粮 * * @return 几鼠偷粮 */ public String getTouLiang() { return getZaoByZhi(0, "几鼠偷粮"); } /** * 获取草子几分 * * @return 草子几分 */ public String getCaoZi() { return getZaoByZhi(0, "草子几分"); } /** * 获取耕田(正月第一个丑日是初几,就是几牛耕田) * * @return 耕田,如:六牛耕田 */ public String getGengTian() { return getZaoByZhi(1, "几牛耕田"); } /** * 获取花收几分 * * @return 花收几分 */ public String getHuaShou() { return getZaoByZhi(3, "花收几分"); } /** * 获取治水(正月第一个辰日是初几,就是几龙治水) * * @return 治水,如:二龙治水 */ public String getZhiShui() { return getZaoByZhi(4, "几龙治水"); } /** * 获取几马驮谷 * * @return 几马驮谷 */ public String getTuoGu() { return getZaoByZhi(6, "几马驮谷"); } /** * 获取几鸡抢米 * * @return 几鸡抢米 */ public String getQiangMi() { return getZaoByZhi(9, "几鸡抢米"); } /** * 获取几姑看蚕 * * @return 几姑看蚕 */ public String getKanCan() { return getZaoByZhi(9, "几姑看蚕"); } /** * 获取几屠共猪 * * @return 几屠共猪 */ public String getGongZhu() { return getZaoByZhi(11, "几屠共猪"); } /** * 获取甲田几分 * * @return 甲田几分 */ public String getJiaTian() { return getZaoByGan(0, "甲田几分"); } /** * 获取分饼(正月第一个丙日是初几,就是几人分饼) * * @return 分饼,如:六人分饼 */ public String getFenBing() { return getZaoByGan(2, "几人分饼"); } /** * 获取得金(正月第一个辛日是初几,就是几日得金) * * @return 得金,如:一日得金 */ public String getDeJin() { return getZaoByGan(7, "几日得金"); } /** * 获取几人几丙 * * @return 几人几丙 */ public String getRenBing() { return getZaoByGan(2, getZaoByZhi(2, "几人几丙")); } /** * 获取几人几锄 * * @return 几人几锄 */ public String getRenChu() { return getZaoByGan(3, getZaoByZhi(2, "几人几锄")); } /** * 获取三元 * * @return 元 */ public String getYuan() { return YUAN[((year + 2696) / 60) % 3] + "元"; } /** * 获取九运 * * @return 运 */ public String getYun() { return YUN[((year + 2696) / 20) % 9] + "运"; } /** * 获取九星 * * @return 九星 */ public NineStar getNineStar() { int index = LunarUtil.getJiaZiIndex(getGanZhi()) + 1; int yuan = ((this.year + 2696) / 60) % 3; int offset = (62 + yuan * 3 - index) % 9; if (0 == offset) { offset = 9; } return NineStar.fromIndex(offset - 1); } /** * 获取喜神方位 * * @return 方位,如艮 */ public String getPositionXi() { return LunarUtil.POSITION_XI[ganIndex + 1]; } /** * 获取喜神方位描述 * * @return 方位描述,如东北 */ public String getPositionXiDesc() { return LunarUtil.POSITION_DESC.get(getPositionXi()); } /** * 获取阳贵神方位 * * @return 方位,如艮 */ public String getPositionYangGui() { return LunarUtil.POSITION_YANG_GUI[ganIndex + 1]; } /** * 获取阳贵神方位描述 * * @return 方位描述,如东北 */ public String getPositionYangGuiDesc() { return LunarUtil.POSITION_DESC.get(getPositionYangGui()); } /** * 获取阴贵神方位 * * @return 方位,如艮 */ public String getPositionYinGui() { return LunarUtil.POSITION_YIN_GUI[ganIndex + 1]; } /** * 获取阴贵神方位描述 * * @return 方位描述,如东北 */ public String getPositionYinGuiDesc() { return LunarUtil.POSITION_DESC.get(getPositionYinGui()); } /** * 获取福神方位(默认流派:2) * * @return 方位,如艮 */ public String getPositionFu() { return getPositionFu(2); } /** * 获取福神方位 * * @param sect 流派,1或2 * @return 方位,如艮 */ public String getPositionFu(int sect) { return (1 == sect ? LunarUtil.POSITION_FU : LunarUtil.POSITION_FU_2)[ganIndex + 1]; } /** * 获取福神方位描述(默认流派:2) * * @return 方位描述,如东北 */ public String getPositionFuDesc() { return getPositionFuDesc(2); } /** * 获取福神方位描述 * * @param sect 流派,1或2 * @return 方位描述,如东北 */ public String getPositionFuDesc(int sect) { return LunarUtil.POSITION_DESC.get(getPositionFu(sect)); } /** * 获取财神方位 * * @return 财神方位,如艮 */ public String getPositionCai() { return LunarUtil.POSITION_CAI[ganIndex + 1]; } /** * 获取财神方位描述 * * @return 方位描述,如东北 */ public String getPositionCaiDesc() { return LunarUtil.POSITION_DESC.get(getPositionCai()); } /** * 获取太岁方位 * * @return 方位,如艮 */ public String getPositionTaiSui() { return LunarUtil.POSITION_TAI_SUI_YEAR[zhiIndex]; } /** * 获取太岁方位描述 * * @return 方位描述,如东北 */ public String getPositionTaiSuiDesc() { return LunarUtil.POSITION_DESC.get(getPositionTaiSui()); } @Override public String toString() { return year + ""; } public String toFullString() { return year + "年"; } /** * 获取往后推几年的阴历年,如果要往前推,则年数用负数 * * @param n 年数 * @return 阴历年 */ public LunarYear next(int n) { return LunarYear.fromYear(year + n); } }
6tail/lunar-java
src/main/java/com/nlf/calendar/LunarYear.java
7,077
/** * 农历年 */
block_comment
zh-cn
package com.nlf.calendar; import com.nlf.calendar.util.LunarUtil; import com.nlf.calendar.util.ShouXingUtil; import java.util.ArrayList; import java.util.List; /** * 农历年 * * @author 6tail */ public class LunarYear { /** * 元 */ private static final String[] YUAN = {"下", "上", "中"}; /** * 运 */ private static final String[] YUN = {"七", "八", "九", "一", "二", "三", "四", "五", "六"}; /** * 闰冬月年份 */ private static final int[] LEAP_11 = {75, 94, 170, 265, 322, 398, 469, 553, 583, 610, 678, 735, 754, 773, 849, 887, 936, 1050, 1069, 1126, 1145, 1164, 1183, 1259, 1278, 1308, 1373, 1403, 1441, 1460, 1498, 1555, 1593, 1612, 1631, 1642, 2033, 2128, 2147, 2242, 2614, 2728, 2910, 3062, 3244, 3339, 3616, 3711, 3730, 3825, 4007, 4159, 4197, 4322, 4341, 4379, 4417, 4531, 4599, 4694, 4713, 4789, 4808, 4971, 5085, 5104, 5161, 5180, 5199, 5294, 5305, 5476, 5677, 5696, 5772, 5791, 5848, 5886, 6049, 6068, 6144, 6163, 6258, 6402, 6440, 6497, 6516, 6630, 6641, 6660, 6679, 6736, 6774, 6850, 6869, 6899, 6918, 6994, 7013, 7032, 7051, 7070, 7089, 7108, 7127, 7146, 7222, 7271, 7290, 7309, 7366, 7385, 7404, 7442, 7461, 7480, 7491, 7499, 7594, 7624, 7643, 7662, 7681, 7719, 7738, 7814, 7863, 7882, 7901, 7939, 7958, 7977, 7996, 8034, 8053, 8072, 8091, 8121, 8159, 8186, 8216, 8235, 8254, 8273, 8311, 8330, 8341, 8349, 8368, 8444, 8463, 8474, 8493, 8531, 8569, 8588, 8626, 8664, 8683, 8694, 8702, 8713, 8721, 8751, 8789, 8808, 8816, 8827, 8846, 8884, 8903, 8922, 8941, 8971, 9036, 9066, 9085, 9104, 9123, 9142, 9161, 9180, 9199, 9218, 9256, 9294, 9313, 9324, 9343, 9362, 9381, 9419, 9438, 9476, 9514, 9533, 9544, 9552, 9563, 9571, 9582, 9601, 9639, 9658, 9666, 9677, 9696, 9734, 9753, 9772, 9791, 9802, 9821, 9886, 9897, 9916, 9935, 9954, 9973, 9992}; /** * 闰腊月年份 */ private static final int[] LEAP_12 = {37, 56, 113, 132, 151, 189, 208, 227, 246, 284, 303, 341, 360, 379, 417, 436, 458, 477, 496, 515, 534, 572, 591, 629, 648, 667, 697, 716, 792, 811, 830, 868, 906, 925, 944, 963, 982, 1001, 1020, 1039, 1058, 1088, 1153, 1202, 1221, 1240, 1297, 1335, 1392, 1411, 1422, 1430, 1517, 1525, 1536, 1574, 3358, 3472, 3806, 3988, 4751, 4941, 5066, 5123, 5275, 5343, 5438, 5457, 5495, 5533, 5552, 5715, 5810, 5829, 5905, 5924, 6421, 6535, 6793, 6812, 6888, 6907, 7002, 7184, 7260, 7279, 7374, 7556, 7746, 7757, 7776, 7833, 7852, 7871, 7966, 8015, 8110, 8129, 8148, 8224, 8243, 8338, 8406, 8425, 8482, 8501, 8520, 8558, 8596, 8607, 8615, 8645, 8740, 8778, 8835, 8865, 8930, 8960, 8979, 8998, 9017, 9055, 9074, 9093, 9112, 9150, 9188, 9237, 9275, 9332, 9351, 9370, 9408, 9427, 9446, 9457, 9465, 9495, 9560, 9590, 9628, 9647, 9685, 9715, 9742, 9780, 9810, 9818, 9829, 9848, 9867, 9905, 9924, 9943, 9962, 10000}; private static final int[] YMC = {11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; private static LunarYear CACHE_YEAR = null; /** * 农历年 <SUF>*/ private final int year; /** * 天干下标 */ private final int ganIndex; /** * 地支下标 */ private final int zhiIndex; /** * 农历月们 */ private final List<LunarMonth> months = new ArrayList<LunarMonth>(); /** * 节气儒略日们 */ private final List<Double> jieQiJulianDays = new ArrayList<Double>(); /** * 初始化 * * @param lunarYear 农历年 */ public LunarYear(int lunarYear) { this.year = lunarYear; int offset = lunarYear - 4; int yearGanIndex = offset % 10; int yearZhiIndex = offset % 12; if (yearGanIndex < 0) { yearGanIndex += 10; } if (yearZhiIndex < 0) { yearZhiIndex += 12; } this.ganIndex = yearGanIndex; this.zhiIndex = yearZhiIndex; compute(); } private static boolean contains(int[] arr, int n) { for (int o : arr) { if (n == o) { return true; } } return false; } /** * 通过农历年初始化 * * @param lunarYear 农历年 * @return 农历年 */ public synchronized static LunarYear fromYear(int lunarYear) { LunarYear y; if (null == LunarYear.CACHE_YEAR || LunarYear.CACHE_YEAR.getYear() != lunarYear) { y = new LunarYear(lunarYear); LunarYear.CACHE_YEAR = y; } else { y = LunarYear.CACHE_YEAR; } return y; } private void compute() { // 节气 double[] jq = new double[27]; // 合朔,即每月初一 double[] hs = new double[16]; // 每月天数 int[] dayCounts = new int[15]; int[] months = new int[15]; int currentYear = this.year; double jd = Math.floor((currentYear - 2000) * 365.2422 + 180); // 355是2000.12冬至,得到较靠近jd的冬至估计值 double w = Math.floor((jd - 355 + 183) / 365.2422) * 365.2422 + 355; if (ShouXingUtil.calcQi(w) > jd) { w -= 365.2422; } // 25个节气时刻(北京时间),从冬至开始到下一个冬至以后 for (int i = 0; i < 26; i++) { jq[i] = ShouXingUtil.calcQi(w + 15.2184 * i); } // 从上年的大雪到下年的立春 for (int i = 0, j = Lunar.JIE_QI_IN_USE.length; i < j; i++) { if (i == 0) { jd = ShouXingUtil.qiAccurate2(jq[0] - 15.2184); } else if (i <= 26) { jd = ShouXingUtil.qiAccurate2(jq[i - 1]); } else { jd = ShouXingUtil.qiAccurate2(jq[25] + 15.2184 * (i - 26)); } jieQiJulianDays.add(jd + Solar.J2000); } // 冬至前的初一,今年"首朔"的日月黄经差w w = ShouXingUtil.calcShuo(jq[0]); if (w > jq[0]) { w -= 29.53; } // 递推每月初一 for (int i = 0; i < 16; i++) { hs[i] = ShouXingUtil.calcShuo(w + 29.5306 * i); } // 每月 for (int i = 0; i < 15; i++) { dayCounts[i] = (int)(hs[i + 1] - hs[i]); months[i] = i; } int prevYear = currentYear - 1; int leapIndex = 16; if (contains(LEAP_11, currentYear)) { leapIndex = 13; } else if (contains(LEAP_12, currentYear)) { leapIndex = 14; } else if (hs[13] <= jq[24]) { int i = 1; while (hs[i + 1] > jq[2 * i] && i < 13) { i++; } leapIndex = i; } for (int i = leapIndex; i < 15; i++) { months[i] -= 1; } int fm = -1; int index = -1; int y = prevYear; for (int i = 0; i < 15; i++) { double dm = hs[i] + Solar.J2000; int v2 = months[i]; int mc = YMC[v2 % 12]; if (1724360 <= dm && dm < 1729794) { mc = YMC[(v2 + 1) % 12]; } else if (1807724 <= dm && dm < 1808699) { mc = YMC[(v2 + 1) % 12]; } else if (dm == 1729794 || dm == 1808699) { mc = 12; } if (fm == -1) { fm = mc; index = mc; } if (mc < fm) { y += 1; index = 1; } fm = mc; if (i == leapIndex) { mc = -mc; } else if (dm == 1729794 || dm == 1808699) { mc = -11; } this.months.add(new LunarMonth(y, mc, dayCounts[i], hs[i] + Solar.J2000, index)); index++; } } /** * 获取农历年 * * @return 农历年 */ public int getYear() { return year; } /** * 获取总天数 * @return 天数 */ public int getDayCount() { int n = 0; for (LunarMonth m : months) { if (m.getYear() == year) { n += m.getDayCount(); } } return n; } /** * 获取当年的农历月们 * * @return 农历月们 */ public List<LunarMonth> getMonthsInYear() { List<LunarMonth> l = new ArrayList<LunarMonth>(); for (LunarMonth m : months) { if (m.getYear() == year) { l.add(m); } } return l; } /** * 获取农历月们 * * @return 农历月们 */ public List<LunarMonth> getMonths() { return months; } /** * 获取节气儒略日们 * * @return 节气儒略日们 */ public List<Double> getJieQiJulianDays() { return jieQiJulianDays; } /** * 获取天干序号,从0开始 * * @return 序号 */ public int getGanIndex() { return ganIndex; } /** * 获取地支序号,从0开始 * * @return 序号 */ public int getZhiIndex() { return zhiIndex; } /** * 获取天干 * * @return 天干 */ public String getGan() { return LunarUtil.GAN[ganIndex + 1]; } /** * 获取地支 * * @return 地支 */ public String getZhi() { return LunarUtil.ZHI[zhiIndex + 1]; } /** * 获取干支 * * @return 干支 */ public String getGanZhi() { return getGan() + getZhi(); } /** * 获取农历月 * * @param lunarMonth 月,1-12,闰月为负数,如闰2月为-2 * @return 农历月 */ public LunarMonth getMonth(int lunarMonth) { for (LunarMonth m : months) { if (m.getYear() == year && m.getMonth() == lunarMonth) { return m; } } return null; } /** * 获取闰月 * * @return 闰月数字,1代表闰1月,0代表无闰月 */ public int getLeapMonth() { for (LunarMonth m : months) { if (m.getYear() == year && m.isLeap()) { return Math.abs(m.getMonth()); } } return 0; } protected String getZaoByGan(int index, String name) { int offset = index - Solar.fromJulianDay(getMonth(1).getFirstJulianDay()).getLunar().getDayGanIndex(); if (offset < 0) { offset += 10; } return name.replaceFirst("几", LunarUtil.NUMBER[offset + 1]); } protected String getZaoByZhi(int index, String name) { int offset = index - Solar.fromJulianDay(getMonth(1).getFirstJulianDay()).getLunar().getDayZhiIndex(); if (offset < 0) { offset += 12; } return name.replaceFirst("几", LunarUtil.NUMBER[offset + 1]); } /** * 获取几鼠偷粮 * * @return 几鼠偷粮 */ public String getTouLiang() { return getZaoByZhi(0, "几鼠偷粮"); } /** * 获取草子几分 * * @return 草子几分 */ public String getCaoZi() { return getZaoByZhi(0, "草子几分"); } /** * 获取耕田(正月第一个丑日是初几,就是几牛耕田) * * @return 耕田,如:六牛耕田 */ public String getGengTian() { return getZaoByZhi(1, "几牛耕田"); } /** * 获取花收几分 * * @return 花收几分 */ public String getHuaShou() { return getZaoByZhi(3, "花收几分"); } /** * 获取治水(正月第一个辰日是初几,就是几龙治水) * * @return 治水,如:二龙治水 */ public String getZhiShui() { return getZaoByZhi(4, "几龙治水"); } /** * 获取几马驮谷 * * @return 几马驮谷 */ public String getTuoGu() { return getZaoByZhi(6, "几马驮谷"); } /** * 获取几鸡抢米 * * @return 几鸡抢米 */ public String getQiangMi() { return getZaoByZhi(9, "几鸡抢米"); } /** * 获取几姑看蚕 * * @return 几姑看蚕 */ public String getKanCan() { return getZaoByZhi(9, "几姑看蚕"); } /** * 获取几屠共猪 * * @return 几屠共猪 */ public String getGongZhu() { return getZaoByZhi(11, "几屠共猪"); } /** * 获取甲田几分 * * @return 甲田几分 */ public String getJiaTian() { return getZaoByGan(0, "甲田几分"); } /** * 获取分饼(正月第一个丙日是初几,就是几人分饼) * * @return 分饼,如:六人分饼 */ public String getFenBing() { return getZaoByGan(2, "几人分饼"); } /** * 获取得金(正月第一个辛日是初几,就是几日得金) * * @return 得金,如:一日得金 */ public String getDeJin() { return getZaoByGan(7, "几日得金"); } /** * 获取几人几丙 * * @return 几人几丙 */ public String getRenBing() { return getZaoByGan(2, getZaoByZhi(2, "几人几丙")); } /** * 获取几人几锄 * * @return 几人几锄 */ public String getRenChu() { return getZaoByGan(3, getZaoByZhi(2, "几人几锄")); } /** * 获取三元 * * @return 元 */ public String getYuan() { return YUAN[((year + 2696) / 60) % 3] + "元"; } /** * 获取九运 * * @return 运 */ public String getYun() { return YUN[((year + 2696) / 20) % 9] + "运"; } /** * 获取九星 * * @return 九星 */ public NineStar getNineStar() { int index = LunarUtil.getJiaZiIndex(getGanZhi()) + 1; int yuan = ((this.year + 2696) / 60) % 3; int offset = (62 + yuan * 3 - index) % 9; if (0 == offset) { offset = 9; } return NineStar.fromIndex(offset - 1); } /** * 获取喜神方位 * * @return 方位,如艮 */ public String getPositionXi() { return LunarUtil.POSITION_XI[ganIndex + 1]; } /** * 获取喜神方位描述 * * @return 方位描述,如东北 */ public String getPositionXiDesc() { return LunarUtil.POSITION_DESC.get(getPositionXi()); } /** * 获取阳贵神方位 * * @return 方位,如艮 */ public String getPositionYangGui() { return LunarUtil.POSITION_YANG_GUI[ganIndex + 1]; } /** * 获取阳贵神方位描述 * * @return 方位描述,如东北 */ public String getPositionYangGuiDesc() { return LunarUtil.POSITION_DESC.get(getPositionYangGui()); } /** * 获取阴贵神方位 * * @return 方位,如艮 */ public String getPositionYinGui() { return LunarUtil.POSITION_YIN_GUI[ganIndex + 1]; } /** * 获取阴贵神方位描述 * * @return 方位描述,如东北 */ public String getPositionYinGuiDesc() { return LunarUtil.POSITION_DESC.get(getPositionYinGui()); } /** * 获取福神方位(默认流派:2) * * @return 方位,如艮 */ public String getPositionFu() { return getPositionFu(2); } /** * 获取福神方位 * * @param sect 流派,1或2 * @return 方位,如艮 */ public String getPositionFu(int sect) { return (1 == sect ? LunarUtil.POSITION_FU : LunarUtil.POSITION_FU_2)[ganIndex + 1]; } /** * 获取福神方位描述(默认流派:2) * * @return 方位描述,如东北 */ public String getPositionFuDesc() { return getPositionFuDesc(2); } /** * 获取福神方位描述 * * @param sect 流派,1或2 * @return 方位描述,如东北 */ public String getPositionFuDesc(int sect) { return LunarUtil.POSITION_DESC.get(getPositionFu(sect)); } /** * 获取财神方位 * * @return 财神方位,如艮 */ public String getPositionCai() { return LunarUtil.POSITION_CAI[ganIndex + 1]; } /** * 获取财神方位描述 * * @return 方位描述,如东北 */ public String getPositionCaiDesc() { return LunarUtil.POSITION_DESC.get(getPositionCai()); } /** * 获取太岁方位 * * @return 方位,如艮 */ public String getPositionTaiSui() { return LunarUtil.POSITION_TAI_SUI_YEAR[zhiIndex]; } /** * 获取太岁方位描述 * * @return 方位描述,如东北 */ public String getPositionTaiSuiDesc() { return LunarUtil.POSITION_DESC.get(getPositionTaiSui()); } @Override public String toString() { return year + ""; } public String toFullString() { return year + "年"; } /** * 获取往后推几年的阴历年,如果要往前推,则年数用负数 * * @param n 年数 * @return 阴历年 */ public LunarYear next(int n) { return LunarYear.fromYear(year + n); } }
1
54700_2
package org.superboot.config.datasource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.superboot.base.BaseConstants; import javax.persistence.EntityManagerFactory; /** * <b> 读写分离配置及事务管理 </b> * <p> * 功能描述:提供事务支持及读写分离等操作支持 * </p> */ @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "org.superboot.dao.jpa", entityManagerFactoryRef = "dataEntityManagerFactory", transactionManagerRef = "dataTransactionManager") public class DataSourceTransactionConfig { @Autowired private JpaProperties jpaProperties; @Autowired @Qualifier("routingDataSource") private AbstractRoutingDataSource dataSource; /** * 我们通过LocalContainerEntityManagerFactoryBean来获取EntityManagerFactory实例 * * @return */ @Bean(name = "dataEntityManagerFactoryBean") public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) { return builder .dataSource(dataSource) .properties(jpaProperties.getProperties()) //设置实体类所在位置 .packages("org.superboot.entity.jpa") .persistenceUnit("dataPersistenceUnit") .build(); } /** * EntityManagerFactory类似于Hibernate的SessionFactory,mybatis的SqlSessionFactory * 总之,在执行操作之前,我们总要获取一个EntityManager,这就类似于Hibernate的Session, * mybatis的sqlSession. * * @param builder * @return */ @Bean(name = "dataEntityManagerFactory") @Primary public EntityManagerFactory entityManagerFactory(EntityManagerFactoryBuilder builder) { return this.entityManagerFactoryBean(builder).getObject(); } /** * 配置事物管理器 * * @return */ @Bean(name = "dataTransactionManager") @Primary public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactory(builder)); } }
7040210/SuperBoot
super-boot-global/src/main/java/org/superboot/config/datasource/DataSourceTransactionConfig.java
627
//设置实体类所在位置
line_comment
zh-cn
package org.superboot.config.datasource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.superboot.base.BaseConstants; import javax.persistence.EntityManagerFactory; /** * <b> 读写分离配置及事务管理 </b> * <p> * 功能描述:提供事务支持及读写分离等操作支持 * </p> */ @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "org.superboot.dao.jpa", entityManagerFactoryRef = "dataEntityManagerFactory", transactionManagerRef = "dataTransactionManager") public class DataSourceTransactionConfig { @Autowired private JpaProperties jpaProperties; @Autowired @Qualifier("routingDataSource") private AbstractRoutingDataSource dataSource; /** * 我们通过LocalContainerEntityManagerFactoryBean来获取EntityManagerFactory实例 * * @return */ @Bean(name = "dataEntityManagerFactoryBean") public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) { return builder .dataSource(dataSource) .properties(jpaProperties.getProperties()) //设置 <SUF> .packages("org.superboot.entity.jpa") .persistenceUnit("dataPersistenceUnit") .build(); } /** * EntityManagerFactory类似于Hibernate的SessionFactory,mybatis的SqlSessionFactory * 总之,在执行操作之前,我们总要获取一个EntityManager,这就类似于Hibernate的Session, * mybatis的sqlSession. * * @param builder * @return */ @Bean(name = "dataEntityManagerFactory") @Primary public EntityManagerFactory entityManagerFactory(EntityManagerFactoryBuilder builder) { return this.entityManagerFactoryBean(builder).getObject(); } /** * 配置事物管理器 * * @return */ @Bean(name = "dataTransactionManager") @Primary public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactory(builder)); } }
0
57653_2
package com.com.mr_wrong.Socket; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import com.Utils.LogUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Random; /** * Created by Mr_Wrong on 15/9/30. */ public class TCPServerService extends Service { private boolean mIsServiceDestoryed = false; private String[] mDefinedMessages = new String[]{"你好啊", "buhao", "哈哈哈", "呵呵", "笔笔什么呢"}; @Override public void onCreate() { new Thread(new TcpService()).start(); super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); mIsServiceDestoryed = true; } @Nullable @Override public IBinder onBind(Intent intent) { return null; } private class TcpService implements Runnable { @Override public void run() { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8688); } catch (IOException e) { LogUtils.d("zhao'bu'd找不到8688端口玩个毛"); e.printStackTrace(); } while (!mIsServiceDestoryed) { try { final Socket client = serverSocket.accept(); LogUtils.e("接受到了"); new Thread() { @Override public void run() { try { responseClient(client); } catch (IOException e) { e.printStackTrace(); } } }.start(); } catch (IOException e) { e.printStackTrace(); } } } } private void responseClient(Socket client) throws IOException { //读取客户端消息 BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); //发送消息给客户端 PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(client.getOutputStream())), true); out.println("欢迎啊 小伙子"); while (!mIsServiceDestoryed) { String str = in.readLine(); LogUtils.e("来自客户端的消息" + str); if (str == null) { break;//断开连接 } int i = new Random().nextInt(mDefinedMessages.length); String msg = mDefinedMessages[i]; out.println(msg); LogUtils.e("服务器发送消息了:" + msg); } LogUtils.e("客户端退出了"); if (in != null) in.close(); if (out != null) out.close(); client.close(); } }
70kg/Android-Studio-Project
app/src/main/java/com/com/mr_wrong/Socket/TCPServerService.java
683
//发送消息给客户端
line_comment
zh-cn
package com.com.mr_wrong.Socket; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import com.Utils.LogUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Random; /** * Created by Mr_Wrong on 15/9/30. */ public class TCPServerService extends Service { private boolean mIsServiceDestoryed = false; private String[] mDefinedMessages = new String[]{"你好啊", "buhao", "哈哈哈", "呵呵", "笔笔什么呢"}; @Override public void onCreate() { new Thread(new TcpService()).start(); super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); mIsServiceDestoryed = true; } @Nullable @Override public IBinder onBind(Intent intent) { return null; } private class TcpService implements Runnable { @Override public void run() { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8688); } catch (IOException e) { LogUtils.d("zhao'bu'd找不到8688端口玩个毛"); e.printStackTrace(); } while (!mIsServiceDestoryed) { try { final Socket client = serverSocket.accept(); LogUtils.e("接受到了"); new Thread() { @Override public void run() { try { responseClient(client); } catch (IOException e) { e.printStackTrace(); } } }.start(); } catch (IOException e) { e.printStackTrace(); } } } } private void responseClient(Socket client) throws IOException { //读取客户端消息 BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); //发送 <SUF> PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(client.getOutputStream())), true); out.println("欢迎啊 小伙子"); while (!mIsServiceDestoryed) { String str = in.readLine(); LogUtils.e("来自客户端的消息" + str); if (str == null) { break;//断开连接 } int i = new Random().nextInt(mDefinedMessages.length); String msg = mDefinedMessages[i]; out.println(msg); LogUtils.e("服务器发送消息了:" + msg); } LogUtils.e("客户端退出了"); if (in != null) in.close(); if (out != null) out.close(); client.close(); } }
0
28402_4
package info.meizi.net; import android.app.IntentService; import android.content.Intent; import com.squareup.okhttp.OkHttpClient; import java.io.IOException; import java.util.List; import info.meizi.bean.MainBean; import info.meizi.utils.LogUtils; import info.meizi.utils.Utils; import io.realm.Realm; /** * Created by Mr_Wrong on 15/10/9. */ public class MainService extends IntentService { private static final String TAG = "MainService"; private final OkHttpClient client = new OkHttpClient(); private Realm realm; private Intent resuleintent; private String type;//首页的类型 性感,日本。。 private String html; private String mPage;//加载更多的 public MainService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { type = intent.getStringExtra("type"); mPage = intent.getStringExtra("page"); //返回结果的 resuleintent = new Intent(type); realm = Realm.getInstance(this); List<MainBean> latest = MainBean.all(realm, type); boolean hasdata = latest.size() >= Page2int(mPage) * 24;//数据库有数据 boolean firstload = Page2int(mPage) == 1;//第一次加载||刷新 boolean loadmore = Page2int(mPage) != 1;//加载更多 LogUtils.e("数据库有数据:" + hasdata + " 第一次加载||刷新:" + firstload + " loadmore:" + loadmore); if (hasdata) {//数据库有 if (firstload) {//刷新 resuleintent.putExtra("isRefreshe", true); } } else {//数据库没有 就是第一次加载 if (loadmore) { resuleintent.putExtra("isLoadmore", true); } else { resuleintent.putExtra("isFirstload", true); } } loaddata(); sendBroadcast(resuleintent); realm.close(); } //加载数据 private void loaddata() { try { html = client.newCall(RequestFactory.make(Utils.makeUrl(type, mPage))).execute().body().string(); LogUtils.d("http://www.mzitu.com/" + Utils.makeUrl(type, mPage)); List<MainBean> list = ContentParser.ParserMainBean(html, type); saveDb(realm, list); } catch (IOException e) { e.printStackTrace(); } } private void saveDb(Realm realm, List<MainBean> list) { realm.beginTransaction(); realm.copyToRealmOrUpdate(list); realm.commitTransaction(); } int Page2int(String s) { int i = 1; if (!s.equals("")) { i = Integer.parseInt(s); } return i; } }
70kg/Meizi
app/src/main/java/info/meizi/net/MainService.java
684
//数据库有数据
line_comment
zh-cn
package info.meizi.net; import android.app.IntentService; import android.content.Intent; import com.squareup.okhttp.OkHttpClient; import java.io.IOException; import java.util.List; import info.meizi.bean.MainBean; import info.meizi.utils.LogUtils; import info.meizi.utils.Utils; import io.realm.Realm; /** * Created by Mr_Wrong on 15/10/9. */ public class MainService extends IntentService { private static final String TAG = "MainService"; private final OkHttpClient client = new OkHttpClient(); private Realm realm; private Intent resuleintent; private String type;//首页的类型 性感,日本。。 private String html; private String mPage;//加载更多的 public MainService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { type = intent.getStringExtra("type"); mPage = intent.getStringExtra("page"); //返回结果的 resuleintent = new Intent(type); realm = Realm.getInstance(this); List<MainBean> latest = MainBean.all(realm, type); boolean hasdata = latest.size() >= Page2int(mPage) * 24;//数据 <SUF> boolean firstload = Page2int(mPage) == 1;//第一次加载||刷新 boolean loadmore = Page2int(mPage) != 1;//加载更多 LogUtils.e("数据库有数据:" + hasdata + " 第一次加载||刷新:" + firstload + " loadmore:" + loadmore); if (hasdata) {//数据库有 if (firstload) {//刷新 resuleintent.putExtra("isRefreshe", true); } } else {//数据库没有 就是第一次加载 if (loadmore) { resuleintent.putExtra("isLoadmore", true); } else { resuleintent.putExtra("isFirstload", true); } } loaddata(); sendBroadcast(resuleintent); realm.close(); } //加载数据 private void loaddata() { try { html = client.newCall(RequestFactory.make(Utils.makeUrl(type, mPage))).execute().body().string(); LogUtils.d("http://www.mzitu.com/" + Utils.makeUrl(type, mPage)); List<MainBean> list = ContentParser.ParserMainBean(html, type); saveDb(realm, list); } catch (IOException e) { e.printStackTrace(); } } private void saveDb(Realm realm, List<MainBean> list) { realm.beginTransaction(); realm.copyToRealmOrUpdate(list); realm.commitTransaction(); } int Page2int(String s) { int i = 1; if (!s.equals("")) { i = Integer.parseInt(s); } return i; } }
0
53280_1
package OMWork2.task3; /* 数据操作类*/ public class DateOperator { /* 年,月,日*/ int year; int month; int day; /* year构造函数*/ public DateOperator(int year) { this.year = year; } /* 全参构造*/ public DateOperator(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } /* 根据日期计算星期数*/ public int getWeekNum(){ /* 借助吉姆拉尔森公式*/ int year; int month; int day; if(this.month == 1 || this.month == 2){ month = this.month + 12; year = this.year - 1; } else { month = this.month; year = this.year; } day = this.day; return (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400+1)%7; } /* 打印日历基本信息*/ public void printBasicInfo(){ System.out.print("\n\n "+this.year+"年"+this.month+"月\n"); System.out.print("日\t一\t二\t三\t四\t五\t六\n"); } /* 给定年份,判断是否为闰年*/ public boolean judLeapYear(){ // bug修复 https://github.com/711lxsky/In-classStorage/issues/1 return (this.year % 4 == 0 && this.year % 100 != 0) || this.year /% 400 == 0; } /* 根据月份,返回该月天数*/ public int getDayNum(){ switch (this.month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: /* 闰年2月29天*/ if(this.judLeapYear()){ return 29; } else { return 28; } default: return 0; } } /* 打印日历*/ public void printCalender(){ /* 循环打印月份日历*/ for(int i = 0 ; i < 12 ; i ++){ this.month = i + 1; this.day = 1 ; this.printBasicInfo(); while (this.day <= this.getDayNum()){ /* 抓取每月1号的星期数,以此为基准打印其余天数*/ int weekNum = this.getWeekNum(); if(this.day == 1){ for(int j = 0 ; j < weekNum ; j ++){ System.out.print("\t"); } System.out.print(this.day+"\t"); } else { System.out.print(this.day+"\t"); } if(weekNum == 6){ System.out.print("\n"); } this.day++; } } } }
711lxsky/In-classStorage
java程序设计/交作业整理/22009200439_赵宇阳_第2次上机作业/src/OMWork2/task3/DateOperator.java
799
/* 年,月,日*/
block_comment
zh-cn
package OMWork2.task3; /* 数据操作类*/ public class DateOperator { /* 年,月 <SUF>*/ int year; int month; int day; /* year构造函数*/ public DateOperator(int year) { this.year = year; } /* 全参构造*/ public DateOperator(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } /* 根据日期计算星期数*/ public int getWeekNum(){ /* 借助吉姆拉尔森公式*/ int year; int month; int day; if(this.month == 1 || this.month == 2){ month = this.month + 12; year = this.year - 1; } else { month = this.month; year = this.year; } day = this.day; return (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400+1)%7; } /* 打印日历基本信息*/ public void printBasicInfo(){ System.out.print("\n\n "+this.year+"年"+this.month+"月\n"); System.out.print("日\t一\t二\t三\t四\t五\t六\n"); } /* 给定年份,判断是否为闰年*/ public boolean judLeapYear(){ // bug修复 https://github.com/711lxsky/In-classStorage/issues/1 return (this.year % 4 == 0 && this.year % 100 != 0) || this.year /% 400 == 0; } /* 根据月份,返回该月天数*/ public int getDayNum(){ switch (this.month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: /* 闰年2月29天*/ if(this.judLeapYear()){ return 29; } else { return 28; } default: return 0; } } /* 打印日历*/ public void printCalender(){ /* 循环打印月份日历*/ for(int i = 0 ; i < 12 ; i ++){ this.month = i + 1; this.day = 1 ; this.printBasicInfo(); while (this.day <= this.getDayNum()){ /* 抓取每月1号的星期数,以此为基准打印其余天数*/ int weekNum = this.getWeekNum(); if(this.day == 1){ for(int j = 0 ; j < weekNum ; j ++){ System.out.print("\t"); } System.out.print(this.day+"\t"); } else { System.out.print(this.day+"\t"); } if(weekNum == 6){ System.out.print("\n"); } this.day++; } } } }
0
65330_6
/* * @Author: error: git config user.name && git config user.email & please set dead value or install git * @Date: 2022-08-23 23:55:45 * @LastEditors: error: git config user.name && git config user.email & please set dead value or install git * @LastEditTime: 2022-08-24 00:02:41 * @FilePath: \CareUEveryDay\src\main\java\cn\ofpp\Application.java * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE */ package cn.ofpp; import cn.ofpp.core.BoyFriend; import cn.ofpp.core.GirlFriend; import cn.ofpp.core.MessageFactory; import cn.ofpp.core.Wx; /** * 启动类 * * 这个理论上只能用测试号 正式的号 个人认证是不支持模板消息的 企业认证的又必须使用微信模板库里的模板 只有测试的可以自定义模板内容 * <a href="https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index">申请公众号测试应用地址</a> * * @author DokiYolo * Date 2022-08-22 */ public class Application { /** * <li>创建配置</li> * <li>创建几个 男/女 朋友</li> * <li>发消息</li> */ public static void main(String[] args) { // load and init Bootstrap.init(); // ----------------- 以下为演示数据 ------------------------ // new 一个 女友 GirlFriend girlFriend = new GirlFriend("某女友", "江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE56Ptipba5kSXWlNk2CG6-uA"); Wx.sendTemplateMessage(MessageFactory.resolveMessage(girlFriend)); // new 一个 男友 也可单独针对一个friend设置模板ID 以达到不同人不同消息 BoyFriend boyFriend = new BoyFriend("某男友", "江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE5ywPoqRjCOLOjZkZMDni1Qo"); Wx.sendTemplateMessage(MessageFactory.resolveMessage(boyFriend)); BoyFriend boysFriend = new BoyFriend("某男友", "江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE53eR8ceYplm-cqOiz2luJD8"); Wx.sendTemplateMessage(MessageFactory.resolveMessage(boysFriend)); } }
717986230/daynew
src/main/java/cn/ofpp/Application.java
784
// new 一个 男友 也可单独针对一个friend设置模板ID 以达到不同人不同消息
line_comment
zh-cn
/* * @Author: error: git config user.name && git config user.email & please set dead value or install git * @Date: 2022-08-23 23:55:45 * @LastEditors: error: git config user.name && git config user.email & please set dead value or install git * @LastEditTime: 2022-08-24 00:02:41 * @FilePath: \CareUEveryDay\src\main\java\cn\ofpp\Application.java * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE */ package cn.ofpp; import cn.ofpp.core.BoyFriend; import cn.ofpp.core.GirlFriend; import cn.ofpp.core.MessageFactory; import cn.ofpp.core.Wx; /** * 启动类 * * 这个理论上只能用测试号 正式的号 个人认证是不支持模板消息的 企业认证的又必须使用微信模板库里的模板 只有测试的可以自定义模板内容 * <a href="https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index">申请公众号测试应用地址</a> * * @author DokiYolo * Date 2022-08-22 */ public class Application { /** * <li>创建配置</li> * <li>创建几个 男/女 朋友</li> * <li>发消息</li> */ public static void main(String[] args) { // load and init Bootstrap.init(); // ----------------- 以下为演示数据 ------------------------ // new 一个 女友 GirlFriend girlFriend = new GirlFriend("某女友", "江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE56Ptipba5kSXWlNk2CG6-uA"); Wx.sendTemplateMessage(MessageFactory.resolveMessage(girlFriend)); // ne <SUF> BoyFriend boyFriend = new BoyFriend("某男友", "江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE5ywPoqRjCOLOjZkZMDni1Qo"); Wx.sendTemplateMessage(MessageFactory.resolveMessage(boyFriend)); BoyFriend boysFriend = new BoyFriend("某男友", "江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE53eR8ceYplm-cqOiz2luJD8"); Wx.sendTemplateMessage(MessageFactory.resolveMessage(boysFriend)); } }
0
19565_14
package com.yuu.recruit.vo; import com.yuu.recruit.domain.Employee; import com.yuu.recruit.domain.Employer; import com.yuu.recruit.domain.TaskCategory; import com.yuu.recruit.domain.TaskSkill; import lombok.Data; import java.io.Serializable; import java.util.Date; import java.util.List; /** * 任务页面展示对象 * * @author by yuu * @Classname TaskVo * @Date 2019/10/13 20:19 * @see com.yuu.recruit.vo */ @Data public class TaskVo implements Serializable { private static final long serialVersionUID = -1264009471871480548L; /** * 任务ID */ private Long id; /** * 任务分类 */ private TaskCategory taskCategory; /** * 任务发布雇主信息 */ private Employer employer; /** * 任务标题 */ private String taskTitle; /** * 任务简介 */ private String taskProfile; /** * 任务描述 */ private String taskDesc; /** * 最低预算价格 */ private Double feesLow; /** * 最高预算价格 */ private Double feesHigh; /** * 任务附件地址 */ private String feesFile; /** * 任务附件地址 */ private String filename; /** * 完成任务雇员ID */ private Employee employee; /** * 任务成交价格 */ private Double taskPrice; /** * 任务状态 */ private Byte taskStatus; /** * 任务中标时间 */ private Date bidTime; /** * 任务成交时间 */ private Date closeTime; /** * 创建时间 */ private Date createTime; /** * 多久以前发布 */ private String beforeTime; /** * 任务到期时间 */ private Date expireTime; /** * 任务所需技能标签 */ private List<TaskSkill> skills; /** * 该任务所有竞标者 */ private List<BidVo> bidVos; /** * 平均竞标价格 */ private Double avgPrice; }
71yuu/springboot-recruit
src/main/java/com/yuu/recruit/vo/TaskVo.java
569
/** * 任务中标时间 */
block_comment
zh-cn
package com.yuu.recruit.vo; import com.yuu.recruit.domain.Employee; import com.yuu.recruit.domain.Employer; import com.yuu.recruit.domain.TaskCategory; import com.yuu.recruit.domain.TaskSkill; import lombok.Data; import java.io.Serializable; import java.util.Date; import java.util.List; /** * 任务页面展示对象 * * @author by yuu * @Classname TaskVo * @Date 2019/10/13 20:19 * @see com.yuu.recruit.vo */ @Data public class TaskVo implements Serializable { private static final long serialVersionUID = -1264009471871480548L; /** * 任务ID */ private Long id; /** * 任务分类 */ private TaskCategory taskCategory; /** * 任务发布雇主信息 */ private Employer employer; /** * 任务标题 */ private String taskTitle; /** * 任务简介 */ private String taskProfile; /** * 任务描述 */ private String taskDesc; /** * 最低预算价格 */ private Double feesLow; /** * 最高预算价格 */ private Double feesHigh; /** * 任务附件地址 */ private String feesFile; /** * 任务附件地址 */ private String filename; /** * 完成任务雇员ID */ private Employee employee; /** * 任务成交价格 */ private Double taskPrice; /** * 任务状态 */ private Byte taskStatus; /** * 任务中 <SUF>*/ private Date bidTime; /** * 任务成交时间 */ private Date closeTime; /** * 创建时间 */ private Date createTime; /** * 多久以前发布 */ private String beforeTime; /** * 任务到期时间 */ private Date expireTime; /** * 任务所需技能标签 */ private List<TaskSkill> skills; /** * 该任务所有竞标者 */ private List<BidVo> bidVos; /** * 平均竞标价格 */ private Double avgPrice; }
0
11400_7
package me.chanjar.weixin.mp.bean.kefu.result; import java.io.Serializable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import lombok.Data; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** * 客服基本信息以及客服在线状态信息 * * @author Binary Wang */ @Data public class WxMpKfInfo implements Serializable { private static final long serialVersionUID = -5877300750666022290L; /** * kf_account 完整客服账号,格式为:账号前缀@公众号微信号 */ @SerializedName("kf_account") private String account; /** * kf_headimgurl 客服头像地址 */ @SerializedName("kf_headimgurl") private String headImgUrl; /** * kf_id 客服工号 */ @SerializedName("kf_id") private String id; /** * kf_nick 客服昵称 */ @SerializedName("kf_nick") private String nick; /** * kf_wx 如果客服帐号已绑定了客服人员微信号,则此处显示微信号 */ @SerializedName("kf_wx") private String wxAccount; /** * invite_wx 如果客服帐号尚未绑定微信号,但是已经发起了一个绑定邀请,则此处显示绑定邀请的微信号 */ @SerializedName("invite_wx") private String inviteWx; /** * invite_expire_time 如果客服帐号尚未绑定微信号,但是已经发起过一个绑定邀请,则此处显示为邀请的过期时间,为unix 时间戳 */ @SerializedName("invite_expire_time") private Long inviteExpireTime; /** * invite_status 邀请的状态,有等待确认“waiting”,被拒绝“rejected”,过期“expired” */ @SerializedName("invite_status") private String inviteStatus; /** * status 客服在线状态,目前为:1、web 在线 */ @SerializedName("status") private Integer status; /** * accepted_case 客服当前正在接待的会话数 */ @Expose @SerializedName("accepted_case") private Integer acceptedCase; @Override public String toString() { return WxMpGsonBuilder.create().toJson(this); } }
723580451/Wechat-Group-WxJava
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfInfo.java
601
/** * invite_expire_time 如果客服帐号尚未绑定微信号,但是已经发起过一个绑定邀请,则此处显示为邀请的过期时间,为unix 时间戳 */
block_comment
zh-cn
package me.chanjar.weixin.mp.bean.kefu.result; import java.io.Serializable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import lombok.Data; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** * 客服基本信息以及客服在线状态信息 * * @author Binary Wang */ @Data public class WxMpKfInfo implements Serializable { private static final long serialVersionUID = -5877300750666022290L; /** * kf_account 完整客服账号,格式为:账号前缀@公众号微信号 */ @SerializedName("kf_account") private String account; /** * kf_headimgurl 客服头像地址 */ @SerializedName("kf_headimgurl") private String headImgUrl; /** * kf_id 客服工号 */ @SerializedName("kf_id") private String id; /** * kf_nick 客服昵称 */ @SerializedName("kf_nick") private String nick; /** * kf_wx 如果客服帐号已绑定了客服人员微信号,则此处显示微信号 */ @SerializedName("kf_wx") private String wxAccount; /** * invite_wx 如果客服帐号尚未绑定微信号,但是已经发起了一个绑定邀请,则此处显示绑定邀请的微信号 */ @SerializedName("invite_wx") private String inviteWx; /** * inv <SUF>*/ @SerializedName("invite_expire_time") private Long inviteExpireTime; /** * invite_status 邀请的状态,有等待确认“waiting”,被拒绝“rejected”,过期“expired” */ @SerializedName("invite_status") private String inviteStatus; /** * status 客服在线状态,目前为:1、web 在线 */ @SerializedName("status") private Integer status; /** * accepted_case 客服当前正在接待的会话数 */ @Expose @SerializedName("accepted_case") private Integer acceptedCase; @Override public String toString() { return WxMpGsonBuilder.create().toJson(this); } }
0
33526_2
package servlet; import java.io.IOException; import java.lang.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class PlayGamesServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub /** * 获取用户名和密码 */ String numberString=request.getParameter("number"); String usernameString=request.getParameter("user"); int number=Integer.valueOf(numberString); /** * 随机生成数字 */ int integer=(int)(1+Math.random()*10); String msgString=null; if(number>integer) { msgString="猜大啦!"; }else if (number==integer) { msgString="猜中了!恭喜"; }else { msgString="猜小了!"; } request.setAttribute("msg", msgString); //封装request后需要用转发而不是重定向,不然数据传不过去 request.getRequestDispatcher("doGames").forward(request, response); //response.sendRedirect("doGames"); } }
729748198/JSPandServlet
src/servlet/PlayGamesServlet.java
317
/** * 随机生成数字 */
block_comment
zh-cn
package servlet; import java.io.IOException; import java.lang.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class PlayGamesServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub /** * 获取用户名和密码 */ String numberString=request.getParameter("number"); String usernameString=request.getParameter("user"); int number=Integer.valueOf(numberString); /** * 随机生 <SUF>*/ int integer=(int)(1+Math.random()*10); String msgString=null; if(number>integer) { msgString="猜大啦!"; }else if (number==integer) { msgString="猜中了!恭喜"; }else { msgString="猜小了!"; } request.setAttribute("msg", msgString); //封装request后需要用转发而不是重定向,不然数据传不过去 request.getRequestDispatcher("doGames").forward(request, response); //response.sendRedirect("doGames"); } }
0
64212_8
//问题描述 //  自从Peter Stuyvesant和Abel Tasman的日子以后,荷兰商人已经周游世界来买卖商品。有一次在Verweggistan的贸易,但是它在很短的时间后就结束了。在读完这个故事之后你就明白了。 //  在当时Verweggistan是非常受欢迎的,因为世界上只有那个地方的人知道怎样制作一个“prul”(或者“prullen”,荷兰语中的复数形式),并且如今只有很少的人知道什么是一个“prul”。 //  “prul”是在工场里生产的。当一个“prul”做完的时候,它被包装在一个箱子里,然后放在之前生产的“prul”所装的箱子堆的上面。 //  价格取决于生产“prul”所需要的时间。如果一切顺利,一个“prul”的价格会是1或者2弗罗林,但是在一个恶劣的日子,价格会很容易地上升到15弗罗林或者更高。“prul”在品质上没有什么差别,所有的“prul”具有相同的价值。 //  在这些天,“prul”在荷兰的售价为每件10弗罗林。交通运输的费用是可以忽略的,因为“prul”无论如何都会作为额外的东西被装载到要航行的船上。当一个荷兰商人去Verweggistan时,他有一个明确的目的:买“prul”,在荷兰销售,并且最大化他的利润。不幸的是,Verweggistan地区对“prul”的交易方式使得这比某些人预想的更为复杂。 //  有人认为这很简单,商人会买那些最便宜的“prul”,而那些售价比10弗罗林高的“prul”会一直不能出售。不幸的是,Verweggistan的所有工场按照一种奇怪的顺序销售“prul”。堆顶的箱子里的“prul”会最先销售,然后销售从顶上开始数的第二个箱子里的“prul”,以此类推。所以即使第五个箱子里的“prul”是最便宜的,商人也必须买它上面四个箱子里的“prul”才能得到它。 //  正如你想象的那样,这使得商人通过购买正确的“prul”的组合来最大化他们的利润是相当难的。没有电脑帮助他们的优化,他们迅速彻底失去了交易“prul”的兴趣。 //  在这个问题中,给你对几个工场里箱子堆的描述。你必须根据上面所给的限制,计算出一个商人通过购买箱子堆中的“prul”可以获得的最大利润。另外,你必须确定他需要买多少个“prul”才能获得最大利润。 //输入格式 //  输入文件包含多组测试数据。每个测试数据的第一行是一个整数w(1<=w<=50),该测试数据中工场的数目。 //  接下来有w行,每行描述一个放“prul”的箱子堆。每行的第一个整数b(0<=b<=20),表示堆中的箱子数。接下来是b个正整数,表示堆中“prul”的价格(单位为弗罗林)。输入中箱子的顺序是从顶到底。 //  输入数据终止于w=0,不再有后续的描述内容。 //输出格式 //  对于每组测试数据,输出测试点的编号(1,2...)。然后输出两行,第一行输出商人可以获得的最大利润。第二行输出为获得最大利润商人需要买的“prul”数量。如果这个数量不是唯一确定的,按照升序输出可能的值。如果有超过10种可能的取值,只输出10个最小的取值。 //样例输入 //1 //6 12 3 10 7 16 5 //2 //5 7 3 11 9 10 //9 1 2 3 4 10 16 10 4 16 //0 //样例输出 //Workyards 1 //Maximum profit is 8. //Number of pruls to buy: 4 //Workyards 2 //Maximum profit is 40. //Number of pruls to buy: 6 7 8 9 10 12 13 //数据规模和约定 //  1<=w<=50,0<=b<=20,输入文件保证测试点个数不超过10。 package 算法提高; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; import java.util.Set; public class Trade_on_Verweggistan { private static int [][]book=new int[52][22]; private static Integer sum=0; @SuppressWarnings("unchecked") public static void main(String[] args) { // TODO Auto-generaed method stub Scanner in=new Scanner(System.in); int n; ArrayList<Integer>[]list = null; int ji=1; while (in.hasNext()) { n=in.nextInt(); if(n==0) { return; } list=new ArrayList[n]; int j2=0; for(int i=0;j2<n;i++) { j2++; int l=in.nextInt(); if(l==0) { i--; continue; } list[i]=new ArrayList<>(l); for(int j=0;j<l;j++) { list[i].add(10-in.nextInt()); book[i][j]=0; } } //存储每个工厂可能是购买数 ArrayList[]result=new ArrayList[n]; for(int i=0;i<n;i++) { result[i]=new ArrayList<>(); } //存储每个工厂的最大利润 ArrayList<Integer> maxnum=new ArrayList<>(); for(int i=0;i<list.length;i++) { //用一个数组计算出每一个工厂最大利润和可能的购买数 int[]temp=new int[list[i].size()]; int max=0; for(int j=0;j<list[i].size();j++) { if(j==0) { temp[0]=list[i].get(0); }else temp[j]=temp[j-1]+list[i].get(j); if(temp[j]>max) { max=temp[j]; } } //每个工厂的最大利润 maxnum.add(max); boolean empty=true; for(int j=0;j<temp.length;j++) { //System.out.println("当前的最大和"+maxnum.get(i)+" temp[j]"+temp[j]); if(temp[j]==maxnum.get(i)) { empty=false; result[i].add(j+1); } } if(empty) { result[i].add(0); } } System.out.println("Workyards "+ji); ji++; //最大利润max int max=0; //System.out.println("每行最大利润"); for(int i=0;i<maxnum.size();i++) { //System.out.print(maxnum.get(i)+" "); max+=maxnum.get(i); } System.out.println("Maximum profit is "+max+"."); //可能的组合,每个 Set<Integer>set=new HashSet<>(); dfs(result, set,0); System.out.print("Number of pruls to buy:"); Iterator iterator=set.iterator(); for(int i=0;i<10;i++) { if(iterator.hasNext()) System.out.print(iterator.next()+" "); else { break; } } System.out.println(); } } public static void dfs(ArrayList[]result,Set<Integer>set,int ji) { if(ji>=result.length) { set.add(sum); return; } for(int i=0;i<result[ji].size();i++) { if(book[ji][i]==0) { sum+=(Integer) result[ji].get(i); book[ji][i]=1; dfs(result, set, ji+1); sum-=(Integer)result[ji].get(i); book[ji][i]=0; } } } }
729748198/Lanqiao
src/算法提高/Trade_on_Verweggistan.java
2,281
//  在这个问题中,给你对几个工场里箱子堆的描述。你必须根据上面所给的限制,计算出一个商人通过购买箱子堆中的“prul”可以获得的最大利润。另外,你必须确定他需要买多少个“prul”才能获得最大利润。
line_comment
zh-cn
//问题描述 //  自从Peter Stuyvesant和Abel Tasman的日子以后,荷兰商人已经周游世界来买卖商品。有一次在Verweggistan的贸易,但是它在很短的时间后就结束了。在读完这个故事之后你就明白了。 //  在当时Verweggistan是非常受欢迎的,因为世界上只有那个地方的人知道怎样制作一个“prul”(或者“prullen”,荷兰语中的复数形式),并且如今只有很少的人知道什么是一个“prul”。 //  “prul”是在工场里生产的。当一个“prul”做完的时候,它被包装在一个箱子里,然后放在之前生产的“prul”所装的箱子堆的上面。 //  价格取决于生产“prul”所需要的时间。如果一切顺利,一个“prul”的价格会是1或者2弗罗林,但是在一个恶劣的日子,价格会很容易地上升到15弗罗林或者更高。“prul”在品质上没有什么差别,所有的“prul”具有相同的价值。 //  在这些天,“prul”在荷兰的售价为每件10弗罗林。交通运输的费用是可以忽略的,因为“prul”无论如何都会作为额外的东西被装载到要航行的船上。当一个荷兰商人去Verweggistan时,他有一个明确的目的:买“prul”,在荷兰销售,并且最大化他的利润。不幸的是,Verweggistan地区对“prul”的交易方式使得这比某些人预想的更为复杂。 //  有人认为这很简单,商人会买那些最便宜的“prul”,而那些售价比10弗罗林高的“prul”会一直不能出售。不幸的是,Verweggistan的所有工场按照一种奇怪的顺序销售“prul”。堆顶的箱子里的“prul”会最先销售,然后销售从顶上开始数的第二个箱子里的“prul”,以此类推。所以即使第五个箱子里的“prul”是最便宜的,商人也必须买它上面四个箱子里的“prul”才能得到它。 //  正如你想象的那样,这使得商人通过购买正确的“prul”的组合来最大化他们的利润是相当难的。没有电脑帮助他们的优化,他们迅速彻底失去了交易“prul”的兴趣。 //   <SUF> //输入格式 //  输入文件包含多组测试数据。每个测试数据的第一行是一个整数w(1<=w<=50),该测试数据中工场的数目。 //  接下来有w行,每行描述一个放“prul”的箱子堆。每行的第一个整数b(0<=b<=20),表示堆中的箱子数。接下来是b个正整数,表示堆中“prul”的价格(单位为弗罗林)。输入中箱子的顺序是从顶到底。 //  输入数据终止于w=0,不再有后续的描述内容。 //输出格式 //  对于每组测试数据,输出测试点的编号(1,2...)。然后输出两行,第一行输出商人可以获得的最大利润。第二行输出为获得最大利润商人需要买的“prul”数量。如果这个数量不是唯一确定的,按照升序输出可能的值。如果有超过10种可能的取值,只输出10个最小的取值。 //样例输入 //1 //6 12 3 10 7 16 5 //2 //5 7 3 11 9 10 //9 1 2 3 4 10 16 10 4 16 //0 //样例输出 //Workyards 1 //Maximum profit is 8. //Number of pruls to buy: 4 //Workyards 2 //Maximum profit is 40. //Number of pruls to buy: 6 7 8 9 10 12 13 //数据规模和约定 //  1<=w<=50,0<=b<=20,输入文件保证测试点个数不超过10。 package 算法提高; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Scanner; import java.util.Set; public class Trade_on_Verweggistan { private static int [][]book=new int[52][22]; private static Integer sum=0; @SuppressWarnings("unchecked") public static void main(String[] args) { // TODO Auto-generaed method stub Scanner in=new Scanner(System.in); int n; ArrayList<Integer>[]list = null; int ji=1; while (in.hasNext()) { n=in.nextInt(); if(n==0) { return; } list=new ArrayList[n]; int j2=0; for(int i=0;j2<n;i++) { j2++; int l=in.nextInt(); if(l==0) { i--; continue; } list[i]=new ArrayList<>(l); for(int j=0;j<l;j++) { list[i].add(10-in.nextInt()); book[i][j]=0; } } //存储每个工厂可能是购买数 ArrayList[]result=new ArrayList[n]; for(int i=0;i<n;i++) { result[i]=new ArrayList<>(); } //存储每个工厂的最大利润 ArrayList<Integer> maxnum=new ArrayList<>(); for(int i=0;i<list.length;i++) { //用一个数组计算出每一个工厂最大利润和可能的购买数 int[]temp=new int[list[i].size()]; int max=0; for(int j=0;j<list[i].size();j++) { if(j==0) { temp[0]=list[i].get(0); }else temp[j]=temp[j-1]+list[i].get(j); if(temp[j]>max) { max=temp[j]; } } //每个工厂的最大利润 maxnum.add(max); boolean empty=true; for(int j=0;j<temp.length;j++) { //System.out.println("当前的最大和"+maxnum.get(i)+" temp[j]"+temp[j]); if(temp[j]==maxnum.get(i)) { empty=false; result[i].add(j+1); } } if(empty) { result[i].add(0); } } System.out.println("Workyards "+ji); ji++; //最大利润max int max=0; //System.out.println("每行最大利润"); for(int i=0;i<maxnum.size();i++) { //System.out.print(maxnum.get(i)+" "); max+=maxnum.get(i); } System.out.println("Maximum profit is "+max+"."); //可能的组合,每个 Set<Integer>set=new HashSet<>(); dfs(result, set,0); System.out.print("Number of pruls to buy:"); Iterator iterator=set.iterator(); for(int i=0;i<10;i++) { if(iterator.hasNext()) System.out.print(iterator.next()+" "); else { break; } } System.out.println(); } } public static void dfs(ArrayList[]result,Set<Integer>set,int ji) { if(ji>=result.length) { set.add(sum); return; } for(int i=0;i<result[ji].size();i++) { if(book[ji][i]==0) { sum+=(Integer) result[ji].get(i); book[ji][i]=1; dfs(result, set, ji+1); sum-=(Integer)result[ji].get(i); book[ji][i]=0; } } } }
0
58988_2
/** * Copyright© 2003-2016 浙江汇信科技有限公司, All Rights Reserved. <br/> */ package com.icinfo.cs.base.model; import com.icinfo.framework.mybatis.mapper.annotation.Before; import java.io.Serializable; import java.util.Date; import javax.persistence.*; /** * 描述: cs_code_regorg 对应的实体类.<br> * WARNING:不是表中字段的属性必须加@Transient注解 * @author framework generator * @date 2016年09月12日 */ @Table(name = "cs_code_regorg") public class CodeRegorg implements Serializable { @Id @Column(name = "id") @Before @GeneratedValue(strategy = GenerationType.IDENTITY,generator="select replace(uuid(), '-', '')") private Integer id; @Column(name = "ContentWord") private String contentWord; @Column(name = "ContentShort") private String contentShort; @Column(name = "Content") private String content; @Column(name = "Code") private String code; //登记机关联络员 @Column(name = "LiaName") private String liaName; //联络员电话号码 @Column(name = "LiaPhone") private String liaPhone; private static final long serialVersionUID = 1L; /** * @return id */ public Integer getId() { return id; } /** * @param id */ public void setId(Integer id) { this.id = id; } /** * @return ContentWord */ public String getContentWord() { return contentWord; } /** * @param contentWord */ public void setContentWord(String contentWord) { this.contentWord = contentWord; } /** * @return ContentShort */ public String getContentShort() { return contentShort; } /** * @param contentShort */ public void setContentShort(String contentShort) { this.contentShort = contentShort; } /** * @return Content */ public String getContent() { return content; } /** * @param content */ public void setContent(String content) { this.content = content; } /** * @return Code */ public String getCode() { return code; } /** * @param code */ public void setCode(String code) { this.code = code; } public void setLiaName(String liaName) { this.liaName = liaName; } public String getLiaName() { return liaName; } public void setLiaPhone(String liaPhone) { this.liaPhone = liaPhone; } public String getLiaPhone() { return liaPhone; } }
7373/enterprise-information-exchange-and-sharing-system
src/main/java/com/src/xt/base/model/CodeRegorg.java
701
//登记机关联络员
line_comment
zh-cn
/** * Copyright© 2003-2016 浙江汇信科技有限公司, All Rights Reserved. <br/> */ package com.icinfo.cs.base.model; import com.icinfo.framework.mybatis.mapper.annotation.Before; import java.io.Serializable; import java.util.Date; import javax.persistence.*; /** * 描述: cs_code_regorg 对应的实体类.<br> * WARNING:不是表中字段的属性必须加@Transient注解 * @author framework generator * @date 2016年09月12日 */ @Table(name = "cs_code_regorg") public class CodeRegorg implements Serializable { @Id @Column(name = "id") @Before @GeneratedValue(strategy = GenerationType.IDENTITY,generator="select replace(uuid(), '-', '')") private Integer id; @Column(name = "ContentWord") private String contentWord; @Column(name = "ContentShort") private String contentShort; @Column(name = "Content") private String content; @Column(name = "Code") private String code; //登记 <SUF> @Column(name = "LiaName") private String liaName; //联络员电话号码 @Column(name = "LiaPhone") private String liaPhone; private static final long serialVersionUID = 1L; /** * @return id */ public Integer getId() { return id; } /** * @param id */ public void setId(Integer id) { this.id = id; } /** * @return ContentWord */ public String getContentWord() { return contentWord; } /** * @param contentWord */ public void setContentWord(String contentWord) { this.contentWord = contentWord; } /** * @return ContentShort */ public String getContentShort() { return contentShort; } /** * @param contentShort */ public void setContentShort(String contentShort) { this.contentShort = contentShort; } /** * @return Content */ public String getContent() { return content; } /** * @param content */ public void setContent(String content) { this.content = content; } /** * @return Code */ public String getCode() { return code; } /** * @param code */ public void setCode(String code) { this.code = code; } public void setLiaName(String liaName) { this.liaName = liaName; } public String getLiaName() { return liaName; } public void setLiaPhone(String liaPhone) { this.liaPhone = liaPhone; } public String getLiaPhone() { return liaPhone; } }
0
51170_8
package cn.itcast.heima2; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class ThreadPoolTest { public static void main(String[] args) { //固定线程池 // ExecutorService threadPool = Executors.newFixedThreadPool(3); //缓存线程池,任务执行不过来,自动增加新的线程 // ExecutorService threadPool = Executors.newCachedThreadPool(); //一个线程,好处,如果池子中的线程死了,会自动增加一个线程 (可以解决:如何实现线程死掉后重新启动) ExecutorService threadPool = Executors.newSingleThreadExecutor(); for(int i = 1; i <= 10; i++){ final int task = i; threadPool.execute(new Runnable() { @Override public void run() { for(int j = 1; j <= 10; j++){ try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task " + task); } } }); } System.out.println(" all of 10 task have committed!!"); // threadPool.shutdown();//任务干完后关闭线程 // threadPool.shutdownNow();//任务没执行完毕也关闭 //定时器的线程池 Executors.newScheduledThreadPool(3).schedule(new Runnable() { @Override public void run() { System.out.println("bombing !!!"); } }, 10,//多长时间后执行,10秒后执行 TimeUnit.SECONDS); //每隔多长时间执行一次,以固定饿频率执行 Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("bombing!!!!!"); } }, 6,//6秒后开始执行 2, //每隔2秒执行一次 TimeUnit.SECONDS); } }
75168859/ThreadTest2
src/cn/itcast/heima2/ThreadPoolTest.java
532
//定时器的线程池
line_comment
zh-cn
package cn.itcast.heima2; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class ThreadPoolTest { public static void main(String[] args) { //固定线程池 // ExecutorService threadPool = Executors.newFixedThreadPool(3); //缓存线程池,任务执行不过来,自动增加新的线程 // ExecutorService threadPool = Executors.newCachedThreadPool(); //一个线程,好处,如果池子中的线程死了,会自动增加一个线程 (可以解决:如何实现线程死掉后重新启动) ExecutorService threadPool = Executors.newSingleThreadExecutor(); for(int i = 1; i <= 10; i++){ final int task = i; threadPool.execute(new Runnable() { @Override public void run() { for(int j = 1; j <= 10; j++){ try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task " + task); } } }); } System.out.println(" all of 10 task have committed!!"); // threadPool.shutdown();//任务干完后关闭线程 // threadPool.shutdownNow();//任务没执行完毕也关闭 //定时 <SUF> Executors.newScheduledThreadPool(3).schedule(new Runnable() { @Override public void run() { System.out.println("bombing !!!"); } }, 10,//多长时间后执行,10秒后执行 TimeUnit.SECONDS); //每隔多长时间执行一次,以固定饿频率执行 Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("bombing!!!!!"); } }, 6,//6秒后开始执行 2, //每隔2秒执行一次 TimeUnit.SECONDS); } }
0
28838_1
package com.lol.constans; import com.lol.util.Utils; public class MonsterData { public static final java.util.HashMap<Integer, MonsterModel> monsterMap = new java.util.HashMap<Integer, MonsterModel>(); /** * 静态构造 初次访问的时候自动调用 */ static { int random = Utils.getRandomNum(4, 7); BuffModel river = new BuffModel(); BuffModel red = new BuffModel(); BuffModel blue = new BuffModel(); BuffModel wind_gragon = new BuffModel(); BuffModel fire_gragon = new BuffModel(); BuffModel water_gragon = new BuffModel(); BuffModel soil_gragon = new BuffModel(); BuffModel ancient_dragon = new BuffModel(); BuffModel pioneer_valley = new BuffModel(); BuffModel nash_baron = new BuffModel(); create(1, "红BUFF怪",0,70,4000,300,0,0,0,5,15,new int[]{},true,60,true,red,true); create(2, "蓝BUFF怪",0,70,4000,300,0,0,0,0,0,new int[]{},true,60,true,blue,true); create(3, "峡谷先锋",250,200,12000,300,0,0,0,0,0,new int[]{},false,0,true,pioneer_valley,true); create(4, "纳什男爵",600,500,100000,300,0,0,0,0,0,new int[]{},true,3000,true,nash_baron,true); //4龙 随机选1 create(5,BuffEnum.fromCode(random).getDescription() ,0,0,8000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(6,"三狼",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(6,"三狼儿子1",120,30,500,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(7,"三狼儿子2",120,30,500,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(8,"F4老爸",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(9,"F4儿子1",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(10,"F4儿子2",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(11,"F4儿子3",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(12,"F4儿子4",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(13,"石头老爸",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(14,"石头儿子1",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(15,"石头儿子2",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(16,"蛤蟆",150,50,2000,300,0,0,0,5,15,new int[]{},true,30,false,null,true); create(17,"河蟹",0,0,4000,300,0,0,0,0,0,new int[]{},true,45,true,river,true); } /** * 创建模型并添加进字典 * @param code * @param name * @param atkBase * @param defBase * @param hpBase * @param speed * @param atkArr * @param defArr * @param hpArr * @param atkRange * @param tailRange * @param skills * @param reborn * @param rebornTime * @param provideBuff * @param buff * @param neutrality */ private static void create(int code, String name, int atkBase, int defBase, int hpBase,int speed,int atkArr, float defArr, int hpArr, float atkRange, float tailRange, int[] skills, boolean reborn,int rebornTime,boolean provideBuff,BuffModel buff, boolean neutrality) { MonsterModel model = new MonsterModel(); model.setCode(code); //策划定义的唯一编号 model.setName(name); //怪物名称 model.setAtkBase(atkBase); //初始(基础)攻击力 model.setDefBase(defBase); //初始防御 model.setHpBase(hpBase); //初始血量 model.setSpeed(speed); //移动速度 model.setAtkArr(atkArr); //攻击成长 model.setDefArr(defArr); //防御成长 model.setHpArr(hpArr); //血量成长 model.setAtkRange(atkRange); //攻击距离 model.setTailRange(tailRange); //跟踪范围 model.setSkills(skills); //拥有技能 model.setReborn(reborn); //是否复活 model.setRebornTime(rebornTime); //复活时间 model.setProvideBuff(provideBuff); //杀死后是否提供增益BUF model.setBuff(buff); //buff; model.setNeutrality(neutrality); //是否中立 monsterMap.put(code, model); } }
765741668/lolserver
Protocol/src/main/java/com/lol/constans/MonsterData.java
1,667
//4龙 随机选1
line_comment
zh-cn
package com.lol.constans; import com.lol.util.Utils; public class MonsterData { public static final java.util.HashMap<Integer, MonsterModel> monsterMap = new java.util.HashMap<Integer, MonsterModel>(); /** * 静态构造 初次访问的时候自动调用 */ static { int random = Utils.getRandomNum(4, 7); BuffModel river = new BuffModel(); BuffModel red = new BuffModel(); BuffModel blue = new BuffModel(); BuffModel wind_gragon = new BuffModel(); BuffModel fire_gragon = new BuffModel(); BuffModel water_gragon = new BuffModel(); BuffModel soil_gragon = new BuffModel(); BuffModel ancient_dragon = new BuffModel(); BuffModel pioneer_valley = new BuffModel(); BuffModel nash_baron = new BuffModel(); create(1, "红BUFF怪",0,70,4000,300,0,0,0,5,15,new int[]{},true,60,true,red,true); create(2, "蓝BUFF怪",0,70,4000,300,0,0,0,0,0,new int[]{},true,60,true,blue,true); create(3, "峡谷先锋",250,200,12000,300,0,0,0,0,0,new int[]{},false,0,true,pioneer_valley,true); create(4, "纳什男爵",600,500,100000,300,0,0,0,0,0,new int[]{},true,3000,true,nash_baron,true); //4龙 <SUF> create(5,BuffEnum.fromCode(random).getDescription() ,0,0,8000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(6,"三狼",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(6,"三狼儿子1",120,30,500,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(7,"三狼儿子2",120,30,500,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(8,"F4老爸",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(9,"F4儿子1",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(10,"F4儿子2",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(11,"F4儿子3",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(12,"F4儿子4",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(13,"石头老爸",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(14,"石头儿子1",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(15,"石头儿子2",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true); create(16,"蛤蟆",150,50,2000,300,0,0,0,5,15,new int[]{},true,30,false,null,true); create(17,"河蟹",0,0,4000,300,0,0,0,0,0,new int[]{},true,45,true,river,true); } /** * 创建模型并添加进字典 * @param code * @param name * @param atkBase * @param defBase * @param hpBase * @param speed * @param atkArr * @param defArr * @param hpArr * @param atkRange * @param tailRange * @param skills * @param reborn * @param rebornTime * @param provideBuff * @param buff * @param neutrality */ private static void create(int code, String name, int atkBase, int defBase, int hpBase,int speed,int atkArr, float defArr, int hpArr, float atkRange, float tailRange, int[] skills, boolean reborn,int rebornTime,boolean provideBuff,BuffModel buff, boolean neutrality) { MonsterModel model = new MonsterModel(); model.setCode(code); //策划定义的唯一编号 model.setName(name); //怪物名称 model.setAtkBase(atkBase); //初始(基础)攻击力 model.setDefBase(defBase); //初始防御 model.setHpBase(hpBase); //初始血量 model.setSpeed(speed); //移动速度 model.setAtkArr(atkArr); //攻击成长 model.setDefArr(defArr); //防御成长 model.setHpArr(hpArr); //血量成长 model.setAtkRange(atkRange); //攻击距离 model.setTailRange(tailRange); //跟踪范围 model.setSkills(skills); //拥有技能 model.setReborn(reborn); //是否复活 model.setRebornTime(rebornTime); //复活时间 model.setProvideBuff(provideBuff); //杀死后是否提供增益BUF model.setBuff(buff); //buff; model.setNeutrality(neutrality); //是否中立 monsterMap.put(code, model); } }
0
57101_5
package greedarithmetic; import java.util.Arrays; import java.util.PriorityQueue; /** * Created by Terry * User: Administrator * Date: 2021-12-25 * Time: 19:34 * Description:最多可参与的会议数量 * https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended/ */ public class Code07_MaxJoinConference { public int maxEvents(int[][] events) { if (events == null || events.length == 0) { return 0; } //先对数组进行排序,第一列的数是会议的开始时间,让开始时间相等的在一堆 Arrays.sort(events, (o1, o2)-> { return o1[0] - o2[0]; //升序 }); PriorityQueue<Integer> minHeap = new PriorityQueue<>(); int curDay = 1; int res = 0; int i = 0; while (i < events.length || !minHeap.isEmpty()) { while (i < events.length && events[i][0] == curDay) {//当前数据的开始时间与cur相等 minHeap.add(events[i][1]);//将结束时间放入小堆 i++; } //当前堆中的结束时间小于当前之间,直接舍弃 while (!minHeap.isEmpty() && minHeap.peek() < curDay) { minHeap.poll(); } if (!minHeap.isEmpty()) { //每天只能开一个会议 minHeap.poll(); res++; } curDay++; } return res; } }
7flyx/Algorithm-of-test-library
bitTrainProblem/untitled/src/greedarithmetic/Code07_MaxJoinConference.java
403
//每天只能开一个会议
line_comment
zh-cn
package greedarithmetic; import java.util.Arrays; import java.util.PriorityQueue; /** * Created by Terry * User: Administrator * Date: 2021-12-25 * Time: 19:34 * Description:最多可参与的会议数量 * https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended/ */ public class Code07_MaxJoinConference { public int maxEvents(int[][] events) { if (events == null || events.length == 0) { return 0; } //先对数组进行排序,第一列的数是会议的开始时间,让开始时间相等的在一堆 Arrays.sort(events, (o1, o2)-> { return o1[0] - o2[0]; //升序 }); PriorityQueue<Integer> minHeap = new PriorityQueue<>(); int curDay = 1; int res = 0; int i = 0; while (i < events.length || !minHeap.isEmpty()) { while (i < events.length && events[i][0] == curDay) {//当前数据的开始时间与cur相等 minHeap.add(events[i][1]);//将结束时间放入小堆 i++; } //当前堆中的结束时间小于当前之间,直接舍弃 while (!minHeap.isEmpty() && minHeap.peek() < curDay) { minHeap.poll(); } if (!minHeap.isEmpty()) { //每天 <SUF> minHeap.poll(); res++; } curDay++; } return res; } }
0
41842_0
package util; import lombok.Data; import java.util.ArrayList; import java.util.List; /* * 机器 * */ @Data public class Machine { //机器名称 private String name; //机器能干的工序 private List<Integer> ability=new ArrayList<>(); //机器的当前位置 private int location; private int time; public int getTime() { return time; } public void setTime(int time) { this.time = time; } public void addTime(int time1){ time=time+time1; } public void subTime(int time2){ time=time+time2; } public int getLocation() { return location; } public void setLocation(int location) { this.location = location; } public Machine(String name){ this.name=name;} public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Integer> getAbility() { return ability; } public void setAbility(List<Integer> ability) { this.ability = ability; } }
7lldevelopers/FJSP-AGV
src/main/java/util/Machine.java
275
/* * 机器 * */
block_comment
zh-cn
package util; import lombok.Data; import java.util.ArrayList; import java.util.List; /* * 机器 <SUF>*/ @Data public class Machine { //机器名称 private String name; //机器能干的工序 private List<Integer> ability=new ArrayList<>(); //机器的当前位置 private int location; private int time; public int getTime() { return time; } public void setTime(int time) { this.time = time; } public void addTime(int time1){ time=time+time1; } public void subTime(int time2){ time=time+time2; } public int getLocation() { return location; } public void setLocation(int location) { this.location = location; } public Machine(String name){ this.name=name;} public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Integer> getAbility() { return ability; } public void setAbility(List<Integer> ability) { this.ability = ability; } }
1
43120_4
package com.test.entity; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 打印存在Object里的实体类的字段和值 * @Explain * 为了方便开发中便于调试,写了这个接口,存入实体类,反射遍历出这个实体类里面的所有字段和值, * 这里只写出了两个常用的普通字段和值的输出,有其他集合或者更负责的解析可以自己修改代码 * @author sevennight */ public class EmptyPrinting { /** * 输出实体类 * @param model */ public static void print(Object model) { Class cls = model.getClass(); Field[] fields = cls.getDeclaredFields(); System.out.println("实体类:"+model.getClass().getName()); for (Field field : fields) { char[] buffer = field.getName().toCharArray(); buffer[0] = Character.toUpperCase(buffer[0]); String mothodName = "get" + new String(buffer); try { Method method = cls.getDeclaredMethod(mothodName); Object resutl = method.invoke(model, null); System.out.println(field.getName() + " : " + resutl); } catch (Exception e) { e.printStackTrace(); } } } /** * 输出实体类指定的属性 * @param model * @param fields */ public static void print(Object model, String[] fields) { Class cls = model.getClass(); System.out.println("实体类:"+model.getClass().getName()); for (String field : fields) { char[] buffer = field.toCharArray(); buffer[0] = Character.toUpperCase(buffer[0]); String mothodName = "get" + new String(buffer); try { Method method = cls.getDeclaredMethod(mothodName); Object resutl = method.invoke(model, null); System.out.println(field + ": " + resutl); } catch (Exception e) { e.printStackTrace(); } } } //测试 public static void main(String[] args) throws Exception { //这是一个实体类 ClassBean1009 bean1009 = new ClassBean1009(); bean1009.setNzxHelpMeType(1); bean1009.setSzxAuthString("234242342343243"); //现在是一个未知类型的对象(模拟一下) Object obj = bean1009; //调用 print(obj); } }
7ye/javacode
EmptyPrinting.java
634
//现在是一个未知类型的对象(模拟一下)
line_comment
zh-cn
package com.test.entity; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 打印存在Object里的实体类的字段和值 * @Explain * 为了方便开发中便于调试,写了这个接口,存入实体类,反射遍历出这个实体类里面的所有字段和值, * 这里只写出了两个常用的普通字段和值的输出,有其他集合或者更负责的解析可以自己修改代码 * @author sevennight */ public class EmptyPrinting { /** * 输出实体类 * @param model */ public static void print(Object model) { Class cls = model.getClass(); Field[] fields = cls.getDeclaredFields(); System.out.println("实体类:"+model.getClass().getName()); for (Field field : fields) { char[] buffer = field.getName().toCharArray(); buffer[0] = Character.toUpperCase(buffer[0]); String mothodName = "get" + new String(buffer); try { Method method = cls.getDeclaredMethod(mothodName); Object resutl = method.invoke(model, null); System.out.println(field.getName() + " : " + resutl); } catch (Exception e) { e.printStackTrace(); } } } /** * 输出实体类指定的属性 * @param model * @param fields */ public static void print(Object model, String[] fields) { Class cls = model.getClass(); System.out.println("实体类:"+model.getClass().getName()); for (String field : fields) { char[] buffer = field.toCharArray(); buffer[0] = Character.toUpperCase(buffer[0]); String mothodName = "get" + new String(buffer); try { Method method = cls.getDeclaredMethod(mothodName); Object resutl = method.invoke(model, null); System.out.println(field + ": " + resutl); } catch (Exception e) { e.printStackTrace(); } } } //测试 public static void main(String[] args) throws Exception { //这是一个实体类 ClassBean1009 bean1009 = new ClassBean1009(); bean1009.setNzxHelpMeType(1); bean1009.setSzxAuthString("234242342343243"); //现在 <SUF> Object obj = bean1009; //调用 print(obj); } }
0
47093_2
package com.example.SingleDog.chain; import lombok.AllArgsConstructor; import lombok.Data; import java.util.List; /** * 分手 */ @Data @AllArgsConstructor public class SingleDogContext { // 是否最终改变 String type; // 意难平策略 private List<String> strategy; // 领悟到的精髓 private List<String> trait; }
805369979/javaDesignShare
src/main/java/com/example/SingleDog/chain/SingleDogContext.java
102
// 意难平策略
line_comment
zh-cn
package com.example.SingleDog.chain; import lombok.AllArgsConstructor; import lombok.Data; import java.util.List; /** * 分手 */ @Data @AllArgsConstructor public class SingleDogContext { // 是否最终改变 String type; // 意难 <SUF> private List<String> strategy; // 领悟到的精髓 private List<String> trait; }
1
36967_1
package com.xiaochao.lcrapiddevelop.UI.entity; /** * Created by Administrator on 2016/5/3. */ public class VideoListDto { /** * pictureUrl : http://img1.youzy.cn/content/media/thumbs/p00188299.jpeg * title : 高考如何备考及大幅提分 * introduction : 程老师结合多年高考备考指导经验,为考生精心讲授快速提高考分的方法,以及如何提高上课效率及做作业效率,科学制定学习计划,大幅提高考分的考前复习妙法等。", 程老师结合多年高考备考指导经验,为考生精心讲授快速提高考分的方法,以及如何提高上课效率及做作业效率,科学制定学习计划,大幅提高考分的考前复习妙法等。", 程老师结合多年高考备考指导经验,为考生精心讲授快速提高考分的方法,以及如何提高上课效率及做作业效率,科学制定学习计划,大幅提高考分的考前复习妙法等。 * viodeoUrl : http://200000455.vod.myqcloud.com/200000455_257c0a4c0b7411e6a480af2c82dfb2fb.f20.mp4 * id : 1 */ private String pictureUrl; private String title; private String introduction; private String viodeoUrl; private int id; public String getPictureUrl() { return pictureUrl; } public void setPictureUrl(String pictureUrl) { this.pictureUrl = pictureUrl; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getViodeoUrl() { return viodeoUrl; } public void setViodeoUrl(String viodeoUrl) { this.viodeoUrl = viodeoUrl; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
80945540/LCRapidDevelop
app/src/main/java/com/xiaochao/lcrapiddevelop/UI/entity/VideoListDto.java
604
/** * pictureUrl : http://img1.youzy.cn/content/media/thumbs/p00188299.jpeg * title : 高考如何备考及大幅提分 * introduction : 程老师结合多年高考备考指导经验,为考生精心讲授快速提高考分的方法,以及如何提高上课效率及做作业效率,科学制定学习计划,大幅提高考分的考前复习妙法等。", 程老师结合多年高考备考指导经验,为考生精心讲授快速提高考分的方法,以及如何提高上课效率及做作业效率,科学制定学习计划,大幅提高考分的考前复习妙法等。", 程老师结合多年高考备考指导经验,为考生精心讲授快速提高考分的方法,以及如何提高上课效率及做作业效率,科学制定学习计划,大幅提高考分的考前复习妙法等。 * viodeoUrl : http://200000455.vod.myqcloud.com/200000455_257c0a4c0b7411e6a480af2c82dfb2fb.f20.mp4 * id : 1 */
block_comment
zh-cn
package com.xiaochao.lcrapiddevelop.UI.entity; /** * Created by Administrator on 2016/5/3. */ public class VideoListDto { /** * pic <SUF>*/ private String pictureUrl; private String title; private String introduction; private String viodeoUrl; private int id; public String getPictureUrl() { return pictureUrl; } public void setPictureUrl(String pictureUrl) { this.pictureUrl = pictureUrl; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getViodeoUrl() { return viodeoUrl; } public void setViodeoUrl(String viodeoUrl) { this.viodeoUrl = viodeoUrl; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1
55384_2
/* * Copyright (C) 2019 823984418@qq.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.dxzc.jstype; import java.util.Collections; import java.util.Iterator; import net.dxzc.util.Action; /** * 一个原型. * * @author 823984418@qq.com */ public interface Type extends Iterable<String> { /** * 默认以此标志不可枚举. */ public static final String NU_ENUM = "#"; /** * 表述多个类型. * * @param types 多个类型 * @return 表述字符串 */ public static String typesToString(Iterator<Type> types) { if (!types.hasNext()) { return "Undefined"; } StringBuilder sb = new StringBuilder(); for (;;) { Type t = types.next(); sb.append(t); if (!types.hasNext()) { return sb.toString(); } sb.append("|"); } } /** * 被调用在哪些类型上. */ public static final String THIS = NU_ENUM + "this"; /** * 实例化类型. */ public static final String NEW = NU_ENUM + "new"; /** * 返回值类型 */ public static final String RETURN = NU_ENUM + "return"; /** * 包含类型. */ public static final String CONTAIN = NU_ENUM + "contain"; /** * 获取成员类型. 实现对此动作也许会创建成员,也许会告知不可能具有此成员 * * @param name 成员 * @param action 对此的动做 * @return 如果(将来也)不可能拥有此成员则返回{@code false} */ public boolean addMemberAction(String name, Action<Type> action); /** * 尝试对此类型进行一次成员赋值.实现也许会为此新建一个成员,也许会拒绝此操作 为空表示初始化 * * @param name 成员 * @param type 新增的类型 * @return 是否成功 */ public boolean putMember(String name, Type type); /** * 迭代所有的可枚举成员. * * @return 成员迭代器 */ @Override public Iterator<String> iterator(); /** * 迭代所有成员. * * @return 成员迭代器 */ public Iterator<String> iteratorAll(); /** * 获取某个成员的所有类型.实现也许会返回{@code null}来表示(暂时)不存在此成员 * * @param name 成员 * @return 类型迭代器 */ public Iterator<Type> getMemberType(String name); /** * 指示此类型是否视为数值. * * @return 是否为数值 */ public default boolean isNumberType() { return false; } /** * 获取某个成员的所有类型.如果不存在则返回空的迭代器 * * @param name 成员 * @return 类型迭代器 */ public default Iterator<Type> getMemberTypeOrEmpty(String name) { Iterator<Type> r = getMemberType(name); if (r == null) { return Collections.<Type>emptyIterator(); } return r; } /** * 获取文档信息. * * @return 文档信息 */ public String getDoc(); /** * 尝试以指定参数调用. * * @param r 返回类型操作 * @param i 调用域 * @param args 参数 * @return 可否调用 */ public default boolean invoke(Action<Type> r, Rvalue i, Rvalue... args) { return false; } /** * 尝试以指定参数实例化. * * @param r 返回类型操作 * @param i 调用域 * @param args 参数 * @return 可否调用 */ public default boolean newInstance(Action<Type> r, Rvalue i, Rvalue... args) { return false; } /** * 显示形参信息. * * @return 表述字符串 */ public default String argsToString() { return "()"; } /** * 显示函数类型信息. * * @return 表述字符串 */ public default String functionToString() { StringBuilder sb = new StringBuilder(); sb.append(argsToString()); sb.append(":"); sb.append(typesToString(getMemberTypeOrEmpty(RETURN))); return sb.toString(); } /** * 显示数组类型信息. * * @return 表述字符串 */ public default String containToString() { Iterator<Type> contain = getMemberTypeOrEmpty(CONTAIN); if (contain == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(typesToString(contain)); sb.append("]"); return sb.toString(); } /** * 显示类型成员信息. * * @return 表述字符串 */ public default String membersToString() { StringBuilder sb = new StringBuilder(); sb.append("{"); for (String m : this) { sb.append(m); sb.append(":"); sb.append(typesToString(getMemberTypeOrEmpty(m))); } sb.append("}"); return sb.toString(); } @Override public String toString(); }
823984418/JsType
src/net/dxzc/jstype/Type.java
1,408
/** * 默认以此标志不可枚举. */
block_comment
zh-cn
/* * Copyright (C) 2019 823984418@qq.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.dxzc.jstype; import java.util.Collections; import java.util.Iterator; import net.dxzc.util.Action; /** * 一个原型. * * @author 823984418@qq.com */ public interface Type extends Iterable<String> { /** * 默认以 <SUF>*/ public static final String NU_ENUM = "#"; /** * 表述多个类型. * * @param types 多个类型 * @return 表述字符串 */ public static String typesToString(Iterator<Type> types) { if (!types.hasNext()) { return "Undefined"; } StringBuilder sb = new StringBuilder(); for (;;) { Type t = types.next(); sb.append(t); if (!types.hasNext()) { return sb.toString(); } sb.append("|"); } } /** * 被调用在哪些类型上. */ public static final String THIS = NU_ENUM + "this"; /** * 实例化类型. */ public static final String NEW = NU_ENUM + "new"; /** * 返回值类型 */ public static final String RETURN = NU_ENUM + "return"; /** * 包含类型. */ public static final String CONTAIN = NU_ENUM + "contain"; /** * 获取成员类型. 实现对此动作也许会创建成员,也许会告知不可能具有此成员 * * @param name 成员 * @param action 对此的动做 * @return 如果(将来也)不可能拥有此成员则返回{@code false} */ public boolean addMemberAction(String name, Action<Type> action); /** * 尝试对此类型进行一次成员赋值.实现也许会为此新建一个成员,也许会拒绝此操作 为空表示初始化 * * @param name 成员 * @param type 新增的类型 * @return 是否成功 */ public boolean putMember(String name, Type type); /** * 迭代所有的可枚举成员. * * @return 成员迭代器 */ @Override public Iterator<String> iterator(); /** * 迭代所有成员. * * @return 成员迭代器 */ public Iterator<String> iteratorAll(); /** * 获取某个成员的所有类型.实现也许会返回{@code null}来表示(暂时)不存在此成员 * * @param name 成员 * @return 类型迭代器 */ public Iterator<Type> getMemberType(String name); /** * 指示此类型是否视为数值. * * @return 是否为数值 */ public default boolean isNumberType() { return false; } /** * 获取某个成员的所有类型.如果不存在则返回空的迭代器 * * @param name 成员 * @return 类型迭代器 */ public default Iterator<Type> getMemberTypeOrEmpty(String name) { Iterator<Type> r = getMemberType(name); if (r == null) { return Collections.<Type>emptyIterator(); } return r; } /** * 获取文档信息. * * @return 文档信息 */ public String getDoc(); /** * 尝试以指定参数调用. * * @param r 返回类型操作 * @param i 调用域 * @param args 参数 * @return 可否调用 */ public default boolean invoke(Action<Type> r, Rvalue i, Rvalue... args) { return false; } /** * 尝试以指定参数实例化. * * @param r 返回类型操作 * @param i 调用域 * @param args 参数 * @return 可否调用 */ public default boolean newInstance(Action<Type> r, Rvalue i, Rvalue... args) { return false; } /** * 显示形参信息. * * @return 表述字符串 */ public default String argsToString() { return "()"; } /** * 显示函数类型信息. * * @return 表述字符串 */ public default String functionToString() { StringBuilder sb = new StringBuilder(); sb.append(argsToString()); sb.append(":"); sb.append(typesToString(getMemberTypeOrEmpty(RETURN))); return sb.toString(); } /** * 显示数组类型信息. * * @return 表述字符串 */ public default String containToString() { Iterator<Type> contain = getMemberTypeOrEmpty(CONTAIN); if (contain == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(typesToString(contain)); sb.append("]"); return sb.toString(); } /** * 显示类型成员信息. * * @return 表述字符串 */ public default String membersToString() { StringBuilder sb = new StringBuilder(); sb.append("{"); for (String m : this) { sb.append(m); sb.append(":"); sb.append(typesToString(getMemberTypeOrEmpty(m))); } sb.append("}"); return sb.toString(); } @Override public String toString(); }
1
11369_7
package cn.ve.lucene.elasticsearch; import java.io.IOException; /** * @author ve * @date 2020/4/1 11:05 */ public class EsMain { public static void main(String[] args) throws IOException { // 创建索引 // EsKit.createIndex("test"); // 为索引创建mappings信息 /*XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); { builder.startObject("properties"); { builder.startObject("id"); { builder.field("type", "long"); builder.field("store", true); } builder.endObject(); builder.startObject("title"); { builder.field("type", "text"); builder.field("store", true); builder.field("analyzer", "ik_smart"); } builder.endObject(); builder.startObject("content"); { builder.field("type", "text"); builder.field("store", true); builder.field("analyzer", "ik_smart"); } builder.endObject(); } builder.endObject(); } builder.endObject(); EsKit.putMapping("test", builder);*/ // 创建数据 /*XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); { builder.field("id", 12112L); builder.field("title", "尲尬”,最早见于《说文解字》:“尲尬、行不正也。”普遍用于《水浒传》《西游 记》《红楼梦》等元明清时期的小说当中,南方方言中也多有使用,如"); builder.field("content", "通话。通常是说人遇到的一种情景,让人觉得窘迫。都形容在心理学上,意味着自身或见到他人,在某种场合下,被逼迫到窘境,发生了无法预料的情况,而体现出的不知所措"); } builder.endObject(); EsKit.index(new IndexRequest().index("test").source(builder));*/ // 检索数据 // SearchResponse searchResponse = EsKit.query("test", "content", "形容"); // System.out.println(searchResponse.toString()); // 分词检索数据 // SearchResponse searchResponse = EsKit.query("test", "ik_smart", "content", "自身或见到 发生了无法预料"); // System.out.println(searchResponse.toString()); } }
834250018/lucene-demo
elasticsearch/src/main/java/cn/ve/lucene/elasticsearch/EsMain.java
618
// 检索数据
line_comment
zh-cn
package cn.ve.lucene.elasticsearch; import java.io.IOException; /** * @author ve * @date 2020/4/1 11:05 */ public class EsMain { public static void main(String[] args) throws IOException { // 创建索引 // EsKit.createIndex("test"); // 为索引创建mappings信息 /*XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); { builder.startObject("properties"); { builder.startObject("id"); { builder.field("type", "long"); builder.field("store", true); } builder.endObject(); builder.startObject("title"); { builder.field("type", "text"); builder.field("store", true); builder.field("analyzer", "ik_smart"); } builder.endObject(); builder.startObject("content"); { builder.field("type", "text"); builder.field("store", true); builder.field("analyzer", "ik_smart"); } builder.endObject(); } builder.endObject(); } builder.endObject(); EsKit.putMapping("test", builder);*/ // 创建数据 /*XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); { builder.field("id", 12112L); builder.field("title", "尲尬”,最早见于《说文解字》:“尲尬、行不正也。”普遍用于《水浒传》《西游 记》《红楼梦》等元明清时期的小说当中,南方方言中也多有使用,如"); builder.field("content", "通话。通常是说人遇到的一种情景,让人觉得窘迫。都形容在心理学上,意味着自身或见到他人,在某种场合下,被逼迫到窘境,发生了无法预料的情况,而体现出的不知所措"); } builder.endObject(); EsKit.index(new IndexRequest().index("test").source(builder));*/ // 检索 <SUF> // SearchResponse searchResponse = EsKit.query("test", "content", "形容"); // System.out.println(searchResponse.toString()); // 分词检索数据 // SearchResponse searchResponse = EsKit.query("test", "ik_smart", "content", "自身或见到 发生了无法预料"); // System.out.println(searchResponse.toString()); } }
1
33857_0
package cn.ve.design_pattern.behavioral_patterns.mediator; /** * 中介者模式 * 类似于消息队列 * 生产者只考虑产生数据,然后把数据交给中介(消息队列),不考虑数据被使用还是丢弃. * 消费者从中介拿到数据,不在乎数据是谁产生的,怎么产生的 * * @author 83425 * @date 2020/12/15 */ public class Main { // 略 }
834250018/some-demo
design-pattern/src/main/java/cn/ve/design_pattern/behavioral_patterns/mediator/Main.java
132
/** * 中介者模式 * 类似于消息队列 * 生产者只考虑产生数据,然后把数据交给中介(消息队列),不考虑数据被使用还是丢弃. * 消费者从中介拿到数据,不在乎数据是谁产生的,怎么产生的 * * @author 83425 * @date 2020/12/15 */
block_comment
zh-cn
package cn.ve.design_pattern.behavioral_patterns.mediator; /** * 中介者 <SUF>*/ public class Main { // 略 }
1
23268_1
//this public class Emp{ String name; int age; String des; public Emp(String name,int agess,String desss){ this.name = name; //不使用this时,默认先从当前函数寻找变量,找不到再从类里面寻找,当有同名变量是,需要使用this来表明使用类的变量 this.age = agess; des = desss; } public void printEmp(){ System.out.println("我叫"+name); System.out.println("年龄"+age); System.out.println("爱好"+des); } }
835501209/JavaTest
Emp.java
148
//不使用this时,默认先从当前函数寻找变量,找不到再从类里面寻找,当有同名变量是,需要使用this来表明使用类的变量
line_comment
zh-cn
//this public class Emp{ String name; int age; String des; public Emp(String name,int agess,String desss){ this.name = name; //不使 <SUF> this.age = agess; des = desss; } public void printEmp(){ System.out.println("我叫"+name); System.out.println("年龄"+age); System.out.println("爱好"+des); } }
0
28178_22
/********************************************************************************* * * * The MIT License (MIT) * * * * Copyright (c) 2015-2024 miaixz.org and other contributors. * * * * 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 org.miaixz.bus.core.math; import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.StringKit; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; /** * 数字解析器 * 用于将字符串解析为对应的数字类型,支持包括: * <ul> * <li>0开头的忽略开头的0</li> * <li>空串返回0</li> * <li>NaN返回0</li> * <li>其它情况按照10进制转换</li> * <li>.123形式返回0.123(按照小于0的小数对待)</li> * </ul> * * <p> * 构造时可选是否将NaN转为0,默认为true。 * 参考:https://stackoverflow.com/questions/5876369/why-does-casting-double-nan-to-int-not-throw-an-exception-in-java * </p> * * @author Kimi Liu * @since Java 17+ */ public class NumberParser { /** * 单例 */ public static final NumberParser INSTANCE = of(null); private static final String NaN = "NaN"; private final Locale locale; private final boolean zeroIfNaN; /** * 构造 * * @param locale 地域,{@code null}表示默认本地 * @param zeroIfNaN 如果用户传入NaN,是否转为0,如果为{@code false},则抛出{@link NumberFormatException} */ public NumberParser(final Locale locale, final boolean zeroIfNaN) { this.locale = locale; this.zeroIfNaN = zeroIfNaN; } /** * 构建NumberParser * * @param locale 地域,{@code null}表示默认本地 * @return NumberParser */ public static NumberParser of(final Locale locale) { return of(locale, true); } /** * 构建NumberParser * * @param locale 地域,{@code null}表示默认本地 * @param zeroIfNaN 如果用户传入NaN,是否转为0,如果为{@code false},则抛出{@link NumberFormatException} * @return NumberParser */ public static NumberParser of(final Locale locale, final boolean zeroIfNaN) { return new NumberParser(locale, zeroIfNaN); } /** * 解析转换数字字符串为int型数字,规则如下: * * <pre> * 1、0x开头的视为16进制数字 * 2、0开头的忽略开头的0 * 3、其它情况按照10进制转换 * 4、空串返回0 * 5、.123形式返回0(按照小于0的小数对待) * 6、123.56截取小数点之前的数字,忽略小数部分 * 7、科学计数法抛出NumberFormatException异常 * </pre> * * @param numberStr 数字字符串 * @return the int * @throws NumberFormatException 数字格式异常 */ public int parseInt(final String numberStr) throws NumberFormatException { if (isBlankOrNaN(numberStr)) { return 0; } if (StringKit.startWithIgnoreCase(numberStr, "0x")) { // 0x04表示16进制数 return Integer.parseInt(numberStr.substring(2), 16); } if (StringKit.containsIgnoreCase(numberStr, "E")) { // 科学计数法忽略支持,科学计数法一般用于表示非常小和非常大的数字,这类数字转换为int后精度丢失,没有意义。 throw new NumberFormatException(StringKit.format("Unsupported int format: [{}]", numberStr)); } try { return Integer.parseInt(numberStr); } catch (final NumberFormatException e) { return doParse(numberStr).intValue(); } } /** * 解析转换数字字符串为long型数字,规则如下: * * <pre> * 1、0x开头的视为16进制数字 * 2、0开头的忽略开头的0 * 3、空串返回0 * 4、其它情况按照10进制转换 * 5、.123形式返回0(按照小于0的小数对待) * 6、123.56截取小数点之前的数字,忽略小数部分 * </pre> * * @param numberStr 数字字符串 * @return the long */ public long parseLong(final String numberStr) { if (isBlankOrNaN(numberStr)) { return 0; } if (StringKit.startWithIgnoreCase(numberStr, "0x")) { // 0x04表示16进制数 return Long.parseLong(numberStr.substring(2), 16); } try { return Long.parseLong(numberStr); } catch (final NumberFormatException e) { return doParse(numberStr).longValue(); } } /** * 解析转换数字字符串为long型数字,规则如下: * * <pre> * 1、0开头的忽略开头的0 * 2、空串返回0 * 3、其它情况按照10进制转换 * 4、.123形式返回0.123(按照小于0的小数对待) * </pre> * * @param numberStr 数字字符串 * @return the long */ public float parseFloat(final String numberStr) { if (isBlankOrNaN(numberStr)) { return 0; } try { return Float.parseFloat(numberStr); } catch (final NumberFormatException e) { return doParse(numberStr).floatValue(); } } /** * 解析转换数字字符串为long型数字,规则如下: * * <pre> * 1、0开头的忽略开头的0 * 2、空串返回0 * 3、其它情况按照10进制转换 * 4、.123形式返回0.123(按照小于0的小数对待) * 5、NaN返回0 * </pre> * * @param numberStr 数字字符串 * @return the double */ public double parseDouble(final String numberStr) { if (isBlankOrNaN(numberStr)) { return 0; } try { return Double.parseDouble(numberStr); } catch (final NumberFormatException e) { return doParse(numberStr).doubleValue(); } } /** * 解析为{@link BigInteger},支持16进制、10进制和8进制,如果传入空白串返回null * * @param text 数字字符串 * @return {@link BigInteger} */ public BigInteger parseBigInteger(String text) { text = StringKit.trimToNull(text); if (null == text) { return null; } int pos = 0; // 数字字符串位置 int radix = 10; boolean negate = false; // 负数与否 if (text.startsWith(Symbol.MINUS)) { negate = true; pos = 1; } if (text.startsWith("0x", pos) || text.startsWith("0X", pos)) { // hex radix = 16; pos += 2; } else if (text.startsWith(Symbol.SHAPE, pos)) { // alternative hex (allowed by Long/Integer) radix = 16; pos++; } else if (text.startsWith("0", pos) && text.length() > pos + 1) { // octal; so long as there are additional digits radix = 8; pos++; } // default is to treat as decimal if (pos > 0) { text = text.substring(pos); } final BigInteger value = new BigInteger(text, radix); return negate ? value.negate() : value; } /** * 将指定字符串转换为{@link Number} 对象 * 此方法不支持科学计数法 * * <ul> * <li>空白符和NaN转换为0</li> * <li>0x开头使用16进制解析为Long类型</li> * </ul> * * <p> * 需要注意的是,在不同Locale下,数字的表示形式也是不同的,例如: * 德国、荷兰、比利时、丹麦、意大利、罗马尼亚和欧洲大多地区使用`,`区分小数 * 也就是说,在这些国家地区,1.20表示120,而非1.2。 * </p> * * @param numberStr 数字字符串 * @return Number对象 * @throws NumberFormatException 包装了{@link ParseException},当给定的数字字符串无法解析时抛出 */ public Number parseNumber(final String numberStr) throws NumberFormatException { if (isBlankOrNaN(numberStr)) { // 在JDK9+中,NaN的处理逻辑是返回0,此处保持一致 return 0; } // 16进制 if (StringKit.startWithIgnoreCase(numberStr, "0x")) { // 0x04表示16进制数 return Long.parseLong(numberStr.substring(2), 16); } return doParse(numberStr); } /** * 使用{@link NumberFormat} 完成数字解析 * 如果为{@link DecimalFormat} * * @return 数字 */ private Number doParse(String numberStr) { Locale locale = this.locale; if (null == locale) { locale = Locale.getDefault(Locale.Category.FORMAT); } if (StringKit.startWith(numberStr, Symbol.C_PLUS)) { numberStr = StringKit.subSuf(numberStr, 1); } try { final NumberFormat format = NumberFormat.getInstance(locale); if (format instanceof DecimalFormat) { // 当字符串数字超出double的长度时,会导致截断,此处使用BigDecimal接收 ((DecimalFormat) format).setParseBigDecimal(true); } return format.parse(numberStr); } catch (final ParseException e) { final NumberFormatException nfe = new NumberFormatException(e.getMessage()); nfe.initCause(e); throw nfe; } } /** * 是否空白串或者NaN * 如果{@link #zeroIfNaN}为{@code false},则抛出{@link NumberFormatException} * * @return 是否空白串或者NaN */ private boolean isBlankOrNaN(final String numberStr) throws NumberFormatException { if (StringKit.isBlank(numberStr)) { return true; } if (NaN.equals(numberStr)) { if (zeroIfNaN) { return true; } else { throw new NumberFormatException("Can not parse NaN when 'zeroIfNaN' is false!"); } } return false; } }
839128/bus
bus-core/src/main/java/org/miaixz/bus/core/math/NumberParser.java
2,974
// 16进制
line_comment
zh-cn
/********************************************************************************* * * * The MIT License (MIT) * * * * Copyright (c) 2015-2024 miaixz.org and other contributors. * * * * 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 org.miaixz.bus.core.math; import org.miaixz.bus.core.lang.Symbol; import org.miaixz.bus.core.xyz.StringKit; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; /** * 数字解析器 * 用于将字符串解析为对应的数字类型,支持包括: * <ul> * <li>0开头的忽略开头的0</li> * <li>空串返回0</li> * <li>NaN返回0</li> * <li>其它情况按照10进制转换</li> * <li>.123形式返回0.123(按照小于0的小数对待)</li> * </ul> * * <p> * 构造时可选是否将NaN转为0,默认为true。 * 参考:https://stackoverflow.com/questions/5876369/why-does-casting-double-nan-to-int-not-throw-an-exception-in-java * </p> * * @author Kimi Liu * @since Java 17+ */ public class NumberParser { /** * 单例 */ public static final NumberParser INSTANCE = of(null); private static final String NaN = "NaN"; private final Locale locale; private final boolean zeroIfNaN; /** * 构造 * * @param locale 地域,{@code null}表示默认本地 * @param zeroIfNaN 如果用户传入NaN,是否转为0,如果为{@code false},则抛出{@link NumberFormatException} */ public NumberParser(final Locale locale, final boolean zeroIfNaN) { this.locale = locale; this.zeroIfNaN = zeroIfNaN; } /** * 构建NumberParser * * @param locale 地域,{@code null}表示默认本地 * @return NumberParser */ public static NumberParser of(final Locale locale) { return of(locale, true); } /** * 构建NumberParser * * @param locale 地域,{@code null}表示默认本地 * @param zeroIfNaN 如果用户传入NaN,是否转为0,如果为{@code false},则抛出{@link NumberFormatException} * @return NumberParser */ public static NumberParser of(final Locale locale, final boolean zeroIfNaN) { return new NumberParser(locale, zeroIfNaN); } /** * 解析转换数字字符串为int型数字,规则如下: * * <pre> * 1、0x开头的视为16进制数字 * 2、0开头的忽略开头的0 * 3、其它情况按照10进制转换 * 4、空串返回0 * 5、.123形式返回0(按照小于0的小数对待) * 6、123.56截取小数点之前的数字,忽略小数部分 * 7、科学计数法抛出NumberFormatException异常 * </pre> * * @param numberStr 数字字符串 * @return the int * @throws NumberFormatException 数字格式异常 */ public int parseInt(final String numberStr) throws NumberFormatException { if (isBlankOrNaN(numberStr)) { return 0; } if (StringKit.startWithIgnoreCase(numberStr, "0x")) { // 0x04表示16进制数 return Integer.parseInt(numberStr.substring(2), 16); } if (StringKit.containsIgnoreCase(numberStr, "E")) { // 科学计数法忽略支持,科学计数法一般用于表示非常小和非常大的数字,这类数字转换为int后精度丢失,没有意义。 throw new NumberFormatException(StringKit.format("Unsupported int format: [{}]", numberStr)); } try { return Integer.parseInt(numberStr); } catch (final NumberFormatException e) { return doParse(numberStr).intValue(); } } /** * 解析转换数字字符串为long型数字,规则如下: * * <pre> * 1、0x开头的视为16进制数字 * 2、0开头的忽略开头的0 * 3、空串返回0 * 4、其它情况按照10进制转换 * 5、.123形式返回0(按照小于0的小数对待) * 6、123.56截取小数点之前的数字,忽略小数部分 * </pre> * * @param numberStr 数字字符串 * @return the long */ public long parseLong(final String numberStr) { if (isBlankOrNaN(numberStr)) { return 0; } if (StringKit.startWithIgnoreCase(numberStr, "0x")) { // 0x04表示16进制数 return Long.parseLong(numberStr.substring(2), 16); } try { return Long.parseLong(numberStr); } catch (final NumberFormatException e) { return doParse(numberStr).longValue(); } } /** * 解析转换数字字符串为long型数字,规则如下: * * <pre> * 1、0开头的忽略开头的0 * 2、空串返回0 * 3、其它情况按照10进制转换 * 4、.123形式返回0.123(按照小于0的小数对待) * </pre> * * @param numberStr 数字字符串 * @return the long */ public float parseFloat(final String numberStr) { if (isBlankOrNaN(numberStr)) { return 0; } try { return Float.parseFloat(numberStr); } catch (final NumberFormatException e) { return doParse(numberStr).floatValue(); } } /** * 解析转换数字字符串为long型数字,规则如下: * * <pre> * 1、0开头的忽略开头的0 * 2、空串返回0 * 3、其它情况按照10进制转换 * 4、.123形式返回0.123(按照小于0的小数对待) * 5、NaN返回0 * </pre> * * @param numberStr 数字字符串 * @return the double */ public double parseDouble(final String numberStr) { if (isBlankOrNaN(numberStr)) { return 0; } try { return Double.parseDouble(numberStr); } catch (final NumberFormatException e) { return doParse(numberStr).doubleValue(); } } /** * 解析为{@link BigInteger},支持16进制、10进制和8进制,如果传入空白串返回null * * @param text 数字字符串 * @return {@link BigInteger} */ public BigInteger parseBigInteger(String text) { text = StringKit.trimToNull(text); if (null == text) { return null; } int pos = 0; // 数字字符串位置 int radix = 10; boolean negate = false; // 负数与否 if (text.startsWith(Symbol.MINUS)) { negate = true; pos = 1; } if (text.startsWith("0x", pos) || text.startsWith("0X", pos)) { // hex radix = 16; pos += 2; } else if (text.startsWith(Symbol.SHAPE, pos)) { // alternative hex (allowed by Long/Integer) radix = 16; pos++; } else if (text.startsWith("0", pos) && text.length() > pos + 1) { // octal; so long as there are additional digits radix = 8; pos++; } // default is to treat as decimal if (pos > 0) { text = text.substring(pos); } final BigInteger value = new BigInteger(text, radix); return negate ? value.negate() : value; } /** * 将指定字符串转换为{@link Number} 对象 * 此方法不支持科学计数法 * * <ul> * <li>空白符和NaN转换为0</li> * <li>0x开头使用16进制解析为Long类型</li> * </ul> * * <p> * 需要注意的是,在不同Locale下,数字的表示形式也是不同的,例如: * 德国、荷兰、比利时、丹麦、意大利、罗马尼亚和欧洲大多地区使用`,`区分小数 * 也就是说,在这些国家地区,1.20表示120,而非1.2。 * </p> * * @param numberStr 数字字符串 * @return Number对象 * @throws NumberFormatException 包装了{@link ParseException},当给定的数字字符串无法解析时抛出 */ public Number parseNumber(final String numberStr) throws NumberFormatException { if (isBlankOrNaN(numberStr)) { // 在JDK9+中,NaN的处理逻辑是返回0,此处保持一致 return 0; } // 16 <SUF> if (StringKit.startWithIgnoreCase(numberStr, "0x")) { // 0x04表示16进制数 return Long.parseLong(numberStr.substring(2), 16); } return doParse(numberStr); } /** * 使用{@link NumberFormat} 完成数字解析 * 如果为{@link DecimalFormat} * * @return 数字 */ private Number doParse(String numberStr) { Locale locale = this.locale; if (null == locale) { locale = Locale.getDefault(Locale.Category.FORMAT); } if (StringKit.startWith(numberStr, Symbol.C_PLUS)) { numberStr = StringKit.subSuf(numberStr, 1); } try { final NumberFormat format = NumberFormat.getInstance(locale); if (format instanceof DecimalFormat) { // 当字符串数字超出double的长度时,会导致截断,此处使用BigDecimal接收 ((DecimalFormat) format).setParseBigDecimal(true); } return format.parse(numberStr); } catch (final ParseException e) { final NumberFormatException nfe = new NumberFormatException(e.getMessage()); nfe.initCause(e); throw nfe; } } /** * 是否空白串或者NaN * 如果{@link #zeroIfNaN}为{@code false},则抛出{@link NumberFormatException} * * @return 是否空白串或者NaN */ private boolean isBlankOrNaN(final String numberStr) throws NumberFormatException { if (StringKit.isBlank(numberStr)) { return true; } if (NaN.equals(numberStr)) { if (zeroIfNaN) { return true; } else { throw new NumberFormatException("Can not parse NaN when 'zeroIfNaN' is false!"); } } return false; } }
0
10016_211
//package com.hxsg.battle.controller; // //import com.alibaba.fastjson.JSONObject; //import com.hxsg.CommonUtil.CommonUtilAjax; //import com.hxsg.CommonUtil.Msg; //import com.hxsg.CommonUtil.RequestParamFormat; //import com.hxsg.Dao.*; //import com.hxsg.po.*; // //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.ComponentScan; //import org.springframework.context.annotation.Configuration; //import org.springframework.stereotype.Controller; //import org.springframework.ui.Model; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RequestMethod; //import org.springframework.web.bind.annotation.RequestParam; //import org.springframework.web.bind.annotation.ResponseBody; // //import javax.jws.WebParam; //import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpSession; //import java.io.PrintWriter; //import java.util.ArrayList; //import java.util.Date; //import java.util.List; //import java.util.Map; // ///** //* Created by dlf on 2015/12/31. //*/ //@Controller //@RequestMapping("/zhanchang") // //public class BattleController { // @Autowired // RoleMapper rm; // @Autowired // RoleFriendsMsgMapper rfmm; // @Autowired // jiangjunMapper jjm; // @Autowired // ZaWuMiaoShuMapper zwmsm; // @Autowired // YouJianWuPinMapper yjwpm; // @Autowired // WaBaoMapper wbm; // @Autowired // WaBaoMiaoShuMapper wbmsm; // // private Logger logger = LoggerFactory.getLogger(getClass()); // @RequestMapping(value = "/yzwb", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String yzwb(HttpSession session, HttpServletResponse response,Model model) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // if (wb != null && wb.getStatus().equals("0")) { // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "你的铁镐已磨损,确定花费100000银两购买铁镐吗?"); // out.write(obj.toString()); // out.flush(); // out.close(); // } // } // // if(li.size()<=0){ // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "小伙子第一次来矿洞吧,留下100000银买路财放你过去。"); // out.write(obj.toString()); // out.flush(); // out.close(); // // } // // return null; // } // @RequestMapping(value = "/appyzwb", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appyzwb(HttpSession session, HttpServletResponse response,HttpServletRequest request) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // if(r.size()>0){ // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // if (wb != null && wb.getStatus().equals("0")) { // CommonUtilAjax.sendAjaxList("msg", "你的铁镐已磨损,确定花费100000银两购买铁镐吗?",request,response); // } // } // if(li.size()<=0){ // CommonUtilAjax.sendAjaxList("msg", "小伙子第一次来矿洞吧,留下100000银买路财放你过去。",request,response); // } // } // // // return null; // } // @RequestMapping(value = "/wdbw", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String wdbw(HttpSession session, HttpServletResponse response,Model model) throws Exception { // // List<WaBaoMiaoShu> li=wbmsm.getWbByTime(); // response.setCharacterEncoding("utf-8"); // PrintWriter out=response.getWriter(); // JSONObject obj=new JSONObject();//使用json // if(li.size()>0&&li!=null){ // obj.put("code", 0); // obj.put("rmsg",li); // // }else{ // obj.put("code", 1); // } // System.out.println(obj.toString()); // // out.write(obj.toString()); // out.flush(); // out.close(); // return null; // } // @RequestMapping(value = "/appwdbw", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appwdbw(HttpSession session, HttpServletRequest request,HttpServletResponse response,Model model) throws Exception { // // List<WaBaoMiaoShu> li=wbmsm.getWbByTime(); // // if(li.size()>0&&li!=null){ // CommonUtilAjax.sendAjaxList("rmsg",li,request, response); // // }else{ // CommonUtilAjax.sendAjaxList("code",1,request, response); // } // // return null; // } // @RequestMapping(value = "/fee", method = {RequestMethod.GET, RequestMethod.POST}) // // public String fee(HttpSession session, HttpServletResponse response,Model model) throws Exception { // // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // model.addAttribute("wb",wb); // } // // //// Integer result = SetRoleMoney.setmoney(roleid, fee); //// if (result == 1) { //// wb.setStatus("1"); //// wb.setNum(50); //// model.addAttribute("wb",wb); //// response.setCharacterEncoding("utf-8"); //// PrintWriter out = response.getWriter(); //// JSONObject obj = new JSONObject();//使用json //// obj.put("msg", "消费成功,快点进去吧!"); //// out.write(obj.toString()); //// out.flush(); //// out.close(); //// //// } else { //// response.setCharacterEncoding("utf-8"); //// PrintWriter out = response.getWriter(); //// JSONObject obj = new JSONObject();//使用json //// obj.put("msg", "钱不够,还想进去?快走快走!"); //// out.write(obj.toString()); //// out.flush(); //// out.close(); //// //// } // return "战场/挖宝"; // } // //app fee刷新挖宝主页 // @RequestMapping(value = "/appfee", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appfee(HttpSession session, HttpServletResponse response,HttpServletRequest request) throws Exception { // // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // if(r.size()>0){ // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // CommonUtilAjax.sendAjaxList("wb",wb,request, response); // } // } // return null; // } // @RequestMapping(value = "/wabao", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public synchronized String wabao(HttpSession session, HttpServletResponse response,Model model) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // String rt = null; // Integer result =null; // int fee = 100000; // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // // if (wb != null && wb.getStatus().equals("0")) { // Role re = rm.selectByPrimaryKey(roleid); // int roleyin = re.getYin(); // if (roleyin >= fee) { // //扣费 // re.setYin(roleyin - fee); // rm.updateByPrimaryKeySelective(re); // result = 1; // } else { // result = 0; // } // // if (result == 1) { // // wb.setW1(1); // wb.setW2(1); // wb.setW3(1); // wb.setW4(1); // wb.setW5(1); // wb.setW6(1); // wb.setW7(1); // wb.setW8(1); // wb.setW9(1); // wb.setNum(50); // wb.setStatus("1"); // wbm.updateByPrimaryKeySelective(wb); // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "宝藏守卫:拿着铁镐去吧。祝你好运!"); // out.write(obj.toString()); // out.flush(); // out.close(); // } else { // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "宝藏守卫:钱不够,还想进去?快走快走!"); // out.write(obj.toString()); // out.flush(); // out.close(); // } // } // // } // // // if (li.size()<=0) { // Role re = rm.selectByPrimaryKey(roleid); // int roleyin = re.getYin(); // if (roleyin >= fee) { // //扣费 // re.setYin(roleyin - fee); // rm.updateByPrimaryKeySelective(re); // result = 1; // } else { // result = 0; // } // if (result == 1) { // WaBao wo = new WaBao(); // wo.setRoleid(roleid); // wo.setRolename(rolename); // wo.setW1(1); // wo.setW2(1); // wo.setW3(1); // wo.setW4(1); // wo.setW5(1); // wo.setW6(1); // wo.setW7(1); // wo.setW8(1); // wo.setW9(1); // wo.setNum(50); // wo.setStatus("1"); // wo.setDate(new Date()); // wo.setType("0"); // wbm.insertSelective(wo); // } else { // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "你所携带的银两不足!无法贿赂宝藏守卫"); // out.write(obj.toString()); // out.flush(); // out.close(); // } // } // // return null; // // } // @RequestMapping(value = "/appwabao", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public synchronized String appwabao(HttpServletRequest request,HttpSession session, HttpServletResponse response,Model model) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // if(r.size()>0){ // String rt = null; // Integer result =null; // int fee = 100000; // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // // if (wb != null && wb.getStatus().equals("0")) { // Role re = rm.selectByPrimaryKey(roleid); // int roleyin = re.getYin(); // if (roleyin >= fee) { // //扣费 // re.setYin(roleyin - fee); // rm.updateByPrimaryKeySelective(re); // result = 1; // } else { // result = 0; // } // // if (result == 1) { // // wb.setW1(1); // wb.setW2(1); // wb.setW3(1); // wb.setW4(1); // wb.setW5(1); // wb.setW6(1); // wb.setW7(1); // wb.setW8(1); // wb.setW9(1); // wb.setNum(50); // wb.setStatus("1"); // wbm.updateByPrimaryKeySelective(wb); // CommonUtilAjax.sendAjaxList("msg", "宝藏守卫:拿着铁镐去吧。祝你好运!",request,response); // // } else { // CommonUtilAjax.sendAjaxList("msg", "宝藏守卫:钱不够,还想进去?快走快走!",request,response); // // // } // } // // } // // // if (li.size()<=0) { // Role re = rm.selectByPrimaryKey(roleid); // int roleyin = re.getYin(); // if (roleyin >= fee) { // //扣费 // re.setYin(roleyin - fee); // rm.updateByPrimaryKeySelective(re); // result = 1; // } else { // result = 0; // } // if (result == 1) { // WaBao wo = new WaBao(); // wo.setRoleid(roleid); // wo.setRolename(rolename); // wo.setW1(1); // wo.setW2(1); // wo.setW3(1); // wo.setW4(1); // wo.setW5(1); // wo.setW6(1); // wo.setW7(1); // wo.setW8(1); // wo.setW9(1); // wo.setNum(50); // wo.setStatus("1"); // wo.setDate(new Date()); // wo.setType("0"); // wbm.insertSelective(wo); // } else { // CommonUtilAjax.sendAjaxList("msg", "你所携带的银两不足!无法贿赂宝藏守卫",request,response); // // // } // } // } // // // return null; // // } // @RequestMapping(value="/xhcs", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String xhcs(@RequestParam(value = "type",required = false)String type,WaBao wb,HttpSession session, HttpServletResponse response,Model model) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid=r.get(0).getId(); // String rolename=r.get(0).getJuesename(); // int gl=0; // String w=type; // WaBao wbo=wbm.selectByPrimaryKey(wb.getId()); // // // gl=(int)((Math.random()*100)+1); // // if(wb.getW1()!=null){ // wbo.setW1(wb.getW1()); // // } // if(wb.getW2()!=null){ // wbo.setW2(wb.getW2()); // // } // if(wb.getW3()!=null){ // wbo.setW3(wb.getW3()); // // } // if(wb.getW4()!=null){ // wbo.setW4(wb.getW4()); // // } // if(wb.getW5()!=null){ // wbo.setW5(wb.getW5()); // // } // if(wb.getW6()!=null){ // wbo.setW6(wb.getW6()); // // } // if(wb.getW7()!=null){ // wbo.setW7(wb.getW7()); // // } // if(wb.getW8()!=null){ // wbo.setW8(wb.getW8()); // // // } // if(wb.getW9()!=null){ // wbo.setW9(wb.getW9()); // // } // wbm.updateByPrimaryKeySelective(wbo); ////刷新继续挖宝 // WaBao sxwb=wbm.selectByPrimaryKey(wb.getId()); // if(sxwb.getW1()==0&&sxwb.getW2()==0&&sxwb.getW3()==0&&sxwb.getW4()==0&&sxwb.getW5()==0&&sxwb.getW6()==0&&sxwb.getW7()==0&&sxwb.getW8()==0&&sxwb.getW9()==0){ // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("sxmsg", "sx"); // out.write(obj.toString()); // out.flush(); // out.close(); // } // // // if(gl!=0&&gl>80){ // int wbgl=(int)((Math.random()*2)); // int rand=0; // if(wbgl==0){ // rand =(int)((Math.random()*17)+1); // } // if(wbgl==1){ // rand =(int)((Math.random()*21)+25); // // } // // // ZaWuMiaoShu zs=zwmsm.selectByPrimaryKey(rand); // jiangjun jj=new jiangjun(); // jj.setJjname(zs.getName()); // jj.setRoleid(roleid); // //jj.setType(zs.getType()); // List<jiangjun> li=jjm.selectAll(jj); // // if(li.size()>0){ // Integer num=li.get(0).getNum(); // if(num==null){ // num=0; // } // li.get(0).setNum(num+1); // jjm.updateByPrimaryKeySelective(li.get(0)); // }else{ // jj.setNum(1); // jj.setType(zs.getType()); // jjm.insertSelective(jj); // } // WaBaoMiaoShu ws=new WaBaoMiaoShu(); // ws.setRoleid(roleid); // ws.setRolename(rolename); // ws.setDate(new Date()); // ws.setStatus("0"); // ws.setBaoid(zs.getId()); // ws.setBaoname(zs.getName()); // wbmsm.insertSelective(ws); // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "恭喜你挖到了"+zs.getName()); // out.write(obj.toString()); // out.flush(); // out.close(); // }else{ // String a="很遗憾,你与珍宝擦肩而过!"; // String b="加油,宝矿中心快挖到了"; // String c="挖空了,运气真差!"; // String d="挖空,不要放弃,宝藏就在身边"; // String e="挖空,该死的,就快挖到了。"; // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // int rand=(int)((Math.random()*5)+1); // if(rand==1){ // obj.put("msg", a); // } // if(rand==2){ // obj.put("msg", b); // } // if(rand==3){ // obj.put("msg", c); // } // if(rand==4){ // obj.put("msg", d); // } // if(rand==5){ // obj.put("msg", e); // } // // out.write(obj.toString()); // out.flush(); // out.close(); // } // // // // return null; // } // @RequestMapping(value="/appxhcs", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appxhcs(@RequestParam(value = "type",required = false)String type,WaBao wb,HttpSession session, HttpServletResponse response,HttpServletRequest request) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid=r.get(0).getId(); // String rolename=r.get(0).getJuesename(); // if(r.size()>0){ // int gl=0; // String w=type; // WaBao wbo=wbm.selectByPrimaryKey(wb.getId()); // // // gl=(int)((Math.random()*100)+1); // // if(wb.getW1()!=null){ // wbo.setW1(wb.getW1()); // // } // if(wb.getW2()!=null){ // wbo.setW2(wb.getW2()); // // } // if(wb.getW3()!=null){ // wbo.setW3(wb.getW3()); // // } // if(wb.getW4()!=null){ // wbo.setW4(wb.getW4()); // // } // if(wb.getW5()!=null){ // wbo.setW5(wb.getW5()); // // } // if(wb.getW6()!=null){ // wbo.setW6(wb.getW6()); // // } // if(wb.getW7()!=null){ // wbo.setW7(wb.getW7()); // // } // if(wb.getW8()!=null){ // wbo.setW8(wb.getW8()); // // // } // if(wb.getW9()!=null){ // wbo.setW9(wb.getW9()); // // } // wbm.updateByPrimaryKeySelective(wbo); ////刷新继续挖宝 // WaBao sxwb=wbm.selectByPrimaryKey(wb.getId()); // if(sxwb.getW1()==0&&sxwb.getW2()==0&&sxwb.getW3()==0&&sxwb.getW4()==0&&sxwb.getW5()==0&&sxwb.getW6()==0&&sxwb.getW7()==0&&sxwb.getW8()==0&&sxwb.getW9()==0){ // CommonUtilAjax.sendAjaxList("msg", "sx",request,response); // // } // if(gl!=0&&gl>80){ // int wbgl=(int)((Math.random()*2)); // int rand=0; // if(wbgl==0){ // rand =(int)((Math.random()*17)+1); // } // if(wbgl==1){ // rand =(int)((Math.random()*21)+25); // // } // // // ZaWuMiaoShu zs=null; // // // // zs=zwmsm.selectByPrimaryKey(rand); // // // jiangjun jj=new jiangjun(); // jj.setJjname(zs.getName()); // jj.setRoleid(roleid); // //jj.setType(zs.getType()); // List<jiangjun> li=jjm.selectAll(jj); // //带决绝 // if(li.size()>0){ // Integer num=li.get(0).getNum(); // if(num==null){ // num=0; // } // li.get(0).setNum(num+1); // jjm.updateByPrimaryKeySelective(li.get(0)); // }else{ // jj.setNum(1); // jj.setType(zs.getType()); // jjm.insertSelective(jj); // } // WaBaoMiaoShu ws=new WaBaoMiaoShu(); // ws.setRoleid(roleid); // ws.setRolename(rolename); // ws.setDate(new Date()); // ws.setStatus("0"); // ws.setBaoid(zs.getId()); // ws.setBaoname(zs.getName()); // wbmsm.insertSelective(ws); // CommonUtilAjax.sendAjaxList("msg", "恭喜你挖到了"+zs.getName(),request,response); // // }else{ // String a="很遗憾,你与珍宝擦肩而过!"; // String b="加油,宝矿中心快挖到了"; // String c="挖空了,运气真差!"; // String d="挖空,不要放弃,宝藏就在身边"; // String e="挖空,该死的,就快挖到了。"; // // int rand=(int)((Math.random()*5)+1); // if(rand==1){ // CommonUtilAjax.sendAjaxList("msg", a,request,response); // // } // if(rand==2){ // CommonUtilAjax.sendAjaxList("msg",b,request,response); // // } // if(rand==3){ // CommonUtilAjax.sendAjaxList("msg", c,request,response); // } // if(rand==4){ // CommonUtilAjax.sendAjaxList("msg",d,request,response); // } // if(rand==5){ // CommonUtilAjax.sendAjaxList("msg", e,request,response); // } // // // } // // } // // // // return null; // } // @RequestMapping(value = "/sxwb", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String sxwb(@RequestParam(value = "id",required = false)Integer id,HttpSession session, HttpServletResponse response,Model model) throws Exception { // WaBao wb=wbm.selectByPrimaryKey(id); // if(wb.getNum()==0){ // wb.setStatus("0"); // wbm.updateByPrimaryKeySelective(wb); // }else{ // wb.setNum(wb.getNum()-1); // wb.setW1(1); // wb.setW2(1); // wb.setW3(1); // wb.setW4(1); // wb.setW5(1); // wb.setW6(1); // wb.setW7(1); // wb.setW8(1); // wb.setW9(1); // wbm.updateByPrimaryKeySelective(wb); // } // // // // return null; // } // //app版本刷新挖宝 // @RequestMapping(value = "/appsxwb", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appsxwb(@RequestParam(value = "id",required = false)Integer id,HttpServletRequest request,HttpSession session, HttpServletResponse response,Model model) throws Exception { // WaBao wb=wbm.selectByPrimaryKey(id); // // CommonUtilAjax.sendAjax("",request,response);//不设置返回json时,ajax succes之后无法执行函数 // if(wb.getNum()==0){ // wb.setStatus("0"); // wbm.updateByPrimaryKeySelective(wb); // }else{ // wb.setNum(wb.getNum()-1); // wb.setW1(1); // wb.setW2(1); // wb.setW3(1); // wb.setW4(1); // wb.setW5(1); // wb.setW6(1); // wb.setW7(1); // wb.setW8(1); // wb.setW9(1); // int a= wbm.updateByPrimaryKeySelective(wb); // System.out.print(a); // // } // // // // return null; // } // // }
8431/hxsg
hxsg-web/src/main/java/com/hxsg/battle/controller/BattleController.java
8,141
// obj.put("msg", "宝藏守卫:钱不够,还想进去?快走快走!");
line_comment
zh-cn
//package com.hxsg.battle.controller; // //import com.alibaba.fastjson.JSONObject; //import com.hxsg.CommonUtil.CommonUtilAjax; //import com.hxsg.CommonUtil.Msg; //import com.hxsg.CommonUtil.RequestParamFormat; //import com.hxsg.Dao.*; //import com.hxsg.po.*; // //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.ComponentScan; //import org.springframework.context.annotation.Configuration; //import org.springframework.stereotype.Controller; //import org.springframework.ui.Model; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RequestMethod; //import org.springframework.web.bind.annotation.RequestParam; //import org.springframework.web.bind.annotation.ResponseBody; // //import javax.jws.WebParam; //import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpSession; //import java.io.PrintWriter; //import java.util.ArrayList; //import java.util.Date; //import java.util.List; //import java.util.Map; // ///** //* Created by dlf on 2015/12/31. //*/ //@Controller //@RequestMapping("/zhanchang") // //public class BattleController { // @Autowired // RoleMapper rm; // @Autowired // RoleFriendsMsgMapper rfmm; // @Autowired // jiangjunMapper jjm; // @Autowired // ZaWuMiaoShuMapper zwmsm; // @Autowired // YouJianWuPinMapper yjwpm; // @Autowired // WaBaoMapper wbm; // @Autowired // WaBaoMiaoShuMapper wbmsm; // // private Logger logger = LoggerFactory.getLogger(getClass()); // @RequestMapping(value = "/yzwb", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String yzwb(HttpSession session, HttpServletResponse response,Model model) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // if (wb != null && wb.getStatus().equals("0")) { // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "你的铁镐已磨损,确定花费100000银两购买铁镐吗?"); // out.write(obj.toString()); // out.flush(); // out.close(); // } // } // // if(li.size()<=0){ // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "小伙子第一次来矿洞吧,留下100000银买路财放你过去。"); // out.write(obj.toString()); // out.flush(); // out.close(); // // } // // return null; // } // @RequestMapping(value = "/appyzwb", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appyzwb(HttpSession session, HttpServletResponse response,HttpServletRequest request) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // if(r.size()>0){ // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // if (wb != null && wb.getStatus().equals("0")) { // CommonUtilAjax.sendAjaxList("msg", "你的铁镐已磨损,确定花费100000银两购买铁镐吗?",request,response); // } // } // if(li.size()<=0){ // CommonUtilAjax.sendAjaxList("msg", "小伙子第一次来矿洞吧,留下100000银买路财放你过去。",request,response); // } // } // // // return null; // } // @RequestMapping(value = "/wdbw", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String wdbw(HttpSession session, HttpServletResponse response,Model model) throws Exception { // // List<WaBaoMiaoShu> li=wbmsm.getWbByTime(); // response.setCharacterEncoding("utf-8"); // PrintWriter out=response.getWriter(); // JSONObject obj=new JSONObject();//使用json // if(li.size()>0&&li!=null){ // obj.put("code", 0); // obj.put("rmsg",li); // // }else{ // obj.put("code", 1); // } // System.out.println(obj.toString()); // // out.write(obj.toString()); // out.flush(); // out.close(); // return null; // } // @RequestMapping(value = "/appwdbw", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appwdbw(HttpSession session, HttpServletRequest request,HttpServletResponse response,Model model) throws Exception { // // List<WaBaoMiaoShu> li=wbmsm.getWbByTime(); // // if(li.size()>0&&li!=null){ // CommonUtilAjax.sendAjaxList("rmsg",li,request, response); // // }else{ // CommonUtilAjax.sendAjaxList("code",1,request, response); // } // // return null; // } // @RequestMapping(value = "/fee", method = {RequestMethod.GET, RequestMethod.POST}) // // public String fee(HttpSession session, HttpServletResponse response,Model model) throws Exception { // // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // model.addAttribute("wb",wb); // } // // //// Integer result = SetRoleMoney.setmoney(roleid, fee); //// if (result == 1) { //// wb.setStatus("1"); //// wb.setNum(50); //// model.addAttribute("wb",wb); //// response.setCharacterEncoding("utf-8"); //// PrintWriter out = response.getWriter(); //// JSONObject obj = new JSONObject();//使用json //// obj.put("msg", "消费成功,快点进去吧!"); //// out.write(obj.toString()); //// out.flush(); //// out.close(); //// //// } else { //// response.setCharacterEncoding("utf-8"); //// PrintWriter out = response.getWriter(); //// JSONObject obj = new JSONObject();//使用json //// obj.put("msg", "钱不够,还想进去?快走快走!"); //// out.write(obj.toString()); //// out.flush(); //// out.close(); //// //// } // return "战场/挖宝"; // } // //app fee刷新挖宝主页 // @RequestMapping(value = "/appfee", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appfee(HttpSession session, HttpServletResponse response,HttpServletRequest request) throws Exception { // // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // if(r.size()>0){ // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // CommonUtilAjax.sendAjaxList("wb",wb,request, response); // } // } // return null; // } // @RequestMapping(value = "/wabao", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public synchronized String wabao(HttpSession session, HttpServletResponse response,Model model) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // String rt = null; // Integer result =null; // int fee = 100000; // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // // if (wb != null && wb.getStatus().equals("0")) { // Role re = rm.selectByPrimaryKey(roleid); // int roleyin = re.getYin(); // if (roleyin >= fee) { // //扣费 // re.setYin(roleyin - fee); // rm.updateByPrimaryKeySelective(re); // result = 1; // } else { // result = 0; // } // // if (result == 1) { // // wb.setW1(1); // wb.setW2(1); // wb.setW3(1); // wb.setW4(1); // wb.setW5(1); // wb.setW6(1); // wb.setW7(1); // wb.setW8(1); // wb.setW9(1); // wb.setNum(50); // wb.setStatus("1"); // wbm.updateByPrimaryKeySelective(wb); // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "宝藏守卫:拿着铁镐去吧。祝你好运!"); // out.write(obj.toString()); // out.flush(); // out.close(); // } else { // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // ob <SUF> // out.write(obj.toString()); // out.flush(); // out.close(); // } // } // // } // // // if (li.size()<=0) { // Role re = rm.selectByPrimaryKey(roleid); // int roleyin = re.getYin(); // if (roleyin >= fee) { // //扣费 // re.setYin(roleyin - fee); // rm.updateByPrimaryKeySelective(re); // result = 1; // } else { // result = 0; // } // if (result == 1) { // WaBao wo = new WaBao(); // wo.setRoleid(roleid); // wo.setRolename(rolename); // wo.setW1(1); // wo.setW2(1); // wo.setW3(1); // wo.setW4(1); // wo.setW5(1); // wo.setW6(1); // wo.setW7(1); // wo.setW8(1); // wo.setW9(1); // wo.setNum(50); // wo.setStatus("1"); // wo.setDate(new Date()); // wo.setType("0"); // wbm.insertSelective(wo); // } else { // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "你所携带的银两不足!无法贿赂宝藏守卫"); // out.write(obj.toString()); // out.flush(); // out.close(); // } // } // // return null; // // } // @RequestMapping(value = "/appwabao", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public synchronized String appwabao(HttpServletRequest request,HttpSession session, HttpServletResponse response,Model model) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid = r.get(0).getId(); // String rolename = r.get(0).getJuesename(); // if(r.size()>0){ // String rt = null; // Integer result =null; // int fee = 100000; // WaBao wbo=new WaBao(); // wbo.setRoleid(roleid); // List<WaBao>li = wbm.selectAll(wbo); // if(li.size()>0){ // WaBao wb=li.get(0); // // if (wb != null && wb.getStatus().equals("0")) { // Role re = rm.selectByPrimaryKey(roleid); // int roleyin = re.getYin(); // if (roleyin >= fee) { // //扣费 // re.setYin(roleyin - fee); // rm.updateByPrimaryKeySelective(re); // result = 1; // } else { // result = 0; // } // // if (result == 1) { // // wb.setW1(1); // wb.setW2(1); // wb.setW3(1); // wb.setW4(1); // wb.setW5(1); // wb.setW6(1); // wb.setW7(1); // wb.setW8(1); // wb.setW9(1); // wb.setNum(50); // wb.setStatus("1"); // wbm.updateByPrimaryKeySelective(wb); // CommonUtilAjax.sendAjaxList("msg", "宝藏守卫:拿着铁镐去吧。祝你好运!",request,response); // // } else { // CommonUtilAjax.sendAjaxList("msg", "宝藏守卫:钱不够,还想进去?快走快走!",request,response); // // // } // } // // } // // // if (li.size()<=0) { // Role re = rm.selectByPrimaryKey(roleid); // int roleyin = re.getYin(); // if (roleyin >= fee) { // //扣费 // re.setYin(roleyin - fee); // rm.updateByPrimaryKeySelective(re); // result = 1; // } else { // result = 0; // } // if (result == 1) { // WaBao wo = new WaBao(); // wo.setRoleid(roleid); // wo.setRolename(rolename); // wo.setW1(1); // wo.setW2(1); // wo.setW3(1); // wo.setW4(1); // wo.setW5(1); // wo.setW6(1); // wo.setW7(1); // wo.setW8(1); // wo.setW9(1); // wo.setNum(50); // wo.setStatus("1"); // wo.setDate(new Date()); // wo.setType("0"); // wbm.insertSelective(wo); // } else { // CommonUtilAjax.sendAjaxList("msg", "你所携带的银两不足!无法贿赂宝藏守卫",request,response); // // // } // } // } // // // return null; // // } // @RequestMapping(value="/xhcs", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String xhcs(@RequestParam(value = "type",required = false)String type,WaBao wb,HttpSession session, HttpServletResponse response,Model model) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid=r.get(0).getId(); // String rolename=r.get(0).getJuesename(); // int gl=0; // String w=type; // WaBao wbo=wbm.selectByPrimaryKey(wb.getId()); // // // gl=(int)((Math.random()*100)+1); // // if(wb.getW1()!=null){ // wbo.setW1(wb.getW1()); // // } // if(wb.getW2()!=null){ // wbo.setW2(wb.getW2()); // // } // if(wb.getW3()!=null){ // wbo.setW3(wb.getW3()); // // } // if(wb.getW4()!=null){ // wbo.setW4(wb.getW4()); // // } // if(wb.getW5()!=null){ // wbo.setW5(wb.getW5()); // // } // if(wb.getW6()!=null){ // wbo.setW6(wb.getW6()); // // } // if(wb.getW7()!=null){ // wbo.setW7(wb.getW7()); // // } // if(wb.getW8()!=null){ // wbo.setW8(wb.getW8()); // // // } // if(wb.getW9()!=null){ // wbo.setW9(wb.getW9()); // // } // wbm.updateByPrimaryKeySelective(wbo); ////刷新继续挖宝 // WaBao sxwb=wbm.selectByPrimaryKey(wb.getId()); // if(sxwb.getW1()==0&&sxwb.getW2()==0&&sxwb.getW3()==0&&sxwb.getW4()==0&&sxwb.getW5()==0&&sxwb.getW6()==0&&sxwb.getW7()==0&&sxwb.getW8()==0&&sxwb.getW9()==0){ // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("sxmsg", "sx"); // out.write(obj.toString()); // out.flush(); // out.close(); // } // // // if(gl!=0&&gl>80){ // int wbgl=(int)((Math.random()*2)); // int rand=0; // if(wbgl==0){ // rand =(int)((Math.random()*17)+1); // } // if(wbgl==1){ // rand =(int)((Math.random()*21)+25); // // } // // // ZaWuMiaoShu zs=zwmsm.selectByPrimaryKey(rand); // jiangjun jj=new jiangjun(); // jj.setJjname(zs.getName()); // jj.setRoleid(roleid); // //jj.setType(zs.getType()); // List<jiangjun> li=jjm.selectAll(jj); // // if(li.size()>0){ // Integer num=li.get(0).getNum(); // if(num==null){ // num=0; // } // li.get(0).setNum(num+1); // jjm.updateByPrimaryKeySelective(li.get(0)); // }else{ // jj.setNum(1); // jj.setType(zs.getType()); // jjm.insertSelective(jj); // } // WaBaoMiaoShu ws=new WaBaoMiaoShu(); // ws.setRoleid(roleid); // ws.setRolename(rolename); // ws.setDate(new Date()); // ws.setStatus("0"); // ws.setBaoid(zs.getId()); // ws.setBaoname(zs.getName()); // wbmsm.insertSelective(ws); // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // obj.put("msg", "恭喜你挖到了"+zs.getName()); // out.write(obj.toString()); // out.flush(); // out.close(); // }else{ // String a="很遗憾,你与珍宝擦肩而过!"; // String b="加油,宝矿中心快挖到了"; // String c="挖空了,运气真差!"; // String d="挖空,不要放弃,宝藏就在身边"; // String e="挖空,该死的,就快挖到了。"; // response.setCharacterEncoding("utf-8"); // PrintWriter out = response.getWriter(); // JSONObject obj = new JSONObject();//使用json // int rand=(int)((Math.random()*5)+1); // if(rand==1){ // obj.put("msg", a); // } // if(rand==2){ // obj.put("msg", b); // } // if(rand==3){ // obj.put("msg", c); // } // if(rand==4){ // obj.put("msg", d); // } // if(rand==5){ // obj.put("msg", e); // } // // out.write(obj.toString()); // out.flush(); // out.close(); // } // // // // return null; // } // @RequestMapping(value="/appxhcs", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appxhcs(@RequestParam(value = "type",required = false)String type,WaBao wb,HttpSession session, HttpServletResponse response,HttpServletRequest request) throws Exception { // List<Role> r = (List<Role>) session.getAttribute("rolelist");//获取session查询角色 // Integer roleid=r.get(0).getId(); // String rolename=r.get(0).getJuesename(); // if(r.size()>0){ // int gl=0; // String w=type; // WaBao wbo=wbm.selectByPrimaryKey(wb.getId()); // // // gl=(int)((Math.random()*100)+1); // // if(wb.getW1()!=null){ // wbo.setW1(wb.getW1()); // // } // if(wb.getW2()!=null){ // wbo.setW2(wb.getW2()); // // } // if(wb.getW3()!=null){ // wbo.setW3(wb.getW3()); // // } // if(wb.getW4()!=null){ // wbo.setW4(wb.getW4()); // // } // if(wb.getW5()!=null){ // wbo.setW5(wb.getW5()); // // } // if(wb.getW6()!=null){ // wbo.setW6(wb.getW6()); // // } // if(wb.getW7()!=null){ // wbo.setW7(wb.getW7()); // // } // if(wb.getW8()!=null){ // wbo.setW8(wb.getW8()); // // // } // if(wb.getW9()!=null){ // wbo.setW9(wb.getW9()); // // } // wbm.updateByPrimaryKeySelective(wbo); ////刷新继续挖宝 // WaBao sxwb=wbm.selectByPrimaryKey(wb.getId()); // if(sxwb.getW1()==0&&sxwb.getW2()==0&&sxwb.getW3()==0&&sxwb.getW4()==0&&sxwb.getW5()==0&&sxwb.getW6()==0&&sxwb.getW7()==0&&sxwb.getW8()==0&&sxwb.getW9()==0){ // CommonUtilAjax.sendAjaxList("msg", "sx",request,response); // // } // if(gl!=0&&gl>80){ // int wbgl=(int)((Math.random()*2)); // int rand=0; // if(wbgl==0){ // rand =(int)((Math.random()*17)+1); // } // if(wbgl==1){ // rand =(int)((Math.random()*21)+25); // // } // // // ZaWuMiaoShu zs=null; // // // // zs=zwmsm.selectByPrimaryKey(rand); // // // jiangjun jj=new jiangjun(); // jj.setJjname(zs.getName()); // jj.setRoleid(roleid); // //jj.setType(zs.getType()); // List<jiangjun> li=jjm.selectAll(jj); // //带决绝 // if(li.size()>0){ // Integer num=li.get(0).getNum(); // if(num==null){ // num=0; // } // li.get(0).setNum(num+1); // jjm.updateByPrimaryKeySelective(li.get(0)); // }else{ // jj.setNum(1); // jj.setType(zs.getType()); // jjm.insertSelective(jj); // } // WaBaoMiaoShu ws=new WaBaoMiaoShu(); // ws.setRoleid(roleid); // ws.setRolename(rolename); // ws.setDate(new Date()); // ws.setStatus("0"); // ws.setBaoid(zs.getId()); // ws.setBaoname(zs.getName()); // wbmsm.insertSelective(ws); // CommonUtilAjax.sendAjaxList("msg", "恭喜你挖到了"+zs.getName(),request,response); // // }else{ // String a="很遗憾,你与珍宝擦肩而过!"; // String b="加油,宝矿中心快挖到了"; // String c="挖空了,运气真差!"; // String d="挖空,不要放弃,宝藏就在身边"; // String e="挖空,该死的,就快挖到了。"; // // int rand=(int)((Math.random()*5)+1); // if(rand==1){ // CommonUtilAjax.sendAjaxList("msg", a,request,response); // // } // if(rand==2){ // CommonUtilAjax.sendAjaxList("msg",b,request,response); // // } // if(rand==3){ // CommonUtilAjax.sendAjaxList("msg", c,request,response); // } // if(rand==4){ // CommonUtilAjax.sendAjaxList("msg",d,request,response); // } // if(rand==5){ // CommonUtilAjax.sendAjaxList("msg", e,request,response); // } // // // } // // } // // // // return null; // } // @RequestMapping(value = "/sxwb", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String sxwb(@RequestParam(value = "id",required = false)Integer id,HttpSession session, HttpServletResponse response,Model model) throws Exception { // WaBao wb=wbm.selectByPrimaryKey(id); // if(wb.getNum()==0){ // wb.setStatus("0"); // wbm.updateByPrimaryKeySelective(wb); // }else{ // wb.setNum(wb.getNum()-1); // wb.setW1(1); // wb.setW2(1); // wb.setW3(1); // wb.setW4(1); // wb.setW5(1); // wb.setW6(1); // wb.setW7(1); // wb.setW8(1); // wb.setW9(1); // wbm.updateByPrimaryKeySelective(wb); // } // // // // return null; // } // //app版本刷新挖宝 // @RequestMapping(value = "/appsxwb", method = {RequestMethod.GET, RequestMethod.POST}) // @ResponseBody // public String appsxwb(@RequestParam(value = "id",required = false)Integer id,HttpServletRequest request,HttpSession session, HttpServletResponse response,Model model) throws Exception { // WaBao wb=wbm.selectByPrimaryKey(id); // // CommonUtilAjax.sendAjax("",request,response);//不设置返回json时,ajax succes之后无法执行函数 // if(wb.getNum()==0){ // wb.setStatus("0"); // wbm.updateByPrimaryKeySelective(wb); // }else{ // wb.setNum(wb.getNum()-1); // wb.setW1(1); // wb.setW2(1); // wb.setW3(1); // wb.setW4(1); // wb.setW5(1); // wb.setW6(1); // wb.setW7(1); // wb.setW8(1); // wb.setW9(1); // int a= wbm.updateByPrimaryKeySelective(wb); // System.out.print(a); // // } // // // // return null; // } // // }
1
24163_0
package IQIYI; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* * 牛牛参加了一场考试,考试包括n道判断题,每做对一道题获得1分,牛牛考试前完全没有准备,所以考试只能看缘分了,牛牛在考试中一共猜测了t道题目的答案是"正确",其他的牛牛猜为"错误"。考试结束后牛牛知道实际上n道题中有a个题目的答案应该是"正确", * 但是牛牛不知道具体是哪些题目,牛牛希望你能帮助他计算可能获得的最高的考试分数是多少。 * */ public class JudgeTime { public static void main(String[] args) throws IOException { BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String[] strings=bf.readLine().split(" "); int num=Integer.parseInt(strings[0]); int yesNum=Integer.parseInt(strings[1]); int realYes=Integer.parseInt(strings[2]); System.out.println(Math.min(realYes,yesNum)+Math.min(num-yesNum,num-realYes)); } }
88-Rising/OnlieJudge
IQIYI/JudgeTime.java
313
/* * 牛牛参加了一场考试,考试包括n道判断题,每做对一道题获得1分,牛牛考试前完全没有准备,所以考试只能看缘分了,牛牛在考试中一共猜测了t道题目的答案是"正确",其他的牛牛猜为"错误"。考试结束后牛牛知道实际上n道题中有a个题目的答案应该是"正确", * 但是牛牛不知道具体是哪些题目,牛牛希望你能帮助他计算可能获得的最高的考试分数是多少。 * */
block_comment
zh-cn
package IQIYI; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* * 牛牛参 <SUF>*/ public class JudgeTime { public static void main(String[] args) throws IOException { BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String[] strings=bf.readLine().split(" "); int num=Integer.parseInt(strings[0]); int yesNum=Integer.parseInt(strings[1]); int realYes=Integer.parseInt(strings[2]); System.out.println(Math.min(realYes,yesNum)+Math.min(num-yesNum,num-realYes)); } }
1
6763_35
/* * Symphony - A modern community (forum/BBS/SNS/blog) platform written in Java. * Copyright (C) 2012-present, b3log.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.b3log.symphony.util; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; import jodd.http.HttpRequest; import jodd.http.HttpResponse; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.b3log.latke.Keys; import org.b3log.latke.util.Crypts; import org.b3log.latke.util.URLs; import org.b3log.symphony.model.Common; import org.json.JSONObject; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.File; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Mail utilities. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://blog.thinkjava.top">VirutalPier</a> * @author <a href="https://github.com/snowflake3721">snowflake</a> * @version 1.2.6.9, Jun 17, 2019 * @since 1.3.0 */ public final class Mails { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(Mails.class); /** * Template name - verifycode. */ public static final String TEMPLATE_NAME_VERIFYCODE = "sym_verifycode"; /** * Template name - weekly. */ public static final String TEMPLATE_NAME_WEEKLY = "sym_weekly"; /** * Template configuration. */ private static final Configuration TEMPLATE_CFG = new Configuration(Templates.FREEMARKER_VER); /** * Domain - Channel mapping. &lt;163.com, aliyun&gt; https://github.com/b3log/symphony/issues/737 */ private static final Map<String, String> DOMAIN_CHANNEL = new HashMap<>(); static { try { TEMPLATE_CFG.setDirectoryForTemplateLoading(new File(Mails.class.getResource("/mail_tpl").toURI())); TEMPLATE_CFG.setDefaultEncoding("UTF-8"); TEMPLATE_CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); TEMPLATE_CFG.setLogTemplateExceptions(false); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Loads mail templates failed", e); } final String mailDomains = Symphonys.MAIL_CHANNEL_MAIL_DOMAINS; if (StringUtils.isNotBlank(mailDomains)) { // aliyun:163.com,126.com;sendcloud:qq.com final String[] channelMaps = StringUtils.split(mailDomains, ";"); for (int i = 0; i < channelMaps.length; i++) { final String channelMap = channelMaps[i]; final String[] channelDomain = StringUtils.split(channelMap, ":"); final String channel = channelDomain[0]; final String[] domains = StringUtils.split(channelDomain[1], ","); for (int j = 0; j < domains.length; j++) { final String domain = domains[j]; DOMAIN_CHANNEL.put(domain, channel); } } } } /** * Private constructor. */ private Mails() { } /** * Sends a HTML mail. * * @param fromName the specified from name * @param subject the specified subject * @param toMail the specified receiver mail * @param templateName the specified template name * @param dataModel the specified data model */ public static void sendHTML(final String fromName, final String subject, final String toMail, final String templateName, final Map<String, Object> dataModel) { if ("sendcloud".equals(Symphonys.MAIL_CHANNEL)) { if (StringUtils.isBlank(Symphonys.MAIL_SENDCLOUD_API_USER) || StringUtils.isBlank(Symphonys.MAIL_SENDCLOUD_API_KEY)) { LOGGER.warn("Please configure [#### SendCloud Mail channel ####] section in symphony.properties for sending mail"); return; } } else if ("aliyun".equals(Symphonys.MAIL_CHANNEL)) { if (StringUtils.isBlank(Symphonys.MAIL_ALIYUN_AK) || StringUtils.isBlank(Symphonys.MAIL_ALIYUN_SK)) { LOGGER.warn("Please configure [#### Aliyun Mail channel ####] section in symphony.properties for sending mail"); return; } } else { if (StringUtils.isBlank(MailSender.username) || StringUtils.isBlank(MailSender.password)) { LOGGER.warn("Please configure [#### Local Mail channel ####] section in symphony.properties for sending mail"); return; } } Keys.fillServer(dataModel); Keys.fillRuntime(dataModel); dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); try { final Template template = TEMPLATE_CFG.getTemplate(templateName + ".ftl"); final StringWriter stringWriter = new StringWriter(); template.process(dataModel, stringWriter); stringWriter.close(); final String html = stringWriter.toString(); final String domain = StringUtils.substringAfter(toMail, "@"); final String channel = DOMAIN_CHANNEL.getOrDefault(domain, Symphonys.MAIL_CHANNEL); switch (channel) { case "aliyun": aliSendHtml(Symphonys.MAIL_ALIYUN_FROM, fromName, subject, toMail, html, Symphonys.MAIL_ALIYUN_AK, Symphonys.MAIL_ALIYUN_SK); return; case "local": MailSender.getInstance().sendHTML(fromName, subject, toMail, html); return; case "sendcloud": final Map<String, Object> formData = new HashMap<>(); formData.put("apiUser", Symphonys.MAIL_SENDCLOUD_API_USER); formData.put("apiKey", Symphonys.MAIL_SENDCLOUD_API_KEY); formData.put("from", Symphonys.MAIL_SENDCLOUD_FROM); formData.put("fromName", fromName); formData.put("subject", subject); formData.put("to", toMail); formData.put("html", html); final HttpResponse response = HttpRequest.post("http://api.sendcloud.net/apiv2/mail/send").form(formData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(5000).send(); response.close(); response.charset("UTF-8"); LOGGER.debug(response.bodyText()); return; default: LOGGER.error("Unknown mail channel [" + channel + "]"); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends a mail [subject=" + subject + ", to=" + toMail + "] failed", e); } } /** * Batch send HTML mails. * * @param fromName the specified from name * @param subject the specified subject * @param toMails the specified receiver mails * @param templateName the specified template name * @param dataModel the specified data model */ public static void batchSendHTML(final String fromName, final String subject, final List<String> toMails, final String templateName, final Map<String, Object> dataModel) { if ("sendcloud".equals(Symphonys.MAIL_CHANNEL)) { if (StringUtils.isBlank(Symphonys.MAIL_SENDCLOUD_BATCH_API_USER) || StringUtils.isBlank(Symphonys.MAIL_SENDCLOUD_BATCH_API_KEY)) { LOGGER.warn("Please configure [#### SendCloud Mail channel ####] section in symphony.properties for sending mail"); return; } } else if ("aliyun".equals(Symphonys.MAIL_CHANNEL)) { if (StringUtils.isBlank(Symphonys.MAIL_ALIYUN_AK) || StringUtils.isBlank(Symphonys.MAIL_ALIYUN_SK)) { LOGGER.warn("Please configure [#### Aliyun Mail channel ####] section in symphony.properties for sending mail"); return; } } else { if (StringUtils.isBlank(MailSender.username) || StringUtils.isBlank(MailSender.password)) { LOGGER.warn("Please configure [#### Local Mail channel ####] section in symphony.properties for sending mail"); return; } } Keys.fillServer(dataModel); Keys.fillRuntime(dataModel); dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); try { final Map<String, Object> formData = new HashMap<>(); formData.put("apiUser", Symphonys.MAIL_SENDCLOUD_BATCH_API_USER); formData.put("apiKey", Symphonys.MAIL_SENDCLOUD_BATCH_API_KEY); formData.put("from", Symphonys.MAIL_SENDCLOUD_BATCH_FROM); formData.put("fromName", fromName); formData.put("subject", subject); formData.put("templateInvokeName", templateName); final Template template = TEMPLATE_CFG.getTemplate(templateName + ".ftl"); final StringWriter stringWriter = new StringWriter(); template.process(dataModel, stringWriter); stringWriter.close(); final String html = stringWriter.toString(); // Creates or updates the SendCloud email template if ("sendcloud".equals(Symphonys.MAIL_CHANNEL)) { refreshWeeklyTemplate(html); } int index = 0; final int size = toMails.size(); List<String> batch = new ArrayList<>(); HttpResponse response; while (index < size) { final String mail = toMails.get(index); batch.add(mail); index++; if (batch.size() > 99) { if ("aliyun".equals(Symphonys.MAIL_CHANNEL)) { final String toMail = getStringToMailByList(batch); aliSendHtml(Symphonys.MAIL_ALIYUN_BATCH_FROM, fromName, subject, toMail, html, Symphonys.MAIL_ALIYUN_AK, Symphonys.MAIL_ALIYUN_SK); LOGGER.info("Sent [" + batch.size() + "] mails"); } else if ("local".equals(Symphonys.MAIL_CHANNEL.toLowerCase())) { MailSender.getInstance().sendHTML(fromName, subject, batch, html); } else { try { final JSONObject xsmtpapi = new JSONObject(); xsmtpapi.put("to", batch); xsmtpapi.put("sub", new JSONObject()); formData.put("xsmtpapi", xsmtpapi.toString()); response = HttpRequest.post("http://api.sendcloud.net/apiv2/mail/sendtemplate").form(formData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send(); response.close(); response.charset("UTF-8"); LOGGER.debug(response.bodyText()); LOGGER.info("Sent [" + batch.size() + "] mails"); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Send mail failed", e); } } batch.clear(); } } if (!batch.isEmpty()) { // Process remains if ("aliyun".equals(Symphonys.MAIL_CHANNEL)) { final String toMail = getStringToMailByList(batch); aliSendHtml(Symphonys.MAIL_ALIYUN_BATCH_FROM, fromName, subject, toMail, html, Symphonys.MAIL_ALIYUN_AK, Symphonys.MAIL_ALIYUN_SK); LOGGER.info("Sent [" + batch.size() + "] mails"); } else if ("local".equals(Symphonys.MAIL_CHANNEL.toLowerCase())) { MailSender.getInstance().sendHTML(fromName, subject, batch, html); } else { try { final JSONObject xsmtpapi = new JSONObject(); xsmtpapi.put("to", batch); xsmtpapi.put("sub", new JSONObject()); formData.put("xsmtpapi", xsmtpapi.toString()); response = HttpRequest.post("http://api.sendcloud.net/apiv2/mail/sendtemplate").form(formData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send(); response.close(); response.charset("UTF-8"); LOGGER.debug(response.bodyText()); LOGGER.info("Sent [" + batch.size() + "] mails"); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Send mail failed", e); } } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Batch send mail failed", e); } } /** * Sends a HTML mail via Aliyun. * * @param fromName the specified from name * @param subject the specified subject * @param toMail the specified receiver mail * @param html send html */ private static void aliSendHtml(final String sendMail, final String fromName, final String subject, final String toMail, final String html, final String accessKey, final String accessSecret) { final Map<String, Object> map = new HashMap<>(); map.put("Action", "SingleSendMail"); map.put("Format", "JSON"); map.put("Version", "2015-11-23"); map.put("AccessKeyId", accessKey); map.put("SignatureMethod", "HMAC-SHA1"); map.put("Timestamp", getISO8601Time()); map.put("SignatureVersion", "1.0"); map.put("SignatureNonce", String.valueOf(System.currentTimeMillis())); map.put("AccountName", sendMail); map.put("FromAlias", fromName); map.put("ReplyToAddress", "true"); map.put("AddressType", "1"); map.put("ToAddress", toMail); map.put("Subject", subject); map.put("HtmlBody", html); final String[] sortedKeys = map.keySet().toArray(new String[]{}); Arrays.sort(sortedKeys); final StringBuilder canonicalizedQueryString = new StringBuilder(); for (String key : sortedKeys) { canonicalizedQueryString.append("&") .append(Mails.percentEncode(key)).append("=") .append(Mails.percentEncode(map.get(key).toString())); } final StringBuffer stringToSign = new StringBuffer(); stringToSign.append("POST"); stringToSign.append("&"); stringToSign.append(Mails.percentEncode("/")); stringToSign.append("&"); stringToSign.append(Mails.percentEncode(canonicalizedQueryString.toString().substring(1))); map.put("Signature", Crypts.signHmacSHA1(stringToSign.toString(), accessSecret + "&")); final HttpResponse response = HttpRequest.post("https://dm.aliyuncs.com").form(map).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send(); response.close(); response.charset("UTF-8"); LOGGER.debug(response.bodyText()); } private static String percentEncode(final String value) { return value != null ? URLs.encode(value).replace("+", "%20") .replace("*", "%2A").replace("%7E", "~") : null; } private static String getISO8601Time() { final Date nowDate = new Date(); final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df.format(nowDate); } private static String getStringToMailByList(final List<String> toMails) { final StringBuffer mails = new StringBuffer(); for (String mail : toMails) { mails.append(mail + ","); } mails.deleteCharAt(mails.length() - 1); return mails.toString(); } private static void refreshWeeklyTemplate(final String html) { final Map<String, Object> addData = new HashMap<>(); addData.put("apiUser", Symphonys.MAIL_SENDCLOUD_BATCH_API_USER); addData.put("apiKey", Symphonys.MAIL_SENDCLOUD_BATCH_API_KEY); addData.put("invokeName", TEMPLATE_NAME_WEEKLY); addData.put("name", "Weekly Newsletter"); addData.put("subject", "Weekly Newsletter"); addData.put("templateType", "1"); // 批量邮件 addData.put("html", html); HttpRequest.post("http://api.sendcloud.net/apiv2/template/add").form(addData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send().close(); final Map<String, Object> updateData = new HashMap<>(); updateData.put("apiUser", Symphonys.MAIL_SENDCLOUD_BATCH_API_USER); updateData.put("apiKey", Symphonys.MAIL_SENDCLOUD_BATCH_API_KEY); updateData.put("invokeName", TEMPLATE_NAME_WEEKLY); updateData.put("html", html); HttpRequest.post("http://api.sendcloud.net/apiv2/template/update").form(updateData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send().close(); } } /** * 通过 JavaMail SMTP 发送邮件. * <p> * 支持三种类型的邮件: * <ul> * <li>SIMPLE 简单类型,可以发送 HTML 格式文本,遵从 FreeMarker 模板的设置</li> * <li>IMAGE HTML 格式类型,同时会保存 HTML 里面的 image 到磁盘,并生成 eml 保存到服务器的配置目录</li> * </ul> * </p> * * @author <a href="https://github.com/snowflake3721">snowflake</a> * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.0.2.2, Jun 17, 2019 * @since 2.1.0 */ final class MailSender implements java.io.Serializable { public static final String sender = Symphonys.MAIL_LOCAL_SMTP_SENDER; public static final String username = Symphonys.MAIL_LOCAL_SMTP_USERNAME; public static final String password = Symphonys.MAIL_LOCAL_SMTP_PASSWORD; private static final long serialVersionUID = -1000794424345267933L; private static final String CHARSET = "text/html;charset=UTF-8"; private static final Logger LOGGER = LogManager.getLogger(Markdowns.class); private static final boolean is_debug = Boolean.valueOf(Symphonys.MAIL_LOCAL_ISDEBUG); private static final String mail_transport_protocol = Symphonys.MAIL_LOCAL_TRANSPORT_PROTOCOL; private static final String mail_host = Symphonys.MAIL_LOCAL_HOST; private static final String mail_port = Symphonys.MAIL_LOCAL_PORT; private static final String mail_smtp_auth = Symphonys.MAIL_LOCAL_SMTP_AUTH; private static final String mail_smtp_ssl_enable = Symphonys.MAIL_LOCAL_SMTP_SSL; private static final String mail_smtp_starttls_enable = Symphonys.MAIL_LOCAL_SMTP_STARTTLS; private static MailSender mailSender; private static final Properties prop = new Properties(); private MailSender() { prop.setProperty("mail.transport.protocol", mail_transport_protocol); prop.setProperty("mail.host", mail_host); prop.setProperty("mail.port", mail_port); prop.setProperty("mail.smtp.auth", mail_smtp_auth); prop.setProperty("mail.smtp.ssl.enable", mail_smtp_ssl_enable); prop.setProperty("mail.smtp.starttls.enable", mail_smtp_starttls_enable); prop.setProperty("mail.smtp.sender", sender); prop.setProperty("mail.smtp.username", username); prop.setProperty("mail.smtp.passsword", password); } public static final MailSender getInstance() { if (null == mailSender) { mailSender = MailSenderHolder.INSTANCE; } return mailSender; } private static Set<String> getImgStr(String htmlStr) { Set<String> pics = new HashSet<>(); String img = ""; Pattern p_image; Matcher m_image; // String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址 String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>"; p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE); m_image = p_image.matcher(htmlStr); while (m_image.find()) { // 得到<img />数据 img = m_image.group(); // 匹配<img>中的src数据 Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img); while (m.find()) { pics.add(m.group(1)); } } return pics; } private static void setTo(String[] to, MimeMessage message) throws MessagingException { // 指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发 if (null != to && to.length > 0) { if (to.length == 1) { message.setRecipient(Message.RecipientType.TO, new InternetAddress(to[0])); } else { List<InternetAddress> iaList = new ArrayList<InternetAddress>(); for (String t : to) { InternetAddress ia = new InternetAddress(t); iaList.add(ia); } InternetAddress[] iaArray = new InternetAddress[to.length]; message.setRecipients(Message.RecipientType.TO, iaList.toArray(iaArray)); } } } public static void main(String[] args) { System.out.println(CHARSET.toLowerCase()); /* * MailSender mailSender = getInstance(); * * String subject = "eml with Image"; String content = * "这是一封邮件正文带图片<img width=\"60px\" src=\"http://localhost:8080/images/logo-M301-161X105.png\" />的邮件" * ; String[] tos = { "bruceyang_it@163.com" }; * mailSender.sendMessage(tos, subject, content, saved_path, * MailType.IMAGE); */ } private Object readResolve() { return MailSenderHolder.INSTANCE; } public void sendMessage(String[] tos, String subject, String content) throws Exception { // 1、创建session Session session = Session.getInstance(prop); // 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 session.setDebug(is_debug); // 2、通过session得到transport对象 Transport ts = session.getTransport(); // 3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。 ts.connect(mail_host, Integer.valueOf(mail_port), username, password); // 4、创建邮件 MimeMessage message = new MimeMessage(session); createTextMail(message, sender, tos, subject, content); // 5、发送邮件 ts.sendMessage(message, message.getAllRecipients()); LOGGER.debug(Arrays.toString(tos)); LOGGER.debug(subject); LOGGER.debug(content); ts.close(); } /** * 创建一封只包含文本的邮件. * * @param message * @param from * @param to * @param subject * @param content * @return * @throws Exception */ public MimeMessage createTextMail(MimeMessage message, String from, String[] to, String subject, String content) throws Exception { // 指明邮件的发件人 message.setFrom(new InternetAddress(from)); setTo(to, message); // 邮件的标题,只包含文本的简单邮件 if (StringUtils.isEmpty(subject)) { subject = "email from the system"; } message.setSubject(StringUtils.trimToEmpty(subject)); // 邮件的文本内容 message.setContent(content, CHARSET); // 返回创建好的邮件对象 return message; } /** * Sends a HTML mail for toMailList. * * @param fromName * @param subject * @param toMailList * @param html */ public void sendHTML(final String fromName, final String subject, final List<String> toMailList, String html) { if (null != toMailList && toMailList.size() > 0) { sendHTML(fromName, subject, toMailList.toArray(new String[toMailList.size()]), html); } } /** * Sends a HTML mail. * * @param fromName * @param subject * @param toMailSingle * @param html */ public void sendHTML(final String fromName, final String subject, final String toMailSingle, String html) { sendHTML(fromName, subject, new String[]{toMailSingle}, html); } private void sendHTML(final String fromName, final String subject, final String[] toMail, final String html) { try { getInstance().sendMessage(toMail, subject, html); LOGGER.debug(html); } catch (Exception e) { LOGGER.log(Level.ERROR, "Send mail failed", e); } } private static class MailSenderHolder { private static final MailSender INSTANCE = new MailSender(); } }
88250/symphony
src/main/java/org/b3log/symphony/util/Mails.java
6,534
// 邮件的标题,只包含文本的简单邮件
line_comment
zh-cn
/* * Symphony - A modern community (forum/BBS/SNS/blog) platform written in Java. * Copyright (C) 2012-present, b3log.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.b3log.symphony.util; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; import jodd.http.HttpRequest; import jodd.http.HttpResponse; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.b3log.latke.Keys; import org.b3log.latke.util.Crypts; import org.b3log.latke.util.URLs; import org.b3log.symphony.model.Common; import org.json.JSONObject; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.File; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Mail utilities. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @author <a href="http://blog.thinkjava.top">VirutalPier</a> * @author <a href="https://github.com/snowflake3721">snowflake</a> * @version 1.2.6.9, Jun 17, 2019 * @since 1.3.0 */ public final class Mails { /** * Logger. */ private static final Logger LOGGER = LogManager.getLogger(Mails.class); /** * Template name - verifycode. */ public static final String TEMPLATE_NAME_VERIFYCODE = "sym_verifycode"; /** * Template name - weekly. */ public static final String TEMPLATE_NAME_WEEKLY = "sym_weekly"; /** * Template configuration. */ private static final Configuration TEMPLATE_CFG = new Configuration(Templates.FREEMARKER_VER); /** * Domain - Channel mapping. &lt;163.com, aliyun&gt; https://github.com/b3log/symphony/issues/737 */ private static final Map<String, String> DOMAIN_CHANNEL = new HashMap<>(); static { try { TEMPLATE_CFG.setDirectoryForTemplateLoading(new File(Mails.class.getResource("/mail_tpl").toURI())); TEMPLATE_CFG.setDefaultEncoding("UTF-8"); TEMPLATE_CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); TEMPLATE_CFG.setLogTemplateExceptions(false); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Loads mail templates failed", e); } final String mailDomains = Symphonys.MAIL_CHANNEL_MAIL_DOMAINS; if (StringUtils.isNotBlank(mailDomains)) { // aliyun:163.com,126.com;sendcloud:qq.com final String[] channelMaps = StringUtils.split(mailDomains, ";"); for (int i = 0; i < channelMaps.length; i++) { final String channelMap = channelMaps[i]; final String[] channelDomain = StringUtils.split(channelMap, ":"); final String channel = channelDomain[0]; final String[] domains = StringUtils.split(channelDomain[1], ","); for (int j = 0; j < domains.length; j++) { final String domain = domains[j]; DOMAIN_CHANNEL.put(domain, channel); } } } } /** * Private constructor. */ private Mails() { } /** * Sends a HTML mail. * * @param fromName the specified from name * @param subject the specified subject * @param toMail the specified receiver mail * @param templateName the specified template name * @param dataModel the specified data model */ public static void sendHTML(final String fromName, final String subject, final String toMail, final String templateName, final Map<String, Object> dataModel) { if ("sendcloud".equals(Symphonys.MAIL_CHANNEL)) { if (StringUtils.isBlank(Symphonys.MAIL_SENDCLOUD_API_USER) || StringUtils.isBlank(Symphonys.MAIL_SENDCLOUD_API_KEY)) { LOGGER.warn("Please configure [#### SendCloud Mail channel ####] section in symphony.properties for sending mail"); return; } } else if ("aliyun".equals(Symphonys.MAIL_CHANNEL)) { if (StringUtils.isBlank(Symphonys.MAIL_ALIYUN_AK) || StringUtils.isBlank(Symphonys.MAIL_ALIYUN_SK)) { LOGGER.warn("Please configure [#### Aliyun Mail channel ####] section in symphony.properties for sending mail"); return; } } else { if (StringUtils.isBlank(MailSender.username) || StringUtils.isBlank(MailSender.password)) { LOGGER.warn("Please configure [#### Local Mail channel ####] section in symphony.properties for sending mail"); return; } } Keys.fillServer(dataModel); Keys.fillRuntime(dataModel); dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); try { final Template template = TEMPLATE_CFG.getTemplate(templateName + ".ftl"); final StringWriter stringWriter = new StringWriter(); template.process(dataModel, stringWriter); stringWriter.close(); final String html = stringWriter.toString(); final String domain = StringUtils.substringAfter(toMail, "@"); final String channel = DOMAIN_CHANNEL.getOrDefault(domain, Symphonys.MAIL_CHANNEL); switch (channel) { case "aliyun": aliSendHtml(Symphonys.MAIL_ALIYUN_FROM, fromName, subject, toMail, html, Symphonys.MAIL_ALIYUN_AK, Symphonys.MAIL_ALIYUN_SK); return; case "local": MailSender.getInstance().sendHTML(fromName, subject, toMail, html); return; case "sendcloud": final Map<String, Object> formData = new HashMap<>(); formData.put("apiUser", Symphonys.MAIL_SENDCLOUD_API_USER); formData.put("apiKey", Symphonys.MAIL_SENDCLOUD_API_KEY); formData.put("from", Symphonys.MAIL_SENDCLOUD_FROM); formData.put("fromName", fromName); formData.put("subject", subject); formData.put("to", toMail); formData.put("html", html); final HttpResponse response = HttpRequest.post("http://api.sendcloud.net/apiv2/mail/send").form(formData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(5000).send(); response.close(); response.charset("UTF-8"); LOGGER.debug(response.bodyText()); return; default: LOGGER.error("Unknown mail channel [" + channel + "]"); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Sends a mail [subject=" + subject + ", to=" + toMail + "] failed", e); } } /** * Batch send HTML mails. * * @param fromName the specified from name * @param subject the specified subject * @param toMails the specified receiver mails * @param templateName the specified template name * @param dataModel the specified data model */ public static void batchSendHTML(final String fromName, final String subject, final List<String> toMails, final String templateName, final Map<String, Object> dataModel) { if ("sendcloud".equals(Symphonys.MAIL_CHANNEL)) { if (StringUtils.isBlank(Symphonys.MAIL_SENDCLOUD_BATCH_API_USER) || StringUtils.isBlank(Symphonys.MAIL_SENDCLOUD_BATCH_API_KEY)) { LOGGER.warn("Please configure [#### SendCloud Mail channel ####] section in symphony.properties for sending mail"); return; } } else if ("aliyun".equals(Symphonys.MAIL_CHANNEL)) { if (StringUtils.isBlank(Symphonys.MAIL_ALIYUN_AK) || StringUtils.isBlank(Symphonys.MAIL_ALIYUN_SK)) { LOGGER.warn("Please configure [#### Aliyun Mail channel ####] section in symphony.properties for sending mail"); return; } } else { if (StringUtils.isBlank(MailSender.username) || StringUtils.isBlank(MailSender.password)) { LOGGER.warn("Please configure [#### Local Mail channel ####] section in symphony.properties for sending mail"); return; } } Keys.fillServer(dataModel); Keys.fillRuntime(dataModel); dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); try { final Map<String, Object> formData = new HashMap<>(); formData.put("apiUser", Symphonys.MAIL_SENDCLOUD_BATCH_API_USER); formData.put("apiKey", Symphonys.MAIL_SENDCLOUD_BATCH_API_KEY); formData.put("from", Symphonys.MAIL_SENDCLOUD_BATCH_FROM); formData.put("fromName", fromName); formData.put("subject", subject); formData.put("templateInvokeName", templateName); final Template template = TEMPLATE_CFG.getTemplate(templateName + ".ftl"); final StringWriter stringWriter = new StringWriter(); template.process(dataModel, stringWriter); stringWriter.close(); final String html = stringWriter.toString(); // Creates or updates the SendCloud email template if ("sendcloud".equals(Symphonys.MAIL_CHANNEL)) { refreshWeeklyTemplate(html); } int index = 0; final int size = toMails.size(); List<String> batch = new ArrayList<>(); HttpResponse response; while (index < size) { final String mail = toMails.get(index); batch.add(mail); index++; if (batch.size() > 99) { if ("aliyun".equals(Symphonys.MAIL_CHANNEL)) { final String toMail = getStringToMailByList(batch); aliSendHtml(Symphonys.MAIL_ALIYUN_BATCH_FROM, fromName, subject, toMail, html, Symphonys.MAIL_ALIYUN_AK, Symphonys.MAIL_ALIYUN_SK); LOGGER.info("Sent [" + batch.size() + "] mails"); } else if ("local".equals(Symphonys.MAIL_CHANNEL.toLowerCase())) { MailSender.getInstance().sendHTML(fromName, subject, batch, html); } else { try { final JSONObject xsmtpapi = new JSONObject(); xsmtpapi.put("to", batch); xsmtpapi.put("sub", new JSONObject()); formData.put("xsmtpapi", xsmtpapi.toString()); response = HttpRequest.post("http://api.sendcloud.net/apiv2/mail/sendtemplate").form(formData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send(); response.close(); response.charset("UTF-8"); LOGGER.debug(response.bodyText()); LOGGER.info("Sent [" + batch.size() + "] mails"); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Send mail failed", e); } } batch.clear(); } } if (!batch.isEmpty()) { // Process remains if ("aliyun".equals(Symphonys.MAIL_CHANNEL)) { final String toMail = getStringToMailByList(batch); aliSendHtml(Symphonys.MAIL_ALIYUN_BATCH_FROM, fromName, subject, toMail, html, Symphonys.MAIL_ALIYUN_AK, Symphonys.MAIL_ALIYUN_SK); LOGGER.info("Sent [" + batch.size() + "] mails"); } else if ("local".equals(Symphonys.MAIL_CHANNEL.toLowerCase())) { MailSender.getInstance().sendHTML(fromName, subject, batch, html); } else { try { final JSONObject xsmtpapi = new JSONObject(); xsmtpapi.put("to", batch); xsmtpapi.put("sub", new JSONObject()); formData.put("xsmtpapi", xsmtpapi.toString()); response = HttpRequest.post("http://api.sendcloud.net/apiv2/mail/sendtemplate").form(formData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send(); response.close(); response.charset("UTF-8"); LOGGER.debug(response.bodyText()); LOGGER.info("Sent [" + batch.size() + "] mails"); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Send mail failed", e); } } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Batch send mail failed", e); } } /** * Sends a HTML mail via Aliyun. * * @param fromName the specified from name * @param subject the specified subject * @param toMail the specified receiver mail * @param html send html */ private static void aliSendHtml(final String sendMail, final String fromName, final String subject, final String toMail, final String html, final String accessKey, final String accessSecret) { final Map<String, Object> map = new HashMap<>(); map.put("Action", "SingleSendMail"); map.put("Format", "JSON"); map.put("Version", "2015-11-23"); map.put("AccessKeyId", accessKey); map.put("SignatureMethod", "HMAC-SHA1"); map.put("Timestamp", getISO8601Time()); map.put("SignatureVersion", "1.0"); map.put("SignatureNonce", String.valueOf(System.currentTimeMillis())); map.put("AccountName", sendMail); map.put("FromAlias", fromName); map.put("ReplyToAddress", "true"); map.put("AddressType", "1"); map.put("ToAddress", toMail); map.put("Subject", subject); map.put("HtmlBody", html); final String[] sortedKeys = map.keySet().toArray(new String[]{}); Arrays.sort(sortedKeys); final StringBuilder canonicalizedQueryString = new StringBuilder(); for (String key : sortedKeys) { canonicalizedQueryString.append("&") .append(Mails.percentEncode(key)).append("=") .append(Mails.percentEncode(map.get(key).toString())); } final StringBuffer stringToSign = new StringBuffer(); stringToSign.append("POST"); stringToSign.append("&"); stringToSign.append(Mails.percentEncode("/")); stringToSign.append("&"); stringToSign.append(Mails.percentEncode(canonicalizedQueryString.toString().substring(1))); map.put("Signature", Crypts.signHmacSHA1(stringToSign.toString(), accessSecret + "&")); final HttpResponse response = HttpRequest.post("https://dm.aliyuncs.com").form(map).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send(); response.close(); response.charset("UTF-8"); LOGGER.debug(response.bodyText()); } private static String percentEncode(final String value) { return value != null ? URLs.encode(value).replace("+", "%20") .replace("*", "%2A").replace("%7E", "~") : null; } private static String getISO8601Time() { final Date nowDate = new Date(); final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df.format(nowDate); } private static String getStringToMailByList(final List<String> toMails) { final StringBuffer mails = new StringBuffer(); for (String mail : toMails) { mails.append(mail + ","); } mails.deleteCharAt(mails.length() - 1); return mails.toString(); } private static void refreshWeeklyTemplate(final String html) { final Map<String, Object> addData = new HashMap<>(); addData.put("apiUser", Symphonys.MAIL_SENDCLOUD_BATCH_API_USER); addData.put("apiKey", Symphonys.MAIL_SENDCLOUD_BATCH_API_KEY); addData.put("invokeName", TEMPLATE_NAME_WEEKLY); addData.put("name", "Weekly Newsletter"); addData.put("subject", "Weekly Newsletter"); addData.put("templateType", "1"); // 批量邮件 addData.put("html", html); HttpRequest.post("http://api.sendcloud.net/apiv2/template/add").form(addData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send().close(); final Map<String, Object> updateData = new HashMap<>(); updateData.put("apiUser", Symphonys.MAIL_SENDCLOUD_BATCH_API_USER); updateData.put("apiKey", Symphonys.MAIL_SENDCLOUD_BATCH_API_KEY); updateData.put("invokeName", TEMPLATE_NAME_WEEKLY); updateData.put("html", html); HttpRequest.post("http://api.sendcloud.net/apiv2/template/update").form(updateData).header(Common.USER_AGENT, Symphonys.USER_AGENT_BOT). connectionTimeout(5000).timeout(30000).send().close(); } } /** * 通过 JavaMail SMTP 发送邮件. * <p> * 支持三种类型的邮件: * <ul> * <li>SIMPLE 简单类型,可以发送 HTML 格式文本,遵从 FreeMarker 模板的设置</li> * <li>IMAGE HTML 格式类型,同时会保存 HTML 里面的 image 到磁盘,并生成 eml 保存到服务器的配置目录</li> * </ul> * </p> * * @author <a href="https://github.com/snowflake3721">snowflake</a> * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.0.2.2, Jun 17, 2019 * @since 2.1.0 */ final class MailSender implements java.io.Serializable { public static final String sender = Symphonys.MAIL_LOCAL_SMTP_SENDER; public static final String username = Symphonys.MAIL_LOCAL_SMTP_USERNAME; public static final String password = Symphonys.MAIL_LOCAL_SMTP_PASSWORD; private static final long serialVersionUID = -1000794424345267933L; private static final String CHARSET = "text/html;charset=UTF-8"; private static final Logger LOGGER = LogManager.getLogger(Markdowns.class); private static final boolean is_debug = Boolean.valueOf(Symphonys.MAIL_LOCAL_ISDEBUG); private static final String mail_transport_protocol = Symphonys.MAIL_LOCAL_TRANSPORT_PROTOCOL; private static final String mail_host = Symphonys.MAIL_LOCAL_HOST; private static final String mail_port = Symphonys.MAIL_LOCAL_PORT; private static final String mail_smtp_auth = Symphonys.MAIL_LOCAL_SMTP_AUTH; private static final String mail_smtp_ssl_enable = Symphonys.MAIL_LOCAL_SMTP_SSL; private static final String mail_smtp_starttls_enable = Symphonys.MAIL_LOCAL_SMTP_STARTTLS; private static MailSender mailSender; private static final Properties prop = new Properties(); private MailSender() { prop.setProperty("mail.transport.protocol", mail_transport_protocol); prop.setProperty("mail.host", mail_host); prop.setProperty("mail.port", mail_port); prop.setProperty("mail.smtp.auth", mail_smtp_auth); prop.setProperty("mail.smtp.ssl.enable", mail_smtp_ssl_enable); prop.setProperty("mail.smtp.starttls.enable", mail_smtp_starttls_enable); prop.setProperty("mail.smtp.sender", sender); prop.setProperty("mail.smtp.username", username); prop.setProperty("mail.smtp.passsword", password); } public static final MailSender getInstance() { if (null == mailSender) { mailSender = MailSenderHolder.INSTANCE; } return mailSender; } private static Set<String> getImgStr(String htmlStr) { Set<String> pics = new HashSet<>(); String img = ""; Pattern p_image; Matcher m_image; // String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址 String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>"; p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE); m_image = p_image.matcher(htmlStr); while (m_image.find()) { // 得到<img />数据 img = m_image.group(); // 匹配<img>中的src数据 Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img); while (m.find()) { pics.add(m.group(1)); } } return pics; } private static void setTo(String[] to, MimeMessage message) throws MessagingException { // 指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发 if (null != to && to.length > 0) { if (to.length == 1) { message.setRecipient(Message.RecipientType.TO, new InternetAddress(to[0])); } else { List<InternetAddress> iaList = new ArrayList<InternetAddress>(); for (String t : to) { InternetAddress ia = new InternetAddress(t); iaList.add(ia); } InternetAddress[] iaArray = new InternetAddress[to.length]; message.setRecipients(Message.RecipientType.TO, iaList.toArray(iaArray)); } } } public static void main(String[] args) { System.out.println(CHARSET.toLowerCase()); /* * MailSender mailSender = getInstance(); * * String subject = "eml with Image"; String content = * "这是一封邮件正文带图片<img width=\"60px\" src=\"http://localhost:8080/images/logo-M301-161X105.png\" />的邮件" * ; String[] tos = { "bruceyang_it@163.com" }; * mailSender.sendMessage(tos, subject, content, saved_path, * MailType.IMAGE); */ } private Object readResolve() { return MailSenderHolder.INSTANCE; } public void sendMessage(String[] tos, String subject, String content) throws Exception { // 1、创建session Session session = Session.getInstance(prop); // 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 session.setDebug(is_debug); // 2、通过session得到transport对象 Transport ts = session.getTransport(); // 3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。 ts.connect(mail_host, Integer.valueOf(mail_port), username, password); // 4、创建邮件 MimeMessage message = new MimeMessage(session); createTextMail(message, sender, tos, subject, content); // 5、发送邮件 ts.sendMessage(message, message.getAllRecipients()); LOGGER.debug(Arrays.toString(tos)); LOGGER.debug(subject); LOGGER.debug(content); ts.close(); } /** * 创建一封只包含文本的邮件. * * @param message * @param from * @param to * @param subject * @param content * @return * @throws Exception */ public MimeMessage createTextMail(MimeMessage message, String from, String[] to, String subject, String content) throws Exception { // 指明邮件的发件人 message.setFrom(new InternetAddress(from)); setTo(to, message); // 邮件 <SUF> if (StringUtils.isEmpty(subject)) { subject = "email from the system"; } message.setSubject(StringUtils.trimToEmpty(subject)); // 邮件的文本内容 message.setContent(content, CHARSET); // 返回创建好的邮件对象 return message; } /** * Sends a HTML mail for toMailList. * * @param fromName * @param subject * @param toMailList * @param html */ public void sendHTML(final String fromName, final String subject, final List<String> toMailList, String html) { if (null != toMailList && toMailList.size() > 0) { sendHTML(fromName, subject, toMailList.toArray(new String[toMailList.size()]), html); } } /** * Sends a HTML mail. * * @param fromName * @param subject * @param toMailSingle * @param html */ public void sendHTML(final String fromName, final String subject, final String toMailSingle, String html) { sendHTML(fromName, subject, new String[]{toMailSingle}, html); } private void sendHTML(final String fromName, final String subject, final String[] toMail, final String html) { try { getInstance().sendMessage(toMail, subject, html); LOGGER.debug(html); } catch (Exception e) { LOGGER.log(Level.ERROR, "Send mail failed", e); } } private static class MailSenderHolder { private static final MailSender INSTANCE = new MailSender(); } }
0
24634_14
package com.hjz.util; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * AES加密 * @author Chen * @version 1 */ public class AES { /** * 加密 * * @param content 需要加密的内容 * @param password 加密密码 * @return */ public static byte[] encrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } /** * 解密 * * @param content 待解密内容 * @param password 解密密钥 * @return */ public static byte[] decrypt(byte[] content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(content); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } /** * 将二进制转换成16进制 * * @param buf * @return */ public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 将16进制转换为二进制 * * @param hexStr * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } /** * 加密 * * @param content 需要加密的内容 * @param password 加密密码 * @return */ public static byte[] encrypt2(String content, String password) { try { SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } //测试主函数 // public static void main(String[] args) throws UnsupportedEncodingException { // String content = "针对现有分布式深度学习外包计算模式下存在的数据隐私泄露问题,分析生成式对抗网络攻击和成员推理攻击等隐私攻击特征,定义分布式深度学习外包计算敌手模型,重点研究基于恶意多方计算协议和矩阵盲化的安全训练交互方法,设计基于多因子盲化与加法同态加密相结合的隐私数据和模型参数安全聚合方案,实现用户数据和训练模型的保护。此外,考虑到针对特定受害者隐私数据的多方共谋攻击场景,研究利用Shamir秘密共享协议等隐私保护技术强化更新聚合和验证过程,从抵御攻击注入以及防止模型滥用角度实现数据隐私的保护。\r\n" + // "仿:针对现有分布式机器学习模型下存在的模型安全问题,分析后门攻击等隐私攻击特征,定义分布式机器学习敌手模型。研究基于分布式机器学习模型的后门攻击检测方案,实质是研究对于植入模型中静态或动态触发器检测。对传统的防御方法频谱签名,激活聚类,STRIP和神经清洁进行优化,设计基于多因子盲化与加法同态加密相结合的隐私数据和模型参数安全聚合方案,实现用户数据和训练模型的保护。此外,考虑到用户共谋攻击场景,研究设计模型培训和测试以及数据收集和验证应由系统提供商直接执行,然后进行安全维护的分布式机器学习模型,从而避免后门攻击的绝大部分威胁。(3)分布式深度学习外包中的可验证性方法研究针对分布式深度学习外包计算过程中数据可用性和结果正确性的验证问题,重点研究多源高维数据的特征提取、聚类分析、离群点检测技术,设计可实时更新的恶意检测模型,实"; // String password = "12345678"; // // 加密 // System.out.println("加密前:" + content); // byte[] encode = encrypt(content, password); // // // 传输过程,不转成16进制的字符串,就等着程序崩溃掉吧 // String code = parseByte2HexStr(encode); // System.out.println("密文字符串:" + code); // byte[] decode = parseHexStr2Byte(code); // // 解密 // byte[] decryptResult = decrypt(decode, password); // System.out.println("解密后:" + new String(decryptResult, "UTF-8")); // 不转码会乱码 // // } }
894346698/QRCodeGUI
src/com/hjz/util/AES.java
2,009
// "仿:针对现有分布式机器学习模型下存在的模型安全问题,分析后门攻击等隐私攻击特征,定义分布式机器学习敌手模型。研究基于分布式机器学习模型的后门攻击检测方案,实质是研究对于植入模型中静态或动态触发器检测。对传统的防御方法频谱签名,激活聚类,STRIP和神经清洁进行优化,设计基于多因子盲化与加法同态加密相结合的隐私数据和模型参数安全聚合方案,实现用户数据和训练模型的保护。此外,考虑到用户共谋攻击场景,研究设计模型培训和测试以及数据收集和验证应由系统提供商直接执行,然后进行安全维护的分布式机器学习模型,从而避免后门攻击的绝大部分威胁。(3)分布式深度学习外包中的可验证性方法研究针对分布式深度学习外包计算过程中数据可用性和结果正确性的验证问题,重点研究多源高维数据的特征提取、聚类分析、离群点检测技术,设计可实时更新的恶意检测模型,实";
line_comment
zh-cn
package com.hjz.util; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * AES加密 * @author Chen * @version 1 */ public class AES { /** * 加密 * * @param content 需要加密的内容 * @param password 加密密码 * @return */ public static byte[] encrypt(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } /** * 解密 * * @param content 待解密内容 * @param password 解密密钥 * @return */ public static byte[] decrypt(byte[] content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(content); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } /** * 将二进制转换成16进制 * * @param buf * @return */ public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 将16进制转换为二进制 * * @param hexStr * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } /** * 加密 * * @param content 需要加密的内容 * @param password 加密密码 * @return */ public static byte[] encrypt2(String content, String password) { try { SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } //测试主函数 // public static void main(String[] args) throws UnsupportedEncodingException { // String content = "针对现有分布式深度学习外包计算模式下存在的数据隐私泄露问题,分析生成式对抗网络攻击和成员推理攻击等隐私攻击特征,定义分布式深度学习外包计算敌手模型,重点研究基于恶意多方计算协议和矩阵盲化的安全训练交互方法,设计基于多因子盲化与加法同态加密相结合的隐私数据和模型参数安全聚合方案,实现用户数据和训练模型的保护。此外,考虑到针对特定受害者隐私数据的多方共谋攻击场景,研究利用Shamir秘密共享协议等隐私保护技术强化更新聚合和验证过程,从抵御攻击注入以及防止模型滥用角度实现数据隐私的保护。\r\n" + // "仿 <SUF> // String password = "12345678"; // // 加密 // System.out.println("加密前:" + content); // byte[] encode = encrypt(content, password); // // // 传输过程,不转成16进制的字符串,就等着程序崩溃掉吧 // String code = parseByte2HexStr(encode); // System.out.println("密文字符串:" + code); // byte[] decode = parseHexStr2Byte(code); // // 解密 // byte[] decryptResult = decrypt(decode, password); // System.out.println("解密后:" + new String(decryptResult, "UTF-8")); // 不转码会乱码 // // } }
1
21771_11
package com.company.admin.util; import org.apache.commons.lang3.StringUtils; /** * <pre> * 本类的主要功能是将带有emoji的字符串,格式化成unicode字符串,并且提供可见unicode字符反解成emoji字符 * * * 相关识知点: * <b> * Unicode平面, * BMP的字符可以使用charAt(index)来处理,计数可以使用length() * 其它平面字符,需要用codePointAt(index),计数可以使用codePointCount(0,str.lenght())</b> * * Unicode可以逻辑分为17平面(Plane),每个平面拥有65536( = 216)个代码点,虽然目前只有少数平面被使 * 用。 * 平面0 (0000–FFFF): 基本多文种平面(Basic Multilingual Plane, BMP). * 平面1 (10000–1FFFF): 多文种补充平面(Supplementary Multilingual Plane, SMP). * 平面2 (20000–2FFFF): 表意文字补充平面(Supplementary Ideographic Plane, SIP). * 平面3 (30000–3FFFF): 表意文字第三平面(Tertiary Ideographic Plane, TIP). * 平面4 to 13 (40000–DFFFF)尚未使用 * 平面14 (E0000–EFFFF): 特别用途补充平面(Supplementary Special-purpose Plane, SSP) * 平面15 (F0000–FFFFF)保留作为私人使用区(Private Use Area, PUA) * 平面16 (100000–10FFFF),保留作为私人使用区(Private Use Area, PUA) * * 参考: * 维基百科: http://en.wikipedia.org/wiki/Emoji * GITHUB: http://punchdrunker.github.io/iOSEmoji/ * 杂项象形符号:1F300-1F5FF * 表情符号:1F600-1F64F * 交通和地图符号:1F680-1F6FF * 杂项符号:2600-26FF * 符号字体:2700-27BF * 国旗:1F100-1F1FF * 箭头:2B00-2BFF 2900-297F * 各种技术符号:2300-23FF * 字母符号: 2100–214F * 中文符号: 303D 3200–32FF 2049 203C * Private Use Area:E000-F8FF; * High Surrogates D800..DB7F; * High Private Use Surrogates DB80..DBFF * Low Surrogates DC00..DFFF D800-DFFF E000-F8FF * 标点符号:2000-200F 2028-202F 205F 2065-206F * 变异选择器:IOS独有 FE00-FE0F * </pre> */ public class EmojiCharacterUtil { // 转义时标识 private static final char unicode_separator = '&'; private static final char unicode_prefix = 'u'; private static final char separator = ':'; private static boolean isEmojiCharacter(int codePoint) { return (codePoint >= 0x2600 && codePoint <= 0x27BF) // 杂项符号与符号字体 || codePoint == 0x303D || codePoint == 0x2049 || codePoint == 0x203C || (codePoint >= 0x2000 && codePoint <= 0x200F)// || (codePoint >= 0x2028 && codePoint <= 0x202F)// || codePoint == 0x205F // || (codePoint >= 0x2065 && codePoint <= 0x206F)// /* 标点符号占用区域 */ || (codePoint >= 0x2100 && codePoint <= 0x214F)// 字母符号 || (codePoint >= 0x2300 && codePoint <= 0x23FF)// 各种技术符号 || (codePoint >= 0x2B00 && codePoint <= 0x2BFF)// 箭头A || (codePoint >= 0x2900 && codePoint <= 0x297F)// 箭头B || (codePoint >= 0x3200 && codePoint <= 0x32FF)// 中文符号 || (codePoint >= 0xD800 && codePoint <= 0xDFFF)// 高低位替代符保留区域 || (codePoint >= 0xE000 && codePoint <= 0xF8FF)// 私有保留区域 || (codePoint >= 0xFE00 && codePoint <= 0xFE0F)// 变异选择器 || codePoint >= 0x10000; // Plane在第二平面以上的,char都不可以存,全部都转 } /** * 将带有emoji字符的字符串转换成可见字符标识 */ public static String escape(String src) { if (StringUtils.isBlank(src)) { return src; } int cpCount = src.codePointCount(0, src.length()); int firCodeIndex = src.offsetByCodePoints(0, 0); int lstCodeIndex = src.offsetByCodePoints(0, cpCount - 1); StringBuilder sb = new StringBuilder(src.length()); for (int index = firCodeIndex; index <= lstCodeIndex; index ++) { int codepoint = src.codePointAt(index); if (isEmojiCharacter(codepoint)) { String hash = Integer.toHexString(codepoint); sb.append(unicode_separator).append(hash.length()).append(unicode_prefix).append(separator).append(hash); // hash 长度,4位1个字节 index += (hash.length() - 1)/4; } else { sb.append((char) codepoint); } } return sb.toString(); } /** 解析可见字符标识字符串 */ public static String reverse(String src) { // 查找对应编码的标识位 if (StringUtils.isBlank(src)) { return src; } StringBuilder sb = new StringBuilder(src.length()); char[] sourceChar = src.toCharArray(); int index = 0; while (index < sourceChar.length) { if (sourceChar[index] == unicode_separator) { if (index + 6 >= sourceChar.length) { sb.append(sourceChar[index]); index++; continue; } // 自已的格式,与通用unicode格式不能互转 if (sourceChar[index + 1] >= '4' && sourceChar[index + 1] <= '6' && sourceChar[index + 2] == unicode_prefix && sourceChar[index + 3] == separator) { int length = Integer.parseInt(String.valueOf(sourceChar[index + 1])); char[] hexchars = new char[length]; // 创建一个4至六位的数组,来存储uncode码的HEX值 for (int j = 0; j < length; j++) { char ch = sourceChar[index + 4 + j];// 4位识别码 if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')) { hexchars[j] = ch; } else { // 字符范围不对 sb.append(sourceChar[index]); index++; break; } } sb.append(Character.toChars(Integer.parseInt(new String(hexchars), 16))); index += (4 + length);// 4位前缀+4-6位字符码 } else if (sourceChar[index + 1] == unicode_prefix) { // 通用字符的反转 // 因为第二平面之上的,已经采用了我们自己转码格式,所以这里是固定的长度4 char[] hexchars = new char[4]; for (int j = 0; j < 4; j++) { char ch = sourceChar[index + 2 + j]; // 两位识别码要去掉 if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')) { hexchars[j] = ch; // 4位识别码 } else { // 字符范围不对 sb.append(sourceChar[index]); index++; break; } sb.append(Character.toChars(Integer.parseInt(String.valueOf(hexchars), 16))); index += (2 + 4);// 2位前缀+4位字符码 } } else { sb.append(sourceChar[index]); index++; continue; } } else { sb.append(sourceChar[index]); index++; continue; } } return sb.toString(); } public static String filter(String src) { if (src == null) { return null; } int cpCount = src.codePointCount(0, src.length()); int firCodeIndex = src.offsetByCodePoints(0, 0); int lstCodeIndex = src.offsetByCodePoints(0, cpCount - 1); StringBuilder sb = new StringBuilder(src.length()); for (int index = firCodeIndex; index <= lstCodeIndex;) { int codepoint = src.codePointAt(index); if (!isEmojiCharacter(codepoint)) { System.err.println("codepoint:" + Integer.toHexString(codepoint)); sb.append((char) codepoint); } index += ((Character.isSupplementaryCodePoint(codepoint)) ? 2 : 1); } return sb.toString(); } public static void main(String[] args) { String aa = "☀☁☔⛄⚡🌀🌁🌂🌃🌄🌅🌆🌇🌈❄⛅🌉🌊🌋🌌🌏🌑🌔🌓🌙🌕🌛🌟🌠🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛⌚⌛⏰⏳♈♉♊♋♌♍♎♏♐♑♒♓⛎🍀🌷🌱🍁🌸🌹🍂🍃🌺🌻🌴🌵🌾🌽🍄🌰🌼🌿🍒🍌🍎🍊🍓🍉🍅🍆🍈🍍🍇🍑🍏👀👂👃👄👅💄💅💆💇💈👤👦👧👨👩👪👫👮👯👰👱👲👳👴👵👶👷👸👹👺👻👼👽👾👿💀💁💂💃🐌🐍🐎🐔🐗🐫🐘🐨🐒🐑🐙🐚🐛🐜🐝🐞🐠🐡🐢🐤🐥🐦🐣🐧🐩🐟🐬🐭🐯🐱🐳🐴🐵🐶🐷🐻🐹🐺🐮🐰🐸🐾🐲🐼🐽😠😩😲😞😵😰😒😍😤😜😝😋😘😚😷😳😃😅😆😁😂😊☺😄😢😭😨😣😡😌😖😔😱😪😏😓😥😫😉😺😸😹😽😻😿😾😼🙀🙅🙆🙇🙈🙊🙉🙋🙌🙍🙎🙏🏠🏡🏢🏣🏥🏦🏧🏨🏩🏪🏫⛪⛲🏬🏯🏰🏭⚓🏮🗻🗼🗽🗾🗿👞👟👠👡👢👣👓👕👖👑👔👒👗👘👙👚👛👜👝💰💱💹💲💳💴💵💸----------🔥🔦🔧🔨🔩🔪🔫🔮🔯🔰🔱💉💊🅰🅱🆎🅾🎀🎁🎂🎄🎅🎌🎆🎈🎉🎍🎎🎓🎒🎏🎇🎐🎃🎊🎋🎑📟☎📞📱📲📝📠✉📨📩📪📫📮📰📢📣📡📤📥📦📧🔠🔡🔢🔣🔤✒💺💻✏📎💼💽💾💿📀✂📍📃📄📅📁📂📓📖📔📕📗📘📙📚📛📜📋📆📊📈📉📇📌📒📏📐📑🎽⚾⛳🎾⚽🎿🏀🏁🏂🏃🏄🏆🏈🏊🚃🚇Ⓜ🚄🚅🚗🚙🚌🚏🚢✈⛵🚉🚀🚤🚕🚚🚒🚑🚓⛽🅿🚥🚧🚨♨⛺🎠🎡🎢🎣🎤🎥🎦🎧🎨🎩🎪🎫🎬🎭🎮🀄🎯🎰🎱🎲🎳🎴🃏🎵🎶🎷🎸🎹🎺🎻🎼〽📷📹📺📻📼💋💌💍💎💏💐💑💒🔞©®™ℹ-----------🔟📶📳📴🍔🍙🍰🍜🍞🍳🍦🍟🍡🍘🍚🍝🍛🍢🍣🍱🍲🍧🍖🍥🍠🍕🍗🍨🍩🍪🍫🍬🍭🍮🍯🍤🍴☕🍸🍺🍵🍶🍷🍻🍹↗↘↖↙⤴⤵↔↕⬆⬇➡⬅▶◀⏩⏪⏫⏬🔺🔻🔼🔽⭕❌❎❗⁉‼❓❔❕〰➰-❤💓💔💕💖💗💘💙💚💛💜💝💞💟♥♠♦♣🚬🚭♿🚩⚠⛔♻🚲🚶🚹🚺🛀🚻🚽🚾🚼🚪🚫✔🆑🆒🆓🆔🆕🆖🆗🆘🆙🆚🈁🈂🈲🈳🈴🈵🈶🈚🈷🈸🈹🈯🈺㊙㊗🉐🉑➕➖✖➗💠💡💢💣💤💥💦💧💨💩💪💫💬✨✴✳⚪⚫🔴🔵🔲🔳⭐⬜⬛▫▪◽◾◻◼🔶🔷🔸🔹❇💮💯↩↪🔃🔊🔋🔌🔍🔎🔒🔓🔏🔐🔑🔔☑🔘🔖🔗🔙🔚🔛🔜🔝✅✊✋✌👊👍☝👆👇👈👉👋👏👌👎👐"; // String aa = "我自从看了这篇文章,恍然大悟😁😂😊,感觉这么多🌑🌔🌓年都白活了,支持嗨老会,多🕓🕔🕕🕖🕗🕘发布些有利我们老年人的文章,年轻生活,从我做起!"; System.out.println("aa:"+aa); long start = 0L; long end = 0L; start = System.currentTimeMillis(); String escape = EmojiCharacterUtil.escape(aa); end = System.currentTimeMillis(); System.out.println((end - start)+" escape:"+escape); start = System.currentTimeMillis(); String reverse = EmojiCharacterUtil.reverse(escape); end = System.currentTimeMillis(); System.out.println((end - start)+" reverse:"+reverse); } }
897665787/springcloud-template
admin/src/main/java/com/company/admin/util/EmojiCharacterUtil.java
4,378
// 变异选择器
line_comment
zh-cn
package com.company.admin.util; import org.apache.commons.lang3.StringUtils; /** * <pre> * 本类的主要功能是将带有emoji的字符串,格式化成unicode字符串,并且提供可见unicode字符反解成emoji字符 * * * 相关识知点: * <b> * Unicode平面, * BMP的字符可以使用charAt(index)来处理,计数可以使用length() * 其它平面字符,需要用codePointAt(index),计数可以使用codePointCount(0,str.lenght())</b> * * Unicode可以逻辑分为17平面(Plane),每个平面拥有65536( = 216)个代码点,虽然目前只有少数平面被使 * 用。 * 平面0 (0000–FFFF): 基本多文种平面(Basic Multilingual Plane, BMP). * 平面1 (10000–1FFFF): 多文种补充平面(Supplementary Multilingual Plane, SMP). * 平面2 (20000–2FFFF): 表意文字补充平面(Supplementary Ideographic Plane, SIP). * 平面3 (30000–3FFFF): 表意文字第三平面(Tertiary Ideographic Plane, TIP). * 平面4 to 13 (40000–DFFFF)尚未使用 * 平面14 (E0000–EFFFF): 特别用途补充平面(Supplementary Special-purpose Plane, SSP) * 平面15 (F0000–FFFFF)保留作为私人使用区(Private Use Area, PUA) * 平面16 (100000–10FFFF),保留作为私人使用区(Private Use Area, PUA) * * 参考: * 维基百科: http://en.wikipedia.org/wiki/Emoji * GITHUB: http://punchdrunker.github.io/iOSEmoji/ * 杂项象形符号:1F300-1F5FF * 表情符号:1F600-1F64F * 交通和地图符号:1F680-1F6FF * 杂项符号:2600-26FF * 符号字体:2700-27BF * 国旗:1F100-1F1FF * 箭头:2B00-2BFF 2900-297F * 各种技术符号:2300-23FF * 字母符号: 2100–214F * 中文符号: 303D 3200–32FF 2049 203C * Private Use Area:E000-F8FF; * High Surrogates D800..DB7F; * High Private Use Surrogates DB80..DBFF * Low Surrogates DC00..DFFF D800-DFFF E000-F8FF * 标点符号:2000-200F 2028-202F 205F 2065-206F * 变异选择器:IOS独有 FE00-FE0F * </pre> */ public class EmojiCharacterUtil { // 转义时标识 private static final char unicode_separator = '&'; private static final char unicode_prefix = 'u'; private static final char separator = ':'; private static boolean isEmojiCharacter(int codePoint) { return (codePoint >= 0x2600 && codePoint <= 0x27BF) // 杂项符号与符号字体 || codePoint == 0x303D || codePoint == 0x2049 || codePoint == 0x203C || (codePoint >= 0x2000 && codePoint <= 0x200F)// || (codePoint >= 0x2028 && codePoint <= 0x202F)// || codePoint == 0x205F // || (codePoint >= 0x2065 && codePoint <= 0x206F)// /* 标点符号占用区域 */ || (codePoint >= 0x2100 && codePoint <= 0x214F)// 字母符号 || (codePoint >= 0x2300 && codePoint <= 0x23FF)// 各种技术符号 || (codePoint >= 0x2B00 && codePoint <= 0x2BFF)// 箭头A || (codePoint >= 0x2900 && codePoint <= 0x297F)// 箭头B || (codePoint >= 0x3200 && codePoint <= 0x32FF)// 中文符号 || (codePoint >= 0xD800 && codePoint <= 0xDFFF)// 高低位替代符保留区域 || (codePoint >= 0xE000 && codePoint <= 0xF8FF)// 私有保留区域 || (codePoint >= 0xFE00 && codePoint <= 0xFE0F)// 变异 <SUF> || codePoint >= 0x10000; // Plane在第二平面以上的,char都不可以存,全部都转 } /** * 将带有emoji字符的字符串转换成可见字符标识 */ public static String escape(String src) { if (StringUtils.isBlank(src)) { return src; } int cpCount = src.codePointCount(0, src.length()); int firCodeIndex = src.offsetByCodePoints(0, 0); int lstCodeIndex = src.offsetByCodePoints(0, cpCount - 1); StringBuilder sb = new StringBuilder(src.length()); for (int index = firCodeIndex; index <= lstCodeIndex; index ++) { int codepoint = src.codePointAt(index); if (isEmojiCharacter(codepoint)) { String hash = Integer.toHexString(codepoint); sb.append(unicode_separator).append(hash.length()).append(unicode_prefix).append(separator).append(hash); // hash 长度,4位1个字节 index += (hash.length() - 1)/4; } else { sb.append((char) codepoint); } } return sb.toString(); } /** 解析可见字符标识字符串 */ public static String reverse(String src) { // 查找对应编码的标识位 if (StringUtils.isBlank(src)) { return src; } StringBuilder sb = new StringBuilder(src.length()); char[] sourceChar = src.toCharArray(); int index = 0; while (index < sourceChar.length) { if (sourceChar[index] == unicode_separator) { if (index + 6 >= sourceChar.length) { sb.append(sourceChar[index]); index++; continue; } // 自已的格式,与通用unicode格式不能互转 if (sourceChar[index + 1] >= '4' && sourceChar[index + 1] <= '6' && sourceChar[index + 2] == unicode_prefix && sourceChar[index + 3] == separator) { int length = Integer.parseInt(String.valueOf(sourceChar[index + 1])); char[] hexchars = new char[length]; // 创建一个4至六位的数组,来存储uncode码的HEX值 for (int j = 0; j < length; j++) { char ch = sourceChar[index + 4 + j];// 4位识别码 if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')) { hexchars[j] = ch; } else { // 字符范围不对 sb.append(sourceChar[index]); index++; break; } } sb.append(Character.toChars(Integer.parseInt(new String(hexchars), 16))); index += (4 + length);// 4位前缀+4-6位字符码 } else if (sourceChar[index + 1] == unicode_prefix) { // 通用字符的反转 // 因为第二平面之上的,已经采用了我们自己转码格式,所以这里是固定的长度4 char[] hexchars = new char[4]; for (int j = 0; j < 4; j++) { char ch = sourceChar[index + 2 + j]; // 两位识别码要去掉 if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')) { hexchars[j] = ch; // 4位识别码 } else { // 字符范围不对 sb.append(sourceChar[index]); index++; break; } sb.append(Character.toChars(Integer.parseInt(String.valueOf(hexchars), 16))); index += (2 + 4);// 2位前缀+4位字符码 } } else { sb.append(sourceChar[index]); index++; continue; } } else { sb.append(sourceChar[index]); index++; continue; } } return sb.toString(); } public static String filter(String src) { if (src == null) { return null; } int cpCount = src.codePointCount(0, src.length()); int firCodeIndex = src.offsetByCodePoints(0, 0); int lstCodeIndex = src.offsetByCodePoints(0, cpCount - 1); StringBuilder sb = new StringBuilder(src.length()); for (int index = firCodeIndex; index <= lstCodeIndex;) { int codepoint = src.codePointAt(index); if (!isEmojiCharacter(codepoint)) { System.err.println("codepoint:" + Integer.toHexString(codepoint)); sb.append((char) codepoint); } index += ((Character.isSupplementaryCodePoint(codepoint)) ? 2 : 1); } return sb.toString(); } public static void main(String[] args) { String aa = "☀☁☔⛄⚡🌀🌁🌂🌃🌄🌅🌆🌇🌈❄⛅🌉🌊🌋🌌🌏🌑🌔🌓🌙🌕🌛🌟🌠🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛⌚⌛⏰⏳♈♉♊♋♌♍♎♏♐♑♒♓⛎🍀🌷🌱🍁🌸🌹🍂🍃🌺🌻🌴🌵🌾🌽🍄🌰🌼🌿🍒🍌🍎🍊🍓🍉🍅🍆🍈🍍🍇🍑🍏👀👂👃👄👅💄💅💆💇💈👤👦👧👨👩👪👫👮👯👰👱👲👳👴👵👶👷👸👹👺👻👼👽👾👿💀💁💂💃🐌🐍🐎🐔🐗🐫🐘🐨🐒🐑🐙🐚🐛🐜🐝🐞🐠🐡🐢🐤🐥🐦🐣🐧🐩🐟🐬🐭🐯🐱🐳🐴🐵🐶🐷🐻🐹🐺🐮🐰🐸🐾🐲🐼🐽😠😩😲😞😵😰😒😍😤😜😝😋😘😚😷😳😃😅😆😁😂😊☺😄😢😭😨😣😡😌😖😔😱😪😏😓😥😫😉😺😸😹😽😻😿😾😼🙀🙅🙆🙇🙈🙊🙉🙋🙌🙍🙎🙏🏠🏡🏢🏣🏥🏦🏧🏨🏩🏪🏫⛪⛲🏬🏯🏰🏭⚓🏮🗻🗼🗽🗾🗿👞👟👠👡👢👣👓👕👖👑👔👒👗👘👙👚👛👜👝💰💱💹💲💳💴💵💸----------🔥🔦🔧🔨🔩🔪🔫🔮🔯🔰🔱💉💊🅰🅱🆎🅾🎀🎁🎂🎄🎅🎌🎆🎈🎉🎍🎎🎓🎒🎏🎇🎐🎃🎊🎋🎑📟☎📞📱📲📝📠✉📨📩📪📫📮📰📢📣📡📤📥📦📧🔠🔡🔢🔣🔤✒💺💻✏📎💼💽💾💿📀✂📍📃📄📅📁📂📓📖📔📕📗📘📙📚📛📜📋📆📊📈📉📇📌📒📏📐📑🎽⚾⛳🎾⚽🎿🏀🏁🏂🏃🏄🏆🏈🏊🚃🚇Ⓜ🚄🚅🚗🚙🚌🚏🚢✈⛵🚉🚀🚤🚕🚚🚒🚑🚓⛽🅿🚥🚧🚨♨⛺🎠🎡🎢🎣🎤🎥🎦🎧🎨🎩🎪🎫🎬🎭🎮🀄🎯🎰🎱🎲🎳🎴🃏🎵🎶🎷🎸🎹🎺🎻🎼〽📷📹📺📻📼💋💌💍💎💏💐💑💒🔞©®™ℹ-----------🔟📶📳📴🍔🍙🍰🍜🍞🍳🍦🍟🍡🍘🍚🍝🍛🍢🍣🍱🍲🍧🍖🍥🍠🍕🍗🍨🍩🍪🍫🍬🍭🍮🍯🍤🍴☕🍸🍺🍵🍶🍷🍻🍹↗↘↖↙⤴⤵↔↕⬆⬇➡⬅▶◀⏩⏪⏫⏬🔺🔻🔼🔽⭕❌❎❗⁉‼❓❔❕〰➰-❤💓💔💕💖💗💘💙💚💛💜💝💞💟♥♠♦♣🚬🚭♿🚩⚠⛔♻🚲🚶🚹🚺🛀🚻🚽🚾🚼🚪🚫✔🆑🆒🆓🆔🆕🆖🆗🆘🆙🆚🈁🈂🈲🈳🈴🈵🈶🈚🈷🈸🈹🈯🈺㊙㊗🉐🉑➕➖✖➗💠💡💢💣💤💥💦💧💨💩💪💫💬✨✴✳⚪⚫🔴🔵🔲🔳⭐⬜⬛▫▪◽◾◻◼🔶🔷🔸🔹❇💮💯↩↪🔃🔊🔋🔌🔍🔎🔒🔓🔏🔐🔑🔔☑🔘🔖🔗🔙🔚🔛🔜🔝✅✊✋✌👊👍☝👆👇👈👉👋👏👌👎👐"; // String aa = "我自从看了这篇文章,恍然大悟😁😂😊,感觉这么多🌑🌔🌓年都白活了,支持嗨老会,多🕓🕔🕕🕖🕗🕘发布些有利我们老年人的文章,年轻生活,从我做起!"; System.out.println("aa:"+aa); long start = 0L; long end = 0L; start = System.currentTimeMillis(); String escape = EmojiCharacterUtil.escape(aa); end = System.currentTimeMillis(); System.out.println((end - start)+" escape:"+escape); start = System.currentTimeMillis(); String reverse = EmojiCharacterUtil.reverse(escape); end = System.currentTimeMillis(); System.out.println((end - start)+" reverse:"+reverse); } }
0
61896_0
package pattern.staticfactory; public class NvWa { public static void main(String[] args) { Human human = null; //白人 human = HumanFactory.createHuman(WhiteHuman.class); human.eat(); human.laugh(); human.run(); //黑人 human = HumanFactory.createHuman(BlackHuman.class); human.eat(); human.laugh(); human.run(); //黄种人 human = HumanFactory.createHuman(YelloHuman.class); human.eat(); human.laugh(); human.run(); System.out.println("============随机生成人类=============================="); for (int i = 0; i < 100; i++) { human = HumanFactory.createHuman(); human.eat(); human.run(); human.laugh(); } } }
898349230/test
src/main/java/pattern/staticfactory/NvWa.java
203
//黄种人
line_comment
zh-cn
package pattern.staticfactory; public class NvWa { public static void main(String[] args) { Human human = null; //白人 human = HumanFactory.createHuman(WhiteHuman.class); human.eat(); human.laugh(); human.run(); //黑人 human = HumanFactory.createHuman(BlackHuman.class); human.eat(); human.laugh(); human.run(); //黄种 <SUF> human = HumanFactory.createHuman(YelloHuman.class); human.eat(); human.laugh(); human.run(); System.out.println("============随机生成人类=============================="); for (int i = 0; i < 100; i++) { human = HumanFactory.createHuman(); human.eat(); human.run(); human.laugh(); } } }
0
58130_3
package cn.wt3.weconds; import android.content.Context; import android.graphics.Color; import android.graphics.PixelFormat; import android.os.Build; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.TextView; import cn.wt3.weconds.R; public class FloatBallView { private Context context; private int height = 0; private int width = 0; private int flag = 1; public static FloatBallView floatView2; private TextView condstext = null; public static FloatBallView getInstance(Context context) { if (floatView2 == null) { floatView2 = new FloatBallView(context); } return floatView2; } public FloatBallView(Context c) { this.context = c; } private WindowManager wm; private View view;// 浮动模块 WindowManager.LayoutParams params; //添加悬浮View public void createFloatView() { if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.floatview, null); } wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); height = wm.getDefaultDisplay().getHeight(); width = wm.getDefaultDisplay().getWidth(); params = new WindowManager.LayoutParams(); params.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;// 所有程序窗口的“基地”窗口,其他应用程序窗口都显示在它上面。 params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; params.format = PixelFormat.TRANSLUCENT;// 不设置这个弹出框的透明遮罩显示为黑色 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; } else { params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; } params.width = WindowManager.LayoutParams.WRAP_CONTENT; params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.gravity = Gravity.TOP | Gravity.LEFT; int screenWidth = context.getResources().getDisplayMetrics().widthPixels; int screenHeight = context.getResources().getDisplayMetrics().heightPixels; params.y = screenHeight - (4 * height) / 5;//设置距离底部高度为屏幕五分之四 params.x = screenWidth; view.setBackgroundColor(Color.TRANSPARENT); view.setVisibility(View.VISIBLE); // 触屏监听移动悬浮框 view.setOnTouchListener(new View.OnTouchListener() { float lastX, lastY; int oldOffsetX, oldOffsetY; int tag = 0;// 悬浮框 所需成员变量 @Override public boolean onTouch(View v, MotionEvent event) { final int action = event.getAction(); float x = event.getX(); float y = event.getY(); if (tag == 0) { oldOffsetX = params.x; // 偏移量 oldOffsetY = params.y; // 偏移量 } if (action == MotionEvent.ACTION_DOWN) { lastX = x; lastY = y; } else if (action == MotionEvent.ACTION_MOVE) { params.x += (int) (x - lastX) / 3; // 减小偏移量,防止过度抖动 params.y += (int) (y - lastY) / 3; // 减小偏移量,防止过度抖动 tag = 1; wm.updateViewLayout(view, params); } else if (action == MotionEvent.ACTION_UP) { int newOffsetX = params.x; int newOffsetY = params.y; // 只要按钮一动位置不是很大,就认为是点击事件 if (Math.abs(oldOffsetX - newOffsetX) <= 20 && Math.abs(oldOffsetY - newOffsetY) <= 20) { if (l != null) { l.onClick(view); } } else { if (params.x < width / 2) { params.x = 0; } else { params.x = width; } wm.updateViewLayout(view, params); tag = 0; } } return true; } }); try { //将控件view和布局参数params加入到windowmanager wm.addView(view, params); } catch (Exception e) { System.out.println("addView失败"); } } //点击浮动按钮触发事件,需要override该方法 private View.OnClickListener l; public void onFloatViewClick(View.OnClickListener l) { this.l = l; } //将悬浮View从WindowManager中移除,需要与createFloatView()成对出现 public void removeFloatView() { if (wm != null && view != null) { wm.removeViewImmediate(view); view = null; wm = null; } } //秒数框数据更新方法 public void updata(String ss) { if (wm != null && view != null && view.isShown()) { condstext = (TextView) view.findViewById(R.id.condstext); condstext.setText(ss); } } public boolean isopfl() { if (wm != null && view != null && view.isShown()) { return true; } else { return false; } } //设置浮窗大小尺寸方法 public void setsize(float fontsize, int width, int height) { //获取TextView对应的LayoutParams ViewGroup.LayoutParams layoutParams = condstext.getLayoutParams(); if (layoutParams != null) { final float scale = context.getResources().getDisplayMetrics().density; //设置字体大小 condstext.setTextSize(fontsize); //设置数字在框内居中 condstext.setGravity(Gravity.CENTER); //设置宽度 layoutParams.width = (int) (width * scale + 0.5f); //设置高度 layoutParams.height = (int) (height * scale + 0.5f); condstext.setLayoutParams(layoutParams); } } //设置浮框不可触摸方法 public boolean notouch() { if (wm != null && view != null) { params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; wm.updateViewLayout(view, params); return true; } else { return false; } } //恢复浮框可触摸方法 public boolean retouch() { if (wm != null && view != null) { params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; wm.updateViewLayout(view, params); return true; } else { return false; } } }
8mv/Weconds
app/src/main/java/cn/wt3/weconds/FloatBallView.java
1,688
// 不设置这个弹出框的透明遮罩显示为黑色
line_comment
zh-cn
package cn.wt3.weconds; import android.content.Context; import android.graphics.Color; import android.graphics.PixelFormat; import android.os.Build; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.TextView; import cn.wt3.weconds.R; public class FloatBallView { private Context context; private int height = 0; private int width = 0; private int flag = 1; public static FloatBallView floatView2; private TextView condstext = null; public static FloatBallView getInstance(Context context) { if (floatView2 == null) { floatView2 = new FloatBallView(context); } return floatView2; } public FloatBallView(Context c) { this.context = c; } private WindowManager wm; private View view;// 浮动模块 WindowManager.LayoutParams params; //添加悬浮View public void createFloatView() { if (view == null) { view = LayoutInflater.from(context).inflate(R.layout.floatview, null); } wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); height = wm.getDefaultDisplay().getHeight(); width = wm.getDefaultDisplay().getWidth(); params = new WindowManager.LayoutParams(); params.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;// 所有程序窗口的“基地”窗口,其他应用程序窗口都显示在它上面。 params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; params.format = PixelFormat.TRANSLUCENT;// 不设 <SUF> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; } else { params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; } params.width = WindowManager.LayoutParams.WRAP_CONTENT; params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.gravity = Gravity.TOP | Gravity.LEFT; int screenWidth = context.getResources().getDisplayMetrics().widthPixels; int screenHeight = context.getResources().getDisplayMetrics().heightPixels; params.y = screenHeight - (4 * height) / 5;//设置距离底部高度为屏幕五分之四 params.x = screenWidth; view.setBackgroundColor(Color.TRANSPARENT); view.setVisibility(View.VISIBLE); // 触屏监听移动悬浮框 view.setOnTouchListener(new View.OnTouchListener() { float lastX, lastY; int oldOffsetX, oldOffsetY; int tag = 0;// 悬浮框 所需成员变量 @Override public boolean onTouch(View v, MotionEvent event) { final int action = event.getAction(); float x = event.getX(); float y = event.getY(); if (tag == 0) { oldOffsetX = params.x; // 偏移量 oldOffsetY = params.y; // 偏移量 } if (action == MotionEvent.ACTION_DOWN) { lastX = x; lastY = y; } else if (action == MotionEvent.ACTION_MOVE) { params.x += (int) (x - lastX) / 3; // 减小偏移量,防止过度抖动 params.y += (int) (y - lastY) / 3; // 减小偏移量,防止过度抖动 tag = 1; wm.updateViewLayout(view, params); } else if (action == MotionEvent.ACTION_UP) { int newOffsetX = params.x; int newOffsetY = params.y; // 只要按钮一动位置不是很大,就认为是点击事件 if (Math.abs(oldOffsetX - newOffsetX) <= 20 && Math.abs(oldOffsetY - newOffsetY) <= 20) { if (l != null) { l.onClick(view); } } else { if (params.x < width / 2) { params.x = 0; } else { params.x = width; } wm.updateViewLayout(view, params); tag = 0; } } return true; } }); try { //将控件view和布局参数params加入到windowmanager wm.addView(view, params); } catch (Exception e) { System.out.println("addView失败"); } } //点击浮动按钮触发事件,需要override该方法 private View.OnClickListener l; public void onFloatViewClick(View.OnClickListener l) { this.l = l; } //将悬浮View从WindowManager中移除,需要与createFloatView()成对出现 public void removeFloatView() { if (wm != null && view != null) { wm.removeViewImmediate(view); view = null; wm = null; } } //秒数框数据更新方法 public void updata(String ss) { if (wm != null && view != null && view.isShown()) { condstext = (TextView) view.findViewById(R.id.condstext); condstext.setText(ss); } } public boolean isopfl() { if (wm != null && view != null && view.isShown()) { return true; } else { return false; } } //设置浮窗大小尺寸方法 public void setsize(float fontsize, int width, int height) { //获取TextView对应的LayoutParams ViewGroup.LayoutParams layoutParams = condstext.getLayoutParams(); if (layoutParams != null) { final float scale = context.getResources().getDisplayMetrics().density; //设置字体大小 condstext.setTextSize(fontsize); //设置数字在框内居中 condstext.setGravity(Gravity.CENTER); //设置宽度 layoutParams.width = (int) (width * scale + 0.5f); //设置高度 layoutParams.height = (int) (height * scale + 0.5f); condstext.setLayoutParams(layoutParams); } } //设置浮框不可触摸方法 public boolean notouch() { if (wm != null && view != null) { params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; wm.updateViewLayout(view, params); return true; } else { return false; } } //恢复浮框可触摸方法 public boolean retouch() { if (wm != null && view != null) { params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; wm.updateViewLayout(view, params); return true; } else { return false; } } }
0
37232_2
package pachong; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { static String SendGet(String url){ String result = null;//定义一个字符串来存储网页内容 BufferedReader in = null ;//空 try{ URL realUrl = new URL(url); URLConnection connection =realUrl.openConnection();//返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。 connection.connect();// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。 in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gbk"));//字节流转化为字符流通过缓冲流读操作 String line; while((line=in.readLine())!=null){ result +=line+"\r\n"; System.out.println(result); } }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(in !=null){ in.close(); } }catch(Exception e2){ e2.printStackTrace(); } } return result; } public static Map<String, String> transStringToMap(String mapString){ String [] str; Map<String, String> map = new HashMap<String, String>(); String pattern = "\\d{4}-\\d{1,2}-\\d{1,2}[,]\\d{2}[:]\\d{2}[:]\\d{2}[,]\\d{2}[:]\\d{2}[:]\\d{2}[,][\\u4E00-\\u9FA5]+"; Pattern r = Pattern.compile(pattern);//将给定的正则表达式编译到模式中。 Matcher m = r.matcher(mapString);// 创建匹配给定输入与此模式的匹配器 while(m.find()){// 尝试查找与该模式匹配的输入序列的下一个子序列 // m.find(); str=m.group().split(",");//m.group:返回由以前匹配操作所匹配的输入子序列.split:根据给定正则表达式的匹配拆分此字符串,返回值为数组 map.put(str[0], str[3]); } return map; } public static void main(String[] args) { String url = "http://hq.sinajs.cn/?list=market_stock_sh"; SendGet(url); Map<String,String> map= transStringToMap(SendGet(url)); for (String key : map.keySet()) { System.out.println("key= " + key + " and value= " + map.get(key)); } } }
905251926/PaChong01
Main.java
724
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
line_comment
zh-cn
package pachong; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { static String SendGet(String url){ String result = null;//定义一个字符串来存储网页内容 BufferedReader in = null ;//空 try{ URL realUrl = new URL(url); URLConnection connection =realUrl.openConnection();//返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。 connection.connect();// 打开 <SUF> in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gbk"));//字节流转化为字符流通过缓冲流读操作 String line; while((line=in.readLine())!=null){ result +=line+"\r\n"; System.out.println(result); } }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(in !=null){ in.close(); } }catch(Exception e2){ e2.printStackTrace(); } } return result; } public static Map<String, String> transStringToMap(String mapString){ String [] str; Map<String, String> map = new HashMap<String, String>(); String pattern = "\\d{4}-\\d{1,2}-\\d{1,2}[,]\\d{2}[:]\\d{2}[:]\\d{2}[,]\\d{2}[:]\\d{2}[:]\\d{2}[,][\\u4E00-\\u9FA5]+"; Pattern r = Pattern.compile(pattern);//将给定的正则表达式编译到模式中。 Matcher m = r.matcher(mapString);// 创建匹配给定输入与此模式的匹配器 while(m.find()){// 尝试查找与该模式匹配的输入序列的下一个子序列 // m.find(); str=m.group().split(",");//m.group:返回由以前匹配操作所匹配的输入子序列.split:根据给定正则表达式的匹配拆分此字符串,返回值为数组 map.put(str[0], str[3]); } return map; } public static void main(String[] args) { String url = "http://hq.sinajs.cn/?list=market_stock_sh"; SendGet(url); Map<String,String> map= transStringToMap(SendGet(url)); for (String key : map.keySet()) { System.out.println("key= " + key + " and value= " + map.get(key)); } } }
0
17046_0
package pattern.adapter; // 适配器类 //适配器Adapter继承自Adaptee,同时又实现了目标(Target)接口。 public class Adapter extends Adaptee implements Target { //所以适配器只是将SpecificRequest()方法作了一层封装,封装成Target可以调用的Request()而已 @Override public void Request() { this.SpecificRequest(); } }
925781609/pattern
src/main/java/pattern/adapter/Adapter.java
92
// 适配器类
line_comment
zh-cn
package pattern.adapter; // 适配 <SUF> //适配器Adapter继承自Adaptee,同时又实现了目标(Target)接口。 public class Adapter extends Adaptee implements Target { //所以适配器只是将SpecificRequest()方法作了一层封装,封装成Target可以调用的Request()而已 @Override public void Request() { this.SpecificRequest(); } }
0
20689_12
import java.io.*; import java.util.Scanner; public class Studynote80_StandardStream { } /* 流的类型:只要记住大体分为 输入流和输出流,根据流的类型分类:字节流和字符流,根据流的传输类型:节点流,处理流,对象流,标准输入/输出流,转换流 标准流 类型 默认设备 System.in标准输入 InputStream 键盘 System.out标准输出 PrintStream 显示器 打印流(只有输出流,没有输入流):PrintStream字节流和PrintWriter字符流 */ class InputAndOutput { public static void main(String[] args) { //System 类 的 public final static InputStream in = null; // System.in 编译类型 InputStream // System.in 运行类型 BufferedInputStream // 表示的是标准输入 键盘 System.out.println(System.in.getClass()); //1. System.out public final static PrintStream out = null; //2. 编译类型 PrintStream //3. 运行类型 PrintStream //4. 表示标准输出 显示器 System.out.println(System.out.getClass()); System.out.println("System.out 方法将数据输出到显示器"); Scanner scanner = new Scanner(System.in); System.out.println("传统的方法,Scanner是从标准输入System.in 获取键盘数据"); String next = scanner.next(); System.out.println("scanner获取到的 next=" + next); } } //演示PrintStream (字节打印流/输出流) class PrintStream_ { public static void main(String[] args) throws IOException { PrintStream out = System.out; //System.out是System类的静态属性,指向PrintStream类的对象。在底层其实被赋值了;final对类的要求是地址不能变,里面的值可以更改 // initializeSystemClass()方法里可以看到,只是赋值具体过程调用的native本地方法,即C++方法无法获取 //在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器 /*源码 public void print(String s) { if (s == null) { s = "null"; } write(s); } */ out.print("john, hello"); //这里out.print 和 out.write 调用的 write 方法不一样,out.print 方法调用的write 是被private修饰的, // 而这里直接调用的write是public,因此调用write进行打印/输出时需要转为byte[]数组传入 //打印Sting时,底层调用的是BufferedWriter的wirte(Sting)方法,但是这个方法是私有的 out.write("约翰,你好".getBytes()); out.close(); //我们可以去修改打印流输出的位置/设备 //1. 输出修改成到 "e:\\f1.txt" //2. "伊万,你好" 就会输出到 e:\f1.txt //3. public static void setOut(PrintStream out) { // checkIO(); // setOut0(out); // native 方法,修改了out // } System.setOut(new PrintStream("e:\\f1.txt"));//构造器中传入文件位置 System.out.println("伊万,你好"); //要改回来就再次调用那个setOut()方法,把上面的out传进去,因为上面那个out对象是输出到控制台 } } class PrintWriter_ { public static void main(String[] args) throws IOException { //可以指定打印位置 //PrintWriter printWriter = new PrintWriter(System.out); PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt")); printWriter.print("hi, 北京你好~~~~"); //flush + 关闭流, 才会将数据写入到文件.. //不只是输出到文件,就算是打印到控制台也是要 flush 刷新一下 printWriter.close(); } } /*转换流InputStreamReader和OutputStreamWriter:将字节流转换为字符流 单用字符流,他默认使用的是我们之前ide设置的(默认UTF-8),不能指定,只能改文件或ide。转换流可以指定更灵活 >介绍 1.InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流) 2.OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流) 3.当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流 4.可以在使用时指定编码格式(比如utf-8,gbk,gb2312,IS08859-1等) 编码转换: 构造器InputStreamReader(InputStream,Charset)传入字节流、编码方式两种参数, 构造器OutputStreamReader(OutputStream,Charset)传入字节流、编码方式两种参数, */ //演示使用转换流解决中文乱码问题:编程将字节流 FileInputStream 包装成(转换成)字符流 InputStreamReader // 对文件进行读取(按照utf-8/gbk格式),进而包装成BufferedReader class InputStreamReader_ { public static void main(String[] args) throws IOException { //读取gbk格式的文件 String filePath = "e:\\a.txt"; //解读 //1. 把 FileInputStream 转成 InputStreamReader //2. 指定编码 gbk //InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk"); //3. 把 InputStreamReader 传入 BufferedReader //BufferedReader br = new BufferedReader(isr); //将2 和 3 合在一起 BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(filePath), "gbk")); //4. 读取 String s = br.readLine(); System.out.println("读取内容=" + s); //5. 关闭外层流 br.close(); } } //演示 OutputStreamWriter 使用:把FileOutputStream 字节流,转成字符流 OutputStreamWriter // 指定输出的编码 utf-8/utf8 class OutputStreamWriter_ { public static void main(String[] args) throws IOException { String filePath = "e:\\hsp.txt"; String charSet = "utf-8";//如果要输出的字符没有中文,最终也可能显示为别的格式 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet); osw.write("按照 " + charSet + " 格式输出字符"); osw.close(); System.out.println("按照 " + charSet + " 保存文件成功~"); } }
92rw/Java-Study-Notes
JavaNote/Studynote80_StandardStream.java
1,563
//在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
line_comment
zh-cn
import java.io.*; import java.util.Scanner; public class Studynote80_StandardStream { } /* 流的类型:只要记住大体分为 输入流和输出流,根据流的类型分类:字节流和字符流,根据流的传输类型:节点流,处理流,对象流,标准输入/输出流,转换流 标准流 类型 默认设备 System.in标准输入 InputStream 键盘 System.out标准输出 PrintStream 显示器 打印流(只有输出流,没有输入流):PrintStream字节流和PrintWriter字符流 */ class InputAndOutput { public static void main(String[] args) { //System 类 的 public final static InputStream in = null; // System.in 编译类型 InputStream // System.in 运行类型 BufferedInputStream // 表示的是标准输入 键盘 System.out.println(System.in.getClass()); //1. System.out public final static PrintStream out = null; //2. 编译类型 PrintStream //3. 运行类型 PrintStream //4. 表示标准输出 显示器 System.out.println(System.out.getClass()); System.out.println("System.out 方法将数据输出到显示器"); Scanner scanner = new Scanner(System.in); System.out.println("传统的方法,Scanner是从标准输入System.in 获取键盘数据"); String next = scanner.next(); System.out.println("scanner获取到的 next=" + next); } } //演示PrintStream (字节打印流/输出流) class PrintStream_ { public static void main(String[] args) throws IOException { PrintStream out = System.out; //System.out是System类的静态属性,指向PrintStream类的对象。在底层其实被赋值了;final对类的要求是地址不能变,里面的值可以更改 // initializeSystemClass()方法里可以看到,只是赋值具体过程调用的native本地方法,即C++方法无法获取 //在默 <SUF> /*源码 public void print(String s) { if (s == null) { s = "null"; } write(s); } */ out.print("john, hello"); //这里out.print 和 out.write 调用的 write 方法不一样,out.print 方法调用的write 是被private修饰的, // 而这里直接调用的write是public,因此调用write进行打印/输出时需要转为byte[]数组传入 //打印Sting时,底层调用的是BufferedWriter的wirte(Sting)方法,但是这个方法是私有的 out.write("约翰,你好".getBytes()); out.close(); //我们可以去修改打印流输出的位置/设备 //1. 输出修改成到 "e:\\f1.txt" //2. "伊万,你好" 就会输出到 e:\f1.txt //3. public static void setOut(PrintStream out) { // checkIO(); // setOut0(out); // native 方法,修改了out // } System.setOut(new PrintStream("e:\\f1.txt"));//构造器中传入文件位置 System.out.println("伊万,你好"); //要改回来就再次调用那个setOut()方法,把上面的out传进去,因为上面那个out对象是输出到控制台 } } class PrintWriter_ { public static void main(String[] args) throws IOException { //可以指定打印位置 //PrintWriter printWriter = new PrintWriter(System.out); PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt")); printWriter.print("hi, 北京你好~~~~"); //flush + 关闭流, 才会将数据写入到文件.. //不只是输出到文件,就算是打印到控制台也是要 flush 刷新一下 printWriter.close(); } } /*转换流InputStreamReader和OutputStreamWriter:将字节流转换为字符流 单用字符流,他默认使用的是我们之前ide设置的(默认UTF-8),不能指定,只能改文件或ide。转换流可以指定更灵活 >介绍 1.InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流) 2.OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流) 3.当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流 4.可以在使用时指定编码格式(比如utf-8,gbk,gb2312,IS08859-1等) 编码转换: 构造器InputStreamReader(InputStream,Charset)传入字节流、编码方式两种参数, 构造器OutputStreamReader(OutputStream,Charset)传入字节流、编码方式两种参数, */ //演示使用转换流解决中文乱码问题:编程将字节流 FileInputStream 包装成(转换成)字符流 InputStreamReader // 对文件进行读取(按照utf-8/gbk格式),进而包装成BufferedReader class InputStreamReader_ { public static void main(String[] args) throws IOException { //读取gbk格式的文件 String filePath = "e:\\a.txt"; //解读 //1. 把 FileInputStream 转成 InputStreamReader //2. 指定编码 gbk //InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk"); //3. 把 InputStreamReader 传入 BufferedReader //BufferedReader br = new BufferedReader(isr); //将2 和 3 合在一起 BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(filePath), "gbk")); //4. 读取 String s = br.readLine(); System.out.println("读取内容=" + s); //5. 关闭外层流 br.close(); } } //演示 OutputStreamWriter 使用:把FileOutputStream 字节流,转成字符流 OutputStreamWriter // 指定输出的编码 utf-8/utf8 class OutputStreamWriter_ { public static void main(String[] args) throws IOException { String filePath = "e:\\hsp.txt"; String charSet = "utf-8";//如果要输出的字符没有中文,最终也可能显示为别的格式 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet); osw.write("按照 " + charSet + " 格式输出字符"); osw.close(); System.out.println("按照 " + charSet + " 保存文件成功~"); } }
0
55115_12
/* * @Author: your name * @Date: 2022-02-15 13:58:56 * @LastEditTime: 2022-02-16 10:05:09 * @LastEditors: Please set LastEditors * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @FilePath: /Blog/img/java/testCode/DobleTest.java */ // public class DoubleTest { // public static void main (String[] args) { // // 1.声明一个boolean类型的变量并初始化 // boolean b1 = true; // // 2.打印变量的数值 // System. out .println("b1 = " + b1); // b1 = true // // 3.修改变量b1的数值=赋值运算符,用于将=右边的数据赋值给=左边的变量,覆盖变量中原来的数值 // b1 = false; // System. out .println("b1 = " + b1); // b1 = false // bl = 1; // 错误:不兼容的类型: int无法转换为boolean // } // } /** * 编程实现字符类型的使用 */ public class DoubleTest { public static void main (String[] args) { // 1.声明一个char类型的变量 并初始化 char c1 = 'a'; // char类型 使用 单引号 引起来 // 2.打印变量的数值 System.out.println("c1 = " + c1); // c1 = a System.out.println("对应的编号是:" + (int)c1 ); // 表示将 char类型 的c1 强制转换为 inta类型 并打印 97 // 1.声明一个char类型的变量 并初始化 char c2 = 98; // 2.打印变量的数值 System.out.println("c2 = " + c2); // c2 = b System.out.println("对应的编号是:" + (int)c2 ); // 98 char c3 = '\u5947'; char c4 = '\u70b9'; System.out.println("最终的结果是: " + c3 + c4); // 奇点 } }
946629031/Blog
img/java/testCode/DoubleTest.java
588
// 1.声明一个char类型的变量 并初始化
line_comment
zh-cn
/* * @Author: your name * @Date: 2022-02-15 13:58:56 * @LastEditTime: 2022-02-16 10:05:09 * @LastEditors: Please set LastEditors * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @FilePath: /Blog/img/java/testCode/DobleTest.java */ // public class DoubleTest { // public static void main (String[] args) { // // 1.声明一个boolean类型的变量并初始化 // boolean b1 = true; // // 2.打印变量的数值 // System. out .println("b1 = " + b1); // b1 = true // // 3.修改变量b1的数值=赋值运算符,用于将=右边的数据赋值给=左边的变量,覆盖变量中原来的数值 // b1 = false; // System. out .println("b1 = " + b1); // b1 = false // bl = 1; // 错误:不兼容的类型: int无法转换为boolean // } // } /** * 编程实现字符类型的使用 */ public class DoubleTest { public static void main (String[] args) { // 1. <SUF> char c1 = 'a'; // char类型 使用 单引号 引起来 // 2.打印变量的数值 System.out.println("c1 = " + c1); // c1 = a System.out.println("对应的编号是:" + (int)c1 ); // 表示将 char类型 的c1 强制转换为 inta类型 并打印 97 // 1.声明一个char类型的变量 并初始化 char c2 = 98; // 2.打印变量的数值 System.out.println("c2 = " + c2); // c2 = b System.out.println("对应的编号是:" + (int)c2 ); // 98 char c3 = '\u5947'; char c4 = '\u70b9'; System.out.println("最终的结果是: " + c3 + c4); // 奇点 } }
0
53312_16
package com.xk.customview.custom.recyclerview; import android.content.Context; import android.support.annotation.IdRes; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import com.xk.customview.R; import java.util.ArrayList; import java.util.List; /** * 大致实现了一个可以向上滚动,回收上面item,添加下面item的功能。不借助scrollBy方法的实现。着重理解原理 * Created by xuekai on 2019/4/6. */ public class RecyclerView extends ViewGroup { @IdRes private final int TAG_TYPE = 1; /** * 内容的偏移量,比如内容的头部距离view的顶部一段距离了,那段距离就是scrollY */ int scrollY; private Adapter adapter; //当前显示的view private List<View> viewList; //行数 private int rowCount; //初始化??? private boolean needRelayout; //recyclerview的宽度 private int width; //recyclerview的高度 private int height; //孩子们的高度 private int[] heights; //回收池 private Recycler recycler; //第一个显示的item的position,该变量用来记录第一个显示的item的position。在onLayout的时候,从这个position开始向后布局 private int firstVisiablePosition = 0; //手指按下的Y private float downY; //上一次事件的Y private float lastY; private int scaledTouchSlop; public RecyclerView(Context context) { this(context, null); } public RecyclerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RecyclerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setAdapter(Adapter adapter) { this.adapter = adapter; init(); requestLayout(); } private void init() { ViewConfiguration vc = ViewConfiguration.get(getContext()); scaledTouchSlop = vc.getScaledTouchSlop(); needRelayout = true; viewList = new ArrayList<>(); if (adapter != null) { recycler = new Recycler(adapter.getViewTypeCount()); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (adapter != null && needRelayout) { needRelayout = false; viewList.clear(); removeAllViews(); //正在摆放的孩子的top。 // TODO: by xk 2019/4/6 18:41 如果只是第一次初始化,top为0,但是如果实在刷新的话,可能第一个显示的孩子的top并不一定是0 int top = 0; if (adapter != null) { width = r - l; height = b - t; // TODO: by xk 2019/4/6 18:43 为啥从0开始,应该是从firstVisiableView开始 //开始循环摆放子控件,但是不是从0开始摆所有,而是只摆放边界之内的。通过top<=height来判断 for (int i = 0; i < adapter.getCount() && top <= height; i++) { makeAndStepView(0, top, r, top + heights[i], i); top += heights[i]; } } } } /** * 创建、获取并且安装一个子View */ private void makeAndStepView(int l, int t, int r, int b, int position) { View view = obtainView(position); //测量孩子。说实话,我们下面layout的时候,位置父亲已经制定好了,不需要测量了。毕竟测量出来的数字也就是为了layout使用。但是最好还是测量一下,毕竟子view自定义控件里面或许自己需要。 view.measure(MeasureSpec.makeMeasureSpec(r - l, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(b - t, MeasureSpec.EXACTLY)); view.layout(l, t, r, b); } private View obtainView(int position) { //通过回收池拿到了一个View,可能为空。然后让adapter去处理。如果是空的,getView中创建。如果不为空,getView设置一下数据直接给返回。 View convertView = recycler.getViewByItemType(adapter.getItemType(position)); View view = adapter.getView(position, convertView, this); if (view == null) { throw new RuntimeException("getView返回的view为空了"); } //???为啥要给第一个添加 viewList.add(view); view.setTag(R.id.tag_type, adapter.getItemType(position)); addView(view); return view; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int heightSize = MeasureSpec.getSize(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int tempH = 0; //把所有孩子的高度遍历放到heights集合中。同时,计算出recyclerview的高度。 if (adapter != null) { heights = new int[adapter.getCount()]; for (int i = 0; i < adapter.getCount(); i++) { heights[i] = adapter.getHeight(); tempH += heights[i]; } } //上一步计算的高度和控件父亲约束的高度取最小值 int minHeight = Math.min(heightSize, tempH); setMeasuredDimension(widthSize, minHeight); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: lastY = downY = ev.getY(); Log.i("RecyclerView", "onInterceptTouchEvent-->down"); break; case MotionEvent.ACTION_MOVE: float diffY = downY - ev.getY(); if (Math.abs(diffY) > Math.abs(scaledTouchSlop)) { Log.i("RecyclerView", "onInterceptTouchEvent-->move"); //拦截 return true; } break; default: break; } return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { Log.i("RecyclerView", "onTouchEvent" + event.getAction()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: int diffY = (int) (lastY - event.getY()); lastY = event.getY(); scrollBy(0, diffY); break; default: break; } return super.onTouchEvent(event); } @Override public void scrollBy(int x, int y) { scrollY += y; //添加孩子、删除孩子 View firstVisiableView = viewList.get(0); if (y > 0) { if (-firstVisiableView.getTop() > adapter.getHeight()) { //这个被划出去了 removeTopView(firstVisiableView); } if (needAddBottom(y)) { addBottomView(); } } firstTop = viewList.get(0).getTop() - y; reLayoutChild(); } private void addBottomView() { int lastPosition = firstVisiablePosition + viewList.size(); View view = obtainView(lastPosition); //测量孩子。说实话,我们下面layout的时候,位置父亲已经制定好了,不需要测量了。毕竟测量出来的数字也就是为了layout使用。但是最好还是测量一下,毕竟子view自定义控件里面或许自己需要。 view.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(adapter.getHeight(), MeasureSpec.EXACTLY)); } private boolean needAddBottom(int y) { int firstTop = viewList.get(0).getTop() - y; int height = 0; for (View view : viewList) { height += view.getHeight(); } //屏幕展示的内容的高度 int showHeight = height - firstTop; return showHeight < getHeight(); } private void removeTopView(View view) { removeView(view); viewList.remove(0); firstVisiablePosition++; recycler.saveView(view, (Integer) view.getTag(R.id.tag_type)); } int firstTop = 0; private void reLayoutChild() { int top = firstTop; for (View view : viewList) { view.layout(0, top, width, adapter.getHeight() + top); top += adapter.getHeight(); } } @Override public void removeView(View view) { super.removeView(view); } }
94kai/Learning-CustomView
app/src/main/java/com/xk/customview/custom/recyclerview/RecyclerView.java
2,129
//测量孩子。说实话,我们下面layout的时候,位置父亲已经制定好了,不需要测量了。毕竟测量出来的数字也就是为了layout使用。但是最好还是测量一下,毕竟子view自定义控件里面或许自己需要。
line_comment
zh-cn
package com.xk.customview.custom.recyclerview; import android.content.Context; import android.support.annotation.IdRes; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import com.xk.customview.R; import java.util.ArrayList; import java.util.List; /** * 大致实现了一个可以向上滚动,回收上面item,添加下面item的功能。不借助scrollBy方法的实现。着重理解原理 * Created by xuekai on 2019/4/6. */ public class RecyclerView extends ViewGroup { @IdRes private final int TAG_TYPE = 1; /** * 内容的偏移量,比如内容的头部距离view的顶部一段距离了,那段距离就是scrollY */ int scrollY; private Adapter adapter; //当前显示的view private List<View> viewList; //行数 private int rowCount; //初始化??? private boolean needRelayout; //recyclerview的宽度 private int width; //recyclerview的高度 private int height; //孩子们的高度 private int[] heights; //回收池 private Recycler recycler; //第一个显示的item的position,该变量用来记录第一个显示的item的position。在onLayout的时候,从这个position开始向后布局 private int firstVisiablePosition = 0; //手指按下的Y private float downY; //上一次事件的Y private float lastY; private int scaledTouchSlop; public RecyclerView(Context context) { this(context, null); } public RecyclerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RecyclerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setAdapter(Adapter adapter) { this.adapter = adapter; init(); requestLayout(); } private void init() { ViewConfiguration vc = ViewConfiguration.get(getContext()); scaledTouchSlop = vc.getScaledTouchSlop(); needRelayout = true; viewList = new ArrayList<>(); if (adapter != null) { recycler = new Recycler(adapter.getViewTypeCount()); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (adapter != null && needRelayout) { needRelayout = false; viewList.clear(); removeAllViews(); //正在摆放的孩子的top。 // TODO: by xk 2019/4/6 18:41 如果只是第一次初始化,top为0,但是如果实在刷新的话,可能第一个显示的孩子的top并不一定是0 int top = 0; if (adapter != null) { width = r - l; height = b - t; // TODO: by xk 2019/4/6 18:43 为啥从0开始,应该是从firstVisiableView开始 //开始循环摆放子控件,但是不是从0开始摆所有,而是只摆放边界之内的。通过top<=height来判断 for (int i = 0; i < adapter.getCount() && top <= height; i++) { makeAndStepView(0, top, r, top + heights[i], i); top += heights[i]; } } } } /** * 创建、获取并且安装一个子View */ private void makeAndStepView(int l, int t, int r, int b, int position) { View view = obtainView(position); //测量 <SUF> view.measure(MeasureSpec.makeMeasureSpec(r - l, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(b - t, MeasureSpec.EXACTLY)); view.layout(l, t, r, b); } private View obtainView(int position) { //通过回收池拿到了一个View,可能为空。然后让adapter去处理。如果是空的,getView中创建。如果不为空,getView设置一下数据直接给返回。 View convertView = recycler.getViewByItemType(adapter.getItemType(position)); View view = adapter.getView(position, convertView, this); if (view == null) { throw new RuntimeException("getView返回的view为空了"); } //???为啥要给第一个添加 viewList.add(view); view.setTag(R.id.tag_type, adapter.getItemType(position)); addView(view); return view; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int heightSize = MeasureSpec.getSize(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int tempH = 0; //把所有孩子的高度遍历放到heights集合中。同时,计算出recyclerview的高度。 if (adapter != null) { heights = new int[adapter.getCount()]; for (int i = 0; i < adapter.getCount(); i++) { heights[i] = adapter.getHeight(); tempH += heights[i]; } } //上一步计算的高度和控件父亲约束的高度取最小值 int minHeight = Math.min(heightSize, tempH); setMeasuredDimension(widthSize, minHeight); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: lastY = downY = ev.getY(); Log.i("RecyclerView", "onInterceptTouchEvent-->down"); break; case MotionEvent.ACTION_MOVE: float diffY = downY - ev.getY(); if (Math.abs(diffY) > Math.abs(scaledTouchSlop)) { Log.i("RecyclerView", "onInterceptTouchEvent-->move"); //拦截 return true; } break; default: break; } return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { Log.i("RecyclerView", "onTouchEvent" + event.getAction()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: int diffY = (int) (lastY - event.getY()); lastY = event.getY(); scrollBy(0, diffY); break; default: break; } return super.onTouchEvent(event); } @Override public void scrollBy(int x, int y) { scrollY += y; //添加孩子、删除孩子 View firstVisiableView = viewList.get(0); if (y > 0) { if (-firstVisiableView.getTop() > adapter.getHeight()) { //这个被划出去了 removeTopView(firstVisiableView); } if (needAddBottom(y)) { addBottomView(); } } firstTop = viewList.get(0).getTop() - y; reLayoutChild(); } private void addBottomView() { int lastPosition = firstVisiablePosition + viewList.size(); View view = obtainView(lastPosition); //测量孩子。说实话,我们下面layout的时候,位置父亲已经制定好了,不需要测量了。毕竟测量出来的数字也就是为了layout使用。但是最好还是测量一下,毕竟子view自定义控件里面或许自己需要。 view.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(adapter.getHeight(), MeasureSpec.EXACTLY)); } private boolean needAddBottom(int y) { int firstTop = viewList.get(0).getTop() - y; int height = 0; for (View view : viewList) { height += view.getHeight(); } //屏幕展示的内容的高度 int showHeight = height - firstTop; return showHeight < getHeight(); } private void removeTopView(View view) { removeView(view); viewList.remove(0); firstVisiablePosition++; recycler.saveView(view, (Integer) view.getTag(R.id.tag_type)); } int firstTop = 0; private void reLayoutChild() { int top = firstTop; for (View view : viewList) { view.layout(0, top, width, adapter.getHeight() + top); top += adapter.getHeight(); } } @Override public void removeView(View view) { super.removeView(view); } }
0
16341_1
package entity; import java.io.Serializable; public class Article implements Serializable { /** * */ private static final long serialVersionUID = 1L; //文章表 private int id; private String title; //标题 private String content; //正文 private String lead; //导语 private String create_user;//创建人 private String create_time;//创建时间 private String type; //文章类型---技术交流1,我的困惑2,谈谈生活3,情感交流4 private String isdelete; //是否删除0不删除,1删除 private String top; //是否置顶0不置顶,1置顶 private int see; //访问量 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getLead() { return lead; } public void setLead(String lead) { this.lead = lead; } public String getCreate_user() { return create_user; } public void setCreate_user(String create_user) { this.create_user = create_user; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getIsdelete() { return isdelete; } public void setIsdelete(String isdelete) { this.isdelete = isdelete; } public String getTop() { return top; } public void setTop(String top) { this.top = top; } public int getSee() { return see; } public void setSee(int see) { this.see = see; } }
970263611/boke
component/api/src/main/java/entity/Article.java
588
//创建人
line_comment
zh-cn
package entity; import java.io.Serializable; public class Article implements Serializable { /** * */ private static final long serialVersionUID = 1L; //文章表 private int id; private String title; //标题 private String content; //正文 private String lead; //导语 private String create_user;//创建 <SUF> private String create_time;//创建时间 private String type; //文章类型---技术交流1,我的困惑2,谈谈生活3,情感交流4 private String isdelete; //是否删除0不删除,1删除 private String top; //是否置顶0不置顶,1置顶 private int see; //访问量 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getLead() { return lead; } public void setLead(String lead) { this.lead = lead; } public String getCreate_user() { return create_user; } public void setCreate_user(String create_user) { this.create_user = create_user; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getIsdelete() { return isdelete; } public void setIsdelete(String isdelete) { this.isdelete = isdelete; } public String getTop() { return top; } public void setTop(String top) { this.top = top; } public int getSee() { return see; } public void setSee(int see) { this.see = see; } }
0
26397_2
package appupdate.bitpai.comz.testz; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class LoadView extends View { //背景颜色,圆环,字 int color_bg,color_circle,color_tv; //背景圆半径,字,圆环宽度,加载时间 int size_cicle,size_tv,size_circle_width,size_time; //字的长度 float length_tv; //圆环的开始角度和结束角度 float angle_start=-90,angle_end; //背景画笔 Paint paint_bg=new Paint(); Paint paint_cicle=new Paint(); Paint paint_tv=new Paint(); //圆环大小,位置 RectF rectF; Path path = new Path(); ValueAnimator animator; public LoadView(Context context) { this(context, null, 0); } public LoadView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public LoadView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void init(){ color_bg= Color.parseColor("#4D161515"); color_circle=Color.WHITE; color_tv=Color.WHITE; size_cicle=dip2px(getContext(),18); size_tv=dip2px(getContext(),12); paint_bg.setColor(color_bg); paint_bg.setAntiAlias(true); size_circle_width=dip2px(getContext(),2); paint_cicle.setStyle(Paint.Style.STROKE); paint_cicle.setStrokeWidth(size_circle_width); paint_cicle.setColor(color_circle); paint_cicle.setAntiAlias(true); paint_tv.setTextSize(size_tv); paint_tv.setColor(color_tv); paint_tv.setAntiAlias(true); length_tv= paint_tv.measureText("跳过"); size_time=2000; rectF=new RectF(size_circle_width,size_circle_width,size_cicle*2-size_circle_width,size_cicle*2-size_circle_width); animator=ValueAnimator.ofFloat(0,1); animator.setDuration(2000); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { if(animation.getAnimatedFraction()==1){ if(getEndListener()!=null){ getEndListener().end(); } } path.reset(); path.addArc(rectF,-90,360*animation.getAnimatedFraction()); invalidate(); } }); } @Override public void draw(Canvas canvas) { super.draw(canvas); canvas.drawCircle(size_cicle,size_cicle,size_cicle,paint_bg); canvas.drawText("跳过",size_cicle-length_tv/2,size_cicle+size_tv/2,paint_tv); canvas.drawPath(path,paint_cicle); } public void start(){ animator.start(); } public void end(){ animator.end(); } public static int dip2px(Context context, float dpValue) { float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } private EndListener endListener; public interface EndListener{ public void end(); } public EndListener getEndListener() { return endListener; } public void setEndListener(EndListener endListener) { this.endListener = endListener; } }
979451341/MDemo
LoadView.java
1,001
//字的长度
line_comment
zh-cn
package appupdate.bitpai.comz.testz; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class LoadView extends View { //背景颜色,圆环,字 int color_bg,color_circle,color_tv; //背景圆半径,字,圆环宽度,加载时间 int size_cicle,size_tv,size_circle_width,size_time; //字的 <SUF> float length_tv; //圆环的开始角度和结束角度 float angle_start=-90,angle_end; //背景画笔 Paint paint_bg=new Paint(); Paint paint_cicle=new Paint(); Paint paint_tv=new Paint(); //圆环大小,位置 RectF rectF; Path path = new Path(); ValueAnimator animator; public LoadView(Context context) { this(context, null, 0); } public LoadView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public LoadView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void init(){ color_bg= Color.parseColor("#4D161515"); color_circle=Color.WHITE; color_tv=Color.WHITE; size_cicle=dip2px(getContext(),18); size_tv=dip2px(getContext(),12); paint_bg.setColor(color_bg); paint_bg.setAntiAlias(true); size_circle_width=dip2px(getContext(),2); paint_cicle.setStyle(Paint.Style.STROKE); paint_cicle.setStrokeWidth(size_circle_width); paint_cicle.setColor(color_circle); paint_cicle.setAntiAlias(true); paint_tv.setTextSize(size_tv); paint_tv.setColor(color_tv); paint_tv.setAntiAlias(true); length_tv= paint_tv.measureText("跳过"); size_time=2000; rectF=new RectF(size_circle_width,size_circle_width,size_cicle*2-size_circle_width,size_cicle*2-size_circle_width); animator=ValueAnimator.ofFloat(0,1); animator.setDuration(2000); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { if(animation.getAnimatedFraction()==1){ if(getEndListener()!=null){ getEndListener().end(); } } path.reset(); path.addArc(rectF,-90,360*animation.getAnimatedFraction()); invalidate(); } }); } @Override public void draw(Canvas canvas) { super.draw(canvas); canvas.drawCircle(size_cicle,size_cicle,size_cicle,paint_bg); canvas.drawText("跳过",size_cicle-length_tv/2,size_cicle+size_tv/2,paint_tv); canvas.drawPath(path,paint_cicle); } public void start(){ animator.start(); } public void end(){ animator.end(); } public static int dip2px(Context context, float dpValue) { float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } private EndListener endListener; public interface EndListener{ public void end(); } public EndListener getEndListener() { return endListener; } public void setEndListener(EndListener endListener) { this.endListener = endListener; } }
0
3291_2
package com.cf.forward.hk.task; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson.JSONObject; import com.cf.forward.hk.hardware.HkHelper; import com.cf.forward.hk.hardware.handle.DvrMessageHandleImpl; import com.cf.forward.hk.utils.SpringContextUtil; import com.cf.framework.domain.response.ResponseResult; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.CronTrigger; import java.io.IOException; import java.math.BigDecimal; import java.util.Date; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; /** * @author why */ @Slf4j public class CheckOrderTask { /** * 当前语音播报对象 */ private static Map<String, JSONObject> radioObj = new ConcurrentHashMap<>(); private static Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>(); public static void startCron(String carLogId, String deviceIP, String baseUrl) { ThreadPoolTaskScheduler scheduler = SpringContextUtil.getBean(ThreadPoolTaskScheduler.class); ScheduledFuture<?> future = futureMap.get(carLogId); if (Objects.isNull(future)) { // 注: 应该清空前一辆车记录, // if (futureMap.size() > 0) { // for (String key : futureMap.keySet()) { // if(!key.equals(carLogId)){ // stopCron(key); // } // } // } // ========= future = scheduler.schedule(new Runnable() { private int retryCount = 0; @Override public void run() { if (retryCount < 600) { retryCount++; checkOrder(carLogId, deviceIP, baseUrl); } else { stopCron(carLogId); } } }, new CronTrigger("0/5 * * * * *")); log.info("开始检查订单是否支付"); futureMap.put(carLogId, future); } } public static void stopCron(String carLogId) { ScheduledFuture<?> future = futureMap.get(carLogId); if (Objects.nonNull(future)) { future.cancel(true); futureMap.remove(carLogId); } log.info("已重试600次,停止检查"); } /** * 检查订单是否支付 * * @param carLogId 记录ID * @param deviceIP 设备IP */ private static void checkOrder(String carLogId, String deviceIP, String baseUrl) { String url = baseUrl + "/carparkorder/check_order_is_pay?id=" + carLogId; String result = HttpUtil.createGet(url).execute().body(); ObjectMapper mapper = new ObjectMapper(); ResponseResult responseResult = null; try { responseResult = mapper.readValue(result, ResponseResult.class); } catch (IOException e) { log.info(e.getMessage()); } if (Objects.nonNull(responseResult) && responseResult.isSuccess() && responseResult.getCode() == 10002 && Objects.nonNull(responseResult.getData())) { HkHelper hkHelper = SpringContextUtil.getBean(HkHelper.class); JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(responseResult.getData())); String carNo = json.getString("effectObject"); BigDecimal money = BigDecimal.ZERO; BigDecimal amountActuallyPaid = json.getBigDecimal("amountActuallyPaid"); if (null != amountActuallyPaid) { money = amountActuallyPaid; } Integer status = json.getInteger("status"); if (null != status && status == 1) { // 判断是否有欠费订单 String effectObject = json.getString("effectObject"); JSONObject currencyMap = json.getJSONObject("currencyMap"); if (null != currencyMap && null != currencyMap.getJSONArray("arrearsOrder") && currencyMap.getJSONArray("arrearsOrder").size() > 0) { JSONObject obj = CheckOrderTask.radioObj.get("carLogId"); if (null == obj) { int size = currencyMap.getJSONArray("arrearsOrder").size(); String info = effectObject + " 还有" + size + "个 订单未支付 请先完成支付"; hkHelper.controlVoice(info); JSONObject jsonObject = new JSONObject(); jsonObject.put("ceateTime", new Date()); jsonObject.put("numberPlate", effectObject); CheckOrderTask.radioObj.put("carLogId", jsonObject); SpaceNumAsyncTask.stopCarInfo.setCreateTime(new Date()); SpaceNumAsyncTask.stopCarInfo.setShowTxt(info); SpaceNumAsyncTask.stopCarInfo.setNumberPlate(carNo); } else { } } else { stopCron(carLogId); CheckOrderTask.radioObj.remove(carLogId); log.info(String.format("ip:%s, 车牌号:%s,停车记录ID:%s,已支付:%s,尝试开闸", deviceIP, carNo, carLogId, money.toPlainString())); hkHelper.openAndClose(true); hkHelper.controlVoice("一路顺风"); DvrMessageHandleImpl dvrMessageHandle = SpringContextUtil.getBean(DvrMessageHandleImpl.class); } } else { // 判断是否有欠费订单 String effectObject = json.getString("effectObject"); JSONObject currencyMap = json.getJSONObject("currencyMap"); if (null != currencyMap && null != currencyMap.getJSONArray("arrearsOrder") && currencyMap.getJSONArray("arrearsOrder").size() > 0) { JSONObject obj = CheckOrderTask.radioObj.get("carLogId"); if (null == obj) { int size = currencyMap.getJSONArray("arrearsOrder").size(); String info = effectObject + " 还有" + size + "个 订单未支付 请先完成支付"; hkHelper.controlVoice(info); JSONObject jsonObject = new JSONObject(); jsonObject.put("ceateTime", new Date()); jsonObject.put("numberPlate", effectObject); CheckOrderTask.radioObj.put("carLogId", jsonObject); SpaceNumAsyncTask.stopCarInfo.setCreateTime(new Date()); SpaceNumAsyncTask.stopCarInfo.setShowTxt(info); SpaceNumAsyncTask.stopCarInfo.setNumberPlate(carNo); } } } } else { log.info(String.format("ip:%s,停车记录ID:%s,未支付", deviceIP, carLogId)); } } }
981011512/--
cf-framework-parent/cf-internet-of-things/cf-car-park/forward/src/main/java/com/cf/forward/hk/task/CheckOrderTask.java
1,608
// 注: 应该清空前一辆车记录,
line_comment
zh-cn
package com.cf.forward.hk.task; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson.JSONObject; import com.cf.forward.hk.hardware.HkHelper; import com.cf.forward.hk.hardware.handle.DvrMessageHandleImpl; import com.cf.forward.hk.utils.SpringContextUtil; import com.cf.framework.domain.response.ResponseResult; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.CronTrigger; import java.io.IOException; import java.math.BigDecimal; import java.util.Date; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; /** * @author why */ @Slf4j public class CheckOrderTask { /** * 当前语音播报对象 */ private static Map<String, JSONObject> radioObj = new ConcurrentHashMap<>(); private static Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>(); public static void startCron(String carLogId, String deviceIP, String baseUrl) { ThreadPoolTaskScheduler scheduler = SpringContextUtil.getBean(ThreadPoolTaskScheduler.class); ScheduledFuture<?> future = futureMap.get(carLogId); if (Objects.isNull(future)) { // 注: <SUF> // if (futureMap.size() > 0) { // for (String key : futureMap.keySet()) { // if(!key.equals(carLogId)){ // stopCron(key); // } // } // } // ========= future = scheduler.schedule(new Runnable() { private int retryCount = 0; @Override public void run() { if (retryCount < 600) { retryCount++; checkOrder(carLogId, deviceIP, baseUrl); } else { stopCron(carLogId); } } }, new CronTrigger("0/5 * * * * *")); log.info("开始检查订单是否支付"); futureMap.put(carLogId, future); } } public static void stopCron(String carLogId) { ScheduledFuture<?> future = futureMap.get(carLogId); if (Objects.nonNull(future)) { future.cancel(true); futureMap.remove(carLogId); } log.info("已重试600次,停止检查"); } /** * 检查订单是否支付 * * @param carLogId 记录ID * @param deviceIP 设备IP */ private static void checkOrder(String carLogId, String deviceIP, String baseUrl) { String url = baseUrl + "/carparkorder/check_order_is_pay?id=" + carLogId; String result = HttpUtil.createGet(url).execute().body(); ObjectMapper mapper = new ObjectMapper(); ResponseResult responseResult = null; try { responseResult = mapper.readValue(result, ResponseResult.class); } catch (IOException e) { log.info(e.getMessage()); } if (Objects.nonNull(responseResult) && responseResult.isSuccess() && responseResult.getCode() == 10002 && Objects.nonNull(responseResult.getData())) { HkHelper hkHelper = SpringContextUtil.getBean(HkHelper.class); JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(responseResult.getData())); String carNo = json.getString("effectObject"); BigDecimal money = BigDecimal.ZERO; BigDecimal amountActuallyPaid = json.getBigDecimal("amountActuallyPaid"); if (null != amountActuallyPaid) { money = amountActuallyPaid; } Integer status = json.getInteger("status"); if (null != status && status == 1) { // 判断是否有欠费订单 String effectObject = json.getString("effectObject"); JSONObject currencyMap = json.getJSONObject("currencyMap"); if (null != currencyMap && null != currencyMap.getJSONArray("arrearsOrder") && currencyMap.getJSONArray("arrearsOrder").size() > 0) { JSONObject obj = CheckOrderTask.radioObj.get("carLogId"); if (null == obj) { int size = currencyMap.getJSONArray("arrearsOrder").size(); String info = effectObject + " 还有" + size + "个 订单未支付 请先完成支付"; hkHelper.controlVoice(info); JSONObject jsonObject = new JSONObject(); jsonObject.put("ceateTime", new Date()); jsonObject.put("numberPlate", effectObject); CheckOrderTask.radioObj.put("carLogId", jsonObject); SpaceNumAsyncTask.stopCarInfo.setCreateTime(new Date()); SpaceNumAsyncTask.stopCarInfo.setShowTxt(info); SpaceNumAsyncTask.stopCarInfo.setNumberPlate(carNo); } else { } } else { stopCron(carLogId); CheckOrderTask.radioObj.remove(carLogId); log.info(String.format("ip:%s, 车牌号:%s,停车记录ID:%s,已支付:%s,尝试开闸", deviceIP, carNo, carLogId, money.toPlainString())); hkHelper.openAndClose(true); hkHelper.controlVoice("一路顺风"); DvrMessageHandleImpl dvrMessageHandle = SpringContextUtil.getBean(DvrMessageHandleImpl.class); } } else { // 判断是否有欠费订单 String effectObject = json.getString("effectObject"); JSONObject currencyMap = json.getJSONObject("currencyMap"); if (null != currencyMap && null != currencyMap.getJSONArray("arrearsOrder") && currencyMap.getJSONArray("arrearsOrder").size() > 0) { JSONObject obj = CheckOrderTask.radioObj.get("carLogId"); if (null == obj) { int size = currencyMap.getJSONArray("arrearsOrder").size(); String info = effectObject + " 还有" + size + "个 订单未支付 请先完成支付"; hkHelper.controlVoice(info); JSONObject jsonObject = new JSONObject(); jsonObject.put("ceateTime", new Date()); jsonObject.put("numberPlate", effectObject); CheckOrderTask.radioObj.put("carLogId", jsonObject); SpaceNumAsyncTask.stopCarInfo.setCreateTime(new Date()); SpaceNumAsyncTask.stopCarInfo.setShowTxt(info); SpaceNumAsyncTask.stopCarInfo.setNumberPlate(carNo); } } } } else { log.info(String.format("ip:%s,停车记录ID:%s,未支付", deviceIP, carLogId)); } } }
0
42990_2
/** * @author Wcy * @Date 2022/3/28 15:57 */ /** * 上小学的时候,小明经常自己发明新算法。一次,老师出的题目是: * * 1/4 乘以 8/5 * * 小明居然把分子拼接在一起,分母拼接在一起,答案是:18/45 (参见图1.png) * * 老师刚想批评他,转念一想,这个答案凑巧也对啊,真是见鬼! * * 对于分子、分母都是 1~9 中的一位数的情况,还有哪些算式可以这样计算呢? * * 请写出所有不同算式的个数(包括题中举例的)。 * * 显然,交换分子分母后,例如:4/1 乘以 5/8 是满足要求的,这算做不同的算式。 * * 但对于分子分母相同的情况,2/2 乘以 3/3 这样的类型太多了,不在计数之列! * * 注意:答案是个整数(考虑对称性,肯定是偶数)。请通过浏览器提交。不要书写多余的内容。 */ public class 奇怪的分式 { public static void main(String[] args) { // 好家伙,相当暴力 int ans=0; for(int a=1;a<10;a++) for(int b=1;b<10;b++) for(int c=1;c<10;c++) for(int d=1;d<10;d++) { int e = 10*a+c; int f = 10*b+d; if(a==b || c==d) continue; if(a*c*f==e*b*d) { ans++; System.out.println(a+"/"+b+" x "+c+"/"+d+" = "+e+"/"+f+" "+ans); } } } }
986515470/lanqiao-codes
2014年第五届蓝桥杯省赛试题及详解/src/奇怪的分式.java
535
// 好家伙,相当暴力
line_comment
zh-cn
/** * @author Wcy * @Date 2022/3/28 15:57 */ /** * 上小学的时候,小明经常自己发明新算法。一次,老师出的题目是: * * 1/4 乘以 8/5 * * 小明居然把分子拼接在一起,分母拼接在一起,答案是:18/45 (参见图1.png) * * 老师刚想批评他,转念一想,这个答案凑巧也对啊,真是见鬼! * * 对于分子、分母都是 1~9 中的一位数的情况,还有哪些算式可以这样计算呢? * * 请写出所有不同算式的个数(包括题中举例的)。 * * 显然,交换分子分母后,例如:4/1 乘以 5/8 是满足要求的,这算做不同的算式。 * * 但对于分子分母相同的情况,2/2 乘以 3/3 这样的类型太多了,不在计数之列! * * 注意:答案是个整数(考虑对称性,肯定是偶数)。请通过浏览器提交。不要书写多余的内容。 */ public class 奇怪的分式 { public static void main(String[] args) { // 好家 <SUF> int ans=0; for(int a=1;a<10;a++) for(int b=1;b<10;b++) for(int c=1;c<10;c++) for(int d=1;d<10;d++) { int e = 10*a+c; int f = 10*b+d; if(a==b || c==d) continue; if(a*c*f==e*b*d) { ans++; System.out.println(a+"/"+b+" x "+c+"/"+d+" = "+e+"/"+f+" "+ans); } } } }
1
46332_12
package com.component.impl; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import android.Manifest; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.MemoryInfo; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.telephony.TelephonyManager; import android.util.Log; public class PhoneInfo { private static final String TAG = PhoneInfo.class.getSimpleName(); private static final String FILE_MEMORY = "/proc/meminfo"; private static final String FILE_CPU = "/proc/cpuinfo"; public String mIMEI = null; public int mPhoneType = 0; public String mSysVersion = null; public String mNetWorkCountryIso = null; public String mNetWorkOperator = null; public String mNetWorkOperatorName = null; public int mNetWorkType = 0; public boolean mIsOnLine = false; public String mConnectTypeName = null; public long mFreeMem = 0; public long mTotalMem = 0; public String mMem = null; public String mCupInfo = null; public String mProductName = null; public String mModelName = null; public String mManufacturerName = null; public String mIP = null; public String mISP = null; public String mDeviceVersion = null; private static PhoneInfo instance; private static Activity context; public static PhoneInfo getInstance() { if (instance == null) instance = new PhoneInfo(); return instance; } public PhoneInfo() { init(); } public static void init(Activity activity) { PhoneInfo.context = activity; } // 设备版本号 public String getIMEI() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getDeviceId(); } catch (Exception e) { e.printStackTrace(); } return null; } public int getPhoneType() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getPhoneType(); } catch (Exception e) { e.printStackTrace(); } return 0; } // ISP public String getISP() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getSimOperatorName(); } catch (Exception e) { Log.d("qhero", "get isp error!!", e); } return null; } // DeviceVersion public String getDeviceVersion() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getDeviceSoftwareVersion(); } catch (Exception e) { Log.d("qhero", "get device version error!!", e); } return null; } // 系统版本号 public String getSysVersion() { PackageManager packageManager = context.getPackageManager(); PackageInfo packInfo = null; try { packInfo = packageManager.getPackageInfo(context.getPackageName(), 0); return "Android:" + packInfo.versionName; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public String getNetWorkCountryIso() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getNetworkCountryIso(); } catch (Exception e) { e.printStackTrace(); } return null; } public String getNetWorkOperator() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getNetworkOperator(); } catch (Exception e) { e.printStackTrace(); } return null; } public String getNetWorkOperatorName() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getNetworkOperatorName(); } catch (Exception e) { e.printStackTrace(); } return null; } public int getNetworkType() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getNetworkType(); } catch (Exception e) { e.printStackTrace(); } return 0; } public boolean isOnline() { ConnectivityManager manager = (ConnectivityManager) context .getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isConnected()) { return true; } return false; } public String getConnectTypeName() { if (!isOnline()) { return "OFFLINE"; } ConnectivityManager manager = (ConnectivityManager) context .getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null) { return info.getTypeName(); } else { return "OFFLINE"; } } // 可用内存 public long getFreeMem() { ActivityManager manager = (ActivityManager) context .getSystemService(Activity.ACTIVITY_SERVICE); MemoryInfo info = new MemoryInfo(); manager.getMemoryInfo(info); long free = info.availMem / 1024 / 1024; return free; } // 总内存 public long getTotalMem() { try { FileReader fr = new FileReader(FILE_MEMORY); BufferedReader br = new BufferedReader(fr); String text = br.readLine(); String[] array = text.split("\\s+"); return Long.valueOf(array[1]) / 1024; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; } public String getMem() { return Long.toString(mTotalMem) + "M"; } // cpu信息 public String getCpuInfo() { try { FileReader fr = new FileReader(FILE_CPU); BufferedReader br = new BufferedReader(fr); String text = br.readLine(); String[] array = text.split(":\\s+", 2); // for (int i = 0; i < array.length; i++) { // Log.w(TAG, " ..... " + array[i]); // } // Log.w(TAG, text); return array[1]; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public String getProductName() { return Build.PRODUCT; } public String getModelName() { return Build.MODEL; } public String getManufacturerName() { return Build.MANUFACTURER; } // 取得IP地址 public String getIPAddress() { //这段代码有问题,光取wifi的IP是没有用的,没考虑移动网络的情况,而且这只能取得本地IP,毫无意义 by Clark 2013/11/11 // WifiManager wifiMgr = (WifiManager) context // .getSystemService(Context.WIFI_SERVICE); // if (!wifiMgr.isWifiEnabled()) { // wifiMgr.setWifiEnabled(true); // } // WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); // int ip = wifiInfo.getIpAddress(); // return intToIP(ip); return "0.0.0.0"; } private String intToIP(final int i) { return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF); } private void init() { mIMEI = getIMEI(); mPhoneType = getPhoneType(); mSysVersion = getSysVersion(); mNetWorkCountryIso = getNetWorkCountryIso(); mNetWorkOperator = getNetWorkOperator(); mNetWorkOperatorName = getNetWorkOperatorName(); mNetWorkType = getNetworkType(); mIsOnLine = isOnline(); mConnectTypeName = getConnectTypeName(); mFreeMem = getFreeMem(); mTotalMem = getTotalMem(); mCupInfo = getCpuInfo(); mProductName = getProductName(); mModelName = getModelName(); mManufacturerName = getManufacturerName(); mIP = getIPAddress(); mISP = getISP(); mDeviceVersion = getDeviceVersion(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("IMEI : " + mIMEI + "\n"); builder.append("mPhoneType : " + mPhoneType + "\n"); builder.append("mSysVersion : " + mSysVersion + "\n"); builder.append("mNetWorkCountryIso : " + mNetWorkCountryIso + "\n"); builder.append("mNetWorkOperator : " + mNetWorkOperator + "\n"); builder.append("mNetWorkOperatorName : " + mNetWorkOperatorName + "\n"); builder.append("mNetWorkType : " + mNetWorkType + "\n"); builder.append("mIsOnLine : " + mIsOnLine + "\n"); builder.append("mConnectTypeName : " + mConnectTypeName + "\n"); builder.append("mFreeMem : " + mMem + "M\n"); builder.append("mTotalMem : " + mTotalMem + "M\n"); builder.append("mCupInfo : " + mCupInfo + "\n"); builder.append("mProductName : " + mProductName + "\n"); builder.append("mModelName : " + mModelName + "\n"); builder.append("mISP : " + mISP + "\n"); builder.append("mManufacturerName : " + mManufacturerName + "\n"); builder.append("ip : " + mIP + "\n"); return builder.toString(); } }
9miao/CartoonHouse
DMZJ/proj.android/src/com/component/impl/PhoneInfo.java
2,702
//这段代码有问题,光取wifi的IP是没有用的,没考虑移动网络的情况,而且这只能取得本地IP,毫无意义 by Clark 2013/11/11
line_comment
zh-cn
package com.component.impl; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import android.Manifest; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.MemoryInfo; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.telephony.TelephonyManager; import android.util.Log; public class PhoneInfo { private static final String TAG = PhoneInfo.class.getSimpleName(); private static final String FILE_MEMORY = "/proc/meminfo"; private static final String FILE_CPU = "/proc/cpuinfo"; public String mIMEI = null; public int mPhoneType = 0; public String mSysVersion = null; public String mNetWorkCountryIso = null; public String mNetWorkOperator = null; public String mNetWorkOperatorName = null; public int mNetWorkType = 0; public boolean mIsOnLine = false; public String mConnectTypeName = null; public long mFreeMem = 0; public long mTotalMem = 0; public String mMem = null; public String mCupInfo = null; public String mProductName = null; public String mModelName = null; public String mManufacturerName = null; public String mIP = null; public String mISP = null; public String mDeviceVersion = null; private static PhoneInfo instance; private static Activity context; public static PhoneInfo getInstance() { if (instance == null) instance = new PhoneInfo(); return instance; } public PhoneInfo() { init(); } public static void init(Activity activity) { PhoneInfo.context = activity; } // 设备版本号 public String getIMEI() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getDeviceId(); } catch (Exception e) { e.printStackTrace(); } return null; } public int getPhoneType() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getPhoneType(); } catch (Exception e) { e.printStackTrace(); } return 0; } // ISP public String getISP() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getSimOperatorName(); } catch (Exception e) { Log.d("qhero", "get isp error!!", e); } return null; } // DeviceVersion public String getDeviceVersion() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getDeviceSoftwareVersion(); } catch (Exception e) { Log.d("qhero", "get device version error!!", e); } return null; } // 系统版本号 public String getSysVersion() { PackageManager packageManager = context.getPackageManager(); PackageInfo packInfo = null; try { packInfo = packageManager.getPackageInfo(context.getPackageName(), 0); return "Android:" + packInfo.versionName; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public String getNetWorkCountryIso() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getNetworkCountryIso(); } catch (Exception e) { e.printStackTrace(); } return null; } public String getNetWorkOperator() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getNetworkOperator(); } catch (Exception e) { e.printStackTrace(); } return null; } public String getNetWorkOperatorName() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getNetworkOperatorName(); } catch (Exception e) { e.printStackTrace(); } return null; } public int getNetworkType() { try { TelephonyManager manager = (TelephonyManager) context .getSystemService(Activity.TELEPHONY_SERVICE); return manager.getNetworkType(); } catch (Exception e) { e.printStackTrace(); } return 0; } public boolean isOnline() { ConnectivityManager manager = (ConnectivityManager) context .getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isConnected()) { return true; } return false; } public String getConnectTypeName() { if (!isOnline()) { return "OFFLINE"; } ConnectivityManager manager = (ConnectivityManager) context .getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null) { return info.getTypeName(); } else { return "OFFLINE"; } } // 可用内存 public long getFreeMem() { ActivityManager manager = (ActivityManager) context .getSystemService(Activity.ACTIVITY_SERVICE); MemoryInfo info = new MemoryInfo(); manager.getMemoryInfo(info); long free = info.availMem / 1024 / 1024; return free; } // 总内存 public long getTotalMem() { try { FileReader fr = new FileReader(FILE_MEMORY); BufferedReader br = new BufferedReader(fr); String text = br.readLine(); String[] array = text.split("\\s+"); return Long.valueOf(array[1]) / 1024; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; } public String getMem() { return Long.toString(mTotalMem) + "M"; } // cpu信息 public String getCpuInfo() { try { FileReader fr = new FileReader(FILE_CPU); BufferedReader br = new BufferedReader(fr); String text = br.readLine(); String[] array = text.split(":\\s+", 2); // for (int i = 0; i < array.length; i++) { // Log.w(TAG, " ..... " + array[i]); // } // Log.w(TAG, text); return array[1]; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public String getProductName() { return Build.PRODUCT; } public String getModelName() { return Build.MODEL; } public String getManufacturerName() { return Build.MANUFACTURER; } // 取得IP地址 public String getIPAddress() { //这段 <SUF> // WifiManager wifiMgr = (WifiManager) context // .getSystemService(Context.WIFI_SERVICE); // if (!wifiMgr.isWifiEnabled()) { // wifiMgr.setWifiEnabled(true); // } // WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); // int ip = wifiInfo.getIpAddress(); // return intToIP(ip); return "0.0.0.0"; } private String intToIP(final int i) { return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF); } private void init() { mIMEI = getIMEI(); mPhoneType = getPhoneType(); mSysVersion = getSysVersion(); mNetWorkCountryIso = getNetWorkCountryIso(); mNetWorkOperator = getNetWorkOperator(); mNetWorkOperatorName = getNetWorkOperatorName(); mNetWorkType = getNetworkType(); mIsOnLine = isOnline(); mConnectTypeName = getConnectTypeName(); mFreeMem = getFreeMem(); mTotalMem = getTotalMem(); mCupInfo = getCpuInfo(); mProductName = getProductName(); mModelName = getModelName(); mManufacturerName = getManufacturerName(); mIP = getIPAddress(); mISP = getISP(); mDeviceVersion = getDeviceVersion(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("IMEI : " + mIMEI + "\n"); builder.append("mPhoneType : " + mPhoneType + "\n"); builder.append("mSysVersion : " + mSysVersion + "\n"); builder.append("mNetWorkCountryIso : " + mNetWorkCountryIso + "\n"); builder.append("mNetWorkOperator : " + mNetWorkOperator + "\n"); builder.append("mNetWorkOperatorName : " + mNetWorkOperatorName + "\n"); builder.append("mNetWorkType : " + mNetWorkType + "\n"); builder.append("mIsOnLine : " + mIsOnLine + "\n"); builder.append("mConnectTypeName : " + mConnectTypeName + "\n"); builder.append("mFreeMem : " + mMem + "M\n"); builder.append("mTotalMem : " + mTotalMem + "M\n"); builder.append("mCupInfo : " + mCupInfo + "\n"); builder.append("mProductName : " + mProductName + "\n"); builder.append("mModelName : " + mModelName + "\n"); builder.append("mISP : " + mISP + "\n"); builder.append("mManufacturerName : " + mManufacturerName + "\n"); builder.append("ip : " + mIP + "\n"); return builder.toString(); } }
0
35217_0
package org.CrossApp.lib; import android.Manifest; import android.content.DialogInterface; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import com.tbruyelle.rxpermissions3.RxPermissions; import java.util.ArrayList; import java.util.List; import io.reactivex.rxjava3.functions.Consumer; import static org.CrossApp.lib.CrossAppDevice.list; public class CAPermissionsManager { public static void request(List<String> types, CAPermissionsManagerCallBack capermissionsmanagercallback) { final CrossAppActivity context = CrossAppActivity.getContext(); final RxPermissions rxPermissions = new RxPermissions(context); String[] array = new String[types.size()]; for (int i = 0; i < types.size(); i++) { String type = types.get(i); switch (type) { case "读取日历": { array[i] = Manifest.permission.READ_CALENDAR; } break; case "修改日历": { array[i] = Manifest.permission.WRITE_CALENDAR; } break; case "相机": { array[i] = Manifest.permission.CAMERA; } break; case "读取联系人": { array[i] = Manifest.permission.READ_CONTACTS; } break; case "修改联系人": { array[i] = Manifest.permission.WRITE_CONTACTS; } break; case "GPS定位": { array[i] = Manifest.permission.ACCESS_FINE_LOCATION; } break; case "WIFI定位": { array[i] = Manifest.permission.ACCESS_COARSE_LOCATION; } break; case "麦克风": { array[i] = Manifest.permission.RECORD_AUDIO; } break; case "拨号": { array[i] = Manifest.permission.CALL_PHONE; } break; case "传感器": { array[i] = Manifest.permission.BODY_SENSORS; } break; case "发短信": { array[i] = Manifest.permission.SEND_SMS; } break; case "读取存储卡": { array[i] = Manifest.permission.READ_EXTERNAL_STORAGE; } break; case "写入存储卡": { array[i] = Manifest.permission.WRITE_EXTERNAL_STORAGE; } break; default: break; } } try { rxPermissions.request(array) .subscribe(granted -> { if (granted) { capermissionsmanagercallback.onCallBack(true); } else { new AlertDialog.Builder(context) .setTitle("权限申请") .setMessage("在设置-应用-" + CAPermissionsManager.getAppName() + "-权限中开启" + CAPermissionsManager.getPermissionStr(types) + "权限,以正常使用" + CAPermissionsManager.getAppName() + "相关功能") .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { CameraView.closed(); } }) .setNegativeButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception {//处理异常 throwable.printStackTrace(); CameraView.closed(); } }); } catch (Exception e) { } } public interface CAPermissionsManagerCallBack { void onCallBack(Boolean isSucess); } public static String getAppName() { try { PackageManager packageManager = CrossAppActivity.getContext().getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( CrossAppActivity.getContext().getPackageName(), 0); int labelRes = packageInfo.applicationInfo.labelRes; return CrossAppActivity.getContext().getResources().getString(labelRes); } catch (Exception e) { e.printStackTrace(); return ""; } } public static String getPermissionStr(List<String> types) { String str = ""; for (int i = 0; i < types.size(); i++) { if (i == types.size() - 1) { str += types.get(i); } else { str += types.get(i) + "、"; } } return str; } private static native void imagePickerWriteCallback(int isSucess); public static void requestImagePickerWrite() { final CrossAppActivity context = CrossAppActivity.getContext(); context.runOnUiThread(new Runnable() { @Override public void run() { ArrayList<String> types = new ArrayList<String>(); types.add("读取存储卡"); types.add("写入存储卡"); CAPermissionsManager.request(types, new CAPermissionsManager.CAPermissionsManagerCallBack() { @Override public void onCallBack(Boolean isSucess) { imagePickerWriteCallback(isSucess ? 1 : 0); } }); } }); } }
9miao/CrossApp
CrossApp/proj.android/src/org/CrossApp/lib/CAPermissionsManager.java
1,231
//处理异常
line_comment
zh-cn
package org.CrossApp.lib; import android.Manifest; import android.content.DialogInterface; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import com.tbruyelle.rxpermissions3.RxPermissions; import java.util.ArrayList; import java.util.List; import io.reactivex.rxjava3.functions.Consumer; import static org.CrossApp.lib.CrossAppDevice.list; public class CAPermissionsManager { public static void request(List<String> types, CAPermissionsManagerCallBack capermissionsmanagercallback) { final CrossAppActivity context = CrossAppActivity.getContext(); final RxPermissions rxPermissions = new RxPermissions(context); String[] array = new String[types.size()]; for (int i = 0; i < types.size(); i++) { String type = types.get(i); switch (type) { case "读取日历": { array[i] = Manifest.permission.READ_CALENDAR; } break; case "修改日历": { array[i] = Manifest.permission.WRITE_CALENDAR; } break; case "相机": { array[i] = Manifest.permission.CAMERA; } break; case "读取联系人": { array[i] = Manifest.permission.READ_CONTACTS; } break; case "修改联系人": { array[i] = Manifest.permission.WRITE_CONTACTS; } break; case "GPS定位": { array[i] = Manifest.permission.ACCESS_FINE_LOCATION; } break; case "WIFI定位": { array[i] = Manifest.permission.ACCESS_COARSE_LOCATION; } break; case "麦克风": { array[i] = Manifest.permission.RECORD_AUDIO; } break; case "拨号": { array[i] = Manifest.permission.CALL_PHONE; } break; case "传感器": { array[i] = Manifest.permission.BODY_SENSORS; } break; case "发短信": { array[i] = Manifest.permission.SEND_SMS; } break; case "读取存储卡": { array[i] = Manifest.permission.READ_EXTERNAL_STORAGE; } break; case "写入存储卡": { array[i] = Manifest.permission.WRITE_EXTERNAL_STORAGE; } break; default: break; } } try { rxPermissions.request(array) .subscribe(granted -> { if (granted) { capermissionsmanagercallback.onCallBack(true); } else { new AlertDialog.Builder(context) .setTitle("权限申请") .setMessage("在设置-应用-" + CAPermissionsManager.getAppName() + "-权限中开启" + CAPermissionsManager.getPermissionStr(types) + "权限,以正常使用" + CAPermissionsManager.getAppName() + "相关功能") .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { CameraView.closed(); } }) .setNegativeButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception {//处理 <SUF> throwable.printStackTrace(); CameraView.closed(); } }); } catch (Exception e) { } } public interface CAPermissionsManagerCallBack { void onCallBack(Boolean isSucess); } public static String getAppName() { try { PackageManager packageManager = CrossAppActivity.getContext().getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( CrossAppActivity.getContext().getPackageName(), 0); int labelRes = packageInfo.applicationInfo.labelRes; return CrossAppActivity.getContext().getResources().getString(labelRes); } catch (Exception e) { e.printStackTrace(); return ""; } } public static String getPermissionStr(List<String> types) { String str = ""; for (int i = 0; i < types.size(); i++) { if (i == types.size() - 1) { str += types.get(i); } else { str += types.get(i) + "、"; } } return str; } private static native void imagePickerWriteCallback(int isSucess); public static void requestImagePickerWrite() { final CrossAppActivity context = CrossAppActivity.getContext(); context.runOnUiThread(new Runnable() { @Override public void run() { ArrayList<String> types = new ArrayList<String>(); types.add("读取存储卡"); types.add("写入存储卡"); CAPermissionsManager.request(types, new CAPermissionsManager.CAPermissionsManagerCallBack() { @Override public void onCallBack(Boolean isSucess) { imagePickerWriteCallback(isSucess ? 1 : 0); } }); } }); } }
0
6646_16
package com.seu.learn.inheritance; public class Person { String name; int age; public void eat(){ System.out.println(" 人,吃饭"); } public void walk(){ System.out.println(" 人,走路"); } } class Woman extends Person { boolean isBeauty; public void goShopping(){ System.out.println(" 女人喜欢购物"); } public void eat(){ System.out.println(" 女人少吃,为了减肥。"); } public void walk(){ System.out.println(" 女人,窈窕的走路。"); } } class Man extends Person { boolean isSmoking; public void earnMoney(){ System.out.println(" 男人负责工作养家"); } public void eat() { System.out.println(" 男人多吃肉,长肌肉"); } public void walk() { System.out.println(" 男人霸气的走路"); } } class PersonTest { public static void main(String[] args) { Person p1 = new Person(); p1.eat(); Man man = new Man(); man.eat(); man.age = 25; man.earnMoney(); // ************************************ System.out.println("************************"); // 对象的多态性,父类的引用指向子类的对象 Person p2 = new Man(); // Person p3 = new Woman(); // 多态的使用: 当调用子父类同名同参数方法时,实际调用的是子类重写父类的方法--- 虚拟方法调用 p2.eat(); p2.walk(); // p2.earnMoney(); System.out.println("**************************"); // 不能调用子类所特有的方法、属性,编译时,p2 是Person类型, p2.name = "Tom"; // p2.isSmoking = true; // 有了对象的多态性以后,内存中实际上是加载了子类特有的属性和方法,但是由于变量声明 // 为父类类型,导致编译时,只能调用父类中声明的属性和方法。子类的属性和方法不能调用。 // 如何才能调用子类所特有的属性和方法? // 使用强制类型转换符,也可称为: 向下转型 Man m1 = (Man) p2; m1.earnMoney(); m1.isSmoking = true; // 使用强转时,可能出现ClassCastException 异常 // Woman w1 = (Woman)p2; // w1.goShopping(); /* * instanceof 关键字的使用 * a instanceof A:判断对象a 是否是类A 的实例。如果是, 返回true,如果不是,返回false; * 使用情境:为了避免在向下转型时出现ClassCastException 异常,我们在进行向下转型之前,先进行instanceof 的判断, 一旦返回 true, 就进行向下转型。如果返回false,不进行向下转型。 * 如果a instanceof A 返回true, 则a instanceof B 也返回 true。 其中类B 是类A 的父类。 */ if (p2 instanceof Woman) { Woman w1 = (Woman) p2; w1.goShopping(); System.out.println("**********Woman*********"); } if (p2 instanceof Man) { Man m2 = (Man) p2; m2.earnMoney(); System.out.println("*********Man************"); } if (p2 instanceof Person) { System.out.println("***********Person************"); } if (p2 instanceof Object) { System.out.println("***********object************"); } // 向下转型的常见问题 // 练习 // 问题1: 编译时通过,运行时不通过 // 举例一 // Person p3 = new Woman(); // Man m3 = (Man)p3; // 举例二 // Person p4 = new Person(); // Man m4 = (Man)p4; // 问题二: 编译通过,运行时也通过 Object obj = new Woman(); Person p = (Person)obj; // 问题三: 编译不通过 // Man m5 = new woman(); // String str = new Date(); // Object o = new Date(); // String str1 = (String)o; } }
A-BigTree/Code_Learning
Java入门/code/inheritance/Person.java
1,067
// 举例一
line_comment
zh-cn
package com.seu.learn.inheritance; public class Person { String name; int age; public void eat(){ System.out.println(" 人,吃饭"); } public void walk(){ System.out.println(" 人,走路"); } } class Woman extends Person { boolean isBeauty; public void goShopping(){ System.out.println(" 女人喜欢购物"); } public void eat(){ System.out.println(" 女人少吃,为了减肥。"); } public void walk(){ System.out.println(" 女人,窈窕的走路。"); } } class Man extends Person { boolean isSmoking; public void earnMoney(){ System.out.println(" 男人负责工作养家"); } public void eat() { System.out.println(" 男人多吃肉,长肌肉"); } public void walk() { System.out.println(" 男人霸气的走路"); } } class PersonTest { public static void main(String[] args) { Person p1 = new Person(); p1.eat(); Man man = new Man(); man.eat(); man.age = 25; man.earnMoney(); // ************************************ System.out.println("************************"); // 对象的多态性,父类的引用指向子类的对象 Person p2 = new Man(); // Person p3 = new Woman(); // 多态的使用: 当调用子父类同名同参数方法时,实际调用的是子类重写父类的方法--- 虚拟方法调用 p2.eat(); p2.walk(); // p2.earnMoney(); System.out.println("**************************"); // 不能调用子类所特有的方法、属性,编译时,p2 是Person类型, p2.name = "Tom"; // p2.isSmoking = true; // 有了对象的多态性以后,内存中实际上是加载了子类特有的属性和方法,但是由于变量声明 // 为父类类型,导致编译时,只能调用父类中声明的属性和方法。子类的属性和方法不能调用。 // 如何才能调用子类所特有的属性和方法? // 使用强制类型转换符,也可称为: 向下转型 Man m1 = (Man) p2; m1.earnMoney(); m1.isSmoking = true; // 使用强转时,可能出现ClassCastException 异常 // Woman w1 = (Woman)p2; // w1.goShopping(); /* * instanceof 关键字的使用 * a instanceof A:判断对象a 是否是类A 的实例。如果是, 返回true,如果不是,返回false; * 使用情境:为了避免在向下转型时出现ClassCastException 异常,我们在进行向下转型之前,先进行instanceof 的判断, 一旦返回 true, 就进行向下转型。如果返回false,不进行向下转型。 * 如果a instanceof A 返回true, 则a instanceof B 也返回 true。 其中类B 是类A 的父类。 */ if (p2 instanceof Woman) { Woman w1 = (Woman) p2; w1.goShopping(); System.out.println("**********Woman*********"); } if (p2 instanceof Man) { Man m2 = (Man) p2; m2.earnMoney(); System.out.println("*********Man************"); } if (p2 instanceof Person) { System.out.println("***********Person************"); } if (p2 instanceof Object) { System.out.println("***********object************"); } // 向下转型的常见问题 // 练习 // 问题1: 编译时通过,运行时不通过 // 举例 <SUF> // Person p3 = new Woman(); // Man m3 = (Man)p3; // 举例二 // Person p4 = new Person(); // Man m4 = (Man)p4; // 问题二: 编译通过,运行时也通过 Object obj = new Woman(); Person p = (Person)obj; // 问题三: 编译不通过 // Man m5 = new woman(); // String str = new Date(); // Object o = new Date(); // String str1 = (String)o; } }
0
17075_6
package com.ctao.qhb; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.ctao.baselib.Global; import com.ctao.baselib.utils.LogUtils; import com.ctao.baselib.utils.SPUtils; /** * Created by A Miracle on 2017/8/17. */ public class Config { public static final String FILE_LOG = "log"; public static final String FILE_IMG = "img"; public static final String FILE_APK = "apk"; public static final String FILE_CACHE = "cache"; public static final String PACKAGE_NAME_WX = "com.tencent.mm"; public static final String PACKAGE_NAME_QQ = "com.tencent.mobileqq"; public static final String PACKAGE_NAME_TIM = "com.tencent.tim"; public static final String SP_LATEST_DATE = "SP_LATEST_DATE"; // 最新时间 public static final String SP_LATEST_CODE = "SP_UPDATE_PACKAGE"; // 最新包Code public static final String SP_AGREEMENT = "SP_AGREEMENT"; // 免责声明 public static final String SP_WX_MODE = "SP_WX_MODE"; // 微信抢模式 public static final String SP_WX_DELAY_TIME = "SP_WX_DELAY_TIME"; // 微信拆延时 public static final String SP_QQ_MODE = "SP_QQ_MODE"; // QQ抢模式 public static final String SP_QQ_DELAY_TIME = "SP_QQ_DELAY_TIME"; // QQ拆延时 public static final String SP_ENABLE_WE_CHAT = "platform_WeChat"; public static final String SP_ENABLE_QQ = "platform_QQ"; public static final String SP_ENABLE_TIM = "platform_TIM"; public static final String SP_SMART_BACK_WE_CHAT = "smart_back_wx"; // 微信智能返回 public static final String SP_SMART_BACK_QQ = "SP_SMART_BACK_QQ"; // QQ智能返回 public static final String SP_WORD_QQ = "qq_word_setting"; // QQ口令红包 public static final String SP_LOCK_SCREEN_ROB = "lock_screen_automatic_grab"; // 锁屏自动抢 public static final String SP_VOICE = "voice"; // 声音 public static final String SP_VIBRATION = "vibration"; // 震动 public static final String SP_NIGHT_NOT_DISTURB = "night_not_disturb"; // 夜间免打扰 public static final int WX_MODE_0 = 0;//自动抢 public static final int WX_MODE_1 = 1;//抢群聊, 包括自己发的; public static final int WX_MODE_2 = 2;//抢群聊, 不包括自己发的 public static final int WX_MODE_3 = 3;//通知手动抢 private boolean isEnableWeChat; private boolean isEnableQQ; private boolean isEnableTIM; private boolean isSmartBackWeChat, isSmartBackQQ; private boolean isLockScreenRob; private boolean isVoice; private boolean isVibration; private boolean isNightNotDisturb; private boolean isWordQQ; private int wxMode, qqMode; private float wxDelayTime, qqDelayTime; private Config(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Global.getContext()); isEnableWeChat = sp.getBoolean(SP_ENABLE_WE_CHAT, true); isEnableQQ = sp.getBoolean(SP_ENABLE_QQ, true); isEnableTIM = sp.getBoolean(SP_ENABLE_TIM, true); isSmartBackWeChat = sp.getBoolean(SP_SMART_BACK_WE_CHAT, true); isSmartBackQQ = SPUtils.getBoolean(SP_SMART_BACK_QQ, false); isLockScreenRob = sp.getBoolean(SP_LOCK_SCREEN_ROB, false); isVoice = sp.getBoolean(SP_VOICE, true); isVibration = sp.getBoolean(SP_VIBRATION, true); isNightNotDisturb = sp.getBoolean(SP_NIGHT_NOT_DISTURB, false); wxMode = SPUtils.getInt(SP_WX_MODE, WX_MODE_0); wxDelayTime = SPUtils.getFloat(SP_WX_DELAY_TIME, 0); qqMode = SPUtils.getInt(SP_QQ_MODE, WX_MODE_0); qqDelayTime = SPUtils.getFloat(SP_QQ_DELAY_TIME, 0); isWordQQ = sp.getBoolean(SP_WORD_QQ, true); } private static class Single { static Config Instance = new Config(); } public static Config getInstance() { return Config.Single.Instance; } /** is Enable */ public void changeEnable(String key) { switch (key){ case SP_ENABLE_WE_CHAT: isEnableWeChat = !isEnableWeChat; break; case SP_ENABLE_QQ: isEnableQQ = !isEnableQQ; break; case SP_ENABLE_TIM: isEnableTIM = !isEnableTIM; break; } LogUtils.printOut(isEnableWeChat+", "+isEnableQQ+", "+isEnableTIM); } /** is SmartBack */ public void changeSmartBack(String key) { switch (key){ case SP_ENABLE_WE_CHAT: isSmartBackWeChat = !isSmartBackWeChat; break; case SP_ENABLE_QQ: isSmartBackQQ = !isSmartBackQQ; SPUtils.putObject(SP_SMART_BACK_QQ, isSmartBackQQ); // 要自己保存 break; case SP_ENABLE_TIM: break; } LogUtils.printOut(isSmartBackWeChat+", "+isSmartBackQQ); } public void changeWordQQ(){ isWordQQ = !isWordQQ; } /** is Global */ public void changeGlobal(String key){ switch (key){ case SP_LOCK_SCREEN_ROB: isLockScreenRob = !isLockScreenRob; break; case SP_VOICE: isVoice = !isVoice; break; case SP_VIBRATION: isVibration = !isVibration; break; case SP_NIGHT_NOT_DISTURB: isNightNotDisturb = !isNightNotDisturb; break; } } /** WX Mode */ public void setWXMode(int mode){ SPUtils.putObject(SP_WX_MODE, mode); wxMode = mode; } /** WX DelayTime */ public void setWXDelayTime(float delayTime){ SPUtils.putObject(SP_WX_DELAY_TIME, delayTime); wxDelayTime = delayTime; } /** WX Mode */ public void setQQMode(int mode){ SPUtils.putObject(SP_QQ_MODE, mode); qqMode = mode; } /** WX DelayTime */ public void setQQDelayTime(float delayTime){ SPUtils.putObject(SP_QQ_DELAY_TIME, delayTime); qqDelayTime = delayTime; } /** 是否启动微信抢红包*/ public boolean isEnableWeChat() { return isEnableWeChat; } /** 是否启动QQ抢红包*/ public boolean isEnableQQ() { return isEnableQQ; } /** 是否启动TIM抢红包*/ public boolean isEnableTIM() { return isEnableTIM; } /** 微信抢红包模式 */ public int getWXMode(){ return wxMode; } /** 微信打开红包后延时时间 s*/ public float getWXDelayTime() { return wxDelayTime; } /** QQ抢红包模式 */ public int getQQMode(){ return qqMode; } /** QQ打开红包后延时时间 s*/ public float getQQDelayTime() { return qqDelayTime; } /** 微信打开红包后延时时间 ms*/ public int getQQOpenDelayTime() { return (int) (qqDelayTime * 1000); } /** 微信打开红包后延时时间 ms*/ public int getWeChatOpenDelayTime() { return (int) (wxDelayTime * 1000); } /** 微信智能返回*/ public boolean isSmartBackWeChat(){ return isSmartBackWeChat; } /** QQ智能返回*/ public boolean isSmartBackQQ(){ return isSmartBackQQ; } /** 锁屏自动抢 */ public boolean isLockScreenRob(){ return isLockScreenRob; } /** 声音 */ public boolean isVoice(){ return isVoice; } /** 震动 */ public boolean isVibration(){ return isVibration; } /** 夜间免打扰 */ public boolean isNightNotDisturb(){ return isNightNotDisturb; } /** QQ口令红包 */ public boolean isWordQQ(){ return isWordQQ; } }
A-Miracle/QiangHongBao
app/src/main/java/com/ctao/qhb/Config.java
2,134
// QQ抢模式
line_comment
zh-cn
package com.ctao.qhb; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.ctao.baselib.Global; import com.ctao.baselib.utils.LogUtils; import com.ctao.baselib.utils.SPUtils; /** * Created by A Miracle on 2017/8/17. */ public class Config { public static final String FILE_LOG = "log"; public static final String FILE_IMG = "img"; public static final String FILE_APK = "apk"; public static final String FILE_CACHE = "cache"; public static final String PACKAGE_NAME_WX = "com.tencent.mm"; public static final String PACKAGE_NAME_QQ = "com.tencent.mobileqq"; public static final String PACKAGE_NAME_TIM = "com.tencent.tim"; public static final String SP_LATEST_DATE = "SP_LATEST_DATE"; // 最新时间 public static final String SP_LATEST_CODE = "SP_UPDATE_PACKAGE"; // 最新包Code public static final String SP_AGREEMENT = "SP_AGREEMENT"; // 免责声明 public static final String SP_WX_MODE = "SP_WX_MODE"; // 微信抢模式 public static final String SP_WX_DELAY_TIME = "SP_WX_DELAY_TIME"; // 微信拆延时 public static final String SP_QQ_MODE = "SP_QQ_MODE"; // QQ <SUF> public static final String SP_QQ_DELAY_TIME = "SP_QQ_DELAY_TIME"; // QQ拆延时 public static final String SP_ENABLE_WE_CHAT = "platform_WeChat"; public static final String SP_ENABLE_QQ = "platform_QQ"; public static final String SP_ENABLE_TIM = "platform_TIM"; public static final String SP_SMART_BACK_WE_CHAT = "smart_back_wx"; // 微信智能返回 public static final String SP_SMART_BACK_QQ = "SP_SMART_BACK_QQ"; // QQ智能返回 public static final String SP_WORD_QQ = "qq_word_setting"; // QQ口令红包 public static final String SP_LOCK_SCREEN_ROB = "lock_screen_automatic_grab"; // 锁屏自动抢 public static final String SP_VOICE = "voice"; // 声音 public static final String SP_VIBRATION = "vibration"; // 震动 public static final String SP_NIGHT_NOT_DISTURB = "night_not_disturb"; // 夜间免打扰 public static final int WX_MODE_0 = 0;//自动抢 public static final int WX_MODE_1 = 1;//抢群聊, 包括自己发的; public static final int WX_MODE_2 = 2;//抢群聊, 不包括自己发的 public static final int WX_MODE_3 = 3;//通知手动抢 private boolean isEnableWeChat; private boolean isEnableQQ; private boolean isEnableTIM; private boolean isSmartBackWeChat, isSmartBackQQ; private boolean isLockScreenRob; private boolean isVoice; private boolean isVibration; private boolean isNightNotDisturb; private boolean isWordQQ; private int wxMode, qqMode; private float wxDelayTime, qqDelayTime; private Config(){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Global.getContext()); isEnableWeChat = sp.getBoolean(SP_ENABLE_WE_CHAT, true); isEnableQQ = sp.getBoolean(SP_ENABLE_QQ, true); isEnableTIM = sp.getBoolean(SP_ENABLE_TIM, true); isSmartBackWeChat = sp.getBoolean(SP_SMART_BACK_WE_CHAT, true); isSmartBackQQ = SPUtils.getBoolean(SP_SMART_BACK_QQ, false); isLockScreenRob = sp.getBoolean(SP_LOCK_SCREEN_ROB, false); isVoice = sp.getBoolean(SP_VOICE, true); isVibration = sp.getBoolean(SP_VIBRATION, true); isNightNotDisturb = sp.getBoolean(SP_NIGHT_NOT_DISTURB, false); wxMode = SPUtils.getInt(SP_WX_MODE, WX_MODE_0); wxDelayTime = SPUtils.getFloat(SP_WX_DELAY_TIME, 0); qqMode = SPUtils.getInt(SP_QQ_MODE, WX_MODE_0); qqDelayTime = SPUtils.getFloat(SP_QQ_DELAY_TIME, 0); isWordQQ = sp.getBoolean(SP_WORD_QQ, true); } private static class Single { static Config Instance = new Config(); } public static Config getInstance() { return Config.Single.Instance; } /** is Enable */ public void changeEnable(String key) { switch (key){ case SP_ENABLE_WE_CHAT: isEnableWeChat = !isEnableWeChat; break; case SP_ENABLE_QQ: isEnableQQ = !isEnableQQ; break; case SP_ENABLE_TIM: isEnableTIM = !isEnableTIM; break; } LogUtils.printOut(isEnableWeChat+", "+isEnableQQ+", "+isEnableTIM); } /** is SmartBack */ public void changeSmartBack(String key) { switch (key){ case SP_ENABLE_WE_CHAT: isSmartBackWeChat = !isSmartBackWeChat; break; case SP_ENABLE_QQ: isSmartBackQQ = !isSmartBackQQ; SPUtils.putObject(SP_SMART_BACK_QQ, isSmartBackQQ); // 要自己保存 break; case SP_ENABLE_TIM: break; } LogUtils.printOut(isSmartBackWeChat+", "+isSmartBackQQ); } public void changeWordQQ(){ isWordQQ = !isWordQQ; } /** is Global */ public void changeGlobal(String key){ switch (key){ case SP_LOCK_SCREEN_ROB: isLockScreenRob = !isLockScreenRob; break; case SP_VOICE: isVoice = !isVoice; break; case SP_VIBRATION: isVibration = !isVibration; break; case SP_NIGHT_NOT_DISTURB: isNightNotDisturb = !isNightNotDisturb; break; } } /** WX Mode */ public void setWXMode(int mode){ SPUtils.putObject(SP_WX_MODE, mode); wxMode = mode; } /** WX DelayTime */ public void setWXDelayTime(float delayTime){ SPUtils.putObject(SP_WX_DELAY_TIME, delayTime); wxDelayTime = delayTime; } /** WX Mode */ public void setQQMode(int mode){ SPUtils.putObject(SP_QQ_MODE, mode); qqMode = mode; } /** WX DelayTime */ public void setQQDelayTime(float delayTime){ SPUtils.putObject(SP_QQ_DELAY_TIME, delayTime); qqDelayTime = delayTime; } /** 是否启动微信抢红包*/ public boolean isEnableWeChat() { return isEnableWeChat; } /** 是否启动QQ抢红包*/ public boolean isEnableQQ() { return isEnableQQ; } /** 是否启动TIM抢红包*/ public boolean isEnableTIM() { return isEnableTIM; } /** 微信抢红包模式 */ public int getWXMode(){ return wxMode; } /** 微信打开红包后延时时间 s*/ public float getWXDelayTime() { return wxDelayTime; } /** QQ抢红包模式 */ public int getQQMode(){ return qqMode; } /** QQ打开红包后延时时间 s*/ public float getQQDelayTime() { return qqDelayTime; } /** 微信打开红包后延时时间 ms*/ public int getQQOpenDelayTime() { return (int) (qqDelayTime * 1000); } /** 微信打开红包后延时时间 ms*/ public int getWeChatOpenDelayTime() { return (int) (wxDelayTime * 1000); } /** 微信智能返回*/ public boolean isSmartBackWeChat(){ return isSmartBackWeChat; } /** QQ智能返回*/ public boolean isSmartBackQQ(){ return isSmartBackQQ; } /** 锁屏自动抢 */ public boolean isLockScreenRob(){ return isLockScreenRob; } /** 声音 */ public boolean isVoice(){ return isVoice; } /** 震动 */ public boolean isVibration(){ return isVibration; } /** 夜间免打扰 */ public boolean isNightNotDisturb(){ return isNightNotDisturb; } /** QQ口令红包 */ public boolean isWordQQ(){ return isWordQQ; } }
1
62831_5
package com.example.asasfans.ui.main.fragment; import static com.example.asasfans.ui.main.fragment.BiliVideoFragment.GET_DATA_SUCCESS; import static com.example.asasfans.ui.main.fragment.BiliVideoFragment.NETWORK_ERROR; import static com.example.asasfans.util.ViewUtilsKt.setMargin; import android.graphics.Rect; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.example.asasfans.AsApplication; import com.example.asasfans.R; import com.example.asasfans.data.ImageDataBean; import com.example.asasfans.ui.main.adapter.ImageAdapter; import com.google.android.material.appbar.AppBarLayout; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.scwang.smart.refresh.footer.ClassicsFooter; import com.scwang.smart.refresh.header.MaterialHeader; import com.scwang.smart.refresh.layout.api.RefreshLayout; import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener; import com.scwang.smart.refresh.layout.listener.OnRefreshListener; import java.io.IOException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * @author: akari * @date: 2022/3/8 * @description 图片加载页面 */ public class ImageFanArtFragment extends Fragment { public static int divider = 15; private ImageAdapter imageAdapter; private ImageUrl imageUrl; private View view; private List<ImageDataBean> imageRecyclerViewData = new ArrayList<>(); private RecyclerView recyclerView; private RefreshLayout refreshLayout; private String[] order = {"最新发布", "B站热门"}; private String[] date = {"无榜单", "日榜", "周榜", "月榜"}; private String[] tag = {"全部TAG", "A-SOUL", "向晚AvA", "贝拉Bella", "珈乐Carol", "嘉然Diana", "乃琳Queen", "贝贝珈", "乃贝", "嘉晚饭", "琳狼", "珈特琳", "果丹皮", "琳嘉女孩"}; private enum sort{ pubdateImage(3), biliHotImage(4); private int value = 3; sort(int value) { this.value = value; } public int value() { return this.value; } } private enum part{ allTag(0), asoul(1712619), ava(9221368), bella(195579), carol(17872743), diana(17520266), queen(17839311), bbj(18207897), nb(18843054), jwf(17895874), ll(21134102), jtl(18579605), gdp(1058727), ljnh(20064249); private int value = 0; part(int value) { this.value = value; } public int value() { return this.value; } } private final ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); private boolean isFirstOrder = true; private boolean isFirstDate = true; private boolean isFirstTag = true; public static ImageFanArtFragment newInstance() { Bundle args = new Bundle(); ImageFanArtFragment fragment = new ImageFanArtFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_fan_art_image, container, false); initImageAdapter(); initSpinner(); imageUrl = new ImageUrl(); refreshLayout = (RefreshLayout)view.findViewById(R.id.fan_art_image_refreshLayout); refreshLayout.setRefreshHeader(new MaterialHeader(getActivity()).setColorSchemeResources(R.color.tab_text_normal,R.color.cardWhite,R.color.cardWhite)); refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity())); refreshLayout.setDragRate(1f); refreshLayout.setEnableAutoLoadMore(true); refreshLayout.setHeaderTriggerRate((float) 0.3); refreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(@NonNull RefreshLayout refreshLayout) { imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); refreshLayout.finishRefresh(); } }); refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() { @Override public void onLoadMore(@NonNull RefreshLayout refreshLayout) { imageUrl.pageSelfAdd(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); refreshLayout.finishLoadMore(100/*,false*/); } }); imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); // cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); // new Thread(networkTask.setParam("https://api.asoul.cloud:8000/getPic?page=1&sort=3&part=0&rank=0&type=1")).start(); View emptyView = view.findViewById(R.id.emptyViewFanArt); CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AsApplication.Companion.getStatusBarHeight()); emptyView.setLayoutParams(layoutParams); AppBarLayout appBarLayout = view.findViewById(R.id.appBar); setMargin(appBarLayout, 0, AsApplication.Companion.getStatusBarHeight(),0,0); return view; } private void initImageAdapter(){ imageAdapter = new ImageAdapter(getActivity(), imageRecyclerViewData.size(), imageRecyclerViewData); recyclerView = view.findViewById(R.id.fan_art_image_recyclerview); setMargin(recyclerView, 0, 0, 0, AsApplication.Companion.getStatusBarHeight()); recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); RecyclerView.ItemDecoration gridItemDecoration = new RecyclerView.ItemDecoration() { @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, RecyclerView parent, @NonNull RecyclerView.State state) { StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams(); int spanIndex = layoutParams.getSpanIndex(); int position = parent.getChildAdapterPosition(view); outRect.bottom = divider; if (position == 0 || position == 1) { outRect.top = divider * 2; } else { outRect.top = 0; } if (spanIndex % 2 == 0) {//偶数项 outRect.left = divider; outRect.right = divider / 2; } else { outRect.left = divider / 2; outRect.right = divider; } } }; recyclerView.addItemDecoration(gridItemDecoration); recyclerView.setAdapter(imageAdapter); } private void initSpinner() { //声明一个下拉列表的数组适配器 ArrayAdapter<String> starAdapterOrder = new ArrayAdapter<String>(this.getContext(), R.layout.item_for_custom_spinner, order); ArrayAdapter<String> starAdapterDate = new ArrayAdapter<String>(this.getContext(), R.layout.item_for_custom_spinner, date); ArrayAdapter<String> starAdapterTag = new ArrayAdapter<String>(this.getContext(), R.layout.item_for_custom_spinner, tag); //设置数组适配器的布局样式 // starAdapter.setDropDownViewResource(R.layout.spinner_item_select); //从布局文件中获取下拉框 Spinner order = view.findViewById(R.id.fragment_fan_art_spinner_order); Spinner date = view.findViewById(R.id.fragment_fan_art_spinner_date); Spinner tag = view.findViewById(R.id.fragment_fan_art_spinner_tag); //设置下拉框的标题,不设置就没有难看的标题了 // sp.setPrompt("请选择配送方式"); //设置下拉框的数组适配器 order.setAdapter(starAdapterOrder); date.setAdapter(starAdapterDate); tag.setAdapter(starAdapterTag); //设置下拉框默认的显示第一项 order.setSelection(-1, true); date.setSelection(-1, true); tag.setSelection(-1, true); //给下拉框设置选择监听器,一旦用户选中某一项,就触发监听器的onItemSelected方法 order.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (isFirstOrder){ isFirstOrder = false; }else { switch (position){ case 0: imageUrl.setPage(1); imageUrl.setSort(sort.pubdateImage.value()); imageUrl.setCtime(0); break; case 1: imageUrl.setPage(1); imageUrl.setSort(sort.biliHotImage.value()); imageUrl.setCtime(0); break; } imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); date.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (isFirstDate){ isFirstDate = false; }else { switch (position) { case 0: imageUrl.setRank(0); imageUrl.setCtime(0); break; case 1: imageUrl.setRank(1); imageUrl.setCtime(System.currentTimeMillis()); break; case 2: imageUrl.setRank(2); imageUrl.setSort(sort.biliHotImage.value()); imageUrl.setCtime(0); break; case 3: imageUrl.setRank(3); imageUrl.setSort(sort.biliHotImage.value()); imageUrl.setCtime(0); break; } imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); tag.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (isFirstTag){ isFirstTag = false; }else { switch (position) { case 0: imageUrl.setPart(part.allTag.value()); break; case 1: imageUrl.setPart(part.asoul.value()); break; case 2: imageUrl.setPart(part.ava.value()); break; case 3: imageUrl.setPart(part.bella.value()); break; case 4: imageUrl.setPart(part.carol.value()); break; case 5: imageUrl.setPart(part.diana.value()); break; case 6: imageUrl.setPart(part.queen.value()); break; case 7: imageUrl.setPart(part.bbj.value()); break; case 8: imageUrl.setPart(part.nb.value()); break; case 9: imageUrl.setPart(part.jwf.value()); break; case 10: imageUrl.setPart(part.ll.value()); break; case 11: imageUrl.setPart(part.jtl.value()); break; case 12: imageUrl.setPart(part.gdp.value()); break; case 13: imageUrl.setPart(part.ljnh.value()); break; } imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); } private Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); Bundle data = msg.getData(); String val = data.getString("dataBean"); Gson gson = new GsonBuilder().serializeNulls().create(); switch (msg.what) { case GET_DATA_SUCCESS: if (val.equals("{\"code\": 1, \"message\": \"\\u6ca1\\u6709\\u66f4\\u591a\\u6570\\u636e\"}")){ imageUrl.pageSelfDecrement(); Toast.makeText(getActivity(),"后面没有了~",Toast.LENGTH_SHORT).show(); // Log.i("GET_DATA_SUCCESS", val); break; }else if (val.startsWith("[{\"dy_id\":")){ // Log.i("GET_DATA_SUCCESS:ImageDataBean", val); List<ImageDataBean> imageDataBean = gson.fromJson(val, new TypeToken<List<ImageDataBean>>() {}.getType()); // Log.i("GET_DATA_SUCCESS:ImageDataBean", val); int pastSize = imageRecyclerViewData.size(); imageRecyclerViewData.addAll(imageDataBean); if (imageRecyclerViewData.size() == 0){ Toast.makeText(getActivity(),"什么都没有了~",Toast.LENGTH_SHORT).show(); } imageAdapter.notifyItemRangeChanged(pastSize, imageDataBean.size()); }else { Log.i("GET_DATA_SUCCESS:ImageDataBean", val); Toast.makeText(getActivity(),"Server Error (500)",Toast.LENGTH_SHORT).show(); } break; case NETWORK_ERROR: // refreshLayout.finishLoadMore(false); break; } } }; private MyRunnable networkTask = new MyRunnable() { String url; @Override public MyRunnable setParam(String param) { url = param; return this; } @Override public void run() { Message msg = new Message(); Bundle data = new Bundle(); // TODO // 在这里进行 http request.网络请求相关操作 OkHttpClient client; client = new OkHttpClient.Builder().hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }).sslSocketFactory(createSSLSocketFactory(), new X509TrustManager() {//忽视https网站的安全证书 @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }).readTimeout(5, TimeUnit.SECONDS).build(); Request request = new Request.Builder().url(url) .get().build(); Call call = client.newCall(request); Response response = null; String tmp; try { response = call.execute(); tmp = response.body().string(); msg.what = GET_DATA_SUCCESS; data.putString("dataBean", tmp); // Log.i("ImageDataBean", tmp); } catch (IOException e) { e.printStackTrace(); // page--; handler.sendEmptyMessage(NETWORK_ERROR); } msg.setData(data); handler.sendMessage(msg); } }; private SSLSocketFactory createSSLSocketFactory() { SSLSocketFactory ssfFactory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom()); ssfFactory = sc.getSocketFactory(); } catch (Exception e) { } return ssfFactory; } public class TrustAllCerts implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } public interface MyRunnable extends Runnable { public MyRunnable setParam(String param); } public class ImageUrl{ private int page; private int sort; private int part; private int rank; private long ctime; private String url; public ImageUrl(){ this.page = 1; this.sort = 3; this.part = 0; this.rank = 0; this.ctime = 0; } public ImageUrl(int page, int sort, int part, int rank, int ctime) { this.page = page; this.sort = sort; this.part = part; this.rank = rank; this.ctime = ctime; } public String getUrl() { url = "https://api.asoul.cloud:8000/getPic?page=" + page + "&sort=" + sort + "&part=" + part + "&rank=" + rank + "&ctime=" + ctime; return url; } public void setUrl(String url) { this.url = url; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public void pageSelfAdd() { this.page++; } public void pageSelfDecrement() { this.page--; } public int getSort() { return sort; } public void setSort(int sort) { this.sort = sort; } public int getPart() { return part; } public void setPart(int part) { this.part = part; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public long getCtime() { return ctime; } public void setCtime(long ctime) { this.ctime = ctime; } } }
A-SoulFan/as-as-fans
app/src/main/java/com/example/asasfans/ui/main/fragment/ImageFanArtFragment.java
4,851
//声明一个下拉列表的数组适配器
line_comment
zh-cn
package com.example.asasfans.ui.main.fragment; import static com.example.asasfans.ui.main.fragment.BiliVideoFragment.GET_DATA_SUCCESS; import static com.example.asasfans.ui.main.fragment.BiliVideoFragment.NETWORK_ERROR; import static com.example.asasfans.util.ViewUtilsKt.setMargin; import android.graphics.Rect; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.example.asasfans.AsApplication; import com.example.asasfans.R; import com.example.asasfans.data.ImageDataBean; import com.example.asasfans.ui.main.adapter.ImageAdapter; import com.google.android.material.appbar.AppBarLayout; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.scwang.smart.refresh.footer.ClassicsFooter; import com.scwang.smart.refresh.header.MaterialHeader; import com.scwang.smart.refresh.layout.api.RefreshLayout; import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener; import com.scwang.smart.refresh.layout.listener.OnRefreshListener; import java.io.IOException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * @author: akari * @date: 2022/3/8 * @description 图片加载页面 */ public class ImageFanArtFragment extends Fragment { public static int divider = 15; private ImageAdapter imageAdapter; private ImageUrl imageUrl; private View view; private List<ImageDataBean> imageRecyclerViewData = new ArrayList<>(); private RecyclerView recyclerView; private RefreshLayout refreshLayout; private String[] order = {"最新发布", "B站热门"}; private String[] date = {"无榜单", "日榜", "周榜", "月榜"}; private String[] tag = {"全部TAG", "A-SOUL", "向晚AvA", "贝拉Bella", "珈乐Carol", "嘉然Diana", "乃琳Queen", "贝贝珈", "乃贝", "嘉晚饭", "琳狼", "珈特琳", "果丹皮", "琳嘉女孩"}; private enum sort{ pubdateImage(3), biliHotImage(4); private int value = 3; sort(int value) { this.value = value; } public int value() { return this.value; } } private enum part{ allTag(0), asoul(1712619), ava(9221368), bella(195579), carol(17872743), diana(17520266), queen(17839311), bbj(18207897), nb(18843054), jwf(17895874), ll(21134102), jtl(18579605), gdp(1058727), ljnh(20064249); private int value = 0; part(int value) { this.value = value; } public int value() { return this.value; } } private final ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); private boolean isFirstOrder = true; private boolean isFirstDate = true; private boolean isFirstTag = true; public static ImageFanArtFragment newInstance() { Bundle args = new Bundle(); ImageFanArtFragment fragment = new ImageFanArtFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_fan_art_image, container, false); initImageAdapter(); initSpinner(); imageUrl = new ImageUrl(); refreshLayout = (RefreshLayout)view.findViewById(R.id.fan_art_image_refreshLayout); refreshLayout.setRefreshHeader(new MaterialHeader(getActivity()).setColorSchemeResources(R.color.tab_text_normal,R.color.cardWhite,R.color.cardWhite)); refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity())); refreshLayout.setDragRate(1f); refreshLayout.setEnableAutoLoadMore(true); refreshLayout.setHeaderTriggerRate((float) 0.3); refreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh(@NonNull RefreshLayout refreshLayout) { imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); refreshLayout.finishRefresh(); } }); refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() { @Override public void onLoadMore(@NonNull RefreshLayout refreshLayout) { imageUrl.pageSelfAdd(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); refreshLayout.finishLoadMore(100/*,false*/); } }); imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); // cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); // new Thread(networkTask.setParam("https://api.asoul.cloud:8000/getPic?page=1&sort=3&part=0&rank=0&type=1")).start(); View emptyView = view.findViewById(R.id.emptyViewFanArt); CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AsApplication.Companion.getStatusBarHeight()); emptyView.setLayoutParams(layoutParams); AppBarLayout appBarLayout = view.findViewById(R.id.appBar); setMargin(appBarLayout, 0, AsApplication.Companion.getStatusBarHeight(),0,0); return view; } private void initImageAdapter(){ imageAdapter = new ImageAdapter(getActivity(), imageRecyclerViewData.size(), imageRecyclerViewData); recyclerView = view.findViewById(R.id.fan_art_image_recyclerview); setMargin(recyclerView, 0, 0, 0, AsApplication.Companion.getStatusBarHeight()); recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); RecyclerView.ItemDecoration gridItemDecoration = new RecyclerView.ItemDecoration() { @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, RecyclerView parent, @NonNull RecyclerView.State state) { StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams(); int spanIndex = layoutParams.getSpanIndex(); int position = parent.getChildAdapterPosition(view); outRect.bottom = divider; if (position == 0 || position == 1) { outRect.top = divider * 2; } else { outRect.top = 0; } if (spanIndex % 2 == 0) {//偶数项 outRect.left = divider; outRect.right = divider / 2; } else { outRect.left = divider / 2; outRect.right = divider; } } }; recyclerView.addItemDecoration(gridItemDecoration); recyclerView.setAdapter(imageAdapter); } private void initSpinner() { //声明 <SUF> ArrayAdapter<String> starAdapterOrder = new ArrayAdapter<String>(this.getContext(), R.layout.item_for_custom_spinner, order); ArrayAdapter<String> starAdapterDate = new ArrayAdapter<String>(this.getContext(), R.layout.item_for_custom_spinner, date); ArrayAdapter<String> starAdapterTag = new ArrayAdapter<String>(this.getContext(), R.layout.item_for_custom_spinner, tag); //设置数组适配器的布局样式 // starAdapter.setDropDownViewResource(R.layout.spinner_item_select); //从布局文件中获取下拉框 Spinner order = view.findViewById(R.id.fragment_fan_art_spinner_order); Spinner date = view.findViewById(R.id.fragment_fan_art_spinner_date); Spinner tag = view.findViewById(R.id.fragment_fan_art_spinner_tag); //设置下拉框的标题,不设置就没有难看的标题了 // sp.setPrompt("请选择配送方式"); //设置下拉框的数组适配器 order.setAdapter(starAdapterOrder); date.setAdapter(starAdapterDate); tag.setAdapter(starAdapterTag); //设置下拉框默认的显示第一项 order.setSelection(-1, true); date.setSelection(-1, true); tag.setSelection(-1, true); //给下拉框设置选择监听器,一旦用户选中某一项,就触发监听器的onItemSelected方法 order.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (isFirstOrder){ isFirstOrder = false; }else { switch (position){ case 0: imageUrl.setPage(1); imageUrl.setSort(sort.pubdateImage.value()); imageUrl.setCtime(0); break; case 1: imageUrl.setPage(1); imageUrl.setSort(sort.biliHotImage.value()); imageUrl.setCtime(0); break; } imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); date.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (isFirstDate){ isFirstDate = false; }else { switch (position) { case 0: imageUrl.setRank(0); imageUrl.setCtime(0); break; case 1: imageUrl.setRank(1); imageUrl.setCtime(System.currentTimeMillis()); break; case 2: imageUrl.setRank(2); imageUrl.setSort(sort.biliHotImage.value()); imageUrl.setCtime(0); break; case 3: imageUrl.setRank(3); imageUrl.setSort(sort.biliHotImage.value()); imageUrl.setCtime(0); break; } imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); tag.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (isFirstTag){ isFirstTag = false; }else { switch (position) { case 0: imageUrl.setPart(part.allTag.value()); break; case 1: imageUrl.setPart(part.asoul.value()); break; case 2: imageUrl.setPart(part.ava.value()); break; case 3: imageUrl.setPart(part.bella.value()); break; case 4: imageUrl.setPart(part.carol.value()); break; case 5: imageUrl.setPart(part.diana.value()); break; case 6: imageUrl.setPart(part.queen.value()); break; case 7: imageUrl.setPart(part.bbj.value()); break; case 8: imageUrl.setPart(part.nb.value()); break; case 9: imageUrl.setPart(part.jwf.value()); break; case 10: imageUrl.setPart(part.ll.value()); break; case 11: imageUrl.setPart(part.jtl.value()); break; case 12: imageUrl.setPart(part.gdp.value()); break; case 13: imageUrl.setPart(part.ljnh.value()); break; } imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); cachedThreadPool.execute(networkTask.setParam(imageUrl.getUrl())); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); imageRecyclerViewData.clear(); imageAdapter.notifyDataSetChanged(); } private Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); Bundle data = msg.getData(); String val = data.getString("dataBean"); Gson gson = new GsonBuilder().serializeNulls().create(); switch (msg.what) { case GET_DATA_SUCCESS: if (val.equals("{\"code\": 1, \"message\": \"\\u6ca1\\u6709\\u66f4\\u591a\\u6570\\u636e\"}")){ imageUrl.pageSelfDecrement(); Toast.makeText(getActivity(),"后面没有了~",Toast.LENGTH_SHORT).show(); // Log.i("GET_DATA_SUCCESS", val); break; }else if (val.startsWith("[{\"dy_id\":")){ // Log.i("GET_DATA_SUCCESS:ImageDataBean", val); List<ImageDataBean> imageDataBean = gson.fromJson(val, new TypeToken<List<ImageDataBean>>() {}.getType()); // Log.i("GET_DATA_SUCCESS:ImageDataBean", val); int pastSize = imageRecyclerViewData.size(); imageRecyclerViewData.addAll(imageDataBean); if (imageRecyclerViewData.size() == 0){ Toast.makeText(getActivity(),"什么都没有了~",Toast.LENGTH_SHORT).show(); } imageAdapter.notifyItemRangeChanged(pastSize, imageDataBean.size()); }else { Log.i("GET_DATA_SUCCESS:ImageDataBean", val); Toast.makeText(getActivity(),"Server Error (500)",Toast.LENGTH_SHORT).show(); } break; case NETWORK_ERROR: // refreshLayout.finishLoadMore(false); break; } } }; private MyRunnable networkTask = new MyRunnable() { String url; @Override public MyRunnable setParam(String param) { url = param; return this; } @Override public void run() { Message msg = new Message(); Bundle data = new Bundle(); // TODO // 在这里进行 http request.网络请求相关操作 OkHttpClient client; client = new OkHttpClient.Builder().hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }).sslSocketFactory(createSSLSocketFactory(), new X509TrustManager() {//忽视https网站的安全证书 @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }).readTimeout(5, TimeUnit.SECONDS).build(); Request request = new Request.Builder().url(url) .get().build(); Call call = client.newCall(request); Response response = null; String tmp; try { response = call.execute(); tmp = response.body().string(); msg.what = GET_DATA_SUCCESS; data.putString("dataBean", tmp); // Log.i("ImageDataBean", tmp); } catch (IOException e) { e.printStackTrace(); // page--; handler.sendEmptyMessage(NETWORK_ERROR); } msg.setData(data); handler.sendMessage(msg); } }; private SSLSocketFactory createSSLSocketFactory() { SSLSocketFactory ssfFactory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom()); ssfFactory = sc.getSocketFactory(); } catch (Exception e) { } return ssfFactory; } public class TrustAllCerts implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } public interface MyRunnable extends Runnable { public MyRunnable setParam(String param); } public class ImageUrl{ private int page; private int sort; private int part; private int rank; private long ctime; private String url; public ImageUrl(){ this.page = 1; this.sort = 3; this.part = 0; this.rank = 0; this.ctime = 0; } public ImageUrl(int page, int sort, int part, int rank, int ctime) { this.page = page; this.sort = sort; this.part = part; this.rank = rank; this.ctime = ctime; } public String getUrl() { url = "https://api.asoul.cloud:8000/getPic?page=" + page + "&sort=" + sort + "&part=" + part + "&rank=" + rank + "&ctime=" + ctime; return url; } public void setUrl(String url) { this.url = url; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public void pageSelfAdd() { this.page++; } public void pageSelfDecrement() { this.page--; } public int getSort() { return sort; } public void setSort(int sort) { this.sort = sort; } public int getPart() { return part; } public void setPart(int part) { this.part = part; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public long getCtime() { return ctime; } public void setCtime(long ctime) { this.ctime = ctime; } } }
0
65748_0
/** * [20] 表示数值的字符串 * * 题目: 实现一个函数用来判断字符串是否表示数值(包括整数和小数) * (字符串 "+100", "5e2", "-123", "3.1416" 和 "-1E-16" 都表示数值, * 但是 "12e", "1a3.14", "1.2.3", "+-5" 和 "12e+4.3" 都不是) * * 思路: 1. 将字符串分为三部分判断, A.Be|EC: A 为数值的整数部分, B 为数值的小数部分, C 为数值的指数部分. * 其中 A 和 C 都是整数(可以有正负号), 而 B 是一个无符号整数. * 2. 使用正则表达式进行匹配: [] : 字符集合 * () : 分组 * ? : 重复 0 ~ 1 次 * + : 重复 1 ~ n 次 * * : 重复 0 ~ n 次 * . : 任意字符 * \\. : 转义后的 . * \\d : 数字 */ class Solution { /** * 时间复杂度: O(n) * 空间复杂度: O(1) */ // because index is same one in this method, // so use global variable to storage index. private int index = 0; public boolean isNumber1(String s) { if (s == null) { return false; } // remove string's space which on both sides. s = s.trim(); boolean isNum = scanInteger(s); // if current char is '.', means the next part is decimal. if (index < s.length() && s.charAt(index) == '.') { index++; // .123 is legal; 123. is legal; 123.123 legal, // so use (scanUnsignedInteger(s) || isNum) to judge. // but can't write like this (isNum || scanUnsignedInteger(s))(important), // because if put isNum in the front. // when isNum is right scanUnsignedInteger(s) will not be execute, // means the part B will not calculate. isNum = scanUnsignedInteger(s) || isNum; } // if current char is 'e' or 'E', means the next part is exponent. if (index < s.length() && (s.charAt(index) == 'e' || s.charAt(index) == 'E')) { index++; // .e1 and e1 is illegal; 12e and 12e+5.4 is illegal. // so use (isNum && scanInteger(s)) to judge. isNum = isNum && scanInteger(s); } // isNum just can imply string have number as start, // only when string's all chars are used and isNum is right can imply string is number. return isNum && index == s.length(); } // take away unsigned integer part. private boolean scanUnsignedInteger(String s) { int i = index; while (index < s.length() && (s.charAt(index) >= '0' && s.charAt(index) <= '9')) { index++; } return index > i; } // take away signed integer part. private boolean scanInteger(String s) { if (index < s.length() && (s.charAt(index) == '-' || s.charAt(index) == '+')) { index++; } return scanUnsignedInteger(s); } /** * 时间复杂度: O() * 空间复杂度: O() */ public boolean isNumber2(String s) { if (s == null || s.length() == 0) { return false; } return s.matches("[+-]?\\d*(\\.\\d+)?([eE][+-]?\\d+)?"); } }
A11Might/codingInterview
code/offer20.java
950
/** * [20] 表示数值的字符串 * * 题目: 实现一个函数用来判断字符串是否表示数值(包括整数和小数) * (字符串 "+100", "5e2", "-123", "3.1416" 和 "-1E-16" 都表示数值, * 但是 "12e", "1a3.14", "1.2.3", "+-5" 和 "12e+4.3" 都不是) * * 思路: 1. 将字符串分为三部分判断, A.Be|EC: A 为数值的整数部分, B 为数值的小数部分, C 为数值的指数部分. * 其中 A 和 C 都是整数(可以有正负号), 而 B 是一个无符号整数. * 2. 使用正则表达式进行匹配: [] : 字符集合 * () : 分组 * ? : 重复 0 ~ 1 次 * + : 重复 1 ~ n 次 * * : 重复 0 ~ n 次 * . : 任意字符 * \\. : 转义后的 . * \\d : 数字 */
block_comment
zh-cn
/** * [20 <SUF>*/ class Solution { /** * 时间复杂度: O(n) * 空间复杂度: O(1) */ // because index is same one in this method, // so use global variable to storage index. private int index = 0; public boolean isNumber1(String s) { if (s == null) { return false; } // remove string's space which on both sides. s = s.trim(); boolean isNum = scanInteger(s); // if current char is '.', means the next part is decimal. if (index < s.length() && s.charAt(index) == '.') { index++; // .123 is legal; 123. is legal; 123.123 legal, // so use (scanUnsignedInteger(s) || isNum) to judge. // but can't write like this (isNum || scanUnsignedInteger(s))(important), // because if put isNum in the front. // when isNum is right scanUnsignedInteger(s) will not be execute, // means the part B will not calculate. isNum = scanUnsignedInteger(s) || isNum; } // if current char is 'e' or 'E', means the next part is exponent. if (index < s.length() && (s.charAt(index) == 'e' || s.charAt(index) == 'E')) { index++; // .e1 and e1 is illegal; 12e and 12e+5.4 is illegal. // so use (isNum && scanInteger(s)) to judge. isNum = isNum && scanInteger(s); } // isNum just can imply string have number as start, // only when string's all chars are used and isNum is right can imply string is number. return isNum && index == s.length(); } // take away unsigned integer part. private boolean scanUnsignedInteger(String s) { int i = index; while (index < s.length() && (s.charAt(index) >= '0' && s.charAt(index) <= '9')) { index++; } return index > i; } // take away signed integer part. private boolean scanInteger(String s) { if (index < s.length() && (s.charAt(index) == '-' || s.charAt(index) == '+')) { index++; } return scanUnsignedInteger(s); } /** * 时间复杂度: O() * 空间复杂度: O() */ public boolean isNumber2(String s) { if (s == null || s.length() == 0) { return false; } return s.matches("[+-]?\\d*(\\.\\d+)?([eE][+-]?\\d+)?"); } }
1
25769_2
/** * @author qhhu * @date 2019/11/15 - 9:34 * * [337] 打家劫舍 III * * 题目: 所有房屋排列类似二叉树, 返回在不触动劲爆的情况下, 小偷一晚上能够偷盗的最高金额 * (若两个直接相连的房子在同一天晚上被打劫, 房屋将自动报警) * * 难度: medium * * 思路: 树型dp, ans[0]代表`不偷盗`当前节点可以获得的最大金额, ans[1]代表`可以偷盗`当前节点可以过得的最大金额 * `可以偷盗`的意思是当前房屋可以偷盗也可以不偷盗 */ class Solution { /** * 时间复杂度: O(n) * 空间复杂度: O(n) (n为树的高度即递归栈的深度) */ public int rob(TreeNode root) { int[] ans = dfs(root); return Math.max(ans[0], ans[1]); } private int[] dfs(TreeNode root) { if (root == null) { return new int[] {0, 0}; } int[] left = dfs(root.left); int[] right = dfs(root.right); int[] ans = new int[2]; ans[0] = left[1] + right[1]; // 可以偷盗当前房屋的情况下, 可以选择不偷盗当前房屋 ans[1] = Math.max(ans[0], root.val + left[0] + right[0]); return ans; } }
A11Might/leetcode
src/lc337.java
437
// 可以偷盗当前房屋的情况下, 可以选择不偷盗当前房屋
line_comment
zh-cn
/** * @author qhhu * @date 2019/11/15 - 9:34 * * [337] 打家劫舍 III * * 题目: 所有房屋排列类似二叉树, 返回在不触动劲爆的情况下, 小偷一晚上能够偷盗的最高金额 * (若两个直接相连的房子在同一天晚上被打劫, 房屋将自动报警) * * 难度: medium * * 思路: 树型dp, ans[0]代表`不偷盗`当前节点可以获得的最大金额, ans[1]代表`可以偷盗`当前节点可以过得的最大金额 * `可以偷盗`的意思是当前房屋可以偷盗也可以不偷盗 */ class Solution { /** * 时间复杂度: O(n) * 空间复杂度: O(n) (n为树的高度即递归栈的深度) */ public int rob(TreeNode root) { int[] ans = dfs(root); return Math.max(ans[0], ans[1]); } private int[] dfs(TreeNode root) { if (root == null) { return new int[] {0, 0}; } int[] left = dfs(root.left); int[] right = dfs(root.right); int[] ans = new int[2]; ans[0] = left[1] + right[1]; // 可以 <SUF> ans[1] = Math.max(ans[0], root.val + left[0] + right[0]); return ans; } }
0
16448_23
package hook; import javassist.*; import java.io.IOException; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; public class SqlHook implements ClassFileTransformer { //声明一个Instrumentation 与ClassPool,设置为类中私有的变量 private Instrumentation inst; private ClassPool classPool; public SqlHook(Instrumentation inst) { this.inst = inst; this.classPool = new ClassPool(true); } //对sql语句进行执行的类进行Hook //通过查看百度Rasp源码,得知jdbc执行statement查询的类名为:com/mysql/jdbc/StatementImpl或com/mysql/cj/jdbc/StatementImpl //com.mysql.jdbc.Driver是mysql-connector-java 5中的,而com.mysql.cj.jdbc.Driver是mysql-connector-java 6中 //本此使用的是5 @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (className.equals("com/mysql/jdbc/StatementImpl")) { CtClass ctClass = null; try { //找到 StatementImpl 对应的字节码 ctClass = this.classPool.get("com.mysql.jdbc.StatementImpl"); //获取所有method /** * 需要Hook的代码 * String sql ="select flag from sql_rasp where sql_test=1 or 1=1"; * Statement stmt =conn.createStatement(); * * ResultSet rs =stmt.executeQuery(sql); */ // String src = "if ($1.substring(971).contains(\"or\"))" + // "{System.out.println(\"危险,检测到sql注入!\");" + // "System.out.println();"+ // "return null;}"; String src =" if($1.contains(\"=\")) {\n" + " System.out.println(\"RASP_ZERO目前只通过正则匹配sql注入攻击\" );\n" + " System.out.println(\"接收到sql语句\");\n" + " System.out.println(\"RASP_ZERO将执行监控\");\n" + " String pattern0 = \"^.*?=(.*)$\";\n" + " String replacement = \"$1\";\n" + " System.out.println();\n" + " String sql = $1.replaceAll(pattern0, replacement);\n" + " System.out.println(\"sql语句为:\" + sql);\n" + " if (sql!=null) {\n" + " String regex = \"(?i)\\\\b(select|order|by|information_schema|outfile|dumpfile|load_file|benchmark|pg_sleep|sleep|is_srvrolemember|updatexml|extractvalue|hex|char|chr|mid|ord|ascii|bin|or)\\\\b\";" + " java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);\n" + " java.util.regex.Matcher matcher = pattern.matcher(sql);\n" + " while (matcher.find()) {\n" + " System.out.println(\"检测到危险字符,RASP_ZERO将阻断此sql语句的执行\");\n" + " return null;\n" + " }\n" + " }\n" + " }"; // String src = "if ($1.contains(\"or\"))" + // "{System.out.println(\"危险,检测到sql注入!\");" + // "System.out.println();"+ // "return null;}"; // String src ="System.out.println(executeQuery.outParameterQuery.toString());"; // 获取所有method CtMethod[] methods = ctClass.getMethods(); for (CtMethod method : methods) { // 找到executeQuery方法,并插入拦截代码 if (method.getName().equals("executeQuery")) { method.insertBefore(src); break; } //方法信息 } // 获取字段 // method.insertBefore(src); // break; //字节码转换 classfileBuffer = ctClass.toBytecode(); } catch (NotFoundException | CannotCompileException | IOException e) { e.printStackTrace(); } } //如果判断存在恶意语句,则进行拦截 //使用javassist 对字节码进行增强(修改) return classfileBuffer; } }
A1AAAAAAAAAA1/RASP_DEMO
RASP_ZERO/src/main/java/hook/SqlHook.java
1,100
//字节码转换
line_comment
zh-cn
package hook; import javassist.*; import java.io.IOException; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; public class SqlHook implements ClassFileTransformer { //声明一个Instrumentation 与ClassPool,设置为类中私有的变量 private Instrumentation inst; private ClassPool classPool; public SqlHook(Instrumentation inst) { this.inst = inst; this.classPool = new ClassPool(true); } //对sql语句进行执行的类进行Hook //通过查看百度Rasp源码,得知jdbc执行statement查询的类名为:com/mysql/jdbc/StatementImpl或com/mysql/cj/jdbc/StatementImpl //com.mysql.jdbc.Driver是mysql-connector-java 5中的,而com.mysql.cj.jdbc.Driver是mysql-connector-java 6中 //本此使用的是5 @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (className.equals("com/mysql/jdbc/StatementImpl")) { CtClass ctClass = null; try { //找到 StatementImpl 对应的字节码 ctClass = this.classPool.get("com.mysql.jdbc.StatementImpl"); //获取所有method /** * 需要Hook的代码 * String sql ="select flag from sql_rasp where sql_test=1 or 1=1"; * Statement stmt =conn.createStatement(); * * ResultSet rs =stmt.executeQuery(sql); */ // String src = "if ($1.substring(971).contains(\"or\"))" + // "{System.out.println(\"危险,检测到sql注入!\");" + // "System.out.println();"+ // "return null;}"; String src =" if($1.contains(\"=\")) {\n" + " System.out.println(\"RASP_ZERO目前只通过正则匹配sql注入攻击\" );\n" + " System.out.println(\"接收到sql语句\");\n" + " System.out.println(\"RASP_ZERO将执行监控\");\n" + " String pattern0 = \"^.*?=(.*)$\";\n" + " String replacement = \"$1\";\n" + " System.out.println();\n" + " String sql = $1.replaceAll(pattern0, replacement);\n" + " System.out.println(\"sql语句为:\" + sql);\n" + " if (sql!=null) {\n" + " String regex = \"(?i)\\\\b(select|order|by|information_schema|outfile|dumpfile|load_file|benchmark|pg_sleep|sleep|is_srvrolemember|updatexml|extractvalue|hex|char|chr|mid|ord|ascii|bin|or)\\\\b\";" + " java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);\n" + " java.util.regex.Matcher matcher = pattern.matcher(sql);\n" + " while (matcher.find()) {\n" + " System.out.println(\"检测到危险字符,RASP_ZERO将阻断此sql语句的执行\");\n" + " return null;\n" + " }\n" + " }\n" + " }"; // String src = "if ($1.contains(\"or\"))" + // "{System.out.println(\"危险,检测到sql注入!\");" + // "System.out.println();"+ // "return null;}"; // String src ="System.out.println(executeQuery.outParameterQuery.toString());"; // 获取所有method CtMethod[] methods = ctClass.getMethods(); for (CtMethod method : methods) { // 找到executeQuery方法,并插入拦截代码 if (method.getName().equals("executeQuery")) { method.insertBefore(src); break; } //方法信息 } // 获取字段 // method.insertBefore(src); // break; //字节 <SUF> classfileBuffer = ctClass.toBytecode(); } catch (NotFoundException | CannotCompileException | IOException e) { e.printStackTrace(); } } //如果判断存在恶意语句,则进行拦截 //使用javassist 对字节码进行增强(修改) return classfileBuffer; } }
0
36273_6
package day03; //Assaultable 接口,接口类型的默认方法是public interface Assaultable { void attack(); } // Mobile 接口 interface Mobile { void move(); } // 抽象类实现Assaultable,Mobile,实现接口权限必须大于或等于接口权限 abstract class Weapon implements Mobile, Assaultable { public void attack() { }; public void move() { }; } // 定义3个类:Tank,Flighter,WarShip都继承自Weapon //分别用不同的方式实现 Weapon 类中的抽象方法。 class Tank extends Weapon { public void attack() { System.out.println("坦克攻击"); } public void move() { System.out.println("坦克移动"); } } class Flighter extends Weapon { public void attack() { System.out.println("飞机攻击"); } public void move() { System.out.println("飞机移动"); } } class WarShip extends Weapon { public void attack() { System.out.println("潜艇攻击"); } public void move() { System.out.println("潜艇移动"); } } // 写一个类Army,代表一支军队,这个类有一个属性是Weapon数组w(用来存储该军队所拥有的所有武器); // 该类还提供一个构造方法,在构造方法里通过传一个int类型的参数来限定该类所能拥有的最大武器数量 // 并用这一大小来初始化数组w。 // 该类还提供一个方法addWeapon(Weapon wa),表示把参数wa所代表的武器加入到数组w中。 // 在这个类中还定义两个方法attackAll()和moveAll(),让w数组中的所有武器攻击和移动。 class Army { private Weapon[] w; static int size; Army(int num) { this.w = new Weapon[num]; size = 0; } void addWeapon(Weapon wa){ if(size<w.length) w[size++]=wa; } void attackAll() { for (int i = 0; i < size; i++) { w[i].attack(); } } void moveAll() { for(int i=0;i<size;i++){ w[i].move(); } } } //主函数 class War { public static void main(String[] args) { Army army=new Army(3); army.addWeapon(new Tank()); army.addWeapon(new Flighter()); army.addWeapon(new WarShip()); army.attackAll(); army.moveAll(); } }
A203/Zhangyu123
day03/War.java
698
// 该类还提供一个构造方法,在构造方法里通过传一个int类型的参数来限定该类所能拥有的最大武器数量
line_comment
zh-cn
package day03; //Assaultable 接口,接口类型的默认方法是public interface Assaultable { void attack(); } // Mobile 接口 interface Mobile { void move(); } // 抽象类实现Assaultable,Mobile,实现接口权限必须大于或等于接口权限 abstract class Weapon implements Mobile, Assaultable { public void attack() { }; public void move() { }; } // 定义3个类:Tank,Flighter,WarShip都继承自Weapon //分别用不同的方式实现 Weapon 类中的抽象方法。 class Tank extends Weapon { public void attack() { System.out.println("坦克攻击"); } public void move() { System.out.println("坦克移动"); } } class Flighter extends Weapon { public void attack() { System.out.println("飞机攻击"); } public void move() { System.out.println("飞机移动"); } } class WarShip extends Weapon { public void attack() { System.out.println("潜艇攻击"); } public void move() { System.out.println("潜艇移动"); } } // 写一个类Army,代表一支军队,这个类有一个属性是Weapon数组w(用来存储该军队所拥有的所有武器); // 该类 <SUF> // 并用这一大小来初始化数组w。 // 该类还提供一个方法addWeapon(Weapon wa),表示把参数wa所代表的武器加入到数组w中。 // 在这个类中还定义两个方法attackAll()和moveAll(),让w数组中的所有武器攻击和移动。 class Army { private Weapon[] w; static int size; Army(int num) { this.w = new Weapon[num]; size = 0; } void addWeapon(Weapon wa){ if(size<w.length) w[size++]=wa; } void attackAll() { for (int i = 0; i < size; i++) { w[i].attack(); } } void moveAll() { for(int i=0;i<size;i++){ w[i].move(); } } } //主函数 class War { public static void main(String[] args) { Army army=new Army(3); army.addWeapon(new Tank()); army.addWeapon(new Flighter()); army.addWeapon(new WarShip()); army.attackAll(); army.moveAll(); } }
0
40201_0
package com.jinaihua.bmi3; import android.os.Bundle; import android.app.TabActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TabHost; import android.widget.TextView; public class TabhostActivity extends TabActivity { private EditText height = null; private EditText weight = null; private Button button = null; private TextView show = null; private TabHost host; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tabhost); host = getTabHost(); //创建标签页 TabHost.TabSpec s1 = host.newTabSpec("one"); //标签名 s1.setIndicator("关于BMI"); //内容 s1.setContent(R.id.aboutBMI); //将标签添加到tabHost组件 host.addTab(s1); TabHost.TabSpec s2 = host.newTabSpec("two"); s2.setIndicator("BMI测试"); s2.setContent(R.id.testBMI); host.addTab(s2); Button button = (Button) findViewById(R.id.BMIbutton); height = (EditText) findViewById(R.id.height); weight = (EditText) findViewById(R.id.weight); show = (TextView) findViewById(R.id.show); button.setOnClickListener(new View.OnClickListener() { double bmi = 0; public void onClick(View v) { double h = Double.valueOf(height.getText().toString()); double w = Double.valueOf(weight.getText().toString()); bmi = w / (h * h); double final_result = exchangeResult(bmi); if (bmi < 18.5) { show.setText("体重指数:" + final_result + " " + "偏轻"); } else if (bmi >= 18.5 && bmi < 24) { show.setText("体重指数:" + final_result + " " + "健康"); } else if (bmi >= 24 && bmi < 28) { show.setText("体重指数:" + final_result + " " + "偏重"); } else if (bmi >= 28 && bmi < 30) { show.setText("体重指数:" + final_result + " " + "轻度肥胖"); } else if (bmi >= 30 && bmi < 35) { show.setText("体重指数:" + final_result + " " + "中度肥胖"); } else if (bmi > 35) { show.setText("体重指数:" + final_result + " " + "重度肥胖"); } } }); } public double exchangeResult(double result) { double first = result * 100; double second = (int) first; double second_first; second_first = first - second; if (second_first > 0.5) { second++; } double jingo = second / 100; return jingo; } }
A203/jinaihua
BMI3/TabhostActivity.java
769
//创建标签页
line_comment
zh-cn
package com.jinaihua.bmi3; import android.os.Bundle; import android.app.TabActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TabHost; import android.widget.TextView; public class TabhostActivity extends TabActivity { private EditText height = null; private EditText weight = null; private Button button = null; private TextView show = null; private TabHost host; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tabhost); host = getTabHost(); //创建 <SUF> TabHost.TabSpec s1 = host.newTabSpec("one"); //标签名 s1.setIndicator("关于BMI"); //内容 s1.setContent(R.id.aboutBMI); //将标签添加到tabHost组件 host.addTab(s1); TabHost.TabSpec s2 = host.newTabSpec("two"); s2.setIndicator("BMI测试"); s2.setContent(R.id.testBMI); host.addTab(s2); Button button = (Button) findViewById(R.id.BMIbutton); height = (EditText) findViewById(R.id.height); weight = (EditText) findViewById(R.id.weight); show = (TextView) findViewById(R.id.show); button.setOnClickListener(new View.OnClickListener() { double bmi = 0; public void onClick(View v) { double h = Double.valueOf(height.getText().toString()); double w = Double.valueOf(weight.getText().toString()); bmi = w / (h * h); double final_result = exchangeResult(bmi); if (bmi < 18.5) { show.setText("体重指数:" + final_result + " " + "偏轻"); } else if (bmi >= 18.5 && bmi < 24) { show.setText("体重指数:" + final_result + " " + "健康"); } else if (bmi >= 24 && bmi < 28) { show.setText("体重指数:" + final_result + " " + "偏重"); } else if (bmi >= 28 && bmi < 30) { show.setText("体重指数:" + final_result + " " + "轻度肥胖"); } else if (bmi >= 30 && bmi < 35) { show.setText("体重指数:" + final_result + " " + "中度肥胖"); } else if (bmi > 35) { show.setText("体重指数:" + final_result + " " + "重度肥胖"); } } }); } public double exchangeResult(double result) { double first = result * 100; double second = (int) first; double second_first; second_first = first - second; if (second_first > 0.5) { second++; } double jingo = second / 100; return jingo; } }
0
36282_2
package 任务练习; public class All { //~~~~~~~~~~ public static void main(String[] args) { Army zuoye = new Army(5);// 定义一只军队,武器上限为6 Weapon tank = new Tank(); Weapon flighter = new Flighter(); Weapon warship = new WarShip(); // 定义三种武器。 zuoye.addWeapon(tank); zuoye.addWeapon(flighter); zuoye.addWeapon(warship); zuoye.moveAll(); zuoye.attackAll(); } }
A205/Liwu
Day03/任务练习/All.java
154
// 定义三种武器。
line_comment
zh-cn
package 任务练习; public class All { //~~~~~~~~~~ public static void main(String[] args) { Army zuoye = new Army(5);// 定义一只军队,武器上限为6 Weapon tank = new Tank(); Weapon flighter = new Flighter(); Weapon warship = new WarShip(); // 定义 <SUF> zuoye.addWeapon(tank); zuoye.addWeapon(flighter); zuoye.addWeapon(warship); zuoye.moveAll(); zuoye.attackAll(); } }
0
47372_9
package com.hfut.caimengqi; public class Person { String name; int age; String address; //无参默认构造方法 Person(){ System.out.println("Person的默认构造方法被调用……"); } //有参构造方法 // Person(String n,dint a,String add){ // name =n; // age=a; // address=add; // } 会报错,一般情况下,当我们设计类时,应该为类显示的添加无参构造方法 //自我介绍 void introduce(){ System.out.println("大家好,我叫"+name+",今年"+age+"岁了,我在"+address); } public static void main(String[] args){ Person person =new Person();//实例化一个person对象 person.name ="张三"; person.age =20; person.address ="USA"; person.introduce(); } } //当没有构造方法时,系统会自动生成一个默认构造方法 //构造方法是一种比较烦特殊的方法 //没有发挥类型,方法名和类同名
A205/caimengqi
Day3/Person.java
287
//当没有构造方法时,系统会自动生成一个默认构造方法
line_comment
zh-cn
package com.hfut.caimengqi; public class Person { String name; int age; String address; //无参默认构造方法 Person(){ System.out.println("Person的默认构造方法被调用……"); } //有参构造方法 // Person(String n,dint a,String add){ // name =n; // age=a; // address=add; // } 会报错,一般情况下,当我们设计类时,应该为类显示的添加无参构造方法 //自我介绍 void introduce(){ System.out.println("大家好,我叫"+name+",今年"+age+"岁了,我在"+address); } public static void main(String[] args){ Person person =new Person();//实例化一个person对象 person.name ="张三"; person.age =20; person.address ="USA"; person.introduce(); } } //当没 <SUF> //构造方法是一种比较烦特殊的方法 //没有发挥类型,方法名和类同名
0
15276_13
package daythree; //导入包,加*表示不导入所有,而是根据需要去导入。 import daythree.boom.*; public class Day3 { public static void main(String[] args){ Phone p=new Phone(); p.name="note"; p.brand="爆米花"; p.price=78; System.out.println("手机名称 "+p.name); System.out.println("手机品牌:"+p.brand); System.out.println("手机价格"+p.price); p.sendMsg(); //Person Person ps=new Person("zhangsan",56,"lunar Street"); ps.introduce(); //Fruit Fruit apple=new Fruit("苹果",13,"兰州王宏农场"); apple.harvest(); //初始化块 Init example=new Init(); //使用另一个包中的类:包名.类名 daythree.pktest.PkTest table=new daythree.pktest.PkTest(); //访问修饰符的作用 daythree.pktest.Access acce=new daythree.pktest.Access(); acce.say_1(); //包的导入实验 Boom bo=new Boom(); //类继承的方法重写 Tiger tig=new Tiger(); tig.sleep("趴着睡"); System.out.println(); //动态绑定 Animal a=new Animal(); a.sleep("趴着睡"); Tiger t=new Tiger(); t.sleep("趴着睡"); Animal g=new Tiger(); g.sleep(g.name); System.out.println("父类引用指向子类实例,得出的对象的属性:"+g.name); g.sleep("diaozheshui"); } } //Phone 类 class Phone{ //属性 String name; String brand; int price; //行为 void call(){ System.out.println("打电话"); } void sendMsg(){ System.out.println("发短信"); } } class Person{ String name; int age; String address; void introduce(){ System.out.println("大家好,我是"+name+",今年"+age+"岁"+",住在"+address); } Person(String name, int age){ this.name=name; this.age=age; } //构造方法(无参数默认) Person (){ System.out.println("构造函数被调用"); } //有参数构造函数 Person(String nam,int ag, String add){ this(nam,ag); address=add; } } //演示this指针的使用 class Fruit{ String name; int price; String farmName; //构造函数 Fruit(){ } Fruit(String name,int price, String farmName){ this.name=name; this.price=price; this.farmName=farmName; } void harvest(){ System.out.println("今年收获了599吨水果"); } } //演示初始化块 class Init{ int num; Init(){ num=5; System.out.println("构造函数被调用"); } //初始化块 { System.out.println("初始化块被调用"); } } //类继承的方法重写 class Animal{ String name="动物"; String sleepPose; Animal(){ } Animal(String name){ this.name = name; } public void sleep(String sleepPose){ this.sleepPose=sleepPose; System.out.println(this.name+"的睡觉姿势谁也不知道"); } } class Tiger extends Animal { String name="老虎"; String sleepPose; Tiger(){ } Tiger(String name){ this.name=name; } public void sleep(String sleepPose){ this.sleepPose=sleepPose; System.out.println(this.name+"是"+sleepPose); //System.out.println(this.name); } } //抽象类 //多态:父类的某一个类型在不同的子类中有不同的形态 abstract class Worker{ String name; int id; public abstract void goToCmy(); public abstract void goToHom(); public abstract void getPayment(); } class Singer extends Worker{ public void goToCmy(){ } public void goToHom(){ } public void getPayment(){ } }
A205/chuchenggui
Day3.java
1,201
//构造函数
line_comment
zh-cn
package daythree; //导入包,加*表示不导入所有,而是根据需要去导入。 import daythree.boom.*; public class Day3 { public static void main(String[] args){ Phone p=new Phone(); p.name="note"; p.brand="爆米花"; p.price=78; System.out.println("手机名称 "+p.name); System.out.println("手机品牌:"+p.brand); System.out.println("手机价格"+p.price); p.sendMsg(); //Person Person ps=new Person("zhangsan",56,"lunar Street"); ps.introduce(); //Fruit Fruit apple=new Fruit("苹果",13,"兰州王宏农场"); apple.harvest(); //初始化块 Init example=new Init(); //使用另一个包中的类:包名.类名 daythree.pktest.PkTest table=new daythree.pktest.PkTest(); //访问修饰符的作用 daythree.pktest.Access acce=new daythree.pktest.Access(); acce.say_1(); //包的导入实验 Boom bo=new Boom(); //类继承的方法重写 Tiger tig=new Tiger(); tig.sleep("趴着睡"); System.out.println(); //动态绑定 Animal a=new Animal(); a.sleep("趴着睡"); Tiger t=new Tiger(); t.sleep("趴着睡"); Animal g=new Tiger(); g.sleep(g.name); System.out.println("父类引用指向子类实例,得出的对象的属性:"+g.name); g.sleep("diaozheshui"); } } //Phone 类 class Phone{ //属性 String name; String brand; int price; //行为 void call(){ System.out.println("打电话"); } void sendMsg(){ System.out.println("发短信"); } } class Person{ String name; int age; String address; void introduce(){ System.out.println("大家好,我是"+name+",今年"+age+"岁"+",住在"+address); } Person(String name, int age){ this.name=name; this.age=age; } //构造方法(无参数默认) Person (){ System.out.println("构造函数被调用"); } //有参数构造函数 Person(String nam,int ag, String add){ this(nam,ag); address=add; } } //演示this指针的使用 class Fruit{ String name; int price; String farmName; //构造 <SUF> Fruit(){ } Fruit(String name,int price, String farmName){ this.name=name; this.price=price; this.farmName=farmName; } void harvest(){ System.out.println("今年收获了599吨水果"); } } //演示初始化块 class Init{ int num; Init(){ num=5; System.out.println("构造函数被调用"); } //初始化块 { System.out.println("初始化块被调用"); } } //类继承的方法重写 class Animal{ String name="动物"; String sleepPose; Animal(){ } Animal(String name){ this.name = name; } public void sleep(String sleepPose){ this.sleepPose=sleepPose; System.out.println(this.name+"的睡觉姿势谁也不知道"); } } class Tiger extends Animal { String name="老虎"; String sleepPose; Tiger(){ } Tiger(String name){ this.name=name; } public void sleep(String sleepPose){ this.sleepPose=sleepPose; System.out.println(this.name+"是"+sleepPose); //System.out.println(this.name); } } //抽象类 //多态:父类的某一个类型在不同的子类中有不同的形态 abstract class Worker{ String name; int id; public abstract void goToCmy(); public abstract void goToHom(); public abstract void getPayment(); } class Singer extends Worker{ public void goToCmy(){ } public void goToHom(){ } public void getPayment(){ } }
0
60631_0
//练习:三角形图案2 package ifandswith; import java.util.Scanner; public class exe04 { public static void main(String[] args){ System.out.println("请输入行数"); Scanner scanner=new Scanner(System.in); int num=scanner.nextInt(); for(int i=1;i<=num;i++){ for(int j=1;j<=num-i;j++){ System.out.print(" "); } for(int j=1;j<=i*2-1;j++){ System.out.print("*"); }System.out.println(); } } }
A205/lixue
day02/课堂练习/exe04.java
160
//练习:三角形图案2
line_comment
zh-cn
//练习 <SUF> package ifandswith; import java.util.Scanner; public class exe04 { public static void main(String[] args){ System.out.println("请输入行数"); Scanner scanner=new Scanner(System.in); int num=scanner.nextInt(); for(int i=1;i<=num;i++){ for(int j=1;j<=num-i;j++){ System.out.print(" "); } for(int j=1;j<=i*2-1;j++){ System.out.print("*"); }System.out.println(); } } }
1
25679_2
package com.buzz.utils; import com.buzz.entity.hotelorders; import com.buzz.service.hotelOrdersService; import lombok.extern.log4j.Log4j2; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.List; /** * @Author: jyh * @Date: 2018/10/20 10:58 * 定时任务 */ @Component @Log4j2 public class timedTask { @Resource hotelOrdersService hotelOrdersService; /** * 订单超时,修改状态 * @Scheduled:将方法注册为定时任务 Scheduled:安排 * fixedRate:上一次启动时间点之后x毫秒执行一次 fixedRate:固定汇率 */ @Scheduled(fixedRate=1000) public void updateOrderState(){ Long currentMillis= System.currentTimeMillis(); // List<hotelorders> hotelordersList=hotelOrdersService.hotelordersList(); for (hotelorders h:hotelordersList) { if(h.getState().equals("待支付")){ Long orderMillis=h.getSubTime().getTime()+1*60*1000; if(currentMillis>=orderMillis){ //订单超时 hotelOrdersService.byHotelOrderIdUpdateState(h.getOrderId(),"超时未支付"); } } } } }
AAAJYH/buzz
src/main/java/com/buzz/utils/timedTask.java
342
//订单超时
line_comment
zh-cn
package com.buzz.utils; import com.buzz.entity.hotelorders; import com.buzz.service.hotelOrdersService; import lombok.extern.log4j.Log4j2; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.List; /** * @Author: jyh * @Date: 2018/10/20 10:58 * 定时任务 */ @Component @Log4j2 public class timedTask { @Resource hotelOrdersService hotelOrdersService; /** * 订单超时,修改状态 * @Scheduled:将方法注册为定时任务 Scheduled:安排 * fixedRate:上一次启动时间点之后x毫秒执行一次 fixedRate:固定汇率 */ @Scheduled(fixedRate=1000) public void updateOrderState(){ Long currentMillis= System.currentTimeMillis(); // List<hotelorders> hotelordersList=hotelOrdersService.hotelordersList(); for (hotelorders h:hotelordersList) { if(h.getState().equals("待支付")){ Long orderMillis=h.getSubTime().getTime()+1*60*1000; if(currentMillis>=orderMillis){ //订单 <SUF> hotelOrdersService.byHotelOrderIdUpdateState(h.getOrderId(),"超时未支付"); } } } } }
0
58897_16
package com.example.anan.AAChartCore.ChartsDemo.chartcomposer; import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartModel; import com.github.AAChartModel.AAChartCore.AAChartCreator.AASeriesElement; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartAnimationType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartFontWeightType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartLineDashStyleType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartStackingType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartVerticalAlignType; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAAnimation; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAChart; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AADataLabels; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAHover; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AALabels; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAOptions; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPlotOptions; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPoint; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPointEvents; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AASelect; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AASeries; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStates; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStyle; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATitle; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATooltip; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAXAxis; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAYAxis; import com.github.AAChartModel.AAChartCore.AATools.AAColor; import com.github.AAChartModel.AAChartCore.AATools.AAGradientColor; import com.github.AAChartModel.AAChartCore.AATools.AALinearGradientDirection; import java.util.Map; public class JSFunctionForAAOptionsComposer { //https://github.com/AAChartModel/AAChartKit/issues/780 public static AAOptions customDoubleXAxesChart() { Map<String, Object> gradientColorDic1 = AAGradientColor.linearGradient( AALinearGradientDirection.ToTop, "#7052f4", "#00b0ff"//颜色字符串设置支持十六进制类型和 rgba 类型 ); Map<String, Object> gradientColorDic2 = AAGradientColor.linearGradient( AALinearGradientDirection.ToTop, "#EF71FF", "#4740C8"//颜色字符串设置支持十六进制类型和 rgba 类型 ); AAChart aaChart = new AAChart() .type(AAChartType.Bar); AATitle aaTitle = new AATitle() .text("2015 年德国人口金字塔") .style(new AAStyle() .color("#000000") .fontSize(12.0)); String[] aaCategories = new String[]{"0-4", "5-9", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40-44", "45-49", "50-54", "55-59", "60-64", "65-69", "70-74", "75-79", "80-84", "85-89", "90-94", "95-99", "100 + "}; AAXAxis aaXAxis1 = new AAXAxis() .reversed(true) .categories(aaCategories) .labels(new AALabels() .step(1)) ; AAXAxis aaXAxis2 = new AAXAxis() .reversed(true) .opposite(true) .categories(aaCategories) .linkedTo(0) .labels(new AALabels() .step(1)); AAYAxis aaYAxis = new AAYAxis() .gridLineWidth(0)// Y 轴网格线宽度 .title(new AATitle() .text(""))//Y 轴标题 .labels(new AALabels() .formatter("function () {\n" + " return (Math.abs(this.value) / 1000000) + 'M';\n" + "}")) .min(-4000000) .max(4000000); AAPlotOptions aaPlotOptions = new AAPlotOptions() .series(new AASeries() .animation(new AAAnimation() .duration(800) .easing(AAChartAnimationType.Bounce) ) .stacking(AAChartStackingType.Normal)); AATooltip aaTooltip = new AATooltip() .enabled(true) .shared(false) .formatter("function () {\n" + " return '<b>' + this.series.name + ', age ' + this.point.category + '</b><br/>' +\n" + " '人口: ' + Highcharts.numberFormat(Math.abs(this.point.y), 0);\n" + "}"); AASeriesElement aaSeriesElement1 = new AASeriesElement() .name("Men") .color(gradientColorDic1) .data(new Object[]{-1746181, -1884428, -2089758, -2222362, -2537431, -2507081, -2443179, -2664537, -3556505, -3680231, -3143062, -2721122, -2229181, -2227768, -2176300, -1329968, -836804, -354784, -90569, -28367, -3878}); AASeriesElement aaSeriesElement2 = new AASeriesElement() .name("Women") .color(gradientColorDic2) .data(new Object[]{1656154, 1787564, 1981671, 2108575, 2403438, 2366003, 2301402, 2519874, 3360596, 3493473, 3050775, 2759560, 2304444, 2426504, 2568938, 1785638, 1447162, 1005011, 330870, 130632, 21208}); return new AAOptions() .chart(aaChart) .title(aaTitle) .xAxisArray(new AAXAxis[]{aaXAxis1,aaXAxis2}) .yAxis(aaYAxis) .plotOptions(aaPlotOptions) .tooltip(aaTooltip) .series(new Object[]{aaSeriesElement1,aaSeriesElement2}); } //https://github.com/AAChartModel/AAChartKit/issues/967 public static AAOptions disableColumnChartUnselectEventEffectBySeriesPointEventClickFunction() { AAChartModel aaChartModel = new AAChartModel() .chartType(AAChartType.Bar) .title("Custom Bar Chart select color") .yAxisReversed(true) .xAxisReversed(true) .series(new AASeriesElement[]{ new AASeriesElement() .name("ElementOne") .data(new Object[]{211,183,157,133,111,91,73,57,43,31,21,13,7,3}) .allowPointSelect(true) .states(new AAStates() .hover(new AAHover() .color(AAColor.Yellow)) .select(new AASelect() .color(AAColor.Red)) ) }); AAOptions aaOptions = aaChartModel.aa_toAAOptions(); AAPoint aaPoint = new AAPoint() .events(new AAPointEvents() .click("function () {\n" + " if (this.selected == true) {\n" + " this.selected = false;\n" + " }\n" + " return;\n" + " }")); aaOptions.plotOptions.series .point(aaPoint); return aaOptions; } // Refer to the issue https://github.com/AAChartModel/AAChartKit/issues/589 public static AAOptions customizeEveryDataLabelSinglelyByDataLabelsFormatter() { AAChartModel aaChartModel = new AAChartModel() .chartType(AAChartType.Areaspline)//图表类型 .dataLabelsEnabled(true) .tooltipEnabled(false) .colorsTheme(new Object[]{AAGradientColor.FizzyPeach}) .markerRadius(0) .legendEnabled(false) .categories(new String[]{"美国🇺🇸","欧洲🇪🇺","中国🇨🇳","日本🇯🇵","韩国🇰🇷","越南🇻🇳","中国香港🇭🇰",}) .series(new AASeriesElement[]{ new AASeriesElement() .data(new Object[]{7.0, 6.9, 2.5, 14.5, 18.2, 21.5, 5.2}), }); AAOptions aaOptions = aaChartModel.aa_toAAOptions(); aaOptions.yAxis.gridLineDashStyle = AAChartLineDashStyleType.LongDash;//设置Y轴的网格线样式为 AAChartLineDashStyleType.LongDash String[] unitArr ={"美元", "欧元", "人民币", "日元", "韩元", "越南盾", "港币", }; String unitJSArrStr = javaScriptArrayStringWithJavaArray(unitArr); String dataLabelsFormatter = String.format("function () {\n" + " return this.y + %s[this.point.index]; \n" + //单组 series 图表, 获取选中的点的索引是 this.point.index ,多组并且共享提示框,则是this.points[0].index " }", unitJSArrStr); AADataLabels aaDatalabels = aaOptions.plotOptions.series.dataLabels; aaDatalabels .style(AAStyle.style(AAColor.Red, 10, AAChartFontWeightType.Bold, "1px 1px contrast")) .formatter(dataLabelsFormatter) .backgroundColor(AAColor.White)// white color .borderColor(AAColor.Red)// red color .borderRadius(1.5) .borderWidth(1.3) .x(3).y(-20) .verticalAlign(AAChartVerticalAlignType.Middle); return aaOptions; } //https://github.com/AAChartModel/AAChartKit-Swift/issues/404 public static AAOptions configureColorfulDataLabelsForPieChart() { AAOptions aaOptions = new AAOptions() .title(new AATitle() .text("Colorful DataLabels For Pie Chart")) .colors(new Object[]{ "#0c9674", "#7dffc0", "#ff3333", "#facd32", "#ffffa0", "#EA007B", "#fe117c", "#ffc069", "#06caf4", "#7dffc0" }) .series(new AASeriesElement[]{ new AASeriesElement() .type(AAChartType.Pie) .name("语言热度值") .innerSize("20%")//内部圆环半径大小占比 .borderWidth(0)//描边的宽度 .allowPointSelect(true)//是否允许在点击数据点标记(扇形图点击选中的块发生位移) .states(new AAStates() .hover(new AAHover() .enabled(false)))//禁用点击区块之后出现的半透明遮罩层 .dataLabels(new AADataLabels() .allowOverlap(true)//允许字符重叠 .useHTML(true) .formatter("function () {\n" + " const point = this.point;\n" + " return '<span style=\\\"color: ' + point.color + '\\\">' +\n" + " point.name + ': ' + point.y + '%</span>';\n" + " }")) .data(new Object[][]{ {"Firefox", 3336.2}, {"IE", 26.8}, {"Chrome", 666.8}, {"Safari", 88.5}, {"Opera", 46.0}, {"Others", 223.0}, {"Firefox", 3336.2}, {"IE", 26.8}, {"Chrome", 666.8}, {"Safari", 88.5}, {"Opera", 46.0}, {"Others", 223.0}, }) }); return aaOptions; } private static String javaScriptArrayStringWithJavaArray(Object[] javaArray) { StringBuilder originalJsArrStr = new StringBuilder(); for (Object element : javaArray) { originalJsArrStr.append("'").append(element.toString()).append("',"); } return "[" + originalJsArrStr + "]"; } }
AAChartModel/AAChartCore
app/src/main/java/com/example/anan/AAChartCore/ChartsDemo/chartcomposer/JSFunctionForAAOptionsComposer.java
3,490
//禁用点击区块之后出现的半透明遮罩层
line_comment
zh-cn
package com.example.anan.AAChartCore.ChartsDemo.chartcomposer; import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartModel; import com.github.AAChartModel.AAChartCore.AAChartCreator.AASeriesElement; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartAnimationType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartFontWeightType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartLineDashStyleType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartStackingType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartType; import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartVerticalAlignType; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAAnimation; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAChart; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AADataLabels; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAHover; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AALabels; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAOptions; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPlotOptions; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPoint; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPointEvents; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AASelect; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AASeries; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStates; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStyle; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATitle; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATooltip; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAXAxis; import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAYAxis; import com.github.AAChartModel.AAChartCore.AATools.AAColor; import com.github.AAChartModel.AAChartCore.AATools.AAGradientColor; import com.github.AAChartModel.AAChartCore.AATools.AALinearGradientDirection; import java.util.Map; public class JSFunctionForAAOptionsComposer { //https://github.com/AAChartModel/AAChartKit/issues/780 public static AAOptions customDoubleXAxesChart() { Map<String, Object> gradientColorDic1 = AAGradientColor.linearGradient( AALinearGradientDirection.ToTop, "#7052f4", "#00b0ff"//颜色字符串设置支持十六进制类型和 rgba 类型 ); Map<String, Object> gradientColorDic2 = AAGradientColor.linearGradient( AALinearGradientDirection.ToTop, "#EF71FF", "#4740C8"//颜色字符串设置支持十六进制类型和 rgba 类型 ); AAChart aaChart = new AAChart() .type(AAChartType.Bar); AATitle aaTitle = new AATitle() .text("2015 年德国人口金字塔") .style(new AAStyle() .color("#000000") .fontSize(12.0)); String[] aaCategories = new String[]{"0-4", "5-9", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40-44", "45-49", "50-54", "55-59", "60-64", "65-69", "70-74", "75-79", "80-84", "85-89", "90-94", "95-99", "100 + "}; AAXAxis aaXAxis1 = new AAXAxis() .reversed(true) .categories(aaCategories) .labels(new AALabels() .step(1)) ; AAXAxis aaXAxis2 = new AAXAxis() .reversed(true) .opposite(true) .categories(aaCategories) .linkedTo(0) .labels(new AALabels() .step(1)); AAYAxis aaYAxis = new AAYAxis() .gridLineWidth(0)// Y 轴网格线宽度 .title(new AATitle() .text(""))//Y 轴标题 .labels(new AALabels() .formatter("function () {\n" + " return (Math.abs(this.value) / 1000000) + 'M';\n" + "}")) .min(-4000000) .max(4000000); AAPlotOptions aaPlotOptions = new AAPlotOptions() .series(new AASeries() .animation(new AAAnimation() .duration(800) .easing(AAChartAnimationType.Bounce) ) .stacking(AAChartStackingType.Normal)); AATooltip aaTooltip = new AATooltip() .enabled(true) .shared(false) .formatter("function () {\n" + " return '<b>' + this.series.name + ', age ' + this.point.category + '</b><br/>' +\n" + " '人口: ' + Highcharts.numberFormat(Math.abs(this.point.y), 0);\n" + "}"); AASeriesElement aaSeriesElement1 = new AASeriesElement() .name("Men") .color(gradientColorDic1) .data(new Object[]{-1746181, -1884428, -2089758, -2222362, -2537431, -2507081, -2443179, -2664537, -3556505, -3680231, -3143062, -2721122, -2229181, -2227768, -2176300, -1329968, -836804, -354784, -90569, -28367, -3878}); AASeriesElement aaSeriesElement2 = new AASeriesElement() .name("Women") .color(gradientColorDic2) .data(new Object[]{1656154, 1787564, 1981671, 2108575, 2403438, 2366003, 2301402, 2519874, 3360596, 3493473, 3050775, 2759560, 2304444, 2426504, 2568938, 1785638, 1447162, 1005011, 330870, 130632, 21208}); return new AAOptions() .chart(aaChart) .title(aaTitle) .xAxisArray(new AAXAxis[]{aaXAxis1,aaXAxis2}) .yAxis(aaYAxis) .plotOptions(aaPlotOptions) .tooltip(aaTooltip) .series(new Object[]{aaSeriesElement1,aaSeriesElement2}); } //https://github.com/AAChartModel/AAChartKit/issues/967 public static AAOptions disableColumnChartUnselectEventEffectBySeriesPointEventClickFunction() { AAChartModel aaChartModel = new AAChartModel() .chartType(AAChartType.Bar) .title("Custom Bar Chart select color") .yAxisReversed(true) .xAxisReversed(true) .series(new AASeriesElement[]{ new AASeriesElement() .name("ElementOne") .data(new Object[]{211,183,157,133,111,91,73,57,43,31,21,13,7,3}) .allowPointSelect(true) .states(new AAStates() .hover(new AAHover() .color(AAColor.Yellow)) .select(new AASelect() .color(AAColor.Red)) ) }); AAOptions aaOptions = aaChartModel.aa_toAAOptions(); AAPoint aaPoint = new AAPoint() .events(new AAPointEvents() .click("function () {\n" + " if (this.selected == true) {\n" + " this.selected = false;\n" + " }\n" + " return;\n" + " }")); aaOptions.plotOptions.series .point(aaPoint); return aaOptions; } // Refer to the issue https://github.com/AAChartModel/AAChartKit/issues/589 public static AAOptions customizeEveryDataLabelSinglelyByDataLabelsFormatter() { AAChartModel aaChartModel = new AAChartModel() .chartType(AAChartType.Areaspline)//图表类型 .dataLabelsEnabled(true) .tooltipEnabled(false) .colorsTheme(new Object[]{AAGradientColor.FizzyPeach}) .markerRadius(0) .legendEnabled(false) .categories(new String[]{"美国🇺🇸","欧洲🇪🇺","中国🇨🇳","日本🇯🇵","韩国🇰🇷","越南🇻🇳","中国香港🇭🇰",}) .series(new AASeriesElement[]{ new AASeriesElement() .data(new Object[]{7.0, 6.9, 2.5, 14.5, 18.2, 21.5, 5.2}), }); AAOptions aaOptions = aaChartModel.aa_toAAOptions(); aaOptions.yAxis.gridLineDashStyle = AAChartLineDashStyleType.LongDash;//设置Y轴的网格线样式为 AAChartLineDashStyleType.LongDash String[] unitArr ={"美元", "欧元", "人民币", "日元", "韩元", "越南盾", "港币", }; String unitJSArrStr = javaScriptArrayStringWithJavaArray(unitArr); String dataLabelsFormatter = String.format("function () {\n" + " return this.y + %s[this.point.index]; \n" + //单组 series 图表, 获取选中的点的索引是 this.point.index ,多组并且共享提示框,则是this.points[0].index " }", unitJSArrStr); AADataLabels aaDatalabels = aaOptions.plotOptions.series.dataLabels; aaDatalabels .style(AAStyle.style(AAColor.Red, 10, AAChartFontWeightType.Bold, "1px 1px contrast")) .formatter(dataLabelsFormatter) .backgroundColor(AAColor.White)// white color .borderColor(AAColor.Red)// red color .borderRadius(1.5) .borderWidth(1.3) .x(3).y(-20) .verticalAlign(AAChartVerticalAlignType.Middle); return aaOptions; } //https://github.com/AAChartModel/AAChartKit-Swift/issues/404 public static AAOptions configureColorfulDataLabelsForPieChart() { AAOptions aaOptions = new AAOptions() .title(new AATitle() .text("Colorful DataLabels For Pie Chart")) .colors(new Object[]{ "#0c9674", "#7dffc0", "#ff3333", "#facd32", "#ffffa0", "#EA007B", "#fe117c", "#ffc069", "#06caf4", "#7dffc0" }) .series(new AASeriesElement[]{ new AASeriesElement() .type(AAChartType.Pie) .name("语言热度值") .innerSize("20%")//内部圆环半径大小占比 .borderWidth(0)//描边的宽度 .allowPointSelect(true)//是否允许在点击数据点标记(扇形图点击选中的块发生位移) .states(new AAStates() .hover(new AAHover() .enabled(false)))//禁用 <SUF> .dataLabels(new AADataLabels() .allowOverlap(true)//允许字符重叠 .useHTML(true) .formatter("function () {\n" + " const point = this.point;\n" + " return '<span style=\\\"color: ' + point.color + '\\\">' +\n" + " point.name + ': ' + point.y + '%</span>';\n" + " }")) .data(new Object[][]{ {"Firefox", 3336.2}, {"IE", 26.8}, {"Chrome", 666.8}, {"Safari", 88.5}, {"Opera", 46.0}, {"Others", 223.0}, {"Firefox", 3336.2}, {"IE", 26.8}, {"Chrome", 666.8}, {"Safari", 88.5}, {"Opera", 46.0}, {"Others", 223.0}, }) }); return aaOptions; } private static String javaScriptArrayStringWithJavaArray(Object[] javaArray) { StringBuilder originalJsArrStr = new StringBuilder(); for (Object element : javaArray) { originalJsArrStr.append("'").append(element.toString()).append("',"); } return "[" + originalJsArrStr + "]"; } }
0
27504_2
package dao.impl; import java.sql.ResultSet; import dao.ITaskDAO; import domain.Task; import jdbc.JDBCHelper; /** * 任务管理DAO实现类 * @author Administrator * */ public class TaskDAOImpl implements ITaskDAO { /** * 根据主键查询任务 * @param taskid 主键 * @return 任务 */ public Task findById(long taskid) { final Task task = new Task(); String sql = "select * from task where task_id=?"; Object[] params = new Object[]{taskid}; JDBCHelper jdbcHelper = JDBCHelper.getInstance(); jdbcHelper.executeQuery(sql, params, new JDBCHelper.QueryCallback() { @Override public void process(ResultSet rs) throws Exception { if(rs.next()) { long taskid = rs.getLong(1); String taskName = rs.getString(2); String createTime = rs.getString(3); String startTime = rs.getString(4); String finishTime = rs.getString(5); String taskType = rs.getString(6); String taskStatus = rs.getString(7); String taskParam = rs.getString(8); task.setTaskid(taskid); task.setTaskName(taskName); task.setCreateTime(createTime); task.setStartTime(startTime); task.setFinishTime(finishTime); task.setTaskType(taskType); task.setTaskStatus(taskStatus); task.setTaskParam(taskParam); } } }); /** * 说在后面的话: * * 大家看到这个代码,包括后面的其他的DAO,就会发现,用JDBC进行数据库操作,最大的问题就是麻烦 * 你为了查询某些数据,需要自己编写大量的Domain对象的封装,数据的获取,数据的设置 * 造成大量很冗余的代码 * * 所以说,之前就是说,不建议用Scala来开发大型复杂的Spark的工程项目 * 因为大型复杂的工程项目,必定是要涉及很多第三方的东西的,MySQL只是最基础的,要进行数据库操作 * 可能还会有其他的redis、zookeeper等等 * * 如果你就用Scala,那么势必会造成与调用第三方组件的代码用java,那么就会变成scala+java混编 * 大大降低我们的开发和维护的效率 * * 此外,即使,你是用了scala+java混编 * 但是,真正最方便的,还是使用一些j2ee的开源框架,来进行第三方 * 技术的整合和操作,比如MySQL,那么可以用MyBatis/Hibernate,大大减少我们的冗余的代码 * 大大提升我们的开发速度和效率 * * 但是如果用了scala,那么用j2ee开源框架,进来,造成scala+java+j2ee开源框架混编 * 简直会造成你的spark工程的代码上的极度混乱和惨不忍睹 * 后期非常难以维护和交接 * */ return task; } }
ABigdataer/AnalysisOfUserBehavior
src/main/java/dao/impl/TaskDAOImpl.java
776
/** * 说在后面的话: * * 大家看到这个代码,包括后面的其他的DAO,就会发现,用JDBC进行数据库操作,最大的问题就是麻烦 * 你为了查询某些数据,需要自己编写大量的Domain对象的封装,数据的获取,数据的设置 * 造成大量很冗余的代码 * * 所以说,之前就是说,不建议用Scala来开发大型复杂的Spark的工程项目 * 因为大型复杂的工程项目,必定是要涉及很多第三方的东西的,MySQL只是最基础的,要进行数据库操作 * 可能还会有其他的redis、zookeeper等等 * * 如果你就用Scala,那么势必会造成与调用第三方组件的代码用java,那么就会变成scala+java混编 * 大大降低我们的开发和维护的效率 * * 此外,即使,你是用了scala+java混编 * 但是,真正最方便的,还是使用一些j2ee的开源框架,来进行第三方 * 技术的整合和操作,比如MySQL,那么可以用MyBatis/Hibernate,大大减少我们的冗余的代码 * 大大提升我们的开发速度和效率 * * 但是如果用了scala,那么用j2ee开源框架,进来,造成scala+java+j2ee开源框架混编 * 简直会造成你的spark工程的代码上的极度混乱和惨不忍睹 * 后期非常难以维护和交接 * */
block_comment
zh-cn
package dao.impl; import java.sql.ResultSet; import dao.ITaskDAO; import domain.Task; import jdbc.JDBCHelper; /** * 任务管理DAO实现类 * @author Administrator * */ public class TaskDAOImpl implements ITaskDAO { /** * 根据主键查询任务 * @param taskid 主键 * @return 任务 */ public Task findById(long taskid) { final Task task = new Task(); String sql = "select * from task where task_id=?"; Object[] params = new Object[]{taskid}; JDBCHelper jdbcHelper = JDBCHelper.getInstance(); jdbcHelper.executeQuery(sql, params, new JDBCHelper.QueryCallback() { @Override public void process(ResultSet rs) throws Exception { if(rs.next()) { long taskid = rs.getLong(1); String taskName = rs.getString(2); String createTime = rs.getString(3); String startTime = rs.getString(4); String finishTime = rs.getString(5); String taskType = rs.getString(6); String taskStatus = rs.getString(7); String taskParam = rs.getString(8); task.setTaskid(taskid); task.setTaskName(taskName); task.setCreateTime(createTime); task.setStartTime(startTime); task.setFinishTime(finishTime); task.setTaskType(taskType); task.setTaskStatus(taskStatus); task.setTaskParam(taskParam); } } }); /** * 说在后 <SUF>*/ return task; } }
1
54363_12
package search.control; import entity.AnalyResult; import search.service.MongoDataServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * 年代:yearbasestatics 终端偏好:usetypestatics 邮件运营商:emailstatics 消费水平:consumptionlevelstatics 潮男潮女:chaoManAndWomenstatics 手机运营商:carrierstatics 品牌偏好:brandlikestatics */ @RestController @RequestMapping("yearBase") public class MongodataControl { @Autowired private MongoDataServiceImpl mongoDataServiceImpl; @RequestMapping(value = "searchYearBase",method = RequestMethod.POST) public List<AnalyResult> searchYearBase(){ List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); //40年代,50年代,60年代,70年代,80年代,90年代,00年代 10后 analyResult.setCount(50l); analyResult.setInfo("40年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(60l); analyResult.setInfo("50年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(100l); analyResult.setInfo("60年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(90l); analyResult.setInfo("70年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(500l); analyResult.setInfo("80年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(600l); analyResult.setInfo("90年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(300l); analyResult.setInfo("00年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(70l); analyResult.setInfo("10后"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("yearbasestatics"); } @RequestMapping(value = "searchUseType",method = RequestMethod.POST) public List<AnalyResult> searchUseType(){ List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); //pc端,小程序端,移动端 analyResult.setCount(50l); analyResult.setInfo("pc端"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(60l); analyResult.setInfo("小程序端"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(40l); analyResult.setInfo("移动端"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("usetypestatics"); } @RequestMapping(value = "searchEmail",method = RequestMethod.POST) public List<AnalyResult> searchEmail(){ List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); //qq邮箱,139邮箱,网易邮箱,阿里邮箱 analyResult.setCount(150l); analyResult.setInfo("qq邮箱"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(60l); analyResult.setInfo("139邮箱"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(240l); analyResult.setInfo("网易邮箱"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(540l); analyResult.setInfo("阿里邮箱"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("emailstatics"); } @RequestMapping(value = "searchConsumptionlevel",method = RequestMethod.POST) public List<AnalyResult> searchConsumptionlevel(){ //高消费 中等消费 低消费 List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); //qq邮箱,139邮箱,网易邮箱,阿里邮箱 analyResult.setCount(50l); analyResult.setInfo("高消费"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(560l); analyResult.setInfo("中等消费"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(760l); analyResult.setInfo("低消费"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("consumptionlevelstatics"); } @RequestMapping(value = "searchChaoManAndWomen",method = RequestMethod.POST) public List<AnalyResult> searchChaoManAndWomen(){ //潮男 潮女 List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); analyResult.setCount(350l); analyResult.setInfo("潮男"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(560l); analyResult.setInfo("潮女"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("chaoManAndWomenstatics"); } @RequestMapping(value = "searchCarrier",method = RequestMethod.POST) public List<AnalyResult> searchCarrier(){ //联通 移动 电信 其他 List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); analyResult.setCount(1350l); analyResult.setInfo("联通"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(1560l); analyResult.setInfo("移动"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(560l); analyResult.setInfo("电信"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(4560l); analyResult.setInfo("其他"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("carrierstatics"); } @RequestMapping(value = "searchBrandlike",method = RequestMethod.POST) public List<AnalyResult> searchBrandlike(){ //李宁 爱迪达斯 森马 海尔 List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); analyResult.setCount(1350l); analyResult.setInfo("李宁"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(1560l); analyResult.setInfo("爱迪达斯"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(560l); analyResult.setInfo("森马"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(4560l); analyResult.setInfo("海尔"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("brandlikestatics"); } }
ABigdataer/UserPortrait
SearchInfo/src/main/java/search/control/MongodataControl.java
1,920
//联通 移动 电信 其他
line_comment
zh-cn
package search.control; import entity.AnalyResult; import search.service.MongoDataServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * 年代:yearbasestatics 终端偏好:usetypestatics 邮件运营商:emailstatics 消费水平:consumptionlevelstatics 潮男潮女:chaoManAndWomenstatics 手机运营商:carrierstatics 品牌偏好:brandlikestatics */ @RestController @RequestMapping("yearBase") public class MongodataControl { @Autowired private MongoDataServiceImpl mongoDataServiceImpl; @RequestMapping(value = "searchYearBase",method = RequestMethod.POST) public List<AnalyResult> searchYearBase(){ List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); //40年代,50年代,60年代,70年代,80年代,90年代,00年代 10后 analyResult.setCount(50l); analyResult.setInfo("40年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(60l); analyResult.setInfo("50年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(100l); analyResult.setInfo("60年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(90l); analyResult.setInfo("70年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(500l); analyResult.setInfo("80年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(600l); analyResult.setInfo("90年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(300l); analyResult.setInfo("00年代"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(70l); analyResult.setInfo("10后"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("yearbasestatics"); } @RequestMapping(value = "searchUseType",method = RequestMethod.POST) public List<AnalyResult> searchUseType(){ List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); //pc端,小程序端,移动端 analyResult.setCount(50l); analyResult.setInfo("pc端"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(60l); analyResult.setInfo("小程序端"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(40l); analyResult.setInfo("移动端"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("usetypestatics"); } @RequestMapping(value = "searchEmail",method = RequestMethod.POST) public List<AnalyResult> searchEmail(){ List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); //qq邮箱,139邮箱,网易邮箱,阿里邮箱 analyResult.setCount(150l); analyResult.setInfo("qq邮箱"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(60l); analyResult.setInfo("139邮箱"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(240l); analyResult.setInfo("网易邮箱"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(540l); analyResult.setInfo("阿里邮箱"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("emailstatics"); } @RequestMapping(value = "searchConsumptionlevel",method = RequestMethod.POST) public List<AnalyResult> searchConsumptionlevel(){ //高消费 中等消费 低消费 List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); //qq邮箱,139邮箱,网易邮箱,阿里邮箱 analyResult.setCount(50l); analyResult.setInfo("高消费"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(560l); analyResult.setInfo("中等消费"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(760l); analyResult.setInfo("低消费"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("consumptionlevelstatics"); } @RequestMapping(value = "searchChaoManAndWomen",method = RequestMethod.POST) public List<AnalyResult> searchChaoManAndWomen(){ //潮男 潮女 List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); analyResult.setCount(350l); analyResult.setInfo("潮男"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(560l); analyResult.setInfo("潮女"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("chaoManAndWomenstatics"); } @RequestMapping(value = "searchCarrier",method = RequestMethod.POST) public List<AnalyResult> searchCarrier(){ //联通 <SUF> List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); analyResult.setCount(1350l); analyResult.setInfo("联通"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(1560l); analyResult.setInfo("移动"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(560l); analyResult.setInfo("电信"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(4560l); analyResult.setInfo("其他"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("carrierstatics"); } @RequestMapping(value = "searchBrandlike",method = RequestMethod.POST) public List<AnalyResult> searchBrandlike(){ //李宁 爱迪达斯 森马 海尔 List<AnalyResult> list = new ArrayList<AnalyResult>(); AnalyResult analyResult = new AnalyResult(); analyResult.setCount(1350l); analyResult.setInfo("李宁"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(1560l); analyResult.setInfo("爱迪达斯"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(560l); analyResult.setInfo("森马"); list.add(analyResult); analyResult = new AnalyResult(); analyResult.setCount(4560l); analyResult.setInfo("海尔"); list.add(analyResult); return list; // return mongoDataServiceImpl.listMongoInfoby("brandlikestatics"); } }
1
46298_5
package com.bocft.meeting.common; public enum MsgType { // 预约回复模板(未通过/已通过) REPLY("1467996", "预约回复模板(未通过/已通过)", "会议室预约申请{1},会议室名称:{2},预约时间:{3},详情请前往个人中心查看,祝您工作愉快。"), // 预约结果通知-多参数 RE_MUL_PARM("1470256", "预约结果通知-多参数", "会议室预约申请{1},会议室名称:{2},预约时间:{3},{4}-{5},祝您工作愉快。"), // 验证码-通用 VALID_CODE("1471039", "验证码-通用", "{1}为您的验证码,请于{2}分钟内填写,如非本人操作,请忽略本短信。"), // 申请未通过-通知模板 REJECT_INFORM("1471528","申请未通过-通知模板","尊敬的{1}您好,会议室预约申请{2},会议室名称:{3},预约时间:{4},{5}-{6},请重新申请。"), // 群发-通知会议详情 INFORM_CON_DETAILS("1471530", "群发-通知会议详情", "会议通知:尊敬的{1}您好,请于{2}{3}-{4}准时到{5}参加{6}会议,非本人请忽略此短信。"), //会议室删除后通知模板 AFTER_ROOM_DEL("1478420", "会议室删除后通知模板", "抱歉,您所预定的会议室{1}场所已关闭,请谅解。如还需会议室,请到系统重新预约会议室。感谢配合!"); private String tmpId; private String usage; private String content; MsgType(String tmpId, String message, String content) { this.tmpId = tmpId; this.usage = message; this.content = content; } public String getTmpId() { return tmpId; } public void setTmpId(String tmpId) { this.tmpId = tmpId; } public String getUsage() { return usage; } public void setUsage(String usage) { this.usage = usage; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
ACui96/easy-meeting
src/main/java/com/bocft/meeting/common/MsgType.java
646
//会议室删除后通知模板
line_comment
zh-cn
package com.bocft.meeting.common; public enum MsgType { // 预约回复模板(未通过/已通过) REPLY("1467996", "预约回复模板(未通过/已通过)", "会议室预约申请{1},会议室名称:{2},预约时间:{3},详情请前往个人中心查看,祝您工作愉快。"), // 预约结果通知-多参数 RE_MUL_PARM("1470256", "预约结果通知-多参数", "会议室预约申请{1},会议室名称:{2},预约时间:{3},{4}-{5},祝您工作愉快。"), // 验证码-通用 VALID_CODE("1471039", "验证码-通用", "{1}为您的验证码,请于{2}分钟内填写,如非本人操作,请忽略本短信。"), // 申请未通过-通知模板 REJECT_INFORM("1471528","申请未通过-通知模板","尊敬的{1}您好,会议室预约申请{2},会议室名称:{3},预约时间:{4},{5}-{6},请重新申请。"), // 群发-通知会议详情 INFORM_CON_DETAILS("1471530", "群发-通知会议详情", "会议通知:尊敬的{1}您好,请于{2}{3}-{4}准时到{5}参加{6}会议,非本人请忽略此短信。"), //会议 <SUF> AFTER_ROOM_DEL("1478420", "会议室删除后通知模板", "抱歉,您所预定的会议室{1}场所已关闭,请谅解。如还需会议室,请到系统重新预约会议室。感谢配合!"); private String tmpId; private String usage; private String content; MsgType(String tmpId, String message, String content) { this.tmpId = tmpId; this.usage = message; this.content = content; } public String getTmpId() { return tmpId; } public void setTmpId(String tmpId) { this.tmpId = tmpId; } public String getUsage() { return usage; } public void setUsage(String usage) { this.usage = usage; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
1
38744_12
package com.aesop.demo.rfcclient.infra.rfc.multitask.multijob.impl; import com.aesop.demo.rfcclient.infra.rfc.multitask.multijob.MultiStepJob; import com.sap.conn.jco.JCoDestination; import com.sap.conn.jco.JCoException; import com.sap.conn.jco.JCoFunction; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * 此类实现了MultiStepJob接口 用于指定线程将要执行的任务,主要逻辑在runNextStep方法中,执行了RFC * * @author tttttwtt */ @Slf4j @Service @NoArgsConstructor public class StatelessMultiStep implements MultiStepJob { @Resource private JCoDestination jCoDestination; private JCoFunction function; private int calls;// 调用次数 private int jobID = 0;// 任务编号 private int executedCalls = 0;// 记录调用次数,即任务步骤 private Exception ex = null;// 记录任务执行过程出现的异常 // private int remoteCounter;// 计数结果 public StatelessMultiStep(JCoFunction function, int calls, int jobID) { this.function = function; this.calls = calls; this.jobID = jobID; } public boolean isFinished() { // 如果已经调用完,或者调用过程中出现了异常,表示任务已完成 return executedCalls == calls || ex != null; } public String getName() {// 任务名 return "Job ID:" + jobID; } // 任务的某一步,究竟有多少步则外界来传递进来的calls变量来控制 public void runNextStep() { try { // 注:在调用远程RFC功能函数之前,JCo框架会去调用SessionReferenceProvider的getCurrentSessionReference()方法 // 取得当前任务所对应的远程会话,确保同一任务是在同一远程会话中执行的 function.execute(jCoDestination); executedCalls++;//记录第几次调用 } catch (JCoException je) { ex = je; } } public void cleanUp() {// 任务结束后,清除任务 StringBuilder sb = new StringBuilder("任务 ").append(getName()).append(" 结束:"); if (ex != null) { sb.append("异常结束 ").append(ex.toString()); } else { // sb.append("成功执行完,计数器值 = ").append(remoteCounter); sb.append("成功执行完毕! "); } log.info(sb.toString()); } }
AES0P/SAP-Interface
rfc-client/src/main/java/com/aesop/demo/rfcclient/infra/rfc/multitask/multijob/impl/StatelessMultiStep.java
630
// 任务结束后,清除任务
line_comment
zh-cn
package com.aesop.demo.rfcclient.infra.rfc.multitask.multijob.impl; import com.aesop.demo.rfcclient.infra.rfc.multitask.multijob.MultiStepJob; import com.sap.conn.jco.JCoDestination; import com.sap.conn.jco.JCoException; import com.sap.conn.jco.JCoFunction; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * 此类实现了MultiStepJob接口 用于指定线程将要执行的任务,主要逻辑在runNextStep方法中,执行了RFC * * @author tttttwtt */ @Slf4j @Service @NoArgsConstructor public class StatelessMultiStep implements MultiStepJob { @Resource private JCoDestination jCoDestination; private JCoFunction function; private int calls;// 调用次数 private int jobID = 0;// 任务编号 private int executedCalls = 0;// 记录调用次数,即任务步骤 private Exception ex = null;// 记录任务执行过程出现的异常 // private int remoteCounter;// 计数结果 public StatelessMultiStep(JCoFunction function, int calls, int jobID) { this.function = function; this.calls = calls; this.jobID = jobID; } public boolean isFinished() { // 如果已经调用完,或者调用过程中出现了异常,表示任务已完成 return executedCalls == calls || ex != null; } public String getName() {// 任务名 return "Job ID:" + jobID; } // 任务的某一步,究竟有多少步则外界来传递进来的calls变量来控制 public void runNextStep() { try { // 注:在调用远程RFC功能函数之前,JCo框架会去调用SessionReferenceProvider的getCurrentSessionReference()方法 // 取得当前任务所对应的远程会话,确保同一任务是在同一远程会话中执行的 function.execute(jCoDestination); executedCalls++;//记录第几次调用 } catch (JCoException je) { ex = je; } } public void cleanUp() {// 任务 <SUF> StringBuilder sb = new StringBuilder("任务 ").append(getName()).append(" 结束:"); if (ex != null) { sb.append("异常结束 ").append(ex.toString()); } else { // sb.append("成功执行完,计数器值 = ").append(remoteCounter); sb.append("成功执行完毕! "); } log.info(sb.toString()); } }
0
41201_22
package com.Domain; import java.io.InputStream; import java.util.Date; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * @author Aexlord * @date 2018年4月23日 * @text 邮件发送系统 */ public class SendingEmail { // 发件人的账户和密码 private static String myEmailAccount; private static String myEmailPassword; // 发件人的SMTP地址 private static String myEmailSMTPHost; //获取配置信息 static { Properties pro = new Properties(); try { InputStream in = SendingEmail.class.getClassLoader() .getResourceAsStream("account.properties"); pro.load(in); } catch (Exception e) { System.out.println("配置文件读取错误"); } myEmailAccount = pro.getProperty("myEmailAccount"); myEmailPassword = pro.getProperty("myEmailPassword"); myEmailSMTPHost = pro.getProperty("myEmailSMTPHost"); } public void sendingEmail(String subject,String content,String receiveMail) throws Exception { // 1.创建参数配置,用于连接邮件服务器 Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用Javamaile的协议规范 props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的smpt服务 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 final String smtpPort = "465"; //由于阿里云禁止了25端口,所以需要修改为465端口,并同时要改为ssl加密传输 props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); Session session = Session.getInstance(props); // session.setDebug(true); // 3.创建一封邮件 MimeMessage message = creatMimeMessage(session, myEmailAccount, receiveMail,subject,content); // 4.根据Session获取邮件传输对象 Transport transport = session.getTransport(); // 5.使用邮箱账号和密码链接邮件服务器 transport.connect(myEmailAccount, myEmailPassword); // 6.发送邮件 transport.sendMessage(message, message.getAllRecipients()); // 7.关闭连接 transport.close(); } /* * 创建邮件 */ private static MimeMessage creatMimeMessage(Session session, String sendMail, String receiveMail ,String subject,String content) throws Exception { // 创建一封邮件 MimeMessage message = new MimeMessage(session); // From 发件人 message.setFrom(new InternetAddress(sendMail, "我的小助手", "UTF-8")); // TO 收件人 message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "主人", "UTF-8")); // 邮件主题 message.setSubject(subject, "UTF-8"); // 邮件正文 message.setContent(content, "text/html;charset=UTF-8"); // 设置发送时间 message.setSentDate(new Date()); // 保存设置 message.saveChanges(); return message; } }
AEXLORD/StockAssistant
src/com/Domain/SendingEmail.java
882
// 设置发送时间
line_comment
zh-cn
package com.Domain; import java.io.InputStream; import java.util.Date; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * @author Aexlord * @date 2018年4月23日 * @text 邮件发送系统 */ public class SendingEmail { // 发件人的账户和密码 private static String myEmailAccount; private static String myEmailPassword; // 发件人的SMTP地址 private static String myEmailSMTPHost; //获取配置信息 static { Properties pro = new Properties(); try { InputStream in = SendingEmail.class.getClassLoader() .getResourceAsStream("account.properties"); pro.load(in); } catch (Exception e) { System.out.println("配置文件读取错误"); } myEmailAccount = pro.getProperty("myEmailAccount"); myEmailPassword = pro.getProperty("myEmailPassword"); myEmailSMTPHost = pro.getProperty("myEmailSMTPHost"); } public void sendingEmail(String subject,String content,String receiveMail) throws Exception { // 1.创建参数配置,用于连接邮件服务器 Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用Javamaile的协议规范 props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的smpt服务 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 final String smtpPort = "465"; //由于阿里云禁止了25端口,所以需要修改为465端口,并同时要改为ssl加密传输 props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.socketFactory.port", smtpPort); Session session = Session.getInstance(props); // session.setDebug(true); // 3.创建一封邮件 MimeMessage message = creatMimeMessage(session, myEmailAccount, receiveMail,subject,content); // 4.根据Session获取邮件传输对象 Transport transport = session.getTransport(); // 5.使用邮箱账号和密码链接邮件服务器 transport.connect(myEmailAccount, myEmailPassword); // 6.发送邮件 transport.sendMessage(message, message.getAllRecipients()); // 7.关闭连接 transport.close(); } /* * 创建邮件 */ private static MimeMessage creatMimeMessage(Session session, String sendMail, String receiveMail ,String subject,String content) throws Exception { // 创建一封邮件 MimeMessage message = new MimeMessage(session); // From 发件人 message.setFrom(new InternetAddress(sendMail, "我的小助手", "UTF-8")); // TO 收件人 message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "主人", "UTF-8")); // 邮件主题 message.setSubject(subject, "UTF-8"); // 邮件正文 message.setContent(content, "text/html;charset=UTF-8"); // 设置 <SUF> message.setSentDate(new Date()); // 保存设置 message.saveChanges(); return message; } }
0
59077_2
package com.af.audio; import android.net.Uri; public interface IAudioRecordListener { /** * 初始化提示视图 */ void initTipView(); /** * 设置倒计时提示视图 * * @param counter 10秒倒计时 */ void setTimeoutTipView(int counter); /** * 设置正在录制提示视图 */ void setRecordingTipView(); /** * 设置语音长度太短提示视图 */ void setAudioShortTipView(); /** * 设置取消提示视图 */ void setCancelTipView(); /** * 销毁提示视图 */ void destroyTipView(); /** * 开始录制 * 如果是做IM的话,这里可以发送一个消息,如:对方正在讲话 */ void onStartRecord(); /** * 录制结束 * * @param audioPath 语音文件路径 * @param duration 语音文件时长 */ void onFinish(Uri audioPath, int duration); /** * 分贝改变 * * @param db 分贝 */ void onAudioDBChanged(int db); }
AFinalStone/AudioRecord
library/src/main/java/com/af/audio/IAudioRecordListener.java
266
/** * 设置正在录制提示视图 */
block_comment
zh-cn
package com.af.audio; import android.net.Uri; public interface IAudioRecordListener { /** * 初始化提示视图 */ void initTipView(); /** * 设置倒计时提示视图 * * @param counter 10秒倒计时 */ void setTimeoutTipView(int counter); /** * 设置正 <SUF>*/ void setRecordingTipView(); /** * 设置语音长度太短提示视图 */ void setAudioShortTipView(); /** * 设置取消提示视图 */ void setCancelTipView(); /** * 销毁提示视图 */ void destroyTipView(); /** * 开始录制 * 如果是做IM的话,这里可以发送一个消息,如:对方正在讲话 */ void onStartRecord(); /** * 录制结束 * * @param audioPath 语音文件路径 * @param duration 语音文件时长 */ void onFinish(Uri audioPath, int duration); /** * 分贝改变 * * @param db 分贝 */ void onAudioDBChanged(int db); }
0
66174_0
package chapter1_exercise1to500.section2_exercise51to100; import java.util.ArrayList; import java.util.List; /* 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。 格雷编码序列必须以 0 开头。   示例 1: 输入: 2 输出: [0,1,3,2] 解释: 00 - 0 01 - 1 11 - 3 10 - 2 对于给定的 n,其格雷编码序列并不唯一。 例如,[0,2,3,1] 也是一个有效的格雷编码序列。 00 - 0 10 - 2 11 - 3 01 - 1 示例 2: 输入: 0 输出: [0] 解释: 我们定义格雷编码序列必须以 0 开头。   给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。   因此,当 n = 0 时,其格雷编码序列为 [0]。 * */ public class Ex89_GrayCode { //以下算法击败91% -- --建议修改为用固定大小的静态数组实现,而不是使用java封装动态数组 public List<Integer> grayCode(int n) { List<Integer>result=new ArrayList<>(); if(n==0){ result.add(0); return result; } int base=1; result.add(base-1); result.add(base); int lt=1; while(lt<n){ base=(int)Math.pow(2,lt); int size=result.size(); for(int i=size-1;i>=0;i--){ result.add(base+result.get(i)); } lt++; } return result; } }
AGUAN-RUN/LeetCode_Better_Best
src/chapter1_exercise1to500/section2_exercise51to100/Ex89_GrayCode.java
537
/* 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。 格雷编码序列必须以 0 开头。   示例 1: 输入: 2 输出: [0,1,3,2] 解释: 00 - 0 01 - 1 11 - 3 10 - 2 对于给定的 n,其格雷编码序列并不唯一。 例如,[0,2,3,1] 也是一个有效的格雷编码序列。 00 - 0 10 - 2 11 - 3 01 - 1 示例 2: 输入: 0 输出: [0] 解释: 我们定义格雷编码序列必须以 0 开头。   给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。   因此,当 n = 0 时,其格雷编码序列为 [0]。 * */
block_comment
zh-cn
package chapter1_exercise1to500.section2_exercise51to100; import java.util.ArrayList; import java.util.List; /* 格雷编 <SUF>*/ public class Ex89_GrayCode { //以下算法击败91% -- --建议修改为用固定大小的静态数组实现,而不是使用java封装动态数组 public List<Integer> grayCode(int n) { List<Integer>result=new ArrayList<>(); if(n==0){ result.add(0); return result; } int base=1; result.add(base-1); result.add(base); int lt=1; while(lt<n){ base=(int)Math.pow(2,lt); int size=result.size(); for(int i=size-1;i>=0;i--){ result.add(base+result.get(i)); } lt++; } return result; } }
1
49153_11
package com.zsc.game.ui.fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.jcodecraeer.xrecyclerview.XRecyclerView; import com.stx.xhb.xbanner.XBanner; import com.zsc.game.R; import com.zsc.game.base.BaseFragment; import com.zsc.game.di.component.ActivityComponent; import com.zsc.game.mvp.model.bean.VideoInfo; import com.zsc.game.mvp.presenter.FaPresenter; import com.zsc.game.mvp.view.FaView; import com.zsc.game.ui.activity.SousuoActivity; import com.zsc.game.ui.adapter.HomeAdapter; import com.zsc.game.util.SystemUtil; import java.util.ArrayList; import java.util.List; import butterknife.Unbinder; /** * 类的用途: * <p> * mac周昇辰 * 2017/12/15 18:33 */ public class FragmentA extends BaseFragment<FaPresenter> implements FaView, SwipeRefreshLayout.OnRefreshListener { Unbinder unbinder; private XBanner mybanner; private int imageHeight = 50; //设置渐变高度,一般为导航图片高度,自己控制 private XRecyclerView siftXr1; private SwipeRefreshLayout idSwipe; private HomeAdapter adapter; private List<String> list = new ArrayList<>(); private ImageView goback; private LinearLayout gobackLayout; private LinearLayout titleBarLayout; private TextView settv; private TextView titleBarName; private RelativeLayout relativeLayout; private RelativeLayout relativeLayout1; private TextView textView; private NetworkChangeReciver network; @Override protected int setLayout() { return R.layout.fragmenta; } @Override protected void processLogic() { mPresenter.loadata(); /** * 注册广播,进行监听是否有网络 * */ IntentFilter intentfile=new IntentFilter(); intentfile.addAction("android.net.conn.CONNECTIVITY_CHANGE"); network = new NetworkChangeReciver(); getActivity().registerReceiver(network, intentfile); } @Override protected void initInject(ActivityComponent mainComponent) { mainComponent.Inject(this); } @Override protected void addLayout() { relativeLayout1 = findViewById(R.id.relative1); relativeLayout = findViewById(R.id.relative); textView = findViewById(R.id.xiexie); siftXr1 = findViewById(R.id.sift_xr); titleBarName = findViewById(R.id.title_bar_name); settv = findViewById(R.id.settv); titleBarLayout = findViewById(R.id.title_bar_layout); gobackLayout = findViewById(R.id.gobackLayout); goback = findViewById(R.id.goback); idSwipe=findViewById(R.id.id_swipe); if(!SystemUtil.isNetworkConnected()){ Log.i("www","宝宝"); relativeLayout1.setVisibility(View.GONE); relativeLayout.setVisibility(View.VISIBLE); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(),"我点击了哦,宝贝",Toast.LENGTH_SHORT).show(); Log.i("www","宝宝111"); // 跳转到系统的网络设置界面 Intent intent = null; // 先判断当前系统版本 if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上 intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); }else{ intent = new Intent(); intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings"); } getActivity().startActivity(intent); } }); } View abnv = View.inflate(getActivity(), R.layout.layout_bann, null); init(); goback.setVisibility(View.GONE); settv.setVisibility(View.GONE); mybanner = abnv.findViewById(R.id.mybanner); /** * 查找头部相对应的控件 * */ TextView tv = abnv.findViewById(R.id.edit_sou); titleBarLayout.bringToFront(); siftXr1.addHeaderView(abnv); siftXr1.addOnScrollListener(new RecyclerView.OnScrollListener() { private int y = 0; @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { y+=dy; if (y <= 0) { titleBarName.setText("精选"); titleBarLayout.setBackgroundColor(Color.argb((int) 0,227,29,26)); titleBarName.setTextColor(Color.argb(0, 255, 255, 255)); } else if (y > 0 && y <= imageHeight) { float scale = (float) y / imageHeight; float alpha = (255 * scale); // 只是layout背景透明 titleBarName.setText("精选"); titleBarLayout.setBackgroundColor(Color.argb((int) alpha,227,29,26)); titleBarName.setTextColor(Color.argb((int) alpha, 255, 255, 255)); } else { titleBarName.setText("精选"); titleBarLayout.setBackgroundColor(Color.argb((int) 255,227,29,26)); titleBarName.setTextColor(Color.argb((int) 225, 255, 255, 255)); } } }); idSwipe.setOnRefreshListener(this); /** * 点击跳转搜索框 * */ tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), SousuoActivity.class)); } }); } /** * recycleview数据展示 * */ private void getData(final List<VideoInfo.RetBean.ListBean.ChildListBean> jcList) { siftXr1.setLayoutManager(new LinearLayoutManager(getActivity())); adapter=new HomeAdapter(getActivity(),jcList); siftXr1.setAdapter(adapter); } /** * 上拉刷新下拉加载 * */ private void init( ) { siftXr1.setLoadingListener(new XRecyclerView.LoadingListener() { @Override public void onRefresh() { adapter.notifyDataSetChanged(); siftXr1.refreshComplete(); } @Override public void onLoadMore() { siftXr1.loadMoreComplete(); } }); } //重写方法进行展示网络数据 /** * 网络数据获取更新UI * */ @Override public void showToast(VideoInfo msg) { List<VideoInfo.RetBean.ListBean.ChildListBean> childList = msg.getRet().getList().get(0).getChildList(); final List<String> xbanimg = new ArrayList<>(); for (int i = 0; i < childList.size(); i++) { if(i!=3){ xbanimg.add(childList.get(i).getPic()); } } mybanner.setData(xbanimg, null); mybanner.setmAutoPalyTime(2500); mybanner.setmAdapter(new XBanner.XBannerAdapter() { @Override public void loadBanner(XBanner banner, View view, int position) { Glide.with(getActivity()).load(xbanimg.get(position)).into((ImageView) view); } }); //获取精彩数据 VideoInfo.RetBean.ListBean listBean = msg.getRet().getList().get(4); List<VideoInfo.RetBean.ListBean.ChildListBean> jcList = listBean.getChildList(); getData(jcList); Log.i("ggg",listBean.getTitle()); } @Override public void onRefresh() { idSwipe.setRefreshing(false); } @Override public void onDestroyView() { super.onDestroyView(); if(unbinder != null){ unbinder.unbind(); } } /** * 广播内部类 * */ class NetworkChangeReciver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub' ConnectivityManager connectivityManager=(ConnectivityManager)getActivity().getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo(); if(networkInfo!=null&&networkInfo.isAvailable()) { Toast.makeText(context, "当前网络正常!", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(context, "当前网络处于断网!", Toast.LENGTH_SHORT).show(); Log.i("ttt","我真的很帅"); } } } @Override public void onDestroy() { //注销广播 getActivity().unregisterReceiver(network); super.onDestroy(); } }
AGreatTeam/MicroFilm
app/src/main/java/com/zsc/game/ui/fragment/FragmentA.java
2,334
//重写方法进行展示网络数据
line_comment
zh-cn
package com.zsc.game.ui.fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.jcodecraeer.xrecyclerview.XRecyclerView; import com.stx.xhb.xbanner.XBanner; import com.zsc.game.R; import com.zsc.game.base.BaseFragment; import com.zsc.game.di.component.ActivityComponent; import com.zsc.game.mvp.model.bean.VideoInfo; import com.zsc.game.mvp.presenter.FaPresenter; import com.zsc.game.mvp.view.FaView; import com.zsc.game.ui.activity.SousuoActivity; import com.zsc.game.ui.adapter.HomeAdapter; import com.zsc.game.util.SystemUtil; import java.util.ArrayList; import java.util.List; import butterknife.Unbinder; /** * 类的用途: * <p> * mac周昇辰 * 2017/12/15 18:33 */ public class FragmentA extends BaseFragment<FaPresenter> implements FaView, SwipeRefreshLayout.OnRefreshListener { Unbinder unbinder; private XBanner mybanner; private int imageHeight = 50; //设置渐变高度,一般为导航图片高度,自己控制 private XRecyclerView siftXr1; private SwipeRefreshLayout idSwipe; private HomeAdapter adapter; private List<String> list = new ArrayList<>(); private ImageView goback; private LinearLayout gobackLayout; private LinearLayout titleBarLayout; private TextView settv; private TextView titleBarName; private RelativeLayout relativeLayout; private RelativeLayout relativeLayout1; private TextView textView; private NetworkChangeReciver network; @Override protected int setLayout() { return R.layout.fragmenta; } @Override protected void processLogic() { mPresenter.loadata(); /** * 注册广播,进行监听是否有网络 * */ IntentFilter intentfile=new IntentFilter(); intentfile.addAction("android.net.conn.CONNECTIVITY_CHANGE"); network = new NetworkChangeReciver(); getActivity().registerReceiver(network, intentfile); } @Override protected void initInject(ActivityComponent mainComponent) { mainComponent.Inject(this); } @Override protected void addLayout() { relativeLayout1 = findViewById(R.id.relative1); relativeLayout = findViewById(R.id.relative); textView = findViewById(R.id.xiexie); siftXr1 = findViewById(R.id.sift_xr); titleBarName = findViewById(R.id.title_bar_name); settv = findViewById(R.id.settv); titleBarLayout = findViewById(R.id.title_bar_layout); gobackLayout = findViewById(R.id.gobackLayout); goback = findViewById(R.id.goback); idSwipe=findViewById(R.id.id_swipe); if(!SystemUtil.isNetworkConnected()){ Log.i("www","宝宝"); relativeLayout1.setVisibility(View.GONE); relativeLayout.setVisibility(View.VISIBLE); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(),"我点击了哦,宝贝",Toast.LENGTH_SHORT).show(); Log.i("www","宝宝111"); // 跳转到系统的网络设置界面 Intent intent = null; // 先判断当前系统版本 if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上 intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); }else{ intent = new Intent(); intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings"); } getActivity().startActivity(intent); } }); } View abnv = View.inflate(getActivity(), R.layout.layout_bann, null); init(); goback.setVisibility(View.GONE); settv.setVisibility(View.GONE); mybanner = abnv.findViewById(R.id.mybanner); /** * 查找头部相对应的控件 * */ TextView tv = abnv.findViewById(R.id.edit_sou); titleBarLayout.bringToFront(); siftXr1.addHeaderView(abnv); siftXr1.addOnScrollListener(new RecyclerView.OnScrollListener() { private int y = 0; @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { y+=dy; if (y <= 0) { titleBarName.setText("精选"); titleBarLayout.setBackgroundColor(Color.argb((int) 0,227,29,26)); titleBarName.setTextColor(Color.argb(0, 255, 255, 255)); } else if (y > 0 && y <= imageHeight) { float scale = (float) y / imageHeight; float alpha = (255 * scale); // 只是layout背景透明 titleBarName.setText("精选"); titleBarLayout.setBackgroundColor(Color.argb((int) alpha,227,29,26)); titleBarName.setTextColor(Color.argb((int) alpha, 255, 255, 255)); } else { titleBarName.setText("精选"); titleBarLayout.setBackgroundColor(Color.argb((int) 255,227,29,26)); titleBarName.setTextColor(Color.argb((int) 225, 255, 255, 255)); } } }); idSwipe.setOnRefreshListener(this); /** * 点击跳转搜索框 * */ tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), SousuoActivity.class)); } }); } /** * recycleview数据展示 * */ private void getData(final List<VideoInfo.RetBean.ListBean.ChildListBean> jcList) { siftXr1.setLayoutManager(new LinearLayoutManager(getActivity())); adapter=new HomeAdapter(getActivity(),jcList); siftXr1.setAdapter(adapter); } /** * 上拉刷新下拉加载 * */ private void init( ) { siftXr1.setLoadingListener(new XRecyclerView.LoadingListener() { @Override public void onRefresh() { adapter.notifyDataSetChanged(); siftXr1.refreshComplete(); } @Override public void onLoadMore() { siftXr1.loadMoreComplete(); } }); } //重写 <SUF> /** * 网络数据获取更新UI * */ @Override public void showToast(VideoInfo msg) { List<VideoInfo.RetBean.ListBean.ChildListBean> childList = msg.getRet().getList().get(0).getChildList(); final List<String> xbanimg = new ArrayList<>(); for (int i = 0; i < childList.size(); i++) { if(i!=3){ xbanimg.add(childList.get(i).getPic()); } } mybanner.setData(xbanimg, null); mybanner.setmAutoPalyTime(2500); mybanner.setmAdapter(new XBanner.XBannerAdapter() { @Override public void loadBanner(XBanner banner, View view, int position) { Glide.with(getActivity()).load(xbanimg.get(position)).into((ImageView) view); } }); //获取精彩数据 VideoInfo.RetBean.ListBean listBean = msg.getRet().getList().get(4); List<VideoInfo.RetBean.ListBean.ChildListBean> jcList = listBean.getChildList(); getData(jcList); Log.i("ggg",listBean.getTitle()); } @Override public void onRefresh() { idSwipe.setRefreshing(false); } @Override public void onDestroyView() { super.onDestroyView(); if(unbinder != null){ unbinder.unbind(); } } /** * 广播内部类 * */ class NetworkChangeReciver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub' ConnectivityManager connectivityManager=(ConnectivityManager)getActivity().getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo(); if(networkInfo!=null&&networkInfo.isAvailable()) { Toast.makeText(context, "当前网络正常!", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(context, "当前网络处于断网!", Toast.LENGTH_SHORT).show(); Log.i("ttt","我真的很帅"); } } } @Override public void onDestroy() { //注销广播 getActivity().unregisterReceiver(network); super.onDestroy(); } }
0
34716_1
package ch03.sec03; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.corpus.dictionary.NatureDictionaryMaker; import com.hankcs.hanlp.corpus.document.CorpusLoader; import com.hankcs.hanlp.corpus.document.sentence.word.IWord; import com.hankcs.hanlp.dictionary.CoreBiGramTableDictionary; import com.hankcs.hanlp.dictionary.CoreDictionary; import com.hankcs.hanlp.seg.Dijkstra.DijkstraSegment; import com.hankcs.hanlp.seg.Segment; import com.hankcs.hanlp.seg.Viterbi.ViterbiSegment; import java.util.List; import static ch03.MSR.*; import static tools.Tools.show_subtitle; public class DemoNgramSegment { public static void main(String[] args) { // 第一次执行会报出警告,然后会转换 txt 文件为 bin 文件,后面就不再报错 // 连续执行两次时,第二次使用的是第一次载入的 bin 文件 // 交换以下现场代码的顺序就可以看到区别 show_subtitle("my_cws_model"); trainBigram(MY_CWS_CORPUS_PATH, MY_MODEL_PATH); loadBigram(MY_MODEL_PATH); // ToDo: HanLP 更新了版本,增加了 CoreDictionary.reload() 函数,我还没有更新版本,没有测试这个功能。 show_subtitle("msr_ngram"); trainBigram(MSR_TRAIN_PATH, MSR_MODEL_PATH); loadBigram(MSR_MODEL_PATH); } /** * 训练 bigram 模型 * * @param corpusPath 语料库路径 * @param modelPath 模型保存路径 */ public static void trainBigram(String corpusPath, String modelPath) { List<List<IWord>> sentenceList = CorpusLoader.convert2SentenceList(corpusPath); for (List<IWord> sentence : sentenceList) for (IWord word : sentence) if (word.getLabel() == null) word.setLabel("n"); // 赋予每个单词一个虚拟的名词词性 final NatureDictionaryMaker dictionaryMaker = new NatureDictionaryMaker(); dictionaryMaker.compute(sentenceList); dictionaryMaker.saveTxtTo(modelPath); } public static Segment loadBigram(String modelPath) { return loadBigram(modelPath, true, true); } public static Segment loadBigram(String modelPath, boolean verbose, boolean viterbi) { // HanLP.Config.enableDebug(); HanLP.Config.CoreDictionaryPath = modelPath + ".txt"; HanLP.Config.BiGramDictionaryPath = modelPath + ".ngram.txt"; if (verbose) { HanLP.Config.ShowTermNature = false; System.out.println("「商品」的词频:" + CoreDictionary.getTermFrequency("商品")); System.out.println("「商品@和」的频次:" + CoreBiGramTableDictionary.getBiFrequency("商品", "和")); Segment segment = new DijkstraSegment() .enableAllNamedEntityRecognize(false) // 禁用命名实体识别 .enableCustomDictionary(false); // 禁用用户词典 System.out.println(segment.seg("商品和服务")); System.out.println(segment.seg("货币和服务")); } Segment viterbiSegment = new ViterbiSegment().enableAllNamedEntityRecognize(false).enableCustomDictionary(false); Segment dijkstraSegment = new DijkstraSegment().enableAllNamedEntityRecognize(false).enableCustomDictionary(false); return viterbi ? viterbiSegment : dijkstraSegment; } }
AI-code-examples/Hanlp-Books-Examples
src/main/java/ch03/sec03/DemoNgramSegment.java
898
// 连续执行两次时,第二次使用的是第一次载入的 bin 文件
line_comment
zh-cn
package ch03.sec03; import com.hankcs.hanlp.HanLP; import com.hankcs.hanlp.corpus.dictionary.NatureDictionaryMaker; import com.hankcs.hanlp.corpus.document.CorpusLoader; import com.hankcs.hanlp.corpus.document.sentence.word.IWord; import com.hankcs.hanlp.dictionary.CoreBiGramTableDictionary; import com.hankcs.hanlp.dictionary.CoreDictionary; import com.hankcs.hanlp.seg.Dijkstra.DijkstraSegment; import com.hankcs.hanlp.seg.Segment; import com.hankcs.hanlp.seg.Viterbi.ViterbiSegment; import java.util.List; import static ch03.MSR.*; import static tools.Tools.show_subtitle; public class DemoNgramSegment { public static void main(String[] args) { // 第一次执行会报出警告,然后会转换 txt 文件为 bin 文件,后面就不再报错 // 连续 <SUF> // 交换以下现场代码的顺序就可以看到区别 show_subtitle("my_cws_model"); trainBigram(MY_CWS_CORPUS_PATH, MY_MODEL_PATH); loadBigram(MY_MODEL_PATH); // ToDo: HanLP 更新了版本,增加了 CoreDictionary.reload() 函数,我还没有更新版本,没有测试这个功能。 show_subtitle("msr_ngram"); trainBigram(MSR_TRAIN_PATH, MSR_MODEL_PATH); loadBigram(MSR_MODEL_PATH); } /** * 训练 bigram 模型 * * @param corpusPath 语料库路径 * @param modelPath 模型保存路径 */ public static void trainBigram(String corpusPath, String modelPath) { List<List<IWord>> sentenceList = CorpusLoader.convert2SentenceList(corpusPath); for (List<IWord> sentence : sentenceList) for (IWord word : sentence) if (word.getLabel() == null) word.setLabel("n"); // 赋予每个单词一个虚拟的名词词性 final NatureDictionaryMaker dictionaryMaker = new NatureDictionaryMaker(); dictionaryMaker.compute(sentenceList); dictionaryMaker.saveTxtTo(modelPath); } public static Segment loadBigram(String modelPath) { return loadBigram(modelPath, true, true); } public static Segment loadBigram(String modelPath, boolean verbose, boolean viterbi) { // HanLP.Config.enableDebug(); HanLP.Config.CoreDictionaryPath = modelPath + ".txt"; HanLP.Config.BiGramDictionaryPath = modelPath + ".ngram.txt"; if (verbose) { HanLP.Config.ShowTermNature = false; System.out.println("「商品」的词频:" + CoreDictionary.getTermFrequency("商品")); System.out.println("「商品@和」的频次:" + CoreBiGramTableDictionary.getBiFrequency("商品", "和")); Segment segment = new DijkstraSegment() .enableAllNamedEntityRecognize(false) // 禁用命名实体识别 .enableCustomDictionary(false); // 禁用用户词典 System.out.println(segment.seg("商品和服务")); System.out.println(segment.seg("货币和服务")); } Segment viterbiSegment = new ViterbiSegment().enableAllNamedEntityRecognize(false).enableCustomDictionary(false); Segment dijkstraSegment = new DijkstraSegment().enableAllNamedEntityRecognize(false).enableCustomDictionary(false); return viterbi ? viterbiSegment : dijkstraSegment; } }
0
23682_3
package com.tianyi.web.model; /** * Created by 雪峰 on 2018/1/3. */ public class UserSportsModel { //运动状态,0未添加,1:零基础,2:有经验,3:经验丰富 private int sportsState; //运动目的 0,未填写:1:健康,2:康复,3:完美 private int sportsGoal; //喜欢的运动 private String sportsLiked; //运动场地 json串 private String sportsFieild; //运动天数 0:未填写,1:不动,2:1-2,3:3-4,3:5-7 private int sportDay; //运动小时 0:未填写,1:30分钟,2:30-60,3:60-90,4:90以上 private int sportsHour; //体重信息0:未填写 ,1:长胖,2:保持,3:不会胖 private int weightInfo; //体型状态 0:未填写,1:圆润,2:标准,3:苗条 private int shape; //手腕长度0:未填写 1:有间隙,2:,3: private int wristLength; public int getSportsState() { return sportsState; } public void setSportsState(int sportsState) { this.sportsState = sportsState; } public int getSportsGoal() { return sportsGoal; } public void setSportsGoal(int sportsGoal) { this.sportsGoal = sportsGoal; } public String getSportsLiked() { return sportsLiked; } public void setSportsLiked(String sportsLiked) { this.sportsLiked = sportsLiked; } public String getSportsFieild() { return sportsFieild; } public void setSportsFieild(String sportsFieild) { this.sportsFieild = sportsFieild; } public int getSportDay() { return sportDay; } public void setSportDay(int sportDay) { this.sportDay = sportDay; } public int getSportsHour() { return sportsHour; } public void setSportsHour(int sportsHour) { this.sportsHour = sportsHour; } public int getWeightInfo() { return weightInfo; } public void setWeightInfo(int weightInfo) { this.weightInfo = weightInfo; } public int getShape() { return shape; } public void setShape(int shape) { this.shape = shape; } public int getWristLength() { return wristLength; } public void setWristLength(int wristLength) { this.wristLength = wristLength; } }
AIDOCGroup/Server
src/main/java/com/tianyi/web/model/UserSportsModel.java
716
//喜欢的运动
line_comment
zh-cn
package com.tianyi.web.model; /** * Created by 雪峰 on 2018/1/3. */ public class UserSportsModel { //运动状态,0未添加,1:零基础,2:有经验,3:经验丰富 private int sportsState; //运动目的 0,未填写:1:健康,2:康复,3:完美 private int sportsGoal; //喜欢 <SUF> private String sportsLiked; //运动场地 json串 private String sportsFieild; //运动天数 0:未填写,1:不动,2:1-2,3:3-4,3:5-7 private int sportDay; //运动小时 0:未填写,1:30分钟,2:30-60,3:60-90,4:90以上 private int sportsHour; //体重信息0:未填写 ,1:长胖,2:保持,3:不会胖 private int weightInfo; //体型状态 0:未填写,1:圆润,2:标准,3:苗条 private int shape; //手腕长度0:未填写 1:有间隙,2:,3: private int wristLength; public int getSportsState() { return sportsState; } public void setSportsState(int sportsState) { this.sportsState = sportsState; } public int getSportsGoal() { return sportsGoal; } public void setSportsGoal(int sportsGoal) { this.sportsGoal = sportsGoal; } public String getSportsLiked() { return sportsLiked; } public void setSportsLiked(String sportsLiked) { this.sportsLiked = sportsLiked; } public String getSportsFieild() { return sportsFieild; } public void setSportsFieild(String sportsFieild) { this.sportsFieild = sportsFieild; } public int getSportDay() { return sportDay; } public void setSportDay(int sportDay) { this.sportDay = sportDay; } public int getSportsHour() { return sportsHour; } public void setSportsHour(int sportsHour) { this.sportsHour = sportsHour; } public int getWeightInfo() { return weightInfo; } public void setWeightInfo(int weightInfo) { this.weightInfo = weightInfo; } public int getShape() { return shape; } public void setShape(int shape) { this.shape = shape; } public int getWristLength() { return wristLength; } public void setWristLength(int wristLength) { this.wristLength = wristLength; } }
0
13196_1
package ajax.model; import java.util.*; public enum JokeType { // id, info, realName, iconClassName, isShowToUser, rank WEISHEZHI(0, "未设置", "未设置", null, false), ONLY_WORD(1, "only words", null, null, false), STATIC_IMAGE(2, "有图片, 不是动态图的笑话", null, null, false), GIF(3, "动态图", null, null, false), ZHIHU(4, "知乎精选", "知乎", null, false), FILM(31, "电影", "电影", "glyphicon glyphicon-film", true, 100), TOUR(32, "旅行", "旅行", "glyphicon glyphicon-plane", true, 100), FOOD(33, "美食", "美食", "glyphicon glyphicon-cutlery", true, 100), SPORTS(34, "健身, 体育, 运动", "运动", "glyphicon glyphicon-fire", true, 100), INTERNET(35, "互联网, 社交网络,网络安全", "互联网", "glyphicon glyphicon-cloud", true, 90), FASHION(36, "时尚", "时尚", "glyphicon glyphicon-credit-card", true, 90), SYB(37, "创业", "创业", "glyphicon glyphicon-usd", true, 90), DESIGN(38, "设计,平面设计", "设计", "glyphicon glyphicon-tower", true, 90), SCIENCE(39, "自然科学", "科学", "glyphicon glyphicon-tree-deciduous", true, 80), ECONOMICS(40, "经济学, 经济", "经济学", null, false), CAREER(41, "职业发展", "职业"), HOME(42, "家居", "家居", "glyphicon glyphicon-home", true, 80), EDUCATION(43, "教育", "教育", "glyphicon glyphicon-education", true, 80), CAR(44, "汽车", "汽车", "glyphicon glyphicon-asterisk", true, 80), LAW(45, "法律,税务", "法律", "glyphicon glyphicon-lock", true, 80), MEDICINE(46, "医疗", "医疗", "glyphicon glyphicon-leaf", true, 80), MUSIC(47, "音乐", "音乐", "glyphicon glyphicon-headphones", true, 70), READ(48, "阅读", "阅读", "glyphicon glyphicon-book", true, 70), HEALTH(49, "健康", "健康", "glyphicon glyphicon-heart", true, 70), LIFESTYLE(50, "生活方式,室友,人生,恋爱,社会现象", "生活", "glyphicon glyphicon-lamp", true, 60), HISTORY(51, "历史", "历史", "glyphicon glyphicon-list-alt", true, 60), CAPTURE(52, "摄影", "摄影", "glyphicon glyphicon-camera", true, 50), LITERATURE(53, "文学", "文学", "glyphicon glyphicon-book", true, 50), INVEST(54, "投资", "投资", "glyphicon glyphicon-object-align-top", true, 50), PHYSICS(55, "物理学", "", "", false), GAME(56, "游戏", "游戏", "glyphicon glyphicon-knight", true, 50), BUSINESS(57, "商业, 金融,职场", "商业", "glyphicon glyphicon-jpy", true, 40), TECH(58, "科技", "科技", "glyphicon glyphicon-apple", true, 40), MIAOPAI(59, "秒拍", "秒拍", "aj-icon aj-icon-video", true, 40), JIUKUAIJIU(60, "九块九", "九块九", "aj-icon aj-icon-iconfontxiexiangbao", true, 90), STORY(101, "故事,清朝历史,考古,AV", "故事", "glyphicon glyphicon-bookmark", true, 30), ALL(9, "所有内容", null, null, false), UNKNOWN(99, "未知分类", "未知世界", "glyphicon glyphicon-menu-right", true), /** * 爱淘宝值得买 */ ZHIDEMAI_AITAO(200, "爱淘", "爱淘", "aj-icon aj-icon-iconfontxiexiangbao", true, 30); private int id; private String info; private String realName; private String iconClassName; private boolean isShowToUser; private int rank; // the more of rank means more important of this type public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public boolean isShowToUser() { return isShowToUser; } public void setShowToUser(boolean isShowToUser) { this.isShowToUser = isShowToUser; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public String getIconClassName() { return iconClassName; } public void setIconClassName(String iconClassName) { this.iconClassName = iconClassName; } /** * 获取类型页面的跳转链接 * @return */ public String getHref() { return UrlRoute.type.getUrl() + "?type=" + this.getId(); } JokeType(int id, String info) { this(id, info, null, "glyphicon glyphicon-star", true, 1); } JokeType(int id, String info, String realName) { this(id, info, realName, "glyphicon glyphicon-star", true, 1); } JokeType(int id, String info, String realName, String iconClassName) { this(id, info, realName, iconClassName, true, 1); } JokeType(int id, String info, String realName, String iconClassName, boolean isShowToUser) { this(id, info, realName, iconClassName, isShowToUser, 1); } JokeType(int id, String info, String realName, String iconClassName, boolean isShowToUser, int rank) { this.id = id; this.info = info; this.realName = realName; this.iconClassName = iconClassName; this.isShowToUser = isShowToUser; this.rank = rank; } public static JokeType getJokeTypeByInfo(String info) { JokeType[] jokeTypes = JokeType.values(); for (JokeType jt : jokeTypes) { if (jt.info.contains(info)) { return jt; } } return JokeType.UNKNOWN; } public static JokeType[] getAllJokeTypes() { return JokeType.values(); } /** * 返回可以展示给用户的类别 * @return */ public static List<JokeType> getLegalJokeTypes() { List<JokeType> types = new ArrayList<JokeType>(); for(JokeType j : JokeType.values()) { if (j.isShowToUser) { types.add(j); } } return types; } /** * 获取类型的链接页面 * @return */ public String getTypeHref() { return Joke.getHrefByJokeType(this); } public static JokeType getJokeType(int id) { JokeType[] jokeTypes = JokeType.values(); for (JokeType jt : jokeTypes) { if (jt.id == id) { return jt; } } return JokeType.UNKNOWN; } /** * * 返回realname, 如果为null 则返回info * @return */ public String getNickName() { if (this.realName != null) { return this.realName; } return this.info; } /** * Cause This returns null when not found the given typeID, You should use getJokeType instead of this method! * @param typeID * @return */ @Deprecated public static JokeType getLegalJokeTypeByTypeId(Integer typeID) { JokeType result = null; for (JokeType jokeType : JokeType.values()) { if (typeID == jokeType.getId()) { result = jokeType; } } if (result == null) { result = JokeType.ALL; } return result; } /** * 根据stamp猜测一个jokeType并返回, 猜测不到返回null * @param stamp * @return */ public static JokeType guessType(String stamp) { JokeType[] types = JokeType.getAllJokeTypes(); for (JokeType type : types) { if (type.getInfo().contains(stamp)) { return type; } } return null; } public String wrapWithBE() { return "b" + this.id + "e"; } /** * 生成js枚举对象 * @return */ private static String generateToJSObject() { StringBuilder sb = new StringBuilder(); sb.append("{"); for (JokeType jt : JokeType.values()) { sb.append(jt.name() + ":" + jt.getId() + ","); } sb.replace(sb.length() - 1, sb.length(), ""); sb.append("}"); return sb.toString(); } public static void main(String[] args) { System.out.println(generateToJSObject()); } }
AJLoveChina/hejie2.0
src/neon/hyy/src/main/java/ajax/model/JokeType.java
2,676
/** * 爱淘宝值得买 */
block_comment
zh-cn
package ajax.model; import java.util.*; public enum JokeType { // id, info, realName, iconClassName, isShowToUser, rank WEISHEZHI(0, "未设置", "未设置", null, false), ONLY_WORD(1, "only words", null, null, false), STATIC_IMAGE(2, "有图片, 不是动态图的笑话", null, null, false), GIF(3, "动态图", null, null, false), ZHIHU(4, "知乎精选", "知乎", null, false), FILM(31, "电影", "电影", "glyphicon glyphicon-film", true, 100), TOUR(32, "旅行", "旅行", "glyphicon glyphicon-plane", true, 100), FOOD(33, "美食", "美食", "glyphicon glyphicon-cutlery", true, 100), SPORTS(34, "健身, 体育, 运动", "运动", "glyphicon glyphicon-fire", true, 100), INTERNET(35, "互联网, 社交网络,网络安全", "互联网", "glyphicon glyphicon-cloud", true, 90), FASHION(36, "时尚", "时尚", "glyphicon glyphicon-credit-card", true, 90), SYB(37, "创业", "创业", "glyphicon glyphicon-usd", true, 90), DESIGN(38, "设计,平面设计", "设计", "glyphicon glyphicon-tower", true, 90), SCIENCE(39, "自然科学", "科学", "glyphicon glyphicon-tree-deciduous", true, 80), ECONOMICS(40, "经济学, 经济", "经济学", null, false), CAREER(41, "职业发展", "职业"), HOME(42, "家居", "家居", "glyphicon glyphicon-home", true, 80), EDUCATION(43, "教育", "教育", "glyphicon glyphicon-education", true, 80), CAR(44, "汽车", "汽车", "glyphicon glyphicon-asterisk", true, 80), LAW(45, "法律,税务", "法律", "glyphicon glyphicon-lock", true, 80), MEDICINE(46, "医疗", "医疗", "glyphicon glyphicon-leaf", true, 80), MUSIC(47, "音乐", "音乐", "glyphicon glyphicon-headphones", true, 70), READ(48, "阅读", "阅读", "glyphicon glyphicon-book", true, 70), HEALTH(49, "健康", "健康", "glyphicon glyphicon-heart", true, 70), LIFESTYLE(50, "生活方式,室友,人生,恋爱,社会现象", "生活", "glyphicon glyphicon-lamp", true, 60), HISTORY(51, "历史", "历史", "glyphicon glyphicon-list-alt", true, 60), CAPTURE(52, "摄影", "摄影", "glyphicon glyphicon-camera", true, 50), LITERATURE(53, "文学", "文学", "glyphicon glyphicon-book", true, 50), INVEST(54, "投资", "投资", "glyphicon glyphicon-object-align-top", true, 50), PHYSICS(55, "物理学", "", "", false), GAME(56, "游戏", "游戏", "glyphicon glyphicon-knight", true, 50), BUSINESS(57, "商业, 金融,职场", "商业", "glyphicon glyphicon-jpy", true, 40), TECH(58, "科技", "科技", "glyphicon glyphicon-apple", true, 40), MIAOPAI(59, "秒拍", "秒拍", "aj-icon aj-icon-video", true, 40), JIUKUAIJIU(60, "九块九", "九块九", "aj-icon aj-icon-iconfontxiexiangbao", true, 90), STORY(101, "故事,清朝历史,考古,AV", "故事", "glyphicon glyphicon-bookmark", true, 30), ALL(9, "所有内容", null, null, false), UNKNOWN(99, "未知分类", "未知世界", "glyphicon glyphicon-menu-right", true), /** * 爱淘宝 <SUF>*/ ZHIDEMAI_AITAO(200, "爱淘", "爱淘", "aj-icon aj-icon-iconfontxiexiangbao", true, 30); private int id; private String info; private String realName; private String iconClassName; private boolean isShowToUser; private int rank; // the more of rank means more important of this type public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public boolean isShowToUser() { return isShowToUser; } public void setShowToUser(boolean isShowToUser) { this.isShowToUser = isShowToUser; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public String getIconClassName() { return iconClassName; } public void setIconClassName(String iconClassName) { this.iconClassName = iconClassName; } /** * 获取类型页面的跳转链接 * @return */ public String getHref() { return UrlRoute.type.getUrl() + "?type=" + this.getId(); } JokeType(int id, String info) { this(id, info, null, "glyphicon glyphicon-star", true, 1); } JokeType(int id, String info, String realName) { this(id, info, realName, "glyphicon glyphicon-star", true, 1); } JokeType(int id, String info, String realName, String iconClassName) { this(id, info, realName, iconClassName, true, 1); } JokeType(int id, String info, String realName, String iconClassName, boolean isShowToUser) { this(id, info, realName, iconClassName, isShowToUser, 1); } JokeType(int id, String info, String realName, String iconClassName, boolean isShowToUser, int rank) { this.id = id; this.info = info; this.realName = realName; this.iconClassName = iconClassName; this.isShowToUser = isShowToUser; this.rank = rank; } public static JokeType getJokeTypeByInfo(String info) { JokeType[] jokeTypes = JokeType.values(); for (JokeType jt : jokeTypes) { if (jt.info.contains(info)) { return jt; } } return JokeType.UNKNOWN; } public static JokeType[] getAllJokeTypes() { return JokeType.values(); } /** * 返回可以展示给用户的类别 * @return */ public static List<JokeType> getLegalJokeTypes() { List<JokeType> types = new ArrayList<JokeType>(); for(JokeType j : JokeType.values()) { if (j.isShowToUser) { types.add(j); } } return types; } /** * 获取类型的链接页面 * @return */ public String getTypeHref() { return Joke.getHrefByJokeType(this); } public static JokeType getJokeType(int id) { JokeType[] jokeTypes = JokeType.values(); for (JokeType jt : jokeTypes) { if (jt.id == id) { return jt; } } return JokeType.UNKNOWN; } /** * * 返回realname, 如果为null 则返回info * @return */ public String getNickName() { if (this.realName != null) { return this.realName; } return this.info; } /** * Cause This returns null when not found the given typeID, You should use getJokeType instead of this method! * @param typeID * @return */ @Deprecated public static JokeType getLegalJokeTypeByTypeId(Integer typeID) { JokeType result = null; for (JokeType jokeType : JokeType.values()) { if (typeID == jokeType.getId()) { result = jokeType; } } if (result == null) { result = JokeType.ALL; } return result; } /** * 根据stamp猜测一个jokeType并返回, 猜测不到返回null * @param stamp * @return */ public static JokeType guessType(String stamp) { JokeType[] types = JokeType.getAllJokeTypes(); for (JokeType type : types) { if (type.getInfo().contains(stamp)) { return type; } } return null; } public String wrapWithBE() { return "b" + this.id + "e"; } /** * 生成js枚举对象 * @return */ private static String generateToJSObject() { StringBuilder sb = new StringBuilder(); sb.append("{"); for (JokeType jt : JokeType.values()) { sb.append(jt.name() + ":" + jt.getId() + ","); } sb.replace(sb.length() - 1, sb.length(), ""); sb.append("}"); return sb.toString(); } public static void main(String[] args) { System.out.println(generateToJSObject()); } }
1
41584_2
package com.demo.hutool.qr; import cn.hutool.extra.qrcode.QrCodeUtil; import cn.hutool.extra.qrcode.QrConfig; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import lombok.extern.slf4j.Slf4j; import java.awt.*; import java.io.File; import java.nio.charset.StandardCharsets; /** * <h1>二维码</h1> * * <p> * createDate 2022/03/10 16:08:11 * </p> * * @author ALI[ali-k@foxmail.com] * @since 1.0.0 **/ @Slf4j public class Main { private static final String content = "爱上对方过后就哭了啊123456789012345678901234567890"; private static final ErrorCorrectionLevel level = ErrorCorrectionLevel.M; private static final String path1 = "E:/qr1.png"; private static final String path2 = "E:/qr2.png"; public static void main(String[] args) { /*生成二维码*/ File file = new File(path1); // 默认M和UTF-8 QrCodeUtil.generate(content, 300, 300, file); /*识别二维码*/ String decode = QrCodeUtil.decode(file); log.info("二维码:" + decode); /*自定义参数*/ QrConfig config = new QrConfig(300, 300); // 设置边距,既二维码和背景之间的边距 config.setMargin(1); // 设置前景色 config.setForeColor(new Color(0x66ccff)); // 设置背景色 config.setBackColor(Color.BLACK); // 设置二维码中的Logo config.setImg(file); // 设置纠错级别 config.setErrorCorrection(level); // 设置文本编码 config.setCharset(StandardCharsets.UTF_8); // 生成二维码到文件,也可以到流 QrCodeUtil.generate(content, config, new File(path2)); } }
ALI1416/springboot-demo
demo-util/src/main/java/com/demo/hutool/qr/Main.java
544
// 默认M和UTF-8
line_comment
zh-cn
package com.demo.hutool.qr; import cn.hutool.extra.qrcode.QrCodeUtil; import cn.hutool.extra.qrcode.QrConfig; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import lombok.extern.slf4j.Slf4j; import java.awt.*; import java.io.File; import java.nio.charset.StandardCharsets; /** * <h1>二维码</h1> * * <p> * createDate 2022/03/10 16:08:11 * </p> * * @author ALI[ali-k@foxmail.com] * @since 1.0.0 **/ @Slf4j public class Main { private static final String content = "爱上对方过后就哭了啊123456789012345678901234567890"; private static final ErrorCorrectionLevel level = ErrorCorrectionLevel.M; private static final String path1 = "E:/qr1.png"; private static final String path2 = "E:/qr2.png"; public static void main(String[] args) { /*生成二维码*/ File file = new File(path1); // 默认 <SUF> QrCodeUtil.generate(content, 300, 300, file); /*识别二维码*/ String decode = QrCodeUtil.decode(file); log.info("二维码:" + decode); /*自定义参数*/ QrConfig config = new QrConfig(300, 300); // 设置边距,既二维码和背景之间的边距 config.setMargin(1); // 设置前景色 config.setForeColor(new Color(0x66ccff)); // 设置背景色 config.setBackColor(Color.BLACK); // 设置二维码中的Logo config.setImg(file); // 设置纠错级别 config.setErrorCorrection(level); // 设置文本编码 config.setCharset(StandardCharsets.UTF_8); // 生成二维码到文件,也可以到流 QrCodeUtil.generate(content, config, new File(path2)); } }
0
42395_19
package Segmentation; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import Ner.TimeRecognition; import common.MyUtil; public class Rule { public static final int NOAction = 0; public static final int Seperate = 1; public static final int Append = 2; int[] Rules;//前处理后的结果 List<String> timeList; List<String> locList; /** * sentence 待分词的句子 * dicmode 这里面前处理后处理都会做所以去掉这个参数 * prefix 路径前缀 * segmode 0是正常分词,1需要前匹配时间地点 * */ Rule(String sentence, String prefix, int segmode,int split,List<String> words) { int i, start, end; int[] Rules = new int[sentence.length()]; timeList=new ArrayList<String>(); locList=new ArrayList<String>(); Rules[0]=Seperate; //处理特殊字符 char[] sep_character={'[',']','【','】',';',';','@','#','—','-','①','②','③','④','⑤','⑥','⑦','⑧','⑨','⑩','甲','乙','丙','丁','→','。'}; Set<Character> sep=new HashSet<>(); for(Character c:sep_character) sep.add(c); for(int j=0;j<sentence.length();j++){ if(sentence.charAt(j)==' ') Rules[j]=Seperate; else if(sep.contains(sentence.charAt(j))){ Rules[j]=Seperate; if(j+1<sentence.length()) Rules[j+1]=Seperate; } } //前处理字典 String str = sentence, temp; DoubleArrayTriePre adt = DoubleArrayTriePre.getInstance(prefix+"dic/pre.txt"); int maxSize = adt.getMax(); int k = 0; while (str.length() > 0) { if (str.length() < maxSize) temp = str; else temp = str.substring(0, maxSize); while (temp.length() > 1) if (adt.exactMatchSearch(temp) >= 0) { if(k<split && k + temp.length()>split) temp = temp.substring(0, temp.length() - 1); else{ Rules[k] = Seperate; for (i = k + 1; i < k + temp.length(); i++) Rules[i] = Append; if (i < sentence.length()) Rules[i] = Seperate; break; } } else temp = temp.substring(0, temp.length() - 1); k += temp.length(); str = str.substring(temp.length()); } // "[A-Za-z0-9\\.\\+\\-]*[A-za-z0-9][年|月|日|时|万|亿|%]*","(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]", //,"(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]""[A-Za-z0-9\\.\\+\\-\\_]*[A-za-z0-9][年|月|日|时|万|亿|%|%]*", //处理正则表达式匹配 String[] pattern_str = { // "[A-Za-z0-9\\.\\+\\_\\/]*[A-Za-z0-9](分钟|分|秒|世纪|年代|年|月份|月|日|时刻|时|万|亿|%|%|℃){0,1}", // "([图|表])([\\d|甲|乙|丙|丁])+([\\(|\\(][a|b|c|d|A|B|C|D][\\)|\\)])*", // "(\\d|\\.)+°[ewsnEWSN]?((\\d|\\.)+[′|’][ewsnEWSN]?)?", // "(?(\\d|\\.)+°[ewsnEWSN]?((\\d|\\.)+[′|’][ewsnEWSN]?)?,(\\d|\\.)+°[ewsnEWSN]?((\\d|\\.)+[′|’][ewsnEWSN]?)?)?", // "[甲|乙|丙|丁|戊|①|②|③|④|⑤|Ⅰ|Ⅱ|Ⅲ|Ⅳ|Ⅴ|[A-Z]|[a-z]]{1,4}(类|图|国|河流|河|市|县|镇|村|点|线|地|区域|区|阶段|河段)", // "[甲|乙|丙|丁|戊|①|②|③|④|⑤|Ⅰ|Ⅱ|Ⅲ|Ⅳ|Ⅴ|[A-Z]|[a-z]][城省处]", // "(洋流|气流|环节)[甲|乙|丙|丁|戊|①|②|③|④|⑤|Ⅰ|Ⅱ|Ⅲ|Ⅳ|Ⅴ|[A-Z]|[a-z]]", // "1[:|︰|:]\\d{1,10}", // "([0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|一|二|三|四|五|六|七|八|九|零|十|百|千|万|亿|〇|两]{0,3})[:|:]([0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|一|二|三|四|五|六|七|八|九|零|十|百|千|万|亿|〇|两]{0,3})" }; for (int j = 0; j < pattern_str.length; j++) { Pattern p = Pattern.compile(pattern_str[j]); Matcher m = p.matcher(sentence); while (m.find()) { start = m.start(); end = m.end(); if(start < split && end > split) continue; Rules[start] = Seperate; for (i = start + 1; i < end; i++) Rules[i] = Append; if(end<sentence.length()) Rules[end]=Seperate; } } //处理昼长夜短、自东向西短语 String[] pattern_4 = { "([自|从|由])([长|短|高|低|东|西|南|北|中|上|下|左|右][部|东|西|南|北]*)([到|至|向])([长|短|高|低|东|西|南|北|中|上|下|左|右][部|东|西|南|北]*)" }; for (int j = 0; j < pattern_4.length; j++) { Pattern p = Pattern.compile(pattern_4[j]); Matcher m = p.matcher(sentence); while (m.find()) { start = m.start(); end = m.end(); if(end-start==4){ //由 高 到 低 Rules[start] = Seperate; Rules[start+1] = Seperate; Rules[start+2] = Seperate; Rules[start+3] = Seperate; if(end<sentence.length()) Rules[end]=Seperate; }else if (end-start==6) { //自 东南 到 西北 Rules[start] = Seperate; Rules[start+1] = Seperate; Rules[start+2] = Append; Rules[start+3] = Seperate; Rules[start+4] = Seperate; Rules[start+5] = Append; if(end<sentence.length()) Rules[end]=Seperate; } } } String[] pattern_5 = { "([昼|夜|东|西|南|北|中|上|下|左|右|风|雨|雾|雪|人|浪|春|夏|秋|冬][间|部|东|西|南|北]*)([冷|热|长|短|高|低|多|少|大|小])([昼|夜|东|西|南|北|中|上|下|左|右|风|雨|雾|雪|浪|春|夏|秋|冬][部|东|西|南|北|间]*)([冷|热|长|短|高|低|多|少|大|小|急])" }; for (int j = 0; j < pattern_5.length; j++) { Pattern p = Pattern.compile(pattern_5[j]); Matcher m = p.matcher(sentence); while (m.find()) { start = m.start(); end = m.end(); if(end-start==4){ //风小雾大,合在一起 Rules[start] = Seperate; Rules[start+1] = Append; Rules[start+2] = Append; Rules[start+3] = Append; if(end<sentence.length()) Rules[end]=Seperate; }else if (end-start==6) { //东南 高 西北 低 Rules[start] = Seperate; Rules[start+1] = Append; Rules[start+2] = Seperate; Rules[start+3] = Seperate; Rules[start+4] = Append; Rules[start+5] = Seperate; if(end<sentence.length()) Rules[end]=Seperate; } } } //处理正*方向 String[] pattern_6 = {"正[东|西|南|北]方[向|位]"}; for (int j = 0; j < pattern_6.length; j++) { Pattern p = Pattern.compile(pattern_6[j]); Matcher m = p.matcher(sentence); while (m.find()) { start = m.start(); end = m.end(); Rules[start] = Seperate; Rules[start+1] = Append; Rules[start+2] = Seperate; Rules[start+3] = Append; if(end<sentence.length()) Rules[end]=Seperate; } } //处理空格,由于会把句中空格过滤,这里不用 // for(i=0;i<sentence.length();i++) // if(sentence.charAt(i)==' ') // Rules[i]=Seperate; // 处理用户词典 // if (dicmode == 0) { // } //处理时间和地点 if(segmode==1){ //时间词典 String tf=prefix+"dic/timeLib.dic"; timeList=MyUtil.read_file(tf); TimeRecognition timeRecognition=new TimeRecognition(); timeList.addAll(timeRecognition.findAllTime(sentence)); //地名词典 String lf=prefix+"dic/simple_place.txt"; locList=MyUtil.read_file(lf); for(String s:timeList){ int j=sentence.indexOf(s); if(j>=0){ Rules[j]=Seperate; for(i=j+1;i<j+s.length();i++) Rules[i]=Append; } } for(String s:locList){ int j=sentence.indexOf(s); if(j>=0){ Rules[j]=Seperate; for(i=j+1;i<j+s.length();i++) Rules[i]=Append; } } } //传入的地点处理 if(words!=null && words.size()>0){ Collections.sort(words); for(String s:words){ int j=sentence.indexOf(s); if(j>=0){ Rules[j]=Seperate; for(i=j+1;i<j+s.length();i++) Rules[i]=Append; if (i < sentence.length()) Rules[i] = Seperate; } } } //利用题干和选项分离信息 if(split>0 && split<sentence.length()) Rules[split]=Seperate; this.Rules = Rules; } int[] getRules() { return this.Rules; } boolean can_sepreate(int i) { if (this.Rules[i] == Append) return false; return true; } boolean can_append(int i) { if (this.Rules[i] == Seperate) return false; return true; } }
ALiZeyu/Geo_Question_Analysis
GeoST/src/Segmentation/Rule.java
3,614
//风小雾大,合在一起
line_comment
zh-cn
package Segmentation; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import Ner.TimeRecognition; import common.MyUtil; public class Rule { public static final int NOAction = 0; public static final int Seperate = 1; public static final int Append = 2; int[] Rules;//前处理后的结果 List<String> timeList; List<String> locList; /** * sentence 待分词的句子 * dicmode 这里面前处理后处理都会做所以去掉这个参数 * prefix 路径前缀 * segmode 0是正常分词,1需要前匹配时间地点 * */ Rule(String sentence, String prefix, int segmode,int split,List<String> words) { int i, start, end; int[] Rules = new int[sentence.length()]; timeList=new ArrayList<String>(); locList=new ArrayList<String>(); Rules[0]=Seperate; //处理特殊字符 char[] sep_character={'[',']','【','】',';',';','@','#','—','-','①','②','③','④','⑤','⑥','⑦','⑧','⑨','⑩','甲','乙','丙','丁','→','。'}; Set<Character> sep=new HashSet<>(); for(Character c:sep_character) sep.add(c); for(int j=0;j<sentence.length();j++){ if(sentence.charAt(j)==' ') Rules[j]=Seperate; else if(sep.contains(sentence.charAt(j))){ Rules[j]=Seperate; if(j+1<sentence.length()) Rules[j+1]=Seperate; } } //前处理字典 String str = sentence, temp; DoubleArrayTriePre adt = DoubleArrayTriePre.getInstance(prefix+"dic/pre.txt"); int maxSize = adt.getMax(); int k = 0; while (str.length() > 0) { if (str.length() < maxSize) temp = str; else temp = str.substring(0, maxSize); while (temp.length() > 1) if (adt.exactMatchSearch(temp) >= 0) { if(k<split && k + temp.length()>split) temp = temp.substring(0, temp.length() - 1); else{ Rules[k] = Seperate; for (i = k + 1; i < k + temp.length(); i++) Rules[i] = Append; if (i < sentence.length()) Rules[i] = Seperate; break; } } else temp = temp.substring(0, temp.length() - 1); k += temp.length(); str = str.substring(temp.length()); } // "[A-Za-z0-9\\.\\+\\-]*[A-za-z0-9][年|月|日|时|万|亿|%]*","(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]", //,"(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]""[A-Za-z0-9\\.\\+\\-\\_]*[A-za-z0-9][年|月|日|时|万|亿|%|%]*", //处理正则表达式匹配 String[] pattern_str = { // "[A-Za-z0-9\\.\\+\\_\\/]*[A-Za-z0-9](分钟|分|秒|世纪|年代|年|月份|月|日|时刻|时|万|亿|%|%|℃){0,1}", // "([图|表])([\\d|甲|乙|丙|丁])+([\\(|\\(][a|b|c|d|A|B|C|D][\\)|\\)])*", // "(\\d|\\.)+°[ewsnEWSN]?((\\d|\\.)+[′|’][ewsnEWSN]?)?", // "(?(\\d|\\.)+°[ewsnEWSN]?((\\d|\\.)+[′|’][ewsnEWSN]?)?,(\\d|\\.)+°[ewsnEWSN]?((\\d|\\.)+[′|’][ewsnEWSN]?)?)?", // "[甲|乙|丙|丁|戊|①|②|③|④|⑤|Ⅰ|Ⅱ|Ⅲ|Ⅳ|Ⅴ|[A-Z]|[a-z]]{1,4}(类|图|国|河流|河|市|县|镇|村|点|线|地|区域|区|阶段|河段)", // "[甲|乙|丙|丁|戊|①|②|③|④|⑤|Ⅰ|Ⅱ|Ⅲ|Ⅳ|Ⅴ|[A-Z]|[a-z]][城省处]", // "(洋流|气流|环节)[甲|乙|丙|丁|戊|①|②|③|④|⑤|Ⅰ|Ⅱ|Ⅲ|Ⅳ|Ⅴ|[A-Z]|[a-z]]", // "1[:|︰|:]\\d{1,10}", // "([0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|一|二|三|四|五|六|七|八|九|零|十|百|千|万|亿|〇|两]{0,3})[:|:]([0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|6|7|8|9|一|二|三|四|五|六|七|八|九|零|十|百|千|万|亿|〇|两]{0,3})" }; for (int j = 0; j < pattern_str.length; j++) { Pattern p = Pattern.compile(pattern_str[j]); Matcher m = p.matcher(sentence); while (m.find()) { start = m.start(); end = m.end(); if(start < split && end > split) continue; Rules[start] = Seperate; for (i = start + 1; i < end; i++) Rules[i] = Append; if(end<sentence.length()) Rules[end]=Seperate; } } //处理昼长夜短、自东向西短语 String[] pattern_4 = { "([自|从|由])([长|短|高|低|东|西|南|北|中|上|下|左|右][部|东|西|南|北]*)([到|至|向])([长|短|高|低|东|西|南|北|中|上|下|左|右][部|东|西|南|北]*)" }; for (int j = 0; j < pattern_4.length; j++) { Pattern p = Pattern.compile(pattern_4[j]); Matcher m = p.matcher(sentence); while (m.find()) { start = m.start(); end = m.end(); if(end-start==4){ //由 高 到 低 Rules[start] = Seperate; Rules[start+1] = Seperate; Rules[start+2] = Seperate; Rules[start+3] = Seperate; if(end<sentence.length()) Rules[end]=Seperate; }else if (end-start==6) { //自 东南 到 西北 Rules[start] = Seperate; Rules[start+1] = Seperate; Rules[start+2] = Append; Rules[start+3] = Seperate; Rules[start+4] = Seperate; Rules[start+5] = Append; if(end<sentence.length()) Rules[end]=Seperate; } } } String[] pattern_5 = { "([昼|夜|东|西|南|北|中|上|下|左|右|风|雨|雾|雪|人|浪|春|夏|秋|冬][间|部|东|西|南|北]*)([冷|热|长|短|高|低|多|少|大|小])([昼|夜|东|西|南|北|中|上|下|左|右|风|雨|雾|雪|浪|春|夏|秋|冬][部|东|西|南|北|间]*)([冷|热|长|短|高|低|多|少|大|小|急])" }; for (int j = 0; j < pattern_5.length; j++) { Pattern p = Pattern.compile(pattern_5[j]); Matcher m = p.matcher(sentence); while (m.find()) { start = m.start(); end = m.end(); if(end-start==4){ //风小 <SUF> Rules[start] = Seperate; Rules[start+1] = Append; Rules[start+2] = Append; Rules[start+3] = Append; if(end<sentence.length()) Rules[end]=Seperate; }else if (end-start==6) { //东南 高 西北 低 Rules[start] = Seperate; Rules[start+1] = Append; Rules[start+2] = Seperate; Rules[start+3] = Seperate; Rules[start+4] = Append; Rules[start+5] = Seperate; if(end<sentence.length()) Rules[end]=Seperate; } } } //处理正*方向 String[] pattern_6 = {"正[东|西|南|北]方[向|位]"}; for (int j = 0; j < pattern_6.length; j++) { Pattern p = Pattern.compile(pattern_6[j]); Matcher m = p.matcher(sentence); while (m.find()) { start = m.start(); end = m.end(); Rules[start] = Seperate; Rules[start+1] = Append; Rules[start+2] = Seperate; Rules[start+3] = Append; if(end<sentence.length()) Rules[end]=Seperate; } } //处理空格,由于会把句中空格过滤,这里不用 // for(i=0;i<sentence.length();i++) // if(sentence.charAt(i)==' ') // Rules[i]=Seperate; // 处理用户词典 // if (dicmode == 0) { // } //处理时间和地点 if(segmode==1){ //时间词典 String tf=prefix+"dic/timeLib.dic"; timeList=MyUtil.read_file(tf); TimeRecognition timeRecognition=new TimeRecognition(); timeList.addAll(timeRecognition.findAllTime(sentence)); //地名词典 String lf=prefix+"dic/simple_place.txt"; locList=MyUtil.read_file(lf); for(String s:timeList){ int j=sentence.indexOf(s); if(j>=0){ Rules[j]=Seperate; for(i=j+1;i<j+s.length();i++) Rules[i]=Append; } } for(String s:locList){ int j=sentence.indexOf(s); if(j>=0){ Rules[j]=Seperate; for(i=j+1;i<j+s.length();i++) Rules[i]=Append; } } } //传入的地点处理 if(words!=null && words.size()>0){ Collections.sort(words); for(String s:words){ int j=sentence.indexOf(s); if(j>=0){ Rules[j]=Seperate; for(i=j+1;i<j+s.length();i++) Rules[i]=Append; if (i < sentence.length()) Rules[i] = Seperate; } } } //利用题干和选项分离信息 if(split>0 && split<sentence.length()) Rules[split]=Seperate; this.Rules = Rules; } int[] getRules() { return this.Rules; } boolean can_sepreate(int i) { if (this.Rules[i] == Append) return false; return true; } boolean can_append(int i) { if (this.Rules[i] == Seperate) return false; return true; } }
1
6082_11
package com.aof.mcinabox.gamecontroller.ckb.button; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatButton; import com.aof.mcinabox.gamecontroller.ckb.achieve.CkbManager; import com.aof.mcinabox.gamecontroller.ckb.achieve.GameButtonDialog; import com.aof.mcinabox.gamecontroller.ckb.support.CallCustomizeKeyboard; import com.aof.mcinabox.gamecontroller.ckb.support.CkbThemeMarker; import com.aof.mcinabox.gamecontroller.ckb.support.CkbThemeRecorder; import com.aof.mcinabox.gamecontroller.controller.Controller; import com.aof.mcinabox.gamecontroller.event.BaseKeyEvent; import com.aof.mcinabox.utils.ColorUtils; import com.aof.mcinabox.utils.DisplayUtils; import org.apache.commons.text.StringEscapeUtils; import java.util.Arrays; import java.util.HashMap; import static androidx.core.math.MathUtils.clamp; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.KEYBOARD_BUTTON; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.MOUSE_BUTTON; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.MOUSE_POINTER; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.MOUSE_POINTER_INC; @SuppressLint("ViewConstructor") public class GameButton extends AppCompatButton implements View.OnTouchListener { private final CallCustomizeKeyboard mCall; private final Controller mController; private final Context mContext; private final CkbManager mManager; private final Activity mActivity; private int buttonMode; private int screenWidth; private int screenHeight; public final static int MODE_MOVEABLE_EDITABLE = 1; public final static int MODE_PREVIEW = 2; public final static int MODE_GAME = 3; public final static int MAX_KEYMAP_SIZE = 4; public final static int MAX_KEY_SIZE_DP = 250; public final static int MIN_KEY_SIZE_DP = 20; public final static int MIN_TEXT_SIZE_SP = 2; public final static int MAX_TEXT_SIZE_SP = 20; public final static int MIN_ALPHA_SIZE_PT = 0; public final static int MAX_ALPHA_SIZE_PT = 100; public final static int MIN_CORNER_SIZE_PT = 0; public final static int MAX_CORNER_SIZE_PT = 100; public final static int MIN_MOVE_DISTANCE = 10; public final static int MAX_CHARS_LENTH = 50; public final static int DEFAULT_DESIGN_INDEX = CkbThemeMarker.DESIGN_SIGNLE_FILL; public final static int DEFAULT_BUTTON_MODE = MODE_MOVEABLE_EDITABLE; public final static int DEFAULT_KEY_SIZE_DP = 50; public final static int DEFAULT_CORNER_SIZE_PT = 20; public final static int DEFAULT_ALPHA_SIZE_PT = 70; public final static int DEFAULT_TEXT_SIZE_SP = 5; public final static String DEFAULT_BACK_COLOR_HEX = "#000000"; public final static String DEFAULT_TEXT_COLOR_HEX = "#FFFFFF"; private final static String TAG = "GameButton"; public final static int KEY_TYPE = KEYBOARD_BUTTON; public final static int POINTER_TYPE = MOUSE_POINTER; public final static int MOUSE_TYPE = MOUSE_BUTTON; public final static int SHOW_ALL = 0; public final static int SHOW_IN_GAME = 1; public final static int SHOW_OUT_GAME = 2; private String[] keyMaps; //最多映射N个按键 private int[] keyTypes; //映射的按键的类型 private CkbThemeRecorder mRecorder; //主题记录器 private boolean isKeep; //自动保持 private boolean isHide; //隐藏 private float[] keyPos; // leftPx , topPx private float[] keySize; // widthDp, heightDp private int alphaSize; //透明度百分比 private String keyName; //按键名 private int textSize; //字体大小 private boolean viewerFollow; //视角跟随 private boolean isGrabbed = false; //输入模式 |捕获|独立| private int show; private boolean isChars; //是否是字符输入 private String keyChars; //字符 private boolean isFirstAdded = false; //被首次创建 public GameButton(@NonNull Context context, @NonNull CallCustomizeKeyboard call, @NonNull CkbManager manager) { this(context, call, null, manager); } public GameButton(Context context, @NonNull CallCustomizeKeyboard call, @Nullable Controller controller, @NonNull CkbManager manager) { super(context); this.mContext = context; this.mCall = call; this.mController = controller; this.mManager = manager; if (mContext instanceof Activity) { this.mActivity = (Activity) mContext; } else { mActivity = null; } //初始化 init(); } @SuppressLint("ClickableViewAccessibility") private void init() { //添加params this.setLayoutParams(new ViewGroup.LayoutParams(0, 0)); //屏幕长宽 screenWidth = (mController == null) ? mManager.getDisplaySize()[0] : mController.getConfig().getScreenWidth(); screenHeight = (mController == null) ? mManager.getDisplaySize()[1] : mController.getConfig().getScreenHeight(); //设定监听 this.setOnTouchListener(this); //初始化状态列表 this.stateMap = new HashMap<>(); //初始化默认属性 initAttribute(); //更新UI updateUI(); } private void initAttribute() { if (mController != null) { this.isGrabbed = mController.isGrabbed(); } mRecorder = new CkbThemeRecorder(); this.setKeyName(""); this.setButtonMode(mManager.getButtonsMode()); this.setTextSize(DEFAULT_TEXT_SIZE_SP); String[] strs = new String[MAX_KEYMAP_SIZE]; Arrays.fill(strs, ""); this.setKeyMaps(strs); this.setKeyTypes(new int[]{KEY_TYPE, KEY_TYPE, KEY_TYPE, KEY_TYPE}); this.setShow(SHOW_ALL); this.setKeep(false); this.setViewerFollow(false); this.setBackColor(DEFAULT_BACK_COLOR_HEX); this.setTextColor(DEFAULT_TEXT_COLOR_HEX); this.setKeyPos(0, 0); this.setKeySize(DEFAULT_KEY_SIZE_DP, DEFAULT_KEY_SIZE_DP); this.setCornerRadius(DEFAULT_CORNER_SIZE_PT); this.setAlphaSize(DEFAULT_ALPHA_SIZE_PT); this.setDesignIndex(DEFAULT_DESIGN_INDEX); this.setInputChars(false); this.setChars(""); } public GameButton setInputChars(boolean b) { this.isChars = b; return this; } public boolean isInputChars() { return this.isChars; } public boolean setChars(String chars) { if (chars != null) { this.keyChars = chars; return true; } else { return false; } } public String getChars() { return this.keyChars; } public boolean setKeyMaps(String[] map) { if (map.length == MAX_KEYMAP_SIZE) { String[] tmp = new String[MAX_KEYMAP_SIZE]; System.arraycopy(map, 0, tmp, 0, MAX_KEYMAP_SIZE); this.keyMaps = tmp; return true; } else { return false; } } public boolean setKeyTypes(int[] types) { if (types.length == MAX_KEYMAP_SIZE) { int[] tmp = new int[MAX_KEYMAP_SIZE]; System.arraycopy(types, 0, tmp, 0, MAX_KEYMAP_SIZE); this.keyTypes = tmp; return true; } else { return false; } } public String[] setKeyMaps(String keyName, int index) { if (index > MAX_KEYMAP_SIZE || index < 0) { return null; } else { keyMaps[index] = keyName; return keyMaps; } } public GameButton setButtonMode(int mode) { if (mode == MODE_GAME || mode == MODE_MOVEABLE_EDITABLE || mode == MODE_PREVIEW) { this.buttonMode = mode; updateUI(); } return this; } public void setKeep(boolean isKeep) { this.isKeep = isKeep; } public void setHide(boolean isHide) { this.isHide = isHide; //UI刷新 updateUI(); } public boolean setBackColor(String colorHex) { int color = ColorUtils.hex2Int(colorHex); if (color != 0) { this.mRecorder.setColors(0, color); updateUI(); return true; } return false; } public boolean setTextColor(String colorHex) { int color = ColorUtils.hex2Int(colorHex); if (color != 0) { this.setTextColor(color); this.mRecorder.setTextColor(color); return true; } return false; } public float[] setKeyPos(float x, float y) { Log.e(TAG, "dpx: " + x + " dpy: " + y); int viewWidth = this.getLayoutParams().width; int viewHeight = this.getLayoutParams().height; int xPx = DisplayUtils.getPxFromDp(mContext, x); int yPx = DisplayUtils.getPxFromDp(mContext, y); float rx, ry; //Clamp between two extremes rx = clamp(xPx, 0f, (float) (screenWidth - viewWidth)); ry = clamp(yPx, 0f, (float) (screenHeight - viewHeight)); this.setX(rx); this.setY(ry); this.keyPos = new float[]{x, y}; return this.keyPos; //x ,y } //按键大小用Dp表示 public boolean setKeySize(float widthDp, float heightDp) { int widthPx = DisplayUtils.getPxFromDp(mContext, widthDp); int heightPx = DisplayUtils.getPxFromDp(mContext, heightDp); if ((widthDp <= MAX_KEY_SIZE_DP && heightDp <= MAX_KEY_SIZE_DP) && (widthDp >= MIN_KEY_SIZE_DP && heightDp >= MIN_KEY_SIZE_DP)) { ViewGroup.LayoutParams params = this.getLayoutParams(); params.width = widthPx; params.height = heightPx; this.requestLayout(); this.keySize = new float[]{widthDp, heightDp}; return true; } else { return false; } } public void setCornerRadius(int radius) { radius = clamp(radius, MIN_CORNER_SIZE_PT, MAX_CORNER_SIZE_PT); this.mRecorder.setCornerRadiusPt(radius); updateUI(); } public void setAlphaSize(int alphaPt) { alphaPt = clamp(alphaPt, MIN_ALPHA_SIZE_PT, MAX_ALPHA_SIZE_PT); this.setAlpha(alphaPt * 0.01f); this.alphaSize = alphaPt; } public boolean setKeyName(String str) { if (str != null) { this.setText(str); this.keyName = str; return true; } else { return false; } } public void setTextSize(int spValue) { spValue = clamp(spValue, MIN_TEXT_SIZE_SP, MAX_TEXT_SIZE_SP); this.setTextSize((float) DisplayUtils.getPxFromSp(mContext, spValue)); this.textSize = spValue; } public GameButton setShow(int s) { this.show = s; updateUI(); return this; } public GameButton setDesignIndex(int index) { this.mRecorder.setDesignIndex(index); updateUI(); return this; } public String[] getColorHexs() { int[] c = mRecorder.getColors(); String[] tmp = new String[CkbThemeRecorder.COLOR_INDEX_LENGTH]; int a; for (a = 0; a < c.length; a++) { tmp[a] = ColorUtils.int2Hex(c[a]); } return tmp; } public void setGrabbed(boolean mode) { this.isGrabbed = mode; //执行UI刷新 updateUI(); } public void setViewerFollow(boolean follow) { this.viewerFollow = follow; } public GameButton getNewButtonLikeThis() { GameButton g = new GameButton(mContext, mCall, mController, mManager); g.setButtonMode(this.buttonMode); g.setKeyName(this.keyName); g.setKeySize(this.keySize[0], this.keySize[1]); g.setKeyPos(this.keyPos[0], this.keyPos[1]); g.setKeyMaps(this.keyMaps); g.setKeyTypes(this.keyTypes); g.setBackColor(ColorUtils.int2Hex(mRecorder.getColor(0))); g.setTextColor(ColorUtils.int2Hex(mRecorder.getTextColor())); g.setAlphaSize(this.alphaSize); g.setCornerRadius(this.mRecorder.getCornerRadiusPt()); g.setTextSize(this.textSize); g.setKeep(this.isKeep); g.setHide(this.isHide); g.setShow(this.show); g.setViewerFollow(this.viewerFollow); g.setGrabbed(this.isGrabbed); g.setDesignIndex(this.mRecorder.getDesignIndex()); g.setInputChars(this.isChars); g.setChars(this.keyChars); return g; } private HashMap<String, Boolean> stateMap; private void sendKey(String keyName, boolean pressed, int type) { //该算法可以保证CustomizeKeyboard不会造成clientinput的setkey()方法堵塞; if (pressed) { if (stateMap.containsKey(keyName) && stateMap.get(keyName)) { return; } if (!stateMap.containsKey(keyName)) { stateMap.put(keyName, pressed); } if (stateMap.containsKey(keyName) && !stateMap.get(keyName)) { stateMap.remove(keyName); stateMap.put(keyName, pressed); } mController.sendKey(new BaseKeyEvent(TAG, keyName, pressed, type, null)); } else { if (stateMap.containsKey(keyName) && stateMap.get(keyName)) { stateMap.remove(keyName); stateMap.put(keyName, pressed); mController.sendKey(new BaseKeyEvent(TAG, keyName, pressed, type, null)); } } } public GameButton setFirstAdded() { this.isFirstAdded = true; return this; } public GameButton unsetFirstAdded() { this.isFirstAdded = false; return this; } private boolean isBeingPressed = false; private int initialX = 0; private int initialY = 0; private void inputPointerEvent(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: initialX = (int) e.getX(); initialY = (int) e.getY(); break; case MotionEvent.ACTION_MOVE: mController.sendKey(new BaseKeyEvent(TAG, null, false, MOUSE_POINTER_INC, new int[]{(int) (e.getX() - initialX), (int) (e.getY() - initialY)})); initialX = (int) e.getX(); initialY = (int) e.getY(); break; case MotionEvent.ACTION_UP: break; } } private void inputKeyEvent(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: if (isKeep && !isChars) { if (!isBeingPressed) { for (int a = 0; a < MAX_KEYMAP_SIZE; a++) { if (keyMaps[a] != null && !keyMaps[a].equals("")) { sendKey(keyMaps[a], true, keyTypes[a]); } } } } else { for (int a = 0; a < MAX_KEYMAP_SIZE; a++) { if (keyMaps[a] != null && !keyMaps[a].equals("")) { sendKey(keyMaps[a], true, keyTypes[a]); } } } break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: if (isKeep && !isChars) { if (isBeingPressed) { for (int a = 0; a < MAX_KEYMAP_SIZE; a++) { if (keyMaps[a] != null && !keyMaps[a].equals("")) { sendKey(keyMaps[a], false, keyTypes[a]); } } isBeingPressed = false; } else { isBeingPressed = true; } } else if (isChars) { mController.typeWords(convertStringWithASCII(this.keyChars)); } else { for (int a = 0; a < MAX_KEYMAP_SIZE; a++) { if (keyMaps[a] != null && !keyMaps[a].equals("")) { sendKey(keyMaps[a], false, keyTypes[a]); } } } break; default: break; } } private String convertStringWithASCII(String str) { if (str == null) return null; return StringEscapeUtils.unescapeJava(str); } private boolean hasDragged = false; private int touchPosX; private int touchPosY; private void editView(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: touchPosX = (int) e.getRawX(); touchPosY = (int) e.getRawY(); break; case MotionEvent.ACTION_MOVE: if (hasDragged) { int tmpTouchPosX = (int) e.getRawX(); int tmpTouchPosY = (int) e.getRawY(); //int lastPosX = DisplayUtils.getPxFromDp(mContext, getKeyPos()[0]); //int lastPosY = DisplayUtils.getPxFromDp(mContext, getKeyPos()[1]); //直接读入px的数值,而不是通过DisplayUtils进行转换,也许可以更精确 int lastPosX = (int) this.getX(); int lastPosY = (int) this.getY(); int dx = tmpTouchPosX - touchPosX; int dy = tmpTouchPosY - touchPosY; int viewWidth = getLayoutParams().width; int viewHeight = getLayoutParams().height; int posLeft = dx + lastPosX; int posTop = dy + lastPosY; int posRight = posLeft + viewWidth; int posBottom = posTop + viewHeight; int resultX = posLeft; int resultY = posTop; //判断边界 if (posLeft < 0) { resultX = 0; } if (posTop < 0) { resultY = 0; } if (posRight > screenWidth) { resultX = screenWidth - viewWidth; } if (posBottom > screenHeight) { resultY = screenHeight - viewHeight; } touchPosX = tmpTouchPosX; touchPosY = tmpTouchPosY; setKeyPos(DisplayUtils.getDpFromPx(mContext, resultX), DisplayUtils.getDpFromPx(mContext, resultY)); } else { if (Math.abs((int) e.getRawX() - touchPosX) >= MIN_MOVE_DISTANCE && Math.abs((int) e.getRawY() - touchPosY) >= MIN_MOVE_DISTANCE) { hasDragged = true; } } break; case MotionEvent.ACTION_UP: if (!hasDragged) { new GameButtonDialog(mContext, this, mManager).show(); } hasDragged = false; break; default: break; } } public void addSelfToParent() { mManager.addGameButton(this); } public void removeSelfFromParent() { mManager.removeGameButton(this); } @Override public boolean onTouch(View v, MotionEvent event) { if (v == this) { switch (this.buttonMode) { case MODE_GAME: if (this.isGrabbed && viewerFollow) { inputPointerEvent(event); } inputKeyEvent(event); break; case MODE_PREVIEW: case MODE_MOVEABLE_EDITABLE: editView(event); break; } return true; } return false; } public void updateUI() { //判断按键的显示/隐藏 switch (this.buttonMode) { case MODE_GAME: if (!isHide) { if (isGrabbed) { if (show == SHOW_ALL || show == SHOW_IN_GAME) { this.setVisibility(VISIBLE); } else { this.setVisibility(GONE); } } else { if (show == SHOW_ALL || show == SHOW_OUT_GAME) { this.setVisibility(VISIBLE); } else { this.setVisibility(GONE); } } } else { this.setVisibility(GONE); } break; case MODE_PREVIEW: case MODE_MOVEABLE_EDITABLE: if (this.getVisibility() == GONE) { this.setVisibility(VISIBLE); } break; } //刷新背景 this.setBackground(CkbThemeMarker.getDesign(mRecorder)); } //getter public int getButtonMode() { return buttonMode; } public String[] getKeyMaps() { return keyMaps; } public boolean isKeep() { return isKeep; } public String getBackColorHex() { return ColorUtils.int2Hex(mRecorder.getColor(0)); } public String getTextColorHex() { return ColorUtils.int2Hex(mRecorder.getTextColor()); } public float[] getKeyPos() { return keyPos; } public float[] getKeySize() { return keySize; } public int getTextProgress() { return textSize; } public int getCornerRadius() { return mRecorder.getCornerRadiusPt(); } public int getAlphaSize() { return alphaSize; } public String getKeyName() { return keyName; } public boolean isHide() { return isHide; } public boolean isFirstAdded() { return isFirstAdded; } public boolean isViewerFollow() { return viewerFollow; } public int getDesignIndex() { return mRecorder.getDesignIndex(); } public CkbThemeRecorder getThemeRecorder() { return this.mRecorder; } public int[] getKeyTypes() { return this.keyTypes; } public int getShow() { return this.show; } }
AOF-Dev/MCinaBox
app/src/main/java/com/aof/mcinabox/gamecontroller/ckb/button/GameButton.java
5,641
//是否是字符输入
line_comment
zh-cn
package com.aof.mcinabox.gamecontroller.ckb.button; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatButton; import com.aof.mcinabox.gamecontroller.ckb.achieve.CkbManager; import com.aof.mcinabox.gamecontroller.ckb.achieve.GameButtonDialog; import com.aof.mcinabox.gamecontroller.ckb.support.CallCustomizeKeyboard; import com.aof.mcinabox.gamecontroller.ckb.support.CkbThemeMarker; import com.aof.mcinabox.gamecontroller.ckb.support.CkbThemeRecorder; import com.aof.mcinabox.gamecontroller.controller.Controller; import com.aof.mcinabox.gamecontroller.event.BaseKeyEvent; import com.aof.mcinabox.utils.ColorUtils; import com.aof.mcinabox.utils.DisplayUtils; import org.apache.commons.text.StringEscapeUtils; import java.util.Arrays; import java.util.HashMap; import static androidx.core.math.MathUtils.clamp; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.KEYBOARD_BUTTON; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.MOUSE_BUTTON; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.MOUSE_POINTER; import static com.aof.mcinabox.gamecontroller.definitions.id.key.KeyEvent.MOUSE_POINTER_INC; @SuppressLint("ViewConstructor") public class GameButton extends AppCompatButton implements View.OnTouchListener { private final CallCustomizeKeyboard mCall; private final Controller mController; private final Context mContext; private final CkbManager mManager; private final Activity mActivity; private int buttonMode; private int screenWidth; private int screenHeight; public final static int MODE_MOVEABLE_EDITABLE = 1; public final static int MODE_PREVIEW = 2; public final static int MODE_GAME = 3; public final static int MAX_KEYMAP_SIZE = 4; public final static int MAX_KEY_SIZE_DP = 250; public final static int MIN_KEY_SIZE_DP = 20; public final static int MIN_TEXT_SIZE_SP = 2; public final static int MAX_TEXT_SIZE_SP = 20; public final static int MIN_ALPHA_SIZE_PT = 0; public final static int MAX_ALPHA_SIZE_PT = 100; public final static int MIN_CORNER_SIZE_PT = 0; public final static int MAX_CORNER_SIZE_PT = 100; public final static int MIN_MOVE_DISTANCE = 10; public final static int MAX_CHARS_LENTH = 50; public final static int DEFAULT_DESIGN_INDEX = CkbThemeMarker.DESIGN_SIGNLE_FILL; public final static int DEFAULT_BUTTON_MODE = MODE_MOVEABLE_EDITABLE; public final static int DEFAULT_KEY_SIZE_DP = 50; public final static int DEFAULT_CORNER_SIZE_PT = 20; public final static int DEFAULT_ALPHA_SIZE_PT = 70; public final static int DEFAULT_TEXT_SIZE_SP = 5; public final static String DEFAULT_BACK_COLOR_HEX = "#000000"; public final static String DEFAULT_TEXT_COLOR_HEX = "#FFFFFF"; private final static String TAG = "GameButton"; public final static int KEY_TYPE = KEYBOARD_BUTTON; public final static int POINTER_TYPE = MOUSE_POINTER; public final static int MOUSE_TYPE = MOUSE_BUTTON; public final static int SHOW_ALL = 0; public final static int SHOW_IN_GAME = 1; public final static int SHOW_OUT_GAME = 2; private String[] keyMaps; //最多映射N个按键 private int[] keyTypes; //映射的按键的类型 private CkbThemeRecorder mRecorder; //主题记录器 private boolean isKeep; //自动保持 private boolean isHide; //隐藏 private float[] keyPos; // leftPx , topPx private float[] keySize; // widthDp, heightDp private int alphaSize; //透明度百分比 private String keyName; //按键名 private int textSize; //字体大小 private boolean viewerFollow; //视角跟随 private boolean isGrabbed = false; //输入模式 |捕获|独立| private int show; private boolean isChars; //是否 <SUF> private String keyChars; //字符 private boolean isFirstAdded = false; //被首次创建 public GameButton(@NonNull Context context, @NonNull CallCustomizeKeyboard call, @NonNull CkbManager manager) { this(context, call, null, manager); } public GameButton(Context context, @NonNull CallCustomizeKeyboard call, @Nullable Controller controller, @NonNull CkbManager manager) { super(context); this.mContext = context; this.mCall = call; this.mController = controller; this.mManager = manager; if (mContext instanceof Activity) { this.mActivity = (Activity) mContext; } else { mActivity = null; } //初始化 init(); } @SuppressLint("ClickableViewAccessibility") private void init() { //添加params this.setLayoutParams(new ViewGroup.LayoutParams(0, 0)); //屏幕长宽 screenWidth = (mController == null) ? mManager.getDisplaySize()[0] : mController.getConfig().getScreenWidth(); screenHeight = (mController == null) ? mManager.getDisplaySize()[1] : mController.getConfig().getScreenHeight(); //设定监听 this.setOnTouchListener(this); //初始化状态列表 this.stateMap = new HashMap<>(); //初始化默认属性 initAttribute(); //更新UI updateUI(); } private void initAttribute() { if (mController != null) { this.isGrabbed = mController.isGrabbed(); } mRecorder = new CkbThemeRecorder(); this.setKeyName(""); this.setButtonMode(mManager.getButtonsMode()); this.setTextSize(DEFAULT_TEXT_SIZE_SP); String[] strs = new String[MAX_KEYMAP_SIZE]; Arrays.fill(strs, ""); this.setKeyMaps(strs); this.setKeyTypes(new int[]{KEY_TYPE, KEY_TYPE, KEY_TYPE, KEY_TYPE}); this.setShow(SHOW_ALL); this.setKeep(false); this.setViewerFollow(false); this.setBackColor(DEFAULT_BACK_COLOR_HEX); this.setTextColor(DEFAULT_TEXT_COLOR_HEX); this.setKeyPos(0, 0); this.setKeySize(DEFAULT_KEY_SIZE_DP, DEFAULT_KEY_SIZE_DP); this.setCornerRadius(DEFAULT_CORNER_SIZE_PT); this.setAlphaSize(DEFAULT_ALPHA_SIZE_PT); this.setDesignIndex(DEFAULT_DESIGN_INDEX); this.setInputChars(false); this.setChars(""); } public GameButton setInputChars(boolean b) { this.isChars = b; return this; } public boolean isInputChars() { return this.isChars; } public boolean setChars(String chars) { if (chars != null) { this.keyChars = chars; return true; } else { return false; } } public String getChars() { return this.keyChars; } public boolean setKeyMaps(String[] map) { if (map.length == MAX_KEYMAP_SIZE) { String[] tmp = new String[MAX_KEYMAP_SIZE]; System.arraycopy(map, 0, tmp, 0, MAX_KEYMAP_SIZE); this.keyMaps = tmp; return true; } else { return false; } } public boolean setKeyTypes(int[] types) { if (types.length == MAX_KEYMAP_SIZE) { int[] tmp = new int[MAX_KEYMAP_SIZE]; System.arraycopy(types, 0, tmp, 0, MAX_KEYMAP_SIZE); this.keyTypes = tmp; return true; } else { return false; } } public String[] setKeyMaps(String keyName, int index) { if (index > MAX_KEYMAP_SIZE || index < 0) { return null; } else { keyMaps[index] = keyName; return keyMaps; } } public GameButton setButtonMode(int mode) { if (mode == MODE_GAME || mode == MODE_MOVEABLE_EDITABLE || mode == MODE_PREVIEW) { this.buttonMode = mode; updateUI(); } return this; } public void setKeep(boolean isKeep) { this.isKeep = isKeep; } public void setHide(boolean isHide) { this.isHide = isHide; //UI刷新 updateUI(); } public boolean setBackColor(String colorHex) { int color = ColorUtils.hex2Int(colorHex); if (color != 0) { this.mRecorder.setColors(0, color); updateUI(); return true; } return false; } public boolean setTextColor(String colorHex) { int color = ColorUtils.hex2Int(colorHex); if (color != 0) { this.setTextColor(color); this.mRecorder.setTextColor(color); return true; } return false; } public float[] setKeyPos(float x, float y) { Log.e(TAG, "dpx: " + x + " dpy: " + y); int viewWidth = this.getLayoutParams().width; int viewHeight = this.getLayoutParams().height; int xPx = DisplayUtils.getPxFromDp(mContext, x); int yPx = DisplayUtils.getPxFromDp(mContext, y); float rx, ry; //Clamp between two extremes rx = clamp(xPx, 0f, (float) (screenWidth - viewWidth)); ry = clamp(yPx, 0f, (float) (screenHeight - viewHeight)); this.setX(rx); this.setY(ry); this.keyPos = new float[]{x, y}; return this.keyPos; //x ,y } //按键大小用Dp表示 public boolean setKeySize(float widthDp, float heightDp) { int widthPx = DisplayUtils.getPxFromDp(mContext, widthDp); int heightPx = DisplayUtils.getPxFromDp(mContext, heightDp); if ((widthDp <= MAX_KEY_SIZE_DP && heightDp <= MAX_KEY_SIZE_DP) && (widthDp >= MIN_KEY_SIZE_DP && heightDp >= MIN_KEY_SIZE_DP)) { ViewGroup.LayoutParams params = this.getLayoutParams(); params.width = widthPx; params.height = heightPx; this.requestLayout(); this.keySize = new float[]{widthDp, heightDp}; return true; } else { return false; } } public void setCornerRadius(int radius) { radius = clamp(radius, MIN_CORNER_SIZE_PT, MAX_CORNER_SIZE_PT); this.mRecorder.setCornerRadiusPt(radius); updateUI(); } public void setAlphaSize(int alphaPt) { alphaPt = clamp(alphaPt, MIN_ALPHA_SIZE_PT, MAX_ALPHA_SIZE_PT); this.setAlpha(alphaPt * 0.01f); this.alphaSize = alphaPt; } public boolean setKeyName(String str) { if (str != null) { this.setText(str); this.keyName = str; return true; } else { return false; } } public void setTextSize(int spValue) { spValue = clamp(spValue, MIN_TEXT_SIZE_SP, MAX_TEXT_SIZE_SP); this.setTextSize((float) DisplayUtils.getPxFromSp(mContext, spValue)); this.textSize = spValue; } public GameButton setShow(int s) { this.show = s; updateUI(); return this; } public GameButton setDesignIndex(int index) { this.mRecorder.setDesignIndex(index); updateUI(); return this; } public String[] getColorHexs() { int[] c = mRecorder.getColors(); String[] tmp = new String[CkbThemeRecorder.COLOR_INDEX_LENGTH]; int a; for (a = 0; a < c.length; a++) { tmp[a] = ColorUtils.int2Hex(c[a]); } return tmp; } public void setGrabbed(boolean mode) { this.isGrabbed = mode; //执行UI刷新 updateUI(); } public void setViewerFollow(boolean follow) { this.viewerFollow = follow; } public GameButton getNewButtonLikeThis() { GameButton g = new GameButton(mContext, mCall, mController, mManager); g.setButtonMode(this.buttonMode); g.setKeyName(this.keyName); g.setKeySize(this.keySize[0], this.keySize[1]); g.setKeyPos(this.keyPos[0], this.keyPos[1]); g.setKeyMaps(this.keyMaps); g.setKeyTypes(this.keyTypes); g.setBackColor(ColorUtils.int2Hex(mRecorder.getColor(0))); g.setTextColor(ColorUtils.int2Hex(mRecorder.getTextColor())); g.setAlphaSize(this.alphaSize); g.setCornerRadius(this.mRecorder.getCornerRadiusPt()); g.setTextSize(this.textSize); g.setKeep(this.isKeep); g.setHide(this.isHide); g.setShow(this.show); g.setViewerFollow(this.viewerFollow); g.setGrabbed(this.isGrabbed); g.setDesignIndex(this.mRecorder.getDesignIndex()); g.setInputChars(this.isChars); g.setChars(this.keyChars); return g; } private HashMap<String, Boolean> stateMap; private void sendKey(String keyName, boolean pressed, int type) { //该算法可以保证CustomizeKeyboard不会造成clientinput的setkey()方法堵塞; if (pressed) { if (stateMap.containsKey(keyName) && stateMap.get(keyName)) { return; } if (!stateMap.containsKey(keyName)) { stateMap.put(keyName, pressed); } if (stateMap.containsKey(keyName) && !stateMap.get(keyName)) { stateMap.remove(keyName); stateMap.put(keyName, pressed); } mController.sendKey(new BaseKeyEvent(TAG, keyName, pressed, type, null)); } else { if (stateMap.containsKey(keyName) && stateMap.get(keyName)) { stateMap.remove(keyName); stateMap.put(keyName, pressed); mController.sendKey(new BaseKeyEvent(TAG, keyName, pressed, type, null)); } } } public GameButton setFirstAdded() { this.isFirstAdded = true; return this; } public GameButton unsetFirstAdded() { this.isFirstAdded = false; return this; } private boolean isBeingPressed = false; private int initialX = 0; private int initialY = 0; private void inputPointerEvent(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: initialX = (int) e.getX(); initialY = (int) e.getY(); break; case MotionEvent.ACTION_MOVE: mController.sendKey(new BaseKeyEvent(TAG, null, false, MOUSE_POINTER_INC, new int[]{(int) (e.getX() - initialX), (int) (e.getY() - initialY)})); initialX = (int) e.getX(); initialY = (int) e.getY(); break; case MotionEvent.ACTION_UP: break; } } private void inputKeyEvent(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: if (isKeep && !isChars) { if (!isBeingPressed) { for (int a = 0; a < MAX_KEYMAP_SIZE; a++) { if (keyMaps[a] != null && !keyMaps[a].equals("")) { sendKey(keyMaps[a], true, keyTypes[a]); } } } } else { for (int a = 0; a < MAX_KEYMAP_SIZE; a++) { if (keyMaps[a] != null && !keyMaps[a].equals("")) { sendKey(keyMaps[a], true, keyTypes[a]); } } } break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: if (isKeep && !isChars) { if (isBeingPressed) { for (int a = 0; a < MAX_KEYMAP_SIZE; a++) { if (keyMaps[a] != null && !keyMaps[a].equals("")) { sendKey(keyMaps[a], false, keyTypes[a]); } } isBeingPressed = false; } else { isBeingPressed = true; } } else if (isChars) { mController.typeWords(convertStringWithASCII(this.keyChars)); } else { for (int a = 0; a < MAX_KEYMAP_SIZE; a++) { if (keyMaps[a] != null && !keyMaps[a].equals("")) { sendKey(keyMaps[a], false, keyTypes[a]); } } } break; default: break; } } private String convertStringWithASCII(String str) { if (str == null) return null; return StringEscapeUtils.unescapeJava(str); } private boolean hasDragged = false; private int touchPosX; private int touchPosY; private void editView(MotionEvent e) { switch (e.getAction()) { case MotionEvent.ACTION_DOWN: touchPosX = (int) e.getRawX(); touchPosY = (int) e.getRawY(); break; case MotionEvent.ACTION_MOVE: if (hasDragged) { int tmpTouchPosX = (int) e.getRawX(); int tmpTouchPosY = (int) e.getRawY(); //int lastPosX = DisplayUtils.getPxFromDp(mContext, getKeyPos()[0]); //int lastPosY = DisplayUtils.getPxFromDp(mContext, getKeyPos()[1]); //直接读入px的数值,而不是通过DisplayUtils进行转换,也许可以更精确 int lastPosX = (int) this.getX(); int lastPosY = (int) this.getY(); int dx = tmpTouchPosX - touchPosX; int dy = tmpTouchPosY - touchPosY; int viewWidth = getLayoutParams().width; int viewHeight = getLayoutParams().height; int posLeft = dx + lastPosX; int posTop = dy + lastPosY; int posRight = posLeft + viewWidth; int posBottom = posTop + viewHeight; int resultX = posLeft; int resultY = posTop; //判断边界 if (posLeft < 0) { resultX = 0; } if (posTop < 0) { resultY = 0; } if (posRight > screenWidth) { resultX = screenWidth - viewWidth; } if (posBottom > screenHeight) { resultY = screenHeight - viewHeight; } touchPosX = tmpTouchPosX; touchPosY = tmpTouchPosY; setKeyPos(DisplayUtils.getDpFromPx(mContext, resultX), DisplayUtils.getDpFromPx(mContext, resultY)); } else { if (Math.abs((int) e.getRawX() - touchPosX) >= MIN_MOVE_DISTANCE && Math.abs((int) e.getRawY() - touchPosY) >= MIN_MOVE_DISTANCE) { hasDragged = true; } } break; case MotionEvent.ACTION_UP: if (!hasDragged) { new GameButtonDialog(mContext, this, mManager).show(); } hasDragged = false; break; default: break; } } public void addSelfToParent() { mManager.addGameButton(this); } public void removeSelfFromParent() { mManager.removeGameButton(this); } @Override public boolean onTouch(View v, MotionEvent event) { if (v == this) { switch (this.buttonMode) { case MODE_GAME: if (this.isGrabbed && viewerFollow) { inputPointerEvent(event); } inputKeyEvent(event); break; case MODE_PREVIEW: case MODE_MOVEABLE_EDITABLE: editView(event); break; } return true; } return false; } public void updateUI() { //判断按键的显示/隐藏 switch (this.buttonMode) { case MODE_GAME: if (!isHide) { if (isGrabbed) { if (show == SHOW_ALL || show == SHOW_IN_GAME) { this.setVisibility(VISIBLE); } else { this.setVisibility(GONE); } } else { if (show == SHOW_ALL || show == SHOW_OUT_GAME) { this.setVisibility(VISIBLE); } else { this.setVisibility(GONE); } } } else { this.setVisibility(GONE); } break; case MODE_PREVIEW: case MODE_MOVEABLE_EDITABLE: if (this.getVisibility() == GONE) { this.setVisibility(VISIBLE); } break; } //刷新背景 this.setBackground(CkbThemeMarker.getDesign(mRecorder)); } //getter public int getButtonMode() { return buttonMode; } public String[] getKeyMaps() { return keyMaps; } public boolean isKeep() { return isKeep; } public String getBackColorHex() { return ColorUtils.int2Hex(mRecorder.getColor(0)); } public String getTextColorHex() { return ColorUtils.int2Hex(mRecorder.getTextColor()); } public float[] getKeyPos() { return keyPos; } public float[] getKeySize() { return keySize; } public int getTextProgress() { return textSize; } public int getCornerRadius() { return mRecorder.getCornerRadiusPt(); } public int getAlphaSize() { return alphaSize; } public String getKeyName() { return keyName; } public boolean isHide() { return isHide; } public boolean isFirstAdded() { return isFirstAdded; } public boolean isViewerFollow() { return viewerFollow; } public int getDesignIndex() { return mRecorder.getDesignIndex(); } public CkbThemeRecorder getThemeRecorder() { return this.mRecorder; } public int[] getKeyTypes() { return this.keyTypes; } public int getShow() { return this.show; } }
0
23791_5
package burp; import burp.application.ApiScanner; import burp.application.apitypes.ApiEndpoint; import burp.application.apitypes.ApiType; import burp.ui.ApiDocumentListTree; import burp.ui.ExtensionTab; import burp.utils.CommonUtils; import burp.utils.Constants; import burp.utils.UrlScanCount; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; public class PassiveScanner implements IScannerCheck { private final UrlScanCount scanedUrl = new UrlScanCount(); private final ApiScanner apiScanner; private int scannedCount = 1; public PassiveScanner() { this.apiScanner = new ApiScanner(); } public ApiScanner getApiScanner() { return apiScanner; } @Override public List<IScanIssue> doPassiveScan(IHttpRequestResponse httpRequestResponse) { URL httpRequestURL = BurpExtender.getHelpers().analyzeRequest(httpRequestResponse).getUrl(); String requestUrl = CommonUtils.getUrlWithoutFilename(httpRequestURL); // 目前检测的查重是将 http://user:pass@host:port/deep/path/filename?query#fragment // 归一化为 http://host:port/deep/path 后检测是否扫描过, 如果未来有对 query 有相关检测需求, 可以在修改 Common.getUrlWithoutFilename if (this.scanedUrl.get(requestUrl) <= 0) { this.scanedUrl.add(requestUrl); } else { return null; // 检测到重复, 直接返回 } ArrayList<ApiType> apiTypes = this.apiScanner.detect(httpRequestResponse, true); return this.parseApiDocument(apiTypes); } public List<IScanIssue> parseApiDocument(ArrayList<ApiType> apiTypes) { List<IScanIssue> issues = new ArrayList<>(); ExtensionTab extensionTab = BurpExtender.getExtensionTab(); //遍历扫到的ApiType for (ApiType apiType : apiTypes) { Map<String, IHttpRequestResponse> apiDocuments = apiType.getApiDocuments(); //遍历ApiType中的接口文档 for (Map.Entry<String, IHttpRequestResponse> entry : apiDocuments.entrySet()) { ApiDocumentListTree apiDocumentListTree = new ApiDocumentListTree(extensionTab); ExtensionTab.ApiTableData mainApiData = new ExtensionTab.ApiTableData(false, apiDocumentListTree, String.valueOf(this.scannedCount), entry.getKey(), String.valueOf(BurpExtender.getHelpers().analyzeResponse(entry.getValue().getResponse()).getStatusCode()), apiType.getApiTypeName(), "true", entry.getValue(), CommonUtils.getCurrentDateTime()); ArrayList<ExtensionTab.ApiTableData> subApiData = new ArrayList<>(); mainApiData.setTreeStatus(Constants.TREE_STATUS_COLLAPSE); apiDocumentListTree.setMainApiData(mainApiData); apiDocumentListTree.setSubApiData(subApiData); // 排序 List<ApiEndpoint> apiEndpoints = apiType.parseApiDocument(entry.getValue()); apiEndpoints.sort(Comparator.comparing(ApiEndpoint::getUrl)); // 遍历接口文档中的接口 for (ApiEndpoint apiEndpoint : apiEndpoints) { IHttpRequestResponse apiParseRequestResponse = apiEndpoint.getHttpRequestResponse(); ExtensionTab.ApiTableData currentData = new ExtensionTab.ApiTableData(true, apiDocumentListTree, "", apiEndpoint.getUrl(), String.valueOf(BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode()), apiType.getApiTypeName(), (BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 200 && BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 405 && BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 500 ? "false" : "true"), apiParseRequestResponse, CommonUtils.getCurrentDateTime()); subApiData.add(currentData); } extensionTab.add(apiDocumentListTree); this.scannedCount++; } // API 指纹检测 - 报告输出 issues.addAll(apiType.exportIssues()); // API 指纹检测 - 控制台报告输出 BurpExtender.getStdout().print(apiType.exportConsole()); } return issues; } @Override public List<IScanIssue> doActiveScan(IHttpRequestResponse httpRequestResponse, IScannerInsertionPoint insertionPoint) { return null; } @Override public int consolidateDuplicateIssues(IScanIssue existingIssue, IScanIssue newIssue) { if (existingIssue.getIssueName().equals(newIssue.getIssueName())) { return -1; } else { return 0; } } }
API-Security/APIKit
src/main/java/burp/PassiveScanner.java
1,146
// 遍历接口文档中的接口
line_comment
zh-cn
package burp; import burp.application.ApiScanner; import burp.application.apitypes.ApiEndpoint; import burp.application.apitypes.ApiType; import burp.ui.ApiDocumentListTree; import burp.ui.ExtensionTab; import burp.utils.CommonUtils; import burp.utils.Constants; import burp.utils.UrlScanCount; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; public class PassiveScanner implements IScannerCheck { private final UrlScanCount scanedUrl = new UrlScanCount(); private final ApiScanner apiScanner; private int scannedCount = 1; public PassiveScanner() { this.apiScanner = new ApiScanner(); } public ApiScanner getApiScanner() { return apiScanner; } @Override public List<IScanIssue> doPassiveScan(IHttpRequestResponse httpRequestResponse) { URL httpRequestURL = BurpExtender.getHelpers().analyzeRequest(httpRequestResponse).getUrl(); String requestUrl = CommonUtils.getUrlWithoutFilename(httpRequestURL); // 目前检测的查重是将 http://user:pass@host:port/deep/path/filename?query#fragment // 归一化为 http://host:port/deep/path 后检测是否扫描过, 如果未来有对 query 有相关检测需求, 可以在修改 Common.getUrlWithoutFilename if (this.scanedUrl.get(requestUrl) <= 0) { this.scanedUrl.add(requestUrl); } else { return null; // 检测到重复, 直接返回 } ArrayList<ApiType> apiTypes = this.apiScanner.detect(httpRequestResponse, true); return this.parseApiDocument(apiTypes); } public List<IScanIssue> parseApiDocument(ArrayList<ApiType> apiTypes) { List<IScanIssue> issues = new ArrayList<>(); ExtensionTab extensionTab = BurpExtender.getExtensionTab(); //遍历扫到的ApiType for (ApiType apiType : apiTypes) { Map<String, IHttpRequestResponse> apiDocuments = apiType.getApiDocuments(); //遍历ApiType中的接口文档 for (Map.Entry<String, IHttpRequestResponse> entry : apiDocuments.entrySet()) { ApiDocumentListTree apiDocumentListTree = new ApiDocumentListTree(extensionTab); ExtensionTab.ApiTableData mainApiData = new ExtensionTab.ApiTableData(false, apiDocumentListTree, String.valueOf(this.scannedCount), entry.getKey(), String.valueOf(BurpExtender.getHelpers().analyzeResponse(entry.getValue().getResponse()).getStatusCode()), apiType.getApiTypeName(), "true", entry.getValue(), CommonUtils.getCurrentDateTime()); ArrayList<ExtensionTab.ApiTableData> subApiData = new ArrayList<>(); mainApiData.setTreeStatus(Constants.TREE_STATUS_COLLAPSE); apiDocumentListTree.setMainApiData(mainApiData); apiDocumentListTree.setSubApiData(subApiData); // 排序 List<ApiEndpoint> apiEndpoints = apiType.parseApiDocument(entry.getValue()); apiEndpoints.sort(Comparator.comparing(ApiEndpoint::getUrl)); // 遍历 <SUF> for (ApiEndpoint apiEndpoint : apiEndpoints) { IHttpRequestResponse apiParseRequestResponse = apiEndpoint.getHttpRequestResponse(); ExtensionTab.ApiTableData currentData = new ExtensionTab.ApiTableData(true, apiDocumentListTree, "", apiEndpoint.getUrl(), String.valueOf(BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode()), apiType.getApiTypeName(), (BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 200 && BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 405 && BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 500 ? "false" : "true"), apiParseRequestResponse, CommonUtils.getCurrentDateTime()); subApiData.add(currentData); } extensionTab.add(apiDocumentListTree); this.scannedCount++; } // API 指纹检测 - 报告输出 issues.addAll(apiType.exportIssues()); // API 指纹检测 - 控制台报告输出 BurpExtender.getStdout().print(apiType.exportConsole()); } return issues; } @Override public List<IScanIssue> doActiveScan(IHttpRequestResponse httpRequestResponse, IScannerInsertionPoint insertionPoint) { return null; } @Override public int consolidateDuplicateIssues(IScanIssue existingIssue, IScanIssue newIssue) { if (existingIssue.getIssueName().equals(newIssue.getIssueName())) { return -1; } else { return 0; } } }
0
51723_2
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON) 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 apijson.demo; import java.net.URLDecoder; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import apijson.RequestMethod; import apijson.StringUtil; import apijson.framework.APIJSONController; import apijson.orm.Parser; /**请求路由入口控制器,包括通用增删改查接口等,转交给 APIJSON 的 Parser 来处理 * 具体见 SpringBoot 文档 * https://www.springcloud.cc/spring-boot.html#boot-features-spring-mvc * 以及 APIJSON 通用文档 3.设计规范 3.1 操作方法 * https://github.com/Tencent/APIJSON/blob/master/Document.md#3.1 * <br > 建议全通过HTTP POST来请求: * <br > 1.减少代码 - 客户端无需写HTTP GET,PUT等各种方式的请求代码 * <br > 2.提高性能 - 无需URL encode和decode * <br > 3.调试方便 - 建议使用 APIAuto(http://apijson.cn/api) 或 Postman * @author Lemon */ @RestController @RequestMapping("") public class DemoController extends APIJSONController<Long> { @Override public Parser<Long> newParser(HttpSession session, RequestMethod method) { return super.newParser(session, method).setNeedVerify(false); // TODO 这里关闭校验,方便新手快速测试,实际线上项目建议开启 } /**增删改查统一接口,这个一个接口可替代 7 个万能通用接口,牺牲一些路由解析性能来提升一点开发效率 * @param method * @param request * @param session * @return */ @PostMapping(value = "{method}") // 如果和其它的接口 URL 冲突,可以加前缀,例如改为 crud/{method} 或 Controller 注解 @RequestMapping("crud") @Override public String crud(@PathVariable String method, @RequestBody String request, HttpSession session) { return super.crud(method, request, session); } /**全能增删改查接口,可同时进行 增、删、改、查 多种操作, * 通过 @method: "POST", @gets: { "Privacy":"Privacy-CIRCLE", "User": { "@role":"LOGIN", "tag":"User" } } 等关键词指定 * @param request * @param session * @return */ @PostMapping(value = "crud") // 直接 {method} 或 apijson/{method} 会和内置网页的路由有冲突 // @Override public String crudAll(@RequestBody String request, HttpSession session) { return newParser(session, RequestMethod.CRUD).parse(request); } /**增删改查统一接口,这个一个接口可替代 7 个万能通用接口,牺牲一些路由解析性能来提升一点开发效率 * @param method * @param tag * @param params * @param request * @param session * @return */ @PostMapping("{method}/{tag}") // 如果和其它的接口 URL 冲突,可以加前缀,例如改为 crud/{method}/{tag} 或 Controller 注解 @RequestMapping("crud") @Override public String crudByTag(@PathVariable String method, @PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) { return super.crudByTag(method, tag, params, request, session); } /**获取 * 只为兼容HTTP GET请求,推荐用HTTP POST,可删除 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GET} */ @GetMapping("get/{request}") public String openGet(@PathVariable String request, HttpSession session) { try { request = URLDecoder.decode(request, StringUtil.UTF_8); } catch (Exception e) { // Parser 会报错 } return get(request, session); } }
APIJSON/APIJSON-Demo
APIJSON-Java-Server/APIJSONDemo/src/main/java/apijson/demo/DemoController.java
1,229
// TODO 这里关闭校验,方便新手快速测试,实际线上项目建议开启
line_comment
zh-cn
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON) 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 apijson.demo; import java.net.URLDecoder; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import apijson.RequestMethod; import apijson.StringUtil; import apijson.framework.APIJSONController; import apijson.orm.Parser; /**请求路由入口控制器,包括通用增删改查接口等,转交给 APIJSON 的 Parser 来处理 * 具体见 SpringBoot 文档 * https://www.springcloud.cc/spring-boot.html#boot-features-spring-mvc * 以及 APIJSON 通用文档 3.设计规范 3.1 操作方法 * https://github.com/Tencent/APIJSON/blob/master/Document.md#3.1 * <br > 建议全通过HTTP POST来请求: * <br > 1.减少代码 - 客户端无需写HTTP GET,PUT等各种方式的请求代码 * <br > 2.提高性能 - 无需URL encode和decode * <br > 3.调试方便 - 建议使用 APIAuto(http://apijson.cn/api) 或 Postman * @author Lemon */ @RestController @RequestMapping("") public class DemoController extends APIJSONController<Long> { @Override public Parser<Long> newParser(HttpSession session, RequestMethod method) { return super.newParser(session, method).setNeedVerify(false); // TO <SUF> } /**增删改查统一接口,这个一个接口可替代 7 个万能通用接口,牺牲一些路由解析性能来提升一点开发效率 * @param method * @param request * @param session * @return */ @PostMapping(value = "{method}") // 如果和其它的接口 URL 冲突,可以加前缀,例如改为 crud/{method} 或 Controller 注解 @RequestMapping("crud") @Override public String crud(@PathVariable String method, @RequestBody String request, HttpSession session) { return super.crud(method, request, session); } /**全能增删改查接口,可同时进行 增、删、改、查 多种操作, * 通过 @method: "POST", @gets: { "Privacy":"Privacy-CIRCLE", "User": { "@role":"LOGIN", "tag":"User" } } 等关键词指定 * @param request * @param session * @return */ @PostMapping(value = "crud") // 直接 {method} 或 apijson/{method} 会和内置网页的路由有冲突 // @Override public String crudAll(@RequestBody String request, HttpSession session) { return newParser(session, RequestMethod.CRUD).parse(request); } /**增删改查统一接口,这个一个接口可替代 7 个万能通用接口,牺牲一些路由解析性能来提升一点开发效率 * @param method * @param tag * @param params * @param request * @param session * @return */ @PostMapping("{method}/{tag}") // 如果和其它的接口 URL 冲突,可以加前缀,例如改为 crud/{method}/{tag} 或 Controller 注解 @RequestMapping("crud") @Override public String crudByTag(@PathVariable String method, @PathVariable String tag, @RequestParam Map<String, String> params, @RequestBody String request, HttpSession session) { return super.crudByTag(method, tag, params, request, session); } /**获取 * 只为兼容HTTP GET请求,推荐用HTTP POST,可删除 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GET} */ @GetMapping("get/{request}") public String openGet(@PathVariable String request, HttpSession session) { try { request = URLDecoder.decode(request, StringUtil.UTF_8); } catch (Exception e) { // Parser 会报错 } return get(request, session); } }
1
34218_37
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON) 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 apijson.framework; import static apijson.RequestMethod.DELETE; import static apijson.RequestMethod.GET; import static apijson.RequestMethod.GETS; import static apijson.RequestMethod.HEAD; import static apijson.RequestMethod.HEADS; import static apijson.RequestMethod.POST; import static apijson.RequestMethod.PUT; import static apijson.RequestMethod.CRUD; import static apijson.framework.APIJSONConstant.ACCESS_; import static apijson.framework.APIJSONConstant.METHODS; import static apijson.framework.APIJSONConstant.DEFAULTS; import static apijson.framework.APIJSONConstant.FORMAT; import static apijson.framework.APIJSONConstant.FUNCTION_; import static apijson.framework.APIJSONConstant.REQUEST_; import static apijson.framework.APIJSONConstant.VERSION; import static apijson.framework.APIJSONConstant.VISITOR_; import static apijson.framework.APIJSONConstant.VISITOR_ID; import java.lang.reflect.Method; import java.rmi.ServerException; import java.util.Map; import jakarta.servlet.AsyncContext; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import com.alibaba.fastjson.JSONObject; import apijson.JSON; import apijson.Log; import apijson.NotNull; import apijson.RequestMethod; import apijson.StringUtil; import apijson.orm.AbstractParser; import apijson.orm.Parser; import apijson.orm.Visitor; import unitauto.MethodUtil; import unitauto.MethodUtil.InterfaceProxy; /**APIJSON base controller,建议在子项目被 @RestController 注解的类继承它或通过它的实例调用相关方法 * <br > 全通过 HTTP POST 来请求: * <br > 1.减少代码 - 客户端无需写 HTTP GET, HTTP PUT 等各种方式的请求代码 * <br > 2.提高性能 - 无需 URL encode 和 decode * <br > 3.调试方便 - 建议使用 APIAuto-机器学习自动化接口管理工具(https://github.com/TommyLemon/APIAuto) * @author Lemon */ public class APIJSONController<T extends Object> { public static final String TAG = "APIJSONController"; @NotNull public static APIJSONCreator<? extends Object> APIJSON_CREATOR; static { APIJSON_CREATOR = new APIJSONCreator<>(); } public String getRequestURL() { return null; } public Parser<T> newParser(HttpSession session, RequestMethod method) { @SuppressWarnings("unchecked") Parser<T> parser = (Parser<T>) APIJSON_CREATOR.createParser(); parser.setMethod(method); if (parser instanceof APIJSONParser) { ((APIJSONParser<T>) parser).setSession(session); } // 可以更方便地通过日志排查错误 if (parser instanceof AbstractParser) { ((AbstractParser<T>) parser).setRequestURL(getRequestURL()); } return parser; } public String parse(RequestMethod method, String request, HttpSession session) { return newParser(session, method).parse(request); } public String parseByTag(RequestMethod method, String tag, Map<String, String> params, String request, HttpSession session) { JSONObject req = AbstractParser.wrapRequest(method, tag, JSON.parseObject(request), false); if (req == null) { req = new JSONObject(true); } if (params != null && params.isEmpty() == false) { req.putAll(params); } return newParser(session, method).parse(req); } //通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /**增删改查统一入口,这个一个方法可替代以下 7 个方法,牺牲一点路由解析性能来提升一些开发效率 * @param method * @param request * @param session * @return */ public String crud(String method, String request, HttpSession session) { if (METHODS.contains(method)) { return parse(RequestMethod.valueOf(method.toUpperCase()), request, session); } return APIJSONParser.newErrorResult(new IllegalArgumentException("URL 路径 /{method} 中 method 值 " + method + " 错误!只允许 " + METHODS + " 中的一个!")).toJSONString(); } /**获取 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GET} */ public String get(String request, HttpSession session) { return parse(GET, request, session); } /**计数 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#HEAD} */ public String head(String request, HttpSession session) { return parse(HEAD, request, session); } /**限制性GET,request和response都非明文,浏览器看不到,用于对安全性要求高的GET请求 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GETS} */ public String gets(String request, HttpSession session) { return parse(GETS, request, session); } /**限制性HEAD,request和response都非明文,浏览器看不到,用于对安全性要求高的HEAD请求 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#HEADS} */ public String heads(String request, HttpSession session) { return parse(HEADS, request, session); } /**新增 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#POST} */ public String post(String request, HttpSession session) { return parse(POST, request, session); } /**修改 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#PUT} */ public String put(String request, HttpSession session) { return parse(PUT, request, session); } /**删除 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#DELETE} */ public String delete(String request, HttpSession session) { return parse(DELETE, request, session); } /**支持全局事物、批量执行多条语句 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GET} */ public String crud(String request, HttpSession session) { return parse(CRUD, request, session); } //通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /**增删改查统一入口,这个一个方法可替代以下 7 个方法,牺牲一些路由解析性能来提升一点开发效率 * @param method * @param tag * @param params * @param request * @param session * @return */ public String crudByTag(String method, String tag, Map<String, String> params, String request, HttpSession session) { if (METHODS.contains(method)) { return parseByTag(RequestMethod.valueOf(method.toUpperCase()), tag, params, request, session); } return APIJSONParser.newErrorResult(new IllegalArgumentException("URL 路径 /{method}/{tag} 中 method 值 " + method + " 错误!只允许 " + METHODS + " 中的一个!")).toJSONString(); } // /**获取列表 // * @param request 只用String,避免encode后未decode // * @param session // * @return // * @see {@link RequestMethod#GET} // */ // public String listByTag(String tag, String request, HttpSession session) { // return parseByTag(GET, tag + JSONRequest.KEY_ARRAY, request, session); // } /**获取 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GET} */ public String getByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(GET, tag, params, request, session); } /**计数 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#HEAD} */ public String headByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(HEAD, tag, params, request, session); } /**限制性GET,request和response都非明文,浏览器看不到,用于对安全性要求高的GET请求 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GETS} */ public String getsByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(GETS, tag, params, request, session); } /**限制性HEAD,request和response都非明文,浏览器看不到,用于对安全性要求高的HEAD请求 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#HEADS} */ public String headsByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(HEADS, tag, params, request, session); } /**新增 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#POST} */ public String postByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(POST, tag, params, request, session); } /**修改 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#PUT} */ public String putByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(PUT, tag, params, request, session); } /**删除 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#DELETE} */ public String deleteByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(DELETE, tag, params, request, session); } //通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /**重新加载配置 * @return * @see * <pre> { "type": "ALL", //重载对象,ALL, FUNCTION, REQUEST, ACCESS,非必须 "phone": "13000082001", "verify": "1234567" //验证码,对应类型为 Verify.TYPE_RELOAD } * </pre> */ public JSONObject reload(String type) { JSONObject result = APIJSONParser.newSuccessResult(); boolean reloadAll = StringUtil.isEmpty(type, true) || "ALL".equals(type); if (reloadAll || "ACCESS".equals(type)) { try { if (reloadAll == false && APIJSONVerifier.ENABLE_VERIFY_ROLE == false) { throw new UnsupportedOperationException("AbstractVerifier.ENABLE_VERIFY_ROLE == false 时不支持校验角色权限!" + "如需支持则设置 AbstractVerifier.ENABLE_VERIFY_ROLE = true !"); } if (APIJSONVerifier.ENABLE_VERIFY_ROLE) { result.put(ACCESS_, APIJSONVerifier.initAccess()); } } catch (ServerException e) { e.printStackTrace(); result.put(ACCESS_, APIJSONParser.newErrorResult(e)); } } if (reloadAll || "FUNCTION".equals(type)) { try { if (reloadAll == false && APIJSONFunctionParser.ENABLE_REMOTE_FUNCTION == false) { throw new UnsupportedOperationException("AbstractFunctionParser.ENABLE_REMOTE_FUNCTION" + " == false 时不支持远程函数!如需支持则设置 AbstractFunctionParser.ENABLE_REMOTE_FUNCTION = true !"); } if (APIJSONFunctionParser.ENABLE_REMOTE_FUNCTION) { result.put(FUNCTION_, APIJSONFunctionParser.init()); } } catch (ServerException e) { e.printStackTrace(); result.put(FUNCTION_, APIJSONParser.newErrorResult(e)); } } if (reloadAll || "REQUEST".equals(type)) { try { if (reloadAll == false && APIJSONVerifier.ENABLE_VERIFY_CONTENT == false) { throw new UnsupportedOperationException("AbstractVerifier.ENABLE_VERIFY_CONTENT == false 时不支持校验请求传参内容!" + "如需支持则设置 AbstractVerifier.ENABLE_VERIFY_CONTENT = true !"); } if (APIJSONVerifier.ENABLE_VERIFY_CONTENT) { result.put(REQUEST_, APIJSONVerifier.initRequest()); } } catch (ServerException e) { e.printStackTrace(); result.put(REQUEST_, APIJSONParser.newErrorResult(e)); } } return result; } /**用户登录 * @param session * @param visitor * @param version * @param format * @param defaults * @return 返回类型设置为 Object 是为了子类重写时可以有返回值,避免因为冲突而另写一个有返回值的登录方法 */ public Object login(@NotNull HttpSession session, Visitor<Long> visitor, Integer version, Boolean format, JSONObject defaults) { //登录状态保存至session session.setAttribute(VISITOR_ID, visitor.getId()); //用户id session.setAttribute(VISITOR_, visitor); //用户 session.setAttribute(VERSION, version); //全局默认版本号 session.setAttribute(FORMAT, format); //全局默认格式化配置 session.setAttribute(DEFAULTS, defaults); //给每个请求JSON最外层加的字段 return null; } /**退出登录,清空session * @param session * @return 返回类型设置为 Object 是为了子类重写时可以有返回值,避免因为冲突而另写一个有返回值的登录方法 */ public Object logout(@NotNull HttpSession session) { Object userId = APIJSONVerifier.getVisitorId(session);//必须在session.invalidate();前! Log.d(TAG, "logout userId = " + userId + "; session.getId() = " + (session == null ? null : session.getId())); session.invalidate(); return null; } public JSONObject listMethod(String request) { if (Log.DEBUG == false) { return APIJSONParser.newErrorResult(new IllegalAccessException("非 DEBUG 模式下不允许使用 UnitAuto 单元测试!")); } return MethodUtil.listMethod(request); } public void invokeMethod(String request, HttpServletRequest servletRequest) { AsyncContext asyncContext = servletRequest.startAsync(); final boolean[] called = new boolean[] { false }; MethodUtil.Listener<JSONObject> listener = new MethodUtil.Listener<JSONObject>() { @Override public void complete(JSONObject data, Method method, InterfaceProxy proxy, Object... extras) throws Exception { ServletResponse servletResponse = called[0] ? null : asyncContext.getResponse(); if (servletResponse == null) { // || servletResponse.isCommitted()) { // isCommitted 在高并发时可能不准,导致写入多次 Log.w(TAG, "invokeMethod listener.complete servletResponse == null || servletResponse.isCommitted() >> return;"); return; } called[0] = true; servletResponse.setCharacterEncoding(servletRequest.getCharacterEncoding()); servletResponse.setContentType(servletRequest.getContentType()); servletResponse.getWriter().println(data); asyncContext.complete(); } }; if (Log.DEBUG == false) { try { listener.complete(MethodUtil.JSON_CALLBACK.newErrorResult(new IllegalAccessException("非 DEBUG 模式下不允许使用 UnitAuto 单元测试!"))); } catch (Exception e1) { e1.printStackTrace(); asyncContext.complete(); } return; } try { MethodUtil.invokeMethod(request, null, listener); } catch (Exception e) { Log.e(TAG, "invokeMethod try { JSONObject req = JSON.parseObject(request); ... } catch (Exception e) { \n" + e.getMessage()); try { listener.complete(MethodUtil.JSON_CALLBACK.newErrorResult(e)); } catch (Exception e1) { e1.printStackTrace(); asyncContext.complete(); } } } }
APIJSON/apijson-framework
src/main/java/apijson/framework/APIJSONController.java
4,375
//给每个请求JSON最外层加的字段
line_comment
zh-cn
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON) 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 apijson.framework; import static apijson.RequestMethod.DELETE; import static apijson.RequestMethod.GET; import static apijson.RequestMethod.GETS; import static apijson.RequestMethod.HEAD; import static apijson.RequestMethod.HEADS; import static apijson.RequestMethod.POST; import static apijson.RequestMethod.PUT; import static apijson.RequestMethod.CRUD; import static apijson.framework.APIJSONConstant.ACCESS_; import static apijson.framework.APIJSONConstant.METHODS; import static apijson.framework.APIJSONConstant.DEFAULTS; import static apijson.framework.APIJSONConstant.FORMAT; import static apijson.framework.APIJSONConstant.FUNCTION_; import static apijson.framework.APIJSONConstant.REQUEST_; import static apijson.framework.APIJSONConstant.VERSION; import static apijson.framework.APIJSONConstant.VISITOR_; import static apijson.framework.APIJSONConstant.VISITOR_ID; import java.lang.reflect.Method; import java.rmi.ServerException; import java.util.Map; import jakarta.servlet.AsyncContext; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import com.alibaba.fastjson.JSONObject; import apijson.JSON; import apijson.Log; import apijson.NotNull; import apijson.RequestMethod; import apijson.StringUtil; import apijson.orm.AbstractParser; import apijson.orm.Parser; import apijson.orm.Visitor; import unitauto.MethodUtil; import unitauto.MethodUtil.InterfaceProxy; /**APIJSON base controller,建议在子项目被 @RestController 注解的类继承它或通过它的实例调用相关方法 * <br > 全通过 HTTP POST 来请求: * <br > 1.减少代码 - 客户端无需写 HTTP GET, HTTP PUT 等各种方式的请求代码 * <br > 2.提高性能 - 无需 URL encode 和 decode * <br > 3.调试方便 - 建议使用 APIAuto-机器学习自动化接口管理工具(https://github.com/TommyLemon/APIAuto) * @author Lemon */ public class APIJSONController<T extends Object> { public static final String TAG = "APIJSONController"; @NotNull public static APIJSONCreator<? extends Object> APIJSON_CREATOR; static { APIJSON_CREATOR = new APIJSONCreator<>(); } public String getRequestURL() { return null; } public Parser<T> newParser(HttpSession session, RequestMethod method) { @SuppressWarnings("unchecked") Parser<T> parser = (Parser<T>) APIJSON_CREATOR.createParser(); parser.setMethod(method); if (parser instanceof APIJSONParser) { ((APIJSONParser<T>) parser).setSession(session); } // 可以更方便地通过日志排查错误 if (parser instanceof AbstractParser) { ((AbstractParser<T>) parser).setRequestURL(getRequestURL()); } return parser; } public String parse(RequestMethod method, String request, HttpSession session) { return newParser(session, method).parse(request); } public String parseByTag(RequestMethod method, String tag, Map<String, String> params, String request, HttpSession session) { JSONObject req = AbstractParser.wrapRequest(method, tag, JSON.parseObject(request), false); if (req == null) { req = new JSONObject(true); } if (params != null && params.isEmpty() == false) { req.putAll(params); } return newParser(session, method).parse(req); } //通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /**增删改查统一入口,这个一个方法可替代以下 7 个方法,牺牲一点路由解析性能来提升一些开发效率 * @param method * @param request * @param session * @return */ public String crud(String method, String request, HttpSession session) { if (METHODS.contains(method)) { return parse(RequestMethod.valueOf(method.toUpperCase()), request, session); } return APIJSONParser.newErrorResult(new IllegalArgumentException("URL 路径 /{method} 中 method 值 " + method + " 错误!只允许 " + METHODS + " 中的一个!")).toJSONString(); } /**获取 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GET} */ public String get(String request, HttpSession session) { return parse(GET, request, session); } /**计数 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#HEAD} */ public String head(String request, HttpSession session) { return parse(HEAD, request, session); } /**限制性GET,request和response都非明文,浏览器看不到,用于对安全性要求高的GET请求 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GETS} */ public String gets(String request, HttpSession session) { return parse(GETS, request, session); } /**限制性HEAD,request和response都非明文,浏览器看不到,用于对安全性要求高的HEAD请求 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#HEADS} */ public String heads(String request, HttpSession session) { return parse(HEADS, request, session); } /**新增 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#POST} */ public String post(String request, HttpSession session) { return parse(POST, request, session); } /**修改 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#PUT} */ public String put(String request, HttpSession session) { return parse(PUT, request, session); } /**删除 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#DELETE} */ public String delete(String request, HttpSession session) { return parse(DELETE, request, session); } /**支持全局事物、批量执行多条语句 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GET} */ public String crud(String request, HttpSession session) { return parse(CRUD, request, session); } //通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< /**增删改查统一入口,这个一个方法可替代以下 7 个方法,牺牲一些路由解析性能来提升一点开发效率 * @param method * @param tag * @param params * @param request * @param session * @return */ public String crudByTag(String method, String tag, Map<String, String> params, String request, HttpSession session) { if (METHODS.contains(method)) { return parseByTag(RequestMethod.valueOf(method.toUpperCase()), tag, params, request, session); } return APIJSONParser.newErrorResult(new IllegalArgumentException("URL 路径 /{method}/{tag} 中 method 值 " + method + " 错误!只允许 " + METHODS + " 中的一个!")).toJSONString(); } // /**获取列表 // * @param request 只用String,避免encode后未decode // * @param session // * @return // * @see {@link RequestMethod#GET} // */ // public String listByTag(String tag, String request, HttpSession session) { // return parseByTag(GET, tag + JSONRequest.KEY_ARRAY, request, session); // } /**获取 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GET} */ public String getByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(GET, tag, params, request, session); } /**计数 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#HEAD} */ public String headByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(HEAD, tag, params, request, session); } /**限制性GET,request和response都非明文,浏览器看不到,用于对安全性要求高的GET请求 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#GETS} */ public String getsByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(GETS, tag, params, request, session); } /**限制性HEAD,request和response都非明文,浏览器看不到,用于对安全性要求高的HEAD请求 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#HEADS} */ public String headsByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(HEADS, tag, params, request, session); } /**新增 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#POST} */ public String postByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(POST, tag, params, request, session); } /**修改 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#PUT} */ public String putByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(PUT, tag, params, request, session); } /**删除 * @param request 只用String,避免encode后未decode * @param session * @return * @see {@link RequestMethod#DELETE} */ public String deleteByTag(String tag, Map<String, String> params, String request, HttpSession session) { return parseByTag(DELETE, tag, params, request, session); } //通用接口,非事务型操作 和 简单事务型操作 都可通过这些接口自动化实现>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> /**重新加载配置 * @return * @see * <pre> { "type": "ALL", //重载对象,ALL, FUNCTION, REQUEST, ACCESS,非必须 "phone": "13000082001", "verify": "1234567" //验证码,对应类型为 Verify.TYPE_RELOAD } * </pre> */ public JSONObject reload(String type) { JSONObject result = APIJSONParser.newSuccessResult(); boolean reloadAll = StringUtil.isEmpty(type, true) || "ALL".equals(type); if (reloadAll || "ACCESS".equals(type)) { try { if (reloadAll == false && APIJSONVerifier.ENABLE_VERIFY_ROLE == false) { throw new UnsupportedOperationException("AbstractVerifier.ENABLE_VERIFY_ROLE == false 时不支持校验角色权限!" + "如需支持则设置 AbstractVerifier.ENABLE_VERIFY_ROLE = true !"); } if (APIJSONVerifier.ENABLE_VERIFY_ROLE) { result.put(ACCESS_, APIJSONVerifier.initAccess()); } } catch (ServerException e) { e.printStackTrace(); result.put(ACCESS_, APIJSONParser.newErrorResult(e)); } } if (reloadAll || "FUNCTION".equals(type)) { try { if (reloadAll == false && APIJSONFunctionParser.ENABLE_REMOTE_FUNCTION == false) { throw new UnsupportedOperationException("AbstractFunctionParser.ENABLE_REMOTE_FUNCTION" + " == false 时不支持远程函数!如需支持则设置 AbstractFunctionParser.ENABLE_REMOTE_FUNCTION = true !"); } if (APIJSONFunctionParser.ENABLE_REMOTE_FUNCTION) { result.put(FUNCTION_, APIJSONFunctionParser.init()); } } catch (ServerException e) { e.printStackTrace(); result.put(FUNCTION_, APIJSONParser.newErrorResult(e)); } } if (reloadAll || "REQUEST".equals(type)) { try { if (reloadAll == false && APIJSONVerifier.ENABLE_VERIFY_CONTENT == false) { throw new UnsupportedOperationException("AbstractVerifier.ENABLE_VERIFY_CONTENT == false 时不支持校验请求传参内容!" + "如需支持则设置 AbstractVerifier.ENABLE_VERIFY_CONTENT = true !"); } if (APIJSONVerifier.ENABLE_VERIFY_CONTENT) { result.put(REQUEST_, APIJSONVerifier.initRequest()); } } catch (ServerException e) { e.printStackTrace(); result.put(REQUEST_, APIJSONParser.newErrorResult(e)); } } return result; } /**用户登录 * @param session * @param visitor * @param version * @param format * @param defaults * @return 返回类型设置为 Object 是为了子类重写时可以有返回值,避免因为冲突而另写一个有返回值的登录方法 */ public Object login(@NotNull HttpSession session, Visitor<Long> visitor, Integer version, Boolean format, JSONObject defaults) { //登录状态保存至session session.setAttribute(VISITOR_ID, visitor.getId()); //用户id session.setAttribute(VISITOR_, visitor); //用户 session.setAttribute(VERSION, version); //全局默认版本号 session.setAttribute(FORMAT, format); //全局默认格式化配置 session.setAttribute(DEFAULTS, defaults); //给每 <SUF> return null; } /**退出登录,清空session * @param session * @return 返回类型设置为 Object 是为了子类重写时可以有返回值,避免因为冲突而另写一个有返回值的登录方法 */ public Object logout(@NotNull HttpSession session) { Object userId = APIJSONVerifier.getVisitorId(session);//必须在session.invalidate();前! Log.d(TAG, "logout userId = " + userId + "; session.getId() = " + (session == null ? null : session.getId())); session.invalidate(); return null; } public JSONObject listMethod(String request) { if (Log.DEBUG == false) { return APIJSONParser.newErrorResult(new IllegalAccessException("非 DEBUG 模式下不允许使用 UnitAuto 单元测试!")); } return MethodUtil.listMethod(request); } public void invokeMethod(String request, HttpServletRequest servletRequest) { AsyncContext asyncContext = servletRequest.startAsync(); final boolean[] called = new boolean[] { false }; MethodUtil.Listener<JSONObject> listener = new MethodUtil.Listener<JSONObject>() { @Override public void complete(JSONObject data, Method method, InterfaceProxy proxy, Object... extras) throws Exception { ServletResponse servletResponse = called[0] ? null : asyncContext.getResponse(); if (servletResponse == null) { // || servletResponse.isCommitted()) { // isCommitted 在高并发时可能不准,导致写入多次 Log.w(TAG, "invokeMethod listener.complete servletResponse == null || servletResponse.isCommitted() >> return;"); return; } called[0] = true; servletResponse.setCharacterEncoding(servletRequest.getCharacterEncoding()); servletResponse.setContentType(servletRequest.getContentType()); servletResponse.getWriter().println(data); asyncContext.complete(); } }; if (Log.DEBUG == false) { try { listener.complete(MethodUtil.JSON_CALLBACK.newErrorResult(new IllegalAccessException("非 DEBUG 模式下不允许使用 UnitAuto 单元测试!"))); } catch (Exception e1) { e1.printStackTrace(); asyncContext.complete(); } return; } try { MethodUtil.invokeMethod(request, null, listener); } catch (Exception e) { Log.e(TAG, "invokeMethod try { JSONObject req = JSON.parseObject(request); ... } catch (Exception e) { \n" + e.getMessage()); try { listener.complete(MethodUtil.JSON_CALLBACK.newErrorResult(e)); } catch (Exception e1) { e1.printStackTrace(); asyncContext.complete(); } } } }
0
50873_10
package example.ricktextview.view.richtext; /** * 表情工具类 */ import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.style.CharacterStyle; import android.text.style.ForegroundColorSpan; import android.widget.EditText; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import example.ricktextview.R; import example.ricktextview.view.richtext.span.CenteredImageSpan; import static android.text.style.DynamicDrawableSpan.ALIGN_BOTTOM; public class SmileUtils { private static final Spannable.Factory spannableFactory = Spannable.Factory .getInstance(); private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>(); private static final List<String> textList = new ArrayList<>(); public Map<Pattern, Integer> getEmotions() { return emoticons; } public static final String f1 = "[汗]"; public static final String f2 = "[发呆]"; public static final String f3 = "[眨眼]"; public static final String f4 = "[痛哭]"; public static final String f5 = "[傻萌]"; public static final String f6 = "[惊恐]"; public static final String f7 = "[流口水]"; public static final String f8 = "[冷漠]"; public static final String f9 = "[乖巧]"; public static final String f10 = "[可爱]"; public static final String f11 = "[抓狂]"; public static final String f12 = "[邪恶]"; public static final String f13 = "[笑哭]"; public static final String f14 = "[得意]"; public static final String f15 = "[抽烟]"; public static final String f16 = "[示爱]"; public static final String f17 = "[输入]"; public static final String f18 = "[无语]"; public static final String f19 = "[大眼崽]"; public static final String f20 = "[微笑]"; public static final String f21 = "[财迷]"; public static final String f22 = "[开心]"; public static final String f23 = "[糗大了]"; public static final String f24 = "[感冒]"; public static final String f25 = "[调皮]"; public static final String f26 = "[尴尬]"; public static final String f27 = "[色迷迷]"; public static final String f28 = "[大笑]"; public static final String f29 = "[笑眯眯]"; public static final String f30 = "[爱你哟]"; public static final String f31 = "[纠结]"; public static final String f32 = "[惊呆]"; public static final String f33 = "[思考]"; public static final String f34 = "[拳头]"; public static final String f35 = "[炸弹]"; public static final String f36 = "[公平]"; public static final String f37 = "[手]"; public static final String f38 = "[朋友]"; public static final String f39 = "[手牵手]"; public static final String f40 = "[美眉]"; public static final String f41 = "[合照]"; public static final String f42 = "[全家福]"; public static final String f43 = "[财迷]"; public static final String f44 = "[臭气熏天]"; public static final String f45 = "[胜利]"; public static final String f46 = "[保密]"; public static final String f47 = "[语音]"; public static final String f48 = "[信封]"; public static final String f49 = "[手机]"; public static final String f50 = "[答卷]"; public static final String f51 = "[合影]"; public static final String f52 = "[电脑]"; public static final String f53 = "[日历]"; public static final String f54 = "[电话]"; public static final String f55 = "[情书]"; public static final String f56 = "[可怜]"; public static final String f57 = "[睡觉]"; public static final String f58 = "[大骂]"; public static final String f59 = "[害羞]"; public static final String f60 = "[撇嘴]"; public static final String f61 = "[闭嘴]"; static { addPattern(emoticons, addResString(f1), R.drawable.f1); addPattern(emoticons, addResString(f2), R.drawable.f2); addPattern(emoticons, addResString(f3), R.drawable.f3); addPattern(emoticons, addResString(f4), R.drawable.f4); addPattern(emoticons, addResString(f5), R.drawable.f5); addPattern(emoticons, addResString(f6), R.drawable.f6); addPattern(emoticons, addResString(f7), R.drawable.f7); addPattern(emoticons, addResString(f8), R.drawable.f8); addPattern(emoticons, addResString(f9), R.drawable.f9); addPattern(emoticons, addResString(f10), R.drawable.f10); addPattern(emoticons, addResString(f11), R.drawable.f11); addPattern(emoticons, addResString(f12), R.drawable.f12); addPattern(emoticons, addResString(f13), R.drawable.f13); addPattern(emoticons, addResString(f14), R.drawable.f14); addPattern(emoticons, addResString(f15), R.drawable.f15); addPattern(emoticons, addResString(f16), R.drawable.f16); addPattern(emoticons, addResString(f17), R.drawable.f17); addPattern(emoticons, addResString(f18), R.drawable.f18); addPattern(emoticons, addResString(f19), R.drawable.f19); addPattern(emoticons, addResString(f20), R.drawable.f20); addPattern(emoticons, addResString(f21), R.drawable.f21); addPattern(emoticons, addResString(f22), R.drawable.f22); addPattern(emoticons, addResString(f23), R.drawable.f23); addPattern(emoticons, addResString(f24), R.drawable.f24); addPattern(emoticons, addResString(f25), R.drawable.f25); addPattern(emoticons, addResString(f26), R.drawable.f26); addPattern(emoticons, addResString(f27), R.drawable.f27); addPattern(emoticons, addResString(f28), R.drawable.f28); addPattern(emoticons, addResString(f29), R.drawable.f29); addPattern(emoticons, addResString(f30), R.drawable.f30); addPattern(emoticons, addResString(f31), R.drawable.f31); addPattern(emoticons, addResString(f32), R.drawable.f32); addPattern(emoticons, addResString(f33), R.drawable.f33); addPattern(emoticons, addResString(f34), R.drawable.f34); addPattern(emoticons, addResString(f35), R.drawable.f35); addPattern(emoticons, addResString(f36), R.drawable.f36); addPattern(emoticons, addResString(f37), R.drawable.f37); addPattern(emoticons, addResString(f38), R.drawable.f38); addPattern(emoticons, addResString(f39), R.drawable.f39); addPattern(emoticons, addResString(f40), R.drawable.f40); addPattern(emoticons, addResString(f41), R.drawable.f41); addPattern(emoticons, addResString(f42), R.drawable.f42); addPattern(emoticons, addResString(f43), R.drawable.f43); addPattern(emoticons, addResString(f44), R.drawable.f44); addPattern(emoticons, addResString(f45), R.drawable.f45); addPattern(emoticons, addResString(f46), R.drawable.f46); addPattern(emoticons, addResString(f47), R.drawable.f47); addPattern(emoticons, addResString(f48), R.drawable.f48); addPattern(emoticons, addResString(f49), R.drawable.f49); addPattern(emoticons, addResString(f50), R.drawable.f50); addPattern(emoticons, addResString(f51), R.drawable.f51); addPattern(emoticons, addResString(f52), R.drawable.f52); addPattern(emoticons, addResString(f53), R.drawable.f53); addPattern(emoticons, addResString(f54), R.drawable.f54); addPattern(emoticons, addResString(f55), R.drawable.f55); addPattern(emoticons, addResString(f56), R.drawable.f56); addPattern(emoticons, addResString(f57), R.drawable.f57); addPattern(emoticons, addResString(f58), R.drawable.f58); addPattern(emoticons, addResString(f59), R.drawable.f59); addPattern(emoticons, addResString(f60), R.drawable.f60); addPattern(emoticons, addResString(f61), R.drawable.f61); } /** * 添加到map * * @param map map * @param smile 文本 * @param resource 显示图片表情列表 */ private static void addPattern(Map<Pattern, Integer> map, String smile, int resource) { map.put(Pattern.compile(Pattern.quote(smile)), resource); } /** * 使用你自己的map * * @param map map * @param smile 文本列表 * @param resource 显示图片表情列表 */ public static void addPatternAll(Map<Pattern, Integer> map, List<String> smile, List<Integer> resource) { map.clear(); textList.clear(); if (smile.size() != resource.size()) { try { throw new Exception("**********文本与图片list不相等"); } catch (Exception e) { e.printStackTrace(); } return; } textList.addAll(smile); for (int i = 0; i < smile.size(); i++) { map.put(Pattern.compile(Pattern.quote(smile.get(i))), resource.get(i)); } } public static String addResString(String resString) { textList.add(resString); return resString; } /*** * 文本对应的资源 * * @param string 需要转化文本 * @return */ public static int getRedId(String string) { for (Map.Entry<Pattern, Integer> entry : emoticons.entrySet()) { Matcher matcher = entry.getKey().matcher(string); while (matcher.find()) { return entry.getValue(); } } return -1; } /** * 文本转化表情处理 * * @param editText 要显示的EditText * @param maxLength 最长高度 * @param size 显示大小 * @param name 需要转化的文本 */ public static void insertIcon(EditText editText, int maxLength, int size, String name) { String curString = editText.toString(); if ((curString.length() + name.length()) > maxLength) { return; } int resId = SmileUtils.getRedId(name); Drawable drawable = editText.getResources().getDrawable(resId); if (drawable == null) return; drawable.setBounds(0, 0, size, size);//这里设置图片的大小 CenteredImageSpan CenteredImageSpan = new CenteredImageSpan(drawable); SpannableString spannableString = new SpannableString(name); spannableString.setSpan(CenteredImageSpan, 0, spannableString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE); int index = Math.max(editText.getSelectionStart(), 0); SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(editText.getText()); spannableStringBuilder.insert(index, spannableString); editText.setText(spannableStringBuilder); editText.setSelection(index + spannableString.length()); } /** * replace existing spannable with smiles * * @param context 上下文 * @param spannable 显示的span * @return 是否添加 */ public static boolean addSmiles(Context context, Spannable spannable) { return addSmiles(context, -1, spannable); } /** * replace existing spannable with smiles * * @param context 上下文 * @param size 大小 * @param spannable 显示的span * @return 是否添加 */ public static boolean addSmiles(Context context, int size, Spannable spannable) { return addSmiles(context, size, ALIGN_BOTTOM, spannable); } /** * replace existing spannable with smiles * * @param context 上下文 * @param size 大小 * @param spannable 显示的span * @param verticalAlignment 垂直方向 * @return 是否添加 */ public static boolean addSmiles(Context context, int size, int verticalAlignment, Spannable spannable) { boolean hasChanges = false; for (Map.Entry<Pattern, Integer> entry : emoticons.entrySet()) { Matcher matcher = entry.getKey().matcher(spannable); while (matcher.find()) { boolean set = true; for (CenteredImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), CenteredImageSpan.class)) if (spannable.getSpanStart(span) >= matcher.start() && spannable.getSpanEnd(span) <= matcher.end()) spannable.removeSpan(span); else { set = false; break; } if (set) { hasChanges = true; if (size <= 0) { spannable.setSpan(new CenteredImageSpan(context, entry.getValue()), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { Drawable drawable = context.getResources().getDrawable(entry.getValue()); if (drawable != null) { drawable.setBounds(0, 0, size, size);//这里设置图片的大小 CenteredImageSpan CenteredImageSpan = new CenteredImageSpan(drawable); spannable.setSpan(CenteredImageSpan, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } } } return hasChanges; } public static Spannable getSmiledText(Context context, CharSequence text) { return getSmiledText(context, text, -1); } public static Spannable getSmiledText(Context context, CharSequence text, int size) { return getSmiledText(context, text, size, ALIGN_BOTTOM); } public static Spannable getSmiledText(Context context, CharSequence text, int size, int verticalAlignment) { Spannable spannable = spannableFactory.newSpannable(text); addSmiles(context, size, verticalAlignment, spannable); return spannable; } public static boolean containsKey(String key) { boolean b = false; for (Map.Entry<Pattern, Integer> entry : emoticons.entrySet()) { Matcher matcher = entry.getKey().matcher(key); if (matcher.find()) { b = true; break; } } return b; } public static Map<Pattern, Integer> getEmoticons() { return emoticons; } public static String stringToUnicode(String string) { StringBuffer unicode = new StringBuffer(); for (int i = 0; i < string.length(); i++) { // 取出每一个字符 char c = string.charAt(i); // 转换为unicode unicode.append("\\u" + String.format("%04", Integer.toHexString(c))); } return "[" + unicode.toString() + "]"; } public static String unicode2String(String unicode) { StringBuffer string = new StringBuffer(); String[] hex = unicode.split("\\\\u"); for (int i = 1; i < hex.length; i++) { // 转换出每一个代码点 int data = Integer.parseInt(hex[i], 16); // 追加成string string.append((char) data); } return string.toString(); } public static String[] specials = {"\\", "\\/", "*", ".", "?", "+", "$", "^", "[", "]", "(", ")", "{", "}", "|"}; public static SpannableStringBuilder highlight(String text, String target) { SpannableStringBuilder spannable = new SpannableStringBuilder(text); CharacterStyle span = null; for (int i = 0; i < specials.length; i++) { if (target.contains(specials[i])) { target = target.replace(specials[i], "\\" + specials[i]); } } Pattern p = Pattern.compile(target.toLowerCase()); Matcher m = p.matcher(text.toLowerCase()); while (m.find()) { span = new ForegroundColorSpan(Color.rgb(253, 113, 34));// 需要重复! spannable.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } return spannable; } public static SpannableStringBuilder highlight(Spannable text, String target) { SpannableStringBuilder spannable = new SpannableStringBuilder(text); CharacterStyle span = null; Pattern p = Pattern.compile(target); Matcher m = p.matcher(text); while (m.find()) { span = new ForegroundColorSpan(Color.rgb(253, 113, 34));// 需要重复! spannable.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } return spannable; } public static SpannableStringBuilder highlight(String text) { SpannableStringBuilder spannable = new SpannableStringBuilder(text); CharacterStyle span = null; span = new ForegroundColorSpan(Color.rgb(253, 113, 34));// 需要重复! spannable.setSpan(span, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return spannable; } public static Spannable unicodeToEmojiName(Context context, String content, int size, int verticalAlignment) { Spannable spannable = getSmiledText(context, content, size, verticalAlignment); return spannable; } public static Spannable unicodeToEmojiName(Context context, String content, int size) { Spannable spannable = getSmiledText(context, content, size); return spannable; } public static Spannable unicodeToEmojiName(Context context, String content) { Spannable spannable = getSmiledText(context, content, -1); return spannable; } public static List<String> getTextList() { return textList; } }
APLK/RichTextView
app/src/main/java/example/ricktextview/view/richtext/SmileUtils.java
4,979
// 取出每一个字符
line_comment
zh-cn
package example.ricktextview.view.richtext; /** * 表情工具类 */ import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.style.CharacterStyle; import android.text.style.ForegroundColorSpan; import android.widget.EditText; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import example.ricktextview.R; import example.ricktextview.view.richtext.span.CenteredImageSpan; import static android.text.style.DynamicDrawableSpan.ALIGN_BOTTOM; public class SmileUtils { private static final Spannable.Factory spannableFactory = Spannable.Factory .getInstance(); private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>(); private static final List<String> textList = new ArrayList<>(); public Map<Pattern, Integer> getEmotions() { return emoticons; } public static final String f1 = "[汗]"; public static final String f2 = "[发呆]"; public static final String f3 = "[眨眼]"; public static final String f4 = "[痛哭]"; public static final String f5 = "[傻萌]"; public static final String f6 = "[惊恐]"; public static final String f7 = "[流口水]"; public static final String f8 = "[冷漠]"; public static final String f9 = "[乖巧]"; public static final String f10 = "[可爱]"; public static final String f11 = "[抓狂]"; public static final String f12 = "[邪恶]"; public static final String f13 = "[笑哭]"; public static final String f14 = "[得意]"; public static final String f15 = "[抽烟]"; public static final String f16 = "[示爱]"; public static final String f17 = "[输入]"; public static final String f18 = "[无语]"; public static final String f19 = "[大眼崽]"; public static final String f20 = "[微笑]"; public static final String f21 = "[财迷]"; public static final String f22 = "[开心]"; public static final String f23 = "[糗大了]"; public static final String f24 = "[感冒]"; public static final String f25 = "[调皮]"; public static final String f26 = "[尴尬]"; public static final String f27 = "[色迷迷]"; public static final String f28 = "[大笑]"; public static final String f29 = "[笑眯眯]"; public static final String f30 = "[爱你哟]"; public static final String f31 = "[纠结]"; public static final String f32 = "[惊呆]"; public static final String f33 = "[思考]"; public static final String f34 = "[拳头]"; public static final String f35 = "[炸弹]"; public static final String f36 = "[公平]"; public static final String f37 = "[手]"; public static final String f38 = "[朋友]"; public static final String f39 = "[手牵手]"; public static final String f40 = "[美眉]"; public static final String f41 = "[合照]"; public static final String f42 = "[全家福]"; public static final String f43 = "[财迷]"; public static final String f44 = "[臭气熏天]"; public static final String f45 = "[胜利]"; public static final String f46 = "[保密]"; public static final String f47 = "[语音]"; public static final String f48 = "[信封]"; public static final String f49 = "[手机]"; public static final String f50 = "[答卷]"; public static final String f51 = "[合影]"; public static final String f52 = "[电脑]"; public static final String f53 = "[日历]"; public static final String f54 = "[电话]"; public static final String f55 = "[情书]"; public static final String f56 = "[可怜]"; public static final String f57 = "[睡觉]"; public static final String f58 = "[大骂]"; public static final String f59 = "[害羞]"; public static final String f60 = "[撇嘴]"; public static final String f61 = "[闭嘴]"; static { addPattern(emoticons, addResString(f1), R.drawable.f1); addPattern(emoticons, addResString(f2), R.drawable.f2); addPattern(emoticons, addResString(f3), R.drawable.f3); addPattern(emoticons, addResString(f4), R.drawable.f4); addPattern(emoticons, addResString(f5), R.drawable.f5); addPattern(emoticons, addResString(f6), R.drawable.f6); addPattern(emoticons, addResString(f7), R.drawable.f7); addPattern(emoticons, addResString(f8), R.drawable.f8); addPattern(emoticons, addResString(f9), R.drawable.f9); addPattern(emoticons, addResString(f10), R.drawable.f10); addPattern(emoticons, addResString(f11), R.drawable.f11); addPattern(emoticons, addResString(f12), R.drawable.f12); addPattern(emoticons, addResString(f13), R.drawable.f13); addPattern(emoticons, addResString(f14), R.drawable.f14); addPattern(emoticons, addResString(f15), R.drawable.f15); addPattern(emoticons, addResString(f16), R.drawable.f16); addPattern(emoticons, addResString(f17), R.drawable.f17); addPattern(emoticons, addResString(f18), R.drawable.f18); addPattern(emoticons, addResString(f19), R.drawable.f19); addPattern(emoticons, addResString(f20), R.drawable.f20); addPattern(emoticons, addResString(f21), R.drawable.f21); addPattern(emoticons, addResString(f22), R.drawable.f22); addPattern(emoticons, addResString(f23), R.drawable.f23); addPattern(emoticons, addResString(f24), R.drawable.f24); addPattern(emoticons, addResString(f25), R.drawable.f25); addPattern(emoticons, addResString(f26), R.drawable.f26); addPattern(emoticons, addResString(f27), R.drawable.f27); addPattern(emoticons, addResString(f28), R.drawable.f28); addPattern(emoticons, addResString(f29), R.drawable.f29); addPattern(emoticons, addResString(f30), R.drawable.f30); addPattern(emoticons, addResString(f31), R.drawable.f31); addPattern(emoticons, addResString(f32), R.drawable.f32); addPattern(emoticons, addResString(f33), R.drawable.f33); addPattern(emoticons, addResString(f34), R.drawable.f34); addPattern(emoticons, addResString(f35), R.drawable.f35); addPattern(emoticons, addResString(f36), R.drawable.f36); addPattern(emoticons, addResString(f37), R.drawable.f37); addPattern(emoticons, addResString(f38), R.drawable.f38); addPattern(emoticons, addResString(f39), R.drawable.f39); addPattern(emoticons, addResString(f40), R.drawable.f40); addPattern(emoticons, addResString(f41), R.drawable.f41); addPattern(emoticons, addResString(f42), R.drawable.f42); addPattern(emoticons, addResString(f43), R.drawable.f43); addPattern(emoticons, addResString(f44), R.drawable.f44); addPattern(emoticons, addResString(f45), R.drawable.f45); addPattern(emoticons, addResString(f46), R.drawable.f46); addPattern(emoticons, addResString(f47), R.drawable.f47); addPattern(emoticons, addResString(f48), R.drawable.f48); addPattern(emoticons, addResString(f49), R.drawable.f49); addPattern(emoticons, addResString(f50), R.drawable.f50); addPattern(emoticons, addResString(f51), R.drawable.f51); addPattern(emoticons, addResString(f52), R.drawable.f52); addPattern(emoticons, addResString(f53), R.drawable.f53); addPattern(emoticons, addResString(f54), R.drawable.f54); addPattern(emoticons, addResString(f55), R.drawable.f55); addPattern(emoticons, addResString(f56), R.drawable.f56); addPattern(emoticons, addResString(f57), R.drawable.f57); addPattern(emoticons, addResString(f58), R.drawable.f58); addPattern(emoticons, addResString(f59), R.drawable.f59); addPattern(emoticons, addResString(f60), R.drawable.f60); addPattern(emoticons, addResString(f61), R.drawable.f61); } /** * 添加到map * * @param map map * @param smile 文本 * @param resource 显示图片表情列表 */ private static void addPattern(Map<Pattern, Integer> map, String smile, int resource) { map.put(Pattern.compile(Pattern.quote(smile)), resource); } /** * 使用你自己的map * * @param map map * @param smile 文本列表 * @param resource 显示图片表情列表 */ public static void addPatternAll(Map<Pattern, Integer> map, List<String> smile, List<Integer> resource) { map.clear(); textList.clear(); if (smile.size() != resource.size()) { try { throw new Exception("**********文本与图片list不相等"); } catch (Exception e) { e.printStackTrace(); } return; } textList.addAll(smile); for (int i = 0; i < smile.size(); i++) { map.put(Pattern.compile(Pattern.quote(smile.get(i))), resource.get(i)); } } public static String addResString(String resString) { textList.add(resString); return resString; } /*** * 文本对应的资源 * * @param string 需要转化文本 * @return */ public static int getRedId(String string) { for (Map.Entry<Pattern, Integer> entry : emoticons.entrySet()) { Matcher matcher = entry.getKey().matcher(string); while (matcher.find()) { return entry.getValue(); } } return -1; } /** * 文本转化表情处理 * * @param editText 要显示的EditText * @param maxLength 最长高度 * @param size 显示大小 * @param name 需要转化的文本 */ public static void insertIcon(EditText editText, int maxLength, int size, String name) { String curString = editText.toString(); if ((curString.length() + name.length()) > maxLength) { return; } int resId = SmileUtils.getRedId(name); Drawable drawable = editText.getResources().getDrawable(resId); if (drawable == null) return; drawable.setBounds(0, 0, size, size);//这里设置图片的大小 CenteredImageSpan CenteredImageSpan = new CenteredImageSpan(drawable); SpannableString spannableString = new SpannableString(name); spannableString.setSpan(CenteredImageSpan, 0, spannableString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE); int index = Math.max(editText.getSelectionStart(), 0); SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(editText.getText()); spannableStringBuilder.insert(index, spannableString); editText.setText(spannableStringBuilder); editText.setSelection(index + spannableString.length()); } /** * replace existing spannable with smiles * * @param context 上下文 * @param spannable 显示的span * @return 是否添加 */ public static boolean addSmiles(Context context, Spannable spannable) { return addSmiles(context, -1, spannable); } /** * replace existing spannable with smiles * * @param context 上下文 * @param size 大小 * @param spannable 显示的span * @return 是否添加 */ public static boolean addSmiles(Context context, int size, Spannable spannable) { return addSmiles(context, size, ALIGN_BOTTOM, spannable); } /** * replace existing spannable with smiles * * @param context 上下文 * @param size 大小 * @param spannable 显示的span * @param verticalAlignment 垂直方向 * @return 是否添加 */ public static boolean addSmiles(Context context, int size, int verticalAlignment, Spannable spannable) { boolean hasChanges = false; for (Map.Entry<Pattern, Integer> entry : emoticons.entrySet()) { Matcher matcher = entry.getKey().matcher(spannable); while (matcher.find()) { boolean set = true; for (CenteredImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), CenteredImageSpan.class)) if (spannable.getSpanStart(span) >= matcher.start() && spannable.getSpanEnd(span) <= matcher.end()) spannable.removeSpan(span); else { set = false; break; } if (set) { hasChanges = true; if (size <= 0) { spannable.setSpan(new CenteredImageSpan(context, entry.getValue()), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { Drawable drawable = context.getResources().getDrawable(entry.getValue()); if (drawable != null) { drawable.setBounds(0, 0, size, size);//这里设置图片的大小 CenteredImageSpan CenteredImageSpan = new CenteredImageSpan(drawable); spannable.setSpan(CenteredImageSpan, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } } } return hasChanges; } public static Spannable getSmiledText(Context context, CharSequence text) { return getSmiledText(context, text, -1); } public static Spannable getSmiledText(Context context, CharSequence text, int size) { return getSmiledText(context, text, size, ALIGN_BOTTOM); } public static Spannable getSmiledText(Context context, CharSequence text, int size, int verticalAlignment) { Spannable spannable = spannableFactory.newSpannable(text); addSmiles(context, size, verticalAlignment, spannable); return spannable; } public static boolean containsKey(String key) { boolean b = false; for (Map.Entry<Pattern, Integer> entry : emoticons.entrySet()) { Matcher matcher = entry.getKey().matcher(key); if (matcher.find()) { b = true; break; } } return b; } public static Map<Pattern, Integer> getEmoticons() { return emoticons; } public static String stringToUnicode(String string) { StringBuffer unicode = new StringBuffer(); for (int i = 0; i < string.length(); i++) { // 取出 <SUF> char c = string.charAt(i); // 转换为unicode unicode.append("\\u" + String.format("%04", Integer.toHexString(c))); } return "[" + unicode.toString() + "]"; } public static String unicode2String(String unicode) { StringBuffer string = new StringBuffer(); String[] hex = unicode.split("\\\\u"); for (int i = 1; i < hex.length; i++) { // 转换出每一个代码点 int data = Integer.parseInt(hex[i], 16); // 追加成string string.append((char) data); } return string.toString(); } public static String[] specials = {"\\", "\\/", "*", ".", "?", "+", "$", "^", "[", "]", "(", ")", "{", "}", "|"}; public static SpannableStringBuilder highlight(String text, String target) { SpannableStringBuilder spannable = new SpannableStringBuilder(text); CharacterStyle span = null; for (int i = 0; i < specials.length; i++) { if (target.contains(specials[i])) { target = target.replace(specials[i], "\\" + specials[i]); } } Pattern p = Pattern.compile(target.toLowerCase()); Matcher m = p.matcher(text.toLowerCase()); while (m.find()) { span = new ForegroundColorSpan(Color.rgb(253, 113, 34));// 需要重复! spannable.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } return spannable; } public static SpannableStringBuilder highlight(Spannable text, String target) { SpannableStringBuilder spannable = new SpannableStringBuilder(text); CharacterStyle span = null; Pattern p = Pattern.compile(target); Matcher m = p.matcher(text); while (m.find()) { span = new ForegroundColorSpan(Color.rgb(253, 113, 34));// 需要重复! spannable.setSpan(span, m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } return spannable; } public static SpannableStringBuilder highlight(String text) { SpannableStringBuilder spannable = new SpannableStringBuilder(text); CharacterStyle span = null; span = new ForegroundColorSpan(Color.rgb(253, 113, 34));// 需要重复! spannable.setSpan(span, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return spannable; } public static Spannable unicodeToEmojiName(Context context, String content, int size, int verticalAlignment) { Spannable spannable = getSmiledText(context, content, size, verticalAlignment); return spannable; } public static Spannable unicodeToEmojiName(Context context, String content, int size) { Spannable spannable = getSmiledText(context, content, size); return spannable; } public static Spannable unicodeToEmojiName(Context context, String content) { Spannable spannable = getSmiledText(context, content, -1); return spannable; } public static List<String> getTextList() { return textList; } }
0
51355_0
package Arrayarray; /** * 输入描述: * 输入多行,先输入随机整数的个数,再输入相应个数的整数 * 输出描述: * 剔除重复数据并大小排序输出。 * * 思考:treeset可以自动过滤重复的元素,直接用lambda表达式输出即可 */ import java.util.*; public class Array1 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int total = sc.nextInt(); TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i <= total - 1; i++) { ts.add(sc.nextInt()); } ts.forEach((t) -> System.out.println(t)); } } }
APanend/codePractice
src/Arrayarray/Array1.java
191
/** * 输入描述: * 输入多行,先输入随机整数的个数,再输入相应个数的整数 * 输出描述: * 剔除重复数据并大小排序输出。 * * 思考:treeset可以自动过滤重复的元素,直接用lambda表达式输出即可 */
block_comment
zh-cn
package Arrayarray; /** * 输入描 <SUF>*/ import java.util.*; public class Array1 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int total = sc.nextInt(); TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i <= total - 1; i++) { ts.add(sc.nextInt()); } ts.forEach((t) -> System.out.println(t)); } } }
1
61668_2
package asia.asoulcnki.api.common.duplicationcheck; import java.math.BigInteger; import java.util.ArrayList; public class SummaryHash { /** * 取样采取连续k个字符进行hash,即连续k个字符相同才判断为相同 */ public static final int DEFAULT_K = 8; /** * 默认的取样滑动窗口,即每个窗口宽度,每个窗口取最小值作为特征hash */ public static final int DEFAULT_W = 8; /** * hash取模的模数,影响碰撞几率 */ private static final long DEFAULT_Q = 100001651L; /** * hash基数,为质数能减少碰撞 */ private static final int DEFAULT_B = 2; /** * 获取一个取样窗口(k个字符)字符串的hash值 * @param s 字符串 * @param nextStartOffset 下次取样开始下标 * @param k 敏感度 每n个字做摘要 * @param q 模数 摘要算法结果对其取模 * @param b 基数 * @return (此次取样hash值, 下次取样开始下标) Tuple<> */ private static Tuple<Long, Integer> hashValue(String s, int nextStartOffset, int k, long q, int b) { BigInteger hash = BigInteger.valueOf(0); int offset = nextStartOffset; int index = 0; while (index < k) { // get unicode code point final int codepoint = s.codePointAt(offset); // calculate hash, codePoint * (b ^ (k - 1 - index)) BigInteger rhs = BigInteger.valueOf(b).pow(k - 1 - index); hash = hash.add(BigInteger.valueOf(codepoint).multiply(rhs)); offset += Character.charCount(codepoint); index++; if (index == 1) { nextStartOffset = offset; } } return new Tuple<>(hash.longValue() % q, nextStartOffset); } /** * 获取经过滑动窗口筛选的字符串hash结果 * @param s 字符串 * @param k 敏感度 每n个字做摘要 * @param q 模数 摘要算法结果对其取模 * @param b 基数 * @param w 窗口宽度 摘要时的窗口大小 * @return 字符串的摘要 */ public static ArrayList<Long> hash(String s, int k, long q, int b, int w) { ArrayList<Long> hashVals = getStringHashVals(s, k, q, b); ArrayList<Long> hashPicks = new ArrayList<>(hashVals.size()); hashPicks.add(pickHash(hashVals, 0, w)); int j = 1; while (j + w <= hashVals.size()) { long minHash = pickHash(hashVals, j, j + w); if (minHash != hashPicks.get(hashPicks.size() - 1)) { hashPicks.add(minHash); } j += 1; } return hashPicks; } /** * 获取未经筛选的字符串hash结果 * @param s 字符串 * @param k 敏感度 每n个字做摘要 * @param q 模数 摘要算法结果对其取模 * @param b 基数 * @return 未经过筛选的字符串的摘要 ArrayList */ public static ArrayList<Long> getStringHashVals(String s, int k, long q, int b) { int codePointNumber = s.codePointCount(0, s.length()); int nextOffset = 0; ArrayList<Long> hashVals = new ArrayList<>(codePointNumber - k + 1); // i indicate the i-th unicode code point // for example 我是🤡 , 我 is the first and 🤡 is the third for (int i = 0; i < codePointNumber - k + 1; i++) { Tuple<Long, Integer> result = hashValue(s, nextOffset, k, q, b); long hashVal = result.first; nextOffset = result.second; hashVals.add(hashVal); } return hashVals; } /** * 在一个滑动窗口中选择合适的hash * @param hashVals 待筛选的hash结果 * @param start 滑动窗口起始下标(index) * @param end 滑动窗口结束下标(index+w) * @return 选择出的hash值 long */ private static long pickHash(ArrayList<Long> hashVals, int start, int end) { int index = start; long minHash = Long.MAX_VALUE; while (index < end && index < hashVals.size()) { if (hashVals.get(index) < minHash) { minHash = hashVals.get(index); } index += 1; } return minHash; } /** * 使用默认参数取字符串s的hash * @param s 待取hash的字符串 * @return hash结果 ArrayList */ public static ArrayList<Long> defaultHash(String s) { return hash(s, DEFAULT_K, DEFAULT_Q, DEFAULT_B, DEFAULT_W); } public static void main(String[] args) { String text1 = "嘉然的脚小小的香香的,不像手经常使用来得灵活,但有一种独特的可爱的笨拙,嫩嫩的脚丫光滑细腻,凌莹剔透,看得见皮肤下面细细的血管与指甲之下粉白的月牙。再高冷的女生小脚也是敏感的害羞的,轻轻挠一挠,她就摇身一变成为娇滴滴的女孩,脚丫像是一把钥匙,轻轻掌握它就能打开女孩子的心灵。"; String text2 = "嘉然的脚小小的香香的,不像手经常使用来得灵活,但有一种独特的可爱的笨拙,嫩嫩的脚丫光滑细腻,凌莹剔透," + "看得见皮肤下面细细的血管与指甲之下粉白的月牙再高冷的女生小脚也是敏感的害羞的,轻轻挠一挠,她就摇身一变成为娇滴滴的女孩,脚丫像是一把钥匙,轻轻掌握它就能打开女孩子的心灵。"; String text3 = "乃琳带我走吧! 双向奔赴~\n" + " \n" + " " + " \n" + "\\uD83E\uDD24/ \\uD83E\uDD8A/  \n" + " " + " " + " / \\ \n" + "ノ) (㇏"; System.out.println(ArticleCompareUtil.trim(text3)); ArrayList<Long> result1 = defaultHash(text1); System.out.println(result1); ArrayList<Long> result2 = defaultHash(text2); System.out.println(result2); System.out.println(ArticleCompareUtil.compareArticle(text1, text2)); System.out.println(ArticleCompareUtil.compareArticle(text2, text2)); } public static class Tuple<A, B> { public final A first; public final B second; public Tuple(A a, B b) { first = a; second = b; } } }
ASoulCnki/ASoulCnkiBackend
src/main/java/asia/asoulcnki/api/common/duplicationcheck/SummaryHash.java
1,975
/** * hash取模的模数,影响碰撞几率 */
block_comment
zh-cn
package asia.asoulcnki.api.common.duplicationcheck; import java.math.BigInteger; import java.util.ArrayList; public class SummaryHash { /** * 取样采取连续k个字符进行hash,即连续k个字符相同才判断为相同 */ public static final int DEFAULT_K = 8; /** * 默认的取样滑动窗口,即每个窗口宽度,每个窗口取最小值作为特征hash */ public static final int DEFAULT_W = 8; /** * has <SUF>*/ private static final long DEFAULT_Q = 100001651L; /** * hash基数,为质数能减少碰撞 */ private static final int DEFAULT_B = 2; /** * 获取一个取样窗口(k个字符)字符串的hash值 * @param s 字符串 * @param nextStartOffset 下次取样开始下标 * @param k 敏感度 每n个字做摘要 * @param q 模数 摘要算法结果对其取模 * @param b 基数 * @return (此次取样hash值, 下次取样开始下标) Tuple<> */ private static Tuple<Long, Integer> hashValue(String s, int nextStartOffset, int k, long q, int b) { BigInteger hash = BigInteger.valueOf(0); int offset = nextStartOffset; int index = 0; while (index < k) { // get unicode code point final int codepoint = s.codePointAt(offset); // calculate hash, codePoint * (b ^ (k - 1 - index)) BigInteger rhs = BigInteger.valueOf(b).pow(k - 1 - index); hash = hash.add(BigInteger.valueOf(codepoint).multiply(rhs)); offset += Character.charCount(codepoint); index++; if (index == 1) { nextStartOffset = offset; } } return new Tuple<>(hash.longValue() % q, nextStartOffset); } /** * 获取经过滑动窗口筛选的字符串hash结果 * @param s 字符串 * @param k 敏感度 每n个字做摘要 * @param q 模数 摘要算法结果对其取模 * @param b 基数 * @param w 窗口宽度 摘要时的窗口大小 * @return 字符串的摘要 */ public static ArrayList<Long> hash(String s, int k, long q, int b, int w) { ArrayList<Long> hashVals = getStringHashVals(s, k, q, b); ArrayList<Long> hashPicks = new ArrayList<>(hashVals.size()); hashPicks.add(pickHash(hashVals, 0, w)); int j = 1; while (j + w <= hashVals.size()) { long minHash = pickHash(hashVals, j, j + w); if (minHash != hashPicks.get(hashPicks.size() - 1)) { hashPicks.add(minHash); } j += 1; } return hashPicks; } /** * 获取未经筛选的字符串hash结果 * @param s 字符串 * @param k 敏感度 每n个字做摘要 * @param q 模数 摘要算法结果对其取模 * @param b 基数 * @return 未经过筛选的字符串的摘要 ArrayList */ public static ArrayList<Long> getStringHashVals(String s, int k, long q, int b) { int codePointNumber = s.codePointCount(0, s.length()); int nextOffset = 0; ArrayList<Long> hashVals = new ArrayList<>(codePointNumber - k + 1); // i indicate the i-th unicode code point // for example 我是🤡 , 我 is the first and 🤡 is the third for (int i = 0; i < codePointNumber - k + 1; i++) { Tuple<Long, Integer> result = hashValue(s, nextOffset, k, q, b); long hashVal = result.first; nextOffset = result.second; hashVals.add(hashVal); } return hashVals; } /** * 在一个滑动窗口中选择合适的hash * @param hashVals 待筛选的hash结果 * @param start 滑动窗口起始下标(index) * @param end 滑动窗口结束下标(index+w) * @return 选择出的hash值 long */ private static long pickHash(ArrayList<Long> hashVals, int start, int end) { int index = start; long minHash = Long.MAX_VALUE; while (index < end && index < hashVals.size()) { if (hashVals.get(index) < minHash) { minHash = hashVals.get(index); } index += 1; } return minHash; } /** * 使用默认参数取字符串s的hash * @param s 待取hash的字符串 * @return hash结果 ArrayList */ public static ArrayList<Long> defaultHash(String s) { return hash(s, DEFAULT_K, DEFAULT_Q, DEFAULT_B, DEFAULT_W); } public static void main(String[] args) { String text1 = "嘉然的脚小小的香香的,不像手经常使用来得灵活,但有一种独特的可爱的笨拙,嫩嫩的脚丫光滑细腻,凌莹剔透,看得见皮肤下面细细的血管与指甲之下粉白的月牙。再高冷的女生小脚也是敏感的害羞的,轻轻挠一挠,她就摇身一变成为娇滴滴的女孩,脚丫像是一把钥匙,轻轻掌握它就能打开女孩子的心灵。"; String text2 = "嘉然的脚小小的香香的,不像手经常使用来得灵活,但有一种独特的可爱的笨拙,嫩嫩的脚丫光滑细腻,凌莹剔透," + "看得见皮肤下面细细的血管与指甲之下粉白的月牙再高冷的女生小脚也是敏感的害羞的,轻轻挠一挠,她就摇身一变成为娇滴滴的女孩,脚丫像是一把钥匙,轻轻掌握它就能打开女孩子的心灵。"; String text3 = "乃琳带我走吧! 双向奔赴~\n" + " \n" + " " + " \n" + "\\uD83E\uDD24/ \\uD83E\uDD8A/  \n" + " " + " " + " / \\ \n" + "ノ) (㇏"; System.out.println(ArticleCompareUtil.trim(text3)); ArrayList<Long> result1 = defaultHash(text1); System.out.println(result1); ArrayList<Long> result2 = defaultHash(text2); System.out.println(result2); System.out.println(ArticleCompareUtil.compareArticle(text1, text2)); System.out.println(ArticleCompareUtil.compareArticle(text2, text2)); } public static class Tuple<A, B> { public final A first; public final B second; public Tuple(A a, B b) { first = a; second = b; } } }
1
18993_7
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.example.qi.tt.permission; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import java.util.ArrayList; import java.util.List; public class Permissions { static final String TAG = Permissions.class.getSimpleName(); static final Object TRIGGER = new Object(); @VisibleForTesting Lazy<PermissionsFragment> mPermissionsFragment; public Permissions(@NonNull final FragmentActivity activity) { mPermissionsFragment = getLazySingleton(activity.getSupportFragmentManager()); } public Permissions(@NonNull final Fragment fragment) { mPermissionsFragment = getLazySingleton(fragment.getChildFragmentManager()); } @NonNull private Lazy<PermissionsFragment> getLazySingleton(@NonNull final FragmentManager fragmentManager) { return new Lazy<PermissionsFragment>() { private PermissionsFragment permissionsFragment; @Override public synchronized PermissionsFragment get() { if (permissionsFragment == null) { permissionsFragment = getPermissionsFragment(fragmentManager); } return permissionsFragment; } }; } private PermissionsFragment getPermissionsFragment(@NonNull final FragmentManager fragmentManager) { PermissionsFragment rxPermissionsFragment = findPermissionsFragment(fragmentManager); boolean isNewInstance = rxPermissionsFragment == null; if (isNewInstance) { rxPermissionsFragment = new PermissionsFragment(); fragmentManager .beginTransaction() .add(rxPermissionsFragment, TAG) .commitNow(); } return rxPermissionsFragment; } private PermissionsFragment findPermissionsFragment(@NonNull final FragmentManager fragmentManager) { return (PermissionsFragment) fragmentManager.findFragmentByTag(TAG); } public void setLogging(boolean logging) { mPermissionsFragment.get().setLogging(logging); } @TargetApi(Build.VERSION_CODES.M) public Permissions requestEach(FragmentActivity activity, PermissionsFragment.PermissionCallBack callBack, final String... permissions) { if (callBack!=null){ setCallBack(callBack); } // // 检测是否有 1、未获取到2、且不再提示 的权限,如果有 就 不再 请求权限 ,由于 第一次检测是否 弹出 询问 为 false 在此 无法使用 // if (!shouldShowRequestPermissionRationaleImplementation(activity,permissions)){ // mPermissionsFragment.get().onRequestPermissionsResult(new Permission("permission",false,false)); // return this; // } List<Permission> list = new ArrayList<>(permissions.length); List<String> unrequestedPermissions = new ArrayList<>(); // In case of multiple permissions, we create an Observable for each of them. // At the end, the observables are combined to have a unique response. for (String permission : permissions) { mPermissionsFragment.get().log("Requesting permission " + permission); if (isGranted(permission)) { // 是否 已获取到权限 // Already granted, or not Android M // Return a granted Permission object. list.add(new Permission(permission, true, false)); continue; }else if (isRevoked(permission)) {// 权限 是否已取消 // Revoked by a policy, return a denied Permission object. list.add(new Permission(permission, false, false)); continue; } else { //未请求 到权限 unrequestedPermissions.add(permission); } } if (!unrequestedPermissions.isEmpty()) {//申请 未获取到的权限 String[] unrequestedPermissionsArray = unrequestedPermissions.toArray(new String[unrequestedPermissions.size()]); requestPermissionsFromFragment(unrequestedPermissionsArray); }else { // 权限 已 全部获取到 mPermissionsFragment.get().onRequestPermissionsResult(new Permission("permission",true,false)); } return this; } @TargetApi(Build.VERSION_CODES.M) private boolean shouldShowRequestPermissionRationaleImplementation(final Activity activity, final String... permissions) { for (String p : permissions) { if (!isGranted(p) && !activity.shouldShowRequestPermissionRationale(p)) { return false; } } return true; } @TargetApi(Build.VERSION_CODES.M) void requestPermissionsFromFragment(String[] permissions) { mPermissionsFragment.get().log("requestPermissionsFromFragment " + TextUtils.join(", ", permissions)); mPermissionsFragment.get().requestPermissions(permissions); } /** * Returns true if the permission is already granted. * <p> * Always true if SDK &lt; 23. */ @SuppressWarnings("WeakerAccess") public boolean isGranted(String permission) { return !isMarshmallow() || mPermissionsFragment.get().isGranted(permission); } /** * Returns true if the permission has been revoked by a policy. * <p> * Always false if SDK &lt; 23. */ @SuppressWarnings("WeakerAccess") private boolean isRevoked(String permission) { return isMarshmallow() && mPermissionsFragment.get().isRevoked(permission); } private boolean isMarshmallow() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } // private void onRequestPermissionsResult(String permissions[], int[] grantResults) { // mPermissionsFragment.get().onRequestPermissionsResult(permissions, grantResults, new boolean[permissions.length]); // } @FunctionalInterface public interface Lazy<V> { V get(); } /** * 设置 回调 函数 * @param callBack */ public void setCallBack(PermissionsFragment.PermissionCallBack callBack){ mPermissionsFragment.get().setCallBack(callBack); } // public void setCallBack(new ){} // abstract class PermissionCallBack{ // private PermissionsFragment.FragmentPermissionResultCallBack callBack; // public void accept(); // public void refuse(); // public void noAsk(); // } }
AWQi/Permission
permission/Permissions.java
1,580
// 是否 已获取到权限
line_comment
zh-cn
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.example.qi.tt.permission; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import java.util.ArrayList; import java.util.List; public class Permissions { static final String TAG = Permissions.class.getSimpleName(); static final Object TRIGGER = new Object(); @VisibleForTesting Lazy<PermissionsFragment> mPermissionsFragment; public Permissions(@NonNull final FragmentActivity activity) { mPermissionsFragment = getLazySingleton(activity.getSupportFragmentManager()); } public Permissions(@NonNull final Fragment fragment) { mPermissionsFragment = getLazySingleton(fragment.getChildFragmentManager()); } @NonNull private Lazy<PermissionsFragment> getLazySingleton(@NonNull final FragmentManager fragmentManager) { return new Lazy<PermissionsFragment>() { private PermissionsFragment permissionsFragment; @Override public synchronized PermissionsFragment get() { if (permissionsFragment == null) { permissionsFragment = getPermissionsFragment(fragmentManager); } return permissionsFragment; } }; } private PermissionsFragment getPermissionsFragment(@NonNull final FragmentManager fragmentManager) { PermissionsFragment rxPermissionsFragment = findPermissionsFragment(fragmentManager); boolean isNewInstance = rxPermissionsFragment == null; if (isNewInstance) { rxPermissionsFragment = new PermissionsFragment(); fragmentManager .beginTransaction() .add(rxPermissionsFragment, TAG) .commitNow(); } return rxPermissionsFragment; } private PermissionsFragment findPermissionsFragment(@NonNull final FragmentManager fragmentManager) { return (PermissionsFragment) fragmentManager.findFragmentByTag(TAG); } public void setLogging(boolean logging) { mPermissionsFragment.get().setLogging(logging); } @TargetApi(Build.VERSION_CODES.M) public Permissions requestEach(FragmentActivity activity, PermissionsFragment.PermissionCallBack callBack, final String... permissions) { if (callBack!=null){ setCallBack(callBack); } // // 检测是否有 1、未获取到2、且不再提示 的权限,如果有 就 不再 请求权限 ,由于 第一次检测是否 弹出 询问 为 false 在此 无法使用 // if (!shouldShowRequestPermissionRationaleImplementation(activity,permissions)){ // mPermissionsFragment.get().onRequestPermissionsResult(new Permission("permission",false,false)); // return this; // } List<Permission> list = new ArrayList<>(permissions.length); List<String> unrequestedPermissions = new ArrayList<>(); // In case of multiple permissions, we create an Observable for each of them. // At the end, the observables are combined to have a unique response. for (String permission : permissions) { mPermissionsFragment.get().log("Requesting permission " + permission); if (isGranted(permission)) { // 是否 <SUF> // Already granted, or not Android M // Return a granted Permission object. list.add(new Permission(permission, true, false)); continue; }else if (isRevoked(permission)) {// 权限 是否已取消 // Revoked by a policy, return a denied Permission object. list.add(new Permission(permission, false, false)); continue; } else { //未请求 到权限 unrequestedPermissions.add(permission); } } if (!unrequestedPermissions.isEmpty()) {//申请 未获取到的权限 String[] unrequestedPermissionsArray = unrequestedPermissions.toArray(new String[unrequestedPermissions.size()]); requestPermissionsFromFragment(unrequestedPermissionsArray); }else { // 权限 已 全部获取到 mPermissionsFragment.get().onRequestPermissionsResult(new Permission("permission",true,false)); } return this; } @TargetApi(Build.VERSION_CODES.M) private boolean shouldShowRequestPermissionRationaleImplementation(final Activity activity, final String... permissions) { for (String p : permissions) { if (!isGranted(p) && !activity.shouldShowRequestPermissionRationale(p)) { return false; } } return true; } @TargetApi(Build.VERSION_CODES.M) void requestPermissionsFromFragment(String[] permissions) { mPermissionsFragment.get().log("requestPermissionsFromFragment " + TextUtils.join(", ", permissions)); mPermissionsFragment.get().requestPermissions(permissions); } /** * Returns true if the permission is already granted. * <p> * Always true if SDK &lt; 23. */ @SuppressWarnings("WeakerAccess") public boolean isGranted(String permission) { return !isMarshmallow() || mPermissionsFragment.get().isGranted(permission); } /** * Returns true if the permission has been revoked by a policy. * <p> * Always false if SDK &lt; 23. */ @SuppressWarnings("WeakerAccess") private boolean isRevoked(String permission) { return isMarshmallow() && mPermissionsFragment.get().isRevoked(permission); } private boolean isMarshmallow() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; } // private void onRequestPermissionsResult(String permissions[], int[] grantResults) { // mPermissionsFragment.get().onRequestPermissionsResult(permissions, grantResults, new boolean[permissions.length]); // } @FunctionalInterface public interface Lazy<V> { V get(); } /** * 设置 回调 函数 * @param callBack */ public void setCallBack(PermissionsFragment.PermissionCallBack callBack){ mPermissionsFragment.get().setCallBack(callBack); } // public void setCallBack(new ){} // abstract class PermissionCallBack{ // private PermissionsFragment.FragmentPermissionResultCallBack callBack; // public void accept(); // public void refuse(); // public void noAsk(); // } }
0
48684_8
package com.common.dto; import java.io.Serializable; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** * 返回给前端的数据 */ @Data @Schema(description = "用户信息DTO") public class UserDto implements Serializable { /** * 用户id */ @Schema(description = "用户id", example = "1789548655582642177") private Long userId; /** * 用户名 */ @Schema(description = "用户名", example = "nick123", minLength = 4) private String username; /** * 昵称 */ @Schema(description = "用户昵称", example = "尼克", minLength = 6) private String nickname; /** * 用户性别 男 女 */ @Schema(description = "用户性别", example = "男") private String gender; /** * 用户年龄 */ @Schema(description = "用户年龄", example = "20", minimum = "0", maximum = "200") private Integer age; /** * 用户头像url */ @Schema(description = "用户头像url", example = "https://ischool-bucket.oss-cn-beijing.aliyuncs.com/4c079b7b-0873-4c99-a666-0874a1595811.jpg") private String userAvatar; /** * 用户邮箱 */ @Schema(description = "用户邮箱", example = "han892577@qq.com") private String email; /** * 用户所属学校名称 */ @Schema(description = "用户所属学校名称", example = "哈尔滨理工大学") private String schoolName; /** * 用户所属学校简写 */ @Schema(description = "用户所属学校简写", example = "HRBUST") private String schoolAbbr; /** * 用户获赞总数 */ @Schema(description = "用户在社区模块的获赞总数", example = "100") private Integer totalLikes; /** * 用户被评论总数 */ @Schema(description = "用户在社区模块的被评论总数", example = "200") private Integer totalComments; /** * 用户被评论总数 */ @Schema(description = "用户未读评论的总数", example = "10") private Integer unReadCommentsCount; private static final long serialVersionUID = 1L; }
AZCodingAccount/iSchool
iSchool-Server/iSchool-model/src/main/java/com/common/dto/UserDto.java
627
/** * 用户邮箱 */
block_comment
zh-cn
package com.common.dto; import java.io.Serializable; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; /** * 返回给前端的数据 */ @Data @Schema(description = "用户信息DTO") public class UserDto implements Serializable { /** * 用户id */ @Schema(description = "用户id", example = "1789548655582642177") private Long userId; /** * 用户名 */ @Schema(description = "用户名", example = "nick123", minLength = 4) private String username; /** * 昵称 */ @Schema(description = "用户昵称", example = "尼克", minLength = 6) private String nickname; /** * 用户性别 男 女 */ @Schema(description = "用户性别", example = "男") private String gender; /** * 用户年龄 */ @Schema(description = "用户年龄", example = "20", minimum = "0", maximum = "200") private Integer age; /** * 用户头像url */ @Schema(description = "用户头像url", example = "https://ischool-bucket.oss-cn-beijing.aliyuncs.com/4c079b7b-0873-4c99-a666-0874a1595811.jpg") private String userAvatar; /** * 用户邮 <SUF>*/ @Schema(description = "用户邮箱", example = "han892577@qq.com") private String email; /** * 用户所属学校名称 */ @Schema(description = "用户所属学校名称", example = "哈尔滨理工大学") private String schoolName; /** * 用户所属学校简写 */ @Schema(description = "用户所属学校简写", example = "HRBUST") private String schoolAbbr; /** * 用户获赞总数 */ @Schema(description = "用户在社区模块的获赞总数", example = "100") private Integer totalLikes; /** * 用户被评论总数 */ @Schema(description = "用户在社区模块的被评论总数", example = "200") private Integer totalComments; /** * 用户被评论总数 */ @Schema(description = "用户未读评论的总数", example = "10") private Integer unReadCommentsCount; private static final long serialVersionUID = 1L; }
0
58831_1
package com.zh.job; /** * @program: data-structures-and-algorithms * @author: AlbertZhang * @create: 2024-03-19 19:20 * @description: 跳跃游戏——leetcode55 **/ public class CanJump { /* 贪心思想,别管最后能不能到,这一步先跳了再说,如果途中有能跳更多步的,就果断换车 */ public boolean canJump(int[] nums) { int step = 0; for (int i = 0; i < nums.length; i++) { step = Math.max(nums[i], step); if (i >= nums.length - 1) { return true; // 说明已经跳到最后了 } if (step == 0 ) { return false; // 说明最后跳不过去了 } step--; } return true; // 通过了校验 } public static void main(String[] args) { System.out.println(new CanJump().canJump(new int[]{2, 3, 1, 0, 4})); } }
AZCodingAccount/java-Data-Structures-and-Algorithms
src/com/zh/job/CanJump.java
282
/* 贪心思想,别管最后能不能到,这一步先跳了再说,如果途中有能跳更多步的,就果断换车 */
block_comment
zh-cn
package com.zh.job; /** * @program: data-structures-and-algorithms * @author: AlbertZhang * @create: 2024-03-19 19:20 * @description: 跳跃游戏——leetcode55 **/ public class CanJump { /* 贪心思 <SUF>*/ public boolean canJump(int[] nums) { int step = 0; for (int i = 0; i < nums.length; i++) { step = Math.max(nums[i], step); if (i >= nums.length - 1) { return true; // 说明已经跳到最后了 } if (step == 0 ) { return false; // 说明最后跳不过去了 } step--; } return true; // 通过了校验 } public static void main(String[] args) { System.out.println(new CanJump().canJump(new int[]{2, 3, 1, 0, 4})); } }
1
60104_11
package com.game.user.handler; import com.game.dispatcher.RequestAnnotation; import com.game.property.manager.InjectProperty; import com.game.role.bean.ConcreteRole; import com.game.role.service.RoleService; import com.game.user.manager.SessionMap; import com.game.user.service.Login; import com.game.user.service.RegisterService; import com.game.utils.CacheUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * 用户controller */ @RequestAnnotation("/user") @Component public class UserHandler { /** * 登录服务 */ @Autowired private Login login; /** * 注册服务 */ @Autowired private RegisterService registerService; /** * 角色服务 */ @Autowired private RoleService roleService; /** * 注入属性 */ @Autowired private InjectProperty injectProperty; /** * 用户登录 * @param username 用户名 * @param password 密码 * @return 信息 */ @RequestAnnotation("/login") public String login(String username, String password) { boolean isSuccess = login.login(username,password); ConcreteRole role = this.getRoleAfterLoginSuccess(username); if(isSuccess){ //加用户名-角色对象 CacheUtils.getMapUsernameRole().put(username,role); injectProperty.initProperty(role.getName()); //校验账号 checkAccount(username,role); return role.getName()+"上线了"; }else{ return role.getName()+"登录失败"; } } /** * 校验账号 * @param username 用户名 * @param role1 角色 */ private void checkAccount(String username, ConcreteRole role1) { ConcreteRole role = CacheUtils.getRole(role1.getName()); Map<String, ConcreteRole> sessionMap = SessionMap.getSessionMap(); ConcreteRole localRole = sessionMap.get(username); if(localRole==null){ sessionMap.put(username,role); }else{ localRole.getChannel().writeAndFlush("账号重复登录"); logout(username); } } /** * 用户登出 * @param username 用户名 */ @RequestAnnotation("/logout") public void logout(String username) { //通过username找到map中的role ConcreteRole role = CacheUtils.getMapUsernameRole().get(username); //移除角色信息,下线 CacheUtils.getMapUsernameRole().remove(username); role.getChannel().writeAndFlush(role.getName()+"下线了"); } /** * 打印当前场景的所有角色信息 * @param mapName 地图名字 * @return 信息 */ @RequestAnnotation("/getRoleInfo") public String getRoleInfo(String mapName) { //获取当前场景的所有角色信息 Map<String,ConcreteRole> map = CacheUtils.getMapUsernameRole(); return returnRoleInfo(map,mapName); } /** * 返回用户角色信息 * @param map 地图 * @param mapName 地图名字 * @return */ private String returnRoleInfo(Map<String, ConcreteRole> map,String mapName) { Set<String> sets = map.keySet(); StringBuffer sb = new StringBuffer(); Iterator<String> iterator = sets.iterator(); while(iterator.hasNext()){ String name = iterator.next(); String map_name = map.get(name).getConcreteMap().getName(); if (map_name.equals(mapName)){ sb.append(map.get(name).getName()+","+map.get(name).getConcreteMap().getName()+","+map.get(name).getCurHp()); } if(iterator.hasNext()){ sb.append(";"); } } return sb.toString(); } /** * 注册 * @param username 用户名 * @param password 密码 * @param ackpassword 确认密码 * @return 信息 */ @RequestAnnotation("/registerService") public String registerService(String username,String password,String ackpassword){ boolean isSuccess = registerService.register(username,password,ackpassword); if(isSuccess){ return returnMsg(username); }else{ return "注册失败"; } } private String returnMsg(String username) { String msg = "成功注册用户"+username+",请继续注册游戏角色"+";\n" +"职业描述:\n" +"1、战士:高物理攻击和高防御,可以使用嘲讽技能,成为BOSS优先攻击的目标\n" +"2、牧师:带有治疗的职业,强力的治疗技能需要有吟唱时间\n" +"3、法师:群体法术伤害,可以攻击复数单位\n" +"4、召唤师:能召唤召唤兽协助战斗。宝宝也能释放技能,而且玩家切换场景的时候自动跟随,玩家收到攻击或主动攻击,宝宝也会释放技能。\n"; return msg; } /** * 成功登录后,获取用户对应人物角色 * @param username 用户名 * @return 角色 */ public ConcreteRole getRoleAfterLoginSuccess(String username){ int id = login.getUserRoleIdByUsername(username); //查找role ConcreteRole role = roleService.getRole(id); //返回role return role; } }
Aaron-TangCode/MMORPG
src/main/java/com/game/user/handler/UserHandler.java
1,414
//移除角色信息,下线
line_comment
zh-cn
package com.game.user.handler; import com.game.dispatcher.RequestAnnotation; import com.game.property.manager.InjectProperty; import com.game.role.bean.ConcreteRole; import com.game.role.service.RoleService; import com.game.user.manager.SessionMap; import com.game.user.service.Login; import com.game.user.service.RegisterService; import com.game.utils.CacheUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * 用户controller */ @RequestAnnotation("/user") @Component public class UserHandler { /** * 登录服务 */ @Autowired private Login login; /** * 注册服务 */ @Autowired private RegisterService registerService; /** * 角色服务 */ @Autowired private RoleService roleService; /** * 注入属性 */ @Autowired private InjectProperty injectProperty; /** * 用户登录 * @param username 用户名 * @param password 密码 * @return 信息 */ @RequestAnnotation("/login") public String login(String username, String password) { boolean isSuccess = login.login(username,password); ConcreteRole role = this.getRoleAfterLoginSuccess(username); if(isSuccess){ //加用户名-角色对象 CacheUtils.getMapUsernameRole().put(username,role); injectProperty.initProperty(role.getName()); //校验账号 checkAccount(username,role); return role.getName()+"上线了"; }else{ return role.getName()+"登录失败"; } } /** * 校验账号 * @param username 用户名 * @param role1 角色 */ private void checkAccount(String username, ConcreteRole role1) { ConcreteRole role = CacheUtils.getRole(role1.getName()); Map<String, ConcreteRole> sessionMap = SessionMap.getSessionMap(); ConcreteRole localRole = sessionMap.get(username); if(localRole==null){ sessionMap.put(username,role); }else{ localRole.getChannel().writeAndFlush("账号重复登录"); logout(username); } } /** * 用户登出 * @param username 用户名 */ @RequestAnnotation("/logout") public void logout(String username) { //通过username找到map中的role ConcreteRole role = CacheUtils.getMapUsernameRole().get(username); //移除 <SUF> CacheUtils.getMapUsernameRole().remove(username); role.getChannel().writeAndFlush(role.getName()+"下线了"); } /** * 打印当前场景的所有角色信息 * @param mapName 地图名字 * @return 信息 */ @RequestAnnotation("/getRoleInfo") public String getRoleInfo(String mapName) { //获取当前场景的所有角色信息 Map<String,ConcreteRole> map = CacheUtils.getMapUsernameRole(); return returnRoleInfo(map,mapName); } /** * 返回用户角色信息 * @param map 地图 * @param mapName 地图名字 * @return */ private String returnRoleInfo(Map<String, ConcreteRole> map,String mapName) { Set<String> sets = map.keySet(); StringBuffer sb = new StringBuffer(); Iterator<String> iterator = sets.iterator(); while(iterator.hasNext()){ String name = iterator.next(); String map_name = map.get(name).getConcreteMap().getName(); if (map_name.equals(mapName)){ sb.append(map.get(name).getName()+","+map.get(name).getConcreteMap().getName()+","+map.get(name).getCurHp()); } if(iterator.hasNext()){ sb.append(";"); } } return sb.toString(); } /** * 注册 * @param username 用户名 * @param password 密码 * @param ackpassword 确认密码 * @return 信息 */ @RequestAnnotation("/registerService") public String registerService(String username,String password,String ackpassword){ boolean isSuccess = registerService.register(username,password,ackpassword); if(isSuccess){ return returnMsg(username); }else{ return "注册失败"; } } private String returnMsg(String username) { String msg = "成功注册用户"+username+",请继续注册游戏角色"+";\n" +"职业描述:\n" +"1、战士:高物理攻击和高防御,可以使用嘲讽技能,成为BOSS优先攻击的目标\n" +"2、牧师:带有治疗的职业,强力的治疗技能需要有吟唱时间\n" +"3、法师:群体法术伤害,可以攻击复数单位\n" +"4、召唤师:能召唤召唤兽协助战斗。宝宝也能释放技能,而且玩家切换场景的时候自动跟随,玩家收到攻击或主动攻击,宝宝也会释放技能。\n"; return msg; } /** * 成功登录后,获取用户对应人物角色 * @param username 用户名 * @return 角色 */ public ConcreteRole getRoleAfterLoginSuccess(String username){ int id = login.getUserRoleIdByUsername(username); //查找role ConcreteRole role = roleService.getRole(id); //返回role return role; } }
0
46735_1
package com.shakazxx.couponspeeder.core.wechat; import android.accessibilityservice.AccessibilityService; import android.graphics.Rect; import android.os.Bundle; import android.view.accessibility.AccessibilityNodeInfo; import com.shakazxx.couponspeeder.core.base.BaseAction; import com.shakazxx.couponspeeder.core.party.CommentDict; import com.shakazxx.couponspeeder.core.util.CommonUtil; import com.shakazxx.couponspeeder.core.util.GestureUtil; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Calendar; import java.util.Date; import java.util.List; import static com.shakazxx.couponspeeder.core.util.CommonUtil.sleep; public class WechatScore extends BaseAction { private BitSet enable = new BitSet(2); private String password; private boolean enableCovid9Report; private boolean enablePartyReport; public WechatScore(AccessibilityService service, Bundle bundle) { super(service); if (bundle == null) { bundle = new Bundle(); } enableCovid9Report = bundle.getBoolean("covid9_report", false); enablePartyReport = bundle.getBoolean("party_report", false); password = bundle.getString("password"); } public void sendMessage(String name, String msg, boolean isGroupChat) { boolean isOnChatPage; // 个人和群组有不同的进入方式 if (!isGroupChat) { isOnChatPage = enterInto("通讯录") && enterInto(name) && enterInto("发消息"); } else { isOnChatPage = enterInto("通讯录") && enterInto("群聊") && enterInto(name); } if (isOnChatPage) { AccessibilityNodeInfo inputNode = CommonUtil.findFirstNodeByClassName(accessibilityService, null, "android.widget.EditText"); CommonUtil.click(inputNode, 1000); CommonUtil.inputText(inputNode, msg); if (!CommonUtil.click(CommonUtil.findFirstNodeByText(accessibilityService, "发送", 2000, 500), 1500)) { // 打开应用后只有第一次可以找到发送按钮,后续只能根据按钮位置点击 GestureUtil.click(accessibilityService, 990, 1230, 1500); } } // 回到首页,恢复状态 goHomePage(); } public void dailyReport(boolean isTodayPartyStudyDone, String resultLog) { if (!loginIfNeeded()) { return; } covid9Report(); partyStudyReport(isTodayPartyStudyDone, resultLog); } private void covid9Report() { if (!enableCovid9Report) { return; } SimpleDateFormat sdf = new SimpleDateFormat("M月d日"); String today = sdf.format(new Date()); String msg = "周沐唯体温36.7"; // sendMessage("哥", msg, false); sendMessage("#2021#中一班", msg, true); // sendMessage("机器人测试", msg, true); sendMessage("哥", today + "幼儿园防疫消息已发", false); enableCovid9Report = false; } private void partyStudyReport(boolean isTodayPartyStudyDone, String resultLog) { if (!enablePartyReport) { return; } SimpleDateFormat sdf = new SimpleDateFormat("M月d日"); String today = sdf.format(new Date()); String msg = String.format("[庆祝][庆祝]%s学习强国完成[烟花][烟花]\n%s", today, resultLog); if (!isTodayPartyStudyDone) { msg = String.format("[叹气][叹气]%s学习强国未完成[衰][衰]\n%s", today, resultLog); } sendMessage("姐", msg, false); sendMessage("哥", msg, false); enablePartyReport = false; } private boolean enterInto(String entryName) { AccessibilityNodeInfo node = CommonUtil.findFirstNodeByText(accessibilityService, entryName, 10000, 1000); if (node == null) { return false; } if (!CommonUtil.click(node, 1500)) { Rect rect = new Rect(); node.getBoundsInScreen(rect); GestureUtil.click(accessibilityService, (rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2, 1500); } return true; } public void cmbScore() { // both has finished if (enable.cardinality() == 1) { return; } if (!loginIfNeeded()) { return; } signScore(); // programScore(); } public void pbcc() { if (!loginIfNeeded()) { return; } exchangeMiles(); } private boolean loginIfNeeded() { AccessibilityNodeInfo pwd = CommonUtil.findFirstNodeByText(accessibilityService, null, "请填写微信密码"); if (pwd == null) { return true; } CommonUtil.inputText(pwd, password); // 点击登陆按钮 GestureUtil.click(accessibilityService, 600, 1100, 5000); // 多等一会儿 return true; } private boolean signScore() { if (enable.get(0)) { return true; } if (CommonUtil.findFirstNodeByText(accessibilityService, "微信", 10000, 1000) == null) { return false; } // 招行信用卡入口 GestureUtil.click(accessibilityService, 600, 300, 1000); AccessibilityNodeInfo item = CommonUtil.findFirstNodeByText(accessibilityService, null, "领积分"); if (item == null) { // title always change, let click fixed position GestureUtil.click(accessibilityService, getWidth() - 10, getHeight() - 10, 5000); } else { CommonUtil.click(item, 5000); } item = CommonUtil.findFirstNodeByText(accessibilityService, null, "签到有好礼"); if (item == null) { GestureUtil.click(accessibilityService, getWidth() - 100, getHeight() - 600, 5000); } else { if (!CommonUtil.click(item, 5000)) { // go back to home page goHomePage(); return false; } } GestureUtil.click(accessibilityService, 500, 300, 1000); enable.set(0); // go back to home page goHomePage(); return true; } private boolean programScore() { if (enable.get(1)) { return true; } GestureUtil.scrollDown(accessibilityService, -600); sleep(1000); List<AccessibilityNodeInfo> nodes = CommonUtil.findAllByViewId(accessibilityService, null, "com.tencent.mm:id/ct"); if (nodes.size() == 0) { return false; } boolean find = false; for (AccessibilityNodeInfo node : nodes) { if (node.getText() != null && "招行信用卡".equalsIgnoreCase(node.getText().toString())) { CommonUtil.click(node, 10000); find = true; break; } } if (!find) { return false; } GestureUtil.click(accessibilityService, 500, 1300, 10000); GestureUtil.click(accessibilityService, 500, 600, 1000); enable.set(1); goHomePage(); return true; } private boolean exchangeMiles() { // 看下时间是不是10点不到些 Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour != 9) { return false; } int minute = calendar.get(Calendar.MINUTE); if (minute != 59) { return false; } List<AccessibilityNodeInfo> nodes = CommonUtil.findAllByViewId(accessibilityService, null, "com.tencent.mm:id/b4o"); if (nodes.size() == 0) { return false; } boolean find = false; for (AccessibilityNodeInfo node : nodes) { if (node.getText() != null && "浦发银行信用卡".equalsIgnoreCase(node.getText().toString())) { CommonUtil.click(node, 5000); find = true; break; } } if (!find) { return false; } AccessibilityNodeInfo item = CommonUtil.findFirstNodeByText(accessibilityService, null, "小浦\uD83C\uDF81福利"); CommonUtil.click(item, 5000); item = CommonUtil.findFirstNodeByText(accessibilityService, null, "消费红包·全能积分"); if (!CommonUtil.click(item, 5000)) { return false; } GestureUtil.click(accessibilityService, 100, 1300, 3000); GestureUtil.click(accessibilityService, 10, 300, 3000); // 等到10点整,再点 while (true) { calendar = Calendar.getInstance(); calendar.setTime(new Date()); hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour != 10) { sleep(100); continue; } GestureUtil.click(accessibilityService, 300, 1000, 3000); break; } // go back to home page goHomePage(); return true; } private void goHomePage() { while (true) { if (CommonUtil.findFirstNodeByText(accessibilityService, null, "通讯录") != null) { return; } CommonUtil.globalBack(accessibilityService, 1000); } } }
AaronGeist/CouponSpeeder
app/src/main/java/com/shakazxx/couponspeeder/core/wechat/WechatScore.java
2,465
// 打开应用后只有第一次可以找到发送按钮,后续只能根据按钮位置点击
line_comment
zh-cn
package com.shakazxx.couponspeeder.core.wechat; import android.accessibilityservice.AccessibilityService; import android.graphics.Rect; import android.os.Bundle; import android.view.accessibility.AccessibilityNodeInfo; import com.shakazxx.couponspeeder.core.base.BaseAction; import com.shakazxx.couponspeeder.core.party.CommentDict; import com.shakazxx.couponspeeder.core.util.CommonUtil; import com.shakazxx.couponspeeder.core.util.GestureUtil; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.BitSet; import java.util.Calendar; import java.util.Date; import java.util.List; import static com.shakazxx.couponspeeder.core.util.CommonUtil.sleep; public class WechatScore extends BaseAction { private BitSet enable = new BitSet(2); private String password; private boolean enableCovid9Report; private boolean enablePartyReport; public WechatScore(AccessibilityService service, Bundle bundle) { super(service); if (bundle == null) { bundle = new Bundle(); } enableCovid9Report = bundle.getBoolean("covid9_report", false); enablePartyReport = bundle.getBoolean("party_report", false); password = bundle.getString("password"); } public void sendMessage(String name, String msg, boolean isGroupChat) { boolean isOnChatPage; // 个人和群组有不同的进入方式 if (!isGroupChat) { isOnChatPage = enterInto("通讯录") && enterInto(name) && enterInto("发消息"); } else { isOnChatPage = enterInto("通讯录") && enterInto("群聊") && enterInto(name); } if (isOnChatPage) { AccessibilityNodeInfo inputNode = CommonUtil.findFirstNodeByClassName(accessibilityService, null, "android.widget.EditText"); CommonUtil.click(inputNode, 1000); CommonUtil.inputText(inputNode, msg); if (!CommonUtil.click(CommonUtil.findFirstNodeByText(accessibilityService, "发送", 2000, 500), 1500)) { // 打开 <SUF> GestureUtil.click(accessibilityService, 990, 1230, 1500); } } // 回到首页,恢复状态 goHomePage(); } public void dailyReport(boolean isTodayPartyStudyDone, String resultLog) { if (!loginIfNeeded()) { return; } covid9Report(); partyStudyReport(isTodayPartyStudyDone, resultLog); } private void covid9Report() { if (!enableCovid9Report) { return; } SimpleDateFormat sdf = new SimpleDateFormat("M月d日"); String today = sdf.format(new Date()); String msg = "周沐唯体温36.7"; // sendMessage("哥", msg, false); sendMessage("#2021#中一班", msg, true); // sendMessage("机器人测试", msg, true); sendMessage("哥", today + "幼儿园防疫消息已发", false); enableCovid9Report = false; } private void partyStudyReport(boolean isTodayPartyStudyDone, String resultLog) { if (!enablePartyReport) { return; } SimpleDateFormat sdf = new SimpleDateFormat("M月d日"); String today = sdf.format(new Date()); String msg = String.format("[庆祝][庆祝]%s学习强国完成[烟花][烟花]\n%s", today, resultLog); if (!isTodayPartyStudyDone) { msg = String.format("[叹气][叹气]%s学习强国未完成[衰][衰]\n%s", today, resultLog); } sendMessage("姐", msg, false); sendMessage("哥", msg, false); enablePartyReport = false; } private boolean enterInto(String entryName) { AccessibilityNodeInfo node = CommonUtil.findFirstNodeByText(accessibilityService, entryName, 10000, 1000); if (node == null) { return false; } if (!CommonUtil.click(node, 1500)) { Rect rect = new Rect(); node.getBoundsInScreen(rect); GestureUtil.click(accessibilityService, (rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2, 1500); } return true; } public void cmbScore() { // both has finished if (enable.cardinality() == 1) { return; } if (!loginIfNeeded()) { return; } signScore(); // programScore(); } public void pbcc() { if (!loginIfNeeded()) { return; } exchangeMiles(); } private boolean loginIfNeeded() { AccessibilityNodeInfo pwd = CommonUtil.findFirstNodeByText(accessibilityService, null, "请填写微信密码"); if (pwd == null) { return true; } CommonUtil.inputText(pwd, password); // 点击登陆按钮 GestureUtil.click(accessibilityService, 600, 1100, 5000); // 多等一会儿 return true; } private boolean signScore() { if (enable.get(0)) { return true; } if (CommonUtil.findFirstNodeByText(accessibilityService, "微信", 10000, 1000) == null) { return false; } // 招行信用卡入口 GestureUtil.click(accessibilityService, 600, 300, 1000); AccessibilityNodeInfo item = CommonUtil.findFirstNodeByText(accessibilityService, null, "领积分"); if (item == null) { // title always change, let click fixed position GestureUtil.click(accessibilityService, getWidth() - 10, getHeight() - 10, 5000); } else { CommonUtil.click(item, 5000); } item = CommonUtil.findFirstNodeByText(accessibilityService, null, "签到有好礼"); if (item == null) { GestureUtil.click(accessibilityService, getWidth() - 100, getHeight() - 600, 5000); } else { if (!CommonUtil.click(item, 5000)) { // go back to home page goHomePage(); return false; } } GestureUtil.click(accessibilityService, 500, 300, 1000); enable.set(0); // go back to home page goHomePage(); return true; } private boolean programScore() { if (enable.get(1)) { return true; } GestureUtil.scrollDown(accessibilityService, -600); sleep(1000); List<AccessibilityNodeInfo> nodes = CommonUtil.findAllByViewId(accessibilityService, null, "com.tencent.mm:id/ct"); if (nodes.size() == 0) { return false; } boolean find = false; for (AccessibilityNodeInfo node : nodes) { if (node.getText() != null && "招行信用卡".equalsIgnoreCase(node.getText().toString())) { CommonUtil.click(node, 10000); find = true; break; } } if (!find) { return false; } GestureUtil.click(accessibilityService, 500, 1300, 10000); GestureUtil.click(accessibilityService, 500, 600, 1000); enable.set(1); goHomePage(); return true; } private boolean exchangeMiles() { // 看下时间是不是10点不到些 Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour != 9) { return false; } int minute = calendar.get(Calendar.MINUTE); if (minute != 59) { return false; } List<AccessibilityNodeInfo> nodes = CommonUtil.findAllByViewId(accessibilityService, null, "com.tencent.mm:id/b4o"); if (nodes.size() == 0) { return false; } boolean find = false; for (AccessibilityNodeInfo node : nodes) { if (node.getText() != null && "浦发银行信用卡".equalsIgnoreCase(node.getText().toString())) { CommonUtil.click(node, 5000); find = true; break; } } if (!find) { return false; } AccessibilityNodeInfo item = CommonUtil.findFirstNodeByText(accessibilityService, null, "小浦\uD83C\uDF81福利"); CommonUtil.click(item, 5000); item = CommonUtil.findFirstNodeByText(accessibilityService, null, "消费红包·全能积分"); if (!CommonUtil.click(item, 5000)) { return false; } GestureUtil.click(accessibilityService, 100, 1300, 3000); GestureUtil.click(accessibilityService, 10, 300, 3000); // 等到10点整,再点 while (true) { calendar = Calendar.getInstance(); calendar.setTime(new Date()); hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour != 10) { sleep(100); continue; } GestureUtil.click(accessibilityService, 300, 1000, 3000); break; } // go back to home page goHomePage(); return true; } private void goHomePage() { while (true) { if (CommonUtil.findFirstNodeByText(accessibilityService, null, "通讯录") != null) { return; } CommonUtil.globalBack(accessibilityService, 1000); } } }
0
38197_0
package com.mk.hms.enums; public enum HmsHotelTypeEnum { // 旅馆/主题酒店/精品酒店/公寓酒店/ // 招待所/客栈 HOTEL(1,"旅馆"),THEMEDHOTEL(2,"主题酒店"),PLAZAHOTEL(3,"精品酒店"),APARTMENTHOTEL(4,"公寓"), HOSTELS(5,"招待所"),INNER(6,"客栈"); private HmsHotelTypeEnum(int value, String text) { this.value = value; this.text = text; } private int value; private String text; public int getValue() { return value; } public String getText() { return text; } }
AaronSum/hotel-mgr-sys
src/main/java/com/mk/hms/enums/HmsHotelTypeEnum.java
210
// 旅馆/主题酒店/精品酒店/公寓酒店/
line_comment
zh-cn
package com.mk.hms.enums; public enum HmsHotelTypeEnum { // 旅馆 <SUF> // 招待所/客栈 HOTEL(1,"旅馆"),THEMEDHOTEL(2,"主题酒店"),PLAZAHOTEL(3,"精品酒店"),APARTMENTHOTEL(4,"公寓"), HOSTELS(5,"招待所"),INNER(6,"客栈"); private HmsHotelTypeEnum(int value, String text) { this.value = value; this.text = text; } private int value; private String text; public int getValue() { return value; } public String getText() { return text; } }
1
56040_1
package com.my.crawler; import java.nio.charset.Charset; import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.util.AntPathMatcher; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration public class SpringWebConfig extends WebMvcConfigurationSupport { @Override public void configurePathMatch(PathMatchConfigurer configurer) { AntPathMatcher pathMatcher = new AntPathMatcher(); pathMatcher.setCaseSensitive(false); configurer.setPathMatcher(pathMatcher); } @Bean public HttpMessageConverter<String> responseBodyConverter() { return new StringHttpMessageConverter(Charset.forName("UTF-8")); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(responseBodyConverter()); // 这里必须加上加载默认转换器,不然bug玩死人,并且该bug目前在网络上似乎没有解决方案 // 百度,谷歌,各大论坛等。你可以试试去掉。 addDefaultHttpMessageConverters(converters); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } }
Abbreviation-g/administrative-division-crawler
administrative-division-crawler/src/main/java/com/my/crawler/SpringWebConfig.java
381
// 百度,谷歌,各大论坛等。你可以试试去掉。
line_comment
zh-cn
package com.my.crawler; import java.nio.charset.Charset; import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.util.AntPathMatcher; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration public class SpringWebConfig extends WebMvcConfigurationSupport { @Override public void configurePathMatch(PathMatchConfigurer configurer) { AntPathMatcher pathMatcher = new AntPathMatcher(); pathMatcher.setCaseSensitive(false); configurer.setPathMatcher(pathMatcher); } @Bean public HttpMessageConverter<String> responseBodyConverter() { return new StringHttpMessageConverter(Charset.forName("UTF-8")); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(responseBodyConverter()); // 这里必须加上加载默认转换器,不然bug玩死人,并且该bug目前在网络上似乎没有解决方案 // 百度 <SUF> addDefaultHttpMessageConverters(converters); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } }
1
27619_1
package algorithm; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.spark.deploy.yarn.Client; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import util.Utils; public class MonitorThread implements Runnable { private Logger log = LoggerFactory.getLogger(getClass()); private ApplicationId appId; private Client client ; public MonitorThread() { } public MonitorThread(ApplicationId applicationId,Client client) { this.appId = applicationId; this.client = client; } @Override public void run() { long interval = 1000;// 更新Application 状态间隔 int count =0; // 时间 ApplicationReport report = null; while (true) { try { Thread.sleep(interval); } catch (InterruptedException e1) { e1.printStackTrace(); } try { report = client.getApplicationReport(appId); } catch (Exception e) { e.printStackTrace(); } YarnApplicationState state = report.getYarnApplicationState(); log.info("Thread:"+Thread.currentThread().getName()+ appId.toString()+",任务状态是:"+state.name()); // 完成/ 失败/杀死 if (state == YarnApplicationState.FINISHED || state == YarnApplicationState.FAILED || state == YarnApplicationState.KILLED) { Utils.cleanupStagingDir(appId); // return (state, report.getFinalApplicationStatus); // 更新 app状态 log.info("Thread:"+Thread.currentThread().getName()+ appId.toString()+"完成,任务状态是:"+state.name()); Utils.updateAppStatus(appId.toString(), state.name()); return; } // 获得ApplicationID后就说明已经是SUBMITTED状态了 if ( state == YarnApplicationState.ACCEPTED) { // 更新app状态 if(count<Integer.parseInt(Utils.getProperty("als.accepted.progress"))){ count++; Utils.updateAppStatus(appId.toString(), count+"%" ); } } if ( state == YarnApplicationState.RUNNING) { // 更新app状态 if(count<Integer.parseInt(Utils.getProperty("als.runing.progress"))){ count++; Utils.updateAppStatus(appId.toString(), count+"%" ); }else { Utils.updateAppStatus(appId.toString(), Utils.getProperty("als.runing.progress")+"%" ); } } } } }
AbnerEarl/Shopping-Recommand-for-Spring-SpringMVC-Hibernate
Spark/shop_recommend/src/algorithm/MonitorThread.java
663
// 完成/ 失败/杀死
line_comment
zh-cn
package algorithm; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.spark.deploy.yarn.Client; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import util.Utils; public class MonitorThread implements Runnable { private Logger log = LoggerFactory.getLogger(getClass()); private ApplicationId appId; private Client client ; public MonitorThread() { } public MonitorThread(ApplicationId applicationId,Client client) { this.appId = applicationId; this.client = client; } @Override public void run() { long interval = 1000;// 更新Application 状态间隔 int count =0; // 时间 ApplicationReport report = null; while (true) { try { Thread.sleep(interval); } catch (InterruptedException e1) { e1.printStackTrace(); } try { report = client.getApplicationReport(appId); } catch (Exception e) { e.printStackTrace(); } YarnApplicationState state = report.getYarnApplicationState(); log.info("Thread:"+Thread.currentThread().getName()+ appId.toString()+",任务状态是:"+state.name()); // 完成 <SUF> if (state == YarnApplicationState.FINISHED || state == YarnApplicationState.FAILED || state == YarnApplicationState.KILLED) { Utils.cleanupStagingDir(appId); // return (state, report.getFinalApplicationStatus); // 更新 app状态 log.info("Thread:"+Thread.currentThread().getName()+ appId.toString()+"完成,任务状态是:"+state.name()); Utils.updateAppStatus(appId.toString(), state.name()); return; } // 获得ApplicationID后就说明已经是SUBMITTED状态了 if ( state == YarnApplicationState.ACCEPTED) { // 更新app状态 if(count<Integer.parseInt(Utils.getProperty("als.accepted.progress"))){ count++; Utils.updateAppStatus(appId.toString(), count+"%" ); } } if ( state == YarnApplicationState.RUNNING) { // 更新app状态 if(count<Integer.parseInt(Utils.getProperty("als.runing.progress"))){ count++; Utils.updateAppStatus(appId.toString(), count+"%" ); }else { Utils.updateAppStatus(appId.toString(), Utils.getProperty("als.runing.progress")+"%" ); } } } } }
1
55683_1
package Others; /** * Author: * Created at:2022/8/8 * Updated at: * * 198. 打家劫舍 * *你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 * * 给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 * **/ public class MaxSumOfNumsInArrayNotConstant { /* LC.198.打家劫舍 2022.3.20:Hou:自己想出了动态规划的方法,自己用代码实现了。 */ static class Solution { public int rob(int[] nums) { //dp[i][j]表示第i间屋子,[j]=0表示截至目前+没偷这间屋子钱时的最大偷取金额;[j]=1表示截至目前+偷了这间屋子钱时的最大偷取金额 int[][ ] dp=new int[nums.length][2]; dp[0][0]=0; dp[0][1]=nums[0]; for(int i=1;i<nums.length;i++){ dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]); if(i==1){ dp[i][1]= Math.max(nums[1],nums[0]); } else{ dp[i][1]=Math.max(dp[i-1][0]+nums[i],dp[i-2][1]+nums[i]); } } return Math.max(dp[dp.length-1][0],dp[dp.length-1][1]); } } }
Abneriii/Algorithm
src/Others/MaxSumOfNumsInArrayNotConstant.java
521
/* LC.198.打家劫舍 2022.3.20:Hou:自己想出了动态规划的方法,自己用代码实现了。 */
block_comment
zh-cn
package Others; /** * Author: * Created at:2022/8/8 * Updated at: * * 198. 打家劫舍 * *你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 * * 给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 * **/ public class MaxSumOfNumsInArrayNotConstant { /* LC. <SUF>*/ static class Solution { public int rob(int[] nums) { //dp[i][j]表示第i间屋子,[j]=0表示截至目前+没偷这间屋子钱时的最大偷取金额;[j]=1表示截至目前+偷了这间屋子钱时的最大偷取金额 int[][ ] dp=new int[nums.length][2]; dp[0][0]=0; dp[0][1]=nums[0]; for(int i=1;i<nums.length;i++){ dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]); if(i==1){ dp[i][1]= Math.max(nums[1],nums[0]); } else{ dp[i][1]=Math.max(dp[i-1][0]+nums[i],dp[i-2][1]+nums[i]); } } return Math.max(dp[dp.length-1][0],dp[dp.length-1][1]); } } }
1
29001_20
package com.jingewenku.abrahamcaijin.commonutil; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Environment; import com.facebook.cache.disk.DiskCacheConfig; import com.facebook.common.internal.Supplier; import com.facebook.common.util.ByteConstants; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.cache.MemoryCacheParams; import com.facebook.imagepipeline.common.ImageDecodeOptions; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequest.RequestLevel; import com.facebook.imagepipeline.request.ImageRequestBuilder; /** * @Description:主要功能:Fresco图片加载工具类 * @Prject: CommonUtilLibrary * @Package: com.jingewenku.abrahamcaijin.commonutil * @author: AbrahamCaiJin * @date: 2017年05月19日 14:38 * @Copyright: 个人版权所有 * @Company: * @version: 1.0.0 */ public class FrescoUtils { private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory();//分配的可用内存 public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4;//使用的缓存数量 public static final int MAX_SMALL_DISK_VERYLOW_CACHE_SIZE = 5 * ByteConstants.MB;//小图极低磁盘空间缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图) public static final int MAX_SMALL_DISK_LOW_CACHE_SIZE = 10 * ByteConstants.MB;//小图低磁盘空间缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图) public static final int MAX_SMALL_DISK_CACHE_SIZE = 20 * ByteConstants.MB;//小图磁盘缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图) public static final int MAX_DISK_CACHE_VERYLOW_SIZE = 10 * ByteConstants.MB;//默认图极低磁盘空间缓存的最大值 public static final int MAX_DISK_CACHE_LOW_SIZE = 30 * ByteConstants.MB;//默认图低磁盘空间缓存的最大值 public static final int MAX_DISK_CACHE_SIZE = 50 * ByteConstants.MB;//默认图磁盘缓存的最大值 private static final String IMAGE_PIPELINE_SMALL_CACHE_DIR = "imagepipeline_cache";//小图所放路径的文件夹名 private static final String IMAGE_PIPELINE_CACHE_DIR = "imagepipeline_cache";//默认图所放路径的文件夹名 private static ImagePipelineConfig sImagePipelineConfig; private FrescoUtils(){ } /** * 初始化配置,单例 * FrescoUtils.initConfig(context); * * 初始化配置的两种方式: * 在 Application 初始化时,在应用调用 setContentView() 之前,进行初始化: * Fresco.initialize(context); * * @param context * @return */ public static void initConfig(Context context) { ImagePipelineConfig initImagePipelineConfig = initImagePipelineConfig(context); Fresco.initialize(context, initImagePipelineConfig); } public static ImagePipelineConfig initImagePipelineConfig(Context context) { if (sImagePipelineConfig == null) { sImagePipelineConfig = configureCaches(context); } return sImagePipelineConfig; } // 默认加载图片和失败图片 public static Drawable sPlaceholderDrawable; public static Drawable sErrorDrawable; public static void init(final Resources resources) { if (sPlaceholderDrawable == null) { sPlaceholderDrawable = resources.getDrawable(R.color.transparency); } if (sErrorDrawable == null) { sErrorDrawable = resources.getDrawable(R.color.gray); } } /** * 初始化配置 * @param context * @return */ private static ImagePipelineConfig configureCaches(Context context) { // 内存配置 final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams( FrescoUtils.MAX_MEMORY_CACHE_SIZE, // 内存缓存中总图片的最大大小,以字节为单位。 Integer.MAX_VALUE, // 内存缓存中图片的最大数量。 FrescoUtils.MAX_MEMORY_CACHE_SIZE, // 内存缓存中准备清除但尚未被删除的总图片的最大大小,以字节为单位。 Integer.MAX_VALUE, // 内存缓存中准备清除的总图片的最大数量。 Integer.MAX_VALUE); // 内存缓存中单个图片的最大大小。 // 修改内存图片缓存数量,空间策略(这个方式有点恶心) Supplier<MemoryCacheParams> mSupplierMemoryCacheParams = new Supplier<MemoryCacheParams>() { @Override public MemoryCacheParams get() { return bitmapCacheParams; } }; // 小图片的磁盘配置 DiskCacheConfig diskSmallCacheConfig = DiskCacheConfig .newBuilder(context) .setBaseDirectoryPath(context.getApplicationContext().getCacheDir())// 缓存图片基路径 .setBaseDirectoryName(IMAGE_PIPELINE_SMALL_CACHE_DIR)// 文件夹名 // .setCacheErrorLogger(cacheErrorLogger)//日志记录器用于日志错误的缓存。 // .setCacheEventListener(cacheEventListener)//缓存事件侦听器。 // .setDiskTrimmableRegistry(diskTrimmableRegistry)//类将包含一个注册表的缓存减少磁盘空间的环境。 .setMaxCacheSize(FrescoUtils.MAX_DISK_CACHE_SIZE)// 默认缓存的最大大小。 .setMaxCacheSizeOnLowDiskSpace(MAX_SMALL_DISK_LOW_CACHE_SIZE)// 缓存的最大大小,使用设备时低磁盘空间。 .setMaxCacheSizeOnVeryLowDiskSpace(MAX_SMALL_DISK_VERYLOW_CACHE_SIZE)// 缓存的最大大小,当设备极低磁盘空间 // .setVersion(version) .build(); // 默认图片的磁盘配置 DiskCacheConfig diskCacheConfig = DiskCacheConfig .newBuilder(context) .setBaseDirectoryPath(Environment.getExternalStorageDirectory().getAbsoluteFile())// 缓存图片基路径 .setBaseDirectoryName(IMAGE_PIPELINE_CACHE_DIR)// 文件夹名 // .setCacheErrorLogger(cacheErrorLogger)//日志记录器用于日志错误的缓存。 // .setCacheEventListener(cacheEventListener)//缓存事件侦听器。 // .setDiskTrimmableRegistry(diskTrimmableRegistry)//类将包含一个注册表的缓存减少磁盘空间的环境。 .setMaxCacheSize(FrescoUtils.MAX_DISK_CACHE_SIZE)// 默认缓存的最大大小。 .setMaxCacheSizeOnLowDiskSpace(MAX_DISK_CACHE_LOW_SIZE)// 缓存的最大大小,使用设备时低磁盘空间。 .setMaxCacheSizeOnVeryLowDiskSpace(MAX_DISK_CACHE_VERYLOW_SIZE)// 缓存的最大大小,当设备极低磁盘空间 // .setVersion(version) .build(); // 缓存图片配置 ImagePipelineConfig.Builder configBuilder = ImagePipelineConfig .newBuilder(context) // .setAnimatedImageFactory(AnimatedImageFactory // animatedImageFactory)//图片加载动画 .setBitmapMemoryCacheParamsSupplier(mSupplierMemoryCacheParams)// 内存缓存配置(一级缓存,已解码的图片) // .setCacheKeyFactory(cacheKeyFactory)//缓存Key工厂 // .setEncodedMemoryCacheParamsSupplier(encodedCacheParamsSupplier)//内存缓存和未解码的内存缓存的配置(二级缓存) // .setExecutorSupplier(executorSupplier)//线程池配置 // .setImageCacheStatsTracker(imageCacheStatsTracker)//统计缓存的命中率 // .setImageDecoder(ImageDecoder imageDecoder) //图片解码器配置 // .setIsPrefetchEnabledSupplier(Supplier<Boolean> // isPrefetchEnabledSupplier)//图片预览(缩略图,预加载图等)预加载到文件缓存 .setMainDiskCacheConfig(diskCacheConfig)// 磁盘缓存配置(总,三级缓存) // .setMemoryTrimmableRegistry(memoryTrimmableRegistry) // //内存用量的缩减,有时我们可能会想缩小内存用量。比如应用中有其他数据需要占用内存,不得不把图片缓存清除或者减小 // 或者我们想检查看看手机是否已经内存不够了。 // .setNetworkFetchProducer(networkFetchProducer)//自定的网络层配置:如OkHttp,Volley // .setPoolFactory(poolFactory)//线程池工厂配置 // .setProgressiveJpegConfig(progressiveJpegConfig)//渐进式JPEG图 // .setRequestListeners(requestListeners)//图片请求监听 // .setResizeAndRotateEnabledForNetwork(boolean // resizeAndRotateEnabledForNetwork)//调整和旋转是否支持网络图片 .setSmallImageDiskCacheConfig(diskSmallCacheConfig)// 磁盘缓存配置(小图片,可选~三级缓存的小图优化缓存) ; return configBuilder.build(); } /** * 在 Application 初始化时,在应用调用 setContentView() 之前,进行初始化: * Fresco.initialize(context); * * 在xml布局文件中, 加入命名空间: * * !-- 其他元素 --> LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:fresco="http://schemas.android.com/apk/res-auto"> * 加入SimpleDraweeView: <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="20dp" android:layout_height="20dp" fresco:placeholderImage="@drawable/my_drawable" /> * SimpleDraweeView draweeView = (SimpleDraweeView) findViewById(R.id.my_image_view); * * <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="20dp" // 不支持wrap_content 如果要设置宽高比, 需要在Java代码中指定setAspectRatio(1.33f); android:layout_height="20dp" // 不支持wrap_content fresco:fadeDuration="300" fresco:actualImageScaleType="focusCrop"// 设置图片缩放. 通常使用focusCrop,该属性值会通过算法把人头像放在中间 fresco:placeholderImage="@color/wait_color"// 下载成功之前显示的图片 fresco:placeholderImageScaleType="fitCenter" fresco:failureImage="@drawable/error"// 加载失败的时候显示的图片 fresco:failureImageScaleType="centerInside" fresco:retryImage="@drawable/retrying"// 加载失败,提示用户点击重新加载的图片(会覆盖failureImage的图片) fresco:retryImageScaleType="centerCrop" fresco:progressBarImage="@drawable/progress_bar"// 提示用户正在加载,和加载进度无关 fresco:progressBarImageScaleType="centerInside" fresco:progressBarAutoRotateInterval="1000" fresco:backgroundImage="@color/blue" fresco:overlayImage="@drawable/watermark" fresco:pressedStateOverlayImage="@color/red" fresco:roundAsCircle="false"// 是不是设置圆圈 fresco:roundedCornerRadius="1dp"// 圆角角度,180的时候会变成圆形图片 fresco:roundTopLeft="true" fresco:roundTopRight="false" fresco:roundBottomLeft="false" fresco:roundBottomRight="true" fresco:roundWithOverlayColor="@color/corner_color" fresco:roundingBorderWidth="2dp" fresco:roundingBorderColor="@color/border_color" /> * * * 特别注意:Fresco 不支持 相对路径的URI. 所有的URI都必须是绝对路径,并且带上该URI的scheme。 如下: 类型 Scheme 示例 远程图片 http://, https:// HttpURLConnection 或者参考 使用其他网络加载方案 本地文件 file:// FileInputStream Content provider content:// ContentResolver asset目录下的资源 asset:// AssetManager res目录下的资源 res:// Resources.openRawResource res 示例: Uri uri = Uri.parse("res://包名(实际可以是任何字符串甚至留空)/" + R.drawable.ic_launcher); * */ /** * 开始加载图片 * @param draweeView * @param uriString */ public static void setImageURI(SimpleDraweeView draweeView , String uriString) { Uri uri = Uri.parse(uriString); draweeView.setImageURI(uri); } /** * 自定义图片尺寸 * @param draweeView 显示的控件 * @param uriString 地址 * @param width 50 * @param height 50 */ public static void changeImgSize(SimpleDraweeView draweeView , String uriString , int width , int height) { ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uriString)) .setResizeOptions(new ResizeOptions(width, height)) .build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setAutoPlayAnimations(true)// other setters .build(); draweeView.setController(controller); } /** * 加载gif图 * @param draweeView * @param uriString */ public static void loadGif(SimpleDraweeView draweeView , String uriString) { ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uriString)).build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setAutoPlayAnimations(true) .build(); draweeView.setController(controller); } /** * 多图请求需 自定义ImageRequest(图片预览) * @param draweeView * @param lowResUri * @param highResUri */ public static void moreImgRequst(SimpleDraweeView draweeView , String lowResUri , String highResUri ) { DraweeController controller = Fresco.newDraweeControllerBuilder() .setLowResImageRequest(ImageRequest.fromUri(Uri.parse(lowResUri)))//低分辨率的缩略图 .setImageRequest(ImageRequest.fromUri(Uri.parse(highResUri)))//高分辨率的图 .setOldController(draweeView.getController()) .build(); draweeView.setController(controller); } /** * 缩略图预览(仅支持本地图片,并且是JPEG图片格式) * @param draweeView * @param uri */ public static void localImg(SimpleDraweeView draweeView , Uri uri ) { ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri) .setLocalThumbnailPreviewsEnabled(true) .build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setOldController(draweeView.getController()) .build(); draweeView.setController(controller); } /** * 请求图片 * @param uri - 唯一的必选的成员. 参考 支持的URIs * @param width * @param height * autoRotateEnabled - 是否支持自动旋转. * progressiveEnabled - 是否支持渐进式加载. * postprocessor - 后处理器(postprocess). * resizeOptions - 图片缩放选项,用前请先阅读缩放和旋转 */ public static void loadImage(SimpleDraweeView draweeView , String uri , int width , int height) { ImageRequest request = ImageRequestBuilder .newBuilderWithSource(Uri.parse(uri)) .setAutoRotateEnabled(true)// 是否支持自动旋转. .setImageDecodeOptions(getImageDecodeOptions())// 图片解码库 //.setImageType(ImageType.SMALL)//图片类型,设置后可调整图片放入小图磁盘空间还是默认图片磁盘空间 //.setLocalThumbnailPreviewsEnabled(true)//缩略图预览,影响图片显示速度(轻微) .setLowestPermittedRequestLevel(RequestLevel.FULL_FETCH)//请求经过缓存级别 BITMAP_MEMORY_CACHE,ENCODED_MEMORY_CACHE,DISK_CACHE,FULL_FETCH .setProgressiveRenderingEnabled(false)//渐进加载,主要用于渐进式的JPEG图,影响图片显示速度(普通) .setResizeOptions(new ResizeOptions(width, height)) .build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setOldController(draweeView.getController()) .build(); draweeView.setController(controller); } /** * 图片解码 * @return */ public static ImageDecodeOptions getImageDecodeOptions() { ImageDecodeOptions decodeOptions = ImageDecodeOptions.newBuilder() // .setBackgroundColor(Color.TRANSPARENT)//图片的背景颜色 // .setDecodeAllFrames(decodeAllFrames)//解码所有帧 // .setDecodePreviewFrame(decodePreviewFrame)//解码预览框 // .setForceOldAnimationCode(forceOldAnimationCode)//使用以前动画 // .setFrom(options)//使用已经存在的图像解码 // .setMinDecodeIntervalMs(intervalMs)//最小解码间隔(分位单位) .setUseLastFrameForPreview(true)// 使用最后一帧进行预览 .build(); return decodeOptions; } }
AbrahamCaiJin/CommonUtilLibrary
CommonUtil/src/main/java/com/jingewenku/abrahamcaijin/commonutil/FrescoUtils.java
4,306
// 修改内存图片缓存数量,空间策略(这个方式有点恶心)
line_comment
zh-cn
package com.jingewenku.abrahamcaijin.commonutil; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Environment; import com.facebook.cache.disk.DiskCacheConfig; import com.facebook.common.internal.Supplier; import com.facebook.common.util.ByteConstants; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.cache.MemoryCacheParams; import com.facebook.imagepipeline.common.ImageDecodeOptions; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequest.RequestLevel; import com.facebook.imagepipeline.request.ImageRequestBuilder; /** * @Description:主要功能:Fresco图片加载工具类 * @Prject: CommonUtilLibrary * @Package: com.jingewenku.abrahamcaijin.commonutil * @author: AbrahamCaiJin * @date: 2017年05月19日 14:38 * @Copyright: 个人版权所有 * @Company: * @version: 1.0.0 */ public class FrescoUtils { private static final int MAX_HEAP_SIZE = (int) Runtime.getRuntime().maxMemory();//分配的可用内存 public static final int MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 4;//使用的缓存数量 public static final int MAX_SMALL_DISK_VERYLOW_CACHE_SIZE = 5 * ByteConstants.MB;//小图极低磁盘空间缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图) public static final int MAX_SMALL_DISK_LOW_CACHE_SIZE = 10 * ByteConstants.MB;//小图低磁盘空间缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图) public static final int MAX_SMALL_DISK_CACHE_SIZE = 20 * ByteConstants.MB;//小图磁盘缓存的最大值(特性:可将大量的小图放到额外放在另一个磁盘空间防止大图占用磁盘空间而删除了大量的小图) public static final int MAX_DISK_CACHE_VERYLOW_SIZE = 10 * ByteConstants.MB;//默认图极低磁盘空间缓存的最大值 public static final int MAX_DISK_CACHE_LOW_SIZE = 30 * ByteConstants.MB;//默认图低磁盘空间缓存的最大值 public static final int MAX_DISK_CACHE_SIZE = 50 * ByteConstants.MB;//默认图磁盘缓存的最大值 private static final String IMAGE_PIPELINE_SMALL_CACHE_DIR = "imagepipeline_cache";//小图所放路径的文件夹名 private static final String IMAGE_PIPELINE_CACHE_DIR = "imagepipeline_cache";//默认图所放路径的文件夹名 private static ImagePipelineConfig sImagePipelineConfig; private FrescoUtils(){ } /** * 初始化配置,单例 * FrescoUtils.initConfig(context); * * 初始化配置的两种方式: * 在 Application 初始化时,在应用调用 setContentView() 之前,进行初始化: * Fresco.initialize(context); * * @param context * @return */ public static void initConfig(Context context) { ImagePipelineConfig initImagePipelineConfig = initImagePipelineConfig(context); Fresco.initialize(context, initImagePipelineConfig); } public static ImagePipelineConfig initImagePipelineConfig(Context context) { if (sImagePipelineConfig == null) { sImagePipelineConfig = configureCaches(context); } return sImagePipelineConfig; } // 默认加载图片和失败图片 public static Drawable sPlaceholderDrawable; public static Drawable sErrorDrawable; public static void init(final Resources resources) { if (sPlaceholderDrawable == null) { sPlaceholderDrawable = resources.getDrawable(R.color.transparency); } if (sErrorDrawable == null) { sErrorDrawable = resources.getDrawable(R.color.gray); } } /** * 初始化配置 * @param context * @return */ private static ImagePipelineConfig configureCaches(Context context) { // 内存配置 final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams( FrescoUtils.MAX_MEMORY_CACHE_SIZE, // 内存缓存中总图片的最大大小,以字节为单位。 Integer.MAX_VALUE, // 内存缓存中图片的最大数量。 FrescoUtils.MAX_MEMORY_CACHE_SIZE, // 内存缓存中准备清除但尚未被删除的总图片的最大大小,以字节为单位。 Integer.MAX_VALUE, // 内存缓存中准备清除的总图片的最大数量。 Integer.MAX_VALUE); // 内存缓存中单个图片的最大大小。 // 修改 <SUF> Supplier<MemoryCacheParams> mSupplierMemoryCacheParams = new Supplier<MemoryCacheParams>() { @Override public MemoryCacheParams get() { return bitmapCacheParams; } }; // 小图片的磁盘配置 DiskCacheConfig diskSmallCacheConfig = DiskCacheConfig .newBuilder(context) .setBaseDirectoryPath(context.getApplicationContext().getCacheDir())// 缓存图片基路径 .setBaseDirectoryName(IMAGE_PIPELINE_SMALL_CACHE_DIR)// 文件夹名 // .setCacheErrorLogger(cacheErrorLogger)//日志记录器用于日志错误的缓存。 // .setCacheEventListener(cacheEventListener)//缓存事件侦听器。 // .setDiskTrimmableRegistry(diskTrimmableRegistry)//类将包含一个注册表的缓存减少磁盘空间的环境。 .setMaxCacheSize(FrescoUtils.MAX_DISK_CACHE_SIZE)// 默认缓存的最大大小。 .setMaxCacheSizeOnLowDiskSpace(MAX_SMALL_DISK_LOW_CACHE_SIZE)// 缓存的最大大小,使用设备时低磁盘空间。 .setMaxCacheSizeOnVeryLowDiskSpace(MAX_SMALL_DISK_VERYLOW_CACHE_SIZE)// 缓存的最大大小,当设备极低磁盘空间 // .setVersion(version) .build(); // 默认图片的磁盘配置 DiskCacheConfig diskCacheConfig = DiskCacheConfig .newBuilder(context) .setBaseDirectoryPath(Environment.getExternalStorageDirectory().getAbsoluteFile())// 缓存图片基路径 .setBaseDirectoryName(IMAGE_PIPELINE_CACHE_DIR)// 文件夹名 // .setCacheErrorLogger(cacheErrorLogger)//日志记录器用于日志错误的缓存。 // .setCacheEventListener(cacheEventListener)//缓存事件侦听器。 // .setDiskTrimmableRegistry(diskTrimmableRegistry)//类将包含一个注册表的缓存减少磁盘空间的环境。 .setMaxCacheSize(FrescoUtils.MAX_DISK_CACHE_SIZE)// 默认缓存的最大大小。 .setMaxCacheSizeOnLowDiskSpace(MAX_DISK_CACHE_LOW_SIZE)// 缓存的最大大小,使用设备时低磁盘空间。 .setMaxCacheSizeOnVeryLowDiskSpace(MAX_DISK_CACHE_VERYLOW_SIZE)// 缓存的最大大小,当设备极低磁盘空间 // .setVersion(version) .build(); // 缓存图片配置 ImagePipelineConfig.Builder configBuilder = ImagePipelineConfig .newBuilder(context) // .setAnimatedImageFactory(AnimatedImageFactory // animatedImageFactory)//图片加载动画 .setBitmapMemoryCacheParamsSupplier(mSupplierMemoryCacheParams)// 内存缓存配置(一级缓存,已解码的图片) // .setCacheKeyFactory(cacheKeyFactory)//缓存Key工厂 // .setEncodedMemoryCacheParamsSupplier(encodedCacheParamsSupplier)//内存缓存和未解码的内存缓存的配置(二级缓存) // .setExecutorSupplier(executorSupplier)//线程池配置 // .setImageCacheStatsTracker(imageCacheStatsTracker)//统计缓存的命中率 // .setImageDecoder(ImageDecoder imageDecoder) //图片解码器配置 // .setIsPrefetchEnabledSupplier(Supplier<Boolean> // isPrefetchEnabledSupplier)//图片预览(缩略图,预加载图等)预加载到文件缓存 .setMainDiskCacheConfig(diskCacheConfig)// 磁盘缓存配置(总,三级缓存) // .setMemoryTrimmableRegistry(memoryTrimmableRegistry) // //内存用量的缩减,有时我们可能会想缩小内存用量。比如应用中有其他数据需要占用内存,不得不把图片缓存清除或者减小 // 或者我们想检查看看手机是否已经内存不够了。 // .setNetworkFetchProducer(networkFetchProducer)//自定的网络层配置:如OkHttp,Volley // .setPoolFactory(poolFactory)//线程池工厂配置 // .setProgressiveJpegConfig(progressiveJpegConfig)//渐进式JPEG图 // .setRequestListeners(requestListeners)//图片请求监听 // .setResizeAndRotateEnabledForNetwork(boolean // resizeAndRotateEnabledForNetwork)//调整和旋转是否支持网络图片 .setSmallImageDiskCacheConfig(diskSmallCacheConfig)// 磁盘缓存配置(小图片,可选~三级缓存的小图优化缓存) ; return configBuilder.build(); } /** * 在 Application 初始化时,在应用调用 setContentView() 之前,进行初始化: * Fresco.initialize(context); * * 在xml布局文件中, 加入命名空间: * * !-- 其他元素 --> LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:fresco="http://schemas.android.com/apk/res-auto"> * 加入SimpleDraweeView: <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="20dp" android:layout_height="20dp" fresco:placeholderImage="@drawable/my_drawable" /> * SimpleDraweeView draweeView = (SimpleDraweeView) findViewById(R.id.my_image_view); * * <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/my_image_view" android:layout_width="20dp" // 不支持wrap_content 如果要设置宽高比, 需要在Java代码中指定setAspectRatio(1.33f); android:layout_height="20dp" // 不支持wrap_content fresco:fadeDuration="300" fresco:actualImageScaleType="focusCrop"// 设置图片缩放. 通常使用focusCrop,该属性值会通过算法把人头像放在中间 fresco:placeholderImage="@color/wait_color"// 下载成功之前显示的图片 fresco:placeholderImageScaleType="fitCenter" fresco:failureImage="@drawable/error"// 加载失败的时候显示的图片 fresco:failureImageScaleType="centerInside" fresco:retryImage="@drawable/retrying"// 加载失败,提示用户点击重新加载的图片(会覆盖failureImage的图片) fresco:retryImageScaleType="centerCrop" fresco:progressBarImage="@drawable/progress_bar"// 提示用户正在加载,和加载进度无关 fresco:progressBarImageScaleType="centerInside" fresco:progressBarAutoRotateInterval="1000" fresco:backgroundImage="@color/blue" fresco:overlayImage="@drawable/watermark" fresco:pressedStateOverlayImage="@color/red" fresco:roundAsCircle="false"// 是不是设置圆圈 fresco:roundedCornerRadius="1dp"// 圆角角度,180的时候会变成圆形图片 fresco:roundTopLeft="true" fresco:roundTopRight="false" fresco:roundBottomLeft="false" fresco:roundBottomRight="true" fresco:roundWithOverlayColor="@color/corner_color" fresco:roundingBorderWidth="2dp" fresco:roundingBorderColor="@color/border_color" /> * * * 特别注意:Fresco 不支持 相对路径的URI. 所有的URI都必须是绝对路径,并且带上该URI的scheme。 如下: 类型 Scheme 示例 远程图片 http://, https:// HttpURLConnection 或者参考 使用其他网络加载方案 本地文件 file:// FileInputStream Content provider content:// ContentResolver asset目录下的资源 asset:// AssetManager res目录下的资源 res:// Resources.openRawResource res 示例: Uri uri = Uri.parse("res://包名(实际可以是任何字符串甚至留空)/" + R.drawable.ic_launcher); * */ /** * 开始加载图片 * @param draweeView * @param uriString */ public static void setImageURI(SimpleDraweeView draweeView , String uriString) { Uri uri = Uri.parse(uriString); draweeView.setImageURI(uri); } /** * 自定义图片尺寸 * @param draweeView 显示的控件 * @param uriString 地址 * @param width 50 * @param height 50 */ public static void changeImgSize(SimpleDraweeView draweeView , String uriString , int width , int height) { ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uriString)) .setResizeOptions(new ResizeOptions(width, height)) .build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setAutoPlayAnimations(true)// other setters .build(); draweeView.setController(controller); } /** * 加载gif图 * @param draweeView * @param uriString */ public static void loadGif(SimpleDraweeView draweeView , String uriString) { ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(uriString)).build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setAutoPlayAnimations(true) .build(); draweeView.setController(controller); } /** * 多图请求需 自定义ImageRequest(图片预览) * @param draweeView * @param lowResUri * @param highResUri */ public static void moreImgRequst(SimpleDraweeView draweeView , String lowResUri , String highResUri ) { DraweeController controller = Fresco.newDraweeControllerBuilder() .setLowResImageRequest(ImageRequest.fromUri(Uri.parse(lowResUri)))//低分辨率的缩略图 .setImageRequest(ImageRequest.fromUri(Uri.parse(highResUri)))//高分辨率的图 .setOldController(draweeView.getController()) .build(); draweeView.setController(controller); } /** * 缩略图预览(仅支持本地图片,并且是JPEG图片格式) * @param draweeView * @param uri */ public static void localImg(SimpleDraweeView draweeView , Uri uri ) { ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri) .setLocalThumbnailPreviewsEnabled(true) .build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setOldController(draweeView.getController()) .build(); draweeView.setController(controller); } /** * 请求图片 * @param uri - 唯一的必选的成员. 参考 支持的URIs * @param width * @param height * autoRotateEnabled - 是否支持自动旋转. * progressiveEnabled - 是否支持渐进式加载. * postprocessor - 后处理器(postprocess). * resizeOptions - 图片缩放选项,用前请先阅读缩放和旋转 */ public static void loadImage(SimpleDraweeView draweeView , String uri , int width , int height) { ImageRequest request = ImageRequestBuilder .newBuilderWithSource(Uri.parse(uri)) .setAutoRotateEnabled(true)// 是否支持自动旋转. .setImageDecodeOptions(getImageDecodeOptions())// 图片解码库 //.setImageType(ImageType.SMALL)//图片类型,设置后可调整图片放入小图磁盘空间还是默认图片磁盘空间 //.setLocalThumbnailPreviewsEnabled(true)//缩略图预览,影响图片显示速度(轻微) .setLowestPermittedRequestLevel(RequestLevel.FULL_FETCH)//请求经过缓存级别 BITMAP_MEMORY_CACHE,ENCODED_MEMORY_CACHE,DISK_CACHE,FULL_FETCH .setProgressiveRenderingEnabled(false)//渐进加载,主要用于渐进式的JPEG图,影响图片显示速度(普通) .setResizeOptions(new ResizeOptions(width, height)) .build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setOldController(draweeView.getController()) .build(); draweeView.setController(controller); } /** * 图片解码 * @return */ public static ImageDecodeOptions getImageDecodeOptions() { ImageDecodeOptions decodeOptions = ImageDecodeOptions.newBuilder() // .setBackgroundColor(Color.TRANSPARENT)//图片的背景颜色 // .setDecodeAllFrames(decodeAllFrames)//解码所有帧 // .setDecodePreviewFrame(decodePreviewFrame)//解码预览框 // .setForceOldAnimationCode(forceOldAnimationCode)//使用以前动画 // .setFrom(options)//使用已经存在的图像解码 // .setMinDecodeIntervalMs(intervalMs)//最小解码间隔(分位单位) .setUseLastFrameForPreview(true)// 使用最后一帧进行预览 .build(); return decodeOptions; } }
0
18572_19
//import java.util.logging.Handler; // ///** // * 完SyncTask的start方法,要求 // * 1,SyncTask的派生类的run方法抛到Handler所属的线程执行。 // * 2,SyncTask派生类的执行线程等待返回,除非等待的超时timeout // * 3,如果timeout或出错,则返回默认值defultRet // */ //public class wm { // public abstract class SyncTask<R> { // protected abstract R run(); // private R result; // private byte[] lock = new byte[0]; // private boolean notified = false; // private Runnable task = new Runnable() { // @Override // public void run() { // R ret = SyncTask.this.run(); // synchronized (lock) { // result = ret; // lock.notify(); // notified = true; // } // } // }; // // /*** // * 将任务抛到其他线程,同步等待其返回结果 // * @param timeout 超过指定时间则直接返回ms // * @param defaultRet 默认返回值,即超时后或出错的返回值 // * @param handler 执行线程handler // * @return // */ // public R start(final long timeout, final R defaultRet, Handler handler) { // // } // } // //}
AceXIE/lintcode
src/main/java/wm.java
341
// * 将任务抛到其他线程,同步等待其返回结果
line_comment
zh-cn
//import java.util.logging.Handler; // ///** // * 完SyncTask的start方法,要求 // * 1,SyncTask的派生类的run方法抛到Handler所属的线程执行。 // * 2,SyncTask派生类的执行线程等待返回,除非等待的超时timeout // * 3,如果timeout或出错,则返回默认值defultRet // */ //public class wm { // public abstract class SyncTask<R> { // protected abstract R run(); // private R result; // private byte[] lock = new byte[0]; // private boolean notified = false; // private Runnable task = new Runnable() { // @Override // public void run() { // R ret = SyncTask.this.run(); // synchronized (lock) { // result = ret; // lock.notify(); // notified = true; // } // } // }; // // /*** // * 将任 <SUF> // * @param timeout 超过指定时间则直接返回ms // * @param defaultRet 默认返回值,即超时后或出错的返回值 // * @param handler 执行线程handler // * @return // */ // public R start(final long timeout, final R defaultRet, Handler handler) { // // } // } // //}
0
66221_2
public class Object01{ public static void main (String[]args) { String name1="黄冰棒"; String name2="黄文强"; int age1=28; int age2=23; String stydy1="不爱学习"; String study2="大师"; //单独变量解决 不利于数据管理,数组解决问题 String[]name3={"黄冰棒","28岁","不爱学习"}; man man1=new man(); man1.name="黄冰棒"; man1.age=28; man1.study="不爱学习"; man man2=new man(); man2.name="黄文强"; man2.age=20; man2.study="爱睡觉"; System.out.println("第一个人的信息"+man1.name+" "+man1.age+" "+man1.study); System.out.println("第二个人的信息"+man2.name+" "+man2.age+" "+man2.study); } }//实例化一个人 //定义1个类型 class man { String name; int age; String study; }
Achilles0622/Achilles
java/Object01.java
280
//定义1个类型
line_comment
zh-cn
public class Object01{ public static void main (String[]args) { String name1="黄冰棒"; String name2="黄文强"; int age1=28; int age2=23; String stydy1="不爱学习"; String study2="大师"; //单独变量解决 不利于数据管理,数组解决问题 String[]name3={"黄冰棒","28岁","不爱学习"}; man man1=new man(); man1.name="黄冰棒"; man1.age=28; man1.study="不爱学习"; man man2=new man(); man2.name="黄文强"; man2.age=20; man2.study="爱睡觉"; System.out.println("第一个人的信息"+man1.name+" "+man1.age+" "+man1.study); System.out.println("第二个人的信息"+man2.name+" "+man2.age+" "+man2.study); } }//实例化一个人 //定义 <SUF> class man { String name; int age; String study; }
0
27042_5
package utils; import java.sql.*; import domain.DomainProducer; import ui.Sylas; import burp.BurpExtender; import com.google.common.base.Joiner; import java.util.Arrays; import java.util.HashMap; import com.google.common.net.InternetDomainName; import java.util.HashSet; import java.util.Locale; import java.util.concurrent.BlockingQueue; import static java.lang.Thread.sleep; /** * @author linchen */ public class DbUtil { public DbUtil(int mode){ this.mode = mode; } /** * 数据库连接模式,0为Mysql,1为SQLITE */ public int mode; /** * 使用Mysql */ public static final int MYSQL_DB = 0; /** * 使用Sqlite */ public static final int SQLITE_DB = 1; /** * 数据库连接状态 */ public boolean isConnect = false; /** * 数据库连接 */ public Connection conn = null; /** * 当前连接的库名 */ public String database; /** * bscan是否已经创建相关表 */ public boolean bscanReady = false; /** * 切换数据库 */ public void switchConn(int mode){ this.mode = mode; closeConn(); setConn(); } /** * 连接数据库 * */ public void setConn(String host, String port, String username, String password, String database) { String jdbcUrl = String.format("jdbc:mysql://%s:%s/%s?useServerPrepStmts=true", host, port, database); this.database = database; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(jdbcUrl, username, password); isConnect = true; } catch (SQLException | ClassNotFoundException e) { BurpExtender.getStderr().println("Mysql连接失败:"+e); e.printStackTrace(); } } public void setConn(){ try { Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("JDBC:sqlite:Sylas.db"); isConnect = true; } catch (Exception e) { BurpExtender.getStderr().println("Sqlite连接失败:"+e); e.printStackTrace(); } } public void closeConn(){ if(isConnect){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } isConnect = false; } } /** * 初始化mysql数据库 * @param db */ private void initMysql(String db){ HashMap<String, String> mysqlTables = getMysqlTableMap(); String[] subDomainTables = new String[]{"SubDomain","SimilarSubDomain"}; try{ ResultSet set = conn.getMetaData().getTables(db,null,"%",null); while (set.next()){ String table = set.getString("TABLE_NAME"); if("Web".equals(table)){ this.bscanReady = true; BurpExtender.getStdout().println("Bscan ready"); } mysqlTables.remove(table.toUpperCase()); } for (String sql:mysqlTables.values()){ conn.createStatement().executeLargeUpdate(sql); } }catch (SQLException e) { BurpExtender.getStderr().println("Mysql初始化失败:"+e); } for (String i:subDomainTables) { scannedFiledIsAlert(i); } } /** * 此处是用来判断是否为旧版本插件,新版本需要在subdomain以及similarDomain中加入scan字段以支持 * @param table */ public void scannedFiledIsAlert(String table){ try { PreparedStatement scanColumnNameCreateSql = conn.prepareStatement("select count(*) as iscreated from information_schema.COLUMNS where TABLE_NAME = ? and TABLE_SCHEMA = ? and COLUMN_NAME = 'scanned'"); scanColumnNameCreateSql.setString(1,table); scanColumnNameCreateSql.setString(2,database); ResultSet set = scanColumnNameCreateSql.executeQuery(); int isCreated = 0; while (set.next()){ isCreated = set.getInt("iscreated"); } if (isCreated == 0){ PreparedStatement createScanSql = conn.prepareStatement("alter table ? add scanned int default 0 not null;"); createScanSql.setString(1,table); createScanSql.execute(); } } catch (SQLException e) { BurpExtender.getStderr().println("扫描scanned字段失败:"+e); } } /** * 初始化Sqlite数据库 * @param db */ private void initSqlite(String db){ HashMap<String, String> sqliteTables = getSqliteTableMap(); // 原先想要给sqlite增加检测url存活的功能,但是想了想实现有点麻烦。 try{ ResultSet set = conn.getMetaData().getTables(db,null,"%",null); while (set.next()){ String table = set.getString("TABLE_NAME"); sqliteTables.remove(table); } for (String sql:sqliteTables.values()){ conn.createStatement().execute(sql); } }catch (SQLException e) { BurpExtender.getStderr().println("Sqlite初始化失败"+e); } } public void init(String db){ switch (mode){ case MYSQL_DB: initMysql(db); break; case SQLITE_DB: initSqlite(db); break; default: break; } } public Boolean projectExist(String project){ String sql = "select count(id) as project from Project where projectName = ?"; try{ PreparedStatement psSQL = conn.prepareStatement(sql); psSQL.setString(1,project); ResultSet set = psSQL.executeQuery(); int projectCount = 0; while (set.next()){ projectCount = set.getInt("project"); } return projectCount != 0; }catch (SQLException e){ BurpExtender.getStderr().println("查找不到project:"+e); } return false; } /** * 对RootDomain表插入数据 */ public void insertData(String rootDomainName,String projectName){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into Project (rootDomainName,projectName) values (?,?)"; break; case SQLITE_DB: sql = "insert or ignore into Project ([rootDomainName],[projectName]) values (?,?)"; break; default: break; } try { PreparedStatement psSQL = conn.prepareStatement(sql); psSQL.setString(1,rootDomainName); psSQL.setString(2,projectName); psSQL.execute(); } catch (SQLException e) { e.printStackTrace(); } } /** * 往数据库增加子域名 * @param queue */ public void insertSubDomainQueueToDb(BlockingQueue<String> queue) { String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into SubDomain (subDomainName,rootDomainName,ipAddress,createTime) values (?,?,?,?)"; break; case SQLITE_DB: sql = "insert or ignore into SubDomain ([subDomainName],[rootDomainName],[ipAddress],[createTime]) values (?,?,?,?)"; break; default: break; } try { PreparedStatement psSQL = conn.prepareStatement(sql); while (!queue.isEmpty()){ String subDomain = queue.take(); HashMap<String, String> data = BurpExtender.subDomainMap.get(subDomain); // if(data==null||"1".equals(data.get("status"))){ if(data==null){ continue; } String ip = data.get("ipAddress"); // 用后台的线程去获取IP,防止DNS延迟造成burp流量堵塞 ip = Config.getDomainIp(subDomain); if("Unknown".equals(ip)){ continue; } BurpExtender.subDomainMap.get(subDomain).put("ipAddress", ip); BurpExtender.subDomainCount += 1; Sylas.addSubDomainToUI(subDomain, ip, data.get("time")); psSQL.setString(1, subDomain); psSQL.setString(2, getRootDomain(subDomain)); psSQL.setString(3, ip); psSQL.setString(4, data.get("time")); psSQL.addBatch(); } psSQL.executeBatch(); } catch (Exception e) { BurpExtender.getStderr().println("子域名入库失败:"+e); } } /** * 插入相似域名的信息 * @param queue */ public void insertSimilarSubDomainQueueToDb(BlockingQueue<String> queue) { String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into SimilarSubDomain (subDomainName,rootDomainName,ipAddress,createTime) values (?,?,?,?)"; break; case SQLITE_DB: sql = "insert or ignore into SimilarSubDomain ([subDomainName],[rootDomainName],[ipAddress],[createTime]) values (?,?,?,?)"; break; default: break; } try { PreparedStatement psSQL = conn.prepareStatement(sql); while (!queue.isEmpty()){ String subDomain = queue.take(); HashMap<String, String> data = BurpExtender.similarSubDomainMap.get(subDomain); if(data==null){ continue; } String ip = Config.getDomainIp(subDomain); if("Unknown".equals(ip)){ continue; } BurpExtender.similarSubDomainMap.get(subDomain).put("ipAddress", ip); BurpExtender.similarSubDomainCount += 1; Sylas.addSimilarSubDomainToUI(subDomain, ip, data.get("time")); psSQL.setString(1, subDomain); psSQL.setString(2, getSimilarRootDomain(subDomain)); psSQL.setString(3, ip); psSQL.setString(4, data.get("time")); psSQL.addBatch(); } psSQL.executeBatch(); } catch (Exception e) { BurpExtender.getStderr().println("无法插入相似域名:"+e); } } public void insertUrlQueueToDb(BlockingQueue<String> queue){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into Url (url, createTime, projectName) values (?,?,?)"; break; case SQLITE_DB: sql = "insert or ignore into Url ([url], [createTime], [projectName]) values (?,?,?)"; break; default: break; } String currentProject = BurpExtender.config.get("currentProject"); try{ PreparedStatement pSQL = conn.prepareStatement(sql); while(!queue.isEmpty()){ String url = queue.take(); String createTime = BurpExtender.urlMap.get(url); if(createTime==null){ continue; } BurpExtender.urlCount += 1; Sylas.addURLToUI(url, createTime); pSQL.setString(1, url); pSQL.setString(2, createTime); pSQL.setString(3, currentProject); pSQL.addBatch(); } pSQL.executeBatch(); }catch (Exception e){ BurpExtender.getStderr().println("无法添加url:"+e); } } public void insertSimilarUrlQueueToDb(BlockingQueue<String> queue){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into SimilarUrl (url, createTime, projectName) values (?,?,?)"; break; case SQLITE_DB: sql = "insert or ignore into SimilarUrl ([url], [createTime], [projectName]) values (?,?,?)"; break; default: break; } String currentProject = BurpExtender.config.get("currentProject"); try{ PreparedStatement pSQL = conn.prepareStatement(sql); while(!queue.isEmpty()){ String url = queue.take(); String createTime = BurpExtender.similarUrlMap.get(url); if(createTime==null){ continue; } BurpExtender.similarUrlCount += 1; Sylas.addSimilarUrlToUI(url, createTime); pSQL.setString(1, url); pSQL.setString(2, createTime); pSQL.setString(3, currentProject); pSQL.addBatch(); } pSQL.executeBatch(); }catch (Exception e){ BurpExtender.getStderr().println("无法添加相似url:"+e); } } /** * 获取根域名 * @param subDomain * @return * (用了新的正则后,这个问题解决了)这里有BUG,目前的正则会匹配到-elis-ecocdn.pingan.com.cn这样错误的域名,然后调用Google这个API就会抛异常 */ private String getRootDomain(String subDomain){ String suffix = InternetDomainName.from(subDomain).publicSuffix().toString(); String[] tmpDomain = subDomain.substring(0, subDomain.lastIndexOf(suffix)-1).split("\\."); return tmpDomain[tmpDomain.length-1]+"."+suffix; } /** * */ private String getSimilarRootDomain(String subDomain){ for (String s:BurpExtender.currentRootDomainSet){ if(DomainProducer.isSimilarSubDomain(subDomain)){ return s; } } return null; } /** * 创建项目 * @param projectName */ public void addProject(String projectName){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into Project (projectName) values (?)"; break; case SQLITE_DB: sql = "insert or ignore into Project ([projectName]) values (?)"; break; default: break; } try{ PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); preSQl.execute(); }catch (SQLException e){ BurpExtender.getStderr().println("无法创建项目:"+e); } } /** * 删除项目 * @param projectName */ public void removeProject(String projectName){ String sql = "DELETE FROM Project WHERE projectName = ?;"; try{ PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); preSQl.execute(); }catch (SQLException e){ BurpExtender.getStderr().println("删除项目失败:"+e); } } /** * 添加根域名 * @param projectName * @param domainName */ public void addRootDomain(String projectName, String domainName){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into RootDomain (projectName,rootDomainName) values (?,?)"; break; case SQLITE_DB: sql = "insert or ignore into RootDomain ([projectName],[rootDomainName]) values (?,?)"; break; default: break; } try{ PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); preSQl.setString(2, domainName); preSQl.execute(); }catch (SQLException e){ BurpExtender.getStderr().println("无法添加根域名:"+e); } } /** * 删除根域名 * @param projectName * @param domainName */ public void removeRootDomain(String projectName,String domainName){ String sql = "delete from RootDomain where projectName = ? and rootDomainName = ?"; try{ PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); preSQl.setString(2, domainName); preSQl.execute(); }catch (SQLException e){ e.printStackTrace(); } } /** * 获取项目的Set * @return */ public HashSet<String> getProjectSet(){ String sql = "select ProjectName from Project"; HashSet<String> projectList = new HashSet<>(); try { PreparedStatement preSQl = conn.prepareStatement(sql); ResultSet set = preSQl.executeQuery(); while(set.next()){ projectList.add(set.getString("ProjectName")); } } catch (SQLException e) { e.printStackTrace(); } return projectList; } public HashSet<String> getRootDomainSet(String projectName){ String sql = "select rootDomainName from RootDomain where ProjectName=?"; HashSet<String> rootDomainList = new HashSet<>(); ResultSet set; try { PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); set = preSQl.executeQuery(); while(set.next()){ rootDomainList.add(set.getString("rootDomainName")); } } catch (SQLException e) { BurpExtender.getStderr().println("无法获取到根域名:"+e); } return rootDomainList; } public HashMap<String, HashMap<String, String>> getSubDomainMap(String projectName){ HashMap<String, HashMap<String, String>> subDomainMap = new HashMap<>(); Object[] rootDomainList = getRootDomainSet(projectName).toArray(); String[] inSql = new String[rootDomainList.length]; Arrays.fill(inSql, "?"); // 还是改回来了,不知道为啥,下面的那个方法取不到数据 String sql = "select subDomainName,rootDomainName,ipAddress,createTime from SubDomain where rootDomainName in ("+Joiner.on(",").join(inSql)+")"; try { PreparedStatement preSQl = conn.prepareStatement(sql); for (int i=0;i<rootDomainList.length;i++){ preSQl.setString(i+1, (String) rootDomainList[i]); } ResultSet set = preSQl.executeQuery(); while(set.next()){ HashMap<String, String> data = new HashMap<>(); data.put("ipAddress", set.getString("ipAddress")); data.put("createTime", set.getString("createTime")); data.put("status", "1"); subDomainMap.put(set.getString("subDomainName"), data); } } catch (SQLException e) { BurpExtender.getStderr().println("获取不到子域名"+e); } return subDomainMap; } public HashMap<String, HashMap<String, String>> getSimilarSubDomainMap(String projectName){ HashMap<String, HashMap<String, String>> subDomainMap = new HashMap<>(); Object[] rootDomainList = getRootDomainSet(projectName).toArray(); String[] inSql = new String[rootDomainList.length]; Arrays.fill(inSql, "?"); // 还是改回来了,不知道为啥,下面的那个方法取不到数据 String sql = "select subDomainName,rootDomainName,ipAddress,createTime from SimilarSubDomain where rootDomainName in ("+Joiner.on(",").join(inSql)+")"; try { PreparedStatement preSQl = conn.prepareStatement(sql); for (int i=0;i<rootDomainList.length;i++){ preSQl.setString(i+1, (String) rootDomainList[i]); } ResultSet set = preSQl.executeQuery(); while(set.next()){ HashMap<String, String> data = new HashMap<>(); data.put("ipAddress", set.getString("ipAddress")); data.put("createTime", set.getString("createTime")); data.put("status", "1"); subDomainMap.put(set.getString("subDomainName"), data); } } catch (SQLException e) { BurpExtender.getStderr().println("无法获取相似域名:"+e); } return subDomainMap; } public HashMap<String,HashMap<String,String>> getSubDomainAlive(String projectName){ HashMap<String, HashMap<String, String>> subDomainAliveMap = new HashMap<>(); Object[] rootDomainList = getRootDomainSet(projectName).toArray(); String[] inSql = new String[rootDomainList.length]; Arrays.fill(inSql, "?"); String sql = "select url,title,status,rootDomainName from SubDomainBscanAlive where rootDomainName in ("+Joiner.on(",").join(inSql)+")"; try{ PreparedStatement preSQL = conn.prepareStatement(sql); for (int i=0;i<rootDomainList.length;i++){ preSQL.setString(i+1, (String) rootDomainList[i]); } ResultSet set = preSQL.executeQuery(); while (set.next()){ HashMap<String,String> data = new HashMap<>(); data.put("rootDomain",set.getString("rootDomainName")); data.put("status",set.getString("status")); data.put("title",set.getString("title")); subDomainAliveMap.put(set.getString("url"),data); } }catch (SQLException e){ BurpExtender.getStderr().println("无法获取Bscan对域名的测活情况:"+e); } return subDomainAliveMap; } public HashMap<String,HashMap<String,String>> getSimilarSubDomainAlive(String projectName){ HashMap<String, HashMap<String, String>> similarDomainAliveMap = new HashMap<>(); Object[] rootDomainList = getRootDomainSet(projectName).toArray(); String[] inSql = new String[rootDomainList.length]; Arrays.fill(inSql, "?"); String sql = "select url,title,status,rootDomainName from SimilarDomainBscanAlive where rootDomainName in ("+Joiner.on(",").join(inSql)+")"; try{ PreparedStatement preSQL = conn.prepareStatement(sql); for (int i=0;i<rootDomainList.length;i++){ preSQL.setString(i+1, (String) rootDomainList[i]); } ResultSet set = preSQL.executeQuery(); while (set.next()){ HashMap<String,String> data = new HashMap<>(); data.put("rootDomain",set.getString("rootDomainName")); data.put("status",set.getString("status")); data.put("title",set.getString("title")); similarDomainAliveMap.put(set.getString("url"),data); } }catch (SQLException e){ BurpExtender.getStderr().println("无法获取Bscan对相似域名的测活情况:"+e); } return similarDomainAliveMap; } public HashMap<String, String> getUrlMap(String projectName){ HashMap<String, String> urlMap = new HashMap<>(); String sql = "select url, createTime from Url where projectName=?"; ResultSet set; try{ PreparedStatement preSQL = conn.prepareStatement(sql); preSQL.setString(1, projectName); set = preSQL.executeQuery(); while(set.next()){ urlMap.put(set.getString("url"), set.getString("createTime")); } }catch (SQLException e){ BurpExtender.getStderr().println("无法获取url:"+e); } return urlMap; } public HashMap<String, String> getSimilarUrlMap(String projectName){ HashMap<String, String> urlMap = new HashMap<>(); String sql = "select url, createTime from SimilarUrl where projectName=?"; ResultSet set; try{ PreparedStatement preSQL = conn.prepareStatement(sql); preSQL.setString(1, projectName); set = preSQL.executeQuery(); while(set.next()){ urlMap.put(set.getString("url"), set.getString("createTime")); } }catch (SQLException e){ BurpExtender.getStderr().println("无法获取相似url:"+e); } return urlMap; } public HashMap<String, HashMap<String, String>> getWebMap(HashSet<String> subDomains){ HashMap<String, HashMap<String, String>> webMap = new HashMap<>(); StringBuilder where = new StringBuilder(); for (String subDomain : subDomains) { where.append(" or url like '%").append(subDomain).append("%'"); } String sql = "select * from Web where 1=2 " + where; ResultSet set; try{ PreparedStatement preSQL = conn.prepareStatement(sql); set = preSQL.executeQuery(); while(set.next()){ String url = set.getString("url"); String status = set.getString("status"); String title = set.getString("title"); String length = set.getString("length"); String application = set.getString("application"); String webserver = set.getString("webserver"); String framework = set.getString("framework"); String os = set.getString("os"); String description = set.getString("description"); String createTime = set.getString("createTime"); HashMap<String, String> web = new HashMap<>(); web.put("status", status); web.put("title", title); web.put("length", length); web.put("application", application); web.put("webserver", webserver); web.put("framework", framework); web.put("os", os); web.put("description", description); web.put("createTime", createTime); webMap.put(url, web); } }catch (SQLException e){ BurpExtender.getStderr().println(e); } return webMap; } public static HashMap<String, String> getMysqlTableMap(){ //项目表 HashMap<String, String> tables = new HashMap<>(); tables.put("Project","CREATE TABLE IF NOT EXISTS `Project` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `projectName` varchar(64) NOT NULL,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `Project_projectName_uindex` (`projectName`)\n" + ") CHARSET=utf8;"); //根域名表 tables.put("RootDomain","CREATE TABLE IF NOT EXISTS `RootDomain` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `rootDomainName` varchar(64) NOT NULL,\n" + " `projectName` varchar(64) NOT NULL,\n" + " `scanned` int default 0 null,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `RootDomain_domainName_uindex` (`rootDomainName`)\n" + ") CHARSET=utf8;"); //子域名表 tables.put("SubDomain","CREATE TABLE IF NOT EXISTS `SubDomain` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `subDomainName` varchar(128) NOT NULL,\n" + " `rootDomainName` varchar(64) DEFAULT NULL,\n" + " `ipAddress` varchar(64) DEFAULT NULL,\n" + " `createTime` datetime NOT NULL,\n" + " `scanned` int default 0 null,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `SubDomain_subDomainName_uindex` (`subDomainName`)\n" + ") CHARSET=utf8;"); //url表 tables.put("Url","CREATE TABLE IF NOT EXISTS `Url` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `url` varchar(256) NOT NULL,\n" + " `projectName` varchar(64) NOT NULL,\n" + " `createTime` datetime NOT NULL,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `Url_url_uindex` (`url`)\n" + ") CHARSET=utf8;"); //相似域名表 tables.put("SimilarSubDomain","CREATE TABLE IF NOT EXISTS `SimilarSubDomain`(\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `subDomainName` varchar(128) NOT NULL,\n" + " `rootDomainName` varchar(64) DEFAULT NULL,\n" + " `ipAddress` varchar(64) DEFAULT NULL,\n" + " `createTime` datetime NOT NULL,\n" + " `scanned` int default 0 null,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `SimilarSubDomain_similarDomainName_uindex` (`subDomainName`)\n" + ") CHARSET=utf8;"); //相似域名子域名表 tables.put("SimilarUrl","CREATE TABLE IF NOT EXISTS `SimilarUrl`(\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `url` varchar(64) NOT NULL,\n" + " `projectName` varchar(64) NOT NULL,\n" + " `createTime` datetime NOT NULL,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `SimilarUrl_url_uindex` (`url`)\n" + ") CHARSET=utf8;"); tables.put("Web", "CREATE TABLE IF NOT EXISTS Web (\n" + " id int(11) AUTO_INCREMENT PRIMARY KEY,\n" + " url varchar(256) UNIQUE,\n" + " status varchar(64),\n" + " title varchar(64),\n" + " length varchar(64),\n" + " application varchar(64),\n" + " webserver varchar(64),\n" + " framework varchar(64),\n" + " os varchar(64),\n" + " description varchar(64),\n" + " createTime datetime not null\n"+ ") CHARSET=utf8;"); return tables; } public static HashMap<String, String> getSqliteTableMap(){ HashMap<String, String> tables = new HashMap<String, String>(6){ { put("Project","CREATE TABLE \"main\".\"Project\" (\n" + " \"id\" integer NOT NULL,\n" + " \"projectName\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"Project_projectName_uindex\" UNIQUE (\"projectName\")"+ ");"); put("RootDomain","CREATE TABLE \"main\".\"RootDomain\" (\n" + " \"id\" integer NOT NULL,\n" + " \"rootDomainName\" TEXT,\n" + " \"projectName\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"RootDomain_projectName_uindex\" UNIQUE (\"rootDomainName\")"+ ");"); put("SubDomain","CREATE TABLE \"main\".\"SubDomain\" (\n" + " \"id\" integer NOT NULL,\n" + " \"subDomainName\" TEXT,\n" + " \"rootDomainName\" TEXT,\n" + " \"ipAddress\" TEXT,\n" + " \"createTime\" TEXT,\n" + " \"scan\" integers DEFAULT 0, \n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"SubDomain_projectName_uindex\" UNIQUE (\"subDomainName\")"+ ");"); put("Url","CREATE TABLE \"main\".\"Url\" (\n" + " \"id\" integer NOT NULL,\n" + " \"url\" TEXT,\n" + " \"projectName\" TEXT,\n" + " \"createTime\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"Url_projectName_uindex\" UNIQUE (\"url\")"+ ");"); put("SimilarSubDomain","CREATE TABLE \"main\".\"SimilarSubDomain\" (\n" + " \"id\" integer NOT NULL,\n" + " \"SubDomainName\" TEXT,\n" + " \"rootDomainName\" TEXT,\n" + " \"ipAddress\" TEXT,\n" + " \"createTime\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"SimilarSubDomain_projectName_uindex\" UNIQUE (\"SubDomainName\")"+ ");"); put("SimilarUrl","CREATE TABLE \"main\".\"SimilarUrl\" (\n" + " \"id\" integer NOT NULL,\n" + " \"url\" TEXT,\n" + " \"projectName\" TEXT,\n" + " \"createTime\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"SimilarUrl_projectName_uindex\" UNIQUE (\"url\")"+ ");"); } }; return tables; } public static void main(String[] args) { HashMap<String, String>
Acmesec/Sylas
src/utils/DbUtil.java
7,598
/** * 数据库连接 */
block_comment
zh-cn
package utils; import java.sql.*; import domain.DomainProducer; import ui.Sylas; import burp.BurpExtender; import com.google.common.base.Joiner; import java.util.Arrays; import java.util.HashMap; import com.google.common.net.InternetDomainName; import java.util.HashSet; import java.util.Locale; import java.util.concurrent.BlockingQueue; import static java.lang.Thread.sleep; /** * @author linchen */ public class DbUtil { public DbUtil(int mode){ this.mode = mode; } /** * 数据库连接模式,0为Mysql,1为SQLITE */ public int mode; /** * 使用Mysql */ public static final int MYSQL_DB = 0; /** * 使用Sqlite */ public static final int SQLITE_DB = 1; /** * 数据库连接状态 */ public boolean isConnect = false; /** * 数据库 <SUF>*/ public Connection conn = null; /** * 当前连接的库名 */ public String database; /** * bscan是否已经创建相关表 */ public boolean bscanReady = false; /** * 切换数据库 */ public void switchConn(int mode){ this.mode = mode; closeConn(); setConn(); } /** * 连接数据库 * */ public void setConn(String host, String port, String username, String password, String database) { String jdbcUrl = String.format("jdbc:mysql://%s:%s/%s?useServerPrepStmts=true", host, port, database); this.database = database; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(jdbcUrl, username, password); isConnect = true; } catch (SQLException | ClassNotFoundException e) { BurpExtender.getStderr().println("Mysql连接失败:"+e); e.printStackTrace(); } } public void setConn(){ try { Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("JDBC:sqlite:Sylas.db"); isConnect = true; } catch (Exception e) { BurpExtender.getStderr().println("Sqlite连接失败:"+e); e.printStackTrace(); } } public void closeConn(){ if(isConnect){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } isConnect = false; } } /** * 初始化mysql数据库 * @param db */ private void initMysql(String db){ HashMap<String, String> mysqlTables = getMysqlTableMap(); String[] subDomainTables = new String[]{"SubDomain","SimilarSubDomain"}; try{ ResultSet set = conn.getMetaData().getTables(db,null,"%",null); while (set.next()){ String table = set.getString("TABLE_NAME"); if("Web".equals(table)){ this.bscanReady = true; BurpExtender.getStdout().println("Bscan ready"); } mysqlTables.remove(table.toUpperCase()); } for (String sql:mysqlTables.values()){ conn.createStatement().executeLargeUpdate(sql); } }catch (SQLException e) { BurpExtender.getStderr().println("Mysql初始化失败:"+e); } for (String i:subDomainTables) { scannedFiledIsAlert(i); } } /** * 此处是用来判断是否为旧版本插件,新版本需要在subdomain以及similarDomain中加入scan字段以支持 * @param table */ public void scannedFiledIsAlert(String table){ try { PreparedStatement scanColumnNameCreateSql = conn.prepareStatement("select count(*) as iscreated from information_schema.COLUMNS where TABLE_NAME = ? and TABLE_SCHEMA = ? and COLUMN_NAME = 'scanned'"); scanColumnNameCreateSql.setString(1,table); scanColumnNameCreateSql.setString(2,database); ResultSet set = scanColumnNameCreateSql.executeQuery(); int isCreated = 0; while (set.next()){ isCreated = set.getInt("iscreated"); } if (isCreated == 0){ PreparedStatement createScanSql = conn.prepareStatement("alter table ? add scanned int default 0 not null;"); createScanSql.setString(1,table); createScanSql.execute(); } } catch (SQLException e) { BurpExtender.getStderr().println("扫描scanned字段失败:"+e); } } /** * 初始化Sqlite数据库 * @param db */ private void initSqlite(String db){ HashMap<String, String> sqliteTables = getSqliteTableMap(); // 原先想要给sqlite增加检测url存活的功能,但是想了想实现有点麻烦。 try{ ResultSet set = conn.getMetaData().getTables(db,null,"%",null); while (set.next()){ String table = set.getString("TABLE_NAME"); sqliteTables.remove(table); } for (String sql:sqliteTables.values()){ conn.createStatement().execute(sql); } }catch (SQLException e) { BurpExtender.getStderr().println("Sqlite初始化失败"+e); } } public void init(String db){ switch (mode){ case MYSQL_DB: initMysql(db); break; case SQLITE_DB: initSqlite(db); break; default: break; } } public Boolean projectExist(String project){ String sql = "select count(id) as project from Project where projectName = ?"; try{ PreparedStatement psSQL = conn.prepareStatement(sql); psSQL.setString(1,project); ResultSet set = psSQL.executeQuery(); int projectCount = 0; while (set.next()){ projectCount = set.getInt("project"); } return projectCount != 0; }catch (SQLException e){ BurpExtender.getStderr().println("查找不到project:"+e); } return false; } /** * 对RootDomain表插入数据 */ public void insertData(String rootDomainName,String projectName){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into Project (rootDomainName,projectName) values (?,?)"; break; case SQLITE_DB: sql = "insert or ignore into Project ([rootDomainName],[projectName]) values (?,?)"; break; default: break; } try { PreparedStatement psSQL = conn.prepareStatement(sql); psSQL.setString(1,rootDomainName); psSQL.setString(2,projectName); psSQL.execute(); } catch (SQLException e) { e.printStackTrace(); } } /** * 往数据库增加子域名 * @param queue */ public void insertSubDomainQueueToDb(BlockingQueue<String> queue) { String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into SubDomain (subDomainName,rootDomainName,ipAddress,createTime) values (?,?,?,?)"; break; case SQLITE_DB: sql = "insert or ignore into SubDomain ([subDomainName],[rootDomainName],[ipAddress],[createTime]) values (?,?,?,?)"; break; default: break; } try { PreparedStatement psSQL = conn.prepareStatement(sql); while (!queue.isEmpty()){ String subDomain = queue.take(); HashMap<String, String> data = BurpExtender.subDomainMap.get(subDomain); // if(data==null||"1".equals(data.get("status"))){ if(data==null){ continue; } String ip = data.get("ipAddress"); // 用后台的线程去获取IP,防止DNS延迟造成burp流量堵塞 ip = Config.getDomainIp(subDomain); if("Unknown".equals(ip)){ continue; } BurpExtender.subDomainMap.get(subDomain).put("ipAddress", ip); BurpExtender.subDomainCount += 1; Sylas.addSubDomainToUI(subDomain, ip, data.get("time")); psSQL.setString(1, subDomain); psSQL.setString(2, getRootDomain(subDomain)); psSQL.setString(3, ip); psSQL.setString(4, data.get("time")); psSQL.addBatch(); } psSQL.executeBatch(); } catch (Exception e) { BurpExtender.getStderr().println("子域名入库失败:"+e); } } /** * 插入相似域名的信息 * @param queue */ public void insertSimilarSubDomainQueueToDb(BlockingQueue<String> queue) { String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into SimilarSubDomain (subDomainName,rootDomainName,ipAddress,createTime) values (?,?,?,?)"; break; case SQLITE_DB: sql = "insert or ignore into SimilarSubDomain ([subDomainName],[rootDomainName],[ipAddress],[createTime]) values (?,?,?,?)"; break; default: break; } try { PreparedStatement psSQL = conn.prepareStatement(sql); while (!queue.isEmpty()){ String subDomain = queue.take(); HashMap<String, String> data = BurpExtender.similarSubDomainMap.get(subDomain); if(data==null){ continue; } String ip = Config.getDomainIp(subDomain); if("Unknown".equals(ip)){ continue; } BurpExtender.similarSubDomainMap.get(subDomain).put("ipAddress", ip); BurpExtender.similarSubDomainCount += 1; Sylas.addSimilarSubDomainToUI(subDomain, ip, data.get("time")); psSQL.setString(1, subDomain); psSQL.setString(2, getSimilarRootDomain(subDomain)); psSQL.setString(3, ip); psSQL.setString(4, data.get("time")); psSQL.addBatch(); } psSQL.executeBatch(); } catch (Exception e) { BurpExtender.getStderr().println("无法插入相似域名:"+e); } } public void insertUrlQueueToDb(BlockingQueue<String> queue){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into Url (url, createTime, projectName) values (?,?,?)"; break; case SQLITE_DB: sql = "insert or ignore into Url ([url], [createTime], [projectName]) values (?,?,?)"; break; default: break; } String currentProject = BurpExtender.config.get("currentProject"); try{ PreparedStatement pSQL = conn.prepareStatement(sql); while(!queue.isEmpty()){ String url = queue.take(); String createTime = BurpExtender.urlMap.get(url); if(createTime==null){ continue; } BurpExtender.urlCount += 1; Sylas.addURLToUI(url, createTime); pSQL.setString(1, url); pSQL.setString(2, createTime); pSQL.setString(3, currentProject); pSQL.addBatch(); } pSQL.executeBatch(); }catch (Exception e){ BurpExtender.getStderr().println("无法添加url:"+e); } } public void insertSimilarUrlQueueToDb(BlockingQueue<String> queue){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into SimilarUrl (url, createTime, projectName) values (?,?,?)"; break; case SQLITE_DB: sql = "insert or ignore into SimilarUrl ([url], [createTime], [projectName]) values (?,?,?)"; break; default: break; } String currentProject = BurpExtender.config.get("currentProject"); try{ PreparedStatement pSQL = conn.prepareStatement(sql); while(!queue.isEmpty()){ String url = queue.take(); String createTime = BurpExtender.similarUrlMap.get(url); if(createTime==null){ continue; } BurpExtender.similarUrlCount += 1; Sylas.addSimilarUrlToUI(url, createTime); pSQL.setString(1, url); pSQL.setString(2, createTime); pSQL.setString(3, currentProject); pSQL.addBatch(); } pSQL.executeBatch(); }catch (Exception e){ BurpExtender.getStderr().println("无法添加相似url:"+e); } } /** * 获取根域名 * @param subDomain * @return * (用了新的正则后,这个问题解决了)这里有BUG,目前的正则会匹配到-elis-ecocdn.pingan.com.cn这样错误的域名,然后调用Google这个API就会抛异常 */ private String getRootDomain(String subDomain){ String suffix = InternetDomainName.from(subDomain).publicSuffix().toString(); String[] tmpDomain = subDomain.substring(0, subDomain.lastIndexOf(suffix)-1).split("\\."); return tmpDomain[tmpDomain.length-1]+"."+suffix; } /** * */ private String getSimilarRootDomain(String subDomain){ for (String s:BurpExtender.currentRootDomainSet){ if(DomainProducer.isSimilarSubDomain(subDomain)){ return s; } } return null; } /** * 创建项目 * @param projectName */ public void addProject(String projectName){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into Project (projectName) values (?)"; break; case SQLITE_DB: sql = "insert or ignore into Project ([projectName]) values (?)"; break; default: break; } try{ PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); preSQl.execute(); }catch (SQLException e){ BurpExtender.getStderr().println("无法创建项目:"+e); } } /** * 删除项目 * @param projectName */ public void removeProject(String projectName){ String sql = "DELETE FROM Project WHERE projectName = ?;"; try{ PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); preSQl.execute(); }catch (SQLException e){ BurpExtender.getStderr().println("删除项目失败:"+e); } } /** * 添加根域名 * @param projectName * @param domainName */ public void addRootDomain(String projectName, String domainName){ String sql = null; switch (mode){ case MYSQL_DB: sql = "insert ignore into RootDomain (projectName,rootDomainName) values (?,?)"; break; case SQLITE_DB: sql = "insert or ignore into RootDomain ([projectName],[rootDomainName]) values (?,?)"; break; default: break; } try{ PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); preSQl.setString(2, domainName); preSQl.execute(); }catch (SQLException e){ BurpExtender.getStderr().println("无法添加根域名:"+e); } } /** * 删除根域名 * @param projectName * @param domainName */ public void removeRootDomain(String projectName,String domainName){ String sql = "delete from RootDomain where projectName = ? and rootDomainName = ?"; try{ PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); preSQl.setString(2, domainName); preSQl.execute(); }catch (SQLException e){ e.printStackTrace(); } } /** * 获取项目的Set * @return */ public HashSet<String> getProjectSet(){ String sql = "select ProjectName from Project"; HashSet<String> projectList = new HashSet<>(); try { PreparedStatement preSQl = conn.prepareStatement(sql); ResultSet set = preSQl.executeQuery(); while(set.next()){ projectList.add(set.getString("ProjectName")); } } catch (SQLException e) { e.printStackTrace(); } return projectList; } public HashSet<String> getRootDomainSet(String projectName){ String sql = "select rootDomainName from RootDomain where ProjectName=?"; HashSet<String> rootDomainList = new HashSet<>(); ResultSet set; try { PreparedStatement preSQl = conn.prepareStatement(sql); preSQl.setString(1, projectName); set = preSQl.executeQuery(); while(set.next()){ rootDomainList.add(set.getString("rootDomainName")); } } catch (SQLException e) { BurpExtender.getStderr().println("无法获取到根域名:"+e); } return rootDomainList; } public HashMap<String, HashMap<String, String>> getSubDomainMap(String projectName){ HashMap<String, HashMap<String, String>> subDomainMap = new HashMap<>(); Object[] rootDomainList = getRootDomainSet(projectName).toArray(); String[] inSql = new String[rootDomainList.length]; Arrays.fill(inSql, "?"); // 还是改回来了,不知道为啥,下面的那个方法取不到数据 String sql = "select subDomainName,rootDomainName,ipAddress,createTime from SubDomain where rootDomainName in ("+Joiner.on(",").join(inSql)+")"; try { PreparedStatement preSQl = conn.prepareStatement(sql); for (int i=0;i<rootDomainList.length;i++){ preSQl.setString(i+1, (String) rootDomainList[i]); } ResultSet set = preSQl.executeQuery(); while(set.next()){ HashMap<String, String> data = new HashMap<>(); data.put("ipAddress", set.getString("ipAddress")); data.put("createTime", set.getString("createTime")); data.put("status", "1"); subDomainMap.put(set.getString("subDomainName"), data); } } catch (SQLException e) { BurpExtender.getStderr().println("获取不到子域名"+e); } return subDomainMap; } public HashMap<String, HashMap<String, String>> getSimilarSubDomainMap(String projectName){ HashMap<String, HashMap<String, String>> subDomainMap = new HashMap<>(); Object[] rootDomainList = getRootDomainSet(projectName).toArray(); String[] inSql = new String[rootDomainList.length]; Arrays.fill(inSql, "?"); // 还是改回来了,不知道为啥,下面的那个方法取不到数据 String sql = "select subDomainName,rootDomainName,ipAddress,createTime from SimilarSubDomain where rootDomainName in ("+Joiner.on(",").join(inSql)+")"; try { PreparedStatement preSQl = conn.prepareStatement(sql); for (int i=0;i<rootDomainList.length;i++){ preSQl.setString(i+1, (String) rootDomainList[i]); } ResultSet set = preSQl.executeQuery(); while(set.next()){ HashMap<String, String> data = new HashMap<>(); data.put("ipAddress", set.getString("ipAddress")); data.put("createTime", set.getString("createTime")); data.put("status", "1"); subDomainMap.put(set.getString("subDomainName"), data); } } catch (SQLException e) { BurpExtender.getStderr().println("无法获取相似域名:"+e); } return subDomainMap; } public HashMap<String,HashMap<String,String>> getSubDomainAlive(String projectName){ HashMap<String, HashMap<String, String>> subDomainAliveMap = new HashMap<>(); Object[] rootDomainList = getRootDomainSet(projectName).toArray(); String[] inSql = new String[rootDomainList.length]; Arrays.fill(inSql, "?"); String sql = "select url,title,status,rootDomainName from SubDomainBscanAlive where rootDomainName in ("+Joiner.on(",").join(inSql)+")"; try{ PreparedStatement preSQL = conn.prepareStatement(sql); for (int i=0;i<rootDomainList.length;i++){ preSQL.setString(i+1, (String) rootDomainList[i]); } ResultSet set = preSQL.executeQuery(); while (set.next()){ HashMap<String,String> data = new HashMap<>(); data.put("rootDomain",set.getString("rootDomainName")); data.put("status",set.getString("status")); data.put("title",set.getString("title")); subDomainAliveMap.put(set.getString("url"),data); } }catch (SQLException e){ BurpExtender.getStderr().println("无法获取Bscan对域名的测活情况:"+e); } return subDomainAliveMap; } public HashMap<String,HashMap<String,String>> getSimilarSubDomainAlive(String projectName){ HashMap<String, HashMap<String, String>> similarDomainAliveMap = new HashMap<>(); Object[] rootDomainList = getRootDomainSet(projectName).toArray(); String[] inSql = new String[rootDomainList.length]; Arrays.fill(inSql, "?"); String sql = "select url,title,status,rootDomainName from SimilarDomainBscanAlive where rootDomainName in ("+Joiner.on(",").join(inSql)+")"; try{ PreparedStatement preSQL = conn.prepareStatement(sql); for (int i=0;i<rootDomainList.length;i++){ preSQL.setString(i+1, (String) rootDomainList[i]); } ResultSet set = preSQL.executeQuery(); while (set.next()){ HashMap<String,String> data = new HashMap<>(); data.put("rootDomain",set.getString("rootDomainName")); data.put("status",set.getString("status")); data.put("title",set.getString("title")); similarDomainAliveMap.put(set.getString("url"),data); } }catch (SQLException e){ BurpExtender.getStderr().println("无法获取Bscan对相似域名的测活情况:"+e); } return similarDomainAliveMap; } public HashMap<String, String> getUrlMap(String projectName){ HashMap<String, String> urlMap = new HashMap<>(); String sql = "select url, createTime from Url where projectName=?"; ResultSet set; try{ PreparedStatement preSQL = conn.prepareStatement(sql); preSQL.setString(1, projectName); set = preSQL.executeQuery(); while(set.next()){ urlMap.put(set.getString("url"), set.getString("createTime")); } }catch (SQLException e){ BurpExtender.getStderr().println("无法获取url:"+e); } return urlMap; } public HashMap<String, String> getSimilarUrlMap(String projectName){ HashMap<String, String> urlMap = new HashMap<>(); String sql = "select url, createTime from SimilarUrl where projectName=?"; ResultSet set; try{ PreparedStatement preSQL = conn.prepareStatement(sql); preSQL.setString(1, projectName); set = preSQL.executeQuery(); while(set.next()){ urlMap.put(set.getString("url"), set.getString("createTime")); } }catch (SQLException e){ BurpExtender.getStderr().println("无法获取相似url:"+e); } return urlMap; } public HashMap<String, HashMap<String, String>> getWebMap(HashSet<String> subDomains){ HashMap<String, HashMap<String, String>> webMap = new HashMap<>(); StringBuilder where = new StringBuilder(); for (String subDomain : subDomains) { where.append(" or url like '%").append(subDomain).append("%'"); } String sql = "select * from Web where 1=2 " + where; ResultSet set; try{ PreparedStatement preSQL = conn.prepareStatement(sql); set = preSQL.executeQuery(); while(set.next()){ String url = set.getString("url"); String status = set.getString("status"); String title = set.getString("title"); String length = set.getString("length"); String application = set.getString("application"); String webserver = set.getString("webserver"); String framework = set.getString("framework"); String os = set.getString("os"); String description = set.getString("description"); String createTime = set.getString("createTime"); HashMap<String, String> web = new HashMap<>(); web.put("status", status); web.put("title", title); web.put("length", length); web.put("application", application); web.put("webserver", webserver); web.put("framework", framework); web.put("os", os); web.put("description", description); web.put("createTime", createTime); webMap.put(url, web); } }catch (SQLException e){ BurpExtender.getStderr().println(e); } return webMap; } public static HashMap<String, String> getMysqlTableMap(){ //项目表 HashMap<String, String> tables = new HashMap<>(); tables.put("Project","CREATE TABLE IF NOT EXISTS `Project` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `projectName` varchar(64) NOT NULL,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `Project_projectName_uindex` (`projectName`)\n" + ") CHARSET=utf8;"); //根域名表 tables.put("RootDomain","CREATE TABLE IF NOT EXISTS `RootDomain` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `rootDomainName` varchar(64) NOT NULL,\n" + " `projectName` varchar(64) NOT NULL,\n" + " `scanned` int default 0 null,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `RootDomain_domainName_uindex` (`rootDomainName`)\n" + ") CHARSET=utf8;"); //子域名表 tables.put("SubDomain","CREATE TABLE IF NOT EXISTS `SubDomain` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `subDomainName` varchar(128) NOT NULL,\n" + " `rootDomainName` varchar(64) DEFAULT NULL,\n" + " `ipAddress` varchar(64) DEFAULT NULL,\n" + " `createTime` datetime NOT NULL,\n" + " `scanned` int default 0 null,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `SubDomain_subDomainName_uindex` (`subDomainName`)\n" + ") CHARSET=utf8;"); //url表 tables.put("Url","CREATE TABLE IF NOT EXISTS `Url` (\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `url` varchar(256) NOT NULL,\n" + " `projectName` varchar(64) NOT NULL,\n" + " `createTime` datetime NOT NULL,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `Url_url_uindex` (`url`)\n" + ") CHARSET=utf8;"); //相似域名表 tables.put("SimilarSubDomain","CREATE TABLE IF NOT EXISTS `SimilarSubDomain`(\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `subDomainName` varchar(128) NOT NULL,\n" + " `rootDomainName` varchar(64) DEFAULT NULL,\n" + " `ipAddress` varchar(64) DEFAULT NULL,\n" + " `createTime` datetime NOT NULL,\n" + " `scanned` int default 0 null,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `SimilarSubDomain_similarDomainName_uindex` (`subDomainName`)\n" + ") CHARSET=utf8;"); //相似域名子域名表 tables.put("SimilarUrl","CREATE TABLE IF NOT EXISTS `SimilarUrl`(\n" + " `id` int(11) NOT NULL AUTO_INCREMENT,\n" + " `url` varchar(64) NOT NULL,\n" + " `projectName` varchar(64) NOT NULL,\n" + " `createTime` datetime NOT NULL,\n" + " PRIMARY KEY (`id`),\n" + " UNIQUE KEY `SimilarUrl_url_uindex` (`url`)\n" + ") CHARSET=utf8;"); tables.put("Web", "CREATE TABLE IF NOT EXISTS Web (\n" + " id int(11) AUTO_INCREMENT PRIMARY KEY,\n" + " url varchar(256) UNIQUE,\n" + " status varchar(64),\n" + " title varchar(64),\n" + " length varchar(64),\n" + " application varchar(64),\n" + " webserver varchar(64),\n" + " framework varchar(64),\n" + " os varchar(64),\n" + " description varchar(64),\n" + " createTime datetime not null\n"+ ") CHARSET=utf8;"); return tables; } public static HashMap<String, String> getSqliteTableMap(){ HashMap<String, String> tables = new HashMap<String, String>(6){ { put("Project","CREATE TABLE \"main\".\"Project\" (\n" + " \"id\" integer NOT NULL,\n" + " \"projectName\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"Project_projectName_uindex\" UNIQUE (\"projectName\")"+ ");"); put("RootDomain","CREATE TABLE \"main\".\"RootDomain\" (\n" + " \"id\" integer NOT NULL,\n" + " \"rootDomainName\" TEXT,\n" + " \"projectName\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"RootDomain_projectName_uindex\" UNIQUE (\"rootDomainName\")"+ ");"); put("SubDomain","CREATE TABLE \"main\".\"SubDomain\" (\n" + " \"id\" integer NOT NULL,\n" + " \"subDomainName\" TEXT,\n" + " \"rootDomainName\" TEXT,\n" + " \"ipAddress\" TEXT,\n" + " \"createTime\" TEXT,\n" + " \"scan\" integers DEFAULT 0, \n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"SubDomain_projectName_uindex\" UNIQUE (\"subDomainName\")"+ ");"); put("Url","CREATE TABLE \"main\".\"Url\" (\n" + " \"id\" integer NOT NULL,\n" + " \"url\" TEXT,\n" + " \"projectName\" TEXT,\n" + " \"createTime\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"Url_projectName_uindex\" UNIQUE (\"url\")"+ ");"); put("SimilarSubDomain","CREATE TABLE \"main\".\"SimilarSubDomain\" (\n" + " \"id\" integer NOT NULL,\n" + " \"SubDomainName\" TEXT,\n" + " \"rootDomainName\" TEXT,\n" + " \"ipAddress\" TEXT,\n" + " \"createTime\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"SimilarSubDomain_projectName_uindex\" UNIQUE (\"SubDomainName\")"+ ");"); put("SimilarUrl","CREATE TABLE \"main\".\"SimilarUrl\" (\n" + " \"id\" integer NOT NULL,\n" + " \"url\" TEXT,\n" + " \"projectName\" TEXT,\n" + " \"createTime\" TEXT,\n" + " CONSTRAINT \"id\" PRIMARY KEY (\"id\")\n" + " CONSTRAINT \"SimilarUrl_projectName_uindex\" UNIQUE (\"url\")"+ ");"); } }; return tables; } public static void main(String[] args) { HashMap<String, String> m
0
30375_30
/* //加了flag以保持后台运行不退出,还没经过测试,(上一版本能用,如果出问题需要恢复上一版本,修改项参看所收藏的相关网页) //2019.12.19增加悬浮窗权限判断:https://blog.csdn.net/qq_27885521/article/details/101510088 //2021.3.2 要添加在“最近应用列表”隐藏的功能。(搞定,并去掉了遮盖整个recent界面的功能) */ package guard.anti_phoneaddiction; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class Guardian extends AppCompatActivity { public int endTime=0; public int startTime=0; EditText startTimeText,endTimeText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.guardian); //enableDeviceAdmin(); //判断无障碍服务是否已经打开,没打开则进入无障碍设置界面 if (!isAccessibilitySettingsOn(this)) { Toast.makeText(this, "请授权打开无障碍服务", Toast.LENGTH_LONG); Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS); this.startActivity(intent); } //在启动服务之前,需要先判断一下当前是否允许开启悬浮窗 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) { Toast.makeText(this, "当前无开启悬浮窗权限,请授权", Toast.LENGTH_LONG); startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0); } //启动后台监控服务,用于监控是否按了recent键 this.startService(new Intent(this, Anti_PhoneAddictionService.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); //加了flag以保持后台运行不退出,还没经过测试,(上一版本能用,如果出问题需要恢复上一版本,修改项参看所收藏的相关网页) //不断循环启动应用锁 // int i=0; // while(i<=20){ // try { // Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.lxq.applocker"); // startActivity(LaunchIntent); // //Thread.sleep(10); // //  按Home键 //// Intent intent = new Intent(Intent.ACTION_MAIN); //// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //// intent.addCategory(Intent.CATEGORY_HOME); //// startActivity(intent); // i++; // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // //用按钮启动应用锁 // Button startLock =(Button)findViewById(R.id.StartLock); // startLock.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.lxq.applocker"); // startActivity(LaunchIntent); // } // }); startTimeText=findViewById(R.id.startTime); endTimeText=findViewById(R.id.endTime); } public void onClick(View v) { //点击设置后把时间传送给后台服务 Anti_PhoneAddictionService.startTime_user=Integer.parseInt(startTimeText.getText().toString()); Anti_PhoneAddictionService.endTime_user=Integer.parseInt(endTimeText.getText().toString()); Toast.makeText(this,"已设置禁止使用手机的时间为"+startTime+" 至 "+ endTime,Toast.LENGTH_LONG); // return true; } private void enableDeviceAdmin() { ComponentName deviceAdmin = new ComponentName(this, DeviceAdmin.class); DevicePolicyManager mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); // First of all, to access anything you must be device owner if (mDpm.isDeviceOwnerApp(getPackageName())) { // If not device admin, ask to become one if (!mDpm.isAdminActive(deviceAdmin) && mDpm.isDeviceOwnerApp(getPackageName())) { //Log.v(TAG, "Not device admin. Asking device owner to become one."); Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "You need to be a device admin to enable device admin."); startActivity(intent); } // Device owner and admin : enter device admin else if (Build.VERSION.SDK_INT >= 21) { mDpm.setLockTaskPackages(deviceAdmin, new String[]{ getPackageName(), // PUT OTHER PACKAGE NAMES HERE! / }); startLockTask(); } } } private boolean isAccessibilitySettingsOn(Context mContext) { int accessibilityEnabled = 0; final String service = getPackageName() + "/" + Anti_PhoneAddictionService.class.getCanonicalName(); try { accessibilityEnabled = Settings.Secure.getInt( mContext.getApplicationContext().getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED); // Log.v(TAG, "accessibilityEnabled = " + accessibilityEnabled); } catch (Settings.SettingNotFoundException e) { // Log.e(TAG, "Error finding setting, default accessibility to not found: " // + e.getMessage()); } TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':'); if (accessibilityEnabled == 1) { // Log.v(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------"); String settingValue = Settings.Secure.getString( mContext.getApplicationContext().getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES); if (settingValue != null) { mStringColonSplitter.setString(settingValue); while (mStringColonSplitter.hasNext()) { String accessibilityService = mStringColonSplitter.next(); // Log.v(TAG, "-------------- > accessibilityService :: " + accessibilityService + " " + service); if (accessibilityService.equalsIgnoreCase(service)) { // Log.v(TAG, "We've found the correct setting - accessibility is switched on!"); return true; } } } } else { // Log.v(TAG, "***ACCESSIBILITY IS DISABLED***"); } return false; } }
ActionWind/Anti-PhoneAddiction
app/src/main/java/guard/anti_phoneaddiction/Guardian.java
1,703
//点击设置后把时间传送给后台服务
line_comment
zh-cn
/* //加了flag以保持后台运行不退出,还没经过测试,(上一版本能用,如果出问题需要恢复上一版本,修改项参看所收藏的相关网页) //2019.12.19增加悬浮窗权限判断:https://blog.csdn.net/qq_27885521/article/details/101510088 //2021.3.2 要添加在“最近应用列表”隐藏的功能。(搞定,并去掉了遮盖整个recent界面的功能) */ package guard.anti_phoneaddiction; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class Guardian extends AppCompatActivity { public int endTime=0; public int startTime=0; EditText startTimeText,endTimeText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.guardian); //enableDeviceAdmin(); //判断无障碍服务是否已经打开,没打开则进入无障碍设置界面 if (!isAccessibilitySettingsOn(this)) { Toast.makeText(this, "请授权打开无障碍服务", Toast.LENGTH_LONG); Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS); this.startActivity(intent); } //在启动服务之前,需要先判断一下当前是否允许开启悬浮窗 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) { Toast.makeText(this, "当前无开启悬浮窗权限,请授权", Toast.LENGTH_LONG); startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0); } //启动后台监控服务,用于监控是否按了recent键 this.startService(new Intent(this, Anti_PhoneAddictionService.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); //加了flag以保持后台运行不退出,还没经过测试,(上一版本能用,如果出问题需要恢复上一版本,修改项参看所收藏的相关网页) //不断循环启动应用锁 // int i=0; // while(i<=20){ // try { // Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.lxq.applocker"); // startActivity(LaunchIntent); // //Thread.sleep(10); // //  按Home键 //// Intent intent = new Intent(Intent.ACTION_MAIN); //// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //// intent.addCategory(Intent.CATEGORY_HOME); //// startActivity(intent); // i++; // Thread.sleep(300); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // //用按钮启动应用锁 // Button startLock =(Button)findViewById(R.id.StartLock); // startLock.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.lxq.applocker"); // startActivity(LaunchIntent); // } // }); startTimeText=findViewById(R.id.startTime); endTimeText=findViewById(R.id.endTime); } public void onClick(View v) { //点击 <SUF> Anti_PhoneAddictionService.startTime_user=Integer.parseInt(startTimeText.getText().toString()); Anti_PhoneAddictionService.endTime_user=Integer.parseInt(endTimeText.getText().toString()); Toast.makeText(this,"已设置禁止使用手机的时间为"+startTime+" 至 "+ endTime,Toast.LENGTH_LONG); // return true; } private void enableDeviceAdmin() { ComponentName deviceAdmin = new ComponentName(this, DeviceAdmin.class); DevicePolicyManager mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); // First of all, to access anything you must be device owner if (mDpm.isDeviceOwnerApp(getPackageName())) { // If not device admin, ask to become one if (!mDpm.isAdminActive(deviceAdmin) && mDpm.isDeviceOwnerApp(getPackageName())) { //Log.v(TAG, "Not device admin. Asking device owner to become one."); Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "You need to be a device admin to enable device admin."); startActivity(intent); } // Device owner and admin : enter device admin else if (Build.VERSION.SDK_INT >= 21) { mDpm.setLockTaskPackages(deviceAdmin, new String[]{ getPackageName(), // PUT OTHER PACKAGE NAMES HERE! / }); startLockTask(); } } } private boolean isAccessibilitySettingsOn(Context mContext) { int accessibilityEnabled = 0; final String service = getPackageName() + "/" + Anti_PhoneAddictionService.class.getCanonicalName(); try { accessibilityEnabled = Settings.Secure.getInt( mContext.getApplicationContext().getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED); // Log.v(TAG, "accessibilityEnabled = " + accessibilityEnabled); } catch (Settings.SettingNotFoundException e) { // Log.e(TAG, "Error finding setting, default accessibility to not found: " // + e.getMessage()); } TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':'); if (accessibilityEnabled == 1) { // Log.v(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------"); String settingValue = Settings.Secure.getString( mContext.getApplicationContext().getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES); if (settingValue != null) { mStringColonSplitter.setString(settingValue); while (mStringColonSplitter.hasNext()) { String accessibilityService = mStringColonSplitter.next(); // Log.v(TAG, "-------------- > accessibilityService :: " + accessibilityService + " " + service); if (accessibilityService.equalsIgnoreCase(service)) { // Log.v(TAG, "We've found the correct setting - accessibility is switched on!"); return true; } } } } else { // Log.v(TAG, "***ACCESSIBILITY IS DISABLED***"); } return false; } }
0
32332_1
package com.management.model.ov.resultsetting; /** * @program: management * @description: 项目的类别 * @author: ggmr * @create: 2018-12-17 23:49 */ public class ConstCorrespond { //这个第一个为空是有说法的,请勿删除 public final static String[] PROJECT_TYPE = { "", "经济管理类", "人文哲学类", "计算科学类", "生物化学类" }; public final static String[] APPLICAN_TYPE = { "", "本科生", "研究生", "博士生", "研究员", "教授" }; public final static String[] reviewPhrase = { "", "业务员审核阶段", "评审专家审核阶段", "会评阶段", "领导审核阶段", "项目申请审核通过", "项目申请审核失败", "待提交任务书阶段", "任务书审核阶段", }; public final static String downloadAddress = "http://118.25.130.89:8081/api/file/download?fileAddress="; public final static String[] PROJECT_PROGRESS = { "", "立项", "中期报告阶段", "结题报告审核阶段", "项目结项", "结题报告审核失败" }; public final static String[] USER_AUTHORIZATION = { "", "ROLE_USER", "ROLE_ADMIN", "ROLE_EXPERT", "ROLE_LEADER", "ROLE_SUPERADMIN" }; public final static String[] USER_IDENTITY = { "", "用户", "业务员", "专家", "领导", "系统管理员" }; public final static int MIDDLE_PROGRESS = 2; public final static int FINAL_PROGRESS = 3; public final static int FINISH_PROGRESS_FAILED = 5; public final static int FINISH_PROJECT = 4; public static final String TOKEN_HEAD = "Bearer "; }
Actooors/ProjectManagement_Service
src/main/java/com/management/model/ov/resultsetting/ConstCorrespond.java
496
//这个第一个为空是有说法的,请勿删除
line_comment
zh-cn
package com.management.model.ov.resultsetting; /** * @program: management * @description: 项目的类别 * @author: ggmr * @create: 2018-12-17 23:49 */ public class ConstCorrespond { //这个 <SUF> public final static String[] PROJECT_TYPE = { "", "经济管理类", "人文哲学类", "计算科学类", "生物化学类" }; public final static String[] APPLICAN_TYPE = { "", "本科生", "研究生", "博士生", "研究员", "教授" }; public final static String[] reviewPhrase = { "", "业务员审核阶段", "评审专家审核阶段", "会评阶段", "领导审核阶段", "项目申请审核通过", "项目申请审核失败", "待提交任务书阶段", "任务书审核阶段", }; public final static String downloadAddress = "http://118.25.130.89:8081/api/file/download?fileAddress="; public final static String[] PROJECT_PROGRESS = { "", "立项", "中期报告阶段", "结题报告审核阶段", "项目结项", "结题报告审核失败" }; public final static String[] USER_AUTHORIZATION = { "", "ROLE_USER", "ROLE_ADMIN", "ROLE_EXPERT", "ROLE_LEADER", "ROLE_SUPERADMIN" }; public final static String[] USER_IDENTITY = { "", "用户", "业务员", "专家", "领导", "系统管理员" }; public final static int MIDDLE_PROGRESS = 2; public final static int FINAL_PROGRESS = 3; public final static int FINISH_PROGRESS_FAILED = 5; public final static int FINISH_PROJECT = 4; public static final String TOKEN_HEAD = "Bearer "; }
0
11537_1
package build; /** * @author Acyco * @create 2020-01-10 03:22 */ public class Client { public static void main(String[] args) { CommonHouse commonHouse = new CommonHouse(); commonHouse.build(); } } /* 优点是比较好理解 简单易操作 设计的程序结构,过于简单,没有设计缓存层对象,程序的扩展和维护不好。也就是说,这种设计方案 把产品(即:房子)和 创建产品的过程(即:建房子的流程)封装在一起,耦合性增强了。 解决方案:将产品和产品建造过程解耦 => 建造者模式 */
Acyco/DesignPattern
src/build/Client.java
172
/* 优点是比较好理解 简单易操作 设计的程序结构,过于简单,没有设计缓存层对象,程序的扩展和维护不好。也就是说,这种设计方案 把产品(即:房子)和 创建产品的过程(即:建房子的流程)封装在一起,耦合性增强了。 解决方案:将产品和产品建造过程解耦 => 建造者模式 */
block_comment
zh-cn
package build; /** * @author Acyco * @create 2020-01-10 03:22 */ public class Client { public static void main(String[] args) { CommonHouse commonHouse = new CommonHouse(); commonHouse.build(); } } /* 优点是 <SUF>*/
1
20719_2
import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; /** * main * * @author Acyco * @create 2019-04-11 15:25 */ public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("JavaFX"); primaryStage.getIcons().add(new Image("/img/logo.jpg"));//设置图标 primaryStage.setWidth(300);//设置窗口宽度 primaryStage.setHeight(300);//设置窗口高度 // primaryStage.setIconified(true); //设置最小化 // primaryStage.setMaximized(true); //设置最大化 // primaryStage.close(); // 关闭窗口 // primaryStage.setResizable(false); // 设置 不可以改变窗口的大小 primaryStage.setWidth(500); primaryStage.setHeight(500); // primaryStage.setMaxWidth(800); // primaryStage.setMaxHeight(800); // // primaryStage.setMinWidth(300); // primaryStage.setMinHeight(300); // getWidth() getHeight() 前面没有设置 一定要放到 放在show()后面 // System.out.println("宽度: "+primaryStage.getWidth()); // System.out.println("高度: "+primaryStage.getHeight()); primaryStage.heightProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { System.out.println("当前高度"+newValue); } }); primaryStage.widthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { System.out.println("当前宽度"+newValue); } }); primaryStage.setFullScreen(true); //设置全屏 设置Scene primaryStage.setScene(new Scene(new Group())); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
Acyco/JavaFX
Stage/src/Main.java
592
//设置窗口宽度
line_comment
zh-cn
import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; /** * main * * @author Acyco * @create 2019-04-11 15:25 */ public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("JavaFX"); primaryStage.getIcons().add(new Image("/img/logo.jpg"));//设置图标 primaryStage.setWidth(300);//设置 <SUF> primaryStage.setHeight(300);//设置窗口高度 // primaryStage.setIconified(true); //设置最小化 // primaryStage.setMaximized(true); //设置最大化 // primaryStage.close(); // 关闭窗口 // primaryStage.setResizable(false); // 设置 不可以改变窗口的大小 primaryStage.setWidth(500); primaryStage.setHeight(500); // primaryStage.setMaxWidth(800); // primaryStage.setMaxHeight(800); // // primaryStage.setMinWidth(300); // primaryStage.setMinHeight(300); // getWidth() getHeight() 前面没有设置 一定要放到 放在show()后面 // System.out.println("宽度: "+primaryStage.getWidth()); // System.out.println("高度: "+primaryStage.getHeight()); primaryStage.heightProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { System.out.println("当前高度"+newValue); } }); primaryStage.widthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { System.out.println("当前宽度"+newValue); } }); primaryStage.setFullScreen(true); //设置全屏 设置Scene primaryStage.setScene(new Scene(new Group())); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
0
5392_18
package basic.tree; //因为一旦有符合的值就会立即返回,那么这个递归函数就会回溯这样的话,有的话立即结束,不会再次判断,所以就是四个结构(不正确) //上面是线性的思路,这时的结构是回溯性质的非线性的要转换思路,从长驱直入转化到懂得用temp来保存,完成非线性的任务来实现 //也就是说递归要开发思路到非线性的,其特点就是用temp //这样多分叉的结构需要用一个临时变量存起来,这是很重要的,考虑不够完全 //注意在韩老师的思路中是指要在Node中核心代码,在Tree中封装代码 //和我写的结构是不一样的 public class TraverseDemo { public static void main(String[] args){ Tree tree = new Tree(); System.out.println(tree.delete(tree.getRoot(),18)); tree.Traverse("pre"); //System.out.println(basic.tree.preSearch(basic.tree.getRoot(),2)); } } //和链表的数据结构是一个样的,结点的定义是一个类,含有基本的逻辑关系 //数据结构的是一个类,对应的具体的唯一标识这个数据结构的结构就是上面的一个类 //这样的思路最好,就是有一个结点类,还有一个具体的数据结构类,也就是树类 class Tree{ //没事,没有一下子想出来没事 Node root;//对象就是指向该类对应开辟内存的部分的指针,root == null那么就是空树 public Tree(){ //先赋值获得堆内存,可以先不给后面的结点获取值 root= new Node(0);//覆盖掉了 root.left = new Node(1); root.right = new Node(2); root.left.left = new Node(3); root.left.right = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); } //前序遍历 public void Traverse(String flag){ switch (flag){ case "pre" : preTraverse(root); break; case "infix" :infixTraverse(root); break; case "post" :postTraverse(root); break; } } //前序遍历 public void preTraverse(Node node){ System.out.println(node.id); if(node.left != null){ preTraverse(node.left); } if(node.right != null){ preTraverse(node.right); } } //前序查找 -- 传的时候是root但是没办法再递归的方法体内体现出来 public Node preSearch(Node node,int id){ //如果在一个子树里面没有的话始终会传回一个null所以这样的思路是不对的,总需要一个变量存起来,逻辑就能变化 //之前的逻辑是无论遍历哪一个子树,只要没有找到总会返回null,并且在当前状态就结束递归了,说明我对递归的思路还没有把握透彻 //但是就是慢慢来,这个东西记住了,必须是这样的逻辑应当是若树中没有对应的结点,就应该全部遍历一遍,显然没有给后面一个机会 //若要给后面一个机会就是如果左子树不为空的话,那么说明找到了,如果为空的话就没找到,必须要都遍历一边 if(node.id == id){ return node; } Node res = null; if(node.left != null){ res = preSearch(node.left,id); } if (res!= null){ return res; } if(node.right != null){ res = preSearch(node.right,id); } return res; } //中序遍历 public void infixTraverse(Node node){ if(node.left != null){ infixTraverse(node.left); } System.out.println(node.id); if(node.right != null){ infixTraverse(node.right); } } public Node infixSearch(Node node,int id){ Node res = null; if(node.left != null){ res = infixSearch(node.left,id); } if( res !=null){ return res; } if(node.id == id){ return node; } if(node.right != null){ res = infixSearch(node.right,id); } return res; } //后序遍历 //同时也可以在一个树类里面进行遍历也就是this.left.preorder //1.韩老师那个思路最好是在一个树里面来遍历就是在一个树类里面来遍历 //然后每个对象既是一个结点又是一棵树也就是Tree left, Tree right这样也可以,那这样的话写在树里面就可以自己调用自己了 //2.第二个就是还是按照之前的数据结构的思路,树类里面封装着方法,然后结点分别有不同的左右 //这样的实现思路就是只需要在树结构内部定义一个根节点就好,但是此时由于递归的特性需要再封装一个类,否则就应该去把头节点传进去 //其实这些不重要主要是思想或者是利用一个静态方法也可以 -- 最后这个比较好一点 //涉及到多分叉的查找应有temp的思想 public void postTraverse(Node node){ if(node.left != null){ postTraverse(node.left); } if(node.right != null){ postTraverse(node.right); } System.out.println(node.id); } public Node postSearch(Node node,int id){ Node res = null; if(node.left != null){ res = postSearch(node.left,id); } if( res != null){ return res; } if(node.right != null){ res = postSearch(node.right,id); } if( res != null){ return res; } if(node.id == id){ return node; } return res; } public boolean delete(Node node,int id){//和递归的思想是一样的,但是实现方式真的是不一样 //id是唯一的 //在树这一章中非线性结构比较需要缓存变量 //思路就是如果找到对应的结点就删除,比如说要删除左右节点,需要先判断左右结点是否为空 //如果不判断的话,会出现空指针异常,整体思路不变还是递归遍历删除 //其实就是前序删除 if(node.left != null && node.left.id == id){ node.left = null; return true; } if(node.right != null && node.right.id == id){ node.right = null; return true; } //如果该结点都没有的话,这时才应该往下遍历 if(node.left != null && delete(node.left,id)){ return true; } if(node.right !=null && delete(node.right,id)){ return true; } return false; } public Node getRoot(){ return root; } } class Node{ int id; char ch = '0'; Node left; Node right; int leftType; int rightType; Node pre; public Node( int id){ this.id = id;//这个赋值也能错也是够可以的 } public Node( int id,char ch){ this.id = id; this.ch = ch; } public String toString(){ return id+""; } } //常见的思想是交给结点自身去递归查找,应该注意的一个点就是多分叉的结构应当是有temp的变量先存 //着这个东西最后都遍历结束再null
AdamZHC/DAlgorithm
src/basic/tree/TraverseDemo.java
1,857
//之前的逻辑是无论遍历哪一个子树,只要没有找到总会返回null,并且在当前状态就结束递归了,说明我对递归的思路还没有把握透彻
line_comment
zh-cn
package basic.tree; //因为一旦有符合的值就会立即返回,那么这个递归函数就会回溯这样的话,有的话立即结束,不会再次判断,所以就是四个结构(不正确) //上面是线性的思路,这时的结构是回溯性质的非线性的要转换思路,从长驱直入转化到懂得用temp来保存,完成非线性的任务来实现 //也就是说递归要开发思路到非线性的,其特点就是用temp //这样多分叉的结构需要用一个临时变量存起来,这是很重要的,考虑不够完全 //注意在韩老师的思路中是指要在Node中核心代码,在Tree中封装代码 //和我写的结构是不一样的 public class TraverseDemo { public static void main(String[] args){ Tree tree = new Tree(); System.out.println(tree.delete(tree.getRoot(),18)); tree.Traverse("pre"); //System.out.println(basic.tree.preSearch(basic.tree.getRoot(),2)); } } //和链表的数据结构是一个样的,结点的定义是一个类,含有基本的逻辑关系 //数据结构的是一个类,对应的具体的唯一标识这个数据结构的结构就是上面的一个类 //这样的思路最好,就是有一个结点类,还有一个具体的数据结构类,也就是树类 class Tree{ //没事,没有一下子想出来没事 Node root;//对象就是指向该类对应开辟内存的部分的指针,root == null那么就是空树 public Tree(){ //先赋值获得堆内存,可以先不给后面的结点获取值 root= new Node(0);//覆盖掉了 root.left = new Node(1); root.right = new Node(2); root.left.left = new Node(3); root.left.right = new Node(4); root.right.left = new Node(5); root.right.right = new Node(6); } //前序遍历 public void Traverse(String flag){ switch (flag){ case "pre" : preTraverse(root); break; case "infix" :infixTraverse(root); break; case "post" :postTraverse(root); break; } } //前序遍历 public void preTraverse(Node node){ System.out.println(node.id); if(node.left != null){ preTraverse(node.left); } if(node.right != null){ preTraverse(node.right); } } //前序查找 -- 传的时候是root但是没办法再递归的方法体内体现出来 public Node preSearch(Node node,int id){ //如果在一个子树里面没有的话始终会传回一个null所以这样的思路是不对的,总需要一个变量存起来,逻辑就能变化 //之前 <SUF> //但是就是慢慢来,这个东西记住了,必须是这样的逻辑应当是若树中没有对应的结点,就应该全部遍历一遍,显然没有给后面一个机会 //若要给后面一个机会就是如果左子树不为空的话,那么说明找到了,如果为空的话就没找到,必须要都遍历一边 if(node.id == id){ return node; } Node res = null; if(node.left != null){ res = preSearch(node.left,id); } if (res!= null){ return res; } if(node.right != null){ res = preSearch(node.right,id); } return res; } //中序遍历 public void infixTraverse(Node node){ if(node.left != null){ infixTraverse(node.left); } System.out.println(node.id); if(node.right != null){ infixTraverse(node.right); } } public Node infixSearch(Node node,int id){ Node res = null; if(node.left != null){ res = infixSearch(node.left,id); } if( res !=null){ return res; } if(node.id == id){ return node; } if(node.right != null){ res = infixSearch(node.right,id); } return res; } //后序遍历 //同时也可以在一个树类里面进行遍历也就是this.left.preorder //1.韩老师那个思路最好是在一个树里面来遍历就是在一个树类里面来遍历 //然后每个对象既是一个结点又是一棵树也就是Tree left, Tree right这样也可以,那这样的话写在树里面就可以自己调用自己了 //2.第二个就是还是按照之前的数据结构的思路,树类里面封装着方法,然后结点分别有不同的左右 //这样的实现思路就是只需要在树结构内部定义一个根节点就好,但是此时由于递归的特性需要再封装一个类,否则就应该去把头节点传进去 //其实这些不重要主要是思想或者是利用一个静态方法也可以 -- 最后这个比较好一点 //涉及到多分叉的查找应有temp的思想 public void postTraverse(Node node){ if(node.left != null){ postTraverse(node.left); } if(node.right != null){ postTraverse(node.right); } System.out.println(node.id); } public Node postSearch(Node node,int id){ Node res = null; if(node.left != null){ res = postSearch(node.left,id); } if( res != null){ return res; } if(node.right != null){ res = postSearch(node.right,id); } if( res != null){ return res; } if(node.id == id){ return node; } return res; } public boolean delete(Node node,int id){//和递归的思想是一样的,但是实现方式真的是不一样 //id是唯一的 //在树这一章中非线性结构比较需要缓存变量 //思路就是如果找到对应的结点就删除,比如说要删除左右节点,需要先判断左右结点是否为空 //如果不判断的话,会出现空指针异常,整体思路不变还是递归遍历删除 //其实就是前序删除 if(node.left != null && node.left.id == id){ node.left = null; return true; } if(node.right != null && node.right.id == id){ node.right = null; return true; } //如果该结点都没有的话,这时才应该往下遍历 if(node.left != null && delete(node.left,id)){ return true; } if(node.right !=null && delete(node.right,id)){ return true; } return false; } public Node getRoot(){ return root; } } class Node{ int id; char ch = '0'; Node left; Node right; int leftType; int rightType; Node pre; public Node( int id){ this.id = id;//这个赋值也能错也是够可以的 } public Node( int id,char ch){ this.id = id; this.ch = ch; } public String toString(){ return id+""; } } //常见的思想是交给结点自身去递归查找,应该注意的一个点就是多分叉的结构应当是有temp的变量先存 //着这个东西最后都遍历结束再null
0
39815_72
package net.doge.sdk.entity.mv.info; import cn.hutool.http.HttpRequest; import cn.hutool.http.Method; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; import net.doge.constant.model.MvInfoType; import net.doge.constant.model.NetMusicSource; import net.doge.constant.system.VideoQuality; import net.doge.model.entity.NetMvInfo; import net.doge.sdk.common.SdkCommon; import net.doge.sdk.common.opt.nc.NeteaseReqOptEnum; import net.doge.sdk.common.opt.nc.NeteaseReqOptsBuilder; import net.doge.util.collection.ArrayUtil; import net.doge.util.common.JsonUtil; import net.doge.util.common.StringUtil; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.util.Map; public class MvUrlReq { private static MvUrlReq instance; private MvUrlReq() { } public static MvUrlReq getInstance() { if (instance == null) instance = new MvUrlReq(); return instance; } // mlog id 转视频 id API private final String MLOG_TO_VIDEO_API = "https://music.163.com/weapi/mlog/video/convert/id"; // MV 视频链接 API private final String MV_URL_API = "https://music.163.com/weapi/song/enhance/play/mv/url"; // 视频链接 API private final String VIDEO_URL_API = "https://music.163.com/weapi/cloudvideo/playurl"; // Mlog 链接 API // private final String MLOG_URL_API = SdkCommon.PREFIX + "/mlog/url?id=%s"; // MV 视频链接获取 API (酷狗) private final String MV_URL_KG_API = "http://m.kugou.com/app/i/mv.php?cmd=100&hash=%s&ismp3=1&ext=mp4"; // private final String MV_URL_KG_API = "/v2/interface/index"; // MV 视频链接获取 API (酷我) private final String MV_URL_KW_API = "https://kuwo.cn/api/v1/www/music/playUrl?mid=%s&type=mv&httpsStatus=1"; // MV 视频链接获取 API (千千) private final String MV_URL_QI_API = "https://music.91q.com/v1/video/info?appid=16073360&assetCode=%s&timestamp=%s"; // MV 视频链接获取 API (5sing) private final String MV_URL_FS_API = "http://service.5sing.kugou.com/mv/play?mvId=%s"; // MV 视频链接获取 API (好看) private final String MV_URL_HK_API = "https://haokan.baidu.com/v?vid=%s&_format=json"; // 视频 bvid 获取 cid (哔哩哔哩) private final String VIDEO_CID_BI_API = "https://api.bilibili.com/x/player/pagelist?bvid=%s"; // MV 视频链接获取 API (哔哩哔哩) private final String VIDEO_URL_BI_API = "https://api.bilibili.com/x/player/playurl?bvid=%s&cid=%s&qn=%s"; // MV 视频链接获取 API (哔哩哔哩) private final String MV_URL_YY_API = "https://video-api.yinyuetai.com/video/get?id=%s"; // 视频链接获取 API (发姐) private final String VIDEO_URL_FA_API = "https://www.chatcyf.com/topics/%s/"; // 视频链接获取 API (李志) private final String VIDEO_URL_LZ_API = "https://www.lizhinb.com/live/%s/"; /** * 根据 MV id 获取 MV 视频链接 */ public String fetchMvUrl(NetMvInfo mvInfo) { int source = mvInfo.getSource(); String id = mvInfo.getId(); String bvId = mvInfo.getBvid(); boolean isVideo = mvInfo.isVideo(); boolean isMlog = mvInfo.isMlog(); // 网易云 if (source == NetMusicSource.NC) { String quality; switch (VideoQuality.quality) { case VideoQuality.UHD: case VideoQuality.FHD: quality = "1080"; break; case VideoQuality.HD: quality = "720"; break; case VideoQuality.SD: quality = "480"; break; default: quality = "240"; break; } if (isVideo || isMlog) { // Mlog 需要先获取视频 id,并转为视频类型 if (isMlog) { Map<NeteaseReqOptEnum, String> options = NeteaseReqOptsBuilder.weapi(); String body = SdkCommon.ncRequest(Method.POST, MLOG_TO_VIDEO_API, String.format("{\"mlogId\":\"%s\"}", id), options) .executeAsync() .body(); id = JSONObject.parseObject(body).getString("data"); mvInfo.setId(id); mvInfo.setType(MvInfoType.VIDEO); } Map<NeteaseReqOptEnum, String> options = NeteaseReqOptsBuilder.weapi(); String mvBody = SdkCommon.ncRequest(Method.POST, VIDEO_URL_API, String.format("{\"ids\":\"['%s']\",\"resolution\":\"%s\"}", id, quality), options) .executeAsync() .body(); JSONObject mvJson = JSONObject.parseObject(mvBody); JSONArray urls = mvJson.getJSONArray("urls"); String url = urls.getJSONObject(0).getString("url"); if (StringUtil.notEmpty(url)) return url; } // else if (isMlog) { // String mvBody = HttpRequest.get(String.format(MLOG_URL_API, id)) // .executeAsync() // .body(); // JSONObject mvJson = JSONObject.parseObject(mvBody); // JSONArray urls = mvJson.getJSONObject("data") // .getJSONObject("resource") // .getJSONObject("content") // .getJSONObject("video") // .getJSONArray("urlInfos"); // String url = null; // int r = 0; // for (int i = 0, s = urls.size(); i < s; i++) { // JSONObject urlJson = urls.getJSONObject(i); // int r1 = urlJson.getIntValue("r"); // if (r < r1) { // r = r1; // url = urlJson.getString("url"); // } // } // if (StringUtil.notEmpty(url)) return url; // } else { Map<NeteaseReqOptEnum, String> options = NeteaseReqOptsBuilder.weapi(); String mvBody = SdkCommon.ncRequest(Method.POST, MV_URL_API, String.format("{\"id\":\"%s\",\"r\":\"%s\"}", id, quality), options) .executeAsync() .body(); JSONObject mvJson = JSONObject.parseObject(mvBody); JSONObject data = mvJson.getJSONObject("data"); String url = data.getString("url"); if (StringUtil.notEmpty(url)) return url; } } // 酷狗 else if (source == NetMusicSource.KG) { String mvBody = HttpRequest.get(String.format(MV_URL_KG_API, id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("mvdata"); // 高画质优先 JSONObject mvJson = VideoQuality.quality <= VideoQuality.FHD ? data.getJSONObject("rq") : null; if (JsonUtil.isEmpty(mvJson)) mvJson = VideoQuality.quality <= VideoQuality.HD ? data.getJSONObject("sq") : null; if (JsonUtil.isEmpty(mvJson)) mvJson = VideoQuality.quality <= VideoQuality.SD ? data.getJSONObject("hd") : null; if (JsonUtil.isEmpty(mvJson)) mvJson = VideoQuality.quality <= VideoQuality.SD ? data.getJSONObject("sd") : null; if (JsonUtil.isEmpty(mvJson)) mvJson = data.getJSONObject("le"); return mvJson.getString("downurl"); // 部分参数缺失,继续使用旧接口 // Map<KugouReqOptEnum, Object> options = KugouReqOptsBuilder.androidGetWithKey(MV_URL_KG_API); // Map<String, Object> params = new TreeMap<>(); // params.put("backupdomain", 1); // params.put("cmd", 123); // params.put("ext", "mp4"); // params.put("ismp3", 0); // params.put("hash", id); // params.put("pid", 1); // params.put("type", 1); // String mvBody = SdkCommon.kgRequest(params, null, options) // .header("x-router", "trackermv.kugou.com") // .executeAsync() // .body(); // JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data").getJSONObject(id.toLowerCase()); // return data.getString("downurl"); } // QQ else if (source == NetMusicSource.QQ) { String mvBody = HttpRequest.post(SdkCommon.QQ_MAIN_API) .body(String.format("{\"getMvUrl\":{\"module\":\"gosrf.Stream.MvUrlProxy\",\"method\":\"GetMvUrls\"," + "\"param\":{\"vids\":[\"%s\"],\"request_typet\":10001}}}", id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("getMvUrl").getJSONObject("data").getJSONObject(id); JSONArray mp4Array = data.getJSONArray("mp4"); String quality; String[] qs = {"50", "40", "30", "20", "10"}; switch (VideoQuality.quality) { case VideoQuality.UHD: quality = "50"; break; case VideoQuality.FHD: quality = "40"; break; case VideoQuality.HD: quality = "30"; break; case VideoQuality.SD: quality = "20"; break; default: quality = "10"; break; } for (int i = mp4Array.size() - 1; i >= 0; i--) { JSONObject urlJson = mp4Array.getJSONObject(i); if (ArrayUtil.indexOf(qs, quality) > ArrayUtil.indexOf(qs, urlJson.getString("filetype"))) continue; JSONArray freeFlowUrl = urlJson.getJSONArray("freeflow_url"); if (JsonUtil.isEmpty(freeFlowUrl)) continue; return freeFlowUrl.getString(freeFlowUrl.size() - 1); } } // 酷我 else if (source == NetMusicSource.KW) { String mvBody = SdkCommon.kwRequest(String.format(MV_URL_KW_API, id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data"); if (JsonUtil.notEmpty(data)) return data.getString("url"); } // 咪咕 (暂时没有 MV url 的获取方式) else if (source == NetMusicSource.MG) { } // 千千 else if (source == NetMusicSource.QI) { String mvBody = SdkCommon.qiRequest(String.format(MV_URL_QI_API, id, System.currentTimeMillis())) .executeAsync() .body(); JSONArray data = JSONObject.parseObject(mvBody).getJSONArray("data"); JSONArray urlArray = data.getJSONObject(0).getJSONArray("allRate"); String quality; String[] qs = {"r2k", "r1080", "r720", "r480", "r360"}; switch (VideoQuality.quality) { case VideoQuality.UHD: quality = "r2k"; break; case VideoQuality.FHD: quality = "r1080"; break; case VideoQuality.HD: quality = "r720"; break; case VideoQuality.SD: quality = "r480"; break; default: quality = "r360"; break; } for (int i = 0, s = urlArray.size(); i < s; i++) { JSONObject urlJson = urlArray.getJSONObject(i); if (ArrayUtil.indexOf(qs, quality) > ArrayUtil.indexOf(qs, urlJson.getString("resolution"))) continue; return urlJson.getString("path"); } } // 5sing else if (source == NetMusicSource.FS) { String mvBody = HttpRequest.get(String.format(MV_URL_FS_API, id)) .executeAsync() .body(); JSONArray urlArray = JSONObject.parseObject(mvBody).getJSONArray("data"); String quality; String[] qs = {"超清", "高清", "标清"}; switch (VideoQuality.quality) { case VideoQuality.UHD: case VideoQuality.FHD: case VideoQuality.HD: quality = "超清"; break; case VideoQuality.SD: quality = "高清"; break; default: quality = "标清"; break; } for (int i = 0, s = urlArray.size(); i < s; i++) { JSONObject urlJson = urlArray.getJSONObject(i); if (ArrayUtil.indexOf(qs, quality) > ArrayUtil.indexOf(qs, urlJson.getString("title"))) continue; return urlJson.getString("url"); } } // 好看 else if (source == NetMusicSource.HK) { String mvBody = HttpRequest.get(String.format(MV_URL_HK_API, id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data"); JSONArray urlArray = data.getJSONObject("apiData").getJSONObject("curVideoMeta").getJSONArray("clarityUrl"); String quality; String[] qs = {"1080p", "sc", "hd", "sd"}; switch (VideoQuality.quality) { case VideoQuality.UHD: case VideoQuality.FHD: quality = "1080p"; break; case VideoQuality.HD: quality = "sc"; break; case VideoQuality.SD: quality = "hd"; break; default: quality = "sd"; break; } for (int i = urlArray.size() - 1; i >= 0; i--) { JSONObject urlJson = urlArray.getJSONObject(i); if (ArrayUtil.indexOf(qs, quality) > ArrayUtil.indexOf(qs, urlJson.getString("key"))) continue; return urlJson.getString("url"); } } // 哔哩哔哩 else if (source == NetMusicSource.BI) { // 先通过 bvid 获取 cid if (StringUtil.isEmpty(id)) { String cidBody = HttpRequest.get(String.format(VIDEO_CID_BI_API, bvId)) .cookie(SdkCommon.BI_COOKIE) .executeAsync() .body(); mvInfo.setId(id = JSONObject.parseObject(cidBody).getJSONArray("data").getJSONObject(0).getString("cid")); } String quality; switch (VideoQuality.quality) { case VideoQuality.UHD: case VideoQuality.FHD: quality = "116"; break; case VideoQuality.HD: quality = "74"; break; case VideoQuality.SD: quality = "32"; break; default: quality = "16"; break; } String mvBody = HttpRequest.get(String.format(VIDEO_URL_BI_API, bvId, id, quality)) .cookie(SdkCommon.BI_COOKIE) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data"); JSONArray urlArray = data.getJSONArray("durl"); return urlArray.getJSONObject(0).getString("url"); } // 音悦台 else if (source == NetMusicSource.YY) { String mvBody = HttpRequest.get(String.format(MV_URL_YY_API, id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data"); JSONArray urlArray = data.getJSONObject("fullClip").getJSONArray("urls"); for (int i = 0, s = urlArray.size(); i < s; i++) { JSONObject urlJson = urlArray.getJSONObject(i); int streamType = urlJson.getIntValue("streamType"); if (VideoQuality.quality <= VideoQuality.FHD && streamType <= 1 || VideoQuality.quality > VideoQuality.FHD && streamType > 1) return urlJson.getString("url"); } } // 发姐 else if (source == NetMusicSource.FA) { String mvBody = HttpRequest.get(String.format(VIDEO_URL_FA_API, id)) .executeAsync() .body(); Document doc = Jsoup.parse(mvBody); Elements vs = doc.select("video source"); if (vs.isEmpty()) vs = doc.select("video"); if (!vs.isEmpty()) return StringUtil.urlEncodeBlank(vs.attr("src")); } // 李志 else if (source == NetMusicSource.LZ) { String mvBody = HttpRequest.get(String.format(VIDEO_URL_LZ_API, id)) .executeAsync() .body(); Document doc = Jsoup.parse(mvBody); Elements video = doc.select("video"); return StringUtil.urlEncodeBlank(video.attr("src")); } return ""; } }
AffectionParadise/LightMusic
src/main/java/net/doge/sdk/entity/mv/info/MvUrlReq.java
4,364
// 音悦台
line_comment
zh-cn
package net.doge.sdk.entity.mv.info; import cn.hutool.http.HttpRequest; import cn.hutool.http.Method; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; import net.doge.constant.model.MvInfoType; import net.doge.constant.model.NetMusicSource; import net.doge.constant.system.VideoQuality; import net.doge.model.entity.NetMvInfo; import net.doge.sdk.common.SdkCommon; import net.doge.sdk.common.opt.nc.NeteaseReqOptEnum; import net.doge.sdk.common.opt.nc.NeteaseReqOptsBuilder; import net.doge.util.collection.ArrayUtil; import net.doge.util.common.JsonUtil; import net.doge.util.common.StringUtil; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.util.Map; public class MvUrlReq { private static MvUrlReq instance; private MvUrlReq() { } public static MvUrlReq getInstance() { if (instance == null) instance = new MvUrlReq(); return instance; } // mlog id 转视频 id API private final String MLOG_TO_VIDEO_API = "https://music.163.com/weapi/mlog/video/convert/id"; // MV 视频链接 API private final String MV_URL_API = "https://music.163.com/weapi/song/enhance/play/mv/url"; // 视频链接 API private final String VIDEO_URL_API = "https://music.163.com/weapi/cloudvideo/playurl"; // Mlog 链接 API // private final String MLOG_URL_API = SdkCommon.PREFIX + "/mlog/url?id=%s"; // MV 视频链接获取 API (酷狗) private final String MV_URL_KG_API = "http://m.kugou.com/app/i/mv.php?cmd=100&hash=%s&ismp3=1&ext=mp4"; // private final String MV_URL_KG_API = "/v2/interface/index"; // MV 视频链接获取 API (酷我) private final String MV_URL_KW_API = "https://kuwo.cn/api/v1/www/music/playUrl?mid=%s&type=mv&httpsStatus=1"; // MV 视频链接获取 API (千千) private final String MV_URL_QI_API = "https://music.91q.com/v1/video/info?appid=16073360&assetCode=%s&timestamp=%s"; // MV 视频链接获取 API (5sing) private final String MV_URL_FS_API = "http://service.5sing.kugou.com/mv/play?mvId=%s"; // MV 视频链接获取 API (好看) private final String MV_URL_HK_API = "https://haokan.baidu.com/v?vid=%s&_format=json"; // 视频 bvid 获取 cid (哔哩哔哩) private final String VIDEO_CID_BI_API = "https://api.bilibili.com/x/player/pagelist?bvid=%s"; // MV 视频链接获取 API (哔哩哔哩) private final String VIDEO_URL_BI_API = "https://api.bilibili.com/x/player/playurl?bvid=%s&cid=%s&qn=%s"; // MV 视频链接获取 API (哔哩哔哩) private final String MV_URL_YY_API = "https://video-api.yinyuetai.com/video/get?id=%s"; // 视频链接获取 API (发姐) private final String VIDEO_URL_FA_API = "https://www.chatcyf.com/topics/%s/"; // 视频链接获取 API (李志) private final String VIDEO_URL_LZ_API = "https://www.lizhinb.com/live/%s/"; /** * 根据 MV id 获取 MV 视频链接 */ public String fetchMvUrl(NetMvInfo mvInfo) { int source = mvInfo.getSource(); String id = mvInfo.getId(); String bvId = mvInfo.getBvid(); boolean isVideo = mvInfo.isVideo(); boolean isMlog = mvInfo.isMlog(); // 网易云 if (source == NetMusicSource.NC) { String quality; switch (VideoQuality.quality) { case VideoQuality.UHD: case VideoQuality.FHD: quality = "1080"; break; case VideoQuality.HD: quality = "720"; break; case VideoQuality.SD: quality = "480"; break; default: quality = "240"; break; } if (isVideo || isMlog) { // Mlog 需要先获取视频 id,并转为视频类型 if (isMlog) { Map<NeteaseReqOptEnum, String> options = NeteaseReqOptsBuilder.weapi(); String body = SdkCommon.ncRequest(Method.POST, MLOG_TO_VIDEO_API, String.format("{\"mlogId\":\"%s\"}", id), options) .executeAsync() .body(); id = JSONObject.parseObject(body).getString("data"); mvInfo.setId(id); mvInfo.setType(MvInfoType.VIDEO); } Map<NeteaseReqOptEnum, String> options = NeteaseReqOptsBuilder.weapi(); String mvBody = SdkCommon.ncRequest(Method.POST, VIDEO_URL_API, String.format("{\"ids\":\"['%s']\",\"resolution\":\"%s\"}", id, quality), options) .executeAsync() .body(); JSONObject mvJson = JSONObject.parseObject(mvBody); JSONArray urls = mvJson.getJSONArray("urls"); String url = urls.getJSONObject(0).getString("url"); if (StringUtil.notEmpty(url)) return url; } // else if (isMlog) { // String mvBody = HttpRequest.get(String.format(MLOG_URL_API, id)) // .executeAsync() // .body(); // JSONObject mvJson = JSONObject.parseObject(mvBody); // JSONArray urls = mvJson.getJSONObject("data") // .getJSONObject("resource") // .getJSONObject("content") // .getJSONObject("video") // .getJSONArray("urlInfos"); // String url = null; // int r = 0; // for (int i = 0, s = urls.size(); i < s; i++) { // JSONObject urlJson = urls.getJSONObject(i); // int r1 = urlJson.getIntValue("r"); // if (r < r1) { // r = r1; // url = urlJson.getString("url"); // } // } // if (StringUtil.notEmpty(url)) return url; // } else { Map<NeteaseReqOptEnum, String> options = NeteaseReqOptsBuilder.weapi(); String mvBody = SdkCommon.ncRequest(Method.POST, MV_URL_API, String.format("{\"id\":\"%s\",\"r\":\"%s\"}", id, quality), options) .executeAsync() .body(); JSONObject mvJson = JSONObject.parseObject(mvBody); JSONObject data = mvJson.getJSONObject("data"); String url = data.getString("url"); if (StringUtil.notEmpty(url)) return url; } } // 酷狗 else if (source == NetMusicSource.KG) { String mvBody = HttpRequest.get(String.format(MV_URL_KG_API, id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("mvdata"); // 高画质优先 JSONObject mvJson = VideoQuality.quality <= VideoQuality.FHD ? data.getJSONObject("rq") : null; if (JsonUtil.isEmpty(mvJson)) mvJson = VideoQuality.quality <= VideoQuality.HD ? data.getJSONObject("sq") : null; if (JsonUtil.isEmpty(mvJson)) mvJson = VideoQuality.quality <= VideoQuality.SD ? data.getJSONObject("hd") : null; if (JsonUtil.isEmpty(mvJson)) mvJson = VideoQuality.quality <= VideoQuality.SD ? data.getJSONObject("sd") : null; if (JsonUtil.isEmpty(mvJson)) mvJson = data.getJSONObject("le"); return mvJson.getString("downurl"); // 部分参数缺失,继续使用旧接口 // Map<KugouReqOptEnum, Object> options = KugouReqOptsBuilder.androidGetWithKey(MV_URL_KG_API); // Map<String, Object> params = new TreeMap<>(); // params.put("backupdomain", 1); // params.put("cmd", 123); // params.put("ext", "mp4"); // params.put("ismp3", 0); // params.put("hash", id); // params.put("pid", 1); // params.put("type", 1); // String mvBody = SdkCommon.kgRequest(params, null, options) // .header("x-router", "trackermv.kugou.com") // .executeAsync() // .body(); // JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data").getJSONObject(id.toLowerCase()); // return data.getString("downurl"); } // QQ else if (source == NetMusicSource.QQ) { String mvBody = HttpRequest.post(SdkCommon.QQ_MAIN_API) .body(String.format("{\"getMvUrl\":{\"module\":\"gosrf.Stream.MvUrlProxy\",\"method\":\"GetMvUrls\"," + "\"param\":{\"vids\":[\"%s\"],\"request_typet\":10001}}}", id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("getMvUrl").getJSONObject("data").getJSONObject(id); JSONArray mp4Array = data.getJSONArray("mp4"); String quality; String[] qs = {"50", "40", "30", "20", "10"}; switch (VideoQuality.quality) { case VideoQuality.UHD: quality = "50"; break; case VideoQuality.FHD: quality = "40"; break; case VideoQuality.HD: quality = "30"; break; case VideoQuality.SD: quality = "20"; break; default: quality = "10"; break; } for (int i = mp4Array.size() - 1; i >= 0; i--) { JSONObject urlJson = mp4Array.getJSONObject(i); if (ArrayUtil.indexOf(qs, quality) > ArrayUtil.indexOf(qs, urlJson.getString("filetype"))) continue; JSONArray freeFlowUrl = urlJson.getJSONArray("freeflow_url"); if (JsonUtil.isEmpty(freeFlowUrl)) continue; return freeFlowUrl.getString(freeFlowUrl.size() - 1); } } // 酷我 else if (source == NetMusicSource.KW) { String mvBody = SdkCommon.kwRequest(String.format(MV_URL_KW_API, id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data"); if (JsonUtil.notEmpty(data)) return data.getString("url"); } // 咪咕 (暂时没有 MV url 的获取方式) else if (source == NetMusicSource.MG) { } // 千千 else if (source == NetMusicSource.QI) { String mvBody = SdkCommon.qiRequest(String.format(MV_URL_QI_API, id, System.currentTimeMillis())) .executeAsync() .body(); JSONArray data = JSONObject.parseObject(mvBody).getJSONArray("data"); JSONArray urlArray = data.getJSONObject(0).getJSONArray("allRate"); String quality; String[] qs = {"r2k", "r1080", "r720", "r480", "r360"}; switch (VideoQuality.quality) { case VideoQuality.UHD: quality = "r2k"; break; case VideoQuality.FHD: quality = "r1080"; break; case VideoQuality.HD: quality = "r720"; break; case VideoQuality.SD: quality = "r480"; break; default: quality = "r360"; break; } for (int i = 0, s = urlArray.size(); i < s; i++) { JSONObject urlJson = urlArray.getJSONObject(i); if (ArrayUtil.indexOf(qs, quality) > ArrayUtil.indexOf(qs, urlJson.getString("resolution"))) continue; return urlJson.getString("path"); } } // 5sing else if (source == NetMusicSource.FS) { String mvBody = HttpRequest.get(String.format(MV_URL_FS_API, id)) .executeAsync() .body(); JSONArray urlArray = JSONObject.parseObject(mvBody).getJSONArray("data"); String quality; String[] qs = {"超清", "高清", "标清"}; switch (VideoQuality.quality) { case VideoQuality.UHD: case VideoQuality.FHD: case VideoQuality.HD: quality = "超清"; break; case VideoQuality.SD: quality = "高清"; break; default: quality = "标清"; break; } for (int i = 0, s = urlArray.size(); i < s; i++) { JSONObject urlJson = urlArray.getJSONObject(i); if (ArrayUtil.indexOf(qs, quality) > ArrayUtil.indexOf(qs, urlJson.getString("title"))) continue; return urlJson.getString("url"); } } // 好看 else if (source == NetMusicSource.HK) { String mvBody = HttpRequest.get(String.format(MV_URL_HK_API, id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data"); JSONArray urlArray = data.getJSONObject("apiData").getJSONObject("curVideoMeta").getJSONArray("clarityUrl"); String quality; String[] qs = {"1080p", "sc", "hd", "sd"}; switch (VideoQuality.quality) { case VideoQuality.UHD: case VideoQuality.FHD: quality = "1080p"; break; case VideoQuality.HD: quality = "sc"; break; case VideoQuality.SD: quality = "hd"; break; default: quality = "sd"; break; } for (int i = urlArray.size() - 1; i >= 0; i--) { JSONObject urlJson = urlArray.getJSONObject(i); if (ArrayUtil.indexOf(qs, quality) > ArrayUtil.indexOf(qs, urlJson.getString("key"))) continue; return urlJson.getString("url"); } } // 哔哩哔哩 else if (source == NetMusicSource.BI) { // 先通过 bvid 获取 cid if (StringUtil.isEmpty(id)) { String cidBody = HttpRequest.get(String.format(VIDEO_CID_BI_API, bvId)) .cookie(SdkCommon.BI_COOKIE) .executeAsync() .body(); mvInfo.setId(id = JSONObject.parseObject(cidBody).getJSONArray("data").getJSONObject(0).getString("cid")); } String quality; switch (VideoQuality.quality) { case VideoQuality.UHD: case VideoQuality.FHD: quality = "116"; break; case VideoQuality.HD: quality = "74"; break; case VideoQuality.SD: quality = "32"; break; default: quality = "16"; break; } String mvBody = HttpRequest.get(String.format(VIDEO_URL_BI_API, bvId, id, quality)) .cookie(SdkCommon.BI_COOKIE) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data"); JSONArray urlArray = data.getJSONArray("durl"); return urlArray.getJSONObject(0).getString("url"); } // 音悦 <SUF> else if (source == NetMusicSource.YY) { String mvBody = HttpRequest.get(String.format(MV_URL_YY_API, id)) .executeAsync() .body(); JSONObject data = JSONObject.parseObject(mvBody).getJSONObject("data"); JSONArray urlArray = data.getJSONObject("fullClip").getJSONArray("urls"); for (int i = 0, s = urlArray.size(); i < s; i++) { JSONObject urlJson = urlArray.getJSONObject(i); int streamType = urlJson.getIntValue("streamType"); if (VideoQuality.quality <= VideoQuality.FHD && streamType <= 1 || VideoQuality.quality > VideoQuality.FHD && streamType > 1) return urlJson.getString("url"); } } // 发姐 else if (source == NetMusicSource.FA) { String mvBody = HttpRequest.get(String.format(VIDEO_URL_FA_API, id)) .executeAsync() .body(); Document doc = Jsoup.parse(mvBody); Elements vs = doc.select("video source"); if (vs.isEmpty()) vs = doc.select("video"); if (!vs.isEmpty()) return StringUtil.urlEncodeBlank(vs.attr("src")); } // 李志 else if (source == NetMusicSource.LZ) { String mvBody = HttpRequest.get(String.format(VIDEO_URL_LZ_API, id)) .executeAsync() .body(); Document doc = Jsoup.parse(mvBody); Elements video = doc.select("video"); return StringUtil.urlEncodeBlank(video.attr("src")); } return ""; } }
1
66404_8
package com.gin.pixiv.response.body.user; import lombok.Getter; import lombok.Setter; /** * 用户完整信息字段 * @author : ginstone * @version : v1.0.0 * @since : 2023/3/30 09:57 */ @Getter @Setter public class UserInfoBodyFullData { /** * 是否可以私信 */ Boolean canSendMessage; /** * 个人简介(备注) */ String comment; /** * 个人简介(备注) HTML格式 */ String commentHtml; /** * 是否回关 */ Boolean followedBack; /** * ta关注的人数 */ Integer following; /** * 所属地区 */ Region region; /** * 其他社交媒体 */ Social social; /** * 个人主页 */ String webpage; /** * 创作环境 */ WorkSpace workspace; @Getter @Setter static class Region { String name; /** * 地方行政区域 */ String prefecture; String privacyLevel; String region; } /** * 其他社交媒体 */ @Getter @Setter static class Social { SocialUrl pawoo; SocialUrl twitter; } @Getter @Setter static class SocialUrl { String url; } @Getter @Setter static class WorkSpace { /** * 椅子 */ String userWorkspaceChair; /** * 桌面大小 */ String userWorkspaceDesk; /** * 桌面物品 */ String userWorkspaceDesktop; /** * 显示器 */ String userWorkspaceMonitor; /** * 操作系统 */ String userWorkspacePc; /** * 数位板 */ String userWorkspaceTablet; /** * 软件 */ String userWorkspaceTool; } }
AgMonk/pixiv-utils
src/main/java/com/gin/pixiv/response/body/user/UserInfoBodyFullData.java
460
/** * 个人主页 */
block_comment
zh-cn
package com.gin.pixiv.response.body.user; import lombok.Getter; import lombok.Setter; /** * 用户完整信息字段 * @author : ginstone * @version : v1.0.0 * @since : 2023/3/30 09:57 */ @Getter @Setter public class UserInfoBodyFullData { /** * 是否可以私信 */ Boolean canSendMessage; /** * 个人简介(备注) */ String comment; /** * 个人简介(备注) HTML格式 */ String commentHtml; /** * 是否回关 */ Boolean followedBack; /** * ta关注的人数 */ Integer following; /** * 所属地区 */ Region region; /** * 其他社交媒体 */ Social social; /** * 个人主 <SUF>*/ String webpage; /** * 创作环境 */ WorkSpace workspace; @Getter @Setter static class Region { String name; /** * 地方行政区域 */ String prefecture; String privacyLevel; String region; } /** * 其他社交媒体 */ @Getter @Setter static class Social { SocialUrl pawoo; SocialUrl twitter; } @Getter @Setter static class SocialUrl { String url; } @Getter @Setter static class WorkSpace { /** * 椅子 */ String userWorkspaceChair; /** * 桌面大小 */ String userWorkspaceDesk; /** * 桌面物品 */ String userWorkspaceDesktop; /** * 显示器 */ String userWorkspaceMonitor; /** * 操作系统 */ String userWorkspacePc; /** * 数位板 */ String userWorkspaceTablet; /** * 软件 */ String userWorkspaceTool; } }
0
61987_8
package com.dstz.form.generator; import org.jsoup.nodes.Element; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.dstz.base.api.exception.BusinessException; import com.dstz.base.core.util.StringUtil; import com.dstz.base.core.util.ThreadMapUtil; import com.dstz.bus.api.constant.BusColumnCtrlType; import com.dstz.bus.api.constant.BusTableRelType; import com.dstz.bus.api.model.IBusTableRel; import com.dstz.bus.api.model.IBusinessColumn; /** * 自定义表单控件生成器<br> * input select radio dic 等等的生成<br> * @author jeff */ @Component public class MobileFormElementGenerator extends AbsFormElementGenerator{ public String getColumn(IBusinessColumn column,IBusTableRel relation) { if("1".equals("1")) { return super.getColumn(column, relation); } BusColumnCtrlType columnType = BusColumnCtrlType.getByKey(column.getCtrl().getType()); String boCode = relation.getBusObj().getKey(); ThreadMapUtil.put("boCode", boCode); ThreadMapUtil.put("relation", relation); return getColumnOnetext(column); } private void handleVModel(Element element,IBusinessColumn column) { String boCode = (String) ThreadMapUtil.get("boCode"); IBusTableRel relation = (IBusTableRel) ThreadMapUtil.get("relation"); //如果是多行子表 if(relation.getType().equals(BusTableRelType.ONE_TO_MANY.getKey())) { element.attr("v-model",column.getTable().getKey() + "." + column.getKey()); return ; } element.attr("v-model",getScopePath(relation)+ "." + column.getKey()); //添加上 placeholder 的支持 String configStr = column.getCtrl().getConfig(); if (StringUtil.isEmpty(configStr)) { return; } JSONObject config = JSON.parseObject(configStr); Boolean placeholder = config.getBoolean("placeholder"); if(placeholder == null || !placeholder )return ; element.attr("placeholder", config.getString("placeholderText")); } protected String getColumnOnetext(IBusinessColumn column) { Element element = getElement("input").attr("type", "text").addClass("weui-input"); handleVModel(element, column); handlePermission(element, column); handleValidateRules(element, column); return element.toString(); } //<ab-date v-model="data.kjcs.sr" format="YYYY-MM-DD HH:mm:ss" ab-validate="{&quot;date&quot;:true}" desc="生日" v-ab-permission="permission.kjcs.cskj.sr"></ab-date> protected String getColumnDate(IBusinessColumn column) { Element element = getElement("ab-date"); handleVModel(element, column); handleValidateRules(element, column); handlePermission(element, column); element.attr(":ab-permission", getPermissionPath(column)); String configStr = column.getCtrl().getConfig(); if(StringUtil.isEmpty(configStr)) { throw new BusinessException(String.format("表【%s】日期字段 【%s】解析失败,配置信息不能为空", column.getTable().getKey(),column.getComment())); } String format = JSON.parseObject(configStr).getString("format"); //yyyy-MM-dd HH:mm:ss pc 移动端为:YYYY-MM-DD HH:mm element.attr("format",format.replace("yyyy", "YYYY").replace("dd", "DD").replace(":ss", "")); return element.toString(); } protected String getColumnDic(IBusinessColumn column) { Element element = getElement("ab-dict").attr("type", "text").addClass("input-div"); handleVModel(element, column); handleValidateRules(element, column); handlePermission(element, column); JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("key")) { throw new BusinessException(String.format("表【%s】数据字典 字段【%s】解析失败,alias 配置信息不能为空", column.getTable().getKey(),column.getComment())); } element.attr("dict-key", config.getString("key")); return element.toString(); } protected String getColumnIdentity(IBusinessColumn column) { Element element = getElement("input").attr("type", "text").addClass("weui-input"); handleVModel(element, column); handlePermission(element, column); handleValidateRules(element, column); JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("alias")) { throw new BusinessException(String.format("表【%s】流水号 字段【%s】解析失败,alias 配置信息不能为空", column.getTable().getKey(),column.getComment())); } element.attr("ab-serial-no", config.getString("alias")); return element.toString(); } protected String getColumnMultitext(IBusinessColumn column) { Element element = getElement("textarea").attr("type", "text").addClass("weui-textarea"); handleVModel(element, column); handlePermission(element, column); handleValidateRules(element, column); return element.toString(); } /** * <ab-checkbox v-model="data.kjcs.ah" v-ab-permission="permission.kjcs.cskj.ah" v-ab-validate="{}" desc="爱好"> <div slot-scope="scope"> <label class=" checkbox-inline"><input type="checkbox" name="testttt" v-model="scope.tempData.currentValue" value="y"/>羽毛器</label> <label class=" checkbox-inline"><input name="testttt" type="checkbox" v-model="scope.tempData.currentValue" value="l"/>篮球</label> <label class=" checkbox-inline"><input type="checkbox" name="testttt" v-model="scope.tempData.currentValue" value="s"/>游泳</label> </div> </ab-checkbox> */ protected String getColumnCheckBox(IBusinessColumn column) { JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("options")) { throw new BusinessException(String.format("表【%s】CheckBox 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment())); } Element checkbox = getElement("ab-checkbox"); handleVModel(checkbox, column); handleValidateRules(checkbox, column); handlePermission(checkbox,column); Element template = checkbox.appendElement("div").attr("slot-scope", "scope"); JSONArray options = config.getJSONArray("options"); for (int i = 0; i < options.size(); i++) { JSONObject option = options.getJSONObject(i); Element element = template.appendElement("label").addClass("checkbox-inline"); Element child = element.appendElement("input").attr("type", "checkbox"); child.attr("v-model", "scope.tempData.currentValue"); child.attr("value", option.getString("key")); child.attr("name",String.format("%s-%s-%s",(String) ThreadMapUtil.get("boCode"), column.getTable().getKey(),column.getName())); handlePermission(child,column); element.appendText(option.getString("txt")); } return checkbox.toString(); } protected String getColumnRadio(IBusinessColumn column) { JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("options")) { throw new BusinessException(String.format("表【%s】Radio 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment())); } Element permissionElement = getElement("div"); JSONArray options = config.getJSONArray("options"); for (int i = 0; i < options.size(); i++) { JSONObject option = options.getJSONObject(i); Element label = permissionElement.appendElement("label").addClass("radio-inline"); Element child = label.appendElement("input").attr("type", "radio"); handleVModel(child, column); child.attr("v-ab-permission", getPermissionPath(column)); handleValidateRules(child, column); child.attr("value", option.getString("key")); label.appendText(option.getString("txt")); } return permissionElement.toString(); } protected String getColumnSelect(IBusinessColumn column,Boolean isMultiple) { JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("options")) { throw new BusinessException(String.format("表【%s】Select 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment())); } Element permissionElement = getElement("select").addClass("weui-input"); handleVModel(permissionElement, column); permissionElement.attr("v-ab-permission",getPermissionPath(column)); handleValidateRules(permissionElement, column); if(isMultiple) { permissionElement.attr("multiple", "true"); } Element select = permissionElement.appendElement("option"); select.attr("value", ""); select.text("请选择"); JSONArray options = config.getJSONArray("options"); for (int i = 0; i < options.size(); i++) { JSONObject option = options.getJSONObject(i); Element element = permissionElement.appendElement("option"); element.attr("value", option.getString("key")); element.text(option.getString("txt")); } return permissionElement.toString(); } /** * <pre> * <ab-upload v-model="files" v-bind:permission="xxx"> * <a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary fa fa-upload">上传</a> * </ab-upload> * </pre> */ protected String getColumnFile(IBusinessColumn column) { Element element = getElement("ab-upload").attr("v-bind:permission", getPermissionPath(column)); handleVModel(element, column); element.append("<a href=\"javascript:;\" class=\"weui-btn weui-btn_mini weui-btn_primary fa fa-upload\">"+column.getComment()+"</a>"); return element.toString(); } // id="boCode-tableKey" ab-basic-permission="boCode.table.tableKey" ... public String getSubAttrs(IBusTableRel rel) { StringBuilder sb = new StringBuilder(); sb.append( " id="+"\""+ rel.getBusObj().getKey()+"-"+rel.getTableKey()+"\" "); //一对多的三层情况下弹框展示 if(rel.getType().equals(BusTableRelType.ONE_TO_MANY.getKey()) && !rel.getParent().getType().equals(BusTableRelType.MAIN.getKey())) { sb.append(" v-transfer-dom "); sb.append(" v-if=\"subTempData."+ rel.getTableKey() +"List\" "); } sb.append(" table-key=\""+rel.getTableKey()+"\" "); return sb.toString() ; } protected void handlePermission(Element element,IBusinessColumn column) { element.attr("v-ab-permission", getPermissionPath(column)); } protected void handleValidateRules(Element element,IBusinessColumn column) { super.handleValidateRules(element, column); element.attr("v-ab-validate", element.attr("ab-validate")); element.removeAttr("ab-validate"); } @Override public String getGeneratorName() { return "mobileGenerator"; } }
AgileBPM/agile-bpm-basic
bus-form/form/form-core/src/main/java/com/dstz/form/generator/MobileFormElementGenerator.java
3,013
//一对多的三层情况下弹框展示
line_comment
zh-cn
package com.dstz.form.generator; import org.jsoup.nodes.Element; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.dstz.base.api.exception.BusinessException; import com.dstz.base.core.util.StringUtil; import com.dstz.base.core.util.ThreadMapUtil; import com.dstz.bus.api.constant.BusColumnCtrlType; import com.dstz.bus.api.constant.BusTableRelType; import com.dstz.bus.api.model.IBusTableRel; import com.dstz.bus.api.model.IBusinessColumn; /** * 自定义表单控件生成器<br> * input select radio dic 等等的生成<br> * @author jeff */ @Component public class MobileFormElementGenerator extends AbsFormElementGenerator{ public String getColumn(IBusinessColumn column,IBusTableRel relation) { if("1".equals("1")) { return super.getColumn(column, relation); } BusColumnCtrlType columnType = BusColumnCtrlType.getByKey(column.getCtrl().getType()); String boCode = relation.getBusObj().getKey(); ThreadMapUtil.put("boCode", boCode); ThreadMapUtil.put("relation", relation); return getColumnOnetext(column); } private void handleVModel(Element element,IBusinessColumn column) { String boCode = (String) ThreadMapUtil.get("boCode"); IBusTableRel relation = (IBusTableRel) ThreadMapUtil.get("relation"); //如果是多行子表 if(relation.getType().equals(BusTableRelType.ONE_TO_MANY.getKey())) { element.attr("v-model",column.getTable().getKey() + "." + column.getKey()); return ; } element.attr("v-model",getScopePath(relation)+ "." + column.getKey()); //添加上 placeholder 的支持 String configStr = column.getCtrl().getConfig(); if (StringUtil.isEmpty(configStr)) { return; } JSONObject config = JSON.parseObject(configStr); Boolean placeholder = config.getBoolean("placeholder"); if(placeholder == null || !placeholder )return ; element.attr("placeholder", config.getString("placeholderText")); } protected String getColumnOnetext(IBusinessColumn column) { Element element = getElement("input").attr("type", "text").addClass("weui-input"); handleVModel(element, column); handlePermission(element, column); handleValidateRules(element, column); return element.toString(); } //<ab-date v-model="data.kjcs.sr" format="YYYY-MM-DD HH:mm:ss" ab-validate="{&quot;date&quot;:true}" desc="生日" v-ab-permission="permission.kjcs.cskj.sr"></ab-date> protected String getColumnDate(IBusinessColumn column) { Element element = getElement("ab-date"); handleVModel(element, column); handleValidateRules(element, column); handlePermission(element, column); element.attr(":ab-permission", getPermissionPath(column)); String configStr = column.getCtrl().getConfig(); if(StringUtil.isEmpty(configStr)) { throw new BusinessException(String.format("表【%s】日期字段 【%s】解析失败,配置信息不能为空", column.getTable().getKey(),column.getComment())); } String format = JSON.parseObject(configStr).getString("format"); //yyyy-MM-dd HH:mm:ss pc 移动端为:YYYY-MM-DD HH:mm element.attr("format",format.replace("yyyy", "YYYY").replace("dd", "DD").replace(":ss", "")); return element.toString(); } protected String getColumnDic(IBusinessColumn column) { Element element = getElement("ab-dict").attr("type", "text").addClass("input-div"); handleVModel(element, column); handleValidateRules(element, column); handlePermission(element, column); JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("key")) { throw new BusinessException(String.format("表【%s】数据字典 字段【%s】解析失败,alias 配置信息不能为空", column.getTable().getKey(),column.getComment())); } element.attr("dict-key", config.getString("key")); return element.toString(); } protected String getColumnIdentity(IBusinessColumn column) { Element element = getElement("input").attr("type", "text").addClass("weui-input"); handleVModel(element, column); handlePermission(element, column); handleValidateRules(element, column); JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("alias")) { throw new BusinessException(String.format("表【%s】流水号 字段【%s】解析失败,alias 配置信息不能为空", column.getTable().getKey(),column.getComment())); } element.attr("ab-serial-no", config.getString("alias")); return element.toString(); } protected String getColumnMultitext(IBusinessColumn column) { Element element = getElement("textarea").attr("type", "text").addClass("weui-textarea"); handleVModel(element, column); handlePermission(element, column); handleValidateRules(element, column); return element.toString(); } /** * <ab-checkbox v-model="data.kjcs.ah" v-ab-permission="permission.kjcs.cskj.ah" v-ab-validate="{}" desc="爱好"> <div slot-scope="scope"> <label class=" checkbox-inline"><input type="checkbox" name="testttt" v-model="scope.tempData.currentValue" value="y"/>羽毛器</label> <label class=" checkbox-inline"><input name="testttt" type="checkbox" v-model="scope.tempData.currentValue" value="l"/>篮球</label> <label class=" checkbox-inline"><input type="checkbox" name="testttt" v-model="scope.tempData.currentValue" value="s"/>游泳</label> </div> </ab-checkbox> */ protected String getColumnCheckBox(IBusinessColumn column) { JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("options")) { throw new BusinessException(String.format("表【%s】CheckBox 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment())); } Element checkbox = getElement("ab-checkbox"); handleVModel(checkbox, column); handleValidateRules(checkbox, column); handlePermission(checkbox,column); Element template = checkbox.appendElement("div").attr("slot-scope", "scope"); JSONArray options = config.getJSONArray("options"); for (int i = 0; i < options.size(); i++) { JSONObject option = options.getJSONObject(i); Element element = template.appendElement("label").addClass("checkbox-inline"); Element child = element.appendElement("input").attr("type", "checkbox"); child.attr("v-model", "scope.tempData.currentValue"); child.attr("value", option.getString("key")); child.attr("name",String.format("%s-%s-%s",(String) ThreadMapUtil.get("boCode"), column.getTable().getKey(),column.getName())); handlePermission(child,column); element.appendText(option.getString("txt")); } return checkbox.toString(); } protected String getColumnRadio(IBusinessColumn column) { JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("options")) { throw new BusinessException(String.format("表【%s】Radio 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment())); } Element permissionElement = getElement("div"); JSONArray options = config.getJSONArray("options"); for (int i = 0; i < options.size(); i++) { JSONObject option = options.getJSONObject(i); Element label = permissionElement.appendElement("label").addClass("radio-inline"); Element child = label.appendElement("input").attr("type", "radio"); handleVModel(child, column); child.attr("v-ab-permission", getPermissionPath(column)); handleValidateRules(child, column); child.attr("value", option.getString("key")); label.appendText(option.getString("txt")); } return permissionElement.toString(); } protected String getColumnSelect(IBusinessColumn column,Boolean isMultiple) { JSONObject config = JSON.parseObject(column.getCtrl().getConfig()); if(!config.containsKey("options")) { throw new BusinessException(String.format("表【%s】Select 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment())); } Element permissionElement = getElement("select").addClass("weui-input"); handleVModel(permissionElement, column); permissionElement.attr("v-ab-permission",getPermissionPath(column)); handleValidateRules(permissionElement, column); if(isMultiple) { permissionElement.attr("multiple", "true"); } Element select = permissionElement.appendElement("option"); select.attr("value", ""); select.text("请选择"); JSONArray options = config.getJSONArray("options"); for (int i = 0; i < options.size(); i++) { JSONObject option = options.getJSONObject(i); Element element = permissionElement.appendElement("option"); element.attr("value", option.getString("key")); element.text(option.getString("txt")); } return permissionElement.toString(); } /** * <pre> * <ab-upload v-model="files" v-bind:permission="xxx"> * <a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary fa fa-upload">上传</a> * </ab-upload> * </pre> */ protected String getColumnFile(IBusinessColumn column) { Element element = getElement("ab-upload").attr("v-bind:permission", getPermissionPath(column)); handleVModel(element, column); element.append("<a href=\"javascript:;\" class=\"weui-btn weui-btn_mini weui-btn_primary fa fa-upload\">"+column.getComment()+"</a>"); return element.toString(); } // id="boCode-tableKey" ab-basic-permission="boCode.table.tableKey" ... public String getSubAttrs(IBusTableRel rel) { StringBuilder sb = new StringBuilder(); sb.append( " id="+"\""+ rel.getBusObj().getKey()+"-"+rel.getTableKey()+"\" "); //一对 <SUF> if(rel.getType().equals(BusTableRelType.ONE_TO_MANY.getKey()) && !rel.getParent().getType().equals(BusTableRelType.MAIN.getKey())) { sb.append(" v-transfer-dom "); sb.append(" v-if=\"subTempData."+ rel.getTableKey() +"List\" "); } sb.append(" table-key=\""+rel.getTableKey()+"\" "); return sb.toString() ; } protected void handlePermission(Element element,IBusinessColumn column) { element.attr("v-ab-permission", getPermissionPath(column)); } protected void handleValidateRules(Element element,IBusinessColumn column) { super.handleValidateRules(element, column); element.attr("v-ab-validate", element.attr("ab-validate")); element.removeAttr("ab-validate"); } @Override public String getGeneratorName() { return "mobileGenerator"; } }
0