file_id
int64
1
66.7k
content
stringlengths
14
343k
repo
stringlengths
6
92
path
stringlengths
5
169
694
package cn.hutool.core.date; import cn.hutool.core.lang.Assert; import java.util.Calendar; import java.util.Date; /** * 星座 来自:https://blog.csdn.net/u010758605/article/details/48317881 * * @author looly * @since 4.4.3 */ public class Zodiac { /** 星座分隔时间日 */ private static final int[] DAY_ARR = new int[] { 20, 19, 21, 20, 21, 22, 23, 23, 23, 24, 23, 22 }; /** 星座 */ private static final String[] ZODIACS = new String[] { "摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座" }; private static final String[] CHINESE_ZODIACS = new String[] { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" }; /** * 通过生日计算星座 * * @param date 出生日期 * @return 星座名 */ public static String getZodiac(Date date) { return getZodiac(DateUtil.calendar(date)); } /** * 通过生日计算星座 * * @param calendar 出生日期 * @return 星座名 */ public static String getZodiac(Calendar calendar) { if (null == calendar) { return null; } return getZodiac(calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); } /** * 通过生日计算星座 * * @param month 月,从0开始计数 * @param day 天 * @return 星座名 * @since 4.5.0 */ public static String getZodiac(Month month, int day) { return getZodiac(month.getValue(), day); } /** * 通过生日计算星座 * * @param month 月,从0开始计数,见{@link Month#getValue()} * @param day 天 * @return 星座名 */ public static String getZodiac(int month, int day) { Assert.checkBetween(month, Month.JANUARY.getValue(), Month.DECEMBER.getValue(), "Unsupported month value, must be [0,12]"); // 在分隔日前为前一个星座,否则为后一个星座 return day < DAY_ARR[month] ? ZODIACS[month] : ZODIACS[month + 1]; } // ----------------------------------------------------------------------------------------------------------- 生肖 /** * 通过生日计算生肖,只计算1900年后出生的人 * * @param date 出生日期(年需农历) * @return 星座名 */ public static String getChineseZodiac(Date date) { return getChineseZodiac(DateUtil.calendar(date)); } /** * 通过生日计算生肖,只计算1900年后出生的人 * * @param calendar 出生日期(年需农历) * @return 星座名 */ public static String getChineseZodiac(Calendar calendar) { if (null == calendar) { return null; } return getChineseZodiac(calendar.get(Calendar.YEAR)); } /** * 计算生肖,只计算1900年后出生的人 * * @param year 农历年 * @return 生肖名 */ public static String getChineseZodiac(int year) { if (year < 1900) { return null; } return CHINESE_ZODIACS[(year - 1900) % CHINESE_ZODIACS.length]; } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/date/Zodiac.java
695
/** * JustAuth,如你所见,它仅仅是一个第三方授权登录的工具类库,它可以让我们脱离繁琐的第三方登录SDK,让登录变得So easy! * <p> * 史上最全的整合第三方登录的开源库。目前已支持Github、Gitee、微博、钉钉、百度、Coding、腾讯云开发者平台、OSChina、 * 支付宝、QQ、微信、淘宝、Google、Facebook、抖音、领英、小米、微软、今日头条、Teambition、StackOverflow、Pinterest、 * 人人、华为和企业微信等第三方平台的授权登录。 Login, so easy! */ package me.zhyd.oauth;
justauth/JustAuth
src/main/java/me/zhyd/oauth/package-info.java
696
H 1518424818 tags: DP, Binary Search, Partition DP 给一串书pages[i], k个人, pages[i] 代表每本书的页数. k个人从不同的点同时开始抄书. 问, 最快什么时候可以抄完? #### Partition DP - 第一步, 理解题目要求的问题: 前k个人copy完n本书, 找到最少的用时; 也可以翻译成: `n本书, 让k个人来copy, 也就是分割成k段`. - 最后需要求出 dp[n][k]. 开: int[n+1][k+1]. - 原理: - 1. 考虑最后一步: 在[0 ~ n - 1]本书里, 最后一个人可以选择copy 1 本, 2 本....n本, 每一种切割的方法的结果都不一样 - 2. 讨论第k个人的情况, 在 j = [0 ~ i] 循环. 而循环j时候最慢的情况决定 第k个人的结果(木桶原理): `Math.max(dp[j][k - 1], sum)`. - 3. 其中: `dp[j][k-1]` 是 [k-1]个人读完j本书的结果, 也就是著名的`上一步`. 这里循环考虑的是第k个人不同的j种上一步 : ) - 4. 循环的结果, 是要存在 dp[i][k] = Math.min(Math.max(dp[j][k - 1], sum[j, i]), loop over i, k, j = [i ~ 0]) - Time: O(kn^2), space O(nk) ##### Init - Init: dp[0][0] = 0, 0个人0本书 - Integer.MAX_VALUE的运用: - 当 i = 1, k = 1, 表达式: dp[i][k] = Math.min(dp[i][k], Math.max(dp[j][k - 1], sum)); - 唯一可行的情况就只有一种: i=0, k=0, 刚好 0 个人 copy 0 本书, dp[0][0] = 0. - 其他情况, i = 1, k = 0, 0 个人读 1本书, 不可能发生: 所以用Integer.MAX_VALUE来冲破 Math.max, 维持荒谬值. - 当 i=0, k=0 的情况被讨论时候, 上面的方程式才会按照实际情况计算出 dp[i][k] - 这道题的init是非常重要而tricky的 ##### 计算顺序 - k个人, 需要一个for loop; - k个人, 从copy1本书开始, 2, 3, ... n-1,所以 i=[1, n], 需要第二个for loop - 在每一个i上, 切割的方式可以有[0 ~ i] 中, 我们要计算每一种的worst time ##### 滚动数组 - [k] 只有和 [k - 1] 相关 - Space: O(n) #### Binary Search - 根据: 每个人花的多少时间(time)来做binary search: 每个人花多久时间, 可以在K个人之内, 用最少的时间完成? - time variable的范围不是index, 也不是page大小. 而是[minPage, pageSum] - validation 的时候注意3种情况: 人够用 k>=0, 人不够所以结尾减成k<0, 还有一种是time(每个人最多花的时间)小于当下的页面, return -1 - O(nLogM). n = pages.length; m = sum of pages. ``` /* LintCode Given n books and the ith book has A[i] pages. You are given k people to copy the n books. n books list in a row and each person can claim a continous range of the n books. For example one copier can copy the books from ith to jth continously, but he can not copy the 1st book, 2nd book and 4th book (without 3rd book). They start copying books at the same time and they all cost 1 minute to copy 1 page of a book. What's the best strategy to assign books so that the slowest copier can finish at earliest time? */ /* // A easier/consistent way to write the dp: Thoughts: 1. dp[i][k]: divide i books into k dividions, for k people to read. 2. Within each division, we need to know where the cut will be. Use j [0 ~ i] to loop all possible division spots. */ public class Solution { public int copyBooks(int[] pages, int K) { if (pages == null || pages.length == 0) { return 0; } int n = pages.length; if (K > n) { K = n; } int[][] dp = new int[n + 1][K + 1]; //dp[0][0~n] = Integer.MAX_VALUE; // 0 people read n books dp[0][0] = 0; // 0 people read 0 book for (int i = 1; i <= n; i++) { dp[i][0] = Integer.MAX_VALUE; } for (int i = 1; i <= n; i++) {// read i books for (int k = 1; k <= K; k++) { // k people int sum = 0; dp[i][k] = Integer.MAX_VALUE; for (int j = i; j >= 0; j--) { // last person k read from [j ~ i] which uses 'sum' time dp[i][k] = Math.min(dp[i][k], Math.max(dp[j][k - 1], sum)); if (j > 0) { sum += pages[j - 1]; } } } } return dp[n][K]; } } /* Thoughts: Considering k people finishing i books. If last person read some books, then all the rest people just need to: k - 1 people to finish j books, and the kth person read [j, j + 1, ..., i-1] books Overall possible time spent is determined by the slowest person(bucket theory): Either dp[k - 1][j] or (pages[j] + pages[j + 1] + ... + pages[i - 1]) = Max{dp[k - 1][j], pages[j] + pages[j + 1] + ... + pages[i - 1]} Of course we weant to minimize the overall time spent: take min of the above equation, where j = 0 ~ i dp[k][i]: time spent for k people to read i books. dp[k][i] = Min{Max{dp[k - 1][j] + sum(pages[j ~ i-1])}}, where j = 0 ~ i Return dp[k][i] init: dp[0][0] = 0; time spent for 0 people copy 0 books */ public class Solution { public int copyBooks(int[] pages, int K) { if (pages == null || pages.length == 0) { return 0; } int n = pages.length; if (K > n) { K = n; } int[][] dp = new int[K + 1][n + 1]; //dp[0][0~n] = Integer.MAX_VALUE; // 0 people read n books dp[0][0] = 0; // 0 people read 0 book for (int i = 1; i <= n; i++) { dp[0][i] = Integer.MAX_VALUE; } for (int k = 1; k <= K; k++) { // k people for (int i = 1; i <= n; i++) {// read i books int sum = 0; dp[k][i] = Integer.MAX_VALUE; for (int j = i; j >= 0; j--) { // person k read from j -> i dp[k][i] = Math.min(dp[k][i], Math.max(dp[k - 1][j], sum)); if (j > 0) { sum += pages[j - 1]; } } } } return dp[K][n]; } } // Rolling array public class Solution { public int copyBooks(int[] pages, int K) { if (pages == null || pages.length == 0) { return 0; } int n = pages.length; if (K > n) { K = n; } int[][] dp = new int[2][n + 1]; //dp[0][0~n] = Integer.MAX_VALUE; // 0 people read n books dp[0][0] = 0; // 0 people read 0 book for (int i = 1; i <= n; i++) { dp[0][i] = Integer.MAX_VALUE; } for (int k = 1; k <= K; k++) { // k people for (int i = 1; i <= n; i++) {// read i books int sum = 0; dp[k % 2][i] = Integer.MAX_VALUE; for (int j = i; j >= 0; j--) { // person k read from j -> i dp[k % 2][i] = Math.min(dp[k % 2][i], Math.max(dp[(k - 1) % 2][j], sum)); if (j > 0) { sum += pages[j - 1]; } } } } return dp[K % 2][n]; } } /* Thoughts: Stupid way of asking 'slowest copier to finish at earliest time'. It does not make sense. The question does not provide speed, what does 'slow/fast' mean? The question does not distinguish each copier, what does 'earliest' time mean? Given the sample results, it's asking: what's the minimum time can be used to finish all books with given k people. - 1 book cannot be split to give to multiple people - cannot sort the book array A person at minimum needs to finish 1 book, and a person at maximum can read all books. should find x in [min, max] such that all books can be finished. The person can read at most x mins, but don't over-read if next book in the row can't be covered within x mins. It's find to not use up all copiers. */ public class Solution { public int copyBooks(int[] pages, int k) { if (pages == null || pages.length == 0) { return 0; } int m = pages.length; int min = Integer.MAX_VALUE; int sum = 0; // Find minimum read mins for (int page : pages) { min = Math.min(min, page); sum += page; } int start = min; int end = sum; while (start + 1 < end) { int mid = start + (end - start) / 2; // mid: total time spent per person int validation = validate(pages, mid, k); if (validation < 0) { start = mid; } else { end = mid; } } if (validate(pages, start, k) >= 0) { return start; } else { return end; } } /* Validate if all copies are utilized to finish. Return 0 if k used to finish books. Return negative needing more copier, which means value is too small. Return postivie, if value is too big, and copies are not utilized. */ private int validate(int[] pages, int totalTimePerPerson, int k) { int temp = 0; for (int i = 0; i < pages.length; i++) { temp += pages[i]; if (temp == totalTimePerPerson) { temp = 0; k--; } else if (temp < totalTimePerPerson) { if (i + 1 >= pages.length || temp + pages[i + 1] > totalTimePerPerson) { // no next page; or not enough capacity to read next page temp = 0; k--; } // else: (i + 1 < pages.length && temp + pages[i + 1] <= totalTimePerPerson) } else { return -1; } } return k; } } ```
awangdev/leet-code
Java/Copy Books.java
697
package org.ansj.library; import org.ansj.dic.DicReader; import org.ansj.domain.AnsjItem; import org.ansj.domain.NumNatureAttr; import org.ansj.domain.PersonNatureAttr; import org.ansj.domain.Term; import org.ansj.recognition.arrimpl.NumRecognition; import org.ansj.util.MyStaticValue; import org.nlpcn.commons.lang.dat.DoubleArrayTire; import org.nlpcn.commons.lang.dat.Item; import org.nlpcn.commons.lang.util.ObjConver; import org.nlpcn.commons.lang.util.logging.Log; import org.nlpcn.commons.lang.util.logging.LogFactory; import java.io.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class DATDictionary { private static final Log LOG = LogFactory.getLog(DATDictionary.class); /** * 人名补充 */ private static final Map<String, PersonNatureAttr> PERSONMAP = new HashMap<>(); /** * 外国人名补充 */ private static final Set<String> FOREIGNSET = new HashSet<>(); /** * 核心词典 */ private static final DoubleArrayTire DAT = loadDAT(); /** * 数组长度 */ public static int arrayLength = DAT.arrayLength; /** * 加载词典 * * @return */ private static DoubleArrayTire loadDAT() { long start = System.currentTimeMillis(); try { DoubleArrayTire dat = DoubleArrayTire.loadText(DicReader.getInputStream("core.dic"), AnsjItem.class); for (char c : NumRecognition.f_NUM) { NumNatureAttr numAttr = ((AnsjItem) dat.getDAT()[c]).termNatures.numAttr; if (numAttr == null || numAttr == NumNatureAttr.NULL) { ((AnsjItem) dat.getDAT()[c]).termNatures.numAttr = NumNatureAttr.NUM; } else { numAttr.setNum(true); } } for (char c : NumRecognition.j_NUM) { NumNatureAttr numAttr = ((AnsjItem) dat.getDAT()[c]).termNatures.numAttr; if (numAttr == null || numAttr == NumNatureAttr.NULL) { ((AnsjItem) dat.getDAT()[c]).termNatures.numAttr = NumNatureAttr.NUM; } else { numAttr.setNum(true); } } // 人名识别必备的 personNameFull(dat); // 记录词典中的词语,并且清除部分数据 for (Item item : dat.getDAT()) { if (item == null || item.getName() == null) { continue; } if (item.getStatus() < 2) { item.setName(null); continue; } } LOG.info("init core library ok use time : " + (System.currentTimeMillis() - start)); return dat; } catch (InstantiationException e) { LOG.warn("无法实例化", e); } catch (IllegalAccessException e) { LOG.warn("非法访问", e); } catch (NumberFormatException e) { LOG.warn("数字格式异常", e); } catch (IOException e) { LOG.warn("IO异常", e); } return null; } private static void personNameFull(DoubleArrayTire dat) throws NumberFormatException, IOException { BufferedReader reader = null; try { reader = MyStaticValue.getPersonDicReader(); AnsjItem item = null; String temp = null, word = null; float score; while ((temp = reader.readLine()) != null) { String[] split = temp.split("\t"); word = split[1]; score = ObjConver.getFloatValue(split[2]); item = dat.getItem(word); if (item == null || item.getStatus() < 2) { if (word.length() < 2 || word.charAt(0) == ':' || "BEGIN".equals(word) || "END".equals(word)) { PersonNatureAttr pna = PERSONMAP.get(split[1]); if (pna == null) { pna = new PersonNatureAttr(); } pna.set(temp.charAt(0), score); PERSONMAP.put(word, pna); } } else { PersonNatureAttr personAttr = item.termNatures.personAttr; if (personAttr == PersonNatureAttr.NULL) { personAttr = new PersonNatureAttr(); item.termNatures.personAttr = personAttr; } personAttr.set(temp.charAt(0), score); } } } finally { reader.close(); } try { //将外国人名放入到map中 reader = MyStaticValue.getForeignDicReader(); String temp = null; while ((temp = reader.readLine()) != null) { FOREIGNSET.add(temp); } } finally { reader.close(); } } public static int status(char c) { Item item = DAT.getDAT()[c]; if (item == null) { return 0; } return item.getStatus(); } /** * 判断一个词语是否在词典中 * * @param word * @return */ public static boolean isInSystemDic(String word) { Item item = DAT.getItem(word); return item != null && item.getStatus() > 1; } public static AnsjItem getItem(int index) { AnsjItem item = DAT.getItem(index); if (item == null) { return AnsjItem.NULL; } return item; } public static AnsjItem getItem(String str) { AnsjItem item = DAT.getItem(str); if (item == null || item.getStatus() < 2) { return AnsjItem.NULL; } return item; } public static int getId(String str) { return DAT.getId(str); } /** * 取得人名补充 * * @param name * @return */ public static PersonNatureAttr person(String name) { return PERSONMAP.get(name); } /** * 取得人名补充 * * @param name * @return */ public static boolean foreign(String name) { return FOREIGNSET.contains(name); } /** * 取得人名补充 * * @param term * @return */ public static boolean foreign(Term term) { String name = term.getName(); boolean contains = FOREIGNSET.contains(name); if (contains) { return contains; } if (!term.getNatureStr().startsWith("nr")) { return false; } for (int i = 0; i < name.length(); i++) { if (!FOREIGNSET.contains(String.valueOf(name.charAt(i)))) { return false; } } return true ; } public static void write2File(String path) throws IOException { ObjectOutput oop = new ObjectOutputStream(new FileOutputStream(new File(path))); oop.writeObject(DAT.getDAT()); oop.writeObject(PERSONMAP); oop.writeObject(FOREIGNSET); oop.flush(); oop.close(); } public static DoubleArrayTire loadFromFile(String path) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(path))); Item[] items = (Item[]) ois.readObject(); DoubleArrayTire dat = new DoubleArrayTire(items); PERSONMAP.putAll(((Map<String, PersonNatureAttr>) ois.readObject())); FOREIGNSET.addAll(((Set<String>) ois.readObject())); return dat; } }
NLPchina/ansj_seg
src/main/java/org/ansj/library/DATDictionary.java
698
package com.xkcoding.neo4j.service; import cn.hutool.core.util.StrUtil; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.xkcoding.neo4j.model.Class; import com.xkcoding.neo4j.model.Lesson; import com.xkcoding.neo4j.model.Student; import com.xkcoding.neo4j.model.Teacher; import com.xkcoding.neo4j.payload.ClassmateInfoGroupByLesson; import com.xkcoding.neo4j.payload.TeacherStudent; import com.xkcoding.neo4j.repository.ClassRepository; import com.xkcoding.neo4j.repository.LessonRepository; import com.xkcoding.neo4j.repository.StudentRepository; import com.xkcoding.neo4j.repository.TeacherRepository; import org.neo4j.ogm.session.Session; import org.neo4j.ogm.session.SessionFactory; import org.neo4j.ogm.transaction.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; import java.util.Set; /** * <p> * NeoService * </p> * * @author yangkai.shen * @date Created in 2018-12-24 15:19 */ @Service public class NeoService { @Autowired private ClassRepository classRepo; @Autowired private LessonRepository lessonRepo; @Autowired private StudentRepository studentRepo; @Autowired private TeacherRepository teacherRepo; @Autowired private SessionFactory sessionFactory; /** * 初始化数据 */ @Transactional public void initData() { // 初始化老师 Teacher akai = Teacher.of("迈特凯"); Teacher kakaxi = Teacher.of("旗木卡卡西"); Teacher zilaiye = Teacher.of("自来也"); Teacher gangshou = Teacher.of("纲手"); Teacher dashewan = Teacher.of("大蛇丸"); teacherRepo.save(akai); teacherRepo.save(kakaxi); teacherRepo.save(zilaiye); teacherRepo.save(gangshou); teacherRepo.save(dashewan); // 初始化课程 Lesson tishu = Lesson.of("体术", akai); Lesson huanshu = Lesson.of("幻术", kakaxi); Lesson shoulijian = Lesson.of("手里剑", kakaxi); Lesson luoxuanwan = Lesson.of("螺旋丸", zilaiye); Lesson xianshu = Lesson.of("仙术", zilaiye); Lesson yiliao = Lesson.of("医疗", gangshou); Lesson zhouyin = Lesson.of("咒印", dashewan); lessonRepo.save(tishu); lessonRepo.save(huanshu); lessonRepo.save(shoulijian); lessonRepo.save(luoxuanwan); lessonRepo.save(xianshu); lessonRepo.save(yiliao); lessonRepo.save(zhouyin); // 初始化班级 Class three = Class.of("第三班", akai); Class seven = Class.of("第七班", kakaxi); classRepo.save(three); classRepo.save(seven); // 初始化学生 List<Student> threeClass = Lists.newArrayList(Student.of("漩涡鸣人", Lists.newArrayList(tishu, shoulijian, luoxuanwan, xianshu), seven), Student.of("宇智波佐助", Lists.newArrayList(huanshu, zhouyin, shoulijian), seven), Student.of("春野樱", Lists.newArrayList(tishu, yiliao, shoulijian), seven)); List<Student> sevenClass = Lists.newArrayList(Student.of("李洛克", Lists.newArrayList(tishu), three), Student.of("日向宁次", Lists.newArrayList(tishu), three), Student.of("天天", Lists.newArrayList(tishu), three)); studentRepo.saveAll(threeClass); studentRepo.saveAll(sevenClass); } /** * 删除数据 */ @Transactional public void delete() { // 使用语句删除 Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.query("match (n)-[r]-() delete n,r", Maps.newHashMap()); session.query("match (n)-[r]-() delete r", Maps.newHashMap()); session.query("match (n) delete n", Maps.newHashMap()); transaction.commit(); // 使用 repository 删除 studentRepo.deleteAll(); classRepo.deleteAll(); lessonRepo.deleteAll(); teacherRepo.deleteAll(); } /** * 根据学生姓名查询所选课程 * * @param studentName 学生姓名 * @param depth 深度 * @return 课程列表 */ public List<Lesson> findLessonsFromStudent(String studentName, int depth) { List<Lesson> lessons = Lists.newArrayList(); studentRepo.findByName(studentName, depth).ifPresent(student -> lessons.addAll(student.getLessons())); return lessons; } /** * 查询全校学生数 * * @return 学生总数 */ public Long studentCount(String className) { if (StrUtil.isBlank(className)) { return studentRepo.count(); } else { return studentRepo.countByClassName(className); } } /** * 查询同学关系,根据课程 * * @return 返回同学关系 */ public Map<String, List<Student>> findClassmatesGroupByLesson() { List<ClassmateInfoGroupByLesson> groupByLesson = studentRepo.findByClassmateGroupByLesson(); Map<String, List<Student>> result = Maps.newHashMap(); groupByLesson.forEach(classmateInfoGroupByLesson -> result.put(classmateInfoGroupByLesson.getLessonName(), classmateInfoGroupByLesson.getStudents())); return result; } /** * 查询所有师生关系,包括班主任/学生,任课老师/学生 * * @return 师生关系 */ public Map<String, Set<Student>> findTeacherStudent() { List<TeacherStudent> teacherStudentByClass = studentRepo.findTeacherStudentByClass(); List<TeacherStudent> teacherStudentByLesson = studentRepo.findTeacherStudentByLesson(); Map<String, Set<Student>> result = Maps.newHashMap(); teacherStudentByClass.forEach(teacherStudent -> result.put(teacherStudent.getTeacherName(), Sets.newHashSet(teacherStudent.getStudents()))); teacherStudentByLesson.forEach(teacherStudent -> result.put(teacherStudent.getTeacherName(), Sets.newHashSet(teacherStudent.getStudents()))); return result; } }
xkcoding/spring-boot-demo
demo-neo4j/src/main/java/com/xkcoding/neo4j/service/NeoService.java
699
package org.jeecg.common.constant; /** * 数据库上下文常量 * @author: jeecg-boot */ public interface DataBaseConstant { //*********数据库类型**************************************** /**MYSQL数据库*/ public static final String DB_TYPE_MYSQL = "MYSQL"; /** ORACLE*/ public static final String DB_TYPE_ORACLE = "ORACLE"; /**达梦数据库*/ public static final String DB_TYPE_DM = "DM"; /**postgreSQL达梦数据库*/ public static final String DB_TYPE_POSTGRESQL = "POSTGRESQL"; /**人大金仓数据库*/ public static final String DB_TYPE_KINGBASEES = "KINGBASEES"; /**sqlserver数据库*/ public static final String DB_TYPE_SQLSERVER = "SQLSERVER"; /**mariadb 数据库*/ public static final String DB_TYPE_MARIADB = "MARIADB"; /**DB2 数据库*/ public static final String DB_TYPE_DB2 = "DB2"; /**HSQL 数据库*/ public static final String DB_TYPE_HSQL = "HSQL"; // // 数据库类型,对应 database_type 字典 // public static final String DB_TYPE_MYSQL_NUM = "1"; // public static final String DB_TYPE_MYSQL7_NUM = "6"; // public static final String DB_TYPE_ORACLE_NUM = "2"; // public static final String DB_TYPE_SQLSERVER_NUM = "3"; // public static final String DB_TYPE_POSTGRESQL_NUM = "4"; // public static final String DB_TYPE_MARIADB_NUM = "5"; //*********系统上下文变量**************************************** /** * 数据-所属机构编码 */ public static final String SYS_ORG_CODE = "sysOrgCode"; /** * 数据-所属机构编码 */ public static final String SYS_ORG_CODE_TABLE = "sys_org_code"; /** * 数据-所属机构编码 */ public static final String SYS_MULTI_ORG_CODE = "sysMultiOrgCode"; /** * 数据-所属机构编码 */ public static final String SYS_MULTI_ORG_CODE_TABLE = "sys_multi_org_code"; /** * 数据-系统用户编码(对应登录用户账号) */ public static final String SYS_USER_CODE = "sysUserCode"; /** * 数据-系统用户编码(对应登录用户账号) */ public static final String SYS_USER_CODE_TABLE = "sys_user_code"; /** * 登录用户真实姓名 */ public static final String SYS_USER_NAME = "sysUserName"; /** * 登录用户真实姓名 */ public static final String SYS_USER_NAME_TABLE = "sys_user_name"; /** * 系统日期"yyyy-MM-dd" */ public static final String SYS_DATE = "sysDate"; /** * 系统日期"yyyy-MM-dd" */ public static final String SYS_DATE_TABLE = "sys_date"; /** * 系统时间"yyyy-MM-dd HH:mm" */ public static final String SYS_TIME = "sysTime"; /** * 系统时间"yyyy-MM-dd HH:mm" */ public static final String SYS_TIME_TABLE = "sys_time"; /** * 数据-所属机构编码 */ public static final String SYS_BASE_PATH = "sys_base_path"; //*********系统上下文变量**************************************** //*********系统建表标准字段**************************************** /** * 创建者登录名称 */ public static final String CREATE_BY_TABLE = "create_by"; /** * 创建者登录名称 */ public static final String CREATE_BY = "createBy"; /** * 创建日期时间 */ public static final String CREATE_TIME_TABLE = "create_time"; /** * 创建日期时间 */ public static final String CREATE_TIME = "createTime"; /** * 更新用户登录名称 */ public static final String UPDATE_BY_TABLE = "update_by"; /** * 更新用户登录名称 */ public static final String UPDATE_BY = "updateBy"; /** * 更新日期时间 */ public static final String UPDATE_TIME = "updateTime"; /** * 更新日期时间 */ public static final String UPDATE_TIME_TABLE = "update_time"; /** * 业务流程状态 */ public static final String BPM_STATUS = "bpmStatus"; /** * 业务流程状态 */ public static final String BPM_STATUS_TABLE = "bpm_status"; //*********系统建表标准字段**************************************** /** * sql语句 where */ String SQL_WHERE = "where"; /** * sql语句 asc */ String SQL_ASC = "asc"; /** * sqlserver数据库,中间有空格 */ String DB_TYPE_SQL_SERVER_BLANK = "sql server"; }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/common/constant/DataBaseConstant.java
700
/* * The MIT License (MIT) * * Copyright (c) 2014-2023 [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.pagehelper.page; import com.github.pagehelper.AutoDialect; import com.github.pagehelper.Dialect; import com.github.pagehelper.PageException; import com.github.pagehelper.dialect.AbstractHelperDialect; import com.github.pagehelper.dialect.auto.*; import com.github.pagehelper.dialect.helper.*; import com.github.pagehelper.util.ClassUtil; import com.github.pagehelper.util.StringUtil; import org.apache.ibatis.mapping.MappedStatement; import javax.sql.DataSource; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * 基础方言信息 * * @author liuzh */ public class PageAutoDialect { private static Map<String, Class<? extends Dialect>> dialectAliasMap = new LinkedHashMap<>(); private static Map<String, Class<? extends AutoDialect>> autoDialectMap = new LinkedHashMap<>(); public static void registerDialectAlias(String alias, Class<? extends Dialect> dialectClass) { dialectAliasMap.put(alias, dialectClass); } static { //注册别名 registerDialectAlias("hsqldb", HsqldbDialect.class); registerDialectAlias("h2", HsqldbDialect.class); registerDialectAlias("phoenix", HsqldbDialect.class); registerDialectAlias("postgresql", PostgreSqlDialect.class); registerDialectAlias("mysql", MySqlDialect.class); registerDialectAlias("mariadb", MySqlDialect.class); registerDialectAlias("sqlite", MySqlDialect.class); registerDialectAlias("herddb", HerdDBDialect.class); registerDialectAlias("oracle", OracleDialect.class); registerDialectAlias("oracle9i", Oracle9iDialect.class); registerDialectAlias("db2", Db2Dialect.class); registerDialectAlias("as400", AS400Dialect.class); registerDialectAlias("informix", InformixDialect.class); //解决 informix-sqli #129,仍然保留上面的 registerDialectAlias("informix-sqli", InformixDialect.class); registerDialectAlias("sqlserver", SqlServerDialect.class); registerDialectAlias("sqlserver2012", SqlServer2012Dialect.class); registerDialectAlias("derby", SqlServer2012Dialect.class); //达梦数据库,https://github.com/mybatis-book/book/issues/43 registerDialectAlias("dm", OracleDialect.class); //阿里云PPAS数据库,https://github.com/pagehelper/Mybatis-PageHelper/issues/281 registerDialectAlias("edb", OracleDialect.class); //神通数据库 registerDialectAlias("oscar", OscarDialect.class); registerDialectAlias("clickhouse", MySqlDialect.class); //瀚高数据库 registerDialectAlias("highgo", HsqldbDialect.class); //虚谷数据库 registerDialectAlias("xugu", HsqldbDialect.class); registerDialectAlias("impala", HsqldbDialect.class); registerDialectAlias("firebirdsql", FirebirdDialect.class); //人大金仓数据库 registerDialectAlias("kingbase", PostgreSqlDialect.class); // 人大金仓新版本kingbase8 registerDialectAlias("kingbase8", PostgreSqlDialect.class); //行云数据库 registerDialectAlias("xcloud", CirroDataDialect.class); //openGauss数据库 registerDialectAlias("opengauss", PostgreSqlDialect.class); //注册 AutoDialect //想要实现和以前版本相同的效果时,可以配置 autoDialectClass=old registerAutoDialectAlias("old", DefaultAutoDialect.class); registerAutoDialectAlias("hikari", HikariAutoDialect.class); registerAutoDialectAlias("druid", DruidAutoDialect.class); registerAutoDialectAlias("tomcat-jdbc", TomcatAutoDialect.class); registerAutoDialectAlias("dbcp", DbcpAutoDialect.class); registerAutoDialectAlias("c3p0", C3P0AutoDialect.class); //不配置时,默认使用 DataSourceNegotiationAutoDialect registerAutoDialectAlias("default", DataSourceNegotiationAutoDialect.class); } public static void registerAutoDialectAlias(String alias, Class<? extends AutoDialect> autoDialectClass) { autoDialectMap.put(alias, autoDialectClass); } /** * 自动获取dialect,如果没有setProperties或setSqlUtilConfig,也可以正常进行 */ private boolean autoDialect = true; /** * 属性配置 */ private Properties properties; /** * 缓存 dialect 实现,key 有两种,分别为 jdbcurl 和 dialectClassName */ private Map<Object, AbstractHelperDialect> urlDialectMap = new ConcurrentHashMap<Object, AbstractHelperDialect>(); private ReentrantLock lock = new ReentrantLock(); private AbstractHelperDialect delegate; private ThreadLocal<AbstractHelperDialect> dialectThreadLocal = new ThreadLocal<AbstractHelperDialect>(); private AutoDialect autoDialectDelegate; public static String fromJdbcUrl(String jdbcUrl) { final String url = jdbcUrl.toLowerCase(); for (String dialect : dialectAliasMap.keySet()) { if (url.contains(":" + dialect.toLowerCase() + ":")) { return dialect; } } return null; } //获取当前的代理对象 public AbstractHelperDialect getDelegate() { if (delegate != null) { return delegate; } return dialectThreadLocal.get(); } //移除代理对象 public void clearDelegate() { dialectThreadLocal.remove(); } public AbstractHelperDialect getDialectThreadLocal() { return dialectThreadLocal.get(); } public void setDialectThreadLocal(AbstractHelperDialect delegate) { this.dialectThreadLocal.set(delegate); } /** * 反射类 * * @param className * @return * @throws Exception */ public static Class resloveDialectClass(String className) throws Exception { if (dialectAliasMap.containsKey(className.toLowerCase())) { return dialectAliasMap.get(className.toLowerCase()); } else { return Class.forName(className); } } /** * 初始化 helper * * @param dialectClass * @param properties */ public static AbstractHelperDialect instanceDialect(String dialectClass, Properties properties) { AbstractHelperDialect dialect; if (StringUtil.isEmpty(dialectClass)) { throw new PageException("When you use the PageHelper pagination plugin, you must set the helper property"); } try { Class sqlDialectClass = resloveDialectClass(dialectClass); if (AbstractHelperDialect.class.isAssignableFrom(sqlDialectClass)) { dialect = (AbstractHelperDialect) sqlDialectClass.newInstance(); } else { throw new PageException("When using PageHelper, the dialect must be an implementation class that implements the " + AbstractHelperDialect.class.getCanonicalName() + " interface!"); } } catch (Exception e) { throw new PageException("error initializing helper dialectclass[" + dialectClass + "]" + e.getMessage(), e); } dialect.setProperties(properties); return dialect; } /** * 多数据动态获取时,每次需要初始化,还可以运行时指定具体的实现 * * @param ms * @param dialectClass 分页实现,必须是 {@link AbstractHelperDialect} 实现类,可以使用当前类中注册的别名,例如 "mysql", "oracle" */ public void initDelegateDialect(MappedStatement ms, String dialectClass) { if (StringUtil.isNotEmpty(dialectClass)) { AbstractHelperDialect dialect = urlDialectMap.get(dialectClass); if (dialect == null) { lock.lock(); try { if ((dialect = urlDialectMap.get(dialectClass)) == null) { dialect = instanceDialect(dialectClass, properties); urlDialectMap.put(dialectClass, dialect); } } finally { lock.unlock(); } } dialectThreadLocal.set(dialect); } else if (delegate == null) { if (autoDialect) { this.delegate = autoGetDialect(ms); } else { dialectThreadLocal.set(autoGetDialect(ms)); } } } /** * 自动获取分页方言实现 * * @param ms * @return */ public AbstractHelperDialect autoGetDialect(MappedStatement ms) { DataSource dataSource = ms.getConfiguration().getEnvironment().getDataSource(); Object dialectKey = autoDialectDelegate.extractDialectKey(ms, dataSource, properties); if (dialectKey == null) { return autoDialectDelegate.extractDialect(dialectKey, ms, dataSource, properties); } else if (!urlDialectMap.containsKey(dialectKey)) { lock.lock(); try { if (!urlDialectMap.containsKey(dialectKey)) { urlDialectMap.put(dialectKey, autoDialectDelegate.extractDialect(dialectKey, ms, dataSource, properties)); } } finally { lock.unlock(); } } return urlDialectMap.get(dialectKey); } /** * 初始化自定义 AutoDialect * * @param properties */ private void initAutoDialectClass(Properties properties) { String autoDialectClassStr = properties.getProperty("autoDialectClass"); if (StringUtil.isNotEmpty(autoDialectClassStr)) { try { Class<? extends AutoDialect> autoDialectClass; if (autoDialectMap.containsKey(autoDialectClassStr)) { autoDialectClass = autoDialectMap.get(autoDialectClassStr); } else { autoDialectClass = (Class<AutoDialect>) Class.forName(autoDialectClassStr); } this.autoDialectDelegate = ClassUtil.newInstance(autoDialectClass, properties); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Make sure that the AutoDialect implementation class (" + autoDialectClassStr + ") for the autoDialectClass configuration exists!", e); } catch (Exception e) { throw new RuntimeException(autoDialectClassStr + "Class must provide a constructor without parameters", e); } } else { this.autoDialectDelegate = new DataSourceNegotiationAutoDialect(); } } /** * 初始化方言别名 * * @param properties */ private void initDialectAlias(Properties properties) { String dialectAlias = properties.getProperty("dialectAlias"); if (StringUtil.isNotEmpty(dialectAlias)) { String[] alias = dialectAlias.split(";"); for (int i = 0; i < alias.length; i++) { String[] kv = alias[i].split("="); if (kv.length != 2) { throw new IllegalArgumentException("dialectAlias parameter misconfigured," + "Please follow alias1=xx.dialectClass; alias2=dialectClass2!"); } for (int j = 0; j < kv.length; j++) { try { //允许配置如 dm=oracle, 直接引用oracle实现 if (dialectAliasMap.containsKey(kv[1])) { registerDialectAlias(kv[0], dialectAliasMap.get(kv[1])); } else { Class<? extends Dialect> diallectClass = (Class<? extends Dialect>) Class.forName(kv[1]); //允许覆盖已有的实现 registerDialectAlias(kv[0], diallectClass); } } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Make sure the Dialect implementation class configured by dialectAlias exists!", e); } } } } } public void setProperties(Properties properties) { this.properties = properties; //初始化自定义AutoDialect initAutoDialectClass(properties); //使用 sqlserver2012 作为默认分页方式,这种情况在动态数据源时方便使用 String useSqlserver2012 = properties.getProperty("useSqlserver2012"); if (StringUtil.isNotEmpty(useSqlserver2012) && Boolean.parseBoolean(useSqlserver2012)) { registerDialectAlias("sqlserver", SqlServer2012Dialect.class); registerDialectAlias("sqlserver2008", SqlServerDialect.class); } initDialectAlias(properties); //指定的 Helper 数据库方言,和 不同 String dialect = properties.getProperty("helperDialect"); //运行时获取数据源 String runtimeDialect = properties.getProperty("autoRuntimeDialect"); //1.动态多数据源 if (StringUtil.isNotEmpty(runtimeDialect) && "TRUE".equalsIgnoreCase(runtimeDialect)) { this.autoDialect = false; } //2.动态获取方言 else if (StringUtil.isEmpty(dialect)) { autoDialect = true; } //3.指定方言 else { autoDialect = false; this.delegate = instanceDialect(dialect, properties); } } }
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/page/PageAutoDialect.java
703
/* * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dianping.cat.alarm.spi.decorator; import org.unidal.lookup.annotation.Inject; import org.unidal.lookup.util.StringUtils; import com.dianping.cat.Cat; import com.dianping.cat.core.dal.Project; import com.dianping.cat.service.ProjectService; public abstract class ProjectDecorator extends Decorator { @Inject protected ProjectService m_projectService; public String buildContactInfo(String domainName) { try { Project project = m_projectService.findByDomain(domainName); if (project != null) { String owners = project.getOwner(); String phones = project.getPhone(); StringBuilder builder = new StringBuilder(); if (!StringUtils.isEmpty(owners)) { builder.append("[业务负责人: ").append(owners).append(" ]"); } if (!StringUtils.isEmpty(phones)) { builder.append("[负责人手机号码: ").append(phones).append(" ]"); } return builder.toString(); } } catch (Exception ex) { Cat.logError("build project contact info error for domain: " + domainName, ex); } return ""; } }
dianping/cat
cat-alarm/src/main/java/com/dianping/cat/alarm/spi/decorator/ProjectDecorator.java
711
package com.macro.mall.model; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; public class PmsProductVertifyRecord implements Serializable { private Long id; private Long productId; private Date createTime; @ApiModelProperty(value = "审核人") private String vertifyMan; private Integer status; @ApiModelProperty(value = "反馈详情") private String detail; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getVertifyMan() { return vertifyMan; } public void setVertifyMan(String vertifyMan) { this.vertifyMan = vertifyMan; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", createTime=").append(createTime); sb.append(", vertifyMan=").append(vertifyMan); sb.append(", status=").append(status); sb.append(", detail=").append(detail); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/model/PmsProductVertifyRecord.java
712
package cn.hutool.extra.mail; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.io.IoUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.StrUtil; import javax.mail.Authenticator; import javax.mail.Session; import java.io.File; import java.io.InputStream; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * 邮件工具类,基于javax.mail封装 * * @author looly * @since 3.1.2 */ public class MailUtil { /** * 使用配置文件中设置的账户发送文本邮件,发送给单个或多个收件人<br> * 多个收件人可以使用逗号“,”分隔,也可以通过分号“;”分隔 * * @param to 收件人 * @param subject 标题 * @param content 正文 * @param files 附件列表 * @return message-id * @since 3.2.0 */ public static String sendText(String to, String subject, String content, File... files) { return send(to, subject, content, false, files); } /** * 使用配置文件中设置的账户发送HTML邮件,发送给单个或多个收件人<br> * 多个收件人可以使用逗号“,”分隔,也可以通过分号“;”分隔 * * @param to 收件人 * @param subject 标题 * @param content 正文 * @param files 附件列表 * @return message-id * @since 3.2.0 */ public static String sendHtml(String to, String subject, String content, File... files) { return send(to, subject, content, true, files); } /** * 使用配置文件中设置的账户发送邮件,发送单个或多个收件人<br> * 多个收件人可以使用逗号“,”分隔,也可以通过分号“;”分隔 * * @param to 收件人 * @param subject 标题 * @param content 正文 * @param isHtml 是否为HTML * @param files 附件列表 * @return message-id */ public static String send(String to, String subject, String content, boolean isHtml, File... files) { return send(splitAddress(to), subject, content, isHtml, files); } /** * 使用配置文件中设置的账户发送邮件,发送单个或多个收件人<br> * 多个收件人、抄送人、密送人可以使用逗号“,”分隔,也可以通过分号“;”分隔 * * @param to 收件人,可以使用逗号“,”分隔,也可以通过分号“;”分隔 * @param cc 抄送人,可以使用逗号“,”分隔,也可以通过分号“;”分隔 * @param bcc 密送人,可以使用逗号“,”分隔,也可以通过分号“;”分隔 * @param subject 标题 * @param content 正文 * @param isHtml 是否为HTML * @param files 附件列表 * @return message-id * @since 4.0.3 */ public static String send(String to, String cc, String bcc, String subject, String content, boolean isHtml, File... files) { return send(splitAddress(to), splitAddress(cc), splitAddress(bcc), subject, content, isHtml, files); } /** * 使用配置文件中设置的账户发送文本邮件,发送给多人 * * @param tos 收件人列表 * @param subject 标题 * @param content 正文 * @param files 附件列表 * @return message-id */ public static String sendText(Collection<String> tos, String subject, String content, File... files) { return send(tos, subject, content, false, files); } /** * 使用配置文件中设置的账户发送HTML邮件,发送给多人 * * @param tos 收件人列表 * @param subject 标题 * @param content 正文 * @param files 附件列表 * @return message-id * @since 3.2.0 */ public static String sendHtml(Collection<String> tos, String subject, String content, File... files) { return send(tos, subject, content, true, files); } /** * 使用配置文件中设置的账户发送邮件,发送给多人 * * @param tos 收件人列表 * @param subject 标题 * @param content 正文 * @param isHtml 是否为HTML * @param files 附件列表 * @return message-id */ public static String send(Collection<String> tos, String subject, String content, boolean isHtml, File... files) { return send(tos, null, null, subject, content, isHtml, files); } /** * 使用配置文件中设置的账户发送邮件,发送给多人 * * @param tos 收件人列表 * @param ccs 抄送人列表,可以为null或空 * @param bccs 密送人列表,可以为null或空 * @param subject 标题 * @param content 正文 * @param isHtml 是否为HTML * @param files 附件列表 * @return message-id * @since 4.0.3 */ public static String send(Collection<String> tos, Collection<String> ccs, Collection<String> bccs, String subject, String content, boolean isHtml, File... files) { return send(GlobalMailAccount.INSTANCE.getAccount(), true, tos, ccs, bccs, subject, content, null, isHtml, files); } // ------------------------------------------------------------------------------------------------------------------------------- Custom MailAccount /** * 发送邮件给多人 * * @param mailAccount 邮件认证对象 * @param to 收件人,多个收件人逗号或者分号隔开 * @param subject 标题 * @param content 正文 * @param isHtml 是否为HTML格式 * @param files 附件列表 * @return message-id * @since 3.2.0 */ public static String send(MailAccount mailAccount, String to, String subject, String content, boolean isHtml, File... files) { return send(mailAccount, splitAddress(to), subject, content, isHtml, files); } /** * 发送邮件给多人 * * @param mailAccount 邮件帐户信息 * @param tos 收件人列表 * @param subject 标题 * @param content 正文 * @param isHtml 是否为HTML格式 * @param files 附件列表 * @return message-id */ public static String send(MailAccount mailAccount, Collection<String> tos, String subject, String content, boolean isHtml, File... files) { return send(mailAccount, tos, null, null, subject, content, isHtml, files); } /** * 发送邮件给多人 * * @param mailAccount 邮件帐户信息 * @param tos 收件人列表 * @param ccs 抄送人列表,可以为null或空 * @param bccs 密送人列表,可以为null或空 * @param subject 标题 * @param content 正文 * @param isHtml 是否为HTML格式 * @param files 附件列表 * @return message-id * @since 4.0.3 */ public static String send(MailAccount mailAccount, Collection<String> tos, Collection<String> ccs, Collection<String> bccs, String subject, String content, boolean isHtml, File... files) { return send(mailAccount, false, tos, ccs, bccs, subject, content, null, isHtml, files); } /** * 使用配置文件中设置的账户发送HTML邮件,发送给单个或多个收件人<br> * 多个收件人可以使用逗号“,”分隔,也可以通过分号“;”分隔 * * @param to 收件人 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:$IMAGE_PLACEHOLDER * @param files 附件列表 * @return message-id * @since 3.2.0 */ public static String sendHtml(String to, String subject, String content, Map<String, InputStream> imageMap, File... files) { return send(to, subject, content, imageMap, true, files); } /** * 使用配置文件中设置的账户发送邮件,发送单个或多个收件人<br> * 多个收件人可以使用逗号“,”分隔,也可以通过分号“;”分隔 * * @param to 收件人 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:$IMAGE_PLACEHOLDER * @param isHtml 是否为HTML * @param files 附件列表 * @return message-id */ public static String send(String to, String subject, String content, Map<String, InputStream> imageMap, boolean isHtml, File... files) { return send(splitAddress(to), subject, content, imageMap, isHtml, files); } /** * 使用配置文件中设置的账户发送邮件,发送单个或多个收件人<br> * 多个收件人、抄送人、密送人可以使用逗号“,”分隔,也可以通过分号“;”分隔 * * @param to 收件人,可以使用逗号“,”分隔,也可以通过分号“;”分隔 * @param cc 抄送人,可以使用逗号“,”分隔,也可以通过分号“;”分隔 * @param bcc 密送人,可以使用逗号“,”分隔,也可以通过分号“;”分隔 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:$IMAGE_PLACEHOLDER * @param isHtml 是否为HTML * @param files 附件列表 * @return message-id * @since 4.0.3 */ public static String send(String to, String cc, String bcc, String subject, String content, Map<String, InputStream> imageMap, boolean isHtml, File... files) { return send(splitAddress(to), splitAddress(cc), splitAddress(bcc), subject, content, imageMap, isHtml, files); } /** * 使用配置文件中设置的账户发送HTML邮件,发送给多人 * * @param tos 收件人列表 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:$IMAGE_PLACEHOLDER * @param files 附件列表 * @return message-id * @since 3.2.0 */ public static String sendHtml(Collection<String> tos, String subject, String content, Map<String, InputStream> imageMap, File... files) { return send(tos, subject, content, imageMap, true, files); } /** * 使用配置文件中设置的账户发送邮件,发送给多人 * * @param tos 收件人列表 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:$IMAGE_PLACEHOLDER * @param isHtml 是否为HTML * @param files 附件列表 * @return message-id */ public static String send(Collection<String> tos, String subject, String content, Map<String, InputStream> imageMap, boolean isHtml, File... files) { return send(tos, null, null, subject, content, imageMap, isHtml, files); } /** * 使用配置文件中设置的账户发送邮件,发送给多人 * * @param tos 收件人列表 * @param ccs 抄送人列表,可以为null或空 * @param bccs 密送人列表,可以为null或空 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:$IMAGE_PLACEHOLDER * @param isHtml 是否为HTML * @param files 附件列表 * @return message-id * @since 4.0.3 */ public static String send(Collection<String> tos, Collection<String> ccs, Collection<String> bccs, String subject, String content, Map<String, InputStream> imageMap, boolean isHtml, File... files) { return send(GlobalMailAccount.INSTANCE.getAccount(), true, tos, ccs, bccs, subject, content, imageMap, isHtml, files); } // ------------------------------------------------------------------------------------------------------------------------------- Custom MailAccount /** * 发送邮件给多人 * * @param mailAccount 邮件认证对象 * @param to 收件人,多个收件人逗号或者分号隔开 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:$IMAGE_PLACEHOLDER * @param isHtml 是否为HTML格式 * @param files 附件列表 * @return message-id * @since 3.2.0 */ public static String send(MailAccount mailAccount, String to, String subject, String content, Map<String, InputStream> imageMap, boolean isHtml, File... files) { return send(mailAccount, splitAddress(to), subject, content, imageMap, isHtml, files); } /** * 发送邮件给多人 * * @param mailAccount 邮件帐户信息 * @param tos 收件人列表 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:$IMAGE_PLACEHOLDER * @param isHtml 是否为HTML格式 * @param files 附件列表 * @return message-id * @since 4.6.3 */ public static String send(MailAccount mailAccount, Collection<String> tos, String subject, String content, Map<String, InputStream> imageMap, boolean isHtml, File... files) { return send(mailAccount, tos, null, null, subject, content, imageMap, isHtml, files); } /** * 发送邮件给多人 * * @param mailAccount 邮件帐户信息 * @param tos 收件人列表 * @param ccs 抄送人列表,可以为null或空 * @param bccs 密送人列表,可以为null或空 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:$IMAGE_PLACEHOLDER * @param isHtml 是否为HTML格式 * @param files 附件列表 * @return message-id * @since 4.6.3 */ public static String send(MailAccount mailAccount, Collection<String> tos, Collection<String> ccs, Collection<String> bccs, String subject, String content, Map<String, InputStream> imageMap, boolean isHtml, File... files) { return send(mailAccount, false, tos, ccs, bccs, subject, content, imageMap, isHtml, files); } /** * 根据配置文件,获取邮件客户端会话 * * @param mailAccount 邮件账户配置 * @param isSingleton 是否单例(全局共享会话) * @return {@link Session} * @since 5.5.7 */ public static Session getSession(MailAccount mailAccount, boolean isSingleton) { Authenticator authenticator = null; if (mailAccount.isAuth()) { authenticator = new UserPassAuthenticator(mailAccount.getUser(), mailAccount.getPass()); } return isSingleton ? Session.getDefaultInstance(mailAccount.getSmtpProps(), authenticator) // : Session.getInstance(mailAccount.getSmtpProps(), authenticator); } // ------------------------------------------------------------------------------------------------------------------------ Private method start /** * 发送邮件给多人 * * @param mailAccount 邮件帐户信息 * @param useGlobalSession 是否全局共享Session * @param tos 收件人列表 * @param ccs 抄送人列表,可以为null或空 * @param bccs 密送人列表,可以为null或空 * @param subject 标题 * @param content 正文 * @param imageMap 图片与占位符,占位符格式为cid:${cid} * @param isHtml 是否为HTML格式 * @param files 附件列表 * @return message-id * @since 4.6.3 */ private static String send(MailAccount mailAccount, boolean useGlobalSession, Collection<String> tos, Collection<String> ccs, Collection<String> bccs, String subject, String content, Map<String, InputStream> imageMap, boolean isHtml, File... files) { final Mail mail = Mail.create(mailAccount).setUseGlobalSession(useGlobalSession); // 可选抄送人 if (CollUtil.isNotEmpty(ccs)) { mail.setCcs(ccs.toArray(new String[0])); } // 可选密送人 if (CollUtil.isNotEmpty(bccs)) { mail.setBccs(bccs.toArray(new String[0])); } mail.setTos(tos.toArray(new String[0])); mail.setTitle(subject); mail.setContent(content); mail.setHtml(isHtml); mail.setFiles(files); // 图片 if (MapUtil.isNotEmpty(imageMap)) { for (Entry<String, InputStream> entry : imageMap.entrySet()) { mail.addImage(entry.getKey(), entry.getValue()); // 关闭流 IoUtil.close(entry.getValue()); } } return mail.send(); } /** * 将多个联系人转为列表,分隔符为逗号或者分号 * * @param addresses 多个联系人,如果为空返回null * @return 联系人列表 */ private static List<String> splitAddress(String addresses) { if (StrUtil.isBlank(addresses)) { return null; } List<String> result; if (StrUtil.contains(addresses, CharUtil.COMMA)) { result = StrUtil.splitTrim(addresses, CharUtil.COMMA); } else if (StrUtil.contains(addresses, ';')) { result = StrUtil.splitTrim(addresses, ';'); } else { result = CollUtil.newArrayList(addresses); } return result; } // ------------------------------------------------------------------------------------------------------------------------ Private method end }
dromara/hutool
hutool-extra/src/main/java/cn/hutool/extra/mail/MailUtil.java
713
package cn.hutool.crypto.symmetric; /** * 维吉尼亚密码实现。<br> * 人们在恺撒移位密码的基础上扩展出多表密码,称为维吉尼亚密码。<br> * 算法实现来自:https://github.com/zhaorenjie110/SymmetricEncryptionAndDecryption * * @author looly,zhaorenjie110 * @since 4.4.1 */ public class Vigenere { /** * 加密 * * @param data 数据 * @param cipherKey 密钥 * @return 密文 */ public static String encrypt(CharSequence data, CharSequence cipherKey) { final int dataLen = data.length(); final int cipherKeyLen = cipherKey.length(); final char[] cipherArray = new char[dataLen]; for (int i = 0; i < dataLen / cipherKeyLen + 1; i++) { for (int t = 0; t < cipherKeyLen; t++) { if (t + i * cipherKeyLen < dataLen) { final char dataChar = data.charAt(t + i * cipherKeyLen); final char cipherKeyChar = cipherKey.charAt(t); cipherArray[t + i * cipherKeyLen] = (char) ((dataChar + cipherKeyChar - 64) % 95 + 32); } } } return String.valueOf(cipherArray); } /** * 解密 * * @param data 密文 * @param cipherKey 密钥 * @return 明文 */ public static String decrypt(CharSequence data, CharSequence cipherKey) { final int dataLen = data.length(); final int cipherKeyLen = cipherKey.length(); final char[] clearArray = new char[dataLen]; for (int i = 0; i < dataLen; i++) { for (int t = 0; t < cipherKeyLen; t++) { if (t + i * cipherKeyLen < dataLen) { final char dataChar = data.charAt(t + i * cipherKeyLen); final char cipherKeyChar = cipherKey.charAt(t); if (dataChar - cipherKeyChar >= 0) { clearArray[t + i * cipherKeyLen] = (char) ((dataChar - cipherKeyChar) % 95 + 32); } else { clearArray[t + i * cipherKeyLen] = (char) ((dataChar - cipherKeyChar + 95) % 95 + 32); } } } } return String.valueOf(clearArray); } }
dromara/hutool
hutool-crypto/src/main/java/cn/hutool/crypto/symmetric/Vigenere.java
714
/* * Copyright 1999-2017 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.fastjson.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.PropertyNamingStrategy; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.JSONScanner; import com.alibaba.fastjson.parser.ParserConfig; import com.alibaba.fastjson.parser.deserializer.EnumDeserializer; import com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.alibaba.fastjson.serializer.CalendarCodec; import com.alibaba.fastjson.serializer.SerializeBeanInfo; import com.alibaba.fastjson.serializer.SerializerFeature; import java.io.InputStream; import java.io.Reader; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Clob; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author wenshao[[email protected]] */ public class TypeUtils { private static final Pattern NUMBER_WITH_TRAILING_ZEROS_PATTERN = Pattern.compile("\\.0*$"); public static boolean compatibleWithJavaBean = false; /** * 根据field name的大小写输出输入数据 */ public static boolean compatibleWithFieldName = false; private static boolean setAccessibleEnable = true; private static boolean oracleTimestampMethodInited = false; private static Method oracleTimestampMethod; private static boolean oracleDateMethodInited = false; private static Method oracleDateMethod; private static boolean optionalClassInited = false; private static Class<?> optionalClass; private static boolean transientClassInited = false; private static Class<? extends Annotation> transientClass; private static Class<? extends Annotation> class_OneToMany = null; private static boolean class_OneToMany_error = false; private static Class<? extends Annotation> class_ManyToMany = null; private static boolean class_ManyToMany_error = false; private static Method method_HibernateIsInitialized = null; private static boolean method_HibernateIsInitialized_error = false; private static volatile Class kotlin_metadata; private static volatile boolean kotlin_metadata_error; private static volatile boolean kotlin_class_klass_error; private static volatile Constructor kotlin_kclass_constructor; private static volatile Method kotlin_kclass_getConstructors; private static volatile Method kotlin_kfunction_getParameters; private static volatile Method kotlin_kparameter_getName; private static volatile boolean kotlin_error; private static volatile Map<Class, String[]> kotlinIgnores; private static volatile boolean kotlinIgnores_error; private static ConcurrentMap<String, Class<?>> mappings = new ConcurrentHashMap<String, Class<?>>(256, 0.75f, 1); private static Class<?> pathClass; private static boolean pathClass_error = false; private static Class<? extends Annotation> class_JacksonCreator = null; private static boolean class_JacksonCreator_error = false; private static volatile Class class_XmlAccessType = null; private static volatile Class class_XmlAccessorType = null; private static volatile boolean classXmlAccessorType_error = false; private static volatile Method method_XmlAccessorType_value = null; private static volatile Field field_XmlAccessType_FIELD = null; private static volatile Object field_XmlAccessType_FIELD_VALUE = null; private static Class class_deque = null; static { try { TypeUtils.compatibleWithJavaBean = "true".equals(IOUtils.getStringProperty(IOUtils.FASTJSON_COMPATIBLEWITHJAVABEAN)); TypeUtils.compatibleWithFieldName = "true".equals(IOUtils.getStringProperty(IOUtils.FASTJSON_COMPATIBLEWITHFIELDNAME)); } catch (Throwable e) { // skip } try { class_deque = Class.forName("java.util.Deque"); } catch (Throwable e) { // skip } } public static boolean isXmlField(Class clazz) { if (class_XmlAccessorType == null && !classXmlAccessorType_error) { try { class_XmlAccessorType = Class.forName("javax.xml.bind.annotation.XmlAccessorType"); } catch (Throwable ex) { classXmlAccessorType_error = true; } } if (class_XmlAccessorType == null) { return false; } Annotation annotation = TypeUtils.getAnnotation(clazz, class_XmlAccessorType); if (annotation == null) { return false; } if (method_XmlAccessorType_value == null && !classXmlAccessorType_error) { try { method_XmlAccessorType_value = class_XmlAccessorType.getMethod("value"); } catch (Throwable ex) { classXmlAccessorType_error = true; } } if (method_XmlAccessorType_value == null) { return false; } Object value = null; if (!classXmlAccessorType_error) { try { value = method_XmlAccessorType_value.invoke(annotation); } catch (Throwable ex) { classXmlAccessorType_error = true; } } if (value == null) { return false; } if (class_XmlAccessType == null && !classXmlAccessorType_error) { try { class_XmlAccessType = Class.forName("javax.xml.bind.annotation.XmlAccessType"); field_XmlAccessType_FIELD = class_XmlAccessType.getField("FIELD"); field_XmlAccessType_FIELD_VALUE = field_XmlAccessType_FIELD.get(null); } catch (Throwable ex) { classXmlAccessorType_error = true; } } return value == field_XmlAccessType_FIELD_VALUE; } public static Annotation getXmlAccessorType(Class clazz) { if (class_XmlAccessorType == null && !classXmlAccessorType_error) { try { class_XmlAccessorType = Class.forName("javax.xml.bind.annotation.XmlAccessorType"); } catch (Throwable ex) { classXmlAccessorType_error = true; } } if (class_XmlAccessorType == null) { return null; } return TypeUtils.getAnnotation(clazz, class_XmlAccessorType); } // // public static boolean isXmlAccessType(Class clazz) { // if (class_XmlAccessType == null && !class_XmlAccessType_error) { // // try{ // class_XmlAccessType = Class.forName("javax.xml.bind.annotation.XmlAccessType"); // } catch(Throwable ex){ // class_XmlAccessType_error = true; // } // } // // if (class_XmlAccessType == null) { // return false; // } // // return class_XmlAccessType.isAssignableFrom(clazz); // } private static Function<Class, Boolean> isClobFunction = new Function<Class, Boolean>() { public Boolean apply(Class clazz) { return Clob.class.isAssignableFrom(clazz); } }; public static boolean isClob(final Class clazz) { Boolean isClob = ModuleUtil.callWhenHasJavaSql(isClobFunction, clazz); return isClob != null ? isClob : false; } public static String castToString(Object value) { if (value == null) { return null; } return value.toString(); } public static Byte castToByte(Object value) { if (value == null) { return null; } if (value instanceof BigDecimal) { return byteValue((BigDecimal) value); } if (value instanceof Number) { return ((Number) value).byteValue(); } if (value instanceof String) { String strVal = (String) value; if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } return Byte.parseByte(strVal); } if (value instanceof Boolean) { return (Boolean) value ? (byte) 1 : (byte) 0; } throw new JSONException("can not cast to byte, value : " + value); } public static Character castToChar(Object value) { if (value == null) { return null; } if (value instanceof Character) { return (Character) value; } if (value instanceof String) { String strVal = (String) value; if (strVal.length() == 0) { return null; } if (strVal.length() != 1) { throw new JSONException("can not cast to char, value : " + value); } return strVal.charAt(0); } throw new JSONException("can not cast to char, value : " + value); } public static Short castToShort(Object value) { if (value == null) { return null; } if (value instanceof BigDecimal) { return shortValue((BigDecimal) value); } if (value instanceof Number) { return ((Number) value).shortValue(); } if (value instanceof String) { String strVal = (String) value; if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } return Short.parseShort(strVal); } if (value instanceof Boolean) { return ((Boolean) value).booleanValue() ? (short) 1 : (short) 0; } throw new JSONException("can not cast to short, value : " + value); } public static BigDecimal castToBigDecimal(Object value) { if (value == null) { return null; } if (value instanceof Float) { if (Float.isNaN((Float) value) || Float.isInfinite((Float) value)) { return null; } } else if (value instanceof Double) { if (Double.isNaN((Double) value) || Double.isInfinite((Double) value)) { return null; } } else if (value instanceof BigDecimal) { return (BigDecimal) value; } else if (value instanceof BigInteger) { return new BigDecimal((BigInteger) value); } else if (value instanceof Map && ((Map) value).size() == 0) { return null; } String strVal = value.toString(); if (strVal.length() == 0 || strVal.equalsIgnoreCase("null")) { return null; } if (strVal.length() > 65535) { throw new JSONException("decimal overflow"); } return new BigDecimal(strVal); } public static BigInteger castToBigInteger(Object value) { if (value == null) { return null; } if (value instanceof Float) { Float floatValue = (Float) value; if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { return null; } return BigInteger.valueOf(floatValue.longValue()); } else if (value instanceof Double) { Double doubleValue = (Double) value; if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { return null; } return BigInteger.valueOf(doubleValue.longValue()); } else if (value instanceof BigInteger) { return (BigInteger) value; } else if (value instanceof BigDecimal) { BigDecimal decimal = (BigDecimal) value; int scale = decimal.scale(); if (scale > -1000 && scale < 1000) { return ((BigDecimal) value).toBigInteger(); } } String strVal = value.toString(); if (strVal.length() == 0 || strVal.equalsIgnoreCase("null")) { return null; } if (strVal.length() > 65535) { throw new JSONException("decimal overflow"); } return new BigInteger(strVal); } public static Float castToFloat(Object value) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).floatValue(); } if (value instanceof String) { String strVal = value.toString(); if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } if (strVal.indexOf(',') != -1) { strVal = strVal.replaceAll(",", ""); } return Float.parseFloat(strVal); } if (value instanceof Boolean) { return (Boolean) value ? 1F : 0F; } throw new JSONException("can not cast to float, value : " + value); } public static Double castToDouble(Object value) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).doubleValue(); } if (value instanceof String) { String strVal = value.toString(); if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } if (strVal.indexOf(',') != -1) { strVal = strVal.replaceAll(",", ""); } return Double.parseDouble(strVal); } if (value instanceof Boolean) { return (Boolean) value ? 1D : 0D; } throw new JSONException("can not cast to double, value : " + value); } public static Date castToDate(Object value) { return castToDate(value, null); } public static Date castToDate(Object value, String format) { if (value == null) { return null; } if (value instanceof Date) { // 使用频率最高的,应优先处理 return (Date) value; } if (value instanceof Calendar) { return ((Calendar) value).getTime(); } long longValue = -1; if (value instanceof BigDecimal) { longValue = longValue((BigDecimal) value); return new Date(longValue); } if (value instanceof Number) { longValue = ((Number) value).longValue(); if ("unixtime".equals(format)) { longValue *= 1000; } return new Date(longValue); } if (value instanceof String) { String strVal = (String) value; JSONScanner dateLexer = new JSONScanner(strVal); try { if (dateLexer.scanISO8601DateIfMatch(false)) { Calendar calendar = dateLexer.getCalendar(); return calendar.getTime(); } } finally { dateLexer.close(); } if (strVal.startsWith("/Date(") && strVal.endsWith(")/")) { strVal = strVal.substring(6, strVal.length() - 2); } if (strVal.indexOf('-') > 0 || strVal.indexOf('+') > 0 || format != null) { if (format == null) { final int len = strVal.length(); if (len == JSON.DEFFAULT_DATE_FORMAT.length() || (len == 22 && JSON.DEFFAULT_DATE_FORMAT.equals("yyyyMMddHHmmssSSSZ"))) { format = JSON.DEFFAULT_DATE_FORMAT; } else if (len == 10) { format = "yyyy-MM-dd"; } else if (len == "yyyy-MM-dd HH:mm:ss".length()) { format = "yyyy-MM-dd HH:mm:ss"; } else if (len == 29 && strVal.charAt(26) == ':' && strVal.charAt(28) == '0') { format = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; } else if (len == 23 && strVal.charAt(19) == ',') { format = "yyyy-MM-dd HH:mm:ss,SSS"; } else { format = "yyyy-MM-dd HH:mm:ss.SSS"; } } SimpleDateFormat dateFormat = new SimpleDateFormat(format, JSON.defaultLocale); dateFormat.setTimeZone(JSON.defaultTimeZone); try { return dateFormat.parse(strVal); } catch (ParseException e) { throw new JSONException("can not cast to Date, value : " + strVal); } } if (strVal.length() == 0) { return null; } longValue = Long.parseLong(strVal); } if (longValue == -1) { Class<?> clazz = value.getClass(); if ("oracle.sql.TIMESTAMP".equals(clazz.getName())) { if (oracleTimestampMethod == null && !oracleTimestampMethodInited) { try { oracleTimestampMethod = clazz.getMethod("toJdbc"); } catch (NoSuchMethodException e) { // skip } finally { oracleTimestampMethodInited = true; } } Object result; try { result = oracleTimestampMethod.invoke(value); } catch (Exception e) { throw new JSONException("can not cast oracle.sql.TIMESTAMP to Date", e); } return (Date) result; } if ("oracle.sql.DATE".equals(clazz.getName())) { if (oracleDateMethod == null && !oracleDateMethodInited) { try { oracleDateMethod = clazz.getMethod("toJdbc"); } catch (NoSuchMethodException e) { // skip } finally { oracleDateMethodInited = true; } } Object result; try { result = oracleDateMethod.invoke(value); } catch (Exception e) { throw new JSONException("can not cast oracle.sql.DATE to Date", e); } return (Date) result; } throw new JSONException("can not cast to Date, value : " + value); } return new Date(longValue); } private static Function<Object, Object> castToSqlDateFunction = new Function<Object, Object>() { public Object apply(Object value) { if (value == null) { return null; } if (value instanceof java.sql.Date) { return (java.sql.Date) value; } if (value instanceof Date) { return new java.sql.Date(((Date) value).getTime()); } if (value instanceof Calendar) { return new java.sql.Date(((Calendar) value).getTimeInMillis()); } long longValue = 0; if (value instanceof BigDecimal) { longValue = longValue((BigDecimal) value); } else if (value instanceof Number) { longValue = ((Number) value).longValue(); } if (value instanceof String) { String strVal = (String) value; if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } if (isNumber(strVal)) { longValue = Long.parseLong(strVal); } else { JSONScanner scanner = new JSONScanner(strVal); if (scanner.scanISO8601DateIfMatch(false)) { longValue = scanner.getCalendar().getTime().getTime(); } else { throw new JSONException("can not cast to Timestamp, value : " + strVal); } } } if (longValue <= 0) { throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理? } return new java.sql.Date(longValue); } }; public static Object castToSqlDate(final Object value) { return ModuleUtil.callWhenHasJavaSql(castToSqlDateFunction, value); } public static long longExtractValue(Number number) { if (number instanceof BigDecimal) { return ((BigDecimal) number).longValueExact(); } return number.longValue(); } private static Function<Object, Object> castToSqlTimeFunction = new Function<Object, Object>() { public Object apply(Object value) { if (value == null) { return null; } if (value instanceof java.sql.Time) { return (java.sql.Time) value; } if (value instanceof java.util.Date) { return new java.sql.Time(((java.util.Date) value).getTime()); } if (value instanceof Calendar) { return new java.sql.Time(((Calendar) value).getTimeInMillis()); } long longValue = 0; if (value instanceof BigDecimal) { longValue = longValue((BigDecimal) value); } else if (value instanceof Number) { longValue = ((Number) value).longValue(); } if (value instanceof String) { String strVal = (String) value; if (strVal.length() == 0 // || "null".equalsIgnoreCase(strVal)) { return null; } if (isNumber(strVal)) { longValue = Long.parseLong(strVal); } else { if (strVal.length() == 8 && strVal.charAt(2) == ':' && strVal.charAt(5) == ':') { return java.sql.Time.valueOf(strVal); } JSONScanner scanner = new JSONScanner(strVal); if (scanner.scanISO8601DateIfMatch(false)) { longValue = scanner.getCalendar().getTime().getTime(); } else { throw new JSONException("can not cast to Timestamp, value : " + strVal); } } } if (longValue <= 0) { throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理? } return new java.sql.Time(longValue); } }; public static Object castToSqlTime(final Object value) { return ModuleUtil.callWhenHasJavaSql(castToSqlTimeFunction, value); } public static Function<Object, Object> castToTimestampFunction = new Function<Object, Object>() { public Object apply(Object value) { if (value == null) { return null; } if (value instanceof Calendar) { return new java.sql.Timestamp(((Calendar) value).getTimeInMillis()); } if (value instanceof java.sql.Timestamp) { return (java.sql.Timestamp) value; } if (value instanceof java.util.Date) { return new java.sql.Timestamp(((java.util.Date) value).getTime()); } long longValue = 0; if (value instanceof BigDecimal) { longValue = longValue((BigDecimal) value); } else if (value instanceof Number) { longValue = ((Number) value).longValue(); } if (value instanceof String) { String strVal = (String) value; if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } if (strVal.endsWith(".000000000")) { strVal = strVal.substring(0, strVal.length() - 10); } else if (strVal.endsWith(".000000")) { strVal = strVal.substring(0, strVal.length() - 7); } if (strVal.length() == 29 && strVal.charAt(4) == '-' && strVal.charAt(7) == '-' && strVal.charAt(10) == ' ' && strVal.charAt(13) == ':' && strVal.charAt(16) == ':' && strVal.charAt(19) == '.') { int year = num( strVal.charAt(0), strVal.charAt(1), strVal.charAt(2), strVal.charAt(3)); int month = num( strVal.charAt(5), strVal.charAt(6)); int day = num( strVal.charAt(8), strVal.charAt(9)); int hour = num( strVal.charAt(11), strVal.charAt(12)); int minute = num( strVal.charAt(14), strVal.charAt(15)); int second = num( strVal.charAt(17), strVal.charAt(18)); int nanos = num( strVal.charAt(20), strVal.charAt(21), strVal.charAt(22), strVal.charAt(23), strVal.charAt(24), strVal.charAt(25), strVal.charAt(26), strVal.charAt(27), strVal.charAt(28)); return new java.sql.Timestamp(year - 1900, month - 1, day, hour, minute, second, nanos); } if (isNumber(strVal)) { longValue = Long.parseLong(strVal); } else { JSONScanner scanner = new JSONScanner(strVal); if (scanner.scanISO8601DateIfMatch(false)) { longValue = scanner.getCalendar().getTime().getTime(); } else { throw new JSONException("can not cast to Timestamp, value : " + strVal); } } } return new java.sql.Timestamp(longValue); } }; public static Object castToTimestamp(final Object value) { return ModuleUtil.callWhenHasJavaSql(castToTimestampFunction, value); } static int num(char c0, char c1) { if (c0 >= '0' && c0 <= '9' && c1 >= '0' && c1 <= '9' ) { return (c0 - '0') * 10 + (c1 - '0'); } return -1; } static int num(char c0, char c1, char c2, char c3) { if (c0 >= '0' && c0 <= '9' && c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9' && c3 >= '0' && c3 <= '9' ) { return (c0 - '0') * 1000 + (c1 - '0') * 100 + (c2 - '0') * 10 + (c3 - '0'); } return -1; } static int num(char c0, char c1, char c2, char c3, char c4, char c5, char c6, char c7, char c8) { if (c0 >= '0' && c0 <= '9' && c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9' && c3 >= '0' && c3 <= '9' && c4 >= '0' && c4 <= '9' && c5 >= '0' && c5 <= '9' && c6 >= '0' && c6 <= '9' && c7 >= '0' && c7 <= '9' && c8 >= '0' && c8 <= '9' ) { return (c0 - '0') * 100000000 + (c1 - '0') * 10000000 + (c2 - '0') * 1000000 + (c3 - '0') * 100000 + (c4 - '0') * 10000 + (c5 - '0') * 1000 + (c6 - '0') * 100 + (c7 - '0') * 10 + (c8 - '0'); } return -1; } public static boolean isNumber(String str) { for (int i = 0; i < str.length(); ++i) { char ch = str.charAt(i); if (ch == '+' || ch == '-') { if (i != 0) { return false; } } else if (ch < '0' || ch > '9') { return false; } } return true; } public static Long castToLong(Object value) { if (value == null) { return null; } if (value instanceof BigDecimal) { return longValue((BigDecimal) value); } if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof String) { String strVal = (String) value; if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } if (strVal.indexOf(',') != -1) { strVal = strVal.replaceAll(",", ""); } try { return Long.parseLong(strVal); } catch (NumberFormatException ex) { // } JSONScanner dateParser = new JSONScanner(strVal); Calendar calendar = null; if (dateParser.scanISO8601DateIfMatch(false)) { calendar = dateParser.getCalendar(); } dateParser.close(); if (calendar != null) { return calendar.getTimeInMillis(); } } if (value instanceof Map) { Map map = (Map) value; if (map.size() == 2 && map.containsKey("andIncrement") && map.containsKey("andDecrement")) { Iterator iter = map.values().iterator(); iter.next(); Object value2 = iter.next(); return castToLong(value2); } } if (value instanceof Boolean) { return (Boolean) value ? 1L : 0L; } throw new JSONException("can not cast to long, value : " + value); } public static byte byteValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.byteValue(); } return decimal.byteValueExact(); } public static short shortValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.shortValue(); } return decimal.shortValueExact(); } public static int intValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.intValue(); } return decimal.intValueExact(); } public static long longValue(BigDecimal decimal) { if (decimal == null) { return 0; } int scale = decimal.scale(); if (scale >= -100 && scale <= 100) { return decimal.longValue(); } return decimal.longValueExact(); } public static Integer castToInt(Object value) { if (value == null) { return null; } if (value instanceof Integer) { return (Integer) value; } if (value instanceof BigDecimal) { return intValue((BigDecimal) value); } if (value instanceof Number) { return ((Number) value).intValue(); } if (value instanceof String) { String strVal = (String) value; if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } if (strVal.indexOf(',') != -1) { strVal = strVal.replaceAll(",", ""); } Matcher matcher = NUMBER_WITH_TRAILING_ZEROS_PATTERN.matcher(strVal); if (matcher.find()) { strVal = matcher.replaceAll(""); } return Integer.parseInt(strVal); } if (value instanceof Boolean) { return (Boolean) value ? 1 : 0; } if (value instanceof Map) { Map map = (Map) value; if (map.size() == 2 && map.containsKey("andIncrement") && map.containsKey("andDecrement")) { Iterator iter = map.values().iterator(); iter.next(); Object value2 = iter.next(); return castToInt(value2); } } throw new JSONException("can not cast to int, value : " + value); } public static byte[] castToBytes(Object value) { if (value instanceof byte[]) { return (byte[]) value; } if (value instanceof String) { return IOUtils.decodeBase64((String) value); } throw new JSONException("can not cast to byte[], value : " + value); } public static Boolean castToBoolean(Object value) { if (value == null) { return null; } if (value instanceof Boolean) { return (Boolean) value; } if (value instanceof BigDecimal) { return intValue((BigDecimal) value) == 1; } if (value instanceof Number) { return ((Number) value).intValue() == 1; } if (value instanceof String) { String strVal = (String) value; if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } if ("true".equalsIgnoreCase(strVal) // || "1".equals(strVal)) { return Boolean.TRUE; } if ("false".equalsIgnoreCase(strVal) // || "0".equals(strVal)) { return Boolean.FALSE; } if ("Y".equalsIgnoreCase(strVal) // || "T".equals(strVal)) { return Boolean.TRUE; } if ("F".equalsIgnoreCase(strVal) // || "N".equals(strVal)) { return Boolean.FALSE; } } throw new JSONException("can not cast to boolean, value : " + value); } public static <T> T castToJavaBean(Object obj, Class<T> clazz) { return cast(obj, clazz, ParserConfig.getGlobalInstance()); } private static BiFunction<Object, Class, Object> castFunction = new BiFunction<Object, Class, Object>() { public Object apply(Object obj, Class clazz) { if (clazz == java.sql.Date.class) { return castToSqlDate(obj); } if (clazz == java.sql.Time.class) { return castToSqlTime(obj); } if (clazz == java.sql.Timestamp.class) { return castToTimestamp(obj); } return null; } }; @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T cast(final Object obj, final Class<T> clazz, ParserConfig config) { if (obj == null) { if (clazz == int.class) { return (T) Integer.valueOf(0); } else if (clazz == long.class) { return (T) Long.valueOf(0); } else if (clazz == short.class) { return (T) Short.valueOf((short) 0); } else if (clazz == byte.class) { return (T) Byte.valueOf((byte) 0); } else if (clazz == float.class) { return (T) Float.valueOf(0); } else if (clazz == double.class) { return (T) Double.valueOf(0); } else if (clazz == boolean.class) { return (T) Boolean.FALSE; } return null; } if (clazz == null) { throw new IllegalArgumentException("clazz is null"); } if (clazz == obj.getClass()) { return (T) obj; } if (obj instanceof Map) { if (clazz == Map.class) { return (T) obj; } Map map = (Map) obj; if (clazz == Object.class && !map.containsKey(JSON.DEFAULT_TYPE_KEY)) { return (T) obj; } return castToJavaBean((Map<String, Object>) obj, clazz, config); } if (clazz.isArray()) { if (obj instanceof Collection) { Collection collection = (Collection) obj; int index = 0; Object array = Array.newInstance(clazz.getComponentType(), collection.size()); for (Object item : collection) { Object value = cast(item, clazz.getComponentType(), config); Array.set(array, index, value); index++; } return (T) array; } if (clazz == byte[].class) { return (T) castToBytes(obj); } } if (clazz.isAssignableFrom(obj.getClass())) { return (T) obj; } if (clazz == boolean.class || clazz == Boolean.class) { return (T) castToBoolean(obj); } if (clazz == byte.class || clazz == Byte.class) { return (T) castToByte(obj); } if (clazz == char.class || clazz == Character.class) { return (T) castToChar(obj); } if (clazz == short.class || clazz == Short.class) { return (T) castToShort(obj); } if (clazz == int.class || clazz == Integer.class) { return (T) castToInt(obj); } if (clazz == long.class || clazz == Long.class) { return (T) castToLong(obj); } if (clazz == float.class || clazz == Float.class) { return (T) castToFloat(obj); } if (clazz == double.class || clazz == Double.class) { return (T) castToDouble(obj); } if (clazz == String.class) { return (T) castToString(obj); } if (clazz == BigDecimal.class) { return (T) castToBigDecimal(obj); } if (clazz == BigInteger.class) { return (T) castToBigInteger(obj); } if (clazz == Date.class) { return (T) castToDate(obj); } T retObj = (T) ModuleUtil.callWhenHasJavaSql(castFunction, obj, clazz); if (retObj != null) { return retObj; } if (clazz.isEnum()) { return castToEnum(obj, clazz, config); } if (Calendar.class.isAssignableFrom(clazz)) { Date date = castToDate(obj); Calendar calendar; if (clazz == Calendar.class) { calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); } else { try { calendar = (Calendar) clazz.newInstance(); } catch (Exception e) { throw new JSONException("can not cast to : " + clazz.getName(), e); } } calendar.setTime(date); return (T) calendar; } String className = clazz.getName(); if (className.equals("javax.xml.datatype.XMLGregorianCalendar")) { Date date = castToDate(obj); Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); calendar.setTime(date); return (T) CalendarCodec.instance.createXMLGregorianCalendar(calendar); } if (obj instanceof String) { String strVal = (String) obj; if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } if (clazz == java.util.Currency.class) { return (T) java.util.Currency.getInstance(strVal); } if (clazz == java.util.Locale.class) { return (T) toLocale(strVal); } if (className.startsWith("java.time.")) { String json = JSON.toJSONString(strVal); return JSON.parseObject(json, clazz); } } final ObjectDeserializer objectDeserializer = config.get(clazz); if (objectDeserializer != null) { String str = JSON.toJSONString(obj); return JSON.parseObject(str, clazz); } throw new JSONException("can not cast to : " + clazz.getName()); } public static Locale toLocale(String strVal) { String[] items = strVal.split("_"); if (items.length == 1) { return new Locale(items[0]); } if (items.length == 2) { return new Locale(items[0], items[1]); } return new Locale(items[0], items[1], items[2]); } @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T castToEnum(Object obj, Class<T> clazz, ParserConfig mapping) { try { if (obj instanceof String) { String name = (String) obj; if (name.length() == 0) { return null; } if (mapping == null) { mapping = ParserConfig.getGlobalInstance(); } ObjectDeserializer deserializer = mapping.getDeserializer(clazz); if (deserializer instanceof EnumDeserializer) { EnumDeserializer enumDeserializer = (EnumDeserializer) deserializer; return (T) enumDeserializer.getEnumByHashCode(TypeUtils.fnv1a_64(name)); } return (T) Enum.valueOf((Class<? extends Enum>) clazz, name); } if (obj instanceof BigDecimal) { int ordinal = intValue((BigDecimal) obj); Object[] values = clazz.getEnumConstants(); if (ordinal < values.length) { return (T) values[ordinal]; } } if (obj instanceof Number) { int ordinal = ((Number) obj).intValue(); Object[] values = clazz.getEnumConstants(); if (ordinal < values.length) { return (T) values[ordinal]; } } } catch (Exception ex) { throw new JSONException("can not cast to : " + clazz.getName(), ex); } throw new JSONException("can not cast to : " + clazz.getName()); } @SuppressWarnings("unchecked") public static <T> T cast(Object obj, Type type, ParserConfig mapping) { if (obj == null) { return null; } if (type instanceof Class) { return cast(obj, (Class<T>) type, mapping); } if (type instanceof ParameterizedType) { return (T) cast(obj, (ParameterizedType) type, mapping); } if (obj instanceof String) { String strVal = (String) obj; if (strVal.length() == 0 // || "null".equals(strVal) // || "NULL".equals(strVal)) { return null; } } if (type instanceof TypeVariable) { return (T) obj; } throw new JSONException("can not cast to : " + type); } @SuppressWarnings({"rawtypes", "unchecked"}) public static <T> T cast(Object obj, ParameterizedType type, ParserConfig mapping) { Type rawTye = type.getRawType(); if (rawTye == List.class || rawTye == ArrayList.class) { Type itemType = type.getActualTypeArguments()[0]; if (obj instanceof List) { List listObj = (List) obj; List arrayList = new ArrayList(listObj.size()); for (Object item : listObj) { Object itemValue; if (itemType instanceof Class) { if (item != null && item.getClass() == JSONObject.class) { itemValue = ((JSONObject) item).toJavaObject((Class<T>) itemType, mapping, 0); } else { itemValue = cast(item, (Class<T>) itemType, mapping); } } else { itemValue = cast(item, itemType, mapping); } arrayList.add(itemValue); } return (T) arrayList; } } if (rawTye == Set.class || rawTye == HashSet.class // || rawTye == TreeSet.class // || rawTye == Collection.class // || rawTye == List.class // || rawTye == ArrayList.class) { Type itemType = type.getActualTypeArguments()[0]; if (obj instanceof Iterable) { Collection collection; if (rawTye == Set.class || rawTye == HashSet.class) { collection = new HashSet(); } else if (rawTye == TreeSet.class) { collection = new TreeSet(); } else { collection = new ArrayList(); } for (Object item : (Iterable) obj) { Object itemValue; if (itemType instanceof Class) { if (item != null && item.getClass() == JSONObject.class) { itemValue = ((JSONObject) item).toJavaObject((Class<T>) itemType, mapping, 0); } else { itemValue = cast(item, (Class<T>) itemType, mapping); } } else { itemValue = cast(item, itemType, mapping); } collection.add(itemValue); } return (T) collection; } } if (rawTye == Map.class || rawTye == HashMap.class) { Type keyType = type.getActualTypeArguments()[0]; Type valueType = type.getActualTypeArguments()[1]; if (obj instanceof Map) { Map map = new HashMap(); for (Map.Entry entry : ((Map<?, ?>) obj).entrySet()) { Object key = cast(entry.getKey(), keyType, mapping); Object value = cast(entry.getValue(), valueType, mapping); map.put(key, value); } return (T) map; } } if (obj instanceof String) { String strVal = (String) obj; if (strVal.length() == 0) { return null; } } Type[] actualTypeArguments = type.getActualTypeArguments(); if (actualTypeArguments.length == 1) { Type argType = type.getActualTypeArguments()[0]; if (argType instanceof WildcardType) { return (T) cast(obj, rawTye, mapping); } } if (rawTye == Map.Entry.class && obj instanceof Map && ((Map) obj).size() == 1) { Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next(); Object entryValue = entry.getValue(); if (actualTypeArguments.length == 2 && entryValue instanceof Map) { Type valueType = actualTypeArguments[1]; entry.setValue( cast(entryValue, valueType, mapping) ); } return (T) entry; } if (rawTye instanceof Class) { if (mapping == null) { mapping = ParserConfig.global; } ObjectDeserializer deserializer = mapping.getDeserializer(rawTye); if (deserializer != null) { String str = JSON.toJSONString(obj); DefaultJSONParser parser = new DefaultJSONParser(str, mapping); return (T) deserializer.deserialze(parser, type, null); } } throw new JSONException("can not cast to : " + type); } @SuppressWarnings({"unchecked"}) public static <T> T castToJavaBean(Map<String, Object> map, Class<T> clazz, ParserConfig config) { try { if (clazz == StackTraceElement.class) { String declaringClass = (String) map.get("className"); String methodName = (String) map.get("methodName"); String fileName = (String) map.get("fileName"); int lineNumber; { Number value = (Number) map.get("lineNumber"); if (value == null) { lineNumber = 0; } else if (value instanceof BigDecimal) { lineNumber = ((BigDecimal) value).intValueExact(); } else { lineNumber = value.intValue(); } } return (T) new StackTraceElement(declaringClass, methodName, fileName, lineNumber); } { Object iClassObject = map.get(JSON.DEFAULT_TYPE_KEY); if (iClassObject instanceof String) { String className = (String) iClassObject; Class<?> loadClazz; if (config == null) { config = ParserConfig.global; } loadClazz = config.checkAutoType(className, null); if (loadClazz == null) { throw new ClassNotFoundException(className + " not found"); } if (!loadClazz.equals(clazz)) { return (T) castToJavaBean(map, loadClazz, config); } } } if (clazz.isInterface()) { JSONObject object; if (map instanceof JSONObject) { object = (JSONObject) map; } else { object = new JSONObject(map); } if (config == null) { config = ParserConfig.getGlobalInstance(); } ObjectDeserializer deserializer = config.get(clazz); if (deserializer != null) { String json = JSON.toJSONString(object); return JSON.parseObject(json, clazz); } return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{clazz}, object); } if (clazz == Locale.class) { Object arg0 = map.get("language"); Object arg1 = map.get("country"); if (arg0 instanceof String) { String language = (String) arg0; if (arg1 instanceof String) { String country = (String) arg1; return (T) new Locale(language, country); } else if (arg1 == null) { return (T) new Locale(language); } } } if (clazz == String.class && map instanceof JSONObject) { return (T) map.toString(); } if (clazz == JSON.class && map instanceof JSONObject) { return (T) map; } if (clazz == LinkedHashMap.class && map instanceof JSONObject) { JSONObject jsonObject = (JSONObject) map; Map<String, Object> innerMap = jsonObject.getInnerMap(); if (innerMap instanceof LinkedHashMap) { return (T) innerMap; } } if (clazz.isInstance(map)) { return (T) map; } if (clazz == JSONObject.class) { return (T) new JSONObject(map); } if (config == null) { config = ParserConfig.getGlobalInstance(); } JavaBeanDeserializer javaBeanDeser = null; ObjectDeserializer deserializer = config.getDeserializer(clazz); if (deserializer instanceof JavaBeanDeserializer) { javaBeanDeser = (JavaBeanDeserializer) deserializer; } if (javaBeanDeser == null) { throw new JSONException("can not get javaBeanDeserializer. " + clazz.getName()); } return (T) javaBeanDeser.createInstance(map, config); } catch (Exception e) { throw new JSONException(e.getMessage(), e); } } private static Function<Map<String, Class<?>>, Void> addBaseClassMappingsFunction = new Function<Map<String, Class<?>>, Void>() { public Void apply(Map<String, Class<?>> mappings) { Class<?>[] classes = new Class[]{ java.sql.Time.class, java.sql.Date.class, java.sql.Timestamp.class }; for (Class clazz : classes) { if (clazz == null) { continue; } mappings.put(clazz.getName(), clazz); } return null; } }; static { addBaseClassMappings(); } private static void addBaseClassMappings() { mappings.put("byte", byte.class); mappings.put("short", short.class); mappings.put("int", int.class); mappings.put("long", long.class); mappings.put("float", float.class); mappings.put("double", double.class); mappings.put("boolean", boolean.class); mappings.put("char", char.class); mappings.put("[byte", byte[].class); mappings.put("[short", short[].class); mappings.put("[int", int[].class); mappings.put("[long", long[].class); mappings.put("[float", float[].class); mappings.put("[double", double[].class); mappings.put("[boolean", boolean[].class); mappings.put("[char", char[].class); mappings.put("[B", byte[].class); mappings.put("[S", short[].class); mappings.put("[I", int[].class); mappings.put("[J", long[].class); mappings.put("[F", float[].class); mappings.put("[D", double[].class); mappings.put("[C", char[].class); mappings.put("[Z", boolean[].class); Class<?>[] classes = new Class[]{ Object.class, java.lang.Cloneable.class, loadClass("java.lang.AutoCloseable"), java.lang.Exception.class, java.lang.RuntimeException.class, java.lang.IllegalAccessError.class, java.lang.IllegalAccessException.class, java.lang.IllegalArgumentException.class, java.lang.IllegalMonitorStateException.class, java.lang.IllegalStateException.class, java.lang.IllegalThreadStateException.class, java.lang.IndexOutOfBoundsException.class, java.lang.InstantiationError.class, java.lang.InstantiationException.class, java.lang.InternalError.class, java.lang.InterruptedException.class, java.lang.LinkageError.class, java.lang.NegativeArraySizeException.class, java.lang.NoClassDefFoundError.class, java.lang.NoSuchFieldError.class, java.lang.NoSuchFieldException.class, java.lang.NoSuchMethodError.class, java.lang.NoSuchMethodException.class, java.lang.NullPointerException.class, java.lang.NumberFormatException.class, java.lang.OutOfMemoryError.class, java.lang.SecurityException.class, java.lang.StackOverflowError.class, java.lang.StringIndexOutOfBoundsException.class, java.lang.TypeNotPresentException.class, java.lang.VerifyError.class, java.lang.StackTraceElement.class, java.util.HashMap.class, java.util.LinkedHashMap.class, java.util.Hashtable.class, java.util.TreeMap.class, java.util.IdentityHashMap.class, java.util.WeakHashMap.class, java.util.LinkedHashMap.class, java.util.HashSet.class, java.util.LinkedHashSet.class, java.util.TreeSet.class, java.util.ArrayList.class, java.util.concurrent.TimeUnit.class, java.util.concurrent.ConcurrentHashMap.class, java.util.concurrent.atomic.AtomicInteger.class, java.util.concurrent.atomic.AtomicLong.class, java.util.Collections.EMPTY_MAP.getClass(), java.lang.Boolean.class, java.lang.Character.class, java.lang.Byte.class, java.lang.Short.class, java.lang.Integer.class, java.lang.Long.class, java.lang.Float.class, java.lang.Double.class, java.lang.Number.class, java.lang.String.class, java.math.BigDecimal.class, java.math.BigInteger.class, java.util.BitSet.class, java.util.Calendar.class, java.util.Date.class, java.util.Locale.class, java.util.UUID.class, java.text.SimpleDateFormat.class, com.alibaba.fastjson.JSONObject.class, com.alibaba.fastjson.JSONPObject.class, com.alibaba.fastjson.JSONArray.class, }; for (Class clazz : classes) { if (clazz == null) { continue; } mappings.put(clazz.getName(), clazz); } ModuleUtil.callWhenHasJavaSql(addBaseClassMappingsFunction, mappings); } public static void clearClassMapping() { mappings.clear(); addBaseClassMappings(); } public static void addMapping(String className, Class<?> clazz) { mappings.put(className, clazz); } public static Class<?> loadClass(String className) { return loadClass(className, null); } public static boolean isPath(Class<?> clazz) { if (pathClass == null && !pathClass_error) { try { pathClass = Class.forName("java.nio.file.Path"); } catch (Throwable ex) { pathClass_error = true; } } if (pathClass != null) { return pathClass.isAssignableFrom(clazz); } return false; } public static Class<?> getClassFromMapping(String className) { return mappings.get(className); } public static Class<?> loadClass(String className, ClassLoader classLoader) { return loadClass(className, classLoader, false); } public static Class<?> loadClass(String className, ClassLoader classLoader, boolean cache) { if (className == null || className.length() == 0) { return null; } if (className.length() > 198) { throw new JSONException("illegal className : " + className); } Class<?> clazz = mappings.get(className); if (clazz != null) { return clazz; } if (className.charAt(0) == '[') { Class<?> componentType = loadClass(className.substring(1), classLoader); return Array.newInstance(componentType, 0).getClass(); } if (className.startsWith("L") && className.endsWith(";")) { String newClassName = className.substring(1, className.length() - 1); return loadClass(newClassName, classLoader); } try { if (classLoader != null) { clazz = classLoader.loadClass(className); if (cache) { mappings.put(className, clazz); } return clazz; } } catch (Throwable e) { e.printStackTrace(); // skip } try { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null && contextClassLoader != classLoader) { clazz = contextClassLoader.loadClass(className); if (cache) { mappings.put(className, clazz); } return clazz; } } catch (Throwable e) { // skip } try { clazz = Class.forName(className); if (cache) { mappings.put(className, clazz); } return clazz; } catch (Throwable e) { // skip } return clazz; } public static SerializeBeanInfo buildBeanInfo(Class<?> beanType // , Map<String, String> aliasMap // , PropertyNamingStrategy propertyNamingStrategy) { return buildBeanInfo(beanType, aliasMap, propertyNamingStrategy, false); } public static SerializeBeanInfo buildBeanInfo(Class<?> beanType // , Map<String, String> aliasMap // , PropertyNamingStrategy propertyNamingStrategy // , boolean fieldBased // ) { JSONType jsonType = TypeUtils.getAnnotation(beanType, JSONType.class); String[] orders = null; final int features; String typeName = null, typeKey = null; if (jsonType != null) { orders = jsonType.orders(); typeName = jsonType.typeName(); if (typeName.length() == 0) { typeName = null; } PropertyNamingStrategy jsonTypeNaming = jsonType.naming(); if (jsonTypeNaming != PropertyNamingStrategy.NeverUseThisValueExceptDefaultValue) { propertyNamingStrategy = jsonTypeNaming; } features = SerializerFeature.of(jsonType.serialzeFeatures()); for (Class<?> supperClass = beanType.getSuperclass() ; supperClass != null && supperClass != Object.class ; supperClass = supperClass.getSuperclass()) { JSONType superJsonType = TypeUtils.getAnnotation(supperClass, JSONType.class); if (superJsonType == null) { break; } typeKey = superJsonType.typeKey(); if (typeKey.length() != 0) { break; } } for (Class<?> interfaceClass : beanType.getInterfaces()) { JSONType superJsonType = TypeUtils.getAnnotation(interfaceClass, JSONType.class); if (superJsonType != null) { typeKey = superJsonType.typeKey(); if (typeKey.length() != 0) { break; } } } if (typeKey != null && typeKey.length() == 0) { typeKey = null; } } else { features = 0; } // fieldName,field ,先生成fieldName的快照,减少之后的findField的轮询 Map<String, Field> fieldCacheMap = new HashMap<String, Field>(); ParserConfig.parserAllFieldToCache(beanType, fieldCacheMap); List<FieldInfo> fieldInfoList = fieldBased ? computeGettersWithFieldBase(beanType, aliasMap, false, propertyNamingStrategy) // : computeGetters(beanType, jsonType, aliasMap, fieldCacheMap, false, propertyNamingStrategy); FieldInfo[] fields = new FieldInfo[fieldInfoList.size()]; fieldInfoList.toArray(fields); FieldInfo[] sortedFields; List<FieldInfo> sortedFieldList; if (orders != null && orders.length != 0) { sortedFieldList = fieldBased ? computeGettersWithFieldBase(beanType, aliasMap, true, propertyNamingStrategy) // : computeGetters(beanType, jsonType, aliasMap, fieldCacheMap, true, propertyNamingStrategy); } else { sortedFieldList = new ArrayList<FieldInfo>(fieldInfoList); Collections.sort(sortedFieldList); } sortedFields = new FieldInfo[sortedFieldList.size()]; sortedFieldList.toArray(sortedFields); if (Arrays.equals(sortedFields, fields)) { sortedFields = fields; } return new SerializeBeanInfo(beanType, jsonType, typeName, typeKey, features, fields, sortedFields); } public static List<FieldInfo> computeGettersWithFieldBase( Class<?> clazz, // Map<String, String> aliasMap, // boolean sorted, // PropertyNamingStrategy propertyNamingStrategy) { Map<String, FieldInfo> fieldInfoMap = new LinkedHashMap<String, FieldInfo>(); for (Class<?> currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()) { Field[] fields = currentClass.getDeclaredFields(); computeFields(currentClass, aliasMap, propertyNamingStrategy, fieldInfoMap, fields); } return getFieldInfos(clazz, sorted, fieldInfoMap); } public static List<FieldInfo> computeGetters(Class<?> clazz, Map<String, String> aliasMap) { return computeGetters(clazz, aliasMap, true); } public static List<FieldInfo> computeGetters(Class<?> clazz, Map<String, String> aliasMap, boolean sorted) { JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class); Map<String, Field> fieldCacheMap = new HashMap<String, Field>(); ParserConfig.parserAllFieldToCache(clazz, fieldCacheMap); return computeGetters(clazz, jsonType, aliasMap, fieldCacheMap, sorted, PropertyNamingStrategy.CamelCase); } public static List<FieldInfo> computeGetters(Class<?> clazz, // JSONType jsonType, // Map<String, String> aliasMap, // Map<String, Field> fieldCacheMap, // boolean sorted, // PropertyNamingStrategy propertyNamingStrategy // ) { Map<String, FieldInfo> fieldInfoMap = new LinkedHashMap<String, FieldInfo>(); boolean kotlin = TypeUtils.isKotlin(clazz); // for kotlin Constructor[] constructors = null; Annotation[][] paramAnnotationArrays = null; String[] paramNames = null; short[] paramNameMapping = null; Method[] methods = clazz.getMethods(); try { Arrays.sort(methods, new MethodInheritanceComparator()); } catch (Throwable ignored) { } for (Method method : methods) { String methodName = method.getName(); int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; String label = null; if (Modifier.isStatic(method.getModifiers())) { continue; } Class<?> returnType = method.getReturnType(); if (returnType.equals(Void.TYPE)) { continue; } if (method.getParameterTypes().length != 0) { continue; } if (returnType == ClassLoader.class || returnType == InputStream.class || returnType == Reader.class) { continue; } if (methodName.equals("getMetaClass") && returnType.getName().equals("groovy.lang.MetaClass")) { continue; } if (methodName.equals("getSuppressed") && method.getDeclaringClass() == Throwable.class) { continue; } if (kotlin && isKotlinIgnore(clazz, methodName)) { continue; } /** * 如果在属性或者方法上存在JSONField注解,并且定制了name属性,不以类上的propertyNamingStrategy设置为准,以此字段的JSONField的name定制为准。 */ Boolean fieldAnnotationAndNameExists = false; JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class); if (annotation == null) { annotation = getSuperMethodAnnotation(clazz, method); } if (annotation == null && kotlin) { if (constructors == null) { constructors = clazz.getDeclaredConstructors(); Constructor creatorConstructor = TypeUtils.getKotlinConstructor(constructors); if (creatorConstructor != null) { paramAnnotationArrays = TypeUtils.getParameterAnnotations(creatorConstructor); paramNames = TypeUtils.getKoltinConstructorParameters(clazz); if (paramNames != null) { String[] paramNames_sorted = new String[paramNames.length]; System.arraycopy(paramNames, 0, paramNames_sorted, 0, paramNames.length); Arrays.sort(paramNames_sorted); paramNameMapping = new short[paramNames.length]; for (short p = 0; p < paramNames.length; p++) { int index = Arrays.binarySearch(paramNames_sorted, paramNames[p]); paramNameMapping[index] = p; } paramNames = paramNames_sorted; } } } if (paramNames != null && paramNameMapping != null && methodName.startsWith("get")) { String propertyName = decapitalize(methodName.substring(3)); int p = Arrays.binarySearch(paramNames, propertyName); if (p < 0) { for (int i = 0; i < paramNames.length; i++) { if (propertyName.equalsIgnoreCase(paramNames[i])) { p = i; break; } } } if (p >= 0) { short index = paramNameMapping[p]; Annotation[] paramAnnotations = paramAnnotationArrays[index]; if (paramAnnotations != null) { for (Annotation paramAnnotation : paramAnnotations) { if (paramAnnotation instanceof JSONField) { annotation = (JSONField) paramAnnotation; break; } } } if (annotation == null) { Field field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field != null) { annotation = TypeUtils.getAnnotation(field, JSONField.class); } } } } } if (annotation != null) { if (!annotation.serialize()) { continue; } ordinal = annotation.ordinal(); serialzeFeatures = SerializerFeature.of(annotation.serialzeFeatures()); parserFeatures = Feature.of(annotation.parseFeatures()); if (annotation.name().length() != 0) { String propertyName = annotation.name(); if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue; } } FieldInfo fieldInfo = new FieldInfo(propertyName, method, null, clazz, null, ordinal, serialzeFeatures, parserFeatures, annotation, null, label); fieldInfoMap.put(propertyName, fieldInfo); continue; } if (annotation.label().length() != 0) { label = annotation.label(); } } if (methodName.startsWith("get")) { if (methodName.length() < 4) { continue; } if (methodName.equals("getClass")) { continue; } if (methodName.equals("getDeclaringClass") && clazz.isEnum()) { continue; } char c3 = methodName.charAt(3); String propertyName; Field field = null; if (Character.isUpperCase(c3) // || c3 > 512 // for unicode method name ) { if (compatibleWithJavaBean) { propertyName = decapitalize(methodName.substring(3)); } else { propertyName = TypeUtils.getPropertyNameByMethodName(methodName); } propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 3); } else if (c3 == '_') { propertyName = methodName.substring(3); field = fieldCacheMap.get(propertyName); if (field == null) { String temp = propertyName; propertyName = methodName.substring(4); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { propertyName = temp; //减少修改代码带来的影响 } } } else if (c3 == 'f') { propertyName = methodName.substring(3); } else if (methodName.length() >= 5 && Character.isUpperCase(methodName.charAt(4))) { propertyName = decapitalize(methodName.substring(3)); } else { propertyName = methodName.substring(3); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { continue; } } boolean ignore = isJSONTypeIgnore(clazz, propertyName); if (ignore) { continue; } if (field == null) { // 假如bean的field很多的情况一下,轮询时将大大降低效率 field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); } if (field == null && propertyName.length() > 1) { char ch = propertyName.charAt(1); if (ch >= 'A' && ch <= 'Z') { String javaBeanCompatiblePropertyName = decapitalize(methodName.substring(3)); field = ParserConfig.getFieldFromCache(javaBeanCompatiblePropertyName, fieldCacheMap); } } JSONField fieldAnnotation = null; if (field != null) { fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class); if (fieldAnnotation != null) { if (!fieldAnnotation.serialize()) { continue; } ordinal = fieldAnnotation.ordinal(); serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); if (fieldAnnotation.name().length() != 0) { fieldAnnotationAndNameExists = true; propertyName = fieldAnnotation.name(); if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue; } } } if (fieldAnnotation.label().length() != 0) { label = fieldAnnotation.label(); } } } if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue; } } if (propertyNamingStrategy != null && !fieldAnnotationAndNameExists) { propertyName = propertyNamingStrategy.translate(propertyName); } FieldInfo fieldInfo = new FieldInfo(propertyName, method, field, clazz, null, ordinal, serialzeFeatures, parserFeatures, annotation, fieldAnnotation, label); fieldInfoMap.put(propertyName, fieldInfo); } if (methodName.startsWith("is")) { if (methodName.length() < 3) { continue; } if (returnType != Boolean.TYPE && returnType != Boolean.class) { continue; } char c2 = methodName.charAt(2); String propertyName; Field field = null; if (Character.isUpperCase(c2)) { if (compatibleWithJavaBean) { propertyName = decapitalize(methodName.substring(2)); } else { propertyName = Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3); } propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 2); } else if (c2 == '_') { propertyName = methodName.substring(3); field = fieldCacheMap.get(propertyName); if (field == null) { String temp = propertyName; propertyName = methodName.substring(2); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { propertyName = temp; } } } else if (c2 == 'f') { propertyName = methodName.substring(2); } else { propertyName = methodName.substring(2); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { continue; } } boolean ignore = isJSONTypeIgnore(clazz, propertyName); if (ignore) { continue; } if (field == null) { field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); } if (field == null) { field = ParserConfig.getFieldFromCache(methodName, fieldCacheMap); } JSONField fieldAnnotation = null; if (field != null) { fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class); if (fieldAnnotation != null) { if (!fieldAnnotation.serialize()) { continue; } ordinal = fieldAnnotation.ordinal(); serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); if (fieldAnnotation.name().length() != 0) { propertyName = fieldAnnotation.name(); if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue; } } } if (fieldAnnotation.label().length() != 0) { label = fieldAnnotation.label(); } } } if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue; } } if (propertyNamingStrategy != null) { propertyName = propertyNamingStrategy.translate(propertyName); } //优先选择get if (fieldInfoMap.containsKey(propertyName)) { continue; } FieldInfo fieldInfo = new FieldInfo(propertyName, method, field, clazz, null, ordinal, serialzeFeatures, parserFeatures, annotation, fieldAnnotation, label); fieldInfoMap.put(propertyName, fieldInfo); } } Field[] fields = clazz.getFields(); computeFields(clazz, aliasMap, propertyNamingStrategy, fieldInfoMap, fields); return getFieldInfos(clazz, sorted, fieldInfoMap); } private static List<FieldInfo> getFieldInfos(Class<?> clazz, boolean sorted, Map<String, FieldInfo> fieldInfoMap) { List<FieldInfo> fieldInfoList = new ArrayList<FieldInfo>(); String[] orders = null; JSONType annotation = TypeUtils.getAnnotation(clazz, JSONType.class); if (annotation != null) { orders = annotation.orders(); } if (orders != null && orders.length > 0) { LinkedHashMap<String, FieldInfo> map = new LinkedHashMap<String, FieldInfo>(fieldInfoMap.size()); for (FieldInfo field : fieldInfoMap.values()) { map.put(field.name, field); } for (String item : orders) { FieldInfo field = map.get(item); if (field != null) { fieldInfoList.add(field); map.remove(item); } } fieldInfoList.addAll(map.values()); } else { fieldInfoList.addAll(fieldInfoMap.values()); if (sorted) { Collections.sort(fieldInfoList); } } return fieldInfoList; } private static void computeFields( Class<?> clazz, // Map<String, String> aliasMap, // PropertyNamingStrategy propertyNamingStrategy, // Map<String, FieldInfo> fieldInfoMap, // Field[] fields) { for (Field field : fields) { if (Modifier.isStatic(field.getModifiers())) { continue; } JSONField fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class); int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; String propertyName = field.getName(); String label = null; if (fieldAnnotation != null) { if (!fieldAnnotation.serialize()) { continue; } ordinal = fieldAnnotation.ordinal(); serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); if (fieldAnnotation.name().length() != 0) { propertyName = fieldAnnotation.name(); } if (fieldAnnotation.label().length() != 0) { label = fieldAnnotation.label(); } } if (aliasMap != null) { propertyName = aliasMap.get(propertyName); if (propertyName == null) { continue; } } if (propertyNamingStrategy != null) { propertyName = propertyNamingStrategy.translate(propertyName); } if (!fieldInfoMap.containsKey(propertyName)) { FieldInfo fieldInfo = new FieldInfo(propertyName, null, field, clazz, null, ordinal, serialzeFeatures, parserFeatures, null, fieldAnnotation, label); fieldInfoMap.put(propertyName, fieldInfo); } } } private static String getPropertyNameByCompatibleFieldName(Map<String, Field> fieldCacheMap, String methodName, String propertyName, int fromIdx) { if (compatibleWithFieldName) { if (!fieldCacheMap.containsKey(propertyName)) { String tempPropertyName = methodName.substring(fromIdx); return fieldCacheMap.containsKey(tempPropertyName) ? tempPropertyName : propertyName; } } return propertyName; } public static JSONField getSuperMethodAnnotation(final Class<?> clazz, final Method method) { Class<?>[] interfaces = clazz.getInterfaces(); if (interfaces.length > 0) { Class<?>[] types = method.getParameterTypes(); for (Class<?> interfaceClass : interfaces) { for (Method interfaceMethod : interfaceClass.getMethods()) { Class<?>[] interfaceTypes = interfaceMethod.getParameterTypes(); if (interfaceTypes.length != types.length) { continue; } if (!interfaceMethod.getName().equals(method.getName())) { continue; } boolean match = true; for (int i = 0; i < types.length; ++i) { if (!interfaceTypes[i].equals(types[i])) { match = false; break; } } if (!match) { continue; } JSONField annotation = TypeUtils.getAnnotation(interfaceMethod, JSONField.class); if (annotation != null) { return annotation; } } } } Class<?> superClass = clazz.getSuperclass(); if (superClass == null) { return null; } if (Modifier.isAbstract(superClass.getModifiers())) { Class<?>[] types = method.getParameterTypes(); for (Method interfaceMethod : superClass.getMethods()) { Class<?>[] interfaceTypes = interfaceMethod.getParameterTypes(); if (interfaceTypes.length != types.length) { continue; } if (!interfaceMethod.getName().equals(method.getName())) { continue; } boolean match = true; for (int i = 0; i < types.length; ++i) { if (!interfaceTypes[i].equals(types[i])) { match = false; break; } } if (!match) { continue; } JSONField annotation = TypeUtils.getAnnotation(interfaceMethod, JSONField.class); if (annotation != null) { return annotation; } } } return null; } private static boolean isJSONTypeIgnore(Class<?> clazz, String propertyName) { JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class); if (jsonType != null) { // 1、新增 includes 支持,如果 JSONType 同时设置了includes 和 ignores 属性,则以includes为准。 // 2、个人认为对于大小写敏感的Java和JS而言,使用 equals() 比 equalsIgnoreCase() 更好,改动的唯一风险就是向后兼容性的问题 // 不过,相信开发者应该都是严格按照大小写敏感的方式进行属性设置的 String[] fields = jsonType.includes(); if (fields.length > 0) { for (String field : fields) { if (propertyName.equals(field)) { return false; } } return true; } else { fields = jsonType.ignores(); for (String field : fields) { if (propertyName.equals(field)) { return true; } } } } if (clazz.getSuperclass() != Object.class && clazz.getSuperclass() != null) { return isJSONTypeIgnore(clazz.getSuperclass(), propertyName); } return false; } public static boolean isGenericParamType(Type type) { if (type instanceof ParameterizedType) { return true; } if (type instanceof Class) { Type superType = ((Class<?>) type).getGenericSuperclass(); return superType != Object.class && isGenericParamType(superType); } return false; } public static Type getGenericParamType(Type type) { if (type instanceof ParameterizedType) { return type; } if (type instanceof Class) { return getGenericParamType(((Class<?>) type).getGenericSuperclass()); } return type; } public static Type unwrapOptional(Type type) { if (!optionalClassInited) { try { optionalClass = Class.forName("java.util.Optional"); } catch (Exception e) { // skip } finally { optionalClassInited = true; } } if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (parameterizedType.getRawType() == optionalClass) { return parameterizedType.getActualTypeArguments()[0]; } } return type; } public static Class<?> getClass(Type type) { if (type.getClass() == Class.class) { return (Class<?>) type; } if (type instanceof ParameterizedType) { return getClass(((ParameterizedType) type).getRawType()); } if (type instanceof TypeVariable) { Type boundType = ((TypeVariable<?>) type).getBounds()[0]; if (boundType instanceof Class) { return (Class) boundType; } return getClass(boundType); } if (type instanceof WildcardType) { Type[] upperBounds = ((WildcardType) type).getUpperBounds(); if (upperBounds.length == 1) { return getClass(upperBounds[0]); } } return Object.class; } public static Field getField(Class<?> clazz, String fieldName, Field[] declaredFields) { for (Field field : declaredFields) { String itemName = field.getName(); if (fieldName.equals(itemName)) { return field; } char c0, c1; if (fieldName.length() > 2 && (c0 = fieldName.charAt(0)) >= 'a' && c0 <= 'z' && (c1 = fieldName.charAt(1)) >= 'A' && c1 <= 'Z' && fieldName.equalsIgnoreCase(itemName)) { return field; } } Class<?> superClass = clazz.getSuperclass(); if (superClass != null && superClass != Object.class) { return getField(superClass, fieldName, superClass.getDeclaredFields()); } return null; } /** * @deprecated */ public static int getSerializeFeatures(Class<?> clazz) { JSONType annotation = TypeUtils.getAnnotation(clazz, JSONType.class); if (annotation == null) { return 0; } return SerializerFeature.of(annotation.serialzeFeatures()); } public static int getParserFeatures(Class<?> clazz) { JSONType annotation = TypeUtils.getAnnotation(clazz, JSONType.class); if (annotation == null) { return 0; } return Feature.of(annotation.parseFeatures()); } public static String decapitalize(String name) { if (name == null || name.length() == 0) { return name; } if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0))) { return name; } char[] chars = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } /** * resolve property name from get/set method name * * @param methodName get/set method name * @return property name */ public static String getPropertyNameByMethodName(String methodName) { return Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); } static void setAccessible(AccessibleObject obj) { if (!setAccessibleEnable) { return; } if (obj.isAccessible()) { return; } try { obj.setAccessible(true); } catch (Throwable error) { setAccessibleEnable = false; } } public static Type getCollectionItemType(Type fieldType) { if (fieldType instanceof ParameterizedType) { return getCollectionItemType((ParameterizedType) fieldType); } if (fieldType instanceof Class<?>) { return getCollectionItemType((Class<?>) fieldType); } return Object.class; } private static Type getCollectionItemType(Class<?> clazz) { return clazz.getName().startsWith("java.") ? Object.class : getCollectionItemType(getCollectionSuperType(clazz)); } private static Type getCollectionItemType(ParameterizedType parameterizedType) { Type rawType = parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (rawType == Collection.class) { return getWildcardTypeUpperBounds(actualTypeArguments[0]); } Class<?> rawClass = (Class<?>) rawType; Map<TypeVariable, Type> actualTypeMap = createActualTypeMap(rawClass.getTypeParameters(), actualTypeArguments); Type superType = getCollectionSuperType(rawClass); if (superType instanceof ParameterizedType) { Class<?> superClass = getRawClass(superType); Type[] superClassTypeParameters = ((ParameterizedType) superType).getActualTypeArguments(); return superClassTypeParameters.length > 0 ? getCollectionItemType(makeParameterizedType(superClass, superClassTypeParameters, actualTypeMap)) : getCollectionItemType(superClass); } return getCollectionItemType((Class<?>) superType); } private static Type getCollectionSuperType(Class<?> clazz) { Type assignable = null; for (Type type : clazz.getGenericInterfaces()) { Class<?> rawClass = getRawClass(type); if (rawClass == Collection.class) { return type; } if (Collection.class.isAssignableFrom(rawClass)) { assignable = type; } } return assignable == null ? clazz.getGenericSuperclass() : assignable; } private static Map<TypeVariable, Type> createActualTypeMap(TypeVariable[] typeParameters, Type[] actualTypeArguments) { int length = typeParameters.length; Map<TypeVariable, Type> actualTypeMap = new HashMap<TypeVariable, Type>(length); for (int i = 0; i < length; i++) { actualTypeMap.put(typeParameters[i], actualTypeArguments[i]); } return actualTypeMap; } private static ParameterizedType makeParameterizedType(Class<?> rawClass, Type[] typeParameters, Map<TypeVariable, Type> actualTypeMap) { int length = typeParameters.length; Type[] actualTypeArguments = new Type[length]; for (int i = 0; i < length; i++) { actualTypeArguments[i] = getActualType(typeParameters[i], actualTypeMap); } return new ParameterizedTypeImpl(actualTypeArguments, null, rawClass); } private static Type getActualType(Type typeParameter, Map<TypeVariable, Type> actualTypeMap) { if (typeParameter instanceof TypeVariable) { return actualTypeMap.get(typeParameter); } else if (typeParameter instanceof ParameterizedType) { return makeParameterizedType(getRawClass(typeParameter), ((ParameterizedType) typeParameter).getActualTypeArguments(), actualTypeMap); } else if (typeParameter instanceof GenericArrayType) { return new GenericArrayTypeImpl(getActualType(((GenericArrayType) typeParameter).getGenericComponentType(), actualTypeMap)); } return typeParameter; } private static Type getWildcardTypeUpperBounds(Type type) { if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Type[] upperBounds = wildcardType.getUpperBounds(); return upperBounds.length > 0 ? upperBounds[0] : Object.class; } return type; } public static Class<?> getCollectionItemClass(Type fieldType) { if (fieldType instanceof ParameterizedType) { Class<?> itemClass; Type actualTypeArgument = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; if (actualTypeArgument instanceof WildcardType) { WildcardType wildcardType = (WildcardType) actualTypeArgument; Type[] upperBounds = wildcardType.getUpperBounds(); if (upperBounds.length == 1) { actualTypeArgument = upperBounds[0]; } } if (actualTypeArgument instanceof Class) { itemClass = (Class<?>) actualTypeArgument; if (!Modifier.isPublic(itemClass.getModifiers())) { throw new JSONException("can not create ASMParser"); } } else { throw new JSONException("can not create ASMParser"); } return itemClass; } return Object.class; } private static final Map primitiveTypeMap = new HashMap<Class, String>(8) {{ put(boolean.class, "Z"); put(char.class, "C"); put(byte.class, "B"); put(short.class, "S"); put(int.class, "I"); put(long.class, "J"); put(float.class, "F"); put(double.class, "D"); }}; public static Type checkPrimitiveArray(GenericArrayType genericArrayType) { Type clz = genericArrayType; Type genericComponentType = genericArrayType.getGenericComponentType(); String prefix = "["; while (genericComponentType instanceof GenericArrayType) { genericComponentType = ((GenericArrayType) genericComponentType) .getGenericComponentType(); prefix += prefix; } if (genericComponentType instanceof Class<?>) { Class<?> ck = (Class<?>) genericComponentType; if (ck.isPrimitive()) { try { String postfix = (String) primitiveTypeMap.get(ck); if (postfix != null) { clz = Class.forName(prefix + postfix); } } catch (ClassNotFoundException ignored) { } } } return clz; } public static Set createSet(Type type) { Class<?> rawClass = getRawClass(type); Set set; if (rawClass == AbstractCollection.class // || rawClass == Collection.class) { set = new HashSet(); } else if (rawClass.isAssignableFrom(HashSet.class)) { set = new HashSet(); } else if (rawClass.isAssignableFrom(LinkedHashSet.class)) { set = new LinkedHashSet(); } else if (rawClass.isAssignableFrom(TreeSet.class)) { set = new TreeSet(); } else if (rawClass.isAssignableFrom(EnumSet.class)) { Type itemType; if (type instanceof ParameterizedType) { itemType = ((ParameterizedType) type).getActualTypeArguments()[0]; } else { itemType = Object.class; } set = EnumSet.noneOf((Class<Enum>) itemType); } else { try { set = (Set) rawClass.newInstance(); } catch (Exception e) { throw new JSONException("create instance error, class " + rawClass.getName()); } } return set; } @SuppressWarnings({"rawtypes", "unchecked"}) public static Collection createCollection(Type type) { Class<?> rawClass = getRawClass(type); Collection list; if (rawClass == AbstractCollection.class // || rawClass == Collection.class) { list = new ArrayList(); } else if (rawClass.isAssignableFrom(HashSet.class)) { list = new HashSet(); } else if (rawClass.isAssignableFrom(LinkedHashSet.class)) { list = new LinkedHashSet(); } else if (rawClass.isAssignableFrom(TreeSet.class)) { list = new TreeSet(); } else if (rawClass.isAssignableFrom(ArrayList.class)) { list = new ArrayList(); } else if (rawClass.isAssignableFrom(EnumSet.class)) { Type itemType; if (type instanceof ParameterizedType) { itemType = ((ParameterizedType) type).getActualTypeArguments()[0]; } else { itemType = Object.class; } list = EnumSet.noneOf((Class<Enum>) itemType); } else if (rawClass.isAssignableFrom(Queue.class) || (class_deque != null && rawClass.isAssignableFrom(class_deque))) { list = new LinkedList(); } else { try { list = (Collection) rawClass.newInstance(); } catch (Exception e) { throw new JSONException("create instance error, class " + rawClass.getName()); } } return list; } public static Class<?> getRawClass(Type type) { if (type instanceof Class<?>) { return (Class<?>) type; } else if (type instanceof ParameterizedType) { return getRawClass(((ParameterizedType) type).getRawType()); } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Type[] upperBounds = wildcardType.getUpperBounds(); if (upperBounds.length == 1) { return getRawClass(upperBounds[0]); } else { throw new JSONException("TODO"); } } else { throw new JSONException("TODO"); } } private static final Set<String> isProxyClassNames = new HashSet<String>(6) {{ add("net.sf.cglib.proxy.Factory"); add("org.springframework.cglib.proxy.Factory"); add("javassist.util.proxy.ProxyObject"); add("org.apache.ibatis.javassist.util.proxy.ProxyObject"); add("org.hibernate.proxy.HibernateProxy"); add("org.springframework.context.annotation.ConfigurationClassEnhancer$EnhancedConfiguration"); }}; public static boolean isProxy(Class<?> clazz) { for (Class<?> item : clazz.getInterfaces()) { String interfaceName = item.getName(); if (isProxyClassNames.contains(interfaceName)) { return true; } } return false; } public static boolean isTransient(Method method) { if (method == null) { return false; } if (!transientClassInited) { try { transientClass = (Class<? extends Annotation>) Class.forName("java.beans.Transient"); } catch (Exception e) { // skip } finally { transientClassInited = true; } } if (transientClass != null) { Annotation annotation = TypeUtils.getAnnotation(method, transientClass); return annotation != null; } return false; } public static boolean isAnnotationPresentOneToMany(Method method) { if (method == null) { return false; } if (class_OneToMany == null && !class_OneToMany_error) { try { class_OneToMany = (Class<? extends Annotation>) Class.forName("javax.persistence.OneToMany"); } catch (Throwable e) { // skip class_OneToMany_error = true; } } return class_OneToMany != null && method.isAnnotationPresent(class_OneToMany); } public static boolean isAnnotationPresentManyToMany(Method method) { if (method == null) { return false; } if (class_ManyToMany == null && !class_ManyToMany_error) { try { class_ManyToMany = (Class<? extends Annotation>) Class.forName("javax.persistence.ManyToMany"); } catch (Throwable e) { // skip class_ManyToMany_error = true; } } return class_ManyToMany != null && (method.isAnnotationPresent(class_OneToMany) || method.isAnnotationPresent(class_ManyToMany)); } public static boolean isHibernateInitialized(Object object) { if (object == null) { return false; } if (method_HibernateIsInitialized == null && !method_HibernateIsInitialized_error) { try { Class<?> class_Hibernate = Class.forName("org.hibernate.Hibernate"); method_HibernateIsInitialized = class_Hibernate.getMethod("isInitialized", Object.class); } catch (Throwable e) { // skip method_HibernateIsInitialized_error = true; } } if (method_HibernateIsInitialized != null) { try { Boolean initialized = (Boolean) method_HibernateIsInitialized.invoke(null, object); return initialized; } catch (Throwable e) { // skip } } return true; } public static double parseDouble(String str) { final int len = str.length(); if (len > 10) { return Double.parseDouble(str); } boolean negative = false; long longValue = 0; int scale = 0; for (int i = 0; i < len; ++i) { char ch = str.charAt(i); if (ch == '-' && i == 0) { negative = true; continue; } if (ch == '.') { if (scale != 0) { return Double.parseDouble(str); } scale = len - i - 1; continue; } if (ch >= '0' && ch <= '9') { int digit = ch - '0'; longValue = longValue * 10 + digit; } else { return Double.parseDouble(str); } } if (negative) { longValue = -longValue; } switch (scale) { case 0: return (double) longValue; case 1: return ((double) longValue) / 10; case 2: return ((double) longValue) / 100; case 3: return ((double) longValue) / 1000; case 4: return ((double) longValue) / 10000; case 5: return ((double) longValue) / 100000; case 6: return ((double) longValue) / 1000000; case 7: return ((double) longValue) / 10000000; case 8: return ((double) longValue) / 100000000; case 9: return ((double) longValue) / 1000000000; } return Double.parseDouble(str); } public static float parseFloat(String str) { final int len = str.length(); if (len >= 10) { return Float.parseFloat(str); } boolean negative = false; long longValue = 0; int scale = 0; for (int i = 0; i < len; ++i) { char ch = str.charAt(i); if (ch == '-' && i == 0) { negative = true; continue; } if (ch == '.') { if (scale != 0) { return Float.parseFloat(str); } scale = len - i - 1; continue; } if (ch >= '0' && ch <= '9') { int digit = ch - '0'; longValue = longValue * 10 + digit; } else { return Float.parseFloat(str); } } if (negative) { longValue = -longValue; } switch (scale) { case 0: return (float) longValue; case 1: return ((float) longValue) / 10; case 2: return ((float) longValue) / 100; case 3: return ((float) longValue) / 1000; case 4: return ((float) longValue) / 10000; case 5: return ((float) longValue) / 100000; case 6: return ((float) longValue) / 1000000; case 7: return ((float) longValue) / 10000000; case 8: return ((float) longValue) / 100000000; case 9: return ((float) longValue) / 1000000000; } return Float.parseFloat(str); } public static final long fnv1a_64_magic_hashcode = 0xcbf29ce484222325L; public static final long fnv1a_64_magic_prime = 0x100000001b3L; public static long fnv1a_64_extract(String key) { long hashCode = fnv1a_64_magic_hashcode; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch == '_' || ch == '-') { continue; } if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= fnv1a_64_magic_prime; } return hashCode; } public static long fnv1a_64_lower(String key) { long hashCode = fnv1a_64_magic_hashcode; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= fnv1a_64_magic_prime; } return hashCode; } public static long fnv1a_64(String key) { long hashCode = fnv1a_64_magic_hashcode; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); hashCode ^= ch; hashCode *= fnv1a_64_magic_prime; } return hashCode; } public static boolean isKotlin(Class clazz) { if (kotlin_metadata == null && !kotlin_metadata_error) { try { kotlin_metadata = Class.forName("kotlin.Metadata"); } catch (Throwable e) { kotlin_metadata_error = true; } } return kotlin_metadata != null && clazz.isAnnotationPresent(kotlin_metadata); } public static Constructor getKotlinConstructor(Constructor[] constructors) { return getKotlinConstructor(constructors, null); } public static Constructor getKotlinConstructor(Constructor[] constructors, String[] paramNames) { Constructor creatorConstructor = null; for (Constructor<?> constructor : constructors) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (paramNames != null && parameterTypes.length != paramNames.length) { continue; } if (parameterTypes.length > 0 && parameterTypes[parameterTypes.length - 1].getName().equals("kotlin.jvm.internal.DefaultConstructorMarker")) { continue; } if (creatorConstructor != null && creatorConstructor.getParameterTypes().length >= parameterTypes.length) { continue; } creatorConstructor = constructor; } return creatorConstructor; } public static String[] getKoltinConstructorParameters(Class clazz) { if (kotlin_kclass_constructor == null && !kotlin_class_klass_error) { try { Class class_kotlin_kclass = Class.forName("kotlin.reflect.jvm.internal.KClassImpl"); kotlin_kclass_constructor = class_kotlin_kclass.getConstructor(Class.class); } catch (Throwable e) { kotlin_class_klass_error = true; } } if (kotlin_kclass_constructor == null) { return null; } if (kotlin_kclass_getConstructors == null && !kotlin_class_klass_error) { try { Class class_kotlin_kclass = Class.forName("kotlin.reflect.jvm.internal.KClassImpl"); kotlin_kclass_getConstructors = class_kotlin_kclass.getMethod("getConstructors"); } catch (Throwable e) { kotlin_class_klass_error = true; } } if (kotlin_kfunction_getParameters == null && !kotlin_class_klass_error) { try { Class class_kotlin_kfunction = Class.forName("kotlin.reflect.KFunction"); kotlin_kfunction_getParameters = class_kotlin_kfunction.getMethod("getParameters"); } catch (Throwable e) { kotlin_class_klass_error = true; } } if (kotlin_kparameter_getName == null && !kotlin_class_klass_error) { try { Class class_kotlinn_kparameter = Class.forName("kotlin.reflect.KParameter"); kotlin_kparameter_getName = class_kotlinn_kparameter.getMethod("getName"); } catch (Throwable e) { kotlin_class_klass_error = true; } } if (kotlin_error) { return null; } try { Object constructor = null; Object kclassImpl = kotlin_kclass_constructor.newInstance(clazz); Iterable it = (Iterable) kotlin_kclass_getConstructors.invoke(kclassImpl); for (Iterator iterator = it.iterator(); iterator.hasNext(); iterator.hasNext()) { Object item = iterator.next(); List parameters = (List) kotlin_kfunction_getParameters.invoke(item); if (constructor != null && parameters.size() == 0) { continue; } constructor = item; } if (constructor == null) { return null; } List parameters = (List) kotlin_kfunction_getParameters.invoke(constructor); String[] names = new String[parameters.size()]; for (int i = 0; i < parameters.size(); i++) { Object param = parameters.get(i); names[i] = (String) kotlin_kparameter_getName.invoke(param); } return names; } catch (Throwable e) { e.printStackTrace(); kotlin_error = true; } return null; } private static boolean isKotlinIgnore(Class clazz, String methodName) { if (kotlinIgnores == null && !kotlinIgnores_error) { try { Map<Class, String[]> map = new HashMap<Class, String[]>(); Class charRangeClass = Class.forName("kotlin.ranges.CharRange"); map.put(charRangeClass, new String[]{"getEndInclusive", "isEmpty"}); Class intRangeClass = Class.forName("kotlin.ranges.IntRange"); map.put(intRangeClass, new String[]{"getEndInclusive", "isEmpty"}); Class longRangeClass = Class.forName("kotlin.ranges.LongRange"); map.put(longRangeClass, new String[]{"getEndInclusive", "isEmpty"}); Class floatRangeClass = Class.forName("kotlin.ranges.ClosedFloatRange"); map.put(floatRangeClass, new String[]{"getEndInclusive", "isEmpty"}); Class doubleRangeClass = Class.forName("kotlin.ranges.ClosedDoubleRange"); map.put(doubleRangeClass, new String[]{"getEndInclusive", "isEmpty"}); kotlinIgnores = map; } catch (Throwable error) { kotlinIgnores_error = true; } } if (kotlinIgnores == null) { return false; } String[] ignores = kotlinIgnores.get(clazz); return ignores != null && Arrays.binarySearch(ignores, methodName) >= 0; } public static <A extends Annotation> A getAnnotation(Class<?> targetClass, Class<A> annotationClass) { A targetAnnotation = targetClass.getAnnotation(annotationClass); Class<?> mixInClass = null; Type type = JSON.getMixInAnnotations(targetClass); if (type instanceof Class<?>) { mixInClass = (Class<?>) type; } if (mixInClass != null) { A mixInAnnotation = mixInClass.getAnnotation(annotationClass); Annotation[] annotations = mixInClass.getAnnotations(); if (mixInAnnotation == null && annotations.length > 0) { for (Annotation annotation : annotations) { mixInAnnotation = annotation.annotationType().getAnnotation(annotationClass); if (mixInAnnotation != null) { break; } } } if (mixInAnnotation != null) { return mixInAnnotation; } } Annotation[] targetClassAnnotations = targetClass.getAnnotations(); if (targetAnnotation == null && targetClassAnnotations.length > 0) { for (Annotation annotation : targetClassAnnotations) { targetAnnotation = annotation.annotationType().getAnnotation(annotationClass); if (targetAnnotation != null) { break; } } } return targetAnnotation; } public static <A extends Annotation> A getAnnotation(Field field, Class<A> annotationClass) { A targetAnnotation = field.getAnnotation(annotationClass); Class<?> clazz = field.getDeclaringClass(); A mixInAnnotation; Class<?> mixInClass = null; Type type = JSON.getMixInAnnotations(clazz); if (type instanceof Class<?>) { mixInClass = (Class<?>) type; } if (mixInClass != null) { Field mixInField = null; String fieldName = field.getName(); // 递归从MixIn类的父类中查找注解(如果有父类的话) for (Class<?> currClass = mixInClass; currClass != null && currClass != Object.class; currClass = currClass.getSuperclass()) { try { mixInField = currClass.getDeclaredField(fieldName); break; } catch (NoSuchFieldException e) { // skip } } if (mixInField == null) { return targetAnnotation; } mixInAnnotation = mixInField.getAnnotation(annotationClass); if (mixInAnnotation != null) { return mixInAnnotation; } } return targetAnnotation; } public static <A extends Annotation> A getAnnotation(Method method, Class<A> annotationClass) { A targetAnnotation = method.getAnnotation(annotationClass); Class<?> clazz = method.getDeclaringClass(); A mixInAnnotation; Class<?> mixInClass = null; Type type = JSON.getMixInAnnotations(clazz); if (type instanceof Class<?>) { mixInClass = (Class<?>) type; } if (mixInClass != null) { Method mixInMethod = null; String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); // 递归从MixIn类的父类中查找注解(如果有父类的话) for (Class<?> currClass = mixInClass; currClass != null && currClass != Object.class; currClass = currClass.getSuperclass()) { try { mixInMethod = currClass.getDeclaredMethod(methodName, parameterTypes); break; } catch (NoSuchMethodException e) { // skip } } if (mixInMethod == null) { return targetAnnotation; } mixInAnnotation = mixInMethod.getAnnotation(annotationClass); if (mixInAnnotation != null) { return mixInAnnotation; } } return targetAnnotation; } public static Annotation[][] getParameterAnnotations(Method method) { Annotation[][] targetAnnotations = method.getParameterAnnotations(); Class<?> clazz = method.getDeclaringClass(); Annotation[][] mixInAnnotations; Class<?> mixInClass = null; Type type = JSON.getMixInAnnotations(clazz); if (type instanceof Class<?>) { mixInClass = (Class<?>) type; } if (mixInClass != null) { Method mixInMethod = null; String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); // 递归从MixIn类的父类中查找注解(如果有父类的话) for (Class<?> currClass = mixInClass; currClass != null && currClass != Object.class; currClass = currClass.getSuperclass()) { try { mixInMethod = currClass.getDeclaredMethod(methodName, parameterTypes); break; } catch (NoSuchMethodException e) { continue; } } if (mixInMethod == null) { return targetAnnotations; } mixInAnnotations = mixInMethod.getParameterAnnotations(); if (mixInAnnotations != null) { return mixInAnnotations; } } return targetAnnotations; } public static Annotation[][] getParameterAnnotations(Constructor constructor) { Annotation[][] targetAnnotations = constructor.getParameterAnnotations(); Class<?> clazz = constructor.getDeclaringClass(); Annotation[][] mixInAnnotations; Class<?> mixInClass = null; Type type = JSON.getMixInAnnotations(clazz); if (type instanceof Class<?>) { mixInClass = (Class<?>) type; } if (mixInClass != null) { Constructor mixInConstructor = null; Class<?>[] parameterTypes = constructor.getParameterTypes(); // 构建参数列表,因为内部类的构造函数需要传入外部类的引用 List<Class<?>> enclosingClasses = new ArrayList<Class<?>>(2); for (Class<?> enclosingClass = mixInClass.getEnclosingClass(); enclosingClass != null; enclosingClass = enclosingClass.getEnclosingClass()) { enclosingClasses.add(enclosingClass); } int level = enclosingClasses.size(); // 递归从MixIn类的父类中查找注解(如果有父类的话) for (Class<?> currClass = mixInClass; currClass != null && currClass != Object.class; currClass = currClass.getSuperclass()) { try { if (level != 0) { Class<?>[] outerClassAndParameterTypes = new Class[level + parameterTypes.length]; System.arraycopy(parameterTypes, 0, outerClassAndParameterTypes, level, parameterTypes.length); for (int i = level; i > 0; i--) { outerClassAndParameterTypes[i - 1] = enclosingClasses.get(i - 1); } mixInConstructor = mixInClass.getDeclaredConstructor(outerClassAndParameterTypes); } else { mixInConstructor = mixInClass.getDeclaredConstructor(parameterTypes); } break; } catch (NoSuchMethodException e) { level--; } } if (mixInConstructor == null) { return targetAnnotations; } mixInAnnotations = mixInConstructor.getParameterAnnotations(); if (mixInAnnotations != null) { return mixInAnnotations; } } return targetAnnotations; } public static boolean isJacksonCreator(Method method) { if (method == null) { return false; } if (class_JacksonCreator == null && !class_JacksonCreator_error) { try { class_JacksonCreator = (Class<? extends Annotation>) Class.forName("com.fasterxml.jackson.annotation.JsonCreator"); } catch (Throwable e) { // skip class_JacksonCreator_error = true; } } return class_JacksonCreator != null && method.isAnnotationPresent(class_JacksonCreator); } private static Object OPTIONAL_EMPTY; private static boolean OPTIONAL_ERROR = false; public static Object optionalEmpty(Type type) { if (OPTIONAL_ERROR) { return null; } Class clazz = getClass(type); if (clazz == null) { return null; } String className = clazz.getName(); if ("java.util.Optional".equals(className)) { if (OPTIONAL_EMPTY == null) { try { Method empty = Class.forName(className).getMethod("empty"); OPTIONAL_EMPTY = empty.invoke(null); } catch (Throwable e) { OPTIONAL_ERROR = true; } } return OPTIONAL_EMPTY; } return null; } public static class MethodInheritanceComparator implements Comparator<Method> { public int compare(Method m1, Method m2) { int cmp = m1.getName().compareTo(m2.getName()); if (cmp != 0) { return cmp; } Class<?> class1 = m1.getReturnType(); Class<?> class2 = m2.getReturnType(); if (class1.equals(class2)) { return 0; } if (class1.isAssignableFrom(class2)) { return -1; } if (class2.isAssignableFrom(class1)) { return 1; } return 0; } } }
alibaba/fastjson
src/main/java/com/alibaba/fastjson/util/TypeUtils.java
715
package cn.hutool.core.date.chinese; import cn.hutool.core.lang.Pair; import cn.hutool.core.map.TableMap; import java.util.List; /** * 节假日(农历)封装 * * @author looly * @since 5.4.1 */ public class LunarFestival { //农历节日 *表示放假日 // 来自:https://baike.baidu.com/item/%E4%B8%AD%E5%9B%BD%E4%BC%A0%E7%BB%9F%E8%8A%82%E6%97%A5/396100 private static final TableMap<Pair<Integer, Integer>, String> L_FTV = new TableMap<>(16); static { // 节日 L_FTV.put(new Pair<>(1, 1), "春节"); L_FTV.put(new Pair<>(1, 2), "犬日"); L_FTV.put(new Pair<>(1, 3), "猪日"); L_FTV.put(new Pair<>(1, 4), "羊日"); L_FTV.put(new Pair<>(1, 5), "牛日 破五日"); L_FTV.put(new Pair<>(1, 6), "马日 送穷日"); L_FTV.put(new Pair<>(1, 7), "人日 人胜节"); L_FTV.put(new Pair<>(1, 8), "谷日 八仙日"); L_FTV.put(new Pair<>(1, 9), "天日 九皇会"); L_FTV.put(new Pair<>(1, 10), "地日 石头生日"); L_FTV.put(new Pair<>(1, 12), "火日 老鼠娶媳妇日"); L_FTV.put(new Pair<>(1, 13), "上(试)灯日 关公升天日"); L_FTV.put(new Pair<>(1, 15), "元宵节 上元节"); L_FTV.put(new Pair<>(1, 18), "落灯日"); // 二月 L_FTV.put(new Pair<>(2, 1), "中和节 太阳生日"); L_FTV.put(new Pair<>(2, 2), "龙抬头"); L_FTV.put(new Pair<>(2, 12), "花朝节"); L_FTV.put(new Pair<>(2, 19), "观世音圣诞"); // 三月 L_FTV.put(new Pair<>(3, 3), "上巳节"); // 四月 L_FTV.put(new Pair<>(4, 1), "祭雹神"); L_FTV.put(new Pair<>(4, 4), "文殊菩萨诞辰"); L_FTV.put(new Pair<>(4, 8), "佛诞节"); // 五月 L_FTV.put(new Pair<>(5, 5), "端午节 端阳节"); // 六月 L_FTV.put(new Pair<>(6, 6), "晒衣节 姑姑节"); L_FTV.put(new Pair<>(6, 6), "天贶节"); L_FTV.put(new Pair<>(6, 24), "彝族火把节"); // 七月 L_FTV.put(new Pair<>(7, 7), "七夕"); L_FTV.put(new Pair<>(7, 14), "鬼节(南方)"); L_FTV.put(new Pair<>(7, 15), "中元节"); L_FTV.put(new Pair<>(7, 15), "盂兰盆节 中元节"); L_FTV.put(new Pair<>(7, 30), "地藏节"); // 八月 L_FTV.put(new Pair<>(8, 15), "中秋节"); // 九月 L_FTV.put(new Pair<>(9, 9), "重阳节"); // 十月 L_FTV.put(new Pair<>(10, 1), "祭祖节"); L_FTV.put(new Pair<>(10, 15), "下元节"); // 十一月 L_FTV.put(new Pair<>(11, 17), "阿弥陀佛圣诞"); // 腊月 L_FTV.put(new Pair<>(12, 8), "腊八节"); L_FTV.put(new Pair<>(12, 16), "尾牙"); L_FTV.put(new Pair<>(12, 23), "小年"); L_FTV.put(new Pair<>(12, 30), "除夕"); } /** * 获得节日列表 * * @param year 年 * @param month 月 * @param day 日 * @return 获得农历节日 * @since 5.4.5 */ public static List<String> getFestivals(int year, int month, int day) { // 春节判断,如果12月是小月,则29为除夕,否则30为除夕 if (12 == month && 29 == day) { if (29 == LunarInfo.monthDays(year, month)) { day++; } } return getFestivals(month, day); } /** * 获得节日列表,此方法无法判断月是否为大月或小月 * * @param month 月 * @param day 日 * @return 获得农历节日 */ public static List<String> getFestivals(int month, int day) { return L_FTV.getValues(new Pair<>(month, day)); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/date/chinese/LunarFestival.java
716
package org.ansj.domain; import org.ansj.exception.LibraryException; import java.io.Serializable; /** * 人名标注pojo类 * * @author ansj */ public class PersonNatureAttr implements Serializable { public static final PersonNatureAttr NULL = new PersonNatureAttr(); private float B = 0;//姓氏 private float C = 0;//双名的首字 private float D = 0;//双名的末字 private float E = 0;//单名 private float K = 0;//上文 private float L = 0;//下文 private float M = 0;//下文 private float Y = 0;//姓与单名成词 private float U = 0 ;//人名的上文和姓成词 private float V = 0 ;//名的末字和下文成词 private float X = 0;//姓与双名的首字成词 private float Z = 0;//双名本身成词 private float A = 0;//双名本身成词 private boolean active; public boolean isActive() { return active; } public float getB() { return B; } public float getC() { return C; } public float getD() { return D; } public float getE() { return E; } public float getK() { return K; } public float getL() { return L; } public float getX() { return X; } public float getY() { return Y; } public float getZ() { return Z; } public float getM() { return M; } public float getA() { return A; } public float getU() { return U; } public float getV() { return V; } public void set(char c, float value) { switch (c) { case 'B': if(value > 0 ) { active = true; } B = value; break; case 'C': C = value; break; case 'D': D = value; break; case 'E': E = value; break; case 'K': K = value; break; case 'L': L = value; break; case 'M': M = value; break; case 'X': if(value > 0 ) { active = true; } X = value; break; case 'Y': Y = value; break; case 'Z': Z = value; break; case 'A': A = value; break; case 'U': U = value; break; case 'V': U = value; break; default: throw new LibraryException("person name status err " + c); } } }
NLPchina/ansj_seg
src/main/java/org/ansj/domain/PersonNatureAttr.java
717
package cn.hutool.db.dialect; /** * 常用数据库驱动池 * * @author looly * @since 5.6.3 */ public interface DriverNamePool { /** * JDBC 驱动 MySQL */ String DRIVER_MYSQL = "com.mysql.jdbc.Driver"; /** * JDBC 驱动 MySQL,在6.X版本中变动驱动类名,且使用SPI机制 */ String DRIVER_MYSQL_V6 = "com.mysql.cj.jdbc.Driver"; /** * JDBC 驱动 MariaDB */ String DRIVER_MARIADB = "org.mariadb.jdbc.Driver"; /** * JDBC 驱动 Oracle */ String DRIVER_ORACLE = "oracle.jdbc.OracleDriver"; /** * JDBC 驱动 Oracle,旧版使用 */ String DRIVER_ORACLE_OLD = "oracle.jdbc.driver.OracleDriver"; /** * JDBC 驱动 PostgreSQL */ String DRIVER_POSTGRESQL = "org.postgresql.Driver"; /** * JDBC 驱动 SQLLite3 */ String DRIVER_SQLLITE3 = "org.sqlite.JDBC"; /** * JDBC 驱动 SQLServer */ String DRIVER_SQLSERVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; /** * JDBC 驱动 Hive */ String DRIVER_HIVE = "org.apache.hadoop.hive.jdbc.HiveDriver"; /** * JDBC 驱动 Hive2 */ String DRIVER_HIVE2 = "org.apache.hive.jdbc.HiveDriver"; /** * JDBC 驱动 H2 */ String DRIVER_H2 = "org.h2.Driver"; /** * JDBC 驱动 Derby */ String DRIVER_DERBY = "org.apache.derby.jdbc.AutoloadedDriver"; /** * JDBC 驱动 HSQLDB */ String DRIVER_HSQLDB = "org.hsqldb.jdbc.JDBCDriver"; /** * JDBC 驱动 达梦7 */ String DRIVER_DM7 = "dm.jdbc.driver.DmDriver"; /** * JDBC 驱动 人大金仓 */ String DRIVER_KINGBASE8 = "com.kingbase8.Driver"; /** * JDBC 驱动 Ignite thin */ String DRIVER_IGNITE_THIN = "org.apache.ignite.IgniteJdbcThinDriver"; /** * JDBC 驱动 ClickHouse */ String DRIVER_CLICK_HOUSE = "com.clickhouse.jdbc.ClickHouseDriver"; /** * JDBC 驱动 瀚高数据库 */ String DRIVER_HIGHGO = "com.highgo.jdbc.Driver"; /** * JDBC 驱动 DB2 */ String DRIVER_DB2 = "com.ibm.db2.jdbc.app.DB2Driver"; /** * JDBC 驱动 虚谷数据库 */ String DRIVER_XUGU = "com.xugu.cloudjdbc.Driver"; /** * JDBC 驱动 Apache Phoenix */ String DRIVER_PHOENIX = "org.apache.phoenix.jdbc.PhoenixDriver"; /** * JDBC 驱动 华为高斯 */ String DRIVER_GAUSS = "com.huawei.gauss.jdbc.ZenithDriver"; /** * JDBC 驱动 南大通用 */ String DRIVER_GBASE = "com.gbase.jdbc.Driver"; /** * JDBC 驱动 神州数据库 */ String DRIVER_OSCAR = "com.oscar.Driver"; /** * JDBC 驱动 Sybase */ String DRIVER_SYBASE = "com.sybase.jdbc4.jdbc.SybDriver"; /** * JDBC 驱动 OpenGauss */ String DRIVER_OPENGAUSS = "org.opengauss.Driver"; }
dromara/hutool
hutool-db/src/main/java/cn/hutool/db/dialect/DriverNamePool.java
718
E tags: String, Stack time: O(n) space: O(n) #### Stack - 剥皮过程。解铃还须系铃人 - 左边的外皮'{['在stack底部 - 右边的外皮应该和stack顶上的左外皮一一对应 ``` /* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Example The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. Tags Expand Stack */ class Solution { public boolean isValid(String s) { if (s == null) return true; if (s.length() % 2 != 0) return false; Stack<Character> stack = new Stack<>(); for (char c : s.toCharArray()) { if (stack.isEmpty() || (c == '(' || c == '{' || c == '[')) stack.push(c); else if (validate(stack.peek(), c)) stack.pop(); else return false; } return stack.isEmpty(); } private boolean validate(char a, char b) { if (a == '(') return b == ')'; if (a == '{') return b == '}'; if (a == '[') return b == ']'; return false; } } ```
awangdev/leet-code
Java/20. Valid Parentheses.java
720
package org.ansj.splitWord.analysis; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.recognition.arrimpl.NumRecognition; import org.ansj.recognition.arrimpl.PersonRecognition; import org.ansj.recognition.arrimpl.UserDefineRecognition; import org.ansj.splitWord.Analysis; import org.ansj.util.AnsjReader; import org.ansj.util.Graph; import org.ansj.util.TermUtil.InsertTermType; import org.nlpcn.commons.lang.tire.domain.Forest; import java.io.Reader; import java.util.ArrayList; import java.util.List; /** * 标准分词 * * @author ansj */ public class ToAnalysis extends Analysis { @Override protected List<Term> getResult(final Graph graph) { Merger merger = new Merger() { @Override public List<Term> merger() { graph.walkPath(); // 姓名识别 if (graph.hasPerson && isNameRecognition) { // 人名识别 new PersonRecognition().recognition(graph); } // 数字发现 if (isNumRecognition) { new NumRecognition(isQuantifierRecognition && graph.hasNumQua).recognition(graph); } // 用户自定义词典的识别 userDefineRecognition(graph, forests); return getResult(); } private void userDefineRecognition(final Graph graph, Forest... forests) { new UserDefineRecognition(InsertTermType.SKIP, forests).recognition(graph); graph.rmLittlePath(); graph.walkPathByScore(); } private List<Term> getResult() { List<Term> result = new ArrayList<Term>(); int length = graph.terms.length - 1; for (int i = 0; i < length; i++) { if (graph.terms[i] != null) { setIsNewWord(graph.terms[i]) ; result.add(graph.terms[i]); } } setRealName(graph, result); return result; } }; return merger.merger(); } public ToAnalysis() { super(); } public ToAnalysis(Reader reader) { super.resetContent(new AnsjReader(reader)); } public static Result parse(String str) { return new ToAnalysis().parseStr(str); } public static Result parse(String str, Forest... forests) { return new ToAnalysis().setForests(forests).parseStr(str); } }
NLPchina/ansj_seg
src/main/java/org/ansj/splitWord/analysis/ToAnalysis.java
721
package cn.hutool.extra.mail; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.setting.Setting; import java.io.Serializable; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * 邮件账户对象 * * @author Luxiaolei */ public class MailAccount implements Serializable { private static final long serialVersionUID = -6937313421815719204L; private static final String MAIL_PROTOCOL = "mail.transport.protocol"; private static final String SMTP_HOST = "mail.smtp.host"; private static final String SMTP_PORT = "mail.smtp.port"; private static final String SMTP_AUTH = "mail.smtp.auth"; private static final String SMTP_TIMEOUT = "mail.smtp.timeout"; private static final String SMTP_CONNECTION_TIMEOUT = "mail.smtp.connectiontimeout"; private static final String SMTP_WRITE_TIMEOUT = "mail.smtp.writetimeout"; // SSL private static final String STARTTLS_ENABLE = "mail.smtp.starttls.enable"; private static final String SSL_ENABLE = "mail.smtp.ssl.enable"; private static final String SSL_PROTOCOLS = "mail.smtp.ssl.protocols"; private static final String SOCKET_FACTORY = "mail.smtp.socketFactory.class"; private static final String SOCKET_FACTORY_FALLBACK = "mail.smtp.socketFactory.fallback"; private static final String SOCKET_FACTORY_PORT = "smtp.socketFactory.port"; // System Properties private static final String SPLIT_LONG_PARAMS = "mail.mime.splitlongparameters"; //private static final String ENCODE_FILE_NAME = "mail.mime.encodefilename"; //private static final String CHARSET = "mail.mime.charset"; // 其他 private static final String MAIL_DEBUG = "mail.debug"; public static final String[] MAIL_SETTING_PATHS = new String[]{"config/mail.setting", "config/mailAccount.setting", "mail.setting"}; /** * SMTP服务器域名 */ private String host; /** * SMTP服务端口 */ private Integer port; /** * 是否需要用户名密码验证 */ private Boolean auth; /** * 用户名 */ private String user; /** * 密码 */ private String pass; /** * 发送方,遵循RFC-822标准 */ private String from; /** * 是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启 */ private boolean debug; /** * 编码用于编码邮件正文和发送人、收件人等中文 */ private Charset charset = CharsetUtil.CHARSET_UTF_8; /** * 对于超长参数是否切分为多份,默认为false(国内邮箱附件不支持切分的附件名) */ private boolean splitlongparameters = false; /** * 对于文件名是否使用{@link #charset}编码,默认为 {@code true} */ private boolean encodefilename = true; /** * 使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口。 */ private boolean starttlsEnable = false; /** * 使用 SSL安全连接 */ private Boolean sslEnable; /** * SSL协议,多个协议用空格分隔 */ private String sslProtocols; /** * 指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字 */ private String socketFactoryClass = "javax.net.ssl.SSLSocketFactory"; /** * 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true */ private boolean socketFactoryFallback; /** * 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口 */ private int socketFactoryPort = 465; /** * SMTP超时时长,单位毫秒,缺省值不超时 */ private long timeout; /** * Socket连接超时值,单位毫秒,缺省值不超时 */ private long connectionTimeout; /** * Socket写出超时值,单位毫秒,缺省值不超时 */ private long writeTimeout; /** * 自定义的其他属性,此自定义属性会覆盖默认属性 */ private final Map<String, Object> customProperty = new HashMap<>(); // -------------------------------------------------------------- Constructor start /** * 构造,所有参数需自行定义或保持默认值 */ public MailAccount() { } /** * 构造 * * @param settingPath 配置文件路径 */ public MailAccount(String settingPath) { this(new Setting(settingPath)); } /** * 构造 * * @param setting 配置文件 */ public MailAccount(Setting setting) { setting.toBean(this); } // -------------------------------------------------------------- Constructor end /** * 获得SMTP服务器域名 * * @return SMTP服务器域名 */ public String getHost() { return host; } /** * 设置SMTP服务器域名 * * @param host SMTP服务器域名 * @return this */ public MailAccount setHost(String host) { this.host = host; return this; } /** * 获得SMTP服务端口 * * @return SMTP服务端口 */ public Integer getPort() { return port; } /** * 设置SMTP服务端口 * * @param port SMTP服务端口 * @return this */ public MailAccount setPort(Integer port) { this.port = port; return this; } /** * 是否需要用户名密码验证 * * @return 是否需要用户名密码验证 */ public Boolean isAuth() { return auth; } /** * 设置是否需要用户名密码验证 * * @param isAuth 是否需要用户名密码验证 * @return this */ public MailAccount setAuth(boolean isAuth) { this.auth = isAuth; return this; } /** * 获取用户名 * * @return 用户名 */ public String getUser() { return user; } /** * 设置用户名 * * @param user 用户名 * @return this */ public MailAccount setUser(String user) { this.user = user; return this; } /** * 获取密码 * * @return 密码 */ public String getPass() { return pass; } /** * 设置密码 * * @param pass 密码 * @return this */ public MailAccount setPass(String pass) { this.pass = pass; return this; } /** * 获取发送方,遵循RFC-822标准 * * @return 发送方,遵循RFC-822标准 */ public String getFrom() { return from; } /** * 设置发送方,遵循RFC-822标准<br> * 发件人可以是以下形式: * * <pre> * 1. [email protected] * 2. name &lt;[email protected]&gt; * </pre> * * @param from 发送方,遵循RFC-822标准 * @return this */ public MailAccount setFrom(String from) { this.from = from; return this; } /** * 是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启 * * @return 是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启 * @since 4.0.2 */ public boolean isDebug() { return debug; } /** * 设置是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启 * * @param debug 是否打开调试模式,调试模式会显示与邮件服务器通信过程,默认不开启 * @return this * @since 4.0.2 */ public MailAccount setDebug(boolean debug) { this.debug = debug; return this; } /** * 获取字符集编码 * * @return 编码,可能为{@code null} */ public Charset getCharset() { return charset; } /** * 设置字符集编码,此选项不会修改全局配置,若修改全局配置,请设置此项为{@code null}并设置: * <pre> * System.setProperty("mail.mime.charset", charset); * </pre> * * @param charset 字符集编码,{@code null} 则表示使用全局设置的默认编码,全局编码为mail.mime.charset系统属性 * @return this */ public MailAccount setCharset(Charset charset) { this.charset = charset; return this; } /** * 对于超长参数是否切分为多份,默认为false(国内邮箱附件不支持切分的附件名) * * @return 对于超长参数是否切分为多份 */ public boolean isSplitlongparameters() { return splitlongparameters; } /** * 设置对于超长参数是否切分为多份,默认为false(国内邮箱附件不支持切分的附件名)<br> * 注意此项为全局设置,此项会调用 * <pre> * System.setProperty("mail.mime.splitlongparameters", true) * </pre> * * @param splitlongparameters 对于超长参数是否切分为多份 */ public void setSplitlongparameters(boolean splitlongparameters) { this.splitlongparameters = splitlongparameters; } /** * 对于文件名是否使用{@link #charset}编码,默认为 {@code true} * * @return 对于文件名是否使用{@link #charset}编码,默认为 {@code true} * @since 5.7.16 */ public boolean isEncodefilename() { return encodefilename; } /** * 设置对于文件名是否使用{@link #charset}编码,此选项不会修改全局配置<br> * 如果此选项设置为{@code false},则是否编码取决于两个系统属性: * <ul> * <li>mail.mime.encodefilename 是否编码附件文件名</li> * <li>mail.mime.charset 编码文件名的编码</li> * </ul> * * @param encodefilename 对于文件名是否使用{@link #charset}编码 * @since 5.7.16 */ public void setEncodefilename(boolean encodefilename) { this.encodefilename = encodefilename; } /** * 是否使用 STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口。 * * @return 是否使用 STARTTLS安全连接 */ public boolean isStarttlsEnable() { return this.starttlsEnable; } /** * 设置是否使用STARTTLS安全连接,STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口。 * * @param startttlsEnable 是否使用STARTTLS安全连接 * @return this */ public MailAccount setStarttlsEnable(boolean startttlsEnable) { this.starttlsEnable = startttlsEnable; return this; } /** * 是否使用 SSL安全连接 * * @return 是否使用 SSL安全连接 */ public Boolean isSslEnable() { return this.sslEnable; } /** * 设置是否使用SSL安全连接 * * @param sslEnable 是否使用SSL安全连接 * @return this */ public MailAccount setSslEnable(Boolean sslEnable) { this.sslEnable = sslEnable; return this; } /** * 获取SSL协议,多个协议用空格分隔 * * @return SSL协议,多个协议用空格分隔 * @since 5.5.7 */ public String getSslProtocols() { return sslProtocols; } /** * 设置SSL协议,多个协议用空格分隔 * * @param sslProtocols SSL协议,多个协议用空格分隔 * @since 5.5.7 */ public void setSslProtocols(String sslProtocols) { this.sslProtocols = sslProtocols; } /** * 获取指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字 * * @return 指定实现javax.net.SocketFactory接口的类的名称, 这个类将被用于创建SMTP的套接字 */ public String getSocketFactoryClass() { return socketFactoryClass; } /** * 设置指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字 * * @param socketFactoryClass 指定实现javax.net.SocketFactory接口的类的名称,这个类将被用于创建SMTP的套接字 * @return this */ public MailAccount setSocketFactoryClass(String socketFactoryClass) { this.socketFactoryClass = socketFactoryClass; return this; } /** * 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true * * @return 如果设置为true, 未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true */ public boolean isSocketFactoryFallback() { return socketFactoryFallback; } /** * 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true * * @param socketFactoryFallback 如果设置为true,未能创建一个套接字使用指定的套接字工厂类将导致使用java.net.Socket创建的套接字类, 默认值为true * @return this */ public MailAccount setSocketFactoryFallback(boolean socketFactoryFallback) { this.socketFactoryFallback = socketFactoryFallback; return this; } /** * 获取指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口 * * @return 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口 */ public int getSocketFactoryPort() { return socketFactoryPort; } /** * 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口 * * @param socketFactoryPort 指定的端口连接到在使用指定的套接字工厂。如果没有设置,将使用默认端口 * @return this */ public MailAccount setSocketFactoryPort(int socketFactoryPort) { this.socketFactoryPort = socketFactoryPort; return this; } /** * 设置SMTP超时时长,单位毫秒,缺省值不超时 * * @param timeout SMTP超时时长,单位毫秒,缺省值不超时 * @return this * @since 4.1.17 */ public MailAccount setTimeout(long timeout) { this.timeout = timeout; return this; } /** * 设置Socket连接超时值,单位毫秒,缺省值不超时 * * @param connectionTimeout Socket连接超时值,单位毫秒,缺省值不超时 * @return this * @since 4.1.17 */ public MailAccount setConnectionTimeout(long connectionTimeout) { this.connectionTimeout = connectionTimeout; return this; } /** * 设置Socket写出超时值,单位毫秒,缺省值不超时 * * @param writeTimeout Socket写出超时值,单位毫秒,缺省值不超时 * @return this * @since 5.8.3 */ public MailAccount setWriteTimeout(long writeTimeout) { this.writeTimeout = writeTimeout; return this; } /** * 获取自定义属性列表 * * @return 自定义参数列表 * @since 5.6.4 */ public Map<String, Object> getCustomProperty() { return customProperty; } /** * 设置自定义属性,如mail.smtp.ssl.socketFactory * * @param key 属性名,空白被忽略 * @param value 属性值, null被忽略 * @return this * @since 5.6.4 */ public MailAccount setCustomProperty(String key, Object value) { if (StrUtil.isNotBlank(key) && ObjectUtil.isNotNull(value)) { this.customProperty.put(key, value); } return this; } /** * 获得SMTP相关信息 * * @return {@link Properties} */ public Properties getSmtpProps() { //全局系统参数 System.setProperty(SPLIT_LONG_PARAMS, String.valueOf(this.splitlongparameters)); final Properties p = new Properties(); p.put(MAIL_PROTOCOL, "smtp"); p.put(SMTP_HOST, this.host); p.put(SMTP_PORT, String.valueOf(this.port)); p.put(SMTP_AUTH, String.valueOf(this.auth)); if (this.timeout > 0) { p.put(SMTP_TIMEOUT, String.valueOf(this.timeout)); } if (this.connectionTimeout > 0) { p.put(SMTP_CONNECTION_TIMEOUT, String.valueOf(this.connectionTimeout)); } // issue#2355 if (this.writeTimeout > 0) { p.put(SMTP_WRITE_TIMEOUT, String.valueOf(this.writeTimeout)); } p.put(MAIL_DEBUG, String.valueOf(this.debug)); if (this.starttlsEnable) { //STARTTLS是对纯文本通信协议的扩展。它将纯文本连接升级为加密连接(TLS或SSL), 而不是使用一个单独的加密通信端口。 p.put(STARTTLS_ENABLE, "true"); if (null == this.sslEnable) { //为了兼容旧版本,当用户没有此项配置时,按照starttlsEnable开启状态时对待 this.sslEnable = true; } } // SSL if (null != this.sslEnable && this.sslEnable) { p.put(SSL_ENABLE, "true"); p.put(SOCKET_FACTORY, socketFactoryClass); p.put(SOCKET_FACTORY_FALLBACK, String.valueOf(this.socketFactoryFallback)); p.put(SOCKET_FACTORY_PORT, String.valueOf(this.socketFactoryPort)); // issue#IZN95@Gitee,在Linux下需自定义SSL协议版本 if (StrUtil.isNotBlank(this.sslProtocols)) { p.put(SSL_PROTOCOLS, this.sslProtocols); } } // 补充自定义属性,允许自定属性覆盖已经设置的值 p.putAll(this.customProperty); return p; } /** * 如果某些值为null,使用默认值 * * @return this */ public MailAccount defaultIfEmpty() { // 去掉发件人的姓名部分 final String fromAddress = InternalMailUtil.parseFirstAddress(this.from, this.charset).getAddress(); if (StrUtil.isBlank(this.host)) { // 如果SMTP地址为空,默认使用smtp.<发件人邮箱后缀> this.host = StrUtil.format("smtp.{}", StrUtil.subSuf(fromAddress, fromAddress.indexOf('@') + 1)); } if (StrUtil.isBlank(user)) { // 如果用户名为空,默认为发件人(issue#I4FYVY@Gitee) //this.user = StrUtil.subPre(fromAddress, fromAddress.indexOf('@')); this.user = fromAddress; } if (null == this.auth) { // 如果密码非空白,则使用认证模式 this.auth = (false == StrUtil.isBlank(this.pass)); } if (null == this.port) { // 端口在SSL状态下默认与socketFactoryPort一致,非SSL状态下默认为25 this.port = (null != this.sslEnable && this.sslEnable) ? this.socketFactoryPort : 25; } if (null == this.charset) { // 默认UTF-8编码 this.charset = CharsetUtil.CHARSET_UTF_8; } return this; } @Override public String toString() { return "MailAccount [host=" + host + ", port=" + port + ", auth=" + auth + ", user=" + user + ", pass=" + (StrUtil.isEmpty(this.pass) ? "" : "******") + ", from=" + from + ", startttlsEnable=" + starttlsEnable + ", socketFactoryClass=" + socketFactoryClass + ", socketFactoryFallback=" + socketFactoryFallback + ", socketFactoryPort=" + socketFactoryPort + "]"; } }
dromara/hutool
hutool-extra/src/main/java/cn/hutool/extra/mail/MailAccount.java
722
M 1516439472 tags: Array, Two Pointers, Binary Search, Lint 与 2sum II - input array is sorted类似. 都是sort array, 然后two pointer. LintCode的题. 注意找的是greater/bigger than target。 由于给定条件允许O(nLogn): sort two pointer while里面two pointer移动。每次如果num[left]+num[right] > target,那么其中所有num[left++]的加上num[right]都>target. 也就是,num[right]不动,计算加入挪动left能有多少组,那就是: right-left这么多。 全部加到count上去。 然后right--.换个right去和前面的left部分作比较。 ``` /* Given an array of integers, find how many pairs in the array such that their sum is bigger than a specific target number. Please return the number of pairs. Example numbers=[2, 7, 11, 15], target=24 return 1 Challenge Either of the following solutions are acceptable: O(1) Space, O(nlogn) Time Tags Expand Two Pointers */ /* Thoughts: After doing Trigle Count...Can we just do the same for this, move while pointers to center? OMG. The original idea was sooooooo complicated. */ public class Solution { public int twoSum2(int[] nums, int target) { if (nums == null || nums.length == 0) { return 0; } int count = 0; int left = 0; int right = nums.length - 1; Arrays.sort(nums); while (left < right) { if (nums[left] + nums[right] > target) { count += (right - left); right--; } else { left++; } } return count; } } //Below are bad solutions. Don't worry about them /* Thoughts: 1. For loop to try each element from (i ~ end). O(n) 2. In for, do binary search on nums[i] + nums[j] > target, 3. count += (length - j) Note: when not found, return nums.length, because at then end, (length - length) == 0, which will be added to count. Note: Always pin target down, and move mid to compare. Don't get confused Also, take care of corner cases. */ public class Solution { public int twoSum2(int[] nums, int target) { if (nums == null || nums.length == 0) { return 0; } int count = 0; Arrays.sort(nums); for (int i = 1; i < nums.length; i++) { int index = binarySearch(nums, target - nums[i - 1], i, nums.length - 1); count += nums.length - index; } return count; } public int binarySearch(int[] nums, int target, int start, int end) { int mid; int sum; while (start + 1 < end) { mid = start + (end - start) /2; if (mid - 1 >= 0 && nums[mid-1] <= target && target < nums[mid]) { return mid; } else if (mid + 1 < nums.length && nums[mid] <= target && target < nums[mid + 1]) { return mid + 1; } else if (target < nums[mid]) { end = mid; } else { start = mid; } } if (nums[start] > target) { return start; } return (nums[end] > target) ? end : nums.length; } } //Brutle force, O(n^2) public class Solution { public int twoSum2(int[] nums, int target) { if (nums == null || nums.length == 0) { return 0; } int count = 0; for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { count += (nums[i] + nums[j] > target) ? 1 : 0; } } } } ```
awangdev/leet-code
Java/[lint]. 2 Sum II.java
726
package skiplist; /** * 跳表的一种实现方法。 * 跳表中存储的是正整数,并且存储的是不重复的。 * * Author:ZHENG */ public class SkipList { private static final float SKIPLIST_P = 0.5f; private static final int MAX_LEVEL = 16; private int levelCount = 1; private Node head = new Node(); // 带头链表 public Node find(int value) { Node p = head; for (int i = levelCount - 1; i >= 0; --i) { while (p.forwards[i] != null && p.forwards[i].data < value) { p = p.forwards[i]; } } if (p.forwards[0] != null && p.forwards[0].data == value) { return p.forwards[0]; } else { return null; } } public void insert(int value) { int level = randomLevel(); Node newNode = new Node(); newNode.data = value; newNode.maxLevel = level; Node update[] = new Node[level]; for (int i = 0; i < level; ++i) { update[i] = head; } // record every level largest value which smaller than insert value in update[] Node p = head; for (int i = level - 1; i >= 0; --i) { while (p.forwards[i] != null && p.forwards[i].data < value) { p = p.forwards[i]; } update[i] = p;// use update save node in search path } // in search path node next node become new node forwords(next) for (int i = 0; i < level; ++i) { newNode.forwards[i] = update[i].forwards[i]; update[i].forwards[i] = newNode; } // update node hight if (levelCount < level) levelCount = level; } public void delete(int value) { Node[] update = new Node[levelCount]; Node p = head; for (int i = levelCount - 1; i >= 0; --i) { while (p.forwards[i] != null && p.forwards[i].data < value) { p = p.forwards[i]; } update[i] = p; } if (p.forwards[0] != null && p.forwards[0].data == value) { for (int i = levelCount - 1; i >= 0; --i) { if (update[i].forwards[i] != null && update[i].forwards[i].data == value) { update[i].forwards[i] = update[i].forwards[i].forwards[i]; } } } while (levelCount>1&&head.forwards[levelCount]==null){ levelCount--; } } // 理论来讲,一级索引中元素个数应该占原始数据的 50%,二级索引中元素个数占 25%,三级索引12.5% ,一直到最顶层。 // 因为这里每一层的晋升概率是 50%。对于每一个新插入的节点,都需要调用 randomLevel 生成一个合理的层数。 // 该 randomLevel 方法会随机生成 1~MAX_LEVEL 之间的数,且 : // 50%的概率返回 1 // 25%的概率返回 2 // 12.5%的概率返回 3 ... private int randomLevel() { int level = 1; while (Math.random() < SKIPLIST_P && level < MAX_LEVEL) level += 1; return level; } public void printAll() { Node p = head; while (p.forwards[0] != null) { System.out.print(p.forwards[0] + " "); p = p.forwards[0]; } System.out.println(); } public class Node { private int data = -1; private Node forwards[] = new Node[MAX_LEVEL]; private int maxLevel = 0; @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{ data: "); builder.append(data); builder.append("; levels: "); builder.append(maxLevel); builder.append(" }"); return builder.toString(); } } }
wangzheng0822/algo
java/17_skiplist/SkipList.java
727
package cn.hutool.core.map; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.lang.Opt; import cn.hutool.core.util.ObjectUtil; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; /** * 基于多个{@link TreeEntry}构成的、彼此平行的树结构构成的森林集合。 * * @param <K> key类型 * @param <V> value类型 * @author huangchengxing * @see TreeEntry */ public interface ForestMap<K, V> extends Map<K, TreeEntry<K, V>> { // ===================== Map接口方法的重定义 ===================== /** * 添加一个节点,效果等同于 {@code putNode(key, node.getValue())} * <ul> * <li>若key对应节点不存在,则以传入的键值创建一个新的节点;</li> * <li>若key对应节点存在,则将该节点的值替换为{@code node}指定的值;</li> * </ul> * * @param key 节点的key值 * @param node 节点 * @return 节点,若key已有对应节点,则返回具有旧值的节点,否则返回null * @see #putNode(Object, Object) */ @Override default TreeEntry<K, V> put(K key, TreeEntry<K, V> node) { return putNode(key, node.getValue()); } /** * 批量添加节点,若节点具有父节点或者子节点,则一并在当前实例中引入该关系 * * @param treeEntryMap 节点集合 */ @Override default void putAll(Map<? extends K, ? extends TreeEntry<K, V>> treeEntryMap) { if (CollUtil.isEmpty(treeEntryMap)) { return; } treeEntryMap.forEach((k, v) -> { if (v.hasParent()) { final TreeEntry<K, V> parent = v.getDeclaredParent(); putLinkedNodes(parent.getKey(), parent.getValue(), v.getKey(), v.getValue()); } else { putNode(v.getKey(), v.getValue()); } }); } /** * 将指定节点从当前{@link Map}中删除 * <ul> * <li>若存在父节点或子节点,则将其断开其与父节点或子节点的引用关系;</li> * <li> * 若同时存在父节点或子节点,则会在删除后将让子节点直接成为父节点的子节点,比如:<br> * 现有引用关系 a -&gt; b -&gt; c,删除 b 后,将有 a -&gt; c * </li> * </ul> * * @param key 节点的key * @return 删除的节点,若key没有对应节点,则返回null */ @Override TreeEntry<K, V> remove(Object key); /** * 将当前集合清空,并清除全部节点间的引用关系 */ @Override void clear(); // ===================== 节点操作 ===================== /** * 批量添加节点 * * @param <C> 集合类型 * @param values 要添加的值 * @param keyGenerator 从值中获取key的方法 * @param parentKeyGenerator 从值中获取父节点key的方法 * @param ignoreNullNode 是否获取到的key为null的子节点/父节点 */ default <C extends Collection<V>> void putAllNode( C values, Function<V, K> keyGenerator, Function<V, K> parentKeyGenerator, boolean ignoreNullNode) { if (CollUtil.isEmpty(values)) { return; } values.forEach(v -> { final K key = keyGenerator.apply(v); final K parentKey = parentKeyGenerator.apply(v); // 不忽略keu为null节点 final boolean hasKey = ObjectUtil.isNotNull(key); final boolean hasParentKey = ObjectUtil.isNotNull(parentKey); if (!ignoreNullNode || (hasKey && hasParentKey)) { linkNodes(parentKey, key); get(key).setValue(v); return; } // 父子节点的key都为null if (!hasKey && !hasParentKey) { return; } // 父节点key为null if (hasKey) { putNode(key, v); return; } // 子节点key为null putNode(parentKey, null); }); } /** * 添加一个节点 * <ul> * <li>若key对应节点不存在,则以传入的键值创建一个新的节点;</li> * <li>若key对应节点存在,则将该节点的值替换为{@code node}指定的值;</li> * </ul> * * @param key 节点的key * @param value 节点的value * @return 节点,若key已有对应节点,则返回具有旧值的节点,否则返回null */ TreeEntry<K, V> putNode(K key, V value); /** * 同时添加父子节点: * <ul> * <li>若{@code parentKey}或{@code childKey}对应的节点不存在,则会根据键值创建一个对应的节点;</li> * <li>若{@code parentKey}或{@code childKey}对应的节点存在,则会更新对应节点的值;</li> * </ul> * 该操作等同于: * <pre>{@code * putNode(parentKey, parentValue); * putNode(childKey, childValue); * linkNodes(parentKey, childKey); * }</pre> * * @param parentKey 父节点的key * @param parentValue 父节点的value * @param childKey 子节点的key * @param childValue 子节点的值 */ default void putLinkedNodes(K parentKey, V parentValue, K childKey, V childValue) { putNode(parentKey, parentValue); putNode(childKey, childValue); linkNodes(parentKey, childKey); } /** * 添加子节点,并为子节点指定父节点: * <ul> * <li>若{@code parentKey}或{@code childKey}对应的节点不存在,则会根据键值创建一个对应的节点;</li> * <li>若{@code parentKey}或{@code childKey}对应的节点存在,则会更新对应节点的值;</li> * </ul> * * @param parentKey 父节点的key * @param childKey 子节点的key * @param childValue 子节点的值 */ void putLinkedNodes(K parentKey, K childKey, V childValue); /** * 为集合中的指定的节点建立父子关系 * * @param parentKey 父节点的key * @param childKey 子节点的key */ default void linkNodes(K parentKey, K childKey) { linkNodes(parentKey, childKey, null); } /** * 为集合中的指定的节点建立父子关系 * * @param parentKey 父节点的key * @param childKey 子节点的key * @param consumer 对父节点和子节点的操作,允许为null */ void linkNodes(K parentKey, K childKey, BiConsumer<TreeEntry<K, V>, TreeEntry<K, V>> consumer); /** * 若{@code parentKey}或{@code childKey}对应节点都存在,则移除指定该父节点与其直接关联的指定子节点间的引用关系 * * @param parentKey 父节点的key * @param childKey 子节点 */ void unlinkNode(K parentKey, K childKey); // ===================== 父节点相关方法 ===================== /** * 获取指定节点所在树结构的全部树节点 <br> * 比如:存在 a -&gt; b -&gt; c 的关系,则输入 a/b/c 都将返回 a, b, c * * @param key 指定节点的key * @return 节点 */ default Set<TreeEntry<K, V>> getTreeNodes(K key) { final TreeEntry<K, V> target = get(key); if (ObjectUtil.isNull(target)) { return Collections.emptySet(); } final Set<TreeEntry<K, V>> results = CollUtil.newLinkedHashSet(target.getRoot()); CollUtil.addAll(results, target.getRoot().getChildren().values()); return results; } /** * 获取以指定节点作为叶子节点的树结构,然后获取该树结构的根节点 <br> * 比如:存在 a -&gt; b -&gt; c 的关系,则输入 a/b/c 都将返回 a * * @param key 指定节点的key * @return 节点 */ default TreeEntry<K, V> getRootNode(K key) { return Opt.ofNullable(get(key)) .map(TreeEntry::getRoot) .orElse(null); } /** * 获取指定节点的直接父节点 <br> * 比如:若存在 a -&gt; b -&gt; c 的关系,此时输入 a 将返回 null,输入 b 将返回 a,输入 c 将返回 b * * @param key 指定节点的key * @return 节点 */ default TreeEntry<K, V> getDeclaredParentNode(K key) { return Opt.ofNullable(get(key)) .map(TreeEntry::getDeclaredParent) .orElse(null); } /** * 获取以指定节点作为叶子节点的树结构,然后获取该树结构中指定节点的指定父节点 * * @param key 指定节点的key * @param parentKey 指定父节点key * @return 节点 */ default TreeEntry<K, V> getParentNode(K key, K parentKey) { return Opt.ofNullable(get(key)) .map(t -> t.getParent(parentKey)) .orElse(null); } /** * 获取以指定节点作为叶子节点的树结构,然后确认该树结构中当前节点是否存在指定父节点 * * @param key 指定节点的key * @param parentKey 指定父节点的key * @return 是否 */ default boolean containsParentNode(K key, K parentKey) { return Opt.ofNullable(get(key)) .map(m -> m.containsParent(parentKey)) .orElse(false); } /** * 获取指定节点的值 * * @param key 节点的key * @return 节点值,若节点不存在,或节点值为null都将返回null */ default V getNodeValue(K key) { return Opt.ofNullable(get(key)) .map(TreeEntry::getValue) .get(); } // ===================== 子节点相关方法 ===================== /** * 判断以该父节点作为根节点的树结构中是否具有指定子节点 * * @param parentKey 父节点 * @param childKey 子节点 * @return 是否 */ default boolean containsChildNode(K parentKey, K childKey) { return Opt.ofNullable(get(parentKey)) .map(m -> m.containsChild(childKey)) .orElse(false); } /** * 获取指定父节点直接关联的子节点 <br> * 比如:若存在 a -&gt; b -&gt; c 的关系,此时输入 b 将返回 c,输入 a 将返回 b * * @param key key * @return 节点 */ default Collection<TreeEntry<K, V>> getDeclaredChildNodes(K key) { return Opt.ofNullable(get(key)) .map(TreeEntry::getDeclaredChildren) .map(Map::values) .orElseGet(Collections::emptyList); } /** * 获取指定父节点的全部子节点 <br> * 比如:若存在 a -&gt; b -&gt; c 的关系,此时输入 b 将返回 c,输入 a 将返回 b,c * * @param key key * @return 该节点的全部子节点 */ default Collection<TreeEntry<K, V>> getChildNodes(K key) { return Opt.ofNullable(get(key)) .map(TreeEntry::getChildren) .map(Map::values) .orElseGet(Collections::emptyList); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/map/ForestMap.java
728
/** * File: edit_distance.java * Created Time: 2023-07-13 * Author: krahets ([email protected]) */ package chapter_dynamic_programming; import java.util.Arrays; public class edit_distance { /* 编辑距离:暴力搜索 */ static int editDistanceDFS(String s, String t, int i, int j) { // 若 s 和 t 都为空,则返回 0 if (i == 0 && j == 0) return 0; // 若 s 为空,则返回 t 长度 if (i == 0) return j; // 若 t 为空,则返回 s 长度 if (j == 0) return i; // 若两字符相等,则直接跳过此两字符 if (s.charAt(i - 1) == t.charAt(j - 1)) return editDistanceDFS(s, t, i - 1, j - 1); // 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1 int insert = editDistanceDFS(s, t, i, j - 1); int delete = editDistanceDFS(s, t, i - 1, j); int replace = editDistanceDFS(s, t, i - 1, j - 1); // 返回最少编辑步数 return Math.min(Math.min(insert, delete), replace) + 1; } /* 编辑距离:记忆化搜索 */ static int editDistanceDFSMem(String s, String t, int[][] mem, int i, int j) { // 若 s 和 t 都为空,则返回 0 if (i == 0 && j == 0) return 0; // 若 s 为空,则返回 t 长度 if (i == 0) return j; // 若 t 为空,则返回 s 长度 if (j == 0) return i; // 若已有记录,则直接返回之 if (mem[i][j] != -1) return mem[i][j]; // 若两字符相等,则直接跳过此两字符 if (s.charAt(i - 1) == t.charAt(j - 1)) return editDistanceDFSMem(s, t, mem, i - 1, j - 1); // 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1 int insert = editDistanceDFSMem(s, t, mem, i, j - 1); int delete = editDistanceDFSMem(s, t, mem, i - 1, j); int replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1); // 记录并返回最少编辑步数 mem[i][j] = Math.min(Math.min(insert, delete), replace) + 1; return mem[i][j]; } /* 编辑距离:动态规划 */ static int editDistanceDP(String s, String t) { int n = s.length(), m = t.length(); int[][] dp = new int[n + 1][m + 1]; // 状态转移:首行首列 for (int i = 1; i <= n; i++) { dp[i][0] = i; } for (int j = 1; j <= m; j++) { dp[0][j] = j; } // 状态转移:其余行和列 for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (s.charAt(i - 1) == t.charAt(j - 1)) { // 若两字符相等,则直接跳过此两字符 dp[i][j] = dp[i - 1][j - 1]; } else { // 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1 dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1; } } } return dp[n][m]; } /* 编辑距离:空间优化后的动态规划 */ static int editDistanceDPComp(String s, String t) { int n = s.length(), m = t.length(); int[] dp = new int[m + 1]; // 状态转移:首行 for (int j = 1; j <= m; j++) { dp[j] = j; } // 状态转移:其余行 for (int i = 1; i <= n; i++) { // 状态转移:首列 int leftup = dp[0]; // 暂存 dp[i-1, j-1] dp[0] = i; // 状态转移:其余列 for (int j = 1; j <= m; j++) { int temp = dp[j]; if (s.charAt(i - 1) == t.charAt(j - 1)) { // 若两字符相等,则直接跳过此两字符 dp[j] = leftup; } else { // 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1 dp[j] = Math.min(Math.min(dp[j - 1], dp[j]), leftup) + 1; } leftup = temp; // 更新为下一轮的 dp[i-1, j-1] } } return dp[m]; } public static void main(String[] args) { String s = "bag"; String t = "pack"; int n = s.length(), m = t.length(); // 暴力搜索 int res = editDistanceDFS(s, t, n, m); System.out.println("将 " + s + " 更改为 " + t + " 最少需要编辑 " + res + " 步"); // 记忆化搜索 int[][] mem = new int[n + 1][m + 1]; for (int[] row : mem) Arrays.fill(row, -1); res = editDistanceDFSMem(s, t, mem, n, m); System.out.println("将 " + s + " 更改为 " + t + " 最少需要编辑 " + res + " 步"); // 动态规划 res = editDistanceDP(s, t); System.out.println("将 " + s + " 更改为 " + t + " 最少需要编辑 " + res + " 步"); // 空间优化后的动态规划 res = editDistanceDPComp(s, t); System.out.println("将 " + s + " 更改为 " + t + " 最少需要编辑 " + res + " 步"); } }
krahets/hello-algo
codes/java/chapter_dynamic_programming/edit_distance.java
729
package com.alibaba.otter.canal.sink.entry.group; import java.util.concurrent.BlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import com.alibaba.otter.canal.store.model.Event; /** * 时间归并控制 * * <pre> * 大致设计: * 1. 多个队列都提交一个timestamp,判断出最小的一个timestamp做为通过的条件,然后唤醒<=该最小时间的线程通过 * 2. 只有当多个队列都提交了一个timestamp,缺少任何一个提交,都会阻塞其他队列通过。(解决当一个库启动过慢或者发生主备切换时出现延迟等问题) * * 存在一个假定,认为提交的timestamp是一个顺序递增,但是在两种case下会出现时间回退 * a. 大事务时,事务头的时间会晚于事务当中数据的时间,相当于出现一个时间回退 * b. 出现主备切换,从备机上发过来的数据会回退几秒钟 * * </pre> * * @author jianghang 2012-10-15 下午10:01:53 * @version 1.0.0 */ public class TimelineBarrier implements GroupBarrier<Event> { protected int groupSize; protected ReentrantLock lock = new ReentrantLock(); protected Condition condition = lock.newCondition(); protected volatile long threshold; protected BlockingQueue<Long> lastTimestamps = new PriorityBlockingQueue<>(); // 当前通道最后一次single的时间戳 public TimelineBarrier(int groupSize){ this.groupSize = groupSize; threshold = Long.MIN_VALUE; } /** * 判断自己的timestamp是否可以通过 * * @throws InterruptedException */ public void await(Event event) throws InterruptedException { long timestamp = getTimestamp(event); try { lock.lockInterruptibly(); single(timestamp); while (isPermit(event, timestamp) == false) { condition.await(); } } finally { lock.unlock(); } } /** * 判断自己的timestamp是否可以通过,带超时控制 * * @throws InterruptedException * @throws TimeoutException */ public void await(Event event, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { long timestamp = getTimestamp(event); try { lock.lockInterruptibly(); single(timestamp); while (isPermit(event, timestamp) == false) { condition.await(timeout, unit); } } finally { lock.unlock(); } } public void clear(Event event) { // 出现中断有两种可能: // 1.出现主备切换,需要剔除到Timeline中的时间占位(这样合并时就会小于groupSize,不满足调度条件,直到主备切换完成后才能重新开启合并处理) // 2.出现关闭操作,退出即可 lastTimestamps.remove(getTimestamp(event)); } public void interrupt() { // do nothing,没有需要清理的上下文状态 } public long state() { return threshold; } /** * 判断是否允许通过 */ protected boolean isPermit(Event event, long state) { return state <= state(); } /** * 通知一下 */ protected void notify(long minTimestamp) { // 通知阻塞的线程恢复, 这里采用single all操作,当group中的几个时间都相同时,一次性触发通过多个 condition.signalAll(); } /** * 通知下一个minTimestamp数据出队列 * * @throws InterruptedException */ private void single(long timestamp) throws InterruptedException { lastTimestamps.add(timestamp); if (timestamp < state()) { // 针对mysql事务中会出现时间跳跃 // 例子: // 2012-08-08 16:24:26 事务头 // 2012-08-08 16:24:24 变更记录 // 2012-08-08 16:24:25 变更记录 // 2012-08-08 16:24:26 事务尾 // 针对这种case,一旦发现timestamp有回退的情况,直接更新threshold,强制阻塞其他的操作,等待最小数据优先处理完成 threshold = timestamp; // 更新为最小值 } if (lastTimestamps.size() >= groupSize) {// 判断队列是否需要触发 // 触发下一个出队列的数据 Long minTimestamp = this.lastTimestamps.peek(); if (minTimestamp != null) { threshold = minTimestamp; notify(minTimestamp); } } else { threshold = Long.MIN_VALUE;// 如果不满足队列长度,需要阻塞等待 } } private Long getTimestamp(Event event) { return event.getExecuteTime(); } }
alibaba/canal
sink/src/main/java/com/alibaba/otter/canal/sink/entry/group/TimelineBarrier.java
731
package me.zhyd.oauth.request; import me.zhyd.oauth.enums.AuthResponseStatus; import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.model.AuthCallback; import me.zhyd.oauth.model.AuthResponse; import me.zhyd.oauth.model.AuthToken; /** * JustAuth {@code Request}公共接口,所有平台的{@code Request}都需要实现该接口 * <p> * {@link AuthRequest#authorize()} * {@link AuthRequest#authorize(String)} * {@link AuthRequest#login(AuthCallback)} * {@link AuthRequest#revoke(AuthToken)} * {@link AuthRequest#refresh(AuthToken)} * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @since 1.8 */ public interface AuthRequest { /** * 返回授权url,可自行跳转页面 * <p> * 不建议使用该方式获取授权地址,不带{@code state}的授权地址,容易受到csrf攻击。 * 建议使用{@link AuthDefaultRequest#authorize(String)}方法生成授权地址,在回调方法中对{@code state}进行校验 * * @return 返回授权地址 */ @Deprecated default String authorize() { throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED); } /** * 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state} * * @param state state 验证授权流程的参数,可以防止csrf * @return 返回授权地址 */ default String authorize(String state) { throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED); } /** * 第三方登录 * * @param authCallback 用于接收回调参数的实体 * @return 返回登录成功后的用户信息 */ default AuthResponse login(AuthCallback authCallback) { throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED); } /** * 撤销授权 * * @param authToken 登录成功后返回的Token信息 * @return AuthResponse */ default AuthResponse revoke(AuthToken authToken) { throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED); } /** * 刷新access token (续期) * * @param authToken 登录成功后返回的Token信息 * @return AuthResponse */ default AuthResponse refresh(AuthToken authToken) { throw new AuthException(AuthResponseStatus.NOT_IMPLEMENTED); } }
justauth/JustAuth
src/main/java/me/zhyd/oauth/request/AuthRequest.java
733
/*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. This source code is licensed under the Apache License Version 2.0.*/ package apijson.orm; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import apijson.NotNull; import apijson.RequestMethod; /**简化Parser,getObject和getArray(getArrayConfig)都能用 * @author Lemon */ public interface ObjectParser<T extends Object> { Parser<T> getParser(); ObjectParser<T> setParser(Parser<T> parser); String getParentPath(); ObjectParser<T> setParentPath(String parentPath); /**解析成员 * response重新赋值 * @param name * @param isReuse * @return null or this * @throws Exception */ ObjectParser<T> parse(String name, boolean isReuse) throws Exception; /**调用 parser 的 sqlExecutor 来解析结果 * @param method * @param table * @param alias * @param request * @param joinList * @param isProcedure * @return * @throws Exception */ JSONObject parseResponse(RequestMethod method, String table, String alias, JSONObject request, List<Join> joinList, boolean isProcedure) throws Exception; /**调用 parser 的 sqlExecutor 来解析结果 * @param config * @param isProcedure * @return * @throws Exception */ JSONObject parseResponse(SQLConfig<T> config, boolean isProcedure) throws Exception; /**解析普通成员 * @param key * @param value * @return whether parse succeed */ boolean onParse(@NotNull String key, @NotNull Object value) throws Exception; /**解析子对象 * @param index * @param key * @param value * @return * @throws Exception */ JSON onChildParse(int index, String key, JSONObject value) throws Exception; /**解析赋值引用 * @param path * @return */ Object onReferenceParse(@NotNull String path); //TODO 改用 MySQL json_add,json_remove,json_contains 等函数! /**修改数组 PUT key:[] * @param key * @param array * @throws Exception */ void onPUTArrayParse(@NotNull String key, @NotNull JSONArray array) throws Exception; /**批量新增或修改 POST or PUT Table[]:[{}] * @param key * @param array * @throws Exception */ void onTableArrayParse(@NotNull String key, @NotNull JSONArray array) throws Exception; /**SQL 配置,for single object * @return {@link #setSQLConfig(int, int, int)} * @throws Exception */ ObjectParser<T> setSQLConfig() throws Exception; /**SQL 配置 * @return * @throws Exception */ ObjectParser<T> setSQLConfig(int count, int page, int position) throws Exception; /**执行 SQL * @return * @throws Exception */ ObjectParser<T> executeSQL() throws Exception; /** * @return * @throws Exception */ JSONObject onSQLExecute() throws Exception; /** * @return response * @throws Exception */ JSONObject response() throws Exception; void onFunctionResponse(String type) throws Exception; void onChildResponse() throws Exception; SQLConfig<T> newSQLConfig(boolean isProcedure) throws Exception; SQLConfig<T> newSQLConfig(RequestMethod method, String table, String alias, JSONObject request, List<Join> joinList, boolean isProcedure) throws Exception; /** * response has the final value after parse (and query if isTableKey) */ void onComplete(); /**回收内存 */ void recycle(); ObjectParser<T> setMethod(RequestMethod method); RequestMethod getMethod(); boolean isTable(); String getPath(); String getTable(); String getAlias(); SQLConfig<T> getArrayConfig(); SQLConfig<T> getSQLConfig(); JSONObject getResponse(); JSONObject getSqlRequest(); JSONObject getSqlResponse(); Map<String, Object> getCustomMap(); Map<String, Map<String, String>> getFunctionMap(); Map<String, JSONObject> getChildMap(); }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/orm/ObjectParser.java
737
package com.taobao.arthas.core.command.monitor200; import com.taobao.arthas.core.advisor.InvokeTraceable; import com.taobao.arthas.core.shell.command.CommandProcess; /** * @author beiwei30 on 29/11/2016. */ public class TraceAdviceListener extends AbstractTraceAdviceListener implements InvokeTraceable { /** * Constructor */ public TraceAdviceListener(TraceCommand command, CommandProcess process, boolean verbose) { super(command, process); super.setVerbose(verbose); } /** * trace 会在被观测的方法体中,在每个方法调用前后插入字节码,所以方法调用开始,结束,抛异常的时候,都会回调下面的接口 */ @Override public void invokeBeforeTracing(ClassLoader classLoader, String tracingClassName, String tracingMethodName, String tracingMethodDesc, int tracingLineNumber) throws Throwable { // normalize className later threadLocalTraceEntity(classLoader).tree.begin(tracingClassName, tracingMethodName, tracingLineNumber, true); } @Override public void invokeAfterTracing(ClassLoader classLoader, String tracingClassName, String tracingMethodName, String tracingMethodDesc, int tracingLineNumber) throws Throwable { threadLocalTraceEntity(classLoader).tree.end(); } @Override public void invokeThrowTracing(ClassLoader classLoader, String tracingClassName, String tracingMethodName, String tracingMethodDesc, int tracingLineNumber) throws Throwable { threadLocalTraceEntity(classLoader).tree.end(true); } }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/command/monitor200/TraceAdviceListener.java
738
package com.macro.mall.portal.config; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; /** * Jackson相关配置 * 配置json不返回null的字段 * Created by macro on 2018/8/2. */ @Configuration public class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 通过该方法对mapper对象进行设置,所有序列化的对象都将按该规则进行系列化 // Include.ALWAYS 所有属性都序列化(默认) // Include.NON_DEFAULT 属性为默认值不序列化 // Include.NON_EMPTY 属性为空("")或者为NULL都不序列化 // Include.NON_NULL 属性为NULL的字段不序列化 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return objectMapper; } }
macrozheng/mall
mall-portal/src/main/java/com/macro/mall/portal/config/JacksonConfig.java
740
E tags: Hash Table time: O(n) #### Brutle, Count Blocks and Walls - 每个格子 +4 个墙; - 每个shared的墙要减去: 从每个island走去另外一个, 都-1 (最终没面墙, -2) #### Hash Table - 把每个block相连的block全部存在以当下block为key的list里面. 那么这里需要把2D坐标, 转化成一个index. - 最后得到的map, 所有的key-value应该都有value-key的反向mapping, 那么就可以消除干净, 每一次消除就是一个shared wall. - 一点点optimization: DFS去找所有的island, 如果island的图非常大, 而island本身不大,那么适合optimize. - 但是整体代码过于复杂. 不建议写. ``` /* You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16 https://leetcode.com/problems/island-perimeter/description/ */ /* DFS all of the 1's 1. each island gives 4 walls 2. one side of shared wall will cause -1. Each shared wall will be counted 2 times, from each size of the wall. */ class Solution { public int islandPerimeter(int[][] grid) { if (grid == null) return 0; int[] dx = {1, -1, 0, 0}; int[] dy = {0, 0, 1, -1}; int count = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] != 1) continue; count += 4; for (int k = 0; k < dx.length; k++) { int mX = i + dx[k], mY = j + dy[k]; if (validate(grid, mX, mY)) count -= 1; } } } return count; } private boolean validate(int[][] grid, int x, int y) { return x >= 0 && y >= 0 && x < grid.length && y < grid[0].length && grid[x][y] == 1; } } // incomplete version using DFS. The code became complicated and not necessary. /* class Solution { private int[] dx = {1, -1, 0, 0}; private int[] dy = {0, 0, 1, -1}; int blocks = 0; int walls = 0; public int islandPerimeter(int[][] grid) { if (grid == null || grid.length == 0 || grid[0].length == 0) { return 0; } Map<Integer, ArrayList<Integer>> map = new HashMap<>(); for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j] == 1) { dfs(map, grid, i, j); return blocks * 4 - walls * 2; } } } return 0; } private void dfs(Map<Integer, ArrayList<Integer>> map, int[][] grid, int x, int y) { if (grid[x][y] != 1) { return; } grid[x][y] = -1; int index = calculateIndex(grid[0].length, x, y); if (!map.containsKey(index)) { map.put(index, new ArrayList<>()); } for (int i = 0; i < dx.length; i++) { int mX = x + dx[i]; int mY = y + dy[i]; if (mX >= 0 && mY >= 0 && mX < grid.length && mY < grid[0].length && grid[mX][mY] != 0) { map.put(index, calculateIndex(grid[0].length, mX, mY)); dfs(grid, mX, mY); } } } private calculateIndex(int width, int x, int y) { return width * x + y; } }*/ ```
awangdev/leet-code
Java/463. Island Perimeter.java
742
/** * @author Anonymous * @since 2019/12/10 */ class Solution { /** * 找出数组中只出现一次的数字,其它数字都出现三次 * * @param nums 数字 * @return 只出现一次的数字 */ public int findNumberAppearingOnce(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int[] bits = new int[32]; int n = nums.length; for (int i = 0; i < n; ++i) { int val = nums[i]; for (int j = 0; j < 32; ++j) { bits[j] += (val & 1); val = val >> 1; } } int res = 0; for (int i = 0; i < 32; ++i) { if (bits[i] % 3 != 0) { res += Math.pow(2, i); } } return res; } }
geekxh/hello-algorithm
算法读物/剑指offer/56_02_NumberAppearingOnce/Solution.java
743
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cn.itcast.util; /** * * @author fqy */ public abstract class MyLookAndFeel { // 系统自带皮肤,5种都能用 public static String SYS_METAL = "javax.swing.plaf.metal.MetalLookAndFeel"; public static String SYS_NIMBUS = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"; // 有个性 public static String SYS_CDE_MOTIF = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; public static String SYS_WINDOWS = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; public static String SYS_WINDOWS_CLASSIC = "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel"; // JIattoo jar包资源 public static String JTATTOO_ACRYL = "com.jtattoo.plaf.acryl.AcrylLookAndFeel"; public static String JTATTOO_AERO = "com.jtattoo.plaf.aero.AeroLookAndFeel"; // 还可以 public static String JTATTOO_ALUMINUM = "com.jtattoo.plaf.aluminium.AluminiumLookAndFeel"; // 很喜欢 public static String JTATTOO_BERNSTEIN = "com.jtattoo.plaf.bernstein.BernsteinLookAndFeel"; public static String JTATTOO_FAST = "com.jtattoo.plaf.fast.FastLookAndFeel"; // 有个性 public static String JTATTOO_HIFI = "com.jtattoo.plaf.hifi.HiFiLookAndFeel"; public static String JTATTOO_LUNA = "com.jtattoo.plaf.luna.LunaLookAndFeel"; // 很喜欢 public static String JTATTOO_MCWIN = "com.jtattoo.plaf.mcwin.McWinLookAndFeel"; public static String JTATTOO_MINT = "com.jtattoo.plaf.mint.MintLookAndFeel"; // 有个性 public static String JTATTOO_NOIRE = "com.jtattoo.plaf.noire.NoireLookAndFeel"; public static String JTATTOO_SMART = "com.jtattoo.plaf.smart.SmartLookAndFeel"; // liquidlnf.jar包资源 // 很喜欢 public static String LIQUIDINF = "com.birosoft.liquid.LiquidLookAndFeel"; }
DuGuQiuBai/Java
day25/code/四则运算/src/cn/itcast/util/MyLookAndFeel.java
745
package org.pdown.gui.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.Proxy.Type; import java.net.URL; import org.pdown.core.boot.HttpDownBootstrap; import org.pdown.core.boot.URLHttpDownBootstrapBuilder; import org.pdown.core.dispatch.HttpDownCallback; import org.pdown.core.entity.HttpDownConfigInfo; import org.pdown.core.entity.HttpResponseInfo; import org.pdown.core.proxy.ProxyConfig; import org.pdown.core.proxy.ProxyType; import org.pdown.core.util.FileUtil; import org.pdown.core.util.OsUtil; import org.pdown.gui.DownApplication; import org.pdown.gui.content.PDownConfigContent; import org.pdown.gui.extension.mitm.server.PDownProxyServer; import org.pdown.gui.extension.mitm.util.ExtensionCertUtil; import org.pdown.gui.extension.mitm.util.ExtensionProxyUtil; import org.pdown.rest.util.PathUtil; import org.springframework.util.StringUtils; public class AppUtil { public static final String SUBJECT = "ProxyeeDown CA"; public static final String SSL_PATH = PathUtil.ROOT_PATH + File.separator + "ssl" + File.separator; public static final String CERT_PATH = SSL_PATH + "ca.crt"; public static final String PRIVATE_PATH = SSL_PATH + ".ca_pri.der"; /** * 证书和私钥文件都存在并且检测到系统安装了这个证书 */ public static boolean checkIsInstalledCert() throws Exception { return FileUtil.exists(CERT_PATH) && FileUtil.exists(PRIVATE_PATH) && ExtensionCertUtil.isInstalledCert(new File(CERT_PATH)); } /** * 刷新系统PAC代理 */ public static void refreshPAC() throws IOException { if (PDownConfigContent.getInstance().get().getProxyMode() == 1) { ExtensionProxyUtil.enabledPACProxy("http://127.0.0.1:" + DownApplication.INSTANCE.API_PORT + "/pac/pdown.pac?t=" + System.currentTimeMillis()); } } /** * 运行代理服务器 */ public static void startProxyServer() throws IOException { DownApplication.INSTANCE.PROXY_PORT = OsUtil.getFreePort(9999); PDownProxyServer.start(DownApplication.INSTANCE.PROXY_PORT); } /** * 下载http资源 */ public static void download(String url, String path) throws IOException { URL u = new URL(url); HttpURLConnection connection; ProxyConfig proxyConfig = PDownConfigContent.getInstance().get().getProxyConfig(); if (proxyConfig != null) { Type type; if (proxyConfig.getProxyType() == ProxyType.HTTP) { type = Type.HTTP; } else { type = Type.SOCKS; } if (!StringUtils.isEmpty(proxyConfig.getUser())) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyConfig.getUser(), proxyConfig.getPwd() == null ? null : proxyConfig.getPwd().toCharArray()); } }; Authenticator.setDefault(authenticator); } Proxy proxy = new Proxy(type, new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort())); connection = (HttpURLConnection) u.openConnection(proxy); } else { connection = (HttpURLConnection) u.openConnection(); } connection.setConnectTimeout(30000); connection.setReadTimeout(0); File file = new File(path); if (!file.exists() || file.isDirectory()) { FileUtil.createFileSmart(file.getPath()); } try ( InputStream input = connection.getInputStream(); FileOutputStream output = new FileOutputStream(file) ) { byte[] bts = new byte[8192]; int len; while ((len = input.read(bts)) != -1) { output.write(bts, 0, len); } } } /** * 使用pdown-core多连接下载http资源 */ public static HttpDownBootstrap fastDownload(String url, File file, HttpDownCallback callback) throws IOException { HttpDownBootstrap httpDownBootstrap = new URLHttpDownBootstrapBuilder(url, null, null) .callback(callback) .downConfig(new HttpDownConfigInfo().setFilePath(file.getParent()).setConnections(64)) .response(new HttpResponseInfo().setFileName(file.getName())) .proxyConfig(PDownConfigContent.getInstance().get().getProxyConfig()) .build(); httpDownBootstrap.start(); return httpDownBootstrap; } }
proxyee-down-org/proxyee-down
main/src/main/java/org/pdown/gui/util/AppUtil.java
746
/* * Copyright 2016 jeasonlzy(廖子尧) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lzy.demo.okgo; import android.content.Intent; import com.lzy.demo.base.MainFragment; import com.lzy.demo.model.ItemModel; import com.lzy.demo.supercache.SuperCacheActivity; import java.util.List; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/6/9 * 描 述: * 修订历史: * ================================================ */ public class OkGoFragment extends MainFragment { @Override public void fillData(List<ItemModel> items) { items.add(new ItemModel("强大的缓存示例 -- 先联网获取数据,然后断开网络再进试试",// "1.OkGo的强大的缓存功能,让你代码无需关心数据来源,专注于业务逻辑的实现\n" +// "2.内置五种缓存模式满足你各种使用场景\n" +// "3.支持自定义缓存策略,可以按照自己的需求改写缓存逻辑\n" +// "4.支持自定义缓存过期时间")); items.add(new ItemModel("基本功能",// "1.GET,HEAD,OPTIONS,POST,PUT,DELETE, PATCH, TRACE 请求方法演示\n" +// "2.请求服务器返回bitmap对象\n" +// "3.支持https请求\n" +// "4.支持同步请求\n" +// "5.支持301重定向")); items.add(new ItemModel("自动解析JSON对象",// "1.自动解析JSONObject对象\n" + // "2.自动解析JSONArray对象")); items.add(new ItemModel("文件下载",// "1.支持大文件或小文件下载,无论多大文件都不会发生OOM\n" +// "2.支持监听下载进度和下载网速\n" +// "3.支持自定义下载目录和下载文件名")); items.add(new ItemModel("文件上传",// "1.支持上传单个文件\n" +// "2.支持同时上传多个文件\n" +// "3.支持多个文件多个参数同时上传\n" +// "4.支持大文件上传,无论多大都不会发生OOM\n" +// "5.支持监听上传进度和上传网速")); } @Override public void onItemClick(int position) { if (position == 0) startActivity(new Intent(context, SuperCacheActivity.class)); if (position == 1) startActivity(new Intent(context, CommonActivity.class)); if (position == 2) startActivity(new Intent(context, JsonActivity.class)); if (position == 3) startActivity(new Intent(context, SimpleDownloadActivity.class)); if (position == 4) startActivity(new Intent(context, FormUploadActivity.class)); } }
jeasonlzy/okhttp-OkGo
demo/src/main/java/com/lzy/demo/okgo/OkGoFragment.java
747
package org.pdown.gui.extension.mitm.server; import com.github.monkeywie.proxyee.exception.HttpProxyExceptionHandle; import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptInitializer; import com.github.monkeywie.proxyee.intercept.HttpProxyInterceptPipeline; import com.github.monkeywie.proxyee.server.HttpProxyServer; import com.github.monkeywie.proxyee.server.HttpProxyServerConfig; import io.netty.channel.Channel; import org.pdown.gui.content.PDownConfigContent; import org.pdown.gui.entity.PDownConfigInfo; import org.pdown.gui.extension.mitm.intercept.AjaxIntercept; import org.pdown.gui.extension.mitm.intercept.CookieIntercept; import org.pdown.gui.extension.mitm.intercept.ScriptIntercept; import org.pdown.gui.extension.mitm.intercept.SniffIntercept; import org.pdown.gui.extension.mitm.ssl.PDownCACertFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PDownProxyServer { private static final Logger LOGGER = LoggerFactory.getLogger(PDownProxyServer.class); private static volatile HttpProxyServer httpProxyServer; public static volatile boolean isStart = false; public static void start(int port) { HttpProxyServerConfig config = new HttpProxyServerConfig(); //处理ssl config.setHandleSsl(true); //线程池数量都设置为1 config.setBossGroupThreads(1); config.setWorkerGroupThreads(1); config.setProxyGroupThreads(1); httpProxyServer = new HttpProxyServer() .serverConfig(config) .proxyConfig(PDownConfigInfo.convert(PDownConfigContent.getInstance().get().getProxyConfig())) .caCertFactory(new PDownCACertFactory()) .proxyInterceptInitializer(new HttpProxyInterceptInitializer() { @Override public void init(HttpProxyInterceptPipeline pipeline) { pipeline.addLast(new CookieIntercept()); pipeline.addLast(new AjaxIntercept()); pipeline.addLast(new ScriptIntercept()); pipeline.addLast(new SniffIntercept()); } }) .httpProxyExceptionHandle(new HttpProxyExceptionHandle() { @Override public void beforeCatch(Channel clientChannel, Throwable cause) throws Exception { LOGGER.warn("beforeCatch", cause); } @Override public void afterCatch(Channel clientChannel, Channel proxyChannel, Throwable cause) throws Exception { LOGGER.warn("afterCatch", cause); } }); isStart = true; httpProxyServer.start(port); } public static void close() { if (httpProxyServer != null) { httpProxyServer.close(); } isStart = false; } }
proxyee-down-org/proxyee-down
main/src/main/java/org/pdown/gui/extension/mitm/server/PDownProxyServer.java
751
package com.xkcoding.zookeeper.aspectj; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.xkcoding.zookeeper.annotation.LockKeyParam; import com.xkcoding.zookeeper.annotation.ZooLock; import lombok.extern.slf4j.Slf4j; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * <p> * 使用 aop 切面记录请求日志信息 * </p> * * @author yangkai.shen * @date Created in 2018-10-01 22:05 */ @Aspect @Component @Slf4j public class ZooLockAspect { private final CuratorFramework zkClient; private static final String KEY_PREFIX = "DISTRIBUTED_LOCK_"; private static final String KEY_SEPARATOR = "/"; @Autowired public ZooLockAspect(CuratorFramework zkClient) { this.zkClient = zkClient; } /** * 切入点 */ @Pointcut("@annotation(com.xkcoding.zookeeper.annotation.ZooLock)") public void doLock() { } /** * 环绕操作 * * @param point 切入点 * @return 原方法返回值 * @throws Throwable 异常信息 */ @Around("doLock()") public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); Object[] args = point.getArgs(); ZooLock zooLock = method.getAnnotation(ZooLock.class); if (StrUtil.isBlank(zooLock.key())) { throw new RuntimeException("分布式锁键不能为空"); } String lockKey = buildLockKey(zooLock, method, args); InterProcessMutex lock = new InterProcessMutex(zkClient, lockKey); try { // 假设上锁成功,以后拿到的都是 false if (lock.acquire(zooLock.timeout(), zooLock.timeUnit())) { return point.proceed(); } else { throw new RuntimeException("请勿重复提交"); } } finally { lock.release(); } } /** * 构造分布式锁的键 * * @param lock 注解 * @param method 注解标记的方法 * @param args 方法上的参数 * @return * @throws NoSuchFieldException * @throws IllegalAccessException */ private String buildLockKey(ZooLock lock, Method method, Object[] args) throws NoSuchFieldException, IllegalAccessException { StringBuilder key = new StringBuilder(KEY_SEPARATOR + KEY_PREFIX + lock.key()); // 迭代全部参数的注解,根据使用LockKeyParam的注解的参数所在的下标,来获取args中对应下标的参数值拼接到前半部分key上 Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameterAnnotations.length; i++) { // 循环该参数全部注解 for (Annotation annotation : parameterAnnotations[i]) { // 注解不是 @LockKeyParam if (!annotation.annotationType().isInstance(LockKeyParam.class)) { continue; } // 获取所有fields String[] fields = ((LockKeyParam) annotation).fields(); if (ArrayUtil.isEmpty(fields)) { // 普通数据类型直接拼接 if (ObjectUtil.isNull(args[i])) { throw new RuntimeException("动态参数不能为null"); } key.append(KEY_SEPARATOR).append(args[i]); } else { // @LockKeyParam的fields值不为null,所以当前参数应该是对象类型 for (String field : fields) { Class<?> clazz = args[i].getClass(); Field declaredField = clazz.getDeclaredField(field); declaredField.setAccessible(true); Object value = declaredField.get(clazz); key.append(KEY_SEPARATOR).append(value); } } } } return key.toString(); } }
xkcoding/spring-boot-demo
demo-zookeeper/src/main/java/com/xkcoding/zookeeper/aspectj/ZooLockAspect.java
753
M tags: Sort, Quick Sort implement quick sort. #### Quick Sort - 首先partition. 返还一个partition的那个中间点的位置: 这个时候, 所有小于nums[partitionIndex] 都应该在 partitionIndex左边 - 然后劈开两半 - 前后各自 quick sort, recursively - 注意:在partition里面, 比较的时候nums[start] < pivot, nums[end]>pivot, 如果写成了 <= 会 stack overflow. - Time O(nlogn), Space: O(1) ``` /* Quick Sort a array. */ public class Solution { public void quickSort(int[] nums) { if (nums == null || nums.length == 0) { return; } dfs(nums, 0, nums.length - 1); } /** Partition one side, and recursively partition(swaping). Once one side finished, move on to partition && sorting the other side. */ private void dfs(int[] nums, int start, int end) { if (start >= end) { return; } int partitionIndex = partition(nums, start, end); dfs(nums, start, partitionIndex - 1); dfs(nums, partitionIndex, end); } /** Use two pointers: find the two points on left/rigth of the pivot that are startNum < pivot < endNum. Swap them, and keep moving star++, end--. This operation partition the array into 2 parts: - numbers less than pivot (unsorted) on left of pivot - numbers breater than pivot (unsorted) on right of pivot */ private int partition(int[] nums, int start, int end) { int mid = start + (end - start) / 2; int pivot = nums[mid]; while (start <= end) { while (start <= end && nums[start] < pivot) { start++; } while (start <= end && nums[end] > pivot) { end--; } if (start <= end) { swap(nums, start, end); start++; end--; } } return start; } private void swap(int[] nums, int x, int y) { int temp = nums[x]; nums[x] = nums[y]; nums[y] = temp; } private void printArray(int[] nums, String str) { System.out.print(str); if (nums == null || nums.length == 0) { System.out.println(); return; } for (int num : nums) { System.out.print(num + ", "); } System.out.println(); } public static void main(String[] args) { Solution sol = new Solution(); System.out.println("Implement and test quick sort"); int[] array = {5,3,2,7,5,4,1,1,2,9,5,3, -1}; sol.quickSort(array); sol.printArray(array, "Return: "); array = null; sol.quickSort(array); sol.printArray(array, "Return Empty: "); array = new int[]{ - 1, 2}; sol.quickSort(array); sol.printArray(array, "Return: "); array = new int[]{ 1,1,1,1,1}; sol.quickSort(array); sol.printArray(array, "Return: "); array = new int[]{ 19,8,7,6,5,4,3,2,1}; sol.quickSort(array); sol.printArray(array, "Return: "); } } ```
awangdev/leet-code
Java/QuickSort.java
755
package com.macro.mall.model; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.math.BigDecimal; public class PmsMemberPrice implements Serializable { private Long id; private Long productId; private Long memberLevelId; @ApiModelProperty(value = "会员价格") private BigDecimal memberPrice; private String memberLevelName; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public Long getMemberLevelId() { return memberLevelId; } public void setMemberLevelId(Long memberLevelId) { this.memberLevelId = memberLevelId; } public BigDecimal getMemberPrice() { return memberPrice; } public void setMemberPrice(BigDecimal memberPrice) { this.memberPrice = memberPrice; } public String getMemberLevelName() { return memberLevelName; } public void setMemberLevelName(String memberLevelName) { this.memberLevelName = memberLevelName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", memberLevelId=").append(memberLevelId); sb.append(", memberPrice=").append(memberPrice); sb.append(", memberLevelName=").append(memberLevelName); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/model/PmsMemberPrice.java
756
package cn.hutool.db; import cn.hutool.core.lang.func.VoidFunc1; import cn.hutool.core.util.StrUtil; import cn.hutool.db.dialect.Dialect; import cn.hutool.db.dialect.DialectFactory; import cn.hutool.db.ds.DSFactory; import cn.hutool.db.sql.Wrapper; import cn.hutool.log.Log; import cn.hutool.log.LogFactory; import javax.sql.DataSource; import java.io.Closeable; import java.sql.Connection; import java.sql.SQLException; import java.sql.Savepoint; /** * 数据库SQL执行会话<br> * 会话通过共用Connection而可以实现JDBC事务<br> * 一个会话只维护一个连接,推荐在执行完后关闭Session,避免重用<br> * 本对象并不是线程安全的,多个线程共用一个Session将会导致不可预知的问题 * * @author loolly * */ public class Session extends AbstractDb implements Closeable { private static final long serialVersionUID = 3421251905539056945L; private final static Log log = LogFactory.get(); /** * 创建默认数据源会话 * * @return Session * @since 3.2.3 */ public static Session create() { return new Session(DSFactory.get()); } /** * 创建会话 * * @param group 分组 * @return Session * @since 4.0.11 */ public static Session create(String group) { return new Session(DSFactory.get(group)); } /** * 创建会话 * * @param ds 数据源 * @return Session */ public static Session create(DataSource ds) { return new Session(ds); } // ---------------------------------------------------------------------------- Constructor start /** * 构造,从DataSource中识别方言 * * @param ds 数据源 */ public Session(DataSource ds) { this(ds, DialectFactory.getDialect(ds)); } /** * 构造 * * @param ds 数据源 * @param driverClassName 数据库连接驱动类名,用于识别方言 */ public Session(DataSource ds, String driverClassName) { this(ds, DialectFactory.newDialect(driverClassName)); } /** * 构造 * * @param ds 数据源 * @param dialect 方言 */ public Session(DataSource ds, Dialect dialect) { super(ds, dialect); } // ---------------------------------------------------------------------------- Constructor end // ---------------------------------------------------------------------------- Getters and Setters end /** * 获得{@link SqlConnRunner} * * @return {@link SqlConnRunner} */ @Override public SqlConnRunner getRunner() { return runner; } // ---------------------------------------------------------------------------- Getters and Setters end // ---------------------------------------------------------------------------- Transaction method start /** * 开始事务 * * @throws SQLException SQL执行异常 */ public void beginTransaction() throws SQLException { final Connection conn = getConnection(); checkTransactionSupported(conn); conn.setAutoCommit(false); } /** * 提交事务 * * @throws SQLException SQL执行异常 */ public void commit() throws SQLException { try { getConnection().commit(); } finally { try { getConnection().setAutoCommit(true); // 事务结束,恢复自动提交 } catch (SQLException e) { log.error(e); } } } /** * 回滚事务 * * @throws SQLException SQL执行异常 */ public void rollback() throws SQLException { try { getConnection().rollback(); } finally { try { getConnection().setAutoCommit(true); // 事务结束,恢复自动提交 } catch (SQLException e) { log.error(e); } } } /** * 静默回滚事务<br> * 回滚事务 */ public void quietRollback() { try { getConnection().rollback(); } catch (Exception e) { log.error(e); } finally { try { getConnection().setAutoCommit(true); // 事务结束,恢复自动提交 } catch (SQLException e) { log.error(e); } } } /** * 回滚到某个保存点,保存点的设置请使用setSavepoint方法 * * @param savepoint 保存点 * @throws SQLException SQL执行异常 */ public void rollback(Savepoint savepoint) throws SQLException { try { getConnection().rollback(savepoint); } finally { try { getConnection().setAutoCommit(true); // 事务结束,恢复自动提交 } catch (SQLException e) { log.error(e); } } } /** * 静默回滚到某个保存点,保存点的设置请使用setSavepoint方法 * * @param savepoint 保存点 */ public void quietRollback(Savepoint savepoint) { try { getConnection().rollback(savepoint); } catch (Exception e) { log.error(e); } finally { try { getConnection().setAutoCommit(true); // 事务结束,恢复自动提交 } catch (SQLException e) { log.error(e); } } } /** * 设置保存点 * * @return 保存点对象 * @throws SQLException SQL执行异常 */ public Savepoint setSavepoint() throws SQLException { return getConnection().setSavepoint(); } /** * 设置保存点 * * @param name 保存点的名称 * @return 保存点对象 * @throws SQLException SQL执行异常 */ public Savepoint setSavepoint(String name) throws SQLException { return getConnection().setSavepoint(name); } /** * 设置事务的隔离级别<br> * * Connection.TRANSACTION_NONE 驱动不支持事务<br> * Connection.TRANSACTION_READ_UNCOMMITTED 允许脏读、不可重复读和幻读<br> * Connection.TRANSACTION_READ_COMMITTED 禁止脏读,但允许不可重复读和幻读<br> * Connection.TRANSACTION_REPEATABLE_READ 禁止脏读和不可重复读,单运行幻读<br> * Connection.TRANSACTION_SERIALIZABLE 禁止脏读、不可重复读和幻读<br> * * @param level 隔离级别 * @throws SQLException SQL执行异常 */ public void setTransactionIsolation(int level) throws SQLException { if (getConnection().getMetaData().supportsTransactionIsolationLevel(level) == false) { throw new SQLException(StrUtil.format("Transaction isolation [{}] not support!", level)); } getConnection().setTransactionIsolation(level); } /** * 在事务中执行操作,通过实现{@link VoidFunc1}接口的call方法执行多条SQL语句从而完成事务 * * @param func 函数抽象,在函数中执行多个SQL操作,多个操作会被合并为同一事务 * @throws SQLException SQL异常 * @since 3.2.3 */ public void tx(VoidFunc1<Session> func) throws SQLException { try { beginTransaction(); func.call(this); commit(); } catch (Throwable e) { quietRollback(); throw (e instanceof SQLException) ? (SQLException) e : new SQLException(e); } } // ---------------------------------------------------------------------------- Transaction method end // ---------------------------------------------------------------------------- Getters and Setters start @Override public Session setWrapper(Character wrapperChar) { return (Session) super.setWrapper(wrapperChar); } @Override public Session setWrapper(Wrapper wrapper) { return (Session) super.setWrapper(wrapper); } @Override public Session disableWrapper() { return (Session) super.disableWrapper(); } // ---------------------------------------------------------------------------- Getters and Setters end @Override public Connection getConnection() throws SQLException { return ThreadLocalConnection.INSTANCE.get(this.ds); } @Override public void closeConnection(Connection conn) { try { if(conn != null && false == conn.getAutoCommit()) { // 事务中的Session忽略关闭事件 return; } } catch (SQLException e) { log.error(e); } // 普通请求关闭(或归还)连接 ThreadLocalConnection.INSTANCE.close(this.ds); } @Override public void close() { closeConnection(null); } }
dromara/hutool
hutool-db/src/main/java/cn/hutool/db/Session.java
757
package com.taobao.arthas.core.advisor; /** * 方法调用跟踪<br/> * 当一个方法内部调用另外一个方法时,会触发此跟踪方法 * Created by vlinux on 15/5/27. */ public interface InvokeTraceable { /** * 调用之前跟踪 * * @param tracingClassName 调用类名 * @param tracingMethodName 调用方法名 * @param tracingMethodDesc 调用方法描述 * @param tracingLineNumber 执行调用行数 * @throws Throwable 通知过程出错 */ void invokeBeforeTracing( ClassLoader classLoader, String tracingClassName, String tracingMethodName, String tracingMethodDesc, int tracingLineNumber) throws Throwable; /** * 抛异常后跟踪 * * @param tracingClassName 调用类名 * @param tracingMethodName 调用方法名 * @param tracingMethodDesc 调用方法描述 * @param tracingLineNumber 执行调用行数 * @throws Throwable 通知过程出错 */ void invokeThrowTracing( ClassLoader classLoader, String tracingClassName, String tracingMethodName, String tracingMethodDesc, int tracingLineNumber) throws Throwable; /** * 调用之后跟踪 * * @param tracingClassName 调用类名 * @param tracingMethodName 调用方法名 * @param tracingMethodDesc 调用方法描述 * @param tracingLineNumber 执行调用行数 * @throws Throwable 通知过程出错 */ void invokeAfterTracing( ClassLoader classLoader, String tracingClassName, String tracingMethodName, String tracingMethodDesc, int tracingLineNumber) throws Throwable; }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/advisor/InvokeTraceable.java
758
/* * The MIT License (MIT) * * Copyright (c) 2014-2023 [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.pagehelper; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.session.RowBounds; import java.util.List; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; /** * 数据库方言,针对不同数据库进行实现 * * @author liuzh */ public interface Dialect { /** * 跳过 count 和 分页查询 * * @param ms MappedStatement * @param parameterObject 方法参数 * @param rowBounds 分页参数 * @return true 跳过,返回默认查询结果,false 执行分页查询 */ boolean skip(MappedStatement ms, Object parameterObject, RowBounds rowBounds); /** * 是否使用异步 count 查询,使用异步后不会根据返回的 count 数来判断是否有必要进行分页查询 * * @return true 异步,false 同步 */ default boolean isAsyncCount() { return false; } /** * 执行异步 count 查询 * * @param task 异步查询任务 * @param <T> * @return */ default <T> Future<T> asyncCountTask(Callable<T> task) { return ForkJoinPool.commonPool().submit(task); } /** * 执行分页前,返回 true 会进行 count 查询,false 会继续下面的 beforePage 判断 * * @param ms MappedStatement * @param parameterObject 方法参数 * @param rowBounds 分页参数 * @return */ boolean beforeCount(MappedStatement ms, Object parameterObject, RowBounds rowBounds); /** * 生成 count 查询 sql * * @param ms MappedStatement * @param boundSql 绑定 SQL 对象 * @param parameterObject 方法参数 * @param rowBounds 分页参数 * @param countKey count 缓存 key * @return */ String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey); /** * 执行完 count 查询后 * * @param count 查询结果总数 * @param parameterObject 接口参数 * @param rowBounds 分页参数 * @return true 继续分页查询,false 直接返回 */ boolean afterCount(long count, Object parameterObject, RowBounds rowBounds); /** * 处理查询参数对象 * * @param ms MappedStatement * @param parameterObject * @param boundSql * @param pageKey * @return */ Object processParameterObject(MappedStatement ms, Object parameterObject, BoundSql boundSql, CacheKey pageKey); /** * 执行分页前,返回 true 会进行分页查询,false 会返回默认查询结果 * * @param ms MappedStatement * @param parameterObject 方法参数 * @param rowBounds 分页参数 * @return */ boolean beforePage(MappedStatement ms, Object parameterObject, RowBounds rowBounds); /** * 生成分页查询 sql * * @param ms MappedStatement * @param boundSql 绑定 SQL 对象 * @param parameterObject 方法参数 * @param rowBounds 分页参数 * @param pageKey 分页缓存 key * @return */ String getPageSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey pageKey); /** * 分页查询后,处理分页结果,拦截器中直接 return 该方法的返回值 * * @param pageList 分页查询结果 * @param parameterObject 方法参数 * @param rowBounds 分页参数 * @return */ Object afterPage(List pageList, Object parameterObject, RowBounds rowBounds); /** * 完成所有任务后 */ void afterAll(); /** * 设置参数 * * @param properties 插件属性 */ void setProperties(Properties properties); }
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/Dialect.java
759
package org.jeecg.config; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.jeecg.common.api.CommonAPI; import org.jeecg.common.system.vo.DictModel; import org.jeecg.common.util.oConvertUtils; import org.jeecgframework.dict.service.AutoPoiDictServiceI; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import lombok.extern.slf4j.Slf4j; /** * 描述:AutoPoi Excel注解支持字典参数设置 * 举例: @Excel(name = "性别", width = 15, dicCode = "sex") * 1、导出的时候会根据字典配置,把值1,2翻译成:男、女; * 2、导入的时候,会把男、女翻译成1,2存进数据库; * * @Author:scott * @since:2019-04-09 * @Version:1.0 */ @Slf4j @Service public class AutoPoiDictConfig implements AutoPoiDictServiceI { final static String EXCEL_SPLIT_TAG = "_"; final static String TEMP_EXCEL_SPLIT_TAG = "---"; @Lazy @Resource private CommonAPI commonApi; /** * 通过字典查询easypoi,所需字典文本 * * @Author:scott * @since:2019-04-09 * @return */ @Override public String[] queryDict(String dicTable, String dicCode, String dicText) { List<String> dictReplaces = new ArrayList<String>(); List<DictModel> dictList = null; // step.1 如果没有字典表则使用系统字典表 if (oConvertUtils.isEmpty(dicTable)) { dictList = commonApi.queryDictItemsByCode(dicCode); } else { try { dicText = oConvertUtils.getString(dicText, dicCode); dictList = commonApi.queryTableDictItemsByCode(dicTable, dicText, dicCode); } catch (Exception e) { log.error(e.getMessage(),e); } } for (DictModel t : dictList) { //update-begin---author:liusq Date:20230517 for:[issues/4917]excel 导出异常--- if(t!=null && t.getText()!=null && t.getValue()!=null){ //update-end---author:liusq Date:20230517 for:[issues/4917]excel 导出异常--- //update-begin---author:scott Date:20211220 for:[issues/I4MBB3]@Excel dicText字段的值有下划线时,导入功能不能正确解析--- if(t.getValue().contains(EXCEL_SPLIT_TAG)){ String val = t.getValue().replace(EXCEL_SPLIT_TAG,TEMP_EXCEL_SPLIT_TAG); dictReplaces.add(t.getText() + EXCEL_SPLIT_TAG + val); }else{ dictReplaces.add(t.getText() + EXCEL_SPLIT_TAG + t.getValue()); } //update-end---author:20211220 Date:20211220 for:[issues/I4MBB3]@Excel dicText字段的值有下划线时,导入功能不能正确解析--- } } if (dictReplaces != null && dictReplaces.size() != 0) { log.info("---AutoPoi--Get_DB_Dict------"+ dictReplaces.toString()); return dictReplaces.toArray(new String[dictReplaces.size()]); } return null; } }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/config/AutoPoiDictConfig.java
760
/* * Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.mycat.config.ErrorCode; import io.mycat.net.handler.FrontendQueryHandler; import io.mycat.net.mysql.OkPacket; import io.mycat.route.RouteService; import io.mycat.server.handler.BeginHandler; import io.mycat.server.handler.CommandHandler; import io.mycat.server.handler.Explain2Handler; import io.mycat.server.handler.ExplainHandler; import io.mycat.server.handler.KillHandler; import io.mycat.server.handler.MigrateHandler; import io.mycat.server.handler.SavepointHandler; import io.mycat.server.handler.SelectHandler; import io.mycat.server.handler.SetHandler; import io.mycat.server.handler.ShowHandler; import io.mycat.server.handler.StartHandler; import io.mycat.server.handler.UseHandler; import io.mycat.server.parser.ServerParse; /** * @author mycat */ public class ServerQueryHandler implements FrontendQueryHandler { private static final Logger LOGGER = LoggerFactory .getLogger(ServerQueryHandler.class); private final ServerConnection source; protected Boolean readOnly; public void setReadOnly(Boolean readOnly) { this.readOnly = readOnly; } public ServerQueryHandler(ServerConnection source) { this.source = source; } @Override public void query(String sql) { ServerConnection c = this.source; if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder().append(c).append(sql).toString()); } // int rs = ServerParse.parse(sql); int sqlType = rs & 0xff; switch (sqlType) { //explain sql case ServerParse.EXPLAIN: ExplainHandler.handle(sql, c, rs >>> 8); break; //explain2 datanode=? sql=? case ServerParse.EXPLAIN2: Explain2Handler.handle(sql, c, rs >>> 8); break; case ServerParse.COMMAND: CommandHandler.handle(sql, c, 16); break; case ServerParse.SET: SetHandler.handle(sql, c, rs >>> 8); break; case ServerParse.SHOW: ShowHandler.handle(sql, c, rs >>> 8); break; case ServerParse.SELECT: SelectHandler.handle(sql, c, rs >>> 8); break; case ServerParse.START: StartHandler.handle(sql, c, rs >>> 8); break; case ServerParse.BEGIN: BeginHandler.handle(sql, c); break; //不支持oracle的savepoint事务回退点 case ServerParse.SAVEPOINT: SavepointHandler.handle(sql, c); break; case ServerParse.KILL: KillHandler.handle(sql, rs >>> 8, c); break; //不支持KILL_Query case ServerParse.KILL_QUERY: LOGGER.warn(new StringBuilder().append("Unsupported command:").append(sql).toString()); c.writeErrMessage(ErrorCode.ER_UNKNOWN_COM_ERROR,"Unsupported command"); break; case ServerParse.USE: UseHandler.handle(sql, c, rs >>> 8); break; case ServerParse.COMMIT: c.commit(); break; case ServerParse.ROLLBACK: c.rollback(); break; case ServerParse.HELP: LOGGER.warn(new StringBuilder().append("Unsupported command:").append(sql).toString()); c.writeErrMessage(ErrorCode.ER_SYNTAX_ERROR, "Unsupported command"); break; case ServerParse.MYSQL_CMD_COMMENT: c.write(c.writeToBuffer(OkPacket.OK, c.allocate())); break; case ServerParse.MYSQL_COMMENT: c.write(c.writeToBuffer(OkPacket.OK, c.allocate())); break; case ServerParse.LOAD_DATA_INFILE_SQL: if(RouteService.isHintSql(sql) > -1){ // 目前仅支持注解 datanode,原理为直接将导入sql发送到指定mysql节点 c.execute(sql , ServerParse.LOAD_DATA_INFILE_SQL); }else{ c.loadDataInfileStart(sql); } break; case ServerParse.MIGRATE: { try { MigrateHandler.handle(sql, c); }catch (Throwable e){ //MigrateHandler中InterProcessMutex slaveIDsLock 会连接zk,zk连接不上会导致类加载失败, // 此后再调用此命令,将会出现类未定义,所以最终还是需要重启mycat e.printStackTrace(); String msg = "Mycat is not connected to zookeeper!!\n"; msg += "Please start zookeeper and restart mycat so that this mycat can temporarily execute the migration command.If other mycat does not connect to this zookeeper, they will not be able to perceive changes in the migration task.\n"; msg += "After starting zookeeper,you can command tas follow:\n\nmigrate -table=schema.test -add=dn2,dn3 -force=true\n\nto perform the migration.\n"; LOGGER.error(e.getMessage()); LOGGER.error(msg); c.writeErrMessage(ErrorCode.ER_UNKNOWN_ERROR, msg); } break; } case ServerParse.LOCK: c.lockTable(sql); break; case ServerParse.UNLOCK: c.unLockTable(sql); break; default: if(readOnly){ LOGGER.warn(new StringBuilder().append("User readonly:").append(sql).toString()); c.writeErrMessage(ErrorCode.ER_USER_READ_ONLY, "User readonly"); break; } c.execute(sql, rs & 0xff); } switch (sqlType) { case ServerParse.SELECT: case ServerParse.DELETE: case ServerParse.UPDATE: case ServerParse.INSERT: case ServerParse.COMMAND: // curd 在后面会更新 break; default: c.setExecuteSql(null); } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/server/ServerQueryHandler.java
763
package org.nutz.mvc; import java.io.IOException; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URLDecoder; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.nutz.Nutz; import org.nutz.conf.NutConf; import org.nutz.ioc.Ioc; import org.nutz.ioc.IocContext; import org.nutz.json.Json; import org.nutz.json.JsonFormat; import org.nutz.lang.Strings; import org.nutz.lang.util.Context; import org.nutz.lang.util.NutMap; import org.nutz.mvc.config.AtMap; import org.nutz.mvc.i18n.LocalizationManager; import org.nutz.mvc.impl.NutMessageMap; import org.nutz.mvc.ioc.SessionIocContext; /** * Mvc 相关帮助函数 * * @author zozoh([email protected]) * @author wendal([email protected]) */ public abstract class Mvcs { // TODO 这个变量应该在 1.b.46 之后的某一个版本删掉 public static final String DEFAULT_MSGS = "$default"; public static final String MSG = "msg"; public static final String LOCALE_KEY = "nutz_mvc_localization_key"; // PS: 如果这个修改导致异常,请报issue,并将这个变量设置为true public static boolean disableFastClassInvoker = false; // 实现显示行号, 如果禁用, 轻微加速启动 public static boolean DISPLAY_METHOD_LINENUMBER = true; // 如果一个Resp已经commit过了,那么是否跳过渲染呢 public static boolean SKIP_COMMITTED = false; public static boolean DISABLE_X_POWERED_BY = false; public static String X_POWERED_BY = "nutz/"+Nutz.version()+" <nutzam.com>"; public static LocalizationManager localizationManager; public static void setLocalizationManager(LocalizationManager localizationManager) { Mvcs.localizationManager = localizationManager; } // ==================================================================== public static Map<String, Object> getLocaleMessage(String local) { if (localizationManager != null) { return localizationManager.getMessageMap(local); } else { Map<String, Map<String, Object>> msgss = getMessageSet(); if (null != msgss) return msgss.get(local); return null; } } /** * 获取当前请求对象的字符串表 * * @param req * 请求对象 * @return 字符串表 */ @SuppressWarnings("unchecked") public static Map<String, String> getMessages(ServletRequest req) { return (Map<String, String>) req.getAttribute(MSG); } /** * 获取当前请求对象的字符串表(NutMessageMap 封装) * * @param req * 请求对象 * @return 字符串表 */ public static NutMessageMap getMessageMap(ServletRequest req) { return (NutMessageMap) req.getAttribute(MSG); } /** * 获取当前请求对象的字符串表中的某一个字符串 * * @param req * 请求对象 * @param key * 字符串键值 * @return 字符串内容 */ public static String getMessage(ServletRequest req, String key) { Map<String, String> map = getMessages(req); if (null != map) return map.get(key); return null; } /** * 获取当前会话的本地字符串集合的键值;如果当前 HTTP 会话不存在,则返回 null * * @return 当前会话的本地字符串集合的键值;如果当前 HTTP 会话不存在,则返回 null */ public static String getLocalizationKey() { return (String) getSessionAttrSafe(LOCALE_KEY); } /** * 设置本地化字符串的键值 * <p> * 如果你用的是 Nutz.Mvc 默认的本地化机制,那么你的本地字符串键值,相当于一个你目录名。 <br> * 比如 "zh_CN" 等 * * @param key * 键值 * @return 是否设置成功 */ public static boolean setLocalizationKey(String key) { HttpSession sess = getHttpSession(); if (null == sess) return false; sess.setAttribute(LOCALE_KEY, key); return true; } /** * 返回当前加载了的本地化字符串的键值 * * @return 当前都加载了哪些种字符串的 KEY */ public static Set<String> getLocalizationKeySet() { Map<String, Map<String, Object>> msgss = getMessageSet(); if (null == msgss) return new HashSet<String>(); return msgss.keySet(); } /** * 默认的本地化字符串 KEY,当为 NULL 时,Nutz.Mvc 会随便用一个 */ private static String default_localization_key = null; /** * 设置默认的多国语言 * * @param key * 默认的多国语言 KEY */ public static void setDefaultLocalizationKey(String key) { default_localization_key = key; } /** * 返回默认的本地化字符串 KEY * * @return 默认的本地化字符串 KEY */ public static String getDefaultLocalizationKey() { return default_localization_key; } /** * 为当前的 HTTP 请求对象设置一些必要的属性。包括: * <ul> * <li>本地化子字符串 => ${msg} * <li>应用的路径名 => ${base} * </ul> * * @param req * HTTP 请求对象 */ public static void updateRequestAttributes(HttpServletRequest req) { // 初始化本次请求的多国语言字符串 if (localizationManager == null) { Map<String, Map<String, Object>> msgss = getMessageSet(); if (msgss == null && !ctx().localizations.isEmpty()) msgss = ctx().localizations.values().iterator().next(); if (null != msgss) { Map<String, Object> msgs = null; String lKey = Strings.sBlank(Mvcs.getLocalizationKey(), getDefaultLocalizationKey()); if (!Strings.isBlank(lKey)) msgs = msgss.get(lKey); // 没有设定特殊的 Local 名字,随便取一个 if (null == msgs) { if (msgss.size() > 0) msgs = msgss.values().iterator().next(); } // 记录到请求中 req.setAttribute(MSG, msgs); } } else { String lKey = Mvcs.getLocalizationKey(); if (Strings.isBlank(lKey)) { lKey = localizationManager.getDefaultLocal(); if (Strings.isBlank(lKey)) lKey = getDefaultLocalizationKey(); } NutMessageMap msg = localizationManager.getMessageMap(lKey); if (msg != null) req.setAttribute(MSG, msg); } // 记录一些数据到请求对象中 req.setAttribute("base", req.getContextPath()); if (NutConf.MVC_ADD_ATTR_$REQUEST) req.setAttribute("$request", req); } /** * 获取当前请求的路径,并去掉后缀 * * @param req * HTTP 请求对象 */ public static String getRequestPath(HttpServletRequest req) { return getRequestPathObject(req).getPath(); } /** * 获取当前请求的路径,并去掉后缀 * * @param req * HTTP 请求对象 */ public static RequestPath getRequestPathObject(HttpServletRequest req) { Object includeUrl = req.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO); if (includeUrl != null) { return getRequestPathObject(includeUrl.toString()); } includeUrl = req.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); if (includeUrl != null) { return getRequestPathObject(includeUrl.toString()); } String url = req.getPathInfo(); if (null == url) url = req.getServletPath(); return getRequestPathObject(url); } /** * 获取当前请求的路径,并去掉后缀 * * @param url * 请求路径的URL */ public static RequestPath getRequestPathObject(String url) { RequestPath rr = new RequestPath(); rr.setUrl(url); if (null != url) { int lio = 0; if (!url.endsWith("/")) { int ll = url.lastIndexOf('/'); lio = url.lastIndexOf('.'); if (lio < ll) lio = -1; } if (lio > 0) { rr.setPath(url.substring(0, lio)); rr.setSuffix(url.substring(lio + 1)); } else { rr.setPath(url); rr.setSuffix(""); } } else { rr.setPath(""); rr.setSuffix(""); } return rr; } /** * 注销当前 HTTP 会话。所有 Ioc 容器存入的对象都会被注销 * * @param session * HTTP 会话对象 */ public static void deposeSession(HttpSession session) { if (session != null) new SessionIocContext(session).depose(); } /** * 它将对象序列化成 JSON 字符串,并写入 HTTP 响应 * * @param resp * 响应对象 * @param obj * 数据对象 * @param format * JSON 的格式化方式 * @throws IOException * 写入失败 */ public static void write(HttpServletResponse resp, Object obj, JsonFormat format) throws IOException { write(resp, resp.getWriter(), obj, format); } public static void write(HttpServletResponse resp, Writer writer, Object obj, JsonFormat format) throws IOException { resp.setHeader("Cache-Control", "no-cache"); if (resp.getContentType() == null) resp.setContentType("text/plain"); // by mawm 改为直接采用resp.getWriter()的方式直接输出! Json.toJson(writer, obj, format); resp.flushBuffer(); } // ================================================================== private static final ThreadLocal<String> NAME = new ThreadLocal<String>(); /** * NutMvc的上下文 */ @Deprecated public static NutMvcContext ctx; public static NutMvcContext ctx() { ServletContext sc = getServletContext(); if (sc == null) { if (ctx == null) ctx = new NutMvcContext(); return ctx; } NutMvcContext c = (NutMvcContext) getServletContext().getAttribute("__nutz__mvc__ctx"); if (c == null) { c = new NutMvcContext(); getServletContext().setAttribute("__nutz__mvc__ctx", c); ctx = c; } return c; } private static ServletContext def_servletContext; private static ThreadLocal<ServletContext> servletContext = new ThreadLocal<ServletContext>(); /** * 获取 HTTP 请求对象 * * @return HTTP 请求对象 */ public static final HttpServletRequest getReq() { return reqt().getAs(HttpServletRequest.class, "req"); } /** * 获取 HTTP 响应对象 * * @return HTTP 响应对象 */ public static final HttpServletResponse getResp() { return reqt().getAs(HttpServletResponse.class, "resp"); } public static final String getName() { return NAME.get(); } /** * 获取 Action 执行的上下文 * * @return Action 执行的上下文 */ public static final ActionContext getActionContext() { return reqt().getAs(ActionContext.class, "ActionContext"); } public static void set(String name, HttpServletRequest req, HttpServletResponse resp) { NAME.set(name); reqt().set("req", req); reqt().set("resp", resp); } /** * 设置 Servlet 执行的上下文 * * @param servletContext * Servlet 执行的上下文 */ public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { Mvcs.servletContext.remove(); } if (def_servletContext == null) def_servletContext = servletContext; Mvcs.servletContext.set(servletContext); } /** * 设置 Action 执行的上下文 * * @param actionContext * Action 执行的上下文 */ public static void setActionContext(ActionContext actionContext) { reqt().set("ActionContext", actionContext); } /** * 获取 Servlet 执行的上下文 * * @return Servlet 执行的上下文 */ public static ServletContext getServletContext() { ServletContext cnt = servletContext.get(); if (cnt != null) return cnt; return def_servletContext; } /** * 设置对象装配的上下文环境 * * @param iocContext * 对象装配的上下文环境 */ public static void setIocContext(IocContext iocContext) { reqt().set("IocContext", iocContext); } /** * 获取对象装配的上下文环境 * * @return 进行对象装配的上下文环境 */ public static IocContext getIocContext() { return reqt().getAs(IocContext.class, "IocContext"); } // 新的,基于ThreadLoacl改造过的Mvc辅助方法 // ==================================================================== /** * 获取全局的Ioc对象 * * @return 全局的Ioc对象 */ public static Ioc getIoc() { return ctx().iocs.get(getName()); } public static void setIoc(Ioc ioc) { ctx().iocs.put(getName(), ioc); } public static AtMap getAtMap() { return ctx().atMaps.get(getName()); } public static void setAtMap(AtMap atmap) { ctx().atMaps.put(getName(), atmap); } public static Map<String, Map<String, Object>> getMessageSet() { return ctx().localizations.get(getName()); } public static void setMessageSet(Map<String, Map<String, Object>> messageSet) { ctx().localizations.put(getName(), messageSet); } public static void setNutConfig(NutConfig config) { ctx().nutConfigs.put(getName(), config); } public static NutConfig getNutConfig() { return ctx().nutConfigs.get(getName()); } // ================================================================== /** * 重置当前线程所持有的对象 */ public static Context resetALL() { Context context = reqt(); NAME.set(null); ctx().removeReqCtx(); return context; } public static HttpSession getHttpSession() { return getHttpSession(true); } public static HttpSession getHttpSession(boolean createNew) { HttpServletRequest req = getReq(); if (null == req) return null; return req.getSession(createNew); } public static void close() { ctx().clear(); ctx().close(); ctx = new NutMvcContext(); } public static Context reqt() { return ctx().reqCtx(); } public static Object getSessionAttrSafe(String key) { try { HttpSession session = getHttpSession(false); return session != null ? session.getAttribute(key) : null; } catch (Throwable e) { return null; } } public static void setSessionAttrSafe(String key, Object val, boolean sessionCreate) { try { HttpSession session = getHttpSession(sessionCreate); if (session != null) session.setAttribute(key, val); } catch (Exception e) { } } public static NutMap toParamMap(Reader r, String enc) throws IOException { try { NutMap map = new NutMap(); char[] buf = new char[1]; StringBuilder sb = new StringBuilder(); while (true) { int len = r.read(buf); if (len == 0) continue; if (buf[0] == '&' || len < 0) { String[] tmp = sb.toString().split("="); if (tmp != null && tmp.length == 2) { map.put(URLDecoder.decode(tmp[0], enc), URLDecoder.decode(tmp[1], enc)); } if (len < 0) break; sb.setLength(0); } else { sb.append(buf[0]); } } return map; } catch (UnsupportedEncodingException e) { throw new IOException(e); } } }
nutzam/nutz
src/org/nutz/mvc/Mvcs.java
764
/* * Copyright 2017 JessYan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jess.arms.base; import android.app.Service; import android.content.Intent; import android.os.IBinder; import androidx.annotation.Nullable; import com.jess.arms.integration.EventBusManager; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; /** * ================================================ * 基类 {@link Service} * <p> * Created by jess on 2016/5/6. * <a href="mailto:[email protected]">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * ================================================ */ public abstract class BaseService extends Service { protected final String TAG = this.getClass().getSimpleName(); protected CompositeDisposable mCompositeDisposable; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); if (useEventBus()) { EventBusManager.getInstance().register(this); } init(); } @Override public void onDestroy() { super.onDestroy(); if (useEventBus()) { EventBusManager.getInstance().unregister(this); } unDispose();//解除订阅 this.mCompositeDisposable = null; } /** * 是否使用 EventBus * Arms 核心库现在并不会依赖某个 EventBus, 要想使用 EventBus, 还请在项目中自行依赖对应的 EventBus * 现在支持两种 EventBus, greenrobot 的 EventBus 和畅销书 《Android源码设计模式解析与实战》的作者 何红辉 所作的 AndroidEventBus * 确保依赖后, 将此方法返回 true, Arms 会自动检测您依赖的 EventBus, 并自动注册 * 这种做法可以让使用者有自行选择三方库的权利, 并且还可以减轻 Arms 的体积 * * @return 返回 {@code true} (默认为 {@code true}), Arms 会自动注册 EventBus */ public boolean useEventBus() { return true; } protected void addDispose(Disposable disposable) { if (mCompositeDisposable == null) { mCompositeDisposable = new CompositeDisposable(); } mCompositeDisposable.add(disposable);//将所有 Disposable 放入容器集中处理 } protected void unDispose() { if (mCompositeDisposable != null) { mCompositeDisposable.clear();//保证 Activity 结束时取消所有正在执行的订阅 } } /** * 初始化 */ abstract public void init(); }
JessYanCoding/MVPArms
arms/src/main/java/com/jess/arms/base/BaseService.java
766
package me.zhyd.oauth.request; import com.xkcoding.http.util.UrlUtil; import me.zhyd.oauth.cache.AuthDefaultStateCache; import me.zhyd.oauth.cache.AuthStateCache; import me.zhyd.oauth.config.AuthConfig; import me.zhyd.oauth.config.AuthSource; import me.zhyd.oauth.enums.AuthResponseStatus; import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.log.Log; import me.zhyd.oauth.model.AuthCallback; import me.zhyd.oauth.model.AuthResponse; import me.zhyd.oauth.model.AuthToken; import me.zhyd.oauth.model.AuthUser; import me.zhyd.oauth.utils.*; import java.util.List; /** * 默认的request处理类 * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @author yangkai.shen (https://xkcoding.com) * @since 1.0.0 */ public abstract class AuthDefaultRequest implements AuthRequest { protected AuthConfig config; protected AuthSource source; protected AuthStateCache authStateCache; public AuthDefaultRequest(AuthConfig config, AuthSource source) { this(config, source, AuthDefaultStateCache.INSTANCE); } public AuthDefaultRequest(AuthConfig config, AuthSource source, AuthStateCache authStateCache) { this.config = config; this.source = source; this.authStateCache = authStateCache; if (!AuthChecker.isSupportedAuth(config, source)) { throw new AuthException(AuthResponseStatus.PARAMETER_INCOMPLETE, source); } // 校验配置合法性 AuthChecker.checkConfig(config, source); } /** * 获取access token * * @param authCallback 授权成功后的回调参数 * @return token * @see AuthDefaultRequest#authorize() * @see AuthDefaultRequest#authorize(String) */ protected abstract AuthToken getAccessToken(AuthCallback authCallback); /** * 使用token换取用户信息 * * @param authToken token信息 * @return 用户信息 * @see AuthDefaultRequest#getAccessToken(AuthCallback) */ protected abstract AuthUser getUserInfo(AuthToken authToken); /** * 统一的登录入口。当通过{@link AuthDefaultRequest#authorize(String)}授权成功后,会跳转到调用方的相关回调方法中 * 方法的入参可以使用{@code AuthCallback},{@code AuthCallback}类中封装好了OAuth2授权回调所需要的参数 * * @param authCallback 用于接收回调参数的实体 * @return AuthResponse */ @Override public AuthResponse login(AuthCallback authCallback) { try { checkCode(authCallback); if (!config.isIgnoreCheckState()) { AuthChecker.checkState(authCallback.getState(), source, authStateCache); } AuthToken authToken = this.getAccessToken(authCallback); AuthUser user = this.getUserInfo(authToken); return AuthResponse.builder().code(AuthResponseStatus.SUCCESS.getCode()).data(user).build(); } catch (Exception e) { Log.error("Failed to login with oauth authorization.", e); return this.responseError(e); } } protected void checkCode(AuthCallback authCallback) { AuthChecker.checkCode(source, authCallback); } /** * 处理{@link AuthDefaultRequest#login(AuthCallback)} 发生异常的情况,统一响应参数 * * @param e 具体的异常 * @return AuthResponse */ AuthResponse responseError(Exception e) { int errorCode = AuthResponseStatus.FAILURE.getCode(); String errorMsg = e.getMessage(); if (e instanceof AuthException) { AuthException authException = ((AuthException) e); errorCode = authException.getErrorCode(); if (StringUtils.isNotEmpty(authException.getErrorMsg())) { errorMsg = authException.getErrorMsg(); } } return AuthResponse.builder().code(errorCode).msg(errorMsg).build(); } /** * 返回授权url,可自行跳转页面 * <p> * 不建议使用该方式获取授权地址,不带{@code state}的授权地址,容易受到csrf攻击。 * 建议使用{@link AuthDefaultRequest#authorize(String)}方法生成授权地址,在回调方法中对{@code state}进行校验 * * @return 返回授权地址 * @see AuthDefaultRequest#authorize(String) */ @Deprecated @Override public String authorize() { return this.authorize(null); } /** * 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state} * * @param state state 验证授权流程的参数,可以防止csrf * @return 返回授权地址 * @since 1.9.3 */ @Override public String authorize(String state) { return UrlBuilder.fromBaseUrl(source.authorize()) .queryParam("response_type", "code") .queryParam("client_id", config.getClientId()) .queryParam("redirect_uri", config.getRedirectUri()) .queryParam("state", getRealState(state)) .build(); } /** * 返回获取accessToken的url * * @param code 授权码 * @return 返回获取accessToken的url */ protected String accessTokenUrl(String code) { return UrlBuilder.fromBaseUrl(source.accessToken()) .queryParam("code", code) .queryParam("client_id", config.getClientId()) .queryParam("client_secret", config.getClientSecret()) .queryParam("grant_type", "authorization_code") .queryParam("redirect_uri", config.getRedirectUri()) .build(); } /** * 返回获取accessToken的url * * @param refreshToken refreshToken * @return 返回获取accessToken的url */ protected String refreshTokenUrl(String refreshToken) { return UrlBuilder.fromBaseUrl(source.refresh()) .queryParam("client_id", config.getClientId()) .queryParam("client_secret", config.getClientSecret()) .queryParam("refresh_token", refreshToken) .queryParam("grant_type", "refresh_token") .queryParam("redirect_uri", config.getRedirectUri()) .build(); } /** * 返回获取userInfo的url * * @param authToken token * @return 返回获取userInfo的url */ protected String userInfoUrl(AuthToken authToken) { return UrlBuilder.fromBaseUrl(source.userInfo()).queryParam("access_token", authToken.getAccessToken()).build(); } /** * 返回获取revoke authorization的url * * @param authToken token * @return 返回获取revoke authorization的url */ protected String revokeUrl(AuthToken authToken) { return UrlBuilder.fromBaseUrl(source.revoke()).queryParam("access_token", authToken.getAccessToken()).build(); } /** * 获取state,如果为空, 则默认取当前日期的时间戳 * * @param state 原始的state * @return 返回不为null的state */ protected String getRealState(String state) { if (StringUtils.isEmpty(state)) { state = UuidUtils.getUUID(); } // 缓存state authStateCache.cache(state, state); return state; } /** * 通用的 authorizationCode 协议 * * @param code code码 * @return Response */ protected String doPostAuthorizationCode(String code) { return new HttpUtils(config.getHttpConfig()).post(accessTokenUrl(code)).getBody(); } /** * 通用的 authorizationCode 协议 * * @param code code码 * @return Response */ protected String doGetAuthorizationCode(String code) { return new HttpUtils(config.getHttpConfig()).get(accessTokenUrl(code)).getBody(); } /** * 通用的 用户信息 * * @param authToken token封装 * @return Response */ @Deprecated protected String doPostUserInfo(AuthToken authToken) { return new HttpUtils(config.getHttpConfig()).post(userInfoUrl(authToken)).getBody(); } /** * 通用的 用户信息 * * @param authToken token封装 * @return Response */ protected String doGetUserInfo(AuthToken authToken) { return new HttpUtils(config.getHttpConfig()).get(userInfoUrl(authToken)).getBody(); } /** * 通用的post形式的取消授权方法 * * @param authToken token封装 * @return Response */ @Deprecated protected String doPostRevoke(AuthToken authToken) { return new HttpUtils(config.getHttpConfig()).post(revokeUrl(authToken)).getBody(); } /** * 通用的post形式的取消授权方法 * * @param authToken token封装 * @return Response */ protected String doGetRevoke(AuthToken authToken) { return new HttpUtils(config.getHttpConfig()).get(revokeUrl(authToken)).getBody(); } /** * 获取以 {@code separator}分割过后的 scope 信息 * * @param separator 多个 {@code scope} 间的分隔符 * @param encode 是否 encode 编码 * @param defaultScopes 默认的 scope, 当客户端没有配置 {@code scopes} 时启用 * @return String * @since 1.16.7 */ protected String getScopes(String separator, boolean encode, List<String> defaultScopes) { List<String> scopes = config.getScopes(); if (null == scopes || scopes.isEmpty()) { if (null == defaultScopes || defaultScopes.isEmpty()) { return ""; } scopes = defaultScopes; } if (null == separator) { // 默认为空格 separator = " "; } String scopeStr = String.join(separator, scopes); return encode ? UrlUtil.urlEncode(scopeStr) : scopeStr; } }
justauth/JustAuth
src/main/java/me/zhyd/oauth/request/AuthDefaultRequest.java
772
package com.zheng.common.base; import com.zheng.common.util.PropertiesFileUtil; import org.apache.shiro.authz.UnauthorizedException; import org.apache.shiro.session.InvalidSessionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 控制器基类 * Created by ZhangShuzheng on 2017/2/4. */ public abstract class BaseController { private final static Logger LOGGER = LoggerFactory.getLogger(BaseController.class); /** * 统一异常处理 * @param request * @param response * @param exception */ @ExceptionHandler public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) { LOGGER.error("统一异常处理:", exception); request.setAttribute("ex", exception); if (null != request.getHeader("X-Requested-With") && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) { request.setAttribute("requestHeader", "ajax"); } // shiro没有权限异常 if (exception instanceof UnauthorizedException) { return "/403.jsp"; } // shiro会话已过期异常 if (exception instanceof InvalidSessionException) { return "/error.jsp"; } return "/error.jsp"; } /** * 返回jsp视图 * @param path * @return */ public static String jsp(String path) { return path.concat(".jsp"); } /** * 返回thymeleaf视图 * @param path * @return */ public static String thymeleaf(String path) { String folder = PropertiesFileUtil.getInstance().get("app.name"); return "/".concat(folder).concat(path).concat(".html"); } }
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/base/BaseController.java
774
/** * File: binary_search_tree.java * Created Time: 2022-11-25 * Author: krahets ([email protected]) */ package chapter_tree; import utils.*; /* 二叉搜索树 */ class BinarySearchTree { private TreeNode root; /* 构造方法 */ public BinarySearchTree() { // 初始化空树 root = null; } /* 获取二叉树根节点 */ public TreeNode getRoot() { return root; } /* 查找节点 */ public TreeNode search(int num) { TreeNode cur = root; // 循环查找,越过叶节点后跳出 while (cur != null) { // 目标节点在 cur 的右子树中 if (cur.val < num) cur = cur.right; // 目标节点在 cur 的左子树中 else if (cur.val > num) cur = cur.left; // 找到目标节点,跳出循环 else break; } // 返回目标节点 return cur; } /* 插入节点 */ public void insert(int num) { // 若树为空,则初始化根节点 if (root == null) { root = new TreeNode(num); return; } TreeNode cur = root, pre = null; // 循环查找,越过叶节点后跳出 while (cur != null) { // 找到重复节点,直接返回 if (cur.val == num) return; pre = cur; // 插入位置在 cur 的右子树中 if (cur.val < num) cur = cur.right; // 插入位置在 cur 的左子树中 else cur = cur.left; } // 插入节点 TreeNode node = new TreeNode(num); if (pre.val < num) pre.right = node; else pre.left = node; } /* 删除节点 */ public void remove(int num) { // 若树为空,直接提前返回 if (root == null) return; TreeNode cur = root, pre = null; // 循环查找,越过叶节点后跳出 while (cur != null) { // 找到待删除节点,跳出循环 if (cur.val == num) break; pre = cur; // 待删除节点在 cur 的右子树中 if (cur.val < num) cur = cur.right; // 待删除节点在 cur 的左子树中 else cur = cur.left; } // 若无待删除节点,则直接返回 if (cur == null) return; // 子节点数量 = 0 or 1 if (cur.left == null || cur.right == null) { // 当子节点数量 = 0 / 1 时, child = null / 该子节点 TreeNode child = cur.left != null ? cur.left : cur.right; // 删除节点 cur if (cur != root) { if (pre.left == cur) pre.left = child; else pre.right = child; } else { // 若删除节点为根节点,则重新指定根节点 root = child; } } // 子节点数量 = 2 else { // 获取中序遍历中 cur 的下一个节点 TreeNode tmp = cur.right; while (tmp.left != null) { tmp = tmp.left; } // 递归删除节点 tmp remove(tmp.val); // 用 tmp 覆盖 cur cur.val = tmp.val; } } } public class binary_search_tree { public static void main(String[] args) { /* 初始化二叉搜索树 */ BinarySearchTree bst = new BinarySearchTree(); // 请注意,不同的插入顺序会生成不同的二叉树,该序列可以生成一个完美二叉树 int[] nums = { 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 }; for (int num : nums) { bst.insert(num); } System.out.println("\n初始化的二叉树为\n"); PrintUtil.printTree(bst.getRoot()); /* 查找节点 */ TreeNode node = bst.search(7); System.out.println("\n查找到的节点对象为 " + node + ",节点值 = " + node.val); /* 插入节点 */ bst.insert(16); System.out.println("\n插入节点 16 后,二叉树为\n"); PrintUtil.printTree(bst.getRoot()); /* 删除节点 */ bst.remove(1); System.out.println("\n删除节点 1 后,二叉树为\n"); PrintUtil.printTree(bst.getRoot()); bst.remove(2); System.out.println("\n删除节点 2 后,二叉树为\n"); PrintUtil.printTree(bst.getRoot()); bst.remove(4); System.out.println("\n删除节点 4 后,二叉树为\n"); PrintUtil.printTree(bst.getRoot()); } }
krahets/hello-algo
codes/java/chapter_tree/binary_search_tree.java
775
/* public class TreeLinkNode { int val; TreeLinkNode left = null; TreeLinkNode right = null; TreeLinkNode next = null; TreeLinkNode(int val) { this.val = val; } } */ /** * @author Anonymous * @since 2019/10/28 */ public class Solution { /** * 获取中序遍历结点的下一个结点 * * @param pNode 某个结点 * @return pNode的下一个结点 */ public TreeLinkNode GetNext(TreeLinkNode pNode) { if (pNode == null) { return null; } if (pNode.right != null) { TreeLinkNode t = pNode.right; while (t.left != null) { t = t.left; } return t; } // 须保证 pNode.next 不为空,否则会出现 NPE if (pNode.next != null && pNode.next.left == pNode) { return pNode.next; } while (pNode.next != null) { if (pNode.next.left == pNode) { return pNode.next; } pNode = pNode.next; } return null; } }
geekxh/hello-algorithm
算法读物/剑指offer/08_NextNodeInBinaryTrees/Solution.java
777
/** * IK 中文分词 版本 5.0.1 * IK Analyzer release 5.0.1 * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * 源代码由林良益([email protected])提供 * 版权声明 2012,乌龙茶工作室 * provided by Linliangyi and copyright 2012 by Oolong studio * * */ package org.wltea.analyzer.lucene; import org.apache.lucene.analysis.Tokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.tokenattributes.TypeAttribute; import org.wltea.analyzer.cfg.Configuration; import org.wltea.analyzer.core.IKSegmenter; import org.wltea.analyzer.core.Lexeme; import java.io.IOException; import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute; /** * IK分词器 Lucene Tokenizer适配器类 * 兼容Lucene 4.0版本 */ public final class IKTokenizer extends Tokenizer { //IK分词器实现 private IKSegmenter _IKImplement; //词元文本属性 private final CharTermAttribute termAtt; //词元位移属性 private final OffsetAttribute offsetAtt; //词元分类属性(该属性分类参考org.wltea.analyzer.core.Lexeme中的分类常量) private final TypeAttribute typeAtt; //记录最后一个词元的结束位置 private int endPosition; private int skippedPositions; private PositionIncrementAttribute posIncrAtt; /** * Lucene 4.0 Tokenizer适配器类构造函数 */ public IKTokenizer(Configuration configuration){ super(); offsetAtt = addAttribute(OffsetAttribute.class); termAtt = addAttribute(CharTermAttribute.class); typeAtt = addAttribute(TypeAttribute.class); posIncrAtt = addAttribute(PositionIncrementAttribute.class); _IKImplement = new IKSegmenter(input,configuration); } /* (non-Javadoc) * @see org.apache.lucene.analysis.TokenStream#incrementToken() */ @Override public boolean incrementToken() throws IOException { //清除所有的词元属性 clearAttributes(); skippedPositions = 0; Lexeme nextLexeme = _IKImplement.next(); if(nextLexeme != null){ posIncrAtt.setPositionIncrement(skippedPositions +1 ); //将Lexeme转成Attributes //设置词元文本 termAtt.append(nextLexeme.getLexemeText()); //设置词元长度 termAtt.setLength(nextLexeme.getLength()); //设置词元位移 offsetAtt.setOffset(correctOffset(nextLexeme.getBeginPosition()), correctOffset(nextLexeme.getEndPosition())); //记录分词的最后位置 endPosition = nextLexeme.getEndPosition(); //记录词元分类 typeAtt.setType(nextLexeme.getLexemeTypeString()); //返会true告知还有下个词元 return true; } //返会false告知词元输出完毕 return false; } /* * (non-Javadoc) * @see org.apache.lucene.analysis.Tokenizer#reset(java.io.Reader) */ @Override public void reset() throws IOException { super.reset(); _IKImplement.reset(input); skippedPositions = 0; endPosition = 0; } @Override public final void end() throws IOException { super.end(); // set final offset int finalOffset = correctOffset(this.endPosition+ _IKImplement.getLastUselessCharNum()); offsetAtt.setOffset(finalOffset, finalOffset); posIncrAtt.setPositionIncrement(posIncrAtt.getPositionIncrement() + skippedPositions); } }
infinilabs/analysis-ik
core/src/main/java/org/wltea/analyzer/lucene/IKTokenizer.java
781
package com.xkcoding.mq.rabbitmq.handler; import cn.hutool.json.JSONUtil; import com.rabbitmq.client.Channel; import com.xkcoding.mq.rabbitmq.constants.RabbitConsts; import com.xkcoding.mq.rabbitmq.message.MessageStruct; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; import java.io.IOException; /** * <p> * 延迟队列处理器 * </p> * * @author yangkai.shen * @date Created in 2019-01-04 17:42 */ @Slf4j @Component @RabbitListener(queues = RabbitConsts.DELAY_QUEUE) public class DelayQueueHandler { @RabbitHandler public void directHandlerManualAck(MessageStruct messageStruct, Message message, Channel channel) { // 如果手动ACK,消息会被监听消费,但是消息在队列中依旧存在,如果 未配置 acknowledge-mode 默认是会在消费完毕后自动ACK掉 final long deliveryTag = message.getMessageProperties().getDeliveryTag(); try { log.info("延迟队列,手动ACK,接收消息:{}", JSONUtil.toJsonStr(messageStruct)); // 通知 MQ 消息已被成功消费,可以ACK了 channel.basicAck(deliveryTag, false); } catch (IOException e) { try { // 处理失败,重新压入MQ channel.basicRecover(); } catch (IOException e1) { e1.printStackTrace(); } } } }
xkcoding/spring-boot-demo
demo-mq-rabbitmq/src/main/java/com/xkcoding/mq/rabbitmq/handler/DelayQueueHandler.java
782
package com.crossoverjie.algorithm; import java.util.LinkedList; /** * Function: * * @author crossoverJie * Date: 04/01/2018 18:26 * @since JDK 1.8 */ public class BinaryNode { private Object data ; private BinaryNode left ; private BinaryNode right ; public BinaryNode() { } public BinaryNode(Object data, BinaryNode left, BinaryNode right) { this.data = data; this.left = left; this.right = right; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public BinaryNode getLeft() { return left; } public void setLeft(BinaryNode left) { this.left = left; } public BinaryNode getRight() { return right; } public void setRight(BinaryNode right) { this.right = right; } public BinaryNode createNode(){ BinaryNode node = new BinaryNode("1",null,null) ; BinaryNode left2 = new BinaryNode("2",null,null) ; BinaryNode left3 = new BinaryNode("3",null,null) ; BinaryNode left4 = new BinaryNode("4",null,null) ; BinaryNode left5 = new BinaryNode("5",null,null) ; BinaryNode left6 = new BinaryNode("6",null,null) ; node.setLeft(left2) ; left2.setLeft(left4); left2.setRight(left6); node.setRight(left3); left3.setRight(left5) ; return node ; } @Override public String toString() { return "BinaryNode{" + "data=" + data + ", left=" + left + ", right=" + right + '}'; } /** * 二叉树的层序遍历 借助于队列来实现 借助队列的先进先出的特性 * * 首先将根节点入队列 然后遍历队列。 * 首先将根节点打印出来,接着判断左节点是否为空 不为空则加入队列 * @param node */ public void levelIterator(BinaryNode node){ LinkedList<BinaryNode> queue = new LinkedList<>() ; //先将根节点入队 queue.offer(node) ; BinaryNode current ; while (!queue.isEmpty()){ current = queue.poll(); System.out.print(current.data+"--->"); if (current.getLeft() != null){ queue.offer(current.getLeft()) ; } if (current.getRight() != null){ queue.offer(current.getRight()) ; } } } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/algorithm/BinaryNode.java
783
package cn.hutool.db.sql; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.db.Entity; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Map.Entry; /** * 包装器<br> * 主要用于字段名的包装(在字段名的前后加字符,例如反引号来避免与数据库的关键字冲突) * * @author Looly */ public class Wrapper implements Serializable { private static final long serialVersionUID = 1L; /** * 前置包装符号 */ private Character preWrapQuote; /** * 后置包装符号 */ private Character sufWrapQuote; public Wrapper() { } /** * 构造 * * @param wrapQuote 单包装字符 */ public Wrapper(Character wrapQuote) { this.preWrapQuote = wrapQuote; this.sufWrapQuote = wrapQuote; } /** * 包装符号 * * @param preWrapQuote 前置包装符号 * @param sufWrapQuote 后置包装符号 */ public Wrapper(Character preWrapQuote, Character sufWrapQuote) { this.preWrapQuote = preWrapQuote; this.sufWrapQuote = sufWrapQuote; } //--------------------------------------------------------------- Getters and Setters start /** * @return 前置包装符号 */ public char getPreWrapQuote() { return preWrapQuote; } /** * 设置前置包装的符号 * * @param preWrapQuote 前置包装符号 */ public void setPreWrapQuote(Character preWrapQuote) { this.preWrapQuote = preWrapQuote; } /** * @return 后置包装符号 */ public char getSufWrapQuote() { return sufWrapQuote; } /** * 设置后置包装的符号 * * @param sufWrapQuote 后置包装符号 */ public void setSufWrapQuote(Character sufWrapQuote) { this.sufWrapQuote = sufWrapQuote; } //--------------------------------------------------------------- Getters and Setters end /** * 包装字段名<br> * 有时字段与SQL的某些关键字冲突,导致SQL出错,因此需要将字段名用单引号或者反引号包装起来,避免冲突 * * @param field 字段名 * @return 包装后的字段名 */ public String wrap(String field) { if (preWrapQuote == null || sufWrapQuote == null || StrUtil.isBlank(field)) { return field; } //如果已经包含包装的引号,返回原字符 if (StrUtil.isSurround(field, preWrapQuote, sufWrapQuote)) { return field; } //如果字段中包含通配符或者括号(字段通配符或者函数),不做包装 if (StrUtil.containsAnyIgnoreCase(field, "*", "(", " ", " as ")) { return field; } //对于Oracle这类数据库,表名中包含用户名需要单独拆分包装 if (field.contains(StrUtil.DOT)) { final Collection<String> target = CollUtil.edit(StrUtil.split(field, CharUtil.DOT, 2), t -> StrUtil.format("{}{}{}", preWrapQuote, t, sufWrapQuote)); return CollectionUtil.join(target, StrUtil.DOT); } return StrUtil.format("{}{}{}", preWrapQuote, field, sufWrapQuote); } /** * 解包装字段名<br> * * @param field 字段名 * @return 未包装的字段名 * @since 5.8.27 */ public String unWrap(String field) { if (preWrapQuote == null || sufWrapQuote == null || StrUtil.isBlank(field)) { return field; } //如果已经包含包装的引号,返回原字符 if (!StrUtil.isSurround(field, preWrapQuote, sufWrapQuote)) { return field; } //如果字段中包含通配符或者括号(字段通配符或者函数),不做解包装 if (StrUtil.containsAnyIgnoreCase(field, "*", "(", " ", " as ")) { return field; } //对于Oracle这类数据库,表名中包含用户名需要单独拆分包装 if (field.contains(StrUtil.DOT)) { final Collection<String> target = CollUtil.edit(StrUtil.split(field, CharUtil.DOT, 2), t -> StrUtil.unWrap(t, preWrapQuote, sufWrapQuote)); return CollectionUtil.join(target, StrUtil.DOT); } return StrUtil.unWrap(field, preWrapQuote, sufWrapQuote); } /** * 包装字段名<br> * 有时字段与SQL的某些关键字冲突,导致SQL出错,因此需要将字段名用单引号或者反引号包装起来,避免冲突 * * @param fields 字段名 * @return 包装后的字段名 */ public String[] wrap(String... fields) { if (ArrayUtil.isEmpty(fields)) { return fields; } String[] wrappedFields = new String[fields.length]; for (int i = 0; i < fields.length; i++) { wrappedFields[i] = wrap(fields[i]); } return wrappedFields; } /** * 包装字段名<br> * 有时字段与SQL的某些关键字冲突,导致SQL出错,因此需要将字段名用单引号或者反引号包装起来,避免冲突 * * @param fields 字段名 * @return 包装后的字段名 */ public Collection<String> wrap(Collection<String> fields) { if (CollectionUtil.isEmpty(fields)) { return fields; } return Arrays.asList(wrap(fields.toArray(new String[0]))); } /** * 包装表名和字段名,此方法返回一个新的Entity实体类<br> * 有时字段与SQL的某些关键字冲突,导致SQL出错,因此需要将字段名用单引号或者反引号包装起来,避免冲突 * * @param entity 被包装的实体 * @return 新的实体 */ public Entity wrap(Entity entity) { if (null == entity) { return null; } final Entity wrapedEntity = new Entity(); //wrap table name wrapedEntity.setTableName(wrap(entity.getTableName())); //wrap fields for (Entry<String, Object> entry : entity.entrySet()) { wrapedEntity.set(wrap(entry.getKey()), entry.getValue()); } return wrapedEntity; } /** * 包装字段名<br> * 有时字段与SQL的某些关键字冲突,导致SQL出错,因此需要将字段名用单引号或者反引号包装起来,避免冲突 * * @param conditions 被包装的实体 * @return 包装后的字段名 */ public Condition[] wrap(Condition... conditions) { final Condition[] clonedConditions = new Condition[conditions.length]; if (ArrayUtil.isNotEmpty(conditions)) { Condition clonedCondition; for (int i = 0; i < conditions.length; i++) { clonedCondition = conditions[i].clone(); clonedCondition.setField(wrap(clonedCondition.getField())); clonedConditions[i] = clonedCondition; } } return clonedConditions; } }
dromara/hutool
hutool-db/src/main/java/cn/hutool/db/sql/Wrapper.java
784
/* * Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dianping.cat.app; import org.unidal.lookup.util.StringUtils; public enum AppDataField { OPERATOR("operator", "运营商"), NETWORK("network", "网络类型"), APP_VERSION("app-version", "版本"), CONNECT_TYPE("connect-type", "连接类型"), PLATFORM("platform", "平台"), SOURCE("source", "来源"), CITY("city", "城市"), CODE("code", "返回码"); private String m_name; private String m_title; AppDataField(String name, String title) { m_name = name; m_title = title; } public static AppDataField getByName(String name, AppDataField defaultField) { if (StringUtils.isNotEmpty(name)) { for (AppDataField field : AppDataField.values()) { if (field.getName().equals(name)) { return field; } } } return defaultField; } public static AppDataField getByTitle(String title) { if (StringUtils.isNotEmpty(title)) { for (AppDataField field : AppDataField.values()) { if (field.getTitle().equals(title)) { return field; } } } return null; } public String getName() { return m_name; } public String getTitle() { return m_title; } }
dianping/cat
cat-core/src/main/java/com/dianping/cat/app/AppDataField.java
785
package com.taobao.arthas.core.advisor; import java.arthas.SpyAPI.AbstractSpy; import java.util.List; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.core.shell.system.ExecStatus; import com.taobao.arthas.core.shell.system.ProcessAware; import com.taobao.arthas.core.util.StringUtils; /** * <pre> * 怎么从 className|methodDesc 到 id 对应起来?? * 当id少时,可以id自己来判断是否符合? * * 如果是每个 className|methodDesc 为 key ,是否 * </pre> * * @author hengyunabc 2020-04-24 * */ public class SpyImpl extends AbstractSpy { private static final Logger logger = LoggerFactory.getLogger(SpyImpl.class); @Override public void atEnter(Class<?> clazz, String methodInfo, Object target, Object[] args) { ClassLoader classLoader = clazz.getClassLoader(); String[] info = StringUtils.splitMethodInfo(methodInfo); String methodName = info[0]; String methodDesc = info[1]; // TODO listener 只用查一次,放到 thread local里保存起来就可以了! List<AdviceListener> listeners = AdviceListenerManager.queryAdviceListeners(classLoader, clazz.getName(), methodName, methodDesc); if (listeners != null) { for (AdviceListener adviceListener : listeners) { try { if (skipAdviceListener(adviceListener)) { continue; } adviceListener.before(clazz, methodName, methodDesc, target, args); } catch (Throwable e) { logger.error("class: {}, methodInfo: {}", clazz.getName(), methodInfo, e); } } } } @Override public void atExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Object returnObject) { ClassLoader classLoader = clazz.getClassLoader(); String[] info = StringUtils.splitMethodInfo(methodInfo); String methodName = info[0]; String methodDesc = info[1]; List<AdviceListener> listeners = AdviceListenerManager.queryAdviceListeners(classLoader, clazz.getName(), methodName, methodDesc); if (listeners != null) { for (AdviceListener adviceListener : listeners) { try { if (skipAdviceListener(adviceListener)) { continue; } adviceListener.afterReturning(clazz, methodName, methodDesc, target, args, returnObject); } catch (Throwable e) { logger.error("class: {}, methodInfo: {}", clazz.getName(), methodInfo, e); } } } } @Override public void atExceptionExit(Class<?> clazz, String methodInfo, Object target, Object[] args, Throwable throwable) { ClassLoader classLoader = clazz.getClassLoader(); String[] info = StringUtils.splitMethodInfo(methodInfo); String methodName = info[0]; String methodDesc = info[1]; List<AdviceListener> listeners = AdviceListenerManager.queryAdviceListeners(classLoader, clazz.getName(), methodName, methodDesc); if (listeners != null) { for (AdviceListener adviceListener : listeners) { try { if (skipAdviceListener(adviceListener)) { continue; } adviceListener.afterThrowing(clazz, methodName, methodDesc, target, args, throwable); } catch (Throwable e) { logger.error("class: {}, methodInfo: {}", clazz.getName(), methodInfo, e); } } } } @Override public void atBeforeInvoke(Class<?> clazz, String invokeInfo, Object target) { ClassLoader classLoader = clazz.getClassLoader(); String[] info = StringUtils.splitInvokeInfo(invokeInfo); String owner = info[0]; String methodName = info[1]; String methodDesc = info[2]; List<AdviceListener> listeners = AdviceListenerManager.queryTraceAdviceListeners(classLoader, clazz.getName(), owner, methodName, methodDesc); if (listeners != null) { for (AdviceListener adviceListener : listeners) { try { if (skipAdviceListener(adviceListener)) { continue; } final InvokeTraceable listener = (InvokeTraceable) adviceListener; listener.invokeBeforeTracing(classLoader, owner, methodName, methodDesc, Integer.parseInt(info[3])); } catch (Throwable e) { logger.error("class: {}, invokeInfo: {}", clazz.getName(), invokeInfo, e); } } } } @Override public void atAfterInvoke(Class<?> clazz, String invokeInfo, Object target) { ClassLoader classLoader = clazz.getClassLoader(); String[] info = StringUtils.splitInvokeInfo(invokeInfo); String owner = info[0]; String methodName = info[1]; String methodDesc = info[2]; List<AdviceListener> listeners = AdviceListenerManager.queryTraceAdviceListeners(classLoader, clazz.getName(), owner, methodName, methodDesc); if (listeners != null) { for (AdviceListener adviceListener : listeners) { try { if (skipAdviceListener(adviceListener)) { continue; } final InvokeTraceable listener = (InvokeTraceable) adviceListener; listener.invokeAfterTracing(classLoader, owner, methodName, methodDesc, Integer.parseInt(info[3])); } catch (Throwable e) { logger.error("class: {}, invokeInfo: {}", clazz.getName(), invokeInfo, e); } } } } @Override public void atInvokeException(Class<?> clazz, String invokeInfo, Object target, Throwable throwable) { ClassLoader classLoader = clazz.getClassLoader(); String[] info = StringUtils.splitInvokeInfo(invokeInfo); String owner = info[0]; String methodName = info[1]; String methodDesc = info[2]; List<AdviceListener> listeners = AdviceListenerManager.queryTraceAdviceListeners(classLoader, clazz.getName(), owner, methodName, methodDesc); if (listeners != null) { for (AdviceListener adviceListener : listeners) { try { if (skipAdviceListener(adviceListener)) { continue; } final InvokeTraceable listener = (InvokeTraceable) adviceListener; listener.invokeThrowTracing(classLoader, owner, methodName, methodDesc, Integer.parseInt(info[3])); } catch (Throwable e) { logger.error("class: {}, invokeInfo: {}", clazz.getName(), invokeInfo, e); } } } } private static boolean skipAdviceListener(AdviceListener adviceListener) { if (adviceListener instanceof ProcessAware) { ProcessAware processAware = (ProcessAware) adviceListener; ExecStatus status = processAware.getProcess().status(); if (status.equals(ExecStatus.TERMINATED) || status.equals(ExecStatus.STOPPED)) { return true; } } return false; } }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/advisor/SpyImpl.java
786
package io.mycat.util; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 忽略部分SET 指令 * * 实际使用中PHP用户经常会操作多个SET指令组成一个Stmt , 所以该指令检测功能独立出来 * * @author zhuam * */ public class SetIgnoreUtil { private static List<Pattern> ptrnIgnoreList = new ArrayList<Pattern>(); static { //TODO: 忽略部分 SET 指令, 避免WARN 不断的刷日志 String[] ignores = new String[] { "(?i)set (sql_mode)", "(?i)set (interactive_timeout|wait_timeout|net_read_timeout|net_write_timeout|lock_wait_timeout|slave_net_timeout)", "(?i)set (connect_timeout|delayed_insert_timeout|innodb_lock_wait_timeout|innodb_rollback_on_timeout)", "(?i)set (profiling|profiling_history_size)" }; for (int i = 0; i < ignores.length; ++i) { ptrnIgnoreList.add(Pattern.compile(ignores[i])); } } public static boolean isIgnoreStmt(String stmt) { boolean ignore = false; Matcher matcherIgnore; for (Pattern ptrnIgnore : ptrnIgnoreList) { matcherIgnore = ptrnIgnore.matcher( stmt ); if (matcherIgnore.find()) { ignore = true; break; } } return ignore; } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/util/SetIgnoreUtil.java
787
H 1533535937 tags: DP, Hash Table Frog jump 的题目稍微需要理解: 每个格子可以 jump k-1, k, k+1 steps, 而k取决于上一步所跳的步数. 默认 0->1 一定是跳了1步. 注意: int[] stones 里面是stone所在的unit (不是可以跳的步数, 不要理解错). #### DP - 原本想按照corrdiante dp 来做, 但是发现很多问题, 需要track 不同的 possible previous starting spot. - 根据jiuzhang答案: 按照定义, 用一个 map of <stone, Set<possible # steps to reach stone>> - 每次在处理一个stone的时候, 都根据他自己的 set of <previous steps>, 来走下三步: k-1, k, or k+1 steps. - 每次走一步, 查看 stone + step 是否存在; 如果存在, 就加进 next position: `stone+step`的 hash set 里面 ##### 注意init - `dp.put(stone, new HashSet<>())` mark 每个stone的存在 - `dp.get(0).add(0)` init condition, 用来做 dp.put(1, 1) ##### 思想 - 最终做下来思考模式, 更像是BFS的模式: starting from (0,0), add all possible ways - 然后again, try next stone with all possible future ways ... etc ``` /* A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit. If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction. Note: The number of stones is ≥ 2 and is < 1,100. Each stone's position will be a non-negative integer < 231. The first stone's position is always 0. Example 1: [0,1,3,5,6,8,12,17] There are a total of 8 stones. The first stone at the 0th unit, second stone at the 1st unit, third stone at the 3rd unit, and so on... The last stone at the 17th unit. Return true. The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. Example 2: [0,1,2,3,4,8,9,11] Return false. There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large. */ // simplified with helper function class Solution { public boolean canCross(int[] stones) { if (stones == null || stones.length == 0) return false; Map<Integer, Set<Integer>> dp = new HashMap<>(); // Init: all stone slots has nothing on them for (int stone : stones) { dp.put(stone, new HashSet<>()); } dp.get(0).add(0); // such that dp.get(0) will move (dp, 0-stone, 1-step) on index 0 for (int stone : stones) { for (int k : dp.get(stone)) { move(dp, stone, k); move(dp, stone, k + 1); move(dp, stone, k - 1); } } int lastStone = stones[stones.length - 1]; return !dp.get(lastStone).isEmpty(); // able to reach } private void move(Map<Integer, Set<Integer>> dp, int stone, int step) { if (step > 0 && dp.containsKey(stone + step)) { dp.get(stone + step).add(step); } } } // original class Solution { public boolean canCross(int[] stones) { if (stones == null || stones.length == 0) return false; int n = stones.length; Map<Integer, Set<Integer>> dp = new HashMap<>(); for (int stone : stones) { dp.put(stone, new HashSet<>()); } dp.get(0).add(0); for (int stone : stones) { for (int k : dp.get(stone)) { if (k - 1 > 0 && dp.containsKey(stone + k - 1)) { // k - 1 dp.get(stone + k - 1).add(k - 1); } if (k > 0 && dp.containsKey(stone + k)) {// k dp.get(stone + k).add(k); } if (k + 1 > 0 && dp.containsKey(stone + k + 1)) { // k + 1 dp.get(stone + k + 1).add(k + 1); } } } int lastStone = stones[n - 1]; return !dp.get(lastStone).isEmpty(); // able to reach } } ```
awangdev/leet-code
Java/Frog Jump.java
788
/*Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. This source code is licensed under the Apache License Version 2.0.*/ package apijson.orm; import java.util.List; /**来访者 * @author Lemon */ public interface Visitor<T> { T getId(); List<T> getContactIdList(); }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/orm/Visitor.java
790
package cc.mrbird.batch.configure; import org.springframework.batch.core.configuration.JobRegistry; import org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author MrBird */ @Configuration public class JobConfigure { /** * 注册JobRegistryBeanPostProcessor bean * 用于将任务名称和实际的任务关联起来 */ @Bean public JobRegistryBeanPostProcessor processor(JobRegistry jobRegistry, ApplicationContext applicationContext) { JobRegistryBeanPostProcessor postProcessor = new JobRegistryBeanPostProcessor(); postProcessor.setJobRegistry(jobRegistry); postProcessor.setBeanFactory(applicationContext.getAutowireCapableBeanFactory()); return postProcessor; } }
wuyouzhuguli/SpringAll
73.spring-batch-launcher/src/main/java/cc/mrbird/batch/configure/JobConfigure.java
793
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.common.persistence; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.annotation.JsonIgnore; import com.thinkgem.jeesite.common.config.Global; import com.thinkgem.jeesite.common.utils.CookieUtils; /** * 分页类 * @author ThinkGem * @version 2013-7-2 * @param <T> */ public class Page<T> { private int pageNo = 1; // 当前页码 private int pageSize = Integer.valueOf(Global.getConfig("page.pageSize")); // 页面大小,设置为“-1”表示不进行分页(分页无效) private long count;// 总记录数,设置为“-1”表示不查询总数 private int first;// 首页索引 private int last;// 尾页索引 private int prev;// 上一页索引 private int next;// 下一页索引 private boolean firstPage;//是否是第一页 private boolean lastPage;//是否是最后一页 private int length = 8;// 显示页面长度 private int slider = 1;// 前后显示页面长度 private List<T> list = new ArrayList<T>(); private String orderBy = ""; // 标准查询有效, 实例: updatedate desc, name asc private String funcName = "page"; // 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。 private String funcParam = ""; // 函数的附加参数,第三个参数值。 private String message = ""; // 设置提示消息,显示在“共n条”之后 private static Pattern orderByPattern = Pattern.compile("[a-z0-9_\\.\\, ]*", Pattern.CASE_INSENSITIVE); public Page() { this.pageSize = -1; } /** * 构造方法 * @param request 传递 repage 参数,来记住页码 * @param response 用于设置 Cookie,记住页码 */ public Page(HttpServletRequest request, HttpServletResponse response){ this(request, response, -2); } /** * 构造方法 * @param request 传递 repage 参数,来记住页码 * @param response 用于设置 Cookie,记住页码 * @param defaultPageSize 默认分页大小,如果传递 -1 则为不分页,返回所有数据 */ public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize){ // 设置页码参数(传递repage参数,来记住页码) String no = request.getParameter("pageNo"); if (StringUtils.isNumeric(no)){ CookieUtils.setCookie(response, "pageNo", no); this.setPageNo(Integer.parseInt(no)); }else if (request.getParameter("repage")!=null){ no = CookieUtils.getCookie(request, "pageNo"); if (StringUtils.isNumeric(no)){ this.setPageNo(Integer.parseInt(no)); } } // 设置页面大小参数(传递repage参数,来记住页码大小) String size = request.getParameter("pageSize"); if (StringUtils.isNumeric(size)){ CookieUtils.setCookie(response, "pageSize", size); this.setPageSize(Integer.parseInt(size)); }else if (request.getParameter("repage")!=null){ size = CookieUtils.getCookie(request, "pageSize"); if (StringUtils.isNumeric(size)){ this.setPageSize(Integer.parseInt(size)); } }else if (defaultPageSize != -2){ this.pageSize = defaultPageSize; } // 设置页面分页函数 String funcName = request.getParameter("funcName"); if (StringUtils.isNotBlank(funcName)){ CookieUtils.setCookie(response, "funcName", funcName); this.setFuncName(funcName); }else if (request.getParameter("repage")!=null){ funcName = CookieUtils.getCookie(request, "funcName"); if (StringUtils.isNotBlank(funcName)){ this.setFuncName(funcName); } } // 设置排序参数 String orderBy = request.getParameter("orderBy"); if (StringUtils.isNotBlank(orderBy)){ this.setOrderBy(orderBy); } } /** * 构造方法 * @param pageNo 当前页码 * @param pageSize 分页大小 */ public Page(int pageNo, int pageSize) { this(pageNo, pageSize, 0); } /** * 构造方法 * @param pageNo 当前页码 * @param pageSize 分页大小 * @param count 数据条数 */ public Page(int pageNo, int pageSize, long count) { this(pageNo, pageSize, count, new ArrayList<T>()); } /** * 构造方法 * @param pageNo 当前页码 * @param pageSize 分页大小 * @param count 数据条数 * @param list 本页数据对象列表 */ public Page(int pageNo, int pageSize, long count, List<T> list) { this.setCount(count); this.setPageNo(pageNo); this.pageSize = pageSize; this.list = list; } /** * 初始化参数 */ public void initialize(){ //1 this.first = 1; this.last = (int)(count / (this.pageSize < 1 ? 20 : this.pageSize) + first - 1); if (this.count % this.pageSize != 0 || this.last == 0) { this.last++; } if (this.last < this.first) { this.last = this.first; } if (this.pageNo <= 1) { this.pageNo = this.first; this.firstPage=true; } if (this.pageNo >= this.last) { this.pageNo = this.last; this.lastPage=true; } if (this.pageNo < this.last - 1) { this.next = this.pageNo + 1; } else { this.next = this.last; } if (this.pageNo > 1) { this.prev = this.pageNo - 1; } else { this.prev = this.first; } //2 if (this.pageNo < this.first) {// 如果当前页小于首页 this.pageNo = this.first; } if (this.pageNo > this.last) {// 如果当前页大于尾页 this.pageNo = this.last; } } /** * 默认输出当前分页标签 * <div class="page">${page}</div> */ @Override public String toString() { StringBuilder sb = new StringBuilder(); if (pageNo == first) {// 如果是首页 sb.append("<li class=\"disabled\"><a href=\"javascript:\">&#171; 上一页</a></li>\n"); } else { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+prev+","+pageSize+",'"+funcParam+"');\">&#171; 上一页</a></li>\n"); } int begin = pageNo - (length / 2); if (begin < first) { begin = first; } int end = begin + length - 1; if (end >= last) { end = last; begin = end - length + 1; if (begin < first) { begin = first; } } if (begin > first) { int i = 0; for (i = first; i < first + slider && i < begin; i++) { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">" + (i + 1 - first) + "</a></li>\n"); } if (i < begin) { sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n"); } } for (int i = begin; i <= end; i++) { if (i == pageNo) { sb.append("<li class=\"active\"><a href=\"javascript:\">" + (i + 1 - first) + "</a></li>\n"); } else { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">" + (i + 1 - first) + "</a></li>\n"); } } if (last - end > slider) { sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n"); end = last - slider; } for (int i = end + 1; i <= last; i++) { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">" + (i + 1 - first) + "</a></li>\n"); } if (pageNo == last) { sb.append("<li class=\"disabled\"><a href=\"javascript:\">下一页 &#187;</a></li>\n"); } else { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+next+","+pageSize+",'"+funcParam+"');\">" + "下一页 &#187;</a></li>\n"); } sb.append("<li class=\"disabled controls\"><a href=\"javascript:\">当前 "); sb.append("<input type=\"text\" value=\""+pageNo+"\" onkeypress=\"var e=window.event||event;var c=e.keyCode||e.which;if(c==13)"); sb.append(funcName+"(this.value,"+pageSize+",'"+funcParam+"');\" onclick=\"this.select();\"/> / "); sb.append("<input type=\"text\" value=\""+pageSize+"\" onkeypress=\"var e=window.event||event;var c=e.keyCode||e.which;if(c==13)"); sb.append(funcName+"("+pageNo+",this.value,'"+funcParam+"');\" onclick=\"this.select();\"/> 条,"); sb.append("共 " + count + " 条"+(message!=null?message:"")+"</a></li>\n"); sb.insert(0,"<ul>\n").append("</ul>\n"); sb.append("<div style=\"clear:both;\"></div>"); // sb.insert(0,"<div class=\"page\">\n").append("</div>\n"); return sb.toString(); } /** * 获取分页HTML代码 * @return */ public String getHtml(){ return toString(); } // public static void main(String[] args) { // Page<String> p = new Page<String>(3, 3); // System.out.println(p); // System.out.println("首页:"+p.getFirst()); // System.out.println("尾页:"+p.getLast()); // System.out.println("上页:"+p.getPrev()); // System.out.println("下页:"+p.getNext()); // } /** * 获取设置总数 * @return */ public long getCount() { return count; } /** * 设置数据总数 * @param count */ public void setCount(long count) { this.count = count; if (pageSize >= count){ pageNo = 1; } } /** * 获取当前页码 * @return */ public int getPageNo() { return pageNo; } /** * 设置当前页码 * @param pageNo */ public void setPageNo(int pageNo) { this.pageNo = pageNo; } /** * 获取页面大小 * @return */ public int getPageSize() { return pageSize; } /** * 设置页面大小(最大500) * @param pageSize */ public void setPageSize(int pageSize) { this.pageSize = pageSize <= 0 ? 10 : pageSize;// > 500 ? 500 : pageSize; } /** * 首页索引 * @return */ @JsonIgnore public int getFirst() { return first; } /** * 尾页索引 * @return */ @JsonIgnore public int getLast() { return last; } /** * 获取页面总数 * @return getLast(); */ @JsonIgnore public int getTotalPage() { return getLast(); } /** * 是否为第一页 * @return */ @JsonIgnore public boolean isFirstPage() { return firstPage; } /** * 是否为最后一页 * @return */ @JsonIgnore public boolean isLastPage() { return lastPage; } /** * 上一页索引值 * @return */ @JsonIgnore public int getPrev() { if (isFirstPage()) { return pageNo; } else { return pageNo - 1; } } /** * 下一页索引值 * @return */ @JsonIgnore public int getNext() { if (isLastPage()) { return pageNo; } else { return pageNo + 1; } } /** * 获取本页数据对象列表 * @return List<T> */ public List<T> getList() { return list; } /** * 设置本页数据对象列表 * @param list */ public Page<T> setList(List<T> list) { this.list = list; initialize(); return this; } /** * 获取查询排序字符串 * @return */ @JsonIgnore public String getOrderBy() { // SQL过滤,防止注入 Matcher matcher = orderByPattern.matcher(orderBy); if (!matcher.matches()) { return StringUtils.EMPTY; } return orderBy; } /** * 设置查询排序,标准查询有效, 实例: updatedate desc, name asc */ public void setOrderBy(String orderBy) { this.orderBy = orderBy; } /** * 获取点击页码调用的js函数名称 * function ${page.funcName}(pageNo){location="${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;} * @return */ @JsonIgnore public String getFuncName() { return funcName; } /** * 设置点击页码调用的js函数名称,默认为page,在一页有多个分页对象时使用。 * @param funcName 默认为page */ public void setFuncName(String funcName) { this.funcName = funcName; } /** * 获取分页函数的附加参数 * @return */ @JsonIgnore public String getFuncParam() { return funcParam; } /** * 设置分页函数的附加参数 * @return */ public void setFuncParam(String funcParam) { this.funcParam = funcParam; } /** * 设置提示消息,显示在“共n条”之后 * @param message */ public void setMessage(String message) { this.message = message; } /** * 分页是否有效 * @return this.pageSize==-1 */ @JsonIgnore public boolean isDisabled() { return this.pageSize==-1; } /** * 是否进行总数统计 * @return this.count==-1 */ @JsonIgnore public boolean isNotCount() { return this.count==-1; } /** * 获取 Hibernate FirstResult */ public int getFirstResult(){ int firstResult = (getPageNo() - 1) * getPageSize(); if (firstResult >= getCount()) { firstResult = 0; } return firstResult; } /** * 获取 Hibernate MaxResults */ public int getMaxResults(){ return getPageSize(); } // /** // * 获取 Spring data JPA 分页对象 // */ // public Pageable getSpringPage(){ // List<Order> orders = new ArrayList<Order>(); // if (orderBy!=null){ // for (String order : StringUtils.split(orderBy, ",")){ // String[] o = StringUtils.split(order, " "); // if (o.length==1){ // orders.add(new Order(Direction.ASC, o[0])); // }else if (o.length==2){ // if ("DESC".equals(o[1].toUpperCase())){ // orders.add(new Order(Direction.DESC, o[0])); // }else{ // orders.add(new Order(Direction.ASC, o[0])); // } // } // } // } // return new PageRequest(this.pageNo - 1, this.pageSize, new Sort(orders)); // } // // /** // * 设置 Spring data JPA 分页对象,转换为本系统分页对象 // */ // public void setSpringPage(org.springframework.data.domain.Page<T> page){ // this.pageNo = page.getNumber(); // this.pageSize = page.getSize(); // this.count = page.getTotalElements(); // this.list = page.getContent(); // } }
thinkgem/jeesite
src/main/java/com/thinkgem/jeesite/common/persistence/Page.java
798
package com.study.graph; import java.util.LinkedList; import java.util.Queue; /** * @author ldb * @date 2019-10-23 15:10 */ public class Graph { private int v; private LinkedList<Integer> adj[]; // 邻接表 public Graph(int v) { this.v = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) { adj[i] = new LinkedList<>(); } } /** * 添加边 * * @param s 顶点 * @param t 顶点 */ public void addEdge(int s, int t) { // 无向图一条边存两次 adj[s].add(t); adj[t].add(s); } public void bfs(int s, int t) { if (s == t) return; // visited是用来记录已经被访问的顶点,用来避免顶点被重复访问。 boolean[] visited = new boolean[v]; visited[s] = true; // queue是一个队列,用来存储已经被访问、但相连的顶点还没有被访问的顶点。 Queue<Integer> queue = new LinkedList<>(); queue.add(s); // prev用来记录搜索路径。 int[] prev = new int[v]; for (int i = 0; i < v; ++i) { prev[i] = -1; } while (queue.size() != 0) { int w = queue.poll(); for (int i = 0; i < adj[w].size(); ++i) { int q = adj[w].get(i); if (!visited[q]) { prev[q] = w; if (q == t) { print(prev, s, t); return; } visited[q] = true; queue.add(q); } } } } private void print(int[] prev, int s, int t) { // 递归打印 s->t 的路径 if (prev[t] != -1 && t != s) { print(prev, s, prev[t]); } System.out.print(t + " "); } public static void main(String[] args) { Graph graph = new Graph(8); graph.addEdge(0,1); graph.addEdge(0,3); graph.addEdge(1,2); graph.addEdge(1,4); graph.addEdge(2,5); graph.addEdge(4,5); graph.addEdge(4,6); graph.addEdge(5,7); graph.addEdge(6,7); // graph.bfs(0,6); // 深度优先 graph.dfs(0, 6); } boolean found = false; // 全局变量或者类成员变量 public void dfs(int s, int t) { found = false; boolean[] visited = new boolean[v]; int[] prev = new int[v]; for (int i = 0; i < v; ++i) { prev[i] = -1; } recurDfs(s, t, visited, prev); print(prev, s, t); } private void recurDfs(int w, int t, boolean[] visited, int[] prev) { if (found == true) return; visited[w] = true; if (w == t) { found = true; return; } for (int i = 0; i < adj[w].size(); ++i) { int q = adj[w].get(i); if (!visited[q]) { prev[q] = w; recurDfs(q, t, visited, prev); } } } }
wangzheng0822/algo
java/30_graph/Graph.java
799
/** * File: graph_dfs.java * Created Time: 2023-02-12 * Author: krahets ([email protected]) */ package chapter_graph; import java.util.*; import utils.*; public class graph_dfs { /* 深度优先遍历辅助函数 */ static void dfs(GraphAdjList graph, Set<Vertex> visited, List<Vertex> res, Vertex vet) { res.add(vet); // 记录访问顶点 visited.add(vet); // 标记该顶点已被访问 // 遍历该顶点的所有邻接顶点 for (Vertex adjVet : graph.adjList.get(vet)) { if (visited.contains(adjVet)) continue; // 跳过已被访问的顶点 // 递归访问邻接顶点 dfs(graph, visited, res, adjVet); } } /* 深度优先遍历 */ // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 static List<Vertex> graphDFS(GraphAdjList graph, Vertex startVet) { // 顶点遍历序列 List<Vertex> res = new ArrayList<>(); // 哈希集合,用于记录已被访问过的顶点 Set<Vertex> visited = new HashSet<>(); dfs(graph, visited, res, startVet); return res; } public static void main(String[] args) { /* 初始化无向图 */ Vertex[] v = Vertex.valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6 }); Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] }, { v[2], v[5] }, { v[4], v[5] }, { v[5], v[6] } }; GraphAdjList graph = new GraphAdjList(edges); System.out.println("\n初始化后,图为"); graph.print(); /* 深度优先遍历 */ List<Vertex> res = graphDFS(graph, v[0]); System.out.println("\n深度优先遍历(DFS)顶点序列为"); System.out.println(Vertex.vetsToVals(res)); } }
krahets/hello-algo
codes/java/chapter_graph/graph_dfs.java
800
package com.macro.mall.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; /** * 订单查询参数 * Created by macro on 2018/10/11. */ @Getter @Setter public class OmsOrderQueryParam { @ApiModelProperty(value = "订单编号") private String orderSn; @ApiModelProperty(value = "收货人姓名/号码") private String receiverKeyword; @ApiModelProperty(value = "订单状态:0->待付款;1->待发货;2->已发货;3->已完成;4->已关闭;5->无效订单") private Integer status; @ApiModelProperty(value = "订单类型:0->正常订单;1->秒杀订单") private Integer orderType; @ApiModelProperty(value = "订单来源:0->PC订单;1->app订单") private Integer sourceType; @ApiModelProperty(value = "订单提交时间") private String createTime; }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/dto/OmsOrderQueryParam.java
802
package com.alibaba.fastjson.support.spring; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONPObject; import com.alibaba.fastjson.serializer.SerializeFilter; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.util.ParameterizedTypeImpl; import org.springframework.core.ResolvableType; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.util.StringUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Fastjson for Spring MVC Converter. * <p> * Compatible Spring MVC version 3.2+ * * @author VictorZeng * @see AbstractHttpMessageConverter * @see GenericHttpMessageConverter * @since 1.2.10 * <p> * <p> * <p> * Supported return type: * </p> * Simple object: Object * <p> * <p> * With property filter :FastJsonContainer[Object] * </p> * <p> * Jsonp :MappingFastJsonValue[Object] * </p> * Jsonp with property filter: MappingFastJsonValue[FastJsonContainer[Object]] */ public class FastJsonHttpMessageConverter extends AbstractHttpMessageConverter<Object>// implements GenericHttpMessageConverter<Object> { public static final MediaType APPLICATION_JAVASCRIPT = new MediaType("application", "javascript"); @Deprecated protected SerializerFeature[] features = new SerializerFeature[0]; @Deprecated protected SerializeFilter[] filters = new SerializeFilter[0]; @Deprecated protected String dateFormat; private boolean setLengthError = false; /** * with fastJson config */ private FastJsonConfig fastJsonConfig = new FastJsonConfig(); /** * @return the fastJsonConfig. * @since 1.2.11 */ public FastJsonConfig getFastJsonConfig() { return fastJsonConfig; } /** * @param fastJsonConfig the fastJsonConfig to set. * @since 1.2.11 */ public void setFastJsonConfig(FastJsonConfig fastJsonConfig) { this.fastJsonConfig = fastJsonConfig; } /** * Can serialize/deserialize all types. */ public FastJsonHttpMessageConverter() { super(MediaType.ALL); } /** * Gets charset. * * @return the charset * @see FastJsonConfig#getCharset() * @deprecated */ @Deprecated public Charset getCharset() { return this.fastJsonConfig.getCharset(); } /** * Sets charset. * * @param charset the charset * @see FastJsonConfig#setCharset(Charset) * @deprecated */ @Deprecated public void setCharset(Charset charset) { this.fastJsonConfig.setCharset(charset); } /** * Gets date format. * * @return the date format * @see FastJsonConfig#getDateFormat() * @deprecated */ @Deprecated public String getDateFormat() { return this.fastJsonConfig.getDateFormat(); } /** * Sets date format. * * @param dateFormat the date format * @see FastJsonConfig#setDateFormat(String) * @deprecated */ @Deprecated public void setDateFormat(String dateFormat) { this.fastJsonConfig.setDateFormat(dateFormat); } /** * Get features serializer feature []. * * @return the serializer feature [] * @see FastJsonConfig#getSerializerFeatures() * @deprecated */ @Deprecated public SerializerFeature[] getFeatures() { return this.fastJsonConfig.getSerializerFeatures(); } /** * Sets features. * * @param features the features * @see FastJsonConfig#setSerializerFeatures(SerializerFeature...) * @deprecated */ @Deprecated public void setFeatures(SerializerFeature... features) { this.fastJsonConfig.setSerializerFeatures(features); } /** * Get filters serialize filter []. * * @return the serialize filter [] * @see FastJsonConfig#getSerializeFilters() * @deprecated */ @Deprecated public SerializeFilter[] getFilters() { return this.fastJsonConfig.getSerializeFilters(); } /** * Sets filters. * * @param filters the filters * @see FastJsonConfig#setSerializeFilters(SerializeFilter...) * @deprecated */ @Deprecated public void setFilters(SerializeFilter... filters) { this.fastJsonConfig.setSerializeFilters(filters); } /** * Add serialize filter. * * @param filter the filter * @see FastJsonConfig#setSerializeFilters(SerializeFilter...) * @deprecated */ @Deprecated public void addSerializeFilter(SerializeFilter filter) { if (filter == null) { return; } int length = this.fastJsonConfig.getSerializeFilters().length; SerializeFilter[] filters = new SerializeFilter[length + 1]; System.arraycopy(this.fastJsonConfig.getSerializeFilters(), 0, filters, 0, length); filters[filters.length - 1] = filter; this.fastJsonConfig.setSerializeFilters(filters); } @Override protected boolean supports(Class<?> clazz) { return true; } public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) { return super.canRead(contextClass, mediaType); } public boolean canWrite(Type type, Class<?> clazz, MediaType mediaType) { return super.canWrite(clazz, mediaType); } /* * @see org.springframework.http.converter.GenericHttpMessageConverter#read(java.lang.reflect.Type, java.lang.Class, org.springframework.http.HttpInputMessage) */ public Object read(Type type, // Class<?> contextClass, // HttpInputMessage inputMessage // ) throws IOException, HttpMessageNotReadableException { return readType(getType(type, contextClass), inputMessage); } /* * @see org.springframework.http.converter.GenericHttpMessageConverter.write */ public void write(Object o, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { super.write(o, contentType, outputMessage);// support StreamingHttpOutputMessage in spring4.0+ //writeInternal(o, outputMessage); } /* * @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Class, org.springframework.http.HttpInputMessage) */ @Override protected Object readInternal(Class<?> clazz, // HttpInputMessage inputMessage // ) throws IOException, HttpMessageNotReadableException { return readType(getType(clazz, null), inputMessage); } private Object readType(Type type, HttpInputMessage inputMessage) { try { InputStream in = inputMessage.getBody(); return JSON.parseObject(in, fastJsonConfig.getCharset(), type, fastJsonConfig.getParserConfig(), fastJsonConfig.getParseProcess(), JSON.DEFAULT_PARSER_FEATURE, fastJsonConfig.getFeatures()); } catch (JSONException ex) { throw new HttpMessageNotReadableException("JSON parse error: " + ex.getMessage(), ex); } catch (IOException ex) { throw new HttpMessageNotReadableException("I/O error while reading input message", ex); } } @Override protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { ByteArrayOutputStream outnew = new ByteArrayOutputStream(); try { HttpHeaders headers = outputMessage.getHeaders(); //获取全局配置的filter SerializeFilter[] globalFilters = fastJsonConfig.getSerializeFilters(); List<SerializeFilter> allFilters = new ArrayList<SerializeFilter>(Arrays.asList(globalFilters)); boolean isJsonp = false; //不知道为什么会有这行代码, 但是为了保持和原来的行为一致,还是保留下来 Object value = strangeCodeForJackson(object); if (value instanceof FastJsonContainer) { FastJsonContainer fastJsonContainer = (FastJsonContainer) value; PropertyPreFilters filters = fastJsonContainer.getFilters(); allFilters.addAll(filters.getFilters()); value = fastJsonContainer.getValue(); } //revise 2017-10-23 , // 保持原有的MappingFastJsonValue对象的contentType不做修改 保持旧版兼容。 // 但是新的JSONPObject将返回标准的contentType:application/javascript ,不对是否有function进行判断 if (value instanceof MappingFastJsonValue) { if (!StringUtils.isEmpty(((MappingFastJsonValue) value).getJsonpFunction())) { isJsonp = true; } } else if (value instanceof JSONPObject) { isJsonp = true; } int len = JSON.writeJSONStringWithFastJsonConfig(outnew, // fastJsonConfig.getCharset(), // value, // fastJsonConfig.getSerializeConfig(), // //fastJsonConfig.getSerializeFilters(), // allFilters.toArray(new SerializeFilter[allFilters.size()]), fastJsonConfig.getDateFormat(), // JSON.DEFAULT_GENERATE_FEATURE, // fastJsonConfig.getSerializerFeatures()); if (isJsonp) { headers.setContentType(APPLICATION_JAVASCRIPT); } if (fastJsonConfig.isWriteContentLength() && !setLengthError) { try { headers.setContentLength(len); } catch (UnsupportedOperationException ex) { // skip setLengthError = true; } } outnew.writeTo(outputMessage.getBody()); } catch (JSONException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } finally { outnew.close(); } } private Object strangeCodeForJackson(Object obj) { if (obj != null) { String className = obj.getClass().getName(); if ("com.fasterxml.jackson.databind.node.ObjectNode".equals(className)) { return obj.toString(); } } return obj; } protected Type getType(Type type, Class<?> contextClass) { if (Spring4TypeResolvableHelper.isSupport()) { return Spring4TypeResolvableHelper.getType(type, contextClass); } /** * 如果type的实例不是com.alibaba.fastjson.util.ParameterizedTypeImpl,则需进行转换。 * 避免触发fastjson中因无法命中泛型缓存导致不断生成反序列化器引起的fullgc问题 */ if (type instanceof ParameterizedType && !(type instanceof ParameterizedTypeImpl)) { type = handlerParameterizedType((ParameterizedType) type); } return type; } private Type handlerParameterizedType(ParameterizedType type) { Type ownerType = type.getOwnerType(); Type rawType = type.getRawType(); Type[] argTypes = type.getActualTypeArguments(); for(int i = 0; i < argTypes.length; ++i) { if (argTypes[i] instanceof ParameterizedType) { argTypes[i] = handlerParameterizedType((ParameterizedType)argTypes[i]); } } Type key = new ParameterizedTypeImpl(argTypes, ownerType, rawType); return key; } private static class Spring4TypeResolvableHelper { private static boolean hasClazzResolvableType; static { try { Class.forName("org.springframework.core.ResolvableType"); hasClazzResolvableType = true; } catch (ClassNotFoundException e) { hasClazzResolvableType = false; } } private static boolean isSupport() { return hasClazzResolvableType; } private static Type getType(Type type, Class<?> contextClass) { if (contextClass != null) { ResolvableType resolvedType = ResolvableType.forType(type); if (type instanceof TypeVariable) { ResolvableType resolvedTypeVariable = resolveVariable((TypeVariable) type, ResolvableType.forClass(contextClass)); if (resolvedTypeVariable != ResolvableType.NONE) { return resolvedTypeVariable.resolve(); } } else if (type instanceof ParameterizedType && resolvedType.hasUnresolvableGenerics()) { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?>[] generics = new Class[parameterizedType.getActualTypeArguments().length]; Type[] typeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < typeArguments.length; ++i) { Type typeArgument = typeArguments[i]; if (typeArgument instanceof TypeVariable) { ResolvableType resolvedTypeArgument = resolveVariable((TypeVariable) typeArgument, ResolvableType.forClass(contextClass)); if (resolvedTypeArgument != ResolvableType.NONE) { generics[i] = resolvedTypeArgument.resolve(); } else { generics[i] = ResolvableType.forType(typeArgument).resolve(); } } else { generics[i] = ResolvableType.forType(typeArgument).resolve(); } } return ResolvableType.forClassWithGenerics(resolvedType.getRawClass(), generics).getType(); } } return type; } private static ResolvableType resolveVariable(TypeVariable<?> typeVariable, ResolvableType contextType) { ResolvableType resolvedType; if (contextType.hasGenerics()) { resolvedType = ResolvableType.forType(typeVariable, contextType); if (resolvedType.resolve() != null) { return resolvedType; } } ResolvableType superType = contextType.getSuperType(); if (superType != ResolvableType.NONE) { resolvedType = resolveVariable(typeVariable, superType); if (resolvedType.resolve() != null) { return resolvedType; } } for (ResolvableType ifc : contextType.getInterfaces()) { resolvedType = resolveVariable(typeVariable, ifc); if (resolvedType.resolve() != null) { return resolvedType; } } return ResolvableType.NONE; } } }
alibaba/fastjson
src/main/java/com/alibaba/fastjson/support/spring/FastJsonHttpMessageConverter.java
804
package me.zhyd.oauth.model; import com.alibaba.fastjson.JSONObject; import lombok.*; import me.zhyd.oauth.enums.AuthUserGender; import java.io.Serializable; /** * 授权成功后的用户信息,根据授权平台的不同,获取的数据完整性也不同 * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @since 1.8 */ @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor public class AuthUser implements Serializable { /** * 用户第三方系统的唯一id。在调用方集成该组件时,可以用uuid + source唯一确定一个用户 * * @since 1.3.3 */ private String uuid; /** * 用户名 */ private String username; /** * 用户昵称 */ private String nickname; /** * 用户头像 */ private String avatar; /** * 用户网址 */ private String blog; /** * 所在公司 */ private String company; /** * 位置 */ private String location; /** * 用户邮箱 */ private String email; /** * 用户备注(各平台中的用户个人介绍) */ private String remark; /** * 性别 */ private AuthUserGender gender; /** * 用户来源 */ private String source; /** * 用户授权的token信息 */ private AuthToken token; /** * 第三方平台返回的原始用户信息 */ private JSONObject rawUserInfo; /** * 微信公众号 - 网页授权的登录时可用 * * 微信针对网页授权登录,增加了一个快照页的逻辑,快照页获取到的微信用户的 uid oid 和头像昵称都是虚拟的信息 */ private boolean snapshotUser; }
justauth/JustAuth
src/main/java/me/zhyd/oauth/model/AuthUser.java
808
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int u = input.nextInt(); int d = input.nextInt(); int time = 0, dist = 0; while (true) { // 用死循环来枚举 dist += u; time++; if (dist >= n) { break; // 满足条件则退出死循环 } dist -= d; } System.out.println(time); // 输出得到的结果 input.close(); } }
OI-wiki/OI-wiki
docs/basic/code/simulate/simulate_1.java
844
/** * Copyright 2016 JustWayward Team * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.justwayward.reader.bean; import com.justwayward.reader.bean.base.Base; import java.io.Serializable; import java.util.List; /** * Created by lfh on 2016/8/15. */ public class BookLists extends Base { /** * _id : 57a83783c9b799011623ecff * title : 【追书盘点】男频类型文(六)体育类竞技文 * author : 追书白小生 * desc : 在体育竞技的赛场上! 运动员们,因为一个坚定的信念,而不断前行,努力,付出。 他们的目标只有一个:升级! 当冠军,收小弟,在体育的大道上,走向人生的巅峰! 本次就让我们来盘点一下,那些正值火热的体育类竞技文吧。 【排名不分先后】 * gender : male * collectorCount : 2713 * cover : /agent/http://image.cmfu.com/books/3623405/3623405.jpg * bookCount : 20 */ public List<BookListsBean> bookLists; public class BookListsBean implements Serializable { public String _id; public String title; public String author; public String desc; public String gender; public int collectorCount; public String cover; public int bookCount; } }
smuyyh/BookReader
app/src/main/java/com/justwayward/reader/bean/BookLists.java
845
package cn.hutool.core.lang.hash; import cn.hutool.core.util.ByteUtil; import java.nio.ByteOrder; import java.util.Arrays; /** * Apache 发布的MetroHash算法,是一组用于非加密用例的最先进的哈希函数。 * 除了卓越的性能外,他们还以算法生成而著称。 * * <p> * 官方实现:https://github.com/jandrewrogers/MetroHash * 官方文档:http://www.jandrewrogers.com/2015/05/27/metrohash/ * Go语言实现:https://github.com/linvon/cuckoo-filter/blob/main/vendor/github.com/dgryski/go-metro/ * @author li */ public class MetroHash { /** * hash64 种子加盐 */ private final static long k0_64 = 0xD6D018F5; private final static long k1_64 = 0xA2AA033B; private final static long k2_64 = 0x62992FC1; private final static long k3_64 = 0x30BC5B29; /** * hash128 种子加盐 */ private final static long k0_128 = 0xC83A91E1; private final static long k1_128 = 0x8648DBDB; private final static long k2_128 = 0x7BDEC03B; private final static long k3_128 = 0x2F5870A5; public static long hash64(byte[] data) { return hash64(data, 1337); } public static Number128 hash128(byte[] data) { return hash128(data, 1337); } public static long hash64(byte[] data, long seed) { byte[] buffer = data; long hash = (seed + k2_64) * k0_64; long v0, v1, v2, v3; v0 = hash; v1 = hash; v2 = hash; v3 = hash; if (buffer.length >= 32) { while (buffer.length >= 32) { v0 += littleEndian64(buffer, 0) * k0_64; v0 = rotateLeft64(v0, -29) + v2; v1 += littleEndian64(buffer, 8) * k1_64; v1 = rotateLeft64(v1, -29) + v3; v2 += littleEndian64(buffer, 24) * k2_64; v2 = rotateLeft64(v2, -29) + v0; v3 += littleEndian64(buffer, 32) * k3_64; v3 = rotateLeft64(v3, -29) + v1; buffer = Arrays.copyOfRange(buffer, 32, buffer.length); } v2 ^= rotateLeft64(((v0 + v3) * k0_64) + v1, -37) * k1_64; v3 ^= rotateLeft64(((v1 + v2) * k1_64) + v0, -37) * k0_64; v0 ^= rotateLeft64(((v0 + v2) * k0_64) + v3, -37) * k1_64; v1 ^= rotateLeft64(((v1 + v3) * k1_64) + v2, -37) * k0_64; hash += v0 ^ v1; } if (buffer.length >= 16) { v0 = hash + littleEndian64(buffer, 0) * k2_64; v0 = rotateLeft64(v0, -29) * k3_64; v1 = hash + littleEndian64(buffer, 8) * k2_64; v1 = rotateLeft64(v1, -29) * k3_64; v0 ^= rotateLeft64(v0 * k0_64, -21) + v1; v1 ^= rotateLeft64(v1 * k3_64, -21) + v0; hash += v1; buffer = Arrays.copyOfRange(buffer, 16, buffer.length); } if (buffer.length >= 8) { hash += littleEndian64(buffer, 0) * k3_64; buffer = Arrays.copyOfRange(buffer, 8, buffer.length); hash ^= rotateLeft64(hash, -55) * k1_64; } if (buffer.length >= 4) { hash += (long) littleEndian32(Arrays.copyOfRange(buffer, 0, 4)) * k3_64; hash ^= rotateLeft64(hash, -26) * k1_64; buffer = Arrays.copyOfRange(buffer, 4, buffer.length); } if (buffer.length >= 2) { hash += (long) littleEndian16(Arrays.copyOfRange(buffer, 0, 2)) * k3_64; buffer = Arrays.copyOfRange(buffer, 2, buffer.length); hash ^= rotateLeft64(hash, -48) * k1_64; } if (buffer.length >= 1) { hash += (long) buffer[0] * k3_64; hash ^= rotateLeft64(hash, -38) * k1_64; } hash ^= rotateLeft64(hash, -28); hash *= k0_64; hash ^= rotateLeft64(hash, -29); return hash; } public static Number128 hash128(byte[] data, long seed) { byte[] buffer = data; long v0, v1, v2, v3; v0 = (seed - k0_128) * k3_128; v1 = (seed + k1_128) * k2_128; if (buffer.length >= 32) { v2 = (seed + k0_128) * k2_128; v3 = (seed - k1_128) * k3_128; while (buffer.length >= 32) { v0 += littleEndian64(buffer, 0) * k0_128; buffer = Arrays.copyOfRange(buffer, 8, buffer.length); v0 = rotateRight(v0, 29) + v2; v1 += littleEndian64(buffer, 0) * k1_128; buffer = Arrays.copyOfRange(buffer, 8, buffer.length); v1 = rotateRight(v1, 29) + v3; v2 += littleEndian64(buffer, 0) * k2_128; buffer = Arrays.copyOfRange(buffer, 8, buffer.length); v2 = rotateRight(v2, 29) + v0; v3 = littleEndian64(buffer, 0) * k3_128; buffer = Arrays.copyOfRange(buffer, 8, buffer.length); v3 = rotateRight(v3, 29) + v1; } v2 ^= rotateRight(((v0 + v3) * k0_128) + v1, 21) * k1_128; v3 ^= rotateRight(((v1 + v2) * k1_128) + v0, 21) * k0_128; v0 ^= rotateRight(((v0 + v2) * k0_128) + v3, 21) * k1_128; v1 ^= rotateRight(((v1 + v3) * k1_128) + v2, 21) * k0_128; } if (buffer.length >= 16) { v0 += littleEndian64(buffer, 0) * k2_128; buffer = Arrays.copyOfRange(buffer, 8, buffer.length); v0 = rotateRight(v0, 33) * k3_128; v1 += littleEndian64(buffer, 0) * k2_128; buffer = Arrays.copyOfRange(buffer, 8, buffer.length); v1 = rotateRight(v1, 33) * k3_128; v0 ^= rotateRight((v0 * k2_128) + v1, 45) + k1_128; v1 ^= rotateRight((v1 * k3_128) + v0, 45) + k0_128; } if (buffer.length >= 8) { v0 += littleEndian64(buffer, 0) * k2_128; buffer = Arrays.copyOfRange(buffer, 8, buffer.length); v0 = rotateRight(v0, 33) * k3_128; v0 ^= rotateRight((v0 * k2_128) + v1, 27) * k1_128; } if (buffer.length >= 4) { v1 += (long) littleEndian32(buffer) * k2_128; buffer = Arrays.copyOfRange(buffer, 4, buffer.length); v1 = rotateRight(v1, 33) * k3_128; v1 ^= rotateRight((v1 * k3_128) + v0, 46) * k0_128; } if (buffer.length >= 2) { v0 += (long) littleEndian16(buffer) * k2_128; buffer = Arrays.copyOfRange(buffer, 2, buffer.length); v0 = rotateRight(v0, 33) * k3_128; v0 ^= rotateRight((v0 * k2_128) * v1, 22) * k1_128; } if (buffer.length >= 1) { v1 += (long) buffer[0] * k2_128; v1 = rotateRight(v1, 33) * k3_128; v1 ^= rotateRight((v1 * k3_128) + v0, 58) * k0_128; } v0 += rotateRight((v0 * k0_128) + v1, 13); v1 += rotateRight((v1 * k1_128) + v0, 37); v0 += rotateRight((v0 * k2_128) + v1, 13); v1 += rotateRight((v1 * k3_128) + v0, 37); return new Number128(v0, v1); } private static long littleEndian64(byte[] b, int start) { return ByteUtil.bytesToLong(b, start, ByteOrder.LITTLE_ENDIAN); } private static int littleEndian32(byte[] b) { return (int) b[0] | (int) b[1] << 8 | (int) b[2] << 16 | (int) b[3] << 24; } private static int littleEndian16(byte[] b) { return ByteUtil.bytesToShort(b, ByteOrder.LITTLE_ENDIAN); } private static long rotateLeft64(long x, int k) { int n = 64; int s = k & (n - 1); return x << s | x >> (n - s); } private static long rotateRight(long val, int shift) { return (val >> shift) | (val << (64 - shift)); } }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/lang/hash/MetroHash.java
846
package edu.cmu.lti.nlp.chinese; public class CConsts { public static final String s_PU = "—…。,、;:?!‘’“”∶〔〕〈〉《》「」『』.()[]{}"; public static final String s_NUM = "一二三四五六七八九〇千万亿十百兆厘壹贰叁肆伍陆柒捌玖零仟拾佰4013526789"; public static final String s_LETR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String s_FN = "弗厦罗丁叶邹胡崔柯朱刘彭唐张萨陈黄邱吴许谭蒋徐梁冯吕薛李苏郭王孙卢浙郑戴沈杜郝赵蔡邓廖宋毕卞曹程池范方樊费符傅葛龚韩洪侯胡姜孔林骆孟潘邱魏邬邢俞袁詹张朱庄"; public static final String sOpen = "‘“〔〈《「『([{〖【"; public static final String paOpen = "["+sOpen+"]"; public static final String sClose = "’”〕〉》」』)]}〗】"; public static final String paClose = "["+sClose+"]"; public static final String sPronoun ="他 她 他们 她们 它 其 它们"; //public static final String paPNP ="["+sPNP+"]"; public static final String sPNO ="这那"; }
noon99jaki/pra
edu/cmu/lti/nlp/chinese/CConsts.java
847
package com.wm.remusic.json; /** * Created by wm on 2016/8/2. */ public class ArtistInfo { /** * constellation : 未知 * weight : 0.00 * ting_uid : 208167 * stature : 0.00 * avatar_s500 : http://b.hiphotos.baidu.com/ting/pic/item/11385343fbf2b211de73a57fc88065380cd78ea5.jpg * aliasname : * country : 中国 * source : web * intro : 环球音乐2006年新年献礼情歌伴侣 Songmate Vol.1 10年之後 或许只有这些歌还记得我们相爱的勇气 用满载回忆和全新感情交织出最温暖的音乐火花 15首引领潮流的情歌在2006年谱出的全新恋曲 ◎数位资深音乐幕後人员的组合 美声团体 情歌伴侣 Songmate 『情歌伴侣Songmate』是由数位幕後的资深音乐人所组成的,是一个强调合声与聆听度的美声团体。这几位都是歌手口中的「老师」们,以自己多年的功力将这些好听而有代表性的歌曲用他们觉得最适当的方式来做全新的诠释。让所有喜欢听音乐的人可以在最舒服没有压力的状况下欣赏这些都是一时之选的好歌。他们选择不露面只献声的方式,是不想模糊了焦点将重点放在他们人的身上。而是将焦点放在这些他们重新诠释的好歌上。 ◎好歌不寂寞<勇气>及<十年>拍成的上下集音乐爱情故事「全民大闷锅」爆红人气新星 阿KEN 首次的MV深情演出 这张《情歌伴侣 Songmate Vol.1》的2首抢先推荐的歌是由梁静茹所原唱的<勇气>和陈亦迅原唱的<十年>。为了衬托出这2首情歌的感动度,环球音乐投下重金拍摄了分为上下2集的音乐爱情故事。并邀请到因为演出「全民大闷锅」而受到欢迎的人气新星阿KEN来演出故事中深情付出的男主角。让平常看惯了阿KEN搞笑演出的人看看他另一面的演技。除了希望MV和这些歌一样让人有全新的感受之外,更希望听了这些歌能让所有烦闷而压力大的人都不闷了。 ◎情歌伴侣 Songmate Vol.1 用满载回忆和全新感情交织出最温暖的音乐火花 15首引领潮流的情歌在2006年谱出的全新恋曲献给曾经 现在 即将相爱的每一对有情人 美声团体情歌伴侣的首张同名专辑《情歌伴侣SongmateVol.》是2006年环球唱片的新春献礼。要给所有爱听音乐及好歌的消费者一个全新的选择。专辑中收录了15首近年来引领潮流的情歌首选,用美声及合声来做全新的诠释,大家可以细细聆听这些脍炙人口的情歌在2006年带来的全新感动。 * url : http://music.baidu.com/artist/1077175 * company : * bloodtype : * avatar_middle : http://musicdata.baidu.com/data2/pic/86611107/86611107.jpg * mv_total : * area : 1 * avatar_mini : http://a.hiphotos.baidu.com/ting/pic/item/377adab44aed2e7372b5a61d8501a18b87d6faa7.jpg * firstchar : Q * piao_id : 0 * avatar_s1000 : http://a.hiphotos.baidu.com/ting/pic/item/c75c10385343fbf2fe718612b27eca8065388fa5.jpg * translatename : * avatar_s180 : http://musicdata.baidu.com/data2/pic/86611103/86611103.jpg * artist_id : 1077175 * name : 情歌伴侣 * gender : 3 * birth : 0000-00-00 * avatar_small : http://c.hiphotos.baidu.com/ting/abpic/item/b17eca8065380cd7c34382dca344ad34598281a5.jpg * avatar_big : http://musicdata.baidu.com/data2/pic/86611101/86611101.jpg * albums_total : 0 * songs_total : 15 */ private String constellation; private String weight; private String ting_uid; private String stature; private String avatar_s500; private String aliasname; private String country; private String source; private String intro; private String url; private String company; private String bloodtype; private String avatar_middle; private String mv_total; private String area; private String avatar_mini; private String firstchar; private String piao_id; private String avatar_s1000; private String translatename; private String avatar_s180; private String artist_id; private String name; private String gender; private String birth; private String avatar_small; private String avatar_big; private String albums_total; private String songs_total; public String getConstellation() { return constellation; } public void setConstellation(String constellation) { this.constellation = constellation; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getTing_uid() { return ting_uid; } public void setTing_uid(String ting_uid) { this.ting_uid = ting_uid; } public String getStature() { return stature; } public void setStature(String stature) { this.stature = stature; } public String getAvatar_s500() { return avatar_s500; } public void setAvatar_s500(String avatar_s500) { this.avatar_s500 = avatar_s500; } public String getAliasname() { return aliasname; } public void setAliasname(String aliasname) { this.aliasname = aliasname; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getBloodtype() { return bloodtype; } public void setBloodtype(String bloodtype) { this.bloodtype = bloodtype; } public String getAvatar_middle() { return avatar_middle; } public void setAvatar_middle(String avatar_middle) { this.avatar_middle = avatar_middle; } public String getMv_total() { return mv_total; } public void setMv_total(String mv_total) { this.mv_total = mv_total; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getAvatar_mini() { return avatar_mini; } public void setAvatar_mini(String avatar_mini) { this.avatar_mini = avatar_mini; } public String getFirstchar() { return firstchar; } public void setFirstchar(String firstchar) { this.firstchar = firstchar; } public String getPiao_id() { return piao_id; } public void setPiao_id(String piao_id) { this.piao_id = piao_id; } public String getAvatar_s1000() { return avatar_s1000; } public void setAvatar_s1000(String avatar_s1000) { this.avatar_s1000 = avatar_s1000; } public String getTranslatename() { return translatename; } public void setTranslatename(String translatename) { this.translatename = translatename; } public String getAvatar_s180() { return avatar_s180; } public void setAvatar_s180(String avatar_s180) { this.avatar_s180 = avatar_s180; } public String getArtist_id() { return artist_id; } public void setArtist_id(String artist_id) { this.artist_id = artist_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getBirth() { return birth; } public void setBirth(String birth) { this.birth = birth; } public String getAvatar_small() { return avatar_small; } public void setAvatar_small(String avatar_small) { this.avatar_small = avatar_small; } public String getAvatar_big() { return avatar_big; } public void setAvatar_big(String avatar_big) { this.avatar_big = avatar_big; } public String getAlbums_total() { return albums_total; } public void setAlbums_total(String albums_total) { this.albums_total = albums_total; } public String getSongs_total() { return songs_total; } public void setSongs_total(String songs_total) { this.songs_total = songs_total; } }
aa112901/remusic
app/src/main/java/com/wm/remusic/json/ArtistInfo.java
848
package class_2023_02_4_week; import java.util.PriorityQueue; // 一所学校里有一些班级,每个班级里有一些学生,现在每个班都会进行一场期末考试 // 给你一个二维数组 classes ,其中 classes[i] = [passi, totali] // 表示你提前知道了第 i 个班级总共有 totali 个学生,其中只有 passi 个学生可以通过考试 // 给你一个整数 extraStudents ,表示额外有 extraStudents 个聪明的学生 // 他们 一定 能通过任何班级的期末考 // 你需要给这 extraStudents 个学生每人都安排一个班级 // 使得 所有 班级的 平均 通过率 最大 。 // 一个班级的 通过率 等于这个班级通过考试的学生人数除以这个班级的总人数 // 平均通过率 是所有班级的通过率之和除以班级数目。 // 请你返回在安排这 extraStudents 个学生去对应班级后的 最大 平均通过率 // 与标准答案误差范围在 10^-5 以内的结果都会视为正确结果。 // 测试链接 : https://leetcode.cn/problems/maximum-average-pass-ratio/ public class Code01_MaximumAveragePassRatio { public static double maxAverageRatio(int[][] classes, int extraStudents) { // 堆 : 谁获得一个天才,得到的通过率增益最大 // 谁先弹出 PriorityQueue<Party> heap = new PriorityQueue<>((a, b) -> a.benefit() - b.benefit() < 0 ? 1 : -1); for (int[] p : classes) { heap.add(new Party(p[0], p[1])); } Party cur; // 一个一个天才分配 for (int i = 0; i < extraStudents; i++) { cur = heap.poll(); cur.pass++; cur.total++; heap.add(cur); } double all = 0; while (!heap.isEmpty()) { cur = heap.poll(); all += cur.pass / cur.total; } return all / classes.length; } public static class Party { public double pass; public double total; public Party(int p, int t) { pass = p; total = t; } public double benefit() { return (pass + 1) / (total + 1) - pass / total; } } }
algorithmzuo/weekly-problems
src/class_2023_02_4_week/Code01_MaximumAveragePassRatio.java
849
/* * Copyright (c) 2017-2020. Nitrite 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dizitart.no2.index.fulltext.languages; import org.dizitart.no2.index.fulltext.Language; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Chinese stop words * * @author Anindya Chatterjee * @since 2.1.0 */ public class Chinese implements Language { @Override public Set<String> stopWords() { return new HashSet<>(Arrays.asList( "、", "。", "〈", "〉", "《", "》", "一", "一些", "一何", "一切", "一则", "一方面", "一旦", "一来", "一样", "一般", "一转眼", "七", "万一", "三", "上", "上下", "下", "不", "不仅", "不但", "不光", "不单", "不只", "不外乎", "不如", "不妨", "不尽", "不尽然", "不得", "不怕", "不惟", "不成", "不拘", "不料", "不是", "不比", "不然", "不特", "不独", "不管", "不至于", "不若", "不论", "不过", "不问", "与", "与其", "与其说", "与否", "与此同时", "且", "且不说", "且说", "两者", "个", "个别", "中", "临", "为", "为了", "为什么", "为何", "为止", "为此", "为着", "乃", "乃至", "乃至于", "么", "之", "之一", "之所以", "之类", "乌乎", "乎", "乘", "九", "也", "也好", "也罢", "了", "二", "二来", "于", "于是", "于是乎", "云云", "云尔", "五", "些", "亦", "人", "人们", "人家", "什", "什么", "什么样", "今", "介于", "仍", "仍旧", "从", "从此", "从而", "他", "他人", "他们", "他们们", "以", "以上", "以为", "以便", "以免", "以及", "以故", "以期", "以来", "以至", "以至于", "以致", "们", "任", "任何", "任凭", "会", "似的", "但", "但凡", "但是", "何", "何以", "何况", "何处", "何时", "余外", "作为", "你", "你们", "使", "使得", "例如", "依", "依据", "依照", "便于", "俺", "俺们", "倘", "倘使", "倘或", "倘然", "倘若", "借", "借傥然", "假使", "假如", "假若", "做", "像", "儿", "先不先", "光是", "全体", "全部", "八", "六", "兮", "共", "关于", "关于具体地说", "其", "其一", "其中", "其二", "其他", "其余", "其它", "其次", "具体地说", "具体说来", "兼之", "内", "再", "再其次", "再则", "再有", "再者", "再者说", "再说", "冒", "冲", "况且", "几", "几时", "凡", "凡是", "凭", "凭借", "出于", "出来", "分", "分别", "则", "则甚", "别", "别人", "别处", "别是", "别的", "别管", "别说", "到", "前后", "前此", "前者", "加之", "加以", "即", "即令", "即使", "即便", "即如", "即或", "即若", "却", "去", "又", "又及", "及", "及其", "及至", "反之", "反而", "反过来", "反过来说", "受到", "另", "另一方面", "另外", "另悉", "只", "只当", "只怕", "只是", "只有", "只消", "只要", "只限", "叫", "叮咚", "可", "可以", "可是", "可见", "各", "各个", "各位", "各种", "各自", "同", "同时", "后", "后者", "向", "向使", "向着", "吓", "吗", "否则", "吧", "吧哒", "含", "吱", "呀", "呃", "呕", "呗", "呜", "呜呼", "呢", "呵", "呵呵", "呸", "呼哧", "咋", "和", "咚", "咦", "咧", "咱", "咱们", "咳", "哇", "哈", "哈哈", "哉", "哎", "哎呀", "哎哟", "哗", "哟", "哦", "哩", "哪", "哪个", "哪些", "哪儿", "哪天", "哪年", "哪怕", "哪样", "哪边", "哪里", "哼", "哼唷", "唉", "唯有", "啊", "啐", "啥", "啦", "啪达", "啷当", "喂", "喏", "喔唷", "喽", "嗡", "嗡嗡", "嗬", "嗯", "嗳", "嘎", "嘎登", "嘘", "嘛", "嘻", "嘿", "嘿嘿", "四", "因", "因为", "因了", "因此", "因着", "因而", "固然", "在", "在下", "在于", "地", "基于", "处在", "多", "多么", "多少", "大", "大家", "她", "她们", "好", "如", "如上", "如上所述", "如下", "如何", "如其", "如同", "如是", "如果", "如此", "如若", "始而", "孰料", "孰知", "宁", "宁可", "宁愿", "宁肯", "它", "它们", "对", "对于", "对待", "对方", "对比", "将", "小", "尔", "尔后", "尔尔", "尚且", "就", "就是", "就是了", "就是说", "就算", "就要", "尽", "尽管", "尽管如此", "岂但", "己", "已", "已矣", "巴", "巴巴", "年", "并", "并且", "庶乎", "庶几", "开外", "开始", "归", "归齐", "当", "当地", "当然", "当着", "彼", "彼时", "彼此", "往", "待", "很", "得", "得了", "怎", "怎么", "怎么办", "怎么样", "怎奈", "怎样", "总之", "总的来看", "总的来说", "总的说来", "总而言之", "恰恰相反", "您", "惟其", "慢说", "我", "我们", "或", "或则", "或是", "或曰", "或者", "截至", "所", "所以", "所在", "所幸", "所有", "才", "才能", "打", "打从", "把", "抑或", "拿", "按", "按照", "换句话说", "换言之", "据", "据此", "接着", "故", "故此", "故而", "旁人", "无", "无宁", "无论", "既", "既往", "既是", "既然", "日", "时", "时候", "是", "是以", "是的", "更", "曾", "替", "替代", "最", "月", "有", "有些", "有关", "有及", "有时", "有的", "望", "朝", "朝着", "本", "本人", "本地", "本着", "本身", "来", "来着", "来自", "来说", "极了", "果然", "果真", "某", "某个", "某些", "某某", "根据", "欤", "正值", "正如", "正巧", "正是", "此", "此地", "此处", "此外", "此时", "此次", "此间", "毋宁", "每", "每当", "比", "比及", "比如", "比方", "没奈何", "沿", "沿着", "漫说", "焉", "然则", "然后", "然而", "照", "照着", "犹且", "犹自", "甚且", "甚么", "甚或", "甚而", "甚至", "甚至于", "用", "用来", "由", "由于", "由是", "由此", "由此可见", "的", "的确", "的话", "直到", "相对而言", "省得", "看", "眨眼", "着", "着呢", "矣", "矣乎", "矣哉", "离", "秒", "竟而", "第", "等", "等到", "等等", "简言之", "管", "类如", "紧接着", "纵", "纵令", "纵使", "纵然", "经", "经过", "结果", "给", "继之", "继后", "继而", "综上所述", "罢了", "者", "而", "而且", "而况", "而后", "而外", "而已", "而是", "而言", "能", "能否", "腾", "自", "自个儿", "自从", "自各儿", "自后", "自家", "自己", "自打", "自身", "至", "至于", "至今", "至若", "致", "般的", "若", "若夫", "若是", "若果", "若非", "莫不然", "莫如", "莫若", "虽", "虽则", "虽然", "虽说", "被", "要", "要不", "要不是", "要不然", "要么", "要是", "譬喻", "譬如", "让", "许多", "论", "设使", "设或", "设若", "诚如", "诚然", "该", "说", "说来", "请", "诸", "诸位", "诸如", "谁", "谁人", "谁料", "谁知", "贼死", "赖以", "赶", "起", "起见", "趁", "趁着", "越是", "距", "跟", "较", "较之", "边", "过", "还", "还是", "还有", "还要", "这", "这一来", "这个", "这么", "这么些", "这么样", "这么点儿", "这些", "这会儿", "这儿", "这就是说", "这时", "这样", "这次", "这般", "这边", "这里", "进而", "连", "连同", "逐步", "通过", "遵循", "遵照", "那", "那个", "那么", "那么些", "那么样", "那些", "那会儿", "那儿", "那时", "那样", "那般", "那边", "那里", "都", "鄙人", "鉴于", "针对", "阿", "除", "除了", "除外", "除开", "除此之外", "除非", "随", "随后", "随时", "随着", "难道说", "零", "非", "非但", "非徒", "非特", "非独", "靠", "顺", "顺着", "首先", "︿", "!", "#", "$", "%", "&", "(", ")", "*", "+", ",", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", ">", "?", "@", "[", "]", "{", "|", "}", "~", "¥" )); } }
nitrite/nitrite-java
nitrite/src/main/java/org/dizitart/no2/index/fulltext/languages/Chinese.java
850
M 1527969793 tags: BFS, DFS 给一个undirected graph, return 所有的component. (这道题找不到了) #### BFS - BFS遍历,把每个node的neighbor都加进来. - 一定注意要把visit过的node Mark一下。因为curr node也会是别人的neighbor,会无限循环。 - Component的定义:所有Component内的node必须被串联起来via path (反正这里是undirected, 只要链接上就好) - 这道题:其实component在input里面都已经给好了,所有能一口气visit到的,全部加进queue里面,他们就是一个component里面的了。 - 而我们这里不需要判断他们是不是Component #### DFS - DFS 应该也可以 visit all nodes, mark visited. ``` /* Find the number connected component in the undirected graph. Each node in the graph contains a label and a list of its neighbors. (a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.) Example Given graph: A------B C \ | | \ | | \ | | \ | | D E Return {A,B,D}, {C,E}. Since there are two connected component which is {A,B,D}, {C,E} Note Tags Expand Breadth First Search */ /** * Definition for Undirected graph. * class UndirectedGraphNode { * int label; * ArrayList<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } * }; */ /* OPTS: 11.07.2015 Try to use ae map<Integer, false> to mark the nodes. Then do a BFS with queue 1. Mark each node in map. 2. BFS each node 3. Whenver one node is checked, mark it check */ public class Solution { /** * @param nodes a array of Undirected graph node * @return a connected set of a Undirected graph */ public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) { List<List<Integer>> rst = new ArrayList<List<Integer>>(); if (nodes == null || nodes.size() == 0) { return rst; } HashMap<Integer, Boolean> map = new HashMap<>(); for (UndirectedGraphNode node : nodes) { map.put(node.label, false); } for (UndirectedGraphNode node : nodes) { if (!map.get(node.label)) { bfs(rst, node, map); } } return rst; } public void bfs(List<List<Integer>> rst, UndirectedGraphNode node, HashMap<Integer, Boolean> map) { Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>(); List<Integer> list = new ArrayList<Integer>(); queue.add(node); map.put(node.label, true); UndirectedGraphNode temp; while (!queue.isEmpty()) { temp = queue.poll(); list.add(temp.label); for (UndirectedGraphNode neighbor : temp.neighbors) { if (!map.get(neighbor.label)) { queue.offer(neighbor); map.put(neighbor.label, true); } } } Collections.sort(list); rst.add(list); } } /* Thoughts: How do we check for a connected graph (any two nodes are connected)? Maybe check for each node: each node represents a lead to a subgraph, then check if this subgraph is valid. 1. In real case, need to ask the intervier: can we assume the given nodes are valid, so that we only need to check for success case? That means, we assume for example a linear list A-B-C does not exist. 2. Then, we can use a 'set' to mark: we've checked this node. 3. Use a queue for BFS 4. Use a arraylist to save the results. 5. Key point: when the queue is empty(), that means one set of connected component is ready to go 6. Iterate through nodes, when it's not empty. More Notes:Have to do Collections.sort()....somehow it want me to sort the results? Note2: Get rid of a node from nodes, whenever add it to component ... don't forget this. Note3: Well, there is a chance that compoents are added, queue is cleaned, but nodes are empty as well.. that means, need to catch the last case of 'remaining component' and add it to rst. Review: How list, ArrayList, Set, Queue work. How to do: add, remove, sort Collections: Set, List, Queue List: ArrayList Set methods: add(), contains(?) Queue methods: offer(E e), add(E e), poll() ArrayList method: add(E e), isEmpty(), remove(object o) */ public class Solution { /** * @param nodes a array of Undirected graph node * @return a connected set of a Undirected graph */ public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) { List<List<Integer>> rst = new ArrayList<>(); if (nodes == null || nodes.size() == 0) { return rst; } //Init: Set<UndirectedGraphNode> checked = new HashSet(); Queue<UndirectedGraphNode> queue = new LinkedList(); ArrayList<Integer> component = new ArrayList<Integer>(); queue.offer(nodes.get(0)); while (!nodes.isEmpty()) { if (queue.isEmpty()) { Collections.sort(component); rst.add(component); queue.offer(nodes.get(0)); component = new ArrayList<Integer>(); } else { UndirectedGraphNode curr = queue.poll(); if (!checked.contains(curr)) { checked.add(curr); component.add(curr.label); nodes.remove(curr); for (UndirectedGraphNode node : curr.neighbors) { queue.add(node); } } } } if (!component.isEmpty()) { rst.add(component); } return rst; } } ```
awangdev/leet-code
Java/Find the Connected Component in the Undirected Graph.java
851
// 索引最大堆的第 1 个版本的实现,引入 indexes 数组,通过 indexes 数组的整理,使得 // data[index[1]],data[index[2]],...,data[index[count]] 成为一个最大堆 // 注意:在这个版本的实现中,如果我们要找到使用者认为的 data 数组索引为 i 的那个元素, // 我们要遍历 indexes 数组,看看从 0 到 count 中的 j,哪个使得 indexes[j] = i // 在下一个版本中,我们会改进这个方法,通过维护一个 reverse 数组,使用 O(1) 复杂度,直接得到 j import java.util.Arrays; // 对于索引堆的使用者,他们只需要知道,这是一个数据结构,可以往里面存入数据, // 而每一次那出来的数据,都是当前已经存放在这个数据结构中最大的那个元素。 // 理解这里的操作要牢牢抓住一点 // indexes 数组(映射以后)的形态形成一个堆 // 最典型的特征就是,indexes 数组的第 1 个存放位置的元素对应的 data 是最大的 public class IndexMaxHeap { /** * 最大索引堆中的数据,我们这个版本的实现中,0 号索引不存数据 */ private int[] data; /** * 当前最大索引堆中的元素个数 */ private int count; /** * 最大索引堆的容量,一经确定,就不能更改 */ private int capacity; /** * 最大索引堆中的内置索引,外部用户并不感知 */ private int[] indexes; /** * 初始化 * @param capacity */ public IndexMaxHeap(int capacity) { data = new int[capacity + 1]; indexes = new int[capacity + 1]; count = 0; this.capacity = capacity; } /** * 返回堆中的元素个数 * @return */ public int getSize() { return count; } /** * 返回一个布尔值, 表示堆中是否为空 * @return */ public boolean isEmpty() { return count == 0; } // insert 是我们第一个要改造的方法,我们给这个方法加上一个位置索引 // 【特别注意】待插入数据的索引的位置是不能存放数据的,或者说这里存放的数据已经失效 // 【特别注意】待插入数据的索引的位置是不能存放数据的,或者说这里存放的数据已经失效 // 【特别注意】待插入数据的索引的位置是不能存放数据的,或者说这里存放的数据已经失效 // 比如:这个索引的位置可以是用户认为的数据的末尾,或者是刚刚出队的那个索引,注意,一定是不能有数据的索引 // 比如:这个索引的位置可以是用户认为的数据的末尾,或者是刚刚出队的那个索引,注意,一定是不能有数据的索引 // 比如:这个索引的位置可以是用户认为的数据的末尾,或者是刚刚出队的那个索引,注意,一定是不能有数据的索引 // 例如,在他们的眼中,可以认为 0 号索引存放他们的第 1 个任务,1 号索引存放他们的第 2 个任务,而每一次出队的操作,我们都返回给他们优先级最高的那个任务 /** * 插入,元素的索引是 i ,对于外部用户来说,i 是从 0 开始计算的 * * @param i * @param item */ public void insert(int i, int item) { // 注意:使用者认为的 i 总是比我们内部使用的 i 少 1 // 检测1:确保可以添加 assert count + 1 <= capacity; // 检测2:确保使用者给出的索引 i,经过转换(即 +1 )以后落在 [1,...,capacity],即是检测使用者传来的索引的合法性 // 【特别注意】这里不要理解成数组的 insert i,要让 i 以及后面的元素后移,这不是这个方法要表达的意思 // 这里的 i 应该保证:(1)还未添加数据;(2)这里存放的数据已经失效,一种应用场景是:刚刚出队的元素的索引,就可以作为这里的 insert 的 i assert i + 1 >= 1 && i + 1 <= capacity; // 0,1,2,3 一共 4 // 转换成内部的索引 i += 1; // 这个 data 在用户眼中认为的值 data[i] = item; // 这一行代码要注意:indexes 数组一定是连续的 // data[indexes[1]],data[indexes[2]],...,data[indexes[count]] 一定是构成堆的 // 多看看这句话,indexes 数组的 [1,2,...,count] 是连续取值的 // 而 // 这一步很关键,在内部索引数组的最后设置索引数组的索引 indexes[count + 1] = i; count++; siftUp(count); } /** * @param k */ private void siftUp(int k) { // 注意:引入了索引以后,表示将索引数组的第 k 的位置的元素逐层上移 // 注意:引入了索引以后,表示将索引数组的第 k 的位置的元素逐层上移 // 注意:引入了索引以后,表示将索引数组的第 k 的位置的元素逐层上移 // 代码编写要点:1、比较的时候使用 data // 2、交换的时候使用 indexes // 有索引就要考虑索引越界的情况 while (k > 1 && data[indexes[k / 2]] < data[indexes[k]]) { swap(indexes, k / 2, k); k /= 2; } } private void swap(int[] data, int index1, int index2) { int temp = data[index1]; data[index1] = data[index2]; data[index2] = temp; } /** * @return */ public int extractMax() { // 将此时二叉堆中的最大的那个数据删除(出队),返回的是数据,不是返回索引 assert count > 0; int ret = data[indexes[1]]; // 只要设计交换的操作,就一定是索引数组交换 swap(indexes, 1, count); count--; siftDown(1); return ret; } /** * 把在索引 k 这个位置元素逐渐下落 * * @param k */ private void siftDown(int k) { // 只要它有孩子,注意,这里的等于号是十分关键的 while (2 * k <= count) { int j = 2 * k; // 如果它有右边的孩子,并且右边的孩子大于左边的孩子 if (j + 1 <= count && data[indexes[j + 1]] > data[indexes[j]]) { // 右边的孩子胜出,此时可以认为没有左孩子, j = j + 1; } // 如果当前的元素的值,比右边的孩子节点要大,则逐渐下落的过程到此结束 if (data[indexes[k]] >= data[indexes[j]]) { break; } // 否则,交换位置,继续循环 swap(indexes, k, j); k = j; } } // 以下是索引堆相比不是索引堆新增的一些操作 /** * 这里应该理解为出队(删除),只不过返回的是当前二叉堆中最大元素的索引值 * @return */ public int extractMaxIndex() { // 将此时二叉堆中的最大元素的索引返回,注意,此时我们相当于让最大数据出栈(删除了元素) // 注意,执行一步这个操作以后,应该马上执行 getItem 获得数据 // 否则,如果再执行一次 extractMaxIndex,得到的就不是原来那个索引值 assert count > 0; // -1 是为了转换成用户的角度 int ret = indexes[1] - 1; swap(indexes, 1, count); count--; siftDown(1); return ret; } public int getItem(int i) { return data[i + 1]; } public void change(int i, int item) { i = i + 1; data[i] = item; // 找到 index[j] = i,j 表示 data[i] 在堆中的位置 // 之后 shiftUp(j),在 shiftDown(j) for (int j = 1; j <= count; j++) { if (indexes[j] == i) { // 找到了 j siftDown(j); siftUp(j); return; } } } /** * 为 LeetCode 第 239 题新增的方法, * 看一眼此时索引堆的最大索引是多少(没用上,我想多了,留到以后用吧) * * @return */ public int peekMaxIndex() { if (this.count == 0) { throw new RuntimeException("堆里没有可以取出的元素"); } // 注意:与用户认为的索引值有一个偏差 return indexes[1] - 1; } /** * 为 LeetCode 第 239 题新增的方法, * 看一眼此时索引堆的最大索引是多少(没用上,我想多了,留到以后用吧) * * @return */ public int peekMaxValue() { if (this.count == 0) { throw new RuntimeException("堆里没有可以取出的元素"); } return data[indexes[1]]; } // 编写测试用例 public static void main(String[] args) { // 测试用例1 // int[] nums = {2, 3, 3, 4, 2, 5, 2, 3, 3, 5}; // IndexMaxHeap4 indexMaxHeap = new IndexMaxHeap4(nums.length); // for (int i = 0; i < nums.length; i++) { // indexMaxHeap.insert(i, nums[i]); // } // for (int i = 0; i < nums.length; i++) { // System.out.print(indexMaxHeap.extractMax() + " "); // System.out.println("还剩多少元素:" + indexMaxHeap.count); // } // 测试用例2: int n = 30; int[] nums = SortTestHelper.generateRandomArray(n, 10, 100); System.out.println("原始数组:" + Arrays.toString(nums)); IndexMaxHeap indexMaxHeap = new IndexMaxHeap(nums.length); for (int i = 0; i < n; i++) { indexMaxHeap.insert(i, nums[i]); } int[] ret = new int[n]; for (int i = 0; i < n; i++) { int extractMax = indexMaxHeap.extractMax(); // System.out.println("还剩多少元素:" + indexMaxHeap.count); ret[n - 1 - i] = extractMax; } System.out.println("我的排序:" + Arrays.toString(ret)); int[] copy = nums.clone(); Arrays.sort(copy); System.out.println("系统排序:" + Arrays.toString(copy)); System.out.println("原始数组:" + Arrays.toString(nums)); int N = 10000; IndexMaxHeap indexMapHeap = new IndexMaxHeap(N); // for (int i = 0; i < N; i++) { // int randomNum = (int) (Math.random() * N); // indexMapHeap.insert(i, randomNum); // } // int[] newArray = new int[N]; // while (!indexMapHeap.isEmpty()) { // newArray[--N] = indexMapHeap.getItem(indexMapHeap.extractMapIndex()); // } // SortTestHelper.testSorted(newArray); int[] data = new int[]{15, 17, 19, 13, 22, 16, 28, 30, 41, 62}; for (int i = 0; i < data.length; i++) { indexMapHeap.insert(i, data[i]); } System.out.println(Arrays.toString(indexMapHeap.indexes)); } }
liweiwei1419/LeetCode-Solutions-in-Good-Style
09-Priority-Queue(Heap)/06-Heap/src/IndexMaxHeap.java
852
/* * Copyright 2009-2014 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.cache.decorators; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.Deque; import java.util.LinkedList; import java.util.concurrent.locks.ReadWriteLock; import org.apache.ibatis.cache.Cache; /** * Soft Reference cache decorator * Thanks to Dr. Heinz Kabutz for his guidance here. * 软引用缓存,核心是SoftReference * * @author Clinton Begin */ public class SoftCache implements Cache { //链表用来引用元素,防垃圾回收 private final Deque<Object> hardLinksToAvoidGarbageCollection; //被垃圾回收的引用队列 private final ReferenceQueue<Object> queueOfGarbageCollectedEntries; private final Cache delegate; private int numberOfHardLinks; public SoftCache(Cache delegate) { this.delegate = delegate; //默认链表可以存256元素 this.numberOfHardLinks = 256; this.hardLinksToAvoidGarbageCollection = new LinkedList<Object>(); this.queueOfGarbageCollectedEntries = new ReferenceQueue<Object>(); } @Override public String getId() { return delegate.getId(); } @Override public int getSize() { removeGarbageCollectedItems(); return delegate.getSize(); } public void setSize(int size) { this.numberOfHardLinks = size; } @Override public void putObject(Object key, Object value) { removeGarbageCollectedItems(); //putObject存了一个SoftReference,这样value没用时会自动垃圾回收 delegate.putObject(key, new SoftEntry(key, value, queueOfGarbageCollectedEntries)); } @Override public Object getObject(Object key) { Object result = null; @SuppressWarnings("unchecked") // assumed delegate cache is totally managed by this cache SoftReference<Object> softReference = (SoftReference<Object>) delegate.getObject(key); if (softReference != null) { //核心调用SoftReference.get取得元素 result = softReference.get(); if (result == null) { delegate.removeObject(key); } else { // See #586 (and #335) modifications need more than a read lock synchronized (hardLinksToAvoidGarbageCollection) { //存入经常访问的键值到链表(最多256元素),防止垃圾回收 hardLinksToAvoidGarbageCollection.addFirst(result); if (hardLinksToAvoidGarbageCollection.size() > numberOfHardLinks) { hardLinksToAvoidGarbageCollection.removeLast(); } } } } return result; } @Override public Object removeObject(Object key) { removeGarbageCollectedItems(); return delegate.removeObject(key); } @Override public void clear() { synchronized (hardLinksToAvoidGarbageCollection) { hardLinksToAvoidGarbageCollection.clear(); } removeGarbageCollectedItems(); delegate.clear(); } @Override public ReadWriteLock getReadWriteLock() { return null; } private void removeGarbageCollectedItems() { SoftEntry sv; //查看被垃圾回收的引用队列,然后调用removeObject移除他们 while ((sv = (SoftEntry) queueOfGarbageCollectedEntries.poll()) != null) { delegate.removeObject(sv.key); } } private static class SoftEntry extends SoftReference<Object> { private final Object key; SoftEntry(Object key, Object value, ReferenceQueue<Object> garbageCollectionQueue) { super(value, garbageCollectionQueue); this.key = key; } } }
tuguangquan/mybatis
src/main/java/org/apache/ibatis/cache/decorators/SoftCache.java
853
//班上有 N 名学生。其中有些人是朋友,有些则不是。他们的友谊具有是传递性。如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友。所谓的朋友圈,是指所有朋友的集合。 // // 给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。你必须输出所有学生中的已知的朋友圈总数。 // // 示例 1: // // //输入: //[[1,1,0], // [1,1,0], // [0,0,1]] //输出: 2 //说明:已知学生0和学生1互为朋友,他们在一个朋友圈。 //第2个学生自己在一个朋友圈。所以返回2。 // // // 示例 2: // // //输入: //[[1,1,0], // [1,1,1], // [0,1,1]] //输出: 1 //说明:已知学生0和学生1互为朋友,学生1和学生2互为朋友,所以学生0和学生2也是朋友,所以他们三个在一个朋友圈,返回1。 // // // 注意: // // // N 在[1,200]的范围内。 // 对于所有学生,有M[i][i] = 1。 // 如果有M[i][j] = 1,则有M[j][i] = 1。 // // Related Topics 深度优先搜索 并查集 package com.aseara.leetcode.editor.cn.a547; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * desc: 547.朋友圈 <br /> * Date: 2019/11/20 <br/> * * @author qiujingde */ class FriendCircles { private Solution solution = new Solution(); @Test void test1() { int[][] M1 = { {1,1,0}, {1,1,0}, {0,0,1} }; assertEquals(2, solution.findCircleNum(M1)); int[][] M2 = { {1,1,0}, {1,1,1}, {0,1,1} }; assertEquals(1, solution.findCircleNum(M2)); } } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int findCircleNum(int[][] M) { if (M == null) { return 0; } if (M.length < 2) { return M.length; } int m = M.length; DisjointSet disjointSet = new DisjointSet(m); for (int i = 0; i < m - 1; i++) { for (int j = i + 1; j < m; j++) { if (M[i][j] == 1) { disjointSet.join(i, j); } } } return disjointSet.count; } } class DisjointSet { int count; private int[] parent; DisjointSet(int size) { count = size; parent = new int[size]; for (int i = 1; i < size; i++) { parent[i] = i; } } private int find(int i) { while (i != parent[i]) { parent[i] = parent[parent[i]]; i = parent[i]; } return i; } void join(int i, int j) { int pi = find(i); int pj = find(j); if (pi != pj) { parent[pj] = pi; count--; } } } //leetcode submit region end(Prohibit modification and deletion)
algorithm004-01/algorithm004-01
Week 06/id_466/LeetCode_547_466.java
854
package com.scwang.smart.refresh.layout.api; import android.view.View; import android.view.ViewGroup; import android.view.animation.Interpolator; import androidx.annotation.ColorInt; import androidx.annotation.ColorRes; import androidx.annotation.FloatRange; import androidx.annotation.IdRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.scwang.smart.refresh.layout.constant.RefreshState; import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener; import com.scwang.smart.refresh.layout.listener.OnMultiListener; import com.scwang.smart.refresh.layout.listener.OnRefreshListener; import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener; import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider; /** * 刷新布局 * interface of the refresh layout * Created by scwang on 2017/5/26. */ @SuppressWarnings({"UnusedReturnValue", "SameParameterValue", "unused"}) public interface RefreshLayout { /** * Set the Footer's height. * 设置 Footer 的高度 * @param dp Density-independent Pixels 虚拟像素(px需要调用px2dp转换) * @return RefreshLayout */ RefreshLayout setFooterHeight(float dp); /** * 设置 Footer 高度 * @param px 像素 * @return RefreshLayout */ RefreshLayout setFooterHeightPx(int px); /** * Set the Header's height. * 设置 Header 高度 * @param dp Density-independent Pixels 虚拟像素(px需要调用px2dp转换) * @return RefreshLayout */ RefreshLayout setHeaderHeight(float dp); /** * 设置 Header 高度 * @param px 像素 * @return RefreshLayout */ RefreshLayout setHeaderHeightPx(int px); /** * Set the Header's start offset(see srlHeaderInsetStart in the RepastPracticeActivity XML in demo-app for the practical application). * 设置 Header 的起始偏移量(使用方法参考 demo-app 中的 RepastPracticeActivity xml 中的 srlHeaderInsetStart) * @param dp Density-independent Pixels 虚拟像素(px需要调用px2dp转换) * @return RefreshLayout */ RefreshLayout setHeaderInsetStart(float dp); /** * Set the Header's start offset(see srlHeaderInsetStart in the RepastPracticeActivity XML in demo-app for the practical application). * 设置 Header 起始偏移量(使用方法参考 demo-app 中的 RepastPracticeActivity xml 中的 srlHeaderInsetStart) * @param px 像素 * @return RefreshLayout */ RefreshLayout setHeaderInsetStartPx(int px); /** * Set the Footer's start offset. * 设置 Footer 起始偏移量(用处和 setHeaderInsetStart 一样) * @see RefreshLayout#setHeaderInsetStart(float) * @param dp Density-independent Pixels 虚拟像素(px需要调用px2dp转换) * @return RefreshLayout */ RefreshLayout setFooterInsetStart(float dp); /** * Set the Footer's start offset. * 设置 Footer 起始偏移量(用处和 setFooterInsetStartPx 一样) * @param px 像素 * @return RefreshLayout */ RefreshLayout setFooterInsetStartPx(int px); /** * Set the damping effect. * 显示拖动高度/真实拖动高度 比率(默认0.5,阻尼效果) * @param rate ratio = (The drag height of the view)/(The actual drag height of the finger) * 比率 = 视图拖动高度 / 手指拖动高度 * @return RefreshLayout */ RefreshLayout setDragRate(@FloatRange(from = 0, to = 1) float rate); /** * Set the ratio of the maximum height to drag header. * 设置下拉最大高度和Header高度的比率(将会影响可以下拉的最大高度) * @param rate ratio = (the maximum height to drag header)/(the height of header) * 比率 = 下拉最大高度 / Header的高度 * @return RefreshLayout */ RefreshLayout setHeaderMaxDragRate(@FloatRange(from = 1, to = 10) float rate); /** * Set the ratio of the maximum height to drag footer. * 设置上拉最大高度和Footer高度的比率(将会影响可以上拉的最大高度) * @param rate ratio = (the maximum height to drag footer)/(the height of footer) * 比率 = 下拉最大高度 / Footer的高度 * @return RefreshLayout */ RefreshLayout setFooterMaxDragRate(@FloatRange(from = 1, to = 10) float rate); /** * Set the ratio at which the refresh is triggered. * 设置 触发刷新距离 与 HeaderHeight 的比率 * @param rate 触发刷新距离 与 HeaderHeight 的比率 * @return RefreshLayout */ RefreshLayout setHeaderTriggerRate(@FloatRange(from = 0, to = 1.0) float rate); /** * Set the ratio at which the load more is triggered. * 设置 触发加载距离 与 FooterHeight 的比率 * @param rate 触发加载距离 与 FooterHeight 的比率 * @return RefreshLayout */ RefreshLayout setFooterTriggerRate(@FloatRange(from = 0, to = 1.0) float rate); /** * Set the rebound interpolator. * 设置回弹显示插值器 [放手时回弹动画,结束时收缩动画] * @param interpolator 动画插值器 * @return RefreshLayout */ RefreshLayout setReboundInterpolator(@NonNull Interpolator interpolator); /** * Set the duration of the rebound animation. * 设置回弹动画时长 [放手时回弹动画,结束时收缩动画] * @param duration 时长 * @return RefreshLayout */ RefreshLayout setReboundDuration(int duration); /** * Set the footer of RefreshLayout. * 设置指定的 Footer * @param footer RefreshFooter 刷新尾巴 * @return RefreshLayout */ RefreshLayout setRefreshFooter(@NonNull RefreshFooter footer); /** * Set the footer of RefreshLayout. * 设置指定的 Footer * @param footer RefreshFooter 刷新尾巴 * @param width the width in px, can use MATCH_PARENT and WRAP_CONTENT. * 宽度 可以使用 MATCH_PARENT, WRAP_CONTENT * @param height the height in px, can use MATCH_PARENT and WRAP_CONTENT. * 高度 可以使用 MATCH_PARENT, WRAP_CONTENT * @return RefreshLayout */ RefreshLayout setRefreshFooter(@NonNull RefreshFooter footer, int width, int height); /** * Set the header of RefreshLayout. * 设置指定的 Header * @param header RefreshHeader 刷新头 * @return RefreshLayout */ RefreshLayout setRefreshHeader(@NonNull RefreshHeader header); /** * Set the header of RefreshLayout. * 设置指定的 Header * @param header RefreshHeader 刷新头 * @param width the width in px, can use MATCH_PARENT and WRAP_CONTENT. * 宽度 可以使用 MATCH_PARENT, WRAP_CONTENT * @param height the height in px, can use MATCH_PARENT and WRAP_CONTENT. * 高度 可以使用 MATCH_PARENT, WRAP_CONTENT * @return RefreshLayout */ RefreshLayout setRefreshHeader(@NonNull RefreshHeader header, int width, int height); /** * Set the content of RefreshLayout(Suitable for non-XML pages, not suitable for replacing empty layouts)。 * 设置指定的 Content(适用于非XML页面,不适合用替换空布局) * @param content View 内容视图 * @return RefreshLayout */ RefreshLayout setRefreshContent(@NonNull View content); /** * Set the content of RefreshLayout(Suitable for non-XML pages, not suitable for replacing empty layouts). * 设置指定的 Content(适用于非XML页面,不适合用替换空布局) * @param content View 内容视图 * @param width the width in px, can use MATCH_PARENT and WRAP_CONTENT. * 宽度 可以使用 MATCH_PARENT, WRAP_CONTENT * @param height the height in px, can use MATCH_PARENT and WRAP_CONTENT. * 高度 可以使用 MATCH_PARENT, WRAP_CONTENT * @return RefreshLayout */ RefreshLayout setRefreshContent(@NonNull View content, int width, int height); /** * Whether to enable pull-down refresh (enabled by default). * 是否启用下拉刷新(默认启用) * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableRefresh(boolean enabled); /** * Set whether to enable pull-up loading more (enabled by default). * 设置是否启用上拉加载更多(默认启用) * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableLoadMore(boolean enabled); /** * Sets whether to listen for the list to trigger a load event when scrolling to the bottom (default true). * 设置是否监听列表在滚动到底部时触发加载事件(默认true) * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableAutoLoadMore(boolean enabled); /** * Set whether to pull down the content while pulling down the header. * 设置是否启在下拉 Header 的同时下拉内容 * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableHeaderTranslationContent(boolean enabled); /** * Set whether to pull up the content while pulling up the header. * 设置是否启在上拉 Footer 的同时上拉内容 * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableFooterTranslationContent(boolean enabled); /** * Set whether to enable cross-border rebound function. * 设置是否启用越界回弹 * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableOverScrollBounce(boolean enabled); /** * Set whether to enable the pure scroll mode. * 设置是否开启纯滚动模式 * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnablePureScrollMode(boolean enabled); /** * Set whether to scroll the content to display new data after loading more complete. * 设置是否在加载更多完成之后滚动内容显示新数据 * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableScrollContentWhenLoaded(boolean enabled); /** * Set whether to scroll the content to display new data after the refresh is complete. * 是否在刷新完成之后滚动内容显示新数据 * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableScrollContentWhenRefreshed(boolean enabled); /** * Set whether to pull up and load more when the content is not full of one page. * 设置在内容不满一页的时候,是否可以上拉加载更多 * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableLoadMoreWhenContentNotFull(boolean enabled); /** * Set whether to enable cross-border drag (imitation iphone effect). * 设置是否启用越界拖动(仿苹果效果) * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableOverScrollDrag(boolean enabled); /** * Set whether or not Footer follows the content after there is no more data. * 设置是否在没有更多数据之后 Footer 跟随内容 * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableFooterFollowWhenNoMoreData(boolean enabled); /** * Set whether to clip header when the Header is in the FixedBehind state. * 设置是否在当 Header 处于 FixedBehind 状态的时候剪裁遮挡 Header * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableClipHeaderWhenFixedBehind(boolean enabled); /** * Set whether to clip footer when the Footer is in the FixedBehind state. * 设置是否在当 Footer 处于 FixedBehind 状态的时候剪裁遮挡 Footer * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableClipFooterWhenFixedBehind(boolean enabled); /** * Setting whether nesting scrolling is enabled (default off + smart on). * 设置是会否启用嵌套滚动功能(默认关闭+智能开启) * @param enabled 是否启用 * @return RefreshLayout */ RefreshLayout setEnableNestedScroll(boolean enabled); /** * 设置固定在 Header 下方的视图Id,可以在 Footer 上下滚动的时候保持不跟谁滚动 * @param id 固定在头部的视图Id * @return RefreshLayout */ RefreshLayout setFixedHeaderViewId(@IdRes int id); /** * 设置固定在 Footer 上方的视图Id,可以在 Header 上下滚动的时候保持不跟谁滚动 * @param id 固定在底部的视图Id * @return RefreshLayout */ RefreshLayout setFixedFooterViewId(@IdRes int id); /** * 设置在 Header 上下滚动时,需要跟随滚动的视图Id,默认整个内容视图 * @param id 固定在头部的视图Id * @return RefreshLayout */ RefreshLayout setHeaderTranslationViewId(@IdRes int id); /** * 设置在 Footer 上下滚动时,需要跟随滚动的视图Id,默认整个内容视图 * @param id 固定在头部的视图Id * @return RefreshLayout */ RefreshLayout setFooterTranslationViewId(@IdRes int id); /** * Set whether to enable the action content view when refreshing. * 设置是否开启在刷新时候禁止操作内容视图 * @param disable 是否禁止 * @return RefreshLayout */ RefreshLayout setDisableContentWhenRefresh(boolean disable); /** * Set whether to enable the action content view when loading. * 设置是否开启在加载时候禁止操作内容视图 * @param disable 是否禁止 * @return RefreshLayout */ RefreshLayout setDisableContentWhenLoading(boolean disable); /** * Set refresh listener separately. * 单独设置刷新监听器 * @param listener OnRefreshListener 刷新监听器 * @return RefreshLayout */ RefreshLayout setOnRefreshListener(OnRefreshListener listener); /** * Set load more listener separately. * 单独设置加载监听器 * @param listener OnLoadMoreListener 加载监听器 * @return RefreshLayout */ RefreshLayout setOnLoadMoreListener(OnLoadMoreListener listener); /** * Set refresh and load listeners at the same time. * 同时设置刷新和加载监听器 * @param listener OnRefreshLoadMoreListener 刷新加载监听器 * @return RefreshLayout */ RefreshLayout setOnRefreshLoadMoreListener(OnRefreshLoadMoreListener listener); /** * Set up a multi-function listener. * Recommended {@link com.scwang.smart.refresh.layout.simple.SimpleMultiListener} * 设置多功能监听器 * 建议使用 {@link com.scwang.smart.refresh.layout.simple.SimpleMultiListener} * @param listener OnMultiPurposeListener 多功能监听器 * @return RefreshLayout */ RefreshLayout setOnMultiListener(OnMultiListener listener); /** * Set the scroll boundary Decider, Can customize when you can refresh. * Recommended {@link com.scwang.smart.refresh.layout.simple.SimpleBoundaryDecider} * 设置滚动边界判断器 * 建议使用 {@link com.scwang.smart.refresh.layout.simple.SimpleBoundaryDecider} * @param boundary ScrollBoundaryDecider 判断器 * @return RefreshLayout */ RefreshLayout setScrollBoundaryDecider(ScrollBoundaryDecider boundary); /** * Set theme color int (primaryColor and accentColor). * 设置主题颜色 * @param primaryColors ColorInt 主题颜色 * @return RefreshLayout */ RefreshLayout setPrimaryColors(@ColorInt int... primaryColors); /** * Set theme color id (primaryColor and accentColor). * 设置主题颜色 * @param primaryColorId ColorRes 主题颜色ID * @return RefreshLayout */ RefreshLayout setPrimaryColorsId(@ColorRes int... primaryColorId); /** * finish refresh. * 完成刷新 * @return RefreshLayout */ RefreshLayout finishRefresh(); /** * finish refresh. * 完成刷新 * @param delayed 开始延时 * @return RefreshLayout */ RefreshLayout finishRefresh(int delayed); /** * finish refresh. * 完成加载 * @param success 数据是否成功刷新 (会影响到上次更新时间的改变) * @return RefreshLayout */ RefreshLayout finishRefresh(boolean success); /** * finish refresh. * 完成刷新 * @param delayed 开始延时 * @param success 数据是否成功刷新 (会影响到上次更新时间的改变) * @param noMoreData 是否有更多数据 * @return RefreshLayout */ RefreshLayout finishRefresh(int delayed, boolean success, Boolean noMoreData); /** * finish load more with no more data. * 完成刷新并标记没有更多数据 * @return RefreshLayout */ RefreshLayout finishRefreshWithNoMoreData(); /** * finish load more. * 完成加载 * @return RefreshLayout */ RefreshLayout finishLoadMore(); /** * finish load more. * 完成加载 * @param delayed 开始延时 * @return RefreshLayout */ RefreshLayout finishLoadMore(int delayed); /** * finish load more. * 完成加载 * @param success 数据是否成功 * @return RefreshLayout */ RefreshLayout finishLoadMore(boolean success); /** * finish load more. * 完成加载 * @param delayed 开始延时 * @param success 数据是否成功 * @param noMoreData 是否有更多数据 * @return RefreshLayout */ RefreshLayout finishLoadMore(int delayed, boolean success, boolean noMoreData); /** * finish load more with no more data. * 完成加载并标记没有更多数据 * @return RefreshLayout */ RefreshLayout finishLoadMoreWithNoMoreData(); /** * Close the Header or Footer, can't replace finishRefresh and finishLoadMore. * 关闭 Header 或者 Footer * 注意: * 1.closeHeaderOrFooter 任何时候任何状态都能关闭 header 和 footer * 2.finishRefresh 和 finishLoadMore 只能在 刷新 或者 加载 的时候关闭 * @return RefreshLayout */ RefreshLayout closeHeaderOrFooter(); /** * Restore the original state after finishLoadMoreWithNoMoreData. * 设置没有更多数据的状态 * @param noMoreData 是否有更多数据 * @return RefreshLayout * 尽量使用下面三个方法代替,他们可以让状态切换与动画结束合拍 * use {@link RefreshLayout#resetNoMoreData()} * use {@link RefreshLayout#finishRefreshWithNoMoreData()} * use {@link RefreshLayout#finishLoadMoreWithNoMoreData()} */ RefreshLayout setNoMoreData(boolean noMoreData); /** * Restore the original state after finishLoadMoreWithNoMoreData. * 恢复没有更多数据的原始状态 * @return RefreshLayout */ RefreshLayout resetNoMoreData(); /** * Get header of RefreshLayout * 获取当前 Header * @return RefreshLayout */ @Nullable RefreshHeader getRefreshHeader(); /** * Get footer of RefreshLayout * 获取当前 Footer * @return RefreshLayout */ @Nullable RefreshFooter getRefreshFooter(); /** * Get the current state of RefreshLayout * 获取当前状态 * @return RefreshLayout */ @NonNull RefreshState getState(); /** * Get the ViewGroup of RefreshLayout * 获取实体布局视图 * @return ViewGroup */ @NonNull ViewGroup getLayout(); /** * Display refresh animation and trigger refresh event. * 显示刷新动画并且触发刷新事件 * @return true or false, Status non-compliance will fail. * 是否成功(状态不符合会失败) */ boolean autoRefresh(); /** * Display refresh animation and trigger refresh event, Delayed start. * 显示刷新动画并且触发刷新事件,延时启动 * @param delayed 开始延时 * @return true or false, Status non-compliance will fail. * 是否成功(状态不符合会失败) */ boolean autoRefresh(int delayed); /** * Display refresh animation without triggering events. * 显示刷新动画,不触发事件 * @return true or false, Status non-compliance will fail. * 是否成功(状态不符合会失败) */ boolean autoRefreshAnimationOnly(); /** * Display refresh animation, Multifunction. * 显示刷新动画并且触发刷新事件 * @param delayed 开始延时 * @param duration 拖拽动画持续时间 * @param dragRate 拉拽的高度比率 * @param animationOnly animation only 只有动画 * @return true or false, Status non-compliance will fail. * 是否成功(状态不符合会失败) */ boolean autoRefresh(int delayed, int duration, float dragRate, boolean animationOnly); /** * Display load more animation and trigger load more event. * 显示加载动画并且触发刷新事件 * @return true or false, Status non-compliance will fail. * 是否成功(状态不符合会失败) */ boolean autoLoadMore(); /** * Display load more animation and trigger load more event, Delayed start. * 显示加载动画并且触发刷新事件, 延时启动 * @param delayed 开始延时 * @return true or false, Status non-compliance will fail. * 是否成功(状态不符合会失败) */ boolean autoLoadMore(int delayed); /** * Display load more animation without triggering events. * 显示加载动画,不触发事件 * @return true or false, Status non-compliance will fail. * 是否成功(状态不符合会失败) */ boolean autoLoadMoreAnimationOnly(); /** * Display load more animation and trigger load more event, Delayed start. * 显示加载动画, 多功能选项 * @param delayed 开始延时 * @param duration 拖拽动画持续时间 * @param dragRate 拉拽的高度比率 * @param animationOnly 是否只是显示动画,不回调 * @return true or false, Status non-compliance will fail. * 是否成功(状态不符合会失败) */ boolean autoLoadMore(int delayed, int duration, float dragRate, boolean animationOnly); /** * 是否正在刷新 * @return RefreshLayout */ boolean isRefreshing(); /** * 是否正在加载 * @return RefreshLayout */ boolean isLoading(); }
scwang90/SmartRefreshLayout
refresh-layout-kernel/src/main/java/com/scwang/smart/refresh/layout/api/RefreshLayout.java
855
/* * Copyright (C) 2010 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. */ // This is an on-disk cache which maps a 64-bits key to a byte array. // // It consists of three files: one index file and two data files. One of the // data files is "active", and the other is "inactive". New entries are // appended into the active region until it reaches the size limit. At that // point the active file and the inactive file are swapped, and the new active // file is truncated to empty (and the index for that file is also cleared). // The index is a hash table with linear probing. When the load factor reaches // 0.5, it does the same thing like when the size limit is reached. // // The index file format: (all numbers are stored in little-endian) // [0] Magic number: 0xB3273030 // [4] MaxEntries: Max number of hash entries per region. // [8] MaxBytes: Max number of data bytes per region (including header). // [12] ActiveRegion: The active growing region: 0 or 1. // [16] ActiveEntries: The number of hash entries used in the active region. // [20] ActiveBytes: The number of data bytes used in the active region. // [24] Version number. // [28] Checksum of [0..28). // [32] Hash entries for region 0. The size is X = (12 * MaxEntries bytes). // [32 + X] Hash entries for region 1. The size is also X. // // Each hash entry is 12 bytes: 8 bytes key and 4 bytes offset into the data // file. The offset is 0 when the slot is free. Note that 0 is a valid value // for key. The keys are used directly as index into a hash table, so they // should be suitably distributed. // // Each data file stores data for one region. The data file is concatenated // blobs followed by the magic number 0xBD248510. // // The blob format: // [0] Key of this blob // [8] Checksum of this blob // [12] Offset of this blob // [16] Length of this blob (not including header) // [20] Blob // // Below are the interface for BlobCache. The instance of this class does not // support concurrent use by multiple threads. // // public BlobCache(String path, int maxEntries, int maxBytes, boolean reset) throws IOException; // public void insert(long key, byte[] data) throws IOException; // public byte[] lookup(long key) throws IOException; // public void lookup(LookupRequest req) throws IOException; // public void close(); // public void syncIndex(); // public void syncAll(); // public static void deleteFiles(String path); // package net.tsz.afinal.bitmap.core; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.zip.Adler32; import android.util.Log; public class DiskCache implements Closeable { private static final String TAG = DiskCache.class.getSimpleName(); private static final int MAGIC_INDEX_FILE = 0xB3273030; private static final int MAGIC_DATA_FILE = 0xBD248510; // index header offset private static final int IH_MAGIC = 0; private static final int IH_MAX_ENTRIES = 4; private static final int IH_MAX_BYTES = 8; private static final int IH_ACTIVE_REGION = 12; private static final int IH_ACTIVE_ENTRIES = 16; private static final int IH_ACTIVE_BYTES = 20; private static final int IH_VERSION = 24; private static final int IH_CHECKSUM = 28; private static final int INDEX_HEADER_SIZE = 32; private static final int DATA_HEADER_SIZE = 4; // blob header offset private static final int BH_KEY = 0; private static final int BH_CHECKSUM = 8; private static final int BH_OFFSET = 12; private static final int BH_LENGTH = 16; private static final int BLOB_HEADER_SIZE = 20; private RandomAccessFile mIndexFile; private RandomAccessFile mDataFile0; private RandomAccessFile mDataFile1; private FileChannel mIndexChannel; private MappedByteBuffer mIndexBuffer; private int mMaxEntries; private int mMaxBytes; private int mActiveRegion; private int mActiveEntries; private int mActiveBytes; private int mVersion; private RandomAccessFile mActiveDataFile; private RandomAccessFile mInactiveDataFile; private int mActiveHashStart; private int mInactiveHashStart; private byte[] mIndexHeader = new byte[INDEX_HEADER_SIZE]; private byte[] mBlobHeader = new byte[BLOB_HEADER_SIZE]; private Adler32 mAdler32 = new Adler32(); private String mPath; /** * 这里会创建 ".idx"和".0"和".1"文件,".0"和".1"是数据缓存,他们只有一个“激活”状态的,当缓存数据达到用户配置量的时候会清空一个数据,然后切换另一个为“激活”状态 * @param path 缓存路径 * @param maxEntries 存放的最大item 容量 * @param maxBytes 存放的最大数据容量 * @param reset 是否重置,如果true,则先清空所有数据才能使用 * @throws IOException */ public DiskCache(String path, int maxEntries, int maxBytes, boolean reset) throws IOException { this(path, maxEntries, maxBytes, reset, 0); } public DiskCache(String path, int maxEntries, int maxBytes, boolean reset, int version) throws IOException { File dir = new File(path); if(!dir.exists()){ if(!dir.mkdirs()){ throw new IOException("unable to make dirs"); } } mPath = path; mIndexFile = new RandomAccessFile(path + ".idx", "rw"); mDataFile0 = new RandomAccessFile(path + ".0", "rw"); mDataFile1 = new RandomAccessFile(path + ".1", "rw"); mVersion = version; if (!reset && loadIndex()) { return; } resetCache(maxEntries, maxBytes); if (!loadIndex()) { closeAll(); throw new IOException("unable to load index"); } } // Delete the files associated with the given path previously created // by the BlobCache constructor. public void delete(){ deleteFileSilently(mPath + ".idx"); deleteFileSilently(mPath + ".0"); deleteFileSilently(mPath + ".1"); } private static void deleteFileSilently(String path) { try { new File(path).delete(); } catch (Throwable t) { // ignore; } } // Close the cache. All resources are released. No other method should be // called after this is called. @Override public void close() { syncAll(); closeAll(); } private void closeAll() { closeSilently(mIndexChannel); closeSilently(mIndexFile); closeSilently(mDataFile0); closeSilently(mDataFile1); } // Returns true if loading index is successful. After this method is called, // mIndexHeader and index header in file should be kept sync. private boolean loadIndex() { try { mIndexFile.seek(0); mDataFile0.seek(0); mDataFile1.seek(0); byte[] buf = mIndexHeader; if (mIndexFile.read(buf) != INDEX_HEADER_SIZE) { Log.w(TAG, "cannot read header"); return false; } if (readInt(buf, IH_MAGIC) != MAGIC_INDEX_FILE) { Log.w(TAG, "cannot read header magic"); return false; } if (readInt(buf, IH_VERSION) != mVersion) { Log.w(TAG, "version mismatch"); return false; } mMaxEntries = readInt(buf, IH_MAX_ENTRIES); mMaxBytes = readInt(buf, IH_MAX_BYTES); mActiveRegion = readInt(buf, IH_ACTIVE_REGION); mActiveEntries = readInt(buf, IH_ACTIVE_ENTRIES); mActiveBytes = readInt(buf, IH_ACTIVE_BYTES); int sum = readInt(buf, IH_CHECKSUM); if (checkSum(buf, 0, IH_CHECKSUM) != sum) { Log.w(TAG, "header checksum does not match"); return false; } // Sanity check if (mMaxEntries <= 0) { Log.w(TAG, "invalid max entries"); return false; } if (mMaxBytes <= 0) { Log.w(TAG, "invalid max bytes"); return false; } if (mActiveRegion != 0 && mActiveRegion != 1) { Log.w(TAG, "invalid active region"); return false; } if (mActiveEntries < 0 || mActiveEntries > mMaxEntries) { Log.w(TAG, "invalid active entries"); return false; } if (mActiveBytes < DATA_HEADER_SIZE || mActiveBytes > mMaxBytes) { Log.w(TAG, "invalid active bytes"); return false; } if (mIndexFile.length() != INDEX_HEADER_SIZE + mMaxEntries * 12 * 2) { Log.w(TAG, "invalid index file length"); return false; } // Make sure data file has magic byte[] magic = new byte[4]; if (mDataFile0.read(magic) != 4) { Log.w(TAG, "cannot read data file magic"); return false; } if (readInt(magic, 0) != MAGIC_DATA_FILE) { Log.w(TAG, "invalid data file magic"); return false; } if (mDataFile1.read(magic) != 4) { Log.w(TAG, "cannot read data file magic"); return false; } if (readInt(magic, 0) != MAGIC_DATA_FILE) { Log.w(TAG, "invalid data file magic"); return false; } // Map index file to memory mIndexChannel = mIndexFile.getChannel(); mIndexBuffer = mIndexChannel.map(FileChannel.MapMode.READ_WRITE, 0, mIndexFile.length()); mIndexBuffer.order(ByteOrder.LITTLE_ENDIAN); setActiveVariables(); return true; } catch (IOException ex) { Log.e(TAG, "loadIndex failed.", ex); return false; } } private void setActiveVariables() throws IOException { mActiveDataFile = (mActiveRegion == 0) ? mDataFile0 : mDataFile1; mInactiveDataFile = (mActiveRegion == 1) ? mDataFile0 : mDataFile1; mActiveDataFile.setLength(mActiveBytes); mActiveDataFile.seek(mActiveBytes); mActiveHashStart = INDEX_HEADER_SIZE; mInactiveHashStart = INDEX_HEADER_SIZE; if (mActiveRegion == 0) { mInactiveHashStart += mMaxEntries * 12; } else { mActiveHashStart += mMaxEntries * 12; } } private void resetCache(int maxEntries, int maxBytes) throws IOException { mIndexFile.setLength(0); // truncate to zero the index mIndexFile.setLength(INDEX_HEADER_SIZE + maxEntries * 12 * 2); mIndexFile.seek(0); byte[] buf = mIndexHeader; writeInt(buf, IH_MAGIC, MAGIC_INDEX_FILE); writeInt(buf, IH_MAX_ENTRIES, maxEntries); writeInt(buf, IH_MAX_BYTES, maxBytes); writeInt(buf, IH_ACTIVE_REGION, 0); writeInt(buf, IH_ACTIVE_ENTRIES, 0); writeInt(buf, IH_ACTIVE_BYTES, DATA_HEADER_SIZE); writeInt(buf, IH_VERSION, mVersion); writeInt(buf, IH_CHECKSUM, checkSum(buf, 0, IH_CHECKSUM)); mIndexFile.write(buf); // This is only needed if setLength does not zero the extended part. // writeZero(mIndexFile, maxEntries * 12 * 2); mDataFile0.setLength(0); mDataFile1.setLength(0); mDataFile0.seek(0); mDataFile1.seek(0); writeInt(buf, 0, MAGIC_DATA_FILE); mDataFile0.write(buf, 0, 4); mDataFile1.write(buf, 0, 4); } // Flip the active region and the inactive region. private void flipRegion() throws IOException { mActiveRegion = 1 - mActiveRegion; mActiveEntries = 0; mActiveBytes = DATA_HEADER_SIZE; writeInt(mIndexHeader, IH_ACTIVE_REGION, mActiveRegion); writeInt(mIndexHeader, IH_ACTIVE_ENTRIES, mActiveEntries); writeInt(mIndexHeader, IH_ACTIVE_BYTES, mActiveBytes); updateIndexHeader(); setActiveVariables(); clearHash(mActiveHashStart); syncIndex(); } // Sync mIndexHeader to the index file. private void updateIndexHeader() { writeInt(mIndexHeader, IH_CHECKSUM, checkSum(mIndexHeader, 0, IH_CHECKSUM)); mIndexBuffer.position(0); mIndexBuffer.put(mIndexHeader); } // Clear the hash table starting from the specified offset. private void clearHash(int hashStart) { byte[] zero = new byte[1024]; mIndexBuffer.position(hashStart); for (int count = mMaxEntries * 12; count > 0;) { int todo = Math.min(count, 1024); mIndexBuffer.put(zero, 0, todo); count -= todo; } } // Inserts a (key, data) pair into the cache. public void insert(long key, byte[] data) throws IOException { if (DATA_HEADER_SIZE + BLOB_HEADER_SIZE + data.length > mMaxBytes) { throw new RuntimeException("blob is too large!"); } if (mActiveBytes + BLOB_HEADER_SIZE + data.length > mMaxBytes || mActiveEntries * 2 >= mMaxEntries) { flipRegion(); } if (!lookupInternal(key, mActiveHashStart)) { // If we don't have an existing entry with the same key, increase // the entry count. mActiveEntries++; writeInt(mIndexHeader, IH_ACTIVE_ENTRIES, mActiveEntries); } insertInternal(key, data, data.length); updateIndexHeader(); } // Appends the data to the active file. It also updates the hash entry. // The proper hash entry (suitable for insertion or replacement) must be // pointed by mSlotOffset. private void insertInternal(long key, byte[] data, int length) throws IOException { byte[] header = mBlobHeader; int sum = checkSum(data); writeLong(header, BH_KEY, key); writeInt(header, BH_CHECKSUM, sum); writeInt(header, BH_OFFSET, mActiveBytes); writeInt(header, BH_LENGTH, length); mActiveDataFile.write(header); mActiveDataFile.write(data, 0, length); mIndexBuffer.putLong(mSlotOffset, key); mIndexBuffer.putInt(mSlotOffset + 8, mActiveBytes); mActiveBytes += BLOB_HEADER_SIZE + length; writeInt(mIndexHeader, IH_ACTIVE_BYTES, mActiveBytes); } public static class LookupRequest { public long key; // input: the key to find public byte[] buffer; // input/output: the buffer to store the blob public int length; // output: the length of the blob } // This method is for one-off lookup. For repeated lookup, use the version // accepting LookupRequest to avoid repeated memory allocation. private LookupRequest mLookupRequest = new LookupRequest(); public byte[] lookup(long key) throws IOException { mLookupRequest.key = key; mLookupRequest.buffer = null; if (lookup(mLookupRequest)) { return mLookupRequest.buffer; } else { return null; } } // Returns true if the associated blob for the given key is available. // The blob is stored in the buffer pointed by req.buffer, and the length // is in stored in the req.length variable. // // The user can input a non-null value in req.buffer, and this method will // try to use that buffer. If that buffer is not large enough, this method // will allocate a new buffer and assign it to req.buffer. // // This method tries not to throw IOException even if the data file is // corrupted, but it can still throw IOException if things get strange. public boolean lookup(LookupRequest req) throws IOException { // Look up in the active region first. if (lookupInternal(req.key, mActiveHashStart)) { if (getBlob(mActiveDataFile, mFileOffset, req)) { return true; } } // We want to copy the data from the inactive file to the active file // if it's available. So we keep the offset of the hash entry so we can // avoid looking it up again. int insertOffset = mSlotOffset; // Look up in the inactive region. if (lookupInternal(req.key, mInactiveHashStart)) { if (getBlob(mInactiveDataFile, mFileOffset, req)) { // If we don't have enough space to insert this blob into // the active file, just return it. if (mActiveBytes + BLOB_HEADER_SIZE + req.length > mMaxBytes || mActiveEntries * 2 >= mMaxEntries) { return true; } // Otherwise copy it over. mSlotOffset = insertOffset; try { insertInternal(req.key, req.buffer, req.length); mActiveEntries++; writeInt(mIndexHeader, IH_ACTIVE_ENTRIES, mActiveEntries); updateIndexHeader(); } catch (Throwable t) { Log.e(TAG, "cannot copy over"); } return true; } } return false; } // Copies the blob for the specified offset in the specified file to // req.buffer. If req.buffer is null or too small, allocate a buffer and // assign it to req.buffer. // Returns false if the blob is not available (either the index file is // not sync with the data file, or one of them is corrupted). The length // of the blob is stored in the req.length variable. private boolean getBlob(RandomAccessFile file, int offset, LookupRequest req) throws IOException { byte[] header = mBlobHeader; long oldPosition = file.getFilePointer(); try { file.seek(offset); if (file.read(header) != BLOB_HEADER_SIZE) { Log.w(TAG, "cannot read blob header"); return false; } long blobKey = readLong(header, BH_KEY); if (blobKey != req.key) { Log.w(TAG, "blob key does not match: " + blobKey); return false; } int sum = readInt(header, BH_CHECKSUM); int blobOffset = readInt(header, BH_OFFSET); if (blobOffset != offset) { Log.w(TAG, "blob offset does not match: " + blobOffset); return false; } int length = readInt(header, BH_LENGTH); if (length < 0 || length > mMaxBytes - offset - BLOB_HEADER_SIZE) { Log.w(TAG, "invalid blob length: " + length); return false; } if (req.buffer == null || req.buffer.length < length) { req.buffer = new byte[length]; } byte[] blob = req.buffer; req.length = length; if (file.read(blob, 0, length) != length) { Log.w(TAG, "cannot read blob data"); return false; } if (checkSum(blob, 0, length) != sum) { Log.w(TAG, "blob checksum does not match: " + sum); return false; } return true; } catch (Throwable t) { Log.e(TAG, "getBlob failed.", t); return false; } finally { file.seek(oldPosition); } } // Tries to look up a key in the specified hash region. // Returns true if the lookup is successful. // The slot offset in the index file is saved in mSlotOffset. If the lookup // is successful, it's the slot found. Otherwise it's the slot suitable for // insertion. // If the lookup is successful, the file offset is also saved in // mFileOffset. private int mSlotOffset; private int mFileOffset; private boolean lookupInternal(long key, int hashStart) { int slot = (int) (key % mMaxEntries); if (slot < 0) slot += mMaxEntries; int slotBegin = slot; while (true) { int offset = hashStart + slot * 12; long candidateKey = mIndexBuffer.getLong(offset); int candidateOffset = mIndexBuffer.getInt(offset + 8); if (candidateOffset == 0) { mSlotOffset = offset; return false; } else if (candidateKey == key) { mSlotOffset = offset; mFileOffset = candidateOffset; return true; } else { if (++slot >= mMaxEntries) { slot = 0; } if (slot == slotBegin) { Log.w(TAG, "corrupted index: clear the slot."); mIndexBuffer.putInt(hashStart + slot * 12 + 8, 0); } } } } public void syncIndex() { try { mIndexBuffer.force(); } catch (Throwable t) { Log.w(TAG, "sync index failed", t); } } public void syncAll() { syncIndex(); try { mDataFile0.getFD().sync(); } catch (Throwable t) { Log.w(TAG, "sync data file 0 failed", t); } try { mDataFile1.getFD().sync(); } catch (Throwable t) { Log.w(TAG, "sync data file 1 failed", t); } } // This is for testing only. // // Returns the active count (mActiveEntries). This also verifies that // the active count matches matches what's inside the hash region. int getActiveCount() { int count = 0; for (int i = 0; i < mMaxEntries; i++) { int offset = mActiveHashStart + i * 12; // long candidateKey = mIndexBuffer.getLong(offset); int candidateOffset = mIndexBuffer.getInt(offset + 8); if (candidateOffset != 0) ++count; } if (count == mActiveEntries) { return count; } else { Log.e(TAG, "wrong active count: " + mActiveEntries + " vs " + count); return -1; // signal failure. } } int checkSum(byte[] data) { mAdler32.reset(); mAdler32.update(data); return (int) mAdler32.getValue(); } int checkSum(byte[] data, int offset, int nbytes) { mAdler32.reset(); mAdler32.update(data, offset, nbytes); return (int) mAdler32.getValue(); } static void closeSilently(Closeable c) { if (c == null) return; try { c.close(); } catch (Throwable t) { // do nothing } } static int readInt(byte[] buf, int offset) { return (buf[offset] & 0xff) | ((buf[offset + 1] & 0xff) << 8) | ((buf[offset + 2] & 0xff) << 16) | ((buf[offset + 3] & 0xff) << 24); } static long readLong(byte[] buf, int offset) { long result = buf[offset + 7] & 0xff; for (int i = 6; i >= 0; i--) { result = (result << 8) | (buf[offset + i] & 0xff); } return result; } static void writeInt(byte[] buf, int offset, int value) { for (int i = 0; i < 4; i++) { buf[offset + i] = (byte) (value & 0xff); value >>= 8; } } static void writeLong(byte[] buf, int offset, long value) { for (int i = 0; i < 8; i++) { buf[offset + i] = (byte) (value & 0xff); value >>= 8; } } }
yangfuhai/afinal
src/net/tsz/afinal/bitmap/core/DiskCache.java
856
/* There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends. Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students. Example 1: Input: [[1,1,0], [1,1,0], [0,0,1]] Output: 2 Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. The 2nd student himself is in a friend circle. So return 2. Example 2: Input: [[1,1,0], [1,1,1], [0,1,1]] Output: 1 Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends, so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1. Note: N is in range [1,200]. M[i][i] = 1 for all students. If M[i][j] = 1, then M[j][i] = 1. */ /** * Approach: Union Find * 初始情况下有 n 个人,他们互相都是不认识的,每当两个人互相成为朋友,就会形成一个 区域。 * 那么,如果初始情况下有 2 个人,当他们成为朋友之后,就会发生一个 2-1 的操作,使得原本独立的两个人 * 成为了 1 个群体,这个群体可以被认为是一个人。 * 而这其实就是我们 并查集 中的 union 操作。 * 每当两个 独立 群体相互认识的时候,我们只需要将 count-1 即可。 * 并且认识这个动作是相互的,即如果 M[i][j]==1,必定有 M[j][i]==1,因此我们只需要遍历 上半/下半 个三角矩形即可。 * 故这道题目,我们只需要使用 并查集 就能够轻松解决。 */ class Solution { public int findCircleNum(int[][] M) { UnionFind uf = new UnionFind(M.length); for (int i = 0; i < M.length; i++) { for (int j = i + 1; j < M.length; j++) { if (M[i][j] == 1) { uf.union(i, j); } } } return uf.count; } class UnionFind { int[] parent, rank; int count; UnionFind(int n) { parent = new int[n]; rank = new int[n]; count = n; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 1; } } public int compressedFind(int index) { while (index != parent[index]) { parent[index] = parent[parent[index]]; index = parent[index]; } return index; } public void union(int a, int b) { int aFather = compressedFind(a); int bFather = compressedFind(b); if (aFather != bFather) { if (rank[aFather] <= rank[bFather]) { parent[aFather] = bFather; rank[bFather] += rank[aFather]; } else { parent[bFather] = aFather; rank[aFather] += rank[bFather]; } count--; } } } }
cherryljr/LeetCode
Friend Circles.java
858
/** * * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.apdplat.word; import java.io.*; import java.nio.charset.Charset; import java.util.*; import org.apdplat.word.segmentation.SegmentationAlgorithm; import org.apdplat.word.segmentation.SegmentationFactory; import org.apdplat.word.recognition.StopWord; import org.apdplat.word.segmentation.Word; import org.apdplat.word.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 中文分词基础入口 * 默认使用双向最大匹配算法 * 也可指定其他分词算法 * @author 杨尚川 */ public class WordSegmenter { private static final Logger LOGGER = LoggerFactory.getLogger(WordSegmenter.class); /** * 对文本进行分词,保留停用词 * 可指定其他分词算法 * @param text 文本 * @param segmentationAlgorithm 分词算法 * @return 分词结果 */ public static List<Word> segWithStopWords(String text, SegmentationAlgorithm segmentationAlgorithm){ return SegmentationFactory.getSegmentation(segmentationAlgorithm).seg(text); } /** * 对文本进行分词,保留停用词 * 使用双向最大匹配算法 * @param text 文本 * @return 分词结果 */ public static List<Word> segWithStopWords(String text){ return SegmentationFactory.getSegmentation(SegmentationAlgorithm.MaxNgramScore).seg(text); } /** * 对文本进行分词,移除停用词 * 可指定其他分词算法 * @param text 文本 * @param segmentationAlgorithm 分词算法 * @return 分词结果 */ public static List<Word> seg(String text, SegmentationAlgorithm segmentationAlgorithm){ List<Word> words = SegmentationFactory.getSegmentation(segmentationAlgorithm).seg(text); //停用词过滤 StopWord.filterStopWords(words); return words; } /** * 对文本进行分词,移除停用词 * 使用双向最大匹配算法 * @param text 文本 * @return 分词结果 */ public static List<Word> seg(String text){ List<Word> words = SegmentationFactory.getSegmentation(SegmentationAlgorithm.MaxNgramScore).seg(text); //停用词过滤 StopWord.filterStopWords(words); return words; } /** * 对文件进行分词,保留停用词 * 可指定其他分词算法 * @param input 输入文件 * @param output 输出文件 * @param segmentationAlgorithm 分词算法 * @throws Exception */ public static void segWithStopWords(File input, File output, SegmentationAlgorithm segmentationAlgorithm) throws Exception{ Utils.seg(input, output, false, segmentationAlgorithm); } /** * 对文件进行分词,保留停用词 * 使用双向最大匹配算法 * @param input 输入文件 * @param output 输出文件 * @throws Exception */ public static void segWithStopWords(File input, File output) throws Exception{ Utils.seg(input, output, false, SegmentationAlgorithm.MaxNgramScore); } /** * 对文件进行分词,移除停用词 * 可指定其他分词算法 * @param input 输入文件 * @param output 输出文件 * @param segmentationAlgorithm 分词算法 * @throws Exception */ public static void seg(File input, File output, SegmentationAlgorithm segmentationAlgorithm) throws Exception{ Utils.seg(input, output, true, segmentationAlgorithm); } /** * 对文件进行分词,移除停用词 * 使用双向最大匹配算法 * @param input 输入文件 * @param output 输出文件 * @throws Exception */ public static void seg(File input, File output) throws Exception{ Utils.seg(input, output, true, SegmentationAlgorithm.MaxNgramScore); } private static void demo(){ long start = System.currentTimeMillis(); List<String> sentences = new ArrayList<>(); sentences.add("杨尚川是APDPlat应用级产品开发平台的作者"); sentences.add("他说的确实在理"); sentences.add("提高人民生活水平"); sentences.add("他俩儿谈恋爱是从头年元月开始的"); sentences.add("王府饭店的设施和服务是一流的"); sentences.add("和服务于三日后裁制完毕,并呈送将军府中"); sentences.add("研究生命的起源"); sentences.add("他明天起身去北京"); sentences.add("在这些企业中国有企业有十个"); sentences.add("他站起身来"); sentences.add("他们是来查金泰撞人那件事的"); sentences.add("行侠仗义的查金泰远近闻名"); sentences.add("长春市长春节致辞"); sentences.add("他从马上摔下来了,你马上下来一下"); sentences.add("乒乓球拍卖完了"); sentences.add("咬死猎人的狗"); sentences.add("地面积了厚厚的雪"); sentences.add("这几块地面积还真不小"); sentences.add("大学生活象白纸"); sentences.add("结合成分子式"); sentences.add("有意见分歧"); sentences.add("发展中国家兔的计划"); sentences.add("明天他将来北京"); sentences.add("税收制度将来会更完善"); sentences.add("依靠群众才能做好工作"); sentences.add("现在是施展才能的好机会"); sentences.add("把手举起来"); sentences.add("请把手拿开"); sentences.add("这个门把手坏了"); sentences.add("茶杯的把手断了"); sentences.add("将军任命了一名中将"); sentences.add("产量三年中将增长两倍"); sentences.add("以新的姿态出现在世界东方"); sentences.add("使节约粮食进一步形成风气"); sentences.add("反映了一个人的精神面貌"); sentences.add("美国加州大学的科学家发现"); sentences.add("我好不挺好"); sentences.add("木有"); sentences.add("下雨天留客天天留我不留"); sentences.add("叔叔亲了我妈妈也亲了我"); sentences.add("白马非马"); sentences.add("学生会写文章"); sentences.add("张掖市民陈军"); sentences.add("张掖市明乐县"); sentences.add("中华人民共和国万岁万岁万万岁"); sentences.add("word是一个中文分词项目,作者是杨尚川,杨尚川的英文名叫ysc"); sentences.add("江阴毛纺厂成立了保持党员先进性爱国主义学习小组,在江阴道路管理局协助下,通过宝鸡巴士公司,与蒙牛酸酸乳房山分销点组成了开放性交互式的讨论组, 认为google退出中国事件赤裸裸体现了帝国主义的文化侵略,掀起了爱国主义的群众性高潮。"); sentences.add("工信处女干事每月经过下属科室都要亲口交代24口交换机等技术性器件的安装工作"); sentences.add("商品和服务"); sentences.add("结婚的和尚未结婚的"); sentences.add("买水果然后来世博园"); sentences.add("中国的首都是北京"); sentences.add("老师说明天下午休息"); sentences.add("今天下雨"); int i=1; for(String sentence : sentences){ List<Word> words = segWithStopWords(sentence); LOGGER.info((i++)+"、切分句子: "+sentence); LOGGER.info(" 切分结果:"+words); } long cost = System.currentTimeMillis() - start; LOGGER.info("耗时: "+cost+" 毫秒"); } public static void processCommand(String... args) { if(args == null || args.length < 1){ LOGGER.info("命令不正确"); return; } try{ switch(args[0].trim().charAt(0)){ case 'd': demo(); break; case 't': if(args.length < 2){ showUsage(); }else{ StringBuilder str = new StringBuilder(); for(int i=1; i<args.length; i++){ str.append(args[i]).append(" "); } List<Word> words = segWithStopWords(str.toString()); LOGGER.info("切分句子:"+str.toString()); LOGGER.info("切分结果:"+words.toString()); } break; case 'f': if(args.length != 3){ showUsage(); }else{ segWithStopWords(new File(args[1]), new File(args[2])); } break; default: StringBuilder str = new StringBuilder(); for(String a : args){ str.append(a).append(" "); } List<Word> words = segWithStopWords(str.toString()); LOGGER.info("切分句子:"+str.toString()); LOGGER.info("切分结果:"+words.toString()); break; } }catch(Exception e){ showUsage(); } } private static void run(String encoding) { try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, encoding))){ String line = null; while((line = reader.readLine()) != null){ if("exit".equals(line)){ System.exit(0); LOGGER.info("退出"); return; } if(line.trim().equals("")){ continue; } processCommand(line.split(" ")); showUsage(); } } catch (IOException ex) { LOGGER.error("程序中断:", ex); } } private static void showUsage(){ LOGGER.info(""); LOGGER.info("********************************************"); LOGGER.info("用法: command [text] [input] [output]"); LOGGER.info("命令command的可选值为:demo、text、file"); LOGGER.info("命令可使用缩写d t f,如不指定命令,则默认为text命令,对输入的文本分词"); LOGGER.info("demo"); LOGGER.info("text 杨尚川是APDPlat应用级产品开发平台的作者"); LOGGER.info("file d:/text.txt d:/word.txt"); LOGGER.info("exit"); LOGGER.info("********************************************"); LOGGER.info("输入命令后回车确认:"); } public static void main(String[] args) { String encoding = "utf-8"; if(args==null || args.length == 0){ showUsage(); run(encoding); }else if(Charset.isSupported(args[0])){ showUsage(); run(args[0]); }else{ processCommand(args); //非交互模式,退出JVM System.exit(0); } } }
ysc/word
src/main/java/org/apdplat/word/WordSegmenter.java
859
package base; // 如果是 Java 则会抛出空指针异常,但是 Kotlin 不会 // 看下 他们的 字节码区别: /* Kotlin---- public final static main()V L0 LINENUMBER 25 L0 GETSTATIC base/CompareTestKt.num : Ljava/lang/Integer; BIPUSH 42 INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer; IF_ACMPNE L1 L2 LINENUMBER 26 L2 LDC "success" ASTORE 0 Java----- public static void main(java.lang.String[]); Code: 0: getstatic #2 // Field i:Ljava/lang/Integer; 3: invokevirtual #3 // Method java/lang/Integer.intValue:()I 6: bipush 42 8: if_icmpne 19 11: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 14: ldc #5 // String success 16: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 19: return Kotlin 和 Java 的比较机制不一样: Kotlin 是比较两个对象 Java 是比较两个Integer的intValue */ public class CompareTest { private static Integer i; public static void main(String[] args) { if (i == 42) { System.out.println("success"); } } }
chiclaim/AndroidAll
language-kotlin/kotlin-sample/kotlin-in-action/src/base/CompareTest.java
861
package com.java3y.austin.handler.receiver.kafka; import cn.hutool.core.collection.CollUtil; import com.alibaba.fastjson.JSON; import com.java3y.austin.common.domain.RecallTaskInfo; import com.java3y.austin.common.domain.TaskInfo; import com.java3y.austin.handler.receiver.service.ConsumeService; import com.java3y.austin.handler.utils.GroupIdMappingUtils; import com.java3y.austin.support.constans.MessageQueuePipeline; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Scope; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.support.KafkaHeaders; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; /** * @author 3y * 消费MQ的消息 */ @Slf4j @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @ConditionalOnProperty(name = "austin.mq.pipeline", havingValue = MessageQueuePipeline.KAFKA) public class Receiver { @Autowired private ConsumeService consumeService; /** * 发送消息 * * @param consumerRecord * @param topicGroupId */ @KafkaListener(topics = "#{'${austin.business.topic.name}'}", containerFactory = "filterContainerFactory") public void consumer(ConsumerRecord<?, String> consumerRecord, @Header(KafkaHeaders.GROUP_ID) String topicGroupId) { Optional<String> kafkaMessage = Optional.ofNullable(consumerRecord.value()); if (kafkaMessage.isPresent()) { List<TaskInfo> taskInfoLists = JSON.parseArray(kafkaMessage.get(), TaskInfo.class); String messageGroupId = GroupIdMappingUtils.getGroupIdByTaskInfo(CollUtil.getFirst(taskInfoLists.iterator())); /** * 每个消费者组 只消费 他们自身关心的消息 */ if (topicGroupId.equals(messageGroupId)) { consumeService.consume2Send(taskInfoLists); } } } /** * 撤回消息 * * @param consumerRecord */ @KafkaListener(topics = "#{'${austin.business.recall.topic.name}'}", groupId = "#{'${austin.business.recall.group.name}'}", containerFactory = "filterContainerFactory") public void recall(ConsumerRecord<?, String> consumerRecord) { Optional<String> kafkaMessage = Optional.ofNullable(consumerRecord.value()); if (kafkaMessage.isPresent()) { RecallTaskInfo recallTaskInfo = JSON.parseObject(kafkaMessage.get(), RecallTaskInfo.class); consumeService.consume2recall(recallTaskInfo); } } }
ZhongFuCheng3y/austin
austin-handler/src/main/java/com/java3y/austin/handler/receiver/kafka/Receiver.java
862
/* * Copyright DDDplus Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.github.dddplus.annotation; import io.github.dddplus.ext.IIdentityResolver; import org.springframework.stereotype.Component; import java.lang.annotation.*; /** * 业务前台身份,需要实现{@link IIdentityResolver}接口. * <p> * <p>垂直业务是不会叠加的,而是互斥的,他们比较的维度是单一的、固定的</p> */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Component public @interface Partner { /** * 前台垂直业务编号. */ String code(); /** * 前台垂直业务名称. */ String name(); }
funkygao/cp-ddd-framework
dddplus-runtime/src/main/java/io/github/dddplus/annotation/Partner.java
863
package com.baidu.paddle.lite.demo.tts; import android.Manifest; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; public class MainActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, AdapterView.OnItemSelectedListener { public static final int REQUEST_LOAD_MODEL = 0; public static final int REQUEST_RUN_MODEL = 1; public static final int RESPONSE_LOAD_MODEL_SUCCESSED = 0; public static final int RESPONSE_LOAD_MODEL_FAILED = 1; public static final int RESPONSE_RUN_MODEL_SUCCESSED = 2; public static final int RESPONSE_RUN_MODEL_FAILED = 3; public MediaPlayer mediaPlayer = new MediaPlayer(); private static final String TAG = Predictor.class.getSimpleName(); protected ProgressDialog pbLoadModel = null; protected ProgressDialog pbRunModel = null; // Receive messages from worker thread protected Handler receiver = null; // Send command to worker thread protected Handler sender = null; // Worker thread to load&run model protected HandlerThread worker = null; // UI components of image classification protected TextView tvInputSetting; protected TextView tvInferenceTime; protected Button btn_play; protected Button btn_pause; protected Button btn_stop; // Model settings of image classification protected String modelPath = ""; protected int cpuThreadNum = 1; protected String cpuPowerMode = ""; protected Predictor predictor = new Predictor(); int sampleRate = 24000; private final String wavName = "tts_output.wav"; private final String wavFile = Environment.getExternalStorageDirectory() + File.separator + wavName; private final String AMmodelName = "fastspeech2_csmsc_arm.nb"; private final String VOCmodelName = "mb_melgan_csmsc_arm.nb"; private float[] phones = {}; private final float[][] sentencesToChoose = { // 009901 昨日,这名“伤者”与医生全部被警方依法刑事拘留。 {261, 231, 175, 116, 179, 262, 44, 154, 126, 177, 19, 262, 42, 241, 72, 177, 56, 174, 245, 37, 186, 37, 49, 151, 127, 69, 19, 179, 72, 69, 4, 260, 126, 177, 116, 151, 239, 153, 141}, // 009902 钱伟长想到上海来办学校是经过深思熟虑的。 {174, 83, 213, 39, 20, 260, 89, 40, 30, 177, 22, 71, 9, 153, 8, 37, 17, 260, 251, 260, 99, 179, 177, 116, 151, 125, 70, 233, 177, 51, 176, 108, 177, 184, 153, 242, 40, 45}, // 009903 她见我一进门就骂,吃饭时也骂,骂得我抬不起头。 {182, 2, 151, 85, 232, 73, 151, 123, 154, 52, 151, 143, 154, 5, 179, 39, 113, 69, 17, 177, 114, 105, 154, 5, 179, 154, 5, 40, 45, 232, 182, 8, 37, 186, 174, 74, 182, 168}, // 009904 李述德在离开之前,只说了一句“柱驼杀父亲了”。 {153, 74, 177, 186, 40, 42, 261, 10, 153, 73, 152, 7, 262, 113, 174, 83, 179, 262, 115, 177, 230, 153, 45, 73, 151, 242, 180, 262, 186, 182, 231, 177, 2, 69, 186, 174, 124, 153, 45}, // 009905 这种车票和保险单捆绑出售属于重复性购买。 {262, 44, 262, 163, 39, 41, 173, 99, 71, 42, 37, 28, 260, 84, 40, 14, 179, 152, 220, 37, 21, 39, 183, 177, 170, 179, 177, 185, 240, 39, 162, 69, 186, 260, 128, 70, 170, 154, 9}, // 009906 戴佩妮的男友西米露接唱情歌,让她非常开心。 {40, 10, 173, 49, 155, 72, 40, 45, 155, 15, 142, 260, 72, 154, 74, 153, 186, 179, 151, 103, 39, 22, 174, 126, 70, 41, 179, 175, 22, 182, 2, 69, 46, 39, 20, 152, 7, 260, 120}, // 009907 观大势、谋大局、出大策始终是该院的办院方针。 {70, 199, 40, 5, 177, 116, 154, 168, 40, 5, 151, 240, 179, 39, 183, 40, 5, 38, 44, 179, 177, 115, 262, 161, 177, 116, 70, 7, 247, 40, 45, 37, 17, 247, 69, 19, 262, 51}, // 009908 他们骑着摩托回家,正好为农忙时的父母帮忙。 {182, 2, 154, 55, 174, 73, 262, 45, 154, 157, 182, 230, 71, 212, 151, 77, 180, 262, 59, 71, 29, 214, 155, 162, 154, 20, 177, 114, 40, 45, 69, 186, 154, 185, 37, 19, 154, 20}, // 009909 但是因为还没到退休年龄,只能掰着指头捱日子。 {40, 17, 177, 116, 120, 214, 71, 8, 154, 47, 40, 30, 182, 214, 260, 140, 155, 83, 153, 126, 180, 262, 115, 155, 57, 37, 7, 262, 45, 262, 115, 182, 171, 8, 175, 116, 261, 112}, // 009910 这几天雨水不断,人们恨不得待在家里不出门。 {262, 44, 151, 74, 182, 82, 240, 177, 213, 37, 184, 40, 202, 180, 175, 52, 154, 55, 71, 54, 37, 186, 40, 42, 40, 7, 261, 10, 151, 77, 153, 74, 37, 186, 39, 183, 154, 52} }; @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_play: if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); } break; case R.id.btn_pause: if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); } break; case R.id.btn_stop: if (mediaPlayer.isPlaying()) { mediaPlayer.reset(); initMediaPlayer(); } break; default: break; } } private void initMediaPlayer() { try { File file = new File(wavFile); // 指定音频文件的路径 mediaPlayer.setDataSource(file.getPath()); // 让 MediaPlayer 进入到准备状态 mediaPlayer.prepare(); // 该方法使得进入应用时就播放音频 // mediaPlayer.setOnPreparedListener(this); // prepare async to not block main thread mediaPlayer.prepareAsync(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onPrepared(MediaPlayer player) { player.start(); } @Override public boolean onError(MediaPlayer mp, int what, int extra) { // The MediaPlayer has moved to the Error state, must be reset! mediaPlayer.reset(); initMediaPlayer(); return true; } @Override protected void onCreate(Bundle savedInstanceState) { requestAllPermissions(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化控件 Spinner spinner = findViewById(R.id.spinner1); // 建立数据源 String[] sentences = getResources().getStringArray(R.array.text); // 建立 Adapter 并且绑定数据源 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, sentences); // 第一个参数表示在哪个 Activity 上显示,第二个参数是系统下拉框的样式,第三个参数是数组。 spinner.setAdapter(adapter);//绑定Adapter到控件 spinner.setOnItemSelectedListener(this); btn_play = findViewById(R.id.btn_play); btn_pause = findViewById(R.id.btn_pause); btn_stop = findViewById(R.id.btn_stop); btn_play.setOnClickListener(this); btn_pause.setOnClickListener(this); btn_stop.setOnClickListener(this); btn_play.setVisibility(View.INVISIBLE); btn_pause.setVisibility(View.INVISIBLE); btn_stop.setVisibility(View.INVISIBLE); // Clear all setting items to avoid app crashing due to the incorrect settings SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.commit(); // Prepare the worker thread for mode loading and inference receiver = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case RESPONSE_LOAD_MODEL_SUCCESSED: pbLoadModel.dismiss(); onLoadModelSuccessed(); break; case RESPONSE_LOAD_MODEL_FAILED: pbLoadModel.dismiss(); Toast.makeText(MainActivity.this, "Load model failed!", Toast.LENGTH_SHORT).show(); onLoadModelFailed(); break; case RESPONSE_RUN_MODEL_SUCCESSED: pbRunModel.dismiss(); onRunModelSuccessed(); break; case RESPONSE_RUN_MODEL_FAILED: pbRunModel.dismiss(); Toast.makeText(MainActivity.this, "Run model failed!", Toast.LENGTH_SHORT).show(); onRunModelFailed(); break; default: break; } } }; worker = new HandlerThread("Predictor Worker"); worker.start(); sender = new Handler(worker.getLooper()) { public void handleMessage(Message msg) { switch (msg.what) { case REQUEST_LOAD_MODEL: // Load model and reload test image if (onLoadModel()) { receiver.sendEmptyMessage(RESPONSE_LOAD_MODEL_SUCCESSED); } else { receiver.sendEmptyMessage(RESPONSE_LOAD_MODEL_FAILED); } break; case REQUEST_RUN_MODEL: // Run model if model is loaded if (onRunModel()) { receiver.sendEmptyMessage(RESPONSE_RUN_MODEL_SUCCESSED); } else { receiver.sendEmptyMessage(RESPONSE_RUN_MODEL_FAILED); } break; default: break; } } }; // Setup the UI components tvInputSetting = findViewById(R.id.tv_input_setting); tvInferenceTime = findViewById(R.id.tv_inference_time); tvInputSetting.setMovementMethod(ScrollingMovementMethod.getInstance()); } @Override protected void onResume() { super.onResume(); boolean settingsChanged = false; SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String model_path = sharedPreferences.getString(getString(R.string.MODEL_PATH_KEY), getString(R.string.MODEL_PATH_DEFAULT)); settingsChanged |= !model_path.equalsIgnoreCase(modelPath); int cpu_thread_num = Integer.parseInt(sharedPreferences.getString(getString(R.string.CPU_THREAD_NUM_KEY), getString(R.string.CPU_THREAD_NUM_DEFAULT))); settingsChanged |= cpu_thread_num != cpuThreadNum; String cpu_power_mode = sharedPreferences.getString(getString(R.string.CPU_POWER_MODE_KEY), getString(R.string.CPU_POWER_MODE_DEFAULT)); settingsChanged |= !cpu_power_mode.equalsIgnoreCase(cpuPowerMode); if (settingsChanged) { modelPath = model_path; cpuThreadNum = cpu_thread_num; cpuPowerMode = cpu_power_mode; // Update UI tvInputSetting.setText("Model: " + modelPath.substring(modelPath.lastIndexOf("/") + 1) + "\n" + "CPU" + " Thread Num: " + cpuThreadNum + "\n" + "CPU Power Mode: " + cpuPowerMode + "\n"); tvInputSetting.scrollTo(0, 0); // Reload model if configure has been changed loadModel(); } } public void loadModel() { pbLoadModel = ProgressDialog.show(this, "", "Loading model...", false, false); sender.sendEmptyMessage(REQUEST_LOAD_MODEL); } public void runModel() { pbRunModel = ProgressDialog.show(this, "", "Running model...", false, false); sender.sendEmptyMessage(REQUEST_RUN_MODEL); } public boolean onLoadModel() { return predictor.init(MainActivity.this, modelPath, AMmodelName, VOCmodelName, cpuThreadNum, cpuPowerMode); } public boolean onRunModel() { return predictor.isLoaded() && predictor.runModel(phones); } public boolean onLoadModelSuccessed() { // Load test image from path and run model // runModel(); return true; } public void onLoadModelFailed() { } public void onRunModelSuccessed() { // Obtain results and update UI btn_play.setVisibility(View.VISIBLE); btn_pause.setVisibility(View.VISIBLE); btn_stop.setVisibility(View.VISIBLE); tvInferenceTime.setText("Inference done!\nInference time: " + predictor.inferenceTime() + " ms" + "\nRTF: " + predictor.inferenceTime() * sampleRate / (predictor.wav.length * 1000) + "\nAudio saved in " + wavFile); try { Utils.rawToWave(wavFile, predictor.wav, sampleRate); } catch (IOException e) { e.printStackTrace(); } if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } else { // 初始化 MediaPlayer initMediaPlayer(); } } public void onRunModelFailed() { } public void onSettingsClicked() { startActivity(new Intent(MainActivity.this, SettingsActivity.class)); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_action_options, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.settings: onSettingsClicked(); } return super.onOptionsItemSelected(item); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show(); } } @Override protected void onDestroy() { if (predictor != null) { predictor.releaseModel(); } worker.quit(); super.onDestroy(); if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } } private boolean requestAllPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0); return false; } return true; } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position > 0) { phones = sentencesToChoose[position - 1]; runModel(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }
PaddlePaddle/PaddleSpeech
demos/TTSAndroid/app/src/main/java/com/baidu/paddle/lite/demo/tts/MainActivity.java
864
/* * Copyright DDDplus Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ /** * Reverse modeling DSL: Object-Oriented Domain Model(As-Is -> To-Be) Re-Design without tech constraints. * <p/> * <p>背景:好的业务模型不仅对产品架构、开发有重大意义,也能够快速的帮助客户分析管理上的不足、业务处理上的漏洞、不合理需求的悖论等.</p> * <p>目标:提供一套模型描述语言,从代码提炼精粹的业务知识,指导并约束模型和系统演进.</p> * <p>路径:明确业务中关键问题,跨越(架构约束,技术限制)等造成代码难以直观表达模型的问题,面向对象地抽取和修正,形成与正向模型正反馈闭环.</p> * <p>价值:通过逆向工程方法揭示代码实现里体现的核心领域问题,发现{@code essential problems}:一方面关联代码实现,一方面关联通用语言.</p> * <p/> * <p>《架构整洁之道》中的定义:软件架构是指设计软件的人为软件赋予的形状。</p> * <p>DSL标注过程,是无技术约束的OO二次设计的过程,是re-shape your code过程,是architecture discovery过程.</p> * <p>DSL标注过程,是Declarative Programming,而非Imperative Programming,关注描述问题和规则,而非实现步骤.</p> * <p>DSL标注过程,是对当前代码进行声明式编程的二次创作过程,它描述的问题的空间结构,结合版本控制就体现了时间维度.</p> * <p>DSL标注过程,是把领域知识注入代码的过程.</p> * <p>由于代码具有(可运行,包含完全细节,演进过程完整追溯,自我修复)特征,因此成为业务的唯一事实真相;但代码里有太多技术细节产生的业务模型噪音,导致代码里无法直观看到业务真相.</p> * <p>{@code 建模 = 图形 + 逻辑 + 现实的抽象},代码(一维的,局部的),而模型(多维立体的,全局的),逆向模型相当于动态的活地图</p> * <p>通过该DSL建立的逆向模型,(业务强相关,代码强相关),它完成了业务与代码双向映射,最终实现(业务模型,代码实现)的持续一致.</p> * <blockquote cite="Martin Fowler 1996 《Analysis Patterns: Reusable Object Models》"> * Although much of the attention in business engineering is about process, most of these patterns are static type models. I like to think of type models as defining the language of the business. These models thus provide a way of coming up with useful concepts that underlie a great deal of the process modeling. * 在面向对象开发过程中很重要的原则:要设计软件,使得软件的结构反映问题的结构。 * </blockquote> * <pre> * DomainModel --> CodeImplementation * ^ | * | V * KnowledgeCrunch <-- ReversedDomainModel * </pre> * <p/> * <ul>DSL能力: * <li>字段级: * <ul> * <li>{@link io.github.dddplus.dsl.KeyElement}</li> * </ul> * </li> * <li>方法级: * <ul> * <li>{@link io.github.dddplus.dsl.KeyRule}</li> * <li>{@link io.github.dddplus.dsl.KeyBehavior}</li> * <li>{@link io.github.dddplus.dsl.KeyFlow}</li> * </ul> * </li> * <li>类级: * <ul> * <li>{@link io.github.dddplus.dsl.KeyRelation}</li> * <li>{@link io.github.dddplus.dsl.KeyEvent}</li> * <li>{@link io.github.dddplus.dsl.IVirtualModel}</li> * </ul> * </li> * <li>包级: * <ul> * <li>{@link io.github.dddplus.dsl.Aggregate}</li> * </ul> * </li> * </ul> * <ul>DSL提供的代码模型修正机制: * <li>显式标注,不标注则视为非模型要素</li> * <li>{@link io.github.dddplus.dsl.KeyElement#name()},{@link io.github.dddplus.dsl.KeyBehavior#name()}等,修正关键概念名称</li> * <li>{@link io.github.dddplus.dsl.KeyFlow#actor()},重新分配行为职责</li> * <li>{@link io.github.dddplus.dsl.IVirtualModel},识别代码里缺失的关键职责对象,并在模型层建立</li> * </ul> * <p/> * <ul>如何评估模型质量?两大标准:1)拟合现状 2)预测未来 * <li>模型是否直观完整表达出了业务核心知识</li> * <li>产品、业务方是否能看懂</li> * <li>日常开发,是否{@code 从模型中来,到模型中去}闭环</li> * </ul> * <ul>如何使用模型?模型驱动开发: * <li>业务需求 -> 从模型入手 -> 模型修改 -> 设计评审 -> 代码实现(依据活地图) -> 自动生成逆向模型,验证设计与实现一致性</li> * <li>围绕模型,持续构造易于维护的软件 * <ul>理解了模型 * <li>就大致理解了代码结构</li> * <li>讨论需求时,研发就能容易明白需要改动的代码,评估工期和风险</li> * <li>改功能就是改模型,改模型就等同于改代码,改代码就是改模型</li> * </ul> * </li> * <li>使用该模型的典型场景: * <ul> * <li>我在网上看到一个开源ERP系统,如何快速掌握其核心设计?</li> * <li>我是业务中台负责人,在与多条线BP合作扩展开发时,他们如何快速掌握我的设计,如何快速承接业务开发</li> * <li>公司新找一批外包人员,如何让他们了解系统</li> * <li>(业务方,产品,研发,架构),他们统一的模型张什么样,它存在吗</li> * <li>我是架构师,新进入一个团队,里面有十几个大型遗留系统,如何快速掌握它们,并识别核心问题</li> * </ul> * </li> * </ul> * <ul>与{@code ArchiMate}/{@code BPMN}/{@code C4 Model}/{@code UML}/{@code TOGAF ADM}/{@code SysML}/{@code 4+1 View Model}等架构模型语言相比,本{@code DSL}: * <li>简单,门槛低</li> * <li>与代码强关联</li> * <li>具有修正机制</li> * </ul> * <ul>FAQ of the DSL: * <li>它在揭示整体结构上表现很好,但貌似缺乏要素间通信的表达力? * <ul> * <li>{@code DDDplus} is not going to re-invent the wheel</li> * <li>{@code IDEA Sequence Diagram plugin}/BPMN等工具已经具备这类能力</li> * <li>{@code CallGraphReport}会绘制关键方法的调用关系</li> * </ul> * </li> * <li>业务约束/规则上貌似只是罗列,缺少场景表现力? * <ul> * <li>{@link io.github.dddplus.model.spcification.ISpecification}已经可以自动追溯了,因此没必要在逆向模型里体现,否则只会产生不必要噪音</li> * <li>可视化的前提是:它真的可视</li> * </ul> * </li> * <li>扩展能力如何可视化表达? * <ul> * <li>已经有了,please see {@code DomainArtifacts}</li> * </ul> * </li> * <li>逆向模型貌似已经把代码变成结构化的数据了,我可以保存到数据库以产生下游应用吗? * <ul> * <li>Sure!</li> * <li>please see {@code ReverseEngineeringModel},which can be defined with multiple RDBMS tables</li> * </ul> * </li> * </ul> * * @see <a href="https://xie.infoq.cn/article/3da89918c7d27ccc8e8f98ab7">面向对象设计的逆向建模方法和开源工具</a> * @see <a href="https://ieeexplore.ieee.org/document/723185/">Requirements for integrating software architecture and reengineering models</a> * @see <a href="http://www.jos.org.cn/jos/article/pdf/6278">面向领域驱动设计的逆向建模支持方法</a> * @see <a href="https://www.eclipse.org/MoDisco/">MoDisco</a> */ package io.github.dddplus.dsl;
funkygao/cp-ddd-framework
dddplus-spec/src/main/java/io/github/dddplus/dsl/package-info.java
865
package com.xuexiang.xuidemo; import android.content.Context; import android.graphics.drawable.Drawable; import androidx.viewpager.widget.ViewPager; import com.google.gson.reflect.TypeToken; import com.kunminx.linkage.bean.DefaultGroupedItem; import com.xuexiang.xaop.annotation.MemoryCache; import com.xuexiang.xui.adapter.simple.AdapterItem; import com.xuexiang.xui.adapter.simple.ExpandableItem; import com.xuexiang.xui.utils.ResUtils; import com.xuexiang.xui.widget.banner.transform.DepthTransformer; import com.xuexiang.xui.widget.banner.transform.FadeSlideTransformer; import com.xuexiang.xui.widget.banner.transform.FlowTransformer; import com.xuexiang.xui.widget.banner.transform.RotateDownTransformer; import com.xuexiang.xui.widget.banner.transform.RotateUpTransformer; import com.xuexiang.xui.widget.banner.transform.ZoomOutSlideTransformer; import com.xuexiang.xui.widget.banner.widget.banner.BannerItem; import com.xuexiang.xui.widget.imageview.nine.NineGridImageView; import com.xuexiang.xuidemo.adapter.entity.NewInfo; import com.xuexiang.xuidemo.adapter.entity.StickyItem; import com.xuexiang.xuidemo.fragment.components.imageview.preview.ImageViewInfo; import com.xuexiang.xuidemo.fragment.components.imageview.preview.NineGridInfo; import com.xuexiang.xuidemo.fragment.components.pickerview.ProvinceInfo; import com.xuexiang.xuidemo.fragment.components.tabbar.tabsegment.MultiPage; import com.xuexiang.xuidemo.fragment.expands.linkage.custom.CustomGroupedItem; import com.xuexiang.xuidemo.fragment.expands.linkage.eleme.ElemeGroupedItem; import com.xuexiang.xutil.net.JsonUtil; import com.xuexiang.xutil.resource.ResourceUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * 演示数据 * * @author xuexiang * @since 2018/11/23 下午5:52 */ public class DemoDataProvider { public static String[] titles = new String[]{ "伪装者:胡歌演绎'痞子特工'", "无心法师:生死离别!月牙遭虐杀", "花千骨:尊上沦为花千骨", "综艺饭:胖轩偷看夏天洗澡掀波澜", "碟中谍4:阿汤哥高塔命悬一线,超越不可能", }; public static String[] urls = new String[]{//640*360 360/640=0.5625 "http://photocdn.sohu.com/tvmobilemvms/20150907/144160323071011277.jpg",//伪装者:胡歌演绎"痞子特工" "http://photocdn.sohu.com/tvmobilemvms/20150907/144158380433341332.jpg",//无心法师:生死离别!月牙遭虐杀 "http://photocdn.sohu.com/tvmobilemvms/20150907/144160286644953923.jpg",//花千骨:尊上沦为花千骨 "http://photocdn.sohu.com/tvmobilemvms/20150902/144115156939164801.jpg",//综艺饭:胖轩偷看夏天洗澡掀波澜 "http://photocdn.sohu.com/tvmobilemvms/20150907/144159406950245847.jpg",//碟中谍4:阿汤哥高塔命悬一线,超越不可能 }; public static List<BannerItem> getBannerList() { ArrayList<BannerItem> list = new ArrayList<>(); for (int i = 0; i < urls.length; i++) { BannerItem item = new BannerItem(); item.imgUrl = urls[i]; item.title = titles[i]; list.add(item); } return list; } public static List<AdapterItem> getGridItems(Context context) { return getGridItems(context, R.array.grid_titles_entry, R.array.grid_icons_entry); } private static List<AdapterItem> getGridItems(Context context, int titleArrayId, int iconArrayId) { List<AdapterItem> list = new ArrayList<>(); String[] titles = ResUtils.getStringArray(context, titleArrayId); Drawable[] icons = ResUtils.getDrawableArray(context, iconArrayId); for (int i = 0; i < titles.length; i++) { list.add(new AdapterItem(titles[i], icons[i])); } return list; } public static List<Object> getUserGuides() { List<Object> list = new ArrayList<>(); list.add(R.drawable.guide_img_1); list.add(R.drawable.guide_img_2); list.add(R.drawable.guide_img_3); list.add(R.drawable.guide_img_4); return list; } public static Class<? extends ViewPager.PageTransformer>[] transformers = new Class[]{ DepthTransformer.class, FadeSlideTransformer.class, FlowTransformer.class, RotateDownTransformer.class, RotateUpTransformer.class, ZoomOutSlideTransformer.class, }; public static String[] dpiItems = new String[]{ "480 × 800", "1080 × 1920", "720 × 1280", }; public static AdapterItem[] menuItems = new AdapterItem[]{ new AdapterItem("登陆", R.drawable.icon_password_login), new AdapterItem("筛选", R.drawable.icon_filter), new AdapterItem("设置", R.drawable.icon_setting), }; public static ExpandableItem[] expandableItems = new ExpandableItem[]{ ExpandableItem.of(new AdapterItem("屏幕尺寸", R.drawable.icon_password_login)).addChild(AdapterItem.arrayof(dpiItems)), ExpandableItem.of(new AdapterItem("设备亮度", R.drawable.icon_filter)).addChild(menuItems), ExpandableItem.of(new AdapterItem("屏幕分辨率", R.drawable.icon_setting)).addChild(AdapterItem.arrayof(dpiItems)) }; public static List<List<ImageViewInfo>> sPics; public static List<List<ImageViewInfo>> sVideos; public static List<ImageViewInfo> imgs; public static List<ImageViewInfo> videos; public static List<List<NineGridInfo>> sNineGridPics; public static List<List<NineGridInfo>> sNineGridVideos; static { imgs = new ArrayList<>(); List<String> list = getUrls(); for (int i = 0; i < list.size(); i++) { imgs.add(new ImageViewInfo(list.get(i))); } videos = getVideos(); sPics = split(imgs, 10); sVideos = split(videos, 10); sNineGridPics = split(getMediaDemos(40, 0), 10); sNineGridVideos = split(getMediaDemos(20, 1), 10); } private static List<NineGridInfo> getMediaDemos(int length, int type) { List<NineGridInfo> list = new ArrayList<>(); NineGridInfo info; for (int i = 0; i < length; i++) { info = new NineGridInfo("我是一只喵,快乐的星猫~~~", getRandomMedias((int) (Math.random() * 10 + 0.5), type)) .setShowType(NineGridImageView.STYLE_FILL); list.add(info); } return list; } private static List<ImageViewInfo> getRandomMedias(int length, int type) { List<ImageViewInfo> list = new ArrayList<>(); for (int i = 0; i < length; i++) { if (type == 0) { list.add(imgs.get(i)); } else { list.add(videos.get(i)); } } return list; } private static List<ImageViewInfo> getVideos() { List<ImageViewInfo> videos = new ArrayList<>(); videos.add(new ImageViewInfo("http://lmp4.vjshi.com/2017-09-13/f55a900d89679ac1c9837d5b5aaf632a.mp4", "http://pic.vjshi.com/2017-09-13/f55a900d89679ac1c9837d5b5aaf632a/online/puzzle.jpg?x-oss-process=style/resize_w_285_crop_h_428")); videos.add(new ImageViewInfo("http://lmp4.vjshi.com/2017-09-13/f55a900d89679ac1c9837d5b5aaf632a.mp4", "http://pic.vjshi.com/2017-05-25/b146e104069c2bd0590bb919269193c4/online/puzzle.jpg?x-oss-process=style/resize_w_285_crop_h_428")); videos.add(new ImageViewInfo("http://ac-QYgvX1CC.clouddn.com/36f0523ee1888a57.jpg")); videos.add(new ImageViewInfo("http://lmp4.vjshi.com/2017-05-07/d0bbfc4ac4dd173cc93873ed4eb0be53.mp4", "http://pic.vjshi.com/2017-05-07/d0bbfc4ac4dd173cc93873ed4eb0be53/online/puzzle.jpg?x-oss-process=style/resize_w_285_crop_h_428")); videos.add(new ImageViewInfo("http://lmp4.vjshi.com/2017-07-18/80d08ce1a84adfbaed5c7067b73d19ed.mp4", "http://pic.vjshi.com/2017-07-18/80d08ce1a84adfbaed5c7067b73d19ed/online/puzzle.jpg?x-oss-process=style/resize_w_285_crop_h_428")); videos.add(new ImageViewInfo("http://img0.imgtn.bdimg.com/it/u=556618733,1205300389&fm=21&gp=0.jpg")); videos.add(new ImageViewInfo("http://lmp4.vjshi.com/2017-09-13/f55a900d89679ac1c9837d5b5aaf632a.mp4", "http://pic.vjshi.com/2017-09-13/f55a900d89679ac1c9837d5b5aaf632a/online/puzzle.jpg?x-oss-process=style/resize_w_285_crop_h_428")); videos.add(new ImageViewInfo("http://img0.imgtn.bdimg.com/it/u=556618733,1205300389&fm=21&gp=0.jpg")); videos.add(new ImageViewInfo("http://lmp4.vjshi.com/2018-06-07/cf673556cce54ab9cf4633fd7d9d0d46.mp4", "http://pic.vjshi.com/2018-06-06/caa296729c8e6e41e6aff2aadf4feff3/online/puzzle.jpg?x-oss-process=style/resize_w_285_crop_h_428")); videos.add(new ImageViewInfo("http://img44.photophoto.cn/20170730/0018090594006661_s.jpg")); videos.add(new ImageViewInfo("http://lmp4.vjshi.com/2017-09-13/f55a900d89679ac1c9837d5b5aaf632a.mp4", "http://pic.vjshi.com/2017-09-13/f55a900d89679ac1c9837d5b5aaf632a/online/puzzle.jpg?x-oss-process=style/resize_w_285_crop_h_428")); videos.add(new ImageViewInfo("http://ac-QYgvX1CC.clouddn.com/36f0523ee1888a57.jpg")); videos.add(new ImageViewInfo("http://lmp4.vjshi.com/2018-01-27/5169bb7bdd7386ce7bd4ce1739229424.mp4", "http://pic.vjshi.com/2018-01-27/5169bb7bdd7386ce7bd4ce1739229424/online/puzzle.jpg?x-oss-process=style/resize_w_285_crop_h_428")); videos.add(new ImageViewInfo("http://photocdn.sohu.com/20160307/mp62252655_1457334772519_2.png")); videos.add(new ImageViewInfo("http://lmp4.vjshi.com/2017-09-27/9a6e69f7c257ff7b7832e8bac6fddf82.mp4", "http://pic.vjshi.com/2017-09-27/9a6e69f7c257ff7b7832e8bac6fddf82/online/puzzle.jpg?x-oss-process=style/resize_w_285_crop_h_428")); videos.add(new ImageViewInfo("http://photocdn.sohu.com/20160307/mp62252655_1457334772519_2.png")); return videos; } private static List<String> getUrls() { List<String> urls = new ArrayList<>(); urls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1605454727961&di=523c0cbc27edf8c9c4dfc705c395f910&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw640h360%2F20180204%2Fe374-fyrhcqy4449849.jpg"); urls.add("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=141294069,864810829&fm=26&gp=0.jpg"); urls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1605454727960&di=cf69e23566394467534c9606e1f65555&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201707%2F03%2F20170703232714_njuTy.jpeg"); urls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1605454727923&di=6b54cc07f6e1aea9ffbdc85348454d8c&imgtype=0&src=http%3A%2F%2Fcdn.duitang.com%2Fuploads%2Fitem%2F201203%2F23%2F20120323140617_ZcAw3.jpeg"); urls.add("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1107220453,145887914&fm=26&gp=0.jpg"); urls.add("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2860640912,1833965317&fm=26&gp=0.jpg"); urls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1605454900301&di=1168cceb30a3e19b6260a2d7f3ab68f4&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201609%2F24%2F20160924221133_w5Ysc.thumb.700_0.jpeg"); urls.add("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3933345026,3409802114&fm=26&gp=0.jpg"); urls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1605454900300&di=47cb3c09f5f02b89942bfda02b4c6c5a&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201611%2F18%2F20161118171843_JGHBz.thumb.700_0.jpeg"); urls.add("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2065870676,3251648368&fm=26&gp=0.jpg"); urls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1605454988368&di=b0002ea6a6ed0d054a57693bb0849076&imgtype=0&src=http%3A%2F%2Fimg.mp.itc.cn%2Fupload%2F20170318%2Fa5e5eb349b80486e949e8919278ef172_th.jpg"); urls.add("http://img1.imgtn.bdimg.com/it/u=3272030875,860665188&fm=21&gp=0.jpg"); urls.add("http://img1.imgtn.bdimg.com/it/u=2237658959,3726297486&fm=21&gp=0.jpg"); urls.add("http://img1.imgtn.bdimg.com/it/u=3016675040,1510439865&fm=21&gp=0.jpg"); urls.add("http://photocdn.sohu.com/20160307/mp62252655_1457334772519_2.png"); urls.add("http://d040779c2cd49.scdn.itc.cn/s_big/pic/20161213/184474627873966848.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/36f0523ee1888a57.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/07915a0154ac4a64.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/9ec4bc44bfaf07ed.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/fa85037f97e8191f.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/de13315600ba1cff.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/9ec4bc44bfaf07ed.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/fa85037f97e8191f.jpg"); urls.add("ttp://ac-QYgvX1CC.clouddn.com/de13315600ba1cff.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/ad99de83e1e3f7d4.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/15c5c50e941ba6b0.jpg"); urls.add("http://ac-QYgvX1CC.clouddn.com/eaf1c9d55c5f9afd.jpg"); urls.add("http://pic44.photophoto.cn/20170802/0017030376585114_b.jpg"); urls.add("http://img44.photophoto.cn/20170727/0847085702814554_s.jpg"); urls.add("http://img44.photophoto.cn/20170802/0017030319134956_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0838084023987260_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0838084009134421_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0838084002855326_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0847085207211178_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0017030319740534_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0838084002855326_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085969586424_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0014105802293676_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0847085242661101_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0886088744582079_s.jpg"); urls.add("http://img44.photophoto.cn/20170801/0017029514287804_s.jpg"); urls.add("http://img44.photophoto.cn/20170730/0018090594006661_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085848134910_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085581124963_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085226124343_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085226124343_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085200668628_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085246003750_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085012707934_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0005018303330857_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085231427344_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085236829578_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085729490157_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0847085751995287_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085729043617_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085786392651_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085761440022_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0847085275244570_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085858434984_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085781987193_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085707961800_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085229451104_s.jpg"); urls.add("http://img44.photophoto.cn/20170720/0847085716198074_s.jpg"); urls.add("http://img44.photophoto.cn/20170720/0847085769259426_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085717385169_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085757949071_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085789079771_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085229451104_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085757949071_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085265005650_s.jpg"); urls.add("http://img44.photophoto.cn/20170730/0008118269110532_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0008118203762697_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0008118269666722_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085858434984_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085781987193_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085707961800_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085229451104_s.jpg"); urls.add("http://img44.photophoto.cn/20170720/0847085716198074_s.jpg"); urls.add("http://img44.photophoto.cn/20170720/0847085769259426_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085717385169_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085757949071_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085789079771_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085229451104_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085757949071_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085265005650_s.jpg"); urls.add("http://img44.photophoto.cn/20170730/0008118269110532_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0008118203762697_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0008118269666722_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085858434984_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085781987193_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085707961800_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085229451104_s.jpg"); urls.add("http://img44.photophoto.cn/20170720/0847085716198074_s.jpg"); urls.add("http://img44.photophoto.cn/20170720/0847085769259426_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085717385169_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085757949071_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085789079771_s.jpg"); urls.add("http://img44.photophoto.cn/20170722/0847085229451104_s.jpg"); urls.add("http://img44.photophoto.cn/20170721/0847085757949071_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085265005650_s.jpg"); urls.add("http://img44.photophoto.cn/20170730/0008118269110532_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0008118203762697_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0008118269666722_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0847085207211178_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0017030319740534_s.jpg"); urls.add("http://img44.photophoto.cn/20170731/0838084002855326_s.jpg"); urls.add("http://img44.photophoto.cn/20170728/0847085969586424_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0014105802293676_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0847085242661101_s.jpg"); urls.add("http://img44.photophoto.cn/20170727/0886088744582079_s.jpg"); urls.add("http://img44.photophoto.cn/20170801/0017029514287804_s.jpg"); urls.add("http://img44.photophoto.cn/20170730/0018090594006661_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085848134910_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085581124963_s.jpg"); urls.add("http://img44.photophoto.cn/20170729/0847085226124343_s.jpg"); return urls; } public static List<ImageViewInfo> getGifUrls() { List<ImageViewInfo> userViewInfos = new ArrayList<>(); userViewInfos.add(new ImageViewInfo("http://img.soogif.com/8Q8Vy8jh6wEYCT4bYiEAOZdmzIf7GrLQ.gif_s400x0")); userViewInfos.add(new ImageViewInfo("http://img.soogif.com/yCPIVl3icfbIhZ1rjKKU6Kl6lCKkC8Wq.gif_s400x0")); userViewInfos.add(new ImageViewInfo("http://img.soogif.com/mQK3vlOYVOIpnhNYKg6XuWqpc3yAg9hR.gif_s400x0")); userViewInfos.add(new ImageViewInfo("http://img.soogif.com/mESQBeZn5V8Xzke0XPsnEEXUF9MaU3sA.gif_s400x0")); userViewInfos.add(new ImageViewInfo("http://img.soogif.com/HFuVvydFj7dgIEcbEBMA9ccGcGOFdEsx.gif_s400x0")); userViewInfos.add(new ImageViewInfo("http://img.soogif.com/SH0FB6FnTNgoCsVtxcAMtSNfV7XxXmo8.gif")); userViewInfos.add(new ImageViewInfo("http://img.soogif.com/KkB9WARG3PFrz9EEX4DJdiy6Vyg95fGl.gif")); return userViewInfos; } /** * 拆分集合 * * @param <T> * @param resList 要拆分的集合 * @param count 每个集合的元素个数 * @return 返回拆分后的各个集合 */ public static <T> List<List<T>> split(List<T> resList, int count) { if (resList == null || count < 1) { return null; } List<List<T>> ret = new ArrayList<>(); int size = resList.size(); if (size <= count) { //数据量不足count指定的大小 ret.add(resList); } else { int pre = size / count; int last = size % count; //前面pre个集合,每个大小都是count个元素 for (int i = 0; i < pre; i++) { List<T> itemList = new ArrayList<>(); for (int j = 0; j < count; j++) { itemList.add(resList.get(i * count + j)); } ret.add(itemList); } //last的进行处理 if (last > 0) { List<T> itemList = new ArrayList<>(); for (int i = 0; i < last; i++) { itemList.add(resList.get(pre * count + i)); } ret.add(itemList); } } return ret; } @MemoryCache public static Collection<String> getDemoData() { return Arrays.asList("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""); } @MemoryCache public static Collection<String> getDemoData1() { return Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"); } /** * 用于占位的空信息 * * @return */ @MemoryCache public static List<NewInfo> getEmptyNewInfo() { List<NewInfo> list = new ArrayList<>(); for (int i = 0; i < 5; i++) { list.add(new NewInfo()); } return list; } @MemoryCache public static List<StickyItem> getStickyDemoData() { List<StickyItem> list = new ArrayList<>(); List<StickyItem> temp = new ArrayList<>(); List<NewInfo> news = DemoDataProvider.getDemoNewInfos(); for (NewInfo newInfo : news) { temp.add(new StickyItem(newInfo)); } for (String page : MultiPage.getPageNames()) { list.add(new StickyItem(page)); list.addAll(temp); } list.add(new StickyItem("测试")); list.addAll(temp.subList(0, 3)); return list; } /** * 用于占位的空信息 * * @return */ @MemoryCache public static List<NewInfo> getDemoNewInfos() { return getRefreshDemoNewInfos(); } public static List<NewInfo> getRefreshDemoNewInfos() { List<NewInfo> list = new ArrayList<>(); list.add(new NewInfo("公众号", "X-Library系列文章视频介绍") .setSummary("获取更多咨询,欢迎点击关注公众号:【我的Android开源之旅】,里面有一整套X-Library系列文章视频介绍!\n") .setDetailUrl("http://mp.weixin.qq.com/mp/homepage?__biz=Mzg2NjA3NDIyMA==&hid=5&sn=bdee5aafe9cc2e0a618d055117c84139&scene=18#wechat_redirect") .setImageUrl("https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/463930705a844f638433d1b26273a7cf~tplv-k3u1fbpfcp-watermark.image")); list.add(new NewInfo("Android UI", "XUI 一个简洁而优雅的Android原生UI框架,解放你的双手") .setSummary("涵盖绝大部分的UI组件:TextView、Button、EditText、ImageView、Spinner、Picker、Dialog、PopupWindow、ProgressBar、LoadingView、StateLayout、FlowLayout、Switch、Actionbar、TabBar、Banner、GuideView、BadgeView、MarqueeView、WebView、SearchView等一系列的组件和丰富多彩的样式主题。\n") .setDetailUrl("https://juejin.im/post/5c3ed1dae51d4543805ea48d") .setImageUrl("https://user-gold-cdn.xitu.io/2019/1/16/1685563ae5456408?imageView2/0/w/1280/h/960/format/webp/ignore-error/1")); list.add(new NewInfo("Android", "XUpdate 一个轻量级、高可用性的Android版本更新框架") .setSummary("XUpdate 一个轻量级、高可用性的Android版本更新框架。本框架借鉴了AppUpdate中的部分思想和UI界面,将版本更新中的各部分环节抽离出来,形成了如下几个部分:") .setDetailUrl("https://juejin.im/post/5b480b79e51d45190905ef44") .setImageUrl("https://user-gold-cdn.xitu.io/2018/7/13/16492d9b7877dc21?imageView2/0/w/1280/h/960/format/webp/ignore-error/1")); list.add(new NewInfo("Android/HTTP", "XHttp2 一个功能强悍的网络请求库,使用RxJava2 + Retrofit2 + OKHttp进行组装") .setSummary("一个功能强悍的网络请求库,使用RxJava2 + Retrofit2 + OKHttp组合进行封装。还不赶紧点击使用说明文档,体验一下吧!") .setDetailUrl("https://juejin.im/post/5b6b9b49e51d4576b828978d") .setImageUrl("https://user-gold-cdn.xitu.io/2018/8/9/1651c568a7e30e02?imageView2/0/w/1280/h/960/format/webp/ignore-error/1")); list.add(new NewInfo("源码", "Android源码分析--Android系统启动") .setSummary("其实Android系统的启动最主要的内容无非是init、Zygote、SystemServer这三个进程的启动,他们一起构成的铁三角是Android系统的基础。") .setDetailUrl("https://juejin.im/post/5c6fc0cdf265da2dda694f05") .setImageUrl("https://user-gold-cdn.xitu.io/2019/2/22/16914891cd8a950a?imageView2/0/w/1280/h/960/format/webp/ignore-error/1")); return list; } /** * 用于占位的空信息 * * @return */ @MemoryCache public static List<NewInfo> getSpecialDemoNewInfos() { List<NewInfo> list = new ArrayList<>(); list.add(new NewInfo("Flutter", "Flutter学习指南App,一起来玩Flutter吧~") .setSummary("Flutter是谷歌的移动UI框架,可以快速在iOS、Android、Web和PC上构建高质量的原生用户界面。 Flutter可以与现有的代码一起工作。在全世界,Flutter正在被越来越多的开发者和组织使用,并且Flutter是完全免费、开源的。同时它也是构建未来的Google Fuchsia应用的主要方式。") .setDetailUrl("https://juejin.im/post/5e39a1b8518825497467e4ec") .setImageUrl("https://pic4.zhimg.com/v2-1236d741cbb3aabf5a9910a5e4b73e4c_1200x500.jpg")); list.add(new NewInfo("Android UI", "XUI 一个简洁而优雅的Android原生UI框架,解放你的双手") .setSummary("涵盖绝大部分的UI组件:TextView、Button、EditText、ImageView、Spinner、Picker、Dialog、PopupWindow、ProgressBar、LoadingView、StateLayout、FlowLayout、Switch、Actionbar、TabBar、Banner、GuideView、BadgeView、MarqueeView、WebView、SearchView等一系列的组件和丰富多彩的样式主题。\n") .setDetailUrl("https://juejin.im/post/5c3ed1dae51d4543805ea48d") .setImageUrl("https://user-gold-cdn.xitu.io/2019/1/16/1685563ae5456408?imageView2/0/w/1280/h/960/format/webp/ignore-error/1")); list.add(new NewInfo("Android", "XUpdate 一个轻量级、高可用性的Android版本更新框架") .setSummary("XUpdate 一个轻量级、高可用性的Android版本更新框架。本框架借鉴了AppUpdate中的部分思想和UI界面,将版本更新中的各部分环节抽离出来,形成了如下几个部分:") .setDetailUrl("https://juejin.im/post/5b480b79e51d45190905ef44") .setImageUrl("https://user-gold-cdn.xitu.io/2018/7/13/16492d9b7877dc21?imageView2/0/w/1280/h/960/format/webp/ignore-error/1")); list.add(new NewInfo("Android/HTTP", "XHttp2 一个功能强悍的网络请求库,使用RxJava2 + Retrofit2 + OKHttp进行组装") .setSummary("一个功能强悍的网络请求库,使用RxJava2 + Retrofit2 + OKHttp组合进行封装。还不赶紧点击使用说明文档,体验一下吧!") .setDetailUrl("https://juejin.im/post/5b6b9b49e51d4576b828978d") .setImageUrl("https://user-gold-cdn.xitu.io/2018/8/9/1651c568a7e30e02?imageView2/0/w/1280/h/960/format/webp/ignore-error/1")); list.add(new NewInfo("源码", "Android源码分析--Android系统启动") .setSummary("其实Android系统的启动最主要的内容无非是init、Zygote、SystemServer这三个进程的启动,他们一起构成的铁三角是Android系统的基础。") .setDetailUrl("https://juejin.im/post/5c6fc0cdf265da2dda694f05") .setImageUrl("https://user-gold-cdn.xitu.io/2019/2/22/16914891cd8a950a?imageView2/0/w/1280/h/960/format/webp/ignore-error/1")); return list; } @MemoryCache public static List<DefaultGroupedItem> getGroupItems() { List<DefaultGroupedItem> items = new ArrayList<>(); for (int i = 0; i < 100; i++) { if (i % 10 == 0) { items.add(new DefaultGroupedItem(true, "菜单" + i / 10)); } else { items.add(new DefaultGroupedItem(new DefaultGroupedItem.ItemInfo("这是标题" + i, "菜单" + i / 10, "这是内容" + i))); } } return items; } @MemoryCache public static List<CustomGroupedItem> getCustomGroupItems() { List<CustomGroupedItem> items = new ArrayList<>(); for (int i = 0; i < 100; i++) { if (i % 10 == 0) { items.add(new CustomGroupedItem(true, "菜单" + i / 10)); } else { items.add(new CustomGroupedItem(new CustomGroupedItem.ItemInfo("这是标题" + i, "菜单" + i / 10, "这是内容" + i))); } } return items; } @MemoryCache public static List<ElemeGroupedItem> getElemeGroupItems() { return JsonUtil.fromJson(ResourceUtils.readStringFromAssert("eleme.json"), new TypeToken<List<ElemeGroupedItem>>() { }.getType()); } /** * @return 省市区数据 */ public static List<ProvinceInfo> getProvinceInfos() { return JsonUtil.fromJson(ResourceUtils.readStringFromAssert("province.json"), new TypeToken<List<ProvinceInfo>>() { }.getType()); } /** * 获取时间段 * * @param interval 时间间隔(分钟) * @return */ public static String[] getTimePeriod(int interval) { return getTimePeriod(24, interval); } /** * 获取时间段 * * @param interval 时间间隔(分钟) * @return */ public static String[] getTimePeriod(int totalHour, int interval) { String[] time = new String[totalHour * 60 / interval]; int point, hour, min; for (int i = 0; i < time.length; i++) { point = i * interval; hour = point / 60; min = point - hour * 60; time[i] = (hour < 9 ? "0" + hour : "" + hour) + ":" + (min < 9 ? "0" + min : "" + min); } return time; } /** * 获取时间段 * * @param interval 时间间隔(分钟) * @return */ public static String[] getTimePeriod(int startHour, int totalHour, int interval) { String[] time = new String[totalHour * 60 / interval]; int point, hour, min; for (int i = 0; i < time.length; i++) { point = i * interval + startHour * 60; hour = point / 60; min = point - hour * 60; time[i] = (hour < 9 ? "0" + hour : "" + hour) + ":" + (min < 9 ? "0" + min : "" + min); } return time; } }
xuexiangjys/XUI
app/src/main/java/com/xuexiang/xuidemo/DemoDataProvider.java
866
package com.example.jingbin.designpattern.builder; import androidx.databinding.DataBindingUtil; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import com.example.jingbin.designpattern.R; import com.example.jingbin.designpattern.app.AppConstant; import com.example.jingbin.designpattern.app.EMTagHandler; import com.example.jingbin.designpattern.databinding.ActivityBuilderBinding; /** * @author jingbin * 建造者模式(Builder Pattern) * 建造模式是对象的创建模式。建造模式可以将一个产品的内部表象(internal representation)与产品的生产过程分割开来, * 从而可以使一个建造过程生成具有不同的内部表象的产品对象。 * <p> * Builder 类是关键,然后定义一个Builder实现类,再之后就是处理实现类的逻辑。 * <p> * 优点: * 1. 首先,建造者模式的封装性很好。使用建造者模式可以有效的封装变化,在使用建造者模式的场景中, * 一般产品类和建造者类是比较稳定的,因此,将主要的业务逻辑封装在导演类中对整体而言可以取得比较好的稳定性。 * 2. 其次,建造者模式很容易进行扩展。如果有新的需求,通过实现一个新的建造者类就可以完成, * 基本上不用修改之前已经测试通过的代码,因此也就不会对原有功能引入风险。 * 总结: * 建造者模式与工厂模式类似,他们都是建造者模式,适用的场景也很相似。 * 一般来说,如果产品的建造很复杂,那么请用工厂模式;如果产品的建造更复杂,那么请用建造者模式。 */ public class BuilderActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityBuilderBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_builder); setTitle("建造者模式"); binding.tvDefine.setText(EMTagHandler.fromHtml(AppConstant.BUILDER_DEFINE)); binding.btBuyAodi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Director director = new Director(); Product product = director.getAProduct(); product.showProduct(); } }); binding.btBuyBaoma.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Director director = new Director(); Product product = director.getBProduct(); product.showProduct(); } }); } }
youlookwhat/DesignPattern
app/src/main/java/com/example/jingbin/designpattern/builder/BuilderActivity.java
867
package com.ocnyang.qbox.app.model.entities; /******************************************************************* * * * * * * * * * * * Created by OCN.Yang * * * * * * * Time:2017/3/3 15:12. * * * * * * * Email address:[email protected] * * * * * * * * * * *.Yang Web site:www.ocnyang.com *******************************************************************/ public class JvHeBaseBean { /** * error_code : 0 * reason : Success * result : {"data":[{"content":"几千年后,一群考古学家挖掘出起点中文网的服务器并恢复出信息,由于文明形态的差异,他们会惊异地发现,早在千年前那个科技极度落后的时代,古地球文明已经拥有了【肉身可以横渡宇宙,一拳能够打爆星球】的强者,而且为数不少,因为在服务器里有上万本内容近似但名字不同的人物传记,这又能证明这种方法已经广泛应用。考古学家们为古地球人的伟力震惊,又为这种强悍的【修炼】方法失传而惋惜。","hashId":"9a05858007372df8ab297f104c047420","unixtime":1488518030,"updatetime":"2017-03-03 13:13:50"}]} */ private int error_code; private String reason; public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } }
OCNYang/QBox
app/src/main/java/com/ocnyang/qbox/app/model/entities/JvHeBaseBean.java
868
/* * Copyright (C) 2020 The zfoo 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 * * 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.zfoo.net.session; import com.zfoo.net.util.SessionUtils; import com.zfoo.protocol.collection.concurrent.ConcurrentHashMapLongObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; /** * @author godotg */ public class SessionManager implements ISessionManager { private static final Logger logger = LoggerFactory.getLogger(SessionManager.class); /** * EN: As a server, the Session is connected by other clients * CN: 作为服务器,被别的客户端连接的Session * <p> * 如:自己作为网关,那肯定有一大堆客户端连接,他们连接上来后,就会保存下来这些信息。 * 因此:要全局消息广播,其实要用这个Map */ private final ConcurrentHashMapLongObject<Session> serverSessionMap = new ConcurrentHashMapLongObject<>(128); /** * EN: As a client, connect to another server and save Sessions * CN: 作为客户端,连接别的服务器上后,保存下来的Session * 如:自己配置了Consumer,说明自己作为消费者将要消费远程接口,就会创建一个TcpClient去连接Provider,那么连接上后,就会保存下来到这个Map中 */ private final ConcurrentHashMapLongObject<Session> clientSessionMap = new ConcurrentHashMapLongObject<>(8); @Override public void addServerSession(Session session) { if (serverSessionMap.containsKey(session.getSid())) { logger.error("Server received duplicate [session:{}]", SessionUtils.sessionInfo(session)); return; } serverSessionMap.put(session.getSid(), session); } @Override public void removeServerSession(Session session) { if (!serverSessionMap.containsKey(session.getSid())) { logger.error("[session:{}] does not exist", SessionUtils.sessionInfo(session)); return; } try (session) { serverSessionMap.remove(session.getSid()); } } @Override public Session getServerSession(long sid) { return serverSessionMap.get(sid); } @Override public int serverSessionSize() { return serverSessionMap.size(); } @Override public void forEachServerSession(Consumer<Session> consumer) { serverSessionMap.forEachPrimitive(it -> consumer.accept(it.value())); } @Override public void addClientSession(Session session) { if (clientSessionMap.containsKey(session.getSid())) { logger.error("client received duplicate [session:{}]", SessionUtils.sessionInfo(session)); return; } clientSessionMap.put(session.getSid(), session); } @Override public void removeClientSession(Session session) { if (!clientSessionMap.containsKey(session.getSid())) { logger.error("[session:{}] does not exist", SessionUtils.sessionInfo(session)); return; } try (session) { clientSessionMap.remove(session.getSid()); } } @Override public Session getClientSession(long sid) { return clientSessionMap.get(sid); } @Override public void forEachClientSession(Consumer<Session> consumer) { clientSessionMap.forEachPrimitive(it -> consumer.accept(it.value())); } @Override public int clientSessionSize() { return clientSessionMap.size(); } }
zfoo-project/zfoo
net/src/main/java/com/zfoo/net/session/SessionManager.java
869
package pers.hdq.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import org.wltea.analyzer.core.IKSegmenter; import org.wltea.analyzer.core.Lexeme; /** * @author HuDaoquan * @version v1.0 * @ClassName: IKUtils * @Description: 调用IK分词器接口实现去停止词分词,停止词存入./ext.dic * @date 2019年7月1日 下午9:14:41 */ public class IKUtils { static Set<String> stopWordSet = new HashSet<>(1598); // 初始化停止词 static { stopWordSet.add("啊"); stopWordSet.add("阿"); stopWordSet.add("哎"); stopWordSet.add("哎呀"); stopWordSet.add("哎哟"); stopWordSet.add("唉"); stopWordSet.add("俺"); stopWordSet.add("俺们"); stopWordSet.add("按"); stopWordSet.add("按照"); stopWordSet.add("吧"); stopWordSet.add("吧哒"); stopWordSet.add("把"); stopWordSet.add("罢了"); stopWordSet.add("被"); stopWordSet.add("本"); stopWordSet.add("本着"); stopWordSet.add("比"); stopWordSet.add("比方"); stopWordSet.add("比如"); stopWordSet.add("鄙人"); stopWordSet.add("彼"); stopWordSet.add("彼此"); stopWordSet.add("边"); stopWordSet.add("别"); stopWordSet.add("别的"); stopWordSet.add("别说"); stopWordSet.add("并"); stopWordSet.add("并且"); stopWordSet.add("不比"); stopWordSet.add("不成"); stopWordSet.add("不单"); stopWordSet.add("不但"); stopWordSet.add("不独"); stopWordSet.add("不管"); stopWordSet.add("不光"); stopWordSet.add("不过"); stopWordSet.add("不仅"); stopWordSet.add("不拘"); stopWordSet.add("不论"); stopWordSet.add("不怕"); stopWordSet.add("不然"); stopWordSet.add("不如"); stopWordSet.add("不特"); stopWordSet.add("不惟"); stopWordSet.add("不问"); stopWordSet.add("不只"); stopWordSet.add("朝"); stopWordSet.add("朝着"); stopWordSet.add("趁"); stopWordSet.add("趁着"); stopWordSet.add("乘"); stopWordSet.add("冲"); stopWordSet.add("除"); stopWordSet.add("除此之外"); stopWordSet.add("除非"); stopWordSet.add("除了"); stopWordSet.add("此"); stopWordSet.add("此间"); stopWordSet.add("此外"); stopWordSet.add("从"); stopWordSet.add("从而"); stopWordSet.add("打"); stopWordSet.add("待"); stopWordSet.add("但"); stopWordSet.add("但是"); stopWordSet.add("当"); stopWordSet.add("当着"); stopWordSet.add("到"); stopWordSet.add("得"); stopWordSet.add("的"); stopWordSet.add("的话"); stopWordSet.add("等"); stopWordSet.add("等等"); stopWordSet.add("地"); stopWordSet.add("第"); stopWordSet.add("叮咚"); stopWordSet.add("对"); stopWordSet.add("对于"); stopWordSet.add("多"); stopWordSet.add("多少"); stopWordSet.add("而"); stopWordSet.add("而况"); stopWordSet.add("而且"); stopWordSet.add("而是"); stopWordSet.add("而外"); stopWordSet.add("而言"); stopWordSet.add("而已"); stopWordSet.add("尔后"); stopWordSet.add("反过来"); stopWordSet.add("反过来说"); stopWordSet.add("反之"); stopWordSet.add("非但"); stopWordSet.add("非徒"); stopWordSet.add("否则"); stopWordSet.add("嘎"); stopWordSet.add("嘎登"); stopWordSet.add("该"); stopWordSet.add("赶"); stopWordSet.add("个"); stopWordSet.add("各"); stopWordSet.add("各个"); stopWordSet.add("各位"); stopWordSet.add("各种"); stopWordSet.add("各自"); stopWordSet.add("给"); stopWordSet.add("根据"); stopWordSet.add("跟"); stopWordSet.add("故"); stopWordSet.add("故此"); stopWordSet.add("固然"); stopWordSet.add("关于"); stopWordSet.add("管"); stopWordSet.add("归"); stopWordSet.add("果然"); stopWordSet.add("果真"); stopWordSet.add("过"); stopWordSet.add("哈"); stopWordSet.add("哈哈"); stopWordSet.add("呵"); stopWordSet.add("和"); stopWordSet.add("何"); stopWordSet.add("何处"); stopWordSet.add("何况"); stopWordSet.add("何时"); stopWordSet.add("嘿"); stopWordSet.add("哼"); stopWordSet.add("哼唷"); stopWordSet.add("呼哧"); stopWordSet.add("乎"); stopWordSet.add("哗"); stopWordSet.add("还是"); stopWordSet.add("还有"); stopWordSet.add("换句话说"); stopWordSet.add("换言之"); stopWordSet.add("或"); stopWordSet.add("或是"); stopWordSet.add("或者"); stopWordSet.add("极了"); stopWordSet.add("及"); stopWordSet.add("及其"); stopWordSet.add("及至"); stopWordSet.add("即"); stopWordSet.add("即便"); stopWordSet.add("即或"); stopWordSet.add("即令"); stopWordSet.add("即若"); stopWordSet.add("即使"); stopWordSet.add("几"); stopWordSet.add("几时"); stopWordSet.add("己"); stopWordSet.add("既"); stopWordSet.add("既然"); stopWordSet.add("既是"); stopWordSet.add("继而"); stopWordSet.add("加之"); stopWordSet.add("假如"); stopWordSet.add("假若"); stopWordSet.add("假使"); stopWordSet.add("鉴于"); stopWordSet.add("将"); stopWordSet.add("较"); stopWordSet.add("较之"); stopWordSet.add("叫"); stopWordSet.add("接着"); stopWordSet.add("结果"); stopWordSet.add("借"); stopWordSet.add("紧接着"); stopWordSet.add("进而"); stopWordSet.add("尽"); stopWordSet.add("尽管"); stopWordSet.add("经"); stopWordSet.add("经过"); stopWordSet.add("就"); stopWordSet.add("就是"); stopWordSet.add("就是说"); stopWordSet.add("据"); stopWordSet.add("具体地说"); stopWordSet.add("具体说来"); stopWordSet.add("开始"); stopWordSet.add("开外"); stopWordSet.add("靠"); stopWordSet.add("咳"); stopWordSet.add("可"); stopWordSet.add("可见"); stopWordSet.add("可是"); stopWordSet.add("可以"); stopWordSet.add("况且"); stopWordSet.add("啦"); stopWordSet.add("来"); stopWordSet.add("来着"); stopWordSet.add("离"); stopWordSet.add("例如"); stopWordSet.add("哩"); stopWordSet.add("连"); stopWordSet.add("连同"); stopWordSet.add("两者"); stopWordSet.add("了"); stopWordSet.add("临"); stopWordSet.add("另"); stopWordSet.add("另外"); stopWordSet.add("另一方面"); stopWordSet.add("论"); stopWordSet.add("嘛"); stopWordSet.add("吗"); stopWordSet.add("慢说"); stopWordSet.add("漫说"); stopWordSet.add("冒"); stopWordSet.add("么"); stopWordSet.add("每"); stopWordSet.add("每当"); stopWordSet.add("们"); stopWordSet.add("莫若"); stopWordSet.add("某"); stopWordSet.add("某个"); stopWordSet.add("某些"); stopWordSet.add("拿"); stopWordSet.add("哪"); stopWordSet.add("哪边"); stopWordSet.add("哪儿"); stopWordSet.add("哪个"); stopWordSet.add("哪里"); stopWordSet.add("哪年"); stopWordSet.add("哪怕"); stopWordSet.add("哪天"); stopWordSet.add("哪些"); stopWordSet.add("哪样"); stopWordSet.add("那"); stopWordSet.add("那边"); stopWordSet.add("那儿"); stopWordSet.add("那个"); stopWordSet.add("那会儿"); stopWordSet.add("那里"); stopWordSet.add("那么"); stopWordSet.add("那么些"); stopWordSet.add("那么样"); stopWordSet.add("那时"); stopWordSet.add("那些"); stopWordSet.add("那样"); stopWordSet.add("乃"); stopWordSet.add("乃至"); stopWordSet.add("呢"); stopWordSet.add("能"); stopWordSet.add("你"); stopWordSet.add("你们"); stopWordSet.add("您"); stopWordSet.add("宁"); stopWordSet.add("宁可"); stopWordSet.add("宁肯"); stopWordSet.add("宁愿"); stopWordSet.add("哦"); stopWordSet.add("呕"); stopWordSet.add("啪达"); stopWordSet.add("旁人"); stopWordSet.add("呸"); stopWordSet.add("凭"); stopWordSet.add("凭借"); stopWordSet.add("其"); stopWordSet.add("其次"); stopWordSet.add("其二"); stopWordSet.add("其他"); stopWordSet.add("其它"); stopWordSet.add("其一"); stopWordSet.add("其余"); stopWordSet.add("其中"); stopWordSet.add("起"); stopWordSet.add("起见"); stopWordSet.add("岂但"); stopWordSet.add("恰恰相反"); stopWordSet.add("前后"); stopWordSet.add("前者"); stopWordSet.add("且"); stopWordSet.add("然而"); stopWordSet.add("然后"); stopWordSet.add("然则"); stopWordSet.add("让"); stopWordSet.add("人家"); stopWordSet.add("任"); stopWordSet.add("任何"); stopWordSet.add("任凭"); stopWordSet.add("如"); stopWordSet.add("如此"); stopWordSet.add("如果"); stopWordSet.add("如何"); stopWordSet.add("如其"); stopWordSet.add("如若"); stopWordSet.add("如上所述"); stopWordSet.add("若"); stopWordSet.add("若非"); stopWordSet.add("若是"); stopWordSet.add("啥"); stopWordSet.add("上下"); stopWordSet.add("尚且"); stopWordSet.add("设若"); stopWordSet.add("设使"); stopWordSet.add("甚而"); stopWordSet.add("甚么"); stopWordSet.add("甚至"); stopWordSet.add("省得"); stopWordSet.add("时候"); stopWordSet.add("什么"); stopWordSet.add("什么样"); stopWordSet.add("使得"); stopWordSet.add("是"); stopWordSet.add("是的"); stopWordSet.add("首先"); stopWordSet.add("谁"); stopWordSet.add("谁知"); stopWordSet.add("顺"); stopWordSet.add("顺着"); stopWordSet.add("似的"); stopWordSet.add("虽"); stopWordSet.add("虽然"); stopWordSet.add("虽说"); stopWordSet.add("虽则"); stopWordSet.add("随"); stopWordSet.add("随着"); stopWordSet.add("所"); stopWordSet.add("所以"); stopWordSet.add("他"); stopWordSet.add("他们"); stopWordSet.add("他人"); stopWordSet.add("它"); stopWordSet.add("它们"); stopWordSet.add("她"); stopWordSet.add("她们"); stopWordSet.add("倘"); stopWordSet.add("倘或"); stopWordSet.add("倘然"); stopWordSet.add("倘若"); stopWordSet.add("倘使"); stopWordSet.add("腾"); stopWordSet.add("替"); stopWordSet.add("通过"); stopWordSet.add("同"); stopWordSet.add("同时"); stopWordSet.add("哇"); stopWordSet.add("万一"); stopWordSet.add("往"); stopWordSet.add("望"); stopWordSet.add("为"); stopWordSet.add("为何"); stopWordSet.add("为了"); stopWordSet.add("为什么"); stopWordSet.add("为着"); stopWordSet.add("喂"); stopWordSet.add("嗡嗡"); stopWordSet.add("我"); stopWordSet.add("我们"); stopWordSet.add("呜"); stopWordSet.add("呜呼"); stopWordSet.add("乌乎"); stopWordSet.add("无论"); stopWordSet.add("无宁"); stopWordSet.add("毋宁"); stopWordSet.add("嘻"); stopWordSet.add("吓"); stopWordSet.add("相对而言"); stopWordSet.add("像"); stopWordSet.add("向"); stopWordSet.add("向着"); stopWordSet.add("嘘"); stopWordSet.add("呀"); stopWordSet.add("焉"); stopWordSet.add("沿"); stopWordSet.add("沿着"); stopWordSet.add("要"); stopWordSet.add("要不"); stopWordSet.add("要不然"); stopWordSet.add("要不是"); stopWordSet.add("要么"); stopWordSet.add("要是"); stopWordSet.add("也"); stopWordSet.add("也罢"); stopWordSet.add("也好"); stopWordSet.add("一"); stopWordSet.add("一般"); stopWordSet.add("一旦"); stopWordSet.add("一方面"); stopWordSet.add("一来"); stopWordSet.add("一切"); stopWordSet.add("一样"); stopWordSet.add("一则"); stopWordSet.add("依"); stopWordSet.add("依照"); stopWordSet.add("矣"); stopWordSet.add("以"); stopWordSet.add("以便"); stopWordSet.add("以及"); stopWordSet.add("以免"); stopWordSet.add("以至"); stopWordSet.add("以至于"); stopWordSet.add("以致"); stopWordSet.add("抑或"); stopWordSet.add("因"); stopWordSet.add("因此"); stopWordSet.add("因而"); stopWordSet.add("因为"); stopWordSet.add("哟"); stopWordSet.add("用"); stopWordSet.add("由"); stopWordSet.add("由此可见"); stopWordSet.add("由于"); stopWordSet.add("有"); stopWordSet.add("有的"); stopWordSet.add("有关"); stopWordSet.add("有些"); stopWordSet.add("又"); stopWordSet.add("于"); stopWordSet.add("于是"); stopWordSet.add("于是乎"); stopWordSet.add("与"); stopWordSet.add("与此同时"); stopWordSet.add("与否"); stopWordSet.add("与其"); stopWordSet.add("越是"); stopWordSet.add("云云"); stopWordSet.add("哉"); stopWordSet.add("再说"); stopWordSet.add("再者"); stopWordSet.add("在"); stopWordSet.add("在下"); stopWordSet.add("咱"); stopWordSet.add("咱们"); stopWordSet.add("则"); stopWordSet.add("怎"); stopWordSet.add("怎么"); stopWordSet.add("怎么办"); stopWordSet.add("怎么样"); stopWordSet.add("怎样"); stopWordSet.add("咋"); stopWordSet.add("照"); stopWordSet.add("照着"); stopWordSet.add("者"); stopWordSet.add("这"); stopWordSet.add("这边"); stopWordSet.add("这儿"); stopWordSet.add("这个"); stopWordSet.add("这会儿"); stopWordSet.add("这就是说"); stopWordSet.add("这里"); stopWordSet.add("这么"); stopWordSet.add("这么点儿"); stopWordSet.add("这么些"); stopWordSet.add("这么样"); stopWordSet.add("这时"); stopWordSet.add("这些"); stopWordSet.add("这样"); stopWordSet.add("正如"); stopWordSet.add("吱"); stopWordSet.add("之"); stopWordSet.add("之类"); stopWordSet.add("之所以"); stopWordSet.add("之一"); stopWordSet.add("只是"); stopWordSet.add("只限"); stopWordSet.add("只要"); stopWordSet.add("只有"); stopWordSet.add("至"); stopWordSet.add("至于"); stopWordSet.add("诸位"); stopWordSet.add("着"); stopWordSet.add("着呢"); stopWordSet.add("自"); stopWordSet.add("自从"); stopWordSet.add("自个儿"); stopWordSet.add("自各儿"); stopWordSet.add("自己"); stopWordSet.add("自家"); stopWordSet.add("自身"); stopWordSet.add("综上所述"); stopWordSet.add("总的来看"); stopWordSet.add("总的来说"); stopWordSet.add("总的说来"); stopWordSet.add("总而言之"); stopWordSet.add("总之"); stopWordSet.add("纵"); stopWordSet.add("纵令"); stopWordSet.add("纵然"); stopWordSet.add("纵使"); stopWordSet.add("遵照"); stopWordSet.add("作为"); stopWordSet.add("兮"); stopWordSet.add("呃"); stopWordSet.add("呗"); stopWordSet.add("咚"); stopWordSet.add("咦"); stopWordSet.add("喏"); stopWordSet.add("啐"); stopWordSet.add("喔唷"); stopWordSet.add("嗬"); stopWordSet.add("嗯"); stopWordSet.add("嗳"); stopWordSet.add("啊哈"); stopWordSet.add("啊呀"); stopWordSet.add("啊哟"); stopWordSet.add("挨次"); stopWordSet.add("挨个"); stopWordSet.add("挨家挨户"); stopWordSet.add("挨门挨户"); stopWordSet.add("挨门逐户"); stopWordSet.add("挨着"); stopWordSet.add("按理"); stopWordSet.add("按期"); stopWordSet.add("按时"); stopWordSet.add("按说"); stopWordSet.add("暗地里"); stopWordSet.add("暗中"); stopWordSet.add("暗自"); stopWordSet.add("昂然"); stopWordSet.add("八成"); stopWordSet.add("白白"); stopWordSet.add("半"); stopWordSet.add("梆"); stopWordSet.add("保管"); stopWordSet.add("保险"); stopWordSet.add("饱"); stopWordSet.add("背地里"); stopWordSet.add("背靠背"); stopWordSet.add("倍感"); stopWordSet.add("倍加"); stopWordSet.add("本人"); stopWordSet.add("本身"); stopWordSet.add("甭"); stopWordSet.add("比起"); stopWordSet.add("比如说"); stopWordSet.add("比照"); stopWordSet.add("毕竟"); stopWordSet.add("必"); stopWordSet.add("必定"); stopWordSet.add("必将"); stopWordSet.add("必须"); stopWordSet.add("便"); stopWordSet.add("别人"); stopWordSet.add("并非"); stopWordSet.add("并肩"); stopWordSet.add("并没"); stopWordSet.add("并没有"); stopWordSet.add("并排"); stopWordSet.add("并无"); stopWordSet.add("勃然"); stopWordSet.add("不"); stopWordSet.add("不必"); stopWordSet.add("不常"); stopWordSet.add("不大"); stopWordSet.add("不得"); stopWordSet.add("不得不"); stopWordSet.add("不得了"); stopWordSet.add("不得已"); stopWordSet.add("不迭"); stopWordSet.add("不定"); stopWordSet.add("不对"); stopWordSet.add("不妨"); stopWordSet.add("不管怎样"); stopWordSet.add("不会"); stopWordSet.add("不仅仅"); stopWordSet.add("不仅仅是"); stopWordSet.add("不经意"); stopWordSet.add("不可开交"); stopWordSet.add("不可抗拒"); stopWordSet.add("不力"); stopWordSet.add("不了"); stopWordSet.add("不料"); stopWordSet.add("不满"); stopWordSet.add("不免"); stopWordSet.add("不能不"); stopWordSet.add("不起"); stopWordSet.add("不巧"); stopWordSet.add("不然的话"); stopWordSet.add("不日"); stopWordSet.add("不少"); stopWordSet.add("不胜"); stopWordSet.add("不时"); stopWordSet.add("不是"); stopWordSet.add("不同"); stopWordSet.add("不能"); stopWordSet.add("不要"); stopWordSet.add("不外"); stopWordSet.add("不外乎"); stopWordSet.add("不下"); stopWordSet.add("不限"); stopWordSet.add("不消"); stopWordSet.add("不已"); stopWordSet.add("不亦乐乎"); stopWordSet.add("不由得"); stopWordSet.add("不再"); stopWordSet.add("不择手段"); stopWordSet.add("不怎么"); stopWordSet.add("不曾"); stopWordSet.add("不知不觉"); stopWordSet.add("不止"); stopWordSet.add("不止一次"); stopWordSet.add("不至于"); stopWordSet.add("才"); stopWordSet.add("才能"); stopWordSet.add("策略地"); stopWordSet.add("差不多"); stopWordSet.add("差一点"); stopWordSet.add("常"); stopWordSet.add("常常"); stopWordSet.add("常言道"); stopWordSet.add("常言说"); stopWordSet.add("常言说得好"); stopWordSet.add("长此下去"); stopWordSet.add("长话短说"); stopWordSet.add("长期以来"); stopWordSet.add("长线"); stopWordSet.add("敞开儿"); stopWordSet.add("彻夜"); stopWordSet.add("陈年"); stopWordSet.add("趁便"); stopWordSet.add("趁机"); stopWordSet.add("趁热"); stopWordSet.add("趁势"); stopWordSet.add("趁早"); stopWordSet.add("成年"); stopWordSet.add("成年累月"); stopWordSet.add("成心"); stopWordSet.add("乘机"); stopWordSet.add("乘胜"); stopWordSet.add("乘势"); stopWordSet.add("乘隙"); stopWordSet.add("乘虚"); stopWordSet.add("诚然"); stopWordSet.add("迟早"); stopWordSet.add("充分"); stopWordSet.add("充其极"); stopWordSet.add("充其量"); stopWordSet.add("抽冷子"); stopWordSet.add("臭"); stopWordSet.add("初"); stopWordSet.add("出"); stopWordSet.add("出来"); stopWordSet.add("出去"); stopWordSet.add("除此"); stopWordSet.add("除此而外"); stopWordSet.add("除此以外"); stopWordSet.add("除开"); stopWordSet.add("除去"); stopWordSet.add("除却"); stopWordSet.add("除外"); stopWordSet.add("处处"); stopWordSet.add("川流不息"); stopWordSet.add("传"); stopWordSet.add("传说"); stopWordSet.add("传闻"); stopWordSet.add("串行"); stopWordSet.add("纯"); stopWordSet.add("纯粹"); stopWordSet.add("此后"); stopWordSet.add("此中"); stopWordSet.add("次第"); stopWordSet.add("匆匆"); stopWordSet.add("从不"); stopWordSet.add("从此"); stopWordSet.add("从此以后"); stopWordSet.add("从古到今"); stopWordSet.add("从古至今"); stopWordSet.add("从今以后"); stopWordSet.add("从宽"); stopWordSet.add("从来"); stopWordSet.add("从轻"); stopWordSet.add("从速"); stopWordSet.add("从头"); stopWordSet.add("从未"); stopWordSet.add("从无到有"); stopWordSet.add("从小"); stopWordSet.add("从新"); stopWordSet.add("从严"); stopWordSet.add("从优"); stopWordSet.add("从早到晚"); stopWordSet.add("从中"); stopWordSet.add("从重"); stopWordSet.add("凑巧"); stopWordSet.add("粗"); stopWordSet.add("存心"); stopWordSet.add("达旦"); stopWordSet.add("打从"); stopWordSet.add("打开天窗说亮话"); stopWordSet.add("大"); stopWordSet.add("大不了"); stopWordSet.add("大大"); stopWordSet.add("大抵"); stopWordSet.add("大都"); stopWordSet.add("大多"); stopWordSet.add("大凡"); stopWordSet.add("大概"); stopWordSet.add("大家"); stopWordSet.add("大举"); stopWordSet.add("大略"); stopWordSet.add("大面儿上"); stopWordSet.add("大事"); stopWordSet.add("大体"); stopWordSet.add("大体上"); stopWordSet.add("大约"); stopWordSet.add("大张旗鼓"); stopWordSet.add("大致"); stopWordSet.add("呆呆地"); stopWordSet.add("带"); stopWordSet.add("殆"); stopWordSet.add("待到"); stopWordSet.add("单"); stopWordSet.add("单纯"); stopWordSet.add("单单"); stopWordSet.add("但愿"); stopWordSet.add("弹指之间"); stopWordSet.add("当场"); stopWordSet.add("当儿"); stopWordSet.add("当即"); stopWordSet.add("当口儿"); stopWordSet.add("当然"); stopWordSet.add("当庭"); stopWordSet.add("当头"); stopWordSet.add("当下"); stopWordSet.add("当真"); stopWordSet.add("当中"); stopWordSet.add("倒不如"); stopWordSet.add("倒不如说"); stopWordSet.add("倒是"); stopWordSet.add("到处"); stopWordSet.add("到底"); stopWordSet.add("到了儿"); stopWordSet.add("到目前为止"); stopWordSet.add("到头"); stopWordSet.add("到头来"); stopWordSet.add("得起"); stopWordSet.add("得天独厚"); stopWordSet.add("的确"); stopWordSet.add("等到"); stopWordSet.add("叮当"); stopWordSet.add("顶多"); stopWordSet.add("定"); stopWordSet.add("动不动"); stopWordSet.add("动辄"); stopWordSet.add("陡然"); stopWordSet.add("都"); stopWordSet.add("独"); stopWordSet.add("独自"); stopWordSet.add("断然"); stopWordSet.add("顿时"); stopWordSet.add("多次"); stopWordSet.add("多多"); stopWordSet.add("多多少少"); stopWordSet.add("多多益善"); stopWordSet.add("多亏"); stopWordSet.add("多年来"); stopWordSet.add("多年前"); stopWordSet.add("而后"); stopWordSet.add("而论"); stopWordSet.add("而又"); stopWordSet.add("尔等"); stopWordSet.add("二话不说"); stopWordSet.add("二话没说"); stopWordSet.add("反倒"); stopWordSet.add("反倒是"); stopWordSet.add("反而"); stopWordSet.add("反手"); stopWordSet.add("反之亦然"); stopWordSet.add("反之则"); stopWordSet.add("方"); stopWordSet.add("方才"); stopWordSet.add("方能"); stopWordSet.add("放量"); stopWordSet.add("非常"); stopWordSet.add("非得"); stopWordSet.add("分期"); stopWordSet.add("分期分批"); stopWordSet.add("分头"); stopWordSet.add("奋勇"); stopWordSet.add("愤然"); stopWordSet.add("风雨无阻"); stopWordSet.add("逢"); stopWordSet.add("弗"); stopWordSet.add("甫"); stopWordSet.add("嘎嘎"); stopWordSet.add("该当"); stopWordSet.add("概"); stopWordSet.add("赶快"); stopWordSet.add("赶早不赶晚"); stopWordSet.add("敢"); stopWordSet.add("敢情"); stopWordSet.add("敢于"); stopWordSet.add("刚"); stopWordSet.add("刚才"); stopWordSet.add("刚好"); stopWordSet.add("刚巧"); stopWordSet.add("高低"); stopWordSet.add("格外"); stopWordSet.add("隔日"); stopWordSet.add("隔夜"); stopWordSet.add("个人"); stopWordSet.add("各式"); stopWordSet.add("更"); stopWordSet.add("更加"); stopWordSet.add("更进一步"); stopWordSet.add("更为"); stopWordSet.add("公然"); stopWordSet.add("共"); stopWordSet.add("共总"); stopWordSet.add("够瞧的"); stopWordSet.add("姑且"); stopWordSet.add("古来"); stopWordSet.add("故而"); stopWordSet.add("故意"); stopWordSet.add("固"); stopWordSet.add("怪"); stopWordSet.add("怪不得"); stopWordSet.add("惯常"); stopWordSet.add("光"); stopWordSet.add("光是"); stopWordSet.add("归根到底"); stopWordSet.add("归根结底"); stopWordSet.add("过于"); stopWordSet.add("毫不"); stopWordSet.add("毫无"); stopWordSet.add("毫无保留地"); stopWordSet.add("毫无例外"); stopWordSet.add("好在"); stopWordSet.add("何必"); stopWordSet.add("何尝"); stopWordSet.add("何妨"); stopWordSet.add("何苦"); stopWordSet.add("何乐而不为"); stopWordSet.add("何须"); stopWordSet.add("何止"); stopWordSet.add("很"); stopWordSet.add("很多"); stopWordSet.add("很少"); stopWordSet.add("轰然"); stopWordSet.add("后来"); stopWordSet.add("呼啦"); stopWordSet.add("忽地"); stopWordSet.add("忽然"); stopWordSet.add("互"); stopWordSet.add("互相"); stopWordSet.add("哗啦"); stopWordSet.add("话说"); stopWordSet.add("还"); stopWordSet.add("恍然"); stopWordSet.add("会"); stopWordSet.add("豁然"); stopWordSet.add("活"); stopWordSet.add("伙同"); stopWordSet.add("或多或少"); stopWordSet.add("或许"); stopWordSet.add("基本"); stopWordSet.add("基本上"); stopWordSet.add("基于"); stopWordSet.add("极"); stopWordSet.add("极大"); stopWordSet.add("极度"); stopWordSet.add("极端"); stopWordSet.add("极力"); stopWordSet.add("极其"); stopWordSet.add("极为"); stopWordSet.add("急匆匆"); stopWordSet.add("即将"); stopWordSet.add("即刻"); stopWordSet.add("即是说"); stopWordSet.add("几度"); stopWordSet.add("几番"); stopWordSet.add("几乎"); stopWordSet.add("几经"); stopWordSet.add("既…又"); stopWordSet.add("继之"); stopWordSet.add("加上"); stopWordSet.add("加以"); stopWordSet.add("间或"); stopWordSet.add("简而言之"); stopWordSet.add("简言之"); stopWordSet.add("简直"); stopWordSet.add("见"); stopWordSet.add("将才"); stopWordSet.add("将近"); stopWordSet.add("将要"); stopWordSet.add("交口"); stopWordSet.add("较比"); stopWordSet.add("较为"); stopWordSet.add("接连不断"); stopWordSet.add("接下来"); stopWordSet.add("皆可"); stopWordSet.add("截然"); stopWordSet.add("截至"); stopWordSet.add("藉以"); stopWordSet.add("借此"); stopWordSet.add("借以"); stopWordSet.add("届时"); stopWordSet.add("仅"); stopWordSet.add("仅仅"); stopWordSet.add("谨"); stopWordSet.add("进来"); stopWordSet.add("进去"); stopWordSet.add("近"); stopWordSet.add("近几年来"); stopWordSet.add("近来"); stopWordSet.add("近年来"); stopWordSet.add("尽管如此"); stopWordSet.add("尽可能"); stopWordSet.add("尽快"); stopWordSet.add("尽量"); stopWordSet.add("尽然"); stopWordSet.add("尽如人意"); stopWordSet.add("尽心竭力"); stopWordSet.add("尽心尽力"); stopWordSet.add("尽早"); stopWordSet.add("精光"); stopWordSet.add("经常"); stopWordSet.add("竟"); stopWordSet.add("竟然"); stopWordSet.add("究竟"); stopWordSet.add("就此"); stopWordSet.add("就地"); stopWordSet.add("就算"); stopWordSet.add("居然"); stopWordSet.add("局外"); stopWordSet.add("举凡"); stopWordSet.add("据称"); stopWordSet.add("据此"); stopWordSet.add("据实"); stopWordSet.add("据说"); stopWordSet.add("据我所知"); stopWordSet.add("据悉"); stopWordSet.add("具体来说"); stopWordSet.add("决不"); stopWordSet.add("决非"); stopWordSet.add("绝"); stopWordSet.add("绝不"); stopWordSet.add("绝顶"); stopWordSet.add("绝对"); stopWordSet.add("绝非"); stopWordSet.add("均"); stopWordSet.add("喀"); stopWordSet.add("看"); stopWordSet.add("看来"); stopWordSet.add("看起来"); stopWordSet.add("看上去"); stopWordSet.add("看样子"); stopWordSet.add("可好"); stopWordSet.add("可能"); stopWordSet.add("恐怕"); stopWordSet.add("快"); stopWordSet.add("快要"); stopWordSet.add("来不及"); stopWordSet.add("来得及"); stopWordSet.add("来讲"); stopWordSet.add("来看"); stopWordSet.add("拦腰"); stopWordSet.add("牢牢"); stopWordSet.add("老"); stopWordSet.add("老大"); stopWordSet.add("老老实实"); stopWordSet.add("老是"); stopWordSet.add("累次"); stopWordSet.add("累年"); stopWordSet.add("理当"); stopWordSet.add("理该"); stopWordSet.add("理应"); stopWordSet.add("历"); stopWordSet.add("立"); stopWordSet.add("立地"); stopWordSet.add("立刻"); stopWordSet.add("立马"); stopWordSet.add("立时"); stopWordSet.add("联袂"); stopWordSet.add("连连"); stopWordSet.add("连日"); stopWordSet.add("连日来"); stopWordSet.add("连声"); stopWordSet.add("连袂"); stopWordSet.add("临到"); stopWordSet.add("另方面"); stopWordSet.add("另行"); stopWordSet.add("另一个"); stopWordSet.add("路经"); stopWordSet.add("屡"); stopWordSet.add("屡次"); stopWordSet.add("屡次三番"); stopWordSet.add("屡屡"); stopWordSet.add("缕缕"); stopWordSet.add("率尔"); stopWordSet.add("率然"); stopWordSet.add("略"); stopWordSet.add("略加"); stopWordSet.add("略微"); stopWordSet.add("略为"); stopWordSet.add("论说"); stopWordSet.add("马上"); stopWordSet.add("蛮"); stopWordSet.add("满"); stopWordSet.add("没"); stopWordSet.add("没有"); stopWordSet.add("每逢"); stopWordSet.add("每每"); stopWordSet.add("每时每刻"); stopWordSet.add("猛然"); stopWordSet.add("猛然间"); stopWordSet.add("莫"); stopWordSet.add("莫不"); stopWordSet.add("莫非"); stopWordSet.add("莫如"); stopWordSet.add("默默地"); stopWordSet.add("默然"); stopWordSet.add("呐"); stopWordSet.add("那末"); stopWordSet.add("奈"); stopWordSet.add("难道"); stopWordSet.add("难得"); stopWordSet.add("难怪"); stopWordSet.add("难说"); stopWordSet.add("内"); stopWordSet.add("年复一年"); stopWordSet.add("凝神"); stopWordSet.add("偶而"); stopWordSet.add("偶尔"); stopWordSet.add("怕"); stopWordSet.add("砰"); stopWordSet.add("碰巧"); stopWordSet.add("譬如"); stopWordSet.add("偏偏"); stopWordSet.add("乒"); stopWordSet.add("平素"); stopWordSet.add("颇"); stopWordSet.add("迫于"); stopWordSet.add("扑通"); stopWordSet.add("其后"); stopWordSet.add("其实"); stopWordSet.add("奇"); stopWordSet.add("齐"); stopWordSet.add("起初"); stopWordSet.add("起来"); stopWordSet.add("起首"); stopWordSet.add("起头"); stopWordSet.add("起先"); stopWordSet.add("岂"); stopWordSet.add("岂非"); stopWordSet.add("岂止"); stopWordSet.add("迄"); stopWordSet.add("恰逢"); stopWordSet.add("恰好"); stopWordSet.add("恰恰"); stopWordSet.add("恰巧"); stopWordSet.add("恰如"); stopWordSet.add("恰似"); stopWordSet.add("千"); stopWordSet.add("万"); stopWordSet.add("千万"); stopWordSet.add("千万千万"); stopWordSet.add("切"); stopWordSet.add("切不可"); stopWordSet.add("切莫"); stopWordSet.add("切切"); stopWordSet.add("切勿"); stopWordSet.add("窃"); stopWordSet.add("亲口"); stopWordSet.add("亲身"); stopWordSet.add("亲手"); stopWordSet.add("亲眼"); stopWordSet.add("亲自"); stopWordSet.add("顷"); stopWordSet.add("顷刻"); stopWordSet.add("顷刻间"); stopWordSet.add("顷刻之间"); stopWordSet.add("请勿"); stopWordSet.add("穷年累月"); stopWordSet.add("取道"); stopWordSet.add("去"); stopWordSet.add("权时"); stopWordSet.add("全都"); stopWordSet.add("全力"); stopWordSet.add("全年"); stopWordSet.add("全然"); stopWordSet.add("全身心"); stopWordSet.add("然"); stopWordSet.add("人人"); stopWordSet.add("仍"); stopWordSet.add("仍旧"); stopWordSet.add("仍然"); stopWordSet.add("日复一日"); stopWordSet.add("日见"); stopWordSet.add("日渐"); stopWordSet.add("日益"); stopWordSet.add("日臻"); stopWordSet.add("如常"); stopWordSet.add("如此等等"); stopWordSet.add("如次"); stopWordSet.add("如今"); stopWordSet.add("如期"); stopWordSet.add("如前所述"); stopWordSet.add("如上"); stopWordSet.add("如下"); stopWordSet.add("汝"); stopWordSet.add("三番两次"); stopWordSet.add("三番五次"); stopWordSet.add("三天两头"); stopWordSet.add("瑟瑟"); stopWordSet.add("沙沙"); stopWordSet.add("上"); stopWordSet.add("上来"); stopWordSet.add("上去"); stopWordSet.add("一."); stopWordSet.add("一一"); stopWordSet.add("一下"); stopWordSet.add("一个"); stopWordSet.add("一些"); stopWordSet.add("一何"); stopWordSet.add("一则通过"); stopWordSet.add("一天"); stopWordSet.add("一定"); stopWordSet.add("一时"); stopWordSet.add("一次"); stopWordSet.add("一片"); stopWordSet.add("一番"); stopWordSet.add("一直"); stopWordSet.add("一致"); stopWordSet.add("一起"); stopWordSet.add("一转眼"); stopWordSet.add("一边"); stopWordSet.add("一面"); stopWordSet.add("上升"); stopWordSet.add("上述"); stopWordSet.add("上面"); stopWordSet.add("下"); stopWordSet.add("下列"); stopWordSet.add("下去"); stopWordSet.add("下来"); stopWordSet.add("下面"); stopWordSet.add("不一"); stopWordSet.add("不久"); stopWordSet.add("不变"); stopWordSet.add("不可"); stopWordSet.add("不够"); stopWordSet.add("不尽"); stopWordSet.add("不尽然"); stopWordSet.add("不敢"); stopWordSet.add("不断"); stopWordSet.add("不若"); stopWordSet.add("不足"); stopWordSet.add("与其说"); stopWordSet.add("专门"); stopWordSet.add("且不说"); stopWordSet.add("且说"); stopWordSet.add("严格"); stopWordSet.add("严重"); stopWordSet.add("个别"); stopWordSet.add("中小"); stopWordSet.add("中间"); stopWordSet.add("丰富"); stopWordSet.add("为主"); stopWordSet.add("为什麽"); stopWordSet.add("为止"); stopWordSet.add("为此"); stopWordSet.add("主张"); stopWordSet.add("主要"); stopWordSet.add("举行"); stopWordSet.add("乃至于"); stopWordSet.add("之前"); stopWordSet.add("之后"); stopWordSet.add("之後"); stopWordSet.add("也就是说"); stopWordSet.add("也是"); stopWordSet.add("了解"); stopWordSet.add("争取"); stopWordSet.add("二来"); stopWordSet.add("云尔"); stopWordSet.add("些"); stopWordSet.add("亦"); stopWordSet.add("产生"); stopWordSet.add("人"); stopWordSet.add("人们"); stopWordSet.add("什麽"); stopWordSet.add("今"); stopWordSet.add("今后"); stopWordSet.add("今天"); stopWordSet.add("今年"); stopWordSet.add("今後"); stopWordSet.add("介于"); stopWordSet.add("从事"); stopWordSet.add("他是"); stopWordSet.add("他的"); stopWordSet.add("代替"); stopWordSet.add("以上"); stopWordSet.add("以下"); stopWordSet.add("以为"); stopWordSet.add("以前"); stopWordSet.add("以后"); stopWordSet.add("以外"); stopWordSet.add("以後"); stopWordSet.add("以故"); stopWordSet.add("以期"); stopWordSet.add("以来"); stopWordSet.add("任务"); stopWordSet.add("企图"); stopWordSet.add("伟大"); stopWordSet.add("似乎"); stopWordSet.add("但凡"); stopWordSet.add("何以"); stopWordSet.add("余外"); stopWordSet.add("你是"); stopWordSet.add("你的"); stopWordSet.add("使"); stopWordSet.add("使用"); stopWordSet.add("依据"); stopWordSet.add("依靠"); stopWordSet.add("便于"); stopWordSet.add("促进"); stopWordSet.add("保持"); stopWordSet.add("做到"); stopWordSet.add("傥然"); stopWordSet.add("儿"); stopWordSet.add("允许"); stopWordSet.add("元/吨"); stopWordSet.add("先不先"); stopWordSet.add("先后"); stopWordSet.add("先後"); stopWordSet.add("先生"); stopWordSet.add("全体"); stopWordSet.add("全部"); stopWordSet.add("全面"); stopWordSet.add("共同"); stopWordSet.add("具体"); stopWordSet.add("具有"); stopWordSet.add("兼之"); stopWordSet.add("再"); stopWordSet.add("再其次"); stopWordSet.add("再则"); stopWordSet.add("再有"); stopWordSet.add("再次"); stopWordSet.add("再者说"); stopWordSet.add("决定"); stopWordSet.add("准备"); stopWordSet.add("凡"); stopWordSet.add("凡是"); stopWordSet.add("出于"); stopWordSet.add("出现"); stopWordSet.add("分别"); stopWordSet.add("则甚"); stopWordSet.add("别处"); stopWordSet.add("别是"); stopWordSet.add("别管"); stopWordSet.add("前此"); stopWordSet.add("前进"); stopWordSet.add("前面"); stopWordSet.add("加入"); stopWordSet.add("加强"); stopWordSet.add("十分"); stopWordSet.add("即如"); stopWordSet.add("却"); stopWordSet.add("却不"); stopWordSet.add("原来"); stopWordSet.add("又及"); stopWordSet.add("及时"); stopWordSet.add("双方"); stopWordSet.add("反应"); stopWordSet.add("反映"); stopWordSet.add("取得"); stopWordSet.add("受到"); stopWordSet.add("变成"); stopWordSet.add("另悉"); stopWordSet.add("只"); stopWordSet.add("只当"); stopWordSet.add("只怕"); stopWordSet.add("只消"); stopWordSet.add("叫做"); stopWordSet.add("召开"); stopWordSet.add("各人"); stopWordSet.add("各地"); stopWordSet.add("各级"); stopWordSet.add("合理"); stopWordSet.add("同一"); stopWordSet.add("同样"); stopWordSet.add("后"); stopWordSet.add("后者"); stopWordSet.add("后面"); stopWordSet.add("向使"); stopWordSet.add("周围"); stopWordSet.add("呵呵"); stopWordSet.add("咧"); stopWordSet.add("唯有"); stopWordSet.add("啷当"); stopWordSet.add("喽"); stopWordSet.add("嗡"); stopWordSet.add("嘿嘿"); stopWordSet.add("因了"); stopWordSet.add("因着"); stopWordSet.add("在于"); stopWordSet.add("坚决"); stopWordSet.add("坚持"); stopWordSet.add("处在"); stopWordSet.add("处理"); stopWordSet.add("复杂"); stopWordSet.add("多么"); stopWordSet.add("多数"); stopWordSet.add("大力"); stopWordSet.add("大多数"); stopWordSet.add("大批"); stopWordSet.add("大量"); stopWordSet.add("失去"); stopWordSet.add("她是"); stopWordSet.add("她的"); stopWordSet.add("好"); stopWordSet.add("好的"); stopWordSet.add("好象"); stopWordSet.add("如同"); stopWordSet.add("如是"); stopWordSet.add("始而"); stopWordSet.add("存在"); stopWordSet.add("孰料"); stopWordSet.add("孰知"); stopWordSet.add("它们的"); stopWordSet.add("它是"); stopWordSet.add("它的"); stopWordSet.add("安全"); stopWordSet.add("完全"); stopWordSet.add("完成"); stopWordSet.add("实现"); stopWordSet.add("实际"); stopWordSet.add("宣布"); stopWordSet.add("容易"); stopWordSet.add("密切"); stopWordSet.add("对应"); stopWordSet.add("对待"); stopWordSet.add("对方"); stopWordSet.add("对比"); stopWordSet.add("小"); stopWordSet.add("少数"); stopWordSet.add("尔"); stopWordSet.add("尔尔"); stopWordSet.add("尤其"); stopWordSet.add("就是了"); stopWordSet.add("就要"); stopWordSet.add("属于"); stopWordSet.add("左右"); stopWordSet.add("巨大"); stopWordSet.add("巩固"); stopWordSet.add("已"); stopWordSet.add("已矣"); stopWordSet.add("已经"); stopWordSet.add("巴"); stopWordSet.add("巴巴"); stopWordSet.add("帮助"); stopWordSet.add("并不"); stopWordSet.add("并不是"); stopWordSet.add("广大"); stopWordSet.add("广泛"); stopWordSet.add("应当"); stopWordSet.add("应用"); stopWordSet.add("应该"); stopWordSet.add("庶乎"); stopWordSet.add("庶几"); stopWordSet.add("开展"); stopWordSet.add("引起"); stopWordSet.add("强烈"); stopWordSet.add("强调"); stopWordSet.add("归齐"); stopWordSet.add("当前"); stopWordSet.add("当地"); stopWordSet.add("当时"); stopWordSet.add("形成"); stopWordSet.add("彻底"); stopWordSet.add("彼时"); stopWordSet.add("往往"); stopWordSet.add("後来"); stopWordSet.add("後面"); stopWordSet.add("得了"); stopWordSet.add("得出"); stopWordSet.add("得到"); stopWordSet.add("心里"); stopWordSet.add("必然"); stopWordSet.add("必要"); stopWordSet.add("怎奈"); stopWordSet.add("怎麽"); stopWordSet.add("总是"); stopWordSet.add("总结"); stopWordSet.add("您们"); stopWordSet.add("您是"); stopWordSet.add("惟其"); stopWordSet.add("意思"); stopWordSet.add("愿意"); stopWordSet.add("成为"); stopWordSet.add("我是"); stopWordSet.add("我的"); stopWordSet.add("或则"); stopWordSet.add("或曰"); stopWordSet.add("战斗"); stopWordSet.add("所在"); stopWordSet.add("所幸"); stopWordSet.add("所有"); stopWordSet.add("所谓"); stopWordSet.add("扩大"); stopWordSet.add("掌握"); stopWordSet.add("接著"); stopWordSet.add("数/"); stopWordSet.add("整个"); stopWordSet.add("方便"); stopWordSet.add("方面"); stopWordSet.add("无"); stopWordSet.add("无法"); stopWordSet.add("既往"); stopWordSet.add("明显"); stopWordSet.add("明确"); stopWordSet.add("是不是"); stopWordSet.add("是以"); stopWordSet.add("是否"); stopWordSet.add("显然"); stopWordSet.add("显著"); stopWordSet.add("普通"); stopWordSet.add("普遍"); stopWordSet.add("曾"); stopWordSet.add("曾经"); stopWordSet.add("替代"); stopWordSet.add("最"); stopWordSet.add("最后"); stopWordSet.add("最大"); stopWordSet.add("最好"); stopWordSet.add("最後"); stopWordSet.add("最近"); stopWordSet.add("最高"); stopWordSet.add("有利"); stopWordSet.add("有力"); stopWordSet.add("有及"); stopWordSet.add("有所"); stopWordSet.add("有效"); stopWordSet.add("有时"); stopWordSet.add("有点"); stopWordSet.add("有的是"); stopWordSet.add("有着"); stopWordSet.add("有著"); stopWordSet.add("末##末"); stopWordSet.add("本地"); stopWordSet.add("来自"); stopWordSet.add("来说"); stopWordSet.add("构成"); stopWordSet.add("某某"); stopWordSet.add("根本"); stopWordSet.add("欢迎"); stopWordSet.add("欤"); stopWordSet.add("正值"); stopWordSet.add("正在"); stopWordSet.add("正巧"); stopWordSet.add("正常"); stopWordSet.add("正是"); stopWordSet.add("此地"); stopWordSet.add("此处"); stopWordSet.add("此时"); stopWordSet.add("此次"); stopWordSet.add("每个"); stopWordSet.add("每天"); stopWordSet.add("每年"); stopWordSet.add("比及"); stopWordSet.add("比较"); stopWordSet.add("没奈何"); stopWordSet.add("注意"); stopWordSet.add("深入"); stopWordSet.add("清楚"); stopWordSet.add("满足"); stopWordSet.add("然後"); stopWordSet.add("特别是"); stopWordSet.add("特殊"); stopWordSet.add("特点"); stopWordSet.add("犹且"); stopWordSet.add("犹自"); stopWordSet.add("现代"); stopWordSet.add("现在"); stopWordSet.add("甚且"); stopWordSet.add("甚或"); stopWordSet.add("甚至于"); stopWordSet.add("用来"); stopWordSet.add("由是"); stopWordSet.add("由此"); stopWordSet.add("目前"); stopWordSet.add("直到"); stopWordSet.add("直接"); stopWordSet.add("相似"); stopWordSet.add("相信"); stopWordSet.add("相反"); stopWordSet.add("相同"); stopWordSet.add("相对"); stopWordSet.add("相应"); stopWordSet.add("相当"); stopWordSet.add("相等"); stopWordSet.add("看出"); stopWordSet.add("看到"); stopWordSet.add("看看"); stopWordSet.add("看见"); stopWordSet.add("真是"); stopWordSet.add("真正"); stopWordSet.add("眨眼"); stopWordSet.add("矣乎"); stopWordSet.add("矣哉"); stopWordSet.add("知道"); stopWordSet.add("确定"); stopWordSet.add("种"); stopWordSet.add("积极"); stopWordSet.add("移动"); stopWordSet.add("突出"); stopWordSet.add("突然"); stopWordSet.add("立即"); stopWordSet.add("竟而"); stopWordSet.add("第二"); stopWordSet.add("类如"); stopWordSet.add("练习"); stopWordSet.add("组成"); stopWordSet.add("结合"); stopWordSet.add("继后"); stopWordSet.add("继续"); stopWordSet.add("维持"); stopWordSet.add("考虑"); stopWordSet.add("联系"); stopWordSet.add("能否"); stopWordSet.add("能够"); stopWordSet.add("自后"); stopWordSet.add("自打"); stopWordSet.add("至今"); stopWordSet.add("至若"); stopWordSet.add("致"); stopWordSet.add("般的"); stopWordSet.add("良好"); stopWordSet.add("若夫"); stopWordSet.add("若果"); stopWordSet.add("范围"); stopWordSet.add("莫不然"); stopWordSet.add("获得"); stopWordSet.add("行为"); stopWordSet.add("行动"); stopWordSet.add("表明"); stopWordSet.add("表示"); stopWordSet.add("要求"); stopWordSet.add("规定"); stopWordSet.add("觉得"); stopWordSet.add("譬喻"); stopWordSet.add("认为"); stopWordSet.add("认真"); stopWordSet.add("认识"); stopWordSet.add("许多"); stopWordSet.add("设或"); stopWordSet.add("诚如"); stopWordSet.add("说明"); stopWordSet.add("说来"); stopWordSet.add("说说"); stopWordSet.add("诸"); stopWordSet.add("诸如"); stopWordSet.add("谁人"); stopWordSet.add("谁料"); stopWordSet.add("贼死"); stopWordSet.add("赖以"); stopWordSet.add("距"); stopWordSet.add("转动"); stopWordSet.add("转变"); stopWordSet.add("转贴"); stopWordSet.add("达到"); stopWordSet.add("迅速"); stopWordSet.add("过去"); stopWordSet.add("过来"); stopWordSet.add("运用"); stopWordSet.add("还要"); stopWordSet.add("这一来"); stopWordSet.add("这次"); stopWordSet.add("这点"); stopWordSet.add("这种"); stopWordSet.add("这般"); stopWordSet.add("这麽"); stopWordSet.add("进入"); stopWordSet.add("进步"); stopWordSet.add("进行"); stopWordSet.add("适应"); stopWordSet.add("适当"); stopWordSet.add("适用"); stopWordSet.add("逐步"); stopWordSet.add("逐渐"); stopWordSet.add("通常"); stopWordSet.add("造成"); stopWordSet.add("遇到"); stopWordSet.add("遭到"); stopWordSet.add("遵循"); stopWordSet.add("避免"); stopWordSet.add("那般"); stopWordSet.add("那麽"); stopWordSet.add("部分"); stopWordSet.add("采取"); stopWordSet.add("里面"); stopWordSet.add("重大"); stopWordSet.add("重新"); stopWordSet.add("重要"); stopWordSet.add("针对"); stopWordSet.add("问题"); stopWordSet.add("防止"); stopWordSet.add("附近"); stopWordSet.add("限制"); stopWordSet.add("随后"); stopWordSet.add("随时"); stopWordSet.add("随著"); stopWordSet.add("难道说"); stopWordSet.add("集中"); stopWordSet.add("需要"); stopWordSet.add("非特"); stopWordSet.add("非独"); stopWordSet.add("高兴"); stopWordSet.add("若果"); } /** * @param content 传入需要分词的字符串 * @param B 选择是否智能分词,为false将精细到最小颗粒分词 * * @return 分完词的 List<String> * @throws * @Title: segStr * @Description: TODO * @author HuDaoquan */ public static List<String> segStr(String content, Boolean B) { List<String> list = new ArrayList<>(); try { // 创建分词对象 StringReader sr = new StringReader(content); IKSegmenter ik = new IKSegmenter(sr, B); Lexeme lex; // 分词 while ((lex = ik.next()) != null) { // 去除停用词 if (stopWordSet.contains(lex.getLexemeText())) { continue; } list.add(lex.getLexemeText()); } } catch (IOException e) { System.out.println("IK分词器分词报错:" + e); } return list; } public static void main(String[] args) { System.out.println(segStr("笔记本电脑", false)); } }
HuDaoquan/HomeworkSimilarity
src/main/java/pers/hdq/util/IKUtils.java
870
package com.yl.lib.privacy_proxy; import android.os.Build; import androidx.annotation.Keep; import com.yl.lib.privacy_annotation.PrivacyClassProxy; import com.yl.lib.privacy_annotation.PrivacyFieldProxy; /** * @author yulun * @since 2022-03-03 19:42 * 注意变量的初始化是在类初始化的时候就执行了,所以这里只适合hook不可变的变量 */ @Keep @PrivacyClassProxy public class ProxyProxyField { @PrivacyFieldProxy( originalClass = android.os.Build.class, originalFieldName = "SERIAL" ) public static final String proxySerial = PrivacyProxyCall.Proxy.getSerial(); // 虽然能保证全局只读取一次,但检测机构是抓包识别的,好像也没什么用,他们好像不能检测变量的读取 @PrivacyFieldProxy( originalClass = android.os.Build.class, originalFieldName = "BRAND" ) public static final String proxyBrand = PrivacyProxyCall.Proxy.getBrand(); }
allenymt/PrivacySentry
privacy-proxy/src/main/java/com/yl/lib/privacy_proxy/ProxyProxyField.java
871
package com.xu.drools.rule.complexProblem; import com.xu.drools.bean.Golfer; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; /** * 使用kmodule的方式调用drools * /resources/META-INF/kmodule.xml * 高尔夫球员站位问题 */ public class GolferProblem { /** * 已知有四个高尔夫球员,他们的名字是Fred,Joe,Bob,Tom; * 今天他们分别穿着红色,蓝色,橙色,以及格子衣服,并且他们按照从左往右的顺序站成一排。 * 我们将最左边的位置定为1,最右边的位置定为4,中间依次是2,3位置。 * 现在我们了解的情况是: * 1.高尔夫球员Fred,目前不知道他的位置和衣服颜色 * 2.Fred右边紧挨着的球员穿蓝色衣服 * 3.Joe排在第2个位置 * 4.Bob穿着格子短裤 * 5.Tom没有排在第1位或第4位,也没有穿橙色衣服 * 请问,这四名球员的位置和衣服颜色。 */ public static void main(final String[] args) { KieContainer kc = KieServices.Factory.get().getKieClasspathContainer(); System.out.println(kc.verify().getMessages().toString()); execute(kc); } private static void execute(KieContainer kc) { KieSession ksession = kc.newKieSession("mingKS"); String[] names = new String[]{"Fred", "Joe", "Bob", "Tom"}; String[] colors = new String[]{"red", "blue", "plaid", "orange"}; int[] positions = new int[]{1, 2, 3, 4}; for (String name : names) { for (String color : colors) { for (int position : positions) { ksession.insert(new Golfer(name, color, position)); } } } ksession.fireAllRules(); ksession.dispose(); } }
MyHerux/drools-springboot
src/main/java/com/xu/drools/rule/complexProblem/GolferProblem.java
873
/** * File: min_path_sum.java * Created Time: 2023-07-10 * Author: krahets ([email protected]) */ package chapter_dynamic_programming; import java.util.Arrays; public class min_path_sum { /* 最小路径和:暴力搜索 */ static int minPathSumDFS(int[][] grid, int i, int j) { // 若为左上角单元格,则终止搜索 if (i == 0 && j == 0) { return grid[0][0]; } // 若行列索引越界,则返回 +∞ 代价 if (i < 0 || j < 0) { return Integer.MAX_VALUE; } // 计算从左上角到 (i-1, j) 和 (i, j-1) 的最小路径代价 int up = minPathSumDFS(grid, i - 1, j); int left = minPathSumDFS(grid, i, j - 1); // 返回从左上角到 (i, j) 的最小路径代价 return Math.min(left, up) + grid[i][j]; } /* 最小路径和:记忆化搜索 */ static int minPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) { // 若为左上角单元格,则终止搜索 if (i == 0 && j == 0) { return grid[0][0]; } // 若行列索引越界,则返回 +∞ 代价 if (i < 0 || j < 0) { return Integer.MAX_VALUE; } // 若已有记录,则直接返回 if (mem[i][j] != -1) { return mem[i][j]; } // 左边和上边单元格的最小路径代价 int up = minPathSumDFSMem(grid, mem, i - 1, j); int left = minPathSumDFSMem(grid, mem, i, j - 1); // 记录并返回左上角到 (i, j) 的最小路径代价 mem[i][j] = Math.min(left, up) + grid[i][j]; return mem[i][j]; } /* 最小路径和:动态规划 */ static int minPathSumDP(int[][] grid) { int n = grid.length, m = grid[0].length; // 初始化 dp 表 int[][] dp = new int[n][m]; dp[0][0] = grid[0][0]; // 状态转移:首行 for (int j = 1; j < m; j++) { dp[0][j] = dp[0][j - 1] + grid[0][j]; } // 状态转移:首列 for (int i = 1; i < n; i++) { dp[i][0] = dp[i - 1][0] + grid[i][0]; } // 状态转移:其余行和列 for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]; } } return dp[n - 1][m - 1]; } /* 最小路径和:空间优化后的动态规划 */ static int minPathSumDPComp(int[][] grid) { int n = grid.length, m = grid[0].length; // 初始化 dp 表 int[] dp = new int[m]; // 状态转移:首行 dp[0] = grid[0][0]; for (int j = 1; j < m; j++) { dp[j] = dp[j - 1] + grid[0][j]; } // 状态转移:其余行 for (int i = 1; i < n; i++) { // 状态转移:首列 dp[0] = dp[0] + grid[i][0]; // 状态转移:其余列 for (int j = 1; j < m; j++) { dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j]; } } return dp[m - 1]; } public static void main(String[] args) { int[][] grid = { { 1, 3, 1, 5 }, { 2, 2, 4, 2 }, { 5, 3, 2, 1 }, { 4, 3, 5, 2 } }; int n = grid.length, m = grid[0].length; // 暴力搜索 int res = minPathSumDFS(grid, n - 1, m - 1); System.out.println("从左上角到右下角的最小路径和为 " + res); // 记忆化搜索 int[][] mem = new int[n][m]; for (int[] row : mem) { Arrays.fill(row, -1); } res = minPathSumDFSMem(grid, mem, n - 1, m - 1); System.out.println("从左上角到右下角的最小路径和为 " + res); // 动态规划 res = minPathSumDP(grid); System.out.println("从左上角到右下角的最小路径和为 " + res); // 空间优化后的动态规划 res = minPathSumDPComp(grid); System.out.println("从左上角到右下角的最小路径和为 " + res); } }
krahets/hello-algo
codes/java/chapter_dynamic_programming/min_path_sum.java
877
package cn.hutool.core.map; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; /** * 自定义键和值转换的的Map<br> * 继承此类后,通过实现{@link #customKey(Object)}和{@link #customValue(Object)},按照给定规则加入到map或获取值。 * * @param <K> 键类型 * @param <V> 值类型 * @author Looly * @since 5.8.0 */ public abstract class TransMap<K, V> extends MapWrapper<K, V> { private static final long serialVersionUID = 1L; /** * 构造<br> * 通过传入一个Map从而确定Map的类型,子类需创建一个空的Map,而非传入一个已有Map,否则值可能会被修改 * * @param mapFactory 空Map创建工厂 * @since 5.8.0 */ public TransMap(Supplier<Map<K, V>> mapFactory) { super(mapFactory); } /** * 构造<br> * 通过传入一个Map从而确定Map的类型,子类需创建一个空的Map,而非传入一个已有Map,否则值可能会被修改 * * @param emptyMap Map 被包装的Map,必须为空Map,否则自定义key会无效 * @since 3.1.2 */ public TransMap(Map<K, V> emptyMap) { super(emptyMap); } @Override public V get(Object key) { return super.get(customKey(key)); } @Override public V put(K key, V value) { return super.put(customKey(key), customValue(value)); } @Override public void putAll(Map<? extends K, ? extends V> m) { m.forEach(this::put); } @Override public boolean containsKey(Object key) { return super.containsKey(customKey(key)); } @Override public V remove(Object key) { return super.remove(customKey(key)); } @Override public boolean remove(Object key, Object value) { return super.remove(customKey(key), customValue(value)); } @Override public boolean replace(K key, V oldValue, V newValue) { return super.replace(customKey(key), customValue(oldValue), customValue(newValue)); } @Override public V replace(K key, V value) { return super.replace(customKey(key), customValue(value)); } //---------------------------------------------------------------------------- Override default methods start @Override public V getOrDefault(Object key, V defaultValue) { return super.getOrDefault(customKey(key), customValue(defaultValue)); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return super.computeIfPresent(customKey(key), (k, v) -> remappingFunction.apply(customKey(k), customValue(v))); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return super.compute(customKey(key), (k, v) -> remappingFunction.apply(customKey(k), customValue(v))); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { return super.merge(customKey(key), customValue(value), (v1, v2) -> remappingFunction.apply(customValue(v1), customValue(v2))); } @Override public V putIfAbsent(K key, V value) { return super.putIfAbsent(customKey(key), customValue(value)); } @Override public V computeIfAbsent(final K key, final Function<? super K, ? extends V> mappingFunction) { return super.computeIfAbsent(customKey(key), mappingFunction); } //---------------------------------------------------------------------------- Override default methods end /** * 自定义键 * * @param key KEY * @return 自定义KEY */ protected abstract K customKey(Object key); /** * 自定义值 * * @param value 值 * @return 自定义值 */ protected abstract V customValue(Object value); }
dromara/hutool
hutool-core/src/main/java/cn/hutool/core/map/TransMap.java
879
H 1518594579 tags: DP, String, Interval DP - 给两个string S, T. 检验他们是不是scramble string. - scramble string 定义: string可以被分拆成binary tree的形式, 也就是切割成substring; - 旋转了不是leaf的node之后, 形成新的substring, 这就是原来string的 scramble. #### Interval DP 区间型 - 降维打击, 分割, 按照长度来dp. - dp[i][j][k]: 数组S从index i 开始, T从index j 开始, 长度为k的子串, 是否为scramble string ##### Break down - 一切两半以后, 看两种情况: , 或者不rotate这两半. 对于这些substring, 各自验证他们是否scramble. - 不rotate分割的两半: S[part1] 对应 T[part1] && S[part2] 对应 T[part2]. - rotate分割的两半: S[part1] 对应 T[part2] && S[part2] 对应 T[part1]. ##### Initialization - len == 1的时候, 其实无法旋转, 也就是看S,T的相对应的index是否字符相等. - initialization非常非常重要. 很神奇, 这个initailization 打好了DP的基础, 后面一蹴而就, 用数学表达式就算出了结果. - input s1, s2 在整个题目的主要内容里面, 几乎没有用到, 只是用在initialization时候. - More details, 看解答 ``` /* Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / \ gr eat / \ / \ g r e at / \ a t To scramble the string, we may choose any non-leaf node and swap its two children. For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". rgeat / \ rg eat / \ / \ r g e at / \ a t We say that "rgeat" is a scrambled string of "great". Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". rgtae / \ rg tae / \ / \ r g ta e / \ t a We say that "rgtae" is a scrambled string of "great". Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. */ /* Thoughts: Want to determin the given string S can be scramble/rotate to T. With the tree formation, it leads us to think of the string in partition: can S[i,j] be scambled to T[i,j]? If all substrings can be in scrambled format, it'll return true. dp[i][j][h][k]: can S(i, j) be scrambled to T(h, k)? Reduce it to dp[i][j][k]: starting from index i for S, index j for T, with length k. Can the substrings be scramble? End: want dp[0][0][n] to be srambled. Need size to be boolean dp[n][n][n + 1] with len == 0, always false with len == 1, if S[i]==T[j], then true. with len == 2, do dp; increase length from 1 ~ len, perform dp. Consider two conditions: rotate parent string || not rotating parent string */ class Solution { public boolean isScramble(String s1, String s2) { if (s1 == null || s2 == null) { return s1 == null && s2 == null; } if (s1.length() != s2.length()) { return false; } if (s1.equals(s2)) { return true; } int n = s1.length(); boolean[][][] dp = new boolean[n][n][n + 1]; int len = 1; // Initialize with len = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j][1] = s1.charAt(i) == s2.charAt(j); } } // len = 2 for (len = 2; len <= n; len++) { for (int i = 0; i <= n - len; i++) { for (int j = 0; j <= n - len; j++) { for (int w = 1; w < len; w++) { // w = length of 1st substring dp[i][j][len] |= dp[i][j][w] && dp[i + w][j + w][len - w]; // not rotating parent string dp[i][j][len] |= dp[i][j + (len - w)][w] && dp[i + w][j][len - w]; // not rotating parent string } } } } return dp[0][0][n]; } } /* Thoughts: 两个string, 代号 S, T 中间砍一刀, 分开两边. 要么是左右交换, 要么是不交换. 首先有了dp[i][j][k][h]: 分隔开来的S[i, j] 跟 T[k, h]是否是scramble string? want to have dp[0][n][0][n] == true 变成了4维数组. 优化: 4维数组, 但是自由度只有3: 有3个变量可以确定第四个变量: 因为scramble string的长度相等, 所以 j - I = h - k => h = j + k- I 也就是说, 我们可以降维, 不需要4维数组. 降维: 最后一个维度省略, 变成了 length为维度: *** dp[i][j][k]: 数组S从index i 开始, T从index j 开始, 长度为k的子串, 是否为scramble string? 等式需要细心写出来: 分割scramble过后, 原string定为S, 生成的string定为T 分割开来一刀, 分别割成 S1,S2, 和 T1,T2 假设S/T的总长都是k, 而分割点割在了位置为w的地方. 两种情况: 子序列不换位置: 要求分割开来的S1和T1是scramble, S2和T2是scramble S1和T1的关系: dp[i][j][w] => s1 从 index[i] 割 w length, s2从index[j]割了 w length; 是否是scramble string S2和T2的关系: dp[i + w][j + w][k - w] => S2和T2都在割过w length后的地方, 也就是i+w, j+w; 长度是总长减去w: k - w. 子序列换位置:要求分开的s1和s2换位置; 也就是s1对应的t1, 现在跑到了后面的位置 S1和T1的关系: s1在原地, t1换到了后面: t1还是w length, 所以位置变成了 j + (k - w) S2和T2的关系: s2照旧在i+w的位置, t2换到了最前面: index j 综合上面的 情况, 并且让w循环[1, k-1] dp[i][j][k] = OR{dp[i][j][w] && dp[i + w][j + w][k - w]}, where w = [1, k-1] OR OR{dp[i][j + k - w][w] && dp[i + w][j][k - w]}, where w = [1, k-1] */ class Solution { public boolean isScramble(String s1, String s2) { if (s1 == null || s2 == null || s1.length() != s2.length()) { return false; } int n = s1.length(); boolean[][][] dp = new boolean[n][n][n + 1]; // len = 1 for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dp[i][j][1] = s1.charAt(i) == s2.charAt(j); } } // len = 2 for (int len = 2; len <= n; len++) { for (int i = 0; i <= n - len; i++) { for (int j = 0; j <= n - len; j++) { // dp[i][j][len] = false; // default is false as well for (int w = 1; w < len; w++) { dp[i][j][len] |= (dp[i][j][w] && dp[i + w][j + w][len - w]); dp[i][j][len] |= (dp[i][j + len - w][w] && dp[i + w][j][len - w]); } } } } return dp[0][0][n]; } } ```
awangdev/leet-code
Java/Scramble String.java
880
package io.mycat.memory; import com.google.common.annotations.VisibleForTesting; import io.mycat.config.model.SystemConfig; import io.mycat.memory.unsafe.Platform; import io.mycat.memory.unsafe.memory.mm.DataNodeMemoryManager; import io.mycat.memory.unsafe.memory.mm.MemoryManager; import io.mycat.memory.unsafe.memory.mm.ResultMergeMemoryManager; import io.mycat.memory.unsafe.storage.DataNodeDiskManager; import io.mycat.memory.unsafe.storage.SerializerManager; import io.mycat.memory.unsafe.utils.JavaUtils; import io.mycat.memory.unsafe.utils.MycatPropertyConf; import org.apache.log4j.Logger; /** * Created by zagnix on 2016/6/2. * Mycat内存管理工具类 * 规划为三部分内存:结果集处理内存,系统预留内存,网络处理内存 * 其中网络处理内存部分全部为Direct Memory * 结果集内存分为Direct Memory 和 Heap Memory,但目前仅使用Direct Memory * 系统预留内存为 Heap Memory。 * 系统运行时,必须设置-XX:MaxDirectMemorySize 和 -Xmx JVM参数 * -Xmx1024m -Xmn512m -XX:MaxDirectMemorySize=2048m -Xss256K -XX:+UseParallelGC */ public class MyCatMemory { private static Logger LOGGER = Logger.getLogger(MyCatMemory.class); public final static double DIRECT_SAFETY_FRACTION = 0.7; private final long systemReserveBufferSize; private final long memoryPageSize; private final long spillsFileBufferSize; private final long resultSetBufferSize; private final int numCores; /** * 内存管理相关关键类 */ private final MycatPropertyConf conf; private final MemoryManager resultMergeMemoryManager; private final DataNodeDiskManager blockManager; private final SerializerManager serializerManager; private final SystemConfig system; public MyCatMemory(SystemConfig system,long totalNetWorkBufferSize) throws NoSuchFieldException, IllegalAccessException { this.system = system; LOGGER.info("useOffHeapForMerge = " + system.getUseOffHeapForMerge()); LOGGER.info("memoryPageSize = " + system.getMemoryPageSize()); LOGGER.info("spillsFileBufferSize = " + system.getSpillsFileBufferSize()); LOGGER.info("useStreamOutput = " + system.getUseStreamOutput()); LOGGER.info("systemReserveMemorySize = " + system.getSystemReserveMemorySize()); LOGGER.info("totalNetWorkBufferSize = " + JavaUtils.bytesToString2(totalNetWorkBufferSize)); LOGGER.info("dataNodeSortedTempDir = " + system.getDataNodeSortedTempDir()); this.conf = new MycatPropertyConf(); numCores = Runtime.getRuntime().availableProcessors(); this.systemReserveBufferSize = JavaUtils. byteStringAsBytes(system.getSystemReserveMemorySize()); this.memoryPageSize = JavaUtils. byteStringAsBytes(system.getMemoryPageSize()); this.spillsFileBufferSize = JavaUtils. byteStringAsBytes(system.getSpillsFileBufferSize()); /** * 目前merge,order by ,limit 没有使用On Heap内存 */ long maxOnHeapMemory = (Platform.getMaxHeapMemory()-systemReserveBufferSize); assert maxOnHeapMemory > 0; resultSetBufferSize = (long)((Platform.getMaxDirectMemory()-2*totalNetWorkBufferSize)*DIRECT_SAFETY_FRACTION); assert resultSetBufferSize > 0; /** * mycat.merge.memory.offHeap.enabled * mycat.buffer.pageSize * mycat.memory.offHeap.size * mycat.merge.file.buffer * mycat.direct.output.result * mycat.local.dir */ if(system.getUseOffHeapForMerge()== 1){ conf.set("mycat.memory.offHeap.enabled","true"); }else{ conf.set("mycat.memory.offHeap.enabled","false"); } if(system.getUseStreamOutput() == 1){ conf.set("mycat.stream.output.result","true"); }else{ conf.set("mycat.stream.output.result","false"); } if(system.getMemoryPageSize() != null){ conf.set("mycat.buffer.pageSize",system.getMemoryPageSize()); }else{ conf.set("mycat.buffer.pageSize","32k"); } if(system.getSpillsFileBufferSize() != null){ conf.set("mycat.merge.file.buffer",system.getSpillsFileBufferSize()); }else{ conf.set("mycat.merge.file.buffer","32k"); } conf.set("mycat.pointer.array.len","1k") .set("mycat.memory.offHeap.size", JavaUtils.bytesToString2(resultSetBufferSize)); LOGGER.info("mycat.memory.offHeap.size: " + JavaUtils.bytesToString2(resultSetBufferSize)); resultMergeMemoryManager = new ResultMergeMemoryManager(conf,numCores,maxOnHeapMemory); serializerManager = new SerializerManager(); blockManager = new DataNodeDiskManager(conf,true,serializerManager); } @VisibleForTesting public MyCatMemory() throws NoSuchFieldException, IllegalAccessException { this.system = null; this.systemReserveBufferSize = 0; this.memoryPageSize = 0; this.spillsFileBufferSize = 0; conf = new MycatPropertyConf(); numCores = Runtime.getRuntime().availableProcessors(); long maxOnHeapMemory = (Platform.getMaxHeapMemory()); assert maxOnHeapMemory > 0; resultSetBufferSize = (long)((Platform.getMaxDirectMemory())*DIRECT_SAFETY_FRACTION); assert resultSetBufferSize > 0; /** * mycat.memory.offHeap.enabled * mycat.buffer.pageSize * mycat.memory.offHeap.size * mycat.testing.memory * mycat.merge.file.buffer * mycat.direct.output.result * mycat.local.dir */ conf.set("mycat.memory.offHeap.enabled","true") .set("mycat.pointer.array.len","8K") .set("mycat.buffer.pageSize","1m") .set("mycat.memory.offHeap.size", JavaUtils.bytesToString2(resultSetBufferSize)) .set("mycat.stream.output.result","false"); LOGGER.info("mycat.memory.offHeap.size: " + JavaUtils.bytesToString2(resultSetBufferSize)); resultMergeMemoryManager = new ResultMergeMemoryManager(conf,numCores,maxOnHeapMemory); serializerManager = new SerializerManager(); blockManager = new DataNodeDiskManager(conf,true,serializerManager); } public MycatPropertyConf getConf() { return conf; } public long getResultSetBufferSize() { return resultSetBufferSize; } public MemoryManager getResultMergeMemoryManager() { return resultMergeMemoryManager; } public SerializerManager getSerializerManager() { return serializerManager; } public DataNodeDiskManager getBlockManager() { return blockManager; } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/memory/MyCatMemory.java
881
/* * The MIT License (MIT) * * Copyright (c) 2014-2023 [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.pagehelper; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.Properties; /** * QueryInterceptor 规范 * * 详细说明见文档:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/Interceptor.md * * @author liuzh/abel533/isea533 * @version 1.0.0 */ @Intercepts( { @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}), } ) public class QueryInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; Executor executor = (Executor) invocation.getTarget(); CacheKey cacheKey; BoundSql boundSql; //由于逻辑关系,只会进入一次 if(args.length == 4){ //4 个参数时 boundSql = ms.getBoundSql(parameter); cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); } else { //6 个参数时 cacheKey = (CacheKey) args[4]; boundSql = (BoundSql) args[5]; } //TODO 自己要进行的各种处理 //注:下面的方法可以根据自己的逻辑调用多次,在分页插件中,count 和 page 各调用了一次 return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } }
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/QueryInterceptor.java
887
package com.example.gsyvideoplayer; import static androidx.media3.common.PlaybackException.*; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.Uri; import android.os.Bundle; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.view.View; import android.widget.ImageView; import android.widget.Switch; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.media3.common.C; import androidx.media3.common.TrackGroup; import androidx.media3.common.TrackSelectionOverride; import androidx.media3.common.TrackSelectionParameters; import androidx.media3.exoplayer.SeekParameters; import androidx.media3.exoplayer.source.TrackGroupArray; import androidx.media3.exoplayer.trackselection.MappingTrackSelector; import androidx.media3.exoplayer.trackselection.TrackSelector; import com.example.gsyvideoplayer.databinding.ActivityDetailPlayerBinding; import com.google.common.collect.ImmutableList; import com.shuyu.gsyvideoplayer.GSYVideoManager; import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder; import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack; import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener; import com.shuyu.gsyvideoplayer.listener.LockClickListener; import com.shuyu.gsyvideoplayer.model.VideoOptionModel; import com.shuyu.gsyvideoplayer.utils.Debuger; import com.shuyu.gsyvideoplayer.utils.OrientationUtils; import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import tv.danmaku.ijk.media.exo2.Exo2PlayerManager; import tv.danmaku.ijk.media.exo2.IjkExo2MediaPlayer; import tv.danmaku.ijk.media.player.IjkMediaPlayer; public class DetailPlayer extends AppCompatActivity { private boolean isPlay; private boolean isPause; private OrientationUtils orientationUtils; private ActivityDetailPlayerBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityDetailPlayerBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); String url = getUrl(); //binding.detailPlayer.setUp(url, false, null, "测试视频"); //binding.detailPlayer.setLooping(true); //binding.detailPlayer.setShowPauseCover(false); //如果视频帧数太高导致卡画面不同步 //VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 30); //如果视频seek之后从头播放 // VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1); // List<VideoOptionModel> list = new ArrayList<>(); // list.add(videoOptionModel); // GSYVideoManager.instance().setOptionModelList(list); //GSYVideoManager.instance().setTimeOut(4000, true); /***************rtsp 配置****************/ /*VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_clear", 1); List<VideoOptionModel> list = new ArrayList<>(); list.add(videoOptionModel); VideoOptionModel videoOptionModel2 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "dns_cache_timeout", -1); VideoOptionModel videoOptionModel3 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_transport", "tcp"); VideoOptionModel videoOptionModel4 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_flags", "prefer_tcp"); VideoOptionModel videoOptionMode04 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0);//是否开启缓冲 VideoOptionModel videoOptionMode14 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "infbuf", 1);//是否限制输入缓存数 VideoOptionModel videoOptionMode15 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fflags", "nobuffer"); VideoOptionModel videoOptionMode17 = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzedmaxduration", 100);//分析码流时长:默认1024*1000 list.add(videoOptionModel2); list.add(videoOptionModel3); list.add(videoOptionModel4); list.add(videoOptionMode04); list.add(videoOptionMode14); list.add(videoOptionMode15); list.add(videoOptionMode17); GSYVideoManager.instance().setOptionModelList(list);*/ /***************rtsp 配置****************/ VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1); List<VideoOptionModel> list = new ArrayList<>(); list.add(videoOptionModel); GSYVideoManager.instance().setOptionModelList(list); /// ijk rtmp /*VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "protocol_whitelist", "crypto,file,http,https,tcp,tls,udp,rtmp,rtsp"); List<VideoOptionModel> list = new ArrayList<>(); list.add(videoOptionModel); GSYVideoManager.instance().setOptionModelList(list);*/ //增加封面 ImageView imageView = new ImageView(this); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.mipmap.xxx1); //binding.detailPlayer.setThumbImageView(imageView); resolveNormalVideoUI(); //外部辅助的旋转,帮助全屏 orientationUtils = new OrientationUtils(this, binding.detailPlayer); //初始化不打开外部的旋转 orientationUtils.setEnable(false); /**仅仅横屏旋转,不变直*/ //orientationUtils.setOnlyRotateLand(true); //ProxyCacheManager.DEFAULT_MAX_SIZE = 1024 * 1024 * 1024 * 1024; //ProxyCacheManager.DEFAULT_MAX_COUNT = 8; Map<String, String> header = new HashMap<>(); header.put("ee", "33"); header.put("allowCrossProtocolRedirects", "true"); header.put("User-Agent", "GSY"); GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder(); gsyVideoOption.setThumbImageView(imageView) .setIsTouchWiget(true) .setRotateViewAuto(false) //仅仅横屏旋转,不变直 //.setOnlyRotateLand(true) .setRotateWithSystem(false) .setLockLand(true) .setAutoFullWithSize(true) .setShowFullAnimation(false) .setNeedLockFull(true) .setUrl(url) .setMapHeadData(header) .setCacheWithPlay(false) .setSurfaceErrorPlay(false) .setVideoTitle("测试视频") .setVideoAllCallBack(new GSYSampleCallBack() { @Override public void onPrepared(String url, Object... objects) { Debuger.printfError("***** onPrepared **** " + objects[0]); Debuger.printfError("***** onPrepared **** " + objects[1]); super.onPrepared(url, objects); //开始播放了才能旋转和全屏 orientationUtils.setEnable(binding.detailPlayer.isRotateWithSystem()); isPlay = true; //设置 seek 的临近帧。 if (binding.detailPlayer.getGSYVideoManager().getPlayer() instanceof Exo2PlayerManager) { ((Exo2PlayerManager) binding.detailPlayer.getGSYVideoManager().getPlayer()).setSeekParameter(SeekParameters.NEXT_SYNC); Debuger.printfError("***** setSeekParameter **** "); } //设置 seek 的临近帧。 if (binding.detailPlayer.getGSYVideoManager().getPlayer() instanceof Exo2PlayerManager) { IjkExo2MediaPlayer player = ((IjkExo2MediaPlayer) binding.detailPlayer.getGSYVideoManager().getPlayer().getMediaPlayer()); MappingTrackSelector.MappedTrackInfo mappedTrackInfo = player.getTrackSelector().getCurrentMappedTrackInfo(); if (mappedTrackInfo != null) { for (int i = 0; i < mappedTrackInfo.getRendererCount(); i++) { TrackGroupArray rendererTrackGroups = mappedTrackInfo.getTrackGroups(i); if (C.TRACK_TYPE_AUDIO == mappedTrackInfo.getRendererType(i)) { //判断是否是音轨 for (int j = 0; j < rendererTrackGroups.length; j++) { TrackGroup trackGroup = rendererTrackGroups.get(j); Debuger.printfError("####### " + trackGroup.getFormat(0).toString() + " #######"); } } } } } } @Override public void onEnterFullscreen(String url, Object... objects) { super.onEnterFullscreen(url, objects); Debuger.printfError("***** onEnterFullscreen **** " + objects[0]);//title Debuger.printfError("***** onEnterFullscreen **** " + objects[1]);//当前全屏player } @Override public void onAutoComplete(String url, Object... objects) { super.onAutoComplete(url, objects); } @Override public void onClickStartError(String url, Object... objects) { super.onClickStartError(url, objects); } @Override public void onQuitFullscreen(String url, Object... objects) { super.onQuitFullscreen(url, objects); Debuger.printfError("***** onQuitFullscreen **** " + objects[0]);//title Debuger.printfError("***** onQuitFullscreen **** " + objects[1]);//当前非全屏player // ------- !!!如果不需要旋转屏幕,可以不调用!!!------- // 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false) if (orientationUtils != null) { orientationUtils.backToProtVideo(); } } @Override public void onPlayError(String url, Object... objects) { super.onPlayError(url, objects); if (objects[2] != null && binding.detailPlayer.getGSYVideoManager().getPlayer() instanceof Exo2PlayerManager) { Debuger.printfError("#######################"); int code = ((int) objects[2]); String errorStatus = "****"; switch (code) { case ERROR_CODE_UNSPECIFIED: errorStatus = "ERROR_CODE_UNSPECIFIED"; break; case ERROR_CODE_REMOTE_ERROR: errorStatus = "ERROR_CODE_REMOTE_ERROR"; break; case ERROR_CODE_BEHIND_LIVE_WINDOW: errorStatus = "ERROR_CODE_BEHIND_LIVE_WINDOW"; break; case ERROR_CODE_TIMEOUT: errorStatus = "ERROR_CODE_TIMEOUT"; break; case ERROR_CODE_FAILED_RUNTIME_CHECK: errorStatus = "ERROR_CODE_FAILED_RUNTIME_CHECK"; break; case ERROR_CODE_IO_UNSPECIFIED: errorStatus = "ERROR_CODE_IO_UNSPECIFIED"; break; case ERROR_CODE_IO_NETWORK_CONNECTION_FAILED: errorStatus = "ERROR_CODE_IO_NETWORK_CONNECTION_FAILED"; break; case ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT: errorStatus = "ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT"; break; case ERROR_CODE_IO_INVALID_HTTP_CONTENT_TYPE: errorStatus = "ERROR_CODE_IO_INVALID_HTTP_CONTENT_TYPE"; break; case ERROR_CODE_IO_BAD_HTTP_STATUS: errorStatus = "ERROR_CODE_IO_BAD_HTTP_STATUS"; break; case ERROR_CODE_IO_FILE_NOT_FOUND: errorStatus = "ERROR_CODE_IO_FILE_NOT_FOUND"; break; case ERROR_CODE_IO_NO_PERMISSION: errorStatus = "ERROR_CODE_IO_NO_PERMISSION"; break; case ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED: errorStatus = "ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED"; break; case ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE: errorStatus = "ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE"; break; case ERROR_CODE_PARSING_CONTAINER_MALFORMED: errorStatus = "ERROR_CODE_PARSING_CONTAINER_MALFORMED"; break; case ERROR_CODE_PARSING_MANIFEST_MALFORMED: errorStatus = "ERROR_CODE_PARSING_MANIFEST_MALFORMED"; break; case ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED: errorStatus = "ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED"; break; case ERROR_CODE_PARSING_MANIFEST_UNSUPPORTED: errorStatus = "ERROR_CODE_PARSING_MANIFEST_UNSUPPORTED"; break; case ERROR_CODE_DECODER_INIT_FAILED: errorStatus = "ERROR_CODE_DECODER_INIT_FAILED"; break; case ERROR_CODE_DECODER_QUERY_FAILED: errorStatus = "ERROR_CODE_DECODER_QUERY_FAILED"; break; case ERROR_CODE_DECODING_FAILED: errorStatus = "ERROR_CODE_DECODING_FAILED"; break; case ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES: errorStatus = "ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES"; break; case ERROR_CODE_DECODING_FORMAT_UNSUPPORTED: errorStatus = "ERROR_CODE_DECODING_FORMAT_UNSUPPORTED"; break; case ERROR_CODE_AUDIO_TRACK_INIT_FAILED: errorStatus = "ERROR_CODE_AUDIO_TRACK_INIT_FAILED"; break; case ERROR_CODE_AUDIO_TRACK_WRITE_FAILED: errorStatus = "ERROR_CODE_AUDIO_TRACK_WRITE_FAILED"; break; case ERROR_CODE_DRM_UNSPECIFIED: errorStatus = "ERROR_CODE_DRM_UNSPECIFIED"; break; case ERROR_CODE_DRM_SCHEME_UNSUPPORTED: errorStatus = "ERROR_CODE_DRM_SCHEME_UNSUPPORTED"; break; case ERROR_CODE_DRM_PROVISIONING_FAILED: errorStatus = "ERROR_CODE_DRM_PROVISIONING_FAILED"; break; case ERROR_CODE_DRM_CONTENT_ERROR: errorStatus = "ERROR_CODE_DRM_CONTENT_ERROR"; break; case ERROR_CODE_DRM_LICENSE_ACQUISITION_FAILED: errorStatus = "ERROR_CODE_DRM_LICENSE_ACQUISITION_FAILED"; break; case ERROR_CODE_DRM_DISALLOWED_OPERATION: errorStatus = "ERROR_CODE_DRM_DISALLOWED_OPERATION"; break; case ERROR_CODE_DRM_SYSTEM_ERROR: errorStatus = "ERROR_CODE_DRM_SYSTEM_ERROR"; break; case ERROR_CODE_DRM_DEVICE_REVOKED: errorStatus = "ERROR_CODE_DRM_DEVICE_REVOKED"; break; case ERROR_CODE_DRM_LICENSE_EXPIRED: errorStatus = "ERROR_CODE_DRM_LICENSE_EXPIRED"; break; case CUSTOM_ERROR_CODE_BASE: errorStatus = "CUSTOM_ERROR_CODE_BASE"; break; } Debuger.printfError(errorStatus); Debuger.printfError("#######################"); } } }) .setLockClickListener(new LockClickListener() { @Override public void onClick(View view, boolean lock) { if (orientationUtils != null) { //配合下方的onConfigurationChanged orientationUtils.setEnable(!lock); } } }) .setGSYVideoProgressListener(new GSYVideoProgressListener() { @Override public void onProgress(long progress, long secProgress, long currentPosition, long duration) { Debuger.printfLog(" progress " + progress + " secProgress " + secProgress + " currentPosition " + currentPosition + " duration " + duration); } }) .build(binding.detailPlayer); binding.detailPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //直接横屏 // ------- !!!如果不需要旋转屏幕,可以不调用!!!------- // 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false) orientationUtils.resolveByClick(); //第一个true是否需要隐藏actionbar,第二个true是否需要隐藏statusbar binding.detailPlayer.startWindowFullscreen(DetailPlayer.this, true, true); } }); binding.openBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fileSearch(); } }); ///exo 切换音轨 binding.change.setOnClickListener(new View.OnClickListener() { int index = 0; @Override public void onClick(View view) { if (binding.detailPlayer.getGSYVideoManager().getPlayer() instanceof Exo2PlayerManager) { IjkExo2MediaPlayer player = ((IjkExo2MediaPlayer) binding.detailPlayer.getGSYVideoManager().getPlayer().getMediaPlayer()); TrackSelector trackSelector = player.getTrackSelector(); MappingTrackSelector.MappedTrackInfo mappedTrackInfo = player.getTrackSelector().getCurrentMappedTrackInfo(); if (mappedTrackInfo != null) { for (int i = 0; i < mappedTrackInfo.getRendererCount(); i++) { TrackGroupArray rendererTrackGroups = mappedTrackInfo.getTrackGroups(i); if (C.TRACK_TYPE_AUDIO == mappedTrackInfo.getRendererType(i)) { //判断是否是音轨 if (index == 0) { index = 1; } else { index = 0; } if (rendererTrackGroups.length <= 1) { return; } TrackGroup trackGroup = rendererTrackGroups.get(index); TrackSelectionParameters parameters = trackSelector.getParameters().buildUpon() .setForceHighestSupportedBitrate(true) .setOverrideForType(new TrackSelectionOverride(trackGroup, 0)).build(); trackSelector.setParameters(parameters); } } } } } }); } @Override public void onBackPressed() { // ------- !!!如果不需要旋转屏幕,可以不调用!!!------- // 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false) if (orientationUtils != null) { orientationUtils.backToProtVideo(); } if (GSYVideoManager.backFromWindowFull(this)) { return; } super.onBackPressed(); } @Override protected void onPause() { getCurPlay().onVideoPause(); super.onPause(); isPause = true; } @Override protected void onResume() { getCurPlay().onVideoResume(false); super.onResume(); isPause = false; } @Override protected void onDestroy() { super.onDestroy(); if (isPlay) { getCurPlay().release(); } //GSYPreViewManager.instance().releaseMediaPlayer(); if (orientationUtils != null) orientationUtils.releaseListener(); } /** * orientationUtils 和 binding.detailPlayer.onConfigurationChanged 方法是用于触发屏幕旋转的 */ @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); //如果旋转了就全屏 if (isPlay && !isPause) { binding.detailPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true); } } private void resolveNormalVideoUI() { //增加title binding.detailPlayer.getTitleTextView().setVisibility(View.GONE); binding.detailPlayer.getBackButton().setVisibility(View.GONE); } private GSYVideoPlayer getCurPlay() { if (binding.detailPlayer.getFullWindowPlayer() != null) { return binding.detailPlayer.getFullWindowPlayer(); } return binding.detailPlayer; } private String getUrl() { //String url = "android.resource://" + getPackageName() + "/" + R.raw.test; //注意,用ijk模式播放raw视频,这个必须打开 GSYVideoManager.instance().enableRawPlay(getApplicationContext()); ///exo 播放 raw //String url = "rawresource://" + getPackageName() + "/" + R.raw.test; ///exo raw 支持 ///exo raw 支持 ///String url = "assets:///test1.mp4"; //断网自动重新链接,url前接上ijkhttphook: //String url = "ijkhttphook:https://res.exexm.com/cw_145225549855002"; //String url = "https://cos.icxl.xyz/c03328206d894477a3f8c9767a4de5649342908.mov"; //String url = "http://9890.vod.myqcloud.com/9890_4e292f9a3dd011e6b4078980237cc3d3.f20.mp4"; //String url = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"; // new mp4 //String url = "https://video.xintujing.cn/d0f2f304vodtranscq1251091601/e27f66955285890796832323682/v.f230.m3u8"; //String url = "https://teamcircle-test.s3.amazonaws.com/public/cbbe6181a0414339b8c20527741d3dd6.mp4"; //String url = "http://las-tech.org.cn/kwai/las-test_ld500d.flv";//flv 直播 //String url = "http://7xjmzj.com1.z0.glb.clouddn.com/20171026175005_JObCxCE2.mp4"; //String url = "http://hjq-1257036536.cos.ap-shanghai.myqcloud.com/m3u8/m1/oxcdes //String url = "http://ipsimg-huabei2.speiyou.cn/010/video/other/20180427/40288b156241ec6301624243bdf7021e/40288b156290270d0162a3e7eb2e0726/1524814477/movie.mp4"; //String url = "http://ipsimg-huabei2.speiyou.cn/010/video/other/20180424/40288b156290270d0162a3db8cdd033e/40288b156290270d0162a3e8207f074f/e787a64c-f2d0-48fe-896d-246af05f111a.mp4"; //String url = "http://video.7k.cn/app_video/20171202/6c8cf3ea/v.m3u8.mp4"; //String url = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8"; //String url = "rtmp://ctc-zhenjiang04.rt1.gensee.com/5324e855b28b453db7b0ec226598b76c_171391_0_8801038305_1591077225_205d01b8/video"; //String url = "http://video1.dgtle.com/backend%2F2020%2F3%2F0%2F%E6%88%91%E6%B2%A1%E6%9C%89%E7%BB%99%E4%B8%80%E5%8A%A08Pro%E5%81%9A%E8%AF%84%E6%B5%8B_%E5%8D%B4%E5%B8%A6%E7%9D%80%E5%AE%83%E6%BC%82%E6%B5%81.mp4_1080.mp4"; //String url = "http://yongtaizx.xyz/20191230/t2Axgh3k/index.m3u8"; //String url = "http://123.56.109.212:8035/users/bfe52074fba74247853caa764b522731/films/orig/aa4c3451-0468-452a-a189-bd064a1963e5-鹿鼎记下.mp4"; //String url = "http://static.hnyequ.cn/yequ_iOS/4940735da1227890e6a261937223e0d2_828x1472.mp4"; // 竖 //String url = "http://39.104.119.42/elevator-1.0/api/downFile?path=demo.ogv"; //String url = "http://pointshow.oss-cn-hangzhou.aliyuncs.com/transcode/ORIGINAL/Mnbc61586842828593.mp4";// 竖 //ssl error //String url = "http://qlqfj2ujf.hn-bkt.clouddn.com/aijianji-fuwupeixunshipin_index.m3u8"; //String url = "http://122.228.250.223/al.flv.huya.com/src/1394565191-1394565191-5989611887484993536-2789253838-10057-A-0-1-imgplus.flv?ali_dispatch_cold_stream=on&ali_redirect_ex_hot=0"; //String url = "http://1258557277.vod2.myqcloud.com/204551f3vodcq1258557277/8cc724f05285890813366287037/playlist_eof.m3u8"; //String url = "http://video.85tstss.com/record/live-nianhui-all_x264.mp4 "; //String url = "https://ops-aiops.oss-cn-hongkong.aliyuncs.com/vod/6103_42349_nvrendesuipian2020H265_play.ts"; //String url = "https://us-4.wl-cdn.com/hls/20200225/fde4f8ef394731f38d68fe6d601cfd56/index.m3u8"; //String url = "https://cdn61.ytbbs.tv/cn/tv/55550/55550-1/play.m3u8?md5=v4sI4lWlo4XojzeAjgBGaQ&expires=1521204012&token=55550"; //String url = "http://1253492636.vod2.myqcloud.com/2e5fc148vodgzp1253492636/d08af82d4564972819086152830/plHZZoSkje0A.mp4"; //String url = "rtsp://ajj:[email protected]:65523/h264/ch40/sub/av_stream"; //String url = "rtsp://ajj:[email protected]:65522/h264/ch15/sub/av_stream"; //String url = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov"; //String url = "http://s.swao.cn/o_1c4gm8o1nniu1had13bk1t0l1rq64m.mov"; //String url = "http://api.ciguang.tv/avideo/play?num=02-041-0491&type=flv&v=1&client=android"; //String url = "http://video.7k.cn/app_video/20171213/276d8195/v.m3u8.mp4"; //String url = "http://103.233.191.21/riak/riak-bucket/6469ac502e813a4c1df7c99f364e70c1.mp4"; //String url = "http://7xjmzj.com1.z0.glb.cl ouddn.com/20171026175005_JObCxCE2.mp4"; //String url = "https://media6.smartstudy.com/ae/07/3997/2/dest.m3u8"; //String url = "http://cdn.tiaobatiaoba.com/Upload/square/2017-11-02/1509585140_1279.mp4"; //String url = "http://hcjs2ra2rytd8v8np1q.exp.bcevod.com/mda-hegtjx8n5e8jt9zv/mda-hegtjx8n5e8jt9zv.m3u8"; //String url = "http://7xse1z.com1.z0.glb.clouddn.com/1491813192"; //String url = "http://ocgk7i2aj.bkt.clouddn.com/17651ac2-693c-47e9-b2d2-b731571bad37"; //String url = "http://111.198.24.133:83/yyy_login_server/pic/YB059284/97778276040859/1.mp4"; //String url = "http://vr.tudou.com/v2proxy/v?sid=95001&id=496378919&st=3&pw="; //String url = "http://pl-ali.youku.com/playlist/m3u8?type=mp4&ts=1490185963&keyframe=0&vid=XMjYxOTQ1Mzg2MA==&ep=ciadGkiFU8cF4SvajD8bYyuwJiYHXJZ3rHbN%2FrYDAcZuH%2BrC6DPcqJ21TPs%3D&sid=04901859548541247bba8&token=0524&ctype=12&ev=1&oip=976319194"; //String url = "http://hls.ciguang.tv/hdtv/video.m3u8"; //String url = "https://res.exexm.com/cw_145225549855002"; //String url = "http://storage.gzstv.net/uploads/media/huangmeiyan/jr05-09.mp4";//mepg //String url = "https://zh-files.oss-cn-qingdao.aliyuncs.com/20170808223928mJ1P3n57.mp4";//90度 String url = "http://7xjmzj.com1.z0.glb.clouddn.com/20171026175005_JObCxCE2.mp4";//90度 //String url = " String source1 = "http://9890.vod.myqcloud.com/9890_4e292f9a3dd011e6b4078980237cc3d3.f20.mp4"; //String url = "http://video.cdn.aizys.com/zzx3.9g.mkv";//long //String url = "rtsp://admin:[email protected]:554/h264/ch01/main/av_stream";//long //String url = "https://aliyuncdnsaascloud.xjhktv.com/video/A%20Lin%2B%E5%80%AA%E5%AD%90%E5%86%88-%E4%B8%8D%E5%B1%91%E5%AE%8C%E7%BE%8E%5B%E5%9B%BD%5D%5B1080P%5D.mp4";//track //String url = "rtmp://pull.sportslive.top/ECOTIME/2022?auth_key=1672823664-0-0-3c01d7b2ba9772929e792d8a2a5fac82"; //String url = "http://t.grelighting.cn/m3u8/TVBYNUdCUXN5MDhQSXJYTTJtN3lMUVZtTGJ0dlZXOEk=.m3u8"; //伪装 png\bmp 的m3u8 //String url = "https://cdn.clicli.cc/static/103701-50881f3281e9a0f6c8b2c96230b922a4.m3u8"; //伪装 png 的m3u8 return url; } private static final int READ_REQUEST_CODE = 42; @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (data == null || resultCode != Activity.RESULT_OK) return; if (requestCode == READ_REQUEST_CODE) { getPathForSearch(data.getData()); } } private void getPathForSearch(Uri uri) { String[] selectionArgs = new String[]{DocumentsContract.getDocumentId(uri).split(":")[1]}; Cursor cursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + "=?", selectionArgs, null); if (null != cursor) { if (cursor.moveToFirst()) { int index = cursor.getColumnIndex(MediaStore.Video.Media.DATA); if (index > -1) { binding.detailPlayer.setUp(uri.toString(), false, "File"); binding.detailPlayer.startPlayLogic(); } } cursor.close(); } } protected void fileSearch() { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("video/*"); startActivityForResult(intent, READ_REQUEST_CODE); } }
CarGuo/GSYVideoPlayer
app/src/main/java/com/example/gsyvideoplayer/DetailPlayer.java
888
package com.alibaba.arthas.tunnel.server; /** * @author hengyunabc 2020-10-30 * */ public class AgentClusterInfo { /** * agent本身以哪个ip连接到 tunnel server */ private String host; private int port; private String arthasVersion; /** * agent 连接到的 tunnel server 的ip 和 port */ private String clientConnectHost; private int clientConnectTunnelPort; public AgentClusterInfo() { } public AgentClusterInfo(AgentInfo agentInfo, String clientConnectHost, int clientConnectTunnelPort) { this.host = agentInfo.getHost(); this.port = agentInfo.getPort(); this.arthasVersion = agentInfo.getArthasVersion(); this.clientConnectHost = clientConnectHost; this.clientConnectTunnelPort = clientConnectTunnelPort; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getArthasVersion() { return arthasVersion; } public void setArthasVersion(String arthasVersion) { this.arthasVersion = arthasVersion; } public String getClientConnectHost() { return clientConnectHost; } public void setClientConnectHost(String clientConnectHost) { this.clientConnectHost = clientConnectHost; } public int getClientConnectTunnelPort() { return clientConnectTunnelPort; } public void setClientConnectTunnelPort(int clientConnectTunnelPort) { this.clientConnectTunnelPort = clientConnectTunnelPort; } }
alibaba/arthas
tunnel-server/src/main/java/com/alibaba/arthas/tunnel/server/AgentClusterInfo.java
889
package com.tencent.mars; import android.content.Context; import android.os.Handler; import com.tencent.mars.comm.PlatformComm; import com.tencent.mars.xlog.Log; import java.util.ArrayList; import java.util.Arrays; /** * Created by caoshaokun on 16/2/1. */ public class Mars { public static void loadDefaultMarsLibrary(){ try { System.loadLibrary("c++_shared"); System.loadLibrary("marsxlog"); System.loadLibrary("marsstn"); } catch (Throwable e) { Log.e("mars.Mars", "", e); } } private static volatile boolean hasInitialized = false; /** * APP创建时初始化平台回调 必须在onCreate方法前调用 * @param _context * @param _handler */ public static void init(Context _context, Handler _handler) { PlatformComm.init(_context, _handler); hasInitialized = true; } /** * APP启动时首次调用onCreate前必须显示调用 init(Context _context, Handler _handler)方法 和 * SignalTransmitNetwork设置长连接和短连接域名ip * @param isFirstStartup 是否首次进行mars create */ public static void onCreate(boolean isFirstStartup) { if (isFirstStartup && hasInitialized) { BaseEvent.onCreate(); } else if (!isFirstStartup) { BaseEvent.onCreate(); } else { /** * 首次启动但未调用init 无法进行BaseEvent create */ throw new IllegalStateException("function MarsCore.init must be executed before Mars.onCreate when application firststartup."); } } /** * APP退出时 销毁组件 */ public static void onDestroy() { BaseEvent.onDestroy(); } }
Tencent/mars
mars/libraries/mars_android_sdk/src/main/java/com/tencent/mars/Mars.java
890
package com.dianping.cat.context.context; import com.dianping.cat.Cat; import java.util.HashMap; import java.util.Map; /** * Cat.context接口实现类,用于context调用链传递,相关方法Cat.logRemoteCall()和Cat.logRemoteServer() * @author soar * @date 2019-01-10 */ public class CatContextImpl implements Cat.Context{ private Map<String, String> properties = new HashMap<>(16); @Override public void addProperty(String key, String value) { properties.put(key, value); } @Override public String getProperty(String key) { return properties.get(key); } }
dianping/cat
integration/context/CatContextImpl.java
893
class Solution { private List<Integer> arr = new ArrayList<>(); private int[] ts; private int inf = 1 << 30; public int closestCost(int[] baseCosts, int[] toppingCosts, int target) { ts = toppingCosts; dfs(0, 0); Collections.sort(arr); int d = inf, ans = inf; // 选择一种冰激淋基料 for (int x : baseCosts) { // 枚举子集和 for (int y : arr) { // 二分查找 int i = search(target - x - y); for (int j : new int[] {i, i - 1}) { if (j >= 0 && j < arr.size()) { int t = Math.abs(x + y + arr.get(j) - target); if (d > t || (d == t && ans > x + y + arr.get(j))) { d = t; ans = x + y + arr.get(j); } } } } } return ans; } private int search(int x) { int left = 0, right = arr.size(); while (left < right) { int mid = (left + right) >> 1; if (arr.get(mid) >= x) { right = mid; } else { left = mid + 1; } } return left; } private void dfs(int i, int t) { if (i >= ts.length) { arr.add(t); return; } dfs(i + 1, t); dfs(i + 1, t + ts[i]); } }
doocs/leetcode
solution/1700-1799/1774.Closest Dessert Cost/Solution.java