file_id
int64
1
66.7k
content
stringlengths
14
343k
repo
stringlengths
6
92
path
stringlengths
5
169
66,532
package kmeans; import java.util.ArrayList; import java.util.Random; /** * K均值聚类算法 */ public class Kmeans { /** * 分成多少簇 */ private int numOfCluster; /** * 迭代次数 */ private int timeOfIteration; /** * 数据集元素个数,即数据集的长度 */ private int dataSetLength; private ArrayList<float[]> dataSet; /** * 中心链表 */ private ArrayList<float[]> center; /** * 簇 */ private ArrayList<ArrayList<float[]>> cluster; /** * 误差平方和 */ private ArrayList<Float> sumOfErrorSquare; private Random random; public static final int DEFAULT_NUM_OF_CLUSTER = 6; /** * float[] 数组的用于计算距离的长度, */ private int calculationLength = 6; /** * 设置需分组的原始数据集 * * @param dataSet */ public void setDataSet(ArrayList<float[]> dataSet) { this.dataSet = dataSet; } /** * 获取结果分组 * * @return 结果集 */ public ArrayList<ArrayList<float[]>> getCluster() { return cluster; } /** * 构造函数,传入需要分成的簇数量 * * @param numOfCluster 簇数量,若numOfCluster<=0时,设置为1,若numOfCluster大于数据源的长度时,置为数据源的长度 */ public Kmeans(int numOfCluster) { if (numOfCluster <= 0) { numOfCluster = DEFAULT_NUM_OF_CLUSTER; } this.numOfCluster = numOfCluster; } /** * 初始化 */ private void init() { timeOfIteration = 0; random = new Random(); //如果调用者未初始化数据集,则采用内部测试数据集 if (dataSet == null || dataSet.size() == 0) { throw new RuntimeException("数据集不能为空"); } dataSetLength = dataSet.size(); //若numOfCluster大于数据源的长度时,置为数据源的长度 if (numOfCluster > dataSetLength) { numOfCluster = dataSetLength; } center = initCenters(); cluster = initCluster(); sumOfErrorSquare = new ArrayList<>(); } /** * 初始化中心数据链表,分成多少簇就有多少个中心点 * * @return 中心点集 */ private ArrayList<float[]> initCenters() { ArrayList<float[]> center = new ArrayList<>(); int[] randoms = new int[numOfCluster]; boolean flag; int temp = random.nextInt(dataSetLength); randoms[0] = temp; //randoms数组中存放数据集的不同的下标 for (int i = 1; i < numOfCluster; i++) { flag = true; while (flag) { temp = random.nextInt(dataSetLength); int j = 0; for (j = 0; j < i; j++) { if (randoms[j] == temp) { break; } } if (j == i) { flag = false; } } randoms[i] = temp; } // 测试随机数生成情况 // for (int i = 0; i < numOfCluster; i++) { // System.out.println("test1:randoms[" + i + "]=" + randoms[i] + ":" + dataSet.get(randoms[i])[0] + "," + dataSet.get(randoms[i])[1] + "," + dataSet.get(randoms[i])[2] + "," + dataSet.get(randoms[i])[3] + "," + dataSet.get(randoms[i])[4] + "," + dataSet.get(randoms[i])[5]); // } // System.out.println(); for (int i = 0; i < numOfCluster; i++) { // 生成初始化中心链表 center.add(dataSet.get(randoms[i])); } return center; } /** * 初始化簇集合 * * @return 一个分为k簇的空数据的簇集合 */ private ArrayList<ArrayList<float[]>> initCluster() { ArrayList<ArrayList<float[]>> cluster = new ArrayList<>(); for (int i = 0; i < numOfCluster; i++) { cluster.add(new ArrayList<>()); } return cluster; } /** * 计算两个点之间的距离 * * @param element 点1 * @param center 点2 * @return 距离 */ private float distance(float[] element, float[] center) { float distance; float r = 0; for (int i = 0; i < calculationLength; i++) { r += (element[i] - center[i]) * (element[i] - center[i]); } distance = (float) Math.sqrt(r); return distance; } /** * 获取距离集合中最小距离的位置 * * @param distance 距离数组 * @return 最小距离在距离数组中的位置 * 加入班级人数限制 */ private int minDistance(float[] distance) { float minDistance = Float.MAX_VALUE; int minLocation = 0; for (int i = 0; i < distance.length; i++) { if (distance[i] <= minDistance) { minDistance = distance[i]; minLocation = i; } } return minLocation; } /** * 核心,将当前元素放到最小距离中心相关的簇中 */ private void clusterSet() { float[] distance = new float[numOfCluster]; for (int i = 0; i < dataSetLength; i++) { for (int j = 0; j < numOfCluster; j++) { // 计算每个点对聚类中心的距离,选取最小的 distance[j] = distance(dataSet.get(i), center.get(j)); } // 计算当前个体聚类最近的聚类中心 minLocation, 然后将当前个体加入聚类中心中 int minLocation = minDistance(distance); // 核心,将当前元素放到最小距离中心相关的簇中 cluster.get(minLocation).add(dataSet.get(i)); } } /** * 求两点误差平方的方法 * * @param element 点1 * @param center 点2 * @return 误差平方 */ private float errorSquare(float[] element, float[] center) { float r = 0; for (int i = 0; i < calculationLength; i++) { r += (element[i] - center[i]) * (element[i] - center[i]); } return r; } /** * 计算误差平方和准则函数方法 */ private void countRule() { float jcF = 0; for (int i = 0; i < cluster.size(); i++) { for (int j = 0; j < cluster.get(i).size(); j++) { jcF += errorSquare(cluster.get(i).get(j), center.get(i)); } } sumOfErrorSquare.add(jcF); } /** * 设置新的簇中心方法 */ private void setNewCenter() { for (int i = 0; i < numOfCluster; i++) { int n = cluster.get(i).size(); if (n != 0) { float[] newCenter = new float[calculationLength]; for (int j = 0; j < n; j++) { for (int k = 0; k < calculationLength; k++) { newCenter[k] += cluster.get(i).get(j)[k]; } // newCenter[0] += cluster.get(i).get(j)[0]; // newCenter[1] += cluster.get(i).get(j)[1]; // newCenter[2] += cluster.get(i).get(j)[2]; // newCenter[3] += cluster.get(i).get(j)[3]; // newCenter[4] += cluster.get(i).get(j)[4]; // newCenter[5] += cluster.get(i).get(j)[5]; } for (int k = 0; k < calculationLength; k++) { newCenter[k] = newCenter[k] / n; } // 设置一个平均值 // newCenter[0] = newCenter[0] / n; // newCenter[1] = newCenter[1] / n; // newCenter[2] = newCenter[2] / n; // newCenter[3] = newCenter[3] / n; // newCenter[4] = newCenter[4] / n; // newCenter[5] = newCenter[5] / n; center.set(i, newCenter); } } } /** * 打印数据,测试用 * * @param dataArray 数据集 * @param dataArrayName 数据集名称 */ public void printDataArray(ArrayList<float[]> dataArray, String dataArrayName) { for (int i = 0; i < dataArray.size(); i++) { System.out.println("print:" + dataArrayName + "[" + i + "]={" + dataArray.get(i)[0] + "," + dataArray.get(i)[1] + "," + dataArray.get(i)[2] + "," + dataArray.get(i)[3] + "," + dataArray.get(i)[4] + "," + dataArray.get(i)[5] + "}"); } System.out.println("==================================="); } /** * Kmeans算法核心过程方法 */ private void kmeans() { init(); // 循环分组,直到误差不变为止 while (true) { clusterSet(); countRule(); // 误差不变了,分组完成 if (timeOfIteration != 0) { if (sumOfErrorSquare.get(timeOfIteration) - sumOfErrorSquare.get(timeOfIteration - 1) == 0) { break; } } setNewCenter(); timeOfIteration++; cluster.clear(); cluster = initCluster(); } } /** * 执行算法 */ public void execute() { kmeans(); } public int getCalculationLength() { return calculationLength; } public void setCalculationLength(int calculationLength) { this.calculationLength = calculationLength; } }
zhangxin0/Split_class-Assign_schedule-algorithm
AssignClass/src/kmeans/Kmeans.java
66,533
package com.achang.eduservice.client; import com.achang.commonutils.R; import com.achang.eduservice.client.impl.VodClientImpl; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; /****** @author 阿昌 @create 2021-03-03 13:07 ******* */ @Component @FeignClient(value = "service-vod",fallback = VodClientImpl.class)//指定调用的服务名,前提要注册到nacos注册中心中 public interface VodClient { //根据视频id删除阿里云视频 @DeleteMapping("/eduvod/video/removeAliyunVideoById/{id}") public R removeAliyunVideoById(@PathVariable("id") String id); //根据多个视频id删除多个阿里云视频 @DeleteMapping("/eduvod/video/removeBatch") public R removeBatch(@RequestParam("videoIdList") List<String> videoIdList); }
qq995931576/guli-online
service/service_edu/src/main/java/com/achang/eduservice/client/VodClient.java
66,534
package cn.mkblog.huashelper.bean; import java.util.List; /** * 金山词霸每日一句 */ public class IcibaBean { /** * http://open.iciba.com/dsapi/ * sid : 2793 * tts : http://news.iciba.com/admin/tts/2017-11-25-day * content : Never say goodbye because saying goodbye means going away and going away means forgetting. * note : 永远都不要说再见,因为说再见意味着离开,离开意味着遗忘。 * love : 1650 * translation : 词霸小编:真正的忘记,并非不再想起,而是偶尔想起,心中却不再有波澜。 * picture : http://cdn.iciba.com/news/word/20171125.jpg * picture2 : http://cdn.iciba.com/news/word/big_20171125b.jpg * caption : 词霸每日一句 * dateline : 2017-11-25 * s_pv : 0 * sp_pv : 0 * tags : [{"id":null,"name":null}] * fenxiang_img : http://cdn.iciba.com/web/news/longweibo/imag/2017-11-25.jpg */ private String sid; private String tts; private String content; private String note; private String love; private String translation; private String picture; private String picture2; private String caption; private String dateline; private String s_pv; private String sp_pv; private String fenxiang_img; private List<TagsBean> tags; public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getTts() { return tts; } public void setTts(String tts) { this.tts = tts; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public String getLove() { return love; } public void setLove(String love) { this.love = love; } public String getTranslation() { return translation; } public void setTranslation(String translation) { this.translation = translation; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getPicture2() { return picture2; } public void setPicture2(String picture2) { this.picture2 = picture2; } public String getCaption() { return caption; } public void setCaption(String caption) { this.caption = caption; } public String getDateline() { return dateline; } public void setDateline(String dateline) { this.dateline = dateline; } public String getS_pv() { return s_pv; } public void setS_pv(String s_pv) { this.s_pv = s_pv; } public String getSp_pv() { return sp_pv; } public void setSp_pv(String sp_pv) { this.sp_pv = sp_pv; } public String getFenxiang_img() { return fenxiang_img; } public void setFenxiang_img(String fenxiang_img) { this.fenxiang_img = fenxiang_img; } public List<TagsBean> getTags() { return tags; } public void setTags(List<TagsBean> tags) { this.tags = tags; } public static class TagsBean { /** * id : null * name : null */ private Object id; private Object name; public Object getId() { return id; } public void setId(Object id) { this.id = id; } public Object getName() { return name; } public void setName(Object name) { this.name = name; } } }
mengkunsoft/HuasHelper
app/src/main/java/cn/mkblog/huashelper/bean/IcibaBean.java
66,535
package com.wenming.library; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Build; import android.os.SystemClock; import android.support.v7.app.NotificationCompat; import android.widget.RemoteViews; import android.widget.Toast; import java.util.ArrayList; @SuppressLint("NewApi") public class NotifyUtil { private static final int FLAG = Notification.FLAG_INSISTENT; int requestCode = (int) SystemClock.uptimeMillis(); private int NOTIFICATION_ID; private NotificationManager nm; private Notification notification; private NotificationCompat.Builder cBuilder; private Notification.Builder nBuilder; private Context mContext; public NotifyUtil(Context context, int ID) { this.NOTIFICATION_ID = ID; mContext = context; // 获取系统服务来初始化对象 nm = (NotificationManager) mContext .getSystemService(Activity.NOTIFICATION_SERVICE); cBuilder = new NotificationCompat.Builder(mContext); } /** * 设置在顶部通知栏中的各种信息 * * @param pendingIntent * @param smallIcon * @param ticker */ private void setCompatBuilder(PendingIntent pendingIntent, int smallIcon, String ticker, String title, String content, boolean sound, boolean vibrate, boolean lights) { // // 如果当前Activity启动在前台,则不开启新的Activity。 // intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // // 当设置下面PendingIntent.FLAG_UPDATE_CURRENT这个参数的时候,常常使得点击通知栏没效果,你需要给notification设置一个独一无二的requestCode // // 将Intent封装进PendingIntent中,点击通知的消息后,就会启动对应的程序 // PendingIntent pIntent = PendingIntent.getActivity(mContext, // requestCode, intent, FLAG); cBuilder.setContentIntent(pendingIntent);// 该通知要启动的Intent cBuilder.setSmallIcon(smallIcon);// 设置顶部状态栏的小图标 cBuilder.setTicker(ticker);// 在顶部状态栏中的提示信息 cBuilder.setContentTitle(title);// 设置通知中心的标题 cBuilder.setContentText(content);// 设置通知中心中的内容 cBuilder.setWhen(System.currentTimeMillis()); /* * 将AutoCancel设为true后,当你点击通知栏的notification后,它会自动被取消消失, * 不设置的话点击消息后也不清除,但可以滑动删除 */ cBuilder.setAutoCancel(true); // 将Ongoing设为true 那么notification将不能滑动删除 // notifyBuilder.setOngoing(true); /* * 从Android4.1开始,可以通过以下方法,设置notification的优先级, * 优先级越高的,通知排的越靠前,优先级低的,不会在手机最顶部的状态栏显示图标 */ cBuilder.setPriority(NotificationCompat.PRIORITY_MAX); /* * Notification.DEFAULT_ALL:铃声、闪光、震动均系统默认。 * Notification.DEFAULT_SOUND:系统默认铃声。 * Notification.DEFAULT_VIBRATE:系统默认震动。 * Notification.DEFAULT_LIGHTS:系统默认闪光。 * notifyBuilder.setDefaults(Notification.DEFAULT_ALL); */ int defaults = 0; if (sound) { defaults |= Notification.DEFAULT_SOUND; } if (vibrate) { defaults |= Notification.DEFAULT_VIBRATE; } if (lights) { defaults |= Notification.DEFAULT_LIGHTS; } cBuilder.setDefaults(defaults); } /** * 设置builder的信息,在用大文本时会用到这个 * * @param pendingIntent * @param smallIcon * @param ticker */ private void setBuilder(PendingIntent pendingIntent, int smallIcon, String ticker, boolean sound, boolean vibrate, boolean lights) { nBuilder = new Notification.Builder(mContext); // 如果当前Activity启动在前台,则不开启新的Activity。 // intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // PendingIntent pIntent = PendingIntent.getActivity(mContext, // requestCode, intent, FLAG); nBuilder.setContentIntent(pendingIntent); nBuilder.setSmallIcon(smallIcon); nBuilder.setTicker(ticker); nBuilder.setWhen(System.currentTimeMillis()); nBuilder.setPriority(NotificationCompat.PRIORITY_MAX); int defaults = 0; if (sound) { defaults |= Notification.DEFAULT_SOUND; } if (vibrate) { defaults |= Notification.DEFAULT_VIBRATE; } if (lights) { defaults |= Notification.DEFAULT_LIGHTS; } nBuilder.setDefaults(defaults); } /** * 普通的通知 * <p/> * 1. 侧滑即消失,下拉通知菜单则在通知菜单显示 * * @param pendingIntent * @param smallIcon * @param ticker * @param title * @param content */ public void notify_normal_singline(PendingIntent pendingIntent, int smallIcon, String ticker, String title, String content, boolean sound, boolean vibrate, boolean lights) { setCompatBuilder(pendingIntent, smallIcon, ticker, title, content, sound, vibrate, lights); sent(); } /** * 进行多项设置的通知(在小米上似乎不能设置大图标,系统默认大图标为应用图标) * * @param pendingIntent * @param smallIcon * @param ticker * @param title * @param content */ public void notify_mailbox(PendingIntent pendingIntent, int smallIcon, int largeIcon, ArrayList<String> messageList, String ticker, String title, String content, boolean sound, boolean vibrate, boolean lights) { setCompatBuilder(pendingIntent, smallIcon, ticker, title, content, sound, vibrate, lights); // 将Ongoing设为true 那么notification将不能滑动删除 //cBuilder.setOngoing(true); /** // 删除时 Intent deleteIntent = new Intent(mContext, DeleteService.class); int deleteCode = (int) SystemClock.uptimeMillis(); // 删除时开启一个服务 PendingIntent deletePendingIntent = PendingIntent.getService(mContext, deleteCode, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT); cBuilder.setDeleteIntent(deletePendingIntent); **/ Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), largeIcon); cBuilder.setLargeIcon(bitmap); cBuilder.setDefaults(Notification.DEFAULT_ALL);// 设置使用默认的声音 //cBuilder.setVibrate(new long[]{0, 100, 200, 300});// 设置自定义的振动 cBuilder.setAutoCancel(true); // builder.setSound(Uri.parse("file:///sdcard/click.mp3")); // 设置通知样式为收件箱样式,在通知中心中两指往外拉动,就能出线更多内容,但是很少见 //cBuilder.setNumber(messageList.size()); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); for (String msg : messageList) { inboxStyle.addLine(msg); } inboxStyle.setSummaryText("[" + messageList.size() + "条]" + title); cBuilder.setStyle(inboxStyle); sent(); } /** * 自定义视图的通知 * * @param remoteViews * @param pendingIntent * @param smallIcon * @param ticker */ public void notify_customview(RemoteViews remoteViews, PendingIntent pendingIntent, int smallIcon, String ticker, boolean sound, boolean vibrate, boolean lights) { setCompatBuilder(pendingIntent, smallIcon, ticker, null, null, sound, vibrate, lights); notification = cBuilder.build(); notification.contentView = remoteViews; // 发送该通知 nm.notify(NOTIFICATION_ID, notification); } /** * 可以容纳多行提示文本的通知信息 (因为在高版本的系统中才支持,所以要进行判断) * * @param pendingIntent * @param smallIcon * @param ticker * @param title * @param content */ public void notify_normail_moreline(PendingIntent pendingIntent, int smallIcon, String ticker, String title, String content, boolean sound, boolean vibrate, boolean lights) { final int sdk = Build.VERSION.SDK_INT; if (sdk < Build.VERSION_CODES.JELLY_BEAN) { notify_normal_singline(pendingIntent, smallIcon, ticker, title, content, sound, vibrate, lights); Toast.makeText(mContext, "您的手机低于Android 4.1.2,不支持多行通知显示!!", Toast.LENGTH_SHORT).show(); } else { setBuilder(pendingIntent, smallIcon, ticker, true, true, false); nBuilder.setContentTitle(title); nBuilder.setContentText(content); nBuilder.setPriority(Notification.PRIORITY_HIGH); notification = new Notification.BigTextStyle(nBuilder).bigText(content).build(); // 发送该通知 nm.notify(NOTIFICATION_ID, notification); } } /** * 有进度条的通知,可以设置为模糊进度或者精确进度 * * @param pendingIntent * @param smallIcon * @param ticker * @param title * @param content */ public void notify_progress(PendingIntent pendingIntent, int smallIcon, String ticker, String title, String content, boolean sound, boolean vibrate, boolean lights) { setCompatBuilder(pendingIntent, smallIcon, ticker, title, content, sound, vibrate, lights); /* * 因为进度条要实时更新通知栏也就说要不断的发送新的提示,所以这里不建议开启通知声音。 * 这里是作为范例,给大家讲解下原理。所以发送通知后会听到多次的通知声音。 */ new Thread(new Runnable() { @Override public void run() { int incr; for (incr = 0; incr <= 100; incr += 10) { // 参数:1.最大进度, 2.当前进度, 3.是否有准确的进度显示 cBuilder.setProgress(100, incr, false); // cBuilder.setProgress(0, 0, true); sent(); try { Thread.sleep(1 * 500); } catch (InterruptedException e) { e.printStackTrace(); } } // 进度满了后,设置提示信息 cBuilder.setContentText("下载完成").setProgress(0, 0, false); sent(); } }).start(); } /** * 容纳大图片的通知 * * @param pendingIntent * @param smallIcon * @param ticker * @param title * @param bigPic */ public void notify_bigPic(PendingIntent pendingIntent, int smallIcon, String ticker, String title, String content, int bigPic, boolean sound, boolean vibrate, boolean lights) { setCompatBuilder(pendingIntent, smallIcon, ticker, title, null, sound, vibrate, lights); NotificationCompat.BigPictureStyle picStyle = new NotificationCompat.BigPictureStyle(); final BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = true; options.inSampleSize = 2; Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), bigPic, options); picStyle.bigPicture(bitmap); picStyle.bigLargeIcon(bitmap); cBuilder.setContentText(content); cBuilder.setStyle(picStyle); sent(); } /** * 里面有两个按钮的通知 * * @param smallIcon * @param leftbtnicon * @param lefttext * @param leftPendIntent * @param rightbtnicon * @param righttext * @param rightPendIntent * @param ticker * @param title * @param content */ public void notify_button(int smallIcon, int leftbtnicon, String lefttext, PendingIntent leftPendIntent, int rightbtnicon, String righttext, PendingIntent rightPendIntent, String ticker, String title, String content, boolean sound, boolean vibrate, boolean lights) { requestCode = (int) SystemClock.uptimeMillis(); setCompatBuilder(rightPendIntent, smallIcon, ticker, title, content, sound, vibrate, lights); cBuilder.addAction(leftbtnicon, lefttext, leftPendIntent); cBuilder.addAction(rightbtnicon, righttext, rightPendIntent); sent(); } public void notify_HeadUp(PendingIntent pendingIntent, int smallIcon, int largeIcon, String ticker, String title, String content, int leftbtnicon, String lefttext, PendingIntent leftPendingIntent, int rightbtnicon, String righttext, PendingIntent rightPendingIntent, boolean sound, boolean vibrate, boolean lights) { setCompatBuilder(pendingIntent, smallIcon, ticker, title, content, sound, vibrate, lights); cBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), largeIcon)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cBuilder.addAction(leftbtnicon, lefttext, leftPendingIntent); cBuilder.addAction(rightbtnicon, righttext, rightPendingIntent); } else { Toast.makeText(mContext, "版本低于Andriod5.0,无法体验HeadUp样式通知", Toast.LENGTH_SHORT).show(); } sent(); } /** * 发送通知 */ private void sent() { notification = cBuilder.build(); // 发送该通知 nm.notify(NOTIFICATION_ID, notification); } /** * 根据id清除通知 */ public void clear() { // 取消通知 nm.cancelAll(); } }
wenmingvs/NotifyUtil
library/src/main/java/com/wenming/library/NotifyUtil.java
66,539
package org.bukkit.entity; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * 代表唤魔者. */ public interface Evoker extends Spellcaster { /** * 代表唤魔者当前使用的咒语. * <p> * 原文:Represents the current spell the Evoker is using. * * @deprecated 将来 Minecraft 会有更多的可施法的生物 */ @Deprecated public enum Spell { /** * 未施法状态. */ NONE, /** * 召唤恼鬼. */ SUMMON, /** * 召唤尖牙进行攻击. */ FANGS, /** * 发出"呜噜噜"的叫声. */ WOLOLO, /** * 使实体隐身的咒语. */ DISAPPEAR, /** * 使目标生物失明的咒语. */ BLINDNESS; } /** * 获取唤魔者当前使用的{@link Spell 咒语}. * <p> * 原文:Gets the {@link Spell} the Evoker is currently using. * * @return 唤魔者当前使用的咒语 * @deprecated 将来 Minecraft 会有更多的可施法的生物 */ @Deprecated @NotNull Spell getCurrentSpell(); /** * 设置唤魔者将要使用的{@link Spell 咒语}. * <p> * 原文:Sets the {@link Spell} the Evoker is currently using. * * @param spell 唤魔者应使用的咒语 * @deprecated 将来 Minecraft 会有更多的可施法的生物 */ @Deprecated void setCurrentSpell(@Nullable Spell spell); }
BukkitAPI-Translation-Group/Chinese_BukkitAPI
BukkitApi/org/bukkit/entity/Evoker.java
66,541
/** * wechatdonal */ package config; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; /** * wechat * * @author donal * */ public interface AppActivitySupport { /** * * 获取EimApplication. * */ public abstract WCApplication getWcApplication(); /** * * 终止服务. * */ public abstract void stopService(); /** * * 开启服务. * */ public abstract void startService(); /** * * 校验网络-如果没有网络就弹出设置,并返回true. * * @return */ public abstract boolean validateInternet(); /** * * 校验网络-如果没有网络就返回true. * * @return */ public abstract boolean hasInternetConnected(); /** * * 退出应用. * */ public abstract void isExit(); /** * * 判断GPS是否已经开启. * * @return */ public abstract boolean hasLocationGPS(); /** * * 判断基站是否已经开启. * * @return */ public abstract boolean hasLocationNetWork(); /** * * 检查内存卡. * */ public abstract void checkMemoryCard(); /** * * 显示toast. * * @param text * 内容 * @param longint * 内容显示多长时间 */ public abstract void showToast(String text, int longint); /** * * 短时间显示toast. * * @param text */ public abstract void showToast(String text); /** * * 获取进度条. * * @return */ public abstract ProgressDialog getProgressDialog(); /** * * 返回当前Activity上下文. * * @return */ public abstract Context getContext(); /** * * 获取当前登录用户的SharedPreferences配置. * * @return */ public SharedPreferences getLoginUserSharedPre(); /** * * 发出Notification的method. * * @param iconId * 图标 * @param contentTitle * 标题 * @param contentText * 你内容 * @param activity */ public void setNotiType(int iconId, String contentTitle, String contentText, Class activity, String from); }
DLTech21/wechat
src/config/AppActivitySupport.java
66,542
import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.BaseAdapter; import android.widget.RelativeLayout; import com.tencent.mobileqq.activity.GesturePWDUnlockActivity; import com.tencent.mobileqq.activity.aio.BaseBubbleBuilder; import com.tencent.mobileqq.activity.aio.BaseBubbleBuilder.e; import com.tencent.mobileqq.activity.aio.BaseChatItemLayout; import com.tencent.mobileqq.activity.aio.SessionInfo; import com.tencent.mobileqq.activity.aio.anim.AIOAnimationConatiner; import com.tencent.mobileqq.activity.aio.item.PokeEmoItemBuilder.1; import com.tencent.mobileqq.activity.aio.stickerbubble.PokeEmoItemView; import com.tencent.mobileqq.activity.aio.stickerbubble.StickerBubbleReceiverAnimationRunnable; import com.tencent.mobileqq.activity.history.ChatHistoryActivity; import com.tencent.mobileqq.app.QQAppInterface; import com.tencent.mobileqq.app.ThreadManager; import com.tencent.mobileqq.data.ChatMessage; import com.tencent.mobileqq.data.MessageForPokeEmo; import com.tencent.qphone.base.util.QLog; import mqq.os.MqqHandler; public class xkp extends BaseBubbleBuilder { protected long IX; private StickerBubbleReceiverAnimationRunnable a; private Drawable mDefaultDrawable; public xkp(QQAppInterface paramQQAppInterface, BaseAdapter paramBaseAdapter, Context paramContext, SessionInfo paramSessionInfo, AIOAnimationConatiner paramAIOAnimationConatiner) { super(paramQQAppInterface, paramBaseAdapter, paramContext, paramSessionInfo, paramAIOAnimationConatiner); } private void a(xkp.a parama, MessageForPokeEmo paramMessageForPokeEmo) { int i = paramMessageForPokeEmo.pokeemoId; int j = paramMessageForPokeEmo.pokeemoPressCount; parama.mMessage = paramMessageForPokeEmo; xks.B(this.app); boolean bool = xks.bhj; if (bool) { Drawable localDrawable = yfx.p(i); parama.a.setImageDrawable(localDrawable); parama.a.setText("x" + Integer.toString(paramMessageForPokeEmo.pokeemoPressCount)); parama.a.setIsSend(paramMessageForPokeEmo.isSend()); if (QLog.isColorLevel()) { QLog.d("PokeEmoItemBuilder", 2, String.format(" initBubbleView.forbidPoke=%b,isResDownload = %b,pokeMsg.isPlay = %b,animatingCount = %d,emoId = %d", new Object[] { Boolean.valueOf(wja.bcL), Boolean.valueOf(bool), Boolean.valueOf(paramMessageForPokeEmo.isNeedPlayed), Integer.valueOf(wja.bNH), Integer.valueOf(paramMessageForPokeEmo.pokeemoId) })); } if (QLog.isColorLevel()) { QLog.d("PokeEmoItemBuilder", 2, "sGesturePWDUnlockShowing: " + GesturePWDUnlockActivity.aXo); } if (!wja.bcL) { break label269; } } label269: label397: do { do { return; if (this.mDefaultDrawable == null) { this.mDefaultDrawable = this.mContext.getResources().getDrawable(2130842311); } parama.a.setImageDrawable(this.mDefaultDrawable); parama.a.setText("x" + paramMessageForPokeEmo.pokeemoPressCount * 1000); break; if ((!bool) || (paramMessageForPokeEmo.isSend()) || (!paramMessageForPokeEmo.isNeedPlayed) || ((this.mContext instanceof ChatHistoryActivity)) || (GesturePWDUnlockActivity.aXo)) { break label397; } if (QLog.isColorLevel()) { QLog.d("PokeEmoItemBuilder", 2, "show animation from item builder"); } wja.bNH += 1; paramMessageForPokeEmo.setIsNeedPlayed(false); parama = ((ViewGroup)((Activity)this.mContext).getWindow().getDecorView()).getChildAt(0).findViewById(2131362332); } while (parama == null); paramMessageForPokeEmo = yfx.cK(i); this.a = new StickerBubbleReceiverAnimationRunnable(this.app, j, parama, paramMessageForPokeEmo); ThreadManager.getUIHandler().post(this.a); return; } while (paramMessageForPokeEmo.isNeedPlayed); paramMessageForPokeEmo.setIsNeedPlayed(false); } public int a(ChatMessage paramChatMessage) { return 0; } public View a(ChatMessage paramChatMessage, BaseBubbleBuilder.e parame, View paramView, BaseChatItemLayout paramBaseChatItemLayout, wlz paramwlz) { Object localObject = this.mContext; paramBaseChatItemLayout = (MessageForPokeEmo)paramChatMessage; xkp.a locala = (xkp.a)parame; if (QLog.isColorLevel()) { QLog.d("PokeMsg", 2, "type: " + paramBaseChatItemLayout.pokeemoId + " count: " + paramBaseChatItemLayout.pokeemoPressCount); } parame = paramView; if (paramView == null) { if (QLog.isColorLevel()) { QLog.d("PokeEmoItemBuilder", 2, "[getBubbleView]:content is null"); } parame = new RelativeLayout((Context)localObject); parame.setId(2131377546); paramView = new PokeEmoItemView((Context)localObject); paramView.setId(2131373478); parame.addView(paramView, new ViewGroup.LayoutParams(-1, wja.dp2px(80.0F, ((Context)localObject).getResources()))); locala.a = paramView; localObject = yfx.mTypeface; if (localObject != null) { QLog.e("PokeEmoItemBuilder", 1, "mTypeface != null "); paramView.setTypeFace((Typeface)localObject); paramView.setText("x3"); aqcl.Q(paramView, false); } } else { if ((!locala.a.Tx()) && (yfx.mTypeface != null)) { locala.a.setTypeFace(yfx.mTypeface); } if ("PEPanelHelper.mTypeface != null :" + yfx.mTypeface == null) { break label359; } } label359: for (boolean bool = true;; bool = false) { QLog.e("PokeEmoItemBuilder", 1, new Object[] { Boolean.valueOf(bool) }); parame.setTag(locala); parame.setOnTouchListener(paramwlz); parame.setOnLongClickListener(paramwlz); a(locala, paramBaseChatItemLayout); if (aTl) { if ((locala.E != null) && (locala.E.length() > 0)) { locala.E.setLength(0); } parame.setContentDescription(b(paramChatMessage)); } return parame; if ((!xks.bhj) || (yfx.bmo)) { break; } yfx.bmo = true; ThreadManager.executeOnSubThread(new PokeEmoItemBuilder.1(this)); break; } } public BaseBubbleBuilder.e a() { return new xkp.a(); } public void a(int paramInt, Context paramContext, ChatMessage paramChatMessage) { switch (paramInt) { default: super.a(paramInt, paramContext, paramChatMessage); return; case 2131365686: ujt.b(this.mContext, this.app, paramChatMessage); return; } super.m(paramChatMessage); } public aqob[] a(View paramView) { aqoa localaqoa = new aqoa(); paramView = (wko.a)wja.a(paramView); if ((paramView != null) && (paramView.mMessage != null) && ((paramView.mMessage instanceof MessageForPokeEmo)) && (paramView.mMessage.istroop == 0)) { a(paramView.mMessage, localaqoa); } ujt.a(localaqoa, this.mContext, this.sessionInfo.cZ); super.e(localaqoa, this.mContext); return localaqoa.a(); } public String b(ChatMessage paramChatMessage) { StringBuilder localStringBuilder = new StringBuilder(); if (paramChatMessage.time > 0L) { localStringBuilder.append(aqmu.a(this.mContext, 3, paramChatMessage.time * 1000L)).append(" "); } MessageForPokeEmo localMessageForPokeEmo = (MessageForPokeEmo)paramChatMessage; if (paramChatMessage.isSend()) { localStringBuilder.append("我向" + this.sessionInfo.aTn + String.format("发出%d个轻互动表情%s", new Object[] { Integer.valueOf(localMessageForPokeEmo.pokeemoPressCount), localMessageForPokeEmo.summary })); } for (;;) { return localStringBuilder.toString(); localStringBuilder.append(this.sessionInfo.aTn + String.format("发来%d个轻互动表情%s", new Object[] { Integer.valueOf(localMessageForPokeEmo.pokeemoPressCount), localMessageForPokeEmo.summary })); } } public void destroy() { super.destroy(); wja.bNH = 0; } public void ei(View paramView) { super.ei(paramView); if (wja.a(paramView).isMultiMsg) {} do { return; paramView = (MessageForPokeEmo)wja.a(paramView); } while (!paramView.isSendFromLocal()); ausj localausj = (ausj)auss.a(this.mContext, null); localausj.addButton(2131690230, 5); localausj.addCancelButton(2131721058); localausj.a(new xkq(this, paramView, localausj)); localausj.show(); } public class a extends BaseBubbleBuilder.e { PokeEmoItemView a; public a() {} } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.tim\classes15.jar * Qualified Name: xkp * JD-Core Version: 0.7.0.1 */
tsuzcx/qq_apk
com.tencent.tim/classes.jar/xkp.java
66,543
package com.xinqi.bean; import java.util.Collections; /** * @author XinQi */ public enum ConfigEnum { CHATGPT_API("chatgpt_api",null), TELEGRAM_BOT_TOKEN("telegram_bot_token",null), START_MSG("start_msg","已新建 ChatGPT 对话,你可以发送 /response 重新回到上一次对话(该消息由 TelegramBot 发出)"), CONFIGURE_DEFAULT_MENU("configure_default_menu",false), WHITELIST("whitelist",Collections.singletonList("*")), NOT_WHITELIST_MSG("not_whitelist_msg","你不在白名单内,无法使用机器人(该消息由 TelegramBot 发出)"), CHATGPT_ERROR_MSG("chatgpt_error_msg","ChatGPT 响应失败,请发送 /response 重试,若频繁出现此问题,请联系管理员(该消息由 TelegramBot 发出)"), END_MSG("end_msg","从上一条 ChatGPT 回复开始,已有段时间未使用 ChatGPT,已自动删除 ChatGPT 对话数据,如需要继续上一次对话请发送 /history(该消息由 TelegramBot 发出)"), HISTORY_MSG("history_msg","已回到上一次对话(该消息由 TelegramBot 发出)"), NO_HISTORY_MSG("no_history_msg","没有上一次对话(该消息由 TelegramBot 发出)"); private final String key; private Object value; ConfigEnum(String key, Object value) { this.key = key; this.value = value; } public String getKey() { return key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } }
Qing-JiuJiu/ChatGPT-TelegramBot
src/main/java/com/xinqi/bean/ConfigEnum.java
66,544
package com.common.util; import com.string.widget.util.ValueWidget; import java.util.HashMap; import java.util.Map; /*** * 枚举工具类<br /> * added at 2018-04-19 中国标准时间 下午3:48:40 */ public class EnumUtil { // 根据 label 获取枚举 public static <E extends Enum<E>> E getByLabel(Class<E> enumClass, String propertyName, String name) { //enumClass.getEnumConstants() 将获取枚举类的所有实例 for (E e : enumClass.getEnumConstants()) { String propertyVal = (String) ReflectHWUtils.getGetterVal(e, "get" + ValueWidget.capitalize(propertyName)); if (propertyVal.equals(name)) { return e; } } return null; } public static <E extends Enum<E>> E getByCode(Class<E> enumClass, String propertyName, int code) { //enumClass.getEnumConstants() 将获取枚举类的所有实例 for (E e : enumClass.getEnumConstants()) { Number propertyVal = (Number) ReflectHWUtils.getGetterVal(e, "get" + ValueWidget.capitalize(propertyName)); if (propertyVal.intValue() == code) { return e; } } return null; } /*** * {验房=4, 经纪人下架=12, 发出=3, 已评价=8, 请求验房=1, 取消=10, 只剩下视频链接没有上传=7, 接单=2, 验房结束=5, 房主确认=6, 拒单=11} * @param enumClass * @param codePropName * @param labelPropName * @param <E> * @return */ public static <E extends Enum<E>> Map<String, Object> getLabelCodeMap(Class<E> enumClass, String codePropName, String labelPropName) { Map<String, Object> labelCodeMap = new HashMap<>(); for (E e : enumClass.getEnumConstants()) { Object code = ReflectHWUtils.getGetterValNoPrefix(e, codePropName); String label = (String) ReflectHWUtils.getGetterValNoPrefix(e, labelPropName); labelCodeMap.put(label, code); } return labelCodeMap; } /*** * {1=请求验房, 2=接单, 3=发出, 4=验房, 5=验房结束, 6=房主确认, 7=只剩下视频链接没有上传, 8=已评价, 10=取消, 11=拒单, 12=经纪人下架} * @param enumClass * @param codePropName * @param labelPropName * @param <E> * @return */ public static <E extends Enum<E>> Map<Object, String> getCodeLabelMap(Class<E> enumClass, String codePropName, String labelPropName) { Map<Object, String> codeLabelMap = new HashMap<>(); for (E e : enumClass.getEnumConstants()) { Object code = ReflectHWUtils.getGetterValNoPrefix(e, codePropName); String label = (String) ReflectHWUtils.getGetterValNoPrefix(e, labelPropName); codeLabelMap.put(code, label); } return codeLabelMap; } }
liuyu520/io0007
src/main/java/com/common/util/EnumUtil.java
66,546
package com.crazyc; import java.util.HashMap; import java.util.Map; import com.crazyc.R; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.ImageButton; public class OptionControl extends Activity { public static MediaPlayer music; public static SoundPool soundPool; public static boolean musicSt = true; //音乐开关 public static boolean soundSt = true ; //音效开关 public static Context context; public static final int[] musicId = {R.raw.mafia}; public static Map<Integer,Integer> soundMap; //音效资源id与加载过后的音源id的映射关系表 //Bundle bundleData = new Bundle(); ImageButton turnOn, turnOff,turnEasy,turnHard; CheckBox cb ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_option_control); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); turnOn = (ImageButton)findViewById(R.id.bturnon); turnOff = (ImageButton)findViewById(R.id.bturnoff); turnEasy = (ImageButton)findViewById(R.id.easymode); turnHard = (ImageButton)findViewById(R.id.hardmode); turnOn.setOnClickListener(new ButtonListener()); turnOff.setOnClickListener(new ButtonListener()); turnEasy.setOnClickListener(new ButtonListener()); turnHard.setOnClickListener(new ButtonListener()); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Intent intent = new Intent(); intent.setClass(OptionControl.this, MainMenu.class); startActivity(intent); } return super.onKeyDown(keyCode, event); } class ButtonListener implements OnClickListener { @Override public void onClick(View arg0) { // TODO Auto-generated method stub if(arg0.getId()== R.id.bturnon) { turnOn.setBackgroundResource(R.drawable.on_clicked); turnOff.setBackgroundResource(R.drawable.off); init(OptionControl.this); startMusic(); arg0.setClickable(false); turnOff.setClickable(true); } else if(arg0.getId()== R.id.bturnoff) { turnOff.setBackgroundResource(R.drawable.off_clicked); turnOn.setBackgroundResource(R.drawable.on); pauseMusic(); arg0.setClickable(false); music.release(); turnOn.setClickable(true); } else if(arg0.getId()== R.id.easymode) { turnEasy.setBackgroundResource(R.drawable.easy_clicked); turnHard.setBackgroundResource(R.drawable.hard); } else if(arg0.getId()== R.id.hardmode) { turnHard.setBackgroundResource(R.drawable.hard_clicked); turnEasy.setBackgroundResource(R.drawable.easy); } } } public static void init(Context c) { context = c; initMusic(); initSound(); } //初始化音效播放器 public static void initSound() { soundPool = new SoundPool(10,AudioManager.STREAM_MUSIC,100); soundMap = new HashMap<Integer,Integer>(); soundMap.put(R.raw.playcardsound, soundPool.load(context, R.raw.playcardsound, 1)); } //初始化音乐播放器 public static void initMusic() { //修改背景音 因為我們只有一首 //int r = new Random().nextInt(musicId.length); music = MediaPlayer.create(context,musicId[0]); music.setLooping(true); } /** * 播放音效 * @param resId 音效资源id */ public static void playSound(int resId) { if(soundSt == false) return; Integer soundId = soundMap.get(resId); if(soundId != null) soundPool.play(soundId, 1, 1, 1, 0, 1); } /** * 暂停音乐 */ public static void pauseMusic() { if(music.isPlaying()) music.pause(); } /** * 播放音乐 */ public static void startMusic() { if(musicSt) music.start(); } /** * 切换一首音乐并播放 */ /* public static void changeAndPlayMusic() { if(music != null) music.release(); initMusic(); startMusic(); }*/ /** * 获得音乐开关状态 * @return */ public static boolean isMusicSt() { return musicSt; } /** * 设置音乐开关 * @param musicSt */ public static void setMusicSt(boolean musicSt) { OptionControl.musicSt = musicSt; if(musicSt) music.start(); else music.stop(); } /** * 获得音效开关状态 * @return */ public static boolean isSoundSt() { return soundSt; } /** * 设置音效开关 * @param soundSt */ public static void setSoundSt(boolean soundSt) { OptionControl.soundSt = soundSt; } /** * 发出‘邦’的声音 */ public static void boom() { playSound(R.raw.playcardsound); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.option_control, menu); return true; } }
StevenLeeTW/CrazyC
src/com/crazyc/OptionControl.java
66,547
package mao.t1; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringEncoder; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.net.InetSocketAddress; /** * Project name(项目名称):Netty_hello_world * Package(包名): mao.t1 * Class(类名): Client * Author(作者): mao * Author QQ:1296193245 * GitHub:https://github.com/maomao124/ * Date(创建日期): 2023/3/17 * Time(创建时间): 14:18 * Version(版本): 1.0 * Description(描述): 客户端 */ @Slf4j public class Client { @SneakyThrows public static void main(String[] args) { new Bootstrap() //创建 NioEventLoopGroup,同 Server .group(new NioEventLoopGroup()) //选择客户 Socket 实现类,NioSocketChannel 表示基于 NIO 的客户端实现 .channel(NioSocketChannel.class) //添加 SocketChannel 的处理器,ChannelInitializer 处理器(仅执行一次), // 它的作用是待客户端 SocketChannel 建立连接后,执行 initChannel 以便添加更多的处理器 .handler(new ChannelInitializer<Channel>() { /** * 初始化通道 * * @param channel 通道 * @throws Exception 异常 */ @Override protected void initChannel(Channel channel) throws Exception { //消息会经过通道 handler 处理,这里是将 String => ByteBuf 发出 channel.pipeline().addLast(new StringEncoder()); } }) //指定要连接的服务器和端口 .connect(new InetSocketAddress(8080)) //Netty 中很多方法都是异步的,如 connect,这时需要使用 sync 方法等待 connect 建立连接完毕 .sync() //获取 channel 对象,它即为通道抽象,可以进行数据读写操作 .channel() //写入消息并清空缓冲区 .writeAndFlush("hello world."); } }
maomao124/Netty_hello_world
src/main/java/mao/t1/Client.java
66,548
package BP.WF; import javax.sound.sampled.Port; import BP.DA.AtPara; import BP.DA.DataType; import BP.En.Entity; import BP.En.EntityMyPK; import BP.En.Map; import BP.En.Row; import BP.Sys.Frm.EventListOfNode; import BP.Tools.StringHelper; import BP.WF.Port.WFEmp; import BP.WF.Template.PushMsgAttr; import BP.Web.WebUser; /** * 消息推送 */ public class PushMsg extends EntityMyPK { ///#region 基本属性 /** 事件 */ public final String getFK_Event() { return this.GetValStringByKey(PushMsgAttr.FK_Event); } public final void setFK_Event(String value) { this.SetValByKey(PushMsgAttr.FK_Event, value); } public final int getPushWay() { return this.GetValIntByKey(PushMsgAttr.PushWay); } public final void setPushWay(int value) { this.SetValByKey(PushMsgAttr.PushWay, value); } /** 节点 */ public final int getFK_Node() { return this.GetValIntByKey(PushMsgAttr.FK_Node); } public final void setFK_Node(int value) { this.SetValByKey(PushMsgAttr.FK_Node, value); } public final String getPushDoc() { String s = this.GetValStringByKey(PushMsgAttr.PushDoc); if (StringHelper.isNullOrEmpty(s) == true) { s = ""; } return s; } public final void setPushDoc(String value) { this.SetValByKey(PushMsgAttr.PushDoc, value); } public final String getTag() { String s = this.GetValStringByKey(PushMsgAttr.Tag); if (StringHelper.isNullOrEmpty(s) == true) { s = ""; } return s; } public final void setTag(String value) { this.SetValByKey(PushMsgAttr.Tag, value); } ///#endregion ///#region 事件消息. /** 邮件推送方式 */ public final int getMailPushWay() { return this.GetValIntByKey(PushMsgAttr.MailPushWay); } public final void setMailPushWay(int value) { this.SetValByKey(PushMsgAttr.MailPushWay, value); } public final String getMailPushWayText() { if (this.getFK_Event().equals(EventListOfNode.WorkArrive)) { if (this.getMailPushWay() == 0) { return "不发送"; } if (this.getMailPushWay() == 1) { return "发送给当前节点的所有处理人"; } if (this.getMailPushWay() == 2) { return "向指定的字段发送"; } } if (this.getFK_Event().equals(EventListOfNode.SendSuccess)) { if (this.getMailPushWay() == 0) { return "不发送"; } if (this.getMailPushWay() == 1) { return "发送给下一个节点的所有接受人"; } if (this.getMailPushWay() == 2) { return "向指定的字段发送"; } } if (this.getFK_Event().equals(EventListOfNode.ReturnAfter)) { if (this.getMailPushWay() == 0) { return "不发送"; } if (this.getMailPushWay() == 1) { return "发送给被退回的节点处理人"; } if (this.getMailPushWay() == 2) { return "向指定的字段发送"; } } return "未知"; } /** 邮件地址 */ public final String getMailAddress() { return this.GetValStringByKey(PushMsgAttr.MailAddress); } public final void setMailAddress(String value) { this.SetValByKey(PushMsgAttr.MailAddress, value); } /** 邮件标题. */ public final String getMailTitle() { String str = this.GetValStrByKey(PushMsgAttr.MailTitle); if (StringHelper.isNullOrEmpty(str) == false) { return str; } String fkEvent = this.getFK_Event(); if (fkEvent.equals(EventListOfNode.WorkArrive)) { return "新工作{{Title}},发送人@WebUser.No,@WebUser.Name"; } else if (fkEvent.equals(EventListOfNode.SendSuccess)) { return "新工作{{Title}},发送人@WebUser.No,@WebUser.Name"; } else if (fkEvent.equals(EventListOfNode.ReturnAfter)) { return "被退回来{{Title}},退回人@WebUser.No,@WebUser.Name"; } else if (fkEvent.equals(EventListOfNode.ShitAfter)) { return "移交来的新工作{{Title}},移交人@WebUser.No,@WebUser.Name"; } else if (fkEvent.equals(EventListOfNode.UndoneAfter)) { return "工作被撤销{{Title}},发送人@WebUser.No,@WebUser.Name"; } else if (fkEvent.equals(EventListOfNode.AskerReAfter)) { return "加签新工作{{Title}},发送人@WebUser.No,@WebUser.Name"; } else { throw new RuntimeException("@该事件类型没有定义默认的消息模版:" + this.getFK_Event()); } } /** 邮件标题 */ public final String getMailTitle_Real() { String str = this.GetValStrByKey(PushMsgAttr.MailTitle); return str; } public final void setMailTitle_Real(String value) { this.SetValByKey(PushMsgAttr.MailTitle, value); } /** 邮件内容 */ public final String getMailDoc_Real() { return this.GetValStrByKey(PushMsgAttr.MailDoc); } public final void setMailDoc_Real(String value) { this.SetValByKey(PushMsgAttr.MailDoc, value); } public final String getMailDoc() { String str = this.GetValStrByKey(PushMsgAttr.MailDoc); if (StringHelper.isNullOrEmpty(str) == false) { return str; } String fkEvent = this.getFK_Event(); if (fkEvent.equals(EventListOfNode.WorkArrive)) { str += "\t\n您好:"; str += "\t\n 有新工作{{Title}}需要您处理, 点击这里打开工作{Url} ."; str += "\t\n致! "; str += "\t\n @WebUser.No, @WebUser.Name"; str += "\t\n @RDT"; } else if (fkEvent.equals(EventListOfNode.SendSuccess)) { str += "\t\n您好:"; str += "\t\n 有新工作{{Title}}需要您处理, 点击这里打开工作{Url} ."; str += "\t\n致! "; str += "\t\n @WebUser.No, @WebUser.Name"; str += "\t\n @RDT"; } else if (fkEvent.equals(EventListOfNode.ReturnAfter)) { str += "\t\n您好:"; str += "\t\n 工作{{Title}}被退回来了, 点击这里打开工作{Url} ."; str += "\t\n 退回意见: \t\n "; str += "\t\n { @ReturnMsg }"; str += "\t\n 致! "; str += "\t\n @WebUser.No,@WebUser.Name"; str += "\t\n @RDT"; } else if (fkEvent.equals(EventListOfNode.ShitAfter)) { str += "\t\n您好:"; str += "\t\n 移交给您的工作{{Title}}, 点击这里打开工作{Url} ."; str += "\t\n 致! "; str += "\t\n @WebUser.No,@WebUser.Name"; str += "\t\n @RDT"; } else if (fkEvent.equals(EventListOfNode.UndoneAfter)) { str += "\t\n您好:"; str += "\t\n 移交给您的工作{{Title}}, 点击这里打开工作{Url} ."; str += "\t\n 致! "; str += "\t\n @WebUser.No,@WebUser.Name"; str += "\t\n @RDT"; } else if (fkEvent.equals(EventListOfNode.AskerReAfter)) { str += "\t\n您好:"; str += "\t\n 移交给您的工作{{Title}}, 点击这里打开工作{Url} ."; str += "\t\n 致! "; str += "\t\n @WebUser.No,@WebUser.Name"; str += "\t\n @RDT"; } else { throw new RuntimeException("@该事件类型没有定义默认的消息模版:" + this.getFK_Event()); } return str; } /** 短信接收人字段 */ public final String getSMSField() { return this.GetValStringByKey(PushMsgAttr.SMSField); } public final void setSMSField(String value) { this.SetValByKey(PushMsgAttr.SMSField, value); } /** 短信提醒方式 */ public final int getSMSPushWay() { return this.GetValIntByKey(PushMsgAttr.SMSPushWay); } public final void setSMSPushWay(int value) { this.SetValByKey(PushMsgAttr.SMSPushWay, value); } /** 发送消息标签 */ public final String getSMSPushWayText() { if (this.getFK_Event().equals(EventListOfNode.WorkArrive)) { if (this.getSMSPushWay() == 0) { return "不发送"; } if (this.getSMSPushWay() == 1) { return "发送给当前节点的所有处理人"; } if (this.getSMSPushWay() == 2) { return "向指定的字段发送"; } } if (this.getFK_Event().equals(EventListOfNode.SendSuccess)) { if (this.getSMSPushWay() == 0) { return "不发送"; } if (this.getSMSPushWay() == 1) { return "发送给下一个节点的所有接受人"; } if (this.getSMSPushWay() == 2) { return "向指定的字段发送"; } } if (this.getFK_Event().equals(EventListOfNode.ReturnAfter)) { if (this.getSMSPushWay() == 0) { return "不发送"; } if (this.getSMSPushWay() == 1) { return "发送给被退回的节点处理人"; } if (this.getSMSPushWay() == 2) { return "向指定的字段发送"; } } return "未知"; } /** 短信模版内容 */ public final String getSMSDoc_Real() { String str = this.GetValStrByKey(PushMsgAttr.SMSDoc); return str; } public final void setSMSDoc_Real(String value) { this.SetValByKey(PushMsgAttr.SMSDoc, value); } /** 短信模版内容 */ public final String getSMSDoc() { String str = this.GetValStrByKey(PushMsgAttr.SMSDoc); if (StringHelper.isNullOrEmpty(str) == false) { return str; } String fkEvent = this.getFK_Event(); if (fkEvent.equals(EventListOfNode.WorkArrive) || fkEvent.equals(EventListOfNode.SendSuccess)) { str = "有新工作{{Title}}需要您处理, 发送人:@WebUser.No, @WebUser.Name,打开{Url} ."; } else if (fkEvent.equals(EventListOfNode.ReturnAfter)) { str = "工作{{Title}}被退回,退回人:@WebUser.No, @WebUser.Name,打开{Url} ."; } else if (fkEvent.equals(EventListOfNode.ShitAfter)) { str = "移交工作{{Title}},移交人:@WebUser.No, @WebUser.Name,打开{Url} ."; } else if (fkEvent.equals(EventListOfNode.UndoneAfter)) { str = "工作撤销{{Title}},撤销人:@WebUser.No, @WebUser.Name,打开{Url}."; } else if (fkEvent.equals(EventListOfNode.AskerReAfter)) { str = "工作加签{{Title}},加签人:@WebUser.No, @WebUser.Name,打开{Url}."; } else { throw new RuntimeException("@该事件类型没有定义默认的消息模版:" + this.getFK_Event()); } return str; } public final void setSMSDoc(String value) { this.SetValByKey(PushMsgAttr.SMSDoc, value); } ///#endregion ///#region 构造方法 /** 消息推送 */ public PushMsg() { } /** 重写基类方法 */ @Override public Map getEnMap() { if (this.get_enMap() != null) { return this.get_enMap(); } Map map = new Map("WF_PushMsg", "消息推送"); map.AddMyPK(); map.AddTBInt(PushMsgAttr.FK_Node, 0, "节点", true, false); map.AddTBString(PushMsgAttr.FK_Event, null, "事件类型", true, false, 0, 15, 10); ///#region 将要删除. map.AddDDLSysEnum(PushMsgAttr.PushWay, 0, "推送方式", true, false, PushMsgAttr.PushWay, "@0=按照指定节点的工作人员@1=按照指定的工作人员@2=按照指定的工作岗位@3=按照指定的部门@4=按照指定的SQL@5=按照系统指定的字段"); //设置内容. map.AddTBString(PushMsgAttr.PushDoc, null, "推送保存内容", true, false, 0, 3500, 10); map.AddTBString(PushMsgAttr.Tag, null, "Tag", true, false, 0, 500, 10); ///#endregion 将要删除. ///#region 短信. map.AddTBInt(PushMsgAttr.SMSPushWay, 0, "短信发送方式", true, true); map.AddTBString(PushMsgAttr.SMSField, null, "短信字段", true, false, 0, 100, 10); map.AddTBStringDoc(PushMsgAttr.SMSDoc, null, "短信内容模版", true, false, true); ///#endregion 短信. ///#region 邮件. map.AddTBInt(PushMsgAttr.MailPushWay, 0, "邮件发送方式",true, true); map.AddTBString(PushMsgAttr.MailAddress, null, "邮件字段", true, false, 0, 100, 10); map.AddTBString(PushMsgAttr.MailTitle, null, "邮件标题模版", true, false, 0, 200, 20, true); map.AddTBStringDoc(PushMsgAttr.MailDoc, null, "邮件内容模版", true, false, true); ///#endregion 邮件. this.set_enMap(map); return this.get_enMap(); } ///#endregion /** 生成提示信息. @return */ private String generAlertMessage = null; /** 执行消息发送 @param currNode 当前节点 @param en 数据实体 @param atPara 参数 @param objs 发送返回对象 @param jumpToNode 跳转到的节点 @param jumpToEmps 跳转到的人员 @return 执行成功的消息 */ public final String DoSendMessage(Node currNode, Entity en, String atPara, SendReturnObjs objs, Node jumpToNode) { return DoSendMessage(currNode, en, atPara, objs, jumpToNode, null); } public final String DoSendMessage(Node currNode, Entity en, String atPara, SendReturnObjs objs) { return DoSendMessage(currNode, en, atPara, objs, null, null); } //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: //ORIGINAL LINE: public string DoSendMessage(Node currNode, Entity en, string atPara, SendReturnObjs objs, Node jumpToNode = null, string jumpToEmps = null) public final String DoSendMessage(Node currNode, Entity en, String atPara, SendReturnObjs objs, Node jumpToNode, String jumpToEmps) { if (en == null) { return ""; } ///#region 处理参数. Row r = en.getRow(); try { //系统参数. r.put("FK_MapData", en.getClassID()); } catch (java.lang.Exception e) { r.put("FK_MapData", en.getClassID()); } if (atPara != null) { AtPara ap = new AtPara(atPara); for (String s : ap.getHisHT().keySet()) { try { r.put(s, ap.GetValStrByKey(s)); } catch (java.lang.Exception e2) { r.put(s, ap.GetValStrByKey(s)); } } } long workid = Long.parseLong(en.getPKVal().toString()); String title = "标题"; if (en.getRow().containsKey("Title") == true) { title = en.GetValStringByKey("Title"); // 获得工作标题. } else { title = BP.DA.DBAccess.RunSQLReturnStringIsNull("SELECT Title FROM WF_GenerWorkFlow WHERE WorkID=" + en.getPKVal(), "标题"); } String hostUrl = Glo.getHostURL(); String sid = "{EmpStr}_" + workid + "_" + currNode.getNodeID() + "_" + DataType.getCurrentDataTime(); String openWorkURl = hostUrl + "WF/Do.jsp?DoType=OF&SID=" + sid; openWorkURl = openWorkURl.replace("//", "/"); openWorkURl = openWorkURl.replace("//", "/"); ///#endregion ///#region 处理发送邮件. // 发送邮件. String mailTitleTmp = ""; String mailDocTmp = ""; if (this.getMailPushWay() != 0) { // 标题. mailTitleTmp = this.getMailTitle(); mailTitleTmp = mailTitleTmp.replace("{Title}", title); mailTitleTmp = mailTitleTmp.replace("@WebUser.No", WebUser.getNo()); mailTitleTmp = mailTitleTmp.replace("@WebUser.Name", WebUser.getName()); // 内容. mailDocTmp = this.getMailDoc(); mailDocTmp = mailDocTmp.replace("{Url}", openWorkURl); mailDocTmp = mailDocTmp.replace("{Title}", title); mailDocTmp = mailDocTmp.replace("@WebUser.No", WebUser.getNo()); mailDocTmp = mailDocTmp.replace("@WebUser.Name", WebUser.getName()); /*如果仍然有没有替换下来的变量.*/ if (mailDocTmp.contains("@")) { mailDocTmp = Glo.DealExp(mailDocTmp, en, null); } //求发送给的人员ID. String toEmpIDs = ""; ///#region WorkArrive-工作到达. - 邮件处理. if (this.getFK_Event().equals(BP.Sys.Frm.EventListOfNode.WorkArrive) || this.getFK_Event().equals(BP.Sys.Frm.EventListOfNode.ReturnAfter)) { /*工作到达.*/ if (this.getMailPushWay() == 1) { /*如果向接受人发送邮件.*/ toEmpIDs = jumpToEmps; String[] emps = toEmpIDs.split("[,]", -1); for (String emp : emps) { if (StringHelper.isNullOrEmpty(emp)) { continue; } // 因为要发给不同的人,所有需要clone 一下,然后替换发送. Object tempVar = mailDocTmp; String mailDocReal = (String)((tempVar instanceof String) ? tempVar : null); mailDocReal = mailDocReal.replace("{EmpStr}", emp); //获得当前人的邮件. BP.WF.Port.WFEmp empEn = new WFEmp(emp); //发送邮件. BP.WF.Dev2Interface.Port_SendEmail(empEn.getEmail(), mailTitleTmp, mailDocReal, "ToDo", "WKAlt" + currNode.getNodeID() + "_" + workid); } generAlertMessage += "@已向:{" + toEmpIDs + "}发送提醒邮件,由 " + this.getFK_Event() + " 发出."; } if (this.getMailPushWay() == 2) { /*如果向指定的字段作为发送邮件的对象, 从字段里取数据. */ String emailAddress = (String)((r.get(this.getMailAddress()) instanceof String) ? r.get(this.getMailAddress()) : null); //发送邮件 BP.WF.Dev2Interface.Port_SendEmail(emailAddress, mailTitleTmp, mailDocTmp, "ToDo", "WKAlt" + currNode.getNodeID() + "_" + workid); generAlertMessage += "@已向:{" + emailAddress + "}发送提醒邮件,由 " + this.getFK_Event() + " 发出."; } } ///#endregion 发送成功事件. ///#region SendSuccess - 发送成功事件. - 邮件处理. if (this.getFK_Event().equals(EventListOfNode.SendSuccess)) { /*发送成功事件.*/ if (this.getMailPushWay() == 1 && objs.getVarAcceptersID() != null) { /*如果向接受人发送邮件.*/ toEmpIDs = objs.getVarAcceptersID(); String[] emps = toEmpIDs.split("[,]", -1); for (String emp : emps) { if (StringHelper.isNullOrEmpty(emp)) { continue; } // 因为要发给不同的人,所有需要clone 一下,然后替换发送. Object tempVar2 = mailDocTmp; String mailDocReal = (String)((tempVar2 instanceof String) ? tempVar2 : null); mailDocReal = mailDocReal.replace("{EmpStr}", emp); //获得当前人的邮件. BP.WF.Port.WFEmp empEn = new WFEmp(emp); //发送邮件. BP.WF.Dev2Interface.Port_SendEmail(empEn.getEmail(), mailTitleTmp, mailDocReal, "ToDo", "WKAlt" + objs.getVarToNodeID() + "_" + workid); } generAlertMessage += "@已向:{" + toEmpIDs + "}发送提醒邮件,由 SendSuccess 发出."; } if (this.getMailPushWay() == 2) { /*如果向指定的字段作为发送邮件的对象, 从字段里取数据. */ String emailAddress = (String)((r.get(this.getMailAddress()) instanceof String) ? r.get(this.getMailAddress()) : null); //发送邮件 BP.WF.Dev2Interface.Port_SendEmail(emailAddress, mailTitleTmp, mailDocTmp, "ToDo", "WKAlt" + objs.getVarToNodeID() + "_" + workid); generAlertMessage += "@已向:{" + emailAddress + "}发送提醒邮件,由 SendSuccess 发出."; } } ///#endregion 发送成功事件. } ///#endregion 处理发送邮件. ///#region 处理短信.. //定义短信内容. String smsDocTmp = ""; if (this.getSMSPushWay() != 0) { ///#region 生成短信内容 Object tempVar3 = this.getSMSDoc(); smsDocTmp = (String)((tempVar3 instanceof String) ? tempVar3 : null); smsDocTmp = smsDocTmp.replace("{Title}", title); smsDocTmp = smsDocTmp.replace("{Url}", openWorkURl); smsDocTmp = smsDocTmp.replace("@WebUser.No", WebUser.getNo()); smsDocTmp = smsDocTmp.replace("@WebUser.Name", WebUser.getName()); /*如果仍然有没有替换下来的变量.*/ if (smsDocTmp.contains("@") == true) { smsDocTmp = Glo.DealExp(smsDocTmp, en, null); } /*如果仍然有没有替换下来的变量.*/ if (smsDocTmp.contains("@")) { smsDocTmp = Glo.DealExp(smsDocTmp, en, null); } ///#endregion 处理当前的内容. //求发送给的人员ID. String toEmpIDs = ""; ///#region WorkArrive - 发送成功事件 if (this.getFK_Event().equals(EventListOfNode.WorkArrive) || this.getFK_Event().equals(EventListOfNode.ReturnAfter)) { String msgType = "ToDo"; if (this.getFK_Event().equals(EventListOfNode.ReturnAfter)) { msgType = "Return"; } /*发送成功事件.*/ if (this.getSMSPushWay() == 1) { /*如果向接受人发送短信.*/ toEmpIDs = jumpToEmps; String[] emps = toEmpIDs.split("[,]", -1); for (String emp : emps) { if (StringHelper.isNullOrEmpty(emp)) { continue; } Object tempVar4 = smsDocTmp; String smsDocTmpReal = (String)((tempVar4 instanceof String) ? tempVar4 : null); smsDocTmpReal = smsDocTmpReal.replace("{EmpStr}", emp); BP.WF.Port.WFEmp empEn = new WFEmp(emp); //发送短信. Dev2Interface.Port_SendSMS(empEn.getTel(), smsDocTmpReal, msgType, "WKAlt" + currNode.getNodeID() + "_" + workid, BP.Web.WebUser.getNo(), null, emp, null); } generAlertMessage += "@已向:{" + toEmpIDs + "}发送提醒手机短信,由 " + this.getFK_Event() + " 发出."; } if (this.getMailPushWay() == 2) { /*如果向指定的字段作为发送邮件的对象, 从字段里取数据. */ String tel = (String)((r.get(this.getSMSField()) instanceof String) ? r.get(this.getSMSField()) : null); //发送短信. BP.WF.Dev2Interface.Port_SendSMS(tel, smsDocTmp, msgType, "WKAlt" + currNode.getNodeID() + "_" + workid); generAlertMessage += "@已向:{" + tel + "}发送提醒手机短信,由 " + this.getFK_Event() + " 发出."; } } ///#endregion WorkArrive - 工作到达事件 ///#region SendSuccess - 发送成功事件 if (this.getFK_Event().equals(EventListOfNode.SendSuccess)) { /*发送成功事件.*/ if (this.getSMSPushWay() == 1 && objs.getVarAcceptersID() != null) { /*如果向接受人发送短信.*/ toEmpIDs = objs.getVarAcceptersID(); String[] emps = toEmpIDs.split("[,]", -1); for (String emp : emps) { if (StringHelper.isNullOrEmpty(emp)) { continue; } Object tempVar5 = smsDocTmp; String smsDocTmpReal = (String)((tempVar5 instanceof String) ? tempVar5 : null); smsDocTmpReal = smsDocTmpReal.replace("{EmpStr}", emp); BP.WF.Port.WFEmp empEn = new WFEmp(emp); //发送短信. Dev2Interface.Port_SendSMS(empEn.getTel(), smsDocTmpReal, "ToDo", "WKAlt" + objs.getVarToNodeID() + "_" + workid, BP.Web.WebUser.getNo(), null, emp, null); } generAlertMessage += "@已向:{" + toEmpIDs + "}发送提醒手机短信,由 SendSuccess 发出."; } if (this.getMailPushWay() == 2) { /*如果向指定的字段作为发送邮件的对象, 从字段里取数据. */ String tel = (String)((r.get(this.getSMSField()) instanceof String) ? r.get(this.getSMSField()) : null); if (tel != null || tel.length() > 6) { //发送短信. BP.WF.Dev2Interface.Port_SendSMS(tel, smsDocTmp, "ToDo", "WKAlt" + objs.getVarToNodeID() + "_" + workid); generAlertMessage += "@已向:{" + tel + "}发送提醒手机短信,由 SendSuccess 发出."; } } } ///#endregion SendSuccess - 发送成功事件 } ///#endregion 处理短信. return generAlertMessage; } @Override protected boolean beforeUpdateInsertAction() { // this.MyPK = this.FK_Event + "_" + this.FK_Node + "_" + this.PushWay; return super.beforeUpdateInsertAction(); } }
yhangleo/NoopsycheOffice
BPM-Components/src/main/java/BP/WF/PushMsg.java
66,550
package com.leon.fgf; import java.util.List; import com.leon.fgf.calculator.PlayerType; import com.leon.fgf.calculator.impl.FlowerLow2HeighCalculator; import com.leon.fgf.calculator.impl.FlowerValueCalculator; import com.leon.fgf.calculator.impl.Low2HeighCalculator; import com.leon.fgf.calculator.impl.NonFlowerValueCalculator; import com.leon.fgf.compare.PlayerComparator; import com.leon.fgf.entity.Card; import com.leon.fgf.entity.Player; import com.leon.fgf.provider.PlayerProvider; import com.leon.fgf.provider.impl.LimitedPlayerProvider; import com.leon.fgf.provider.impl.UnlimitedPlayerProvider; /** * 测试庄家,负责洗牌,发牌,比较牌 * * @author Leon * */ public class DealerTest { // 测试结果: // 发出1000副牌耗时1-15毫秒,计算牌大小并排序耗时1-15毫秒 private static final int PlayerNumber = 1024; public static void main(String args[]) { testManualInputPlayer(); System.out.println("\n==============================================="); testSinglePlayer(); System.out.println("\n==============================================="); testLimitedPlayer(); System.out.println("\n==============================================="); testManyPlayers(); } // 测试手动产生一副牌 public static void testManualInputPlayer() { // 使用花色参与大小比较的计算器,并且牌值越大,牌越小 PlayerComparator comparator = new PlayerComparator(new Low2HeighCalculator()); Player player = new Player(new Card(Card.FLOWER_SPADE, 6), new Card(Card.FLOWER_HEART, 6), new Card(Card.FLOWER_DIAMOND, 6)); // 对于一副未按大小排好序的牌,调用setupUnRegularPlayer()方法 comparator.setupUnRegularPlayer(player); printPlayerCards(player); printTypeValue(player); } // 测试从一副牌中产生一个玩家 private static void testSinglePlayer() { // 使用有人数限制的发牌器 PlayerProvider playerProvider = new LimitedPlayerProvider(); // 使用花色参与大小比较的计算器 PlayerComparator juger = new PlayerComparator(new FlowerValueCalculator()); Player player = playerProvider.getSinglePlayer(); // 使用发牌器发出的牌,每副牌已经自动按大到小排好序,调用setupRegularPlayer()方法 juger.setupRegularPlayer(player); printPlayerCards(player); printTypeValue(player); } // 测试从一副牌中产生多个玩家,一般玩家数量2-6个 private static void testLimitedPlayer() { // 使用有人数限制的发牌器 PlayerProvider playerProvider = new LimitedPlayerProvider(); // 使用花色参与大小比较的计算器 PlayerComparator juger = new PlayerComparator(new FlowerValueCalculator()); List<Player> players = playerProvider.getPlayers(16); // 使用发牌器发出的牌,每副牌已经自动按大到小排好序,调用sortRegularPlayers()方法 juger.sortRegularPlayers(players); printPlayers(players); } // 测试随机产生不限制数量的玩家,不考虑多个玩家出现完全相同牌型的情况,但一个玩家不会出现完全相同的两张牌 private static void testManyPlayers() { // 使用没有人数限制的发牌器 PlayerProvider generator = new UnlimitedPlayerProvider(); // 使用花色参与大小比较的计算器,并且按照牌的值越大,牌越小 PlayerComparator juger = new PlayerComparator(new FlowerValueCalculator()); System.out.println("\n开始发牌..." + System.currentTimeMillis()); List<Player> players = generator.getPlayers(PlayerNumber); System.out.println("发牌完成,开始排序..." + System.currentTimeMillis()); juger.sortRegularPlayers(players); System.out.println("排序完成..." + System.currentTimeMillis()); printPlayers(players); } // ========================以下代码全是打印输出==================================== private static void printPlayers(List<Player> players) { for (int i = 0; i < players.size(); i++) { System.out.print("玩家_" + i + "_的牌:"); printPlayerCards(players.get(i)); printTypeValue(players.get(i)); System.out.println(); } } private static void printPlayerCards(Player player) { for (int j = 0; j < 3; j++) { printCard(player.cards[j]); } } private static void printCard(Card card) { int flower = card.getFlower(); int number = card.getNumber(); switch (flower) { case Card.FLOWER_SPADE: System.out.print("黑桃" + getCardStringNumber(number)); break; case Card.FLOWER_HEART: System.out.print("红桃" + getCardStringNumber(number)); break; case Card.FLOWER_CLUB: System.out.print("梅花" + getCardStringNumber(number)); break; default: System.out.print("方片" + getCardStringNumber(number)); break; } System.out.print(", "); } private static String getCardStringNumber(int number) { if (number <= 10) { return "" + number; } else if (number == 11) { return "J"; } else if (number == 12) { return "Q"; } else if (number == 13) { return "K"; } else { return "A"; } } private static void printTypeValue(Player player) { int type = player.getType(); int value = player.getValue(); switch (type) { case PlayerType.BOMB: System.out.print("炸弹, 牌值:" + value); break; case PlayerType.STRAIGHT_FLUSH: System.out.print("同花顺, 牌值:" + value); break; case PlayerType.FLUSH: System.out.print("同花, 牌值:" + value); break; case PlayerType.STRAIGHT: System.out.print("顺子, 牌值:" + value); break; case PlayerType.DOUBLE: System.out.print("对子, 牌值:" + value); break; default: if (player.isSpecial()) { System.out.print("特殊牌, 牌值:" + value); } else { System.out.print("普通牌, 牌值:" + value); } break; } } }
LeonXtp/FriedGoldenFlower
src/com/leon/fgf/DealerTest.java
66,553
package SaveServlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lyq.bean.User; import com.lyq.bean.service.Login_service; @WebServlet(name = "Login_Servlet", urlPatterns = "/Login_Servlet") // 注释配置文件 public class Login_Servlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取表单中属性值, String Usersort = request.getParameter("UserSort"); // 获得用户登录类型、用户名、密码 String Username = request.getParameter("username"); String Pwd = request.getParameter("pwd"); User user = new User(); user = new Login_service().getLoginSql(Usersort, Username, Pwd); if (user != null) { request.getSession().setAttribute("UNAME", Username);// 用户名 request.getSession().setAttribute("SORT", Usersort);// 身份 if (Usersort.equals("管理员")) {// 用户类型为管理员时转换到M_Home.jsp页面 request.getRequestDispatcher("/jsp/manager/M_Home.jsp").forward(request, response); } else if (Usersort.equals("学生")) {// 用户类型为学生时转换到R_Home.jsp页面 request.getRequestDispatcher("/jsp/student/s/S_Home.jsp").forward(request, response); } else if (Usersort.equals("教师")) {// 用户类型为教师时转换到T_Home.jsp页面 request.getRequestDispatcher("/jsp/teacher/t/T_Home.jsp").forward(request, response); } } else {// 发出错误提示 request.getSession().setAttribute("message", "用户名或密码错误,请重写输入!"); request.getSession().setAttribute("url", "Login.jsp"); response.sendRedirect("Message.jsp"); } } }
jiaoxiangyu/ElectiveManage
src/SaveServlet/Login_Servlet.java
66,554
package com.lzh.entity; import java.sql.Timestamp; import java.text.SimpleDateFormat; /** * @Description * @author 林泽鸿 * @time 2019年5月14日 上午4:34:33 */ public class Doumail { /** * 豆邮表的id */ private int doumailId ; /** * 发出豆邮的人的用户id */ private int fromUserId; /** * 发出豆邮的人的头像 */ private String fromUserImg; /** * 发送豆邮的人的昵称 */ private String fromUserNick; /** * 接受豆邮的人的用户id */ private int toUserId ; /** * 接收豆邮的人的头像 */ private String toUserImg ; /** * 接收豆邮的人的昵称 */ private String toUserNick ; /** * 豆邮的内容 */ private String chatMsg; /** * 豆邮的发送时间 */ private java.sql.Timestamp chatTime ; /** * 记录当前记录的删除情况--- * ----0为无状态, * ----1为发送豆邮的人进行了删除, * ----2为接收豆邮的人进行了删除 */ private int status ; /** * 记录当前的豆邮是否已被阅读 */ private int read ; /** * @param doumailId * @param fromUserId * @param fromUserImg * @param fromUserNick * @param toUserId * @param toUserImg * @param toUserNick * @param chatMsg * @param chatTime * @param status * @param read */ public Doumail(int doumailId, int fromUserId, String fromUserImg, String fromUserNick, int toUserId, String toUserImg, String toUserNick, String chatMsg, Timestamp chatTime, int status, int read) { super(); this.doumailId = doumailId; this.fromUserId = fromUserId; this.fromUserImg = fromUserImg; this.fromUserNick = fromUserNick; this.toUserId = toUserId; this.toUserImg = toUserImg; this.toUserNick = toUserNick; this.chatMsg = chatMsg; this.chatTime = chatTime; this.status = status; this.read = read; } /** * */ public Doumail() { super(); // TODO Auto-generated constructor stub } public int getDoumailId() { return doumailId; } public void setDoumailId(int doumailId) { this.doumailId = doumailId; } public int getFromUserId() { return fromUserId; } public void setFromUserId(int fromUserId) { this.fromUserId = fromUserId; } public String getFromUserImg() { return fromUserImg; } public void setFromUserImg(String fromUserImg) { this.fromUserImg = fromUserImg; } public String getFromUserNick() { return fromUserNick; } public void setFromUserNick(String fromUserNick) { this.fromUserNick = fromUserNick; } public int getToUserId() { return toUserId; } public void setToUserId(int toUserId) { this.toUserId = toUserId; } public String getToUserImg() { return toUserImg; } public void setToUserImg(String toUserImg) { this.toUserImg = toUserImg; } public String getToUserNick() { return toUserNick; } public void setToUserNick(String toUserNick) { this.toUserNick = toUserNick; } public String getChatMsg() { return chatMsg; } public void setChatMsg(String chatMsg) { this.chatMsg = chatMsg; } public String getChatTime() { //更改其时间格式 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.format(chatTime); } public void setChatTime(java.sql.Timestamp chatTime) { this.chatTime = chatTime; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getRead() { return read; } public void setRead(int read) { this.read = read; } }
linzworld/iDouban
src/com/lzh/entity/Doumail.java
66,555
package work; //package justep; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import javax.naming.NamingException; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import com.alibaba.fastjson.JSONObject; import com.justep.baas.Utils; import com.justep.baas.action.ActionContext; import com.justep.baas.data.DataUtils; import com.justep.baas.data.Table; import com.justep.baas.data.Transform; public class Dx { private static final String DATASOURCE_TAKEOUT = "takeout"; public static JSONObject DuanXinCheck(JSONObject params, ActionContext context) throws SQLException, NamingException, IOException { HttpServletRequest request = (HttpServletRequest)context.get(ActionContext.REQUEST); // request.getSession(); // boolean flag = false; String fPhoneNumber = params.getString("fPhoneNumber"); //生成6位数字的随机字符串 int suiji = new Random().nextInt(899999) + 100000; String backStr = Integer.toString(suiji); // 将随机字符串通过jsonOBJ返回前台 JSONObject jsonObj = new JSONObject(); // System.out.println("backStr==="+backStr); // jsonObj.put("CheckCode", backStr); // DataUtils.writeJsonToResponse((ServletResponse)(context.get(ActionContext.RESPONSE)), jsonObj); HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn"); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk"); //在头文件中设置转码 NameValuePair[] data = { new NameValuePair("Uid", "justep"), new NameValuePair("Key", "5280d1eac8b167c419fb"), new NameValuePair("smsMob", fPhoneNumber), new NameValuePair("smsText", "验证码:" + backStr + " (本信息由系统自动发出,不要回复)") }; //这段Java代码是直接从他家demo拷贝下来的,只需要修改这句话,填写你在他家注册的用户名、短信密钥,参数中加要发送的手机号和验证码短信 post.setRequestBody(data); try { client.executeMethod(post); Header[] headers = post.getResponseHeaders(); int statusCode = post.getStatusCode(); System.out.println("状态码:" + statusCode); for (Header h : headers) { System.out.println(h.toString()); } String result = new String(post.getResponseBodyAsString().getBytes("gbk")); if(Integer.parseInt(result)> 0){ request.getSession().setAttribute(fPhoneNumber, backStr); request.getSession().setAttribute(fPhoneNumber+"Time", WorkUtil.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss")); // flag = true; }else{ backStr = ""; } System.out.println(result); //打印返回消息状态 } finally { post.releaseConnection(); } jsonObj.put("backStr", backStr); return jsonObj; } public static JSONObject login(JSONObject params, ActionContext context) throws SQLException, NamingException, IOException { // 获取参数 Object columns = params.get("columns"); Integer limit = params.getInteger("limit"); Integer offset = params.getInteger("offset"); String search = params.getString("search"); String fPhoneNumber = params.getString("fPhoneNumber"); String fPassWord = params.getString("fPassWord"); // System.out.println("fPhoneNumber="+fPhoneNumber+"#fPassWord="+fPassWord); List<Object> sqlParams = new ArrayList<Object>(); // 构造过滤条件 List<String> filters = new ArrayList<String>(); if (!Utils.isEmptyString(search)) { filters.add(" fPhoneNumber = ? OR fPassWord = ? "); // 多个问号参数的值 search = (search.indexOf("%") != -1) ? search : "%" + search + "%"; for (int i = 0; i < 2; i++) { sqlParams.add(search); } } sqlParams.add(fPhoneNumber); sqlParams.add(fPassWord); Table table = null; Connection conn = context.getConnection(DATASOURCE_TAKEOUT); String querysql = "select * from user_info u where u.fPhoneNumber=? and u.fPassWord=?"; try { table = DataUtils.queryData(conn, querysql, sqlParams, columns, offset, limit); return Transform.tableToJson(table); // System.out.println("jsonObj==="+Transform.tableToJson(table)); } finally { conn.close(); } } }
wex5/wex5-work
Baas/work/Dx.java
66,556
package TomcatServer.Request; import TomcatServer.Util.GetParam; import com.hjy.util.GetParm; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.util.HashMap; import java.util.Map; public class Request { private Socket client; //客户端 private BufferedReader reader; private String url; //请求资源 private String method; //请求方式 private String protocal; //请求协议 private Map<String,String> map; //参数列表 private GetParam getParam; //请求参数分割工具 public Request() {} /* * @auther: Ragty * @describe: 接收并客户端(Client)发出的请求,获取请求的链接及参数 * @param: [client] * @return: * @date: 2019/1/25 */ public Request(Socket client) { this.client = client; map = new HashMap<>(); getParam = new GetParam(); try { reader = new BufferedReader(new InputStreamReader(client.getInputStream())); String firstLine = reader.readLine(); String[] spilt = firstLine.split(" "); method = spilt[0]; url = spilt[1]; protocal = spilt[2]; System.out.println(url); if (method.equalsIgnoreCase("get")) { if(url.contains("?")) { String[] split2 = url.split("[?]"); url = split2[0]; //重新定义url String property = split2[1]; map = getParam.getParam(property); //分割参数 } } else { int length = 0; while (reader.ready()) { //确保已经缓冲完毕 String line = reader.readLine(); if (line.contains("Content-Length")) { String[] spilt2 = line.split(" "); length = Integer.parseInt(spilt2[1]); } if (line.equals("")) { //Post方法无参数 break; } } String info = null; char[] ch = new char[length]; reader.read(ch , 0, length); info = new String(ch, 0, length); map = getParam.getParam(info); } } catch (IOException e) { e.printStackTrace(); } } public Socket getClient() { return client; } public void setClient(Socket client) { this.client = client; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getProtocal() { return protocal; } public void setProtocal(String protocal) { this.protocal = protocal; } }
huoji555/Shadow
TomcatServer/Request/Request.java
66,557
package utils; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.Set; import probability.ProbabilityComputer; /** * 抽象类SuperAI实现了一个AI算法 * 包含了一个AI算法应该包含的属性及方法,用于客户端主程序与算法程序的交互 * @author wangtao * */ public abstract class SuperAI { private ArrayList<Poker> holdPokers; //底牌 private ArrayList<Poker> publicPokers; //公共牌 private String playerID; //自己的注册ID private int blind; //盲注金额或最小押注金额 private int initJetton; //初始总筹码 private int totalJetton; //剩余筹码 private int totalMoney; //剩余金币 private int playerNum; //玩家人数 private float winProb; //战胜一个对手的概率 private ArrayList<String> activePlayers; //当前没有弃牌的玩家 private String buttonID; //庄家ID private boolean isTheLastOne; //是否是最后一个玩家 private boolean isLastHalf; //是否是位置偏后的一半玩家 private boolean hasAllIn; //是否有all_in娃 // private int position; //自己的位置,即押注的顺序 private int handNum; //当前局数 private boolean folded; //是否已弃牌 private boolean hasRaised; //标记本环节是否已加过注 private ArrayList<InitState> initStates; //用于记录所有玩家的初始状态 private ArrayList<BetState> betStates; //用于记录所有未弃牌玩家的押注状态 // private BetPredict predictor; //机器学习算法 public SuperAI(String playerID) { this.holdPokers = new ArrayList<Poker>(); this.publicPokers = new ArrayList<Poker>(); this.activePlayers = new ArrayList<String>(); this.playerID = playerID; this.playerNum = -1; this.folded = false; // this.predictor = BetPredict.getInstance(); } public void setPlayerID(String playerID) { this.playerID = playerID; } /** * 设置玩家人数 * @param number */ public void setPlayersNumber(int number) { this.playerNum = number; } /** * 设置该局的盲注金额,即最小押注金额 * @param blind */ public void setBlind(int blind) { this.blind = blind; } public int getInitJetton() { return this.initJetton; } /** * 设置剩余筹码,剩余金币,玩家人数,自己的位置,当前局数 * @param jetton * @param money */ public void setInitInfo(int jetton, int money, int playerNum, int position, int handNum, ArrayList<InitState> states) { this.totalJetton = jetton; this.totalMoney = money; if (this.playerNum != playerNum) { this.playerNum = playerNum; this.hasAllIn = false; } // this.position = position; this.handNum = handNum; if (this.handNum == 1) this.initJetton = this.totalJetton + this.totalMoney; this.winProb = 0; this.holdPokers.clear(); this.publicPokers.clear(); this.activePlayers.clear(); this.initStates = states; for (InitState state: this.initStates) { this.activePlayers.add(state.getPlayerID()); } this.buttonID = this.activePlayers.get(0); if (this.buttonID.equals(this.playerID)) { this.isTheLastOne = true; } else { this.isTheLastOne = false; } this.isLastHalf = false; this.folded = false; this.betStates = null; } public boolean getFolded() { return this.folded; } public String getPlayerID() { return this.playerID; } public int getTotalJetton() { return this.totalJetton; } public int getTotalMoney() { return this.totalMoney; } public int getTotalMoneyAndJetton() { return this.totalMoney + this.totalJetton; } public int getPlayerNum() { return this.playerNum; } public int getActiverPlayerNum() { return this.activePlayers.size(); } public void computeLastHalf() { if (this.isTheLastOne) { this.isLastHalf = true; return ; } int count = 1; for (String player: this.activePlayers) { if (player.equals(this.playerID)) break; if (!player.equals(this.buttonID)) count ++; } if (count > this.activePlayers.size() / 2) { this.isLastHalf = true; return ; } this.isLastHalf = false; } public boolean isLastHalf() { return this.isLastHalf; } public boolean IsTheLastOne() { return this.isTheLastOne; } public boolean hasAllIn() { return this.hasAllIn; } public String getButtonID() { return this.buttonID; } public float getWinOnePlayerProb() { return this.winProb; } public float getWinAllPlayerProb() { float res = 1; for (int i = 0; i < this.getActiverPlayerNum() - 1; i++) res *= this.winProb; return res; } public int getHandNum() { return this.handNum; } public ArrayList<Poker> getHoldPokers() { return this.holdPokers; } public ArrayList<Poker> getPublicPokers() { return this.publicPokers; } public int getBlind() { return this.blind; } public boolean getHasRaised() { return this.hasRaised; } public void setHasRaised(boolean flag) { this.hasRaised = flag; } public void setBetStates(ArrayList<BetState> states) { this.betStates = states; for (BetState state: states) { if (state.getAction().equals("fold")) this.activePlayers.remove(state.getPlayerID()); } if (this.buttonID.equals(this.playerID)) { this.isTheLastOne = true; } else if (!this.activePlayers.get(0).equals(this.buttonID) && this.activePlayers.get(this.activePlayers.size() - 1) .equals(this.playerID)) { this.isTheLastOne = true; } this.computeLastHalf(); if (!this.hasAllIn && this.publicPokers.size() == 0) { for (BetState state: states) { if (state.getAction().equals("all_in")) { this.hasAllIn = true; break; } } } } public void setInitStates(ArrayList<InitState> states) { this.initStates = states; } /** * 玩家playerID需要下筹码为jet的盲注 */ public void postBlind(String playerID, int jet) { if (this.playerID == playerID) { this.totalJetton -= jet; } } /** * 在发送下注策略之前必须通过该方法获得策略 * @param diff * @param jetton * @return */ public String getResponse(int diff, int jetton) { if (this.activePlayers.size() == 1) { return "check"; } if(this.getHasRaised() && jetton > diff) { jetton = diff; } if (jetton == 0 && diff > 0) { return "fold"; } else if (jetton == 0 && diff == 0) { return "check"; } else if (jetton >= this.getTotalJetton()) { this.totalJetton = 0; this.setHasRaised(true); return "all_in"; } else if (jetton == diff) { this.totalJetton -= jetton; return "call"; } else if (jetton > diff) { Random random = new Random(); int sum = jetton + (random.nextInt(5) + 1); this.totalJetton -= sum; this.setHasRaised(true); return "raise " + (sum); } else { this.totalJetton -= diff; return "call"; } } /** * 添加两张底牌 */ public void addHoldPokers(Poker p1, Poker p2) { this.holdPokers.add(p1); this.holdPokers.add(p2); this.hasRaised = false; } /** * 发出两张底牌之后思考策略 * @param betStates 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ public abstract String thinkAfterHold( ArrayList<BetState> betStates); /** * 添加三张公共牌 */ public void addFlopPokers(Poker p1, Poker p2, Poker p3) { this.publicPokers.add(p1); this.publicPokers.add(p2); this.publicPokers.add(p3); this.winProb = ProbabilityComputer.computeProbability( this.holdPokers, this.publicPokers); this.hasRaised = false; } /** * 发出三张公共牌之后思考策略 * @param betStates 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ public abstract String thinkAfterFlop( ArrayList<BetState> betStates); /** * 添加一张转牌 */ public void addTurnPoker(Poker p) { this.publicPokers.add(p); this.winProb = ProbabilityComputer.computeProbability( this.holdPokers, this.publicPokers); this.hasRaised = false; } /** * 发出一张转牌之后思考策略 * @param betStates 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ public abstract String thinkAfterTurn( ArrayList<BetState> betStates); /** * 添加一张河牌 */ public void addRiverPoker(Poker p) { this.publicPokers.add(p); this.winProb = ProbabilityComputer.computeProbability( this.holdPokers, this.publicPokers); this.hasRaised = false; } /** * 发出一张河牌之后思考策略 * @param betStates 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ public abstract String thinkAfterRiver( ArrayList<BetState> betStates); /** * 跟注 * * @param diff * @param maxMultiple 最大可容忍跟注倍数 * @return */ public String callByDiff(int diff, int maxMultiple) { if (this.getPublicPokers().size() == 0) { ArrayList<Poker> hp = this.getHoldPokers(); if (this.isHoldBigPair(hp)) { if (hp.get(0).getValue() >= 12) return this.getResponse(diff, diff); else { if (diff >= this.getTotalJetton()) return this.getResponse(diff, 0); return this.getResponse(diff, diff); } } if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); return this.getResponse(diff, diff); } else if (this.getPublicPokers().size() == 3) { float prob = this.getWinAllPlayerProb(); if (prob < 0.10f) { return this.getResponse(diff, 0); } else if (prob < 0.50f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 4 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 6 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.75f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 3 >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 8 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.95f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 2 >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 10 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.98f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 15 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.99f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 30 * this.getBlind()) return this.getResponse(diff, 0); } return this.getResponse(diff, diff); } else if (this.getPublicPokers().size() == 4) { float prob = this.getWinAllPlayerProb(); if (prob < 0.20f) { return this.getResponse(diff, 0); } else if (prob < 0.50f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 4 >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 8 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.75f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 3 >= this.getTotalMoneyAndJetton()) { return this.getResponse(diff, 0); } if (diff > 10 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.95f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 2 >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 15 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.97f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 15 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.985f) { if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 30 * this.getBlind()) return this.getResponse(diff, 0); } return this.getResponse(diff, diff); } else if (this.getPublicPokers().size() == 5) { float prob = this.getWinAllPlayerProb(); if (prob < 0.25f) { return this.getResponse(diff, 0); } else if (prob < 0.50f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 4 >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 5 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.80f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 3 >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 6 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.95f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 2 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 8 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.97f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 12 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.985f) { if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 50 * this.getBlind()) return this.getResponse(diff, 0); } return this.getResponse(diff, diff); } return this.getResponse(diff, diff); } /** * 加注:加注金额为mutiple * blind * * @param diff * 根据前面玩家下注,需要跟注的最小数量 * @param multiple * @param maxMultiple 最大可接受倍数 * @return */ public String raiseByDiff(int diff, int multiple, int maxMultiple) { // 本环节已经加过注,则选择跟注 if (this.getHasRaised()) return this.callByDiff(diff, maxMultiple); if (this.getPublicPokers().size() == 0) { ArrayList<Poker> hp = this.getHoldPokers(); if (this.isHoldBigPair(hp)) { if (hp.get(0).getValue() >= 12) return this.getResponse(diff, multiple * this.getBlind()); else { if (diff >= this.getTotalJetton()) return this.getResponse(diff, 0); return this.getResponse(diff, multiple * this.getBlind()); } } if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); return this.getResponse(diff, multiple * this.getBlind()); } else if (this.getPublicPokers().size() == 3) { float prob = this.getWinAllPlayerProb(); if (prob < 0.10f) { return this.getResponse(diff, 0); } else if (prob < 0.50f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 4 >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 5 * this.getBlind()) return this.getResponse(diff, 0); multiple = 1; } else if (prob < 0.75f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 3 >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 6 * this.getBlind()) return this.getResponse(diff, 0); multiple = 2; } else if (prob < 0.95f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 2 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 10 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.97f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 25 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.985f) { if (diff > 50 * this.getBlind()) return this.getResponse(diff, 0); if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } } else { return this.getResponse(diff, 2 * multiple * this.getBlind()); } return this.getResponse(diff, multiple * this.getBlind()); } else if (this.getPublicPokers().size() == 4) { float prob = this.getWinAllPlayerProb(); if (prob < 0.20f) { return this.getResponse(diff, 0); } else if (prob < 0.60f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 4 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 5 * this.getBlind()) return this.getResponse(diff, 0); multiple = 1; } else if (prob < 0.80f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 3 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 6 * this.getBlind()) return this.getResponse(diff, 0); multiple = 2; } else if (prob < 0.96f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 3 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 8 * this.getBlind()) return this.getResponse(diff, 0); multiple = 3; } else if (prob < 0.97f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 2 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 20 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.985f) { if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 50 * this.getBlind()) return this.getResponse(diff, 0); return this.getResponse(diff, 2 * multiple * this.getBlind()); } else { return this.getResponse(diff, this.getTotalJetton()); } return this.getResponse(diff, multiple * this.getBlind()); } else if (this.getPublicPokers().size() == 5) { float prob = this.getWinAllPlayerProb(); if (prob < 0.25f) { return this.getResponse(diff, 0); } else if (prob < 0.65f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 4 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 5 * this.getBlind()) return this.getResponse(diff, 0); multiple = 1; } else if (prob < 0.85f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 3 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 8 * this.getBlind()) return this.getResponse(diff, 0); multiple = 2; } else if (prob < 0.95f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 3 > this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 15 * this.getBlind()) return this.getResponse(diff, 0); multiple = 3; } else if (prob < 0.97f) { if (diff > maxMultiple * this.getBlind()) return this.getResponse(diff, 0); if (diff * 2 >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 20 * this.getBlind()) return this.getResponse(diff, 0); } else if (prob < 0.985f) { if (diff >= 55 * this.getBlind()) return this.getResponse(diff, 0); if (diff >= this.getTotalJetton()) { return this.getResponse(diff, 0); } if (diff > 50 * this.getBlind()) return this.getResponse(diff, 0); return this.getResponse(diff, 2 * multiple * this.getBlind()); } else if (prob < 0.99f) { return this.getResponse(diff, 3 * multiple * this.getBlind()); } else { return this.getResponse(diff, this.getTotalJetton()); } } return this.getResponse(diff, multiple * this.getBlind()); } /** * 判断手牌是否是大对:AA, KK, QQ, JJ, 1010等 * * @param hp * 手牌 * @return 大对返回true, 否则返回false */ private boolean isHoldBigPair(ArrayList<Poker> hp) { // 避免出错 if (hp == null || hp.size() < 2) return false; // 手牌是大对:AA, KK, QQ, JJ, 1010等 else if (hp.get(0).getValue() == hp.get(1).getValue() && hp.get(0).getValue() >= Constants.MORE_GAP_VALUE) return true; return false; } // /** // * 处理其他玩家的该局押注情况,用于机器学习 // * @param holds // */ // public void parseOtherPlayerInfo(HashMap<String, ArrayList<Poker>> holdsMap) { // ArrayList<BetRecord> records = new ArrayList<BetRecord>(); // // for (BetState betstate: betStates) { // for (InitState initstate: initStates) { // if (!betstate.getPlayerID().equals(initstate.getPlayerID())) // continue; // String id = betstate.getPlayerID(); // int pos = this.computePlayerPosition(id); // int jet = initstate.getJetton(); // MlCardType type = this.computeMaxMlCardType(holdsMap.get(id), // this.getPublicPokers()); // float ost = this.computeMaxOtherStrategy(); // float st = this.computeStrategy(id); // // records.add(new BetRecord(id, pos, jet, type, ost, st)); // break; // } // } // // // 此处与机器学习模块对接 // for (BetRecord record: records) { // this.predictor.addUserUnit(new UserUnit(record.getPlayerID(), // this.getHandNum(), record.getPosition(), // (float)record.getJetton() / this.getBlind(), // record.getType().toString(), record.getOtherStrategy(), // record.getStrategy())); // } // } // // /** // * 计算玩家在牌桌的位置,用于机器学习 // * @param playerID // * @return "0|1|2" 分别表示"最后位置|首位|中间位置" // */ // private int computePlayerPosition(String playerID) { // int pos = 0; // for (int i = 0; i < initStates.size(); i++) { // if (initStates.get(i).equals(playerID)) { // pos = i; // break; // } // } // if (pos == 0) { // //最后位置 // return 2; // } // else if (pos == 1) { // //第一个位置 // return 0; // } // else { // //中间位置 // return 1; // } // } // // /** // * 计算玩家的最大机器学习牌型,用于机器学习 // * @param holds // * @param publics // * @return // */ // private MlCardType computeMaxMlCardType(ArrayList<Poker> holds, // ArrayList<Poker> publics) { // CardGroup maxGroup = (new MaxCardComputer(holds, publics)) // .getMaxCardGroup(); // // switch (maxGroup.getType()) { // case STRAIGHT_FLUSH: // case FOUR_OF_A_KIND: // case FULL_HOUSE: // return MlCardType.FULL_HOUSE_UP; // case FLUSH: // return MlCardType.FLUSH; // case STRAIGHT: // return MlCardType.STRAIGHT; // case THREE_OF_A_KIND: // return MlCardType.THREE_OF_A_KIND; // case TWO_PAIR: // if (maxGroup.getPokers().get(0).getValue() >= 9) // return MlCardType.HIGH_TWO_PAIR; // else // return MlCardType.LOW_TWO_PAIR; // case ONE_PAIR: // if (maxGroup.getPokers().get(0).getValue() >= 9) // return MlCardType.HIGH_ONE_PAIR; // else // return MlCardType.LOW_ONE_PAIR; // case HIGH_CARD: // return MlCardType.HIGH_CARD; // } // return MlCardType.HIGH_CARD; // } // // /** // * 计算其他玩家的最大押注策略,用于机器学习 // * @return // */ // private float computeMaxOtherStrategy() { // int maxJet = -1; // String maxSt = ""; // for (BetState state: betStates) { // if (state.getPlayerID().equals(this.getPlayerID())) // continue; // if (state.getBet() > maxJet) { // maxJet = state.getBet(); // maxSt = state.getAction(); // } // } // if (maxSt.equals("all_in")) // return -1; // else if (maxSt.equals("check")) // return 0; // else // return (float)maxJet / this.getBlind(); // } // // /** // * 计算玩家的押注策略,用于机器学习 // * @param playerID // * @return // */ // private float computeStrategy(String playerID) { // int jet = -1; // String st = ""; // for (BetState state: betStates) { // if (!state.getPlayerID().equals(playerID)) // continue; // jet = state.getBet(); // st = state.getAction(); // } // if (st.equals("all_in")) // return -1; // else if (st.equals("check")) // return 0; // else // return (float)jet / this.getBlind(); // } // // /** // * 使用机器学习根据玩家的当前押注情况预测牌型 // * @param state // * @return // */ // public HashMap<MlCardType, Float> computePlayerCardTypeByMl( // BetState state) { // String id = state.getPlayerID(); // int pos = this.computePlayerPosition(id); // int jet = 0; // for (InitState initstate: initStates) { // if (initstate.getPlayerID().equals(id)) // jet = initstate.getJetton(); // } // float ost = this.computeMaxOtherStrategy(); // float st = this.computeStrategy(id); // // // TODO: 与机器学习模块对接 // Set<Pair<String,Float>> res = this.predictor.getPredict(new UserUnit( // id, this.getHandNum(), pos, (float)jet / this.getBlind(), // "", ost, st)); // // HashMap<MlCardType, Float> map = new HashMap<MlCardType, Float>(); // for (Pair<String, Float> pair: res) { // switch (pair.first) { // case "FULL_HOUSE_UP": // map.put(MlCardType.FULL_HOUSE_UP, pair.second); // break; // case "FLUSH": // map.put(MlCardType.FLUSH, pair.second); // break; // case "STRAIGHT": // map.put(MlCardType.STRAIGHT, pair.second); // break; // case "THREE_OF_A_KIND": // map.put(MlCardType.THREE_OF_A_KIND, pair.second); // break; // case "HIGH_TWO_PAIR": // map.put(MlCardType.HIGH_TWO_PAIR, pair.second); // break; // case "LOW_TWO_PAIR": // map.put(MlCardType.LOW_TWO_PAIR, pair.second); // break; // case "HIGH_ONE_PAIR": // map.put(MlCardType.HIGH_ONE_PAIR, pair.second); // break; // case "LOW_ONE_PAIR": // map.put(MlCardType.LOW_ONE_PAIR, pair.second); // break; // case "HIGH_CARD": // map.put(MlCardType.HIGH_CARD, pair.second); // break; // } // } // return map; // } }
wangtaoking1/texaspoker
trunk/game/works/source/utils/SuperAI.java
66,558
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.view; import android.graphics.Matrix; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.util.SparseArray; /** * Object used to report movement (mouse, pen, finger, trackball) events. * Motion events may hold either absolute or relative movements and other data, * depending on the type of device. * * <h3>Overview</h3> * <p> * Motion events describe movements 运动 in terms of 依据 按照 an action code and a set of axis values. * The action code specifies the state change that occurred such as a pointer going * down or up. The axis values describe the position and other movement properties. * </p><p> * For example, when the user first touches the screen, the system delivers 分发 送货 传送 a touch * event to the appropriate {@link View} with the action code {@link #ACTION_DOWN} * and a set of axis values that include the X and Y coordinates of the touch and * information about the pressure, size and orientation of the contact 接触 area. * </p><p> * Some devices can report multiple movement traces at the same time. Multi-touch * screens emit 发出 one movement trace for each finger. The individual fingers or * other objects that generate movement traces are referred to as <em>pointers</em>. * Motion events contain information about all of the pointers that are currently active * even if some of them have not moved since the last event was delivered. * </p><p> * The number of pointers only ever changes by one as individual pointers go up and down, * except when the gesture is canceled. * </p><p> * Each pointer has a unique id that is assigned when it first goes down * (indicated by {@link #ACTION_DOWN} or {@link #ACTION_POINTER_DOWN}). A pointer id * remains valid until the pointer eventually goes up (indicated by {@link #ACTION_UP} * or {@link #ACTION_POINTER_UP}) or when the gesture is canceled (indicated by * {@link #ACTION_CANCEL}). * </p><p> * The MotionEvent class provides many methods to query the position and other properties of * pointers, such as {@link #getX(int)}, {@link #getY(int)}, {@link #getAxisValue}, * {@link #getPointerId(int)}, {@link #getToolType(int)}, and many others. Most of these * methods accept the pointer index as a parameter rather than the pointer id. * The pointer index of each pointer in the event ranges from 0 to one less than the value * returned by {@link #getPointerCount()}. * </p><p> * The order in which individual pointers appear within a motion event is undefined. * Thus the pointer index of a pointer can change from one event to the next but * the pointer id of a pointer is guaranteed to remain constant as long as the pointer * remains active. Use the {@link #getPointerId(int)} method to obtain the * pointer id of a pointer to track it across all subsequent 后来的 motion events in a gesture. * Then for successive 连续的 motion events, use the {@link #findPointerIndex(int)} method * to obtain the pointer index for a given pointer id in that motion event. * </p><p> * Mouse and stylus 触针 buttons can be retrieved using {@link #getButtonState()}. It is a * good idea to check the button state while handling {@link #ACTION_DOWN} as part * of a touch event. The application may choose to perform some different action * if the touch event starts due to a secondary button click, such as presenting a * context menu. * </p> * * <h3>Batching</h3> * <p> * For efficiency 效率 , motion events with {@link #ACTION_MOVE} may batch together * multiple 许多的 movement samples within a single object. The most current * pointer coordinates are available using {@link #getX(int)} and {@link #getY(int)}. * Earlier coordinates within the batch are accessed using {@link #getHistoricalX(int, int)} * and {@link #getHistoricalY(int, int)}. The coordinates are "historical" only * insofar as 在…的范围内 they are older than the current coordinates in the batch; however, * they are still distinct 有区别的 from any other coordinates reported in prior motion events. * To process all coordinates in the batch in time order, first consume the historical * coordinates then consume the current coordinates. * </p><p> * Example: Consuming all samples for all pointers in a motion event in time order. * </p><p><pre><code> * void printSamples(MotionEvent ev) { * final int historySize = ev.getHistorySize(); * final int pointerCount = ev.getPointerCount(); * for (int h = 0; h &lt; historySize; h++) { * System.out.printf("At time %d:", ev.getHistoricalEventTime(h)); * for (int p = 0; p &lt; pointerCount; p++) { * System.out.printf(" pointer %d: (%f,%f)", * ev.getPointerId(p), ev.getHistoricalX(p, h), ev.getHistoricalY(p, h)); * } * } * System.out.printf("At time %d:", ev.getEventTime()); * for (int p = 0; p &lt; pointerCount; p++) { * System.out.printf(" pointer %d: (%f,%f)", * ev.getPointerId(p), ev.getX(p), ev.getY(p)); * } * } * </code></pre></p> * * <h3>Device Types</h3> * <p> * The interpretation 解释 of the contents of a MotionEvent varies significantly 显著地 depending * on the source class of the device. * </p><p> * On pointing devices with source class {@link InputDevice#SOURCE_CLASS _POINTER} * such as touch screens, the pointer coordinates specify absolute * positions such as view X/Y coordinates. Each complete gesture is represented * by a sequence of motion events with actions that describe pointer state transitions * and movements. A gesture starts with a motion event with {@link #ACTION_DOWN} * that provides the location of the first pointer down. As each additional * pointer that goes down or up, the framework will generate a motion event with * {@link #ACTION_POINTER_DOWN} or {@link #ACTION_POINTER_UP} accordingly 相应地 . * Pointer movements are described by motion events with {@link #ACTION_MOVE}. * Finally, a gesture end either when the final pointer goes up as represented * by a motion event with {@link #ACTION_UP} or when gesture is canceled * with {@link #ACTION_CANCEL}. * </p><p> * Some pointing devices such as mice 老鼠 may support vertical and/or horizontal scrolling. * A scroll event is reported as a generic motion event with {@link #ACTION_SCROLL} that * includes the relative scroll offset in the {@link #AXIS_VSCROLL} and * {@link #AXIS_HSCROLL} axes. See {@link #getAxisValue(int)} for information * about retrieving these additional axes. * </p><p> * On trackball devices with source class {@link InputDevice#SOURCE_CLASS_TRACKBALL}, * the pointer coordinates specify relative movements as X/Y deltas. * A trackball gesture consists of a sequence of movements described by motion * events with {@link #ACTION_MOVE} interspersed 散布 with occasional 偶然的;临时的;特殊场合的 {@link #ACTION_DOWN} * or {@link #ACTION_UP} motion events when the trackball button is pressed or released. * </p><p> * On joystick 控制杆 devices with source class {@link InputDevice#SOURCE_CLASS_JOYSTICK}, * the pointer coordinates specify the absolute position of the joystick axes. * The joystick axis values are normalized to a range of -1.0 to 1.0 where 0.0 corresponds * to the center position. More information about the set of available axes and the * range of motion can be obtained using {@link InputDevice#getMotionRange}. * Some common joystick axes are {@link #AXIS_X}, {@link #AXIS_Y}, * {@link #AXIS_HAT_X}, {@link #AXIS_HAT_Y}, {@link #AXIS_Z} and {@link #AXIS_RZ}. * </p><p> * Refer to {@link InputDevice} for more information about how different kinds of * input devices and sources represent pointer coordinates. * </p> * * <h3>Consistency 一致性 Guarantees 保证 </h3> * <p> * Motion events are always delivered to views as a consistent 一致的 stream of events. * What constitutes 构成 a consistent stream varies depending on the type of device. * For touch events, consistency implies that pointers go down one at a time, * move around as a group and then go up one at a time or are canceled. * </p><p> * While the framework tries to deliver consistent streams of motion events to * views, it cannot guarantee it. Some events may be dropped or modified by * containing views in the application before they are delivered thereby 因此 making * the stream of events inconsistent. Views should always be prepared to * handle {@link #ACTION_CANCEL} and should tolerate 宽恕 anomalous 不规则的 * situations such as receiving a new {@link #ACTION_DOWN} without first having * received an {@link #ACTION_UP} for the prior gesture. * </p> */ public final class MotionEvent extends InputEvent implements Parcelable { private static final long NS_PER_MS = 1000000; private static final String LABEL_PREFIX = "AXIS_"; /** * An invalid pointer id. * * This value (-1) can be used as a placeholder to indicate that a pointer id * has not been assigned or is not available. It cannot appear as * a pointer id inside a {@link MotionEvent}. */ public static final int INVALID_POINTER_ID = -1; /** * Bit mask of the parts of the action code that are the action itself. */ public static final int ACTION_MASK = 0xff; /** * Constant for {@link #getActionMasked}: A pressed gesture has started, the * motion contains the initial starting location. * <p> * This is also a good time to check the button state to distinguish * secondary and tertiary 第三的 button clicks and handle them appropriately. * Use {@link #getButtonState} to retrieve the button state. * </p> */ public static final int ACTION_DOWN = 0; /** * Constant for {@link #getActionMasked}: A pressed gesture has finished, the * motion contains the final release location as well as any intermediate 中间的 * points since the last down or move event. */ public static final int ACTION_UP = 1; /** * Constant for {@link #getActionMasked}: A change has happened during a * press gesture (between {@link #ACTION_DOWN} and {@link #ACTION_UP}). * The motion contains the most recent point, as well as any intermediate 中间物 * points since the last down or move event. */ public static final int ACTION_MOVE = 2; /** * Constant for {@link #getActionMasked}: The current gesture has been aborted. * You will not receive any more points in it. You should treat this as * an up event, but not perform any action that you normally would. */ public static final int ACTION_CANCEL = 3; /** * Constant for {@link #getActionMasked}: A movement has happened outside of the * normal bounds of the UI element. This does not provide a full gesture, * but only the initial location of the movement/touch. */ public static final int ACTION_OUTSIDE = 4; /** * Constant for {@link #getActionMasked}: A non-primary pointer has gone down. * <p> * Use {@link #getActionIndex} to retrieve the index of the pointer that changed. * </p><p> * The index is encoded in the {@link #ACTION_POINTER_INDEX_MASK} bits of the * unmasked action returned by {@link #getAction}. * </p> */ public static final int ACTION_POINTER_DOWN = 5; /** * Constant for {@link #getActionMasked}: A non-primary pointer has gone up. * <p> * Use {@link #getActionIndex} to retrieve the index of the pointer that changed. * </p><p> * The index is encoded in the {@link #ACTION_POINTER_INDEX_MASK} bits of the * unmasked action returned by {@link #getAction}. * </p> */ public static final int ACTION_POINTER_UP = 6; /** * Constant for {@link #getActionMasked}: A change happened but the pointer * is not down (unlike {@link #ACTION_MOVE}). The motion contains the most * recent point, as well as any intermediate points since the last * hover move event. * <p> * This action is always delivered to the window or view under the pointer. * </p><p> * This action is not a touch event so it is delivered to * {@link View#onGenericMotionEvent(MotionEvent)} rather than * {@link View#onTouchEvent(MotionEvent)}. * </p> */ public static final int ACTION_HOVER_MOVE = 7; /** * Constant for {@link #getActionMasked}: The motion event contains relative * vertical and/or horizontal scroll offsets. Use {@link #getAxisValue(int)} * to retrieve the information from {@link #AXIS_VSCROLL} and {@link #AXIS_HSCROLL}. * The pointer may or may not be down when this event is dispatched. * <p> * This action is always delivered to the window or view under the pointer, which * may not be the window or view currently touched. * </p><p> * This action is not a touch event so it is delivered to * {@link View#onGenericMotionEvent(MotionEvent)} rather than * {@link View#onTouchEvent(MotionEvent)}. * </p> */ public static final int ACTION_SCROLL = 8; /** * Constant for {@link #getActionMasked}: The pointer is not down but has entered the * boundaries of a window or view. * <p> * This action is always delivered to the window or view under the pointer. * </p><p> * This action is not a touch event so it is delivered to * {@link View#onGenericMotionEvent(MotionEvent)} rather than * {@link View#onTouchEvent(MotionEvent)}. * </p> */ public static final int ACTION_HOVER_ENTER = 9; /** * Constant for {@link #getActionMasked}: The pointer is not down but has exited the * boundaries of a window or view. * <p> * This action is always delivered to the window or view that was previously under the pointer. * </p><p> * This action is not a touch event so it is delivered to * {@link View#onGenericMotionEvent(MotionEvent)} rather than * {@link View#onTouchEvent(MotionEvent)}. * </p> */ public static final int ACTION_HOVER_EXIT = 10; /** * Constant for {@link #getActionMasked}: A button has been pressed. * * <p> * Use {@link #getActionButton()} to get which button was pressed. * </p><p> * This action is not a touch event so it is delivered to * {@link View#onGenericMotionEvent(MotionEvent)} rather than * {@link View#onTouchEvent(MotionEvent)}. * </p> */ public static final int ACTION_BUTTON_PRESS = 11; /** * Constant for {@link #getActionMasked}: A button has been released. * * <p> * Use {@link #getActionButton()} to get which button was released. * </p><p> * This action is not a touch event so it is delivered to * {@link View#onGenericMotionEvent(MotionEvent)} rather than * {@link View#onTouchEvent(MotionEvent)}. * </p> */ public static final int ACTION_BUTTON_RELEASE = 12; /** * Bits in the action code that represent a pointer index, used with * {@link #ACTION_POINTER_DOWN} and {@link #ACTION_POINTER_UP}. Shifting * down by {@link #ACTION_POINTER_INDEX_SHIFT} provides the actual pointer * index where the data for the pointer going up or down can be found; you can * get its identifier with {@link #getPointerId(int)} and the actual * data with {@link #getX(int)} etc. * * @see #getActionIndex */ public static final int ACTION_POINTER_INDEX_MASK = 0xff00; /** * Bit shift for the action bits holding the pointer index as * defined by {@link #ACTION_POINTER_INDEX_MASK}. * * @see #getActionIndex */ public static final int ACTION_POINTER_INDEX_SHIFT = 8; /** * @deprecated Use {@link #ACTION_POINTER_INDEX_MASK} to retrieve the * data index associated with {@link #ACTION_POINTER_DOWN}. */ @Deprecated public static final int ACTION_POINTER_1_DOWN = ACTION_POINTER_DOWN | 0x0000; /** * @deprecated Use {@link #ACTION_POINTER_INDEX_MASK} to retrieve the * data index associated with {@link #ACTION_POINTER_DOWN}. */ @Deprecated public static final int ACTION_POINTER_2_DOWN = ACTION_POINTER_DOWN | 0x0100; /** * @deprecated Use {@link #ACTION_POINTER_INDEX_MASK} to retrieve the * data index associated with {@link #ACTION_POINTER_DOWN}. */ @Deprecated public static final int ACTION_POINTER_3_DOWN = ACTION_POINTER_DOWN | 0x0200; /** * @deprecated Use {@link #ACTION_POINTER_INDEX_MASK} to retrieve the * data index associated with {@link #ACTION_POINTER_UP}. */ @Deprecated public static final int ACTION_POINTER_1_UP = ACTION_POINTER_UP | 0x0000; /** * @deprecated Use {@link #ACTION_POINTER_INDEX_MASK} to retrieve the * data index associated with {@link #ACTION_POINTER_UP}. */ @Deprecated public static final int ACTION_POINTER_2_UP = ACTION_POINTER_UP | 0x0100; /** * @deprecated Use {@link #ACTION_POINTER_INDEX_MASK} to retrieve the * data index associated with {@link #ACTION_POINTER_UP}. */ @Deprecated public static final int ACTION_POINTER_3_UP = ACTION_POINTER_UP | 0x0200; /** * @deprecated Renamed to {@link #ACTION_POINTER_INDEX_MASK} to match * the actual data contained in these bits. */ @Deprecated public static final int ACTION_POINTER_ID_MASK = 0xff00; /** * @deprecated Renamed to {@link #ACTION_POINTER_INDEX_SHIFT} to match * the actual data contained in these bits. */ @Deprecated public static final int ACTION_POINTER_ID_SHIFT = 8; /** * This flag indicates that the window that received this motion event is partly * or wholly obscured by another visible window above it. This flag is set to true * even if the event did not directly pass through the obscured area. * A security sensitive application can check this flag to identify situations in which * a malicious 恶意的 application may have covered up part of its content for the purpose * of misleading the user or hijacking 劫持 touches. An appropriate response might be * to drop the suspect 犯罪嫌疑人 touches or to take additional precautions 防范 to confirm 证实 the user's * actual intent. */ public static final int FLAG_WINDOW_IS_OBSCURED = 0x1; /** * This flag indicates that the window that received this motion event is partly * or wholly obscured by another visible window above it. This flag is set to true * even if the event did not directly pass through the obscured area. * A security sensitive application can check this flag to identify situations in which * a malicious application may have covered up part of its content for the purpose * of misleading the user or hijacking . 劫持 touches. An appropriate response might be * to drop the suspect touches or to take additional precautions to confirm the user's * actual intent. * * Unlike FLAG_WINDOW_IS_OBSCURED, this is actually true. * @hide */ public static final int FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 0x2; /** * Private flag that indicates when the system has detected that this motion event * may be inconsistent with respect to the sequence of previously delivered motion events, * such as when a pointer move event is sent but the pointer is not down. * * @hide * @see #isTainted * @see #setTainted */ public static final int FLAG_TAINTED = 0x80000000; /** * Private flag indicating that this event was synthesized 综合的 by the system and * should be delivered to the accessibility focused view first. When being * dispatched such an event is not handled by predecessors 前任 of the accessibility * focused view and after the event reaches that view the flag is cleared and * normal event dispatch is performed. This ensures that the platform can click * on any view that has accessibility focus which is semantically 语义地 equivalent 相等的 to * asking the view to perform a click accessibility action but more generic 一般的 as * views not implementing click action correctly can still be activated. * * @hide * @see #isTargetAccessibilityFocus() * @see #setTargetAccessibilityFocus(boolean) */ //// TODO: 2017/9/4 public static final int FLAG_TARGET_ACCESSIBILITY_FOCUS = 0x40000000; /** * Flag indicating the motion event intersected 分割的 横穿 相交 the top edge of the screen. */ public static final int EDGE_TOP = 0x00000001; /** * Flag indicating the motion event intersected the bottom edge of the screen. */ public static final int EDGE_BOTTOM = 0x00000002; /** * Flag indicating the motion event intersected the left edge of the screen. */ public static final int EDGE_LEFT = 0x00000004; /** * Flag indicating the motion event intersected the right edge of the screen. */ public static final int EDGE_RIGHT = 0x00000008; /** * Axis constant: X axis of a motion event. * <p> * <ul> * <li>For a touch screen, reports the absolute X screen position of the center of * the touch contact area. The units are display pixels. * <li>For a touch pad, reports the absolute X surface position of the center of the touch * contact area. The units are device-dependent; use {@link InputDevice#getMotionRange(int)} * to query the effective range of values. * <li>For a mouse, reports the absolute X screen position of the mouse pointer. * The units are display pixels. * <li>For a trackball, reports the relative horizontal displacement 位移 of the trackball. * The value is normalized to a range from -1.0 (left) to 1.0 (right). * <li>For a joystick, reports the absolute X position of the joystick. * The value is normalized to a range from -1.0 (left) to 1.0 (right). * </ul> * </p> * * @see #getX(int) * @see #getHistoricalX(int, int) * @see MotionEvent.PointerCoords#x * @see InputDevice#getMotionRange */ public static final int AXIS_X = 0; /** * Axis constant: Y axis of a motion event. * <p> * <ul> * <li>For a touch screen, reports the absolute Y screen position of the center of * the touch contact area. The units are display pixels. * <li>For a touch pad, reports the absolute Y surface position of the center of the touch * contact area. The units are device-dependent; use {@link InputDevice#getMotionRange(int)} * to query the effective range of values. * <li>For a mouse, reports the absolute Y screen position of the mouse pointer. * The units are display pixels. * <li>For a trackball, reports the relative vertical displacement of the trackball. * The value is normalized to a range from -1.0 (up) to 1.0 (down). * <li>For a joystick, reports the absolute Y position of the joystick. * The value is normalized to a range from -1.0 (up or far) to 1.0 (down or near). * </ul> * </p> * * @see #getY(int) * @see #getHistoricalY(int, int) * @see MotionEvent.PointerCoords#y * @see InputDevice#getMotionRange */ public static final int AXIS_Y = 1; /** * Axis constant: Pressure axis of a motion event. * <p> * <ul> * <li>For a touch screen or touch pad, reports the approximate pressure applied to the surface * by a finger or other tool. The value is normalized to a range from * 0 (no pressure at all) to 1 (normal pressure), although values higher than 1 * may be generated depending on the calibration 校准 of the input device. * <li>For a trackball, the value is set to 1 if the trackball button is pressed * or 0 otherwise. * <li>For a mouse, the value is set to 1 if the primary mouse button is pressed * or 0 otherwise. * </ul> * </p> * * @see #getPressure(int) * @see #getHistoricalPressure(int, int) * @see MotionEvent.PointerCoords#pressure * @see InputDevice#getMotionRange */ public static final int AXIS_PRESSURE = 2; /** * Axis constant: Size axis of a motion event. * <p> * <ul> * <li>For a touch screen or touch pad, reports the approximate size of the contact area in * relation to the maximum detectable size for the device. The value is normalized * to a range from 0 (smallest detectable size) to 1 (largest detectable size), * although it is not a linear scale. This value is of limited use. * To obtain calibrated 校准 size information, use * {@link #AXIS_TOUCH_MAJOR} or {@link #AXIS_TOOL_MAJOR}. * </ul> * </p> * * @see #getSize(int) * @see #getHistoricalSize(int, int) * @see MotionEvent.PointerCoords#size * @see InputDevice#getMotionRange */ public static final int AXIS_SIZE = 3; /** * Axis constant: TouchMajor axis of a motion event. * <p> * <ul> * <li>For a touch screen, reports the length of the major axis of an ellipse 椭圆形 that * represents the touch area at the point of contact. * The units are display pixels. * <li>For a touch pad, reports the length of the major axis of an ellipse that * represents the touch area at the point of contact. * The units are device-dependent; use {@link InputDevice#getMotionRange(int)} * to query the effective range of values. * </ul> * </p> * * @see #getTouchMajor(int) * @see #getHistoricalTouchMajor(int, int) * @see MotionEvent.PointerCoords#touchMajor * @see InputDevice#getMotionRange */ public static final int AXIS_TOUCH_MAJOR = 4; /** * Axis constant: TouchMinor axis of a motion event. * <p> * <ul> * <li>For a touch screen, reports the length of the minor axis of an ellipse that * represents the touch area at the point of contact. * The units are display pixels. * <li>For a touch pad, reports the length of the minor axis of an ellipse that * represents the touch area at the point of contact. * The units are device-dependent; use {@link InputDevice#getMotionRange(int)} * to query the effective range of values. * </ul> * </p><p> * When the touch is circular 圆形的 , the major and minor axis lengths will be equal to one another. * </p> * * @see #getTouchMinor(int) * @see #getHistoricalTouchMinor(int, int) * @see MotionEvent.PointerCoords#touchMinor * @see InputDevice#getMotionRange */ public static final int AXIS_TOUCH_MINOR = 5; /** * Axis constant: ToolMajor axis of a motion event. * <p> * <ul> * <li>For a touch screen, reports the length of the major axis of an ellipse that * represents the size of the approaching 接近 finger or tool used to make contact. * <li>For a touch pad, reports the length of the major axis of an ellipse that * represents the size of the approaching finger or tool used to make contact. * The units are device-dependent; use {@link InputDevice#getMotionRange(int)} * to query the effective range of values. * </ul> * </p><p> * When the touch is circular, the major and minor axis lengths will be equal to one another. * </p><p> * The tool size may be larger than the touch size since the tool may not be fully * in contact with the touch sensor. * </p> * * @see #getToolMajor(int) * @see #getHistoricalToolMajor(int, int) * @see MotionEvent.PointerCoords#toolMajor * @see InputDevice#getMotionRange */ public static final int AXIS_TOOL_MAJOR = 6; /** * Axis constant: ToolMinor axis of a motion event. * <p> * <ul> * <li>For a touch screen, reports the length of the minor axis of an ellipse that * represents the size of the approaching finger or tool used to make contact. * <li>For a touch pad, reports the length of the minor axis of an ellipse that * represents the size of the approaching finger or tool used to make contact. * The units are device-dependent; use {@link InputDevice#getMotionRange(int)} * to query the effective range of values. * </ul> * </p><p> * When the touch is circular, the major and minor axis lengths will be equal to one another. * </p><p> * The tool size may be larger than the touch size since the tool may not be fully * in contact with the touch sensor. * </p> * * @see #getToolMinor(int) * @see #getHistoricalToolMinor(int, int) * @see MotionEvent.PointerCoords#toolMinor * @see InputDevice#getMotionRange */ public static final int AXIS_TOOL_MINOR = 7; /** * Axis constant: Orientation axis of a motion event. * <p> * <ul> * <li>For a touch screen or touch pad, reports the orientation of the finger * or tool in radians 弧度 relative to the vertical plane 垂直面 of the device. * An angle of 0 radians indicates that the major axis of contact is oriented * upwards 向上 , is perfectly circular 循环的;圆形的 or is of unknown orientation. A positive angle * indicates that the major axis of contact is oriented to the right. A negative angle * indicates that the major axis of contact is oriented to the left. * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians * (finger pointing fully right). * <li>For a stylus, the orientation indicates the direction in which the stylus * is pointing in relation to the vertical axis of the current orientation of the screen. * The range is from -PI radians to PI radians, where 0 is pointing up, * -PI/2 radians is pointing left, -PI or PI radians is pointing down, and PI/2 radians * is pointing right. See also {@link #AXIS_TILT}. * </ul> * </p> * * @see #getOrientation(int) * @see #getHistoricalOrientation(int, int) * @see MotionEvent.PointerCoords#orientation * @see InputDevice#getMotionRange */ public static final int AXIS_ORIENTATION = 8; /** * Axis constant: Vertical Scroll axis of a motion event. * <p> * <ul> * <li>For a mouse, reports the relative movement of the vertical scroll wheel. * The value is normalized to a range from -1.0 (down) to 1.0 (up). * </ul> * </p><p> * This axis should be used to scroll views vertically. * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_VSCROLL = 9; /** * Axis constant: Horizontal Scroll axis of a motion event. * <p> * <ul> * <li>For a mouse, reports the relative movement of the horizontal scroll wheel. * The value is normalized to a range from -1.0 (left) to 1.0 (right). * </ul> * </p><p> * This axis should be used to scroll views horizontally. * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_HSCROLL = 10; /** * Axis constant: Z axis of a motion event. * <p> * <ul> * <li>For a joystick 操纵杆 , reports the absolute Z position of the joystick. * The value is normalized to a range from -1.0 (high) to 1.0 (low). * <em>On game pads with two analog joysticks, this axis is often reinterpreted 重新解释 * to report the absolute X position of the second joystick instead.</em> * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_Z = 11; /** * Axis constant: X Rotation axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute rotation angle about the X axis. * The value is normalized to a range from -1.0 (counter-clockwise) to 1.0 (clockwise). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_RX = 12; /** * Axis constant: Y Rotation axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute rotation angle about the Y axis. * The value is normalized to a range from -1.0 (counter-clockwise) to 1.0 (clockwise). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_RY = 13; /** * Axis constant: Z Rotation axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute rotation angle about the Z axis. * The value is normalized to a range from -1.0 (counter-clockwise) to 1.0 (clockwise). * <em>On game pads with two analog joysticks, this axis is often reinterpreted * to report the absolute Y position of the second joystick instead.</em> * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_RZ = 14; /** * Axis constant: Hat 帽子 帽子 带沿的帽子 X axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute X position of the directional 方向的 hat control. * The value is normalized to a range from -1.0 (left) to 1.0 (right). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_HAT_X = 15; /** * Axis constant: Hat Y axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute Y position of the directional hat control. * The value is normalized to a range from -1.0 (up) to 1.0 (down). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_HAT_Y = 16; /** * Axis constant: Left Trigger 扳机;[电子] 触发器;制滑机 axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute position of the left trigger control. * The value is normalized to a range from 0.0 (released) to 1.0 (fully pressed). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_LTRIGGER = 17; /** * Axis constant: Right Trigger axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute position of the right trigger control. * The value is normalized to a range from 0.0 (released) to 1.0 (fully pressed). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_RTRIGGER = 18; /** * Axis constant: Throttle 节流阀 axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute position of the throttle control. * The value is normalized to a range from 0.0 (fully open) to 1.0 (fully closed). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_THROTTLE = 19; /** * Axis constant: Rudder 方向舵 axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute position of the rudder control. * The value is normalized to a range from -1.0 (turn left) to 1.0 (turn right). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_RUDDER = 20; /** * Axis constant: Wheel 方向盘 axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute position of the steering 驾驶 wheel 方向盘 control. * The value is normalized to a range from -1.0 (turn left) to 1.0 (turn right). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_WHEEL = 21; /** * Axis constant: Gas 气体 煤气 瓦斯 axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute position of the gas (accelerator) control. * The value is normalized to a range from 0.0 (no acceleration) * to 1.0 (maximum acceleration). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GAS = 22; /** * Axis constant: Brake 刹车 axis of a motion event. * <p> * <ul> * <li>For a joystick, reports the absolute position of the brake 刹车 control. * The value is normalized to a range from 0.0 (no braking) to 1.0 (maximum braking). * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_BRAKE = 23; /** * Axis constant: Distance axis of a motion event. * <p> * <ul> * <li>For a stylus, reports the distance of the stylus from the screen. * A value of 0.0 indicates direct contact and larger values indicate increasing * distance from the surface. * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_DISTANCE = 24; /** * Axis constant: Tilt 倾斜 axis of a motion event. * <p> * <ul> * <li>For a stylus, reports the tilt angle of the stylus in radians 弧度 where * 0 radians indicates that the stylus is being held perpendicular 垂直的 to the * surface, and PI/2 radians indicates that the stylus is being held flat * against the surface. * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int, int) * @see InputDevice#getMotionRange */ public static final int AXIS_TILT = 25; /** * Axis constant: Generic scroll axis of a motion event. * <p> * <ul> * <li>Reports the relative movement of the generic scrolling device. * </ul> * </p><p> * This axis should be used for scroll events that are neither strictly 严格地 vertical nor horizontal. * A good example would be the rotation 旋转 of a rotary 旋转的 encoder 编码器 input device. * </p> * * @see #getAxisValue(int, int) * {@hide} */ public static final int AXIS_SCROLL = 26; /** * Axis constant: The movement of x position of a motion event. * <p> * <ul> * <li>For a mouse, reports a difference of x position between the previous position. * This is useful when pointer is captured, in that case the mouse pointer doesn't change * the location but this axis reports the difference which allows the app to see * how the mouse is moved. * </ul> * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int, int) * @see InputDevice#getMotionRange */ public static final int AXIS_RELATIVE_X = 27; /** * Axis constant: The movement of y position of a motion event. * <p> * This is similar to {@link #AXIS_RELATIVE_X} but for y-axis. * </p> * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int, int) * @see InputDevice#getMotionRange */ public static final int AXIS_RELATIVE_Y = 28; /** * Axis constant: Generic 1 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_1 = 32; /** * Axis constant: Generic 2 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_2 = 33; /** * Axis constant: Generic 3 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_3 = 34; /** * Axis constant: Generic 4 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_4 = 35; /** * Axis constant: Generic 5 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_5 = 36; /** * Axis constant: Generic 6 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_6 = 37; /** * Axis constant: Generic 7 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_7 = 38; /** * Axis constant: Generic 8 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_8 = 39; /** * Axis constant: Generic 9 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_9 = 40; /** * Axis constant: Generic 10 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_10 = 41; /** * Axis constant: Generic 11 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_11 = 42; /** * Axis constant: Generic 12 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_12 = 43; /** * Axis constant: Generic 13 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_13 = 44; /** * Axis constant: Generic 14 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_14 = 45; /** * Axis constant: Generic 15 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_15 = 46; /** * Axis constant: Generic 16 axis of a motion event. * The interpretation of a generic axis is device-specific. * * @see #getAxisValue(int, int) * @see #getHistoricalAxisValue(int, int, int) * @see MotionEvent.PointerCoords#getAxisValue(int) * @see InputDevice#getMotionRange */ public static final int AXIS_GENERIC_16 = 47; // NOTE: If you add a new axis here you must also add it to: // native/include/android/input.h // frameworks/base/include/ui/KeycodeLabels.h // Symbolic names of all axes. private static final SparseArray<String> AXIS_SYMBOLIC_NAMES = new SparseArray<String>(); static { SparseArray<String> names = AXIS_SYMBOLIC_NAMES; names.append(AXIS_X, "AXIS_X"); names.append(AXIS_Y, "AXIS_Y"); names.append(AXIS_PRESSURE, "AXIS_PRESSURE"); names.append(AXIS_SIZE, "AXIS_SIZE"); names.append(AXIS_TOUCH_MAJOR, "AXIS_TOUCH_MAJOR"); names.append(AXIS_TOUCH_MINOR, "AXIS_TOUCH_MINOR"); names.append(AXIS_TOOL_MAJOR, "AXIS_TOOL_MAJOR"); names.append(AXIS_TOOL_MINOR, "AXIS_TOOL_MINOR"); names.append(AXIS_ORIENTATION, "AXIS_ORIENTATION"); names.append(AXIS_VSCROLL, "AXIS_VSCROLL"); names.append(AXIS_HSCROLL, "AXIS_HSCROLL"); names.append(AXIS_Z, "AXIS_Z"); names.append(AXIS_RX, "AXIS_RX"); names.append(AXIS_RY, "AXIS_RY"); names.append(AXIS_RZ, "AXIS_RZ"); names.append(AXIS_HAT_X, "AXIS_HAT_X"); names.append(AXIS_HAT_Y, "AXIS_HAT_Y"); names.append(AXIS_LTRIGGER, "AXIS_LTRIGGER"); names.append(AXIS_RTRIGGER, "AXIS_RTRIGGER"); names.append(AXIS_THROTTLE, "AXIS_THROTTLE"); names.append(AXIS_RUDDER, "AXIS_RUDDER"); names.append(AXIS_WHEEL, "AXIS_WHEEL"); names.append(AXIS_GAS, "AXIS_GAS"); names.append(AXIS_BRAKE, "AXIS_BRAKE"); names.append(AXIS_DISTANCE, "AXIS_DISTANCE"); names.append(AXIS_TILT, "AXIS_TILT"); names.append(AXIS_SCROLL, "AXIS_SCROLL"); names.append(AXIS_RELATIVE_X, "AXIS_REALTIVE_X"); names.append(AXIS_RELATIVE_Y, "AXIS_REALTIVE_Y"); names.append(AXIS_GENERIC_1, "AXIS_GENERIC_1"); names.append(AXIS_GENERIC_2, "AXIS_GENERIC_2"); names.append(AXIS_GENERIC_3, "AXIS_GENERIC_3"); names.append(AXIS_GENERIC_4, "AXIS_GENERIC_4"); names.append(AXIS_GENERIC_5, "AXIS_GENERIC_5"); names.append(AXIS_GENERIC_6, "AXIS_GENERIC_6"); names.append(AXIS_GENERIC_7, "AXIS_GENERIC_7"); names.append(AXIS_GENERIC_8, "AXIS_GENERIC_8"); names.append(AXIS_GENERIC_9, "AXIS_GENERIC_9"); names.append(AXIS_GENERIC_10, "AXIS_GENERIC_10"); names.append(AXIS_GENERIC_11, "AXIS_GENERIC_11"); names.append(AXIS_GENERIC_12, "AXIS_GENERIC_12"); names.append(AXIS_GENERIC_13, "AXIS_GENERIC_13"); names.append(AXIS_GENERIC_14, "AXIS_GENERIC_14"); names.append(AXIS_GENERIC_15, "AXIS_GENERIC_15"); names.append(AXIS_GENERIC_16, "AXIS_GENERIC_16"); } /** * Button constant: Primary button (left mouse button). * * This button constant is not set in response to simple touches with a finger * or stylus tip. The user must actually push a button. * * @see #getButtonState */ public static final int BUTTON_PRIMARY = 1 << 0; /** * Button constant: Secondary button (right mouse button). * * @see #getButtonState */ public static final int BUTTON_SECONDARY = 1 << 1; /** * Button constant: Tertiary 第三的 button (middle mouse button). * * @see #getButtonState */ public static final int BUTTON_TERTIARY = 1 << 2; /** * Button constant: Back button pressed (mouse back button). * <p> * The system may send a {@link KeyEvent#KEYCODE_BACK} key press to the application * when this button is pressed. * </p> * * @see #getButtonState */ public static final int BUTTON_BACK = 1 << 3; /** * Button constant: Forward button pressed (mouse forward button). * <p> * The system may send a {@link KeyEvent#KEYCODE_FORWARD} key press to the application * when this button is pressed. * </p> * * @see #getButtonState */ public static final int BUTTON_FORWARD = 1 << 4; /** * Button constant: Primary stylus button pressed. * * @see #getButtonState */ public static final int BUTTON_STYLUS_PRIMARY = 1 << 5; /** * Button constant: Secondary stylus button pressed. * * @see #getButtonState */ public static final int BUTTON_STYLUS_SECONDARY = 1 << 6; // NOTE: If you add a new axis here you must also add it to: // native/include/android/input.h // Symbolic names of all button states in bit order from least significant // to most significant. private static final String[] BUTTON_SYMBOLIC_NAMES = new String[] { "BUTTON_PRIMARY", "BUTTON_SECONDARY", "BUTTON_TERTIARY", "BUTTON_BACK", "BUTTON_FORWARD", "BUTTON_STYLUS_PRIMARY", "BUTTON_STYLUS_SECONDARY", "0x00000080", "0x00000100", "0x00000200", "0x00000400", "0x00000800", "0x00001000", "0x00002000", "0x00004000", "0x00008000", "0x00010000", "0x00020000", "0x00040000", "0x00080000", "0x00100000", "0x00200000", "0x00400000", "0x00800000", "0x01000000", "0x02000000", "0x04000000", "0x08000000", "0x10000000", "0x20000000", "0x40000000", "0x80000000", }; /** * Tool type constant: Unknown tool type. * This constant is used when the tool type is not known or is not relevant 目的明确的 , * such as for a trackball or other non-pointing device. * * @see #getToolType */ public static final int TOOL_TYPE_UNKNOWN = 0; /** * Tool type constant: The tool is a finger. * * @see #getToolType */ public static final int TOOL_TYPE_FINGER = 1; /** * Tool type constant: The tool is a stylus. * * @see #getToolType */ public static final int TOOL_TYPE_STYLUS = 2; /** * Tool type constant: The tool is a mouse or trackpad 触控板 . * * @see #getToolType */ public static final int TOOL_TYPE_MOUSE = 3; /** * Tool type constant: The tool is an eraser or a stylus being used in an inverted 反转 posture 姿势 . * * @see #getToolType */ public static final int TOOL_TYPE_ERASER = 4; // NOTE: If you add a new tool type here you must also add it to: // native/include/android/input.h // Symbolic names of all tool types. private static final SparseArray<String> TOOL_TYPE_SYMBOLIC_NAMES = new SparseArray<String>(); static { SparseArray<String> names = TOOL_TYPE_SYMBOLIC_NAMES; names.append(TOOL_TYPE_UNKNOWN, "TOOL_TYPE_UNKNOWN"); names.append(TOOL_TYPE_FINGER, "TOOL_TYPE_FINGER"); names.append(TOOL_TYPE_STYLUS, "TOOL_TYPE_STYLUS"); names.append(TOOL_TYPE_MOUSE, "TOOL_TYPE_MOUSE"); names.append(TOOL_TYPE_ERASER, "TOOL_TYPE_ERASER"); } // Private value for history pos that obtains the current sample. private static final int HISTORY_CURRENT = -0x80000000; private static final int MAX_RECYCLED = 10; private static final Object gRecyclerLock = new Object(); private static int gRecyclerUsed; private static MotionEvent gRecyclerTop; // Shared temporary 临时 objects used when translating coordinates supplied by // the caller into single element PointerCoords and pointer id arrays. private static final Object gSharedTempLock = new Object(); private static PointerCoords[] gSharedTempPointerCoords; private static PointerProperties[] gSharedTempPointerProperties; private static int[] gSharedTempPointerIndexMap; private static final void ensureSharedTempPointerCapacity(int desiredCapacity) { if (gSharedTempPointerCoords == null || gSharedTempPointerCoords.length < desiredCapacity) { int capacity = gSharedTempPointerCoords != null ? gSharedTempPointerCoords.length : 8; while (capacity < desiredCapacity) { capacity *= 2; } gSharedTempPointerCoords = PointerCoords.createArray(capacity); gSharedTempPointerProperties = PointerProperties.createArray(capacity); gSharedTempPointerIndexMap = new int[capacity]; } } // Pointer to the native MotionEvent object that contains the actual data. private long mNativePtr; private MotionEvent mNext; private MotionEvent() { } @Override protected void finalize() throws Throwable { try { if (mNativePtr != 0) { nativeDispose(mNativePtr); // 处置 mNativePtr = 0; } } finally { super.finalize(); } } static private MotionEvent obtain() { final MotionEvent ev; synchronized (gRecyclerLock) { ev = gRecyclerTop; if (ev == null) { return new MotionEvent(); } gRecyclerTop = ev.mNext; gRecyclerUsed -= 1; } ev.mNext = null; ev.prepareForReuse(); return ev; } /** * Create a new MotionEvent, filling in all of the basic values that * define the motion. * * @param downTime The time (in ms) when the user originally pressed down to start * a stream of position events. This must be obtained from {@link SystemClock#uptimeMillis()}. * @param eventTime The the time (in ms) when this specific event was generated. This * must be obtained from {@link SystemClock#uptimeMillis()}. * @param action The kind of action being performed, such as {@link #ACTION_DOWN}. * @param pointerCount The number of pointers that will be in this event. * @param pointerProperties An array of <em>pointerCount</em> values providing * a {@link PointerProperties} property object for each pointer, which must * include the pointer identifier. * @param pointerCoords An array of <em>pointerCount</em> values providing * a {@link PointerCoords} coordinate object for each pointer. * @param metaState The state of any meta / modifier keys that were in effect when * the event was generated. * @param buttonState The state of buttons that are pressed. * @param xPrecision The precision of the X coordinate being reported. * @param yPrecision The precision of the Y coordinate being reported. * @param deviceId The id for the device that this event came from. An id of * zero indicates that the event didn't come from a physical device; other * numbers are arbitrary and you shouldn't depend on the values. * @param edgeFlags A bitfield 位字段 indicating which edges, if any, were touched by this * MotionEvent. * @param source The source of this event. * @param flags The motion event flags. */ static public MotionEvent obtain(long downTime, long eventTime, int action, int pointerCount, PointerProperties[] pointerProperties, PointerCoords[] pointerCoords, int metaState, int buttonState, float xPrecision, float yPrecision, int deviceId, int edgeFlags, int source, int flags) { MotionEvent ev = obtain(); ev.mNativePtr = nativeInitialize(ev.mNativePtr, deviceId, source, action, flags, edgeFlags, metaState, buttonState, 0, 0, xPrecision, yPrecision, downTime * NS_PER_MS, eventTime * NS_PER_MS, pointerCount, pointerProperties, pointerCoords); return ev; } /** * Create a new MotionEvent, filling in all of the basic values that * define the motion. * * @param downTime The time (in ms) when the user originally pressed down to start * a stream of position events. This must be obtained from {@link SystemClock#uptimeMillis()}. * @param eventTime The the time (in ms) when this specific event was generated. This * must be obtained from {@link SystemClock#uptimeMillis()}. * @param action The kind of action being performed, such as {@link #ACTION_DOWN}. * @param pointerCount The number of pointers that will be in this event. * @param pointerIds An array of <em>pointerCount</em> values providing * an identifier for each pointer. * @param pointerCoords An array of <em>pointerCount</em> values providing * a {@link PointerCoords} coordinate object for each pointer. * @param metaState The state of any meta / modifier keys that were in effect when * the event was generated. * @param xPrecision The precision of the X coordinate being reported. * @param yPrecision The precision of the Y coordinate being reported. * @param deviceId The id for the device that this event came from. An id of * zero indicates that the event didn't come from a physical device; other * numbers are arbitrary and you shouldn't depend on the values. * @param edgeFlags A bitfield indicating which edges, if any, were touched by this * MotionEvent. * @param source The source of this event. * @param flags The motion event flags. * * @deprecated Use {@link #obtain(long, long, int, int, PointerProperties[], PointerCoords[], int, int, float, float, int, int, int, int)} * instead. */ @Deprecated static public MotionEvent obtain(long downTime, long eventTime, int action, int pointerCount, int[] pointerIds, PointerCoords[] pointerCoords, int metaState, float xPrecision, float yPrecision, int deviceId, int edgeFlags, int source, int flags) { synchronized (gSharedTempLock) { ensureSharedTempPointerCapacity(pointerCount); final PointerProperties[] pp = gSharedTempPointerProperties; for (int i = 0; i < pointerCount; i++) { pp[i].clear(); pp[i].id = pointerIds[i]; } return obtain(downTime, eventTime, action, pointerCount, pp, pointerCoords, metaState, 0, xPrecision, yPrecision, deviceId, edgeFlags, source, flags); } } /** * Create a new MotionEvent, filling in all of the basic values that * define the motion. * * @param downTime The time (in ms) when the user originally pressed down to start * a stream of position events. This must be obtained from {@link SystemClock#uptimeMillis()}. * @param eventTime The the time (in ms) when this specific event was generated. This * must be obtained from {@link SystemClock#uptimeMillis()}. * @param action The kind of action being performed, such as {@link #ACTION_DOWN}. * @param x The X coordinate of this event. * @param y The Y coordinate of this event. * @param pressure The current pressure of this event. The pressure generally * ranges from 0 (no pressure at all) to 1 (normal pressure), however * values higher than 1 may be generated depending on the calibration of * the input device. * @param size A scaled value of the approximate size of the area being pressed when * touched with the finger. The actual value in pixels corresponding to the finger * touch is normalized with a device specific range of values * and scaled to a value between 0 and 1. * @param metaState The state of any meta / modifier keys that were in effect when * the event was generated. * @param xPrecision The precision of the X coordinate being reported. * @param yPrecision The precision of the Y coordinate being reported. * @param deviceId The id for the device that this event came from. An id of * zero indicates that the event didn't come from a physical device; other * numbers are arbitrary and you shouldn't depend on the values. * @param edgeFlags A bitfield indicating which edges, if any, were touched by this * MotionEvent. */ static public MotionEvent obtain(long downTime, long eventTime, int action, float x, float y, float pressure, float size, int metaState, float xPrecision, float yPrecision, int deviceId, int edgeFlags) { MotionEvent ev = obtain(); synchronized (gSharedTempLock) { ensureSharedTempPointerCapacity(1); final PointerProperties[] pp = gSharedTempPointerProperties; pp[0].clear(); pp[0].id = 0; final PointerCoords pc[] = gSharedTempPointerCoords; pc[0].clear(); pc[0].x = x; pc[0].y = y; pc[0].pressure = pressure; pc[0].size = size; ev.mNativePtr = nativeInitialize(ev.mNativePtr, deviceId, InputDevice.SOURCE_UNKNOWN, action, 0, edgeFlags, metaState, 0, 0, 0, xPrecision, yPrecision, downTime * NS_PER_MS, eventTime * NS_PER_MS, 1, pp, pc); return ev; } } /** * Create a new MotionEvent, filling in all of the basic values that * define the motion. * * @param downTime The time (in ms) when the user originally pressed down to start * a stream of position events. This must be obtained from {@link SystemClock#uptimeMillis()}. * @param eventTime The the time (in ms) when this specific event was generated. This * must be obtained from {@link SystemClock#uptimeMillis()}. * @param action The kind of action being performed, such as {@link #ACTION_DOWN}. * @param pointerCount The number of pointers that are active in this event. * @param x The X coordinate of this event. * @param y The Y coordinate of this event. * @param pressure The current pressure of this event. The pressure generally * ranges from 0 (no pressure at all) to 1 (normal pressure), however * values higher than 1 may be generated depending on the calibration of * the input device. * @param size A scaled value of the approximate size of the area being pressed when * touched with the finger. The actual value in pixels corresponding to the finger * touch is normalized with a device specific range of values * and scaled to a value between 0 and 1. * @param metaState The state of any meta / modifier keys that were in effect when * the event was generated. * @param xPrecision The precision of the X coordinate being reported. * @param yPrecision The precision of the Y coordinate being reported. * @param deviceId The id for the device that this event came from. An id of * zero indicates that the event didn't come from a physical device; other * numbers are arbitrary and you shouldn't depend on the values. * @param edgeFlags A bitfield indicating which edges, if any, were touched by this * MotionEvent. * * @deprecated Use {@link #obtain(long, long, int, float, float, float, float, int, float, float, int, int)} * instead. */ @Deprecated static public MotionEvent obtain(long downTime, long eventTime, int action, int pointerCount, float x, float y, float pressure, float size, int metaState, float xPrecision, float yPrecision, int deviceId, int edgeFlags) { return obtain(downTime, eventTime, action, x, y, pressure, size, metaState, xPrecision, yPrecision, deviceId, edgeFlags); } /** * Create a new MotionEvent, filling in a subset of the basic motion * values. Those not specified here are: device id (always 0), pressure * and size (always 1), x and y precision (always 1), and edgeFlags (always 0). * * @param downTime The time (in ms) when the user originally pressed down to start * a stream of position events. This must be obtained from {@link SystemClock#uptimeMillis()}. * @param eventTime The the time (in ms) when this specific event was generated. This * must be obtained from {@link SystemClock#uptimeMillis()}. * @param action The kind of action being performed, such as {@link #ACTION_DOWN}. * @param x The X coordinate of this event. * @param y The Y coordinate of this event. * @param metaState The state of any meta / modifier keys that were in effect when * the event was generated. */ static public MotionEvent obtain(long downTime, long eventTime, int action, float x, float y, int metaState) { return obtain(downTime, eventTime, action, x, y, 1.0f, 1.0f, metaState, 1.0f, 1.0f, 0, 0); } /** * Create a new MotionEvent, copying from an existing one. */ static public MotionEvent obtain(MotionEvent other) { if (other == null) { throw new IllegalArgumentException("other motion event must not be null"); } MotionEvent ev = obtain(); ev.mNativePtr = nativeCopy(ev.mNativePtr, other.mNativePtr, true /*keepHistory*/); return ev; } /** * Create a new MotionEvent, copying from an existing one, but not including * any historical point information. */ static public MotionEvent obtainNoHistory(MotionEvent other) { if (other == null) { throw new IllegalArgumentException("other motion event must not be null"); } MotionEvent ev = obtain(); ev.mNativePtr = nativeCopy(ev.mNativePtr, other.mNativePtr, false /*keepHistory*/); return ev; } /** @hide */ @Override public MotionEvent copy() { return obtain(this); } /** * Recycle the MotionEvent, to be re-used by a later caller. After calling * this function you must not ever touch the event again. */ @Override public final void recycle() { super.recycle(); synchronized (gRecyclerLock) { if (gRecyclerUsed < MAX_RECYCLED) { gRecyclerUsed++; mNext = gRecyclerTop; gRecyclerTop = this; } } } /** * Applies a scale factor to all points within this event. * * This method is used to adjust touch events to simulate different density * displays for compatibility mode. The values returned by {@link #getRawX()}, * {@link #getRawY()}, {@link #getXPrecision()} and {@link #getYPrecision()} * are also affected by the scale factor. * * @param scale The scale factor to apply. * @hide */ public final void scale(float scale) { if (scale != 1.0f) { nativeScale(mNativePtr, scale); } } /** {@inheritDoc} */ @Override public final int getDeviceId() { return nativeGetDeviceId(mNativePtr); } /** {@inheritDoc} */ @Override public final int getSource() { return nativeGetSource(mNativePtr); } /** {@inheritDoc} */ @Override public final void setSource(int source) { nativeSetSource(mNativePtr, source); } /** * Return the kind of action being performed. * Consider using {@link #getActionMasked} and {@link #getActionIndex} to retrieve * the separate masked action and pointer index. * @return The action, such as {@link #ACTION_DOWN} or * the combination of {@link #ACTION_POINTER_DOWN} with a shifted pointer index. */ public final int getAction() { return nativeGetAction(mNativePtr); } /** * Return the masked action being performed, without pointer index information. * Use {@link #getActionIndex} to return the index associated with pointer actions. * @return The action, such as {@link #ACTION_DOWN} or {@link #ACTION_POINTER_DOWN}. */ public final int getActionMasked() { return nativeGetAction(mNativePtr) & ACTION_MASK; } /** * For {@link #ACTION_POINTER_DOWN} or {@link #ACTION_POINTER_UP} * as returned by {@link #getActionMasked}, this returns the associated * pointer index. * The index may be used with {@link #getPointerId(int)}, * {@link #getX(int)}, {@link #getY(int)}, {@link #getPressure(int)}, * and {@link #getSize(int)} to get information about the pointer that has * gone down or up. * @return The index associated with the action. */ public final int getActionIndex() { return (nativeGetAction(mNativePtr) & ACTION_POINTER_INDEX_MASK) >> ACTION_POINTER_INDEX_SHIFT; } /** * Returns true if this motion event is a touch event. * <p> * Specifically 特别地 excludes 排除 pointer events with action {@link #ACTION_HOVER_MOVE}, * {@link #ACTION_HOVER_ENTER}, {@link #ACTION_HOVER_EXIT}, or {@link #ACTION_SCROLL} * because they are not actually touch events (the pointer is not down). * </p> * @return True if this motion event is a touch event. * @hide */ public final boolean isTouchEvent() { return nativeIsTouchEvent(mNativePtr); } /** * Gets the motion event flags. * * @see #FLAG_WINDOW_IS_OBSCURED */ public final int getFlags() { return nativeGetFlags(mNativePtr); } /** @hide */ @Override public final boolean isTainted() { final int flags = getFlags(); return (flags & FLAG_TAINTED) != 0; } /** @hide */ @Override public final void setTainted(boolean tainted) { final int flags = getFlags(); nativeSetFlags(mNativePtr, tainted ? flags | FLAG_TAINTED : flags & ~FLAG_TAINTED); } /** @hide */ public final boolean isTargetAccessibilityFocus() { final int flags = getFlags(); return (flags & FLAG_TARGET_ACCESSIBILITY_FOCUS) != 0; } /** @hide */ public final void setTargetAccessibilityFocus(boolean targetsFocus) { final int flags = getFlags(); nativeSetFlags(mNativePtr, targetsFocus ? flags | FLAG_TARGET_ACCESSIBILITY_FOCUS : flags & ~FLAG_TARGET_ACCESSIBILITY_FOCUS); } /** * Returns the time (in ms) when the user originally pressed down to start * a stream of position events. */ public final long getDownTime() { return nativeGetDownTimeNanos(mNativePtr) / NS_PER_MS; } /** * Sets the time (in ms) when the user originally pressed down to start * a stream of position events. * * @hide */ public final void setDownTime(long downTime) { nativeSetDownTimeNanos(mNativePtr, downTime * NS_PER_MS); } /** * Retrieve the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base. * * @return Returns the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base. */ @Override public final long getEventTime() { return nativeGetEventTimeNanos(mNativePtr, HISTORY_CURRENT) / NS_PER_MS; } /** * Retrieve the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base but with * nanosecond precision. * <p> * The value is in nanosecond precision but it may not have nanosecond accuracy. * </p> * * @return Returns the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base but with * nanosecond precision. * * @hide */ @Override public final long getEventTimeNano() { return nativeGetEventTimeNanos(mNativePtr, HISTORY_CURRENT); } /** * {@link #getX(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @see #AXIS_X */ public final float getX() { return nativeGetAxisValue(mNativePtr, AXIS_X, 0, HISTORY_CURRENT); } /** * {@link #getY(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @see #AXIS_Y */ public final float getY() { return nativeGetAxisValue(mNativePtr, AXIS_Y, 0, HISTORY_CURRENT); } /** * {@link #getPressure(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @see #AXIS_PRESSURE */ public final float getPressure() { return nativeGetAxisValue(mNativePtr, AXIS_PRESSURE, 0, HISTORY_CURRENT); } /** * {@link #getSize(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @see #AXIS_SIZE */ public final float getSize() { return nativeGetAxisValue(mNativePtr, AXIS_SIZE, 0, HISTORY_CURRENT); } /** * {@link #getTouchMajor(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @see #AXIS_TOUCH_MAJOR */ public final float getTouchMajor() { return nativeGetAxisValue(mNativePtr, AXIS_TOUCH_MAJOR, 0, HISTORY_CURRENT); } /** * {@link #getTouchMinor(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @see #AXIS_TOUCH_MINOR */ public final float getTouchMinor() { return nativeGetAxisValue(mNativePtr, AXIS_TOUCH_MINOR, 0, HISTORY_CURRENT); } /** * {@link #getToolMajor(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @see #AXIS_TOOL_MAJOR */ public final float getToolMajor() { return nativeGetAxisValue(mNativePtr, AXIS_TOOL_MAJOR, 0, HISTORY_CURRENT); } /** * {@link #getToolMinor(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @see #AXIS_TOOL_MINOR */ public final float getToolMinor() { return nativeGetAxisValue(mNativePtr, AXIS_TOOL_MINOR, 0, HISTORY_CURRENT); } /** * {@link #getOrientation(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @see #AXIS_ORIENTATION */ public final float getOrientation() { return nativeGetAxisValue(mNativePtr, AXIS_ORIENTATION, 0, HISTORY_CURRENT); } /** * {@link #getAxisValue(int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param axis The axis identifier for the axis value to retrieve. * * @see #AXIS_X * @see #AXIS_Y */ public final float getAxisValue(int axis) { return nativeGetAxisValue(mNativePtr, axis, 0, HISTORY_CURRENT); } /** * The number of pointers of data contained in this event. Always * >= 1. */ public final int getPointerCount() { return nativeGetPointerCount(mNativePtr); } /** * Return the pointer identifier associated with a particular pointer * data index in this event. The identifier tells you the actual pointer * number associated with the data, accounting for individual pointers * going up and down since the start of the current gesture. * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. */ public final int getPointerId(int pointerIndex) { return nativeGetPointerId(mNativePtr, pointerIndex); } /** * Gets the tool type of a pointer for the given pointer index. * The tool type indicates the type of tool used to make contact such * as a finger or stylus, if known. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @return The tool type of the pointer. * * @see #TOOL_TYPE_UNKNOWN * @see #TOOL_TYPE_FINGER * @see #TOOL_TYPE_STYLUS * @see #TOOL_TYPE_MOUSE */ public final int getToolType(int pointerIndex) { return nativeGetToolType(mNativePtr, pointerIndex); } /** * Given a pointer identifier, find the index of its data in the event. * * @param pointerId The identifier of the pointer to be found. * @return Returns either the index of the pointer (for use with * {@link #getX(int)} et al.), or -1 if there is no data available for * that pointer identifier. */ public final int findPointerIndex(int pointerId) { return nativeFindPointerIndex(mNativePtr, pointerId); } /** * Returns the X coordinate of this event for the given pointer * <em>index</em> (use {@link #getPointerId(int)} to find the pointer * identifier for this index). * Whole numbers are pixels; the * value may have a fraction for input devices that are sub-pixel precise. * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * * @see #AXIS_X */ public final float getX(int pointerIndex) { return nativeGetAxisValue(mNativePtr, AXIS_X, pointerIndex, HISTORY_CURRENT); } /** * Returns the Y coordinate of this event for the given pointer * <em>index</em> (use {@link #getPointerId(int)} to find the pointer * identifier for this index). * Whole numbers are pixels; the * value may have a fraction for input devices that are sub-pixel precise. * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * * @see #AXIS_Y */ public final float getY(int pointerIndex) { return nativeGetAxisValue(mNativePtr, AXIS_Y, pointerIndex, HISTORY_CURRENT); } /** * Returns the current pressure of this event for the given pointer * <em>index</em> (use {@link #getPointerId(int)} to find the pointer * identifier for this index). * The pressure generally * ranges from 0 (no pressure at all) to 1 (normal pressure), however * values higher than 1 may be generated depending on the calibration of * the input device. * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * * @see #AXIS_PRESSURE */ public final float getPressure(int pointerIndex) { return nativeGetAxisValue(mNativePtr, AXIS_PRESSURE, pointerIndex, HISTORY_CURRENT); } /** * Returns a scaled value of the approximate size for the given pointer * <em>index</em> (use {@link #getPointerId(int)} to find the pointer * identifier for this index). * This represents some approximation of the area of the screen being * pressed; the actual value in pixels corresponding to the * touch is normalized with the device specific range of values * and scaled to a value between 0 and 1. The value of size can be used to * determine fat touch events. * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * * @see #AXIS_SIZE */ public final float getSize(int pointerIndex) { return nativeGetAxisValue(mNativePtr, AXIS_SIZE, pointerIndex, HISTORY_CURRENT); } /** * Returns the length of the major axis of an ellipse that describes the touch * area at the point of contact for the given pointer * <em>index</em> (use {@link #getPointerId(int)} to find the pointer * identifier for this index). * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * * @see #AXIS_TOUCH_MAJOR */ public final float getTouchMajor(int pointerIndex) { return nativeGetAxisValue(mNativePtr, AXIS_TOUCH_MAJOR, pointerIndex, HISTORY_CURRENT); } /** * Returns the length of the minor axis of an ellipse that describes the touch * area at the point of contact for the given pointer * <em>index</em> (use {@link #getPointerId(int)} to find the pointer * identifier for this index). * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * * @see #AXIS_TOUCH_MINOR */ public final float getTouchMinor(int pointerIndex) { return nativeGetAxisValue(mNativePtr, AXIS_TOUCH_MINOR, pointerIndex, HISTORY_CURRENT); } /** * Returns the length of the major axis of an ellipse that describes the size of * the approaching tool for the given pointer * <em>index</em> (use {@link #getPointerId(int)} to find the pointer * identifier for this index). * The tool area represents the estimated size of the finger or pen that is * touching the device independent of its actual touch area at the point of contact. * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * * @see #AXIS_TOOL_MAJOR */ public final float getToolMajor(int pointerIndex) { return nativeGetAxisValue(mNativePtr, AXIS_TOOL_MAJOR, pointerIndex, HISTORY_CURRENT); } /** * Returns the length of the minor axis of an ellipse that describes the size of * the approaching tool for the given pointer * <em>index</em> (use {@link #getPointerId(int)} to find the pointer * identifier for this index). * The tool area represents the estimated size of the finger or pen that is * touching the device independent of its actual touch area at the point of contact. * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * * @see #AXIS_TOOL_MINOR */ public final float getToolMinor(int pointerIndex) { return nativeGetAxisValue(mNativePtr, AXIS_TOOL_MINOR, pointerIndex, HISTORY_CURRENT); } /** * Returns the orientation of the touch area and tool area in radians clockwise from vertical * for the given pointer <em>index</em> (use {@link #getPointerId(int)} to find the pointer * identifier for this index). * An angle of 0 radians indicates that the major axis of contact is oriented * upwards, is perfectly circular or is of unknown orientation. A positive angle * indicates that the major axis of contact is oriented to the right. A negative angle * indicates that the major axis of contact is oriented to the left. * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians * (finger pointing fully right). * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * * @see #AXIS_ORIENTATION */ public final float getOrientation(int pointerIndex) { return nativeGetAxisValue(mNativePtr, AXIS_ORIENTATION, pointerIndex, HISTORY_CURRENT); } /** * Returns the value of the requested axis for the given pointer <em>index</em> * (use {@link #getPointerId(int)} to find the pointer identifier for this index). * * @param axis The axis identifier for the axis value to retrieve. * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @return The value of the axis, or 0 if the axis is not available. * * @see #AXIS_X * @see #AXIS_Y */ public final float getAxisValue(int axis, int pointerIndex) { return nativeGetAxisValue(mNativePtr, axis, pointerIndex, HISTORY_CURRENT); } /** * Populates a {@link PointerCoords} object with pointer coordinate data for * the specified pointer index. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param outPointerCoords The pointer coordinate object to populate. * * @see PointerCoords */ public final void getPointerCoords(int pointerIndex, PointerCoords outPointerCoords) { nativeGetPointerCoords(mNativePtr, pointerIndex, HISTORY_CURRENT, outPointerCoords); } /** * Populates a {@link PointerProperties} object with pointer properties for * the specified pointer index. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param outPointerProperties The pointer properties object to populate. * * @see PointerProperties */ public final void getPointerProperties(int pointerIndex, PointerProperties outPointerProperties) { nativeGetPointerProperties(mNativePtr, pointerIndex, outPointerProperties); } /** * Returns the state of any meta / modifier keys that were in effect when * the event was generated. This is the same values as those * returned by {@link KeyEvent#getMetaState() KeyEvent.getMetaState}. * * @return an integer in which each bit set to 1 represents a pressed * meta key * * @see KeyEvent#getMetaState() */ public final int getMetaState() { return nativeGetMetaState(mNativePtr); } /** * Gets the state of all buttons that are pressed such as a mouse or stylus button. * * @return The button state. * * @see #BUTTON_PRIMARY * @see #BUTTON_SECONDARY * @see #BUTTON_TERTIARY * @see #BUTTON_FORWARD * @see #BUTTON_BACK * @see #BUTTON_STYLUS_PRIMARY * @see #BUTTON_STYLUS_SECONDARY */ public final int getButtonState() { return nativeGetButtonState(mNativePtr); } /** * Sets the bitfield indicating which buttons are pressed. * * @see #getButtonState() * @hide */ public final void setButtonState(int buttonState) { nativeSetButtonState(mNativePtr, buttonState); } /** * Gets which button has been modified during a press or release action. * * For actions other than {@link #ACTION_BUTTON_PRESS} and {@link #ACTION_BUTTON_RELEASE} * the returned value is undefined. * * @see #getButtonState() */ public final int getActionButton() { return nativeGetActionButton(mNativePtr); } /** * Sets the action button for the event. * * @see #getActionButton() * @hide */ public final void setActionButton(int button) { nativeSetActionButton(mNativePtr, button); } /** * Returns the original raw X coordinate of this event. For touch * events on the screen, this is the original location of the event * on the screen, before it had been adjusted for the containing window * and views. * * @see #getX(int) * @see #AXIS_X */ public final float getRawX() { return nativeGetRawAxisValue(mNativePtr, AXIS_X, 0, HISTORY_CURRENT); } /** * Returns the original raw Y coordinate of this event. For touch * events on the screen, this is the original location of the event * on the screen, before it had been adjusted for the containing window * and views. * * @see #getY(int) * @see #AXIS_Y */ public final float getRawY() { return nativeGetRawAxisValue(mNativePtr, AXIS_Y, 0, HISTORY_CURRENT); } /** * Return the precision of the X coordinates being reported. You can * multiply this number with {@link #getX} to find the actual hardware * value of the X coordinate. * @return Returns the precision of X coordinates being reported. * * @see #AXIS_X */ public final float getXPrecision() { return nativeGetXPrecision(mNativePtr); } /** * Return the precision of the Y coordinates being reported. You can * multiply this number with {@link #getY} to find the actual hardware * value of the Y coordinate. * @return Returns the precision of Y coordinates being reported. * * @see #AXIS_Y */ public final float getYPrecision() { return nativeGetYPrecision(mNativePtr); } /** * Returns the number of historical points in this event. These are * movements that have occurred between this event and the previous event. * This only applies to ACTION_MOVE events -- all other actions will have * a size of 0. * * @return Returns the number of historical points in the event. */ public final int getHistorySize() { return nativeGetHistorySize(mNativePtr); } /** * Returns the time that a historical movement occurred between this event * and the previous event, in the {@link android.os.SystemClock#uptimeMillis} time base. * <p> * This only applies to ACTION_MOVE events. * </p> * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * @return Returns the time that a historical movement occurred between this * event and the previous event, * in the {@link android.os.SystemClock#uptimeMillis} time base. * * @see #getHistorySize * @see #getEventTime */ public final long getHistoricalEventTime(int pos) { return nativeGetEventTimeNanos(mNativePtr, pos) / NS_PER_MS; } /** * Returns the time that a historical movement occurred between this event * and the previous event, in the {@link android.os.SystemClock#uptimeMillis} time base * but with nanosecond (instead of millisecond) precision. * <p> * This only applies to ACTION_MOVE events. * </p><p> * The value is in nanosecond precision but it may not have nanosecond accuracy. * </p> * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * @return Returns the time that a historical movement occurred between this * event and the previous event, * in the {@link android.os.SystemClock#uptimeMillis} time base but with * nanosecond (instead of millisecond) precision. * * @see #getHistorySize * @see #getEventTime * * @hide */ public final long getHistoricalEventTimeNano(int pos) { return nativeGetEventTimeNanos(mNativePtr, pos); } /** * {@link #getHistoricalX(int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getX() * @see #AXIS_X */ public final float getHistoricalX(int pos) { return nativeGetAxisValue(mNativePtr, AXIS_X, 0, pos); } /** * {@link #getHistoricalY(int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getY() * @see #AXIS_Y */ public final float getHistoricalY(int pos) { return nativeGetAxisValue(mNativePtr, AXIS_Y, 0, pos); } /** * {@link #getHistoricalPressure(int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getPressure() * @see #AXIS_PRESSURE */ public final float getHistoricalPressure(int pos) { return nativeGetAxisValue(mNativePtr, AXIS_PRESSURE, 0, pos); } /** * {@link #getHistoricalSize(int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getSize() * @see #AXIS_SIZE */ public final float getHistoricalSize(int pos) { return nativeGetAxisValue(mNativePtr, AXIS_SIZE, 0, pos); } /** * {@link #getHistoricalTouchMajor(int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getTouchMajor() * @see #AXIS_TOUCH_MAJOR */ public final float getHistoricalTouchMajor(int pos) { return nativeGetAxisValue(mNativePtr, AXIS_TOUCH_MAJOR, 0, pos); } /** * {@link #getHistoricalTouchMinor(int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getTouchMinor() * @see #AXIS_TOUCH_MINOR */ public final float getHistoricalTouchMinor(int pos) { return nativeGetAxisValue(mNativePtr, AXIS_TOUCH_MINOR, 0, pos); } /** * {@link #getHistoricalToolMajor(int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getToolMajor() * @see #AXIS_TOOL_MAJOR */ public final float getHistoricalToolMajor(int pos) { return nativeGetAxisValue(mNativePtr, AXIS_TOOL_MAJOR, 0, pos); } /** * {@link #getHistoricalToolMinor(int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getToolMinor() * @see #AXIS_TOOL_MINOR */ public final float getHistoricalToolMinor(int pos) { return nativeGetAxisValue(mNativePtr, AXIS_TOOL_MINOR, 0, pos); } /** * {@link #getHistoricalOrientation(int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getOrientation() * @see #AXIS_ORIENTATION */ public final float getHistoricalOrientation(int pos) { return nativeGetAxisValue(mNativePtr, AXIS_ORIENTATION, 0, pos); } /** * {@link #getHistoricalAxisValue(int, int, int)} for the first pointer index (may be an * arbitrary pointer identifier). * * @param axis The axis identifier for the axis value to retrieve. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getAxisValue(int) * @see #AXIS_X * @see #AXIS_Y */ public final float getHistoricalAxisValue(int axis, int pos) { return nativeGetAxisValue(mNativePtr, axis, 0, pos); } /** * Returns a historical X coordinate, as per {@link #getX(int)}, that * occurred between this event and the previous event for the given pointer. * Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getX(int) * @see #AXIS_X */ public final float getHistoricalX(int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, AXIS_X, pointerIndex, pos); } /** * Returns a historical Y coordinate, as per {@link #getY(int)}, that * occurred between this event and the previous event for the given pointer. * Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getY(int) * @see #AXIS_Y */ public final float getHistoricalY(int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, AXIS_Y, pointerIndex, pos); } /** * Returns a historical pressure coordinate, as per {@link #getPressure(int)}, * that occurred between this event and the previous event for the given * pointer. Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getPressure(int) * @see #AXIS_PRESSURE */ public final float getHistoricalPressure(int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, AXIS_PRESSURE, pointerIndex, pos); } /** * Returns a historical size coordinate, as per {@link #getSize(int)}, that * occurred between this event and the previous event for the given pointer. * Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getSize(int) * @see #AXIS_SIZE */ public final float getHistoricalSize(int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, AXIS_SIZE, pointerIndex, pos); } /** * Returns a historical touch major axis coordinate, as per {@link #getTouchMajor(int)}, that * occurred between this event and the previous event for the given pointer. * Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getTouchMajor(int) * @see #AXIS_TOUCH_MAJOR */ public final float getHistoricalTouchMajor(int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, AXIS_TOUCH_MAJOR, pointerIndex, pos); } /** * Returns a historical touch minor axis coordinate, as per {@link #getTouchMinor(int)}, that * occurred between this event and the previous event for the given pointer. * Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getTouchMinor(int) * @see #AXIS_TOUCH_MINOR */ public final float getHistoricalTouchMinor(int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, AXIS_TOUCH_MINOR, pointerIndex, pos); } /** * Returns a historical tool major axis coordinate, as per {@link #getToolMajor(int)}, that * occurred between this event and the previous event for the given pointer. * Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getToolMajor(int) * @see #AXIS_TOOL_MAJOR */ public final float getHistoricalToolMajor(int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, AXIS_TOOL_MAJOR, pointerIndex, pos); } /** * Returns a historical tool minor axis coordinate, as per {@link #getToolMinor(int)}, that * occurred between this event and the previous event for the given pointer. * Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getToolMinor(int) * @see #AXIS_TOOL_MINOR */ public final float getHistoricalToolMinor(int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, AXIS_TOOL_MINOR, pointerIndex, pos); } /** * Returns a historical orientation coordinate, as per {@link #getOrientation(int)}, that * occurred between this event and the previous event for the given pointer. * Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * * @see #getHistorySize * @see #getOrientation(int) * @see #AXIS_ORIENTATION */ public final float getHistoricalOrientation(int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, AXIS_ORIENTATION, pointerIndex, pos); } /** * Returns the historical value of the requested axis, as per {@link #getAxisValue(int, int)}, * occurred between this event and the previous event for the given pointer. * Only applies to ACTION_MOVE events. * * @param axis The axis identifier for the axis value to retrieve. * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * @return The value of the axis, or 0 if the axis is not available. * * @see #AXIS_X * @see #AXIS_Y */ public final float getHistoricalAxisValue(int axis, int pointerIndex, int pos) { return nativeGetAxisValue(mNativePtr, axis, pointerIndex, pos); } /** * Populates a {@link PointerCoords} object with historical pointer coordinate data, * as per {@link #getPointerCoords}, that occurred between this event and the previous * event for the given pointer. * Only applies to ACTION_MOVE events. * * @param pointerIndex Raw index of pointer to retrieve. Value may be from 0 * (the first pointer that is down) to {@link #getPointerCount()}-1. * @param pos Which historical value to return; must be less than * {@link #getHistorySize} * @param outPointerCoords The pointer coordinate object to populate. * * @see #getHistorySize * @see #getPointerCoords * @see PointerCoords */ public final void getHistoricalPointerCoords(int pointerIndex, int pos, PointerCoords outPointerCoords) { nativeGetPointerCoords(mNativePtr, pointerIndex, pos, outPointerCoords); } /** * Returns a bitfield indicating which edges, if any, were touched by this * MotionEvent. For touch events, clients can use this to determine if the * user's finger was touching the edge of the display. * * This property is only set for {@link #ACTION_DOWN} events. * * @see #EDGE_LEFT * @see #EDGE_TOP * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ public final int getEdgeFlags() { return nativeGetEdgeFlags(mNativePtr); } /** * Sets the bitfield indicating which edges, if any, were touched by this * MotionEvent. * * @see #getEdgeFlags() */ public final void setEdgeFlags(int flags) { nativeSetEdgeFlags(mNativePtr, flags); } /** * Sets this event's action. */ public final void setAction(int action) { nativeSetAction(mNativePtr, action); } /** * Adjust this event's location. * @param deltaX Amount to add to the current X coordinate of the event. * @param deltaY Amount to add to the current Y coordinate of the event. */ public final void offsetLocation(float deltaX, float deltaY) { if (deltaX != 0.0f || deltaY != 0.0f) { nativeOffsetLocation(mNativePtr, deltaX, deltaY); } } /** * Set this event's location. Applies {@link #offsetLocation} with a * delta from the current location to the given new location. * * @param x New absolute X location. * @param y New absolute Y location. */ public final void setLocation(float x, float y) { float oldX = getX(); float oldY = getY(); offsetLocation(x - oldX, y - oldY); } /** * Applies a transformation matrix to all of the points in the event. * * @param matrix The transformation matrix to apply. */ public final void transform(Matrix matrix) { if (matrix == null) { throw new IllegalArgumentException("matrix must not be null"); } nativeTransform(mNativePtr, matrix); } /** * Add a new movement to the batch of movements in this event. The event's * current location, position and size is updated to the new values. * The current values in the event are added to a list of historical values. * * Only applies to {@link #ACTION_MOVE} or {@link #ACTION_HOVER_MOVE} events. * * @param eventTime The time stamp (in ms) for this data. * @param x The new X position. * @param y The new Y position. * @param pressure The new pressure. * @param size The new size. * @param metaState Meta key state. */ public final void addBatch(long eventTime, float x, float y, float pressure, float size, int metaState) { synchronized (gSharedTempLock) { ensureSharedTempPointerCapacity(1); final PointerCoords[] pc = gSharedTempPointerCoords; pc[0].clear(); pc[0].x = x; pc[0].y = y; pc[0].pressure = pressure; pc[0].size = size; nativeAddBatch(mNativePtr, eventTime * NS_PER_MS, pc, metaState); } } /** * Add a new movement to the batch of movements in this event. The event's * current location, position and size is updated to the new values. * The current values in the event are added to a list of historical values. * * Only applies to {@link #ACTION_MOVE} or {@link #ACTION_HOVER_MOVE} events. * * @param eventTime The time stamp (in ms) for this data. * @param pointerCoords The new pointer coordinates. * @param metaState Meta key state. */ public final void addBatch(long eventTime, PointerCoords[] pointerCoords, int metaState) { nativeAddBatch(mNativePtr, eventTime * NS_PER_MS, pointerCoords, metaState); } /** * Adds all of the movement samples of the specified event to this one if * it is compatible. To be compatible, the event must have the same device id, * source, action, flags, pointer count, pointer properties. * * Only applies to {@link #ACTION_MOVE} or {@link #ACTION_HOVER_MOVE} events. * * @param event The event whose movements samples should be added to this one * if possible. * @return True if batching was performed or false if batching was not possible. * @hide */ public final boolean addBatch(MotionEvent event) { final int action = nativeGetAction(mNativePtr); if (action != ACTION_MOVE && action != ACTION_HOVER_MOVE) { return false; } if (action != nativeGetAction(event.mNativePtr)) { return false; } if (nativeGetDeviceId(mNativePtr) != nativeGetDeviceId(event.mNativePtr) || nativeGetSource(mNativePtr) != nativeGetSource(event.mNativePtr) || nativeGetFlags(mNativePtr) != nativeGetFlags(event.mNativePtr)) { return false; } final int pointerCount = nativeGetPointerCount(mNativePtr); if (pointerCount != nativeGetPointerCount(event.mNativePtr)) { return false; } synchronized (gSharedTempLock) { ensureSharedTempPointerCapacity(Math.max(pointerCount, 2)); final PointerProperties[] pp = gSharedTempPointerProperties; final PointerCoords[] pc = gSharedTempPointerCoords; for (int i = 0; i < pointerCount; i++) { nativeGetPointerProperties(mNativePtr, i, pp[0]); nativeGetPointerProperties(event.mNativePtr, i, pp[1]); if (!pp[0].equals(pp[1])) { return false; } } final int metaState = nativeGetMetaState(event.mNativePtr); final int historySize = nativeGetHistorySize(event.mNativePtr); for (int h = 0; h <= historySize; h++) { final int historyPos = (h == historySize ? HISTORY_CURRENT : h); for (int i = 0; i < pointerCount; i++) { nativeGetPointerCoords(event.mNativePtr, i, historyPos, pc[i]); } final long eventTimeNanos = nativeGetEventTimeNanos(event.mNativePtr, historyPos); nativeAddBatch(mNativePtr, eventTimeNanos, pc, metaState); } } return true; } /** * Returns true if all points in the motion event are completely within the specified bounds. * @hide */ public final boolean isWithinBoundsNoHistory(float left, float top, float right, float bottom) { final int pointerCount = nativeGetPointerCount(mNativePtr); for (int i = 0; i < pointerCount; i++) { final float x = nativeGetAxisValue(mNativePtr, AXIS_X, i, HISTORY_CURRENT); final float y = nativeGetAxisValue(mNativePtr, AXIS_Y, i, HISTORY_CURRENT); if (x < left || x > right || y < top || y > bottom) { return false; } } return true; } private static final float clamp(float value, float low, float high) { if (value < low) { return low; } else if (value > high) { return high; } return value; } /** * Returns a new motion events whose points have been clamped to the specified bounds. * @hide */ public final MotionEvent clampNoHistory(float left, float top, float right, float bottom) { MotionEvent ev = obtain(); synchronized (gSharedTempLock) { final int pointerCount = nativeGetPointerCount(mNativePtr); ensureSharedTempPointerCapacity(pointerCount); final PointerProperties[] pp = gSharedTempPointerProperties; final PointerCoords[] pc = gSharedTempPointerCoords; for (int i = 0; i < pointerCount; i++) { nativeGetPointerProperties(mNativePtr, i, pp[i]); nativeGetPointerCoords(mNativePtr, i, HISTORY_CURRENT, pc[i]); pc[i].x = clamp(pc[i].x, left, right); pc[i].y = clamp(pc[i].y, top, bottom); } ev.mNativePtr = nativeInitialize(ev.mNativePtr, nativeGetDeviceId(mNativePtr), nativeGetSource(mNativePtr), nativeGetAction(mNativePtr), nativeGetFlags(mNativePtr), nativeGetEdgeFlags(mNativePtr), nativeGetMetaState(mNativePtr), nativeGetButtonState(mNativePtr), nativeGetXOffset(mNativePtr), nativeGetYOffset(mNativePtr), nativeGetXPrecision(mNativePtr), nativeGetYPrecision(mNativePtr), nativeGetDownTimeNanos(mNativePtr), nativeGetEventTimeNanos(mNativePtr, HISTORY_CURRENT), pointerCount, pp, pc); return ev; } } /** * Gets an integer where each pointer id present in the event is marked as a bit. * @hide */ //// TODO: 2017/9/7 public final int getPointerIdBits() { int idBits = 0; final int pointerCount = nativeGetPointerCount(mNativePtr); for (int i = 0; i < pointerCount; i++) { idBits |= 1 << nativeGetPointerId(mNativePtr, i); } return idBits; } /** * Splits a motion event such that it includes only a subset of pointer ids. * @hide */ //// TODO: 2017/9/7 public final MotionEvent split(int idBits) { MotionEvent ev = obtain(); synchronized (gSharedTempLock) { final int oldPointerCount = nativeGetPointerCount(mNativePtr); ensureSharedTempPointerCapacity(oldPointerCount); final PointerProperties[] pp = gSharedTempPointerProperties; final PointerCoords[] pc = gSharedTempPointerCoords; final int[] map = gSharedTempPointerIndexMap; final int oldAction = nativeGetAction(mNativePtr); final int oldActionMasked = oldAction & ACTION_MASK; final int oldActionPointerIndex = (oldAction & ACTION_POINTER_INDEX_MASK) >> ACTION_POINTER_INDEX_SHIFT; int newActionPointerIndex = -1; int newPointerCount = 0; int newIdBits = 0; for (int i = 0; i < oldPointerCount; i++) { nativeGetPointerProperties(mNativePtr, i, pp[newPointerCount]); final int idBit = 1 << pp[newPointerCount].id; if ((idBit & idBits) != 0) { if (i == oldActionPointerIndex) { newActionPointerIndex = newPointerCount; } map[newPointerCount] = i; newPointerCount += 1; newIdBits |= idBit; } } if (newPointerCount == 0) { throw new IllegalArgumentException("idBits did not match any ids in the event"); } final int newAction; if (oldActionMasked == ACTION_POINTER_DOWN || oldActionMasked == ACTION_POINTER_UP) { if (newActionPointerIndex < 0) { // An unrelated pointer changed. newAction = ACTION_MOVE; } else if (newPointerCount == 1) { // The first/last pointer went down/up. newAction = oldActionMasked == ACTION_POINTER_DOWN ? ACTION_DOWN : ACTION_UP; } else { // A secondary pointer went down/up. newAction = oldActionMasked | (newActionPointerIndex << ACTION_POINTER_INDEX_SHIFT); } } else { // Simple up/down/cancel/move or other motion action. newAction = oldAction; } final int historySize = nativeGetHistorySize(mNativePtr); for (int h = 0; h <= historySize; h++) { final int historyPos = h == historySize ? HISTORY_CURRENT : h; for (int i = 0; i < newPointerCount; i++) { nativeGetPointerCoords(mNativePtr, map[i], historyPos, pc[i]); } final long eventTimeNanos = nativeGetEventTimeNanos(mNativePtr, historyPos); if (h == 0) { ev.mNativePtr = nativeInitialize(ev.mNativePtr, nativeGetDeviceId(mNativePtr), nativeGetSource(mNativePtr), newAction, nativeGetFlags(mNativePtr), nativeGetEdgeFlags(mNativePtr), nativeGetMetaState(mNativePtr), nativeGetButtonState(mNativePtr), nativeGetXOffset(mNativePtr), nativeGetYOffset(mNativePtr), nativeGetXPrecision(mNativePtr), nativeGetYPrecision(mNativePtr), nativeGetDownTimeNanos(mNativePtr), eventTimeNanos, newPointerCount, pp, pc); } else { nativeAddBatch(ev.mNativePtr, eventTimeNanos, pc, 0); } } return ev; } } @Override public String toString() { StringBuilder msg = new StringBuilder(); msg.append("MotionEvent { action=").append(actionToString(getAction())); msg.append(", actionButton=").append(buttonStateToString(getActionButton())); final int pointerCount = getPointerCount(); for (int i = 0; i < pointerCount; i++) { msg.append(", id[").append(i).append("]=").append(getPointerId(i)); msg.append(", x[").append(i).append("]=").append(getX(i)); msg.append(", y[").append(i).append("]=").append(getY(i)); msg.append(", toolType[").append(i).append("]=").append( toolTypeToString(getToolType(i))); } msg.append(", buttonState=").append(MotionEvent.buttonStateToString(getButtonState())); msg.append(", metaState=").append(KeyEvent.metaStateToString(getMetaState())); msg.append(", flags=0x").append(Integer.toHexString(getFlags())); msg.append(", edgeFlags=0x").append(Integer.toHexString(getEdgeFlags())); msg.append(", pointerCount=").append(pointerCount); msg.append(", historySize=").append(getHistorySize()); msg.append(", eventTime=").append(getEventTime()); msg.append(", downTime=").append(getDownTime()); msg.append(", deviceId=").append(getDeviceId()); msg.append(", source=0x").append(Integer.toHexString(getSource())); msg.append(" }"); return msg.toString(); } /** * Returns a string that represents the symbolic name of the specified unmasked action * such as "ACTION_DOWN", "ACTION_POINTER_DOWN(3)" or an equivalent numeric constant * such as "35" if unknown. * * @param action The unmasked action. * @return The symbolic name of the specified action. * @see #getAction() */ public static String actionToString(int action) { switch (action) { case ACTION_DOWN: return "ACTION_DOWN"; case ACTION_UP: return "ACTION_UP"; case ACTION_CANCEL: return "ACTION_CANCEL"; case ACTION_OUTSIDE: return "ACTION_OUTSIDE"; case ACTION_MOVE: return "ACTION_MOVE"; case ACTION_HOVER_MOVE: return "ACTION_HOVER_MOVE"; case ACTION_SCROLL: return "ACTION_SCROLL"; case ACTION_HOVER_ENTER: return "ACTION_HOVER_ENTER"; case ACTION_HOVER_EXIT: return "ACTION_HOVER_EXIT"; case ACTION_BUTTON_PRESS: return "ACTION_BUTTON_PRESS"; case ACTION_BUTTON_RELEASE: return "ACTION_BUTTON_RELEASE"; } int index = (action & ACTION_POINTER_INDEX_MASK) >> ACTION_POINTER_INDEX_SHIFT; switch (action & ACTION_MASK) { case ACTION_POINTER_DOWN: return "ACTION_POINTER_DOWN(" + index + ")"; case ACTION_POINTER_UP: return "ACTION_POINTER_UP(" + index + ")"; default: return Integer.toString(action); } } /** * Returns a string that represents the symbolic name of the specified axis * such as "AXIS_X" or an equivalent numeric constant such as "42" if unknown. * * @param axis The axis. * @return The symbolic name of the specified axis. */ public static String axisToString(int axis) { String symbolicName = nativeAxisToString(axis); return symbolicName != null ? LABEL_PREFIX + symbolicName : Integer.toString(axis); } /** * Gets an axis by its symbolic name such as "AXIS_X" or an * equivalent numeric constant such as "42". * * @param symbolicName The symbolic name of the axis. * @return The axis or -1 if not found. * @see KeyEvent#keyCodeToString(int) */ public static int axisFromString(String symbolicName) { if (symbolicName.startsWith(LABEL_PREFIX)) { symbolicName = symbolicName.substring(LABEL_PREFIX.length()); int axis = nativeAxisFromString(symbolicName); if (axis >= 0) { return axis; } } try { return Integer.parseInt(symbolicName, 10); } catch (NumberFormatException ex) { return -1; } } /** * Returns a string that represents the symbolic name of the specified combined * button state flags such as "0", "BUTTON_PRIMARY", * "BUTTON_PRIMARY|BUTTON_SECONDARY" or an equivalent numeric constant such as "0x10000000" * if unknown. * * @param buttonState The button state. * @return The symbolic name of the specified combined button state flags. * @hide */ public static String buttonStateToString(int buttonState) { if (buttonState == 0) { return "0"; } StringBuilder result = null; int i = 0; while (buttonState != 0) { final boolean isSet = (buttonState & 1) != 0; buttonState >>>= 1; // unsigned shift! if (isSet) { final String name = BUTTON_SYMBOLIC_NAMES[i]; if (result == null) { if (buttonState == 0) { return name; } result = new StringBuilder(name); } else { result.append('|'); result.append(name); } } i += 1; } return result.toString(); } /** * Returns a string that represents the symbolic name of the specified tool type * such as "TOOL_TYPE_FINGER" or an equivalent numeric constant such as "42" if unknown. * * @param toolType The tool type. * @return The symbolic name of the specified tool type. * @hide */ public static String toolTypeToString(int toolType) { String symbolicName = TOOL_TYPE_SYMBOLIC_NAMES.get(toolType); return symbolicName != null ? symbolicName : Integer.toString(toolType); } /** * Checks if a mouse or stylus button (or combination of buttons) is pressed. * @param button Button (or combination of buttons). * @return True if specified buttons are pressed. * * @see #BUTTON_PRIMARY * @see #BUTTON_SECONDARY * @see #BUTTON_TERTIARY * @see #BUTTON_FORWARD * @see #BUTTON_BACK * @see #BUTTON_STYLUS_PRIMARY * @see #BUTTON_STYLUS_SECONDARY */ public final boolean isButtonPressed(int button) { if (button == 0) { return false; } return (getButtonState() & button) == button; } public static final Parcelable.Creator<MotionEvent> CREATOR = new Parcelable.Creator<MotionEvent>() { public MotionEvent createFromParcel(Parcel in) { in.readInt(); // skip token, we already know this is a MotionEvent return MotionEvent.createFromParcelBody(in); } public MotionEvent[] newArray(int size) { return new MotionEvent[size]; } }; /** @hide */ public static MotionEvent createFromParcelBody(Parcel in) { MotionEvent ev = obtain(); ev.mNativePtr = nativeReadFromParcel(ev.mNativePtr, in); return ev; } /** @hide */ @Override public final void cancel() { setAction(ACTION_CANCEL); } public void writeToParcel(Parcel out, int flags) { out.writeInt(PARCEL_TOKEN_MOTION_EVENT); nativeWriteToParcel(mNativePtr, out); } private static native long nativeInitialize(long nativePtr, int deviceId, int source, int action, int flags, int edgeFlags, int metaState, int buttonState, float xOffset, float yOffset, float xPrecision, float yPrecision, long downTimeNanos, long eventTimeNanos, int pointerCount, PointerProperties[] pointerIds, PointerCoords[] pointerCoords); private static native long nativeCopy(long destNativePtr, long sourceNativePtr, boolean keepHistory); private static native void nativeDispose(long nativePtr); private static native void nativeAddBatch(long nativePtr, long eventTimeNanos, PointerCoords[] pointerCoords, int metaState); private static native int nativeGetDeviceId(long nativePtr); private static native int nativeGetSource(long nativePtr); private static native int nativeSetSource(long nativePtr, int source); private static native int nativeGetAction(long nativePtr); private static native void nativeSetAction(long nativePtr, int action); private static native boolean nativeIsTouchEvent(long nativePtr); private static native int nativeGetFlags(long nativePtr); private static native void nativeSetFlags(long nativePtr, int flags); private static native int nativeGetEdgeFlags(long nativePtr); private static native void nativeSetEdgeFlags(long nativePtr, int action); private static native int nativeGetMetaState(long nativePtr); private static native int nativeGetButtonState(long nativePtr); private static native void nativeSetButtonState(long nativePtr, int buttonState); private static native int nativeGetActionButton(long nativePtr); private static native void nativeSetActionButton(long nativePtr, int actionButton); private static native void nativeOffsetLocation(long nativePtr, float deltaX, float deltaY); private static native float nativeGetXOffset(long nativePtr); private static native float nativeGetYOffset(long nativePtr); private static native float nativeGetXPrecision(long nativePtr); private static native float nativeGetYPrecision(long nativePtr); private static native long nativeGetDownTimeNanos(long nativePtr); private static native void nativeSetDownTimeNanos(long nativePtr, long downTime); private static native int nativeGetPointerCount(long nativePtr); private static native int nativeGetPointerId(long nativePtr, int pointerIndex); private static native int nativeGetToolType(long nativePtr, int pointerIndex); private static native int nativeFindPointerIndex(long nativePtr, int pointerId); private static native int nativeGetHistorySize(long nativePtr); private static native long nativeGetEventTimeNanos(long nativePtr, int historyPos); private static native float nativeGetRawAxisValue(long nativePtr, int axis, int pointerIndex, int historyPos); private static native float nativeGetAxisValue(long nativePtr, int axis, int pointerIndex, int historyPos); private static native void nativeGetPointerCoords(long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoords); private static native void nativeGetPointerProperties(long nativePtr, int pointerIndex, PointerProperties outPointerProperties); private static native void nativeScale(long nativePtr, float scale); private static native void nativeTransform(long nativePtr, Matrix matrix); private static native long nativeReadFromParcel(long nativePtr, Parcel parcel); private static native void nativeWriteToParcel(long nativePtr, Parcel parcel); private static native String nativeAxisToString(int axis); private static native int nativeAxisFromString(String label); /** * Transfer object for pointer coordinates. * * Objects of this type can be used to specify the pointer coordinates when * creating new {@link MotionEvent} objects and to query pointer coordinates * in bulk. * * Refer to {@link InputDevice} for information about how different kinds of * input devices and sources represent pointer coordinates. */ public static final class PointerCoords { private static final int INITIAL_PACKED_AXIS_VALUES = 8; private long mPackedAxisBits; private float[] mPackedAxisValues; /** * Creates a pointer coords object with all axes initialized to zero. */ public PointerCoords() { } /** * Creates a pointer coords object as a copy of the * contents of another pointer coords object. * * @param other The pointer coords object to copy. */ public PointerCoords(PointerCoords other) { copyFrom(other); } /** @hide */ public static PointerCoords[] createArray(int size) { PointerCoords[] array = new PointerCoords[size]; for (int i = 0; i < size; i++) { array[i] = new PointerCoords(); } return array; } /** * The X component of the pointer movement. * * @see MotionEvent#AXIS_X */ public float x; /** * The Y component of the pointer movement. * * @see MotionEvent#AXIS_Y */ public float y; /** * A normalized value that describes the pressure applied to the device * by a finger or other tool. * The pressure generally ranges from 0 (no pressure at all) to 1 (normal pressure), * although values higher than 1 may be generated depending on the calibration of * the input device. * * @see MotionEvent#AXIS_PRESSURE */ public float pressure; /** * A normalized value that describes the approximate size of the pointer touch area * in relation to the maximum detectable size of the device. * It represents some approximation 近似值 of the area of the screen being * pressed; the actual value in pixels corresponding to the * touch is normalized with the device specific range of values * and scaled to a value between 0 and 1. The value of size can be used to * determine fat touch events. * * @see MotionEvent#AXIS_SIZE */ public float size; /** * The length of the major axis of an ellipse that describes the touch area at * the point of contact. * If the device is a touch screen, the length is reported in pixels, otherwise it is * reported in device-specific units. * * @see MotionEvent#AXIS_TOUCH_MAJOR */ public float touchMajor; /** * The length of the minor axis of an ellipse that describes the touch area at * the point of contact. * If the device is a touch screen, the length is reported in pixels, otherwise it is * reported in device-specific units. * * @see MotionEvent#AXIS_TOUCH_MINOR */ public float touchMinor; /** * The length of the major axis of an ellipse that describes the size of * the approaching 接近 tool. * The tool area represents the estimated 估计的 size of the finger or pen that is * touching the device independent of its actual touch area at the point of contact. * If the device is a touch screen, the length is reported in pixels, otherwise it is * reported in device-specific units. * * @see MotionEvent#AXIS_TOOL_MAJOR */ public float toolMajor; /** * The length of the minor axis of an ellipse that describes the size of * the approaching tool. * The tool area represents the estimated size of the finger or pen that is * touching the device independent of its actual touch area at the point of contact. * If the device is a touch screen, the length is reported in pixels, otherwise it is * reported in device-specific units. * * @see MotionEvent#AXIS_TOOL_MINOR */ public float toolMinor; /** * The orientation of the touch area and tool area in radians clockwise from vertical. * An angle of 0 radians indicates that the major axis of contact is oriented * upwards, is perfectly circular or is of unknown orientation. A positive angle * indicates that the major axis of contact is oriented to the right. A negative angle * indicates that the major axis of contact is oriented to the left. * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians * (finger pointing fully right). * * @see MotionEvent#AXIS_ORIENTATION */ public float orientation; /** * Clears the contents of this object. * Resets all axes to zero. */ public void clear() { mPackedAxisBits = 0; x = 0; y = 0; pressure = 0; size = 0; touchMajor = 0; touchMinor = 0; toolMajor = 0; toolMinor = 0; orientation = 0; } /** * Copies the contents of another pointer coords object. * * @param other The pointer coords object to copy. */ public void copyFrom(PointerCoords other) { final long bits = other.mPackedAxisBits; mPackedAxisBits = bits; if (bits != 0) { final float[] otherValues = other.mPackedAxisValues; final int count = Long.bitCount(bits); float[] values = mPackedAxisValues; if (values == null || count > values.length) { values = new float[otherValues.length]; mPackedAxisValues = values; } System.arraycopy(otherValues, 0, values, 0, count); } x = other.x; y = other.y; pressure = other.pressure; size = other.size; touchMajor = other.touchMajor; touchMinor = other.touchMinor; toolMajor = other.toolMajor; toolMinor = other.toolMinor; orientation = other.orientation; } /** * Gets the value associated with the specified axis. * * @param axis The axis identifier for the axis value to retrieve. * @return The value associated with the axis, or 0 if none. * * @see MotionEvent#AXIS_X * @see MotionEvent#AXIS_Y */ public float getAxisValue(int axis) { switch (axis) { case AXIS_X: return x; case AXIS_Y: return y; case AXIS_PRESSURE: return pressure; case AXIS_SIZE: return size; case AXIS_TOUCH_MAJOR: return touchMajor; case AXIS_TOUCH_MINOR: return touchMinor; case AXIS_TOOL_MAJOR: return toolMajor; case AXIS_TOOL_MINOR: return toolMinor; case AXIS_ORIENTATION: return orientation; default: { if (axis < 0 || axis > 63) { throw new IllegalArgumentException("Axis out of range."); } final long bits = mPackedAxisBits; final long axisBit = 0x8000000000000000L >>> axis; if ((bits & axisBit) == 0) { return 0; } final int index = Long.bitCount(bits & ~(0xFFFFFFFFFFFFFFFFL >>> axis)); return mPackedAxisValues[index]; } } } /** * Sets the value associated with the specified axis. * * @param axis The axis identifier for the axis value to assign. * @param value The value to set. * * @see MotionEvent#AXIS_X * @see MotionEvent#AXIS_Y */ public void setAxisValue(int axis, float value) { switch (axis) { case AXIS_X: x = value; break; case AXIS_Y: y = value; break; case AXIS_PRESSURE: pressure = value; break; case AXIS_SIZE: size = value; break; case AXIS_TOUCH_MAJOR: touchMajor = value; break; case AXIS_TOUCH_MINOR: touchMinor = value; break; case AXIS_TOOL_MAJOR: toolMajor = value; break; case AXIS_TOOL_MINOR: toolMinor = value; break; case AXIS_ORIENTATION: orientation = value; break; default: { if (axis < 0 || axis > 63) { throw new IllegalArgumentException("Axis out of range."); } final long bits = mPackedAxisBits; final long axisBit = 0x8000000000000000L >>> axis; final int index = Long.bitCount(bits & ~(0xFFFFFFFFFFFFFFFFL >>> axis)); float[] values = mPackedAxisValues; if ((bits & axisBit) == 0) { if (values == null) { values = new float[INITIAL_PACKED_AXIS_VALUES]; mPackedAxisValues = values; } else { final int count = Long.bitCount(bits); if (count < values.length) { if (index != count) { System.arraycopy(values, index, values, index + 1, count - index); } } else { float[] newValues = new float[count * 2]; System.arraycopy(values, 0, newValues, 0, index); System.arraycopy(values, index, newValues, index + 1, count - index); values = newValues; mPackedAxisValues = values; } } mPackedAxisBits = bits | axisBit; } values[index] = value; } } } } /** * Transfer object for pointer properties. * * Objects of this type can be used to specify the pointer id and tool type * when creating new {@link MotionEvent} objects and to query pointer properties in bulk. */ public static final class PointerProperties { /** * Creates a pointer properties object with an invalid pointer id. */ public PointerProperties() { clear(); } /** * Creates a pointer properties object as a copy of the contents of * another pointer properties object. * @param other */ public PointerProperties(PointerProperties other) { copyFrom(other); } /** @hide */ public static PointerProperties[] createArray(int size) { PointerProperties[] array = new PointerProperties[size]; for (int i = 0; i < size; i++) { array[i] = new PointerProperties(); } return array; } /** * The pointer id. * Initially set to {@link #INVALID_POINTER_ID} (-1). * * @see MotionEvent#getPointerId(int) */ public int id; /** * The pointer tool type. * Initially set to 0. * * @see MotionEvent#getToolType(int) */ public int toolType; /** * Resets the pointer properties to their initial values. */ public void clear() { id = INVALID_POINTER_ID; toolType = TOOL_TYPE_UNKNOWN; } /** * Copies the contents of another pointer properties object. * * @param other The pointer properties object to copy. */ public void copyFrom(PointerProperties other) { id = other.id; toolType = other.toolType; } @Override public boolean equals(Object other) { if (other instanceof PointerProperties) { return equals((PointerProperties)other); } return false; } private boolean equals(PointerProperties other) { return other != null && id == other.id && toolType == other.toolType; } @Override public int hashCode() { return id | (toolType << 8); } } }
fengyunmars/android-24
android/view/MotionEvent.java
66,559
package com.whinc.model; import com.whinc.Config; import com.whinc.util.PacketUtils; import org.jnetpcap.packet.PcapPacket; import org.jnetpcap.protocol.network.Ip4; /** * {@link PacketInfo}获取数据包的相关信息,内部只保存{@link PcapPacket}的引用 */ public class PacketInfo { /** 标识数据包的流向。true表示数据包发出,false表示数据包流入*/ boolean reversed; private PcapPacket packet; private String name; public PacketInfo(PcapPacket packet) { this.packet = packet; } public PcapPacket getPacket() { return packet; } public boolean isReversed() { return reversed; } public void setReversed(boolean reversed) { this.reversed = reversed; } public long getNumber() { return packet.getFrameNumber(); } public long getTimestamp() { return packet.getCaptureHeader().timestampInMicros() - Config.getTimestamp(); } public String getSourcee() { String addr = "unknown"; Ip4 ip4 = new Ip4(); if (packet.hasHeader(ip4)) { addr = PacketUtils.getReadableIp(ip4.source()); } return addr; } public String getDestination() { String addr = "unknown"; Ip4 ip4 = new Ip4(); if (packet.hasHeader(ip4)) { addr = PacketUtils.getReadableIp(ip4.destination()); } return addr; } public String getProtocolName() { if (name == null || name.isEmpty()) { name = PacketUtils.parseProtocolName(packet); } return name; } public long getLength() { return packet.getTotalSize(); } public String getInfo() { return ""; } }
whinc/PcapAnalyzer
src/com/whinc/model/PacketInfo.java
66,560
package com.lc.algorithms; import com.lc.Exception.AllocationException; import com.lc.model.GCRoots; import com.lc.model.HeapObject; /** * 分代垃圾回收 * @author lc */ public class GenerationalGC { private static final int AGE_MAX = 4; //晋升年龄 private HeapObject[] heap = new HeapObject[1000]; //堆 int old_start = 333; //老年代起点,比例设为2:1 int new_start = 0; //生成空间的起点 int survivor1_start = 266; //survivor1 的起点 int survivor2_start = 300; //survivor2 的起点 int from_survivor_start = survivor1_start; //from_survivor 的起点 int to_survivor_start = survivor2_start; //to_survivor 的起点 HeapObject[] remebered_set = new HeapObject[100]; //记录集 int index = 0; //记录集下标 public int new_free = new_start; //执行生成空间分块开头的指针 int old_free = old_start; //老年代空间的空闲指针 int to_survivor_free = survivor1_start; //幸存空间的空闲空间起点 boolean has_new_obj; //复制后的对象是否还在新生代空间 private GCRoots roots; //根 /** * 写入屏障,用于往记录集里写入对象 * @param obj 发出引用的对象 * @param new_obj 指针更新后成为引用目标的对象 */ public void write_barrier(HeapObject obj, HeapObject new_obj) { //检查三点: //1.发出引用的对象是不是老年代对象 //2.指针更新后的目标对象是不是新生代对象 //3.发出引用的对象是否还没被标记过 //满足这三条,即可被记录到记录集里 if(obj.position > old_start && new_obj.position < old_start && obj.remebered == false) { remebered_set[index] = obj; index++; obj.remebered = true; System.out.println("第 " + obj.position + " 个对象已被记录到记录集中。"); obj.forwarding = new_obj.position; obj.forwarded = true; } } /** * 分配函数 * @param size * @return * @throws AllocationException */ public HeapObject new_obj(int size) throws AllocationException { if(new_free + size >= survivor1_start) { //如果没有足够大小的分块,执行 minor_gc() minor_gc(); if(new_free + size >= survivor1_start) { try { allocation_fail(); } catch (Exception e) { e.printStackTrace(); } } HeapObject obj = new HeapObject(size, new_free); new_free += size; obj.age = 0; obj.remebered = false; return obj; } return null; } /** * 分配失败函数 * @throws AllocationException */ private void allocation_fail() throws AllocationException { throw new AllocationException("分配分块失败"); } /** * 新生代 GC * @throws AllocationException */ private void minor_gc() throws AllocationException { System.out.println("=========新生代垃圾回收启动========="); for(int i = 0; i < roots.getReference().length; i++) { //从根复制能找到的新生代对象 if(roots.getReference()[i].position < old_start) { copy(roots.getReference()[i]); } } int i = 0; while(i < index) { for(HeapObject child : remebered_set) { if(child.position < old_start) { copy(child); } if(child.position < old_start) { has_new_obj = true; } } //如果对象已经不再新生代空间里了 if(has_new_obj == false) { remebered_set[i].remebered = false; index--; } else { i++; } } swap(from_survivor_start, to_survivor_start); System.out.println("=========新生代垃圾回收结束========="); } /** * 交换 from_survivor 空间与 to_survivor 空间 * @param from_survivor_start * @param to_survivor_start */ private void swap(int from_survivor_start, int to_survivor_start) { int temp = to_survivor_start; to_survivor_start = from_survivor_start; from_survivor_start = temp; System.out.println("------->交换from_survivor 与 to_survivor 完成"); } /** * 复制函数 * @param obj * @return 复制的对象地址 * @throws AllocationException */ private int copy(HeapObject obj) throws AllocationException { if(obj.forwarded == false) { //如果复制对象还年轻 if(obj.age < AGE_MAX) { copy_data(to_survivor_free, obj, obj.size); obj.forwarding = to_survivor_free; obj.forwarded = true; heap[to_survivor_free].age++; to_survivor_free += heap[to_survivor_free].size; new_free -= obj.size; //复制子对象 if(obj.children != null) { for(HeapObject child : obj.children) { copy(child); } } } else { //如果达到了晋升年龄 promote(obj); } } return obj.forwarding; } /** * @param to_survivor_free * @param obj * @param size */ private void copy_data(int to_survivor_free, HeapObject obj, int size) { heap[to_survivor_free] = (HeapObject) obj.clone(); to_survivor_free += obj.size; obj.COPIED = true; System.out.println("第 " + obj.position + " 号对象已复制完成"); } /** * 晋升函数 * @param obj * @throws AllocationException */ private void promote(HeapObject obj) throws AllocationException { HeapObject new_obj = allocate_in_old(obj); if(new_obj == null) { major_gc(roots); new_obj = allocate_in_old(obj); if(new_obj == null) { allocation_fail(); } } obj.forwarded = true; obj.forwarding = new_obj.position; for(HeapObject child : obj.children) { if(child.position < old_start) { remebered_set[index] = new_obj; index++; new_obj.remebered = true; } } } /** * 将对象分配到老年代 * @param obj * @return */ private HeapObject allocate_in_old(HeapObject obj) { int pos = obj.position; heap[old_free] = obj; obj.position = old_free; old_free += obj.size; System.out.println("将 " + pos + " 位置上的对象分配到了 " + obj.position + " 位置上"); return heap[obj.position]; } /** * 老年代 GC * @param roots */ private void major_gc(GCRoots roots) { //老年代垃圾回收使用 标记-清除 Mark_Sweep mark_sweep = new Mark_Sweep(); mark_sweep.mark_phase(roots); mark_sweep.sweep_phase(); } public void setRoots(GCRoots roots) { this.roots = roots; } public HeapObject[] getHeap() { return heap; } }
GoldenLiang/GCAlgorithms
src/com/lc/algorithms/GenerationalGC.java
66,561
package events; import java.util.EventObject; import java.util.EventListener; public class events { static public class Panel_over_event extends EventObject{ //一个面板结束的事件对象 public Panel_over_event(Object source){ super(source); } } static public class Add_zidan_event extends EventObject{ //发出一个子弹的事件对象 public int x; //子弹的x,y坐标;或许应该存储每次x,y移动的多少 public int y; //子弹的x,y坐标; public boolean ismy; //是魂斗罗的子弹还是敌人的子弹。 public int jiaodu; //子弹打出时候的角度。 public Add_zidan_event(int x,int y,boolean ismy,int jiaodu,Object source){ super(source); this.x = x; this.y = y; this.ismy = ismy; this.jiaodu = jiaodu; } } /* static public class MenuPanel_over_linstener implements MenuPanel_over_linstener_jiekou{ public void EventActivated(events.MenuPanel_over_event me) { System.out.println("事件已经被触发"); } } */ public interface Panel_over_linstener_jiekou extends EventListener{ //EventListener是一个接口,可是为什么要用extends继承而不是用implements实现接口? public void EventActivated(events.Panel_over_event me); } public interface Add_zidan_jiekou extends EventListener{ //EventListener是一个接口,可是为什么要用extends继承而不是用implements实现接口? public void add_zidan(events.Add_zidan_event event); } } /* * 事件,监听器 * 事件类包含了要传递了一些消息 * 监听器类是一个含有处理事件函数的类 * * 注册监听器就是把一个监听器的引用(指针)传递给要注册的事件源类。当事件发生时,事件源类根 * 据这个指针调用监听器类的 * 处理方法函数 * * 要想实现自定义事件,要在事件源类中添加实现(如addDemoListener)来把这个处理类的指针添 * 加到自己的监听器数组集中(这里要注意同步问题) */
zhangyangjing/JavaContra
events/events.java
66,562
package hardware; import file.DiskInode; import file.UserFileItem; import interrupt.*; import kernel.Instruction; import kernel.PCB; import kernel.Page; import kernel.Schedule; import os.Manager; import java.util.Iterator; /** * CPU中央处理器,负责程序运行的相关操作 * * 用以处理中断,执行指令等 * * @author ZJC */ public class CPU implements InterruptVector { /** * 系统管理器,用以获取系统资源 */ private Manager manager; /** * 程序计数器,下一条指令的执行编号 */ private int PC; /** * 指令寄存器,正在执行的指令编号 */ private int IR; /** * 状态寄存器 0用户态 1内核态 */ private int PSW; public static final int USER_STATE = 0; public static final int KERNEL_STATE = 1; /** * 当前运行态的PCB指针 */ private PCB runningPCB; /** * 允许调度标志,控制调度时机 * 只有该标志打开后,才可以进行三级调度,否则CPU执行指令和调度操作将会出现混乱 */ private volatile boolean canSchedule; /** * 当前剩余时间片 */ private int timeSlice; /** * 因缺页中断而剩余的时间片 */ private int missPageRemainTimeSlice; public CPU(Manager manager) { this.manager = manager; this.PC = 1; this.IR = 0; this.PSW = USER_STATE; this.runningPCB = null; this.canSchedule = false; this.timeSlice = 0; this.missPageRemainTimeSlice = 0; this.manager.getDashboard().consoleSuccess("CPU初始化完成"); } /** * 中断处理 * @param interruptVector 中断向量 用以区别中断例程 * @param index 中断处理的附加参数 */ public synchronized void interrupt(int interruptVector, int index) { switch (interruptVector) { // 时钟中断处理 case CLOCK_INTERRUPT: { // 允许调度 this.openSchedule(); break; } // 缺页中断处理 case MISS_PAGE_INTERRUPT: { this.switchToKernelState(); // 缺页中断线程启动, index为缺页的逻辑页号 new MissPageInterrupt(this.manager, this.runningPCB, index).start(); // 设置缺页标志 this.runningPCB.setMissPage(true); // 当前进程阻塞 this.runningPCB.block(this.manager.getSchedule().getBlockQueue()); break; } // 资源申请中断处理 case APPLY_RESOURCE_INTERRUPT: { // 申请资源,index为资源种类 this.manager.getDeadlock().applyResource(this.runningPCB, index); // 尝试分配资源 int allocateResult = this.manager.getDeadlock().tryAllocateResource(this.runningPCB, index); // 如果返回阻塞标志,则阻塞进程 if (allocateResult == -1) { this.manager.getDashboard().consoleError("资源 " + index + " 分配失败,进程 " + this.runningPCB.getId() + " 阻塞"); this.runningPCB.block(this.manager.getSchedule().getResourceBlockQueues()[index]); } break; } // 资源释放中断处理 case RELEASE_RESOURCE_INTERRUPT: { // 释放资源,index为资源种类 this.manager.getDeadlock().releaseResource(this.runningPCB, index); // 尝试重分配资源 if (this.manager.getSchedule().getResourceBlockQueues()[index].size() > 0) { int reallocateResult = this.manager.getDeadlock().tryReallocateResource(this.manager.getSchedule().getResourceBlockQueues()[index].get(0), index); // 如果返回唤醒标志,则唤醒阻塞队列队首进程 if (reallocateResult == -1) { this.manager.getSchedule().getResourceBlockQueues()[index].get(0).wakeUp(this.manager.getSchedule().getResourceBlockQueues()[index]); } } break; } // 输入中断 case INPUT_INTERRUPT: { // index 为页框号 PCB tempPCB = this.runningPCB; tempPCB.block(this.manager.getSchedule().getBlockQueue()); String filePath = tempPCB.getCodeSegment().getInstruction()[this.IR - 1].getExtra().split(" ")[1]; Iterator<UserFileItem> iterator = tempPCB.getUserOpenFileTable().iterator(); while (iterator.hasNext()) { UserFileItem userFileItem = iterator.next(); try { DiskInode currentInode = this.manager.getFileSystem().getDiskInodeMap().get("" + userFileItem.getFp().getInode().getInodeNo()); DiskInode targetInode = this.manager.getFileSystem().getDiskInodeByPath(filePath); if (currentInode == targetInode) { this.switchToKernelState(); new IOInterrupt(this.manager, tempPCB, IOInterrupt.INPUT, index, userFileItem.getFd()).start(); break; } } catch (Exception e) { e.printStackTrace(); } } break; } // 输出中断 case OUTPUT_INTERRUPT: { // index 为页框号 PCB tempPCB = this.runningPCB; tempPCB.block(this.manager.getSchedule().getBlockQueue()); String filePath = tempPCB.getCodeSegment().getInstruction()[this.IR - 1].getExtra().split(" ")[1]; Iterator<UserFileItem> iterator = tempPCB.getUserOpenFileTable().iterator(); while (iterator.hasNext()) { UserFileItem userFileItem = iterator.next(); try { if (this.manager.getFileSystem().getDiskInodeMap().get("" + userFileItem.getFp().getInode().getInodeNo()) == this.manager.getFileSystem().getDiskInodeByPath(filePath)) { this.switchToKernelState(); new IOInterrupt(this.manager, tempPCB, IOInterrupt.OUTPUT, index, userFileItem.getFd()).start(); break; } } catch (Exception e) { e.printStackTrace(); } } break; } // 作业请求中断 case JOB_REQUEST_INTERRUPT: { this.switchToKernelState(); new JobRequestInterrupt(this.manager).start(); break; } // 文件创建中断 case CREATE_FILE_INTERRUPT: { this.switchToKernelState(); PCB tempPCB = this.runningPCB; tempPCB.block(this.manager.getSchedule().getBlockQueue()); new FileOperationInterrupt(this.manager, tempPCB, FileOperationInterrupt.CREATE_FILE).start(); break; } // 文件关闭中断 case CLOSE_FILE_INTERRUPT: { this.switchToKernelState(); PCB tempPCB = this.runningPCB; tempPCB.block(this.manager.getSchedule().getBlockQueue()); new FileOperationInterrupt(this.manager, tempPCB, FileOperationInterrupt.CLOSE_FILE).start(); break; } default: { break; } } this.switchToUserState(); } /** * 执行当前指令 */ public synchronized void execute() { // 刷新GUI this.manager.getDashboard().refreshRunningProcess(); if (this.runningPCB == null) { return; } // 执行指令需要内存中有代码段数据 int codeSegmentPageItemAddress = this.runningPCB.getPageTableBaseAddress() + this.runningPCB.getCodeSegment().getLogicPageStartNo() * InternalMem.PAGE_TABLE_ITEM_SIZE; this.manager.getAddressLine().setAddress((short) codeSegmentPageItemAddress); Page codePage = this.manager.getInMem().readPageItem(this.manager.getAddressLine()); if (codePage.getCallFlag() == 0) { // 代码段页面未装入,则执行缺页中断,装入代码页 this.manager.getDashboard().consoleLog("代码段数据未装入内存,优先装入代码段"); this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, codePage.getLogicPageNo()); return; } else { // 代码段页面已经装入,则看作一次访问内存,并更新快表 this.manager.getInMem().readPage(codePage); this.runningPCB.accessPage(codePage.getLogicPageNo()); this.manager.getMmu().updateTLB(codePage.getLogicPageNo(), codePage.getInternalFrameNo()); } // 指令指针自增并获取当前指令 this.IR = this.PC++; Instruction currentInstrction = new Instruction(); int id = ((((int) codePage.getData()[8 * (IR - 1) + 1]) << 8) & 0x0000FF00) | (((int) codePage.getData()[8 * (IR - 1) + 0]) & 0x0000FF); int state = ((((int) codePage.getData()[8 * (IR - 1) + 3]) << 8) & 0x0000FF00) | (((int) codePage.getData()[8 * (IR - 1) + 2]) & 0x0000FF); int argument = ((((int) codePage.getData()[8 * (IR - 1) + 5]) << 8) & 0x0000FF00) | (((int) codePage.getData()[8 * (IR - 1) + 4]) & 0x0000FF); currentInstrction.setId(id); currentInstrction.setState(state); currentInstrction.setArgument(argument); currentInstrction.setExtra(this.runningPCB.getCodeSegment().getInstruction()[this.IR - 1].getExtra()); this.manager.getDashboard().consoleLog("执行进程 " + this.runningPCB.getId() + " :" + " 指令 " + currentInstrction.getId() + " 类型 " + currentInstrction.getState() + " 参数 " + currentInstrction.getArgument() + " 附加数据 " + currentInstrction.getExtra()); switch (currentInstrction.getState()) { // 0 system 系统调用,本系统中仿真为输入、输出、创建文件操作 case 0: { int type = currentInstrction.getArgument(); String extra = currentInstrction.getExtra(); if (type == 0) { // 创建文件 this.interrupt(InterruptVector.CREATE_FILE_INTERRUPT, 0); } else if (type == 1) { // 输入操作 try { int logicAddress = (this.runningPCB.getDataSegment().getLogicPageStartNo() + Integer.parseInt(extra.split(" ")[0])) * InternalMem.PAGE_SIZE; String filePath = extra.split(" ")[1]; short physicAddress = this.manager.getMmu().resolveLogicAddress((short) logicAddress, this.runningPCB.getPageTableBaseAddress()); if (physicAddress == -1) { // 出现缺页,则PC、IR回退一步 --this.IR; --this.PC; // 保存当前时间片 this.missPageRemainTimeSlice = this.timeSlice; // 发出缺页中断请求 this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, logicAddress / InternalMem.PAGE_SIZE); } else { this.runningPCB.accessPage(logicAddress / InternalMem.PAGE_SIZE); this.interrupt(InterruptVector.INPUT_INTERRUPT, physicAddress / InternalMem.PAGE_SIZE); } } catch (Exception e) { e.printStackTrace(); } } else if (type == 2) { // 输出操作 int logicAddress = (this.runningPCB.getDataSegment().getLogicPageStartNo() + Integer.parseInt(extra.split(" ")[0])) * InternalMem.PAGE_SIZE; String filePath = extra.split(" ")[1]; short physicAddress = this.manager.getMmu().resolveLogicAddress((short) logicAddress, this.runningPCB.getPageTableBaseAddress()); if (physicAddress == -1) { // 出现缺页,则PC、IR回退一步 --this.IR; --this.PC; // 保存当前时间片 this.missPageRemainTimeSlice = this.timeSlice; // 发出缺页中断请求 this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, logicAddress / InternalMem.PAGE_SIZE); } else { this.runningPCB.accessPage(logicAddress / InternalMem.PAGE_SIZE); this.interrupt(InterruptVector.OUTPUT_INTERRUPT, physicAddress / InternalMem.PAGE_SIZE); } } else if (type == 3) { // 关闭文件 this.interrupt(InterruptVector.CLOSE_FILE_INTERRUPT, 0); } break; } // 1 calculate 计算指令,CPU不需要调用任何额外资源,可直接运行 case 1: { // CPU内部进行计算操作,不做任何处理 this.manager.getDashboard().consoleLog("计算指令"); break; } // 2 load 读取指令,对内存数据进行读取 case 2: { // 解析逻辑地址,返回 -1,则表示缺页 short physicAddress = this.manager.getMmu().resolveLogicAddress((short)currentInstrction.getArgument(), this.runningPCB.getPageTableBaseAddress()); if (physicAddress == -1) { // 出现缺页,则PC、IR回退一步 --this.IR; --this.PC; // 保存当前时间片 this.missPageRemainTimeSlice = this.timeSlice; // 发出缺页中断请求 this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, currentInstrction.getArgument() / InternalMem.PAGE_SIZE); } else { this.manager.getAddressLine().setAddress(physicAddress); short loadData = this.manager.getInMem().readData(this.manager.getAddressLine()); this.runningPCB.accessPage(currentInstrction.getArgument() / InternalMem.PAGE_SIZE); this.manager.getDashboard().consoleLog("从内存地址" + physicAddress + " 读取数据 " + loadData); } break; } // 3 store 写入指令,对内存数据进行写入 case 3: { // 解析逻辑地址,返回 -1,则表示缺页 short physicAddress = this.manager.getMmu().resolveLogicAddress((short)currentInstrction.getArgument(), this.runningPCB.getPageTableBaseAddress()); if (physicAddress == -1) { // 出现缺页,则PC、IR回退一步 --this.IR; --this.PC; // 保存当前时间片 this.missPageRemainTimeSlice = this.timeSlice; // 发出缺页中断请求 this.interrupt(InterruptVector.MISS_PAGE_INTERRUPT, currentInstrction.getArgument() / InternalMem.PAGE_SIZE); } else { this.manager.getAddressLine().setAddress(physicAddress); this.manager.getDataLine().setData((short)0x6666); this.manager.getInMem().writeData(this.manager.getAddressLine(), this.manager.getDataLine()); this.runningPCB.accessPage(currentInstrction.getArgument() / InternalMem.PAGE_SIZE); // 设置页表项修改位为1 int pageItemAddress = this.runningPCB.getPageTableBaseAddress() + currentInstrction.getArgument() / InternalMem.PAGE_SIZE * InternalMem.PAGE_TABLE_ITEM_SIZE; this.manager.getAddressLine().setAddress((short) pageItemAddress); Page page = this.manager.getInMem().readPageItem(this.manager.getAddressLine()); page.setModifyFlag(1); this.manager.getAddressLine().setAddress((short) pageItemAddress); this.manager.getInMem().writePageItem(this.manager.getAddressLine(), page); this.manager.getDashboard().consoleLog("向内存地址" + physicAddress + " 写入数据 " + 0x6666); } break; } // 4 switch 进程切换,直接进行调度 case 4: { // 时间片置1,执行指令后时间片统一 -1,完成进程强制切换 this.timeSlice = 1; this.manager.getDashboard().consoleLog("切换指令"); break; } // 5 jump 跳转指令,跳过代码段执行 case 5: { // 设置PC指向跳转地址 this.PC = currentInstrction.getArgument(); this.manager.getDashboard().consoleLog("跳转指令"); break; } // 6 apply 资源申请,申请一个系统资源 case 6: { // 发出资源申请中断 this.interrupt(InterruptVector.APPLY_RESOURCE_INTERRUPT, currentInstrction.getArgument()); break; } // 7 release 资源释放,释放一个系统资源 case 7: { // 发出资源释放中断 this.interrupt(InterruptVector.RELEASE_RESOURCE_INTERRUPT, currentInstrction.getArgument()); break; } default: { break; } } // 时间片 -1 --this.timeSlice; } /** * 恢复CPU现场 * @param pcb 即将进入运行态的进程 PCB */ public synchronized void recoverSpot(PCB pcb) { this.PC = pcb.getPC(); this.IR = pcb.getIR(); this.timeSlice = Schedule.SYSTEM_TIME_SLICE; // 进程设置运行态 this.runningPCB = pcb; // 初始化快表 this.manager.getMmu().initTLB(); // 如果因为缺页中断而恢复CPU现场,则使用之前的时间片 if (this.missPageRemainTimeSlice != 0) { this.timeSlice = this.missPageRemainTimeSlice; this.missPageRemainTimeSlice = 0; } // 更新GUI this.manager.getDashboard().refreshRunningProcess(); } /** * 保护CPU现场 */ public synchronized void protectSpot() { this.runningPCB.setIR((short)this.IR); this.runningPCB.setPC((short)this.PC); // 进程解除运行态 this.runningPCB = null; // 更新GUI this.manager.getDashboard().refreshRunningProcess(); } /** * 打开调度 */ public synchronized void openSchedule() { this.canSchedule = true; } /** * 关闭调度 */ public synchronized void closeSchedule() { this.canSchedule = false; } /** * 切换内核态 */ public synchronized void switchToKernelState() { if (this.PSW == KERNEL_STATE) { return; } this.PSW = KERNEL_STATE; this.manager.getDashboard().consoleLog("CPU -> 内核态"); this.manager.getDashboard().refreshCPU(); } /** * 切换用户态 */ public synchronized void switchToUserState() { if (this.PSW == USER_STATE) { return; } this.PSW = USER_STATE; this.manager.getDashboard().consoleLog("CPU -> 用户态"); this.manager.getDashboard().refreshCPU(); } public Manager getManager() { return manager; } public void setManager(Manager manager) { this.manager = manager; } public int getPC() { return PC; } public void setPC(int PC) { this.PC = PC; } public int getIR() { return IR; } public void setIR(int IR) { this.IR = IR; } public int getPSW() { return PSW; } public void setPSW(int PSW) { this.PSW = PSW; } public PCB getRunningPCB() { return runningPCB; } public void setRunningPCB(PCB runningPCB) { this.runningPCB = runningPCB; } public boolean isCanSchedule() { return canSchedule; } public void setCanSchedule(boolean canSchedule) { this.canSchedule = canSchedule; } public int getTimeSlice() { return timeSlice; } public void setTimeSlice(int timeSlice) { this.timeSlice = timeSlice; } }
404874351/NJAU-OS-course-design-simulated-linux
src/hardware/CPU.java
66,564
package ts; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.alibaba.fastjson.JSON; import com.hanqinet.edm.ws.prnasia.dto.upload.Task; import com.hanqinet.edm.ws.prnasia.dto.upload.Template; import com.lvmama.operate.mail.HqEMailSenderService; import com.lvmama.operate.mail.model.ResultMessage; public class Demo1 { public static void main(String[] args) throws Exception { // sendEmail(); test1(); } public static void test1() throws MalformedURLException { long startTime = System.currentTimeMillis(); List<Integer> taskIdList = new ArrayList<Integer>(); for (int i = 107; i <=110; i++) { taskIdList.add(i); } String result = JSON.toJSONString(HqEMailSenderService.getInstance().getEdmService().getTaskInfo(taskIdList),true); System.out.println(result); System.out.println(System.currentTimeMillis()-startTime); } public static void sendEmail() throws IOException { //组装任务对象 Task task = new Task(); task.setTaskGroupId("1"); task.setTaskName("test" + UUID.randomUUID().toString()); task.setEmailColumnName("email,vary01"); //组装模板对象 Template template = new Template(); template.setTemplateName("template-test" + UUID.randomUUID().toString()); template.setSenderChinese("demo11测试");//发件人昵称 template.setSenderEmail("[email protected]");//发件人email template.setSubject("test" + UUID.randomUUID().toString()); template.setBodyCharset("GBK"); template.setBodyEncoding("base64"); //发出邮件使用编码格式 template.setTemplateContent("<h2 style='color:#FF0000;'>$$data.vary01$$</h2>"); template.setToChinese("$$fullname$$"); template.setTemplateType("1"); //html格式模板 String [] emaiList = new String[]{"[email protected],你好啊","[email protected],你好啊"}; ResultMessage message =HqEMailSenderService.getInstance().sendEmail(task, template, emaiList, null,true); System.out.println(JSON.toJSONString(message,true)); } }
feiniu7903/feiniu_pet
Super_operate/src/java/ts/Demo1.java
66,565
package com.mrpoid.utils; import com.mrpoid.utils.Frequency.Entiry; import android.content.Context; import android.database.Cursor; import android.net.Uri; public final class SmsUtil { public static final String SMS_URI_ALL = "content://sms/"; public static final String SMS_URI_INBOX = "content://sms/inbox"; public static final String SMS_URI_SEND = "content://sms/sent"; public static final String SMS_URI_DRAFT = "content://sms/draft"; /** * * @param args *<ol> * <li>_id => 短消息序号 如100 </li> * <li>thread_id => 对话的序号 如100</li> * <li>address => 发件人地址,手机号.如+8613811810000</li> * <li>person => 发件人,返回一个数字就是联系人列表里的序号,陌生人为null</li> * <li>date => 日期 long型。如1256539465022</li> * <li>protocol => 协议 0 SMS_RPOTO, 1 MMS_PROTO</li> * <li>read => 是否阅读 0未读, 1已读</li> * <li>status => 状态 -1接收,0 complete, 64 pending, 128 failed</li> * <li>type => 类型 1是接收到的,2是已发出</li> * <li>body => 短消息内容</li> * <li>service_center => 短信服务中心号码编号。如+8613800755500</li> *</ol> */ public static Cursor getSms(Context context, String where, String[] args) { final String SORT_ORDER = "date DESC";//时间降序查找 return context.getContentResolver().query( Uri.parse(where), args, null, null, //条件 SORT_ORDER); } /** * 读取短信 * * @return */ public static String getSmsCenter(Context context) { return doCursor(getSms(context, SMS_URI_INBOX, new String[] { "service_center" }) ); } /** * 处理游标,得到短信中心号 * * @param cur * 游标 * @return 短信中心号 */ private static String doCursor(Cursor cur) { // 短信中心号 String smscenter = ""; if (cur!=null && cur.moveToFirst()) { int smscColumn = cur.getColumnIndex("service_center"); // 频率统计 Frequency fre = new Frequency(); int index = 0; String smsc; do { smsc = cur.getString(smscColumn); if(smsc != null && smsc.length() > 0){ //获取到的可能是 null fre.addStatistics(smsc); // 添加到频率统计 index++; } } while (cur.moveToNext() && index < 50); Entiry e = fre.getMaxValueItem(); if(e != null){ smscenter = e.getKey(); } } return smscenter; } }
Yichou/libMrpoid
src/com/mrpoid/utils/SmsUtil.java
66,566
package com.gogo.event; /** * User: 刘永健 * Date: 12-10-2 * Time: 下午10:53 * To change this template use File | Settings | File Templates. */ /** * 一个EventEmitter能为某个事件注册监听器,或发出某个事件的通知 */ public interface EventEmitter { /** * 为事件注册监听器 * * @param eventName * 事件名 * @param handler */ public void on(String eventName, EventHandler handler); /** * 发出某个事件的通知 * * @param eventName * 事件名 * @param args */ public void emit(String eventName, Object... args); /** * 移除该事件的所有监听器 * * @param eventName */ public void remove(String eventName); }
guoshun0321/GOGO-s-TEST
nio/EventEmitter.java
66,567
package xzg.Reflect.com; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class TestJdbcBlog { public static void main(String[] args) { Connection con = null; try { // 1. 加载驱动(Java6以上版本可以省略) Class.forName("com.mysql.jdbc.Driver"); // 2. 建立连接 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); // 3. 创建语句对象 PreparedStatement ps = con.prepareStatement("insert into tb_user values (default, ?, ?)"); ps.setString(1, "名字"); // 将SQL语句中第一个占位符换成字符串 try (InputStream in = new FileInputStream("test.jpg")) { // Java 7的TWR ps.setBinaryStream(2, in); // 将SQL语句中第二个占位符换成二进制流 // 4. 发出SQL语句获得受影响行数 System.out.println(ps.executeUpdate() == 1 ? "插入成功" : "插入失败"); } catch(IOException e) { System.out.println("读取照片失败!"); } } catch (ClassNotFoundException | SQLException e) { // Java 7的多异常捕获 e.printStackTrace(); } finally { // 释放外部资源的代码都应当放在finally中保证其能够得到执行 try { if(con != null && !con.isClosed()) { con.close(); // 5. 释放数据库连接 con = null; // 指示垃圾回收器可以回收该对象 } } catch (SQLException e) { e.printStackTrace(); } } } }
xiongzhenggang/xiongzhenggang.github.io
java运用/反射/TestJdbcBlog.java
66,568
package WeeklyContest; import java.util.Arrays; /** * 5969. 摧毁小行星 * 给你一个整数 mass ,它表示一颗行星的初始质量。再给你一个整数数组 asteroids ,其中 asteroids[i] 是第 i 颗小行星的质量。 * <p> * 你可以按 任意顺序 重新安排小行星的顺序,然后让行星跟它们发生碰撞。如果行星碰撞时的质量 大于等于 小行星的质量,那么小行星被 摧毁 ,并且行星会 获得 这颗小行星的质量。否则,行星将被摧毁。 * <p> * 如果所有小行星 都 能被摧毁,请返回 true ,否则返回 false 。 * <p> * 示例 1: * 输入:mass = 10, asteroids = [3,9,19,5,21] * 输出:true * 解释:一种安排小行星的方式为 [9,19,5,3,21] : * - 行星与质量为 9 的小行星碰撞。新的行星质量为:10 + 9 = 19 * - 行星与质量为 19 的小行星碰撞。新的行星质量为:19 + 19 = 38 * - 行星与质量为 5 的小行星碰撞。新的行星质量为:38 + 5 = 43 * - 行星与质量为 3 的小行星碰撞。新的行星质量为:43 + 3 = 46 * - 行星与质量为 21 的小行星碰撞。新的行星质量为:46 + 21 = 67 * 所有小行星都被摧毁。 * <p> * 示例 2: * 输入:mass = 5, asteroids = [4,9,23,4] * 输出:false * 解释: * 行星无论如何没法获得足够质量去摧毁质量为 23 的小行星。 * 行星把别的小行星摧毁后,质量为 5 + 4 + 9 + 4 = 22 。 * 它比 23 小,所以无法摧毁最后一颗小行星。 *   * <p> * 提示: * 1 <= mass <= 10^5 * 1 <= asteroids.length <= 10^5 * 1 <= asteroids[i] <= 10^5 * <p> * 链接:https://leetcode-cn.com/problems/destroying-asteroids * * @author xurongfei * @Date 2022/1/2 */ public class no5969_destroying_asteroids { public boolean asteroidsDestroyed(int mass, int[] asteroids) { //BigInteger res = new BigInteger(mass+""); long result = mass; Arrays.sort(asteroids); int len = asteroids.length; for (int i = 0; i < len; i++) { int val = asteroids[i]; if (result >= val) { result += val; } else { result = 0; break; } } return result == 0 ? false : true; } }
xrfinbupt/leetcode_java
src/main/java/WeeklyContest/no5969_destroying_asteroids.java
66,569
package com.topnews.fragment; import java.util.ArrayList; import org.w3c.dom.Text; import com.topnews.CityListActivity; import com.topnews.DetailsActivity; import com.topnews.R; import com.topnews.adapter.NewsAdapter; import com.topnews.bean.NewsEntity; import com.topnews.tool.Constants; import com.topnews.view.HeadListView; import com.topnews.view.TopToastView; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.util.Log; 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.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; public class NewsFragment extends Fragment { private final static String TAG = "NewsFragment"; Activity activity; ArrayList<NewsEntity> newsList = new ArrayList<NewsEntity>(); HeadListView mListView; NewsAdapter mAdapter; String text; int channel_id; ImageView detail_loading; public final static int SET_NEWSLIST = 0; //Toast提示框 private RelativeLayout notify_view; private TextView notify_view_text; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub Bundle args = getArguments(); text = args != null ? args.getString("text") : ""; channel_id = args != null ? args.getInt("id", 0) : 0; initData(); super.onCreate(savedInstanceState); } @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub this.activity = activity; super.onAttach(activity); } /** 此方法意思为fragment是否可见 ,可见时候加载数据 */ @Override public void setUserVisibleHint(boolean isVisibleToUser) { if (isVisibleToUser) { //fragment可见时加载数据 if(newsList !=null && newsList.size() !=0){ handler.obtainMessage(SET_NEWSLIST).sendToTarget(); }else{ new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.obtainMessage(SET_NEWSLIST).sendToTarget(); } }).start(); } }else{ //fragment不可见时不执行操作 } super.setUserVisibleHint(isVisibleToUser); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = LayoutInflater.from(getActivity()).inflate(R.layout.news_fragment, null); mListView = (HeadListView) view.findViewById(R.id.mListView); TextView item_textview = (TextView)view.findViewById(R.id.item_textview); detail_loading = (ImageView)view.findViewById(R.id.detail_loading); //Toast提示框 notify_view = (RelativeLayout)view.findViewById(R.id.notify_view); notify_view_text = (TextView)view.findViewById(R.id.notify_view_text); item_textview.setText(text); return view; } private void initData() { newsList = Constants.getNewsList(); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub switch (msg.what) { case SET_NEWSLIST: detail_loading.setVisibility(View.GONE); if(mAdapter == null){ mAdapter = new NewsAdapter(activity, newsList); //判断是不是城市的频道 if(channel_id == Constants.CHANNEL_CITY){ //是城市频道 mAdapter.setCityChannel(true); initCityChannel(); } } mListView.setAdapter(mAdapter); mListView.setOnScrollListener(mAdapter); mListView.setPinnedHeaderView(LayoutInflater.from(activity).inflate(R.layout.list_item_section, mListView, false)); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(activity, DetailsActivity.class); if(channel_id == Constants.CHANNEL_CITY){ if(position != 0){ intent.putExtra("news", mAdapter.getItem(position - 1)); startActivity(intent); activity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } }else{ intent.putExtra("news", mAdapter.getItem(position)); startActivity(intent); activity.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } } }); if(channel_id == 1){ initNotify(); } break; default: break; } super.handleMessage(msg); } }; /* 初始化选择城市的header*/ public void initCityChannel() { View headview = LayoutInflater.from(activity).inflate(R.layout.city_category_list_tip, null); TextView chose_city_tip = (TextView) headview.findViewById(R.id.chose_city_tip); chose_city_tip.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(activity, CityListActivity.class); startActivity(intent); } }); mListView.addHeaderView(headview); } /* 初始化通知栏目*/ private void initNotify() { new Handler().postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub notify_view_text.setText(String.format(getString(R.string.ss_pattern_update), 10)); notify_view.setVisibility(View.VISIBLE); new Handler().postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub notify_view.setVisibility(View.GONE); } }, 2000); } }, 1000); } /* 摧毁视图 */ @Override public void onDestroyView() { // TODO Auto-generated method stub super.onDestroyView(); Log.d("onDestroyView", "channel_id = " + channel_id); mAdapter = null; } /* 摧毁该Fragment,一般是FragmentActivity 被摧毁的时候伴随着摧毁 */ @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Log.d(TAG, "channel_id = " + channel_id); } }
Rano1/TopNews
TopNews/src/com/topnews/fragment/NewsFragment.java
66,570
/* We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. Example 1: Input: asteroids = [5, 10, -5] Output: [5, 10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. Example 2: Input: asteroids = [8, -8] Output: [] Explanation: The 8 and -8 collide exploding each other. Example 3: Input: asteroids = [10, 2, -5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. Example 4: Input: asteroids = [-2, -1, 1, 2] Output: [-2, -1, 1, 2] Explanation: The -2 and -1 are moving left, while the 1 and 2 are moving right. Asteroids moving the same direction never meet, so no asteroids will meet each other. Note: The length of asteroids will be at most 10000. Each asteroid will be a non-zero integer in the range [-1000, 1000].. */ /** * Approach: Stack (Simulation) * 根据分析,我们发现结果只可能是 [-, -, -, ... +, +, +] * 当然也可能只有一种方向存在。但是如果两种方向都存在的话,必定为左边全为负方向,右边全为正方向。 * 否则就会发生碰撞。并且我们可以分析出来只有一种情况下会发生碰撞: * 前一个方向为 正方形 且当前方向为 负方向 时,此时才可能发生碰撞情况。 * 其他情况下是不可能发生碰撞的,这个过程和 Stack 的进出非常类似,因此我们可以使用 Stack 来模拟整个过程。 * 当碰撞发生时,我们根据陨石的大小进行分情况处理,而没发生的时候直接 push 到 Stack 中即可。 * 碰撞发生时有以下情况: * 1. 当前陨石大小 > 栈顶陨石大小即前一个陨石的大小,此时栈顶的陨石被摧毁,即 stack.pop(),后续将 push 当前陨石 * 2. 当前陨石大小 = 栈顶陨石大小,此时二者均被摧毁,即 stack.pop(),后续不能进行 push 操作 * 3. 当前陨石大小 < 栈顶陨石大小,此时当前陨石被摧毁,即跳过当前陨石的 push() 操作即可。 * * 时间复杂度:O(n) * 空间复杂度:O(n) */ class Solution { public int[] asteroidCollision(int[] asteroids) { Stack<Integer> stack = new Stack<>(); for (int asteroid : asteroids) { // 左边的陨石向右,当前的陨石向左,且当前陨石的大小更大 // 因此栈顶的陨石将被摧毁(pop出栈顶元素) while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < -asteroid) { stack.pop(); } // 否则,如果左边不存在陨石,或者左边陨石方向向左,或者当前陨石方向向右,均不会发生碰撞情况 if (stack.isEmpty() || asteroid > 0 || stack.peek() < 0) { stack.push(asteroid); } else if (asteroid < 0 && stack.peek() == -asteroid) { // 如果会发生碰撞,并且两个陨石大小相等,则左边的陨石被摧毁,同时当前陨石无法入栈 stack.pop(); } } int[] rst = new int[stack.size()]; for (int i = rst.length - 1; i >= 0; i--) { rst[i] = stack.pop(); } return rst; } }
cherryljr/LeetCode
Asteroid Collision.java
66,572
package in.hocg.netty.server.netty; /** * Created by hocgin on 2019/3/2. * email: [email protected] * * @author hocgin */ public interface NettyServer { /** * 启动 */ void start(); /** * 摧毁 */ void destroy(); }
hocgin/spring-boot-starters-project
spring-boot-netty/netty-server/src/main/java/in/hocg/netty/server/netty/NettyServer.java
66,573
package web.Listener; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Timer; import java.util.TimerTask; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionIdListener; import javax.servlet.http.HttpSessionListener; /** * Application Lifecycle Listener implementation class SessionScanner * */ @WebListener public class SessionScanner implements HttpSessionListener, HttpSessionAttributeListener, HttpSessionActivationListener, HttpSessionBindingListener, HttpSessionIdListener,ServletContextListener { private List list = Collections.synchronizedList(new LinkedList());//调用该方法可以让List是线程安全的,不会发生两个对象抢一个位置的情况,列表也是单线程的 private Object lock = new Object();//该Lock的作用是将多个代码放到线程安全的代码块内,几段代码共享同一个Lock,如果有一个线程在使用lock,则其他要用到Lock的对象要等待 static final int SESSION_EXSIT_TIME = 5*60*1000; public SessionScanner() { // TODO Auto-generated constructor stub } public void sessionCreated(HttpSessionEvent se) { HttpSession session = se.getSession(); System.out.println("创建!!!!!!!"); synchronized(lock) { list.add(session); } } public void valueBound(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub } public void sessionIdChanged(HttpSessionEvent arg0, String arg1) { // TODO Auto-generated method stub } public void sessionDestroyed(HttpSessionEvent arg0) { System.out.println("摧毁!!!!!!!!!!"); } public void sessionDidActivate(HttpSessionEvent arg0) { // TODO Auto-generated method stub } public void attributeAdded(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub } public void attributeRemoved(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub } public void attributeReplaced(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub } public void sessionWillPassivate(HttpSessionEvent arg0) { // TODO Auto-generated method stub } public void valueUnbound(HttpSessionBindingEvent arg0) { // TODO Auto-generated method stub } @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent arg0) { Timer timer = new Timer(); timer.schedule(new MyTask(list,lock), 0, SESSION_EXSIT_TIME); } } class MyTask extends TimerTask{ private List list; private Object lock; public MyTask(List list,Object lock) { this.list = list; this.lock = lock; } public void run() { synchronized(this.lock) { ListIterator it = list.listIterator(); while(it.hasNext()) { HttpSession session = (HttpSession) it.next(); if(System.currentTimeMillis() - session.getLastAccessedTime() > SessionScanner.SESSION_EXSIT_TIME) { session.invalidate();//getLastAccessedTime可以得到session的上次访问时间,判断和系统当前时间的差异,如果大于5分钟则摧毁掉 //list.remove(session);在集合迭代器迭代的时候如果删除元素,会抛出并发修改异常。 //如果要在迭代的过程中进行增删改查,要使用iterator的子类ListIterator的方法 //但也会出现问题,比如在迭代器正在迭代的过程中如果又有用户访问,此时向List中添加了数据,但是迭代器并不知道,此时会出现并发异常 it.remove(); } } } } }
bybywudi/testt
src/web/Listener/SessionScanner.java
66,574
package org.triple.rpc; import org.triple.common.TpURL; import org.triple.common.extension.SPI; import org.triple.rpc.exception.RpcException; /** * 这是一个核心类,用于对外暴露服务,不通种的protocol应该采用不同的port * @author Cxl * @createTime 2013-4-2 */ @SPI("triple") public interface Protocol { /** * 获取协议名 * @return * @author Cxl * @createTime 2013-5-2 */ public String getProtocolName(); /** * 获取默认的端口 * @return * @author Cxl * @createTime 2013-4-2 */ public int getDefaultPort(); /** * Invoker【这个是P端的invoker】,进行暴露动作,将一个包含实际执行实例(代理对象)的Invoker进行发布动作 * 采用注册中心时,这个方法被执行后 可以在注册中心发现对应的信息 * @param invoker * @return * @throws RpcException * @author Cxl * @createTime 2013-4-2 */ public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException; /** * Invoker【这个是C端的invoker】, 对iface 进行处理,得到一个能通过TpURL进行调用的Invoker * @param iface * @param tpURL * @return * @throws RpcException * @author Cxl * @createTime 2013-4-2 */ public <T> Invoker<T> refer(Class<T> iface, TpURL tpURL) throws RpcException; /** * 将一个protocol 摧毁,关闭服务,关闭端口 * @author Cxl * @createTime 2013-4-2 */ public void destroy(); }
GoliathGeek/TripleFrameWork
src/org/triple/rpc/Protocol.java
66,576
package LeeCode; public class code2511 { public static void main(String[] args) { //给你一个长度为 n ,下标从 0 开始的整数数组 forts ,表示一些城堡。forts[i] 可以是 -1 ,0 或者 1 ,其中: // //-1 表示第 i 个位置 没有 城堡。 //0 表示第 i 个位置有一个 敌人 的城堡。 //1 表示第 i 个位置有一个你控制的城堡。 //现在,你需要决定,将你的军队从某个你控制的城堡位置 i 移动到一个空的位置 j ,满足: // //0 <= i, j <= n - 1 //军队经过的位置 只有 敌人的城堡。正式的,对于所有 min(i,j) < k < max(i,j) 的 k ,都满足 forts[k] == 0 。 //当军队移动时,所有途中经过的敌人城堡都会被 摧毁 。 // //请你返回 最多 可以摧毁的敌人城堡数目。如果 无法 移动你的军队,或者没有你控制的城堡,请返回 0 。 int[] forts = {0,0,1,-1}; System.out.println(captureForts(forts)); } public static int captureForts(int[] forts) { int n = forts.length; int ans = 0; int pre = -1;//起点 for (int i = 0; i < n; i++) { if (forts[i] == 1 || forts[i] == -1) {//如果是1或-1 if (pre >= 0 && forts[i] != forts[pre]) {//起点被设置并且前后不同时是1或-1 ans = Math.max(ans, i - pre - 1); } pre = i;//设定起点 } } return ans; } }
tadne/LeeCode
src/LeeCode/code2511.java
66,579
package com.pancm.design.singleton; /** * @author ZERO * @Data 2017-6-7 下午4:08:26 * @Description */ /** * 方法一 * 单例模式的实现:饿汉式,线程安全 但效率比较低 * * 方法一就是传说的中的饿汉模式 * 优点是:写起来比较简单,而且不存在多线程同步问题,避免了synchronized所造成的性能问题; * 缺点是:当类SingletonTest被加载的时候,会初始化static的instance,静态变量被创建并分配内存空间, * 从这以后,这个static的instance对象便一直占着这段内存(即便你还没有用到这个实例), * 当类被卸载时,静态变量被摧毁,并释放所占有的内存,因此在某些特定条件下会耗费内存。 * */ class SingletonTest1 { // 定义一个私有的构造方法 private SingletonTest1() { } // 将自身的实例对象设置为一个属性,并加上Static和final修饰符 private static final SingletonTest1 instance = new SingletonTest1(); // 静态方法返回该类的实例 public static SingletonTest1 getInstance() { return instance; } } /** * 方法二 * 单例模式的实现:饱汉式,非线程安全 * 方法二就是传说的中的饱汉模式 * 优点是:写起来比较简单,当类SingletonTest被加载的时候,静态变量static的instance未被创建并分配内存空间, * 当getInstance方法第一次被调用时,初始化instance变量,并分配内存,因此在某些特定条件下会节约了内存; * 缺点是:并发环境下很可能出现多个SingletonTest实例。 */ class SingletonTest2 { // 定义私有构造方法(防止通过 new SingletonTest()去实例化) private SingletonTest2() { } // 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字) private static SingletonTest2 instance; // 定义一个静态的方法(调用时再初始化SingletonTest,但是多线程访问时,可能造成重复初始化问题) public static SingletonTest2 getInstance() { if (instance == null) { instance = new SingletonTest2(); } return instance; } } /** *方法三 * 单例模式的实现:饱汉式,线程安全简单实现 * 方法三为方法二的简单优化 * 优点是:使用synchronized关键字避免多线程访问时,出现多个SingletonTest实例。 * 缺点是:同步方法频繁调用时,效率略低 */ class SingletonTest3 { // 定义私有构造方法(防止通过 new SingletonTest()去实例化) private SingletonTest3() { } // 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字) private static SingletonTest3 instance; // 定义一个静态的方法(调用时再初始化SingletonTest,使用synchronized 避免多线程访问时,可能造成重的复初始化问题) public static synchronized SingletonTest3 getInstance() { if (instance == null) { instance = new SingletonTest3(); } return instance; } } /** * 方法四 * 静态内部类 * 这种写法仍然使用JVM本身机制保证了线程安全问题;由于SingletonTest5是私有的, 除了getInstance()之外没有办法访问它, * 因此它是懒汉式的;同时读取实例的时候不会进行同步,没有性能缺陷;也不依赖JDK版本。 */ class SingletonTest4 { private SingletonTest4(){ } private static class SingletonTest5{ private static SingletonTest4 instance = new SingletonTest4(); } public static final SingletonTest4 getInstance(){ return SingletonTest5.instance; } } /** * 方法五 双重锁 * 单例模式最优方案 * 线程安全 并且效率高 * 方法四为单例模式的最佳实现。内存占用低,效率高,线程安全,多线程操作原子性。 */ class SingletonTest6 { // 定义一个私有构造方法 private SingletonTest6() { } //定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用) private static volatile SingletonTest6 instance; //定义一个共有的静态方法,返回该类型实例 public static SingletonTest6 getIstance() { // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率) if (instance == null) { //同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建) synchronized (SingletonTest6.class) { //未初始化,则初始instance变量 if (instance == null) { instance = new SingletonTest6(); } } } return instance; } } /** * 方法六,枚举单例模式 * 1.从Java1.5开始支持; * 2.无偿提供序列化机制; * 3.绝对防止多次实例化,即使在面对复杂的序列化或者反射攻击的时候; * 自由序列化,线程安全,保证单例 */ enum SingletonTest7{ INSTANCE; } public class SingletonTest { public static void main(String[] args) { } }
xuwujing/java-study
src/main/java/com/pancm/design/singleton/SingletonTest.java
66,580
package com.own.face.filter; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Slf4j @Component public class CrossFilter implements Filter { @Override public void init(FilterConfig arg0) throws ServletException { log.info("初始化拦截器....."); } @Override public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpRes = (HttpServletResponse) res; httpRes.setHeader("Access-Control-Allow-Origin", "*"); httpRes.setHeader("Access-Control-Allow-Methods", "DELETE, GET, POST, PUT"); httpRes.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept,X-Requested-With"); httpRes.setHeader("Access-Control-Max-Age", "43200"); chain.doFilter(req, res); } @Override public void destroy() { log.info("摧毁拦截器....."); } }
Blucezhang/micro-server-own
own-common/src/main/java/com/own/face/filter/CrossFilter.java
66,581
//给你一个长度为 n ,下标从 0 开始的整数数组 forts ,表示一些城堡。forts[i] 可以是 -1 ,0 或者 1 ,其中: // // // -1 表示第 i 个位置 没有 城堡。 // 0 表示第 i 个位置有一个 敌人 的城堡。 // 1 表示第 i 个位置有一个你控制的城堡。 // // // 现在,你需要决定,将你的军队从某个你控制的城堡位置 i 移动到一个空的位置 j ,满足: // // // 0 <= i, j <= n - 1 // 军队经过的位置 只有 敌人的城堡。正式的,对于所有 min(i,j) < k < max(i,j) 的 k ,都满足 forts[k] == 0 。 // // // 当军队移动时,所有途中经过的敌人城堡都会被 摧毁 。 // // 请你返回 最多 可以摧毁的敌人城堡数目。如果 无法 移动你的军队,或者没有你控制的城堡,请返回 0 。 // // // // 示例 1: // // 输入:forts = [1,0,0,-1,0,0,0,0,1] //输出:4 //解释: //- 将军队从位置 0 移动到位置 3 ,摧毁 2 个敌人城堡,位置分别在 1 和 2 。 //- 将军队从位置 8 移动到位置 3 ,摧毁 4 个敌人城堡。 //4 是最多可以摧毁的敌人城堡数目,所以我们返回 4 。 // // // 示例 2: // // 输入:forts = [0,0,1,-1] //输出:0 //解释:由于无法摧毁敌人的城堡,所以返回 0 。 // // // // // 提示: // // // 1 <= forts.length <= 1000 // -1 <= forts[i] <= 1 // // // Related Topics 数组 双指针 // 👍 65 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int captureForts(int[] forts) { int n = forts.length; int ans = 0, pre = -1; for (int i = 0; i < n; i++) { if (forts[i] == 1 || forts[i] == -1) { if (pre >= 0 && forts[i] != forts[pre]) { ans = Math.max(ans, i - pre - 1); } pre = i; } } return ans; } } //leetcode submit region end(Prohibit modification and deletion)
DEAiFISH/LeetCode
editor/cn/[2511]最多可以摧毁的敌人城堡数目.java
66,583
package com.zhouyou.recyclerview.refresh; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * <p>描述:fragment基类</p> * * @author zhouyou * @version v1.0 * @date 2015-8-17 下午8:55:40 */ @SuppressWarnings(value={"unchecked", "deprecation"}) public abstract class BaseFragment extends Fragment { public Context mContext; public Resources mResources; public LayoutInflater mInflater; @Override public void onAttach(Activity activity) { super.onAttach(activity); this.mContext = activity; this.mResources = mContext.getResources(); this.mInflater = LayoutInflater.from(mContext); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private View rootView;//缓存Fragment view @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) { rootView = inflater.inflate(getLayoutID(), container, false); } //缓存的rootView需要判断是否已经被加过parent, 如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。 ViewGroup parent = (ViewGroup) rootView.getParent(); if (parent != null) { parent.removeView(rootView); } return rootView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); bindEvent(); initData(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } /* 摧毁视图 */ @Override public void onDestroyView() { super.onDestroyView(); mContext = null; } /** * 查找View * * @param view 父view * @param id 控件的id * @param <VT> View类型 */ protected <VT extends View> VT findView(View view, @IdRes int id) { return (VT) view.findViewById(id); } protected <VT extends View> VT findView(@IdRes int id) { return (VT) rootView.findViewById(id); } /** * 布局的LayoutID * * @return */ protected abstract int getLayoutID(); /** * 初始化子View */ protected abstract void initView(View contentView); /** * 绑定事件 */ protected abstract void bindEvent(); /** * 初始化数据 */ protected abstract void initData(); }
zhou-you/EasyXRecyclerView
app/src/main/java/com/zhouyou/recyclerview/refresh/BaseFragment.java
66,584
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.config; import java.beans.PropertyEditor; import java.security.AccessControlContext; import org.springframework.beans.PropertyEditorRegistrar; import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.TypeConverter; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.HierarchicalBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.core.convert.ConversionService; import org.springframework.lang.Nullable; import org.springframework.util.StringValueResolver; /** * Configuration interface to be implemented by most bean factories. Provides * facilities to configure a bean factory, in addition to the bean factory * client methods in the {@link org.springframework.beans.factory.BeanFactory} * interface. * * <p>This bean factory interface is not meant to be used in normal application * code: Stick to {@link org.springframework.beans.factory.BeanFactory} or * {@link org.springframework.beans.factory.ListableBeanFactory} for typical * needs. This extended interface is just meant to allow for framework-internal * plug'n'play and for special access to bean factory configuration methods. * * @author Juergen Hoeller * @since 03.11.2003 * @see org.springframework.beans.factory.BeanFactory * @see org.springframework.beans.factory.ListableBeanFactory * @see ConfigurableListableBeanFactory */ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry { /** * Scope identifier for the standard singleton scope: {@value}. * <p>Custom scopes can be added via {@code registerScope}. * 作用域: 单例 * @see #registerScope */ String SCOPE_SINGLETON = "singleton"; /** * Scope identifier for the standard prototype scope: {@value}. * <p>Custom scopes can be added via {@code registerScope}. * 作用域: 原型模式 * @see #registerScope */ String SCOPE_PROTOTYPE = "prototype"; /** * Set the parent of this bean factory. * <p>Note that the parent cannot be changed: It should only be set outside * a constructor if it isn't available at the time of factory instantiation. * 设置父bean工厂 * @param parentBeanFactory the parent BeanFactory * @throws IllegalStateException if this factory is already associated with * a parent BeanFactory * @see #getParentBeanFactory() */ void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException; /** * Return this factory's class loader for loading bean classes * (only {@code null} if even the system ClassLoader isn't accessible). * 获取bean类加载器 * @see org.springframework.util.ClassUtils#forName(String, ClassLoader) */ @Nullable ClassLoader getBeanClassLoader(); /** * Set the class loader to use for loading bean classes. * Default is the thread context class loader. * <p>Note that this class loader will only apply to bean definitions * that do not carry a resolved bean class yet. This is the case as of * Spring 2.0 by default: Bean definitions only carry bean class names, * to be resolved once the factory processes the bean definition. * 设置bean类加载器 * @param beanClassLoader the class loader to use, * or {@code null} to suggest the default class loader */ void setBeanClassLoader(@Nullable ClassLoader beanClassLoader); /** * Return the temporary ClassLoader to use for type matching purposes, * if any. * 获取临时类加载器 * @since 2.5 */ @Nullable ClassLoader getTempClassLoader(); /** * Specify a temporary ClassLoader to use for type matching purposes. * Default is none, simply using the standard bean ClassLoader. * <p>A temporary ClassLoader is usually just specified if * <i>load-time weaving</i> is involved, to make sure that actual bean * classes are loaded as lazily as possible. The temporary loader is * then removed once the BeanFactory completes its bootstrap phase. * 设置临时类加载器 * @since 2.5 */ void setTempClassLoader(@Nullable ClassLoader tempClassLoader); /** * Return whether to cache bean metadata such as given bean definitions * (in merged fashion) and resolved bean classes. * 是否缓存bean元信息 */ boolean isCacheBeanMetadata(); /** * Set whether to cache bean metadata such as given bean definitions * (in merged fashion) and resolved bean classes. Default is on. * <p>Turn this flag off to enable hot-refreshing of bean definition objects * and in particular bean classes. If this flag is off, any creation of a bean * instance will re-query the bean class loader for newly resolved classes. * 设置是否需要缓存bean元信息 */ void setCacheBeanMetadata(boolean cacheBeanMetadata); /** * Return the resolution strategy for expressions in bean definition values. * 获取 EL 表达式解析器 * @since 3.0 */ @Nullable BeanExpressionResolver getBeanExpressionResolver(); /** * Specify the resolution strategy for expressions in bean definition values. * <p>There is no expression support active in a BeanFactory by default. * An ApplicationContext will typically set a standard expression strategy * here, supporting "#{...}" expressions in a Unified EL compatible style. * 设置 EL 表达式解析器 * @since 3.0 */ void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver); /** * Return the associated ConversionService, if any. * 获取转换服务 * @since 3.0 */ @Nullable ConversionService getConversionService(); /** * Specify a Spring 3.0 ConversionService to use for converting * property values, as an alternative to JavaBeans PropertyEditors. * 设置转换服务 * @since 3.0 */ void setConversionService(@Nullable ConversionService conversionService); /** * Add a PropertyEditorRegistrar to be applied to all bean creation processes. * <p>Such a registrar creates new PropertyEditor instances and registers them * on the given registry, fresh for each bean creation attempt. This avoids * the need for synchronization on custom editors; hence, it is generally * preferable to use this method instead of {@link #registerCustomEditor}. * 添加属性编辑器注册工具 * @param registrar the PropertyEditorRegistrar to register */ void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar); /** * Register the given custom property editor for all properties of the * given type. To be invoked during factory configuration. * <p>Note that this method will register a shared custom editor instance; * access to that instance will be synchronized for thread-safety. It is * generally preferable to use {@link #addPropertyEditorRegistrar} instead * of this method, to avoid for the need for synchronization on custom editors. * 注册自定义属性编辑器 * @param requiredType type of the property * @param propertyEditorClass the {@link PropertyEditor} class to register */ void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass); /** * Initialize the given PropertyEditorRegistry with the custom editors * that have been registered with this BeanFactory. * * 属性编辑器复制, 使用已在此BeanFactory中注册的自定义编辑器来初始化给定的PropertyEditorRegistry。 * @param registry the PropertyEditorRegistry to initialize */ void copyRegisteredEditorsTo(PropertyEditorRegistry registry); /** * Obtain a type converter as used by this BeanFactory. This may be a fresh * instance for each call, since TypeConverters are usually <i>not</i> thread-safe. * <p>If the default PropertyEditor mechanism is active, the returned * TypeConverter will be aware of all custom editors that have been registered. * 获取类型转换接口 * @since 2.5 */ TypeConverter getTypeConverter(); /** * Set a custom type converter that this BeanFactory should use for converting * bean property values, constructor argument values, etc. * <p>This will override the default PropertyEditor mechanism and hence make * any custom editors or custom editor registrars irrelevant. * 设置类型转换接口 * @since 2.5 * @see #addPropertyEditorRegistrar * @see #registerCustomEditor */ void setTypeConverter(TypeConverter typeConverter); /** * Add a String resolver for embedded values such as annotation attributes. * * 添加 字符串解析工具 * @param valueResolver the String resolver to apply to embedded values * @since 3.0 */ void addEmbeddedValueResolver(StringValueResolver valueResolver); /** * Determine whether an embedded value resolver has been registered with this * bean factory, to be applied through {@link #resolveEmbeddedValue(String)}. * * 是否存在值解析器 * @since 4.3 */ boolean hasEmbeddedValueResolver(); /** * Resolve the given embedded value, e.g. an annotation attribute. * 进行值解析 * @param value the value to resolve * @return the resolved value (may be the original value as-is) * @since 3.0 */ @Nullable String resolveEmbeddedValue(String value); /** * Add a new BeanPostProcessor that will get applied to beans created * by this factory. To be invoked during factory configuration. * <p>Note: Post-processors submitted here will be applied in the order of * registration; any ordering semantics expressed through implementing the * {@link org.springframework.core.Ordered} interface will be ignored. Note * that autodetected post-processors (e.g. as beans in an ApplicationContext) * will always be applied after programmatically registered ones. * * 添加 bean 后置处理器 * @param beanPostProcessor the post-processor to register */ void addBeanPostProcessor(BeanPostProcessor beanPostProcessor); /** * Return the current number of registered BeanPostProcessors, if any. * 获取 bean 后置处理器的数量 */ int getBeanPostProcessorCount(); /** * Register the given scope, backed by the given Scope implementation. * * scope 注册 * @param scopeName the scope identifier * @param scope the backing Scope implementation */ void registerScope(String scopeName, Scope scope); /** * Return the names of all currently registered scopes. * <p>This will only return the names of explicitly registered scopes. * Built-in scopes such as "singleton" and "prototype" won't be exposed. * 获取注册的 scope name * @return the array of scope names, or an empty array if none * @see #registerScope */ String[] getRegisteredScopeNames(); /** * Return the Scope implementation for the given scope name, if any. * <p>This will only return explicitly registered scopes. * Built-in scopes such as "singleton" and "prototype" won't be exposed. * 获取 scope 接口对象 * @param scopeName the name of the scope * @return the registered Scope implementation, or {@code null} if none * @see #registerScope */ @Nullable Scope getRegisteredScope(String scopeName); /** * Provides a security access control context relevant to this factory. * 安全上下文 * @return the applicable AccessControlContext (never {@code null}) * @since 3.0 */ AccessControlContext getAccessControlContext(); /** * Copy all relevant configuration from the given other factory. * <p>Should include all standard configuration settings as well as * BeanPostProcessors, Scopes, and factory-specific internal settings. * Should not include any metadata of actual bean definitions, * such as BeanDefinition objects and bean name aliases. * * bean 工厂的配置信息复制 * 配置拷贝 * @param otherFactory the other BeanFactory to copy from */ void copyConfigurationFrom(ConfigurableBeanFactory otherFactory); /** * Given a bean name, create an alias. We typically use this method to * support names that are illegal within XML ids (used for bean names). * <p>Typically invoked during factory configuration, but can also be * used for runtime registration of aliases. Therefore, a factory * implementation should synchronize alias access. * * 别名注册 * @param beanName the canonical name of the target bean * @param alias the alias to be registered for the bean * @throws BeanDefinitionStoreException if the alias is already in use */ void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException; /** * Resolve all alias target names and aliases registered in this * factory, applying the given StringValueResolver to them. * <p>The value resolver may for example resolve placeholders * in target bean names and even in alias names. * * 别名解析 * @param valueResolver the StringValueResolver to apply * @since 2.5 */ void resolveAliases(StringValueResolver valueResolver); /** * Return a merged BeanDefinition for the given bean name, * merging a child bean definition with its parent if necessary. * Considers bean definitions in ancestor factories as well. * 获取合并的bean定义. 自己+父类 * @param beanName the name of the bean to retrieve the merged definition for * @return a (potentially merged) BeanDefinition for the given bean * @throws NoSuchBeanDefinitionException if there is no bean definition with the given name * @since 2.5 */ BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException; /** * Determine whether the bean with the given name is a FactoryBean. * 是否是 工厂bean * @param name the name of the bean to check * @return whether the bean is a FactoryBean * ({@code false} means the bean exists but is not a FactoryBean) * @throws NoSuchBeanDefinitionException if there is no bean with the given name * @since 2.5 */ boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException; /** * Explicitly control the current in-creation status of the specified bean. * For container-internal use only. * 设置 bean 是否正在被创建 * @param beanName the name of the bean * @param inCreation whether the bean is currently in creation * @since 3.1 */ void setCurrentlyInCreation(String beanName, boolean inCreation); /** * Determine whether the specified bean is currently in creation. * * 判断 bean 是否正在被创建 * @param beanName the name of the bean * @return whether the bean is currently in creation * @since 2.5 */ boolean isCurrentlyInCreation(String beanName); /** * Register a dependent bean for the given bean, * to be destroyed before the given bean is destroyed. * * 注册依赖的bean * @param beanName the name of the bean * @param dependentBeanName the name of the dependent bean * @since 2.5 */ void registerDependentBean(String beanName, String dependentBeanName); /** * Return the names of all beans which depend on the specified bean, if any. * 获取依赖的bean * @param beanName the name of the bean * @return the array of dependent bean names, or an empty array if none * @since 2.5 */ String[] getDependentBeans(String beanName); /** * Return the names of all beans that the specified bean depends on, if any. * 获取依赖的bean * @param beanName the name of the bean * @return the array of names of beans which the bean depends on, * or an empty array if none * @since 2.5 */ String[] getDependenciesForBean(String beanName); /** * Destroy the given bean instance (usually a prototype instance * obtained from this factory) according to its bean definition. * <p>Any exception that arises during destruction should be caught * and logged instead of propagated to the caller of this method. * 摧毁 bean * @param beanName the name of the bean definition * @param beanInstance the bean instance to destroy */ void destroyBean(String beanName, Object beanInstance); /** * Destroy the specified scoped bean in the current target scope, if any. * <p>Any exception that arises during destruction should be caught * and logged instead of propagated to the caller of this method. * 摧毁bean,带有作用域的 * @param beanName the name of the scoped bean */ void destroyScopedBean(String beanName); /** * Destroy all singleton beans in this factory, including inner beans that have * been registered as disposable. To be called on shutdown of a factory. * <p>Any exception that arises during destruction should be caught * and logged instead of propagated to the caller of this method. * * 摧毁单例 bean */ void destroySingletons(); }
SourceHot/spring-framework-read
spring-beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java
66,585
package com.jess.mobilesafe.activity; import com.jess.mobilesafe.R; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class LostFindActivity extends BaseTouch { private SharedPreferences shp; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); // 拿到配置信息查看是否设置过向导 shp = getSharedPreferences("config", MODE_PRIVATE); checkConfiged(); } /** * 判断是否进入向导页 */ public void checkConfiged() { boolean configed = shp.getBoolean("configed", false); // 设置过就显示页面否则跳转到向导页 if (configed) { // 显示页面 setContentView(R.layout.activity_lostfind); //拿到显示电话的view TextView tv = (TextView) findViewById(R.id.tv_lostfind_phone); //拿到开启状态的view ImageView iv = (ImageView) findViewById(R.id.iv_isok); //初始化时检查配置信息 String phone = shp.getString("phone", null); //将配置信息中的安全号码设置到view if (!TextUtils.isEmpty(phone)) { tv.setText(phone); }else{ //如果没有设置则提示 tv.setText(""); } //读取配置文件中是否开启保护 boolean protect = shp.getBoolean("protect", false); if (protect) { iv.setBackgroundResource(R.drawable.ok); }else{ iv.setBackgroundResource(R.drawable.no); } } else { // 跳转到向导页 Intent intent = new Intent(this, Step1Activity.class); startActivity(intent); // 摧毁当前页 finish(); // 设置动画 nextAnimation(); } } /** * 重新跳转到向导页 * * @param v */ public void reEnter(View v) { // 跳转到向导页 Intent intent = new Intent(this, Step1Activity.class); startActivity(intent); // 摧毁当前页 finish(); // 设置动画 previousAnimation(); } public void nextAnimation() { // 设置进入和退出的动画 overridePendingTransition(R.anim.step_next_in, R.anim.step_next_out); } public void previousAnimation() { // 设置进入和退出的动画 overridePendingTransition(R.anim.step_previous_in, R.anim.step_previous_out); } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); // 返回时调用进出动画效果 previousAnimation(); } @Override public void showNextPage() { } @Override public void showPreviousPage() { // 跳转到主页 // Intent intent = new Intent(this, HomeActivity.class); // startActivity(intent); // 关闭页面 finish(); // step动画 previousAnimation(); } }
JessYanCoding/MobileSafe
app/src/main/java/com/jess/mobilesafe/activity/LostFindActivity.java
66,586
package com.yuyh.library.permission; import android.app.Activity; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.provider.Settings; import android.util.Log; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * Created by hupei on 2016/4/26. */ class AcpManager { private static final String TAG = "AcpManager"; private static final int REQUEST_CODE_PERMISSION = 0x38; private static final int REQUEST_CODE_SETTING = 0x39; private Context mContext; private Activity mActivity; private AcpService mService; private AcpOptions mOptions; private AcpListener mCallback; private final List<String> mDeniedPermissions = new LinkedList<>(); private final Set<String> mManifestPermissions = new HashSet<>(1); AcpManager(Context context) { mContext = context; mService = new AcpService(); getManifestPermissions(); } private synchronized void getManifestPermissions() { PackageInfo packageInfo = null; try { packageInfo = mContext.getPackageManager().getPackageInfo( mContext.getPackageName(), PackageManager.GET_PERMISSIONS); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (packageInfo != null) { String[] permissions = packageInfo.requestedPermissions; if (permissions != null) { for (String perm : permissions) { mManifestPermissions.add(perm); } } } } synchronized void request(AcpOptions options, AcpListener acpListener) { mCallback = acpListener; mOptions = options; checkSelfPermission(); } private synchronized void checkSelfPermission() { mDeniedPermissions.clear(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Log.i(TAG, "Build.VERSION.SDK_INT < Build.VERSION_CODES.M"); mCallback.onGranted(); onDestroy(); return; } String[] permissions = mOptions.getPermissions(); for (String permission : permissions) { //检查申请的权限是否在 AndroidManifest.xml 中 if (mManifestPermissions.contains(permission)) { int checkSelfPermission = mService.checkSelfPermission(mContext, permission); Log.i(TAG, "checkSelfPermission = " + checkSelfPermission); //如果是拒绝状态则装入拒绝集合中 if (checkSelfPermission == PackageManager.PERMISSION_DENIED) { mDeniedPermissions.add(permission); } } } //如果没有一个拒绝是响应同意回调 if (mDeniedPermissions.isEmpty()) { Log.i(TAG, "mDeniedPermissions.isEmpty()"); mCallback.onGranted(); onDestroy(); return; } startAcpActivity(); } private synchronized void startAcpActivity() { Intent intent = new Intent(mContext, AcpActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); } synchronized void requestPermissions(Activity activity) { mActivity = activity; boolean shouldShowRational = false; for (String permission : mDeniedPermissions) { shouldShowRational = shouldShowRational || mService.shouldShowRequestPermissionRationale(mActivity, permission); } Log.i(TAG, "shouldShowRational = " + shouldShowRational); String[] permissions = mDeniedPermissions.toArray(new String[mDeniedPermissions.size()]); if (shouldShowRational) showRationalDialog(permissions); else requestPermissions(permissions); } private synchronized void showRationalDialog(final String[] permissions) { new AlertDialog.Builder(mActivity) .setMessage(mOptions.getRationalMessage()) .setPositiveButton(mOptions.getRationalBtnText(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { requestPermissions(permissions); } }).show(); } private synchronized void requestPermissions(String[] permissions) { mService.requestPermissions(mActivity, permissions, REQUEST_CODE_PERMISSION); } synchronized void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_CODE_PERMISSION: LinkedList<String> grantedPermissions = new LinkedList<>(); LinkedList<String> deniedPermissions = new LinkedList<>(); for (int i = 0; i < permissions.length; i++) { String permission = permissions[i]; if (grantResults[i] == PackageManager.PERMISSION_GRANTED) grantedPermissions.add(permission); else deniedPermissions.add(permission); } if (!grantedPermissions.isEmpty() && deniedPermissions.isEmpty()) { mCallback.onGranted(); onDestroy(); } else if (!deniedPermissions.isEmpty()) showDeniedDialog(deniedPermissions); break; } } private synchronized void showDeniedDialog(final List<String> permissions) { new AlertDialog.Builder(mActivity) .setMessage(mOptions.getDeniedMessage()) .setCancelable(false) .setNegativeButton(mOptions.getDeniedCloseBtn(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { mCallback.onDenied(permissions); onDestroy(); } }) .setPositiveButton(mOptions.getDeniedSettingBtn(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startSetting(); } }).show(); } /** * 摧毁本库的 AcpActivity */ private void onDestroy() { if (mActivity != null) mActivity.finish(); } /** * 跳转到设置界面 */ private void startSetting() { if (MiuiOs.isMIUI()) { Intent intent = MiuiOs.getSettingIntent(mActivity); if (MiuiOs.isIntentAvailable(mActivity, intent)) { mActivity.startActivityForResult(intent, REQUEST_CODE_SETTING); } } else { try { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) .setData(Uri.parse("package:" + mActivity.getPackageName())); mActivity.startActivityForResult(intent, REQUEST_CODE_SETTING); } catch (ActivityNotFoundException e) { e.printStackTrace(); try { Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS); mActivity.startActivityForResult(intent, REQUEST_CODE_SETTING); } catch (Exception e1) { e1.printStackTrace(); } } } } synchronized void onActivityResult(int requestCode, int resultCode, Intent data) { if (mCallback == null || mOptions == null || requestCode != REQUEST_CODE_SETTING) { onDestroy(); return; } checkSelfPermission(); } }
smuyyh/SprintNBA
CommonLibrary/src/main/java/com/yuyh/library/permission/AcpManager.java
66,588
package com.hanyi.thread.common.component; import com.hanyi.thread.domain.ScheduledTask; import lombok.RequiredArgsConstructor; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.config.CronTask; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * cron任务注册器 * * @author [email protected] * @since 2021-08-03 10:29 */ @Component @RequiredArgsConstructor public class CronTaskRegistrar { /** * 计划任务 */ private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16); /** * 任务调度器 */ private final TaskScheduler taskScheduler; /** * 添加cron任务 * * @param task 任务 * @param cronExpression cron表达式 */ public void addCronTask(Runnable task, String cronExpression) { this.addCronTask(new CronTask(task, cronExpression)); } /** * 添加cron任务 * * @param cronTask cron任务 */ public void addCronTask(CronTask cronTask) { if (cronTask != null) { Runnable task = cronTask.getRunnable(); this.removeCronTask(task); this.scheduledTasks.computeIfAbsent(task, k -> this.scheduledTasks.put(k, this.scheduleCronTask(cronTask))); } } /** * 删除cron任务 * * @param task 任务 */ public void removeCronTask(Runnable task) { ScheduledTask scheduledTask = this.scheduledTasks.remove(task); if (scheduledTask != null) { scheduledTask.cancel(); } } /** * 安排cron任务 * * @param cronTask cron任务 * @return {@link ScheduledTask} */ public ScheduledTask scheduleCronTask(CronTask cronTask) { ScheduledTask scheduledTask = new ScheduledTask(); scheduledTask.setFuture(this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger())); return scheduledTask; } /** * 摧毁 */ @PreDestroy public void destroy() { this.scheduledTasks.values().forEach(ScheduledTask::cancel); this.scheduledTasks.clear(); } }
Dearker/middleground
hanyi-dynamic-threadpool/src/main/java/com/hanyi/thread/common/component/CronTaskRegistrar.java
66,589
package com.potato.study.leetcodecn.p02511.t001; /** * 2511. 最多可以摧毁的敌人城堡数目 * * 给你一个长度为 n ,下标从 0 开始的整数数组 forts ,表示一些城堡。forts[i] 可以是 -1 ,0 或者 1 ,其中: -1 表示第 i 个位置 没有 城堡。 0 表示第 i 个位置有一个 敌人 的城堡。 1 表示第 i 个位置有一个你控制的城堡。 现在,你需要决定,将你的军队从某个你控制的城堡位置 i 移动到一个空的位置 j ,满足: 0 <= i, j <= n - 1 军队经过的位置 只有 敌人的城堡。正式的,对于所有 min(i,j) < k < max(i,j) 的 k ,都满足 forts[k] == 0 。 当军队移动时,所有途中经过的敌人城堡都会被 摧毁 。 请你返回 最多 可以摧毁的敌人城堡数目。如果 无法 移动你的军队,或者没有你控制的城堡,请返回 0 。   示例 1: 输入:forts = [1,0,0,-1,0,0,0,0,1] 输出:4 解释: - 将军队从位置 0 移动到位置 3 ,摧毁 2 个敌人城堡,位置分别在 1 和 2 。 - 将军队从位置 8 移动到位置 3 ,摧毁 4 个敌人城堡。 4 是最多可以摧毁的敌人城堡数目,所以我们返回 4 。 示例 2: 输入:forts = [0,0,1,-1] 输出:0 解释:由于无法摧毁敌人的城堡,所以返回 0 。   提示: 1 <= forts.length <= 1000 -1 <= forts[i] <= 1 来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/maximum-enemy-forts-that-can-be-captured 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * */ public class Solution { public int captureForts(int[] forts) { // 记录上次出现 -1 或者1的index int max = 0; int index = -1; // 遍历 forts 遇到-1 1 修改位置 记录最大值 for (int i = 0; i < forts.length; i++) { if (forts[i] == 0) { continue; } int pre = index; index = i; if (pre == -1) { continue; } if (forts[pre] == forts[i]) { continue; } int dis = i - pre - 1; max = Math.max(max, dis); } return max; } }
potatobeancox/leetcode-java
src/main/java/com/potato/study/leetcodecn/p02511/t001/Solution.java
66,590
package com.scene; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import com.common.GameContext; import com.common.ServiceCollection; import com.constant.BattleConstant; import com.constant.RewardTypeConstant; import com.constant.SceneConstant; import com.domain.battle.DropItemInfo; import com.domain.battle.WigSkillInfo; import com.domain.collect.Collect; import com.domain.monster.RefreshMonsterInfo; import com.domain.puppet.MonsterPuppet; import com.domain.tianti.BaseDropItem; import com.service.ITiantiService; import com.util.LogUtil; /** * 场景服务线程 * @author ken * @date 2017-1-9 */ public class SceneThreadHandler implements Runnable { /** 线程下标*/ private int index; public SceneThreadHandler() { } public SceneThreadHandler(int index) { this.index = index; } @Override public void run() { ServiceCollection serviceCollection = GameContext.getInstance().getServiceCollection(); ITiantiService tiantiService = serviceCollection.getTiantiService(); while (true) { try { long currentTime = System.currentTimeMillis(); List<SceneModel> sceneList = SceneServer.getInstance().getSceneModelList(index); if(sceneList != null && !sceneList.isEmpty()){ for(SceneModel scene : sceneList){ if(scene.getSceneState() == SceneConstant.SCENE_STATE_COMMON){ //刷怪 Map<Integer, RefreshMonsterInfo> map = scene.getRefMonsterMap(); for(Map.Entry<Integer, RefreshMonsterInfo> entry : map.entrySet()){ RefreshMonsterInfo model = entry.getValue(); if(model.getRefreshDate() > 0 && currentTime >= model.getRefreshDate()){ model.setRefreshDate(0); model.setCurNum(0); serviceCollection.getMonsterService().refreshMonsters(scene, entry.getKey(), model.getCurLayerId(), true); } } while (!scene.getDeadList().isEmpty()) { MonsterPuppet m = scene.getDeadList().peek(); if (m != null) { if (currentTime - m.getDeadTime() >= m.getRefreshTime()) { serviceCollection.getMonsterService().resetMonsterPuppet(scene, m); scene.getDeadList().poll(); } else { break; } } else { break; } } // 刷竞技场掉落 if(scene.getMapType() == SceneConstant.TIANTI_SCENE){ if(scene.getBaseDropItems() != null){ // 计算场景已存在时间 int haveTime = (int)(scene.getLifeTime() - (scene.getEndTime() - currentTime))/1000; // 首次掉落 if(haveTime >= 30){ int spaceTime = (int)((currentTime - scene.getDropItemTime())/1000); if(scene.getDropItemTime() < 1 || spaceTime > 30){ BaseDropItem baseDropItem = scene.getBaseDropItems().get(scene.getIndex()); // 产生掉落列表 tiantiService.refreshDropItem(baseDropItem, scene); scene.setDropItemTime(currentTime); scene.setIndex(scene.getIndex() + 1); } } // 添加固定buff int buffId = 0; if(haveTime >= SceneConstant.ADD_PK_BUFF_SCE_1 && haveTime < SceneConstant.ADD_PK_BUFF_SCE_2){ buffId = SceneConstant.PK_BUFF_1; }else if(haveTime >= SceneConstant.ADD_PK_BUFF_SCE_2 && haveTime < SceneConstant.ADD_PK_BUFF_SCE_3){ buffId = SceneConstant.PK_BUFF_2; }else if(haveTime >= SceneConstant.ADD_PK_BUFF_SCE_3){ buffId = SceneConstant.PK_BUFF_3; } if(buffId > 0 && !scene.getPkBuff().contains(buffId)){ tiantiService.addPKbuff(scene, buffId); } } } //掉落过期重刷检测 for(Map.Entry<Integer, Map<Integer,DropItemInfo>> entry : scene.getDropItemMap().entrySet()){ scene.getRemoveDrops().clear(); Iterator<Map.Entry<Integer, DropItemInfo>> iterator = entry.getValue().entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<Integer, DropItemInfo> infoMap = iterator.next(); DropItemInfo info = infoMap.getValue(); if(info.getGoodsType() != RewardTypeConstant.BOX){ long calTime = currentTime - info.getDropTime(); if(info.getState() == BattleConstant.DROP_NORMAL && calTime >= 20000){ info.setBelongPlayerIds(null); if(calTime >= 60000){ info.setState(BattleConstant.DROP_TIMEOUT); scene.getRemoveDrops().add(infoMap.getKey()); iterator.remove(); if(info.getPlayerEquipmentId() > 0){ serviceCollection.getEquipmentService().deleteDropEquipment(info.getPlayerEquipmentId()); } } } } } if(!scene.getRemoveDrops().isEmpty()){ serviceCollection.getBattleService().removeDropItems(scene.getRemoveDrops(), serviceCollection.getSceneService().getNearbyPlayerIdsByGridId(scene, entry.getKey())); } } for(Map.Entry<Integer, Map<Integer, Collect>> entry : scene.getCollectMap().entrySet()){ // 高级采集信息 scene.getCollectList().clear(); for(Map.Entry<Integer, Collect> entry1 : entry.getValue().entrySet()){ Collect collect = entry1.getValue(); if(collect.getRefreshDate() > 0 && currentTime >= collect.getRefreshDate()){ collect.setRefreshDate(0); collect.setCollectNum(0); collect.getPlayerIds().clear(); collect.setState(BattleConstant.COLLECT_NORMAL); scene.getCollectList().add(collect); } } //同步场景采集信息 if (!scene.getCollectList().isEmpty()){ serviceCollection.getCollectService().offerAddCollect(scene.getCollectList(), serviceCollection.getSceneService().getNearbyPlayerIdsByGridId(scene, entry.getKey())); } } } //地效技能 Map<Integer, BlockingQueue<WigSkillInfo>> wigMap = scene.getWigSkillMap(); for(Map.Entry<Integer, BlockingQueue<WigSkillInfo>> entry : wigMap.entrySet()){ BlockingQueue<WigSkillInfo> wigInfos = entry.getValue(); if (wigInfos != null && !wigInfos.isEmpty()) { while (!wigInfos.isEmpty()) { WigSkillInfo info = wigInfos.peek(); if (info != null) { if (currentTime - info.getEndTime() >= -100) { info.setDeleteFlag(true); wigInfos.poll(); } else { break; } } else { break; } } } } //副本到时间 if(scene.getMapType() == SceneConstant.INSTANCE_SCENE){ if(scene.getSceneState() == SceneConstant.SCENE_STATE_COMMON){ if(scene.getEndTime() > 0 && currentTime >= scene.getEndTime()){ //结束 serviceCollection.getInstanceService().end(scene, 2); } }else if(scene.getSceneState() == SceneConstant.SCENE_STATE_END){ if(scene.getWaitingTime() > 0 && currentTime - scene.getEndTime() >= scene.getWaitingTime()){ //摧毁 serviceCollection.getSceneService().destroy(scene); } } }else if(scene.getMapType() == SceneConstant.TIANTI_SCENE){ if(scene.getSceneState() == SceneConstant.SCENE_STATE_COMMON){ if(scene.getEndTime() > 0 && currentTime >= scene.getEndTime()){ //结束 serviceCollection.getTiantiService().end(scene, 0, 0); } }else if(scene.getSceneState() == SceneConstant.SCENE_STATE_END){ if(scene.getWaitingTime() > 0 && currentTime - scene.getEndTime() >= scene.getWaitingTime()){ //摧毁 serviceCollection.getSceneService().destroy(scene); } } } } } // 等待500毫秒 TimeUnit.MILLISECONDS.sleep(500); } catch (Exception e) { LogUtil.error("SceneRefreshMonsHandler: ",e); } } } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
corefan/xunhai
server/XHGameServer/src/com/scene/SceneThreadHandler.java
66,591
package vip.hyzt.questions; /** * <h1>2511. 最多可以摧毁的敌人城堡数目</h1> * <p>给你一个长度为 n ,下标从 <strong>0</strong> 开始的整数数组 forts ,表示一些城堡。forts[i] 可以是 -1 ,0 或者 1 ,其中:</p> * <ul> * <li>-1 表示第 i 个位置 <strong>没有</strong> 城堡。</li> * <li>0 表示第 i 个位置有一个 <strong>敌人</strong> 的城堡。</li> * <li>1 表示第 i 个位置有一个你控制的城堡。</li> * * * </ul> * <p>现在,你需要决定,将你的军队从某个你控制的城堡位置 i 移动到一个空的位置 j ,满足:</p> * <ul> * <li>0 <= i, j <= n - 1</li> * <li>军队经过的位置 <strong>只有</strong> 敌人的城堡。正式的,对于所有 min(i,j) < k < max(i,j) 的 k ,都满足 forts[k] == 0 。</li> * </ul> * <p>当军队移动时,所有途中经过的敌人城堡都会被 <strong>摧毁</strong> 。</p> * <p>请你返回 <strong>最多</strong> 可以摧毁的敌人城堡数目。如果 <strong>无法</strong> 移动你的军队,或者没有你控制的城堡,请返回 0 。</p> * <p></p> * <h2>示例 1:</h2> * <pre> * 输入:forts = [1,0,0,-1,0,0,0,0,1] * 输出:4 * 解释: * - 将军队从位置 0 移动到位置 3 ,摧毁 2 个敌人城堡,位置分别在 1 和 2 。 * - 将军队从位置 8 移动到位置 3 ,摧毁 4 个敌人城堡。 * 4 是最多可以摧毁的敌人城堡数目,所以我们返回 4 。 * </pre> * <h2>示例 2:</h2> * <pre> * 输入:forts = [0,0,1,-1] * 输出:0 * 解释:由于无法摧毁敌人的城堡,所以返回 0 。 * </pre> * <p></p> * <h2>提示:</h2> * <ul> * <li>1 <= forts.length <= 1000</li> * <li>-1 <= forts[i] <= 1</li> * </ul> * @author 力扣(LeetCode) * @author hy * @see <a href="https://leetcode.cn/problems/maximum-enemy-forts-that-can-be-captured/">https://leetcode.cn/problems/maximum-enemy-forts-that-can-be-captured/</a> */ public class Topic2511CaptureForts { public int captureForts(int[] forts) { int max = 0; for (int i = 0; i < forts.length; i++) { if (forts[i] != 0) { for (int j = i + 1; j < forts.length; j++) { if (forts[j] != 0) { max = Math.max(max, forts[i] == forts[j] ? 0 : j - i - 1); i = j; } } } } return max; } }
FromSouthToNorth/algorithm
all-the-questions/src/main/java/vip/hyzt/questions/Topic2511CaptureForts.java
66,592
package work.huangdu.question_bank.easy; /** * 2511. 最多可以摧毁的敌人城堡数目 * 给你一个长度为 n ,下标从 0 开始的整数数组 forts ,表示一些城堡。forts[i] 可以是 -1 ,0 或者 1 ,其中: * -1 表示第 i 个位置 没有 城堡。 * 0 表示第 i 个位置有一个 敌人 的城堡。 * 1 表示第 i 个位置有一个你控制的城堡。 * 现在,你需要决定,将你的军队从某个你控制的城堡位置 i 移动到一个空的位置 j ,满足: * 0 <= i, j <= n - 1 * 军队经过的位置 只有 敌人的城堡。正式的,对于所有 min(i,j) < k < max(i,j) 的 k ,都满足 forts[k] == 0 。 * 当军队移动时,所有途中经过的敌人城堡都会被 摧毁 。 * 请你返回 最多 可以摧毁的敌人城堡数目。如果 无法 移动你的军队,或者没有你控制的城堡,请返回 0 。 * 示例 1: * 输入:forts = [1,0,0,-1,0,0,0,0,1] * 输出:4 * 解释: * - 将军队从位置 0 移动到位置 3 ,摧毁 2 个敌人城堡,位置分别在 1 和 2 。 * - 将军队从位置 8 移动到位置 3 ,摧毁 4 个敌人城堡。 * 4 是最多可以摧毁的敌人城堡数目,所以我们返回 4 。 * 示例 2: * 输入:forts = [0,0,1,-1] * 输出:0 * 解释:由于无法摧毁敌人的城堡,所以返回 0 。 * 提示: * 1 <= forts.length <= 1000 * -1 <= forts[i] <= 1 * * @author [email protected] * @version 2023/9/2 */ public class CaptureForts { public int captureForts(int[] forts) { int n = forts.length, ans = 0, pre = -1; for (int i = 0; i < n; i++) { int fort = forts[i]; if (fort != 0) { if (pre != -1 && forts[pre] != fort) { ans = Math.max(ans, i - pre - 1); } pre = i; } } return ans; } }
huangdu94/algorithms
src/main/java/work/huangdu/question_bank/easy/CaptureForts.java
66,593
package org.pstale.service.aging; import java.util.Random; public class Aging { // 锻造石 String[][] SheltomName = { { "星遗石", "lucidy" }, { "流云石", "sereneo" }, { "海精石", "fadeo" }, { "天仪石", "sparky" }, { "冰晶石", "raident" }, { "玄风石", "transparo" }, { "水晶石", "murky" }, { "虎翼石", "devine" }, { "龙鳞石", "celesto" }, { "钻晶石", "mirage" }, { "龙睛石", "inferna" }, { "圣晶石", "enigma" }, { "恶魔石", "bellum" }, { "荣誉石", "oredo" }, { "蓝晶石", "sapphire" }}; // 锻造升级配方 int[][] AgingLevelSheltom = { { 3, 3, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0 }, { 3, 3, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0 }, { 3, 3, 4, 4, 5, 5, 6, 0, 0, 0, 0, 0 }, { 3, 3, 4, 4, 5, 5, 6, 6, 0, 0, 0, 0 }, { 3, 3, 4, 4, 5, 5, 6, 6, 7, 0, 0, 0 }, { 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 0, 0 }, { 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 0 }, { 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8 }, { 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 0 }, { 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9 }, { 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 0 }, { 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10 }, { 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 0 }, { 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11 }, { 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 0 }, { 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12 }, { 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 0 }, { 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }, { 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 0 }, { 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14 } }; /********************** 锻造升级所需的条件 **********************/ // 升级所需攻击次数 int[] AgingLevelAttack = { 100, 130, 169, 219, 284, 369, 479, 622, 808, 1049, 1362, 1769, 2297, 2983, 3874, 5031, 6534, 8486, 11021, 14313 }; // 升级所需必杀次数 int[] AgingLevelCritical = { 12, 16, 21, 27, 35, 45, 58, 75, 97, 126, 164, 213, 277, 360, 468, 608, 790, 1026, 1332, 1730 }; // 升级所需格挡次数 int[] AgingLevelBlock = { 15, 19, 25, 32, 42, 55, 71, 92, 119, 155, 201, 261, 339, 440, 571, 742, 964, 1252, 1626, 2112 }; // 升级所需命中次数 int[] AgingLevelHit = { 45, 58, 75, 97, 126, 164, 213, 277, 360, 468, 608, 790, 1026, 1332, 1730, 2247, 2918, 3790, 4922, 6392 }; /********************** 锻造几率 **********************/ // 锻造失败率 % private int[] AgingOkPercent = { 0, 0, 0, 0, 0, 5, 10, 15, 20, 30, 35, 40, 45, 50, 55, 65, 75, 85, 95, 95 }; // private int[] AgingOkPercent = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 20, 30, 40, 50, 60, 70, 80 }; // 触发双倍锻造几率 % private int[] PlusAgingPercent = { 30, 25, 20, 10, 10, 10, 10, 5, 5, 5, 5, 4, 4, 3, 3, 2, 2, 2, 0 ,0}; //Aging twice private int[][] AgingFailPercent = { // FIXED, DOWN_LVL, DESTRY {100, 0, 0},// +1 {100, 0, 0},// +2 {100, 0, 0},// +3 {100, 0, 0},// +4 {100, 0, 0},// +5 {10, 90, 0},// +6 {20, 80, 0},// +7 {15, 70, 15},// +8 {20, 60, 20},// +9 {20, 50, 30},// +10 {20, 40, 40},// +11 {20, 30, 50},// +12 {10, 30, 60},// +13 {10, 20, 70},// +14 {10, 10, 80},// +15 {10, 10, 80},// +16 {10, 10, 80},// +17 {10, 10, 80},// +18 {10, 10, 80},// +19 {10, 10, 80}};// +20 public enum RESULT { DESTROY , DOWN_2LVL, DOWN_LVL, FIXED, SUCCESS, DOUBLE_LVL } Random rand = new Random(); public RESULT aging(int agingNum, int add) { int destroy = rand.nextInt(100); int plus = rand.nextInt(100); if (destroy >= getAgingPercent(agingNum, add)) { // 锻造失败 if (destroy < AgingFailPercent[agingNum][0]) { return RESULT.FIXED;// 不变 } else if (destroy < AgingFailPercent[agingNum][0] + AgingFailPercent[agingNum][1]) { return RESULT.DOWN_LVL;// 不变 } else { if (add > 0) { if (rand.nextInt(100) < 80) { return RESULT.DOWN_LVL; } else { return RESULT.DOWN_2LVL; } } else { return RESULT.DESTROY;// 摧毁 } } } else { // 锻造成功 if (plus <= PlusAgingPercent[agingNum]*2) { // 额外+1 return RESULT.DOUBLE_LVL; } else { // +1 return RESULT.SUCCESS; } } } /** * 查询锻造成功率 * @param agingNum 0~19 锻造级别 * @param add 附加几率 * @return */ public int getAgingPercent(int agingNum, int add) { int per = 100 - AgingOkPercent[agingNum]; per += per*add/100; if (per > 100) per = 100; if (per < 0) per = 0; return per; } public int getAgingMoney(int price, int agingLvl) { int money = price * (1 + agingLvl) / 2; return money; } public void simulator() { int n = 0; int s = 0; int money = 0; int add = 0;// 额外锻造几率 int price = 350000; int agingLvl = 0; System.out.println("锻造\t| 等级\t| 成功率\t| 结果"); System.out.println("--------|-------|-------|-------"); while(agingLvl<20) { s++; System.out.printf("第%d次\t| +%d\t| %d%%\t| ",s, (agingLvl+1), getAgingPercent(agingLvl, add)); switch (aging(agingLvl, add)) { case DESTROY: { System.out.println("摧毁"); agingLvl = 0; n++; break; } case DOWN_2LVL: { System.out.println("-2"); agingLvl--; agingLvl--; break; } case DOWN_LVL: { System.out.println("-1"); agingLvl--; break; } case FIXED: { System.out.println("+0"); break; } case SUCCESS: { System.out.println("+1"); agingLvl++; break; } case DOUBLE_LVL: { System.out.println("+2"); agingLvl++; agingLvl++; break; } } } // TODO 计算锻造费用 money += price; System.out.println("使用+" + add + "%几率锻造石,共消耗" + (n+1) +"件装备, 锻造" + s + "次。" + " 价格:" + money); } /** * @param args */ public static void main(String[] args) { Aging aging = new Aging(); aging.simulator(); } }
smileclound/JPsTale
JPsTale-Core/src/main/java/org/pstale/service/aging/Aging.java
66,594
package com.notification; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.constant.Cparams; import com.helper.HttpsUtil; import com.viewer.main.MainRun; public class WeChatUtil { Logger logger = LoggerFactory.getLogger(WeChatUtil.class); // https://work.weixin.qq.com/api/doc API文档 String corpid = ""; String corpsecret = ""; String agentid = ""; Timer access_token_timer; String TAG = "[微信企业号]";// 日志标记 int access_token_wrongful = 40014;// 不合法 int access_token_overdue = 42001;// 过期 int access_token_lack = 41001;// 缺少 int errcode_ok = 0;// 成功 // 缓存数据 boolean init = false; String access_token = ""; JSONArray departmentinfo; JSONArray peopleinfo; /** * 获取历史部门信息 * * @return */ public JSONArray getDepartmentInfo() { if (departmentinfo == null) { refreshDepartmentInfo(); } return departmentinfo; } /** * 获取历史人员信息 * * @return */ public JSONArray getPeopleInfo() { if (peopleinfo == null) { refreshPeopleInfo(); } return peopleinfo; } /** * 定时刷新access_token,2小时一次,失败重试三次 */ public boolean timingAccess_token() { corpid = MainRun.sysConfigBean.getWechat().get(Cparams.corpid); corpsecret = MainRun.sysConfigBean.getWechat().get(Cparams.corpsecret); agentid = MainRun.sysConfigBean.getWechat().get(Cparams.agentid); if (corpid.equals("") || corpsecret.equals("") || agentid.equals("")) { logger.info("timingAccess_token does not set, corpid=" + corpid + ",corpsecret=" + corpsecret + ",agentid=" + agentid); } else { if (!init) { logger.info("timingAccess_token start work!..."); refreshAccess_token(); // access_token_timer = new Timer(); access_token_timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub refreshAccess_token(); try2getAccess_token(10 * 1000, 3); } }, 1000 * 60 * 60 * 2, 1000 * 60 * 60 * 2); init = true; } else { logger.info("timingAccess_token has been run"); } } return !access_token.equals(""); } /** * 摧毁 */ public void destory() { if (access_token_timer != null) { access_token_timer.cancel(); access_token_timer = null; } init = false; } /** * 获取access_token失败后尝试 * * @param time 每隔多少时间,秒 * @param max 尝试多少次 * @return */ private boolean try2getAccess_token(int time, int max) { int failcount = 0; while (access_token.equals("") && failcount < max) {// 失败尝试 try { Thread.sleep(1000 * time); } catch (InterruptedException e) { // TODO Auto-generated catch block } failcount++; refreshAccess_token(); } return !access_token.equals(""); } /** * 获取access_token,2小时过期,不可频繁调用! * * @return */ public String refreshAccess_token() { // https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRECT String access_token = ""; Map<String, Object> paramsMap = new HashMap<>(); paramsMap.put("corpid", corpid); paramsMap.put("corpsecret", corpsecret); JSONObject jsonObject = (JSONObject) HttpsUtil .sendGetData("https://qyapi.weixin.qq.com", "/cgi-bin/gettoken", paramsMap, null) .get(HttpsUtil.JSONOBJECT);// 2小时过期,不能频繁调用 try { if (jsonObject.has("errcode") && jsonObject.getInt("errcode") == errcode_ok) {// 请求成功 // { // "errcode":0, // "errmsg":"", // "access_token": "accesstoken000001", // "expires_in": 7200 // } access_token = jsonObject.getString("access_token"); } else { access_token = ""; logger.error(TAG + "get access_token failed"); } } catch (JSONException e) { // TODO Auto-generated catch block logger.error("EXCEPTION", e); } logger.info("access_token info :" + access_token); this.access_token = access_token; return access_token; } /** * 获取部门信息 * * @return "department": [ { "id": 2, "name": "广州研发中心", "parentid": 1, "order": * 10 }, { "id": 3 "name": "邮箱产品部", "parentid": 2, "order": 40 } ] */ public JSONArray refreshDepartmentInfo() { // https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN&id=ID JSONArray jsonArray = null; Map<String, Object> paramsMap = new HashMap<>(); paramsMap.put("access_token", access_token); // paramsMap.put("id", 1); JSONObject jsonObject = (JSONObject) HttpsUtil .sendGetData("https://qyapi.weixin.qq.com", "/cgi-bin/department/list", paramsMap, null) .get(HttpsUtil.JSONOBJECT); try { if (jsonObject.has("errcode")) {// 请求成功 if (jsonObject.getInt("errcode") == errcode_ok) { jsonArray = jsonObject.getJSONArray("department"); } else if (jsonObject.getInt("errcode") == access_token_lack || jsonObject.getInt("errcode") == access_token_overdue || jsonObject.getInt("errcode") == access_token_wrongful) { refreshAccess_token(); } } else { logger.error(TAG + "get department info failed!"); } } catch (JSONException e) { // TODO Auto-generated catch block logger.error("EXCEPTION", e); } logger.info("department info:" + (jsonArray == null ? "null" : jsonArray.toString())); departmentinfo = jsonArray; return jsonArray; } /** * 获取成员信息 * * @return "userlist": [ { "userid": "zhangsan", "name": "李四", "department": [1, * 2] } ] */ public JSONArray refreshPeopleInfo() { JSONArray jsonArray = null; Map<String, Object> paramsMap = new HashMap<>(); paramsMap.put("access_token", access_token); paramsMap.put("department_id", 1); paramsMap.put("fetch_child", 1); JSONObject jsonObject = (JSONObject) HttpsUtil .sendGetData("https://qyapi.weixin.qq.com", "/cgi-bin/user/simplelist", paramsMap, null) .get(HttpsUtil.JSONOBJECT); try { if (jsonObject.has("errcode")) {// 请求成功 if (jsonObject.getInt("errcode") == errcode_ok) { jsonArray = jsonObject.getJSONArray("userlist"); } else if (jsonObject.getInt("errcode") == access_token_lack || jsonObject.getInt("errcode") == access_token_overdue || jsonObject.getInt("errcode") == access_token_wrongful) { refreshAccess_token(); } } else { logger.error(TAG + "get people info failed"); } } catch (JSONException e) { // TODO Auto-generated catch block logger.error("EXCEPTION", e); } logger.info("people info :" + (jsonArray == null ? "null" : jsonArray.toString())); peopleinfo = jsonArray; return jsonArray; } /** * 发送消息 * * @param userid 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向该企业应用的全部成员发送 * @param toparty 部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数 * @param totag 标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数 * @param text * @return { "errcode" : 0, "errmsg" : "ok", "invaliduser" : "userid1|userid2", * // 不区分大小写,返回的列表都统一转为小写 "invalidparty" : "partyid1|partyid2", * "invalidtag":"tagid1|tagid2" } */ public JSONObject sendText(String touser, String toparty, String totag, String text) { // 参数 是否必须 说明 // touser 否 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向该企业应用的全部成员发送 // toparty 否 部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数 // totag 否 标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数 // msgtype 是 消息类型,此时固定为:text // agentid 是 企业应用的id,整型。可在应用的设置页面查看 // content 是 消息内容,最长不超过2048个字节 // safe 否 表示是否是保密消息,0表示否,1表示是,默认0 JSONObject jsonObject = null; try { JSONObject params = new JSONObject(); JSONObject content = new JSONObject(); params.put("text", content.put("content", text)); params.put("msgtype", "text"); params.put("agentid", agentid); params.put("safe", 0); if (touser != null) { params.put("touser", touser); } if (toparty != null) { params.put("toparty", toparty); } if (totag != null) { params.put("totag", totag); } jsonObject = (JSONObject) HttpsUtil.sendPostData("https://qyapi.weixin.qq.com", "/cgi-bin/message/send?access_token=" + access_token, params.toString(), null) .get(HttpsUtil.JSONOBJECT); if (jsonObject.has("errcode")) {// 请求成功 if (jsonObject.getInt("errcode") == errcode_ok) { if (jsonObject.has("invaliduser")) { String invaliduser = jsonObject.getString("invaliduser"); logger.info("send message invaliduser fail:" + invaliduser); } if (jsonObject.has("invalidparty")) { String invalidparty = jsonObject.getString("invalidparty"); logger.info("send message invalidparty fail:" + invalidparty); } if (jsonObject.has("invalidtag")) { String invalidtag = jsonObject.getString("invalidtag"); logger.info("send message invalidtag fail:" + invalidtag); } } else if (jsonObject.getInt("errcode") == access_token_lack || jsonObject.getInt("errcode") == access_token_overdue || jsonObject.getInt("errcode") == access_token_wrongful) { refreshAccess_token(); } } else { logger.error(TAG + "send message to " + touser + "/" + toparty + "/" + totag + " failed"); } } catch (JSONException e) { // TODO Auto-generated catch block logger.error("EXCEPTION", e); } return jsonObject; } /** * 发送卡片消息,格式只有在企业微信中显示.微信不支持颜色格式 * * @param userid 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向该企业应用的全部成员发送 * @param toparty 部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数 * @param totag 标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数 * @param title 是 标题,不超过128个字节,超过会自动截断 * @param description 是 描述,不超过512个字节,超过会自动截断 * @param url 是 点击后跳转的链接。 * @param btntxt 否 按钮文字。 默认为“详情”, 不超过4个文字,超过自动截断。 * @return { "errcode" : 0, "errmsg" : "ok", "invaliduser" : "userid1|userid2", * // 不区分大小写,返回的列表都统一转为小写 "invalidparty" : "partyid1|partyid2", * "invalidtag":"tagid1|tagid2" } */ public JSONObject sendTextcard(String touser, String toparty, String totag, String title, String description, String url, String btntxt) { JSONObject jsonObject = null; try { JSONObject params = new JSONObject(); JSONObject content = new JSONObject(); content.put("title", title); content.put("description", description); content.put("url", url.equals("") ? "www.baidu.com" : url);// 为空则跳转百度 content.put("btntxt", btntxt); params.put("textcard", content); params.put("msgtype", "textcard"); params.put("agentid", agentid); if (touser != null) { params.put("touser", touser); } if (toparty != null) { params.put("toparty", toparty); } if (totag != null) { params.put("totag", totag); } jsonObject = (JSONObject) HttpsUtil.sendPostData("https://qyapi.weixin.qq.com", "/cgi-bin/message/send?access_token=" + access_token, params.toString(), null) .get(HttpsUtil.JSONOBJECT); if (jsonObject.has("errcode")) {// 请求成功 if (jsonObject.getInt("errcode") == errcode_ok) { if (jsonObject.has("invaliduser")) { String invaliduser = jsonObject.getString("invaliduser"); logger.info("send message invaliduser fail:" + invaliduser); } if (jsonObject.has("invalidparty")) { String invalidparty = jsonObject.getString("invalidparty"); logger.info("send message invalidparty fail:" + invalidparty); } if (jsonObject.has("invalidtag")) { String invalidtag = jsonObject.getString("invalidtag"); logger.info("send message invalidtag fail:" + invalidtag); } } else if (jsonObject.getInt("errcode") == access_token_lack || jsonObject.getInt("errcode") == access_token_overdue || jsonObject.getInt("errcode") == access_token_wrongful) { refreshAccess_token(); } } else { logger.error(TAG + "send message to " + touser + "/" + toparty + "/" + totag + " failed"); } } catch (JSONException e) { // TODO Auto-generated catch block logger.error("EXCEPTION", e); } return jsonObject; } // 单例 private static class SingletonHolder { private static final WeChatUtil INSTANCE = new WeChatUtil(); } /** * 获取单例 * * @return */ public static final WeChatUtil getInstance() { return SingletonHolder.INSTANCE; } }
hhhaiai/QAUi
qauiframework/src/com/notification/WeChatUtil.java
66,595
package testproject; import org.junit.Test; import java.util.*; public class 摧毁小行星 { public boolean asteroidsDestroyed(int mass, int[] asteroids) { //List<Integer>list=new ArrayList<>(); // for(int i=0;i<asteroids.length;i++){ // list.add(asteroids[i]); // } // Collections.sort(list, new Comparator<Integer>() { // @Override // public int compare(Integer o1, Integer o2) { // return Math.abs(mass-o1)-Math.abs(mass-o2); // } // }); Arrays.sort(asteroids); long mm=mass; for(int i=0;i<asteroids.length;i++){ if(mm<asteroids[i]){ return false; } mm=mm+asteroids[i]; } return true; } @Test public void test(){ int mass = 10; int[]asteroids =new int[]{3,9,19,5,21}; System.out.println(asteroidsDestroyed(mass,asteroids)); } }
lhh520/hello
offer/src/testproject/摧毁小行星.java
66,596
package com.yisingle.map.move.library; import android.util.Log; import com.amap.api.maps.model.LatLng; import com.autonavi.amap.mapcore.DPoint; import com.autonavi.amap.mapcore.IPoint; import com.autonavi.amap.mapcore.MapProjection; import java.util.ArrayList; import java.util.List; /** * @author jikun * Created by jikun on 2018/6/7. */ public class MoveUtils implements CustomAnimator.OnTimeListener { private CustomAnimator customAnimator = new CustomAnimator(); private IPoint startIPoint = new IPoint(0, 0); private OnCallBack callBack; public MoveUtils() { customAnimator.setOnTimeListener(this); } /** * @param latLng 坐标 * @param time 时间 毫秒 * @param isContinue 是否在以上次停止后的坐标点继续移动 当list.size()=1 isContinue 就会变的非常有用 * 注意:如果调用 startMove(list,time,isContinue) 如果list.size=1 只传递了一个点并且isContinue=false * 那么 onSetGeoPoint回调方法返回的角度是0 因为只有一个点是无法计算角度的 */ public void startMove(LatLng latLng, long time, boolean isContinue) { List<LatLng> list = new ArrayList<>(); list.add(latLng); startMove(list, time, isContinue); } /** * @param list 坐标数组 * @param time 时间 毫秒 多长时间走完这些数组 * @param isContinue 是否在以上次停止后的坐标点继续移动 当list.size()=1 * 注意:如果调用 startMove(list,time,isContinue) 如果list.size=1 只传递了一个点并且isContinue=false * 那么 onSetGeoPoint回调方法返回的角度是0 因为只有一个点是无法计算角度的 */ public void startMove(List<LatLng> list, long time, boolean isContinue) { if (time <= 0) { //如果传递过来的参数时间小于等于0 time = 10; } List<IPoint> pointList = new ArrayList<>(); if (isContinue && startIPoint.x != 0 && startIPoint.y != 0) { pointList.add(startIPoint); } for (LatLng latLng : list) { IPoint point = new IPoint(); MapProjection.lonlat2Geo(latLng.longitude, latLng.latitude, point); pointList.add(point); } if (null != list && pointList.size() >= 2) { customAnimator.ofIPoints(pointList).start(time); } else if (null != list && pointList.size() == 1) { if (null != callBack) { startIPoint = pointList.get(0); DPoint dPoint = new DPoint(); MapProjection.geo2LonLat(startIPoint.x, startIPoint.y, dPoint); callBack.onSetLatLng(new LatLng(dPoint.y, dPoint.x), 0); } } else { Log.e("MoveUtils", "MoveUtils move list is null"); } } /** * 停止移动 */ public void stop() { customAnimator.end(); } /** * 摧毁 */ public void destory() { callBack = null; customAnimator.setOnTimeListener(null); customAnimator.destory(); } public OnCallBack getCallBack() { return callBack; } /** * 设置监听回调 * * @param callBack OnCallBack */ public void setCallBack(OnCallBack callBack) { this.callBack = callBack; } @Override public void onUpdate(IPoint start, IPoint moveIPoint, IPoint end) { if (null != callBack) { startIPoint = moveIPoint; DPoint dPoint = new DPoint(); MapProjection.geo2LonLat(startIPoint.x, startIPoint.y, dPoint); callBack.onSetLatLng(new LatLng(dPoint.y, dPoint.x), getRotate(start, end)); } } public interface OnCallBack { /** * @param latLng IPoint 移动坐标IPoint * @param rotate 角度 角度返回 这里的角度返回是根据两个点坐标来计算汽车在地图上的角度的 * 并不是传感器返回的 * 如果调用 startMove(list,time,isContinue) 如果list.size=1 只传递了一个点并且isContinue=false * 那么 onSetGeoPoint回调方法返回的角度是0 */ void onSetLatLng(LatLng latLng, float rotate); } private float getRotate(IPoint var1, IPoint var2) { if (var1 != null && var2 != null) { double var3 = (double) var2.y; double var5 = (double) var1.y; double var7 = (double) var1.x; return (float) (Math.atan2((double) var2.x - var7, var5 - var3) / 3.141592653589793D * 180.0D); } else { return 0.0F; } } }
jikun2008/MarkerMoveUtils
movelibrary/src/main/java/com/yisingle/map/move/library/MoveUtils.java
66,597
/* * 版权所有(c)<2021><蔡永程> * * 反996许可证版本1.0 * * 在符合下列条件的情况下,特此免费向任何得到本授权作品的副本(包括源代码、文件和/或相关内容,以 * 下统称为“授权作品”)的个人和法人实体授权:被授权个人或法人实体有权以任何目的处置授权作品,包括 * 但不限于使用、复制,修改,衍生利用、散布,发布和再许可: * * 1. 个人或法人实体必须在许可作品的每个再散布或衍生副本上包含以上版权声明和本许可证,不得自行修 * 改。 * 2. 个人或法人实体必须严格遵守与个人实际所在地或个人出生地或归化地、或法人实体注册地或经营地( * 以较严格者为准)的司法管辖区所有适用的与劳动和就业相关法律、法规、规则和标准。如果该司法管辖区 * 没有此类法律、法规、规章和标准或其法律、法规、规章和标准不可执行,则个人或法人实体必须遵守国际 * 劳工标准的核心公约。 * 3. 个人或法人不得以任何方式诱导、暗示或强迫其全职或兼职员工或其独立承包人以口头或书面形式同意 * 直接或间接限制、削弱或放弃其所拥有的,受相关与劳动和就业有关的法律、法规、规则和标准保护的权利 * 或补救措施,无论该等书面或口头协议是否被该司法管辖区的法律所承认,该等个人或法人实体也不得以任 * 何方法限制其雇员或独立承包人向版权持有人或监督许可证合规情况的有关当局报告或投诉上述违反许可证 * 的行为的权利。 * * 该授权作品是"按原样"提供,不做任何明示或暗示的保证,包括但不限于对适销性、特定用途适用性和非侵 * 权性的保证。在任何情况下,无论是在合同诉讼、侵权诉讼或其他诉讼中,版权持有人均不承担因本软件或 * 本软件的使用或其他交易而产生、引起或与之相关的任何索赔、损害或其他责任。 */ package letcode.normal.easy; /** * @author Caiyongcheng * @version 1.0.0 * @since 2023/9/2 12:00 * description 给你一个长度为 n ,下标从 0 开始的整数数组 forts ,表示一些城堡。forts[i] 可以是 -1 ,0 或者 1 , * 其中: -1 表示第 i 个位置 没有 城堡。 0 表示第 i 个位置有一个 敌人 的城堡。 1 表示第 i 个位置有一个你控制的城堡。 * 现在,你需要决定,将你的军队从某个你控制的城堡位置 i 移动到一个空的位置 j , * 满足: 0 <= i, j <= n - 1 军队经过的位置 只有 敌人的城堡。 * 正式的,对于所有 min(i,j) < k < max(i,j) 的 k ,都满足 forts[k] == 0 。 当军队移动时,所有途中经过的敌人城堡都会被 摧毁 。 * 请你返回 最多 可以摧毁的敌人城堡数目。如果 无法 移动你的军队,或者没有你控制的城堡,请返回 0 。 */ public class _2511TwoThousandFiveHundredEleven { public int captureForts(int[] forts) { //题目简化为 找到连续的敌军堡垒 并且左边和右边一个是我方堡垒 一个是空堡垒 int rst = 0; for (int i = 0; i < forts.length; i++) { if (forts[i] == 0) { int curIdx = i; //跳过连续的地方堡垒 while (curIdx < forts.length && forts[curIdx] == 0) { ++curIdx; } //左右两边一个是我方堡垒 一个是空堡垒 if (i > 0 && curIdx < forts.length && forts[i - 1] * forts[curIdx] == -1) { rst = Math.max(rst, curIdx - i); } i = curIdx; } } return rst; } /** * 示例 1: * <p> * 输入:forts = [1,0,0,-1,0,0,0,0,1] * 输出:4 * 解释: * - 将军队从位置 0 移动到位置 3 ,摧毁 2 个敌人城堡,位置分别在 1 和 2 。 * - 将军队从位置 8 移动到位置 3 ,摧毁 4 个敌人城堡。 * 4 是最多可以摧毁的敌人城堡数目,所以我们返回 4 。 * 示例 2: * <p> * 输入:forts = [0,0,1,-1] * 输出:0 * 解释:由于无法摧毁敌人的城堡,所以返回 0 。 * * @param args */ public static void main(String[] args) { System.out.println(new _2511TwoThousandFiveHundredEleven().captureForts( new int[]{0, 0, 1, -1} )); } }
caiyongcheng/MyLeetcode
src/main/java/letcode/normal/easy/_2511TwoThousandFiveHundredEleven.java
66,629
package pp.arithmetic.leetcode; import java.util.HashMap; /** * Created by wangpeng on 2019-05-14. * 36. 有效的数独 * * 判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。 * * 数字 1-9 在每一行只能出现一次。 * 数字 1-9 在每一列只能出现一次。 * 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。 * * <image src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png" /> * 上图是一个部分填充的有效的数独。 * * 数独部分空格内已填入了数字,空白格用 '.' 表示。 * * 示例 1: * * 输入: * [ * ["5","3",".",".","7",".",".",".","."], * ["6",".",".","1","9","5",".",".","."], * [".","9","8",".",".",".",".","6","."], * ["8",".",".",".","6",".",".",".","3"], * ["4",".",".","8",".","3",".",".","1"], * ["7",".",".",".","2",".",".",".","6"], * [".","6",".",".",".",".","2","8","."], * [".",".",".","4","1","9",".",".","5"], * [".",".",".",".","8",".",".","7","9"] * ] * 输出: true * 示例 2: * * 输入: * [ * ["8","3",".",".","7",".",".",".","."], * ["6",".",".","1","9","5",".",".","."], * [".","9","8",".",".",".",".","6","."], * ["8",".",".",".","6",".",".",".","3"], * ["4",".",".","8",".","3",".",".","1"], * ["7",".",".",".","2",".",".",".","6"], * [".","6",".",".",".",".","2","8","."], * [".",".",".","4","1","9",".",".","5"], * [".",".",".",".","8",".",".","7","9"] * ] * 输出: false * 解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。 * 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。 * 说明: * * 一个有效的数独(部分已被填充)不一定是可解的。 * 只需要根据以上规则,验证已经填入的数字是否有效即可。 * 给定数独序列只包含数字 1-9 和字符 '.' 。 * 给定数独永远是 9x9 形式的。 */ public class _36_isValidSudoku { public static void main(String[] args) { char[][] board = new char[][]{ {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'} }; _36_isValidSudoku isValidSudoku = new _36_isValidSudoku(); System.out.println(isValidSudoku.isValidSudoku(board)); } /** * 解题思路: * 首先必须理解有效数独的定义 * 要知道是否满足数独的要求,肯定所有的点都得遍历到,所以得双重遍历 * 在双重遍历中得匹配之前的遍历结果,看是否有重复的数字,考虑用hashmap报错遍历结果 * hashmap中存储的key是有三种:行的index+数字、列的index+数字、3*3宫格的index+数字 * * 提交结果: * 执行用时 : 16 ms, 在Valid Sudoku的Java提交中击败了62.19% 的用户 * 内存消耗 : 42.4 MB, 在Valid Sudoku的Java提交中击败了81.42% 的用户 * 结果并不是很出色,看了其他优秀解法,发现他们存储是固定大小三个数组, * 仔细想想也是,HashMap虽然查找是O(1),但是扩容的时候是有时间消耗的,对于这种固定大小的可以考虑用数组进行优化 * 官方解题,是分了三个HashMap,估计也是为了减少扩容的时间消耗吧 * * @param board * @return */ public boolean isValidSudoku(char[][] board) { HashMap<String, Boolean> map = new HashMap<>(); for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { char num = board[i][j]; if (num == '.') continue; String rowKey = i + "row" + num; String colKey = j + "col" + num; int groupIndex = i / 3 + j / 3 * 3; String groupKey = groupIndex + "group" + num; //寻找是否有重复的数字 if (map.getOrDefault(rowKey, false) || map.getOrDefault(colKey, false) || map.getOrDefault(groupKey, false)) { return false; } //更新遍历记录 map.put(rowKey, true); map.put(colKey, true); map.put(groupKey, true); } } return true; } }
pphdsny/Leetcode-Java
src/pp/arithmetic/leetcode/_36_isValidSudoku.java
66,632
package org.zyf.javabasic.workflowpipline.worker.aideal; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Service; import org.zyf.javabasic.workflowpipline.annotations.WorkerInfo; import org.zyf.javabasic.workflowpipline.core.Workflow; import org.zyf.javabasic.workflowpipline.core.WorkflowExecutionContext; import org.zyf.javabasic.workflowpipline.dataprocess.Item; import org.zyf.javabasic.workflowpipline.model.KnowledgeMetadata; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * @program: zyfboot-javabasic * @description: 情绪分生成分析 * @author: zhangyanfeng * @create: 2024-02-15 13:40 **/ @Slf4j @WorkerInfo(name = "moodScoreCreateWorker") @Service public class MoodScoreCreateWorker extends AbstractAIDealWorker implements InitializingBean { @Override protected WorkflowExecutionContext doWork(WorkflowExecutionContext context) { //抽取item List<Item> typedItems = context.getResult().getItems(); if (CollectionUtils.isEmpty(typedItems)) { return context; } //模拟:通过请求算法服务,根据当前标题和文本给出对应的关键词和实体词信息 for (Item item : typedItems) { KnowledgeMetadata data = Item.getData(item.getData(), KnowledgeMetadata.class); if (Objects.isNull(data)) { log.warn("AIWordCreateWorker Item data is null! item={}", item); continue; } String content = data.getContent(); if (StringUtils.isBlank(content)) { continue; } //模拟:根据标题成对应的情绪分 data.setMoodScore(getSentimentScore(content)); item.setData(data); } context.getResult().setItems(typedItems); return context; } private double getSentimentScore(String text) { if (text == null || text.isEmpty()) { return 0.0; // 文本为空时情绪分为0 } final List<String> POSITIVE_WORDS = Arrays.asList( "好", "出色", "快乐", "幸福", "赞", "发现", "可能存在生命" ); final List<String> NEGATIVE_WORDS = Arrays.asList( "坏", "糟糕", "悲伤", "愤怒", "批评", "冲击", "不稳定", "下调", "影响", "衰退", "下降", "担忧" ); double score = 0.0; // 对于文本中的每个正面词,增加分数 for (String word : POSITIVE_WORDS) { if (text.contains(word)) { score += 1.0; } } // 对于文本中的每个负面词,减少分数 for (String word : NEGATIVE_WORDS) { if (text.contains(word)) { score -= 1.0; } } return score; } @Override public void afterPropertiesSet() throws Exception { Workflow.registerWorker(getName(), this); } }
ZYFCodes/zyfboot-javabasic
src/main/java/org/zyf/javabasic/workflowpipline/worker/aideal/MoodScoreCreateWorker.java
66,633
package chapter08_05_Queue集合; import java.util.*; /** * Description: * 1.属于List接口实现类 * 2.实现Deque接口,可以被当成双端队列使用。因此也可以被当成栈来使用。 * * 1.LinkedList、ArrayList、ArrayDeque实现机制完全不同 * ArrayList、ArrayDeque内部以数组形式保存集合元素,随机访问集合元素性能好 * LinkedList内部以链表保存集合元素,随机访问性能差,插入、删除元素性能出色,只改变指针所指向地址。 * * 1.ArrayList.get()性能好 * 2.LinkedList,采用迭代器Iterator遍历性能好 */ public class LinkedListTest { public static void main(String[] args) { LinkedList books = new LinkedList(); // 将字符串元素加入队列的尾部 books.offer("疯狂Java讲义"); // 将一个字符串元素加入栈的顶部 books.push("轻量级Java EE企业应用实战"); // 将字符串元素添加到队列的头部(相当于栈的顶部) books.offerFirst("疯狂Android讲义"); // 以List的方式(按索引访问的方式)来遍历集合元素 for (int i = 0; i < books.size() ; i++ ) { System.out.println("遍历中:" + books.get(i)); } // 访问、并不删除栈顶的元素 System.out.println(books.peekFirst()); // 访问、并不删除队列的最后一个元素 System.out.println(books.peekLast()); // 将栈顶的元素弹出“栈” System.out.println(books.pop()); // 下面输出将看到队列中第一个元素被删除 System.out.println(books); // 访问、并删除队列的最后一个元素 System.out.println(books.pollLast()); // 下面输出:[轻量级Java EE企业应用实战] System.out.println(books); } }
3792274/crazyJava3
第8章Java集合/chapter08_05_Queue集合/LinkedListTest.java
66,634
package p1840; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class CF1840C { public static void main(String[] args) { Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); int t = scanner.nextInt(); while (t-- > 0) { int n = scanner.nextInt(); int k = scanner.nextInt(); int q = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } System.out.println(solve(n, k, q, a)); } } private static String solve(int n, int k, int q, int[] a) { int cnt = 0; long ans = 0; for (int i = 0; i < n; i++) { if (a[i] <= q) { cnt++; } else { if (cnt >= k) { int a1 = 1, an = cnt - k + 1; ans += (long) (a1 + an) * an / 2; } cnt = 0; } } if (cnt >= k) { int a1 = 1, an = cnt - k + 1; ans += (long) (a1 + an) * an / 2; } return String.valueOf(ans); } } /* C. Ski Resort https://codeforces.com/contest/1840/problem/C 题目大意: Dima Vatrushin 是学校的一名数学老师。由于工作出色,他被派去休假十天。迪马一直梦想着去滑雪胜地,所以他想连续拨出几天去滑雪。由于假期需要精心准备,他至少只会去 k 天。 给定一个数组 a,其中包含度假胜地的天气预报。也就是说,在第 i 天,温度将是 ai 度。 迪马出生在西伯利亚,所以他只有在整个假期温度不超过 q 度的情况下才能去度假。 不幸的是,迪马太专注于抽象代数,以至于忘记了如何数数。他让你帮他数一数选择度假日期的方法。 连续区间长度,等差数列求和。 ====== input 7 3 1 15 -5 0 -10 5 3 -33 8 12 9 0 5 4 3 12 12 12 10 15 4 1 -5 0 -1 2 5 5 5 0 3 -1 4 -5 -3 1 1 5 5 6 1 3 0 3 -2 5 -4 -4 output 6 0 1 0 0 1 9 */
gdut-yy/leetcode-hub-java
codeforces/codeforces-19/src/main/java/p1840/CF1840C.java
66,636
package Other.AdvancedAlgorithm._26_ChangeString; /* * 整体交换字符串 * * 题目描述: * 给定一个字符串 str 和长度 leftSize,请把左侧 leftSize 的部分和有部分做整体交换。 * 要求空间复杂度是 O(1)。 * * 思路: * 0. https://github.com/dyfloveslife/LeetCodeAndSwordToOffer/blob/master/src/Other/AdvancedAlgorithm/_23_RotateString/Solution.java * 1. 先将 [0...leftSize] 部分进行逆序,然后再将 [leftSize + 1...s.length() - 1] 进行逆序,最后再将整体进行逆序; * 2. 另一种方法是:假如给定 [a, b, c, d, e, f, g, h],leftSize=5: * 首先,右侧部分短,那么就将左侧部分(从左开始数)与右侧等长的部分,与右侧部分交换,也就是将 [a, b, c] 和 [f, g, h] 进行交换, * 也就是 a 和 f 交换,b 和 g 交换,c 和 h 交换; * 3. 然后就变成 [f, g, h | d, e, a, b, c],此时对于 [d, e | a, b, c] 来说,左侧部分短,就将右侧(从右开始数)与左侧等长的部分,与左侧进行交换; * 4. 也就将 d 和 b 交换,e 和 c 交换,变成 [b, c, a, d, e],然后 [d, e] 就不动了,也就是谁短,谁交换过来就不动了; * 5. 然后变成了 [b, c, a],此时右侧短,继续之前的逻辑,将 b 和 a 交换,即 [a, c, b],然后 a 就不动了; * 6. 最后,c 和 b 再进行交换,就结束了。 * 7. 这种方法的好处就是,在某些情况下,例如左右部分是等长的,那么就可以划分结束了,就不需要再进行交换了。 * 8. 这种方法可以在某些场景下表现得很出色,例如限制了交换次数,那么此时用该方法的话,就会比第一种方法要好很多。 */ public class Solution { // 方法一 public String changeString1(String str, int leftSize) { if (leftSize <= 0 || str == null || str.length() <= leftSize) { return ""; } return process1(str.toCharArray(), 0, leftSize - 1, str.length() - 1); } // 将左部分 chars[left...mid] 整体移动到右部分 chars[mid+1...right] private String process1(char[] chars, int left, int mid, int right) { reverse(chars, left, mid); reverse(chars, mid + 1, right); reverse(chars, left, right); return String.valueOf(chars); } private void reverse(char[] chars, int left, int right) { while (left < right) { char temp = chars[left]; chars[left++] = chars[right]; chars[right--] = temp; } } // 方法二 public String changeString2(String str, int leftSize) { if (leftSize <= 0 || str == null || str.length() <= leftSize) { return ""; } char[] chars = str.toCharArray(); int left = 0; int right = str.length() - 1; // 左右部分的大小 int lpart = leftSize; int rpart = str.length() - leftSize; // 左右两个部分需要交换的长度,以少的部分为主 int same = Math.min(lpart, rpart); // 左部分和右部分相差的长度 int diff = lpart - rpart; exchange(chars, left, right, same); while (diff != 0) { // 左侧大 if (diff > 0) { // 既然左侧大了,那么右侧缓过来之后,left 应该来到 left+same 的位置 left += same; lpart = diff; // 右侧大,那么 right 就需要往左缩 } else { right -= same; rpart = -diff; } same = Math.min(lpart, rpart); diff = lpart - rpart; exchange(chars, left, right, same); } return String.valueOf(chars); } // 该函数实现的是:在 chars[] 中,将 chars[left...] 数出(从左往右) size 长度的字符与 chars[...right] 数出(从右往左) size 长度的字符交换 private void exchange(char[] chars, int left, int right, int size) { int i = right - size + 1; char temp = 0; while (size-- != 0) { temp = chars[left]; chars[left] = chars[i]; chars[i] = temp; left++; i++; } } public static void main(String[] args) { Solution solution = new Solution(); String s = "abcdefgh"; System.out.println(solution.changeString1(s, 5)); System.out.println(solution.changeString2(s, 5)); } }
dyfloveslife/LeetCodeAndSwordToOffer
src/Other/AdvancedAlgorithm/_26_ChangeString/Solution.java
66,639
/** * Project Name:algorithm * File Name:BayesClassifier.java * Package Name:com.zongtui.algorithm.classifier.bayes * Date:2015-4-14上午10:57:18 * Copyright (c) 2015, 众推项目组版权所有. * */ package com.zongtui.algorithm.classifier.bayes; /** * ClassName: BayesClassifier <br/> * Function: 朴素贝叶斯分类器. <br/> * date: 2015-4-14 上午10:57:18 <br/> * * C000007 汽车 C000008 财经 C000010 IT C000013 健康 C000014 体育 C000016 旅游 C000020 教育 C000022 招聘 C000023 文化 C000024 军事 * * @author feng * @version * @since JDK 1.7 */ import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Vector; public class BayesClassifier { private TrainingDataManager tdm;// 训练集管理器 private String trainnigDataPath;// 训练集路径 private static double zoomFactor = 10.0f; /** * * 默认的构造器,初始化训练集 */ public BayesClassifier() { tdm = new TrainingDataManager(); } /** * * 计算给定的文本属性向量X在给定的分类Cj中的类条件概率 * * <code>ClassConditionalProbability</code>连乘值 * * @param X * 给定的文本属性向量 * * @param Cj * 给定的类别 * * @return 分类条件概率连乘值,即<br> */ float calcProd(String[] X, String Cj) { float ret = 1.0F; // 类条件概率连乘 for (int i = 0; i < X.length; i++) { String Xi = X[i]; // 因为结果过小,因此在连乘之前放大10倍,这对最终结果并无影响,因为我们只是比较概率大小而已 ret *= ClassConditionalProbability.calculatePxc(Xi, Cj) * zoomFactor; } // 再乘以先验概率 ret *= PriorProbability.calculatePc(Cj); return ret; } /** * * 去掉停用词 * * @param text * 给定的文本 * * @return 去停用词后结果 */ public String[] DropStopWords(String[] oldWords) { Vector<String> v1 = new Vector<String>(); for (int i = 0; i < oldWords.length; ++i) { if (StopWordsHandler.IsStopWord(oldWords[i]) == false) {// 不是停用词 v1.add(oldWords[i]); } } String[] newWords = new String[v1.size()]; v1.toArray(newWords); return newWords; } /** * * 对给定的文本进行分类 * * @param text * 给定的文本 * * @return 分类结果 */ @SuppressWarnings("unchecked") public String classify(String text) { String[] terms = null; terms = ChineseSpliter.split(text, " ").split(" ");// 中文分词处理(分词后结果可能还包含有停用词) terms = DropStopWords(terms);// 去掉停用词,以免影响分类 String[] Classes = tdm.getTraningClassifications();// 分类 float probility = 0.0F; List<ClassifyResult> crs = new ArrayList<ClassifyResult>();// 分类结果 for (int i = 0; i < Classes.length; i++) { String Ci = Classes[i];// 第i个分类 System.out.println(" 分类数据 "+Ci); probility = calcProd(terms, Ci);// 计算给定的文本属性向量terms在给定的分类Ci中的分类条件概率 // 保存分类结果 ClassifyResult cr = new ClassifyResult(); cr.classification = Ci;// 分类 cr.probility = probility;// 关键字在分类的条件概率 System.out.println("In process."); System.out.println(Ci + ":" + probility); crs.add(cr); } // 对最后概率结果进行排序 java.util.Collections.sort(crs, new Comparator() { public int compare(final Object o1, final Object o2) { final ClassifyResult m1 = (ClassifyResult) o1; final ClassifyResult m2 = (ClassifyResult) o2; final double ret = m1.probility - m2.probility; if (ret < 0) { return 1; } else { return -1; } } }); // 返回概率最大的分类 return crs.get(0).classification; } public static void main(String[] args) { String text = "此役,马刺这边4人得分上双,邓肯得到28分11篮板,生涯季后赛总得分达到5027分,他也成为了继乔丹、贾巴尔、科比和奥尼尔之后,NBA历史上第五位生涯季后赛总分5000+的球星。另外,今天的比赛,也是石佛第100次在季后赛中打出得分20+、篮板球10+的表现。帕克送出5次助攻,生涯季后赛助攻总数达到1040次,追平了科比排名历史榜单第7位。但整场球,法国跑车的发挥并不好,他6投0中,仅得到1分,还在比赛末节,因为右脚脚踝、跟腱和大腿的多处伤势复发,遗憾退赛。吉诺比利在今天得到9分,比赛末节,他6次犯规离场,这是他职业生涯第四次在季后赛中遭遇驱逐,前三场,马刺都输了球,但今天这一历史却被改写了。马刺替补迪奥拿到了12分9篮板6助攻,他也成为了自从1985-86赛季以来,马刺队史上第二位在季后赛中替补出场,却至少拿下12分9个篮板6个助攻的球员。2007年5月19日,吉诺比利在对阵太阳的比赛中,也做到过这一点(33分11篮板6助攻)。另外,米尔斯替补出场发挥出色,砍下16分;伦纳德斩下23分9篮板。"; // String text = "怎么买迷藥订货Q:285829120怎么买迷藥,不货比怕货,就怕不识货,质量第一,验货付款,担保交易,货到付款,保密配送,安心取货,欢迎前来咨询,医药专卖。"; BayesClassifier classifier = new BayesClassifier();// 构造Bayes分类器 String result = classifier.classify(text);// 进行分类 System.out.println("此项属于[" + result + "]"); } }
zongtui/zongtui-Algorithm-test
algorithm/src/main/java/com/zongtui/algorithm/classifier/bayes/BayesClassifier.java
66,643
package com.liyafeng.video; public class Video { /** * 视频入门指南 * https://zhuanlan.zhihu.com/p/28518637 (七牛音视频架构师) * https://blog.csdn.net/leixiaohua1020 (雷霄骅(leixiaohua1020)的专栏) * * * ===================3gp================ * 3GP是一种多媒体单元格式,由Third Generation Partnership Project(3GPP)定义,主要用于3G手机上。 * 3GP是 MPEG-4 第12部分,又被称为MPEG-4/JPEG2000基本媒体文件格式 * 3GP是MPEG-4 Part 14(MP4)的一种简化版本,减少了存储空间和较低的带宽需求, * 让手机上有限的存储空间可以使用。 * 3GP文件视频的部分可以用MPEG-4 Part 2、H.263或MPEG-4 Part 10 (AVC/H.264)等格式来存储, * 声音的部分则支持AMR-NB、AMR-WB、AMR-WB+、AAC-LC或HE-AAC来当作声音的编码。 * <p> * -------------------------- * 3gp是一种容器,除了头部的视频信息外,还包括编码后的视频信息,而且支持多种编码方式 * 很显然头部信息包含了编码方式。而且播放器的原理都是一样的,取出文件的头部信息 * 然后将视频信息解码,然后播放 * <p> * * <p> * =======================mp4========================= * MP4或称MPEG-4第14部分(英语:MPEG-4 Part 14)是一种标准的数字多媒体容器格式 * 注意是容器格式 * --------------------------------- * 同时拥有音频視频的MPEG-4文件通常使用标准扩展名.mp4 * 仅有音频的MPEG-4文件会使用.m4a扩展名 * <p> * * http://www.infoq.com/cn/articles/improving-android-video-on-news-feed-with-litho * * Facebook构建高性能Android视频组件实践之路 * * @param args */ public static void main(String[] args) { } /** * https://m.huxiu.com/article/263561.html (从.JPG到.AVI:视频编码最强入门科普) * https://www.jianshu.com/p/1379ed99783e ( 视频相关的理论知识与基础概念) * <p> * <p> * ============基础知识============ * <p> * ---------像素(图像的元素)----------------- * 像素点的英文叫Pixel(缩写为PX)。这个单词是由 Picture(图像) 和 Element(元素)这两个单词的字母所组成的。 * <p> * 像素是图像显示的基本单位。我们通常说一幅图片的大小,例如是1920×1080,就是长度为1920个像素点,宽度为1080个像素点。 * 乘积是2,073,600,也就是说,这个图片是两百万像素的。 * 1920×1080,这个也被称为这幅图片的分辨率 * <p> * ---------ppi------------ * PPI,就是“Pixels Per Inch”,每英寸像素数。也就是,手机(或显示器)屏幕上每英寸面积,到底能放下多少个“像素点”。 * 这个值当然是越高越好啦!PPI越高,图像就越清晰细腻。 * <p> * 以前的功能机,例如诺基亚,屏幕PPI都很低,有很强烈的颗粒感 * 后来,苹果开创了史无前例的“视网膜”(Retina)屏幕,PPI值高达326(每英寸屏幕有326像素),画质清晰,再也没有了颗粒感 * <p> * -------------rgb------------- * 任何颜色,都可以通过红色(Red)、绿色(Green)、蓝色(Blue)按照一定比例调制出来。这三种颜色,被称为“三原色”。 * 在计算机里,R、G、B也被称为“基色分量”。它们的取值,分别从0到255,一共256个等级 * 256×256×256=16,777,216种,因此也简称为1600万色。 * <p> * 256是2的8次方,所以最少一个8位的二进制就能表示256个数,所以三个颜色有占用内存的24位 * 因此,这种方式表达出来的颜色,也被称为24位色。 * <p> * 所以这种表示1一个像素点占用24bit内存 * <p> * ------------帧率(Frame Rate)-------------- * 在视频中,一个帧(Frame)就是指一幅静止的画面。帧率, * 就是指视频每秒钟包括的画面数量(FPS,Frame per second)。 * 帧率越高,视频就越逼真、越流畅。 */ public void f1() { } /** * ==================视频采集=============== * <p> * ------------摄像头工作原理----------- * https://www.cnblogs.com/fjutacm/p/220631977df995512d136e4dbd411951.html (camera理论基础和工作原理) * <p> * 光线通过镜头进入摄像头内部,然后经过IR Filter过滤红外光,最后到达sensor(传感器), * senor分为按照材质可以分为CMOS和CCD两种,可以将光学信号转换为电信号, * 再通过内部的ADC电路转换为数字信号, * 然后传输给DSP(如果有的话,如果没有则以DVP的方式传送数据到基带芯片baseband,此时的数据格式Raw Data,后面有讲进行加工)加工处理, * 转换成RGB、YUV等格式输出 * <p> * 摄像头模组,Camera Compact Module,简写为CCM,是影响捕捉的重要元器件,我的理解就是硬件上的摄像头 * 1.镜头 * 一般由几片透镜组成透镜结构,按材质可分为塑胶透镜(plastic)或玻璃透镜(glass) * 透镜越多,成本越高,相对成像效果会更出色(个人理解是光线更均匀、更细致;对光线的选通更丰富;成像畸变更小,但是会导致镜头变长,光通量变小)。 * 2.红外滤光片 IR Filter * 主要是过滤掉进入镜头的光线中的红外光,这是因为人眼看不到红外光,但是sensor却能感受到红外光,所以需要将光线中的红外光滤掉,以便图像更接近人眼看到的效果 * <p> * 3.传感器 Sensor * sensor是摄像头的核心,负责将通过Lens的光信号转换为电信号,再经过内部AD转换为数字信号。 * 每个pixel像素点只能感受R、G、B中的一种,因此每个像素点中存放的数据是单色光, * 所以我们通常所说的30万像素或者130万像素,表示的就是有30万或130万个感光点, * 每个感光点只能感应一种光,这些最原始的感光数据我们称为RAW Data。 * Raw Data数据要经过ISP(应该理解为Image Sensor Processor,是Sensor模块的组成部分,下面有解释)的处理才能还原出三原色, * 也就是说如果一个像素点感应为R值,那么ISP会根据该感光点周围的G、B的值, * 通过插值和特效处理等,计算出该R点的G、B值,这样该点的RGB就被还原了,除此之外,ISP还有很多操作, * <p> * >>CCD(Charge Coupled Device),电荷耦合器件传感器:使用一种高感光度的半导体材料制成,能把光线转变成电荷, * 通过模数转换器芯片转换成电信号。CCD由许多独立的感光单位组成,通常以百万像素为单位。当CCD表面受到光照时, * 每个感光单位都会将电荷反映在组件上,所有的感光单位产生的信号加在一起,就构成了一幅完整的图像。CCD传感器以日本厂商为主导, * 全球市场上有90%被日本厂商垄断,索尼、松下、夏普是龙头。 * >>CMOS(Complementary Metal-Oxide Semiconductor),互补性氧化金属半导体:主要是利用硅和锗做成的半导体, * 使其在CMOS上共存着带N(-)和P(+)级的半导体,这两个互补效应所产生的电流可以被处理芯片记录并解读成影像。 * CMOS传感器主要以美国、韩国和中国台湾为主导,主要生产厂家是美国的OmnVison、Agilent、Micron, * 中国台湾的锐像、原相、泰视等,韩国的三星、现代。 * <p> * 4.图像处理芯片 DSP (digital singnal processor) * DSP是CCM的重要组成部分,它的作用是将感光芯片获得的数据及时地快速地传递到中央处理器并刷新感光芯片, * 因此DSP芯片的好坏,直接影响画面品质,如:色彩饱和度、清晰度、流畅度等。 * 如果sensor没有集成DSP,则通过DVP的方式传输到baseband芯片中(可以理解为外挂DSP), * 进入DSP的数据是RAW Data,采集到的原始数据。 * 如果集成了DSP,则RAW Data会经过AWB、color matrix、lens shading、gamma、sharpness、AE和de-noise处理, * 最终输出YUV或者RGB格式的数据。 * * * <p> * 总结:摄像头模组,光信号 -(传感器)> 电信号 -(A/D)> Raw data -(DSP)> rgb或yuv * <p> * 光学图像再同学半导体的图像传感器生成电学信号; * 电学信号由A/D转换器转化为数字图像信号; * 数字图像信号经由DSP处理,输出RGB或者YUV * <p> * --------------A/D转换---------------- * 将模拟信号转换成数字信号的电路,称为模数转换器 * (简称a/d转换器或adc,analog to digital converter) * <p> * A/D转换的作用是将时间连续、幅值也连续的模拟量转换为时间离散、幅值也离散的数字信号,因此,A/D转换一般要经过取样、保持、量化及编码4个过程。 * 在实际电路中,这些过程有的是合并进行的,例如,取样和保持,量化和编码往往都是在转换过程中同时实现的。 * <p> * <p> * ==================采样率================ * 采样率,从连续的模拟信号中 转换为数字信号 的 频率 * 比如采样率为 10kHz 就是说1秒内从模拟信号中采取 10k 个数字信号 * 那么它的倒数就是0.1/1k,代表取一个数字信号所用的时间 * 采样率越高代表 越接近 真实 * <p> * 连续的光信号转化为连续的电信号,从连续的电信号中取样,取出raw data,输出给dsp * <p> * =================赫兹========= * 赫兹 hz 频率单位,指1秒内 "运动周期"的 次数 * <p> * ============码率/比特率=========== * 码率 = 比特率 = bit/s = bit per second = bps * 采样率*每个样本的bit = 码率 * 清晰度高,每个样本的bit就大(更清晰), 或者采样率高(更流畅) = 视频更接近真实 * <p> * 一个MP4的比特率就是文件字节数*8bit/ 视频长度 * <p> * 采样率是1秒取多少个样点,码率是一秒钟所有样点占用内存的大小 * * * ============主流采样方式============ * 通常用的是YUV4:2:0的采样方式,能获得1/2的压缩率 * * * * */ void f2() { } /** * ==============音频采集=============== * PCM Pulse-code modulation 脉冲编码调制 (调制=调整,转化)模拟信号-》数字信号 叫调制 * PCM是一种调制规则,并不是编码(压缩)规则 * pcm是音频 由模拟信号转换为数字信号的规则 * * AudioRecord 采集pcm数据 * 双声道(stereo) 单声道 mono * * 在16位声卡中有22KHz、44KHz等几级,当中,22KHz相当于普通FM广播的音质,44KHz已相当于CD音质了,眼下的经常使用採样频率都不超过48KHz。 * * 音频 PCM 8/16 bit per sample 44100hz * * 8bit 1 字节(也就是8bit) 只能记录 256 个数, 也就是只能将振幅划分成 256 个等级; * 16 bit 2 字节(也就是16bit) 可以细到 65536 个数, 这已是 CD 标准了; * */ void f2_1(){} /** * ===============yuv================== * YUV(Y'CbCr,Y'PbPr)和RGB都是颜色编码的方案, * Y代表亮度,UV代表色彩信息 * yuv y表示亮度 u和v表示色差(u和v也被称为:Cb-蓝色差,Cr-红色差), * b-blue r-red * u和v作用是描述影像色彩及饱和度 * <p> * Y'UV最大的优点在于只需占用极少的带宽。 * <p> * YUV数据有两种格式 * 紧缩格式(packed formats)yuv数据聚集在一起的数组 * 平面格式(planar formats)三个分量存储在不同的矩阵中(代表一种存储风格) * * * YUV,分为三个分量, * “Y”表示明亮度(Luminance或Luma),也就是灰度值;(从黑到白,所以黑白电视只要Y即可) * 而“U”和“V” 表示的则是色度(Chrominance或Chroma), * 作用是描述影像色彩及饱和度,用于指定像素的颜色。 * 采样,光信号转换为数字信号 * 主流的采样方式有三种,YUV4:4:4,YUV4:2:2,YUV4:2:0 (见drawable) * 1. YUV 4:4:4采样,每一个Y对应一组UV分量8+8+8 = 24bits,3个字节。 * 2. YUV 4:2:2采样,每两个Y共用一组UV分量,一个YUV占8+4+4 = 16bits 2个字节。 * 3. YUV 4:2:0采样,每四个Y共用一组UV分量一个YUV占8+2+2 = 12bits  1.5个字节。 * 也就是一个y是一个像素点,每个y大小是8位(一个byte) u是8位,v是8位 * 而YUV 4:2:2 是每两个y用一个uv ,所以一个y就是4位的u和v, * * =====存储 * 是 yyyyyyyyuvuv 代表8个像素,如此循环 * * ========YUV420=============== * 因为YUV420比较常用,(4个y共享一个u和一个v) 在这里就重点介绍YUV420。YUV420分为两种:YUV420p和YUV420sp * (格式见drawable) * 如图 * YUV420p:又叫planer平面模式,Y ,U,V分别再不同平面,也就是有三个平面。 * YUV420sp:又叫bi-planer或two-planer双平面,Y一个平面,UV在同一个平面交叉存储。 * <p> * 根据uv的存储顺序不同 * <p> * YUV420p 又细分:(这个是平面模式,所以yuv是存在三个数组中) * I420(又叫YU12): 安卓的模式。存储顺序是先存Y,再存U,最后存V。yyyyyyyyuuvv(4个y公用一个u和v) * YV12:存储顺序是先存Y,再存V,最后存U。yyyyyyyyvvuu * <p> * YUV420sp又分为 (这个是uv交错) * NV12:IOS只有这一种模式。存储顺序是先存Y,再UV交替存储。yyyyyyyyuvuv * NV21:安卓的模式。存储顺序是先存Y,再存U,再VU交替存储。yyyyyyyyvuvu * <p> * 所以一个yuv420图片大小计算的方法是 * 一个像素大小= 1byte y + 0.25(2/8) byte的 u 和0.25byte的v =1.5byte * 所以 height*width*1.5byte就是这个帧的大小了 * <p> * * 常用的YUV存储(采样)格式(平面格式) 有I420(4:2:0)、YV12、IYUV等(具体的存储格式) * 4:4:4表示完全取样。 * 4:2:2表示2:1的水平取样,垂直完全采样。(具体见drawable) * 4:2:0表示2:1的水平取样,垂直2:1采样。 * 4:1:1表示4:1的水平取样,垂直完全采样。 * <p> * DVD-Video是以YUV 4:2:0的方式记录,也就是我们俗称的I420 * <p> * https://www.jianshu.com/p/e67f79f10c65(图片表示) * <p> * * */ void f3() {} /** * ===============视频编码============ * yuv格式的视频还是很大,而且冗余信息很多,比如上一帧和这一帧只有一个像素点颜色不同, * 那么这一帧就不需要存其他像素点的信息了。 * * 而且不压缩的数据非常大,使得存储和传输变为不可接受 * 所以要制定一套视频压缩(编码)标准是很有必要的。 * * 提到视频编码标准,先介绍几个制定标准的组织 * -----------ITU(国际电信联盟)------------- * * ITU 国际电信联盟 International Telecommunication Union * * VCEG video coding expert group 是ITU下的子组织(工作组) * *1865年5月17日,为了顺利实现国际电报通信,法、德、俄、意、奥等20个欧洲国家的代表在巴黎签订了《国际电报公约》,国际电报联盟(International Telegraph Union ,ITU)也宣告成立。 * 随着电话与无线电的应用与发展,ITU的职权不断扩大。 * * 1906年,德、英、法、美、日等27个国家的代表在柏林签订了《国际无线电报公约》。 * 1932年,70多个国家的代表在西班牙马德里召开会议,将《国际电报公约》与《国际无线电报公约》合并, 制定《国际电信公约》,并决定自1934年1月1日起正式改称为“国际电信联盟” ,也就是现在的ITU。 * ITU是联合国下属的一个专门机构,其总部在瑞士的日内瓦。 * * ITU下属有三个部门,分别是ITU-R(前身是国际无线电咨询委员会CCIR)、ITU-T(前身是国际电报电话咨询委员会CCITT)、ITU-D * ITU-R 无线电通信部门 * ITU-T 电信标准化部门 * ITU-D 电信发展部门 * * * ------------MPEG Moving Picture Expert Group(动态图像专家组)------------- * * * 除了ITU之外,另外两个和视频编码关系密切的组织,是ISO/IEC * ISO大家都知道,就是推出ISO9001质量认证的那个“国际标准化组织”。IEC,是“国际电工委员会”。 * * 1988年,ISO和IEC联合成立了一个专家组,负责开发电视图像数据和声音数据的编码、解码和它们的同步等标准。 * 这个专家组,就是大名鼎鼎的MPEG,Moving Picture Expert Group(动态图像专家组)。 * * ISO international organization for standardization (国际标准化组织) * IEC 国际电工委员会 * MPEG moving picture expert group 移动图像专家组,是iso/IEC下的一个工作组 * 几百名成员组成,专门负责 音频视频 编码标准制定的工作 * * -------------Video coding format(视频编码格式) /编码标准---------- * * 三十多年以来,世界上主流的视频编码标准,基本上都是它们提出来的。 * ITU提出了H.261、H.262、H.263、H.263+、H.263++,这些统称为H.26X系列,主要应用于实时视频通信领域,如会议电视、可视电话等 * * ISO/IEC提出了MPEG1、MPEG2、MPEG4、MPEG7、MPEG21,统称为MPEG系列 * * ITU和ISO/IEC一开始是各自捣鼓,后来,两边成立了一个联合小组,名叫JVT(Joint Video Team,视频联合工作组) * * JVT致力于新一代视频编码标准的制定,后来推出了包括H.264在内的一系列标准。 * * 时间线见 video_encode_timeline.jpg * * * * 1.H.262 or MPEG-2 Part 2 = MPEG-2 Part 2 = H.262 * <p> * 2.MPEG-4 Part 2 = 兼容H.263 * <p> * 3.AVC Advanced Video Coding = H.264 or MPEG-4 Part 10 = MPEG-4 AVC =H.264 AVC (这是MPEG组织和ITU-T组织联合定义的) * <p> * 4.High Efficiency Video Coding (HEVC) = H.265 and MPEG-H Part 2 = H.265 = MPEG-H Part 2 * * * MPEG组织,他们制定了 * · MPEG-1 (这个组织在1990年制定的第一个视频 和音频 压缩(编码)标准) 用于CD 、VCD * <p> * · MPEG-2 也叫"ISO/IEC 13818-2" 94年制定的第二个版本,用于DVD * <p> * · MPEG-3 本来是用于为HDTV(High Definition Television 高清电视)制定的压缩标准, * 但后来发现MPEG-2就足以满足需求,所以就合并到MPEG-2中了,其实没有MPEG-3的叫法 * <p> * · MPEG-4 99年制定,用于网络流媒体 * · MPEG-7 ??? * · MPEG-21 正在开发? * · MPEG-H ?? * <p> * 每个MPEG-xxx都由很多部分(part)组成,每个部分定义了不同的规则 * 比如MP3压缩规则是在MPEG-1 Layer 3 中定义的 * 当然后来有改进 MPEG-1 or MPEG-2 Audio Layer III 是一种音频编码 ,有损压缩 * * * ITU-T 是ITU下的一个部门,他下的一个叫VCEG的工作组制定了音频视频编码标准 * H.261 * H.262 就是MPEG-2 的视频部分 * H.263 * H.264 其实就是 MPEG-4 part 10 ,AVC 这个VCEG和MPEG一起制定的,只不过他们的叫法不一样,就像圣西罗和煤阿茶 * H.265 就是MPEG-H 的第二部分 ,他们内容一样,叫法不一样 * * * * */ void f4(){} /** * ================视频编码原理=========== * 具体可以参考《深入理解视频编解码技术——基于H.264标准及参考模型》 * * 要实现压缩,就要设计各种算法,将视频数据中的冗余信息去除 * 如果一段1分钟的视频,有十几秒画面是不动的,或者,有80%的图像面积,整个过程都是不变(不动)的。那么,是不是这块存储开销,就可以节约掉了? * 是的,所谓编码算法,就是寻找规律,构建模型。谁能找到更精准的规律,建立更高效的模型,谁就是厉害的算法。 * 通常来说,视频里面的冗余信息包括: 见 video_encode_content.jpg 和 video_encode_example.jpg * * 空间冗余,这一块的像素区域颜色都是一样的,而且和上一个区域也是一样的 * 时间冗余,这一帧和上一帧有很大部分像素都是一样的 * * 视频编码技术优先消除目标,就是空间冗余和时间冗余。 * * 所以把这些帧分为三类,分别是I帧,B帧,P帧。 * I帧,是自带全部信息的独立帧,是最完整的画面(占用的空间最大),无需参考其它图像便可独立进行解码。视频序列中的第一个帧,始终都是I帧。 * P帧,“帧间预测编码帧”,需要参考前面的I帧和/或P帧的不同部分,才能进行编码。P帧对前面的P和I参考帧有依赖性。但是,P帧压缩率比较高,占用的空间较小 * B帧,“双向预测编码帧”,以前帧和后作为参考帧。不仅参考前面,还参考后面的帧,所以,它的压缩率最高,可以达到200:1。不过,因为依赖后面的帧,所以不适合实时传输(例如视频会议) * * 见:video_encode_frame.jpg * * 我们可以用软件查看帧的信息,它里面有标明这一帧是哪种类型的帧 * * 对I帧的处理,是采用帧内编码方式,只利用本帧图像内的空间相关性。 流程见 video_encode_flow_based_one_frame.jpg * (帧内编码就是只根据本帧的数据去除冗余) * 对P帧的处理,采用帧间编码(前向运动估计),同时利用空间和时间上的相关性。简单来说,采用运动补偿(motion compensation)算法来去掉冗余信息。 * (帧间编码就是本帧根据上一帧的数据去除冗余) * * ==========视频压缩编码的主要原理=== * 帧内编码(变换编码和熵编码):像素点之间存在相关性。图像变换到频域可以实现去相关和能量集中。 * 帧间编码(运动估计和运动补偿):将图像划分为一个个小区块,进行预测。 * */ void f5(){} /** * ===============音频编码================= * 音频编码规则 * ACC Advanced Audio Coding 97年由杜比实验室、AT&T、Sony、Nokia 共同研发 * 基于MPEG-2 所以又叫 MPEG-2 ACC * 后来2000年MPEG-4标准出现后,经过改良 成为 MPEG-4 ACC * <p> * MP1 MPEG-1 Audio Layer I 是mp2的简化,它不用很复杂的压缩算法(计算快),但是压缩率比较低,现在几乎都不支持这个格式 .mp1 * MP2 MPEG-1 Audio Layer II .mp2 这个压缩规则多用于广播 * MP3 MPEG-1 or MPEG-2 Audio Layer III 这个用于网络音乐(压缩率高) * <p> * 注意不要混淆MPEG-1 和MP3的关系,MPEG-1是一组规则,而MP3是MPEG-1中音频压缩规则的一种 * <p> * WMV 99年微软提出的音频编码格式 * * ACC /MPEG-1 Layer 3 /杜比数字(Dolby Digital),或称AC-3----音频编码规则 * * */ void f4_1(){} /** * ===============封装格式================== * 将已经编码压缩好的视频轨和音频轨按照一定的格式放到一个文件中 * 目前主要的视频容器有如下:MPG、VOB、MP4、3GP、ASF、RMVB、WMV、MOV、Divx、MKV、FLV、TS/PS等 * * MPEG制定的Container Format((视频的) 封装格式/(放置视频的)容器格式) * 有.mp4 .mpg .mpeg * <p> * 当然还有其他组织/公司制定的container format * 比如苹果的 .mov 微软的.avi realnetworks 的.rmvb adobe的.flv * <p> * container format 容器格式 封装格式 是定义编码后的视频和音频 如何存放的格式 * * * .mp4 .rmvb .avi .mkv .flv(flash video)--都是不同组织定义的封装视频的规则 * .mp3 .acc .ogg --封装音频规则 * * */ void f6(){} /** * ===========flv封装格式=============== * http://www.mamicode.com/info-detail-422904.html 如何实现一个c/s模式的flv视频点播系统 * https://www.cnblogs.com/chyingp/p/flv-getting-started.html FLV 5分钟入门浅析 * 见flv_box.jpg * * FLV (Flash Video) 是 Adobe 公司推出的另一种视频格式,是一种在网络上传输的流媒体数据存储容器格式。 * 其格式相对简单轻量,不需要很大的媒体头部信息。整个 FLV 由 The FLV Header, The FLV Body 以及其它 Tag 组成。 * 因此加载速度极快。采用 FLV 格式封装的文件后缀为 .flv。 * * 而我们所说的 HTTP-FLV 即将流媒体数据封装成 FLV 格式,然后通过 HTTP 协议传输给客户端。 * * 是一种专门用来在网络上传输的视频存储容器格式。 * 其格式相对简单,不需要很大的媒体头部信息,因此加载速度极快。国内各大视频网站,均有采用FLV格式作为其点播、甚至直播的视频格式。 * FLV容器格式的主要特点是tag,整个FLV由Video Tag, Audio Tag以及其他Tag组成,没有映射表。 * * * * */ void f6_1(){} /** * ============mp4封装格式=================== * https://zhuanlan.zhihu.com/p/52842679 短视频宝贝=慢?阿里巴巴工程师这样秒开短视频。 * MP4目前被广泛用于封装h.264视频和AAC音频,是高清视频的代表 * * * * MP4(MPEG-4 Part 14)是一种常见的多媒体容器格式,它是在“ISO/IEC 14496-14”标准文件中定义的,属于MPEG-4的一部分, * 是“ISO/IEC 14496-12(MPEG-4 Part 12 ISO base media file format)”标准中所定义的媒体格式的一种实现(在H.264标准文档约14章位置), * 后者定义了一种通用的媒体文件结构标准。MP4是一种描述较为全面的容器格式,被认为可以在其中嵌入任何形式的数据, * 各种编码的视频、音频等都不在话下,不过我们常见的大部分的MP4文件存放的AVC(H.264)或MPEG-4(Part 2)编码的视频和AAC编码的音频。 * MP4格式的官方文件后缀名是“.mp4”,还有其他的以mp4为基础进行的扩展或者是阉割版的格式,如:M4V, 3GP, F4V等 * ———————————————— * 版权声明:本文为CSDN博主「码农突围」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 * 原文链接:https://blog.csdn.net/hejjunlin/article/details/73162841 * * mp4是由一个个“box”组成的,大box中存放小box,一级嵌套一级来存放媒体信息。box的基本结构如下: * * * ================具体格式==== * 见 mp4_box.jpg * * */ void f7(){} /** * ===================ffmepg==================== * * https://blog.csdn.net/leixiaohua1020/article/details/15811977 ([总结]FFMPEG视音频编解码零基础学习方法) * *FFmpeg是一个开源的跨平台音视频处理工具,它包含了一系列用于处理多媒体数据的库和工具,可以用于录制、转换和流式传输音视频内容。FFmpeg具有以下特点: * * 1. 功能丰富:FFmpeg支持多种音视频格式的编解码、转换和处理,包括但不限于MP4、AVI、FLV、MP3、AAC等。 * * 2. 跨平台:FFmpeg可以在多种操作系统上运行,包括Windows、macOS和Linux等。 * * 3. 灵活性:FFmpeg提供了丰富的命令行工具和API,可以满足各种音视频处理需求,如剪辑、合并、转码、添加水印等。 * * 4. 广泛应用:FFmpeg被广泛应用于音视频处理、流媒体服务、视频编辑软件、转码工具等领域。 * * 5. 开源:FFmpeg是一个开源项目,可以免费获取并在遵循其许可协议的情况下进行使用和修改。 * * 总的来说,FFmpeg是一个功能强大、灵活且广泛应用的音视频处理工具,为开发者和用户提供了丰富的多媒体处理能力。 * * * */ void f8(){} /** * ================android 播放器============= * https://www.jianshu.com/p/5345ab4cf979 (ijkplayer 源码分析(上)) * * AndroidMediaPlayer:即安卓系统自带的播放器 MediaPlayer,基于 MediaCodec、AudioTrack 等安卓系统 API. * IjkExoMediaPlayer:即谷歌新推出的 ExoPlayer,同样是基于 MediaCodec、AudioTrack 等安卓系统 API,但相比 MediaPlayer 具有支持 DASH、高级 HLS、自定义扩展等优点。 * IjkMediaPlayer:IjkPlayer 基于 FFmpeg 的 ffplay,集成了 MediaCodec 硬解码器、Opengl 渲染方式等。 * * * ===MediaCodec * MediaCodec 是一个用于音视频编解码的API,它允许开发者在Android设备上进行低延迟的音视频编解码操作 * * 如果你想使用 MediaCodec 来解码 MP4 文件,你需要使用 MediaExtractor 从 MP4 文件中提取音视频数据, * 然后使用 MediaCodec 进行解码。但这种方式相对复杂,一般情况下更推荐使用成熟的播放器来处理视频播放。 * * ==============ijkplayer播放流程======== * * ijkplayer播放主要流程 * * 根据链接的schema找到对应的URLProtocol。 * 如Http的链接,对应libavformat/http.c * 而http的请求后续会转换成Tcp的协议,对应libavformat/tcp.c * 进行DNS解析ip地址,并且解析完后进行缓存,以便下次复用 * 从链路中读取数据到Buffer * 有可能从tcp链路,也有可能从磁盘链路 * TCP链路则会需要等待三次握手的时间 * 读取Buffer进行文件类型的probe * 探测文件格式,判断是mp4,flv等等 * 读取Buffer的头部信息进行解析 * 解析文件头部,判断是否为该格式文件,如果失败则返回错误 * 解析audio,video,subtitle流 * 根据文件信息找到多媒体流 * 优先使用H264的视频流 * 根据流信息找到解码器 * 开启各个线程开始对各个流进行解码成packet * 同步到read_thread线程后,装入pakcetQueue中 * 在video_refresh_thread线程中,读取packetQueue中的包,进行时钟同步 * 开始绘制视频,播放音频内容 * * ==============秒开优化========== * https://cloud.tencent.com/developer/article/1357997 (IjkPlayer起播速度优化) * https://www.jianshu.com/p/843c86a9e9ad (IjkPlayer播放器秒开优化以及常用Option设置) * * 要实现网络视频的“秒开”优化,可以考虑以下几个方面的优化策略: * * 1. 视频编码格式:选择适合网络传输和快速解码的视频编码格式,如H.264。这样可以减小视频文件大小,提高网络传输速度,并且在解码时能够更快地展示视频画面。 * * 2. 视频预加载:在用户观看视频之前,可以提前加载视频的关键帧或部分视频数据,以便在用户点击播放时能够快速展示视频画面,从而实现“秒开”的效果。 * * 3. 视频流优化:使用适当的视频码率和分辨率,以确保视频能够在较低的网络带宽下也能够快速加载和播放。 * * 4. CDN 加速:利用内容分发网络(CDN)来加速视频的传输,将视频内容缓存在离用户较近的节点上,减小视频加载时间。 * * 5. 视频预缓存:在用户观看视频时,可以预先缓存一段时间的视频数据,以确保用户在观看过程中不会遇到卡顿和加载延迟。 * * 6. 逐帧渐进式加载:使用逐帧渐进式加载的方式,先加载视频的低清晰度画面,然后逐渐加载高清晰度画面,以实现快速展示视频画面。 * * 通过以上优化策略,可以有效提高网络视频的加载速度,实现“秒开”的效果,提升用户的观看体验。 * * ======surface texture * https://developer.android.google.cn/guide/topics/media/ui/playerview?hl=zh-cn * * 与 TextureView 相比,SurfaceView 在视频播放方面具有多项优势: * * 在许多设备上显著降低功耗。 * 更准确的帧时间,带来更流畅的视频播放。 * 在符合条件的设备上支持更高质量的 HDR 视频输出。 * 支持播放受 DRM 保护的内容时的安全输出。 * 在提高界面层的 Android TV 设备上以完整显示屏分辨率呈现视频内容。 * 因此,应尽可能优先使用 SurfaceView,而非 TextureView。仅当 SurfaceView 无法满足您的需求时, * 才应使用 TextureView。 * 例如,在 Android 7.0(API 级别 24)之前,需要流畅的动画或视频界面滚动, * 如以下说明中所述。在这种情况下,最好仅在 SDK_INT 小于 24 (Android 7.0) 时使用 TextureView,否则使用 SurfaceView。 * * 在 Android 7.0(API 级别 24)之前,SurfaceView 渲染无法与视图动画正确同步。 * 在早期版本中,当 SurfaceView 被放入滚动容器或对其进行动画处理时,这可能会导致不必要的效果。 * 此类效果包括视图的内容显示稍微滞后于应显示的位置,以及在受到动画处理后视图变为黑色。 * 在 Android 7.0 之前,为了实现流畅的视频动画或滚动,需要使用 TextureView,而不是 SurfaceView。 * * * * ==============ijkplayer切换后台黑屏问题=========== * https://cloud.tencent.com/developer/article/1192700 (IJKPlayer问题集锦之不定时更新) * 暂停的时候,退到后台再回到前台,画面黑了? * * 1、这时候个人处理方式是,可以在暂停的时候,通过TextureView.getBitmap(point.x, point.y);获取到暂停的画面 * ,用ImageView显示它,在onSurfaceTextureUpdated的时候隐藏ImageView,来实现画面的衔接。 * 2、暂停时绘制静态画面多TextureView的Surface上,详细参考GSYVideoPlayer。 * */ void f9(){} /** * ================Android中音视频播放============== * 视频可以用 MediaCodec 进行硬解码 * 解码后用Android框架内置的OpenGL es框架进行播放?? * Android用SurfaceView来渲染视频帧。 * * https://www.jianshu.com/p/13320a8549db(用openGL ES+MediaPlayer 渲染播放视频+滤镜效果) * * * 音频用AudioTrack这个类可以直接播放pcm数据 * * * https://blog.csdn.net/moruihong/article/details/7739086 ( Android MediaPlayer的核心原理) * MediaPlayer在底层是基于OpenCore(PacketVideo)的库实现的 * OpenCorePlayer的实现libopencoreplayer.so * * */ void a10(){} /** * ========Android编码============ * https://cloud.tencent.com/developer/article/1006240 微信 Android 视频编码爬过的那些坑 * https://blog.csdn.net/u010126792/article/details/86580878 MediaCodec * https://www.jianshu.com/p/343d7e10cf6b Android MediaCodec * 硬编码: * 用设备GPU去实现编解码,这样可以减轻CPU的压力。 * 软编码: * 让CPU来进行编解码,在c层代码来进行编解码,因为c/c++有很多好的编解码库。 * * * =========== android.media.MediaCodec ============== * 在Android 4.1之前没有提供硬编解码的API,所以基本都是采用开源的那些库,比如著名的FFMpeg实现软编解码。 * 在Android4.1出来了一个新的API:MediaCodec可以支持硬编解码,MediaCodec可以支持对音频和视频的编解码. * * MediaCodec支持的视频格式有vp8 、VP9 、H.264、H.265、MPEG4、H.263等。 * MediaCodec支持的音频格式有3gpp、amr-wb、amr-wb、amr-wb、g711-A、g711-U 、AAC等。 * 类型: * “video/x-vnd.on2.vp8” - VP8 video (i.e. video in .webm) * “video/x-vnd.on2.vp9” - VP9 video (i.e. video in .webm) * “video/avc” - H.264/AVC video * “video/hevc” - H.265/HEVC video * “video/mp4v-es” - MPEG4 video * “video/3gpp” - H.263 video * “audio/3gpp” - AMR narrowband audio * “audio/amr-wb” - AMR wideband audio * “audio/amr-wb” - MPEG1/2 audio layer III * “audio/mp4a-latm” - AAC audio (note, this is raw AAC packets, not packaged in LATM!) * “audio/amr-wb” - vorbis audio * “audio/g711-alaw” - G.711 alaw audio * “audio/g711-mlaw” - G.711 ulaw audio * ———————————————— * 版权声明:本文为CSDN博主「lidongxiu0714」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 * 原文链接:https://blog.csdn.net/u010126792/article/details/86580878 * * ====== ffmpeg ============= * https://cloud.tencent.com/developer/article/1006240 微信 Android 视频编码爬过的那些坑 * 另外一种比较流行的方案就是使用ffmpeg+x264/openh264进行软编码,ffmpeg是用于一些视频帧的预处理。这里主要是使用x264/openh264作为视频的编码器。 * * * x264 基本上被认为是当今市面上最快的商用视频编码器,而且基本上所有h264的特性都支持,通过合理配置各种参数还是能够得到较好的压缩率和编码速度的, * * openh264 (https://github.com/cisco/openh264)则是由思科开源的另外一个h264编码器,项目在2013年开源,对比起x264来说略显年轻,不过由于思科支付满了h264的年度专利费,所以对于外部用户来说,相当于可以直接免费使用了,另外,firefox直接内置了openh264,作为其在webRTC中的视频的编解码器使用。 * * */ void a11(){} /** * ======android.media.MediaRecorder=== * 录制音频,视频。直接输出成文件, * 对于录制视频的需求,不少app都需要对每一帧数据进行单独处理,因此很少会直接用到MediaRecorder来直接录取视频 * * =====android.media.MediaMuxer ==== * 将 camera输出nv21用 mediacodec 编码为h264后,将audioRecord输出的pcm用mediacodec aac后,用MediaMuxer合并为mp4 * 是Android 4.3新增的API * Currently MediaMuxer supports MP4, Webm and 3GP file as the output * * */ void a12(){} }
pop1234o/BestPracticeApp
Video/src/main/java/com/liyafeng/video/Video.java
66,644
package com.lajigaga.MQ.JMS; import org.apache.activemq.ActiveMQConnectionFactory; import javax.jms.*; /** * Created by lajigaga on 2019/3/18 0018. * ActiveMQ是Apache软件基金下的一个开源软件, * 它遵循JMS1.1规范(Java Message Service),是消息驱动中间件软件(MOM)。 * 它为企业消息传递提供高可用,出色性能,可扩展,稳定和安全保障。 * * P2P (点对点)消息域使用 queue 作为 Destination,消息可以被同步或异步的发送和接收, * 每个消息只会给一个 Consumer 传送一次。 * * Pub/Sub(发布/订阅,Publish/Subscribe)消息域使用 topic 作为 Destination, * 发布者向 topic 发送消息,订阅者注册接收来自 topic 的消息。 * 发送到 topic 的任何消息都将自动传递给所有订阅者。 * 接收方式(同步和异步)与 P2P 域相同。 */ public class ActiveMQEasyDemo { /** * 消息生产者 */ public static void ActiveMQProducer(){ try { //创建session会话 ConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); //创建一个消息队列 session.createQueue("jms.test.topic")--P2P模式 Destination destination = session.createTopic("jms.test.topic"); //创建消息生产者 MessageProducer producer = session.createProducer(destination); //消息持久化 // producer.setDeliveryMode(DeliveryMode.PERSISTENT); for (int i = 0; i < 5; i++) { producer.send(session.createTextMessage("Message Producer:" + i)); } //提交会话 session.commit(); connection.close(); }catch (Exception e){ } } public static void ActiveMQConsumer() { try { //创建session会话 ConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_BROKER_URL); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); //创建一个消息队列 session.createQueue("jms.test.topic")--P2P模式 Destination destination = session.createTopic("jms.test.topic"); //创建消息消费者 MessageConsumer consumer = session.createConsumer(destination); while (true) { TextMessage message = (TextMessage) consumer.receive(); if (message != null) { System.out.println("Message Consumer:" + message.getText()); } else { break; } } session.commit(); } catch (Exception e) { } } public static void main(String[] args) { //TODO 本地安装ActiveMQ可以发消息,但在消费端接收消息时有问题 ActiveMQEasyDemo.ActiveMQProducer(); ActiveMQEasyDemo.ActiveMQConsumer(); } }
frede2010/interview
src/main/java/com/lajigaga/MQ/JMS/ActiveMQEasyDemo.java
66,645
package cn.rongcloud.im.im; import static android.content.Context.MODE_PRIVATE; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import cn.rongcloud.im.BuildConfig; import cn.rongcloud.im.R; import cn.rongcloud.im.SealApp; import cn.rongcloud.im.common.ErrorCode; import cn.rongcloud.im.common.IntentExtra; import cn.rongcloud.im.common.LogTag; import cn.rongcloud.im.common.NetConstant; import cn.rongcloud.im.common.ResultCallback; import cn.rongcloud.im.db.DBManager; import cn.rongcloud.im.im.message.GroupApplyMessage; import cn.rongcloud.im.im.message.GroupClearMessage; import cn.rongcloud.im.im.message.PokeMessage; import cn.rongcloud.im.im.message.SealContactNotificationMessage; import cn.rongcloud.im.im.message.SealGroupConNtfMessage; import cn.rongcloud.im.im.message.SealGroupNotificationMessage; import cn.rongcloud.im.im.message.SealUltraGroupNotificationMessage; import cn.rongcloud.im.im.plugin.ImageTextModule; import cn.rongcloud.im.im.plugin.InsertMessageModule; import cn.rongcloud.im.im.plugin.MentionAllModule; import cn.rongcloud.im.im.plugin.PokeExtensionModule; import cn.rongcloud.im.im.plugin.SendKVMessageModule; import cn.rongcloud.im.im.provider.ContactNotificationMessageProvider; import cn.rongcloud.im.im.provider.GroupApplyMessageItemProvider; import cn.rongcloud.im.im.provider.PokeMessageItemProvider; import cn.rongcloud.im.im.provider.SealGroupConNtfMessageProvider; import cn.rongcloud.im.im.provider.SealGroupNotificationMessageItemProvider; import cn.rongcloud.im.model.ChatRoomAction; import cn.rongcloud.im.model.ConversationRecord; import cn.rongcloud.im.model.LoginResult; import cn.rongcloud.im.model.ProxyModel; import cn.rongcloud.im.model.QuietHours; import cn.rongcloud.im.model.Resource; import cn.rongcloud.im.model.TranslationTokenResult; import cn.rongcloud.im.model.UserCacheInfo; import cn.rongcloud.im.net.AppProxyManager; import cn.rongcloud.im.net.CallBackWrapper; import cn.rongcloud.im.net.SealTalkUrl; import cn.rongcloud.im.net.proxy.RetrofitProxyServiceCreator; import cn.rongcloud.im.net.service.UserService; import cn.rongcloud.im.sp.UserCache; import cn.rongcloud.im.sp.UserConfigCache; import cn.rongcloud.im.task.AppTask; import cn.rongcloud.im.task.UserTask; import cn.rongcloud.im.ui.activity.ConversationActivity; import cn.rongcloud.im.ui.activity.ForwardActivity; import cn.rongcloud.im.ui.activity.GroupNoticeListActivity; import cn.rongcloud.im.ui.activity.GroupReadReceiptDetailActivity; import cn.rongcloud.im.ui.activity.MainActivity; import cn.rongcloud.im.ui.activity.MemberMentionedExActivity; import cn.rongcloud.im.ui.activity.NewFriendListActivity; import cn.rongcloud.im.ui.activity.PokeInviteChatActivity; import cn.rongcloud.im.ui.activity.SplashActivity; import cn.rongcloud.im.ui.activity.SubConversationListActivity; import cn.rongcloud.im.ui.activity.UserDetailActivity; import cn.rongcloud.im.ui.adapter.CombineV2MessageItemProvider; import cn.rongcloud.im.utils.DataCenter; import cn.rongcloud.im.utils.log.SLog; import com.google.gson.Gson; import io.rong.common.RLog; import io.rong.contactcard.ContactCardExtensionModule; import io.rong.contactcard.IContactCardInfoProvider; import io.rong.imkit.IMCenter; import io.rong.imkit.MessageInterceptor; import io.rong.imkit.config.ConversationClickListener; import io.rong.imkit.config.ConversationListBehaviorListener; import io.rong.imkit.config.DataProcessor; import io.rong.imkit.config.RongConfigCenter; import io.rong.imkit.conversation.extension.RongExtensionManager; import io.rong.imkit.conversation.messgelist.provider.GroupNotificationMessageItemProvider; import io.rong.imkit.conversationlist.model.BaseUiConversation; import io.rong.imkit.feature.mention.IExtensionEventWatcher; import io.rong.imkit.feature.mention.IMentionedInputListener; import io.rong.imkit.feature.mention.RongMentionManager; import io.rong.imkit.feature.quickreply.IQuickReplyProvider; import io.rong.imkit.manager.UnReadMessageManager; import io.rong.imkit.model.GroupNotificationMessageData; import io.rong.imkit.notification.RongNotificationManager; import io.rong.imkit.userinfo.RongUserInfoManager; import io.rong.imkit.userinfo.model.GroupUserInfo; import io.rong.imkit.utils.RouteUtils; import io.rong.imlib.ChannelClient; import io.rong.imlib.IRongCallback; import io.rong.imlib.IRongCoreCallback; import io.rong.imlib.IRongCoreEnum; import io.rong.imlib.IRongCoreListener; import io.rong.imlib.RongCoreClient; import io.rong.imlib.RongIMClient; import io.rong.imlib.chatroom.base.RongChatRoomClient; import io.rong.imlib.common.DeviceUtils; import io.rong.imlib.cs.CustomServiceConfig; import io.rong.imlib.cs.CustomServiceManager; import io.rong.imlib.model.AndroidConfig; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.ConversationIdentifier; import io.rong.imlib.model.Group; import io.rong.imlib.model.IOSConfig; import io.rong.imlib.model.InitOption; import io.rong.imlib.model.MentionedInfo; import io.rong.imlib.model.Message; import io.rong.imlib.model.MessageAuditInfo; import io.rong.imlib.model.MessageAuditType; import io.rong.imlib.model.MessageConfig; import io.rong.imlib.model.MessageContent; import io.rong.imlib.model.MessagePushConfig; import io.rong.imlib.model.RCIMProxy; import io.rong.imlib.model.RCTranslationResult; import io.rong.imlib.model.UltraGroupTypingStatusInfo; import io.rong.imlib.model.UserInfo; import io.rong.imlib.publicservice.model.PublicServiceProfile; import io.rong.imlib.translation.TranslationClient; import io.rong.imlib.translation.TranslationResultListener; import io.rong.message.CombineV2Message; import io.rong.message.ContactNotificationMessage; import io.rong.message.GroupNotificationMessage; import io.rong.push.PushEventListener; import io.rong.push.PushType; import io.rong.push.RongPushClient; import io.rong.push.RongPushPlugin; import io.rong.push.notification.PushNotificationMessage; import io.rong.recognizer.RecognizeExtensionModule; import io.rong.sight.SightExtensionModule; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class IMManager { private static volatile IMManager instance; private final String TAG = IMManager.class.getSimpleName(); private MutableLiveData<ChatRoomAction> chatRoomActionLiveData = new MutableLiveData<>(); private Context context; private AppTask appTask; private UserConfigCache configCache; private UserCache userCache; private MutableLiveData<Boolean> autologinResult = new MutableLiveData<>(); private MutableLiveData<Message> messageRouter = new MutableLiveData<>(); private MutableLiveData<Boolean> kickedOffline = new MutableLiveData<>(); private MutableLiveData<Boolean> userIsAbandon = new MutableLiveData<>(); private MutableLiveData<Boolean> userIsBlocked = new MutableLiveData<>(); /** 接收戳一下消息 */ private volatile Boolean isReceivePokeMessage = null; private IMInfoProvider imInfoProvider; private ConversationRecord lastConversationRecord; private List<IRongCoreListener.UltraGroupMessageChangeListener> mUltraGroupMessageChangeListener = new ArrayList<>(); private CopyOnWriteArrayList<IRongCoreListener.UserGroupStatusListener> mUserGroupStatusListeners = new CopyOnWriteArrayList<>(); private IMManager() { RongMentionManager.getInstance() .setMentionedInputListener( new IMentionedInputListener() { @Override public boolean onMentionedInput( Conversation.ConversationType conversationType, String targetId) { Intent intent = new Intent(getContext(), MemberMentionedExActivity.class); intent.putExtra( RouteUtils.CONVERSATION_TYPE, conversationType.getValue()); intent.putExtra(RouteUtils.TARGET_ID, targetId); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); return true; } }); } public static IMManager getInstance() { if (instance == null) { synchronized (IMManager.class) { if (instance == null) { instance = new IMManager(); } } } return instance; } public Context getContext() { return context; } /** @param application */ public void init(Application application) { RongCoreClient.getInstance().setAppVer(BuildConfig.VERSION_NAME); this.context = application.getApplicationContext(); appTask = new AppTask(this.context); // 初始化 IM 相关缓存 initIMCache(); // 初始化推送 initPush(); initPhrase(); initIMConfig(); // 调用 RongIM 初始化 initRongIM(application); initDebug(); initInterceptor(); // 初始化用户和群组信息内容提供者 initInfoProvider(context); // 初始化自定义消息和消息模版 initMessageAndTemplate(); // 初始化扩展模块 initExtensionModules(context); // 初始化连接状态变化监听 initConnectStateChangeListener(); // 初始化消息监听 initOnReceiveMessage(context); // 初始化聊天室监听 initChatRoomActionListener(); // 初始化超级群相关监听 initUltraGroup(); // 初始化翻译监听 initTranslationListener(); // 缓存连接 cacheConnectIM(); RongExtensionManager.getInstance() .addExtensionEventWatcher( new IExtensionEventWatcher() { @Override public void onTextChanged( Context context, Conversation.ConversationType type, String targetId, int cursorPos, int count, String text) {} @Override public void onSendToggleClick(Message message) { if (message != null && message.getContent() != null && message.getContent().getMentionedInfo() != null && message.getContent() .getMentionedInfo() .getMentionedUserIdList() != null && message.getContent() .getMentionedInfo() .getMentionedUserIdList() .size() > 0 && message.getContent() .getMentionedInfo() .getMentionedUserIdList() .get(0) .equals(String.valueOf(-1))) { message.getContent() .getMentionedInfo() .setType(MentionedInfo.MentionedType.ALL); } sendUltraGroupTypingStatus(message); } @Override public void onDeleteClick( Conversation.ConversationType type, String targetId, EditText editText, int cursorPos) {} @Override public void onDestroy( Conversation.ConversationType type, String targetId) {} }); } private void initInterceptor() { IMCenter.getInstance() .setMessageInterceptor( new MessageInterceptor() { @Override public boolean interceptReceivedMessage( Message message, int left, boolean hasPackage, boolean offline) { return false; } @Override public boolean interceptOnSendMessage(Message message) { // 推送配置测试相关 SharedPreferences sharedPreferences = context.getSharedPreferences("push_config", MODE_PRIVATE); String id = sharedPreferences.getString("id", ""); String title = sharedPreferences.getString("title", ""); String content = sharedPreferences.getString("content", ""); String data = sharedPreferences.getString("data", ""); String hw = sharedPreferences.getString("hw", ""); String hwImportance = sharedPreferences.getString("importance", "NORMAL"); String mi = sharedPreferences.getString("mi", ""); String oppo = sharedPreferences.getString("oppo", ""); String threadId = sharedPreferences.getString("threadId", ""); String apnsId = sharedPreferences.getString("apnsId", ""); String category = sharedPreferences.getString("category", ""); String richMediaUri = sharedPreferences.getString("richMediaUri", ""); String interruptionLevel = sharedPreferences.getString("interruptionLevel", ""); String fcm = sharedPreferences.getString("fcm", ""); String imageUrl = sharedPreferences.getString("imageUrl", ""); String hwCategory = sharedPreferences.getString("hwCategory", null); String vivoCategory = sharedPreferences.getString("vivoCategory", null); boolean vivo = sharedPreferences.getBoolean("vivo", true); boolean disableTitle = sharedPreferences.getBoolean("disableTitle", false); String templateId = sharedPreferences.getString("templateId", ""); boolean forceDetail = sharedPreferences.getBoolean("forceDetail", false); String imageUrlHW = sharedPreferences.getString("imageUrlHW", ""); String imageUrlMi = sharedPreferences.getString("imageUrlMi", ""); String fcmChannelId = sharedPreferences.getString("fcmChannelId", ""); String imageUrlHonor = sharedPreferences.getString("imageUrlHonor", ""); String importanceHonor = sharedPreferences.getString("importanceHonor", "NORMAL"); IOSConfig iosConfig = new IOSConfig(threadId, apnsId, category, richMediaUri); iosConfig.setInterruptionLevel(interruptionLevel); MessagePushConfig messagePushConfig = new MessagePushConfig.Builder() .setPushTitle(title) .setPushContent(content) .setPushData(data) .setForceShowDetailContent(forceDetail) .setDisablePushTitle(disableTitle) .setTemplateId(templateId) .setAndroidConfig( new AndroidConfig.Builder() .setNotificationId(id) .setChannelIdHW(hw) .setChannelIdMi(mi) .setChannelIdOPPO(oppo) .setTypeVivo( vivo ? AndroidConfig .SYSTEM : AndroidConfig .OPERATE) .setFcmCollapseKey(fcm) .setFcmImageUrl(imageUrl) .setImportanceHW( getImportance(hwImportance)) .setChannelIdFCM(fcmChannelId) .setImageUrlMi(imageUrlMi) .setImageUrlHW(imageUrlHW) .setCategoryHW(hwCategory) .setCategoryVivo(vivoCategory) .setImportanceHonor( AndroidConfig .ImportanceHonor .getImportanceHonor( importanceHonor)) .setImageUrlHonor(imageUrlHonor) .build()) .setIOSConfig(iosConfig) .build(); message.setMessagePushConfig(messagePushConfig); SharedPreferences sharedPreferencesPush = context.getSharedPreferences("MessageConfig", MODE_PRIVATE); boolean disableNotification = sharedPreferencesPush.getBoolean( "disableNotification", false); message.setMessageConfig( new MessageConfig.Builder() .setDisableNotification(disableNotification) .build()); message.getContent().setAuditInfo(getTestAuditInfo()); return false; } private MessageAuditInfo getTestAuditInfo() { SharedPreferences sharedPreferences = context.getSharedPreferences("audit_config", MODE_PRIVATE); int switchInt = sharedPreferences.getInt("switch", 0); String projectText = sharedPreferences.getString("project", ""); String strategyText = sharedPreferences.getString("strategy", ""); MessageAuditInfo messageAuditInfo = new MessageAuditInfo( MessageAuditType.valueOf(switchInt), projectText, strategyText); return messageAuditInfo; } @Override public boolean interceptOnSentMessage(Message message) { if (message != null) { message.setMessageConfig(null); } return false; } @Override public boolean interceptOnInsertOutgoingMessage( Conversation.ConversationType type, String targetId, Message.SentStatus sentStatus, MessageContent content, long time) { return false; } @Override public boolean interceptOnInsertIncomingMessage( Conversation.ConversationType type, String targetId, String senderId, Message.ReceivedStatus receivedStatus, MessageContent content, long time) { return false; } }); } private void initTranslationListener() { if (TranslationClient.getInstance().isTextTranslationSupported()) { TranslationClient.getInstance() .addTranslationResultListener( new TranslationResultListener() { @Override public void onTranslationResult( int code, RCTranslationResult result) { handleTranslationFailedEvent(code, result); } }); } } private void handleTranslationFailedEvent(int code, RCTranslationResult result) { if (code == IRongCoreEnum.CoreErrorCode.RC_TRANSLATION_CODE_INVALID_AUTH_TOKEN.code || code == IRongCoreEnum.CoreErrorCode.RC_TRANSLATION_CODE_AUTH_FAILED.code || code == IRongCoreEnum.CoreErrorCode.RC_TRANSLATION_CODE_SERVER_AUTH_FAILED .code) { updateJwtToken(); } } private void initUltraGroupMessageChangeListener() { ChannelClient.getInstance() .setUltraGroupMessageChangeListener( new IRongCoreListener.UltraGroupMessageChangeListener() { @Override public void onUltraGroupMessageExpansionUpdated( List<Message> messages) { if (messages == null) { return; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("扩展更新: "); for (Message message : messages) { stringBuilder.append(message.getUId()).append(","); } new Handler(Looper.getMainLooper()) .post( new Runnable() { @Override public void run() { // 此时已经回到主线程 Toast.makeText( context, stringBuilder.toString(), Toast.LENGTH_LONG) .show(); } }); RLog.e(TAG, "onUltraGroupMessageExpansionUpdated:" + stringBuilder); for (IRongCoreListener.UltraGroupMessageChangeListener l : mUltraGroupMessageChangeListener) { l.onUltraGroupMessageExpansionUpdated(messages); } } @Override public void onUltraGroupMessageModified(List<Message> messages) { if (messages == null) { return; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("消息修改:"); for (Message message : messages) { stringBuilder.append(message.getUId()).append(","); } new Handler(Looper.getMainLooper()) .post( new Runnable() { @Override public void run() { // 此时已经回到主线程 Toast.makeText( context, stringBuilder.toString(), Toast.LENGTH_LONG) .show(); } }); RLog.e(TAG, "onUltraGroupMessageModified:" + stringBuilder); for (IRongCoreListener.UltraGroupMessageChangeListener l : mUltraGroupMessageChangeListener) { l.onUltraGroupMessageModified(messages); } } @Override public void onUltraGroupMessageRecalled(List<Message> messages) { if (messages == null) { return; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("消息撤回:"); for (Message message : messages) { stringBuilder.append(message.getUId()).append(","); } new Handler(Looper.getMainLooper()) .post( new Runnable() { @Override public void run() { // 此时已经回到主线程 Toast.makeText( context, stringBuilder.toString(), Toast.LENGTH_LONG) .show(); } }); RLog.e(TAG, "onUltraGroupMessageRecalled:" + stringBuilder); for (IRongCoreListener.UltraGroupMessageChangeListener l : mUltraGroupMessageChangeListener) { l.onUltraGroupMessageRecalled(messages); } } }); } private void initUserGroupEventListener() { ChannelClient.getInstance() .setUserGroupStatusListener( new IRongCoreListener.UserGroupStatusListener() { @Override public void userGroupDisbandFrom( ConversationIdentifier identifier, String[] userGroupIds) { String users = Arrays.toString(userGroupIds); RLog.d(TAG, "userGroupDisbandFrom: " + identifier + "," + users); for (IRongCoreListener.UserGroupStatusListener listener : mUserGroupStatusListeners) { try { listener.userGroupDisbandFrom(identifier, userGroupIds); } catch (Exception e) { RLog.e(TAG, "userGroupDisbandFrom e: " + e); } } } @Override public void userAddedTo( ConversationIdentifier identifier, String[] userGroupIds) { String users = Arrays.toString(userGroupIds); RLog.d(TAG, "userAddedTo: " + identifier + "," + users); for (IRongCoreListener.UserGroupStatusListener listener : mUserGroupStatusListeners) { try { listener.userAddedTo(identifier, userGroupIds); } catch (Exception e) { RLog.e(TAG, "userAddedTo e: " + e); } } } @Override public void userRemovedFrom( ConversationIdentifier identifier, String[] userGroupIds) { String users = Arrays.toString(userGroupIds); RLog.d(TAG, "userRemovedFrom: " + identifier + "," + users); for (IRongCoreListener.UserGroupStatusListener listener : mUserGroupStatusListeners) { try { listener.userRemovedFrom(identifier, userGroupIds); } catch (Exception e) { RLog.e(TAG, "userRemovedFrom e: " + e); } } } @Override public void userGroupBindTo( ConversationIdentifier identifier, IRongCoreEnum.UltraGroupChannelType channelType, String[] userGroupIds) { String users = Arrays.toString(userGroupIds); RLog.d( TAG, "userGroupBindTo: " + identifier + "," + channelType + "," + users); for (IRongCoreListener.UserGroupStatusListener listener : mUserGroupStatusListeners) { try { listener.userGroupBindTo( identifier, channelType, userGroupIds); } catch (Exception e) { RLog.e(TAG, "userGroupBindTo e: " + e); } } } @Override public void userGroupUnbindFrom( ConversationIdentifier identifier, IRongCoreEnum.UltraGroupChannelType channelType, String[] userGroupIds) { String users = Arrays.toString(userGroupIds); RLog.d( TAG, "userGroupUnbindFrom: " + identifier + "," + channelType + "," + users); for (IRongCoreListener.UserGroupStatusListener listener : mUserGroupStatusListeners) { try { listener.userGroupUnbindFrom( identifier, channelType, userGroupIds); } catch (Exception e) { RLog.e(TAG, "userGroupUnbindFrom e: " + e); } } } }); } private void initUltraGroupConversationListener() { ChannelClient.getInstance() .setUltraGroupConversationListener( new IRongCoreListener.UltraGroupConversationListener() { @Override public void ultraGroupConversationListDidSync() { RLog.e(TAG, "ultraGroupConversationListDidSync"); } }); } public void addUltraGroupMessageChangeListener( IRongCoreListener.UltraGroupMessageChangeListener listener) { this.mUltraGroupMessageChangeListener.add(listener); } public void removeUltraGroupMessageChangeListener( IRongCoreListener.UltraGroupMessageChangeListener listener) { this.mUltraGroupMessageChangeListener.remove(listener); } public void addUserGroupStatusListener(IRongCoreListener.UserGroupStatusListener listener) { this.mUserGroupStatusListeners.add(listener); } public void removeUserGroupStatusListener(IRongCoreListener.UserGroupStatusListener listener) { this.mUserGroupStatusListeners.remove(listener); } private void initUltraGroupTyingStatusListener() { ChannelClient.getInstance() .setUltraGroupTypingStatusListener( infoList -> { if (infoList == null || infoList.isEmpty()) { return; } RLog.e(TAG, "onUltraGroupTypingStatusChanged: " + infoList.size()); for (UltraGroupTypingStatusInfo info : infoList) { StringBuilder infoString = new StringBuilder(); infoString .append(info.getTargetId()) .append(",") .append(info.getChannelId()) .append(",") .append(info.getUserId()); RLog.e(TAG, "onUltraGroupTypingStatusChanged: " + infoString); } }); } private void initUltraGroup() { // 初始化超级群已读状态监听 initUltraGroupReadStatusListener(); // 初始化超级群输入状态监听 initUltraGroupTyingStatusListener(); // 设置超级群消息变化监听 initUltraGroupMessageChangeListener(); // 初始化超级群会话监听 initUltraGroupConversationListener(); // 初始化用户组监听 initUserGroupEventListener(); } private void initUltraGroupReadStatusListener() { ChannelClient.getInstance() .setUltraGroupReadTimeListener( (targetId, channelId, time) -> { RLog.e( TAG, "onUltraGroupReadTimeReceived: " + targetId + "," + channelId + "," + time); ChannelClient.getInstance() .syncUltraGroupReadStatus( targetId, channelId, time, new IRongCoreCallback.OperationCallback() { @Override public void onSuccess() { RLog.e( TAG, "syncUltraGroupReadStatus success " + targetId + "," + channelId + "," + time); } @Override public void onError( IRongCoreEnum.CoreErrorCode coreErrorCode) { RLog.e( TAG, "syncUltraGroupReadStatus " + targetId + "," + channelId + "," + time + ",e:" + coreErrorCode); } }); }); } /** 缓存登录 */ public void cacheConnectIM() { if (RongIMClient.getInstance().getCurrentConnectionStatus() == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED) { autologinResult.setValue(true); return; } UserCacheInfo userCache = this.userCache.getUserCache(); if (userCache == null) { autologinResult.setValue(false); return; } String loginToken = this.userCache.getUserCache().getLoginToken(); if (TextUtils.isEmpty(loginToken)) { autologinResult.setValue(false); return; } connectIM( loginToken, true, true, new ResultCallback<String>() { @Override public void onSuccess(String s) { autologinResult.postValue(true); } @Override public void onFail(int errorCode) { RLog.e(TAG, "cacheConnectIM errorCode:" + errorCode); // 缓存登录时可以认为缓存了之前连接成功过的结果,所以当再次连接失败时可以通过 SDK 自动重连连接成功 if (ErrorCode.USER_ABANDON.getCode() == errorCode || ErrorCode.USER_BLOCKED.getCode() == errorCode) { autologinResult.postValue(false); } else { autologinResult.postValue(true); } } }); } public void evaluateCustomService( String targetId, int stars, CustomServiceConfig.CSEvaSolveStatus resolveStatus, String lables, String suggestion, String dialogId) { RongIMClient.getInstance() .evaluateCustomService( targetId, stars, resolveStatus, lables, suggestion, dialogId, null); } /** * 设置人工评价监听 当人工评价有标签等配置时,在回调中返回配置 * * @param listener */ public void setCustomServiceHumanEvaluateListener( CustomServiceManager.OnHumanEvaluateListener listener) { RongIMClient.getInstance().setCustomServiceHumanEvaluateListener(listener); } /** * 设置正在输入消息状态 * * @param listener */ public void setTypingStatusListener(RongIMClient.TypingStatusListener listener) { RongIMClient.setTypingStatusListener(listener); } /** * 获取从公众号信息 * * @param type * @param targetId * @param callback */ public void getPublicServiceProfile( Conversation.PublicServiceType type, String targetId, RongIMClient.ResultCallback<PublicServiceProfile> callback) { RongIMClient.getInstance() .getPublicServiceProfile( type, targetId, new RongIMClient.ResultCallback<PublicServiceProfile>() { @Override public void onSuccess(PublicServiceProfile publicServiceProfile) { if (callback != null) { callback.onSuccess(publicServiceProfile); } } @Override public void onError(RongIMClient.ErrorCode e) { if (callback != null) { callback.onError(RongIMClient.ErrorCode.valueOf(e.getValue())); } } }); } /** 初始化会话相关 */ private void initConversation() { RongConfigCenter.conversationConfig() .setConversationClickListener( new ConversationClickListener() { @Override public boolean onUserPortraitClick( Context context, Conversation.ConversationType conversationType, UserInfo user, String targetId) { if (conversationType != Conversation.ConversationType.CUSTOMER_SERVICE) { Intent intent = new Intent(context, UserDetailActivity.class); intent.putExtra(IntentExtra.STR_TARGET_ID, user.getUserId()); if (conversationType == Conversation.ConversationType.GROUP) { Group groupInfo = RongUserInfoManager.getInstance() .getGroupInfo(targetId); if (groupInfo != null) { intent.putExtra( IntentExtra.GROUP_ID, groupInfo.getId()); intent.putExtra( IntentExtra.STR_GROUP_NAME, groupInfo.getName()); } } context.startActivity(intent); } return true; } @Override public boolean onUserPortraitLongClick( Context context, Conversation.ConversationType conversationType, UserInfo user, String targetId) { return false; } @Override public boolean onMessageClick( Context context, View view, Message message) { // todo 二维码相关功能 // if (message.getContent() instanceof ImageMessage) // { // Intent intent = new Intent(view.getContext(), // SealPicturePagerActivity.class); // // intent.setPackage(view.getContext().getPackageName()); // intent.putExtra("message", message); // view.getContext().startActivity(intent); // return true; // } return false; } @Override public boolean onMessageLongClick( Context context, View view, Message message) { return false; } @Override public boolean onMessageLinkClick( Context context, String link, Message message) { return false; } @Override public boolean onReadReceiptStateClick( Context context, Message message) { if (message.getConversationType() == Conversation.ConversationType.GROUP) { // 目前只适配了群组会话 // 群组显示未读消息的人的信息 Intent intent = new Intent( context, GroupReadReceiptDetailActivity.class); intent.putExtra(IntentExtra.PARCEL_MESSAGE, message); context.startActivity(intent); return true; } return false; } }); } /** 初始化 IM 相关缓存 */ private void initIMCache() { // 用户设置缓存 sp configCache = new UserConfigCache(context.getApplicationContext()); userCache = new UserCache(context.getApplicationContext()); } /** 初始化会话列表相关事件 */ private void initConversationList() { Conversation.ConversationType[] supportedTypes = { Conversation.ConversationType.PRIVATE, Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM, Conversation.ConversationType.APP_PUBLIC_SERVICE, Conversation.ConversationType.PUBLIC_SERVICE, }; RouteUtils.registerActivity( RouteUtils.RongActivityType.ConversationActivity, ConversationActivity.class); RouteUtils.registerActivity( RouteUtils.RongActivityType.ForwardSelectConversationActivity, ForwardActivity.class); RouteUtils.registerActivity( RouteUtils.RongActivityType.SubConversationListActivity, SubConversationListActivity.class); RongConfigCenter.conversationListConfig() .setDataProcessor( new DataProcessor<Conversation>() { @Override public Conversation.ConversationType[] supportedTypes() { return supportedTypes; } @Override public List<Conversation> filtered(List<Conversation> data) { return data; } @Override public boolean isGathered(Conversation.ConversationType type) { if (type.equals(Conversation.ConversationType.SYSTEM)) { return true; } else { return false; } } }); RongConfigCenter.conversationListConfig() .setBehaviorListener( new ConversationListBehaviorListener() { @Override public boolean onConversationPortraitClick( Context context, Conversation.ConversationType conversationType, String targetId) { // 如果是群通知,点击头像进入群通知页面 if (targetId.equals("__group_apply__")) { Intent noticeListIntent = new Intent(context, GroupNoticeListActivity.class); context.startActivity(noticeListIntent); return true; } return false; } @Override public boolean onConversationPortraitLongClick( Context context, Conversation.ConversationType conversationType, String targetId) { return false; } @Override public boolean onConversationLongClick( Context context, View view, BaseUiConversation conversation) { return false; } @Override public boolean onConversationClick( Context context, View view, BaseUiConversation conversation) { /* * 当点击会话列表中通知添加好友消息时,判断是否已成为好友 * 已成为好友时,跳转到私聊界面 * 非好友时跳转到新的朋友界面查看添加好友状态 */ // MessageContent messageContent = // conversation.mCore.getLatestMessage(); // if (messageContent instanceof // ContactNotificationMessage) { // ContactNotificationMessage // contactNotificationMessage = (ContactNotificationMessage) // messageContent; // if // (contactNotificationMessage.getOperation().equals("AcceptResponse")) { // // 被加方同意请求后 // if // (contactNotificationMessage.getExtra() != null) { // ContactNotificationMessageData // bean = null; // try { // Gson gson = new Gson(); // bean = // gson.fromJson(contactNotificationMessage.getExtra(), // ContactNotificationMessageData.class); // } catch (Exception e) { // e.printStackTrace(); // } // Bundle bundle = new Bundle(); // // bundle.putString(RouteUtils.TITLE, bean.getSourceUserNickname()); // // RouteUtils.routeToConversationActivity(context, // conversation.mCore.getConversationType(), // conversation.mCore.getTargetId(), bundle); // } // } else { // context.startActivity(new // Intent(context, NewFriendListActivity.class)); // } // return true; // } else if (messageContent instanceof // GroupApplyMessage) { // Intent noticeListIntent = new // Intent(context, GroupNoticeListActivity.class); // // context.startActivity(noticeListIntent); // return true; // } return false; } }); RongConfigCenter.gatheredConversationConfig() .setConversationTitle( Conversation.ConversationType.SYSTEM, R.string.seal_conversation_title_system); } /** * 更新 IMKit 显示用用户信息 * * @param userId * @param userName * @param portraitUri */ public void updateUserInfoCache(String userId, String userName, Uri portraitUri, String alias) { UserInfo oldUserInfo = RongUserInfoManager.getInstance().getUserInfo(userId); if (oldUserInfo == null || (!oldUserInfo.getName().equals(userName) || oldUserInfo.getPortraitUri() == null || !oldUserInfo.getPortraitUri().equals(portraitUri)) || !TextUtils.equals(oldUserInfo.getAlias(), alias)) { UserInfo userInfo = new UserInfo(userId, userName, portraitUri); userInfo.setAlias(alias); RongUserInfoManager.getInstance().refreshUserInfoCache(userInfo); } } /** * 更新 IMKit 显示用群组信息 * * @param groupId * @param groupName * @param portraitUri */ public void updateGroupInfoCache(String groupId, String groupName, Uri portraitUri) { Group oldGroup = RongUserInfoManager.getInstance().getGroupInfo(groupId); if (oldGroup == null || (!oldGroup.getName().equals(groupName) || oldGroup.getPortraitUri() == null || !oldGroup.getPortraitUri().equals(portraitUri))) { Group group = new Group(groupId, groupName, portraitUri); RongUserInfoManager.getInstance().refreshGroupInfoCache(group); } } /** * 更新 IMKit 显示用群组成员信息 * * @param groupId * @param userId * @param nickName */ public void updateGroupMemberInfoCache(String groupId, String userId, String nickName) { GroupUserInfo oldGroupUserInfo = RongUserInfoManager.getInstance().getGroupUserInfo(groupId, userId); if (oldGroupUserInfo == null || (!oldGroupUserInfo.getNickname().equals(nickName))) { GroupUserInfo groupMemberInfo = new GroupUserInfo(groupId, userId, nickName); RongUserInfoManager.getInstance().refreshGroupUserInfoCache(groupMemberInfo); } } /** * 清除会话及消息 * * @param targetId * @param conversationType */ public void clearConversationAndMessage( String targetId, Conversation.ConversationType conversationType) { RongIMClient.getInstance() .getConversation( conversationType, targetId, new RongIMClient.ResultCallback<Conversation>() { @Override public void onSuccess(Conversation conversation) { IMCenter.getInstance() .cleanHistoryMessages( ConversationIdentifier.obtain( conversationType, targetId, ""), 0, false, new RongIMClient.OperationCallback() { @Override public void onSuccess() { IMCenter.getInstance() .removeConversation( conversationType, targetId, new RongIMClient .ResultCallback< Boolean>() { @Override public void onSuccess( Boolean aBoolean) {} @Override public void onError( RongIMClient .ErrorCode errorCode) {} }); } @Override public void onError( RongIMClient.ErrorCode errorCode) {} }); } @Override public void onError(RongIMClient.ErrorCode errorCode) {} }); } /** 初始化推送 */ private void initPush() { /* * 配置 融云 IM 消息推送 * 根据需求配置各个平台的推送 * 配置推送需要在初始化 融云 SDK 之前 */ RongPushPlugin.init(getContext()); RongPushClient.setPushEventListener( new PushEventListener() { @Override public boolean preNotificationMessageArrived( Context context, PushType pushType, PushNotificationMessage notificationMessage) { RLog.d(TAG, "preNotificationMessageArrived"); RongPushClient.recordPushArriveEvent( context, pushType, notificationMessage); return false; } @Override public void afterNotificationMessageArrived( Context context, PushType pushType, PushNotificationMessage notificationMessage) { RLog.d(TAG, "afterNotificationMessageArrived"); } @Override public boolean onNotificationMessageClicked( Context context, PushType pushType, PushNotificationMessage notificationMessage) { RLog.d(TAG, "onNotificationMessageClicked"); if (!notificationMessage .getSourceType() .equals(PushNotificationMessage.PushSourceType.FROM_ADMIN)) { String targetId = notificationMessage.getTargetId(); // 10000 为 Demo Server 加好友的 id,若 targetId 为 10000,则为加好友消息,默认跳转到 // NewFriendListActivity if (targetId != null && targetId.equals("10000")) { Intent intentMain = new Intent(context, NewFriendListActivity.class); intentMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Intent intentNewFriend = new Intent(context, MainActivity.class); intentNewFriend.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Intent[] intents = new Intent[] {}; intents[0] = intentMain; intents[1] = intentNewFriend; context.startActivities(intents); return true; } else { Intent intentMain = new Intent(context, SplashActivity.class); intentMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intentMain); return true; } } return false; } @Override public void onThirdPartyPushState( PushType pushType, String action, long resultCode) {} @Override public void onTokenReceived(PushType pushType, String token) { RLog.d( TAG, "onTokenReceived: pushType = " + pushType + ",token = " + token); } @Override public void onTokenReportResult( PushType reportType, int code, PushType finalType, String finalToken) { RLog.d( TAG, "onTokenReportResult: reportType = " + reportType + ",code = " + code + ",finalType = " + finalType + ",finalToken = " + finalToken); } }); } /** IM 配置 */ private void initIMConfig() { // 将私聊,群组加入消息已读回执 Conversation.ConversationType[] types = new Conversation.ConversationType[] { Conversation.ConversationType.PRIVATE, Conversation.ConversationType.GROUP, Conversation.ConversationType.ENCRYPTED }; RongConfigCenter.featureConfig().enableReadReceipt(types); // 配置会话列表界面相关内容 initConversationList(); // 配置会话界面 initConversation(); RongConfigCenter.featureConfig().enableDestruct(BuildConfig.DEBUG); } private void initPhrase() { if (appTask.isDebugMode()) { List<String> phraseList = new ArrayList<>(); phraseList.add( "1为了研究编译器的实现原理,我们需要使用 clang 命令。clang 命令可以将 Objetive-C 的源码改写成 C / C++ 语言的,借此可以研究 block 中各个特性的源码实现方式。该命令是为了研究编译器的实现原理,我们需要使用 clang "); phraseList.add( "clang 命令可以将 Objetive-C 的源码改写成 C / C++ 语言的,借此可以研究 block 中各个特性的源码实现方式。该命令是\",@\"2为了研究编译器的实现原理,我们需要使用 clang 命令"); phraseList.add( "clang 命令可以将 Objetive-C 的源码改写成 C / C++ 语言的,借此可以研究 block 中各个特性的源码实现方式\", @\"33333333\", @\"4超瓷晶的最大优势就是缺点很少但硬度很高\", @\"5苹果iPhone 12采用了一种新的保护玻璃涂层,名叫超瓷晶(Ceramic Shield)。官方称新机的防摔能力增强4倍,光学性能更加出色,更加防刮。考虑到之前iPhone的玻璃保护做得并不算好,如果这次真如苹果所说那么好,进步还是很明显的"); phraseList.add("6超瓷晶技术由康宁开发,利用超高温结晶制造工艺,他们将微小陶瓷纳米晶嵌入玻璃基体。晶体的连锁结构有助于让裂缝偏转。"); phraseList.add("45263573475"); phraseList.add("随后,康宁再用离子交换技术强化玻璃,本质上就是扩大离子尺寸,让结构更牢固"); RongConfigCenter.featureConfig() .enableQuickReply( new IQuickReplyProvider() { @Override public List<String> getPhraseList( Conversation.ConversationType type) { return phraseList; } }); } } /** 注册消息及消息模版 */ public void initMessageAndTemplate() { SLog.d("ss_register_message", "initMessageAndTemplate"); ArrayList<Class<? extends MessageContent>> myMessages = new ArrayList<>(); myMessages.add(SealGroupNotificationMessage.class); myMessages.add(SealUltraGroupNotificationMessage.class); myMessages.add(SealContactNotificationMessage.class); myMessages.add(SealGroupConNtfMessage.class); myMessages.add(GroupApplyMessage.class); myMessages.add(GroupClearMessage.class); myMessages.add(CombineV2Message.class); myMessages.add(PokeMessage.class); RongIMClient.registerMessageType(myMessages); RongConfigCenter.conversationConfig() .addMessageProvider(new ContactNotificationMessageProvider()); RongConfigCenter.conversationConfig().addMessageProvider(new PokeMessageItemProvider()); RongConfigCenter.conversationConfig() .addMessageProvider(new CombineV2MessageItemProvider()); RongConfigCenter.conversationConfig() .addMessageProvider(new SealGroupConNtfMessageProvider()); RongConfigCenter.conversationConfig() .addMessageProvider(new GroupApplyMessageItemProvider()); RongConfigCenter.conversationConfig() .replaceMessageProvider( GroupNotificationMessageItemProvider.class, new SealGroupNotificationMessageItemProvider()); } /** * 初始化扩展模块 * * @param context */ public void initExtensionModules(Context context) { RongExtensionManager.getInstance().setExtensionConfig(new SealExtensionConfig()); // 语音输入 RongExtensionManager.getInstance().registerExtensionModule(new RecognizeExtensionModule()); // 个人名片 RongExtensionManager.getInstance() .registerExtensionModule(createContactCardExtensionModule()); // 小视频 为了调整位置将此注册放入 SealExtensionModule 中进行,无此需求可直接在此注册 RongExtensionManager.getInstance().registerExtensionModule(new SightExtensionModule()); // 戳一下 RongExtensionManager.getInstance().registerExtensionModule(new PokeExtensionModule()); if (appTask.isDebugMode()) { // 图文消息 RongExtensionManager.getInstance().registerExtensionModule(new ImageTextModule()); // @所有人 RongExtensionManager.getInstance().registerExtensionModule(new MentionAllModule()); // 插入一条消息 RongExtensionManager.getInstance().registerExtensionModule(new InsertMessageModule()); // 发送一条KV消息 RongExtensionManager.getInstance().registerExtensionModule(new SendKVMessageModule()); } } /** * 调用初始化 RongIM * * @param application */ private void initRongIM(Application application) { /* * 如果是连接到私有云需要在此配置服务器地址 * 如果是公有云则不需要调用此方法 */ // RongIMClient.getInstance() // .setServerInfo(BuildConfig.SEALTALK_NAVI_SERVER, // BuildConfig.SEALTALK_FILE_SERVER); ProxyModel proxy = appTask.getProxy(); if (proxy != null) { AppProxyManager.getInstance() .setProxy( new RCIMProxy( proxy.getProxyHost(), proxy.getPort(), proxy.getUserName(), proxy.getPassword())); } /* * 初始化 SDK,在整个应用程序全局,只需要调用一次。建议在 Application 继承类中调用。 */ /* 若直接调用init方法请在 IMLib 模块中的 AndroidManifest.xml 中, 找到 <meta-data> 中 android:name 为 RONG_CLOUD_APP_KEY的标签, * 将 android:value 替换为融云 IM 申请的APP KEY */ // RongIM.init(this); RongCoreClient.getInstance().setReconnectKickEnable(true); // 可在初始 SDK 时直接带入融云 IM 申请的APP KEY DataCenter currentDataCenter = appTask.getCurrentDataCenter(); String appkey = currentDataCenter.getAppKey(); InitOption initOption = new InitOption.Builder() .setNaviServer(currentDataCenter.getNaviUrl()) .setFileServer(BuildConfig.SEALTALK_FILE_SERVER) .enablePush(true) .setAreaCode(currentDataCenter.getAreaCode()) .build(); IMCenter.init(application, appkey, initOption); SealTalkUrl.DOMAIN = currentDataCenter.getAppServer(); } /** 初始化信息提供者,包括用户信息,群组信息,群主成员信息 */ private void initInfoProvider(Context context) { imInfoProvider = new IMInfoProvider(); imInfoProvider.init(context); } /** * 创建个人名片模块 * * @return */ private ContactCardExtensionModule createContactCardExtensionModule() { return new ContactCardExtensionModule( new IContactCardInfoProvider() { /** * 获取所有通讯录用户 * * @param contactInfoCallback */ @Override public void getContactAllInfoProvider( IContactCardInfoCallback contactInfoCallback) { imInfoProvider.getAllContactUserInfo(contactInfoCallback); } /** * 获取单一用户 * * @param userId * @param name * @param portrait * @param contactInfoCallback */ @Override public void getContactAppointedInfoProvider( String userId, String name, String portrait, IContactCardInfoProvider.IContactCardInfoCallback contactInfoCallback) { imInfoProvider.getContactUserInfo(userId, contactInfoCallback); } }, (view, content) -> { Context activityContext = view.getContext(); // 点击名片进入到个人详细界面 Intent intent = new Intent(activityContext, UserDetailActivity.class); intent.putExtra(IntentExtra.STR_TARGET_ID, content.getId()); activityContext.startActivity(intent); }); } /** 初始化连接状态监听 */ private void initConnectStateChangeListener() { IMCenter.getInstance() .addConnectionStatusListener( new RongIMClient.ConnectionStatusListener() { @Override public void onChanged(ConnectionStatus connectionStatus) { SLog.d( LogTag.IM, "ConnectionStatus onChanged = " + connectionStatus.getMessage()); if (connectionStatus.equals( ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT)) { // 被其他提出时,需要返回登录界面 kickedOffline.postValue(true); } else if (connectionStatus == ConnectionStatus.TOKEN_INCORRECT) { // TODO token 错误时,重新登录 } else if (connectionStatus.equals(ConnectionStatus.USER_LOGOUT)) { userIsAbandon.postValue(true); } else if (connectionStatus.equals( ConnectionStatus.CONN_USER_BLOCKED)) { userIsBlocked.postValue(true); } } }); } private void initDebug() { if (appTask.isDebugMode()) { RongConfigCenter.featureConfig() .enableQuickReply( type -> { List<String> phraseList = new ArrayList<>(); phraseList.add( "1为了研究编译器的实现原理,我们需要使用 clang 命令。clang 命令可以将 Objetive-C 的源码改写成 C / C++ 语言的,借此可以研究 block 中各个特性的源码实现方式。该命令是为了研究编译器的实现原理,我们需要使用 clang "); phraseList.add( "clang 命令可以将 Objetive-C 的源码改写成 C / C++ 语言的,借此可以研究 block 中各个特性的源码实现方式。该命令是\",@\"2为了研究编译器的实现原理,我们需要使用 clang 命令"); phraseList.add( "clang 命令可以将 Objetive-C 的源码改写成 C / C++ 语言的,借此可以研究 block 中各个特性的源码实现方式\", @\"33333333\", @\"4超瓷晶的最大优势就是缺点很少但硬度很高\", @\"5苹果iPhone 12采用了一种新的保护玻璃涂层,名叫超瓷晶(Ceramic Shield)。官方称新机的防摔能力增强4倍,光学性能更加出色,更加防刮。考虑到之前iPhone的玻璃保护做得并不算好,如果这次真如苹果所说那么好,进步还是很明显的"); phraseList.add( "6超瓷晶技术由康宁开发,利用超高温结晶制造工艺,他们将微小陶瓷纳米晶嵌入玻璃基体。晶体的连锁结构有助于让裂缝偏转。"); phraseList.add("45263573475"); phraseList.add("随后,康宁再用离子交换技术强化玻璃,本质上就是扩大离子尺寸,让结构更牢固"); return phraseList; }); } } /** 初始化消息监听 */ private void initOnReceiveMessage(Context context) { IMCenter.getInstance() .addAsyncOnReceiveMessageListener( new RongIMClient.OnReceiveMessageWrapperListener() { @Override public boolean onReceived( Message message, int i, boolean hasPackage, boolean isOffline) { messageRouter.postValue(message); MessageContent messageContent = message.getContent(); String targetId = message.getTargetId(); if (messageContent instanceof ContactNotificationMessage) { // 添加好友状态信息 ContactNotificationMessage contactNotificationMessage = (ContactNotificationMessage) messageContent; if (contactNotificationMessage .getOperation() .equals("Request")) { } else if (contactNotificationMessage .getOperation() .equals("AcceptResponse")) { // 根据好友 id 进行获取好友信息并刷新 String sourceUserId = contactNotificationMessage.getSourceUserId(); imInfoProvider.updateFriendInfo(sourceUserId); } return true; } else if (messageContent instanceof GroupNotificationMessage) { // 群组通知消息 GroupNotificationMessage groupNotificationMessage = (GroupNotificationMessage) messageContent; SLog.d( LogTag.IM, "onReceived GroupNotificationMessage:" + groupNotificationMessage.getMessage()); String groupID = targetId; GroupNotificationMessageData data = null; try { String currentID = RongIMClient.getInstance().getCurrentUserId(); try { Gson gson = new Gson(); data = gson.fromJson( groupNotificationMessage.getData(), GroupNotificationMessageData.class); } catch (Exception e) { e.printStackTrace(); } if (groupNotificationMessage .getOperation() .equals("Create")) { // 创建群组,获取群组信息 imInfoProvider.updateGroupInfo(groupID); imInfoProvider.updateGroupMember(groupID); } else if (groupNotificationMessage .getOperation() .equals("Dismiss")) { // 被踢出群组,删除群组会话和消息 clearConversationAndMessage( groupID, Conversation.ConversationType.GROUP); imInfoProvider.deleteGroupInfoInDb(groupID); } else if (groupNotificationMessage .getOperation() .equals("Kicked")) { // 群组踢人 boolean isKicked = false; if (data != null) { List<String> memberIdList = data.getTargetUserIds(); if (memberIdList != null) { for (String userId : memberIdList) { if (currentID.equals(userId)) { // 被踢出群组,删除群组会话和消息 clearConversationAndMessage( groupID, Conversation.ConversationType .GROUP); imInfoProvider.deleteGroupInfoInDb( groupID); isKicked = true; break; } } } } // 如果未被提出,则更新群组信息和群成员 if (!isKicked) { imInfoProvider.updateGroupInfo(groupID); imInfoProvider.updateGroupMember(groupID); } } else if (groupNotificationMessage .getOperation() .equals("Add")) { // 群组添加人员 imInfoProvider.updateGroupInfo(groupID); imInfoProvider.updateGroupMember(groupID); } else if (groupNotificationMessage .getOperation() .equals("Quit")) { // 刷新退群列表 imInfoProvider.refreshGroupExitedInfo(groupID); // 退出群组,当非自己退出室刷新群组信息 if (!currentID.equals( groupNotificationMessage.getOperatorUserId())) { imInfoProvider.updateGroupInfo(groupID); imInfoProvider.updateGroupMember(groupID); } } else if (groupNotificationMessage .getOperation() .equals("Rename")) { // 群组重命名,更新群信息 if (data != null) { // 更新数据库中群组名称 String targetGroupName = data.getTargetGroupName(); imInfoProvider.updateGroupNameInDb( groupID, targetGroupName); } } else if (groupNotificationMessage .getOperation() .equals("Transfer")) { // 转移群主,获取群组信息 imInfoProvider.updateGroupInfo(groupID); imInfoProvider.updateGroupMember(groupID); } else if (groupNotificationMessage .getOperation() .equals("SetManager")) { // 设置管理员,获取群组信息 imInfoProvider.updateGroupInfo(groupID); imInfoProvider.updateGroupMember(groupID); } else if (groupNotificationMessage .getOperation() .equals("RemoveManager")) { // 移除管理员,获取群组信息 imInfoProvider.updateGroupInfo(groupID); imInfoProvider.updateGroupMember(groupID); } } catch (Exception e) { SLog.d( LogTag.IM, "onReceived process GroupNotificationMessage catch exception:" + e.getMessage()); e.printStackTrace(); } return true; } else if (messageContent instanceof GroupApplyMessage) { imInfoProvider.refreshGroupNotideInfo(); return true; } else if (messageContent instanceof PokeMessage) { PokeMessage pokeMessage = (PokeMessage) messageContent; if (getReceivePokeMessageStatus()) { // 显示戳一下界面 // 判断当前是否在目标的会话界面中 boolean isInConversation = false; ConversationRecord lastConversationRecord = IMManager.getInstance().getLastConversationRecord(); if (lastConversationRecord != null && targetId.equals( lastConversationRecord.targetId)) { isInConversation = true; } // 当戳一下的目标不在会话界面且在前台时显示戳一下界面 if (!isInConversation) { Intent showPokeIntent = new Intent( context, PokeInviteChatActivity.class); showPokeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); showPokeIntent.addFlags( Intent.FLAG_ACTIVITY_SINGLE_TOP); showPokeIntent.putExtra( IntentExtra.START_FROM_ID, message.getSenderUserId()); showPokeIntent.putExtra( IntentExtra.STR_POKE_MESSAGE, pokeMessage.getContent()); if (message.getConversationType() == Conversation.ConversationType.GROUP) { Group groupInfo = RongUserInfoManager.getInstance() .getGroupInfo(targetId); if (groupInfo != null) { showPokeIntent.putExtra( IntentExtra.STR_GROUP_NAME, groupInfo.getName()); } } showPokeIntent.putExtra( IntentExtra.SERIA_CONVERSATION_TYPE, message.getConversationType()); showPokeIntent.putExtra( IntentExtra.STR_TARGET_ID, targetId); /* * 判断是否在在前台,如果不在前台则下次进入 app 时进行弹出 * 再判断是否已进入到了主界面,反正拉取离线消息时再未进入主界面前弹出戳一下界面 */ if (SealApp.getApplication().isAppInForeground() && SealApp.getApplication() .isMainActivityCreated()) { context.startActivity(showPokeIntent); } else { // 若之前有未启动的戳一下消息则默认启动第一个戳一下消息 Intent lastIntent = SealApp.getApplication() .getLastOnAppForegroundStartIntent(); if (lastIntent == null || (lastIntent.getComponent() != null && !lastIntent .getComponent() .getClassName() .equals( PokeInviteChatActivity .class .getName()))) { SealApp.getApplication() .setOnAppForegroundStartIntent( showPokeIntent); } } } return true; } else { // 如果不接受戳一下消息则什么也不做 return true; } } else if (messageContent instanceof GroupClearMessage) { GroupClearMessage groupClearMessage = (GroupClearMessage) messageContent; SLog.i( "GroupClearMessage", groupClearMessage.toString() + "***" + message.getTargetId()); if (groupClearMessage.getClearTime() > 0) { IMCenter.getInstance() .cleanHistoryMessages( ConversationIdentifier.obtain(message), groupClearMessage.getClearTime(), true, null); } return true; } return true; } }); } /** * 设置通知消息免打扰 * * @param startTime * @param spanMinutes * @return */ public MutableLiveData<Resource<QuietHours>> setNotificationQuietHours( final String startTime, final int spanMinutes, boolean isCache) { MutableLiveData<Resource<QuietHours>> result = new MutableLiveData<>(); RongIMClient.getInstance() .setNotificationQuietHours( startTime, spanMinutes, new RongIMClient.OperationCallback() { @Override public void onSuccess() { RongNotificationManager.getInstance() .setNotificationQuietHours(startTime, spanMinutes, null); // 设置用户消息免打扰缓存状态 if (isCache) { configCache.setNotifiDonotDistrabStatus(getCurrentId(), true); configCache.setNotifiQuietHours( getCurrentId(), startTime, spanMinutes); result.setValue( Resource.success( configCache.getNotifiQUietHours( getCurrentId()))); } } @Override public void onError(RongIMClient.ErrorCode errorCode) { result.postValue( Resource.error(ErrorCode.IM_ERROR.getCode(), null)); } }); return result; } /** * 获取当前用户 id * * @return */ public String getCurrentId() { return RongIMClient.getInstance().getCurrentUserId(); } /** * 获取通知时间 * * @return */ public MutableLiveData<Resource<QuietHours>> getNotificationQuietHours() { MutableLiveData<Resource<QuietHours>> result = new MutableLiveData<>(); RongNotificationManager.getInstance() .getNotificationQuietHours( new RongIMClient.GetNotificationQuietHoursCallback() { @Override public void onSuccess(String s, int i) { QuietHours quietHours = new QuietHours(); quietHours.startTime = s; quietHours.spanMinutes = i; result.postValue(Resource.success(quietHours)); } @Override public void onError(RongIMClient.ErrorCode errorCode) { result.postValue( Resource.error(ErrorCode.IM_ERROR.getCode(), null)); } }); return result; } /** * 获取消息通知设置 * * @return */ public boolean getRemindStatus() { return configCache.getNewMessageRemind(getCurrentId()); } /** * 新消息通知设置 * * @param status */ public void setRemindStatus(boolean status) { if (status) { boolean donotDistrabStatus = configCache.getNotifiDonotDistrabStatus(getCurrentId()); if (!donotDistrabStatus) { removeNotificationQuietHours(); } } else { RongNotificationManager.getInstance().setNotificationQuietHours("00:00:00", 1439, null); } configCache.setNewMessageRemind(getCurrentId(), status); } /** * 清理通知免打扰 * * @return */ public MutableLiveData<Resource<Boolean>> removeNotificationQuietHours() { MutableLiveData<Resource<Boolean>> result = new MutableLiveData<>(); RongNotificationManager.getInstance() .removeNotificationQuietHours( new RongIMClient.OperationCallback() { @Override public void onSuccess() { // 设置用户消息免打扰缓存状态 configCache.setNotifiDonotDistrabStatus(getCurrentId(), false); result.postValue(Resource.success(true)); } @Override public void onError(RongIMClient.ErrorCode errorCode) { result.postValue( Resource.error(ErrorCode.IM_ERROR.getCode(), false)); } }); return result; } /** * 获取通知设置消息 * * @return */ public QuietHours getNotifiQuietHours() { return configCache.getNotifiQUietHours(getCurrentId()); } /** 初始化聊天室监听 */ public void initChatRoomActionListener() { RongChatRoomClient.setChatRoomAdvancedActionListener( new RongChatRoomClient.ChatRoomAdvancedActionListener() { @Override public void onJoining(String roomId) { chatRoomActionLiveData.postValue(ChatRoomAction.joining(roomId)); } @Override public void onJoined(String roomId) { chatRoomActionLiveData.postValue(ChatRoomAction.joined(roomId)); } @Override public void onReset(String roomId) { chatRoomActionLiveData.postValue(ChatRoomAction.reset(roomId)); } @Override public void onQuited(String roomId) { chatRoomActionLiveData.postValue(ChatRoomAction.quited(roomId)); } @Override public void onDestroyed( String chatRoomId, IRongCoreEnum.ChatRoomDestroyType type) { chatRoomActionLiveData.postValue(ChatRoomAction.destroyed(chatRoomId)); } @Override public void onError(String chatRoomId, IRongCoreEnum.CoreErrorCode code) { chatRoomActionLiveData.postValue(ChatRoomAction.error(chatRoomId, code)); } }); } /** * 获取聊天室行为状态 * * @return */ public LiveData<ChatRoomAction> getChatRoomAction() { return chatRoomActionLiveData; } /** 监听未读消息状态 */ public void addUnReadMessageCountChangedObserver( UnReadMessageManager.IUnReadMessageObserver observer, Conversation.ConversationType[] conversationTypes) { UnReadMessageManager.getInstance().addForeverObserver(conversationTypes, observer); } /** * 移除未读消息监听 * * @param observer */ public void removeUnReadMessageCountChangedObserver( UnReadMessageManager.IUnReadMessageObserver observer) { UnReadMessageManager.getInstance().removeForeverObserver(observer); } /** * 清理未读消息状态 * * @param conversationTypes 指定清理的会话类型 */ public void clearMessageUnreadStatus(Conversation.ConversationType[] conversationTypes) { RongIMClient.getInstance() .getConversationList( new RongIMClient.ResultCallback<List<Conversation>>() { @Override public void onSuccess(List<Conversation> conversations) { if (conversations != null && conversations.size() > 0) { for (Conversation c : conversations) { IMCenter.getInstance() .clearMessagesUnreadStatus( ConversationIdentifier.obtain(c), null); if (c.getConversationType() == Conversation.ConversationType.PRIVATE || c.getConversationType() == Conversation.ConversationType .ENCRYPTED) { RongIMClient.getInstance() .sendReadReceiptMessage( c.getConversationType(), c.getTargetId(), c.getSentTime(), new IRongCallback .ISendMessageCallback() { @Override public void onAttached( Message message) {} @Override public void onSuccess( Message message) {} @Override public void onError( Message message, RongIMClient.ErrorCode errorCode) {} }); } RongIMClient.getInstance() .syncConversationReadStatus( c.getConversationType(), c.getTargetId(), c.getSentTime(), null); } } } @Override public void onError(RongIMClient.ErrorCode e) {} }, conversationTypes); } private String getSavedReadReceiptTimeName( String targetId, Conversation.ConversationType conversationType) { String savedId = DeviceUtils.ShortMD5( RongIMClient.getInstance().getCurrentUserId(), targetId, conversationType.getName()); return "ReadReceipt" + savedId + "Time"; } /** * 自动重连结果 * * @return */ public LiveData<Boolean> getAutoLoginResult() { return autologinResult; } public MutableLiveData<Message> getMessageRouter() { return messageRouter; } /** 退出 */ public void logout() { IMCenter.getInstance().logout(); } /** 退出并清除缓存,等同于手动logout */ public void logoutAndClear() { IMCenter.getInstance().logout(); UserTask userTask = new UserTask(context); userTask.logout(); } /** * 是否登录状态 * * @return */ public boolean userIsLoginState() { UserCache userCache = new UserCache(context); return userCache.getUserCache() != null; } /** * 连接 IM 服务 * * @param token * @param autoConnect 是否在连接失败时无限时间自动重连 * @param cacheConnect 是否为缓存登录而做的IM连接 (true:只连接IM;false:主动操作,会在业务登录成功后再连接im) * @param callback */ public void connectIM( String token, boolean autoConnect, boolean cacheConnect, ResultCallback<String> callback) { if (autoConnect) { connectIM(token, cacheConnect, 0, callback); } else { connectIM(token, cacheConnect, NetConstant.API_IM_CONNECT_TIME_OUT, callback); } } /** * 连接 IM 服务 * * @param token * @param cacheConnect 是否为缓存登录而做的IM连接 (true:只连接IM;false:主动操作,会在业务登录成功后再连接im) * @param timeOut 自动重连超时时间。 * @param callback */ public void connectIM( String token, boolean cacheConnect, int timeOut, ResultCallback<String> callback) { /* * 考虑到会有后台调用此方法,所以不采用 LiveData 做返回值 */ IMCenter.getInstance() .connect( token, timeOut, new RongIMClient.ConnectCallback() { @Override public void onSuccess(String s) { // 连接 IM 成功后,初始化数据库 DBManager.getInstance(context).openDb(s); updateJwtToken(); // 如果是非缓存连接,既主动登录触发的连接,onSuccess才抛给上层 if (!cacheConnect) { if (callback != null) { callback.onSuccess(s); } } } public void onError(RongIMClient.ConnectionErrorCode errorCode) { SLog.e(LogTag.IM, "connect error - code:" + errorCode.getValue()); RLog.e(TAG, "connectIM errorCode:" + errorCode); if (errorCode == RongIMClient.ConnectionErrorCode .RC_CONN_TOKEN_INCORRECT) { if (callback != null) { callback.onFail(ErrorCode.IM_ERROR.getCode()); } } else if (errorCode == RongIMClient.ConnectionErrorCode.RC_CONN_USER_ABANDON) { callback.onFail(ErrorCode.USER_ABANDON.getCode()); } else if (errorCode == RongIMClient.ConnectionErrorCode.RC_CONN_USER_BLOCKED) { callback.onFail(ErrorCode.USER_BLOCKED.getCode()); } else { if (callback != null) { callback.onFail(ErrorCode.IM_ERROR.getCode()); } else { // do nothing } } } @Override public void onDatabaseOpened( RongIMClient.DatabaseOpenStatus databaseOpenStatus) { String currentUserId = RongIMClient.getInstance().getCurrentUserId(); DBManager.getInstance(context).openDb(currentUserId); // 如果是缓存连接,在onDatabaseOpened抛给上层 if (cacheConnect) { if (callback != null) { callback.onSuccess(currentUserId); } } } }); } private void updateJwtToken() { RLog.d(TAG, "updateJwtToken: "); if (!RongCoreClient.getInstance().isTextTranslationSupported()) { RLog.d(TAG, "updateJwtToken: not support translation"); return; } UserService service = RetrofitProxyServiceCreator.getRetrofitService(context, UserService.class); service.getTranslationToken(RongIMClient.getInstance().getCurrentUserId()) .observeForever( new Observer<TranslationTokenResult>() { @Override public void onChanged(TranslationTokenResult translationTokenResult) { if (translationTokenResult == null) { RLog.d(TAG, "updateJwtToken: translationTokenResult is null"); return; } RLog.d( TAG, "updateJwtToken: jwtToken = " + translationTokenResult.getToken()); TranslationClient.getInstance() .updateAuthToken(translationTokenResult.getToken()); } }); RongConfigCenter.featureConfig().rc_translation_src_language = appTask.getTranslationSrcLanguage(); RongConfigCenter.featureConfig().rc_translation_target_language = appTask.getTranslationTargetLanguage(); } /** * 获取用户 IM token 此接口需要在登录成功后可调用,用于在 IM 提示 token 失效时刷新 token 使用 * * @param callback */ private void getToken(ResultCallback<LoginResult> callback) { UserService userService = RetrofitProxyServiceCreator.getRetrofitService(context, UserService.class); /* * 考虑到会有后台调用此方法,所以不采用 LiveData 做返回值 */ userService.getToken().enqueue(new CallBackWrapper<>(callback)); } /** * 获取连接状态 * * @return */ public RongIMClient.ConnectionStatusListener.ConnectionStatus getConnectStatus() { return RongIMClient.getInstance().getCurrentConnectionStatus(); } /** * 被踢监听, true 为当前为被提出状态, false 为不需要处理踢出状态 * * @return */ public LiveData<Boolean> getKickedOffline() { return kickedOffline; } /** * 被踢销户, true 为当前为被销户状态, false 为不需要处理 * * @return */ public LiveData<Boolean> getUserIsAbandon() { return userIsAbandon; } /** * 封禁状态, true 为当前为被封禁状态, false 为不需要处理 * * @return */ public LiveData<Boolean> getUserIsBlocked() { return userIsBlocked; } /** 重置被提出状态为 false */ public void resetKickedOfflineState() { resetState(kickedOffline); } /** 重置销户状态 */ public void resetUserLogoutState() { resetState(userIsAbandon); } /** 重置封禁状态 */ public void resetUserBlockedState() { resetState(userIsBlocked); } /** 登录后重置状态 */ public void resetAfterLogin() { resetUserLogoutState(); resetUserBlockedState(); saveLoginDataCenter(); } private void saveLoginDataCenter() { appTask.saveDataCenter(appTask.getCurrentDataCenter()); } public void resetState(MutableLiveData<Boolean> state) { if (Looper.getMainLooper().getThread().equals(Thread.currentThread())) { state.setValue(false); } else { state.postValue(false); } } /** * 发送图片消息 * * @param conversationType * @param targetId * @param imageList * @param origin */ public void sendImageMessage( Conversation.ConversationType conversationType, String targetId, List<Uri> imageList, boolean origin) { // Todo // SendImageManager.getInstance().sendImages(conversationType, targetId, imageList, // origin); } /** * 获取是否接受戳一下消息 * * @return */ public boolean getReceivePokeMessageStatus() { if (isReceivePokeMessage == null) { // 第一次获取时 boolean receivePokeMessageStatus = configCache.getReceivePokeMessageStatus(getCurrentId()); imInfoProvider.refreshReceivePokeMessageStatus(); isReceivePokeMessage = receivePokeMessageStatus; } return isReceivePokeMessage; } /** * 更新是否接受戳一下消息状态 * * @param isReceive */ public void updateReceivePokeMessageStatus(boolean isReceive) { if (isReceivePokeMessage == null || isReceivePokeMessage != isReceive) { isReceivePokeMessage = isReceive; configCache.setReceivePokeMessageStatus(getCurrentId(), isReceive); } } /** 发送戳一下消息给单人 */ public void sendPokeMessageToPrivate( String targetId, String content, IRongCallback.ISendMessageCallback callback) { PokeMessage pokeMessage = PokeMessage.obtain(content); Message message = Message.obtain(targetId, Conversation.ConversationType.PRIVATE, pokeMessage); IMCenter.getInstance().sendMessage(message, null, null, callback); } /** * 发送戳一下消息给群组 * * @param targetId * @param content * @param userIds 发送目标用户 id,当为 null 时发给群内所有人 * @param callback */ public void sendPokeMessageToGroup( String targetId, String content, String[] userIds, IRongCallback.ISendMessageCallback callback) { PokeMessage pokeMessage = PokeMessage.obtain(content); if (userIds != null && userIds.length > 0) { IMCenter.getInstance() .sendDirectionalMessage( Conversation.ConversationType.GROUP, targetId, pokeMessage, userIds, null, null, callback); } else { Message message = Message.obtain(targetId, Conversation.ConversationType.GROUP, pokeMessage); IMCenter.getInstance().sendMessage(message, null, null, callback); } } /** * 记录最新的会话信息 * * @param targetId * @param conversationType */ public void setLastConversationRecord( String targetId, Conversation.ConversationType conversationType) { ConversationRecord record = new ConversationRecord(); record.targetId = targetId; record.conversationType = conversationType; lastConversationRecord = record; } /** 清除最后的会话信息 */ public void clearConversationRecord(String targetId) { if (lastConversationRecord != null && lastConversationRecord.targetId.equals(targetId)) { lastConversationRecord = null; } } /** * 获取最后的会话信息 * * @return */ public ConversationRecord getLastConversationRecord() { return lastConversationRecord; } /** * 设置推送消息通知是否显示信息 * * @param isDetail 是否显示通知详情 */ public LiveData<Resource<Boolean>> setPushDetailContentStatus(boolean isDetail) { MutableLiveData<Resource<Boolean>> result = new MutableLiveData<>(); RongIMClient.getInstance() .setPushContentShowStatus( isDetail, new RongIMClient.OperationCallback() { @Override public void onSuccess() { result.postValue(Resource.success(isDetail)); } @Override public void onError(RongIMClient.ErrorCode errorCode) { int errCode = ErrorCode.IM_ERROR.getCode(); if (errorCode == RongIMClient.ErrorCode.RC_NET_CHANNEL_INVALID || errorCode == RongIMClient.ErrorCode.RC_NET_UNAVAILABLE || errorCode == RongIMClient.ErrorCode .RC_NETWORK_IS_DOWN_OR_UNREACHABLE) { errCode = ErrorCode.NETWORK_ERROR.getCode(); } result.postValue(Resource.error(errCode, !isDetail)); } }); return result; } /** * 获取推送消息通知详情状态 * * @return Resource 结果为 success 时,data 值为当前是否为显示消息通知详情。 */ public LiveData<Resource<Boolean>> getPushDetailContentStatus() { MutableLiveData<Resource<Boolean>> result = new MutableLiveData<>(); RongIMClient.getInstance() .getPushContentShowStatus( new RongIMClient.ResultCallback<Boolean>() { @Override public void onSuccess(Boolean isDetail) { result.postValue(Resource.success(isDetail)); } @Override public void onError(RongIMClient.ErrorCode errorCode) { int errCode = ErrorCode.IM_ERROR.getCode(); if (errorCode == RongIMClient.ErrorCode.RC_NET_CHANNEL_INVALID || errorCode == RongIMClient.ErrorCode.RC_NET_UNAVAILABLE || errorCode == RongIMClient.ErrorCode .RC_NETWORK_IS_DOWN_OR_UNREACHABLE) { errCode = ErrorCode.NETWORK_ERROR.getCode(); } result.postValue(Resource.error(errCode, false)); } }); return result; } public AndroidConfig.ImportanceHW getImportance(String hwImportance) { if (!TextUtils.isEmpty(hwImportance) && TextUtils.equals(hwImportance, "LOW")) { return AndroidConfig.ImportanceHW.LOW; } return AndroidConfig.ImportanceHW.NORMAL; } public AppTask getAppTask() { return appTask; } private void sendUltraGroupTypingStatus(Message message) { if (appTask.isDebugMode()) { // 超级群测试代码 if (Conversation.ConversationType.ULTRA_GROUP.equals(message.getConversationType())) { ChannelClient.getInstance() .sendUltraGroupTypingStatus( message.getTargetId(), message.getChannelId(), IRongCoreEnum.UltraGroupTypingStatus.ULTRA_GROUP_TYPING_STATUS_TEXT, new IRongCoreCallback.OperationCallback() { @Override public void onSuccess() { new Handler(Looper.getMainLooper()) .post( () -> { // 此时已经回到主线程 Toast.makeText( getContext(), "发送超级群 Typing 状态成功", Toast.LENGTH_LONG) .show(); }); } @Override public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) { new Handler(Looper.getMainLooper()) .post( () -> { // 此时已经回到主线程 Toast.makeText( getContext(), "发送超级群 Typing 状态错误" + coreErrorCode .getValue(), Toast.LENGTH_LONG) .show(); }); } }); } } } }
rongcloud/sealtalk-android
sealtalk/src/main/java/cn/rongcloud/im/im/IMManager.java
66,646
package jz.cbq.work_buy_car.entity; import java.util.ArrayList; import java.util.List; import jz.cbq.work_buy_car.R; /** * 源数据提供者 */ public class DataService { /** * 根据 position 获取 list * * @param position position * @return list */ public static List<ProductInfo> getListData(int position) { List<ProductInfo> list = new ArrayList<>(); if (position == 0) { list.add(new ProductInfo(1, R.drawable.p_0_1, "夏季短袖T恤", "舒适透气的夏季短袖T恤,适合日常休闲穿着。", 39)); list.add(new ProductInfo(2, R.drawable.p_0_2, "牛仔裤", "经典款牛仔裤,适合各种场合穿着。", 119)); list.add(new ProductInfo(3, R.drawable.p_0_3, "连衣裙", "时尚简约的连衣裙,适合派对和约会穿着。", 89)); list.add(new ProductInfo(4, R.drawable.p_0_4, "运动裤", "舒适透气的运动裤,适合运动和健身穿着。", 79)); list.add(new ProductInfo(5, R.drawable.p_0_5, "风衣", "时尚简约的风衣,适合春秋季节穿着。", 189)); } else if (position == 1){ list.add(new ProductInfo(101, R.drawable.p_1_1, "智能手机", "高性能智能手机,配置强大,拍照效果出色。", 1999)); list.add(new ProductInfo(102, R.drawable.p_1_2, "平板电脑", "轻薄便携的平板电脑,适合娱乐和办公使用。", 1299)); list.add(new ProductInfo(103, R.drawable.p_1_3, "耳机", "高音质蓝牙耳机,舒适佩戴,适合运动和旅行。", 188)); list.add(new ProductInfo(104, R.drawable.p_1_4, "智能手表", "功能强大的智能手表,支持健康监测和智能通知。", 599)); }else if (position == 2){ list.add(new ProductInfo(1001, R.drawable.p_2_1, "保温杯", "不锈钢保温杯,保温效果好,容量适中。", 59)); list.add(new ProductInfo(1002, R.drawable.p_2_2, "电风扇", "静音电风扇,风力强劲,适合夏季使用。", 139)); list.add(new ProductInfo(1003, R.drawable.p_2_3, "洗衣液", "高效去污的洗衣液,衣物清洁彻底。", 29)); }else if (position == 3){ list.add(new ProductInfo(10001, R.drawable.p_3_1, "经典硬皮笔记本", "经典款式的硬皮笔记本,尺寸适中,方便携带。", 15)); list.add(new ProductInfo(10002, R.drawable.p_3_2, "文具套装", "包含铅笔、橡皮、尺子等文具的套装。", 19)); list.add(new ProductInfo(10003, R.drawable.p_3_3, "书包", "时尚耐用的书包,适合学生使用。", 99)); } return list; } }
CaoBaoQi/homework-android
work-buy-car/src/main/java/jz/cbq/work_buy_car/entity/DataService.java
66,648
package cn.lanink.huntgame.utils.update; import cn.lanink.gamecore.utils.VersionUtils; import cn.lanink.huntgame.HuntGame; import cn.nukkit.utils.Config; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.jetbrains.annotations.NotNull; import java.util.*; /** * @author LT_Name */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ConfigUpdateUtils { public static void updateConfig() { update1_X_X_To_1_2_2(); update1_2_2_To_1_3_0(); update1_3_0_To_1_3_1(); } @NotNull private static Config getConfig() { return new Config(HuntGame.getInstance().getDataFolder() + "/config.yml", Config.YAML); } private static void update1_3_0_To_1_3_1() { Config config = getConfig(); if (VersionUtils.compareVersion(config.getString("ConfigVersion", "1.0.0"), "1.3.1") >= 0) { return; } config.set("ConfigVersion", "1.3.1"); if (!config.exists("AutomaticJoinGame")) { config.set("AutomaticJoinGame", false); } config.save(); } private static void update1_2_2_To_1_3_0() { Config config = getConfig(); if (VersionUtils.compareVersion(config.getString("ConfigVersion", "1.0.0"), "1.3.0") >= 0) { return; } config.set("ConfigVersion", "1.3.0"); if (!config.exists("victoryRewardCmd")) { HashMap<String, List<String>> map = new HashMap<>(); map.put("0", Collections.singletonList("tell \"@p\" 参与奖!&con")); map.put("60", Collections.singletonList("tell \"@p\" 表现良好!&con")); map.put("121", Arrays.asList("tell \"@p\" 表现出色!&con", "me I am the best")); config.set("victoryRewardCmd", map); } config.save(); } private static void update1_X_X_To_1_2_2() { Config config = getConfig(); if (VersionUtils.compareVersion(config.getString("ConfigVersion", "1.0.0"), "1.2.2") >= 0) { return; } config.set("ConfigVersion", "1.2.2"); LinkedHashMap<String, Integer> map = config.get("integral", new LinkedHashMap<>()); if (!map.containsKey("complete_game")) { map.put("complete_game", 100); } if (!map.containsKey("prey_taunt_safe")) { map.put("prey_taunt_safe", 1); } if (!map.containsKey("prey_taunt_danger")) { map.put("prey_taunt_danger", 2); } if (!map.containsKey("prey_taunt_fireworks")) { map.put("prey_taunt_fireworks", 3); } if (!map.containsKey("prey_taunt_lightning")) { map.put("prey_taunt_lightning", 5); } if (!map.containsKey("hunter_kill_prey")) { map.put("hunter_kill_prey", 100); } if (!map.containsKey("prey_bow_hit_hunter")) { map.put("prey_bow_hit_hunter", 10); } config.set("integral", map); config.save(); } }
MemoriesOfTime/HuntGame
src/main/java/cn/lanink/huntgame/utils/update/ConfigUpdateUtils.java
66,649
package com.asiainfo.chapter1.dongwenchao.day08; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Created by 超超 on 2017/8/2 0002. */ public class demo3 { public demo3(){ String s="董稳超,有志者事竟成!置的集合元素。(*****自己理解:定义一个数组,可以在数组里实现增删改查,只要定义一个对象List books = new ArrayList();*****) LinkedList与ArrayList、Vector的实现机制完全不同,ArrayList、Vector内部以数组的形式来保存集合中的元素,因此随机访问集合元素上有较好的性能;而LinkedList内部以链表的形式来保存集合中的元素,因此随机访问集合时性能较差,但在插入、删除元素时性能非常出色(只需改变指针所指的地址即可)。Vector因实现了线程同步功能,所以各方面性能有所下降。 Set集合不允许重复元素,是因为Set判断两个对象相同不是使用==运算符,而是根据equals方法。即两个对象用equals方法比较返回true,Set就不能接受两个对象。(Set<String> books = new HashSet<String>();这是Map的) Treeset主要是对象比较排序用compareTo(Object"; byte[] b=s.getBytes(); try{ FileOutputStream f=new FileOutputStream("文件.txt"); f.write(b); f.flush();//将缓存的内容强制输出 f.close(); }catch (IOException e){ System.out.println(e); e.printStackTrace(); } } public static void main(String []args){ new demo3(); } }
luomin23/study
src/main/java/com/asiainfo/chapter1/dongwenchao/day08/demo3.java
66,650
package com.geniusmart.two; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.util.Log; import com.geniusmart.R; import com.geniusmart.one.Employee; public class HandlerThreadActivity2 extends Activity { public static final String TAG = "geniusmart"; //老张你好 Thread mCEO = Thread.currentThread(); //总监你好 Handler mCTOHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what){ case Employee.ZHEGNWEI: Message message = Message.obtain(); message.what = Employee.CTO; message.obj = "表现异常出色,这个月的绩效名额会适当倾斜"; //向政委发送消息(实现了主线程->HandlerThread的通讯) mZhengWeiHandler.sendMessage(message); break; } } }; //团长你好 HandlerThread mTuanZhangThread; //政委你好 Handler mZhengWeiHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler); mTuanZhangThread = new HandlerThread("强项目1团长"); mTuanZhangThread.start();//团长启动了项目 //团长选拔了助理小春 Looper looper = mTuanZhangThread.getLooper(); //团长指派助理小春协助政委完成工作,通过构造器传参 mZhengWeiHandler = new Handler(looper){ @Override public void handleMessage(Message msg) { switch (msg.what){ case Employee.CODER: Message message = Message.obtain(); message.what = Employee.ZHEGNWEI; message.obj = "汇报项目组工作进度和团队建设情况"; //向CTO发送消息(实现了HandlerThread->主线程通讯) mCTOHandler.sendMessage(message); break; case Employee.CTO: Log.i(TAG, "真是受宠若惊,谢主隆恩!"); break; } } }; //程序猿开始工作 new CoderThread().start(); } /** * 程序猿 */ class CoderThread extends Thread { @Override public void run() { Message message = Message.obtain(); message.what = Employee.CODER; message.obj = "上交周报"; //向政委发送消息 mZhengWeiHandler.sendMessageDelayed(message,2000); } } }
geniusmart/handler-project
app/src/main/java/com/geniusmart/two/HandlerThreadActivity2.java
66,652
package com.ncist.Pokemon.PlayXML; import com.ncist.Pokemon.Message.MessageMain; import com.ncist.Pokemon.Spirit.SpiritOption.SpiritArray; import org.dom4j.*; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static com.ncist.Pokemon.Main.Main.useraccount; public class ChangeXml { // 详见:https://www.cnblogs.com/xiqingbo/p/java-09.html //修改个人xml中所有精灵的血量 恢复血量 public static void recovery_blood() throws DocumentException { // 创建SAXReader实例,读xml文件必备 SAXReader reader = new SAXReader(); // read()读取指定的XML文档并形成DOM树 String fileName = String.format("D:\\Coding\\C\\Pokemon\\XML\\%d.xml", useraccount); Document document = reader.read(new File(fileName)); // getRootElement()获取根节点 Element rootEle = document.getRootElement(); // elements()获取根节点的子节点 List<Element> playersEles = rootEle.elements(); //选择SpiritNums节点 Element player = playersEles.get(4); //将SpiritNums节点作为根节点 List<Element> SpiritEles = player.elements(); //进入Spirit节点,并遍历Spirit节点 for (Element SpiritElement : SpiritEles) { //将原始状态的血量给到blood Element bloodText = SpiritElement.element("blood"); Element orignBloodText = SpiritElement.element("orignBlood"); bloodText.setText(orignBloodText.getText()); System.out.println("\n~~~~~~在生命泉水的帮助下,每个精灵都焕然一新~~~~~~"); MessageMain.stop_key(); break; } OutputFormat format = OutputFormat.createPrettyPrint(); //设置xml文档的编码为utf-8 format.setEncoding("utf-8"); Writer out; try { //创建一个输出流对象 out = new FileWriter(fileName); //创建一个dom4j创建xml的对象 XMLWriter writer = new XMLWriter(out, format); //调用write方法将doc文档写到指定路径 writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } } //修改个人金钱 public static void change_moeny(int isAdd, int money) throws DocumentException { // 创建SAXReader实例,读xml文件必备 SAXReader reader = new SAXReader(); // read()读取指定的XML文档并形成DOM树 String fileName = String.format("D:\\Coding\\C\\Pokemon\\XML\\%d.xml", useraccount); Document document = reader.read(new File(fileName)); // getRootElement()获取根节点 Element rootEle = document.getRootElement(); // elements()获取根节点的子节点 List<Element> playersEles = rootEle.elements(); Element player = playersEles.get(2); int lastMoney; if (isAdd == 1) { lastMoney = Integer.parseInt(player.getText()) + money; } else { lastMoney = Integer.parseInt(player.getText()) - money; } player.setText(String.valueOf(lastMoney)); //如果没钱了,就给0块钱 if (Integer.parseInt(player.getText()) < 0) { player.setText("0"); } OutputFormat format = OutputFormat.createPrettyPrint(); //设置xml文档的编码为utf-8 format.setEncoding("utf-8"); Writer out; try { //创建一个输出流对象 out = new FileWriter(fileName); //创建一个dom4j创建xml的对象 XMLWriter writer = new XMLWriter(out, format); //调用write方法将doc文档写到指定路径 writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } } //战斗完成,将结果的血量,伤害,等级,经验等传回个人xml中 public static void feedback_xml(int isVictory, String spiritNum, String blood, String attackPower, String grade, String exp) throws DocumentException { int money = 0; if (isVictory == 1) { money = (int) (Math.random() * 12 + 10); ChangeXml.change_moeny(1, money); } // 创建SAXReader实例,读xml文件必备 SAXReader reader = new SAXReader(); // read()读取指定的XML文档并形成DOM树 String fileName = String.format("D:\\Coding\\C\\Pokemon\\XML\\%d.xml", useraccount); Document document = reader.read(new File(fileName)); // getRootElement()获取根节点 Element rootEle = document.getRootElement(); // elements()获取根节点的子节点 List<Element> playersEles = rootEle.elements(); //选择SpiritNums节点 Element player = playersEles.get(4); //将SpiritNums节点作为根节点 List<Element> SpiritEles = player.elements(); //进入Spirit节点,并遍历Spirit节点 Element gradeText, bloodText, attackPowerText, expText, orignBloodText; for (Element SpiritElement : SpiritEles) { //获取sn属性.并与 传入的 spiritNum 作比较,如果相等则讲结果保存进xml Attribute attribute = SpiritElement.attribute("sn"); if (Objects.equals(attribute.getValue(), spiritNum)) { //获取Spirit节点的相关信息,如名字,等级等 //如果胜利了,则isVictory为1 if (isVictory == 1) { expText = SpiritElement.element("exp"); int randomExp = (int) (Math.random() * 22 + 1); int intExp = Integer.parseInt(exp); intExp = intExp + randomExp; //大于100说明升级了 if (intExp > 100) { System.out.println("~~~~~~精灵表现出色,学到了很多东西,成功升级!~~~~~~"); intExp = intExp - 100; //等级+1 gradeText = SpiritElement.element("grade"); int intGrade = Integer.parseInt(grade); intGrade++; gradeText.setText(String.valueOf(intGrade)); //因为升级了,所以血量和攻击力要上升 bloodText = SpiritElement.element("blood"); int intBlood = Integer.parseInt(blood); intBlood = intBlood + (intGrade * 3) + 20; bloodText.setText(String.valueOf(intBlood)); orignBloodText = SpiritElement.element("orignBlood"); int orignBlood = Integer.parseInt(orignBloodText.getText()) + (intGrade * 3) + 20; orignBloodText.setText(String.valueOf(orignBlood)); attackPowerText = SpiritElement.element("attackPower"); int intAttackPower = Integer.parseInt(attackPower); intAttackPower = intAttackPower + intGrade + 2; attackPowerText.setText(String.valueOf(intAttackPower)); System.out.println(String.format("~~~~~~战斗结果↓~~~~~~\n获得金币:%d\n精灵等级:%d\t精灵经验值:%d\t精灵血量:%d\t精灵攻击力:%d\n~~~~~~战斗结果↑~~~~~~", money, intGrade, intExp, intBlood, intAttackPower)); } else { feedback_xml_small(SpiritElement, blood, attackPower, grade, exp); System.out.println(String.format("~~~~~~精灵表现出色,学到了很多东西!~~~~~~\n~~~~~~战斗结果↓~~~~~~\n获得金币:%d\n精灵等级:%s\t精灵经验值:%s\t精灵血量:%s\t精灵攻击力:%s\n~~~~~~战斗结果↑~~~~~~", money, grade, intExp, blood, attackPower)); } expText.setText(String.valueOf(intExp)); } else { feedback_xml_small(SpiritElement, blood, attackPower, grade, exp); System.out.println(String.format("~~~~~~精灵已经很努力了,可惜对手太强了~~~~~~\n~~~~~~战斗结果↓~~~~~~\n获得金币:0\n精灵等级:%s\t精灵经验值:%s\t精灵血量:%s\t精灵攻击力:%s\n~~~~~~战斗结果↑~~~~~~", grade, exp, blood, attackPower)); } } } OutputFormat format = OutputFormat.createPrettyPrint(); //设置xml文档的编码为utf-8 format.setEncoding("utf-8"); Writer out; try { //创建一个输出流对象 out = new FileWriter(fileName); //创建一个dom4j创建xml的对象 XMLWriter writer = new XMLWriter(out, format); //调用write方法将doc文档写到指定路径 writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } } //feedback_xml的一个小部分 public static void feedback_xml_small(Element SpiritElement, String blood, String attackPower, String grade, String exp) { Element gradeText, bloodText, attackPowerText, expText; bloodText = SpiritElement.element("blood"); bloodText.setText(blood); attackPowerText = SpiritElement.element("attackPower"); attackPowerText.setText(attackPower); gradeText = SpiritElement.element("grade"); gradeText.setText(grade); expText = SpiritElement.element("exp"); expText.setText(exp); } //(初始化用)用个人信息创建xml文件 public static void save_info_Xml(String PlayerNameText, String PlayerNumText, String PlayerMoneyText, String spiritNum, String nameText, String englishText, String gradeText, String bloodText, String orignBloodText, String attackPowerText) { // Document:表示xml文档信息,是一个树形结构。 // Eelment:表示xml文件的元素节点,主要是提供一些元素的操作方法。 // Attribute:表示元素结点中的属性,可以自定义。 String fileName = String.format("D:\\Coding\\C\\Pokemon\\XML\\%d.xml", useraccount); Document document = DocumentHelper.createDocument(); //创建根元素 Element root = document.addElement("Players"); //创建子元素 Element PlayerName = root.addElement("PlayerName"); PlayerName.setText(PlayerNameText); Element PlayerNum = root.addElement("PlayerNum"); PlayerNum.setText(PlayerNumText); Element PlayerMoney = root.addElement("PlayerMoney"); PlayerMoney.setText(PlayerMoneyText); Element FightSpirit = root.addElement("FightSpirit"); Element Fight = FightSpirit.addElement("Fight"); Element FightNum = Fight.addAttribute("sn", "1"); FightNum.setText(String.valueOf(1)); for (int i = 2; i < 5; i++) { Fight = FightSpirit.addElement("Fight"); FightNum = Fight.addAttribute("sn", String.valueOf(i)); FightNum.setText(String.valueOf(0)); } Element SpiritNums = root.addElement("SpiritNums"); Element Spirit = SpiritNums.addElement("Spirit"); Element SpiritElement = Spirit.addAttribute("sn", spiritNum); Element name = SpiritElement.addElement("name"); name.setText(nameText); Element english = SpiritElement.addElement("english"); english.setText(englishText); Element grade = SpiritElement.addElement("grade"); grade.setText(gradeText); Element exp = SpiritElement.addElement("exp"); exp.setText("1"); Element blood = SpiritElement.addElement("blood"); blood.setText(bloodText); Element orignBlood = SpiritElement.addElement("orignBlood"); orignBlood.setText(orignBloodText); Element attackPower = SpiritElement.addElement("attackPower"); attackPower.setText(attackPowerText); OutputFormat format = OutputFormat.createPrettyPrint(); //设置xml文档的编码为utf-8 format.setEncoding("utf-8"); Writer out; try { //创建一个输出流对象 out = new FileWriter(fileName); //创建一个dom4j创建xml的对象 XMLWriter writer = new XMLWriter(out, format); //调用write方法将doc文档写到指定路径 writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } } //展示要出战的精灵,,返回值:返回一个二维数组,数组中有 精灵编号 和对应的 精灵名字 public static SpiritArray[] show_fight_spirit() throws DocumentException { //用于返回二维数组 SpiritArray[] spiritArray1 = new SpiritArray[4]; for (int i = 0; i < 4; i++) { spiritArray1[i] = new SpiritArray(); } // 创建SAXReader实例,读xml文件必备 SAXReader reader = new SAXReader(); // read()读取指定的XML文档并形成DOM树 String fileName = String.format("D:\\Coding\\C\\Pokemon\\XML\\%d.xml", useraccount); Document document = reader.read(new File(fileName)); // getRootElement()获取根节点 Element rootEle = document.getRootElement(); // elements()获取根节点的子节点 List<Element> playersEles = rootEle.elements(); //将FightSpirit节点作为根节点 Element Fight = playersEles.get(3); List<Element> FightEles = Fight.elements(); String[] stringTextArray1 = new String[4]; int i = 0; //进入FightSpirit节点,并遍历FightSpirit节点 for (Element FightElement : FightEles) { //获取FightSpirit节点的信息,即获取要出战精灵的编号 stringTextArray1[i] = (FightElement.getText()); i++; } i = 0; while (i != 4) { if (stringTextArray1[i] != null) { System.out.printf(stringTextArray1[i] + " "); } i++; } System.out.println(); //选择SpiritNums节点 Element player = playersEles.get(4); //将SpiritNums节点作为根节点 List<Element> SpiritEles = player.elements(); //进入Spirit节点,并遍历Spirit节点 i = 0; int snValue, gradeText, bloodText, attackPowerText, exp; String nameText, englishName; for (; i < stringTextArray1.length; i++) { for (Element SpiritElement : SpiritEles) { //获取Spirit节点的相关信息,如名字,等级等 snValue = Integer.parseInt(SpiritElement.attributeValue("sn")); if (stringTextArray1[i] == null) { break; } if (i < stringTextArray1.length - 1 && Integer.parseInt(stringTextArray1[i]) == snValue) { nameText = SpiritElement.elementText("name"); englishName = SpiritElement.elementText("english"); gradeText = Integer.parseInt(SpiritElement.elementText("grade")); exp = Integer.parseInt(SpiritElement.elementText("exp")); bloodText = Integer.parseInt(SpiritElement.elementText("blood")); attackPowerText = Integer.parseInt(SpiritElement.elementText("attackPower")); spiritArray1[i].spiritNum = snValue; spiritArray1[i].englishName = englishName; spiritArray1[i].chineseName = nameText; spiritArray1[i].grade = gradeText; spiritArray1[i].blood = bloodText; spiritArray1[i].attackPower = attackPowerText; spiritArray1[i].exp = exp; System.out.println(String.format("可出战的精灵编号:%d\t可出战的精灵名字:%s\t可出战的精灵等级:%d\n可出战的精灵经验:%d\t可出战的精灵血量:%d\t\t可出战的精灵攻击力:%d\n", snValue, nameText, gradeText, exp, bloodText, attackPowerText)); break; } } } return spiritArray1; } //展示输入的玩家编号的用户信息 public static void main_for_showinfo() throws DocumentException { // 创建SAXReader实例,读xml文件必备 SAXReader reader = new SAXReader(); // read()读取指定的XML文档并形成DOM树 String fileName = String.format("D:\\Coding\\C\\Pokemon\\XML\\%d.xml", useraccount); Document document = reader.read(new File(fileName)); // getRootElement()获取根节点 Element rootEle = document.getRootElement(); // elements()获取根节点的子节点 List<Element> playersEles = rootEle.elements(); System.out.println("~~~~~~玩家信息:~~~~~~"); String[] stringTextArray = new String[4]; String[] stringTextArray1 = new String[4]; //将子节点当做根节点,重复上诉过程 for (int i = 0; i < 3; i++) { Element player = playersEles.get(i); stringTextArray[i] = player.getText(); } //将FightSpirit节点作为根节点 Element Fight = playersEles.get(3); List<Element> FightEles = Fight.elements(); int i = 0; //进入FightSpirit节点,并遍历FightSpirit节点 for (Element FightElement : FightEles) { //获取FightSpirit节点的信息,即获取要出战精灵的编号 stringTextArray1[i] = FightElement.getText(); i++; } //后期 用户ID 和 账户余额 需要强制类型转换 System.out.printf(String.format("用户名:%s\t\t用户ID:%s\t\t账户余额:%s\t\t已选择要出战的精灵:(0编号则为不出战)", stringTextArray[0], stringTextArray[1], stringTextArray[2])); i = 0; while (i != 4) { if (stringTextArray1[i] != null) { System.out.printf(stringTextArray1[i] + " "); } i++; } System.out.println(); //选择SpiritNums节点 Element player = playersEles.get(4); //将SpiritNums节点作为根节点 List<Element> SpiritEles = player.elements(); //进入Spirit节点,并遍历Spirit节点 i = 0; int snValue, gradeText, bloodText, attackPowerText, exp; System.out.println("~~~~~~第1页~~~~~~"); for (Element SpiritElement : SpiritEles) { //获取Spirit节点的相关信息,如名字,等级等 snValue = Integer.parseInt(SpiritElement.attributeValue("sn")); String nameText = SpiritElement.elementText("name"); gradeText = Integer.parseInt(SpiritElement.elementText("grade")); exp = Integer.parseInt(SpiritElement.elementText("exp")); bloodText = Integer.parseInt(SpiritElement.elementText("blood")); attackPowerText = Integer.parseInt(SpiritElement.elementText("attackPower")); System.out.println(String.format("所拥有的精灵编号:%d\t所拥有的精灵名字:%s\t所拥有的精灵等级:%d\n所拥有的精灵经验值:%d\t所拥有的精灵血量:%d\t\t所拥有的精灵攻击力:%d\n", snValue, nameText, gradeText, exp, bloodText, attackPowerText)); i++; if (i % 4 == 0 && i != 4 && i != 0) { //四个为一组输出 //暂停键 MessageMain.stop_key(); System.out.println(String.format("~~~~~~第%d页~~~~~~", (i / 4) + 1)); } } //暂停键 MessageMain.stop_key(); } }
TonyD0g/JavaHacker
0 Java开发基础/1 Java SE基础/12.项目实训/src/com/ncist/Pokemon/PlayXML/ChangeXml.java
66,653
package com.wy; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.DatagramChannel; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Java中的输入/输出:以程序为中心,向程序是数据源的起点,那就是输出(写);若程序是接收数据的,那就是输入(读) * * NIO:同步非阻塞流,适用于高并发,短连接的架构,如聊天室.主要类,, NIO在read/write的时候是同步的,要等待操作完成,但和操作系统交互是异步的. * NIO在while读取客户端的流时不会阻塞,BIO会阻塞,多线程情况下,NIO比BIO性能更出色,消耗资源更小,且更稳定 在读取流中的数据时,将不会一直等待,而是通过轮询来判断其他线程是否也需要进行读写操作. * * NIO主要是通过{@link Channels},{@link Buffer}以及Selector(多路复用选择器)对socket,io流等进行操作, * channel是线程安全的,读写都是用Buffer,而Buffer分为读和写模式,中间通过flip进行切换 * * {@link Buffer}:缓冲,{@link ByteBuffer}是其主要实现类,大部分的操作都是通过ByteBuffer完成,还有其他基本类型Buffer * * <pre> * capacity: 容量,buffer的最大长度 * limit:buffer能写入数据的最大长度,必须小于等于capacity * position:无参方法读取buffer指针下标,当前下标是还没有读的,要小于等于limit.有参方法指定当前buffer索引 * mark:记号下标,方便重新读取buffer中的数据,要小于等于position * flip():设置limit为position值,再将position设为0,以备用于读取,各种读写操作都是在postion和limit之间进行 * rewind():将limit和position恢复到读取数据之前,重复读取缓冲区数据 * clear():重置buffer到初始状态,用于下次写入新的数据,但实际上次的数据仍在缓冲区中,重复写入会覆盖以前的数据 * allocate():在jvm的堆中分配内存创建缓冲区,并给缓冲区分配大小 * allocateDirect():在os内核中分配内存创建缓冲区,不占用jvm的内存空间,速度更快,默认是64M,但不可回收 * array():将缓冲区数据转为字节数组 * </pre> * * Channel:通道,主要是为了进行Selector的切换,主要可分为以下四种: * * <pre> * {@link FileChannel}:从文件中读取数据 * {@link DatagramChannel}:从UDP中读写网络数据 * {@link SocketChannel}:从TCP中读写网络数据,用在Socket客户端 * {@link ServerSocketChannel}:监听新连接的TCP请求,对每一个新的连接新建一个SocketChannel,用在Socket服务端 * </pre> * * 网络七层模型: * * <pre> * 物理层:中继器,集线器,双绞线等网络传输设备 * 数据链路层:网桥,以太网交换机,网卡等物理网络连接设备 * 网络层:路由器,三层交换机等网络设备 * 传输层:四层交换机,四层路由器等设备 * 会话层:和表示层,应用层都可以统称为应用层. * 表示层:数据展示 * 应用层:数据展示 * </pre> * * @author 飞花梦影 * @date 2020-09-29 10:47:14 * @git {@link https://github.com/dreamFlyingFlower} */ @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
dreamFlyingFlower/dream-study-java
dream-study-java-io/src/main/java/com/wy/Application.java
66,654
package org.xueyinhu.ssm; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.xueyinhu.ssm.mapper.EmployeeMapper; import org.xueyinhu.ssm.pojo.Employee; import java.io.IOException; import java.io.InputStream; /** MyBatis * 持久化框架对比: * JDBC: * SQL 夹杂在代码中耦合度过高,不容易维护且开发效率低 * 运行效率最高 -- JDBC > Mybatis > Hibernate * Hibernate 和 JPA: * 开发效率比直接使用 JDBC 高 -- JDBC < Mybatis < Hibernate * 程序中的长难复杂 SQL 需要绕过框架 * 内部自动生成的 SQL,不容易做特殊优化 * 基于全映射的全自动框架,大量字段的 POJO 进行部分映射时比较困难 * 反射操作太多,导致数据库性能下降 * MyBatis * 轻量级,性能出色 * SQL 和 Java 编码分开,功能边界清晰 * 开发效率逊于 Hibernate,但是完全能够接受 */ public class Main { /** mybatis * 1. 读取外部配置文件 mybatis-config.xml * 2. 创建 SqlSessionFactory 对象 * 3. 创建 SqlSession,每次业务创建一个,用完释放 * 4. 获取接口的代理对象,就会查找 mapper 接口的方法 * 5。 提交事务(非DQL)和释放资源 */ public static void main(String[] args) throws IOException { String mybatisConfigFilePath = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(mybatisConfigFilePath); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); System.out.println(mapper.queryById(1).getName()); // 查询事务不需要提交 // session.commit(); session.close(); } }
stre-lizia/java-ssm
mybatis-a/src/main/java/org/xueyinhu/ssm/Main.java
66,655
package com.example.demo.web; import com.example.demo.domain.*; import com.example.demo.domain.result.ExceptionMsg; import com.example.demo.domain.result.Response; import com.example.demo.domain.result.ResponseData; import com.example.demo.service.LoveService; import com.example.demo.service.imp.*; import com.example.demo.tf.TensorflowModel; import groovy.transform.Undefined; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @ClassName TopicController * @Description TODO * @Auther ydc * @Date 2019/1/25 14:39 * @Version 1.0 **/ @RestController public class TopicController extends BaseController { private TopicServiceImp topicServiceImp; private UserServiceImp userServiceImp; private BoardServiceImp boardServiceImp; private PraiseServiceImp praiseServiceImp; private PostServiceImp postServiceImp; private LoveService loveService; private TensorflowModel tensorflowModel; @Autowired public void setTopicServiceImp(TopicServiceImp topicServiceImp) { this.topicServiceImp = topicServiceImp; } @Autowired public void setUserServiceImp(UserServiceImp userServiceImp) { this.userServiceImp = userServiceImp; } @Autowired public void setPraiseServiceImp(PraiseServiceImp praiseServiceImp) { this.praiseServiceImp = praiseServiceImp; } @Autowired public void setBoardServiceImp(BoardServiceImp boardServiceImp) { this.boardServiceImp = boardServiceImp; } @Autowired public void setPostServiceImp(PostServiceImp postServiceImp) { this.postServiceImp = postServiceImp; } @Autowired public void setLoveService(LoveService loveService) { this.loveService = loveService; } @Autowired public void setTensorflowModel(TensorflowModel tensorflowModel) { this.tensorflowModel = tensorflowModel; } @RequestMapping("topic/like/{topicId}") //映射点赞 public ResponseData changePraise(HttpServletRequest request, @PathVariable("topicId") int topicId){ System.out.println(111); try { User user = getSessionUser(request); praiseServiceImp.like(topicId,user.getUserId());//完成修改 } catch (Exception e){ System.err.println("有错误"); } return new ResponseData(ExceptionMsg.SUCCESS); } @RequestMapping("userTopicSave/{userId}") //写文章后保存,由于使用了tensorflow导致速度有的忙 public ResponseData userTopicSave(HttpServletRequest request,@PathVariable("userId")int userId,String html,String title,String content,String boardId){ // System.out.println(tensorflowModel.cnn("体育面对威斯布鲁克的雷霆,独行侠却不会害怕。本赛季首次交锋,独行侠就以111-96取得胜利场投上一场打太阳,威斯布鲁克几乎三双,拿下了40分、12个篮板和8次助攻。今天他却状态低迷,不断“打铁”。雷霆还得靠乔治。他们在首节中段打出一波10-0,以18-9取得优势,乔治在这波攻击中独得5分。巴恩斯和东契奇相继还以颜色,独行侠也打出一波9-0,双方战成21-21。两队开始拉锯战,首节过后,雷霆以28-27领先1分。雷霆替补发挥出色,第四节开始后,他们打出一波17-4,在本节将过半时,帕特森空中接力扣篮,他们以90-88反超。双方派上主力后,雷霆近3分钟一分未得,而东契奇命中三分,独行侠连得5分,又成为领先的一方。乔治三罚三中,然后又投中三分,雷霆以96-95再度超出。双方进入拼刺刀阶段,在最后1秒才分出高下。比赛还有24.8秒时,史密斯杀了个“回马枪”,突然上篮得手,独行侠连得5分,以104-103反超。独行侠关键时刻成功防守,乔治急停跳投不中,时间只剩下1.6秒。乔丹两罚一中后,独行侠以105-103领先。全场手感冰凉的威斯布鲁克执行最后一攻,未能命中,雷霆功亏一篑。")); try { int bd = Integer.parseInt(boardId); Topic topic = new Topic(bd, userId, title, new Date(), new Date(), 1, 0, 0, 1, "PRIVATE", "/userRead/", "/img/favicon.png", html, 0, content); System.out.println(html); System.out.println(content); topic.setLabel(tensorflowModel.cnn(html)); topicServiceImp.TopicSave(topic); return new ResponseData(ExceptionMsg.SUCCESS); } catch (Exception e){ e.printStackTrace(); return new ResponseData(ExceptionMsg.FAILED); } } @RequestMapping("userWritePage") //映射到写文文章页面 public ModelAndView userWriting(){ ModelAndView mv = new ModelAndView(); mv.setViewName("user/write"); return mv; } @RequestMapping("userRead/{topicId}") //阅读文章 public ModelAndView userReading(@PathVariable("topicId")int topicId){ Topic topic = topicServiceImp.getTopicByTopicId(topicId); ModelAndView mv = new ModelAndView(); mv.addObject("topic",topic); mv.addObject("user",userServiceImp.getUserById(topic.getUserId())); mv.setViewName("user/read"); return mv; } @RequestMapping("userReadDetail/{topicId}") //阅读文章 public ModelAndView userReadDetail(@PathVariable("topicId")int topicId){ Topic topic = topicServiceImp.getTopicByTopicId(topicId); ModelAndView mv = new ModelAndView(); List<Post> posts = postServiceImp.findPostByTopicId(topicId); mv.addObject("topic",topic); mv.addObject("posts",posts); // System.out.println(posts); mv.addObject("board",boardServiceImp.findBoardById(topic.getBoardId())); mv.addObject("user",userServiceImp.getUserById(topic.getUserId())); mv.setViewName("user/readDetail"); return mv; } @RequestMapping("userAmend/{topicId}") //再次修改编辑文章 public ModelAndView userAmend(@PathVariable("topicId")int topicId){ Topic topic = topicServiceImp.getTopicByTopicId(topicId); List<Board> boards= boardServiceImp.findAllBoard(); ModelAndView mv = new ModelAndView(); mv.addObject("topic",topic); mv.addObject("boards",boards); mv.setViewName("user/amend"); return mv; } @RequestMapping("userTopicAmend/{topicId}") public ResponseData userTopicAmend(@PathVariable("topicId")int topicId,String html,String content,String title,String boardId){ try { int bd = Integer.parseInt(boardId); topicServiceImp.AmendTopic(bd,html,content,title,topicId); return new ResponseData(ExceptionMsg.SUCCESS); } catch (Exception e){ e.printStackTrace(); return new ResponseData(ExceptionMsg.FAILED); } } @RequestMapping("search/{key}") //根据关键字查询 public ModelAndView search(@PathVariable("key") String key,HttpServletRequest request,@RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "25") Integer size){ Page<Topic> pages = topicServiceImp.getTopicBySearch(page,size,key); User user = getSessionUser(request); ModelAndView mv = new ModelAndView(); mv.setViewName("user/search"); mv.addObject("user",user); List<Topic> topics2 = new ArrayList<>(); for(Topic topic:pages) { topic.setUser(userServiceImp.getUserById(topic.getUserId())); topic.setBoard(boardServiceImp.findBoardById(topic.getBoardId())); topic.setUrl("/userReadDetail/"+topic.getTopicId()); topics2.add(topic); } mv.addObject("topics",topics2); return mv; } @RequestMapping("topic/delete/{topicId}") //删除Topic public ResponseData topicDelete(@PathVariable("topicId")int topicId){ try{ /** * 必须先删除相关引用topic的元素 */ int de=topicId; praiseServiceImp.deleteAllByTopicId(topicId); loveService.deleteAllByTopciId(topicId); //praiseServiceImp.deleteAllByTopicId(topicId); postServiceImp.deleteAllByTopicId(topicId); topicServiceImp.deleteTopicByTopicId(de); System.out.println(de); //topicServiceImp.deleteTopicByTopicId(topicId); return new ResponseData(ExceptionMsg.SUCCESS); } catch (Exception e){ e.printStackTrace(); return new ResponseData(ExceptionMsg.FAILED); } } @RequestMapping("myArticle") //我的文章 public ModelAndView userArticle(HttpServletRequest request,@RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "15") Integer size){ User user = getSessionUser(request); ModelAndView mv = new ModelAndView(); if(user==null){ mv.setViewName("error"); return mv; } // ModelAndView mv = new ModelAndView(); mv.setViewName("user/myArticle"); mv.addObject("user",user); Page<Topic> topics1 = topicServiceImp.getAllPageTopicByUserId(page,size,user.getUserId()); List<Topic> topics2 = new ArrayList<>(); for(Topic topic:topics1) { topic.setUser(userServiceImp.getUserById(topic.getUserId())); topic.setBoard(boardServiceImp.findBoardById(topic.getBoardId())); topic.setUrl("/userReadDetail/"+topic.getTopicId()); setIsPraise(topic,user); topics2.add(topic); } mv.addObject("topics",topics2); return mv; } @RequestMapping("myArticle/more") //分页加载我的文章,每页15条数据 public List<Topic> loadMoreArticle(HttpServletRequest request, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "15") Integer size){ page++; System.out.println(page); User user = getSessionUser(request); if(user==null){ return null; } Page<Topic> topics = topicServiceImp.getAllPageTopicByUserId(page,size,user.getUserId()); List<Topic> topics1 = new ArrayList<>(); for(Topic topic:topics){ topic.setUser(userServiceImp.getUserById(topic.getUserId())); topic.setBoard(boardServiceImp.findBoardById(topic.getBoardId())); topic.setUrl("/userReadDetail/"+topic.getTopicId()); setIsPraise(topic,user); topics1.add(topic); } return topics1; } private void setIsPraise(Topic topic,User user){ List<Praise> praises = praiseServiceImp.getAllPraiseByTopicId(topic.getTopicId()); for(Praise praise:praises){ if(praise.getUserId()==user.getUserId()){ topic.setIsPraise(1); break; } } topic.setIsPraise(0); } @RequestMapping("lookRecord/save/{topicId}") //文章浏览次数更新 public ResponseData lookRecord(@PathVariable("topicId") int topicId){ try{ Topic topic = topicServiceImp.getTopicByTopicId(topicId); topicServiceImp.updateTopicViewByTopicId(topic.getTopicViews()+1,topicId); return new ResponseData(ExceptionMsg.SUCCESS); } catch (Exception e){ e.printStackTrace(); return new ResponseData(ExceptionMsg.FAILED); } } }
yangdongchao/springboot
forum/src/main/java/com/example/demo/web/TopicController.java
66,656
/** * Redis: Redis是一个开源的内存中的数据结构存储系统,它可以用作:数据库、缓存和消息中间件。 Redis 内置了复制(Replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(Transactions) 和不同级别的磁盘持久化(Persistence), 并通过 Redis哨兵(Sentinel)和自动分区(Cluster)提供高可用性(High Availability)。 Redis本质上是一个Key-Value类型的内存数据库,整个数据库统统加载在内存当中进行操作,定期通过异步操作把数据库数据flush到硬盘上进行保存。 因为是纯内存操作,Redis的性能非常出色,每秒可以处理超过 10万次读写操作,是已知性能最快的Key-Value DB。 Redis支持保存多种数据结构(String、List、Set、Sorted Set、Hash),此外单个value的最大限制是1GB,可以对存入的Key-Value设置expire时间。 Redis的主要缺点是数据库容量受到物理内存的限制,不能用作海量数据的高性能读写,因此Redis适合的场景主要局限在较小数据量的高性能操作和运算上。 Redis为什么这么快: 1、完全基于内存 2、数据结构简单 3、采用单线程,避免了不必要的上下文切换和竞争条件 4、使用多路I/O复用模型,非阻塞IO; 5、单线程的方式是无法发挥多核CPU 性能,不过我们可以通过在单机开多个Redis 实例来完善! Redis的优点: 1、速度快,因为数据存在内存中,类似于HashMap,HashMap的优势就是查找和操作的时间复杂度都是O(1) 2、支持丰富数据类型,支持string,list,set,sorted set,hash 3、支持事务,操作都是原子性,所谓的原子性就是对数据的更改要么全部执行,要么全部不执行 4、丰富的特性:可用于缓存,消息,按key设置过期时间,过期后将会自动删除 5、Redis支持数据的备份,即master-slave模式的数据备份。 6、Redis支持数据的持久化,可以将内存中的数据保持在磁盘中,重启的时候可以再次加载进行使用。 适用场景: 会话缓存(Session Cache):最常用的一种使用Redis的情景是会话缓存(session cache)。 用Redis缓存会话比其他存储(如Memcached)的优势在于:Redis提供持久化。Redis并不能保证数据的强一致性,适用于维护一个不是严格要求一致性的缓存。 队列:Reids在内存存储引擎领域的一大优点是提供 list 和 set 操作,这使得Redis能作为一个很好的消息队列平台来使用。 排行榜/计数器:Redis在内存中对数字进行递增或递减的操作实现的非常好。集合(Set)和有序集合(Sorted Set)也使得我们在执行这些操作的时候变的非常简单。 发布/订阅: 使用较少 Redis分布式锁: 先拿setnx来争抢锁,抢到之后,再用expire给锁加一个过期时间防止锁忘记了释放。 如果在setnx之后执行expire之前进程意外crash或者要重启维护了,那会怎么样? set指令有非常复杂的参数,这个应该是可以同时把setnx和expire合成一条指令来用的! Redis秒杀: incrby key -1 返回结果大于等于0算拍到。 Redis持久化: 持久化就是把内存的数据写到磁盘中去,防止服务宕机了内存数据丢失。 Redis 提供了两种持久化方式:RDB(默认) 和AOF 。 RDB:Redis DataBase,功能核心函数rdbSave(生成RDB文件)和rdbLoad(从文件加载内存)。 AOF:redis 写命令日志。 1、aof文件比rdb更新频率高,优先使用aof还原数据。 2、aof比rdb更安全也更大 3、rdb性能比aof好 4、如果两个都配了优先加载AOF Redis哈希槽: Redis集群没有使用一致性hash,而是引入了哈希槽的概念,Redis集群有16384个哈希槽,每个key通过CRC16校验后对16384取模来决定放置哪个槽,集群的每个节点负责一部分hash槽。 Redis事务: 事务是一个单独的隔离操作:事务中的所有命令都会序列化、按顺序地执行。事务在执行的过程中,不会被其他客户端发送来的命令请求所打断。 事务是一个原子操作,事务中的命令要么全部被执行,要么全部都不执行。 Redis cluster 1. 所有的redis节点彼此互联(PING-PONG机制), 内部使用二进制协议优化传输速度和带宽. 2. 节点的fail是通过集群中超过半数的master节点检测失效时才生效. 3. 客户端与redis节点直连, 不需要中间proxy层; 客户端不需要连接集群所有节点, 连接集群中任何一个可用节点即可 4. redis-cluster把所有的物理节点映射到[0-16383]slot上, cluster 负责维护node<->slot<->key Redis cluster 选举 1. 选举过程是集群中所有master参与, 如果半数以上master节点与故障节点通信超过(cluster-node-timeout), 认为该节点故障, 自动触发故障转移操作. 2. 什么时候整个集群不可用(cluster_state:fail)? a. 如果集群任意master挂掉, 且当前master没有slave. 集群进入fail状态, 也可以理解成集群的slot映射[0-16383]不完整时进入fail状态. b. 如果集群超过半数以上master挂掉,无论是否有slave集群进入fail状态. ps: 当集群不可用时, 所有对集群的操作做都不可用,收到((error) CLUSTERDOWN The cluster is down)错误. ************************************************************************************************************************ - Jedis 实现与节点的连接、命令传输、返回结果读取 - Jedis extends BinaryJedis, Jedis持有Pool对象,在close时,如果Pool不为空则,释放会缓存池中 protected Pool<Jedis> dataSource = null; - Jedis 提供基本类型和String参数的方法,BinaryJedis提供byte[]类型参数方法,String类型使用utf8编码转换成byte[] - BinaryJedis持有Client、Pipeline、Transaction - 真正的操作最后都会由Client执行, Jedis/BinaryJedis 在执行操作前都会先调用checkIsInMultiOrPipeline检查当前Jedis连接是否在进行multi、pipeline操作 protected Client client = null; protected Transaction transaction = null; protected Pipeline pipeline; - Client extends BinaryClient, BinaryClient extends Connection - Client 提供基本类型和String参数的方法,BinaryClient提供byte[]类型参数方法 - Connection 提供socket连接,socket.setReuseAddress(true);socket.setKeepAlive(true);socket.setTcpNoDelay(true);socket.setSoLinger(true, 0); - Connection 通过Protocol.sendCommand(out, cmd, args) 发送命令到redis节点对应的Client out.write(ASTERISK_BYTE); //(byte)42 out.writeIntCrLf(args.length + 1); out.write(DOLLAR_BYTE); //(byte)36 out.writeIntCrLf(command.length); out.write(command); out.writeCrLf(); out.flush(); - Connection 通过Protocol.processStatusCodeReply(is) 返回 byte[] 状态反馈 - Connection 通过Protocol.processInteger(is) 返回 Long 执行结果 - Connection 通过Protocol.processBulkReply(is) 返回 byte[] 大对象执行结果 - Connection 通过Protocol.processMultiBulkReply(is) 返回List<Object> 多个大对象执行结果 ************************************************************************************************************************ - JedisClusterCRC16 用于获取key对应的slot - JedisCluster 集群环境下的封装,实现集群环境下的节点slot和host:port对应的JedisPool缓存 - 通过getConnectionFromSlot获取key对应的slot节点的Jedis连接进行读写操作,通过JedisClusterCommand回调 实现失败重试功能 - JedisCluster extends BinaryJedisCluster - BinaryJedisCluster 持有 JedisClusterConnectionHandler, protected JedisClusterConnectionHandler connectionHandler; protected int maxAttempts; - JedisClusterConnectionHandler持有JedisClusterInfoCache, protected final JedisClusterInfoCache cache; - JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandler 实现了initializeSlotsCache和getConnection方法 // 构建 private void initializeSlotsCache(Set<HostAndPort> startNodes, GenericObjectPoolConfig poolConfig, String password) { for (HostAndPort hostAndPort : startNodes) { Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort()); if (password != null) { jedis.auth(password); } try { cache.discoverClusterNodesAndSlots(jedis); break; } catch (JedisConnectionException e) { // try next nodes } finally { if (jedis != null) { jedis.close(); } } } } // 随机节点jedis连接 public Jedis getConnection() { List<JedisPool> pools = cache.getShuffledNodesPool(); for (JedisPool pool : pools) { Jedis jedis = null; try { jedis = pool.getResource(); if (jedis == null) { continue; } // 测试连接 String result = jedis.ping(); if (result.equalsIgnoreCase("pong")) return jedis; jedis.close(); } catch (JedisException ex) { if (jedis != null) { jedis.close(); } } } throw new JedisNoReachableClusterNodeException("No reachable node in cluster"); } // 返回slot对应node的jedis 连接 public Jedis getConnectionFromSlot(int slot) { JedisPool connectionPool = cache.getSlotPool(slot); if (connectionPool != null) { // It can't guaranteed to get valid connection because of node assignment return connectionPool.getResource(); } else { //It's abnormal situation for cluster mode, that we have just nothing for slot, try to rediscover state renewSlotCache(); connectionPool = cache.getSlotPool(slot); if (connectionPool != null) { return connectionPool.getResource(); } else { //no choice, fallback to new connection to random node return getConnection(); } } } - JedisClusterInfoCache 持有Map<String, JedisPool> nodes和Map<Integer, JedisPool> slots两个jedispool缓存,key分别是节点 host:port 和 slot private final GenericObjectPoolConfig poolConfig; private final Map<String, JedisPool> nodes = new HashMap<String, JedisPool>(); // ip:port 对应的连接池缓存 private final Map<Integer, JedisPool> slots = new HashMap<Integer, JedisPool>(); // slot 对应的连接池缓存 private static final int MASTER_NODE_INDEX = 2; // 主节点SlotInfo下标,通常前两位是节点slot的范围 // 节点的槽位集合:[[10924, 16383, [B@4ae82894, 6386], [B@543788f3, 6387]], [5462, 10923, [B@6d3af739, 6384], [B@1da51a35, 6385]], [0, 5461, [B@16022d9d, 6382], [B@7e9a5fbe, 6383]]] - JedisClusterInfoCache实现了discoverClusterNodesAndSlots()初始化 和 renewSlotCache()刷新集群slot jedispool缓存 // 初始化时,同时初始化ip:port为key的缓存(包括master、slave),slot为key的缓存(只缓存master的slot对应的jedispool) public void discoverClusterNodesAndSlots(Jedis jedis) { w.lock(); try { reset(); // destroy cache List<Object> slots = jedis.clusterSlots(); // 集群节点slot信息 for (Object slotInfoObj : slots) { // 遍历节点slot信息 List<Object> slotInfo = (List<Object>) slotInfoObj; // [slotIndexStart, slotIndexEnd, [ip byte[], port], [ip byte[], port] ...] // 如果此节点信息少于3 个, 说明节点出错没有ip:host信息,跳过此次循环 if (slotInfo.size() <= MASTER_NODE_INDEX) { continue; } // 节点对应的所有slot数字,用于在cache里作为key存储jedispool List<Integer> slotNums = getAssignedSlotArray(slotInfo); int size = slotInfo.size(); // 遍历 slot对应的master、slave节点ip:host,从下表2开始 for (int i = MASTER_NODE_INDEX; i < size; i++) { List<Object> hostInfos = (List<Object>) slotInfo.get(i); if (hostInfos.isEmpty()) { continue; } // 解析主机信息 HostAndPort HostAndPort targetNode = generateHostAndPort(hostInfos); // 如果 以ip:host为key的nodes缓存里没有对应的jedispool,就使用poolconfig 新建一个并放入缓存,nodes缓存master/slave节点对应的jedispool // new JedisPool(poolConfig, node.getHost(), node.getPort()) 放入nodes中 setupNodeIfNotExist(targetNode); // slot缓存只缓存master节点slot对应的jedispool if (i == MASTER_NODE_INDEX) { assignSlotsToNode(slotNums, targetNode); } } } } finally { w.unlock(); } } // 刷新时只更新ip:port为key的缓存(只更新master),slot为key的缓存(只更新master的slot对应的jedispool) public void renewClusterSlots(Jedis jedis) { try { w.lock(); List<Object> slots = jedis.clusterSlots(); for (Object slotInfoObj : slots) { List<Object> slotInfo = (List<Object>) slotInfoObj; if (slotInfo.size() <= MASTER_NODE_INDEX) { continue; } List<Integer> slotNums = getAssignedSlotArray(slotInfo); // 刷新时只取主节点的ip:host List<Object> hostInfos = (List<Object>) slotInfo.get(MASTER_NODE_INDEX); if (hostInfos.isEmpty()) { continue; } HostAndPort targetNode = generateHostAndPort(hostInfos); // 刷新master节点的缓存 assignSlotsToNode(slotNums, targetNode); } } finally { w.unlock(); } } - JedisCluster通过JedisClusterCommand 实现失败重试功能 new JedisClusterCommand<Long>(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pexpireAt(key, millisecondsTimestamp); } }.run(key); private ThreadLocal<Jedis> askConnection = new ThreadLocal<Jedis>(); private T runWithRetries(byte[] key, int attempts) { if (attempts <= 0) { throw new JedisClusterMaxRedirectionsException("Too many Cluster redirections?"); } Jedis connection = null; try { // 第一次 false,如果节点 A 正在迁移槽 i 至节点 B , 那么当节点 A 没能在自己的数据库中找到命令指定的数据库键时, // 节点 A 会向客户端返回一个 ASK 错误, 指引客户端到节点 B 继续查找指定的数据库键 if (asking) { // TODO: Pipeline asking with the original command to make it faster connection = askConnection.get(); // 到目标节点打开客户端连接标识 connection.asking(); // if asking success, reset asking flag asking = false; } else { // 通过 CRC16 算法获取 slot 对应的节点的连接池中的连接 connection = connectionHandler.getConnectionFromSlot(JedisClusterCRC16.getSlot(key)); } return execute(connection); // 集群不存在 } catch (JedisNoReachableClusterNodeException jnrcne) { throw jnrcne; // 连接异常 } catch (JedisConnectionException jce) { releaseConnection(connection); connection = null; // 如果重试次数只有一次,那就更新连接池,并抛出异常 if (attempts <= 1) { // do renewing only if there were no successful responses from this node last few seconds this.connectionHandler.renewSlotCache(); //no more redirections left, throw original exception, not JedisClusterMaxRedirectionsException, because it's not MOVED situation throw jce; } // 递归重试,重试次数减一 return runWithRetries(key, attempts - 1); // 如果是重定向异常,例如 moved ,ASK } catch (JedisRedirectionException jre) { // if MOVED redirection occurred, // 节点在接到一个命令请求时, 会先检查这个命令请求要处理的键所在的槽是否由自己负责, 如果不是的话, 节点将向客户端返回一个 MOVED 错误, // MOVED 错误携带的信息可以指引客户端转向至正在负责相关槽的节点 if (jre instanceof JedisMovedDataException) { // it rebuilds cluster's slot cache // 如果是 moved 错误,就更新连接池, ASK 就不必更新缓存,只需要临时访问就行 this.connectionHandler.renewSlotCache(connection); } releaseConnection(connection); connection = null; // 如果是 ASK if (jre instanceof JedisAskDataException) { asking = true; // 设置 ThreadLocal,新的连接是 ASK 指定的节点 askConnection.set(this.connectionHandler.getConnectionFromNode(jre.getTargetNode())); } else if (jre instanceof JedisMovedDataException) { } else { throw new JedisClusterException(jre); } // 递归重试,重试次数减一 return runWithRetries(key, attempts - 1); } finally { releaseConnection(connection); } } *********************************************************************************************************** - Jedis持有Pool对象,在close时,如果Pool不为空则,释放会缓存池中 protected Pool<Jedis> dataSource = null; - JedisPoolConfig extends GenericObjectPoolConfig 用于配置JedisPool连接池 - JedisPool extends Pool<Jedis>, Pool 持有commonpool2的GenericObjectPool, 用于缓存Jedis连接 protected GenericObjectPool<T> internalPool; - JedisFactory implements PooledObjectFactory<Jedis>, 实现了makeObject用于新建Jedis连接 public PooledObject<Jedis> makeObject() throws Exception { final Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort(), connectionTimeout, soTimeout); try { jedis.connect(); if (null != this.password) { jedis.auth(this.password); } if (database != 0) { jedis.select(database); } if (clientName != null) { jedis.clientSetname(clientName); } } catch (JedisException je) { jedis.close(); throw je; } return new DefaultPooledObject<Jedis>(jedis); } // 从pool中取出时进行初始化,重置到默认db上 public void activateObject(PooledObject<Jedis> pooledJedis) throws Exception { final BinaryJedis jedis = pooledJedis.getObject(); if (jedis.getDB() != database) { jedis.select(database); } } // 从pool中取出时进行ping/pong校验 public boolean validateObject(PooledObject<Jedis> pooledJedis) { pooledJedis.getObject().ping().equals("PONG") } // 销毁Jedis public void destroyObject(PooledObject<Jedis> pooledJedis) { final BinaryJedis jedis = pooledJedis.getObject(); if (jedis.isConnected()) { try { try { jedis.quit(); } catch (Exception e) { } jedis.disconnect(); } catch (Exception e) { } } * * @author chenzq * @date 2019年4月24日 下午10:48:29 * @version V1.0 * @Copyright: Copyright(c) 2019 jaesonchen.com Inc. All rights reserved. */ package com.asiainfo.redis;
jaesonchen/redis-study
src/main/java/com/asiainfo/redis/package-info.java
66,657
package exp.libs.algorithm.basic; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * <PRE> * FIXME 排序算法 * 适用范围: * 时间复杂度: * 空间复杂度: * </PRE> * <br/><B>PROJECT : </B> exp-libs * <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a> * @version 2022-03-06 * @author EXP: [email protected] * @since JDK 1.8+ */ public class Sorts { public static void radixSort() { // TODO 基排 } public static void quickSort() { // TODO 快排 } public static void heapSort() { // TODO: 堆排 } public static void binSort() { // TODO: 桶排序/箱排序 } /** * <pre> * 冒泡排序 * 在最优情况下只需要经过n-1次比较即可得出结果(这个最优情况那就是序列己是正序, * 从100K的正序结果可以看出结果正是如此),但在最坏情况下,即倒序(或一个较小值在最后), * 下沉算法将需要n(n-1)/2次比较。所以一般情况下,特别是在逆序时,它很不理想。 * 它是对数据有序性非常敏感的排序算法。 * 默认为升序 * </pre> * * @param list * 集合 */ @SuppressWarnings("rawtypes") public static void bubbleSort(List<Comparable> list) { bubbleSort(list, true); } /** * <pre> * 冒泡排序 * 在最优情况下只需要经过n-1次比较即可得出结果(这个最优情况那就是序列己是正序, * 从100K的正序结果可以看出结果正是如此),但在最坏情况下,即倒序(或一个较小值在最后), * 下沉算法将需要n(n-1)/2次比较。所以一般情况下,特别是在逆序时,它很不理想。 * 它是对数据有序性非常敏感的排序算法。 * </pre> * * @param list * 集合 * @param asc * 是否升序排列,true升序,false降序 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void bubbleSort(List<Comparable> list, boolean asc) { for (int i = 0; i < list.size() - 1; i++) { for (int j = 0; j < list.size() - i - 1; j++) { Comparable a; if (asc && list.get(j).compareTo(list.get(j + 1)) > 0) { // 升序 a = list.get(j); list.set((j), list.get(j + 1)); list.set(j + 1, a); } else if (!asc & list.get(j).compareTo(list.get(j + 1)) < 0) { // 降序 a = list.get(j); list.set((j), list.get(j + 1)); list.set(j + 1, a); } } } } /** * <pre> * 选择排序 * 它的比较次数一定:n(n-1)/2。也因此无论在序列何种情况下, * 它都不会有优秀的表现(从上100K的正序和反序数据可以发现它耗时相差不多, * 相差的只是数据移动时间),可见对数据的有序性不敏感。它虽然比较次数多, * 但它的数据交换量却很少。所以我们将发现它在一般情况下将快于冒泡排序。 * </pre> * * @param list * 集合 * @param asc * 是否升序排列 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void selectionSort(List<Comparable> list, boolean asc) { for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { if (asc && (list.get(i).compareTo(list.get(j)) > 0)) { Comparable temp = list.get(i); list.set((i), list.get(j)); list.set(j, temp); } else if (!asc && list.get(i).compareTo(list.get(j)) < 0) { Comparable temp = list.get(i); list.set((i), list.get(j)); list.set(j, temp); } } } } /** * <pre> * 选择排序 * 它的比较次数一定:n(n-1)/2。也因此无论在序列何种情况下, * 它都不会有优秀的表现(从上100K的正序和反序数据可以发现它耗时相差不多, * 相差的只是数据移动时间),可见对数据的有序性不敏感。它虽然比较次数多, * 但它的数据交换量却很少。所以我们将发现它在一般情况下将快于冒泡排序。 * 默认是升序 * </pre> * * @param list * 集合 */ @SuppressWarnings("rawtypes") public static void selectionSort(List<Comparable> list) { selectionSort(list, true); } /** * <pre> * 插入排序 * 每次比较后最多移掉一个逆序,因此与冒泡排序的效率相同.但它在速度 * 上还是要高点,这是因为在冒泡排序下是进行值交换,而在插入排序下是值移动, * 所以直接插入排序将要优于冒泡排序.直接插入法也是一种对数据的有序性非常敏感的一种算法. * 在有序情况下只需要经过n-1次比较,在最坏情况下,将需要n(n-1)/2次比较 * </pre> * * @param list * 集合 * @param asc * 是否升序排列 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void insertSort(List<Comparable> list, boolean asc) { int i; int j; Comparable temp; for (i = 1; i < list.size(); i++) { temp = list.get(i); if (asc) { for (j = i - 1; j >= 0 && temp.compareTo(list.get(j)) < 0; j--) { list.set((j + 1), list.get(j)); } list.set((j + 1), temp); } else { for (j = i - 1; j >= 0 && temp.compareTo(list.get(j)) > 0; j--) { list.set((j + 1), list.get(j)); } list.set((j + 1), temp); } } } /** * <pre> * 插入排序 * 每次比较后最多移掉一个逆序,因此与冒泡排序的效率相同.但它在速度 * 上还是要高点,这是因为在冒泡排序下是进行值交换,而在插入排序下是值移动, * 所以直接插入排序将要优于冒泡排序.直接插入法也是一种对数据的有序性非常敏感的一种算法. * 在有序情况下只需要经过n-1次比较,在最坏情况下,将需要n(n-1)/2次比较 * 默认为升序 * </pre> * * @param list * 集合 */ @SuppressWarnings("rawtypes") public static void insertSort(List<Comparable> list) { insertSort(list, true); } /** * <pre> * 快速排序 * 它同样是冒泡排序的改进,它通过一次交换能消除多个逆序,这样可以减少逆序时所消耗的扫描和数据交换次数. * 在最优情况下,它的排序时间复杂度为O(nlog2n).即每次划分序列时,能均匀分成两个子串. * 但最差情况下它的时间复杂度将是O(n&circ;2).即每次划分子串时,一串为空,另一串为m-1 * (程序中的100K正序和逆序就正是这样,如果程序中采用每次取序列中部数据作为划分点,那将在正序和逆时达到最优). * 从100K中正序的结果上看“快速排序”会比“冒泡排序”更慢,这主要是“冒泡排序”中采用了提前结束排序的方法. * 有的书上这解释“快速排序”,在理论上讲,如果每次能均匀划分序列,它将是最快的排序算法,因此称它作快速排序. * 虽然很难均匀划分序列,但就平均性能而言,它仍是基于关键字比较的内部排序算法中速度最快者。 * 默认为升序 * </pre> * * @param obj * 集合 */ @SuppressWarnings("rawtypes") public static void quickSort(List<Comparable> obj) { quickSort(obj, 0, obj.size(), true); } /** * <pre> * 快速排序 * 它同样是冒泡排序的改进,它通过一次交换能消除多个逆序,这样可以减少逆序时所消耗的扫描和数据交换次数. * 在最优情况下,它的排序时间复杂度为O(nlog2n).即每次划分序列时,能均匀分成两个子串. * 但最差情况下它的时间复杂度将是O(n&circ;2).即每次划分子串时,一串为空,另一串为m-1 * (程序中的100K正序和逆序就正是这样,如果程序中采用每次取序列中部数据作为划分点,那将在正序和逆时达到最优). * 从100K中正序的结果上看“快速排序”会比“冒泡排序”更慢,这主要是“冒泡排序”中采用了提前结束排序的方法. * 有的书上这解释“快速排序”,在理论上讲,如果每次能均匀划分序列,它将是最快的排序算法,因此称它作快速排序. * 虽然很难均匀划分序列,但就平均性能而言,它仍是基于关键字比较的内部排序算法中速度最快者。 * </pre> * * @param obj * 集合 * @param asc * 是否升序排列 */ @SuppressWarnings("rawtypes") public static void quickSort(List<Comparable> obj, boolean asc) { quickSort(obj, 0, obj.size(), asc); } @SuppressWarnings({ "rawtypes", "unchecked" }) private static void quickSort(List<Comparable> obj, int left, int right, boolean asc) { int i, j; Comparable middle, temp; i = left; j = right; middle = obj.get(left); while (true) { if (asc) { while ((++i) < right - 1 && obj.get(i).compareTo(middle) < 0) ; while ((--j) > left && obj.get(j).compareTo(middle) > 0) ; if (i >= j) break; temp = obj.get(i); obj.set(i, obj.get(j)); obj.set(j, temp); } else { while ((++i) < right - 1 && obj.get(i).compareTo(middle) > 0) ; while ((--j) > left && obj.get(j).compareTo(middle) < 0) ; if (i >= j) break; temp = obj.get(i); obj.set(i, obj.get(j)); obj.set(j, temp); } } obj.set(left, obj.get(j)); obj.set(j, middle); if (left < j) quickSort(obj, left, j, asc); if (right > i) quickSort(obj, i, right, asc); } /** * <pre> * 归并排序 * 归并排序是一种非就地排序,将需要与待排序序列一样多的辅助空间.在使用它对两个己有序的序列归并, * 将有无比的优势.其时间复杂度无论是在最好情况下还是在最坏情况下均是O(nlog2n). * 对数据的有序性不敏感.若数据节点数据量大,那将不适合.但可改造成索引操作,效果将非常出色. * 默认为升序 * </pre> * * @param obj * 集合 */ @SuppressWarnings("rawtypes") public static void mergeSort(List<Comparable> obj) { List<Comparable> bridge = new ArrayList<Comparable>(obj); // 初始化中间数组 mergeSort(obj, 0, obj.size() - 1, true, bridge); // 归并排序 bridge = null; } /** * <pre> * 归并排序 * 归并排序是一种非就地排序,将需要与待排序序列一样多的辅助空间.在使用它对两个己有序的序列归并, * 将有无比的优势.其时间复杂度无论是在最好情况下还是在最坏情况下均是O(nlog2n). * 对数据的有序性不敏感.若数据节点数据量大,那将不适合.但可改造成索引操作,效果将非常出色. * </pre> * * @param obj * 集合 * @param asc * 是否升序排列 */ @SuppressWarnings("rawtypes") public static void mergeSort(List<Comparable> obj, boolean asc) { List<Comparable> bridge = new ArrayList<Comparable>(obj); // 初始化中间数组 mergeSort(obj, 0, obj.size() - 1, asc, bridge); // 归并排序 bridge = null; } @SuppressWarnings("rawtypes") private static void mergeSort(List<Comparable> obj, int left, int right, boolean asc, List<Comparable> bridge) { if (left < right) { int center = (left + right) / 2; mergeSort(obj, left, center, asc, bridge); mergeSort(obj, center + 1, right, asc, bridge); merge(obj, left, center, right, asc, bridge); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private static void merge(List<Comparable> obj, int left, int center, int right, boolean asc, List<Comparable> bridge) { int mid = center + 1; int third = left; int tmp = left; while (left <= center && mid <= right) { // 从两个数组中取出小的放入中间数组 if (asc) { if (obj.get(left).compareTo(obj.get(mid)) <= 0) { bridge.set(third++, obj.get(left++)); } else { bridge.set(third++, obj.get(mid++)); } } else { if (obj.get(left).compareTo(obj.get(mid)) > 0) { bridge.set(third++, obj.get(left++)); } else { bridge.set(third++, obj.get(mid++)); } } } // 剩余部分依次置入中间数组 while (mid <= right) { bridge.set(third++, obj.get(mid++)); } while (left <= center) { bridge.set(third++, obj.get(left++)); } // 将中间数组的内容拷贝回原数组 copy(obj, tmp, right, bridge); } @SuppressWarnings("rawtypes") private static void copy(List<Comparable> obj, int left, int right, List<Comparable> bridge) { while (left <= right) { obj.set(left, bridge.get(left)); left++; } } /** * <pre> * 对排序后的队列进行快速合并,使合并后的队列有序(归并排序算法). * 默认为升序 * * 使用实例: * List list1 = new ArrayList(); * list1.add(&quot;dsd&quot;); * list1.add(&quot;tsest&quot;); * list1.add(&quot;ga&quot;); * list1.add(&quot;aaaa&quot;); * list1.add(&quot;bb&quot;); * ListUtils.quickSort(list1); * * List list2 = new ArrayList(); * list2.add(&quot;cc&quot;); * list2.add(&quot;dd&quot;); * list2.add(&quot;zz&quot;); * ListUtils.quickSort(list2); * * List listAll = new ArrayList(); * listAll.add(list1); * listAll.add(list2); * * List sortList = ListUtils.listMerge(listAll); * System.out.println(sortList); * </pre> * * @param objs * 集合的集合 * @return 排序后的集合 */ @SuppressWarnings("rawtypes") public static List listMerge(List<List<Comparable>> objs) { return listMerge(objs, true); } /** * <pre> * 对排序后的队列进行快速合并,使合并后的队列有序(归并排序算法). * List list1 = new ArrayList(); * list1.add(&quot;dsd&quot;); * list1.add(&quot;tsest&quot;); * list1.add(&quot;ga&quot;); * list1.add(&quot;aaaa&quot;); * list1.add(&quot;bb&quot;); * ListUtils.quickSort(list1); * * List list2 = new ArrayList(); * list2.add(&quot;cc&quot;); * list2.add(&quot;dd&quot;); * list2.add(&quot;zz&quot;); * ListUtils.quickSort(list2); * * List listAll = new ArrayList(); * listAll.add(list1); * listAll.add(list2); * * List sortList = ListUtils.listMerge(listAll,false); * System.out.println(sortList); * </pre> * * @param objs * 集合的集合 * @param asc * 是否升序排列 * @return 排序后的集合 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static List listMerge(List<List<Comparable>> objs, boolean asc) { List list = new ArrayList(); for (List<Comparable> obj : objs) { list.addAll(obj); mergeSort(list, asc); } return list; } /** * <pre> * 二分查找法 * 在进行此调用之前,必须根据列表元素的自然顺序对列表进行升序排序(通过 sort(List) 方法). * 如果没有对列表进行排序,则结果是不确定的。如果列表包含多个等于指定对象的元素,则无法保证找到的是哪一个。 * </pre> * * @param obj * 集合 * @param key * 查找内容 * @return 关键字在集合中的位置 */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static int binarySearch(List obj, Object key) { int index = Collections.binarySearch(obj, key); return index; } /** * 根据下标找到相对应的对象 * * @param obj * 集合 * @param key * 查找内容 * @return 对应的对象值 */ @SuppressWarnings("rawtypes") public static Object getObject(List obj, int key) { return obj.get(key); } }
EXP-Codes/exp-libs-refactor
exp-libs-algorithm/src/main/java/exp/libs/algorithm/basic/Sorts.java
66,661
package p1840; import java.nio.charset.StandardCharsets; import java.util.Scanner; import java.util.TreeSet; public class CF1840D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); int t = scanner.nextInt(); while (t-- > 0) { int n = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } System.out.println(solve(n, a)); } } private static int min, max; private static String solve(int n, int[] a) { TreeSet<Integer> treeSet = new TreeSet<>(); for (int x : a) { treeSet.add(x); } min = treeSet.first(); max = treeSet.last(); int left = 0; int right = max - min; while (left < right) { int mid = left + (right - left) / 2; // 边界二分 F, F,..., F, [T, T,..., T] // ----------------------^ if (checkMid(treeSet, mid)) { right = mid; } else { left = mid + 1; } } return String.valueOf(left); } private static boolean checkMid(TreeSet<Integer> treeSet, int mid) { int lo = min + mid * 2; int hi = max - mid * 2; Integer low = treeSet.higher(lo); Integer high = treeSet.lower(hi); if (low == null || high == null) return true; return high - low <= mid * 2; } } /* D. Wooden Toy Festival https://codeforces.com/contest/1840/problem/D 题目大意: 在一个小镇上,有一家木工作坊。由于小镇很小,只有三个雕刻师在那里工作。 不久,镇上计划举办一个木制玩具节。车间员工想为此做准备。 他们知道 n 个人会带着制作木制玩具的要求来车间。每个人都是不同的,可能想要不同的玩具。为简单起见,我们将第 i 个人想要的玩具样式表示为 ai(1≤ai≤109)。 每个雕刻家可以提前选择一个图案 x(1≤x≤10^9),不同的雕刻家可以选择不同的图案。在节日的准备过程中,雕刻家将完美地研究出制作选定图案的玩具的技术,这将使他们能够立即将其从木头中切割出来。 为选择了 x 图案的雕刻家制作一个 y 图案的玩具,需要花费 x - y 时间,因为这个玩具越像他能立即做出来的玩具,雕刻家就能越快地完成工作。 在节日当天,当下一个人带着制作木制玩具的要求来到作坊时,雕刻家可以选择谁来做这项工作。同时,雕刻师是非常熟练的人,可以同时为不同的人工作。 由于人们不喜欢等待,雕刻家希望选择这样的准备模式,即所有人的最大等待时间尽可能小。 输出雕刻师可以达到的最佳最大等待时间。 --- 在第一个例子中,雕刻家可以选择图案 1、7、9 进行准备。 在第二例中,雕刻家可以选择图案 3、30、60 进行准备。 在本例中,雕刻师可选择图案 14、50、85 进行准备。 二分套二分 ====== input 5 6 1 7 7 9 9 9 6 5 4 2 1 30 60 9 14 19 37 59 1 4 4 98 73 1 2 6 3 10 1 17 15 11 output 0 2 13 0 1 */
gdut-yy/leetcode-hub-java
codeforces/codeforces-19/src/main/java/p1840/CF1840D.java
66,662
package com.tapdata.tm.task.service; import com.tapdata.tm.base.dto.Page; import com.tapdata.tm.base.dto.ResponseMessage; import com.tapdata.tm.commons.dag.vo.TestRunDto; import com.tapdata.tm.commons.schema.MetadataTransformerItemDto; import com.tapdata.tm.commons.task.dto.TaskDto; import com.tapdata.tm.config.security.UserDetail; import com.tapdata.tm.task.vo.JsResultDto; import com.tapdata.tm.task.vo.JsResultVo; import java.util.Map; public interface TaskNodeService { Page<MetadataTransformerItemDto> getNodeTableInfo(String taskId, String taskRecordId, String nodeId, String searchTableName, Integer page, Integer pageSize, UserDetail userDetail); void testRunJsNode(TestRunDto dto, UserDetail userDetail); Map<String, Object> testRunJsNodeRPC(TestRunDto dto, UserDetail userDetail, int jsType); void saveResult(JsResultDto jsResultDto); /** * @deprecated 执行试运行后即可获取到试运行结果和试运行日志,无需使用此获取结果,不久的将来会移除这个function * */ ResponseMessage<JsResultVo> getRun(String taskId, String jsNodeId, Long version); void checkFieldNode(TaskDto taskDto, UserDetail userDetail); }
tapdata/tapdata
manager/tm/src/main/java/com/tapdata/tm/task/service/TaskNodeService.java
66,664
package com.yeyue.learns.enity.movie; import java.util.List; /** * Created by li.xiao on 2018-1-26. */ public class MovieCelebrity { /** * website : * mobile_url : https://movie.douban.com/celebrity/1054395/mobile * aka_en : ["Elijah Jordan Wood (本名)","Elwood, Lij and Monkey (昵称)"] * name : 伊利亚·伍德 * works : [{"roles":["演员"],"subject":{"rating":{"max":10,"average":9.3,"details":{"1":7,"3":72,"2":6,"5":1000,"4":337},"stars":"50","min":0},"genres":["喜剧","短片","音乐"],"title":"SMAPxSMAP","casts":[{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1941.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1941.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1941.jpg"},"name_en":"Masahiro Nakai","name":"中居正广","alt":"https://movie.douban.com/celebrity/1023890/","id":"1023890"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1365448692.55.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1365448692.55.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1365448692.55.jpg"},"name_en":"Takuya Kimura","name":"木村拓哉","alt":"https://movie.douban.com/celebrity/1041371/","id":"1041371"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1875.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1875.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1875.jpg"},"name_en":"Gorô Inagaki","name":"稻垣吾郎","alt":"https://movie.douban.com/celebrity/1104097/","id":"1104097"}],"durations":["52分钟"],"collect_count":2456,"mainland_pubdate":"","has_video":false,"original_title":"SMAPxSMAP","subtype":"tv","directors":[],"pubdates":["1996-04-15"],"year":"1996","images":{"small":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2375579599.jpg","large":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2375579599.jpg","medium":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2375579599.jpg"},"alt":"https://movie.douban.com/subject/1763308/","id":"1763308"}},{"roles":["演员"],"subject":{"rating":{"max":10,"average":9.2,"details":{"1":2,"3":83,"2":4,"5":771,"4":263},"stars":"50","min":0},"genres":["喜剧","爱情"],"title":"欢乐一家亲 第一季","casts":[{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1396501988.66.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1396501988.66.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1396501988.66.jpg"},"name_en":"Kelsey Grammer","name":"凯尔希·格兰莫","alt":"https://movie.douban.com/celebrity/1031847/","id":"1031847"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p38076.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p38076.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p38076.jpg"},"name_en":"Jane Leeves","name":"简·丽芙丝","alt":"https://movie.douban.com/celebrity/1000062/","id":"1000062"},{"avatars":{"small":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p21378.jpg","large":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p21378.jpg","medium":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p21378.jpg"},"name_en":"David Hyde Pierce","name":"大卫·海德·皮尔斯","alt":"https://movie.douban.com/celebrity/1000151/","id":"1000151"}],"durations":["22分钟"],"collect_count":1659,"mainland_pubdate":"","has_video":false,"original_title":"Frasier","subtype":"tv","directors":[{"avatars":{"small":"https://img1.doubanio.com/f/movie/ca527386eb8c4e325611e22dfcb04cc116d6b423/pics/movie/celebrity-default-small.png","large":"https://img3.doubanio.com/f/movie/63acc16ca6309ef191f0378faf793d1096a3e606/pics/movie/celebrity-default-large.png","medium":"https://img1.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png"},"name_en":"David Angell","name":"David Angell","alt":"https://movie.douban.com/celebrity/1000586/","id":"1000586"},{"avatars":null,"name_en":"","name":"Peter Casey","alt":null,"id":null},{"avatars":null,"name_en":"","name":"David Lee","alt":null,"id":null}],"pubdates":["1993-09-16(美国)"],"year":"1993","images":{"small":"https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2212098341.jpg","large":"https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2212098341.jpg","medium":"https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2212098341.jpg"},"alt":"https://movie.douban.com/subject/1438242/","id":"1438242"}},{"roles":["演员"],"subject":{"rating":{"max":10,"average":9.2,"details":{"1":0,"3":244,"2":22,"5":3039,"4":1105},"stars":"50","min":0},"genres":["动画","惊悚","冒险"],"title":"花园墙外","casts":[{"avatars":{"small":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg","large":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg","medium":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg"},"name_en":"Elijah Wood","name":"伊利亚·伍德","alt":"https://movie.douban.com/celebrity/1054395/","id":"1054395"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1475344076.93.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1475344076.93.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1475344076.93.jpg"},"name_en":"Collin Dean","name":"科林·迪恩","alt":"https://movie.douban.com/celebrity/1354353/","id":"1354353"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p56083.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p56083.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p56083.jpg"},"name_en":"Melanie Lynskey","name":"梅兰妮·林斯基","alt":"https://movie.douban.com/celebrity/1044729/","id":"1044729"}],"durations":["11分钟"],"collect_count":6843,"mainland_pubdate":"","has_video":true,"original_title":"Over the Garden Wall","subtype":"tv","directors":[{"avatars":{"small":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/pc4A2hFhLBxUcel_avatar_uploaded1444453249.48.jpg","large":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/pc4A2hFhLBxUcel_avatar_uploaded1444453249.48.jpg","medium":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/pc4A2hFhLBxUcel_avatar_uploaded1444453249.48.jpg"},"name_en":"Patrick McHale","name":"帕特里克·麦克海尔","alt":"https://movie.douban.com/celebrity/1352267/","id":"1352267"}],"pubdates":["2014-11-03(美国)"],"year":"2014","images":{"small":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2212480699.jpg","large":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2212480699.jpg","medium":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2212480699.jpg"},"alt":"https://movie.douban.com/subject/25941842/","id":"25941842"}},{"roles":["演员"],"subject":{"rating":{"max":10,"average":9.1,"details":{"1":372,"3":15996,"2":1173,"5":137412,"4":60717},"stars":"45","min":0},"genres":["剧情","动作","奇幻"],"title":"指环王3:王者无敌","casts":[{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p29922.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p29922.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p29922.jpg"},"name_en":"Viggo Mortensen","name":"维果·莫腾森","alt":"https://movie.douban.com/celebrity/1054520/","id":"1054520"},{"avatars":{"small":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg","large":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg","medium":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg"},"name_en":"Elijah Wood","name":"伊利亚·伍德","alt":"https://movie.douban.com/celebrity/1054395/","id":"1054395"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p34032.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p34032.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p34032.jpg"},"name_en":"Sean Astin","name":"西恩·奥斯汀","alt":"https://movie.douban.com/celebrity/1031818/","id":"1031818"}],"durations":["201分钟","251分钟(加长版)","263分钟(蓝光加长版)"],"collect_count":396049,"mainland_pubdate":"2004-03-12","has_video":true,"original_title":"The Lord of the Rings: The Return of the King","subtype":"movie","directors":[{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p40835.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p40835.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p40835.jpg"},"name_en":"Peter Jackson","name":"彼得·杰克逊","alt":"https://movie.douban.com/celebrity/1040524/","id":"1040524"}],"pubdates":["2003-12-17(美国)","2004-03-12(中国大陆)"],"year":"2003","images":{"small":"https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1910825503.jpg","large":"https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1910825503.jpg","medium":"https://img3.doubanio.com/view/photo/s_ratio_poster/public/p1910825503.jpg"},"alt":"https://movie.douban.com/subject/1291552/","id":"1291552"}},{"roles":["演员"],"subject":{"rating":{"max":10,"average":9.1,"details":{"1":12,"3":135,"2":23,"5":1374,"4":546},"stars":"45","min":0},"genres":["喜剧","科幻"],"title":"全能侦探社 第二季","casts":[{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p2491.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p2491.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p2491.jpg"},"name_en":"Samuel Barnett","name":"塞缪尔·巴奈特","alt":"https://movie.douban.com/celebrity/1045095/","id":"1045095"},{"avatars":{"small":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg","large":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg","medium":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg"},"name_en":"Elijah Wood","name":"伊利亚·伍德","alt":"https://movie.douban.com/celebrity/1054395/","id":"1054395"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p20243.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p20243.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p20243.jpg"},"name_en":"Hannah Marks","name":"汉娜·马克斯","alt":"https://movie.douban.com/celebrity/1000221/","id":"1000221"}],"durations":["43分钟"],"collect_count":2699,"mainland_pubdate":"","has_video":false,"original_title":"Dirk Gently's Holistic Detective Agency","subtype":"tv","directors":[{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1491833329.11.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1491833329.11.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1491833329.11.jpg"},"name_en":"Douglas Mackinnon","name":"道格拉斯·麦金农","alt":"https://movie.douban.com/celebrity/1290655/","id":"1290655"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1497764721.35.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1497764721.35.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1497764721.35.jpg"},"name_en":"Michael Patrick Jann","name":"迈克尔·帕特里克·詹恩","alt":"https://movie.douban.com/celebrity/1045183/","id":"1045183"},{"avatars":{"small":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1405220759.67.jpg","large":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1405220759.67.jpg","medium":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1405220759.67.jpg"},"name_en":"Max Landis","name":"马克斯·兰迪斯 ","alt":"https://movie.douban.com/celebrity/1023473/","id":"1023473"},{"avatars":{"small":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1374043154.58.jpg","large":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1374043154.58.jpg","medium":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1374043154.58.jpg"},"name_en":"Dean Parisot","name":"迪恩·帕里索特","alt":"https://movie.douban.com/celebrity/1293954/","id":"1293954"}],"pubdates":["2017-10-14(美国)"],"year":"2017","images":{"small":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2502201879.jpg","large":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2502201879.jpg","medium":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2502201879.jpg"},"alt":"https://movie.douban.com/subject/26946433/","id":"26946433"}}] * name_en : Elijah Wood * gender : 男 * professions : ["演员","制片","配音","副导演"] * avatars : {"small":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg","large":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg","medium":"https://img1.doubanio.com/view/celebrity/s_ratio_celebrity/public/p51597.jpg"} * summary : 伊利亚·乔丹·伍德(Elijah Jordan Wood),1981年1月28日出生于美国爱荷华州的锡达拉皮兹,父亲沃伦 伊利亚·伍德·伍德,母亲黛比·伍德。他在家中排行老二,上边有一个哥哥扎克,下面有一个妹妹汉纳·伍德。年幼时候,表现欲极强的伊利亚就表现出取悦别人的才能,母亲决定带他到洛杉矶,参加一年一度的国际模特人材协会大会,寻找发展机会。很快,他在好莱坞令人眼花缭乱的表演世界找到了一份工作。不久,他开始涉足商业表演,在电视表演界得到一些小的角色。1990年,他参加了影片《适者生存》(Avalon)的拍摄,这是他第一次扮演主角,从此揭开了他表演生涯的序幕。此后,他一口气参演了《温馨赤子情》(Paradise),《海阔天空》(Radio Flyer)和《今生有约》(Forever Young)等影片。 1993年,和麦考利·卡尔金共同主演过《危险小天使》(The Good Son)之后,伊利亚又参加了影片《浪子保镖》(North)的拍摄。虽然《浪子保镖》的票房收入十分惨淡,但伊影片中的伊利亚·伍德(8张)利亚的表现却受到人们的称赞,成为该片惟一一个亮点。此后2年间,他在演艺方面表现平平。1996年,伊利亚参加了由旧电视节目 伊利亚·伍德翻拍的影片《飞宝》(Flipper),立即重新获得观众的认可。之后,他先后参加了无数影片的拍摄,增加了自己在好莱坞电影界的影响力。这时,有不少电影评论家怀疑,他那种博得观众喜欢的孩子气的表演才华是否会重蹈很多儿童演员的覆辙,逐渐江郎才尽,但伊利亚用事实证明,这种表演才华只会使他变得更加有力。 1998年,他先后出演《慧星撞地球(又译深度撞击)》(Deep Impact)和《老师不是人》(The Faculty),赢得观众广泛支持。1999年,伊利亚参加了3部影片的拍摄:《记忆的旅人》(The Bumblebee Flies Anyway),《纵横黑白道》(Black and White)和《傻瓜一族》(Chain of Fools),但这几部影片都从来没有在更为大的范围内发行。接着,伊利亚参加了由J·R·R·Tolkien原著改编的《魔戒三部曲》的拍摄,这三部影片被称为电影史上最大的一项工程。 * photos : [{"thumb":"https://img1.doubanio.com/view/photo/thumb/public/p2203408008.jpg","image":"https://img1.doubanio.com/view/photo/photo/public/p2203408008.jpg","cover":"https://img1.doubanio.com/view/photo/albumcover/public/p2203408008.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/2203408008/","id":"2203408008","icon":"https://img1.doubanio.com/view/photo/icon/public/p2203408008.jpg"},{"thumb":"https://img3.doubanio.com/view/photo/thumb/public/p1573366851.jpg","image":"https://img3.doubanio.com/view/photo/photo/public/p1573366851.jpg","cover":"https://img3.doubanio.com/view/photo/albumcover/public/p1573366851.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/1573366851/","id":"1573366851","icon":"https://img3.doubanio.com/view/photo/icon/public/p1573366851.jpg"},{"thumb":"https://img3.doubanio.com/view/photo/thumb/public/p1327676224.jpg","image":"https://img3.doubanio.com/view/photo/photo/public/p1327676224.jpg","cover":"https://img3.doubanio.com/view/photo/albumcover/public/p1327676224.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/1327676224/","id":"1327676224","icon":"https://img3.doubanio.com/view/photo/icon/public/p1327676224.jpg"},{"thumb":"https://img3.doubanio.com/view/photo/thumb/public/p912171586.jpg","image":"https://img3.doubanio.com/view/photo/photo/public/p912171586.jpg","cover":"https://img3.doubanio.com/view/photo/albumcover/public/p912171586.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/912171586/","id":"912171586","icon":"https://img3.doubanio.com/view/photo/icon/public/p912171586.jpg"},{"thumb":"https://img1.doubanio.com/view/photo/thumb/public/p1376901737.jpg","image":"https://img1.doubanio.com/view/photo/photo/public/p1376901737.jpg","cover":"https://img1.doubanio.com/view/photo/albumcover/public/p1376901737.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/1376901737/","id":"1376901737","icon":"https://img1.doubanio.com/view/photo/icon/public/p1376901737.jpg"},{"thumb":"https://img1.doubanio.com/view/photo/thumb/public/p912171217.jpg","image":"https://img1.doubanio.com/view/photo/photo/public/p912171217.jpg","cover":"https://img1.doubanio.com/view/photo/albumcover/public/p912171217.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/912171217/","id":"912171217","icon":"https://img1.doubanio.com/view/photo/icon/public/p912171217.jpg"},{"thumb":"https://img3.doubanio.com/view/photo/thumb/public/p912171444.jpg","image":"https://img3.doubanio.com/view/photo/photo/public/p912171444.jpg","cover":"https://img3.doubanio.com/view/photo/albumcover/public/p912171444.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/912171444/","id":"912171444","icon":"https://img3.doubanio.com/view/photo/icon/public/p912171444.jpg"},{"thumb":"https://img3.doubanio.com/view/photo/thumb/public/p2226580306.jpg","image":"https://img3.doubanio.com/view/photo/photo/public/p2226580306.jpg","cover":"https://img3.doubanio.com/view/photo/albumcover/public/p2226580306.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/2226580306/","id":"2226580306","icon":"https://img3.doubanio.com/view/photo/icon/public/p2226580306.jpg"},{"thumb":"https://img3.doubanio.com/view/photo/thumb/public/p2221495494.jpg","image":"https://img3.doubanio.com/view/photo/photo/public/p2221495494.jpg","cover":"https://img3.doubanio.com/view/photo/albumcover/public/p2221495494.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/2221495494/","id":"2221495494","icon":"https://img3.doubanio.com/view/photo/icon/public/p2221495494.jpg"},{"thumb":"https://img3.doubanio.com/view/photo/thumb/public/p1139491646.jpg","image":"https://img3.doubanio.com/view/photo/photo/public/p1139491646.jpg","cover":"https://img3.doubanio.com/view/photo/albumcover/public/p1139491646.jpg","alt":"https://movie.douban.com/celebrity/1054395/photo/1139491646/","id":"1139491646","icon":"https://img3.doubanio.com/view/photo/icon/public/p1139491646.jpg"}] * birthday : 1981-01-28 * aka : ["伊莱贾·伍德"] * alt : https://movie.douban.com/celebrity/1054395/ * born_place : 美国,爱荷华州,锡达拉皮兹 * constellation : 水瓶座 * id : 1054395 */ private String website; private String mobile_url; private String name; private String name_en; private String gender; private MovieImage avatars; private String summary; private String birthday; private String alt; private String born_place; private String constellation; private String id; private List<String> aka_en; private List<WorksBean> works; private List<String> professions; private List<MovieImage> photos; private List<String> aka; public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public String getMobile_url() { return mobile_url; } public void setMobile_url(String mobile_url) { this.mobile_url = mobile_url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getName_en() { return name_en; } public void setName_en(String name_en) { this.name_en = name_en; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public MovieImage getAvatars() { return avatars; } public void setAvatars(MovieImage avatars) { this.avatars = avatars; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getAlt() { return alt; } public void setAlt(String alt) { this.alt = alt; } public String getBorn_place() { return born_place; } public void setBorn_place(String born_place) { this.born_place = born_place; } public String getConstellation() { return constellation; } public void setConstellation(String constellation) { this.constellation = constellation; } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getAka_en() { return aka_en; } public void setAka_en(List<String> aka_en) { this.aka_en = aka_en; } public List<WorksBean> getWorks() { return works; } public void setWorks(List<WorksBean> works) { this.works = works; } public List<String> getProfessions() { return professions; } public void setProfessions(List<String> professions) { this.professions = professions; } public List<MovieImage> getPhotos() { return photos; } public void setPhotos(List<MovieImage> photos) { this.photos = photos; } public List<String> getAka() { return aka; } public void setAka(List<String> aka) { this.aka = aka; } public static class WorksBean { /** * roles : ["演员"] * subject : {"rating":{"max":10,"average":9.3,"details":{"1":7,"3":72,"2":6,"5":1000,"4":337},"stars":"50","min":0},"genres":["喜剧","短片","音乐"],"title":"SMAPxSMAP","casts":[{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1941.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1941.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1941.jpg"},"name_en":"Masahiro Nakai","name":"中居正广","alt":"https://movie.douban.com/celebrity/1023890/","id":"1023890"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1365448692.55.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1365448692.55.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1365448692.55.jpg"},"name_en":"Takuya Kimura","name":"木村拓哉","alt":"https://movie.douban.com/celebrity/1041371/","id":"1041371"},{"avatars":{"small":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1875.jpg","large":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1875.jpg","medium":"https://img3.doubanio.com/view/celebrity/s_ratio_celebrity/public/p1875.jpg"},"name_en":"Gorô Inagaki","name":"稻垣吾郎","alt":"https://movie.douban.com/celebrity/1104097/","id":"1104097"}],"durations":["52分钟"],"collect_count":2456,"mainland_pubdate":"","has_video":false,"original_title":"SMAPxSMAP","subtype":"tv","directors":[],"pubdates":["1996-04-15"],"year":"1996","images":{"small":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2375579599.jpg","large":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2375579599.jpg","medium":"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p2375579599.jpg"},"alt":"https://movie.douban.com/subject/1763308/","id":"1763308"} */ private MovieBean subject; private List<String> roles; public MovieBean getSubject() { return subject; } public void setSubject(MovieBean subject) { this.subject = subject; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } } }
yeyueduxing/YeLearns
Learns/app/src/main/java/com/yeyue/learns/enity/movie/MovieCelebrity.java
66,666
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.Hashtable; public class MineGame extends JFrame implements ActionListener { JMenuBar bar; JMenu fileMenu1, fileMenu2; JMenuItem junior, middle, senior, custom, record; JMenuItem introduction, gamePlay; MineArea mineArea = null; File Record = new File("Record.txt"); Hashtable hashtable = null; ShowRecord showHeroRecord = null; JDialog set = null; JPanel panel, panel1, panel2, panel3, panel4; JLabel label, label1, label2, label3; JTextField row = null, column = null, mine = null; JButton confirm, cancel; JDialog introduce = null, play = null; JLabel label4, label5; MineGame() { mineArea = new MineArea(16, 16, 40, 2); add(mineArea, BorderLayout.CENTER); // 边框布局 bar = new JMenuBar(); fileMenu1 = new JMenu("游戏"); junior = new JMenuItem("初级"); middle = new JMenuItem("中级"); senior = new JMenuItem("高级"); custom = new JMenuItem("自定义"); record = new JMenuItem("扫雷榜"); fileMenu1.add(junior); fileMenu1.add(middle); fileMenu1.add(senior); fileMenu1.add(custom); fileMenu1.add(record); fileMenu2 = new JMenu("帮助"); introduction = new JMenuItem("介绍"); gamePlay = new JMenuItem("玩法"); fileMenu2.add(introduction); fileMenu2.add(gamePlay); bar.add(fileMenu1); bar.add(fileMenu2); setJMenuBar(bar); // 设置窗体的菜单栏 junior.addActionListener(this); middle.addActionListener(this); senior.addActionListener(this); custom.addActionListener(this); record.addActionListener(this); introduction.addActionListener(this); gamePlay.addActionListener(this); hashtable = new Hashtable(); hashtable.put("初级", "初级#" + 999 + "#匿名"); hashtable.put("中级", "中级#" + 999 + "#匿名"); hashtable.put("高级", "高级#" + 999 + "#匿名"); if (!Record.exists()) { try { FileOutputStream out = new FileOutputStream(Record); ObjectOutputStream objectOut = new ObjectOutputStream(out); objectOut.writeObject(hashtable); objectOut.close(); out.close(); } catch (IOException e) { } } showHeroRecord = new ShowRecord(this, hashtable); setBounds(300, 100, 480, 560); // 移动组件并调整大小 setVisible(true); // 使Window可见 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭Window的同时关闭资源 validate(); // 再次布置子组件 } public void actionPerformed(ActionEvent e) { if (e.getSource() == junior) { mineArea.initMineArea(9, 9, 10, 1); setBounds(300, 100, 270, 350); } if (e.getSource() == middle) { mineArea.initMineArea(16, 16, 40, 2); setBounds(300, 100, 480, 560); } if (e.getSource() == senior) { mineArea.initMineArea(16, 30, 99, 3); setBounds(100, 100, 900, 560); } if (e.getSource() == custom) { set = new JDialog(); set.setTitle("自定义难度"); set.setBounds(300, 100, 300, 130); set.setResizable(false);//设置大小不可变 set.setModal(true);//设置为对话框模式 panel = new JPanel(); //panel.setLayout(new BorderLayout()); panel1 = new JPanel(); panel2 = new JPanel(); panel3 = new JPanel(); panel4 = new JPanel(); label = new JLabel("请输入行列数与地雷数:", JLabel.CENTER); label1 = new JLabel("行:", JLabel.CENTER); label2 = new JLabel("列:", JLabel.CENTER); label3 = new JLabel("地雷数:", JLabel.CENTER); row = new JTextField(); row.setText("16"); row.setSize(1, 6); column = new JTextField(); column.setText("16"); mine = new JTextField(); mine.setText("40"); confirm = new JButton("确认"); confirm.addActionListener(this); cancel = new JButton("取消"); cancel.addActionListener(this); panel1.add(label1); panel1.add(row); panel2.add(label2); panel2.add(column); panel3.add(label3); panel3.add(mine); panel4.add(confirm); panel4.add(cancel); panel.add(panel1); panel.add(panel2); panel.add(panel3); set.add(label, BorderLayout.NORTH); set.add(panel, BorderLayout.CENTER); set.add(panel4, BorderLayout.SOUTH); set.setVisible(true); } if (e.getSource() == record) { if (showHeroRecord != null) showHeroRecord.setVisible(true); } if (e.getSource() == confirm) { int rowNum = Integer.parseInt(row.getText()); int columnNum = Integer.parseInt(column.getText()); int mineNum = Integer.parseInt(mine.getText()); if (rowNum < 9) rowNum = 9; if (rowNum > 16) rowNum = 16; if (columnNum < 9) columnNum = 9; if (columnNum > 30) columnNum = 30; if (mineNum < 10) mineNum = 10; if (mineNum > 99) mineNum = 99; mineArea.initMineArea(rowNum, columnNum, mineNum, 4); setBounds(100, 100, columnNum * 30, rowNum * 30 + 80); set.setVisible(false); } if (e.getSource() == cancel) { set.setVisible(false); } if (e.getSource() == introduction) { introduce = new JDialog(); introduce.setTitle("扫雷介绍"); introduce.setBounds(300, 100, 300, 300); introduce.setResizable(false); introduce.setModal(true); label4 = new JLabel(); label4.setSize(280, 250); label4.setText("<html><body>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp扫雷最原始的版本可以追溯到1973年" + "一款名为“方块”的游戏。不久,“方块”被改写成了游戏“Rlogic”。在“Rlogic”里,玩家的任务是作为美国" + "海军陆战队队员,为指挥中心探出一条没有地雷的安全路线,如果路全被地雷堵死就算输。" + "两年后,汤姆·安德森在“Rlogic”的基础上又编写出了游戏“地雷”,由此奠定了现代扫雷游戏的雏形。" + "1981年,微软公司的罗伯特·杜尔和卡特·约翰逊两位工程师在Windows3.1系统上加载了该游戏," + "扫雷游戏才正式在全世界推广开来。</body></html>"); introduce.add(label4); introduce.setVisible(true); } if (e.getSource() == gamePlay) { play = new JDialog(); play.setTitle("游戏玩法"); play.setBounds(300, 100, 300, 300); play.setResizable(false); play.setModal(true); label4 = new JLabel(); label4.setSize(280, 250); label4.setText("<html><body>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp扫游戏目标是在最短的时间内" + "根据点击格子出现的数字找出所有非雷格子,同时避免踩雷。<br>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp" + "&nbsp&nbsp当玩家点开一个格子时,会在该格子上显示周围8个格子的雷数" + "(如果没有雷则自动点开周围的格子),玩家需要通过这些数字来判断雷的位置," + "将是雷的格子标记为小红旗。当所有地雷被标记且非雷格子都被点开时游戏胜利。</body></html>"); play.add(label4); play.setVisible(true); } validate(); } public static void main(String args[]) { new MineGame(); } }
JaD1ng/Mine_Sweeper
src/MineGame.java
66,668
package algorithm; import java.util.Scanner; /** * * * T Torry从小喜爱数学。一天,老师告诉他,像2、3、5、7……这样的数叫做质数。 * Torry突然想到一个问题,前10、100、1000、10000……个质数的乘积是多少呢? * 他把这个问题告诉老师。老师愣住了,一时回答不出来。 * 于是Torry求助于会编程的你,请你算出前n个质数的乘积。 * 不过,考虑到你才接触编程不久,Torry只要你算出这个数模上50000的值。 * * * 输入格式 * 仅包含一个正整数n,其中n<=100000。 * * 输出格式 * 输出一行,即前n个质数的乘积模50000的值。 * * * 样例输入 * 1 * * 样例输出 * 2 * * * * * * @author tugeng * */ public class Perplexity_Of_Torry_Basic { public static boolean is_prime(Integer a) { if(a.intValue() ==2 || a.intValue()==3) { return true; } //bug所在,不加的话,会判断1为true if (a.intValue() == 1) { return false; } //不在6的倍数两侧的一定不是质数 if(a.intValue() % 6!= 1 && a.intValue() % 6!= 5) { return false; } //在6的倍数两侧的也可能不是质数 double tmp = Math.sqrt(a.intValue()); for(double i = 5; i <= tmp; i+=6 ) { if(a.intValue() % i== 0 || a.intValue() % (i+ 2) == 0) { return false; } } return true; } public static void main(String[] args) { Integer n = new Scanner(System.in).nextInt(); int rs = 1; int i = 1; while (n > 0) { i ++; if (is_prime(i)) { rs = ((rs % 50000) * (i % 50000) % 50000); n --; } } System.out.println(rs); } }
TuGengs/Blue_Bridge_Cup
src/algorithm/Perplexity_Of_Torry_Basic.java
66,672
package edu.tools; import edu.question.Question; import edu.question.QuestionCandidate; import java.io.*; import java.util.ArrayList; /** * Created by shawn on 16-3-12. */ public class OutputQuestion { public static void outputQuestionsAndRightContents(ArrayList<Question> questionList, String fileName) { System.out.println("Now, it's outputting"); File outputFile = new File(fileName); try { FileOutputStream outputStream = new FileOutputStream(outputFile); PrintStream printStream = new PrintStream(outputStream); for (Question question : questionList) { for (String word : question.getQuestionWords()) { printStream.print(word + " "); } for (QuestionCandidate candidate : question.getRightCandidates()) { for (String word : candidate.getWords()) { printStream.print(word + " "); } } printStream.println(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void outputQuestionsAsRNNInput(ArrayList<Question> questionList, String fileName) { FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(fileName); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintStream printStream = new PrintStream(outputStream); for (Question question : questionList) { for (String word : question.getQuestionWords()) { printStream.print(word + " "); } if (question.getNumericalType()) { } else { if (question.getAnswer().equals("A")) { for (String word : question.getCandidateWords(1)) { printStream.print(word + " "); } } else if (question.getAnswer().equals("B")) { for (String word : question.getCandidateWords(2)) { printStream.print(word + " "); } } else if (question.getAnswer().equals("C")) { for (String word : question.getCandidateWords(3)) { printStream.print(word + " "); } } else if (question.getAnswer().equals("D")) { for (String word : question.getCandidateWords(4)) { printStream.print(word + " "); } } } printStream.println(); } } public static void outputQuestion2XML(ArrayList<Question> questionList, String fileName) { FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(fileName); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintStream printStream = new PrintStream(outputStream); printStream.println("<questionlist>"); for (Question question : questionList) { printStream.println("<question id=\"" + questionList.indexOf(question) + "\">"); printStream.println("\t<description>" + question.getQuestion() + "</description>"); if (question.getNumericalType()) { for (int i = 0; i < question.getNumericalCandidateNum(); i++) { char one = "①".toCharArray()[0]; char id = (char)((int)one + i); printStream.println("\t\t<entity id=\"" + Integer.sum(i, 1) + "\">" + id +question.getNumCandidates(i) + "</entity>"); } } printStream.println("\t<candidates>"); int answer = (int)question.getAnswer().toCharArray()[0] - (int) 'A'; for(int i = 0; i < 4; i++) { printStream.print("\t\t<candidate value=\""); if (i == answer) { printStream.print("1"); } else { printStream.print("0"); } char num = (char) ((int)'A' + i); printStream.println("\">" + num+ "." + question.getCandidates(i) + "</candidate>"); } printStream.println("\t</candidates>"); printStream.println("</question>"); } printStream.println("</questionlist>"); } public static void normalOutput(ArrayList<Question> questionList) { System.out.println("Now, it's outputting"); File outputFile = new File("out/output.txt"); try { FileOutputStream outputStream = new FileOutputStream(outputFile); PrintStream printStream = new PrintStream(outputStream); int i = 0; for (Question question : questionList) { i += 1; printStream.println("Question #" + i); printStream.println("Question:\t" + question.getQuestion()); printStream.println("Candidates:\tA." + question.getCandidates(0) + " B." + question.getCandidates(1) + " C." + question.getCandidates(2) + " D." + question.getCandidates(3)); printStream.println("Answer:\t" + question.getAnswer()); printStream.println("Type:\t" + question.getStemType()); printStream.println("Question Segments:\t"); for (String word : question.getQuestionWords()) { printStream.print(word + " "); } printStream.println(); for (String pos : question.getQuestionPOS()) { printStream.print(pos + " "); } printStream.println(); for (String pos : question.getQuestionOriginalPOS()) { printStream.print(pos + " "); } printStream.println(); for (String entity : question.getQuestionEntities()) { printStream.print(entity + " "); } printStream.println(); if(question.getNumericalType()) { printStream.println("Numerical Type:\t" + question.getNumericalType()); printStream.println("Numerical Candidates:"); ArrayList<QuestionCandidate> candidates = question.getNumCandidates(); for (QuestionCandidate candidate : candidates) { printStream.println(candidate.getContent()); } } else { printStream.println("Candidate Type:\t" + question.getCandidateType()); printStream.println("Candidates Segment:\t"); for (int j = 0; j <= 3; j++) { ArrayList<String> words = question.getCandidateWords(j); ArrayList<String> pos = question.getCandidatePOS(j); ArrayList<String> ners = question.getCandidateNER(j); for (String word : words) { printStream.print(word + " "); } for (String po : pos) { printStream.print(po + " "); } for (String nerStr : ners) { printStream.print(nerStr + " "); } printStream.println(); } } printStream.print("RightAnswer Content:\t"); for (QuestionCandidate candidate : question.getRightCandidates()) { printStream.print(candidate.getContent() + " "); } printStream.println(); printStream.println("Materials:\t" + question.getMaterial()); printStream.println("QuestionStem:\t" + question.getQuestionStem()); printStream.print("Original Material:\t"); for (String originalMaterial : question.getOrignialMaterials()) { printStream.print(originalMaterial + " "); } printStream.println(); printStream.println(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void outputQuestionsAndContents(ArrayList<Question> questionList, String fileName) { System.out.println("Now, it's outputting"); File outputFile = new File(fileName); try { FileOutputStream outputStream = new FileOutputStream(outputFile); PrintStream printStream = new PrintStream(outputStream); for (Question question : questionList) { for (String word : question.getQuestionWords()) { printStream.print(word + " "); } for (QuestionCandidate candidate : question.getRightCandidates()) { for (String word : candidate.getWords()) { printStream.print(word + " "); } } printStream.println(); for (String word : question.getQuestionWords()) { printStream.print(word + " "); } for (QuestionCandidate candidate : question.getWrongCandidates()) { for (String word : candidate.getWords()) { printStream.print(word + " "); } } printStream.println(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void outputQuestionsContentsAndLables(ArrayList<Question> questionList, String strFileName, String labelFileName) { deletFile(strFileName); deletFile(labelFileName); /** * 输出形如下方: * 秦遂 并兼 四海 以为 周制 微弱 终 诸侯 丧 不 立 尺土 封 分 天下 郡县 …… 材料 中的 周制 指 郡县制 * 秦遂 并兼 四海 以为 周制 微弱 终 诸侯 丧 不 立 尺土 封 分 天下 郡县 …… 材料 中的 周制 指 分封制 * 秦遂 并兼 四海 以为 周制 微弱 终 诸侯 丧 不 立 尺土 封 分 天下 郡县 …… 材料 中的 周制 指 王位世袭制 * 秦遂 并兼 四海 以为 周制 微弱 终 诸侯 丧 不 立 尺土 封 分 天下 郡县 …… 材料 中的 周制 指 行省制 * 0 * 1 * 0 * 0 */ System.out.println("Now, it's outputting"); File wordFile = new File(strFileName); File labelFile = new File(labelFileName); try { FileOutputStream wordFileStream = new FileOutputStream(wordFile); FileOutputStream labelFileStream = new FileOutputStream(labelFile); PrintStream wordStream = new PrintStream(wordFileStream); PrintStream labelStream = new PrintStream(labelFileStream); for (Question question : questionList) { if (question.getNumericalType()) { int rightIndex = question.getAnswer().charAt(0) - 65; for (String word : question.getQuestionWords()) { wordStream.print(word + " "); } for (int i = 0; i < 4; i++) { for (char word : question.getCandidates(i).toCharArray()) { char one = "①".toCharArray()[0]; if (word - one > 3 || word - one < 0) { break; } for (String printWord : question.getNumCandidates().get(word - one).getWords()) { wordStream.print(printWord + " "); } } wordStream.println(); if (i == rightIndex) { labelStream.println("1"); } else { labelStream.println("0"); } } } else { int rightIndex = question.getAnswer().charAt(0) - 65; for (int i = 0; i < 4; i++) { for (String word : question.getQuestionWords()) { wordStream.print(word + " "); } for (String word : question.getCandidateWords(i)) { wordStream.print(word + " "); } wordStream.println(); if (i == rightIndex) { labelStream.println("1"); } else { labelStream.println("0"); } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void asNNTest(ArrayList<Question> questionList, String strFileName, String labelFileName) { deletFile(strFileName); deletFile(labelFileName); /** * 输出形如下方: * 秦遂 并兼 四海 以为 周制 微弱 终 诸侯 丧 不 立 尺土 封 分 天下 郡县 …… 材料 中的 周制 指 郡县制 * 秦遂 并兼 四海 以为 周制 微弱 终 诸侯 丧 不 立 尺土 封 分 天下 郡县 …… 材料 中的 周制 指 分封制 * 秦遂 并兼 四海 以为 周制 微弱 终 诸侯 丧 不 立 尺土 封 分 天下 郡县 …… 材料 中的 周制 指 王位世袭制 * 秦遂 并兼 四海 以为 周制 微弱 终 诸侯 丧 不 立 尺土 封 分 天下 郡县 …… 材料 中的 周制 指 行省制 * 0 * 1 * 0 * 0 */ System.out.println("Now, it's outputting"); File wordFile = new File(strFileName); File labelFile = new File(labelFileName); try { FileOutputStream wordFileStream = new FileOutputStream(wordFile); FileOutputStream labelFileStream = new FileOutputStream(labelFile); PrintStream wordStream = new PrintStream(wordFileStream); PrintStream labelStream = new PrintStream(labelFileStream); for (Question question : questionList) { /** if (question.getNumericalType()) { int rightIndex = question.getAnswer().charAt(0) - 65; for (int i = 0; i < 4; i++) { for (char word : question.getCandidates(i).toCharArray()) { for (String qword : question.getQuestionWords()) { wordStream.print(qword + " "); } char one = "①".toCharArray()[0]; if (word - one > 3 || word - one < 0) { break; } for (String printWord : question.getNumCandidates().get(word - one).getWords()) { wordStream.print(printWord + " "); } } wordStream.println(); if (i == rightIndex) { labelStream.println("1"); } else { labelStream.println("0"); } } } else { **/ int rightIndex = question.getAnswer().charAt(0) - 65; for (int i = 0; i < 4; i++) { for (String word : question.getQuestionWords()) { wordStream.print(word + " "); } for (String word : question.getCandidateWords(i)) { wordStream.print(word + " "); } wordStream.println(); if (i == rightIndex) { labelStream.println("1"); } else { labelStream.println("0"); } } } // } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void outputQuestionsWithAllCandidates(ArrayList<Question> questionList, String strFileName, String labelFileName) { System.out.println("Now, it's outputting"); File wordFile = new File(strFileName); File labelFile = new File(labelFileName); try { FileOutputStream wordFileStream = new FileOutputStream(wordFile); FileOutputStream labelFileStream = new FileOutputStream(labelFile); PrintStream wordStream = new PrintStream(wordFileStream); PrintStream labelStream = new PrintStream(labelFileStream); for (Question question : questionList) { if (question.getNumericalType()) { int rightIndex = question.getAnswer().charAt(0) - 65; for (int i = 0; i < 4; i++) { for (String word : question.getQuestionWords()) { wordStream.print(word + " "); } for (char word : question.getCandidates(i).toCharArray()) { char one = "①".toCharArray()[0]; if (word - one > 3 || word - one < 0) { break; } for (String printWord : question.getNumCandidates().get(word - one).getWords()) { wordStream.print(printWord + " "); } } wordStream.println(); if (i == rightIndex) { labelStream.println("1"); } else { labelStream.println("0"); } } } else { int rightIndex = question.getAnswer().charAt(0) - 65; for (int i = 0; i < 4; i++) { for (String word : question.getQuestionWords()) { wordStream.print(word + " "); } for (String word : question.getCandidateWords(i)) { wordStream.print(word + " "); } wordStream.println(); if (i == rightIndex) { labelStream.println("1"); } else { labelStream.println("0"); } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void outputQuestionsandAllCansRightFirst(ArrayList<Question> questionList, String fileName) { System.out.println("Now, it's outputting"); File outputFile = new File(fileName); try { FileOutputStream outputStream = new FileOutputStream(outputFile); PrintStream printStream = new PrintStream(outputStream); for (Question question : questionList) { for (String word : question.getQuestionWords()) { printStream.print(word + " "); } for (String word : question.getCandidateWords(question.getAnswer().toCharArray()[0] - 65)) { printStream.print(word + " "); } printStream.println(); for (int i = 0; i < 4; i++) { if (i == question.getAnswer().toCharArray()[0] - 65) { continue; } for (String word : question.getQuestionWords()) { printStream.print(word + " "); } for (String word : question.getCandidateWords(i)) { printStream.print(word + " "); } printStream.println(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void asNNTrain_QAS(ArrayList<Question> questionList, String strFileName, String labelFileName) { /** 中国 古代 某 时期 朝廷 地方 矛盾 尖锐 某 节度使 派 人 中书省 办事 态度 恶劣 遭 宰相 武元衡 呵斥 不久 武元衡 靖安坊 东门 节度使 派 人 刺杀 此事 发生 汉长安 唐长安 宋汴梁 唐长安 元大都 唐长安 -1 1 -1 1 -1 1 */ System.out.println("Now, it's outputting"); File wordFile = new File(strFileName); File labelFile = new File(labelFileName); try { FileOutputStream wordFileStream = new FileOutputStream(wordFile); FileOutputStream labelFileStream = new FileOutputStream(labelFile); PrintStream wordStream = new PrintStream(wordFileStream); PrintStream labelStream = new PrintStream(labelFileStream); for (Question question : questionList) { if (question.getNumericalType()) { int rightIndex = question.getAnswer().charAt(0) - 65; for (String word : question.getQuestionWords()) { wordStream.print(word + " "); } wordStream.println(); for (int i = 0; i < 4; i++) { if (i == rightIndex) continue; for (char word : question.getCandidates(i).toCharArray()) { char one = "①".toCharArray()[0]; if (word - one > 3 || word - one < 0) { break; } for (String printWord : question.getNumCandidates().get(word - one).getWords()) { wordStream.print(printWord + " "); } } wordStream.println(); labelStream.println("-1"); for (char word : question.getCandidates(rightIndex).toCharArray()) { char one = "①".toCharArray()[0]; if (word - one > 3 || word - one < 0) { break; } for (String printWord : question.getNumCandidates().get(word - one).getWords()) { wordStream.print(printWord + " "); } } wordStream.println(); labelStream.println("1"); } } else { int rightIndex = question.getAnswer().charAt(0) - 65; for (String word : question.getQuestionWords()) { wordStream.print(word + " "); } wordStream.println(); for (int i = 0; i < 4; i++) { if (i == rightIndex) continue; for (String word : question.getCandidateWords(i)) { wordStream.print(word + " "); } wordStream.println(); labelStream.println("-1"); for (String word : question.getCandidateWords(rightIndex)) { wordStream.print(word + " "); } wordStream.println(); labelStream.println("1"); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void asNNTrain_QAS_leadin(ArrayList<Question> questionList, String strFileName, String labelFileName) { /** 中国 古代 某 时期 朝廷 地方 矛盾 尖锐 某 节度使 派 人 中书省 办事 态度 恶劣 遭 宰相 武元衡 呵斥 不久 武元衡 靖安坊 东门 节度使 派 人 刺杀 此事 发生 汉长安 唐长安 宋汴梁 唐长安 元大都 唐长安 ------------------------------------------------------------------------------------------- -1 1 -1 1 -1 1 */ System.out.println("Now, it's outputting"); File wordFile = new File(strFileName); File labelFile = new File(labelFileName); try { FileOutputStream wordFileStream = new FileOutputStream(wordFile); FileOutputStream labelFileStream = new FileOutputStream(labelFile); PrintStream wordStream = new PrintStream(wordFileStream); PrintStream labelStream = new PrintStream(labelFileStream); for (Question question : questionList) { if(question.getStemWords().size() == 0) { continue; } if (question.getNumericalType()) { int rightIndex = question.getAnswer().charAt(0) - 65; boolean flag = false; char one = "①".toCharArray()[0]; for (int i = 0; i < 4; i++) { for(char index : question.getCandidates(i).toCharArray()) { if (index - one >= question.getNumCandidates().size()) flag = true; } } if (flag) continue; for (String word : question.getMaterialWords()) { wordStream.print(word + " "); } wordStream.println(); for (String word : question.getStemWords()) { wordStream.print(word + " "); } wordStream.println(); for (int i = 0; i < 4; i++) { if (i == rightIndex) continue; for (char word : question.getCandidates(i).toCharArray()) { if ( word - one < 0) { break; } for (String printWord : question.getNumCandidates().get(word - one).getWords()) { wordStream.print(printWord + " "); } } wordStream.println(); labelStream.println("-1"); for (char word : question.getCandidates(rightIndex).toCharArray()) { if ( word - one < 0) { break; } for (String printWord : question.getNumCandidates().get(word - one).getWords()) { wordStream.print(printWord + " "); } } wordStream.println(); labelStream.println("1"); } } else { int rightIndex = question.getAnswer().charAt(0) - 65; for (String word : question.getMaterialWords()) { wordStream.print(word + " "); } wordStream.println(); for (String word : question.getStemWords()) { wordStream.print(word + " "); } wordStream.println(); for (int i = 0; i < 4; i++) { if (i == rightIndex) continue; for (String word : question.getCandidateWords(i)) { wordStream.print(word + " "); } wordStream.println(); labelStream.println("-1"); for (String word : question.getCandidateWords(rightIndex)) { wordStream.print(word + " "); } wordStream.println(); labelStream.println("1"); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void asNNTest_QAS_leadin(ArrayList<Question> questionList, String strFileName, String labelFileName) { /** 中国 古代 某 时期 朝廷 地方 矛盾 尖锐 某 节度使 派 人 中书省 办事 态度 恶劣 遭 宰相 武元衡 呵斥 不久 武元衡 靖安坊 东门 节度使 派 人 刺杀 此事 发生 汉长安 唐长安 宋汴梁 元大都 ------------------------------------------------------------------------------------------- 0 1 0 0 */ System.out.println("Now, it's outputting"); File wordFile = new File(strFileName); File labelFile = new File(labelFileName); try { FileOutputStream wordFileStream = new FileOutputStream(wordFile); FileOutputStream labelFileStream = new FileOutputStream(labelFile); PrintStream wordStream = new PrintStream(wordFileStream); PrintStream labelStream = new PrintStream(labelFileStream); for (Question question : questionList) { if(question.getStemWords().size() == 0) { continue; } if (question.getNumericalType()) { int rightIndex = question.getAnswer().charAt(0) - 65; boolean flag = false; char one = "①".toCharArray()[0]; for (int i = 0; i < 4; i++) { for(char index : question.getCandidates(i).toCharArray() ) { if (index - one >= question.getNumCandidates().size() || question.getMaterialWords().size() == 0 || question.getStemWords().size() == 0) flag = true; } } if (flag) continue; for (String word : question.getMaterialWords()) { wordStream.print(word + " "); } wordStream.println(); for (String word : question.getStemWords()) { wordStream.print(word + " "); } wordStream.println(); for (int i = 0; i < 4; i++) { for (char word : question.getCandidates(i).toCharArray()) { if ( word - one < 0) { break; } for (String printWord : question.getNumCandidates().get(word - one).getWords()) { wordStream.print(printWord + " "); } } wordStream.println(); if (i == rightIndex) { labelStream.println("1"); } else { labelStream.println("0"); } } } else { int rightIndex = question.getAnswer().charAt(0) - 65; for (String word : question.getMaterialWords()) { wordStream.print(word + " "); } wordStream.println(); for (String word : question.getStemWords()) { wordStream.print(word + " "); } wordStream.println(); for (int i = 0; i < 4; i++) { for (String word : question.getCandidateWords(i)) { wordStream.print(word + " "); } wordStream.println(); if (i == rightIndex) { labelStream.println("1"); } else { labelStream.println("0"); } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void outputCandidateCertainty(ArrayList<Question> questionList, String filename){ deletFile(filename); BufferedWriter bw; try { bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename))); for(Question question : questionList){ String line = ""; // line += question.getID() + "\t" + question.getCandidateRealType() + "\n"; if (question.questionRealType.size() != 0) { line += question.getID() + "\t" + question.questionRealType.get(0) + "\n"; }else { line += question.getID() + "\t" + question.getCandidateType() + "\n"; } for (int i = 0; i < 4; i++) { line += question.getCandidateCertainties().get(i) + "\n"; } bw.write(line); } bw.flush(); bw.close(); } catch (Exception e) { e.printStackTrace(); } } static void deletFile(String filename){ File f = new File(filename); if(f.exists()){ boolean isDeleteSuccess = f.delete(); if (!isDeleteSuccess) System.out.println("删除失败:" + filename); } } }
IACASNLPIR/GKHMC
IRapproach/src/edu/tools/OutputQuestion.java
66,676
package com.ottd.libs.utils; /** * Created by zixie on 2017/11/10. */ public class TimeUtils { public static String getDateCompareResult(long oldTimestamp){ long minute = 1000 * 60; long hour = minute * 60; long day = hour * 24; long month = day * 30; long year = month * 12; long currentTimestamp = System.currentTimeMillis(); long diffValue = currentTimestamp - oldTimestamp; long yearC = diffValue / year; long monthC = diffValue / month; long weekC = diffValue / (7 * day); long dayC = diffValue / day; long hourC = diffValue / hour; long minC = diffValue / minute; if (yearC > 0) { return yearC + "年前"; } else if (monthC > 0) { return monthC + "月前"; } else if (weekC > 0) { return weekC + "周前"; } else if (dayC > 0) { return dayC + "天前"; } else if (hourC > 0) { return hourC + "小时前"; } else if (minC > 0) { return minC + "分钟前"; } else if (diffValue > 0) { return diffValue/1000 + "秒前"; } else { return "不久前"; } } }
bihe0832/readhub-android
LibUtils/src/main/java/com/ottd/libs/utils/TimeUtils.java
66,681
package com.example.franklinzquantum.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; public class class10 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.class10); ListView listView = (ListView) findViewById(R.id.listview10);//在视图中找到ListView ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);//新建并配置ArrayAapeter listView.setAdapter(adapter); } String data[] = {"городской 市立的;城市的","Детство 童年","детский 儿童的","молодой 年轻的","красный 红色的","домашний 家庭的","синйй 蓝色的","вечернйй 晚上的;参加晚会穿的","английский 英国的;英语的","плохой 不好的","свежий 新鲜的","горячий 热的;热烈的","Пальто 大衣","дерево 树","человек 人","зимний 冬天的;冬季用的","Квартира 一套房间(独户的)住房","вода 复воды 水","рабочий 办公的;工人的;工人","средний 中间的;中等的;平均的","Китайский 中国的","Маленький 小的;","лекция (大学的)讲座,讲课","родители 父母,双亲","дворец 宫殿;馆","летний 夏天的","Занятие 课堂,课","или 或者","Старший 年长的;年岁最大的","младший 年级较小的","московский 莫斯科的","кинотеатр 电影院","Больница 医院","свой своя своё свои 自己的","сидеть сижу сидишь сидят 坐着","Торговый 贸易的","Фирма 公司","Медицинский 医学的","пекинский 北京的","Исторический 历史的","факультет 系","почему 为什么","больной 有病的;病人","Москвич 【阳】","Москвичка 【阴】莫斯科人","родиться 出生;产生","уже 已经","Педагогический 师范的","звать зову зовёшь зовут 招呼;叫来;叫做","Специальность 专业","Литература 文学","недавно 不久","каждый 每个;每","Кроме того 除此之外,此外","видеофильм 影视剧","даже 甚至","весёлый 快乐的","Добрый 善良的","Родной 家乡的;亲爱的","рассказ 讲述,故事,短篇小说","знаменитый 著名的","Место 地方,座位","ли 是否,吗"}; }
f2quantum/HIT--Annual-project
app/src/main/java/com/example/franklinzquantum/myapplication/class10.java
66,684
package me.ghui.v2er.module.topic; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.SharedElementCallback; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.browser.customtabs.CustomTabsClient; import com.google.android.material.bottomsheet.BottomSheetDialog; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.text.Editable; import android.text.Html; import android.text.TextWatcher; import android.transition.Transition; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewAnimationUtils; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.EditText; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.inject.Inject; import butterknife.BindView; import butterknife.OnClick; import me.ghui.v2er.util.Check; import me.ghui.v2er.util.Theme; import me.ghui.v2er.R; import me.ghui.v2er.general.ActivityReloader; import me.ghui.v2er.general.Navigator; import me.ghui.v2er.general.Pref; import me.ghui.v2er.general.ShareElementTransitionCallBack; import me.ghui.v2er.general.ShareManager; import me.ghui.v2er.general.Vtml; import me.ghui.v2er.injector.component.DaggerTopicComponent; import me.ghui.v2er.injector.module.TopicModule; import me.ghui.v2er.module.append.AppendTopicActivity; import me.ghui.v2er.module.base.BaseActivity; import me.ghui.v2er.module.user.UserHomeActivity; import me.ghui.v2er.network.bean.TopicBasicInfo; import me.ghui.v2er.network.bean.TopicInfo; import me.ghui.v2er.util.L; import me.ghui.v2er.util.ScaleUtils; import me.ghui.v2er.util.UriUtils; import me.ghui.v2er.util.UserUtils; import me.ghui.v2er.util.Utils; import me.ghui.v2er.util.Voast; import me.ghui.v2er.widget.AndroidBug5497Workaround; import me.ghui.v2er.widget.BaseRecyclerView; import me.ghui.v2er.widget.BaseToolBar; import me.ghui.v2er.widget.KeyboardDetectorRelativeLayout; import me.ghui.v2er.widget.LoadMoreRecyclerView; import me.ghui.v2er.widget.MentionedReplySheetDialog; import me.ghui.v2er.widget.dialog.ConfirmDialog; import static android.view.View.VISIBLE; /** * Created by ghui on 04/05/2017. */ public class TopicActivity extends BaseActivity<TopicContract.IPresenter> implements TopicContract.IView, LoadMoreRecyclerView.OnLoadMoreListener, KeyboardDetectorRelativeLayout.IKeyboardChanged, TopicReplyItemDelegate.OnMemberClickListener, HtmlView.OnHtmlRenderListener { public static final String TOPIC_ID_KEY = KEY("topic_id_key"); private static final String TOPIC_BASIC_INFO = KEY("TOPIC_BASIC_INFO"); private static final String TOPIC_AUTO_SCROLL_REPLY = KEY("TOPIC_AUTO_SCROLL_REPLY"); public static final String TOPIC_INTO_KEY = KEY("TOPIC_INTO_KEY"); private static final String TOPIC_CURRENT_PAGE = KEY("TOPIC_CURRENT_PAGE"); private static final String TOPIC_PAGE_Y_POS_KEY = KEY("TOPIC_PAGE_Y_POS_KEY"); public boolean isNeedAutoScroll = true; @BindView(R.id.base_recyclerview) LoadMoreRecyclerView mLoadMoreRecyclerView; @BindView(R.id.topic_reply_wrapper) KeyboardDetectorRelativeLayout mReplyWrapper; @BindView(R.id.topic_inner_reply_wrapper) ViewGroup mReplyInnerWrapper; @BindView(R.id.inner_reply_wrapper_content) ViewGroup mReplyLayout; @BindView(R.id.topic_reply_et) EditText mReplyEt; @BindView(R.id.reply_fab_btn) FloatingActionButton mReplyFabBtn; @BindView(R.id.repliers_recyclerview) BaseRecyclerView mReplierRecyView; @Inject LoadMoreRecyclerView.Adapter<TopicInfo.Item> mAdapter; @Inject TopicModule.TopicAtAdapter mReplierAdapter; private LinearLayoutManager mLinearLayoutManager; private LinearLayoutManager mMentionedLinearLayoutManager; private String mTopicId; private TopicBasicInfo mTopicBasicInfo; private String mAutoScrollReply; private TopicInfo mTopicInfo; private MenuItem mLoveMenuItem; private MenuItem mThxMenuItem; private MenuItem mReportMenuItem; private MenuItem mAppendItem; private MenuItem mFadeItem; private MenuItem mStickyItem; private BottomSheetDialog mMenuSheetDialog; private OnBottomDialogItemClickListener mBottomSheetDialogItemClickListener; private List<TopicInfo.Item> repliersInfo; private boolean mNeedWaitForTransitionEnd = true; private boolean mIsReturning; private final SharedElementCallback mCallback = new SharedElementCallback() { @Override public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) { if (mIsReturning) { if (mLoadMoreRecyclerView.computeVerticalScrollOffset() > getResources().getDimension(R.dimen.common_padding_size)) { names.clear(); sharedElements.clear(); } } } }; private boolean mIsHideReplyBtn; private boolean mIsLogin = UserUtils.isLogin(); private boolean mIsScanInOrder = !Pref.readBool(R.string.pref_key_is_scan_in_reverse, false); /** * @param topicId * @param context * @param sourceView shareElement view * @param topicBasicInfo pre show info * @param scrollToReply auto to scrollTo the reply item */ public static void openById(String topicId, Context context, View sourceView, TopicBasicInfo topicBasicInfo, String scrollToReply) { if (sourceView == null || topicBasicInfo == null) { topicBasicInfo = null; sourceView = null; } Navigator.from(context) .to(TopicActivity.class) .putExtra(TopicActivity.TOPIC_ID_KEY, topicId) .putExtra(TOPIC_BASIC_INFO, topicBasicInfo) .putExtra(TOPIC_AUTO_SCROLL_REPLY, scrollToReply) .shareElement(sourceView) .start(); } public static void openById(String topicId, Context context, View sourceView, TopicBasicInfo topicBasicInfo) { openById(topicId, context, sourceView, topicBasicInfo, null); } public static void open(String link, Context context) { open(link, context, null, null); } public static void open(String link, Context context, View sourceView, TopicBasicInfo topicBasicInfo) { openById(UriUtils.getLastSegment(link), context, sourceView, topicBasicInfo, null); } public static void openWithAutoScroll(String link, Context context, String autoScrollReply) { openById(UriUtils.getLastSegment(link), context, null, null, autoScrollReply); } @Override protected void autoLoad() { if (mTopicInfo == null) { super.autoLoad(); showLoading(); } } @Override protected int attachLayoutRes() { return R.layout.act_topic_info_page; } @Override protected void startInject() { DaggerTopicComponent.builder() .appComponent(getAppComponent()) .topicModule(new TopicModule(this)) .build().inject(this); } @Override protected void onStart() { super.onStart(); CustomTabsClient.connectAndInitialize(this, "com.android.chrome"); } @Override protected void parseExtras(Intent intent) { mTopicId = intent.getStringExtra(TOPIC_ID_KEY); mTopicBasicInfo = (TopicBasicInfo) intent.getSerializableExtra(TOPIC_BASIC_INFO); mTopicInfo = (TopicInfo) intent.getSerializableExtra(TOPIC_INTO_KEY); mAutoScrollReply = intent.getStringExtra(TOPIC_AUTO_SCROLL_REPLY); isNeedAutoScroll = Check.notEmpty(mAutoScrollReply); } @Override protected void configToolBar(BaseToolBar toolBar) { super.configToolBar(toolBar); Utils.setPaddingForStatusBar(toolBar); mToolbar.inflateMenu(R.menu.topic_info_toolbar_menu); Menu menu = mToolbar.getMenu(); mLoveMenuItem = menu.findItem(R.id.action_star); mThxMenuItem = menu.findItem(R.id.action_thx); mAppendItem = menu.findItem(R.id.action_append); mFadeItem = menu.findItem(R.id.action_fade); mStickyItem = menu.findItem(R.id.action_sticky); mReportMenuItem = menu.findItem(R.id.action_report); MenuItem replyMenuItem = menu.findItem(R.id.action_reply); mIsHideReplyBtn = Pref.readBool(R.string.pref_key_hide_reply_btn); replyMenuItem.setVisible(mIsHideReplyBtn); MenuItem scanOrderMenuItem = menu.findItem(R.id.action_scan_order); scanOrderMenuItem.setTitle(mIsScanInOrder ? "顺序浏览" : "逆序浏览"); mToolbar.setOnMenuItemClickListener(item -> { if (mTopicInfo == null) { if (item.getItemId() == R.id.action_open_in_browser) { String topicLink = Utils.generateTopicLinkById(mTopicId); Utils.openInBrowser(topicLink, this); } else { toast("请等到加载完成"); } return true; } TopicInfo.HeaderInfo headerInfo = mTopicInfo.getHeaderInfo(); switch (item.getItemId()) { case R.id.action_star: if (headerInfo.hadStared()) { mPresenter.unStarTopic(mTopicId, mTopicInfo.getOnce()); } else { mPresenter.starTopic(mTopicId, mTopicInfo.getOnce()); } break; case R.id.action_append: AppendTopicActivity.open(mTopicId, TopicActivity.this); break; case R.id.action_thx: if (UserUtils.notLoginAndProcessToLogin(false, this)) return false; if (mTopicInfo.getHeaderInfo().isSelf()) { toast("自己不能感谢自己"); return false; } if (!headerInfo.canSendThanks()) { toast("感谢发送失败,可能因为您刚注册不久"); return true; } if (!headerInfo.hadThanked()) { mPresenter.thxCreator(mTopicId, getOnce()); } else { toast(R.string.already_thx_cannot_return); return true; } break; case R.id.action_block: if (UserUtils.notLoginAndProcessToLogin(false, this)) return false; new ConfirmDialog.Builder(getActivity()) .msg("确定忽略此主题吗?") .positiveText(R.string.ok, dialog -> mPresenter.ignoreTopic(mTopicId, mTopicInfo.getOnce())) .negativeText(R.string.cancel) .build().show(); break; case R.id.action_report: if (UserUtils.notLoginAndProcessToLogin(false, this)) return false; new ConfirmDialog.Builder(getActivity()) .msg("确定要举报这个主题吗?") .positiveText(R.string.ok, dialog -> mPresenter.reportTopic()) .negativeText(R.string.cancel) .build().show(); break; case R.id.action_sticky: if (UserUtils.notLoginAndProcessToLogin(false, this)) return false; new ConfirmDialog.Builder(getActivity()) .msg("你确认要将此主题置顶 10 分钟?该操作价格为 200 铜币。") .positiveText(R.string.ok, dialog -> mPresenter.stickyTopic()) .negativeText(R.string.cancel) .build().show(); break; case R.id.action_fade: if (UserUtils.notLoginAndProcessToLogin(false, this)) return false; new ConfirmDialog.Builder(getActivity()) .msg("你确认要将此主题下沉 1 天?") .positiveText(R.string.ok, dialog -> mPresenter.fadeTopic()) .negativeText(R.string.cancel) .build().show(); break; case R.id.action_share: ShareManager.ShareData shareData = new ShareManager.ShareData.Builder(headerInfo.getTitle()) .content(Vtml.fromHtml(mTopicInfo.getContentInfo().getFormattedHtml()).toString()) .link(UriUtils.topicLink(mTopicId)) .img(headerInfo.getAvatar()) .build(); ShareManager shareManager = new ShareManager(shareData, this); shareManager.showShareDialog(); break; case R.id.action_open_in_browser: // Utils.copyToClipboard(this, mTopicInfo.getTopicLink()); // toast("链接已拷贝成功"); Utils.openInBrowser(mTopicInfo.getTopicLink(), this); break; case R.id.action_reply: animateEditInnerWrapper(true); break; case R.id.action_scan_order: // reload mIsScanInOrder = !mIsScanInOrder; scanOrderMenuItem.setTitle(mIsScanInOrder ? "顺序浏览" : "逆序浏览"); Pref.saveBool(R.string.pref_key_is_scan_in_reverse, !mIsScanInOrder); mLoadMoreRecyclerView.setLoadOrder(mIsScanInOrder); // 重新加载 loadFromStart(); showLoading(); break; } return true; }); } @Override protected boolean supportShareElement() { return mTopicBasicInfo != null && Check.notEmpty(mTopicBasicInfo.getAvatar()); } private void shareElementAnimation() { mNeedWaitForTransitionEnd = supportShareElement(); final Transition transition = getWindow().getSharedElementEnterTransition(); if (transition == null) { mNeedWaitForTransitionEnd = false; return; } transition.addListener(new ShareElementTransitionCallBack() { @Override public void onTransitionStart(Transition transition) { if (mIsReturning) { // mReplyFabBtn.setVisibility(View.GONE); mReplyFabBtn.hide(); } } @Override public void onTransitionEnd(Transition transition) { L.e("onTransitionEnd"); mNeedWaitForTransitionEnd = false; if (mTopicInfo != null) { delay(30, () -> fillView(mTopicInfo, mIsScanInOrder ? 1 : mTopicInfo.getTotalPage())); } } }); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null || mTopicInfo != null) { mNeedWaitForTransitionEnd = false; } } @Override protected void reloadMode(int mode) { int pos = mLinearLayoutManager.findFirstCompletelyVisibleItemPosition(); L.d("firstVisiablePos: " + pos); ActivityReloader.target(this) .putExtra(TOPIC_ID_KEY, getIntent().getStringExtra(TOPIC_ID_KEY)) .putExtra(TOPIC_INTO_KEY, mTopicInfo) .putExtra(TOPIC_CURRENT_PAGE, mPresenter.getPage()) .putExtra(TOPIC_PAGE_Y_POS_KEY, pos) .reload(); } @Override protected void init() { AndroidBug5497Workaround.assistActivity(this); Utils.setPaddingForNavbar(mReplyLayout); setEnterSharedElementCallback(mCallback); setFirstLoadingDelay(300); shareElementAnimation(); // mReplyFabBtn.setVisibility(!mIsLogin || mIsHideReplyBtn ? View.GONE : VISIBLE); if (!mIsLogin || mIsHideReplyBtn) { mReplyFabBtn.hide(); } else mReplyFabBtn.show(); CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) mReplyFabBtn.getLayoutParams(); layoutParams.bottomMargin = ScaleUtils.dp(20) + Utils.getNavigationBarHeight(); mReplyWrapper.addKeyboardStateChangedListener(this); mLinearLayoutManager = new LinearLayoutManager(getContext()); mLoadMoreRecyclerView.setLoadOrder(mIsScanInOrder); mLoadMoreRecyclerView.setTransitionGroup(true); mLoadMoreRecyclerView.setLayoutManager(mLinearLayoutManager); mLoadMoreRecyclerView.setAdapter(mAdapter); mLoadMoreRecyclerView.setOnLoadMoreListener(this); mLoadMoreRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int pos = mLinearLayoutManager.findFirstVisibleItemPosition(); if (pos == 0) { //title 可见 mToolbar.setSubtitle(null); } else { //title 不可见 if (mTopicInfo != null && mTopicInfo.getHeaderInfo() != null) { mToolbar.setSubtitle(mTopicInfo.getHeaderInfo().getTitle()); } } } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { if (recyclerView.getLayerType() != View.LAYER_TYPE_SOFTWARE) { recyclerView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } } else { if (recyclerView.getLayerType() != View.LAYER_TYPE_HARDWARE) { recyclerView.setLayerType(View.LAYER_TYPE_HARDWARE, null); } } } }); if (mTopicInfo != null) { // 代表是从夜间模式切换过来的 mNeedWaitForTransitionEnd = false; int page = getIntent().getIntExtra(TOPIC_CURRENT_PAGE, 1); fillView(mTopicInfo, page); int pos = getIntent().getIntExtra(TOPIC_PAGE_Y_POS_KEY, 0); L.d("firstVisiablePos2: " + pos); post(() -> mLinearLayoutManager.scrollToPosition(pos)); } else if (mTopicBasicInfo != null) { List<TopicInfo.Item> data = new ArrayList<>(); data.add(TopicInfo.HeaderInfo.build(mTopicBasicInfo)); mAdapter.setData(data); post(() -> scheduleStartPostponedTransition($(R.id.topic_header_title_tv))); } mMentionedLinearLayoutManager = new LinearLayoutManager(this); mReplierRecyView.setLayoutManager(mMentionedLinearLayoutManager); mReplierRecyView.setAdapter(mReplierAdapter); mReplierAdapter.setOnItemClickListener((view, holder, position) -> { //do fill @username String selectUsername = mReplierAdapter.getItem(position).getUserName(); String inputStr = mReplyEt.getText().toString(); int cursorPos = mReplyEt.getSelectionStart(); String[] cuttedStrs = Utils.cutString(inputStr, cursorPos); if (cuttedStrs == null) return; if (Check.isEmpty(cuttedStrs[1])) { //后面无文字,append StringBuilder inputTextBuilder = new StringBuilder(inputStr); int lastIndexOfAt = inputTextBuilder.lastIndexOf("@"); if (lastIndexOfAt > 0 && inputTextBuilder.charAt(lastIndexOfAt - 1) != ' ') { inputTextBuilder.insert(lastIndexOfAt, ' '); } lastIndexOfAt = inputTextBuilder.lastIndexOf("@"); inputTextBuilder.replace(lastIndexOfAt + 1, inputTextBuilder.length(), selectUsername + " "); mReplyEt.setText(inputTextBuilder); mReplyEt.setSelection(inputTextBuilder.length()); } else { //后面有文字,insert int lastIndexOfAt = cuttedStrs[0].lastIndexOf("@"); StringBuilder result = new StringBuilder(cuttedStrs[0].substring(0, lastIndexOfAt)); String appendStr = " @" + selectUsername; result.append(appendStr + " " + cuttedStrs[1]); mReplyEt.setText(result); mReplyEt.setSelection(lastIndexOfAt + appendStr.length() + 1); } mReplierRecyView.setVisibility(View.GONE); }); mReplyEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { CharSequence changedText = s.subSequence(start, start + count); L.d("text: onTextChanged: " + changedText); if ("@".equals(changedText.toString())) { int startIndex = mLinearLayoutManager.findFirstVisibleItemPosition(); int endIndex = mLinearLayoutManager.findLastVisibleItemPosition() + 2; endIndex = Math.min(endIndex, mAdapter.getContentItemCount() - 1); List<String> hintNames = new ArrayList<>(endIndex - startIndex + 1); List<TopicInfo.Item> items = mAdapter.getDatas(); for (int i = endIndex; i >= startIndex; i--) { hintNames.add(items.get(i).getUserName()); } for (String name : hintNames) { for (int i = 0; i < repliersInfo.size(); i++) { TopicInfo.Item item = repliersInfo.get(i); if (item.getUserName().equals(name)) { repliersInfo.remove(item); repliersInfo.add(0, item); } } } mReplierRecyView.setVisibility(VISIBLE); } if (mReplierRecyView.getVisibility() != VISIBLE) return; String inputStr = mReplyEt.getText().toString(); int cursorPos = mReplyEt.getSelectionStart(); int lastIndexOfat = 0; for (int i = cursorPos - 1; i >= 0; i--) { if (inputStr.charAt(i) == '@') { lastIndexOfat = i; break; } } L.e("lastIndexOfAt: " + lastIndexOfat); String text = inputStr.substring(lastIndexOfat, cursorPos); onInputQueryTextChanged(text); } }); } private void onInputQueryTextChanged(String query) { L.d("1Query: " + query); if (Check.isEmpty(query)) { mReplierRecyView.setVisibility(View.GONE); return; } if (Check.notEmpty(query) && query.startsWith("@")) { query = query.substring(1); } L.d("2Query: " + query); mReplierAdapter.getFilter().filter(query); } /** * 下拉刷新,重新加载页面 */ private void loadFromStart() { // TODO: 2019/4/17 逆序第一次加载完需要重置willLoadPage = totalPage -1 mTopicInfo = null; int willLoadPage = mIsScanInOrder ? 1 : 999; mLoadMoreRecyclerView.setWillLoadPage(willLoadPage); mNeedWaitForTransitionEnd = false; mPresenter.loadData(mTopicId, willLoadPage); } @Override protected SwipeRefreshLayout.OnRefreshListener attachOnRefreshListener() { return () -> loadFromStart(); } @Override public void onLoadMore(int willLoadPage) { mPresenter.loadData(mTopicId, willLoadPage); } @Override public boolean getScanOrder() { return mIsScanInOrder; } @Override public String getTopicId() { return mTopicId; } @Override public String getOnce() { if (mTopicInfo == null) return null; return mTopicInfo.getOnce(); } @Override public void fillView(TopicInfo topicInfo, int page) { mTopicInfo = topicInfo; if (mNeedWaitForTransitionEnd) return; if (topicInfo == null) { mAdapter.setData(null); return; } // 对于逆序加载,页面第一次打开时不知道一共有多少页,自然也就不知道首先应该加载哪一页 // 所以对于这种情况,默认要加载的页面为999,这样v2ex也会返回最后一页的内容,当内容返回 // 后就可以拿到准确的总页面数,此时记得如果是逆序浏览要修正正确的willLoadPage if (page == 999) { // 纠正当前加载的真实页面 page = topicInfo.getTotalPage(); // 纠正当前加载的willLoadPage为正确值 mLoadMoreRecyclerView.setWillLoadPage(page); } boolean hasMore = mIsScanInOrder ? page < mTopicInfo.getTotalPage() : page > 1; // 内部会计算下一次的willLoadPage mLoadMoreRecyclerView.setHasMore(hasMore); // TODO: 2019/4/17 reverse boolean isLoadMore = mIsScanInOrder ? page > 1 : page != topicInfo.getTotalPage(); if (!mIsScanInOrder) { // 逆序加载的话需要reverse reply序列 } // TODO: 2019-06-23 save info from adapter mAdapter.setData(topicInfo.getItems(isLoadMore, mIsScanInOrder), isLoadMore); if (!topicInfo.getContentInfo().isValid()) { onRenderCompleted(); } TopicInfo.HeaderInfo headerInfo = mTopicInfo.getHeaderInfo(); updateStarStatus(headerInfo.hadStared(), false); updateThxCreatorStatus(headerInfo.hadThanked(), false); updateReportMenuItem(mTopicInfo.hasReportPermission(), mTopicInfo.hasReported()); boolean isSelf = mTopicInfo.getHeaderInfo().isSelf(); mAppendItem.setVisible(isSelf && mTopicInfo.getHeaderInfo().canAppend()); mFadeItem.setVisible(isSelf && mTopicInfo.canfade()); mStickyItem.setVisible(isSelf && mTopicInfo.canSticky()); if (!mIsHideReplyBtn && mIsLogin) { // mReplyFabBtn.setVisibility(VISIBLE); mReplyFabBtn.show(); } fillAtList(); autoScroll(); } private void autoScroll() { // TODO: 2019-08-11 向上滑动帖子调动 if (!isNeedAutoScroll) return; List<TopicInfo.Reply> items = mTopicInfo.getReplies(); if (Check.isEmpty(items)) return; int position = 0; for (int i = 0; i < items.size(); i++) { TopicInfo.Reply item = items.get(i); if (mAutoScrollReply.equals(item.getReplyContent())) { position = i; if (mTopicInfo.getContentInfo().isValid()) { position += 2; } else { position += 1; } break; } } if (isNeedAutoScroll && position > 0) { isNeedAutoScroll = false; int finalPosition = position; delay(350, () -> { mLinearLayoutManager.scrollToPositionWithOffset(finalPosition, 0); post(() -> { // if (mLinearLayoutManager.findFirstVisibleItemPosition() == finalPosition) // return; View itemView = mLinearLayoutManager.findViewByPosition(finalPosition); if (itemView == null) { Voast.debug("itemView is null"); return; } itemView.startAnimation(AnimationUtils.loadAnimation(TopicActivity.this, R.anim.item_shake)); }); }); } } private void fillAtList() { List<TopicInfo.Item> datum = mAdapter.getDatas(); if (repliersInfo == null) { repliersInfo = new ArrayList<>(datum.size() - 1); } else { repliersInfo.clear(); } for (TopicInfo.Item item : datum) { String name = item.getUserName(); //do check... if (Check.notEmpty(name)) { boolean alreadyHas = false; for (TopicInfo.Item reply : repliersInfo) { if (name.equals(reply.getUserName())) { //already has the same username one , break alreadyHas = true; break; } } if (!alreadyHas) { repliersInfo.add(item); } } } mReplierAdapter.setData(repliersInfo); } @Override public List<TopicInfo.Item> topicReplyInfo() { return repliersInfo; } @Override public void finishAfterTransition() { mIsReturning = true; super.finishAfterTransition(); } @Override public void onBackPressed() { if (mReplyWrapper.getVisibility() == View.VISIBLE) { animateEditInnerWrapper(false); return; } super.onBackPressed(); } @OnClick(R.id.reply_fab_btn) void onNewReplyFlbClicked(FloatingActionButton button) { if (button != null) { button.hide(); } animateEditInnerWrapper(true); } private int getRelativeY() { int[] loc = new int[2]; mReplyInnerWrapper.getLocationOnScreen(loc); int wrapperY = loc[1]; mReplyFabBtn.getLocationOnScreen(loc); int btnY = loc[1]; int delta = btnY - wrapperY + mReplyFabBtn.getMeasuredHeight() / 2; return delta; } void animateEditInnerWrapper(boolean isShow) { if (mSlidrInterface != null) { if (isShow) mSlidrInterface.lock(); else mSlidrInterface.unlock(); } int cX = ScaleUtils.getScreenW() - mReplyFabBtn.getMeasuredWidth() / 2 - ScaleUtils.dp(16); int startRadius = ScaleUtils.dp(25); int endRadius = ScaleUtils.getScreenW(); if (isShow) {//show edit wrapper mReplyFabBtn.hide(); Animator animator = ViewAnimationUtils.createCircularReveal(mReplyInnerWrapper, cX, getRelativeY(), startRadius, endRadius); animator.setDuration(400); animator.setStartDelay(100); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { mReplyWrapper.setVisibility(View.VISIBLE); } }); animator.start(); } else {//hide wrapper if (mReplyWrapper.getVisibility() != View.VISIBLE) return; Animator animator = ViewAnimationUtils.createCircularReveal(mReplyInnerWrapper, cX, getRelativeY(), endRadius, startRadius); animator.setDuration(300); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mReplyWrapper.setVisibility(View.INVISIBLE); if (!mIsHideReplyBtn && mIsLogin) mReplyFabBtn.show(); } @Override public void onAnimationCancel(Animator animation) { Voast.debug("TopicPage onAnimationCancel"); onAnimationEnd(animation); } }); animator.start(); mReplierRecyView.setVisibility(View.GONE); } } private void updateStarStatus(boolean isStared, boolean needUpdateData) { mLoveMenuItem.setIcon(isStared ? R.drawable.ic_star_selected : R.drawable.ic_star_normal); mLoveMenuItem.getIcon().setTint(Theme.getColor(R.attr.icon_tint_color, this)); if (needUpdateData) { mTopicInfo.getHeaderInfo().updateStarStatus(isStared); } } private void updateThxCreatorStatus(boolean thxed, boolean needUpdateData) { mThxMenuItem.setTitle(thxed ? getString(R.string.thx_already_send) : getString(R.string.thx_str)); if (needUpdateData) { mTopicInfo.getHeaderInfo().updateThxStatus(thxed); } } private void updateReportMenuItem(boolean hasReportPermission, boolean hasReported) { mReportMenuItem.setTitle(hasReported ? "已举报" : "举报"); mReportMenuItem.setEnabled(!hasReported); mReportMenuItem.setVisible(hasReportPermission); } @Override public void afterStarTopic(TopicInfo topicInfo) { if (mTopicInfo == null) { toast("收藏遇到问题"); return; } mTopicInfo.getHeaderInfo().setFavoriteLink(topicInfo.getHeaderInfo().getFavoriteLink()); updateStarStatus(mTopicInfo.getHeaderInfo().hadStared(), true); toast("收藏成功"); } @Override public void afterUnStarTopic(TopicInfo topicInfo) { mTopicInfo.getHeaderInfo().setFavoriteLink(topicInfo.getHeaderInfo().getFavoriteLink()); updateStarStatus(mTopicInfo.getHeaderInfo().hadStared(), true); toast("取消收藏成功"); } @Override public void afterThxCreator(boolean success) { if (success) { updateThxCreatorStatus(true, true); toast(R.string.thx_already_send); } else { toast(getString(R.string.send_thx_occured_error)); } } @Override public void afterIgnoreTopic(boolean success) { if (success) { toast("主题已忽略"); finish(); } else { toast("忽略主题遇到问题"); } } @Override public void afterIgnoreReply(int position) { toast("已忽略"); mAdapter.getDatas().remove(position); mAdapter.notifyDataSetChanged(); } @Override public void afterReportTopic(boolean success) { if (success) { toast("举报成功"); finish(); } else { toast("举报主题遇到问题"); } } @Override public void afterReplyTopic(TopicInfo topicInfo) { if (topicInfo.isValid()) { toast("回复成功"); Utils.toggleKeyboard(false, mReplyEt); animateEditInnerWrapper(false); fillView(topicInfo, topicInfo.getTotalPage()); mReplyEt.setText(null); } else { toast("回复失败"); } } @Override public void afterFadeTopic(boolean isSuccess) { toast(isSuccess ? "下沉成功" : "下沉失败"); } @Override public void afterStickyTopic(boolean isSuccess) { toast(isSuccess ? "置顶10分钟成功" : "置顶失败"); } @OnClick(R.id.reply_send_btn) void onPostBtnClicked() { CharSequence text = mReplyEt.getText(); if (Check.isEmpty(text)) { toast("回复不能为空"); return; } if (mTopicInfo == null) { toast("页面加载失败"); return; } mPresenter.replyTopic(mTopicId, mTopicInfo.toReplyMap(text.toString())); } public void onItemMoreMenuClick(int position) { if (mMenuSheetDialog == null) { mMenuSheetDialog = new BottomSheetDialog(getContext()); mMenuSheetDialog.setContentView(R.layout.topic_reply_dialog_item); ViewGroup parentView = mMenuSheetDialog.findViewById(R.id.topic_reply_dialog_rootview); mBottomSheetDialogItemClickListener = new OnBottomDialogItemClickListener(); for (int i = 0; i < parentView.getChildCount(); i++) { parentView.getChildAt(i).setOnClickListener(mBottomSheetDialogItemClickListener); } } mBottomSheetDialogItemClickListener.setPosition(position); mMenuSheetDialog.show(); } @Override public void onKeyboardShown() { L.d("onKeyboardShown"); mReplyLayout.setPadding(0, 0, 0, 0); } @Override public void onKeyboardHidden() { L.d("onKeyboardHidden"); Utils.setPaddingForNavbar(mReplyLayout); } @Override public void onRenderCompleted() { hideLoading(); } @Override public void onMemberClick(String userName, int index) { List<TopicInfo.Item> datum = mAdapter.getDatas(); List<TopicInfo.Reply> replies = new ArrayList<>(); if (mIsScanInOrder) { for (int i = index - 1; i >= 0; i--) { TopicInfo.Item item = datum.get(i); if (item instanceof TopicInfo.Reply && item.getUserName().equals(userName)) { replies.add((TopicInfo.Reply) item); } } } else { for (int i = index + 1; i < datum.size(); i++) { TopicInfo.Item item = datum.get(i); if (item instanceof TopicInfo.Reply && item.getUserName().equals(userName)) { replies.add((TopicInfo.Reply) item); } } } if (Check.isEmpty(replies)) return; MentionedReplySheetDialog mentionedReplySheetDialog = new MentionedReplySheetDialog(this); mentionedReplySheetDialog.setData(replies, userName); mentionedReplySheetDialog.show(); } private class OnBottomDialogItemClickListener implements View.OnClickListener { private TopicInfo.Reply item; private int position; public void setPosition(int position) { this.position = position; this.item = (TopicInfo.Reply) mAdapter.getItem(position); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.reply_dialog_btn1: //reply to the comment if (UserUtils.notLoginAndProcessToLogin(false, getContext())) return; animateEditInnerWrapper(true); mReplyEt.setText("@" + item.getUserName() + " "); mReplyEt.setSelection(mReplyEt.getText().length()); Utils.toggleKeyboard(true, mReplyEt); break; case R.id.reply_dialog_btn2: //copy reply to clipboard Utils.copyToClipboard(TopicActivity.this, Html.fromHtml(item.getReplyContent()).toString()); toast("拷贝成功"); break; case R.id.reply_dialog_btn3: //ignore reply if (UserUtils.notLoginAndProcessToLogin(false, getContext())) return; new ConfirmDialog.Builder(getActivity()) .title("忽略回复") .msg("确定不再显示来自@" + item.getUserName() + "的这条回复?") .positiveText(R.string.ok, dialog -> mPresenter.ignoreReply(position, item.getReplyId(), mTopicInfo.getOnce())) .negativeText(R.string.cancel) .build().show(); break; case R.id.reply_dialog_btn4: //homepage UserHomeActivity.open(item.getUserName(), TopicActivity.this, null, item.getAvatar()); break; } mMenuSheetDialog.dismiss(); } } }
v2er-app/Android
app/src/main/java/me/ghui/v2er/module/topic/TopicActivity.java
66,686
package com.hotcaffeine.worker.consumer; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.hotcaffeine.common.cache.CaffeineCache; import com.hotcaffeine.common.model.KeyCount; import com.hotcaffeine.common.model.KeyRule; import com.hotcaffeine.common.model.KeyRuleCacher; import com.hotcaffeine.common.util.MemoryMQ.MemoryMQConsumer; import com.hotcaffeine.common.util.MetricsUtil; import com.hotcaffeine.worker.cache.AppCaffeineCache; import com.hotcaffeine.worker.cache.AppKeyRuleCacher; import com.hotcaffeine.worker.metric.BucketLeapArray; import com.hotcaffeine.worker.pusher.IPusher; /** * 新key消费 * * @author yongfeigao * @date 2021年1月12日 */ @Component public class NewKeyConsumer implements MemoryMQConsumer<KeyCount> { private Logger logger = LoggerFactory.getLogger("hotcaffeine"); private Cache<String, AtomicInteger> recentCache; @Resource private List<IPusher> iPushers; @Autowired private AppKeyRuleCacher appKeyRuleCacher; @Autowired private AppCaffeineCache appCaffeineCache; public NewKeyConsumer() { initRecentCache(); } public void initRecentCache() { long maximumSize = 50000; Caffeine<Object, Object> caffeine = Caffeine.newBuilder() .initialCapacity(256)// 初始大小 .maximumSize(maximumSize)// 最大数量 .expireAfterWrite(5, TimeUnit.SECONDS)// 过期时间 .softValues() .recordStats(); CaffeineCache<AtomicInteger> caffeineCache = new CaffeineCache<>("recentCache", caffeine, TimeUnit.SECONDS.toMillis(5), maximumSize); recentCache = caffeineCache.getCache(); } public void consume(KeyCount keyCount) { // 统计 MetricsUtil.incrDealKeys(); // 唯一key String uniqueKey = keyCount.getKey(); // 判断是不是刚热不久 AtomicInteger hotCounter = recentCache.getIfPresent(uniqueKey); if (hotCounter != null) { return; } // 获取key规则 KeyRuleCacher keyRuleCacher = appKeyRuleCacher.getKeyRuleCacher(keyCount.getAppName()); if (keyRuleCacher == null) { return; } String key = keyCount.getKey(); KeyRule keyRule = keyRuleCacher.findRule(key); if (keyRule == null) { return; } // 获取缓存 CaffeineCache<BucketLeapArray> caffeineCache = appCaffeineCache.getCacheOrBuildIfAbsent(keyCount.getAppName()); caffeineCache.setActiveTime(System.currentTimeMillis()); // 获取滑动窗口 BucketLeapArray leapArray = getBucketLeapArray(caffeineCache, key, keyRule); long count = leapArray.count(keyCount.getCount()); // 没hot if (count < keyRule.getThreshold()) { return; } // 并发安全,保障hotCounter只有一个 hotCounter = recentCache.get(uniqueKey, k -> new AtomicInteger()); // 已经执行过直接返回,保障只通知一次 if (hotCounter.incrementAndGet() > 1) { return; } // 删掉该key caffeineCache.delete(key); // 开启推送 keyCount.setCreateTime(System.currentTimeMillis()); logger.info("appName:{} key:{} inner:{} rule:{} hot:{}", keyCount.getAppName(), key, keyCount.isInner(), keyRule.getKey(), count); // 分别推送到各client和dashboard MetricsUtil.incrSendKeys(); for (IPusher pusher : iPushers) { pusher.push(keyCount); } } /** * 获取滑动窗口 * * @param appName * @param key * @param keyRule * @return */ private BucketLeapArray getBucketLeapArray(CaffeineCache<BucketLeapArray> caffeineCache, String key, KeyRule keyRule) { BucketLeapArray bucketLeapArray = caffeineCache.getCache().getIfPresent(key); if(bucketLeapArray == null) { bucketLeapArray = new BucketLeapArray(getSampleCount(keyRule.getInterval()), keyRule.getInterval() * 1000); caffeineCache.getCache().put(key, bucketLeapArray); } return bucketLeapArray; } private int getSampleCount(int interval) { // 2秒及以下,每秒2窗口 if (interval <= 2) { return interval * 2; } // 3秒及以上每秒一个窗口 return interval; } public Cache<String, AtomicInteger> getRecentCache() { return recentCache; } }
sohutv/hotcaffeine
worker/src/main/java/com/hotcaffeine/worker/consumer/NewKeyConsumer.java
66,687
package com.qiniu.pili.droid.shortvideo.demo.transition; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import com.qiniu.pili.droid.shortvideo.PLFadeTransition; import com.qiniu.pili.droid.shortvideo.PLImageView; import com.qiniu.pili.droid.shortvideo.PLPositionTransition; import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting; import com.qiniu.pili.droid.shortvideo.demo.R; import com.qiniu.pili.droid.shortvideo.demo.view.TransitionTextView; public class Transition3 extends TransitionBase { private static final int MOVE_DISTANCE = 100; private static final String TEXT_DISPLAY = "村上春树1949年1月12日出生在日本京都市伏见区,为国语教师村上千秋、村上美幸夫妇的长子。出生不久,家迁至兵库县西宫市夙川。村上春树1949年1月12日出生在日本京都市伏见区,为国语教师村上千秋、村上美幸夫妇的长子。出生不久,家迁至兵库县西宫市夙川。"; private PLImageView mImageView; public Transition3(ViewGroup viewGroup, PLVideoEncodeSetting setting) { super(viewGroup, setting); } @Override protected void initPosAndTrans() { //you should init positions and transitions in post runnable , because the view has been layout at that moment. mImageView.post(new Runnable() { @Override public void run() { initPosition(); initTransitions(); } }); } @Override protected void initViews() { mTitle = new TransitionTextView(mContext); mTitle.setText(TEXT_DISPLAY); mTitle.setPadding(0, 0, 0, 0); mTitle.setTextColor(Color.parseColor("#339900")); mTitle.setTextSize(16); mImageView = new PLImageView(mContext); mImageView.setImageDrawable(mContext.getResources().getDrawable(R.drawable.green_quot)); addViews(); setViewsVisible(View.INVISIBLE); } private void initTransitions() { PLPositionTransition positionTransition = new PLPositionTransition(0, DURATION / 2, (int) mTitle.getX(), (int) mTitle.getY(), (int) mTitle.getX(), (int) mTitle.getY() - MOVE_DISTANCE); mTransitionMaker.addTransition(mTitle, positionTransition); PLFadeTransition fadeTransition = new PLFadeTransition(0, DURATION / 2, 0, 1); mTransitionMaker.addTransition(mTitle, fadeTransition); positionTransition = new PLPositionTransition(0, DURATION / 2, (int) mImageView.getX(), (int) mImageView.getY(), (int) mImageView.getX(), (int) mImageView.getY() - MOVE_DISTANCE); mTransitionMaker.addTransition(mImageView, positionTransition); fadeTransition = new PLFadeTransition(0, DURATION / 2, 0, 1); mTransitionMaker.addTransition(mImageView, fadeTransition); mTransitionMaker.play(); setViewsVisible(View.VISIBLE); } private void initPosition() { int titleY = mHeight / 2 - mTitle.getHeight() / 2 + MOVE_DISTANCE; mTitle.setTranslationX(0); mTitle.setTranslationY(titleY); int imageY = titleY - mImageView.getHeight(); mImageView.setTranslationY(imageY); mImageView.setTranslationX(0); } @Override protected void addViews() { super.addViews(); mTransitionMaker.addImage(mImageView); } @Override protected void setViewsVisible(int visible) { super.setViewsVisible(visible); mImageView.setVisibility(visible); } }
ChenViVi/eden
src/main/java/com/qiniu/pili/droid/shortvideo/demo/transition/Transition3.java
66,693
package com.jzy.game.ai.nav.polygon; import com.jzy.game.ai.pfa.Heuristic; /** * 多边形消耗计算 * * @author JiangZhiYong * @date 2018年2月20日 * @mail [email protected] */ public class PolygonHeuristic implements Heuristic<Polygon> { @Override public float estimate(Polygon node, Polygon endNode) { // 多边形中点坐标距离 是否需要各个边的距离取最小值? //理论曼哈顿要快要欧几里得,单实际测试不是 // 曼哈顿启发因子 // return Math.abs(node.center.x - endNode.center.x) + Math.abs(node.center.z - // endNode.center.z); // 欧几里得 距离启发因子 return node.center.dst(endNode.center); } }
jzyong/game-server
game-ai/src/main/java/com/jzy/game/ai/nav/polygon/PolygonHeuristic.java
66,694
package com.cser.play.message; import com.cser.play.common.wx.MessageUtil; public class MessageService { public static final MessageService ME = new MessageService(); private static final String TEXT = "快要上班啦,记得去签到领取牛贝哦!"; public void sendMessage(){ MessageUtil.getInstance().initMessage(TEXT); } }
cser700/play-together
src/main/java/com/cser/play/message/MessageService.java
66,697
package com.jarvis.cache; import com.jarvis.cache.annotation.Cache; import com.jarvis.cache.annotation.CacheDelete; import com.jarvis.cache.annotation.CacheDeleteKey; import com.jarvis.cache.annotation.CacheDeleteMagicKey; import com.jarvis.cache.annotation.CacheDeleteTransactional; import com.jarvis.cache.annotation.ExCache; import com.jarvis.cache.aop.CacheAopProxyChain; import com.jarvis.cache.aop.DeleteCacheAopProxyChain; import com.jarvis.cache.aop.DeleteCacheTransactionalAopProxyChain; import com.jarvis.cache.clone.ICloner; import com.jarvis.cache.exception.CacheCenterConnectionException; import com.jarvis.cache.lock.ILock; import com.jarvis.cache.script.AbstractScriptParser; import com.jarvis.cache.to.AutoLoadConfig; import com.jarvis.cache.to.AutoLoadTO; import com.jarvis.cache.to.CacheKeyTO; import com.jarvis.cache.to.CacheWrapper; import com.jarvis.cache.to.ProcessingTO; import com.jarvis.cache.type.CacheOpType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * 处理AOP * * */ public class CacheHandler { /** * 正在处理中的请求 */ public final ConcurrentHashMap<CacheKeyTO, ProcessingTO> processing; private final ICacheManager cacheManager; private final AutoLoadConfig config; private final ICloner cloner; private final AutoLoadHandler autoLoadHandler; private static final Logger log = LoggerFactory.getLogger(CacheHandler.class); /** * 表达式解析器 */ private final AbstractScriptParser scriptParser; private final RefreshHandler refreshHandler; /** * 分布式锁 */ private ILock lock; private ChangeListener changeListener; public CacheHandler(ICacheManager cacheManager, AbstractScriptParser scriptParser, AutoLoadConfig config, ICloner cloner) throws IllegalArgumentException{ if(null == cacheManager) { throw new IllegalArgumentException("cacheManager is null"); } if(null == cloner) { throw new IllegalArgumentException("cloner is null"); } if(null == scriptParser) { throw new IllegalArgumentException("scriptParser is null"); } this.processing = new ConcurrentHashMap<>(config.getProcessingMapSize()); this.cacheManager = cacheManager; this.config = config; this.cloner = cloner; this.autoLoadHandler = new AutoLoadHandler(this, config); this.scriptParser = scriptParser; registerFunction(config.getFunctions()); refreshHandler = new RefreshHandler(this, config); } /** * 从数据源中获取最新数据,并写入缓存。注意:这里不使用“拿来主义”机制,是因为当前可能是更新数据的方法。 * * @param pjp CacheAopProxyChain * @param cache Cache注解 * @return 最新数据 * @throws Throwable 异常 */ private Object writeOnly(CacheAopProxyChain pjp, Cache cache) throws Throwable { DataLoader dataLoader; if (config.isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); dataLoader = factory.getDataLoader(); } else { dataLoader = new DataLoader(); } CacheWrapper<Object> cacheWrapper; try { cacheWrapper = dataLoader.init(pjp, cache, this).getData().getCacheWrapper(); } catch (Throwable e) { throw e; } finally { if (config.isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); factory.returnObject(dataLoader); } } Object result = cacheWrapper.getCacheObject(); Object[] arguments = pjp.getArgs(); if (scriptParser.isCacheable(cache, pjp.getTarget(), arguments, result)) { CacheKeyTO cacheKey = getCacheKey(pjp, cache, result); // 注意:这里只能获取AutoloadTO,不能生成AutoloadTO AutoLoadTO autoLoadTO = autoLoadHandler.getAutoLoadTO(cacheKey); try { writeCache(pjp, pjp.getArgs(), cache, cacheKey, cacheWrapper); if (null != autoLoadTO) { // 同步加载时间 autoLoadTO.setLastLoadTime(cacheWrapper.getLastLoadTime()) // 同步过期时间 .setExpire(cacheWrapper.getExpire()); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } } if (cache.resultDeepCloneEnable()) { return cloner.deepClone(result, null); } return result; } /** * 获取CacheOpType,从三个地方获取:<br> * 1. Cache注解中获取;<br> * 2. 从ThreadLocal中获取;<br> * 3. 从参数中获取;<br> * 上面三者的优先级:从低到高。 * * @param cache 注解 * @param arguments 参数 * @return CacheOpType */ private CacheOpType getCacheOpType(Cache cache, Object[] arguments) { CacheOpType opType = cache.opType(); CacheOpType tmpOpType = CacheHelper.getCacheOpType(); if (null != tmpOpType) { opType = tmpOpType; } if (null != arguments && arguments.length > 0) { for (Object tmp : arguments) { if (null != tmp && tmp instanceof CacheOpType) { opType = (CacheOpType) tmp; break; } } } if (null == opType) { opType = CacheOpType.READ_WRITE; } return opType; } /** * 处理@Cache 拦截 * * @param pjp 切面 * @param cache 注解 * @return T 返回值 * @throws Exception 异常 */ public Object proceed(CacheAopProxyChain pjp, Cache cache) throws Throwable { Object[] arguments = pjp.getArgs(); CacheOpType opType = getCacheOpType(cache, arguments); if (log.isTraceEnabled()) { log.trace("CacheHandler.proceed-->{}.{}--{})", pjp.getTarget().getClass().getName(), pjp.getMethod().getName(), opType.name()); } if (opType == CacheOpType.WRITE) { return writeOnly(pjp, cache); } else if (opType == CacheOpType.LOAD || !scriptParser.isCacheable(cache, pjp.getTarget(), arguments)) { return getData(pjp); } Method method = pjp.getMethod(); if (MagicHandler.isMagic(cache, method)) { return new MagicHandler(this, pjp, cache).magic(); } CacheKeyTO cacheKey = getCacheKey(pjp, cache); if (null == cacheKey) { return getData(pjp); } CacheWrapper<Object> cacheWrapper = null; try { // 从缓存中获取数据 cacheWrapper = this.get(cacheKey, method); } catch (Exception ex) { log.error(ex.getMessage(), ex); } if (log.isTraceEnabled()) { log.trace("cache key:{}, cache data is {} ", cacheKey.getCacheKey(), cacheWrapper); } if (opType == CacheOpType.READ_ONLY) { return null == cacheWrapper ? null : cacheWrapper.getCacheObject(); } if (null != cacheWrapper && !cacheWrapper.isExpired()) { AutoLoadTO autoLoadTO = autoLoadHandler.putIfAbsent(cacheKey, pjp, cache, cacheWrapper); if (null != autoLoadTO) { autoLoadTO.flushRequestTime(cacheWrapper); } else { // 如果缓存快要失效,则自动刷新 refreshHandler.doRefresh(pjp, cache, cacheKey, cacheWrapper); } return cacheWrapper.getCacheObject(); } DataLoader dataLoader; if (config.isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); dataLoader = factory.getDataLoader(); } else { dataLoader = new DataLoader(); } CacheWrapper<Object> newCacheWrapper = null; long loadDataUseTime = 0L; boolean isFirst; try { newCacheWrapper = dataLoader.init(pjp, cacheKey, cache, this).loadData().getCacheWrapper(); loadDataUseTime = dataLoader.getLoadDataUseTime(); } catch (Throwable e) { throw e; } finally { // dataLoader 的数据必须在放回对象池之前获取 isFirst = dataLoader.isFirst(); if (config.isDataLoaderPooled()) { DataLoaderFactory factory = DataLoaderFactory.getInstance(); factory.returnObject(dataLoader); } } if (isFirst) { AutoLoadTO autoLoadTO = autoLoadHandler.putIfAbsent(cacheKey, pjp, cache, newCacheWrapper); try { writeCache(pjp, pjp.getArgs(), cache, cacheKey, newCacheWrapper); if (null != autoLoadTO) { autoLoadTO.flushRequestTime(newCacheWrapper); autoLoadTO.addUseTotalTime(loadDataUseTime); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } } if (cache.resultDeepCloneEnable()) { return cloner.deepClone(newCacheWrapper.getCacheObject(), null); } return newCacheWrapper.getCacheObject(); } /** * 处理@CacheDelete 拦截 * * @param jp 切点 * @param cacheDelete 拦截到的注解 * @param retVal 返回值 * @throws Throwable 异常 */ public void deleteCache(DeleteCacheAopProxyChain jp, CacheDelete cacheDelete, Object retVal) throws Throwable { Object[] arguments = jp.getArgs(); CacheDeleteKey[] keys = cacheDelete.value(); CacheDeleteMagicKey[] magicKeys = cacheDelete.magic(); Object target = jp.getTarget(); String methodName = jp.getMethod().getName(); try { boolean isOnTransactional = CacheHelper.isOnTransactional(); Set<CacheKeyTO> keySet = null; if (!isOnTransactional) { keySet = new HashSet<>(keys.length); } if (null != magicKeys && magicKeys.length > 0) { DeleteCacheMagicHandler magicHandler = new DeleteCacheMagicHandler(this, jp, magicKeys, retVal); List<List<CacheKeyTO>> lists = magicHandler.getCacheKeyForMagic(); if (null != lists && !lists.isEmpty()) { for (List<CacheKeyTO> list : lists) { for (CacheKeyTO key : list) { if (null == key) { continue; } if (isOnTransactional) { CacheHelper.addDeleteCacheKey(key); } else { keySet.add(key); } this.getAutoLoadHandler().resetAutoLoadLastLoadTime(key); } } } } if (null != keys && keys.length > 0) { for (int i = 0; i < keys.length; i++) { CacheDeleteKey keyConfig = keys[i]; if (!scriptParser.isCanDelete(keyConfig, arguments, retVal)) { continue; } String[] tempKeys = keyConfig.value(); String tempHfield = keyConfig.hfield(); for (String tempKey : tempKeys) { CacheKeyTO key = getCacheKey(target, methodName, arguments, tempKey, tempHfield, retVal, true); if (null == key) { continue; } if (isOnTransactional) { CacheHelper.addDeleteCacheKey(key); } else { keySet.add(key); } this.getAutoLoadHandler().resetAutoLoadLastLoadTime(key); } } } this.delete(keySet); } catch (Throwable e) { log.error(e.getMessage(), e); throw e; } } /** * 用于处理事务下,事务处理完后才删除缓存,避免因事务失败造成缓存中的数据不一致问题。 * * @param pjp 切面 * @param cacheDeleteTransactional 注解 * @return Object 返回值 * @throws Throwable 异常 */ public Object proceedDeleteCacheTransactional(DeleteCacheTransactionalAopProxyChain pjp, CacheDeleteTransactional cacheDeleteTransactional) throws Throwable { Object result = null; Set<CacheKeyTO> set0 = CacheHelper.getDeleteCacheKeysSet(); boolean isStart = null == set0; if (!cacheDeleteTransactional.useCache()) { // 在事务环境下尽量直接去数据源加载数据,而不是从缓存中加载,减少数据不一致的可能 CacheHelper.setCacheOpType(CacheOpType.LOAD); } boolean getError = false; try { CacheHelper.initDeleteCacheKeysSet();// 初始化Set result = pjp.doProxyChain(); } catch (Throwable e) { getError = true; throw e; } finally { CacheHelper.clearCacheOpType(); if (isStart) { if (getError && !cacheDeleteTransactional.deleteCacheOnError()) { // do nothing } else { clearCache(); } } } return result; } private void clearCache() throws Throwable { try { Set<CacheKeyTO> set = CacheHelper.getDeleteCacheKeysSet(); if (null != set && set.size() > 0) { this.delete(set); } else { if (log.isWarnEnabled()) { log.warn("proceedDeleteCacheTransactional: key set is empty!"); } } } catch (Throwable e) { log.error(e.getMessage(), e); // 抛出异常,让事务回滚,避免数据库和缓存双写不一致问题 throw e; } finally { CacheHelper.clearDeleteCacheKeysSet(); } } /** * 直接加载数据(加载后的数据不往缓存放) * * @param pjp CacheAopProxyChain * @return Object * @throws Throwable 异常 */ private Object getData(CacheAopProxyChain pjp) throws Throwable { return getData(pjp, pjp.getArgs()); } public Object getData(CacheAopProxyChain pjp, Object[] arguments) throws Throwable { try { long startTime = System.currentTimeMillis(); Object result = pjp.doProxyChain(arguments); long useTime = System.currentTimeMillis() - startTime; if (config.isPrintSlowLog() && useTime >= config.getSlowLoadTime()) { String className = pjp.getTarget().getClass().getName(); if (log.isWarnEnabled()) { log.warn("{}.{}, use time:{}ms", className, pjp.getMethod().getName(), useTime); } } return result; } catch (Throwable e) { throw e; } } public void writeCache(CacheAopProxyChain pjp, Object[] arguments, Cache cache, CacheKeyTO cacheKey, CacheWrapper<Object> cacheWrapper) throws Exception { if (null == cacheKey) { return; } ExCache[] exCaches = cache.exCache(); Method method = pjp.getMethod(); List<MSetParam> params = new ArrayList<>(exCaches.length + 1); if (cacheWrapper.getExpire() >= 0) { params.add(new MSetParam(cacheKey, cacheWrapper)); } Object result = cacheWrapper.getCacheObject(); Object target = pjp.getTarget(); for (ExCache exCache : exCaches) { try { if (!scriptParser.isCacheable(exCache, pjp.getTarget(), arguments, result)) { continue; } CacheKeyTO exCacheKey = getCacheKey(pjp, arguments, exCache, result); if (null == exCacheKey) { continue; } Object exResult = null; if (null == exCache.cacheObject() || exCache.cacheObject().isEmpty()) { exResult = result; } else { exResult = scriptParser.getElValue(exCache.cacheObject(), target, arguments, result, true, Object.class); } int exCacheExpire = scriptParser.getRealExpire(exCache.expire(), exCache.expireExpression(), arguments, exResult); CacheWrapper<Object> exCacheWrapper = new CacheWrapper<Object>(exResult, exCacheExpire); AutoLoadTO tmpAutoLoadTO = this.autoLoadHandler.getAutoLoadTO(exCacheKey); if (exCacheExpire >= 0) { params.add(new MSetParam(exCacheKey, exCacheWrapper)); if (null != tmpAutoLoadTO) { tmpAutoLoadTO.setExpire(exCacheExpire) // .setLastLoadTime(exCacheWrapper.getLastLoadTime()); } } } catch (Exception ex) { log.error(ex.getMessage(), ex); } } int size = params.size(); if (size == 1) { MSetParam param = params.get(0); this.setCache(param.getCacheKey(), param.getResult(), method); } else if (size > 1) { this.mset(method, params); } } public void destroy() { autoLoadHandler.shutdown(); refreshHandler.shutdown(); log.trace("cache destroy ... ... ..."); } /** * 生成缓存KeyTO * * @param target 类名 * @param methodName 方法名 * @param arguments 参数 * @param keyExpression key表达式 * @param hfieldExpression hfield表达式 * @param result 执行实际方法的返回值 * @param hasRetVal 是否有返回值 * @return CacheKeyTO */ public CacheKeyTO getCacheKey(Object target, String methodName, Object[] arguments, String keyExpression, String hfieldExpression, Object result, boolean hasRetVal) { String key = null; String hfield = null; if (null != keyExpression && keyExpression.trim().length() > 0) { try { key = scriptParser.getDefinedCacheKey(keyExpression, target, arguments, result, hasRetVal); if (null != hfieldExpression && hfieldExpression.trim().length() > 0) { hfield = scriptParser.getDefinedCacheKey(hfieldExpression, target, arguments, result, hasRetVal); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } } else { key = CacheUtil.getDefaultCacheKey(target.getClass().getName(), methodName, arguments); } if (null == key || key.trim().isEmpty()) { throw new IllegalArgumentException("cache key for " + target.getClass().getName() + "." + methodName + " is empty"); } return new CacheKeyTO(config.getNamespace(), key, hfield); } /** * 生成缓存 Key * * @param pjp * @param cache * @return String 缓存Key */ private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, Cache cache) { Object target = pjp.getTarget(); String methodName = pjp.getMethod().getName(); Object[] arguments = pjp.getArgs(); String keyExpression = cache.key(); String hfieldExpression = cache.hfield(); return getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, null, false); } /** * 生成缓存 Key * * @param pjp * @param cache * @param result 执行结果值 * @return 缓存Key */ private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, Cache cache, Object result) { Object target = pjp.getTarget(); String methodName = pjp.getMethod().getName(); Object[] arguments = pjp.getArgs(); String keyExpression = cache.key(); String hfieldExpression = cache.hfield(); return getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, result, true); } /** * 生成缓存 Key * * @param pjp * @param arguments * @param exCache * @param result 执行结果值 * @return 缓存Key */ private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, Object[] arguments, ExCache exCache, Object result) { Object target = pjp.getTarget(); String methodName = pjp.getMethod().getName(); String keyExpression = exCache.key(); if (null == keyExpression || keyExpression.trim().length() == 0) { return null; } String hfieldExpression = exCache.hfield(); return getCacheKey(target, methodName, arguments, keyExpression, hfieldExpression, result, true); } public AutoLoadHandler getAutoLoadHandler() { return this.autoLoadHandler; } public AbstractScriptParser getScriptParser() { return scriptParser; } private void registerFunction(Map<String, String> funcs) { if (null == scriptParser) { return; } if (null == funcs || funcs.isEmpty()) { return; } Iterator<Map.Entry<String, String>> it = funcs.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); try { String name = entry.getKey(); Class<?> cls = Class.forName(entry.getValue()); Method method = cls.getDeclaredMethod(name, new Class[]{Object.class}); scriptParser.addFunction(name, method); } catch (Exception e) { log.error(e.getMessage(), e); } } } public ILock getLock() { return lock; } public void setLock(ILock lock) { this.lock = lock; } public void setCache(CacheKeyTO cacheKey, CacheWrapper<Object> result, Method method) throws CacheCenterConnectionException { cacheManager.setCache(cacheKey, result, method); if (null != changeListener) { changeListener.update(cacheKey, result); } } public Map<CacheKeyTO, CacheWrapper<Object>> mget(Method method, final Type returnType, Set<CacheKeyTO> keySet) throws CacheCenterConnectionException { return cacheManager.mget(method, returnType, keySet); } public void mset(final Method method, final Collection<MSetParam> params) throws CacheCenterConnectionException { cacheManager.mset(method, params); } public CacheWrapper<Object> get(CacheKeyTO key, Method method) throws CacheCenterConnectionException { return cacheManager.get(key, method); } public void delete(Set<CacheKeyTO> keys) throws CacheCenterConnectionException { if (null == keys || keys.isEmpty()) { return; } cacheManager.delete(keys); if (null != changeListener) { changeListener.delete(keys); } } public ICloner getCloner() { return cloner; } public AutoLoadConfig getAutoLoadConfig() { return this.config; } public ChangeListener getChangeListener() { return changeListener; } public void setChangeListener(ChangeListener changeListener) { this.changeListener = changeListener; } }
qiujiayu/AutoLoadCache
autoload-cache-core/src/main/java/com/jarvis/cache/CacheHandler.java
66,698
/******************************************************************************* * Copyright [2015] [Onboard team of SERC, Peking University] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.onboard.service.collaboration.scheduler; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.onboard.domain.mapper.TodoMapper; import com.onboard.domain.mapper.model.TodoExample; import com.onboard.domain.model.IterationItemStatus; import com.onboard.domain.model.Project; import com.onboard.domain.model.Todo; import com.onboard.domain.model.User; import com.onboard.service.account.UserService; import com.onboard.service.collaboration.ProjectService; import com.onboard.service.common.identifiable.IdentifiableManager; import com.onboard.service.email.EmailService; import com.onboard.service.email.TemplateEngineService; import com.onboard.service.email.exception.MessageSendingException; import com.onboard.utils.DataCipher; @Service public class DueTodosScheduler { private static final String VM_PATH = "templates/todo-due.vm"; public static final Logger logger = LoggerFactory.getLogger(DueTodosScheduler.class); private final String protocol = "https://"; @Value("${site.host}") private String host; @Autowired private TodoMapper todoMapper; @Autowired private ProjectService projectService; @Autowired private UserService userService; @Autowired private EmailService emailService; @Autowired protected IdentifiableManager identifiableManager; @Autowired protected TemplateEngineService templateEngineService; private List<Todo> getDueTodosOfToday() { Todo sample = new Todo(false); sample.setStatus(IterationItemStatus.TODO.getValue()); TodoExample example = new TodoExample(sample); DateTime today = new DateTime().withTimeAtStartOfDay(); example.getOredCriteria().get(0).andDueDateGreaterThanOrEqualTo(today.toDate()) .andDueDateLessThan(today.plusDays(1).toDate()); return todoMapper.selectByExample(example); } @Scheduled(cron = "0 1 0 * * ?") public void notifyDueTodo() throws MessageSendingException { List<Todo> todos = this.getDueTodosOfToday(); logger.info("todos of day {} counts : {}", new DateTime(), todos.size()); for (Todo todo : todos) { if (todo.getAssigneeId() == null) { continue; } Project project = projectService.getById(todo.getProjectId()); User user = userService.getById(todo.getAssigneeId()); Map<String, Object> model = new HashMap<String, Object>(); model.put("content", todo.getContent()); model.put("host", protocol + this.host); model.put("date", new SimpleDateFormat("yyyy年MM月dd日").format(todo.getDueDate())); //TODO: get url // String url = identifiableManager.getIdentifiableURL(todo); String url = String.format("https://onboard.cn/teams/%s/projects/%s/todolists/open?id=%s1&type=todo", todo.getCompanyId(), todo.getProjectId(), todo.getId()); model.put("url", url); String content = templateEngineService.process(getClass(), VM_PATH, model); String replyTo = StringUtils.arrayToDelimitedString( new String[] { todo.getType(), String.valueOf(todo.getId()), DataCipher.encode(user.getEmail()) }, "-"); emailService.sendEmail("OnBoard", user.getEmail(), null, null, String.format("[%s]%s 快要到期了!", project.getName(), todo.getContent()), content, replyTo); } } public String getHost() { return host; } public void setHost(String host) { this.host = host; } }
sercxtyf/onboard
kernel/com.onboard.service.collaboration.impl/src/main/java/com/onboard/service/collaboration/scheduler/DueTodosScheduler.java
66,699
package com.xnx3.wangmarket.admin.vo; import com.xnx3.j2ee.vo.BaseVO; /** * 站点过期提示,网站登陆后,即将过期时的提示 * <br/>其中的result参数 * <ul> * <li>当result为成功( SiteRemainHintVO.SUCCESS )时,网站正常不需要过期提醒。</li> * <li>当result为失败( ( SiteRemainHintVO.FAILURE ) )时,就是快要过期了,使用过时间还不到两个月了,需要提示</li> * <li>当result为 3 时,网站已经到期</li> * </ul> * @author 管雷鸣 */ public class SiteRemainHintVO extends BaseVO { private String remainTimeString; //距离过期剩余时间文字提醒 private String companyName; //此网站上级代理的名字,公司名 private String phone; //此网站上级代理的联系电话 private String qq; //此网站上级代理的联系QQ public String getRemainTimeString() { return remainTimeString; } public void setRemainTimeString(String remainTimeString) { this.remainTimeString = remainTimeString; setInfo(remainTimeString); } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } }
xnx3/wangmarket
src/main/java/com/xnx3/wangmarket/admin/vo/SiteRemainHintVO.java
66,700
package com.github.cchao.touchnews.javaBean.joke; import java.util.List; /** * Created by cchao on 2016/4/25. * E-mail: [email protected] * Description: */ /* { "showapi_res_code": 0, "showapi_res_error": "", "showapi_res_body": { "allNum": 28928, "allPages": 1447, "contentlist": [ { "ct": "2016-04-25 02:30:39.704", "img": "http://img5.hao123.com/data/3_1d1c26faf76a9523c7c9071f1e65226d_430", "title": "非常有生活气息的工艺品", "type": 2 }, { "ct": "2016-04-24 21:30:47.980", "img": "http://img0.hao123.com/data/3_c06d0b29050afa070d19c67af372bf88_430", "title": "快要被玩坏的节奏呀", "type": 2 } ], "currentPage": 1, "maxResult": 20, "ret_code": 0 } } */ public class JokeImageRoot { private int showapi_res_code; private String showapi_res_error; private Showapi_res_body showapi_res_body; public void setShowapi_res_code(int showapi_res_code) { this.showapi_res_code = showapi_res_code; } public int getShowapi_res_code() { return this.showapi_res_code; } public void setShowapi_res_error(String showapi_res_error) { this.showapi_res_error = showapi_res_error; } public String getShowapi_res_error() { return this.showapi_res_error; } public void setShowapi_res_body(Showapi_res_body showapi_res_body) { this.showapi_res_body = showapi_res_body; } public Showapi_res_body getShowapi_res_body() { return this.showapi_res_body; } public static class Showapi_res_body { private int allNum; private int allPages; private List<Contentlist> contentlist; private int currentPage; private int maxResult; private int ret_code; public void setAllNum(int allNum) { this.allNum = allNum; } public int getAllNum() { return this.allNum; } public void setAllPages(int allPages) { this.allPages = allPages; } public int getAllPages() { return this.allPages; } public void setContentlist(List<Contentlist> contentlist) { this.contentlist = contentlist; } public List<Contentlist> getContentlist() { return this.contentlist; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getCurrentPage() { return this.currentPage; } public void setMaxResult(int maxResult) { this.maxResult = maxResult; } public int getMaxResult() { return this.maxResult; } public void setRet_code(int ret_code) { this.ret_code = ret_code; } public int getRet_code() { return this.ret_code; } } /** * Created by cchao on 2016/4/25. * E-mail: [email protected] * Description: */ public static class Contentlist { private String ct; private String img; private String title; private int type; public void setCt(String ct) { this.ct = ct; } public String getCt() { return this.ct; } public void setImg(String img) { this.img = img; } public String getImg() { return this.img; } public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } public void setType(int type) { this.type = type; } public int getType() { return this.type; } } }
cchao1024/TouchNews
app/src/main/java/com/github/cchao/touchnews/javaBean/joke/JokeImageRoot.java
66,701
import android.content.Context; import android.os.AsyncTask; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AbsListView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.Scroller; import android.widget.TextView; import com.kot32.ksimplelibrary.util.tools.DisplayUtil; import com.kot32.ksimplelibrary.util.tools.FieldUtil; import java.util.concurrent.atomic.AtomicBoolean; /** * Created by kot32 on 15/10/18. * 实现下拉刷新的 View * KRefreshView{SubView:HeaderView、ListView} */ public class KRefreshView extends LinearLayout { private Scroller scroller = new Scroller(getContext()); private TextView default_header_tips; private TextView default_bottom_tips; private boolean shouldRefresh = false; private boolean isRefreshing = false; private boolean shouldLoadMore = false; private boolean isLoadMoreing = false; //是否开启上拉加载更多的开关 private LoadMoreConfig loadMoreConfig; //头部刷新View的父容器 private RelativeLayout headerContent; //尾部『加载更多』 View 的父容器 private RelativeLayout bottomContent; //头部刷新View private View headerView; //尾部『加载更多』 的 View private View bottomView; //下拉刷新-控制UI更新 private RefreshViewHolder refreshViewHolder; //下拉刷新-控制事务更新 private IRefreshAction iRefreshAction; //下拉刷新-控制UI更新 private LoadMoreViewHolder loadMoreViewHolder; //下拉刷新-控制事务更新 private ILoadMoreAction iLoadMoreAction; //触摸事件传递接口 private onRefreshViewTouch onRefreshViewTouch; //默认高度 private int HEADER_HEIGHT = 100; private int BOTTOM_HEIGHT = 100; private int MAX_LIMIT_SLOT = 50; private int totalLimit; private AtomicBoolean isInitListViewListener = new AtomicBoolean(false); private boolean isShouldShowLoadMore = false; public KRefreshView(Context context) { super(context); initView(); initData(); initController(); } public KRefreshView(Context context, AttributeSet attrs) { super(context, attrs); initView(); initData(); initController(); } private void initView() { setOrientation(VERTICAL); //增加头部View容器 LinearLayout.LayoutParams headerContentParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(getContext(), HEADER_HEIGHT)); headerContent = new RelativeLayout(getContext()); headerContentParams.setMargins(0, -DisplayUtil.dip2px(getContext(), HEADER_HEIGHT), 0, 0); headerContent.setLayoutParams(headerContentParams); addView(headerContent, 0); //增加隐藏的View default_header_tips = new TextView(getContext()); default_header_tips.setText("继续下拉以刷新..."); RelativeLayout.LayoutParams defaultHeaderTextParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); defaultHeaderTextParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); default_header_tips.setLayoutParams(defaultHeaderTextParams); headerContent.addView(default_header_tips, 0); // 尾部View容器 bottomContent = new RelativeLayout(getContext()); LayoutParams bottomContentParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT)); bottomContentParams.setMargins(0, 0, 0, -DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT)); bottomContent.setLayoutParams(bottomContentParams); default_bottom_tips = new TextView(getContext()); default_bottom_tips.setText("上拉加载更多.."); RelativeLayout.LayoutParams defaultBottomTextParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); defaultBottomTextParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); default_bottom_tips.setLayoutParams(defaultBottomTextParams); bottomContent.addView(default_bottom_tips, 0); } private void initData() { refreshViewHolder = new RefreshViewHolder() { @Override public void pullingTips(View headerView, int progress) { default_header_tips.setText("继续下拉以刷新..."); } @Override public void willRefreshTips(View headerView) { default_header_tips.setText("松开以刷新"); } @Override public void refreshingTips(View headerView) { default_header_tips.setText("正在刷新..."); } @Override public void refreshCompleteTips(View headerView) { default_header_tips.setText("刷新成功"); } }; loadMoreViewHolder = new LoadMoreViewHolder() { @Override public void loadTips(View headerView, int progress) { default_bottom_tips.setText("继续上拉以加载更多"); } @Override public void willloadTips(View headerView) { default_bottom_tips.setText("松开以加载更多"); } @Override public void loadingTips(View headerView) { default_bottom_tips.setText("正在加载"); } @Override public void loadCompleteTips(View headerView) { default_bottom_tips.setText("加载完成"); } }; totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT); } private void initController() { } public void initLoadMoreFunc() { if (isInitListViewListener.compareAndSet(false, true)) { View view = getChildAt(1); if (view instanceof ListView) { final AbsListView.OnScrollListener oldListener = (AbsListView.OnScrollListener) FieldUtil.getDefedValue("mOnScrollListener", ListView.class, view); ((ListView) view).setOnScrollListener(new AbsListView.OnScrollListener() { private boolean scrollFlag = false;// 标记是否滑动 private int lastVisibleItemPosition = 0;// 标记上次滑动位置 @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (oldListener != null) { oldListener.onScrollStateChanged(view, scrollState); } switch (scrollState) { // 当不滚动时 case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时 scrollFlag = false; break; case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时 scrollFlag = true; break; case AbsListView.OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指,屏幕产生惯性滑动时 scrollFlag = false; break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (oldListener != null) { oldListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } if (view.getLastVisiblePosition() == (view .getCount() - 1)) { if (bottomContent.getParent() == null) { //显示加载更多View KRefreshView.this.addView(bottomContent, 2); } //当滑到最下面时,控制权交给父 View isShouldShowLoadMore = true; } else { isShouldShowLoadMore = false; } } }); } } } private float preY; private float tmpY; private float Y1; private float Y2; enum INTERCEPT_ACTION { REFRESH, LOAD_MORE } private INTERCEPT_ACTION intercept_action; //判断是否拦截事件 @Override public boolean onInterceptTouchEvent(MotionEvent ev) { //如果是方向向上,且ListView switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: Y1 = ev.getRawY(); preY = ev.getRawY(); tmpY = ev.getRawY(); break; case MotionEvent.ACTION_MOVE: Y2 = ev.getRawY(); //没有滑动到一定距离,就不拦截 if (Math.abs(Y2 - Y1) < 3) return false; if (Y2 > Y1) { View view = getChildAt(1); if (view instanceof ListView) { //如果ListView可见的第一个index是0,并且还没滑动 if (((ListView) view).getFirstVisiblePosition() == 0) { View v = ((ListView) view).getChildAt(0); if ((v == null) || (v != null && v.getTop() == 0)) { intercept_action = INTERCEPT_ACTION.REFRESH; return true; } } } else if (view instanceof ScrollView) { if (view.getScrollY() == 0) { intercept_action = INTERCEPT_ACTION.REFRESH; return true; } } else if (view instanceof WebView) { if (view.getScrollY() == 0) { intercept_action = INTERCEPT_ACTION.REFRESH; return true; } } } else { if (loadMoreConfig.canLoadMore) { if (isShouldShowLoadMore) { intercept_action = INTERCEPT_ACTION.LOAD_MORE; return true; } } } break; } return false; } @Override public boolean onTouchEvent(MotionEvent ev) { boolean isRefreshTiping = false; boolean isLoadMoreTiping = false; if (onRefreshViewTouch != null) { onRefreshViewTouch.onTouch((int) ev.getRawX(), (int) ev.getRawY()); } switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: preY = ev.getRawY(); tmpY = ev.getRawY(); isRefreshTiping = false; isLoadMoreTiping = false; if (refreshViewHolder != null) { if (isRefreshing) break; refreshViewHolder.pullingTips(headerView, 0); } if (loadMoreViewHolder != null) { if (isLoadMoreing) break; loadMoreViewHolder.loadTips(bottomView, 0); } break; case MotionEvent.ACTION_MOVE: float currentY = ev.getRawY(); float offsetY = currentY - tmpY; float dis = currentY - preY; //下拉刷新 if (intercept_action == INTERCEPT_ACTION.REFRESH) { if (dis >= DisplayUtil.dip2px(getContext(), HEADER_HEIGHT)) { if (refreshViewHolder != null) { if (!isRefreshTiping) { //提示只有一次 refreshViewHolder.willRefreshTips(headerView); isRefreshTiping = true; } } shouldRefresh = true; } else { shouldRefresh = false; float ratio = dis / DisplayUtil.dip2px(getContext(), HEADER_HEIGHT); if (refreshViewHolder != null && !isRefreshing) refreshViewHolder.pullingTips(headerView, (int) (100 * ratio)); } if (dis >= 0 && (dis < totalLimit)) { this.scrollBy(0, -(int) offsetY); } if (dis >= totalLimit) { this.scrollTo(0, -totalLimit); } } else if ((intercept_action == INTERCEPT_ACTION.LOAD_MORE) && (dis < 0)) { //上拉加载 this.scrollBy(0, -(int) offsetY); if (Math.abs(dis) >= DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT)) { if (!isLoadMoreTiping) { loadMoreViewHolder.willloadTips(bottomView); isLoadMoreTiping = true; } shouldLoadMore = true; } else { shouldLoadMore = false; float ratio = dis / DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT); if (loadMoreViewHolder != null && !isLoadMoreing) loadMoreViewHolder.loadTips(headerView, (int) (100 * ratio)); } } tmpY = currentY; break; case MotionEvent.ACTION_UP: smoothToZeroPos(); break; case MotionEvent.ACTION_CANCEL: smoothToZeroPos(); break; } return true; } private void startRefresh() { if (refreshViewHolder != null) { refreshViewHolder.refreshingTips(headerView); //开始后台刷新任务 if (!isRefreshing) new RefreshTask().execute(); } } private void startLoadMore() { if (loadMoreViewHolder != null) { loadMoreViewHolder.loadingTips(bottomView); if (!isLoadMoreing) { new LoadMoreTask().execute(); } } } private void smoothToZeroPos() { //下拉刷新 if (intercept_action == INTERCEPT_ACTION.REFRESH) { if (shouldRefresh) startRefresh(); } else if (intercept_action == INTERCEPT_ACTION.LOAD_MORE) { //上拉加载更多 if (shouldLoadMore) { startLoadMore(); } } smoothScrollTo(0, 0); } private void smoothScrollTo(int destX, int destY) { int offsetY = destY - getScrollY(); scroller.startScroll(0, getScrollY(), 0, offsetY, 500); invalidate(); } @Override public void computeScroll() { super.computeScroll(); if (scroller.computeScrollOffset()) { scrollTo(scroller.getCurrX(), scroller.getCurrY()); postInvalidate(); } } //下拉刷新-管理UI方面的接口 public interface RefreshViewHolder { //还没到刷新点的提示 void pullingTips(View headerView, int progress); //快要刷新时的提示 void willRefreshTips(View headerView); //正在刷新时的状态 void refreshingTips(View headerView); //刷新完毕 void refreshCompleteTips(View headerView); } //下拉刷新-管理事务方面的接口 public interface IRefreshAction { void refresh(); void refreshComplete(); } //上拉加载-管理UI 接口 public interface LoadMoreViewHolder { //还没到加载点的提示 void loadTips(View headerView, int progress); //快要加载时的提示 void willloadTips(View headerView); //正在加载时的状态 void loadingTips(View headerView); //加载完毕 void loadCompleteTips(View headerView); } public interface ILoadMoreAction { void loadMore(); void loadMoreComplete(); } //触摸点传递的接口,可供实现类扩展更多自定义动画 public interface onRefreshViewTouch { void onTouch(int x, int y); } public View getHeaderView() { return headerView; } public void setHeaderView(View headerView, RelativeLayout.LayoutParams layoutParams) { this.headerView = headerView; headerContent.removeViewAt(0); RelativeLayout.LayoutParams defaultLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); defaultLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); if (layoutParams == null) headerView.setLayoutParams(defaultLayoutParams); else headerView.setLayoutParams(layoutParams); headerContent.addView(headerView, 0); } public void setBottomView(View bottomView, RelativeLayout.LayoutParams layoutParams) { this.bottomView = bottomView; bottomContent.removeViewAt(0); RelativeLayout.LayoutParams defaultLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); defaultLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); if (layoutParams == null) bottomView.setLayoutParams(defaultLayoutParams); else bottomView.setLayoutParams(layoutParams); bottomContent.addView(bottomView, 0); } public RefreshViewHolder getRefreshViewHolder() { return refreshViewHolder; } public void setRefreshViewHolder(RefreshViewHolder refreshViewHolder) { this.refreshViewHolder = refreshViewHolder; } private class RefreshTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { isRefreshing = true; shouldRefresh = false; if (iRefreshAction != null) { iRefreshAction.refresh(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); post(new Runnable() { @Override public void run() { if (refreshViewHolder != null) { refreshViewHolder.refreshCompleteTips(headerView); smoothScrollTo(0, 0); } } }); if (iRefreshAction != null) { iRefreshAction.refreshComplete(); } isRefreshing = false; } @Override protected void onCancelled() { super.onCancelled(); smoothScrollTo(0, 0); shouldRefresh = false; isRefreshing = false; } } private class LoadMoreTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { isLoadMoreing = true; shouldLoadMore = false; if (iLoadMoreAction != null) { iLoadMoreAction.loadMore(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); super.onPostExecute(aVoid); post(new Runnable() { @Override public void run() { if (loadMoreViewHolder != null) { loadMoreViewHolder.loadCompleteTips(headerView); smoothScrollTo(0, 0); } } }); if (iLoadMoreAction != null) { iLoadMoreAction.loadMoreComplete(); } isLoadMoreing = false; } @Override protected void onCancelled() { super.onCancelled(); smoothScrollTo(0, 0); shouldLoadMore = false; isLoadMoreing = false; } } public void setiRefreshAction(IRefreshAction iRefreshAction) { this.iRefreshAction = iRefreshAction; } public ILoadMoreAction getiLoadMoreAction() { return iLoadMoreAction; } public void setiLoadMoreAction(ILoadMoreAction iLoadMoreAction) { this.iLoadMoreAction = iLoadMoreAction; } public LoadMoreViewHolder getLoadMoreViewHolder() { return loadMoreViewHolder; } public void setLoadMoreViewHolder(LoadMoreViewHolder loadMoreViewHolder) { this.loadMoreViewHolder = loadMoreViewHolder; } public KRefreshView.onRefreshViewTouch getOnRefreshViewTouch() { return onRefreshViewTouch; } public void setOnRefreshViewTouch(KRefreshView.onRefreshViewTouch onRefreshViewTouch) { this.onRefreshViewTouch = onRefreshViewTouch; } public void setHeaderHeight(int headerHeightDp) { this.HEADER_HEIGHT = headerHeightDp; totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT); } public int getMAX_LIMIT_SLOT() { return MAX_LIMIT_SLOT; } public void setMAX_LIMIT_SLOT(int MAX_LIMIT_SLOT) { this.MAX_LIMIT_SLOT = MAX_LIMIT_SLOT; totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT); } public LoadMoreConfig getLoadMoreConfig() { return loadMoreConfig; } public void setLoadMoreConfig(LoadMoreConfig loadMoreConfig) { this.loadMoreConfig = loadMoreConfig; if (loadMoreConfig.canLoadMore) { if (loadMoreConfig.loadMoreView != null) setBottomView(loadMoreConfig.loadMoreView, null); if (loadMoreConfig.iLoadMoreAction != null) setiLoadMoreAction(loadMoreConfig.iLoadMoreAction); if (loadMoreConfig.loadMoreViewHolder != null) setLoadMoreViewHolder(loadMoreConfig.loadMoreViewHolder); if (loadMoreConfig.height > 0) BOTTOM_HEIGHT = loadMoreConfig.height; } } public static class LoadMoreConfig { public boolean canLoadMore; public View loadMoreView; public ILoadMoreAction iLoadMoreAction; public LoadMoreViewHolder loadMoreViewHolder; public int height; public LoadMoreConfig(boolean canLoadMore, View loadMoreView, ILoadMoreAction iLoadMoreAction, LoadMoreViewHolder loadMoreViewHolder, int height) { this.canLoadMore = canLoadMore; this.loadMoreView = loadMoreView; this.iLoadMoreAction = iLoadMoreAction; this.loadMoreViewHolder = loadMoreViewHolder; this.height = height; } } }
kkkkkkkkkkkkmay/RefreshView
RefreshView.java
66,702
package com.juhe.demo.component; import com.juhe.demo.common.CommonResult; import com.juhe.demo.constant.SystemConstant.PermitRequest; import com.juhe.demo.service.IAdminService; import io.jsonwebtoken.Claims; import java.util.Arrays; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; /** * @CLassName TokenCheckAspect * @Description token 快要过期切面处理 * @Author xuman.xu * @Date 2019/7/16 18:02 * @Version 1.0 **/ @Aspect @Component @Order(1) public class TokenCheckAspect { //刷新token时间间隔 private static final String CLAIM_KEY_CREATED = "created"; @Value("${jwt.tokenHeader}") private String tokenHeader; @Value("${jwt.tokenHead}") private String tokenHead; @Value("${jwt.expiration}") private Long expiration; @Autowired private JwtTokenUtil jwtTokenUtil; @Pointcut("execution(public * com.juhe.demo.controller.*.*(..))") public void TokenCheck() { } @Around("TokenCheck()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) attributes; HttpServletRequest request = servletRequestAttributes.getRequest(); String token = request.getHeader(tokenHeader); String newToken = null; if (!Arrays.asList(PermitRequest.MATCH_PERMIT_PATH).contains(request.getServletPath()) && StringUtils.isNotEmpty(token) && token.startsWith(tokenHead)) { Claims claims = jwtTokenUtil.getClaimsFromToken(token.substring(tokenHead.length())); if (claims != null) { Date expiredDate = claims.getExpiration(); //距离token过期时间三分之一时间内刷新token if (expiredDate.getTime() - System.currentTimeMillis() < expiration * 1000 / 3) { claims.put(CLAIM_KEY_CREATED, new Date()); newToken = jwtTokenUtil.refreshToken(claims); } } } Object result = joinPoint.proceed(); if (result instanceof CommonResult && StringUtils.isNotEmpty(newToken)) { CommonResult commonResult = (CommonResult) result; commonResult.setToken(tokenHead + " " + newToken); } return result; } }
juhedata/magic_mirror_service
src/main/java/com/juhe/demo/component/TokenCheckAspect.java
66,704
package com.java110.user.cmd.login; import com.alibaba.fastjson.JSONObject; import com.java110.core.annotation.Java110Cmd; import com.java110.core.context.ICmdDataFlowContext; import com.java110.core.event.cmd.Cmd; import com.java110.core.event.cmd.CmdEvent; import com.java110.core.factory.AuthenticationFactory; import com.java110.core.factory.GenerateCodeFactory; import com.java110.core.log.LoggerFactory; import com.java110.doc.annotation.*; import com.java110.dto.store.StoreUserDto; import com.java110.dto.user.UserDto; import com.java110.dto.user.UserLoginDto; import com.java110.intf.store.IStoreInnerServiceSMO; import com.java110.intf.user.IUserInnerServiceSMO; import com.java110.intf.user.IUserLoginInnerServiceSMO; import com.java110.po.user.UserLoginPo; import com.java110.utils.constant.CommonConstant; import com.java110.utils.constant.ResponseConstant; import com.java110.utils.exception.CmdException; import com.java110.utils.exception.SMOException; import com.java110.utils.util.Assert; import com.java110.utils.util.BeanConvertUtil; import com.java110.utils.util.DateUtil; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 用户登录 功能 * 请求地址为/app/login.pcUserLogin */ @Java110CmdDoc(title = "员工登录", description = "登录功能 主要用于 员工 或者管理员登录使用,<br/>" + "请求其他接口时 头信息中需要加 Authorization: Bearer token ,<br/>" + "token 是这个接口返回的内容<br/> " + "会话保持为2小时,请快要到2小时时,再次登录,保持会话</br>", httpMethod = "post", url = "http://{ip}:{port}/app/login.pcUserLogin", resource = "userDoc", author = "吴学文", serviceCode = "login.pcUserLogin", seq = 1 ) @Java110ParamsDoc( headers = { @Java110HeaderDoc(name="APP-ID",defaultValue = "通过dev账户分配应用",description = "应用APP-ID"), @Java110HeaderDoc(name="TRANSACTION-ID",defaultValue = "uuid",description = "交易流水号"), @Java110HeaderDoc(name="REQ-TIME",defaultValue = "20220917120915",description = "请求时间 YYYYMMDDhhmmss"), @Java110HeaderDoc(name="JAVA110-LANG",defaultValue = "zh-cn",description = "语言中文"), @Java110HeaderDoc(name="USER-ID",defaultValue = "-1",description = "调用用户ID 一般写-1"), }, params = { @Java110ParamDoc(name = "username", length = 30, remark = "用户名,物业系统分配"), @Java110ParamDoc(name = "passwd", length = 30, remark = "密码,物业系统分配"), }) @Java110ResponseDoc( params = { @Java110ParamDoc(name = "code", type = "int", length = 11, defaultValue = "0", remark = "返回编号,0 成功 其他失败"), @Java110ParamDoc(name = "msg", type = "String", length = 250, defaultValue = "成功", remark = "描述"), @Java110ParamDoc(name = "data", type = "Object", remark = "有效数据"), @Java110ParamDoc(parentNodeName = "data",name = "userId", type = "String", remark = "用户ID"), @Java110ParamDoc(parentNodeName = "data",name = "token", type = "String", remark = "临时票据"), } ) @Java110ExampleDoc( reqBody="{'username':'wuxw','passwd':'admin'}", resBody="{'code':0,'msg':'成功','data':{'userId':'123123','token':'123213'}}" ) @Java110Cmd(serviceCode = "login.pcUserLogin") public class PcUserLoginCmd extends Cmd { private final static Logger logger = LoggerFactory.getLogger(PcUserLoginCmd.class); @Autowired private IUserLoginInnerServiceSMO userLoginInnerServiceSMOImpl; @Autowired private IStoreInnerServiceSMO storeInnerServiceSMOImpl; @Autowired private IUserInnerServiceSMO userInnerServiceSMOImpl; @Override public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) { String paramIn = cmdDataFlowContext.getReqData(); Assert.isJsonObject(paramIn, "用户注册请求参数有误,不是有效的json格式 " + paramIn); Assert.jsonObjectHaveKey(paramIn, "username", "用户登录,未包含username节点,请检查" + paramIn); Assert.jsonObjectHaveKey(paramIn, "passwd", "用户登录,未包含passwd节点,请检查" + paramIn); AuthenticationFactory.checkLoginErrorCount(reqJson.getString("username")); } @Override public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException { ResponseEntity responseEntity = null; JSONObject paramInJson = JSONObject.parseObject(cmdDataFlowContext.getReqData()); //根据AppId 查询 是否有登录的服务,查询登录地址调用 UserDto userDto = new UserDto(); userDto.setName(paramInJson.getString("username")); userDto.setPassword(paramInJson.getString("passwd")); userDto.setLevelCds(new String[]{UserDto.LEVEL_CD_ADMIN, UserDto.LEVEL_CD_STAFF}); List<UserDto> userDtos = userInnerServiceSMOImpl.getUsers(userDto); if (userDtos == null || userDtos.size() < 1) { userDto.setName(""); userDto.setTel(paramInJson.getString("username")); userDtos = userInnerServiceSMOImpl.getUsers(userDto); } if (userDtos == null || userDtos.size() < 1) { responseEntity = new ResponseEntity<String>("用户或密码错误", HttpStatus.UNAUTHORIZED); AuthenticationFactory.userLoginError(paramInJson.getString("username")); cmdDataFlowContext.setResponseEntity(responseEntity); return; } //检查商户状态 StoreUserDto storeUserDto = new StoreUserDto(); storeUserDto.setUserId(userDtos.get(0).getUserId()); List<StoreUserDto> storeUserDtos = storeInnerServiceSMOImpl.getStoreUserInfo(storeUserDto); if (storeUserDtos != null && storeUserDtos.size() > 0) { String state = storeUserDtos.get(0).getState(); if ("48002".equals(state)) { responseEntity = new ResponseEntity<String>("当前商户限制登录,请联系管理员", HttpStatus.UNAUTHORIZED); cmdDataFlowContext.setResponseEntity(responseEntity); return; } } try { Map userMap = new HashMap(); userMap.put(CommonConstant.LOGIN_USER_ID, userDtos.get(0).getUserId()); userMap.put(CommonConstant.LOGIN_USER_NAME, userDtos.get(0).getUserName()); String token = AuthenticationFactory.createAndSaveToken(userMap); JSONObject userInfo = BeanConvertUtil.beanCovertJson(userDtos.get(0)); userInfo.remove("userPwd"); userInfo.put("token", token); //记录登录日志 UserLoginPo userLoginPo = new UserLoginPo(); userLoginPo.setLoginId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_loginId)); userLoginPo.setLoginTime(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_A)); userLoginPo.setPassword(userDtos.get(0).getPassword()); userLoginPo.setSource(UserLoginDto.SOURCE_WEB); userLoginPo.setToken(token); userLoginPo.setUserId(userInfo.getString("userId")); userLoginPo.setUserName(userInfo.getString("userName")); userLoginInnerServiceSMOImpl.saveUserLogin(userLoginPo); responseEntity = new ResponseEntity<String>(userInfo.toJSONString(), HttpStatus.OK); cmdDataFlowContext.setResponseEntity(responseEntity); } catch (Exception e) { logger.error("登录异常:", e); throw new SMOException(ResponseConstant.RESULT_CODE_INNER_ERROR, "系统内部错误,请联系管理员"); } } }
java110/MicroCommunity
service-user/src/main/java/com/java110/user/cmd/login/PcUserLoginCmd.java
66,705
package com.cmazxiaoma.site.web.site; import com.cmazxiaoma.support.message.entity.Message; import com.cmazxiaoma.support.message.service.MessageService; import com.cmazxiaoma.support.remind.entity.StartRemind; import com.cmazxiaoma.support.remind.service.StartRemindService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.*; import static java.util.concurrent.TimeUnit.NANOSECONDS; /** * @author cmazxiaoma * @version V1.0 * @Description: TODO * @date 2018/4/16 21:22 */ @Component @Slf4j public class MessageTimer { @Autowired private StartRemindService startRemindService; @Autowired private MessageService messageService; @PostConstruct public void start() { ScheduledExecutorService pool = Executors.newScheduledThreadPool(1); pool.scheduleAtFixedRate(new TimerTask() { @Override public void run() { List<StartRemind> startRemindList = startRemindService.listAll(); log.info("startRemindList={}", startRemindList); startRemindList.forEach(startRemind -> { log.info("站内通知用户" + startRemind.getUserId()); System.out.println("站内通知用户" + startRemind.getUserId()); Message message = new Message(); message.setUserId(startRemind.getUserId()); message.setDealSkuId(startRemind.getDealSkuId()); message.setTitle("开团提醒"); message.setContent(startRemind.getDealTitle() + "快要开团了"); message.setReaded(0); message.setCreateTime(new Date()); message.setUpdateTime(new Date()); messageService.save(message); // startRemindService.deleteById(startRemind.getId()); }); } }, 1000, 10 * 60 * 1000, TimeUnit.MILLISECONDS); } }
cmazxiaoma/groupon
groupon-site/site-controller/src/main/java/com/cmazxiaoma/site/web/site/MessageTimer.java
66,707
package com.weweibuy.webuy.learning.spring.rx; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import lombok.extern.slf4j.Slf4j; import java.io.IOException; /** * 被监听者 * @ClassName RxDefObservable * @Description * @Author durenhao * @Date 2019/3/24 20:18 **/ @Slf4j public class RxObservable implements ObservableOnSubscribe<String> { @Override public void subscribe(ObservableEmitter<String> emitter) throws Exception { int count = 0; String text = "hello rx ..." ; log.error("被观察者 发射 内容 {}", text + count++); emitter.onNext(text); emitter.onNext(text + count++); emitter.onNext(text + count++); emitter.onNext(text + count++); // Thread.sleep(1000); log.error("被观察者 业务完成了"); // onComplete 将无法发射消息 // emitter.onComplete(); Thread.sleep(1000); log.error("被观察者出错了"); emitter.onError(new IOException("io 异常了")); log.error("被观察者 快要完蛋了"); emitter.onComplete(); } }
weweibuy/weweibuy
webuy-learning/webuy-learning-spring/src/main/java/com/weweibuy/webuy/learning/spring/rx/RxObservable.java
66,708
package com.wanjian.scrollscreenshots; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.os.Bundle; import android.os.SystemClock; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * Created by wanjian on 2018/1/3. */ public class AutoScreenShotsAct extends Activity { private ListView listView; private ImageView img; private ViewGroup container; private List<Bitmap> bitmaps = new ArrayList<>(); private boolean isScreenShots = false; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_auto_scroll_demo); listView = findViewById(R.id.listview); img = findViewById(R.id.img); container = findViewById(R.id.container); setAdapter(); findViewById(R.id.start).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bitmaps.clear(); img.setImageBitmap(null); isScreenShots = true; autoScroll(); } }); findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { isScreenShots = false; } }); } private void autoScroll() { final int delay = 16;//延时16毫秒分发滑动事件 final int step = 10;//每次滑动距离5像素,可以根据需要调整(若卡顿的话实际滚动距离可能小于5) final MotionEvent motionEvent = MotionEvent.obtain(SystemClock.uptimeMillis() , SystemClock.uptimeMillis() , MotionEvent.ACTION_DOWN , listView.getWidth() / 2 , listView.getHeight() / 2 , 0); //先分发 MotionEvent.ACTION_DOWN 事件,我们指定为按下位置是listview的中间位置,当然其他位置也可以 listView.dispatchTouchEvent(motionEvent); /* 注意: 查看Listview源码可知 滑动距离大于ViewConfiguration.get(view.getContext()).getScaledTouchSlop()时listview才开始滚动 private boolean startScrollIfNeeded(int x, int y, MotionEvent vtev) { // Check if we have moved far enough that it looks more like a // scroll than a tap final int deltaY = y - mMotionY; final int distance = Math.abs(deltaY); final boolean overscroll = mScrollY != 0; if ((overscroll || distance > mTouchSlop) && (getNestedScrollAxes() & SCROLL_AXIS_VERTICAL) == 0) { ... return true; } return false; } */ motionEvent.setAction(MotionEvent.ACTION_MOVE); motionEvent.setLocation(motionEvent.getX(), motionEvent.getY() - (ViewConfiguration.get(listView.getContext()).getScaledTouchSlop())); listView.dispatchTouchEvent(motionEvent); final int startScrollY = (int) motionEvent.getY(); listView.postDelayed(new Runnable() { @Override public void run() { if (isScreenShots == false) {//注意:我们无法通过滚动距离来判断是否滚动到了最后,所以需要通过其他方式停止滚动 drawRemainAndAssemble(startScrollY, (int) motionEvent.getY()); return; } //滚动刚好一整屏时画到bitmap上 drawIfNeeded(startScrollY, (int) motionEvent.getY()); motionEvent.setAction(MotionEvent.ACTION_MOVE); //延时分发 MotionEvent.ACTION_MOVE 事件 /* 改变motionEvent的y坐标,nextStep越大滚动越快,但太大可能会导致掉帧,导致实际滚动距离小于我们滑动的距离 因为我们是根据(curScrollY - startScrollY) % container.getHeight() == 0来判定是否刚好滚动了一屏幕的, 所以快要滚动到刚好一屏幕位置时,修改nextStep的值,使下次滚动后刚好是一屏幕的距离。 当然nextStep也可以一直是1,这时就不需要凑整了,但这样会导致滚动的特别慢 */ int nextStep; int gap = (startScrollY - (int) motionEvent.getY() + step) % container.getHeight(); if (gap > 0 && gap < step) { nextStep = step - gap; } else { nextStep = step; } motionEvent.setLocation((int) motionEvent.getX(), (int) motionEvent.getY() - nextStep); listView.dispatchTouchEvent(motionEvent); listView.postDelayed(this, delay); } }, delay); } private void drawRemainAndAssemble(int startScrollY, int curScrollY) { //最后的可能不足一屏幕,需要单独处理 if ((curScrollY - startScrollY) % container.getHeight() != 0) { Bitmap film = Bitmap.createBitmap(container.getWidth(), container.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(); canvas.setBitmap(film); container.draw(canvas); int part = (startScrollY - curScrollY) / container.getHeight(); int remainHeight = startScrollY - curScrollY - container.getHeight() * part; Bitmap remainBmp = Bitmap.createBitmap(film, 0, container.getHeight() - remainHeight, container.getWidth(), remainHeight); bitmaps.add(remainBmp); } assembleBmp(); } private void assembleBmp() { int h = 0; for (Bitmap bitmap : bitmaps) { h += bitmap.getHeight(); } Bitmap bitmap = Bitmap.createBitmap(container.getWidth(), h, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); for (Bitmap b : bitmaps) { canvas.drawBitmap(b, 0, 0, null); canvas.translate(0, b.getHeight()); } ViewGroup.LayoutParams params = img.getLayoutParams(); params.width = bitmap.getWidth() * 2; params.height = bitmap.getHeight() * 2; img.requestLayout(); img.setImageBitmap(bitmap); } private void drawIfNeeded(int startScrollY, int curScrollY) { if ((curScrollY - startScrollY) % container.getHeight() == 0) { //正好滚动满一屏 //为了更通用,我们是把ListView的父布局(和ListView宽高相同)画到了bitmap上 Bitmap film = Bitmap.createBitmap(container.getWidth(), container.getHeight(), Bitmap.Config.RGB_565); Canvas canvas = new Canvas(); canvas.setBitmap(film); container.draw(canvas); bitmaps.add(film); } } private void setAdapter() { listView.setAdapter(new BaseAdapter() { @Override public int getCount() { return 100; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, listView, false); convertView.setTag(R.id.index, convertView.findViewById(R.id.index)); } ((TextView) convertView.getTag(R.id.index)).setText(position + ""); return convertView; } }); } }
android-notes/auto-scroll-capture
app/src/main/java/com/wanjian/scrollscreenshots/AutoScreenShotsAct.java
66,709
package com.guet.ARC.service; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.guet.ARC.common.domain.PageInfo; import com.guet.ARC.common.domain.ResultCode; import com.guet.ARC.common.enmu.RedisCacheKey; import com.guet.ARC.common.exception.AlertException; import com.guet.ARC.dao.RoomRepository; import com.guet.ARC.dao.RoomReservationRepository; import com.guet.ARC.dao.UserRepository; import com.guet.ARC.dao.mybatis.RoomReservationQueryRepository; import com.guet.ARC.dao.mybatis.query.RoomReservationQuery; import com.guet.ARC.domain.Message; import com.guet.ARC.domain.Room; import com.guet.ARC.domain.RoomReservation; import com.guet.ARC.domain.User; import com.guet.ARC.domain.dto.apply.MyApplyQueryDTO; import com.guet.ARC.domain.dto.room.ApplyRoomDTO; import com.guet.ARC.domain.dto.room.RoomApplyDetailListQueryDTO; import com.guet.ARC.domain.dto.room.RoomReserveReviewedDTO; import com.guet.ARC.domain.dto.room.UserRoomReservationDetailQueryDTO; import com.guet.ARC.domain.enums.MessageType; import com.guet.ARC.domain.enums.ReservationState; import com.guet.ARC.domain.vo.room.RoomReservationAdminVo; import com.guet.ARC.domain.vo.room.RoomReservationUserVo; import com.guet.ARC.domain.vo.room.RoomReservationVo; import com.guet.ARC.util.CommonUtils; import com.guet.ARC.util.RedisCacheUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cglib.beans.BeanCopier; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.transaction.Transactional; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @Service @Slf4j public class RoomReservationService { @Autowired private UserRepository userRepository; @Autowired private RoomReservationQueryRepository roomReservationQueryRepository; @Autowired private RoomReservationRepository roomReservationRepository; @Autowired private RoomReservationQuery roomReservationQuery; @Autowired private RoomRepository roomRepository; @Autowired private EmailService emailService; @Autowired private MessageService messageService; @Autowired private RedisCacheUtil<String> redisCacheUtil; public void cancelApply(String roomReservationId, String reason) { if (roomReservationId == null || roomReservationId.trim().isEmpty()) { throw new AlertException(ResultCode.PARAM_IS_BLANK); } Optional<RoomReservation> optionalRoomReservation = roomReservationRepository.findById(roomReservationId); if (optionalRoomReservation.isPresent()) { RoomReservation roomReservation = optionalRoomReservation.get(); roomReservation.setState(ReservationState.ROOM_RESERVE_CANCELED); roomReservation.setUpdateTime(System.currentTimeMillis()); roomReservation.setRemark(reason); roomReservationRepository.save(roomReservation); // 发送取消预约申请,给审核人发 Optional<Room> roomOptional = roomRepository.findById(roomReservation.getRoomId()); if (roomOptional.isPresent()) { Room room = roomOptional.get(); Optional<User> userOptional = userRepository.findById(room.getChargePersonId()); if (userOptional.isPresent()) { User user = userOptional.get(); CompletableFuture.runAsync(() -> { roomReservation.getState().sendReservationNoticeMessage(room, user, roomReservation); }); // 发送消息 userRepository.findById(roomReservation.getUserId()).ifPresent(curUser -> { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); String startTimeStr = sdf.format(new Date(roomReservation.getReserveStartTime())); String endTimeStr = sdf.format(new Date(roomReservation.getReserveEndTime())); Message message = new Message(); message.setMessageReceiverId(room.getChargePersonId()); message.setMessageType(MessageType.RESULT); message.setContent(curUser.getName() + "取消了房间" + room.getRoomName() + "的预约申请。预约时间:" + startTimeStr + "~" + endTimeStr + "。"); messageService.sendMessage(message); // 发送邮件提醒,发给房间负责人 if (!StrUtil.isEmpty(user.getMail())) { String content = "您收到来自" + curUser.getName() + "的" + room.getRoomName() + "房间预约申请取消通知,预约时间" + startTimeStr + "至" + endTimeStr + "。" + "取消理由:" + reason + "。"; emailService.sendSimpleMail(user.getMail(), curUser.getName() + "的" + room.getRoomName() + "预约申请取消通知", content); } }); } } } } //同步方法 @Transactional(rollbackOn = RuntimeException.class) public synchronized RoomReservation applyRoom(ApplyRoomDTO applyRoomDTO) { // 检测预约起始和预约结束时间 long subTime = applyRoomDTO.getEndTime() - applyRoomDTO.getStartTime(); long hour12 = 43200000; long halfHour = 1800000; if (subTime <= 0) { throw new AlertException(1000, "预约起始时间不能大于等于结束时间"); } else if (subTime > hour12) { throw new AlertException(1000, "单次房间的预约时间不能大于12小时"); } else if (subTime < halfHour) { throw new AlertException(1000, "单次房间的预约时间不能小于30分钟"); } // 检测是否已经预约 String userId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); // 是待审核状态且在这段预约时间内代表我已经预约过了, 预约起始时间不能在准备预约的时间范围内,结束时间不能在准备结束预约的时间范围内 List<RoomReservation> roomReservations = roomReservationQueryRepository.selectMany( roomReservationQuery.queryMyReservationListByTimeSql(applyRoomDTO, userId) ); if (!roomReservations.isEmpty()) { throw new AlertException(1000, "您已经预约过该房间,请勿重复操作,在我的预约中查看"); } long time = System.currentTimeMillis(); RoomReservation roomReservation = new RoomReservation(); roomReservation.setId(CommonUtils.generateUUID()); roomReservation.setRoomUsage(applyRoomDTO.getRoomUsage()); roomReservation.setReserveStartTime(applyRoomDTO.getStartTime()); roomReservation.setReserveEndTime(applyRoomDTO.getEndTime()); roomReservation.setState(ReservationState.ROOM_RESERVE_TO_BE_REVIEWED); roomReservation.setCreateTime(time); roomReservation.setUpdateTime(time); roomReservation.setUserId(userId); roomReservation.setRoomId(applyRoomDTO.getRoomId()); roomReservationRepository.save(roomReservation); setRoomApplyNotifyCache(roomReservation, userId); Optional<Room> roomOptional = roomRepository.findById(roomReservation.getRoomId()); if (roomOptional.isPresent()) { Room room = roomOptional.get(); String chargePersonId = room.getChargePersonId(); Optional<User> userOptional = userRepository.findById(chargePersonId); Optional<User> curUserOptional = userRepository.findById(userId); if (userOptional.isPresent() && curUserOptional.isPresent()) { User user = userOptional.get(); String content = ""; // 发送审核邮件 if (!StrUtil.isEmpty(user.getMail())) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); String startTimeStr = sdf.format(new Date(applyRoomDTO.getStartTime())); String endTimeStr = sdf.format(new Date(applyRoomDTO.getEndTime())); content = "您收到来自" + curUserOptional.get().getName() + "的" + room.getRoomName() + "房间预约申请,预约时间" + startTimeStr + "至" + endTimeStr + ",请您及时处理。"; // 异步发送 emailService.sendHtmlMail(user.getMail(), curUserOptional.get().getName() + "房间预约申请待审核通知", content); } // 发送订阅消息 if (!StrUtil.isEmpty(user.getOpenId())) { // 绑定微信才可接受订阅消息 // 构建消息体,并异步发送 CompletableFuture.runAsync(() -> { // 因为需要房间管理者的openid,所有user要更改一下name未预约人 user.setName(curUserOptional.get().getName()); roomReservation.getState().sendReservationNoticeMessage(room, user, roomReservation); }); } // 发送系统消息 Message message = new Message(); message.setMessageReceiverId(room.getChargePersonId()); message.setMessageType(MessageType.TODO); message.setContent(content); messageService.sendMessage(message); } } return roomReservation; } public PageInfo<RoomReservationUserVo> queryRoomApplyDetailList(RoomApplyDetailListQueryDTO roomApplyDetailListQueryDTO) { String roomId = roomApplyDetailListQueryDTO.getRoomId(); Long startTime = roomApplyDetailListQueryDTO.getStartTime(); Long endTime = roomApplyDetailListQueryDTO.getEndTime(); Long[] standardTime = CommonUtils.getStandardStartTimeAndEndTime(startTime, endTime); // 获取startTime的凌晨00:00 long webAppDateStart = standardTime[0]; // 获取这endTime 23:59:59的毫秒值 long webAppDateEnd = standardTime[1]; // 检查时间跨度是否超过14天 if (webAppDateEnd - webAppDateStart <= 0) { throw new AlertException(1000, "结束时间不能小于等于开始时间"); } long days = (webAppDateEnd - webAppDateStart) / 1000 / 60 / 60 / 24; if (days > 30) { throw new AlertException(1000, "查询数据的时间跨度不允许超过30天"); } // 查询相应房间的所有预约记录 PageRequest pageRequest = PageRequest.of(roomApplyDetailListQueryDTO.getPage() - 1, roomApplyDetailListQueryDTO.getSize()); org.springframework.data.domain.Page<RoomReservation> queryPageData = roomReservationRepository.findByRoomIdAndReserveStartTimeBetweenOrderByCreateTimeDesc(roomId, webAppDateStart, webAppDateEnd, pageRequest); List<RoomReservation> roomReservationList = queryPageData.getContent(); List<RoomReservationUserVo> roomReservationUserVos = new ArrayList<>(); BeanCopier beanCopier = BeanCopier.create(RoomReservation.class, RoomReservationUserVo.class, false); // 添加每条预约记录的预约人姓名 for (RoomReservation roomReservation : roomReservationList) { RoomReservationUserVo roomReservationUserVo = new RoomReservationUserVo(); beanCopier.copy(roomReservation, roomReservationUserVo, null); Optional<User> optionalUser = userRepository.findById(roomReservation.getUserId()); if (optionalUser.isPresent()) { User user = optionalUser.get(); roomReservationUserVo.setName(user.getName()); } roomReservationUserVos.add(roomReservationUserVo); } PageInfo<RoomReservationUserVo> pageInfo = new PageInfo<>(); pageInfo.setPage(roomApplyDetailListQueryDTO.getPage()); pageInfo.setTotalSize(queryPageData.getTotalElements()); pageInfo.setPageData(roomReservationUserVos); return pageInfo; } public PageInfo<RoomReservationVo> queryMyApply(MyApplyQueryDTO myApplyQueryDTO) { String userId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); Page<RoomReservationVo> queryPageData = PageHelper.startPage(myApplyQueryDTO.getPage(), myApplyQueryDTO.getSize()); List<RoomReservationVo> roomReservationVos = roomReservationQueryRepository.selectRoomReservationsVo( roomReservationQuery.queryMyApplySql(myApplyQueryDTO, userId) ); return new PageInfo<>(queryPageData); } public PageInfo<RoomReservationVo> queryUserReserveRecord(UserRoomReservationDetailQueryDTO queryDTO) { Page<RoomReservationVo> queryPageData = PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize()); List<RoomReservationVo> roomReservationVos = roomReservationQueryRepository.selectRoomReservationsVo( roomReservationQuery.queryUserReserveRecordSql(queryDTO) ); PageInfo<RoomReservationVo> roomReservationPageInfo = new PageInfo<>(); roomReservationPageInfo.setPage(queryDTO.getPage()); roomReservationPageInfo.setTotalSize(queryPageData.getTotal()); roomReservationPageInfo.setPageData(roomReservationVos); return roomReservationPageInfo; } // 获取待审核列表 public PageInfo<RoomReservationAdminVo> queryRoomReserveToBeReviewed(RoomReserveReviewedDTO queryDTO) { String currentUserId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); Page<RoomReservationAdminVo> queryPageData = PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize()); if (!StrUtil.isEmpty(queryDTO.getStuNum())) { Optional<User> userOptional = userRepository.findByStuNum(queryDTO.getStuNum()); userOptional.ifPresent(user -> queryDTO.setApplyUserId(user.getId())); } List<RoomReservationAdminVo> filteredList = new ArrayList<>(); List<RoomReservationAdminVo> roomReservationAdminVos = roomReservationQueryRepository.selectRoomReservationsAdminVo(roomReservationQuery.queryRoomReserveToBeReviewedSql(queryDTO, currentUserId)); long now = System.currentTimeMillis(); for (RoomReservationAdminVo roomReservationAdminVo : roomReservationAdminVos) { Optional<User> optionalUser = userRepository.findById(roomReservationAdminVo.getUserId()); optionalUser.ifPresent(user -> { roomReservationAdminVo.setName(user.getName()); roomReservationAdminVo.setStuNum(user.getStuNum()); }); // fix:问题:只要现在的时间大于起始时间就会被认为超时未处理,应该要加上是否已经被处理,未被处理的才要判断是否超时 if (now > roomReservationAdminVo.getReserveStartTime() && roomReservationAdminVo.getState().equals(ReservationState.ROOM_RESERVE_TO_BE_REVIEWED)) { handleTimeOutReservationAdmin(roomReservationAdminVo); // 被设置超时的房间预约信息,从列表中去除 continue; } filteredList.add(roomReservationAdminVo); } // 移除超市 PageInfo<RoomReservationAdminVo> roomReservationPageInfo = new PageInfo<>(); roomReservationPageInfo.setPage(queryDTO.getPage()); roomReservationPageInfo.setTotalSize(queryPageData.getTotal()); roomReservationPageInfo.setPageData(filteredList); return roomReservationPageInfo; } // 通过或者驳回预约 public void passOrRejectReserve(String reserveId, boolean pass, String reason) { if (!StringUtils.hasLength(reason)) { reason = ""; } String userId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); Optional<RoomReservation> roomReservationOptional = roomReservationRepository.findById(reserveId); // 审核人 Optional<User> userOptional = userRepository.findById(userId); if (roomReservationOptional.isPresent() && userOptional.isPresent()) { RoomReservation roomReservation = roomReservationOptional.get(); User user = userOptional.get(); // 是否超出预约结束时间 if (System.currentTimeMillis() >= roomReservation.getReserveStartTime()) { throw new AlertException(1000, "已超过预约起始时间, 系统已自动更改申请状态,无法操作。请刷新页面。"); } // 发送通知邮件信息 // 发起请求的用户 Optional<User> roomReservationUserOptional = userRepository.findById(roomReservation.getUserId()); String toPersonMail = null; if (roomReservationUserOptional.isPresent()) { toPersonMail = roomReservationUserOptional.get().getMail(); } else { throw new AlertException(ResultCode.PARAM_IS_ILLEGAL); } Optional<Room> roomOptional = roomRepository.findById(roomReservation.getRoomId()); String roomName = null; if (roomOptional.isPresent()) { roomName = roomOptional.get().getRoomName(); } else { throw new AlertException(ResultCode.PARAM_IS_ILLEGAL); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); String startTimeStr = sdf.format(new Date(roomReservation.getReserveStartTime())); String endTimeStr = sdf.format(new Date(roomReservation.getReserveEndTime())); String createTimeStr = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(roomReservation.getCreateTime())); String content = ""; if (pass) { // 是否在相同时间内已经预约过了,也就是这段时间内是否有其他待审核预约、已审核预约,表示该房间已被站其他人占用,本次预约就不能再给通过了,已经是驳回状态 if (roomReservation.getState().equals(ReservationState.ROOM_RESERVE_TO_BE_REJECTED) && checkSameTimeReservationWithStatus(reserveId)) { throw new AlertException(1000, "用户在相同时间再次进行预约,无法从驳回进行通过操作"); } roomReservation.setRemark(reason); roomReservation.setState(ReservationState.ROOM_RESERVE_ALREADY_REVIEWED); // 发送通过邮件提醒 if (StringUtils.hasLength(toPersonMail)) { // 如果有邮箱就发送通知 content = "您" + createTimeStr + "发起的" + roomName + "预约申请,预约时间为" + startTimeStr + "至" + endTimeStr + ",已由审核员审核通过。"; emailService.sendSimpleMail(toPersonMail, roomName + "预约申请审核结果通知", content); } } else { roomReservation.setRemark(reason); roomReservation.setState(ReservationState.ROOM_RESERVE_TO_BE_REJECTED); // 发送通过邮件提醒 if (StringUtils.hasLength(toPersonMail)) { // 如果有邮箱就发送通知 content = "您" + createTimeStr + "发起的" + roomName + "预约申请,预约时间为" + startTimeStr + "至" + endTimeStr + ",审核不通过。原因为:" + reason + "。"; emailService.sendSimpleMail(toPersonMail, roomName + "预约申请审核结果通知", content); } } roomReservation.setVerifyUserName(user.getName()); roomReservation.setUpdateTime(System.currentTimeMillis()); roomReservationRepository.save(roomReservation); // 发送订阅消息 CompletableFuture.runAsync(() -> { roomReservation.getState().sendReservationNoticeMessage(roomOptional.get(), roomReservationUserOptional.get(), roomReservation); }); // 发送系统消息 Message message = new Message(); message.setMessageReceiverId(roomOptional.get().getChargePersonId()); message.setMessageType(MessageType.RESULT); message.setContent(content); messageService.sendMessage(message); } else { throw new AlertException(ResultCode.PARAM_IS_INVALID); } } // 删除预约记录 public void delRoomReservationRecord(String id) { roomReservationRepository.deleteById(id); } /** * 主要是用于处理已驳回是在进行通过的情况 * * @param reserveId * @return */ private boolean checkSameTimeReservationWithStatus(String reserveId) { // 这段时间内这个房间是否有其他待审核预约、已审核预约记录,这两个状态表示房间已经被占有 Optional<RoomReservation> roomReservationOptional = roomReservationRepository.findById(reserveId); if (roomReservationOptional.isPresent()) { RoomReservation roomReservation = roomReservationOptional.get(); // 预约起始和截止时间 Long reserveStartTime = roomReservation.getReserveStartTime(); Long reserveEndTime = roomReservation.getReserveEndTime(); String roomId = roomReservation.getRoomId(); List<ReservationState> reservationStates = new ArrayList<>(); reservationStates.add(ReservationState.ROOM_RESERVE_TO_BE_REVIEWED); reservationStates.add(ReservationState.ROOM_RESERVE_ALREADY_REVIEWED); long count = roomReservationRepository.countByReserveStartTimeAndReserveEndTimeAndRoomIdAndStateIn( reserveStartTime, reserveEndTime, roomId, reservationStates ); // 表示有冲突,驳回后用户在这段时间尝试了重新预约 return count > 0; } else { throw new AlertException(ResultCode.ILLEGAL_OPERATION); } } private void handleTimeOutReservationAdmin(RoomReservationAdminVo roomReservationVo) { roomReservationVo.setState(ReservationState.ROOM_RESERVE_IS_TIME_OUT); BeanCopier copier = BeanCopier.create(RoomReservationAdminVo.class, RoomReservation.class, false); RoomReservation roomReservation = new RoomReservation(); copier.copy(roomReservationVo, roomReservation, null); roomReservation.setUpdateTime(System.currentTimeMillis()); roomReservationRepository.save(roomReservation); } /** * 包含两个提醒,发送时机就是key过期时,快要过期提醒审核,已过期提醒申请人超时未处理重新申请。 * @param roomReservation 房间预约实体 * @param userId 当前登陆人id */ private void setRoomApplyNotifyCache(RoomReservation roomReservation, String userId) { // 记录当前时间->房间预约起始时间,redis缓存,用于判断是否管理员超期未处理,自动更改状态,通知用户房间预约超期未处理,防止占用时间段,用户可以重新预约 long cacheTimeSecond = DateUtil.between(new Date(), new Date(roomReservation.getReserveStartTime()), DateUnit.SECOND); String roomOccupancyApplyKey = RedisCacheKey.ROOM_OCCUPANCY_APPLY_KEY.concatKey(roomReservation.getId()); redisCacheUtil.setCacheObject(roomOccupancyApplyKey, userId, cacheTimeSecond, TimeUnit.SECONDS); // 前一个小时提醒负责人审核。 预约间隔最少是30分钟 long cacheNotifyChargerSecond = cacheTimeSecond - (60 * 60); // 当前时间距离预约起始时间小于一个小时 if (cacheTimeSecond <= 3600L && cacheTimeSecond > 1800L) { // 不足一个小时,但是大于半个小时 cacheNotifyChargerSecond = cacheTimeSecond - (30 * 60); } else if (cacheTimeSecond < 1800L) { // 不设置通知审核人 return; } // 缓存 String notifyChargerKey = RedisCacheKey.ROOM_APPLY_TIMEOUT_NOTIFY_KEY.concatKey(roomReservation.getId()); redisCacheUtil.setCacheObject(notifyChargerKey, userId, cacheNotifyChargerSecond, TimeUnit.SECONDS); } }
MuShanYu/apply-room-record
src/main/java/com/guet/ARC/service/RoomReservationService.java
66,710
package org.song.demo.listvideo; import android.graphics.Rect; import android.os.Handler; import android.view.View; /** * list列表 item的生命周期控制(即将滚出屏幕 和 进入活动状态的item 监听) * item高度大于listview的一半以上最好 * Created by song on 2017/6/1. * Contact github.com/tohodog */ public class ListCalculator { private boolean isScrollUp = true;//滚动方向 private Getter getter; private CallBack callBack; public int VISIBILITY_PERCENTS = 80; private int currentActiveItem = -1;//当前活动的item public ListCalculator(Getter getter, CallBack callBack) { this.getter = getter; this.callBack = callBack; } /** * 滚动中 */ public void onScrolling(int status) { if (!checkUpDown() || (status == 0 & currentActiveItem >= 0)) return; int firstVisiblePosition = getter.getFirstVisiblePosition(); int lastVisiblePosition = getter.getLastVisiblePosition(); int activeItem = currentActiveItem; //确保 活动item 在屏幕里了 if (activeItem < firstVisiblePosition || activeItem > lastVisiblePosition) { activeItem = isScrollUp ? firstVisiblePosition : lastVisiblePosition; } //计算当前新的活动item应该是哪个 View currentView = getter.getChildAt(activeItem - firstVisiblePosition); int currentP = getVisibilityPercents(currentView); if (isScrollUp) {//往上滚动 if (lastVisiblePosition >= activeItem + 1) {//存在下一个item View nextView = getter.getChildAt(activeItem + 1 - firstVisiblePosition); int nextP = getVisibilityPercents(nextView); if (enoughPercentsForDeactivation(currentP, nextP)) { activeItem = activeItem + 1; } } } else {//往下滚动 if (firstVisiblePosition <= activeItem - 1) {//存在上一个item View preView = getter.getChildAt(activeItem - 1 - firstVisiblePosition); int preP = getVisibilityPercents(preView); if (enoughPercentsForDeactivation(currentP, preP)) { activeItem = activeItem - 1; } } } handler.removeCallbacks(run); //不一样说明活动的item改变了 if (activeItem != currentActiveItem) { View v1 = getter.getChildAt(currentActiveItem - firstVisiblePosition); if (v1 != null) callBack.deactivate(v1, currentActiveItem); View v2 = getter.getChildAt(activeItem - firstVisiblePosition); if (v2 != null) { callBack.activeOnScrolling(v2, activeItem); if (currentActiveItem < 0){ handler.postDelayed(run, 300); //callBack.activeOnScrolled(v2, activeItem); } } currentActiveItem = activeItem; isChangeFlag = true; } } private boolean isChangeFlag; //根据两个item的显示百分比 判断是否销毁上一个item private boolean enoughPercentsForDeactivation(int visibilityPercents, int nextVisibilityPercents) { return (visibilityPercents < VISIBILITY_PERCENTS && nextVisibilityPercents >= VISIBILITY_PERCENTS) || (visibilityPercents <= 20 && visibilityPercents > 0) ||//活动的item快要消失 (visibilityPercents < 95 && nextVisibilityPercents == 100);//下一个item100%显示了 上一个活动item只需要隐藏一点就切换 } /** * 停止滚动 */ public void onScrolled(int delayed) { if (isChangeFlag) { handler.removeCallbacks(run); handler.postDelayed(run, delayed); } } private Handler handler = new Handler(); private Runnable run = new Runnable() { @Override public void run() { isChangeFlag = false; View v = getter.getChildAt(currentActiveItem - getter.getFirstVisiblePosition()); if (v != null) callBack.activeOnScrolled(v, currentActiveItem); } }; //todo 如果外部手动点了播放 改变了活动item 需要设置这里的活动item public void setCurrentActiveItem(int currentActiveItem) { if (this.currentActiveItem != currentActiveItem) { int firstVisiblePosition = getter.getFirstVisiblePosition(); View currentView = getter.getChildAt(this.currentActiveItem - firstVisiblePosition); if (currentView != null) callBack.deactivate(currentView, this.currentActiveItem); currentView = getter.getChildAt(currentActiveItem - firstVisiblePosition); if (currentView != null) { this.currentActiveItem = currentActiveItem; callBack.activeOnScrolled(currentView, currentActiveItem); } } } public int getCurrentActiveItem() { return currentActiveItem; } ///////////////以下为判断item显示百分比的逻辑代码/////////////////// private int mOldTop; private int mOldFirstVisibleItem; //检测滑动方向 private boolean checkUpDown() { View view = getter.getChildAt(0); if (view == null) return false; int top = view.getTop(); int firstVisibleItem = getter.getFirstVisiblePosition(); if (firstVisibleItem == mOldFirstVisibleItem) { if (top > mOldTop) { isScrollUp = false; } else if (top < mOldTop) { isScrollUp = true; } } else { isScrollUp = firstVisibleItem > mOldFirstVisibleItem; } mOldTop = top; mOldFirstVisibleItem = firstVisibleItem; return true; } //获取item的显示在屏幕上的百分比 private int getVisibilityPercents(View view) { final Rect currentViewRect = new Rect(); int percents = 100; int height = (view == null || view.getVisibility() != View.VISIBLE) ? 0 : view.getHeight(); if (height == 0) { return 0; } view.getLocalVisibleRect(currentViewRect); if (viewIsPartiallyHiddenTop(currentViewRect)) { // view is partially hidden behind the top edge percents = (height - currentViewRect.top) * 100 / height; } else if (viewIsPartiallyHiddenBottom(currentViewRect, height)) { percents = currentViewRect.bottom * 100 / height; } return percents; } private boolean viewIsPartiallyHiddenBottom(Rect currentViewRect, int height) { return currentViewRect.bottom > 0 && currentViewRect.bottom < height; } private boolean viewIsPartiallyHiddenTop(Rect currentViewRect) { return currentViewRect.top > 0; } }
tohodog/QSVideoPlayer
app/src/main/java/org/song/demo/listvideo/ListCalculator.java
66,711
/* * Copyright [2016-2026] wangcheng([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.wantedonline.puppy.httpserver.system; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import cn.wantedonline.puppy.httpserver.common.HttpServerConfig; import cn.wantedonline.puppy.spring.annotation.AfterBootstrap; import cn.wantedonline.puppy.spring.annotation.Config; import cn.wantedonline.puppy.util.Log; import cn.wantedonline.puppy.util.concurrent.ConcurrentUtil; import io.netty.channel.nio.NioEventLoopGroup; import org.slf4j.Logger; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SystemChecker { private static final Logger log = Log.getLogger(SystemMonitor.class); private static SystemChecker INSTANCE; private SystemChecker() { INSTANCE = this; } public static SystemChecker getInstance() { return INSTANCE; } @Autowired protected HttpServerConfig config; private static volatile boolean denialOfService = false; /** 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500 */ private static volatile boolean denialOfServiceAlmost = false; /** 系统最重要的线程池的监控,要很实时 */ @Config private int dosMonitorCheckSec = 1; /** 垃圾回收监控,建议5分钟监控一次(因为是总回收时间的对比) */ @Config private int gcMonitorSec = 5 * 60; private static volatile boolean lastTestDenialOfService = false; @Config(resetable = true) private double loadMonitorErrorThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM; /** 系统负载监控,建议半分钟监控一次(因为是平均负载) */ @Config private int loadMonitorSec = 1 * 30; /** 数值的界定,请参考http://blog.csdn.net/marising/article/details/5182771 */ @Config(resetable = true) private double loadMonitorWarnThreshold = ConcurrentUtil.CORE_PROCESSOR_NUM * 0.7; /** 线程cpu时间监控,建议每半分钟监控一次 */ @Config private int threadCpuTimeMonitorSec = 1 * 30; @Config(resetable = true) private int threadMonitorQueueThreshold = 1000; /** 线程池监控,建议每5秒钟监控一次(因为每时每刻的queue的数量都可能在大幅度变化) */ @Config private int threadMonitorSec = 5; /** log线程池监控,要严防队列过大导致IO过高和内存溢出 */ @Config private int logMonitorCheckSec = 10; @Config(resetable = true) private int logMonitorLimit = 20000; private static volatile boolean logEnabled = true; private static volatile boolean logAlreadyExceeded = false; /** 为了防止启动时候突然飙高而报,启动时候第一次不报,可以防止服务器启动时突然的堆积日志把服务器搞崩溃 */ private static volatile boolean logExceededFirstTime = true; /** 线程池允许等待的线程数 */ @Config(resetable = true) private int threadPoolQueueCountLimit = 30000; @AfterBootstrap protected void init() { SystemMonitor.initGarbageCollectMonitor(gcMonitorSec); SystemMonitor.initLoadAverageMonitor(loadMonitorSec); SystemMonitor.initThreadCpuTimeMonitor(threadCpuTimeMonitorSec); SystemMonitor.initThreadPoolMonitor(threadMonitorSec, threadMonitorQueueThreshold); initDenialOfServiceMonitor(); initLogMonitor(); } public void initDenialOfServiceMonitor() { if (dosMonitorCheckSec > 0) { log.info("DenialOfServiceMonitor ON, interval:{}sec, Worker EventLoop Size:{}", dosMonitorCheckSec, config.getWorkerEventLoopGroup().executorCount()); ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() { /** * check denialOfServiceAlmost */ private boolean check2(NioEventLoopGroup workerEventLoop) { int _threadPoolQueueCountLimit = threadPoolQueueCountLimit - 500;// 几乎要拒绝服务的等待队列阀值 //TODO:如何实现DOS防范 /* int activeCount = executor.getActiveCount(); int queueCount = executor.getQueue().size(); // 等待队列的大小 int largestPoolSize = executor.getLargestPoolSize(); int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数 if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) { ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS activeCount = executor.getActiveCount(); int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > _threadPoolQueueCountLimit) { denialOfServiceAlmost = true; return true; } } */ return false; } /** * check denialOfService */ private boolean check(NioEventLoopGroup workerEventLoop) { /* int activeCount = executor.getActiveCount(); int queueCount = executor.getQueue().size(); // 等待队列的大小 int largestPoolSize = executor.getLargestPoolSize(); int atLeastReamin = largestPoolSize <= HttpServerConfig.PROCESSOR_NUM ? 1 : HttpServerConfig.PROCESSOR_NUM; // 最少要剩余的空闲线程数 if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize) { String pipelineInfo = SystemInfo.getThreadsDetailInfo("PIPELINE", true, 20); // 先打印好 ConcurrentUtil.threadSleep(2000); // 小小暂停一下,防止是那种突然一下子冲过来的情况而报DOS activeCount = executor.getActiveCount(); int currQueueCount = executor.getQueue().size(); // 等待队列的大小,如果持续增大,就说明肯定有问题,需要DOS if (activeCount > 0 && activeCount + atLeastReamin >= largestPoolSize && currQueueCount > queueCount && currQueueCount > threadPoolQueueCountLimit) { // 打印好了,线程池仍然大量占用,就发出报警邮件 if (!lastTestDenialOfService) { MDC.put("mailTitle", "DenialOfService"); log.error("DENIAL OF SERVICE, ACTIVE_SIZE:{}, WAITTING_QUEUE_SIZE:{}, RUNNING PIPELINE:\n{}\n\n", activeCount, currQueueCount, pipelineInfo); } denialOfService = true; lastTestDenialOfService = true; denialOfServiceAlmost = true; return true; } } */ return false; } @Override public void run() { boolean r = check(config.getWorkerEventLoopGroup()); boolean r1 = check(config.getWorkerEventLoopGroup()); if (!r && !r1) { denialOfService = false; lastTestDenialOfService = false; } boolean r2 = check2(config.getWorkerEventLoopGroup()); boolean r21 = check2(config.getWorkerEventLoopGroup()); if (!r2 && !r21) { denialOfServiceAlmost = false; } } }, dosMonitorCheckSec * 5, dosMonitorCheckSec, TimeUnit.SECONDS);// httpServer刚启动时,很有可能很多请求冲进来,先不拒绝服务,所以暂定5s后再开始定时 } } public void initLogMonitor() { if (logMonitorCheckSec > 0) { final ThreadPoolExecutor logExecutor = (ThreadPoolExecutor) ConcurrentUtil.getLogExecutor(); log.info("LogMonitor ON, interval:{}sec, logExecutorSize:{}", logMonitorCheckSec, logExecutor.getQueue().size()); ConcurrentUtil.getWatchdog().scheduleWithFixedDelay(new Runnable() { @Override public void run() { boolean r = isLogExceeded(logExecutor); if (!r) { logEnabled = true; logAlreadyExceeded = false; } } /** * 检查日志线程池队列任务数 * * @return 如果超过限值返回true,没超过返回false */ private boolean isLogExceeded(ThreadPoolExecutor executor) { int queueCount = executor.getQueue().size(); // 如果队列的log超过限制,就临时把日志功能关闭 if (queueCount > logMonitorLimit) { if (!logAlreadyExceeded) { // 保证超过限定值之后只报出一次,如果回退到限定值内,再超过才再报 if (logExceededFirstTime) { logExceededFirstTime = false; } else { MDC.put("mailTitle", "TOO MANY LOGS"); log.error("TOO MANY LOGS,WAITTING_QUEUE_SIZE:{}\n", queueCount); } } logEnabled = false; logAlreadyExceeded = true; return true; } return false; } }, logMonitorCheckSec, logMonitorCheckSec, TimeUnit.SECONDS); } } /** * 是否达到拒绝服务的阀值 */ public static boolean isDenialOfService() { return denialOfService; } /** * 快要接近denialOfService了,进一步退化,参数是: threadPoolQueueCountLimit - 500 */ public static boolean isDenialOfServiceAlmost() { return denialOfServiceAlmost; } /** * 如果日志功能打开了,才记录日志 */ public static boolean isLogEnabled() { return logEnabled; } public double getLoadMonitorErrorThreshold() { return loadMonitorErrorThreshold; } public double getLoadMonitorWarnThreshold() { return loadMonitorWarnThreshold; } }
34benma/Puppy
src/main/java/cn/wantedonline/puppy/httpserver/system/SystemChecker.java
66,712
package com.redmoon.oa.job; import java.sql.SQLException; import java.util.Iterator; import java.util.Vector; import cn.js.fan.db.ResultIterator; import cn.js.fan.db.ResultRecord; import cn.js.fan.util.*; import com.cloudwebsoft.framework.aop.ProxyFactory; import com.cloudwebsoft.framework.aop.Pointcut.MethodNamePointcut; import com.cloudwebsoft.framework.aop.base.Advisor; import com.cloudwebsoft.framework.db.JdbcTemplate; import com.cloudwebsoft.framework.util.LogUtil; import com.redmoon.oa.Config; import com.redmoon.oa.flow.Leaf; import com.redmoon.oa.flow.MyActionDb; import com.redmoon.oa.flow.WorkflowActionDb; import com.redmoon.oa.flow.WorkflowDb; import com.redmoon.oa.message.*; import com.redmoon.oa.sms.SMSFactory; import com.redmoon.oa.sys.DebugUtil; import com.redmoon.oa.visual.Attachment; import com.redmoon.oa.visual.FormDAO; import lombok.extern.slf4j.Slf4j; import org.quartz.*; import cn.js.fan.db.SQLFilter; import org.springframework.scheduling.quartz.QuartzJobBean; /** * <p>Title: 流程超时提醒高度</p> * * <p>Description: </p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: </p> * * @author not attributable * * @version 1.0 */ //持久化 @PersistJobDataAfterExecution //禁止并发执行(Quartz不要并发地执行同一个job定义(这里指一个job类的多个实例)) @DisallowConcurrentExecution @Slf4j public class WorkflowExpireRemindJob extends QuartzJobBean { public WorkflowExpireRemindJob() { } /** * execute * * @param jobExecutionContext JobExecutionContext * @throws JobExecutionException */ @Override public void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { // 根据快要到期的myaction,发送提醒 MyActionDb mad = new MyActionDb(); Config cfg = new Config(); IMessage imsg = null; ProxyFactory proxyFactory = new ProxyFactory("com.redmoon.oa.message.MessageDb"); Advisor adv = new Advisor(); MobileAfterAdvice mba = new MobileAfterAdvice(); adv.setAdvice(mba); adv.setPointcut(new MethodNamePointcut("sendSysMsg", false)); proxyFactory.addAdvisor(adv); imsg = (IMessage) proxyFactory.getProxy(); // 是否发送短信 boolean isToMobile = SMSFactory.isUseSMS(); WorkflowActionDb wad = new WorkflowActionDb(); WorkflowDb wd = new WorkflowDb(); Vector<MyActionDb> v = mad.listWillExpire(); for (MyActionDb myActionDb : v) { mad = myActionDb; // 发送信息 MessageDb md = new MessageDb(); wad = wad.getWorkflowActionDb((int) mad.getActionId()); wd = wd.getWorkflowDb((int) mad.getFlowId()); Leaf leaf = new Leaf(wd.getTypeCode()); String t = ""; String c = ""; // 提示信息 modify by jfy 2015-06-24 if (Leaf.TYPE_FREE == leaf.getType()) { t = StrUtil.format(cfg.get("flowActionExpireRemindTitle"), new Object[]{wd.getTitle()}); c = StrUtil.format(cfg.get("atFlowActionExpireRemindContent"), new Object[]{wd.getTitle(), DateUtil.format(mad.getExpireDate(), "yyyy-MM-dd HH:mm:ss")}); } else { t = StrUtil.format(cfg.get("flowActionExpireRemindTitle"), new Object[]{wd.getTitle()}); c = StrUtil.format(cfg.get("flowActionExpireRemindContent"), new Object[]{wad.getTitle(), DateUtil.format(mad.getExpireDate(), "yyyy-MM-dd HH:mm:ss")}); } try { if (!isToMobile) { md.sendSysMsg(mad.getUserName(), t, c); } else { if (imsg != null) { imsg.sendSysMsg(mad.getUserName(), t, c); } } } catch (ErrMsgException e) { LogUtil.getLog(getClass()).error("execute2:" + e.getMessage()); } } } }
cloudwebsoft/ywoa
c-main/src/main/java/com/redmoon/oa/job/WorkflowExpireRemindJob.java
66,715
/* Copyright 2017 yangchong211(github.com/yangchong211) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.yc.pagerlib.pager; import java.lang.reflect.Field; import java.util.ArrayList; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; import androidx.core.os.ParcelableCompat; import androidx.core.os.ParcelableCompatCreatorCallbacks; import androidx.core.view.MotionEventCompat; import androidx.core.view.VelocityTrackerCompat; import androidx.core.view.ViewConfigurationCompat; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.Interpolator; import android.widget.Scroller; /** * <pre> * @author 杨充 * blog : https://github.com/yangchong211 * time : 2019/6/20 * desc : 参考JakeWharton大神的代码 * revise: * </pre> */ public class DirectionalViewPager extends ViewPager implements ViewPager.OnPageChangeListener{ private static final String TAG = "DirectionalViewPager"; private static final boolean DEBUG = true; private static final boolean USE_CACHE = false; public static final int HORIZONTAL = 0; public static final int VERTICAL = 1; static class ItemInfo { Object object; int position; boolean scrolling; } private final ArrayList<ItemInfo> mItems = new ArrayList<>(); private PagerAdapter mAdapter; private int mCurItem; private int mRestoredCurItem = -1; private Parcelable mRestoredAdapterState = null; private ClassLoader mRestoredClassLoader = null; private Scroller mScroller; private PagerObserver mObserver; private int mChildWidthMeasureSpec; private int mChildHeightMeasureSpec; private boolean mInLayout; private boolean mScrollingCacheEnabled; private boolean mPopulatePending; private boolean mScrolling; private boolean mIsBeingDragged; private boolean mIsUnableToDrag; private int mTouchSlop; private float mInitialMotion; /** * Position of the last motion event. */ private float mLastMotionX; private float mLastMotionY; private int mOrientation = HORIZONTAL; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ private int mActivePointerId = INVALID_POINTER; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; /** * Determines speed during touch scrolling */ private VelocityTracker mVelocityTracker; private int mMinimumVelocity; private int mMaximumVelocity; private OnPageChangeListener mOnPageChangeListener; private int mScrollState = SCROLL_STATE_IDLE; private long mRecentTouchTime; public DirectionalViewPager(Context context) { super(context); initViewPager(); } public DirectionalViewPager(Context context, AttributeSet attrs) { super(context, attrs); initViewPager(); } void initViewPager() { setWillNotDraw(false); mScroller = new Scroller(getContext()); final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); } /** * 设置viewPager滑动动画持续时间 * API>19 */ @TargetApi(Build.VERSION_CODES.KITKAT) public void setAnimationDuration(final int during){ try { // viewPager平移动画事件 Field mField = ViewPager.class.getDeclaredField("mScroller"); mField.setAccessible(true); // 动画效果与ViewPager的一致 Interpolator interpolator = new Interpolator() { @Override public float getInterpolation(float t) { t -= 1.0f; return t * t * t * t * t + 1.0f; } }; FixedSpeedScroller scroller = new FixedSpeedScroller(getContext(), interpolator, mRecentTouchTime); scroller.setDuration(during); mField.set(this, scroller); } catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) { e.printStackTrace(); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mAdapter != null) { populate(); } } /** * 在viewpager滑动过程中执行,并且会被调用很多次。 * 需要注意的是,position的值使用等于屏幕最左侧暴露出来的view的position,即使该view已经快看不见了。 * 第二个参数positionOffset:从左向右滑动时该值从1---0 变化,从右向左滑动时该值从0---1变化。 * 第三个参数positionOffsetPixels:这个参数是viewpager滑动偏移量的具体值 * 比如屏幕宽度值是1080px而viewpager的宽度等于屏幕宽度,则这个值就会在0-1080之间变化。 * @param i 索引 * @param v 判断滑动方向 * @param i1 滑动偏移量 */ @Override public void onPageScrolled(int i, float v, int i1) { super.onPageScrolled(i, v, i1); } /** * 这个方法会在viewpager快要成功切换的时候调用。怎么理解这句话呢 * 当我们滑动距离很小的时候,viewpager会自动回弹到当前页,也就是不进行页面切换, * 此时该方法不会被调用,因为页面并没有被成功切换;当我们滑动距离很大的时候, * viewpager会自动帮我们滑动到下一页,此时手指抬起,viewpager判断即将成功切换到下一页, * 那么该方法就会被调用,并且position的值等于即将切换过去的页面的下标。 * @param i 索引 */ @Override public void onPageSelected(int i) { } /** * 主要用来监测viewpager的滑动状态: * 当我们手指按下时 state=1, * 当我们手指抬起时 state=2, * 当viewpager处于空闲状态时 state=0; * 所以我们完全可以在state=0时 去加载或者处理我们的事情,因为这时候滑动已经结束。 * @param i 状态 */ @Override public void onPageScrollStateChanged(int i) { } private void setScrollState(int newState) { if (mScrollState == newState) { return; } mScrollState = newState; if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrollStateChanged(newState); } } @Override public void setAdapter(PagerAdapter adapter) { mAdapter = adapter; if (mAdapter != null) { if (mObserver == null) { mObserver = new PagerObserver(); } mAdapter.registerDataSetObserver(mObserver); mPopulatePending = false; if (mRestoredCurItem >= 0) { mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader); setCurrentItemInternal(mRestoredCurItem, false, true); mRestoredCurItem = -1; mRestoredAdapterState = null; mRestoredClassLoader = null; } else { populate(); } } } @Override public PagerAdapter getAdapter() { return mAdapter; } /** * 这个方法是设置滚动的 * @param item 索引 */ @Override public void setCurrentItem(int item) { mPopulatePending = false; setCurrentItemInternal(item, true, false); } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { if (mAdapter == null || mAdapter.getCount() <= 0) { setScrollingCacheEnabled(false); return; } if (!always && mCurItem == item && mItems.size() != 0) { setScrollingCacheEnabled(false); return; } if (item < 0) { item = 0; } else if (item >= mAdapter.getCount()) { item = mAdapter.getCount() - 1; } if (item > (mCurItem+1) || item < (mCurItem-1)) { // We are doing a jump by more than one page. To avoid // glitches, we want to keep all current pages in the view // until the scroll ends. for (int i=0; i<mItems.size(); i++) { mItems.get(i).scrolling = true; } } final boolean dispatchSelected = mCurItem != item; mCurItem = item; populate(); if (smoothScroll) { if (mOrientation == HORIZONTAL) { smoothScrollTo(getWidth()*item, 0); } else { smoothScrollTo(0, getHeight()*item); } if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item); } } else { if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item); } completeScroll(); if (mOrientation == HORIZONTAL) { scrollTo(getWidth()*item, 0); } else { scrollTo(0, getHeight()*item); } } } public void setOnPageChangeListener(OnPageChangeListener listener) { mOnPageChangeListener = listener; } /** * 这个方法是控制滚动效果的 * @param x x * @param y y */ void smoothScrollTo(int x, int y) { if (getChildCount() == 0) { // Nothing to do. setScrollingCacheEnabled(false); return; } int sx = getScrollX(); int sy = getScrollY(); int dx = x - sx; int dy = y - sy; if (dx == 0 && dy == 0) { completeScroll(); return; } setScrollingCacheEnabled(true); mScrolling = true; setScrollState(SCROLL_STATE_SETTLING); mScroller.startScroll(sx, sy, dx, dy); invalidate(); } void addNewItem(int position, int index) { ItemInfo ii = new ItemInfo(); ii.position = position; ii.object = mAdapter.instantiateItem(this, position); if (index < 0) { mItems.add(ii); } else { mItems.add(index, ii); } } void dataSetChanged() { boolean needPopulate = mItems.isEmpty() && mAdapter.getCount() > 0; int newCurrItem = -1; for (int i = 0; i < mItems.size(); i++) { final ItemInfo ii = mItems.get(i); final int newPos = mAdapter.getItemPosition(ii.object); if (newPos == PagerAdapter.POSITION_UNCHANGED) { continue; } if (newPos == PagerAdapter.POSITION_NONE) { mItems.remove(i); i--; mAdapter.destroyItem(this, ii.position, ii.object); needPopulate = true; if (mCurItem == ii.position) { // Keep the current item in the valid range newCurrItem = Math.max(0, Math.min(mCurItem, mAdapter.getCount() - 1)); } continue; } if (ii.position != newPos) { if (ii.position == mCurItem) { // Our current item changed position. Follow it. newCurrItem = newPos; } ii.position = newPos; needPopulate = true; } } if (newCurrItem >= 0) { setCurrentItemInternal(newCurrItem, false, true); needPopulate = true; } if (needPopulate) { populate(); requestLayout(); } } void populate() { if (mAdapter == null) { return; } // Bail now if we are waiting to populate. This is to hold off // on creating views from the time the user releases their finger to // fling to a new position until we have finished the scroll to // that position, avoiding glitches from happening at that point. if (mPopulatePending) { if (DEBUG) { Log.i(TAG, "populate is pending, skipping for now..."); } return; } // Also, don't populate until we are attached to a window. This is to // avoid trying to populate before we have restored our view hierarchy // state and conflicting with what is restored. if (getWindowToken() == null) { return; } mAdapter.startUpdate(this); final int startPos = mCurItem > 0 ? mCurItem - 1 : mCurItem; final int count = mAdapter.getCount(); final int endPos = mCurItem < (count-1) ? mCurItem+1 : count-1; if (DEBUG) { Log.v(TAG, "populating: startPos=" + startPos + " endPos=" + endPos); } // Add and remove pages in the existing list. int lastPos = -1; for (int i=0; i<mItems.size(); i++) { ItemInfo ii = mItems.get(i); if ((ii.position < startPos || ii.position > endPos) && !ii.scrolling) { if (DEBUG) { Log.i(TAG, "removing: " + ii.position + " @ " + i); } mItems.remove(i); i--; mAdapter.destroyItem(this, ii.position, ii.object); } else if (lastPos < endPos && ii.position > startPos) { // The next item is outside of our range, but we have a gap // between it and the last item where we want to have a page // shown. Fill in the gap. lastPos++; if (lastPos < startPos) { lastPos = startPos; } while (lastPos <= endPos && lastPos < ii.position) { if (DEBUG) { Log.i(TAG, "inserting: " + lastPos + " @ " + i); } addNewItem(lastPos, i); lastPos++; i++; } } lastPos = ii.position; } // Add any new pages we need at the end. lastPos = mItems.size() > 0 ? mItems.get(mItems.size()-1).position : -1; if (lastPos < endPos) { lastPos++; lastPos = lastPos > startPos ? lastPos : startPos; while (lastPos <= endPos) { if (DEBUG) { Log.i(TAG, "appending: " + lastPos); } addNewItem(lastPos, -1); lastPos++; } } if (DEBUG) { Log.i(TAG, "Current page list:"); for (int i=0; i<mItems.size(); i++) { Log.i(TAG, "#" + i + ": page " + mItems.get(i).position); } } mAdapter.finishUpdate(this); } public static class SavedState extends BaseSavedState { int position; Parcelable adapterState; ClassLoader loader; public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(position); out.writeParcelable(adapterState, flags); } @NonNull @Override public String toString() { return "FragmentPager.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " position=" + position + "}"; } public static final Parcelable.Creator<SavedState> CREATOR = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks<SavedState>() { @Override public SavedState createFromParcel(Parcel in, ClassLoader loader) { return new SavedState(in, loader); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }); SavedState(Parcel in, ClassLoader loader) { super(in); if (loader == null) { loader = getClass().getClassLoader(); } position = in.readInt(); adapterState = in.readParcelable(loader); this.loader = loader; } } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.position = mCurItem; ss.adapterState = mAdapter.saveState(); return ss; } @Override public void onRestoreInstanceState(Parcelable state) { if (!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState)state; super.onRestoreInstanceState(ss.getSuperState()); if (mAdapter != null) { mAdapter.restoreState(ss.adapterState, ss.loader); setCurrentItemInternal(ss.position, false, true); } else { mRestoredCurItem = ss.position; mRestoredAdapterState = ss.adapterState; mRestoredClassLoader = ss.loader; } } public void setOrientation(int orientation) { switch (orientation) { case HORIZONTAL: case VERTICAL: break; default: throw new IllegalArgumentException("Only HORIZONTAL and VERTICAL are valid orientations."); } if (orientation == mOrientation) { return; } //Complete any scroll we are currently in the middle of completeScroll(); //Reset values mInitialMotion = 0; mLastMotionX = 0; mLastMotionY = 0; if (mVelocityTracker != null) { mVelocityTracker.clear(); } //Adjust scroll for new orientation mOrientation = orientation; if (mOrientation == HORIZONTAL) { scrollTo(mCurItem * getWidth(), 0); } else { scrollTo(0, mCurItem * getHeight()); } requestLayout(); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (mInLayout) { addViewInLayout(child, index, params); child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec); } else { super.addView(child, index, params); } if (USE_CACHE) { if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(mScrollingCacheEnabled); } else { child.setDrawingCacheEnabled(false); } } } ItemInfo infoForChild(View child) { for (int i=0; i<mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (mAdapter.isViewFromObject(child, ii.object)) { return ii; } } return null; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // For simple implementation, or internal size is always 0. // We depend on the container to specify the layout size of // our view. We can't really know what it is since we will be // adding and removing different arbitrary views and do not // want the layout to change as this happens. setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); // Children are just made to fill our space. mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY); mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY); // Make sure we have created all fragments that we need to have shown. mInLayout = true; populate(); mInLayout = false; // Make sure all children have been properly measured. final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { if (DEBUG) { Log.v(TAG, "Measuring #" + i + " " + child + ": " + mChildWidthMeasureSpec + " x " + mChildHeightMeasureSpec); } child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec); } } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Make sure scroll position is set correctly. if (mOrientation == HORIZONTAL) { int scrollPos = mCurItem*w; if (scrollPos != getScrollX()) { completeScroll(); scrollTo(scrollPos, getScrollY()); } } else { int scrollPos = mCurItem*h; if (scrollPos != getScrollY()) { completeScroll(); scrollTo(getScrollX(), scrollPos); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mInLayout = true; populate(); mInLayout = false; final int count = getChildCount(); final int size = (mOrientation == HORIZONTAL) ? r-l : b-t; for (int i = 0; i < count; i++) { View child = getChildAt(i); ItemInfo ii; if (child.getVisibility() != GONE && (ii=infoForChild(child)) != null) { int off = size*ii.position; int childLeft = getPaddingLeft(); int childTop = getPaddingTop(); if (mOrientation == HORIZONTAL) { childLeft += off; } else { childTop += off; } if (DEBUG) { Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth() + "x" + child.getMeasuredHeight()); } child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } @Override public void computeScroll() { if (DEBUG) { Log.i(TAG, "computeScroll: finished=" + mScroller.isFinished()); } if (!mScroller.isFinished()) { if (mScroller.computeScrollOffset()) { if (DEBUG) { Log.i(TAG, "computeScroll: still scrolling"); } int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); } if (mOnPageChangeListener != null) { int size; int value; if (mOrientation == HORIZONTAL) { size = getWidth(); value = x; } else { size = getHeight(); value = y; } final int position = value / size; final int offsetPixels = value % size; final float offset = (float) offsetPixels / size; mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); } // Keep on drawing until the animation has finished. invalidate(); return; } } // Done with scroll, clean up state. completeScroll(); } private void completeScroll() { boolean needPopulate; if ((needPopulate=mScrolling)) { // Done with scroll, no longer want to cache view drawing. setScrollingCacheEnabled(false); mScroller.abortAnimation(); int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); } setScrollState(SCROLL_STATE_IDLE); } mPopulatePending = false; mScrolling = false; for (int i=0; i<mItems.size(); i++) { ItemInfo ii = mItems.get(i); if (ii.scrolling) { needPopulate = true; ii.scrolling = false; } } if (needPopulate) { populate(); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { mRecentTouchTime = System.currentTimeMillis(); final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; // Always take care of the touch gesture being complete. if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { // Release the drag. if (DEBUG) { Log.v(TAG, "Intercept done!"); } mIsBeingDragged = false; mIsUnableToDrag = false; mActivePointerId = INVALID_POINTER; return false; } // Nothing more to do here if we have decided whether or not we // are dragging. if (action != MotionEvent.ACTION_DOWN) { if (mIsBeingDragged) { if (DEBUG) { Log.v(TAG, "Intercept returning true!"); } return true; } if (mIsUnableToDrag) { if (DEBUG) { Log.v(TAG, "Intercept returning false!"); } return false; } } switch (action) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value * of the down event. */ final int activePointerId = mActivePointerId; if (activePointerId == INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on content. break; } final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float y = MotionEventCompat.getY(ev, pointerIndex); final float xDiff = Math.abs(x - mLastMotionX); final float yDiff = Math.abs(y - mLastMotionY); float primaryDiff; float secondaryDiff; if (mOrientation == HORIZONTAL) { primaryDiff = xDiff; secondaryDiff = yDiff; } else { primaryDiff = yDiff; secondaryDiff = xDiff; } if (DEBUG) { Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); } if (primaryDiff > mTouchSlop && primaryDiff > secondaryDiff) { if (DEBUG) { Log.v(TAG, "Starting drag!"); } mIsBeingDragged = true; setScrollState(SCROLL_STATE_DRAGGING); if (mOrientation == HORIZONTAL) { mLastMotionX = x; } else { mLastMotionY = y; } setScrollingCacheEnabled(true); } else { if (secondaryDiff > mTouchSlop) { // The finger has moved enough in the vertical // direction to be counted as a drag... abort // any attempt to drag horizontally, to work correctly // with children that have scrolling containers. if (DEBUG) { Log.v(TAG, "Starting unable to drag!"); } mIsUnableToDrag = true; } } break; } case MotionEvent.ACTION_DOWN: { /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ if (mOrientation == HORIZONTAL) { mLastMotionX = mInitialMotion = ev.getX(); mLastMotionY = ev.getY(); } else { mLastMotionX = ev.getX(); mLastMotionY = mInitialMotion = ev.getY(); } mActivePointerId = MotionEventCompat.getPointerId(ev, 0); if (mScrollState == SCROLL_STATE_SETTLING) { // Let the user 'catch' the pager as it animates. mIsBeingDragged = true; mIsUnableToDrag = false; setScrollState(SCROLL_STATE_DRAGGING); } else { completeScroll(); mIsBeingDragged = false; mIsUnableToDrag = false; } if (DEBUG) { Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY + " mIsBeingDragged=" + mIsBeingDragged + "mIsUnableToDrag=" + mIsUnableToDrag); } break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; default: break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return mIsBeingDragged; } @Override public boolean onTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { // Don't handle edge touches immediately -- they may actually belong to one of our // descendants. return false; } if (mAdapter == null || mAdapter.getCount() == 0) { // Nothing to present or scroll; nothing to touch. return false; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ completeScroll(); // Remember where the motion event started if (mOrientation == HORIZONTAL) { mLastMotionX = mInitialMotion = ev.getX(); } else { mLastMotionY = mInitialMotion = ev.getY(); } mActivePointerId = MotionEventCompat.getPointerId(ev, 0); break; } case MotionEvent.ACTION_MOVE: if (!mIsBeingDragged) { final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, pointerIndex); final float y = MotionEventCompat.getY(ev, pointerIndex); final float xDiff = Math.abs(x - mLastMotionX); final float yDiff = Math.abs(y - mLastMotionY); float primaryDiff; float secondaryDiff; if (mOrientation == HORIZONTAL) { primaryDiff = xDiff; secondaryDiff = yDiff; } else { primaryDiff = yDiff; secondaryDiff = xDiff; } if (DEBUG) { Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); } if (primaryDiff > mTouchSlop && primaryDiff > secondaryDiff) { if (DEBUG) { Log.v(TAG, "Starting drag!"); } mIsBeingDragged = true; if (mOrientation == HORIZONTAL) { mLastMotionX = x; } else { mLastMotionY = y; } setScrollState(SCROLL_STATE_DRAGGING); setScrollingCacheEnabled(true); } } if (mIsBeingDragged) { // Scroll to follow the motion event final int activePointerIndex = MotionEventCompat.findPointerIndex( ev, mActivePointerId); final float x = MotionEventCompat.getX(ev, activePointerIndex); final float y = MotionEventCompat.getY(ev, activePointerIndex); int size; float scroll; if (mOrientation == HORIZONTAL) { size = getWidth(); scroll = getScrollX() + (mLastMotionX - x); mLastMotionX = x; } else { size = getHeight(); scroll = getScrollY() + (mLastMotionY - y); mLastMotionY = y; } final float lowerBound = Math.max(0, (mCurItem - 1) * size); final float upperBound = Math.min(mCurItem + 1, mAdapter.getCount() - 1) * size; if (scroll < lowerBound) { scroll = lowerBound; } else if (scroll > upperBound) { scroll = upperBound; } if (mOrientation == HORIZONTAL) { // Don't lose the rounded component mLastMotionX += scroll - (int) scroll; scrollTo((int) scroll, getScrollY()); } else { // Don't lose the rounded component mLastMotionY += scroll - (int) scroll; scrollTo(getScrollX(), (int) scroll); } if (mOnPageChangeListener != null) { final int position = (int) scroll / size; final int positionOffsetPixels = (int) scroll % size; final float positionOffset = (float) positionOffsetPixels / size; mOnPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } } break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity; float lastMotion; int sizeOverThree; if (mOrientation == HORIZONTAL) { initialVelocity = (int)VelocityTrackerCompat.getXVelocity( velocityTracker, mActivePointerId); lastMotion = mLastMotionX; sizeOverThree = getWidth() / 3; } else { initialVelocity = (int)VelocityTrackerCompat.getYVelocity( velocityTracker, mActivePointerId); lastMotion = mLastMotionY; sizeOverThree = getHeight() / 3; } mPopulatePending = true; if ((Math.abs(initialVelocity) > mMinimumVelocity) || Math.abs(mInitialMotion-lastMotion) >= sizeOverThree) { if (lastMotion > mInitialMotion) { setCurrentItemInternal(mCurItem-1, true, true); } else { setCurrentItemInternal(mCurItem+1, true, true); } } else { setCurrentItemInternal(mCurItem, true, true); } mActivePointerId = INVALID_POINTER; endDrag(); } break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged) { setCurrentItemInternal(mCurItem, true, true); mActivePointerId = INVALID_POINTER; endDrag(); } break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); if (mOrientation == HORIZONTAL) { mLastMotionX = MotionEventCompat.getX(ev, index); } else { mLastMotionY = MotionEventCompat.getY(ev, index); } mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId); if (mOrientation == HORIZONTAL) { mLastMotionX = MotionEventCompat.getX(ev, index); } else { mLastMotionY = MotionEventCompat.getY(ev, index); } break; default: break; } return true; } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; if (mOrientation == HORIZONTAL) { mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); } else { mLastMotionY = MotionEventCompat.getY(ev, newPointerIndex); } mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } private void endDrag() { mIsBeingDragged = false; mIsUnableToDrag = false; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private void setScrollingCacheEnabled(boolean enabled) { if (mScrollingCacheEnabled != enabled) { mScrollingCacheEnabled = enabled; if (USE_CACHE) { final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(enabled); } } } } } /** * 用来实现adapter的notifyDataSetChanged通知变化 */ private class PagerObserver extends android.database.DataSetObserver { @Override public void onChanged() { dataSetChanged(); } @Override public void onInvalidated() { dataSetChanged(); } } }
yangchong211/YCScrollPager
PagerLib/src/main/java/com/yc/pagerlib/pager/DirectionalViewPager.java
66,716
package com.taobao.api.internal.stream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import org.apache.log4j.Logger; import com.taobao.api.internal.stream.connect.ConnectionLifeCycleListener; import com.taobao.api.internal.stream.connect.HttpClient; import com.taobao.api.internal.stream.connect.HttpResponse; import com.taobao.api.internal.stream.message.StreamMessageConsume; import com.taobao.api.internal.stream.message.StreamMsgConsumeFactory; import com.taobao.api.internal.stream.message.TopCometMessageListener; import com.taobao.api.internal.util.RequestParametersHolder; import com.taobao.api.internal.util.StringUtils; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.internal.util.TaobaoUtils; /** * * @author zhenzi 2011-8-9 上午09:59:31 */ public class TopCometStreamImpl implements TopCometStream { private static final Logger logger = Logger .getLogger(TopCometStreamImpl.class); private ConnectionLifeCycleListener connectionListener; private TopCometMessageListener cometMessageListener; private Configuration conf; private StreamMsgConsumeFactory msgConsumeFactory = null; /** * 停掉全部连接 */ private boolean gloableStop = false; private List<ControlThread> controlThreads = new ArrayList<ControlThread>(); protected TopCometStreamImpl(Configuration conf) { this.conf = conf; } public void setConnectionListener( ConnectionLifeCycleListener connectionLifeCycleListener) { this.connectionListener = connectionLifeCycleListener; } public void setMessageListener(TopCometMessageListener cometMessageListener) { this.cometMessageListener = cometMessageListener; } public void start() { Set<TopCometStreamRequest> cometRequests = conf.getConnectReqParam(); for (TopCometStreamRequest cometRequest : cometRequests) { if (cometRequest.getConnectListener() == null) { cometRequest.setConnectListener(connectionListener); } if (cometRequest.getMsgListener() == null) { if (cometMessageListener == null) {//如果又没有自己的message listener又没设置全局的message listener 则系统不能启动,抛错。 throw new RuntimeException("Comet message listener must not null"); } cometRequest.setMsgListener(cometMessageListener); } } msgConsumeFactory = new StreamMsgConsumeFactory(conf.getMinThreads(), conf.getMaxThreads(), conf.getQueueSize(), conf.getMsgConsumeThreadPoolRejectHandler()); for (TopCometStreamRequest cometRequest : cometRequests) { // 这里不把线程设置成daemon线程的原因,如果设置成daemon线程后,如果主线程退出后这些线程都将自动退出 ControlThread ct = new ControlThread(cometRequest); controlThreads.add(ct); Thread t = new Thread(ct, "stream-control-thread-connectid-" + cometRequest.getConnectId()); t.setDaemon(false); t.start(); } } /** * 连接管理线程 * * @author zhenzi * * 2012-8-12 下午3:06:48 */ public class ControlThread implements Runnable { private static final String threadName = "top-stream-consume-thread"; private TopCometStreamConsume currentStreamConsume; private boolean isReconnect = false;// 是否客户端发起重连 private String serverRespCode = StreamConstants.CLIENT_FIRST_CONNECT; private ReentrantLock lock = new ReentrantLock(); private Condition controlCondition = lock.newCondition(); // 发生了多少次readtimeout private int readTimeoutOccureTimes = 0; private long lastStartConsumeThread = System.currentTimeMillis(); /** * 停掉 */ private boolean stop = false; private TopCometStreamRequest cometReq; public ControlThread(TopCometStreamRequest cometReq) { this.cometReq = cometReq; } public ReentrantLock getLock() { return lock; } public Condition getControlCondition() { return controlCondition; } public void setServerRespCode(String serverRespCode) { this.serverRespCode = serverRespCode; } public void run() { long lastSleepTime = 0; while (!stop) { if (gloableStop) { break; } try { if (StreamConstants.SERVER_DEPLOY.equals(serverRespCode)) {// 服务端在发布 if (logger.isDebugEnabled()) { logger.debug("Server is upgrade sleep " + conf.getSleepTimeOfServerInUpgrade() + " seconds"); } try { Thread.sleep(conf.getSleepTimeOfServerInUpgrade() * 1000); } catch (InterruptedException e) { // ignore; } startConsumeThread(); } else if (/* 客户端第一次发起连接请求 */ StreamConstants.CLIENT_FIRST_CONNECT.equals(serverRespCode) || /* 服务端主动断开了所有的连接 */ StreamConstants.SERVER_REHASH .equals(serverRespCode) || /* 连接到达最大时间 */ StreamConstants.CONNECT_REACH_MAX_TIME .equals(serverRespCode) || /* 在一些异常情况下需要重连 */ StreamConstants.RECONNECT.equals(serverRespCode)) { startConsumeThread(); } else if (/* 客户端自己把自己踢开 */ StreamConstants.CLIENT_KICKOFF.equals(serverRespCode) || /* 服务端把客户端踢开 */ StreamConstants.SERVER_KICKOFF.equals(serverRespCode)) { if ((StreamConstants.CLIENT_KICKOFF .equals(serverRespCode) && !isReconnect) || StreamConstants.SERVER_KICKOFF .equals(serverRespCode)) { stop = true; if (currentStreamConsume != null) { currentStreamConsume.closed = true; } break;// 终止掉当前线程 } } else {// 错误码设置出错,停止线程 stop = true; break; } // 连接成功,开始休眠 if (!stop && !gloableStop) { try { lock.lock(); lastSleepTime = System.currentTimeMillis(); controlCondition.await( conf.getHttpReconnectInterval(), TimeUnit.SECONDS); if (System.currentTimeMillis() - lastSleepTime >= (conf .getHttpReconnectInterval() - 5 * 60) * 1000) { /* * 快要到达连接的最大时间了,需要重新发起连接 */ serverRespCode = StreamConstants.RECONNECT; isReconnect = true; }// 否则,是由于某种原因被唤醒的 } catch (Exception e) { logger.error(e, e); } finally { lock.unlock(); } } } catch (Throwable e) { logger.error("Occur some error,stop the stream consume", e); stop = true; try { lock.lock(); controlCondition.signalAll(); } catch (Exception ex) { // ignore } finally { lock.unlock(); } } } //关闭资源 if(currentStreamConsume != null){ currentStreamConsume.close(); } // 此控制线程由于某种原因退出,从列表中移除掉 controlThreads.remove(this); } private void startConsumeThread() { StreamMessageConsume stream = null; try { stream = getMsgConsume(); } catch (Exception ex) { stop = true; gloableStop = true; if (cometReq.getConnectListener() != null) { cometReq.getConnectListener().onException(ex); } return; } currentStreamConsume = new TopCometStreamConsume(stream, this, cometReq.getConnectListener()); Thread consumeThread = new Thread(currentStreamConsume, threadName); consumeThread.setDaemon(true); consumeThread.start(); lastStartConsumeThread = System.currentTimeMillis(); /** * 重新连接以后,修改isReconnect=false * 这里去掉,因为当消息量很大的时候会出现: * 客户端重连先连接成功了,但是服务端在之前的连接上发送的client kickoff消息还没有处理完, * 导致在收到这个消息的时候,在控制线程里面处理的时候因为isReconnect = false了, * 导致控制线程认为是客户端踢出。 * * 这里去掉的问题就是:如果isv需要在别的地方部署同一个appkey+userid+connect_id的长连接 * 的时候需要把之前的那个关闭掉,否则会出现永远互相踢的过程。 */ //isReconnect = false; } private StreamMessageConsume getMsgConsume() throws TopCometSysErrorException, Exception { if (cometReq.getConnectListener() != null) { cometReq.getConnectListener().onBeforeConnect(); } TaobaoHashMap param = new TaobaoHashMap(); param.put(StreamConstants.PARAM_APPKEY, cometReq.getAppkey()); if (!StringUtils.isEmpty(cometReq.getUserId())) { param.put(StreamConstants.PARAM_USERID, cometReq.getUserId()); } if (!StringUtils.isEmpty(cometReq.getConnectId())) { param.put(StreamConstants.PARAM_CONNECT_ID, cometReq.getConnectId()); } if (!StringUtils.isEmpty(cometReq.getGroupId())) { param.put(StreamConstants.PARAM_GROUP_ID, cometReq.getGroupId()); } if(cometReq.getIsReliable()!=null){ param.put(StreamConstants.PARAM_IS_RELIABLE, cometReq.getIsReliable()); } String timestamp = String.valueOf(System.currentTimeMillis()); param.put(StreamConstants.PARAM_TIMESTAMP, timestamp); Map<String, String> otherParam = cometReq.getOtherParam(); if (otherParam != null) { Iterator<Entry<String, String>> it = otherParam.entrySet() .iterator(); while (it.hasNext()) { Entry<String, String> e = it.next(); param.put(e.getKey(), e.getValue()); } } RequestParametersHolder paramHolder = new RequestParametersHolder(); paramHolder.setProtocalMustParams(param); String sign = null; try { sign = TaobaoUtils.signTopRequestNew(paramHolder, cometReq.getSecret(), false); if (StringUtils.isEmpty(sign)) { throw new RuntimeException("Get sign error"); } } catch (IOException e) { throw new RuntimeException(e); } param.put(StreamConstants.PARAM_SIGN, sign); HttpClient httpClient = new HttpClient(conf, param); HttpResponse response = httpClient.post(); response.setCometRequest(cometReq); StreamMessageConsume consume= new StreamMessageConsume(msgConsumeFactory, response, cometReq.getMsgListener(), this); consume.setConfiguration(conf); return consume; } } /** * 从长连接的通道中读取消息 * * @author zhenzi * * 2012-8-12 下午3:08:47 */ class TopCometStreamConsume implements Runnable { private StreamMessageConsume stream; private boolean closed = false; private ControlThread ct; private ConnectionLifeCycleListener connectListener; TopCometStreamConsume(StreamMessageConsume stream, ControlThread ct, ConnectionLifeCycleListener connectListener) { this.stream = stream; this.ct = ct; this.connectListener = connectListener; } public void run() { while (!gloableStop && !closed && stream.isAlive()) { try { stream.nextMsg(); } catch (IOException e) {// 出现了read time out异常 // 资源清理 if (stream != null) { try { stream.close(); } catch (IOException e1) { //ignore; } } stream = null; closed = true; /** * 30分钟内发送了10次read time out exception 告知isv,但是不退出,继续发起重新连接 */ ct.readTimeoutOccureTimes++; if (System.currentTimeMillis() - ct.lastStartConsumeThread < 30 * 60 * 1000) { // 如果30分钟内,read time out发生了10次,则告知isv if (ct.readTimeoutOccureTimes >= 10) { if (connectListener != null) { try { connectListener.onMaxReadTimeoutException(); } catch (Exception ex) {} } //告知完后清0 ct.readTimeoutOccureTimes = 0; } } else {// 如果超过30分钟,则清0 ct.readTimeoutOccureTimes = 0; } // 通知重连 ct.serverRespCode = StreamConstants.RECONNECT; try { ct.lock.lock(); ct.controlCondition.signalAll(); } catch (Exception e2) { } finally { ct.lock.unlock(); } } } // 出现异常情况下做资源清理 close(); } /** * 在外面调用stop需要关闭整个长连接的时候,ControlThread会调用此方法,把一些资源正确的释放掉 */ public void close(){ if (this.stream != null) { try { this.stream.close(); } catch (Exception e) { // logger.warn(e.getMessage(), e); //ignore; } } } } /** * 在运行期添加新的长连接 * @param newClient */ public void addNewStreamClient(TopCometStreamRequest newClient){ if(newClient.getConnectListener() == null){ newClient.setConnectListener(connectionListener); } if (newClient.getMsgListener() == null) { newClient.setMsgListener(cometMessageListener); } ControlThread ct = new ControlThread(newClient); controlThreads.add(ct); Thread t = new Thread(ct, "stream-control-thread-connectid-" + newClient.getConnectId()); t.setDaemon(false); t.start(); } /** * 关闭长连接。 * 这里没有休眠一段时间,让服务端清理资源, * 这样的话客户端只要保证每次发起连接请求的connectid是一样的就不会出现问题。 * 其实在客户端使用的过程中,客户端使用固定的connectid,在多连接情况下更应该 * 使用固定的connectid,并且不能超过服务端的最大连接数限制. */ public void stop() { logger.warn("start stop stream consume..."); // 设置所有的线程都关闭掉 gloableStop = true; // 关闭控制线程 //这里先复制一份controlThreads,因为在关闭的时候,control thread会从list中移除掉自己。 Object[] copyControlThreads = controlThreads.toArray(); for (Object o : copyControlThreads) { if(o instanceof ControlThread){ ControlThread ct = (ControlThread)o; try { ct.lock.lock(); ct.controlCondition.signalAll(); } catch (Exception e) { logger.error(e, e); } finally { ct.lock.unlock(); } } } // 关闭处理数据的线程池 msgConsumeFactory.shutdown(); logger.warn("stream consume stoped..."); } }
lianying/asdf
src/main/java/com/taobao/api/internal/stream/TopCometStreamImpl.java
66,717
package com.kot32.ksimplelibrary.widgets.view; import android.content.Context; import android.os.AsyncTask; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AbsListView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.Scroller; import android.widget.TextView; import com.kot32.ksimplelibrary.util.tools.DisplayUtil; import com.kot32.ksimplelibrary.util.tools.reflect.FieldUtil; import java.util.concurrent.atomic.AtomicBoolean; /** * Created by kot32 on 15/10/18. * 实现下拉刷新的 View * KRefreshView{SubView:HeaderView、ListView} */ public class KRefreshView extends LinearLayout { private Scroller scroller = new Scroller(getContext()); private TextView default_header_tips; private TextView default_bottom_tips; private boolean shouldRefresh = false; private boolean isRefreshing = false; private boolean shouldLoadMore = false; private boolean isLoadMoreing = false; //是否开启上拉加载更多的开关 private LoadMoreConfig loadMoreConfig; //头部刷新View的父容器 private RelativeLayout headerContent; //尾部『加载更多』 View 的父容器 private RelativeLayout bottomContent; //头部刷新View private View headerView; //尾部『加载更多』 的 View private View bottomView; //下拉刷新-控制UI更新 private RefreshViewHolder refreshViewHolder; //下拉刷新-控制事务更新 private IRefreshAction iRefreshAction; //下拉刷新-控制UI更新 private LoadMoreViewHolder loadMoreViewHolder; //下拉刷新-控制事务更新 private ILoadMoreAction iLoadMoreAction; //触摸事件传递接口 private onRefreshViewTouch onRefreshViewTouch; //默认高度 private int HEADER_HEIGHT = 100; private int BOTTOM_HEIGHT = 100; private int MAX_LIMIT_SLOT = 50; private int totalLimit; private AtomicBoolean isInitListViewListener = new AtomicBoolean(false); private boolean isShouldShowLoadMore = false; public KRefreshView(Context context) { super(context); initView(); initData(); initController(); } public KRefreshView(Context context, AttributeSet attrs) { super(context, attrs); initView(); initData(); initController(); } private void initView() { setOrientation(VERTICAL); //增加头部View容器 LinearLayout.LayoutParams headerContentParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(getContext(), HEADER_HEIGHT)); headerContent = new RelativeLayout(getContext()); headerContentParams.setMargins(0, -DisplayUtil.dip2px(getContext(), HEADER_HEIGHT), 0, 0); headerContent.setLayoutParams(headerContentParams); addView(headerContent, 0); //增加隐藏的View default_header_tips = new TextView(getContext()); default_header_tips.setText("继续下拉以刷新..."); RelativeLayout.LayoutParams defaultHeaderTextParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); defaultHeaderTextParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); default_header_tips.setLayoutParams(defaultHeaderTextParams); headerContent.addView(default_header_tips, 0); // 尾部View容器 bottomContent = new RelativeLayout(getContext()); LayoutParams bottomContentParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT)); bottomContentParams.setMargins(0, 0, 0, -DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT)); bottomContent.setLayoutParams(bottomContentParams); default_bottom_tips = new TextView(getContext()); default_bottom_tips.setText("上拉加载更多.."); RelativeLayout.LayoutParams defaultBottomTextParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); defaultBottomTextParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); default_bottom_tips.setLayoutParams(defaultBottomTextParams); bottomContent.addView(default_bottom_tips, 0); } private void initData() { refreshViewHolder = new RefreshViewHolder() { @Override public void pullingTips(View headerView, int progress) { default_header_tips.setText("继续下拉以刷新..."); } @Override public void willRefreshTips(View headerView) { default_header_tips.setText("松开以刷新"); } @Override public void refreshingTips(View headerView) { default_header_tips.setText("正在刷新..."); } @Override public void refreshCompleteTips(View headerView) { default_header_tips.setText("刷新成功"); } }; loadMoreViewHolder = new LoadMoreViewHolder() { @Override public void loadTips(View headerView, int progress) { default_bottom_tips.setText("继续上拉以加载更多"); } @Override public void willloadTips(View headerView) { default_bottom_tips.setText("松开以加载更多"); } @Override public void loadingTips(View headerView) { default_bottom_tips.setText("正在加载"); } @Override public void loadCompleteTips(View headerView) { default_bottom_tips.setText("加载完成"); } }; totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT); } private void initController() { } public void initLoadMoreFunc() { if (isInitListViewListener.compareAndSet(false, true)) { View view = getChildAt(1); if (view instanceof ListView) { final AbsListView.OnScrollListener oldListener = (AbsListView.OnScrollListener) FieldUtil.getDefedValue("mOnScrollListener", ListView.class, view); ((ListView) view).setOnScrollListener(new AbsListView.OnScrollListener() { private boolean scrollFlag = false;// 标记是否滑动 private int lastVisibleItemPosition = 0;// 标记上次滑动位置 @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (oldListener != null) { oldListener.onScrollStateChanged(view, scrollState); } switch (scrollState) { // 当不滚动时 case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时 scrollFlag = false; break; case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时 scrollFlag = true; break; case AbsListView.OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指,屏幕产生惯性滑动时 scrollFlag = false; break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (oldListener != null) { oldListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } if (view.getLastVisiblePosition() == (view .getCount() - 1)) { if (bottomContent.getParent() == null) { //显示加载更多View KRefreshView.this.addView(bottomContent, 2); } //当滑到最下面时,控制权交给父 View isShouldShowLoadMore = true; } else { isShouldShowLoadMore = false; } } }); } } } private float preY; private float tmpY; private float Y1; private float Y2; enum INTERCEPT_ACTION { REFRESH, LOAD_MORE } private INTERCEPT_ACTION intercept_action; //判断是否拦截事件 @Override public boolean onInterceptTouchEvent(MotionEvent ev) { //如果是方向向上,且ListView switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: Y1 = ev.getRawY(); preY = ev.getRawY(); tmpY = ev.getRawY(); break; case MotionEvent.ACTION_MOVE: Y2 = ev.getRawY(); //没有滑动到一定距离,就不拦截 if (Math.abs(Y2 - Y1) < 3) return false; if (Y2 > Y1) { View view = getChildAt(1); if (view instanceof ListView) { //如果ListView可见的第一个index是0,并且还没滑动 if (((ListView) view).getFirstVisiblePosition() == 0) { View v = ((ListView) view).getChildAt(0); if ((v == null) || (v != null && v.getTop() == 0)) { intercept_action = INTERCEPT_ACTION.REFRESH; return true; } } } else if (view instanceof ScrollView) { if (view.getScrollY() == 0) { intercept_action = INTERCEPT_ACTION.REFRESH; return true; } } else if (view instanceof WebView) { if (view.getScrollY() == 0) { intercept_action = INTERCEPT_ACTION.REFRESH; return true; } } } else { if (loadMoreConfig != null && loadMoreConfig.canLoadMore) { if (isShouldShowLoadMore) { intercept_action = INTERCEPT_ACTION.LOAD_MORE; return true; } } } break; } return false; } @Override public boolean onTouchEvent(MotionEvent ev) { boolean isRefreshTiping = false; boolean isLoadMoreTiping = false; if (onRefreshViewTouch != null) { onRefreshViewTouch.onTouch((int) ev.getRawX(), (int) ev.getRawY()); } switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: preY = ev.getRawY(); tmpY = ev.getRawY(); isRefreshTiping = false; isLoadMoreTiping = false; if (refreshViewHolder != null) { if (isRefreshing) break; refreshViewHolder.pullingTips(headerView, 0); } if (loadMoreViewHolder != null) { if (isLoadMoreing) break; loadMoreViewHolder.loadTips(bottomView, 0); } break; case MotionEvent.ACTION_MOVE: float currentY = ev.getRawY(); float offsetY = currentY - tmpY; float dis = currentY - preY; //下拉刷新 if (intercept_action == INTERCEPT_ACTION.REFRESH) { if (dis >= DisplayUtil.dip2px(getContext(), HEADER_HEIGHT)) { if (refreshViewHolder != null) { if (!isRefreshTiping) { //提示只有一次 refreshViewHolder.willRefreshTips(headerView); isRefreshTiping = true; } } shouldRefresh = true; } else { shouldRefresh = false; float ratio = dis / DisplayUtil.dip2px(getContext(), HEADER_HEIGHT); if (refreshViewHolder != null && !isRefreshing) refreshViewHolder.pullingTips(headerView, (int) (100 * Math.abs(ratio))); } if (dis >= 0 && (dis < totalLimit)) { this.scrollBy(0, -(int) offsetY); } if (dis >= totalLimit) { this.scrollTo(0, -totalLimit); } } else if ((intercept_action == INTERCEPT_ACTION.LOAD_MORE) && (dis < 0)) { //上拉加载 this.scrollBy(0, -(int) offsetY); if (Math.abs(dis) >= DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT)) { if (!isLoadMoreTiping) { loadMoreViewHolder.willloadTips(bottomView); isLoadMoreTiping = true; } shouldLoadMore = true; } else { shouldLoadMore = false; float ratio = dis / DisplayUtil.dip2px(getContext(), BOTTOM_HEIGHT); if (loadMoreViewHolder != null && !isLoadMoreing) loadMoreViewHolder.loadTips(headerView, (int) (100 * Math.abs(ratio))); } } tmpY = currentY; break; case MotionEvent.ACTION_UP: smoothToZeroPos(); break; case MotionEvent.ACTION_CANCEL: smoothToZeroPos(); break; } return true; } private void startRefresh() { if (refreshViewHolder != null) { refreshViewHolder.refreshingTips(headerView); //开始后台刷新任务 if (!isRefreshing) new RefreshTask().execute(); } } private void startLoadMore() { if (loadMoreViewHolder != null) { loadMoreViewHolder.loadingTips(bottomView); if (!isLoadMoreing) { new LoadMoreTask().execute(); } } } private void smoothToZeroPos() { //下拉刷新 if (intercept_action == INTERCEPT_ACTION.REFRESH) { if (shouldRefresh) startRefresh(); } else if (intercept_action == INTERCEPT_ACTION.LOAD_MORE) { //上拉加载更多 if (shouldLoadMore) { startLoadMore(); } } smoothScrollTo(0, 0); } private void smoothScrollTo(int destX, int destY) { int offsetY = destY - getScrollY(); scroller.startScroll(0, getScrollY(), 0, offsetY, 500); invalidate(); } @Override public void computeScroll() { super.computeScroll(); if (scroller.computeScrollOffset()) { scrollTo(scroller.getCurrX(), scroller.getCurrY()); postInvalidate(); } } //下拉刷新-管理UI方面的接口 public interface RefreshViewHolder { //还没到刷新点的提示 void pullingTips(View headerView, int progress); //快要刷新时的提示 void willRefreshTips(View headerView); //正在刷新时的状态 void refreshingTips(View headerView); //刷新完毕 void refreshCompleteTips(View headerView); } //下拉刷新-管理事务方面的接口 public interface IRefreshAction { void refresh(); void refreshComplete(); } //上拉加载-管理UI 接口 public interface LoadMoreViewHolder { //还没到加载点的提示 void loadTips(View headerView, int progress); //快要加载时的提示 void willloadTips(View headerView); //正在加载时的状态 void loadingTips(View headerView); //加载完毕 void loadCompleteTips(View headerView); } public interface ILoadMoreAction { void loadMore(); void loadMoreComplete(); } //触摸点传递的接口,可供实现类扩展更多自定义动画 public interface onRefreshViewTouch { void onTouch(int x, int y); } public View getHeaderView() { return headerView; } public void setHeaderView(View headerView, RelativeLayout.LayoutParams layoutParams) { this.headerView = headerView; headerContent.removeViewAt(0); RelativeLayout.LayoutParams defaultLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); defaultLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); if (layoutParams == null) headerView.setLayoutParams(defaultLayoutParams); else headerView.setLayoutParams(layoutParams); headerContent.addView(headerView, 0); } public void setBottomView(View bottomView, RelativeLayout.LayoutParams layoutParams) { this.bottomView = bottomView; bottomContent.removeViewAt(0); RelativeLayout.LayoutParams defaultLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); defaultLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); if (layoutParams == null) bottomView.setLayoutParams(defaultLayoutParams); else bottomView.setLayoutParams(layoutParams); bottomContent.addView(bottomView, 0); } public RefreshViewHolder getRefreshViewHolder() { return refreshViewHolder; } public void setRefreshViewHolder(RefreshViewHolder refreshViewHolder) { this.refreshViewHolder = refreshViewHolder; } private class RefreshTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { isRefreshing = true; shouldRefresh = false; if (iRefreshAction != null) { iRefreshAction.refresh(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); post(new Runnable() { @Override public void run() { if (refreshViewHolder != null) { refreshViewHolder.refreshCompleteTips(headerView); smoothScrollTo(0, 0); } } }); if (iRefreshAction != null) { iRefreshAction.refreshComplete(); } isRefreshing = false; } @Override protected void onCancelled() { super.onCancelled(); smoothScrollTo(0, 0); shouldRefresh = false; isRefreshing = false; } } private class LoadMoreTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { isLoadMoreing = true; shouldLoadMore = false; if (iLoadMoreAction != null) { iLoadMoreAction.loadMore(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); super.onPostExecute(aVoid); post(new Runnable() { @Override public void run() { if (loadMoreViewHolder != null) { loadMoreViewHolder.loadCompleteTips(headerView); smoothScrollTo(0, 0); } } }); if (iLoadMoreAction != null) { iLoadMoreAction.loadMoreComplete(); } isLoadMoreing = false; } @Override protected void onCancelled() { super.onCancelled(); smoothScrollTo(0, 0); shouldLoadMore = false; isLoadMoreing = false; } } public void setiRefreshAction(IRefreshAction iRefreshAction) { this.iRefreshAction = iRefreshAction; } public ILoadMoreAction getiLoadMoreAction() { return iLoadMoreAction; } public void setiLoadMoreAction(ILoadMoreAction iLoadMoreAction) { this.iLoadMoreAction = iLoadMoreAction; } public LoadMoreViewHolder getLoadMoreViewHolder() { return loadMoreViewHolder; } public void setLoadMoreViewHolder(LoadMoreViewHolder loadMoreViewHolder) { this.loadMoreViewHolder = loadMoreViewHolder; } public KRefreshView.onRefreshViewTouch getOnRefreshViewTouch() { return onRefreshViewTouch; } public void setOnRefreshViewTouch(KRefreshView.onRefreshViewTouch onRefreshViewTouch) { this.onRefreshViewTouch = onRefreshViewTouch; } public void setHeaderHeight(int headerHeightDp) { this.HEADER_HEIGHT = headerHeightDp; totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT); } public int getMAX_LIMIT_SLOT() { return MAX_LIMIT_SLOT; } public void setMAX_LIMIT_SLOT(int MAX_LIMIT_SLOT) { this.MAX_LIMIT_SLOT = MAX_LIMIT_SLOT; totalLimit = DisplayUtil.dip2px(getContext(), HEADER_HEIGHT + MAX_LIMIT_SLOT); } public LoadMoreConfig getLoadMoreConfig() { return loadMoreConfig; } public void setLoadMoreConfig(LoadMoreConfig loadMoreConfig) { this.loadMoreConfig = loadMoreConfig; if (loadMoreConfig.canLoadMore) { if (loadMoreConfig.loadMoreView != null) setBottomView(loadMoreConfig.loadMoreView, null); if (loadMoreConfig.iLoadMoreAction != null) setiLoadMoreAction(loadMoreConfig.iLoadMoreAction); if (loadMoreConfig.loadMoreViewHolder != null) setLoadMoreViewHolder(loadMoreConfig.loadMoreViewHolder); if (loadMoreConfig.height > 0) BOTTOM_HEIGHT = loadMoreConfig.height; } } public static class LoadMoreConfig { public boolean canLoadMore; public View loadMoreView; public ILoadMoreAction iLoadMoreAction; public LoadMoreViewHolder loadMoreViewHolder; public int height; public LoadMoreConfig(boolean canLoadMore, View loadMoreView, ILoadMoreAction iLoadMoreAction, LoadMoreViewHolder loadMoreViewHolder, int height) { this.canLoadMore = canLoadMore; this.loadMoreView = loadMoreView; this.iLoadMoreAction = iLoadMoreAction; this.loadMoreViewHolder = loadMoreViewHolder; this.height = height; } } }
CookieDSEU/PlantNurse
ksimplelibrary/src/main/java/com/kot32/ksimplelibrary/widgets/view/KRefreshView.java