file_id
int64
1
66.7k
content
stringlengths
14
343k
repo
stringlengths
6
92
path
stringlengths
5
169
142
package com.xkcoding.session.controller; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.ObjectUtil; import com.xkcoding.session.constants.Consts; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * <p> * 页面跳转 Controller * </p> * * @author yangkai.shen * @date Created in 2018-12-19 19:57 */ @Controller @RequestMapping("/page") public class PageController { /** * 跳转到 首页 * * @param request 请求 */ @GetMapping("/index") public ModelAndView index(HttpServletRequest request) { ModelAndView mv = new ModelAndView(); String token = (String) request.getSession().getAttribute(Consts.SESSION_KEY); mv.setViewName("index"); mv.addObject("token", token); return mv; } /** * 跳转到 登录页 * * @param redirect 是否是跳转回来的 */ @GetMapping("/login") public ModelAndView login(Boolean redirect) { ModelAndView mv = new ModelAndView(); if (ObjectUtil.isNotNull(redirect) && ObjectUtil.equal(true, redirect)) { mv.addObject("message", "请先登录!"); } mv.setViewName("login"); return mv; } @GetMapping("/doLogin") public String doLogin(HttpSession session) { session.setAttribute(Consts.SESSION_KEY, IdUtil.fastUUID()); return "redirect:/page/index"; } }
xkcoding/spring-boot-demo
demo-session/src/main/java/com/xkcoding/session/controller/PageController.java
143
package org.apache.ibatis.thread; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.session.Configuration; import org.apache.log4j.Logger; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.core.NestedIOException; /** * 刷新使用进程 * * @author liubaoquan * */ public class Runnable implements java.lang.Runnable { public static Logger log = Logger.getLogger(Runnable.class); private String location; private Configuration configuration; private Long beforeTime = 0L; // 上一次刷新时间 private static boolean refresh = false; // 是否执行刷新 private static String mappingPath = "mappings"; // xml文件夹匹配字符串,需要根据需要修改 private static int delaySeconds = 10;// 延迟刷新秒数 private static int sleepSeconds = 1;// 休眠时间 private static boolean enabled = false; static { delaySeconds = PropertiesUtil.getInt("delaySeconds"); sleepSeconds = PropertiesUtil.getInt("sleepSeconds"); mappingPath = PropertiesUtil.getString("mappingPath"); enabled = "true".equals(PropertiesUtil.getString("enabled")); delaySeconds = delaySeconds == 0 ? 50 : delaySeconds; sleepSeconds = sleepSeconds == 0 ? 1 : sleepSeconds; mappingPath = StringUtils.isBlank(mappingPath) ? "mappings" : mappingPath; log.debug("[delaySeconds] " + delaySeconds); log.debug("[sleepSeconds] " + sleepSeconds); log.debug("[mappingPath] " + mappingPath); } public static boolean isRefresh() { return refresh; } public Runnable(String location, Configuration configuration) { this.location = location.replaceAll("\\\\", "/"); this.configuration = configuration; } @Override public void run() { location = location.substring("file [".length(), location.lastIndexOf(mappingPath) + mappingPath.length()); beforeTime = System.currentTimeMillis(); log.debug("[location] " + location); log.debug("[configuration] " + configuration); if (enabled) { start(this); } } public void start(final Runnable runnable) { new Thread(new java.lang.Runnable() { @Override public void run() { try { Thread.sleep(delaySeconds * 1000); } catch (InterruptedException e2) { e2.printStackTrace(); } refresh = true; System.out.println("========= Enabled refresh mybatis mapper ========="); while (true) { try { runnable.refresh(location, beforeTime); } catch (Exception e1) { e1.printStackTrace(); } try { Thread.sleep(sleepSeconds * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } /** * 执行刷新 * * @param filePath 刷新目录 * @param beforeTime 上次刷新时间 * @throws NestedIOException 解析异常 * @throws FileNotFoundException 文件未找到 */ public void refresh(String filePath, Long beforeTime) throws Exception { // 本次刷新时间 Long refrehTime = System.currentTimeMillis(); List<File> refreshs = this.getRefreshFile(new File(filePath), beforeTime); if (refreshs.size() > 0) { log.debug("refresh files:" + refreshs.size()); } for (int i = 0; i < refreshs.size(); i++) { System.out.println("Refresh file: " + mappingPath + StringUtils.substringAfterLast(refreshs.get(i).getAbsolutePath(), mappingPath)); log.debug("refresh file:" + refreshs.get(i).getAbsolutePath()); log.debug("refresh filename:" + refreshs.get(i).getName()); SqlSessionFactoryBean.refresh(new FileInputStream(refreshs.get(i)), refreshs.get(i).getAbsolutePath(), configuration); } // 如果刷新了文件,则修改刷新时间,否则不修改 if (refreshs.size() > 0) { this.beforeTime = refrehTime; } } /** * 获取需要刷新的文件列表 * * @param dir 目录 * @param beforeTime 上次刷新时间 * @return 刷新文件列表 */ public List<File> getRefreshFile(File dir, Long beforeTime) { List<File> refreshs = new ArrayList<File>(); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { refreshs.addAll(this.getRefreshFile(file, beforeTime)); } else if (file.isFile()) { if (this.check(file, beforeTime)) { refreshs.add(file); } } else { System.out.println("error file." + file.getName()); } } return refreshs; } /** * 判断文件是否需要刷新 * * @param file 文件 * @param beforeTime 上次刷新时间 * @return 需要刷新返回true,否则返回false */ public boolean check(File file, Long beforeTime) { if (file.lastModified() > beforeTime) { return true; } return false; } }
thinkgem/jeesite
src/main/java/org/apache/ibatis/thread/Runnable.java
144
/** * * IK 中文分词 版本 5.0 * IK Analyzer release 5.0 * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * 源代码由林良益([email protected])提供 * 版权声明 2012,乌龙茶工作室 * provided by Linliangyi and copyright 2012 by Oolong studio * */ package org.wltea.analyzer.dic; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 词典树分段,表示词典树的一个分枝 */ class DictSegment implements Comparable<DictSegment>{ //公用字典表,存储汉字 private static final Map<Character , Character> charMap = new ConcurrentHashMap<Character , Character>(16 , 0.95f); //数组大小上限 private static final int ARRAY_LENGTH_LIMIT = 3; //Map存储结构 private Map<Character , DictSegment> childrenMap; //数组方式存储结构 private DictSegment[] childrenArray; //当前节点上存储的字符 private Character nodeChar; //当前节点存储的Segment数目 //storeSize <=ARRAY_LENGTH_LIMIT ,使用数组存储, storeSize >ARRAY_LENGTH_LIMIT ,则使用Map存储 private int storeSize = 0; //当前DictSegment状态 ,默认 0 , 1表示从根节点到当前节点的路径表示一个词 private int nodeState = 0; DictSegment(Character nodeChar){ if(nodeChar == null){ throw new IllegalArgumentException("node char cannot be empty"); } this.nodeChar = nodeChar; } Character getNodeChar() { return nodeChar; } /* * 判断是否有下一个节点 */ boolean hasNextNode(){ return this.storeSize > 0; } /** * 匹配词段 * @param charArray * @return Hit */ Hit match(char[] charArray){ return this.match(charArray , 0 , charArray.length , null); } /** * 匹配词段 * @param charArray * @param begin * @param length * @return Hit */ Hit match(char[] charArray , int begin , int length){ return this.match(charArray , begin , length , null); } /** * 匹配词段 * @param charArray * @param begin * @param length * @param searchHit * @return Hit */ Hit match(char[] charArray , int begin , int length , Hit searchHit){ if(searchHit == null){ //如果hit为空,新建 searchHit= new Hit(); //设置hit的其实文本位置 searchHit.setBegin(begin); }else{ //否则要将HIT状态重置 searchHit.setUnmatch(); } //设置hit的当前处理位置 searchHit.setEnd(begin); Character keyChar = Character.valueOf(charArray[begin]); DictSegment ds = null; //引用实例变量为本地变量,避免查询时遇到更新的同步问题 DictSegment[] segmentArray = this.childrenArray; Map<Character , DictSegment> segmentMap = this.childrenMap; //STEP1 在节点中查找keyChar对应的DictSegment if(segmentArray != null){ //在数组中查找 DictSegment keySegment = new DictSegment(keyChar); int position = Arrays.binarySearch(segmentArray, 0 , this.storeSize , keySegment); if(position >= 0){ ds = segmentArray[position]; } }else if(segmentMap != null){ //在map中查找 ds = (DictSegment)segmentMap.get(keyChar); } //STEP2 找到DictSegment,判断词的匹配状态,是否继续递归,还是返回结果 if(ds != null){ if(length > 1){ //词未匹配完,继续往下搜索 return ds.match(charArray, begin + 1 , length - 1 , searchHit); }else if (length == 1){ //搜索最后一个char if(ds.nodeState == 1){ //添加HIT状态为完全匹配 searchHit.setMatch(); } if(ds.hasNextNode()){ //添加HIT状态为前缀匹配 searchHit.setPrefix(); //记录当前位置的DictSegment searchHit.setMatchedDictSegment(ds); } return searchHit; } } //STEP3 没有找到DictSegment, 将HIT设置为不匹配 return searchHit; } /** * 加载填充词典片段 * @param charArray */ void fillSegment(char[] charArray){ this.fillSegment(charArray, 0 , charArray.length , 1); } /** * 屏蔽词典中的一个词 * @param charArray */ void disableSegment(char[] charArray){ this.fillSegment(charArray, 0 , charArray.length , 0); } /** * 加载填充词典片段 * @param charArray * @param begin * @param length * @param enabled */ private synchronized void fillSegment(char[] charArray , int begin , int length , int enabled){ //获取字典表中的汉字对象 Character beginChar = Character.valueOf(charArray[begin]); Character keyChar = charMap.get(beginChar); //字典中没有该字,则将其添加入字典 if(keyChar == null){ charMap.put(beginChar, beginChar); keyChar = beginChar; } //搜索当前节点的存储,查询对应keyChar的keyChar,如果没有则创建 DictSegment ds = lookforSegment(keyChar , enabled); if(ds != null){ //处理keyChar对应的segment if(length > 1){ //词元还没有完全加入词典树 ds.fillSegment(charArray, begin + 1, length - 1 , enabled); }else if (length == 1){ //已经是词元的最后一个char,设置当前节点状态为enabled, //enabled=1表明一个完整的词,enabled=0表示从词典中屏蔽当前词 ds.nodeState = enabled; } } } /** * 查找本节点下对应的keyChar的segment * * @param keyChar * @param create =1如果没有找到,则创建新的segment ; =0如果没有找到,不创建,返回null * @return */ private DictSegment lookforSegment(Character keyChar , int create){ DictSegment ds = null; if(this.storeSize <= ARRAY_LENGTH_LIMIT){ //获取数组容器,如果数组未创建则创建数组 DictSegment[] segmentArray = getChildrenArray(); //搜寻数组 DictSegment keySegment = new DictSegment(keyChar); int position = Arrays.binarySearch(segmentArray, 0 , this.storeSize, keySegment); if(position >= 0){ ds = segmentArray[position]; } //遍历数组后没有找到对应的segment if(ds == null && create == 1){ ds = keySegment; if(this.storeSize < ARRAY_LENGTH_LIMIT){ //数组容量未满,使用数组存储 segmentArray[this.storeSize] = ds; //segment数目+1 this.storeSize++; Arrays.sort(segmentArray , 0 , this.storeSize); }else{ //数组容量已满,切换Map存储 //获取Map容器,如果Map未创建,则创建Map Map<Character , DictSegment> segmentMap = getChildrenMap(); //将数组中的segment迁移到Map中 migrate(segmentArray , segmentMap); //存储新的segment segmentMap.put(keyChar, ds); //segment数目+1 , 必须在释放数组前执行storeSize++ , 确保极端情况下,不会取到空的数组 this.storeSize++; //释放当前的数组引用 this.childrenArray = null; } } }else{ //获取Map容器,如果Map未创建,则创建Map Map<Character , DictSegment> segmentMap = getChildrenMap(); //搜索Map ds = (DictSegment)segmentMap.get(keyChar); if(ds == null && create == 1){ //构造新的segment ds = new DictSegment(keyChar); segmentMap.put(keyChar , ds); //当前节点存储segment数目+1 this.storeSize ++; } } return ds; } /** * 获取数组容器 * 线程同步方法 */ private DictSegment[] getChildrenArray(){ synchronized(this){ if(this.childrenArray == null){ this.childrenArray = new DictSegment[ARRAY_LENGTH_LIMIT]; } } return this.childrenArray; } /** * 获取Map容器 * 线程同步方法 */ private Map<Character , DictSegment> getChildrenMap(){ synchronized(this){ if(this.childrenMap == null){ this.childrenMap = new ConcurrentHashMap<Character, DictSegment>(ARRAY_LENGTH_LIMIT * 2,0.8f); } } return this.childrenMap; } /** * 将数组中的segment迁移到Map中 * @param segmentArray */ private void migrate(DictSegment[] segmentArray , Map<Character , DictSegment> segmentMap){ for(DictSegment segment : segmentArray){ if(segment != null){ segmentMap.put(segment.nodeChar, segment); } } } /** * 实现Comparable接口 * @param o * @return int */ public int compareTo(DictSegment o) { //对当前节点存储的char进行比较 return this.nodeChar.compareTo(o.nodeChar); } }
infinilabs/analysis-ik
core/src/main/java/org/wltea/analyzer/dic/DictSegment.java
145
package org.nutz.dao; import java.io.Serializable; import java.lang.reflect.Field; import java.util.Map; import org.nutz.dao.entity.Entity; import org.nutz.dao.entity.MappingField; import org.nutz.dao.jdbc.ValueAdaptor; import org.nutz.dao.util.Daos; import org.nutz.json.Json; import org.nutz.lang.Mirror; import org.nutz.lang.Strings; import org.nutz.lang.util.Callback2; import org.nutz.lang.util.NutMap; /** * 名值链。 * <p> * 通过 add 方法,建立一条名值对的链表 * * @author zozoh([email protected]) * @author Wendal([email protected]) * @author lzxz1234 */ public abstract class Chain implements Serializable { private static final long serialVersionUID = 1L; /** * 建立一条名值链开始的一环 * * @param name * 名称 * @param value * 值 * @return 链头 */ public static Chain make(String name, Object value) { return new DefaultChain(name, value); } /** * @return 链的长度 */ public abstract int size(); /** * 改变当前节点的名称 * * @param name * 新名称 * @return 当前节点 */ public abstract Chain name(String name); /** * 改变当前节点的值 * * @param value * 新值 * @return 当前节点 */ public abstract Chain value(Object value); /** * 设置节点的参考适配器 * * @param adaptor * 适配器 * @return 当前节点 */ public abstract Chain adaptor(ValueAdaptor adaptor); /** * @return 当前节点的参考适配器 */ public abstract ValueAdaptor adaptor(); /** * 将一个名值对,添加为本链节点的下一环 * * @param name * 名 * @param value * 值 * @return 新增加的节点 */ public abstract Chain add(String name, Object value); /** * @return 当前节点的名称 */ public abstract String name(); /** * @return 当前节点的值 */ public abstract Object value(); /** * @return 往后移动一个结点,到达末尾返回空,否则返回当前对象 */ public abstract Chain next(); /** * @return 整个链的第一环(头节点) */ public abstract Chain head(); /** * 根据 Entity 里的设定,更新整个链所有节点的名称。 * <p> * 如果节点的名称是 Entity 的一个字段,则采用数据库字段的名称 * * @param entity * 实体 * @return 链头节点 */ public abstract Chain updateBy(Entity<?> entity); /** * 由当前的名值链,生成一个对象 * * @param classOfT * 对象类型 * @return 对象实例 */ public abstract <T> T toObject(Class<T> classOfT); /** * 由当前名值链,生成一个 Map * * @return Map */ public abstract Map<String, Object> toMap(); /** * 整个Chain是否为特殊Chain,只要有一个特殊结点,就是特殊Chain * @see org.nutz.dao.Chain#addSpecial(String, Object) * @since 1.b.44 */ public abstract boolean isSpecial(); /** * 当前结点是不是特殊结点 * @return 是不是特殊结点 */ public abstract boolean special(); /** * 由当前的值链生成一个可被实体化的 Map。 即有 '.table' 属性 * * @param tableName * 表名 * @return 可被实体化的 Map */ public Map<String, Object> toEntityMap(String tableName) { Map<String, Object> map = toMap(); map.put(".table", tableName); return map; } /** * 生成一个 JSON 字符串 */ public String toString() { return Json.toJson(toMap()); } /** * 根据一个对象的字段 生成一个 Chain 对象 * <p> * 这个对象可以是一个 POJO 或者是一个 Map。 * <p> * 支持 FieldMatcher,即你可以通过 FieldMatcher 来指定你需要哪些字段加入 Chain * * @param obj * 对象,可以是一个 POJO 或者是一个 Map * @param fm * 指明可用字段,null 表示全部字段可用 * @return Chain 对象,null 表示对象中没有可用字段 * * @see org.nutz.dao.FieldMatcher */ public static Chain from(Object obj, FieldMatcher fm) { if (null == obj) return null; Chain c = null; /* * Is Map */ if (obj instanceof Map<?, ?>) { for (Map.Entry<?, ?> en : ((Map<?, ?>) obj).entrySet()) { Object key = en.getKey(); if (null == key) continue; String name = key.toString(); if (null != fm && !fm.match(name)) continue; Object v = en.getValue(); if (null != fm ) { if (null == v) { if (fm.isIgnoreNull()) continue; } else if (fm.isIgnoreBlankStr() && v instanceof String && Strings.isBlank((String)v)) { continue; } } if (c == null) { c = Chain.make(name, v); } else { c = c.add(name, v); } } } /* * Is POJO */ else { Mirror<?> mirror = Mirror.me(obj.getClass()); for (Field f : mirror.getFields()) { if (null != fm && !fm.match(f.getName())) continue; Object v = mirror.getValue(obj, f.getName()); if (null == v) { if (fm != null && fm.isIgnoreNull()) continue; } else if (fm != null && fm.isIgnoreBlankStr() && v instanceof String && Strings.isBlank((String)v)) { continue; } if (c == null) { c = Chain.make(f.getName(), v); } else { c = c.add(f.getName(), v); } } } return c; } /** * 根据一个 POJO 对象的字段 生成一个 Chain 对象 * <p> * 相当于 Chain.from(obj,null) * * @param obj * POJO 对象 * @return Chain 对象 */ public static Chain from(Object obj) { return from(obj, null); } public static Chain from(Object obj, FieldMatcher fm, Dao dao) { final Chain[] chains = new Chain[1]; boolean re = Daos.filterFields(obj, fm, dao, new Callback2<MappingField, Object>() { public void invoke(MappingField mf, Object val) { if (mf.isReadonly() || !mf.isUpdate()) return; if (chains[0] == null) chains[0] = Chain.make(mf.getName(), val); else chains[0].add(mf.getName(), val); } }); if (re) return chains[0]; return null; } //============================================================= //===========update语句使用特定的值,例如+1 -1 toDate()等======== //============================================================= /** * 添加一个特殊节点, 如果value非空而且是String类型,则有3个情况:<p> * <li>+1 效果如age=age+1</li> * <li>-1 效果如count=count-1</li> * <li>支持的运算符有 + - *\/ % & ^ | * <li>其他值, 则对value.toString()</li> * <p/> * <code>Chain chain = Chain.makeSpecial("age", "+1");//输出的SQL会是 age=age+1</code> * <p/> * <code>Chain chain = Chain.makeSpecial("ct", "now()");//输出的SQL会是 ct=now(),但不建议用依赖特定数据库的now(),仅供演示.</code> * @since 1.b.44 */ public abstract Chain addSpecial(String name, Object value); /** * @see org.nutz.dao.Chain#addSpecial(String, Object) * @since 1.b.44 */ public static Chain makeSpecial(String name, Object value) { DefaultChain chain = new DefaultChain(name, value); chain.head.special = true; return chain; } public static class DefaultChain extends Chain implements Serializable { private static final long serialVersionUID = 1L; private ChainEntry head; private ChainEntry current; private ChainEntry tail; private int size; public DefaultChain(String name, Object value) { this.head = new ChainEntry(name, value); this.current = head; this.tail = head; this.size = 1; } public int size() { return size; } public Chain name(String name) { current.name = name; return this; } public Chain value(Object value) { current.value = value; return this; } public Chain adaptor(ValueAdaptor adaptor) { current.adaptor = adaptor; return this; } public ValueAdaptor adaptor() { return current.adaptor; } public Chain add(String name, Object value) { tail.next = new ChainEntry(name, value); tail = tail.next; size ++; return this; } public String name() { return current.name; } public Object value() { return current.value; } public Chain next() { current = current.next; return current == null ? null : this; } public Chain head() { current = head; return this; } public Chain addSpecial(String name, Object value) { add(name, value); tail.special = true; return this; } public boolean special() { return current.special; } public boolean isSpecial() { ChainEntry entry = head; do { if(entry.special) { return true; } } while ((entry = entry.next) != null); return false; } public Map<String, Object> toMap() { NutMap map = new NutMap(); ChainEntry current = head; while (current != null) { map.put(current.name, current.value); if (current.adaptor != null) map.put("."+current.name+".adaptor", current.adaptor); current = current.next; } return map; } public Chain updateBy(Entity<?> entity) { if (null != entity) { ChainEntry current = head; while (current != null) { MappingField ef = entity.getField(current.name); if (null != ef) { current.name = ef.getColumnNameInSql(); } current = current.next; } } return head(); } public <T> T toObject(Class<T> classOfT) { Mirror<T> mirror = Mirror.me(classOfT); T re = mirror.born(); ChainEntry current = head; while (current != null) { mirror.setValue(re, current.name, current.value); current = current.next; } return re; } } public static class ChainEntry implements Serializable { private static final long serialVersionUID = 1L; protected String name; protected Object value; protected transient ValueAdaptor adaptor; protected boolean special; protected ChainEntry next; public ChainEntry(String name, Object value) { this.name = name; this.value = value; } } }
nutzam/nutz
src/org/nutz/dao/Chain.java
147
package com.xkcoding.mq.rabbitmq.config; import com.google.common.collect.Maps; import com.xkcoding.mq.rabbitmq.constants.RabbitConsts; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Map; /** * <p> * RabbitMQ配置,主要是配置队列,如果提前存在该队列,可以省略本配置类 * </p> * * @author yangkai.shen * @date Created in 2018-12-29 17:03 */ @Slf4j @Configuration public class RabbitMqConfig { @Bean public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) { connectionFactory.setPublisherConfirms(true); connectionFactory.setPublisherReturns(true); RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMandatory(true); rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause)); rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode, replyText, message)); return rabbitTemplate; } /** * 直接模式队列1 */ @Bean public Queue directOneQueue() { return new Queue(RabbitConsts.DIRECT_MODE_QUEUE_ONE); } /** * 队列2 */ @Bean public Queue queueTwo() { return new Queue(RabbitConsts.QUEUE_TWO); } /** * 队列3 */ @Bean public Queue queueThree() { return new Queue(RabbitConsts.QUEUE_THREE); } /** * 分列模式队列 */ @Bean public FanoutExchange fanoutExchange() { return new FanoutExchange(RabbitConsts.FANOUT_MODE_QUEUE); } /** * 分列模式绑定队列1 * * @param directOneQueue 绑定队列1 * @param fanoutExchange 分列模式交换器 */ @Bean public Binding fanoutBinding1(Queue directOneQueue, FanoutExchange fanoutExchange) { return BindingBuilder.bind(directOneQueue).to(fanoutExchange); } /** * 分列模式绑定队列2 * * @param queueTwo 绑定队列2 * @param fanoutExchange 分列模式交换器 */ @Bean public Binding fanoutBinding2(Queue queueTwo, FanoutExchange fanoutExchange) { return BindingBuilder.bind(queueTwo).to(fanoutExchange); } /** * 主题模式队列 * <li>路由格式必须以 . 分隔,比如 user.email 或者 user.aaa.email</li> * <li>通配符 * ,代表一个占位符,或者说一个单词,比如路由为 user.*,那么 user.email 可以匹配,但是 user.aaa.email 就匹配不了</li> * <li>通配符 # ,代表一个或多个占位符,或者说一个或多个单词,比如路由为 user.#,那么 user.email 可以匹配,user.aaa.email 也可以匹配</li> */ @Bean public TopicExchange topicExchange() { return new TopicExchange(RabbitConsts.TOPIC_MODE_QUEUE); } /** * 主题模式绑定分列模式 * * @param fanoutExchange 分列模式交换器 * @param topicExchange 主题模式交换器 */ @Bean public Binding topicBinding1(FanoutExchange fanoutExchange, TopicExchange topicExchange) { return BindingBuilder.bind(fanoutExchange).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_ONE); } /** * 主题模式绑定队列2 * * @param queueTwo 队列2 * @param topicExchange 主题模式交换器 */ @Bean public Binding topicBinding2(Queue queueTwo, TopicExchange topicExchange) { return BindingBuilder.bind(queueTwo).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_TWO); } /** * 主题模式绑定队列3 * * @param queueThree 队列3 * @param topicExchange 主题模式交换器 */ @Bean public Binding topicBinding3(Queue queueThree, TopicExchange topicExchange) { return BindingBuilder.bind(queueThree).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_THREE); } /** * 延迟队列 */ @Bean public Queue delayQueue() { return new Queue(RabbitConsts.DELAY_QUEUE, true); } /** * 延迟队列交换器, x-delayed-type 和 x-delayed-message 固定 */ @Bean public CustomExchange delayExchange() { Map<String, Object> args = Maps.newHashMap(); args.put("x-delayed-type", "direct"); return new CustomExchange(RabbitConsts.DELAY_MODE_QUEUE, "x-delayed-message", true, false, args); } /** * 延迟队列绑定自定义交换器 * * @param delayQueue 队列 * @param delayExchange 延迟交换器 */ @Bean public Binding delayBinding(Queue delayQueue, CustomExchange delayExchange) { return BindingBuilder.bind(delayQueue).to(delayExchange).with(RabbitConsts.DELAY_QUEUE).noargs(); } }
xkcoding/spring-boot-demo
demo-mq-rabbitmq/src/main/java/com/xkcoding/mq/rabbitmq/config/RabbitMqConfig.java
148
package org.pdown.gui.http.controller; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import io.netty.channel.Channel; import io.netty.handler.codec.http.*; import javafx.application.Platform; import jdk.nashorn.internal.runtime.Undefined; import org.pdown.core.boot.HttpDownBootstrap; import org.pdown.core.dispatch.HttpDownCallback; import org.pdown.core.util.OsUtil; import org.pdown.gui.DownApplication; import org.pdown.gui.com.Components; import org.pdown.gui.content.PDownConfigContent; import org.pdown.gui.entity.PDownConfigInfo; import org.pdown.gui.extension.ExtensionContent; import org.pdown.gui.extension.ExtensionInfo; import org.pdown.gui.extension.HookScript; import org.pdown.gui.extension.HookScript.Event; 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.gui.extension.util.ExtensionUtil; import org.pdown.gui.http.util.HttpHandlerUtil; import org.pdown.gui.util.AppUtil; import org.pdown.gui.util.ConfigUtil; import org.pdown.gui.util.ExecUtil; import org.pdown.rest.form.HttpRequestForm; import org.pdown.rest.form.TaskForm; import org.pdown.rest.util.PathUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.HashMap; import java.util.List; import java.util.Map; @RequestMapping("native") public class NativeController { private static final Logger LOGGER = LoggerFactory.getLogger(NativeController.class); @RequestMapping("dirChooser") public FullHttpResponse dirChooser(Channel channel, FullHttpRequest request) throws Exception { Platform.runLater(() -> { File file = Components.dirChooser(); Map<String, Object> data = null; if (file != null) { data = new HashMap<>(); data.put("path", file.getPath()); data.put("canWrite", file.canWrite()); data.put("freeSpace", file.getFreeSpace()); data.put("totalSpace", file.getTotalSpace()); } HttpHandlerUtil.writeJson(channel, data); }); return null; } @RequestMapping("fileChooser") public FullHttpResponse handle(Channel channel, FullHttpRequest request) throws Exception { Platform.runLater(() -> { File file = Components.fileChooser(); Map<String, Object> data = null; if (file != null) { data = new HashMap<>(); data.put("name", file.getName()); data.put("path", file.getPath()); data.put("parent", file.getParent()); data.put("size", file.length()); } HttpHandlerUtil.writeJson(channel, data); }); return null; } //启动的时候检查一次 private boolean checkFlag = true; private static final long WEEK = 7 * 24 * 60 * 60 * 1000L; @RequestMapping("getInitConfig") public FullHttpResponse getInitConfig(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> data = new HashMap<>(); PDownConfigInfo configInfo = PDownConfigContent.getInstance().get(); //语言 data.put("locale", configInfo.getLocale()); //后台管理API请求地址 data.put("adminServer", ConfigUtil.getString("adminServer")); //是否要检查更新 boolean needCheckUpdate = false; if (checkFlag) { int rate = configInfo.getUpdateCheckRate(); if (rate == 2 || (rate == 1 && (System.currentTimeMillis() - configInfo.getLastUpdateCheck()) > WEEK)) { needCheckUpdate = true; checkFlag = false; configInfo.setLastUpdateCheck(System.currentTimeMillis()); PDownConfigContent.getInstance().save(); } } data.put("needCheckUpdate", needCheckUpdate); //扩展下载服务器列表 data.put("extFileServers", configInfo.getExtFileServers()); //软件版本 data.put("version", ConfigUtil.getString("version")); return HttpHandlerUtil.buildJson(data); } @RequestMapping("getConfig") public FullHttpResponse getConfig(Channel channel, FullHttpRequest request) throws Exception { return HttpHandlerUtil.buildJson(PDownConfigContent.getInstance().get()); } @RequestMapping("setConfig") public FullHttpResponse setConfig(Channel channel, FullHttpRequest request) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); PDownConfigInfo configInfo = objectMapper.readValue(request.content().toString(Charset.forName("UTF-8")), PDownConfigInfo.class); PDownConfigInfo beforeConfigInfo = PDownConfigContent.getInstance().get(); boolean proxyChange = (beforeConfigInfo.getProxyConfig() != null && configInfo.getProxyConfig() == null) || (configInfo.getProxyConfig() != null && beforeConfigInfo.getProxyConfig() == null) || (beforeConfigInfo.getProxyConfig() != null && !beforeConfigInfo.getProxyConfig().equals(configInfo.getProxyConfig())) || (configInfo.getProxyConfig() != null && !configInfo.getProxyConfig().equals(beforeConfigInfo.getProxyConfig())); boolean localeChange = !configInfo.getLocale().equals(beforeConfigInfo.getLocale()); BeanUtils.copyProperties(configInfo, beforeConfigInfo); if (localeChange) { DownApplication.INSTANCE.loadPopupMenu(); DownApplication.INSTANCE.refreshBrowserMenu(); } //检查到前置代理有变动重启MITM代理服务器 if (proxyChange && PDownProxyServer.isStart) { new Thread(() -> { PDownProxyServer.close(); PDownProxyServer.start(DownApplication.INSTANCE.PROXY_PORT); }).start(); } PDownConfigContent.getInstance().save(); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } @RequestMapping("showFile") public FullHttpResponse showFile(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> map = getJSONParams(request); String path = (String) map.get("path"); if (!StringUtils.isEmpty(path)) { File file = new File(path); if (!file.exists() || OsUtil.isUnix()) { Desktop.getDesktop().open(file.getParentFile()); } else if (OsUtil.isWindows()) { ExecUtil.execBlock("explorer.exe", "/select,", file.getPath()); } else if (OsUtil.isMac()) { ExecUtil.execBlock("open", "-R", file.getPath()); } } return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } @RequestMapping("openUrl") public FullHttpResponse openUrl(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> map = getJSONParams(request); String url = (String) map.get("url"); Desktop.getDesktop().browse(URI.create(URLDecoder.decode(url, "UTF-8"))); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } private static volatile HttpDownBootstrap updateBootstrap; @RequestMapping("doUpdate") public FullHttpResponse doUpdate(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> map = getJSONParams(request); String url = (String) map.get("path"); String path = PathUtil.ROOT_PATH + File.separator + "proxyee-down-main.jar.tmp"; try { File updateTmpJar = new File(path); if (updateTmpJar.exists()) { updateTmpJar.delete(); } updateBootstrap = AppUtil.fastDownload(url, updateTmpJar, new HttpDownCallback() { @Override public void onDone(HttpDownBootstrap httpDownBootstrap) { File updateBakJar = new File(updateTmpJar.getParent() + File.separator + "proxyee-down-main.jar.bak"); updateTmpJar.renameTo(updateBakJar); } @Override public void onError(HttpDownBootstrap httpDownBootstrap) { File file = new File(path); if (file.exists()) { file.delete(); } httpDownBootstrap.close(); } }); } catch (Exception e) { throw e; } return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } @RequestMapping("getUpdateProgress") public FullHttpResponse getUpdateProgress(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> data = new HashMap<>(); if (updateBootstrap != null) { data.put("status", updateBootstrap.getTaskInfo().getStatus()); data.put("totalSize", updateBootstrap.getResponse().getTotalSize()); data.put("downSize", updateBootstrap.getTaskInfo().getDownSize()); data.put("speed", updateBootstrap.getTaskInfo().getSpeed()); } else { data.put("status", 0); } return HttpHandlerUtil.buildJson(data); } @RequestMapping("doRestart") public FullHttpResponse doRestart(Channel channel, FullHttpRequest request) throws Exception { System.out.println("proxyee-down-exit"); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } /** * 获取已安装的插件列表 */ @RequestMapping("getExtensions") public FullHttpResponse getExtensions(Channel channel, FullHttpRequest request) throws Exception { //刷新扩展信息 ExtensionContent.load(); return HttpHandlerUtil.buildJson(ExtensionContent.get()); } /** * 安装扩展 */ @RequestMapping("installExtension") public FullHttpResponse installExtension(Channel channel, FullHttpRequest request) throws Exception { return extensionCommon(request, false); } /** * 更新扩展 */ @RequestMapping("updateExtension") public FullHttpResponse updateExtension(Channel channel, FullHttpRequest request) throws Exception { return extensionCommon(request, true); } /** * 加载本地扩展 */ @RequestMapping("installLocalExtension") public FullHttpResponse installLocalExtension(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> data = new HashMap<>(); Map<String, Object> map = getJSONParams(request); String path = (String) map.get("path"); //刷新扩展content ExtensionInfo loadExt = ExtensionContent.refresh(path, true); if (loadExt == null) { return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST); } data.put("data", loadExt); //刷新系统pac代理 AppUtil.refreshPAC(); return HttpHandlerUtil.buildJson(data); } /** * 卸载扩展 */ @RequestMapping("uninstallExtension") public FullHttpResponse uninstallExtension(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> data = new HashMap<>(); Map<String, Object> map = getJSONParams(request); String path = (String) map.get("path"); boolean local = map.get("local") != null ? (boolean) map.get("local") : false; //卸载扩展 ExtensionContent.remove(path, local); //刷新系统pac代理 AppUtil.refreshPAC(); return HttpHandlerUtil.buildJson(data); } private FullHttpResponse extensionCommon(FullHttpRequest request, boolean isUpdate) throws Exception { Map<String, Object> map = getJSONParams(request); String server = (String) map.get("server"); String path = (String) map.get("path"); String files = (String) map.get("files"); if (isUpdate) { ExtensionUtil.update(server, path, files); } else { ExtensionUtil.install(server, path, files); } //刷新扩展content ExtensionContent.refresh(path); //刷新系统pac代理 AppUtil.refreshPAC(); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } /** * 启用或禁用插件 */ @RequestMapping("toggleExtension") public FullHttpResponse toggleExtension(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> map = getJSONParams(request); String path = (String) map.get("path"); boolean enabled = (boolean) map.get("enabled"); boolean local = map.get("local") != null ? (boolean) map.get("local") : false; ExtensionInfo extensionInfo = ExtensionContent.get() .stream() .filter(e -> e.getMeta().getPath().equals(path)) .findFirst() .get(); extensionInfo.getMeta().setEnabled(enabled).save(); //刷新pac ExtensionContent.refresh(extensionInfo.getMeta().getFullPath(), local); AppUtil.refreshPAC(); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } @RequestMapping("getProxyMode") public FullHttpResponse getProxyMode(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> data = new HashMap<>(); data.put("mode", PDownConfigContent.getInstance().get().getProxyMode()); return HttpHandlerUtil.buildJson(data); } @RequestMapping("changeProxyMode") public FullHttpResponse changeProxyMode(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> map = getJSONParams(request); int mode = (int) map.get("mode"); PDownConfigContent.getInstance().get().setProxyMode(mode); //修改系统代理 if (mode == 1) { AppUtil.refreshPAC(); } else { ExtensionProxyUtil.disabledProxy(); } PDownConfigContent.getInstance().save(); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } @RequestMapping("checkCert") public FullHttpResponse checkCert(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> data = new HashMap<>(); data.put("status", AppUtil.checkIsInstalledCert()); return HttpHandlerUtil.buildJson(data); } @RequestMapping("installCert") public FullHttpResponse installCert(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> data = new HashMap<>(); boolean status; if (OsUtil.isUnix() || OsUtil.isWindowsXP()) { if (!AppUtil.checkIsInstalledCert()) { ExtensionCertUtil.buildCert(AppUtil.SSL_PATH, AppUtil.SUBJECT); } Desktop.getDesktop().open(new File(AppUtil.SSL_PATH)); status = true; } else { //再检测一次,确保不重复安装 if (!AppUtil.checkIsInstalledCert()) { if (ExtensionCertUtil.existsCert(AppUtil.SUBJECT)) { //存在无用证书需要卸载 ExtensionCertUtil.uninstallCert(AppUtil.SUBJECT); } //生成新的证书 ExtensionCertUtil.buildCert(AppUtil.SSL_PATH, AppUtil.SUBJECT); //安装 ExtensionCertUtil.installCert(new File(AppUtil.CERT_PATH)); //检测是否安装成功,可能点了取消就没安装成功 status = AppUtil.checkIsInstalledCert(); } else { status = true; } } data.put("status", status); if (status && !PDownProxyServer.isStart) { new Thread(() -> { try { AppUtil.startProxyServer(); } catch (IOException e) { LOGGER.error("Start proxy server error", e); } }).start(); } return HttpHandlerUtil.buildJson(data); } @RequestMapping("copy") public FullHttpResponse copy(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> map = getJSONParams(request); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable selection = null; if ("text".equalsIgnoreCase((String) map.get("type"))) { selection = new StringSelection((String) map.get("data")); } clipboard.setContents(selection, null); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } @RequestMapping("updateExtensionSetting") public FullHttpResponse updateExtensionSetting(Channel channel, FullHttpRequest request) throws Exception { Map<String, Object> map = getJSONParams(request); String path = (String) map.get("path"); Map<String, Object> setting = (Map<String, Object>) map.get("setting"); ExtensionInfo extensionInfo = ExtensionContent.get() .stream() .filter(e -> e.getMeta().getPath().equals(path)) .findFirst() .get(); extensionInfo.getMeta().setSettings(setting).save(); return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } @RequestMapping("onResolve") public FullHttpResponse onResolve(Channel channel, FullHttpRequest request) throws Exception { HttpRequestForm taskRequest = getJSONParams(request, HttpRequestForm.class); //遍历扩展模块是否有对应的处理 List<ExtensionInfo> extensionInfos = ExtensionContent.get(); for (ExtensionInfo extensionInfo : extensionInfos) { if (extensionInfo.getMeta().isEnabled()) { if (extensionInfo.getHookScript() != null && !StringUtils.isEmpty(extensionInfo.getHookScript().getScript())) { Event event = extensionInfo.getHookScript().hasEvent(HookScript.EVENT_RESOLVE, taskRequest.getUrl()); if (event != null) { try { //执行resolve方法 Object result = ExtensionUtil.invoke(extensionInfo, event, taskRequest, false); if (result != null && !(result instanceof Undefined)) { ObjectMapper objectMapper = new ObjectMapper(); String temp = objectMapper.writeValueAsString(result); TaskForm taskForm = objectMapper.readValue(temp, TaskForm.class); //有一个扩展解析成功的话直接返回 return HttpHandlerUtil.buildJson(taskForm, Include.NON_DEFAULT); } } catch (Exception e) { LOGGER.error("An exception occurred while resolve()", e); } } } } } return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } private Map<String, Object> getJSONParams(FullHttpRequest request) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(request.content().toString(Charset.forName("UTF-8")), Map.class); } private <T> T getJSONParams(FullHttpRequest request, Class<T> clazz) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(request.content().toString(Charset.forName("UTF-8")), clazz); } }
proxyee-down-org/proxyee-down
main/src/main/java/org/pdown/gui/http/controller/NativeController.java
149
package com.xkcoding.codegen.utils; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.db.Entity; import cn.hutool.setting.dialect.Props; import com.google.common.collect.Lists; import com.xkcoding.codegen.constants.GenConstants; import com.xkcoding.codegen.entity.ColumnEntity; import com.xkcoding.codegen.entity.GenConfig; import com.xkcoding.codegen.entity.TableEntity; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; import org.apache.commons.text.WordUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * <p> * 代码生成器 工具类 * </p> * * @author yangkai.shen * @date Created in 2019-03-22 09:27 */ @Slf4j @UtilityClass public class CodeGenUtil { private final String ENTITY_JAVA_VM = "Entity.java.vm"; private final String MAPPER_JAVA_VM = "Mapper.java.vm"; private final String SERVICE_JAVA_VM = "Service.java.vm"; private final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm"; private final String CONTROLLER_JAVA_VM = "Controller.java.vm"; private final String MAPPER_XML_VM = "Mapper.xml.vm"; private final String API_JS_VM = "api.js.vm"; private List<String> getTemplates() { List<String> templates = new ArrayList<>(); templates.add("template/Entity.java.vm"); templates.add("template/Mapper.java.vm"); templates.add("template/Mapper.xml.vm"); templates.add("template/Service.java.vm"); templates.add("template/ServiceImpl.java.vm"); templates.add("template/Controller.java.vm"); templates.add("template/api.js.vm"); return templates; } /** * 生成代码 */ public void generatorCode(GenConfig genConfig, Entity table, List<Entity> columns, ZipOutputStream zip) { //配置信息 Props propsDB2Java = getConfig("generator.properties"); Props propsDB2Jdbc = getConfig("jdbc_type.properties"); boolean hasBigDecimal = false; //表信息 TableEntity tableEntity = new TableEntity(); tableEntity.setTableName(table.getStr("tableName")); if (StrUtil.isNotBlank(genConfig.getComments())) { tableEntity.setComments(genConfig.getComments()); } else { tableEntity.setComments(table.getStr("tableComment")); } String tablePrefix; if (StrUtil.isNotBlank(genConfig.getTablePrefix())) { tablePrefix = genConfig.getTablePrefix(); } else { tablePrefix = propsDB2Java.getStr("tablePrefix"); } //表名转换成Java类名 String className = tableToJava(tableEntity.getTableName(), tablePrefix); tableEntity.setCaseClassName(className); tableEntity.setLowerClassName(StrUtil.lowerFirst(className)); //列信息 List<ColumnEntity> columnList = Lists.newArrayList(); for (Entity column : columns) { ColumnEntity columnEntity = new ColumnEntity(); columnEntity.setColumnName(column.getStr("columnName")); columnEntity.setDataType(column.getStr("dataType")); columnEntity.setComments(column.getStr("columnComment")); columnEntity.setExtra(column.getStr("extra")); //列名转换成Java属性名 String attrName = columnToJava(columnEntity.getColumnName()); columnEntity.setCaseAttrName(attrName); columnEntity.setLowerAttrName(StrUtil.lowerFirst(attrName)); //列的数据类型,转换成Java类型 String attrType = propsDB2Java.getStr(columnEntity.getDataType(), "unknownType"); columnEntity.setAttrType(attrType); String jdbcType = propsDB2Jdbc.getStr(columnEntity.getDataType(), "unknownType"); columnEntity.setJdbcType(jdbcType); if (!hasBigDecimal && "BigDecimal".equals(attrType)) { hasBigDecimal = true; } //是否主键 if ("PRI".equalsIgnoreCase(column.getStr("columnKey")) && tableEntity.getPk() == null) { tableEntity.setPk(columnEntity); } columnList.add(columnEntity); } tableEntity.setColumns(columnList); //没主键,则第一个字段为主键 if (tableEntity.getPk() == null) { tableEntity.setPk(tableEntity.getColumns().get(0)); } //设置velocity资源加载器 Properties prop = new Properties(); prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.init(prop); //封装模板数据 Map<String, Object> map = new HashMap<>(16); map.put("tableName", tableEntity.getTableName()); map.put("pk", tableEntity.getPk()); map.put("className", tableEntity.getCaseClassName()); map.put("classname", tableEntity.getLowerClassName()); map.put("pathName", tableEntity.getLowerClassName().toLowerCase()); map.put("columns", tableEntity.getColumns()); map.put("hasBigDecimal", hasBigDecimal); map.put("datetime", DateUtil.now()); map.put("year", DateUtil.year(new Date())); if (StrUtil.isNotBlank(genConfig.getComments())) { map.put("comments", genConfig.getComments()); } else { map.put("comments", tableEntity.getComments()); } if (StrUtil.isNotBlank(genConfig.getAuthor())) { map.put("author", genConfig.getAuthor()); } else { map.put("author", propsDB2Java.getStr("author")); } if (StrUtil.isNotBlank(genConfig.getModuleName())) { map.put("moduleName", genConfig.getModuleName()); } else { map.put("moduleName", propsDB2Java.getStr("moduleName")); } if (StrUtil.isNotBlank(genConfig.getPackageName())) { map.put("package", genConfig.getPackageName()); map.put("mainPath", genConfig.getPackageName()); } else { map.put("package", propsDB2Java.getStr("package")); map.put("mainPath", propsDB2Java.getStr("mainPath")); } VelocityContext context = new VelocityContext(map); //获取模板列表 List<String> templates = getTemplates(); for (String template : templates) { //渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8); tpl.merge(context, sw); try { //添加到zip zip.putNextEntry(new ZipEntry(Objects.requireNonNull(getFileName(template, tableEntity.getCaseClassName(), map.get("package").toString(), map.get("moduleName").toString())))); IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString()); IoUtil.close(sw); zip.closeEntry(); } catch (IOException e) { throw new RuntimeException("渲染模板失败,表名:" + tableEntity.getTableName(), e); } } } /** * 列名转换成Java属性名 */ private String columnToJava(String columnName) { return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", ""); } /** * 表名转换成Java类名 */ private String tableToJava(String tableName, String tablePrefix) { if (StrUtil.isNotBlank(tablePrefix)) { tableName = tableName.replaceFirst(tablePrefix, ""); } return columnToJava(tableName); } /** * 获取配置信息 */ private Props getConfig(String fileName) { Props props = new Props(fileName); props.autoLoad(true); return props; } /** * 获取文件名 */ private String getFileName(String template, String className, String packageName, String moduleName) { // 包路径 String packagePath = GenConstants.SIGNATURE + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator; // 资源路径 String resourcePath = GenConstants.SIGNATURE + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator; // api路径 String apiPath = GenConstants.SIGNATURE + File.separator + "api" + File.separator; if (StrUtil.isNotBlank(packageName)) { packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator; } if (template.contains(ENTITY_JAVA_VM)) { return packagePath + "entity" + File.separator + className + ".java"; } if (template.contains(MAPPER_JAVA_VM)) { return packagePath + "mapper" + File.separator + className + "Mapper.java"; } if (template.contains(SERVICE_JAVA_VM)) { return packagePath + "service" + File.separator + className + "Service.java"; } if (template.contains(SERVICE_IMPL_JAVA_VM)) { return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java"; } if (template.contains(CONTROLLER_JAVA_VM)) { return packagePath + "controller" + File.separator + className + "Controller.java"; } if (template.contains(MAPPER_XML_VM)) { return resourcePath + "mapper" + File.separator + className + "Mapper.xml"; } if (template.contains(API_JS_VM)) { return apiPath + className.toLowerCase() + ".js"; } return null; } }
xkcoding/spring-boot-demo
demo-codegen/src/main/java/com/xkcoding/codegen/utils/CodeGenUtil.java
150
package com.sloop.canvas; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.view.View; /** * <ul type="disc"> * <li>Author: Sloop</li> * <li>Version: v1.0.0</li> * <li>Copyright: Copyright (c) 2015</li> * <li>Date: 2016/2/5</li> * <li><a href="http://www.sloop.icoc.cc" target="_blank">作者网站</a> </li> * <li><a href="http://weibo.com/5459430586" target="_blank">作者微博</a> </li> * <li><a href="https://github.com/GcsSloop" target="_blank">作者GitHub</a> </li> * </ul> */ public class CheckView extends View { private static final int ANIM_NULL = 0; //动画状态-没有 private static final int ANIM_CHECK = 1; //动画状态-开启 private static final int ANIM_UNCHECK = 2; //动画状态-结束 private Context mContext; // 上下文 private int mWidth, mHeight; // 宽高 private Handler mHandler; // handler private Paint mPaint; private Bitmap okBitmap; private int animCurrentPage = -1; // 当前页码 private int animMaxPage = 13; // 总页数 private int animDuration = 500; // 动画时长 private int animState = ANIM_NULL; // 动画状态 private boolean isCheck = false; // 是否只选中状态 public CheckView(Context context) { super(context, null); } public CheckView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } /** * 初始化 * @param context */ private void init(Context context) { mContext = context; mPaint = new Paint(); mPaint.setColor(0xffFF5317); mPaint.setStyle(Paint.Style.FILL); mPaint.setAntiAlias(true); okBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.checkres); mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (animCurrentPage < animMaxPage && animCurrentPage >= 0) { invalidate(); if (animState == ANIM_NULL) return; if (animState == ANIM_CHECK) { animCurrentPage++; } else if (animState == ANIM_UNCHECK) { animCurrentPage--; } this.sendEmptyMessageDelayed(0, animDuration / animMaxPage); Log.e("AAA", "Count=" + animCurrentPage); } else { if (isCheck) { animCurrentPage = animMaxPage - 1; } else { animCurrentPage = -1; } invalidate(); animState = ANIM_NULL; } } }; } /** * View大小确定 * @param w * @param h * @param oldw * @param oldh */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; } /** * 绘制内容 * @param canvas */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 移动坐标系到画布中央 canvas.translate(mWidth / 2, mHeight / 2); // 绘制背景圆形 canvas.drawCircle(0, 0, 240, mPaint); // 得出图像边长 int sideLength = okBitmap.getHeight(); // 得到图像选区 和 实际绘制位置 Rect src = new Rect(sideLength * animCurrentPage, 0, sideLength * (animCurrentPage + 1), sideLength); Rect dst = new Rect(-200, -200, 200, 200); // 绘制 canvas.drawBitmap(okBitmap, src, dst, null); } /** * 选择 */ public void check() { if (animState != ANIM_NULL || isCheck) return; animState = ANIM_CHECK; animCurrentPage = 0; mHandler.sendEmptyMessageDelayed(0, animDuration / animMaxPage); isCheck = true; } /** * 取消选择 */ public void unCheck() { if (animState != ANIM_NULL || (!isCheck)) return; animState = ANIM_UNCHECK; animCurrentPage = animMaxPage - 1; mHandler.sendEmptyMessageDelayed(0, animDuration / animMaxPage); isCheck = false; } /** * 设置动画时长 * @param animDuration */ public void setAnimDuration(int animDuration) { if (animDuration <= 0) return; this.animDuration = animDuration; } /** * 设置背景圆形颜色 * @param color */ public void setBackgroundColor(int color){ mPaint.setColor(color); } }
GcsSloop/AndroidNote
CustomView/Advance/Code/CheckView.java
152
package com.macro.mall.model; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; public class PmsProductCategory implements Serializable { private Long id; @ApiModelProperty(value = "上机分类的编号:0表示一级分类") private Long parentId; private String name; @ApiModelProperty(value = "分类级别:0->1级;1->2级") private Integer level; private Integer productCount; private String productUnit; @ApiModelProperty(value = "是否显示在导航栏:0->不显示;1->显示") private Integer navStatus; @ApiModelProperty(value = "显示状态:0->不显示;1->显示") private Integer showStatus; private Integer sort; @ApiModelProperty(value = "图标") private String icon; private String keywords; @ApiModelProperty(value = "描述") private String description; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } public Integer getProductCount() { return productCount; } public void setProductCount(Integer productCount) { this.productCount = productCount; } public String getProductUnit() { return productUnit; } public void setProductUnit(String productUnit) { this.productUnit = productUnit; } public Integer getNavStatus() { return navStatus; } public void setNavStatus(Integer navStatus) { this.navStatus = navStatus; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @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(", parentId=").append(parentId); sb.append(", name=").append(name); sb.append(", level=").append(level); sb.append(", productCount=").append(productCount); sb.append(", productUnit=").append(productUnit); sb.append(", navStatus=").append(navStatus); sb.append(", showStatus=").append(showStatus); sb.append(", sort=").append(sort); sb.append(", icon=").append(icon); sb.append(", keywords=").append(keywords); sb.append(", description=").append(description); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
macrozheng/mall
mall-mbg/src/main/java/com/macro/mall/model/PmsProductCategory.java
153
package com.crossoverjie.actual; import java.util.HashMap; import java.util.Map; /** * Function: * * @author crossoverJie * Date: 03/04/2018 00:08 * @since JDK 1.8 */ public class LRUMap<K, V> { private final Map<K, V> cacheMap = new HashMap<>(); /** * 最大缓存大小 */ private int cacheSize; /** * 节点大小 */ private int nodeCount; /** * 头结点 */ private Node<K, V> header; /** * 尾结点 */ private Node<K, V> tailer; public LRUMap(int cacheSize) { this.cacheSize = cacheSize; //头结点的下一个结点为空 header = new Node<>(); header.next = null; //尾结点的上一个结点为空 tailer = new Node<>(); tailer.tail = null; //双向链表 头结点的上结点指向尾结点 header.tail = tailer; //尾结点的下结点指向头结点 tailer.next = header; } public void put(K key, V value) { cacheMap.put(key, value); //双向链表中添加结点 addNode(key, value); } public V get(K key){ Node<K, V> node = getNode(key); //移动到头结点 moveToHead(node) ; return cacheMap.get(key); } private void moveToHead(Node<K,V> node){ //如果是最后的一个节点 if (node.tail == null){ node.next.tail = null ; tailer = node.next ; nodeCount -- ; } //如果是本来就是头节点 不作处理 if (node.next == null){ return ; } //如果处于中间节点 if (node.tail != null && node.next != null){ //它的上一节点指向它的下一节点 也就删除当前节点 node.tail.next = node.next ; node.next.tail = node.tail; nodeCount -- ; } //最后在头部增加当前节点 //注意这里需要重新 new 一个对象,不然原本的node 还有着下面的引用,会造成内存溢出。 node = new Node<>(node.getKey(),node.getValue()) ; addHead(node) ; } /** * 链表查询 效率较低 * @param key * @return */ private Node<K,V> getNode(K key){ Node<K,V> node = tailer ; while (node != null){ if (node.getKey().equals(key)){ return node ; } node = node.next ; } return null ; } /** * 写入头结点 * @param key * @param value */ private void addNode(K key, V value) { Node<K, V> node = new Node<>(key, value); //容量满了删除最后一个 if (cacheSize == nodeCount) { //删除尾结点 delTail(); } //写入头结点 addHead(node); } /** * 添加头结点 * * @param node */ private void addHead(Node<K, V> node) { //写入头结点 header.next = node; node.tail = header; header = node; nodeCount++; //如果写入的数据大于2个 就将初始化的头尾结点删除 if (nodeCount == 2) { tailer.next.next.tail = null; tailer = tailer.next.next; } } private void delTail() { //把尾结点从缓存中删除 cacheMap.remove(tailer.getKey()); //删除尾结点 tailer.next.tail = null; tailer = tailer.next; nodeCount--; } private class Node<K, V> { private K key; private V value; Node<K, V> tail; Node<K, V> next; public Node(K key, V value) { this.key = key; this.value = value; } public Node() { } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } } @Override public String toString() { StringBuilder sb = new StringBuilder() ; Node<K,V> node = tailer ; while (node != null){ sb.append(node.getKey()).append(":") .append(node.getValue()) .append("-->") ; node = node.next ; } return sb.toString(); } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/actual/LRUMap.java
154
/** * File: max_product_cutting.java * Created Time: 2023-07-21 * Author: krahets ([email protected]) */ package chapter_greedy; import java.lang.Math; public class max_product_cutting { /* 最大切分乘积:贪心 */ public static int maxProductCutting(int n) { // 当 n <= 3 时,必须切分出一个 1 if (n <= 3) { return 1 * (n - 1); } // 贪心地切分出 3 ,a 为 3 的个数,b 为余数 int a = n / 3; int b = n % 3; if (b == 1) { // 当余数为 1 时,将一对 1 * 3 转化为 2 * 2 return (int) Math.pow(3, a - 1) * 2 * 2; } if (b == 2) { // 当余数为 2 时,不做处理 return (int) Math.pow(3, a) * 2; } // 当余数为 0 时,不做处理 return (int) Math.pow(3, a); } public static void main(String[] args) { int n = 58; // 贪心算法 int res = maxProductCutting(n); System.out.println("最大切分乘积为 " + res); } }
krahets/hello-algo
codes/java/chapter_greedy/max_product_cutting.java
155
package cn.hutool.jwt; import cn.hutool.core.codec.Base64; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.exceptions.ValidateException; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONObject; import cn.hutool.jwt.signers.AlgorithmUtil; import cn.hutool.jwt.signers.JWTSigner; import cn.hutool.jwt.signers.JWTSignerUtil; import cn.hutool.jwt.signers.NoneJWTSigner; import java.nio.charset.Charset; import java.security.Key; import java.security.KeyPair; import java.util.List; import java.util.Map; /** * JSON Web Token (JWT),基于JSON的开放标准((RFC 7519)用于在网络应用环境间传递声明。<br> * <p> * 结构:header.payload.signature * <ul> * <li>header:主要声明了JWT的签名算法</li> * <li>payload:主要承载了各种声明并传递明文数据</li> * <li>signature:拥有该部分的JWT被称为JWS,也就是签了名的JWS</li> * </ul> * * <p> * 详细介绍见;https://www.jianshu.com/p/576dbf44b2ae * </p> * * @author looly * @since 5.7.0 */ public class JWT implements RegisteredPayload<JWT> { private final JWTHeader header; private final JWTPayload payload; private Charset charset; private JWTSigner signer; private List<String> tokens; /** * 创建空的JWT对象 * * @return JWT */ public static JWT create() { return new JWT(); } /** * 创建并解析JWT对象 * * @param token JWT Token字符串,格式为xxxx.yyyy.zzzz * @return JWT */ public static JWT of(String token) { return new JWT(token); } /** * 构造 */ public JWT() { this.header = new JWTHeader(); this.payload = new JWTPayload(); this.charset = CharsetUtil.CHARSET_UTF_8; } /** * 构造 * * @param token JWT Token字符串,格式为xxxx.yyyy.zzzz */ public JWT(String token) { this(); parse(token); } /** * 解析JWT内容 * * @param token JWT Token字符串,格式为xxxx.yyyy.zzzz * @return this */ public JWT parse(String token) { Assert.notBlank(token, "Token String must be not blank!"); final List<String> tokens = splitToken(token); this.tokens = tokens; this.header.parse(tokens.get(0), this.charset); this.payload.parse(tokens.get(1), this.charset); return this; } /** * 设置编码 * * @param charset 编码 * @return this */ public JWT setCharset(Charset charset) { this.charset = charset; return this; } /** * 设置密钥,如果头部指定了算法,直接使用,否则默认算法是:HS256(HmacSHA256) * * @param key 密钥 * @return this */ public JWT setKey(byte[] key) { // 检查头信息中是否有算法信息 final String claim = (String) this.header.getClaim(JWTHeader.ALGORITHM); if (StrUtil.isNotBlank(claim)) { return setSigner(JWTSignerUtil.createSigner(claim, key)); } return setSigner(JWTSignerUtil.hs256(key)); } /** * 设置签名算法 * * @param algorithmId 签名算法ID,如HS256 * @param key 密钥 * @return this */ public JWT setSigner(String algorithmId, byte[] key) { return setSigner(JWTSignerUtil.createSigner(algorithmId, key)); } /** * 设置签名算法 * * @param algorithmId 签名算法ID,如HS256 * @param key 密钥 * @return this * @since 5.7.2 */ public JWT setSigner(String algorithmId, Key key) { return setSigner(JWTSignerUtil.createSigner(algorithmId, key)); } /** * 设置非对称签名算法 * * @param algorithmId 签名算法ID,如HS256 * @param keyPair 密钥对 * @return this * @since 5.7.2 */ public JWT setSigner(String algorithmId, KeyPair keyPair) { return setSigner(JWTSignerUtil.createSigner(algorithmId, keyPair)); } /** * 设置签名算法 * * @param signer 签名算法 * @return this */ public JWT setSigner(JWTSigner signer) { this.signer = signer; return this; } /** * 获取JWT算法签名器 * * @return JWT算法签名器 */ public JWTSigner getSigner() { return this.signer; } /** * 获取所有头信息 * * @return 头信息 */ public JSONObject getHeaders() { return this.header.getClaimsJson(); } /** * 获取头 * * @return 头信息 * @since 5.7.2 */ public JWTHeader getHeader() { return this.header; } /** * 获取头信息 * * @param name 头信息名称 * @return 头信息 */ public Object getHeader(String name) { return this.header.getClaim(name); } /** * 获取算法ID(alg)头信息 * * @return 算法头信息 * @see JWTHeader#ALGORITHM */ public String getAlgorithm() { return (String) this.header.getClaim(JWTHeader.ALGORITHM); } /** * 设置JWT头信息 * * @param name 头名 * @param value 头 * @return this */ public JWT setHeader(String name, Object value) { this.header.setClaim(name, value); return this; } /** * 增加JWT头信息 * * @param headers 头信息 * @return this */ public JWT addHeaders(Map<String, ?> headers) { this.header.addHeaders(headers); return this; } /** * 获取所有载荷信息 * * @return 载荷信息 */ public JSONObject getPayloads() { return this.payload.getClaimsJson(); } /** * 获取载荷对象 * * @return 载荷信息 * @since 5.7.2 */ public JWTPayload getPayload() { return this.payload; } /** * 获取载荷信息 * * @param name 载荷信息名称 * @return 载荷信息 */ public Object getPayload(String name) { return getPayload().getClaim(name); } /** * 设置JWT载荷信息 * * @param name 载荷名 * @param value 头 * @return this */ @Override public JWT setPayload(String name, Object value) { this.payload.setClaim(name, value); return this; } /** * 增加JWT载荷信息 * * @param payloads 载荷信息 * @return this */ public JWT addPayloads(Map<String, ?> payloads) { this.payload.addPayloads(payloads); return this; } /** * 签名生成JWT字符串 * * @return JWT字符串 */ public String sign() { return sign(true); } /** * 签名生成JWT字符串 * * @param addTypeIfNot 如果'typ'头不存在,是否赋值默认值 * @return JWT字符串 * @since 5.8.24 */ public String sign(boolean addTypeIfNot) { return sign(this.signer, addTypeIfNot); } /** * 签名生成JWT字符串 * * @param signer JWT签名器 * @return JWT字符串 */ public String sign(JWTSigner signer) { return sign(signer, true); } /** * 签名生成JWT字符串 * * @param signer JWT签名器 * @param addTypeIfNot 如果'typ'头不存在,是否赋值默认值 * @return JWT字符串 * @since 5.8.24 */ public String sign(JWTSigner signer, boolean addTypeIfNot) { Assert.notNull(signer, () -> new JWTException("No Signer provided!")); // 检查tye信息 if (addTypeIfNot) { final String type = (String) this.header.getClaim(JWTHeader.TYPE); if (StrUtil.isBlank(type)) { this.header.setClaim(JWTHeader.TYPE, "JWT"); } } // 检查头信息中是否有算法信息 final String algorithm = (String) this.header.getClaim(JWTHeader.ALGORITHM); if (StrUtil.isBlank(algorithm)) { this.header.setClaim(JWTHeader.ALGORITHM, AlgorithmUtil.getId(signer.getAlgorithm())); } final String headerBase64 = Base64.encodeUrlSafe(this.header.toString(), charset); final String payloadBase64 = Base64.encodeUrlSafe(this.payload.toString(), charset); final String sign = signer.sign(headerBase64, payloadBase64); return StrUtil.format("{}.{}.{}", headerBase64, payloadBase64, sign); } /** * 验证JWT Token是否有效 * * @return 是否有效 */ public boolean verify() { return verify(this.signer); } /** * 验证JWT是否有效,验证包括: * * <ul> * <li>Token是否正确</li> * <li>{@link JWTPayload#NOT_BEFORE}:生效时间不能晚于当前时间</li> * <li>{@link JWTPayload#EXPIRES_AT}:失效时间不能早于当前时间</li> * <li>{@link JWTPayload#ISSUED_AT}: 签发时间不能晚于当前时间</li> * </ul> * * @param leeway 容忍空间,单位:秒。当不能晚于当前时间时,向后容忍;不能早于向前容忍。 * @return 是否有效 * @see JWTValidator * @since 5.7.4 */ public boolean validate(long leeway) { if (false == verify()) { return false; } // 校验时间字段 try { JWTValidator.of(this).validateDate(DateUtil.date(), leeway); } catch (ValidateException e) { return false; } return true; } /** * 验证JWT Token是否有效 * * @param signer 签名器(签名算法) * @return 是否有效 */ public boolean verify(JWTSigner signer) { if (null == signer) { // 如果无签名器提供,默认认为是无签名JWT信息 signer = NoneJWTSigner.NONE; } final List<String> tokens = this.tokens; if (CollUtil.isEmpty(tokens)) { throw new JWTException("No token to verify!"); } return signer.verify(tokens.get(0), tokens.get(1), tokens.get(2)); } /** * 将JWT字符串拆分为3部分,无加密算法则最后一部分是"" * * @param token JWT Token * @return 三部分内容 */ private static List<String> splitToken(String token) { final List<String> tokens = StrUtil.split(token, CharUtil.DOT); if (3 != tokens.size()) { throw new JWTException("The token was expected 3 parts, but got {}.", tokens.size()); } return tokens; } }
dromara/hutool
hutool-jwt/src/main/java/cn/hutool/jwt/JWT.java
157
package com.zheng.common.util; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * AES加解密工具类 * Created by shuzheng on 2017/2/5. */ public class AESUtil { private static final String ENCODE_RULES = "zheng"; /** * 加密 * 1.构造密钥生成器 * 2.根据ecnodeRules规则初始化密钥生成器 * 3.产生密钥 * 4.创建和初始化密码器 * 5.内容加密 * 6.返回字符串 */ public static String aesEncode(String content) { try { //1.构造密钥生成器,指定为AES算法,不区分大小写 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); //2.根据ecnodeRules规则初始化密钥生成器 //生成一个128位的随机源,根据传入的字节数组 SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(ENCODE_RULES.getBytes()); keyGenerator.init(128, random); //3.产生原始对称密钥 SecretKey originalKey = keyGenerator.generateKey(); //4.获得原始对称密钥的字节数组 byte[] raw = originalKey.getEncoded(); //5.根据字节数组生成AES密钥 SecretKey key = new SecretKeySpec(raw, "AES"); //6.根据指定算法AES自成密码器 Cipher cipher = Cipher.getInstance("AES"); //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY cipher.init(Cipher.ENCRYPT_MODE, key); //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码 byte[] byteEncode = content.getBytes("utf-8"); //9.根据密码器的初始化方式--加密:将数据加密 byte[] byteAES = cipher.doFinal(byteEncode); //10.将加密后的数据转换为字符串 //这里用Base64Encoder中会找不到包 //解决办法: //在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。 String aesEncode = new String(new BASE64Encoder().encode(byteAES)); //11.将字符串返回 return aesEncode; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //如果有错就返加nulll return null; } /** * 解密 * 解密过程: * 1.同加密1-4步 * 2.将加密后的字符串反纺成byte[]数组 * 3.将加密内容解密 */ public static String aesDecode(String content) { try { //1.构造密钥生成器,指定为AES算法,不区分大小写 KeyGenerator keygen = KeyGenerator.getInstance("AES"); //2.根据ecnodeRules规则初始化密钥生成器 //生成一个128位的随机源,根据传入的字节数组 SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(ENCODE_RULES.getBytes()); keygen.init(128, random); //3.产生原始对称密钥 SecretKey originalKey = keygen.generateKey(); //4.获得原始对称密钥的字节数组 byte[] raw = originalKey.getEncoded(); //5.根据字节数组生成AES密钥 SecretKey key = new SecretKeySpec(raw, "AES"); //6.根据指定算法AES自成密码器 Cipher cipher = Cipher.getInstance("AES"); //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY cipher.init(Cipher.DECRYPT_MODE, key); //8.将加密并编码后的内容解码成字节数组 byte[] byteContent = new BASE64Decoder().decodeBuffer(content); /* * 解密 */ byte[] byteDecode = cipher.doFinal(byteContent); String aesDecode = new String(byteDecode, "utf-8"); return aesDecode; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { throw new RuntimeException("兄弟,配置文件中的密码需要使用AES加密,请使用com.zheng.common.util.AESUtil工具类修改这些值!"); //e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } //如果有错就返加nulll return null; } public static void main(String[] args) { String[] keys = { "", "123456" }; System.out.println("key | AESEncode | AESDecode"); for (String key : keys) { System.out.print(key + " | "); String encryptString = aesEncode(key); System.out.print(encryptString + " | "); String decryptString = aesDecode(encryptString); System.out.println(decryptString); } } }
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/util/AESUtil.java
158
/* * 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.util; /** * @author mycat */ public class RandomUtil { private static final byte[] bytes = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M' }; private static final long multiplier = 0x5DEECE66DL; private static final long addend = 0xBL; private static final long mask = (1L << 48) - 1; private static final long integerMask = (1L << 33) - 1; private static final long seedUniquifier = 8682522807148012L; private static long seed; static { long s = seedUniquifier + System.nanoTime(); s = (s ^ multiplier) & mask; seed = s; } public static final byte[] randomBytes(int size) { byte[] bb = bytes; byte[] ab = new byte[size]; for (int i = 0; i < size; i++) { ab[i] = randomByte(bb); } return ab; } private static byte randomByte(byte[] b) { int ran = (int) ((next() & integerMask) >>> 16); return b[ran % b.length]; } private static long next() { long oldSeed = seed; long nextSeed = 0L; do { nextSeed = (oldSeed * multiplier + addend) & mask; } while (oldSeed == nextSeed); seed = nextSeed; return nextSeed; } /** * 随机指定范围内N个不重复的数 * 最简单最基本的方法 * @param min 指定范围最小值(包含) * @param max 指定范围最大值(不包含) * @param n 随机数个数 */ public static int[] getNRandom(int min, int max, int n){ if (n > (max - min + 1) || max < min) { return null; } int[] result = new int[n]; for(int i = 0 ; i < n ; i++){ result[i] = -9999; } int count = 0; while(count < n) { int num = (int) ((Math.random() * (max - min)) + min); boolean flag = true; for (int j = 0; j < n; j++) { if(num == result[j]){ flag = false; break; } } if(flag){ result[count] = num; count++; } } return result; } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/util/RandomUtil.java
160
/*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 com.alibaba.fastjson.JSONObject; import apijson.NotNull; import apijson.StringUtil; /**连表 配置 * @author Lemon */ public class Join { private String path; // /User/id@ private String joinType; // "@" - APP, "<" - LEFT, ">" - RIGHT, "*" - CROSS, "&" - INNER, "|" - FULL, "!" - OUTER, "^" - SIDE, "(" - ANTI, ")" - FOREIGN private String table; // User private String alias; // owner private int count = 1; // 当app join子表,需要返回子表的行数,默认1行; private List<On> onList; // ON User.id = Moment.userId AND ... private JSONObject request; // { "id@":"/Moment/userId" } private JSONObject outer; // "join": { "</User": { "@order":"id-", "@group":"id", "name~":"a", "tag$":"%a%", "@combine": "name~,tag$" } } 中的 </User 对应值 private SQLConfig joinConfig; private SQLConfig cacheConfig; private SQLConfig outerConfig; public String getPath() { return path; } public void setPath(String path) { this.path = path; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getJoinType() { return joinType; } public void setJoinType(String joinType) { this.joinType = joinType; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public List<On> getOnList() { return onList; } public void setOnList(List<On> onList) { this.onList = onList; } public JSONObject getRequest() { return request; } public void setRequest(JSONObject request) { this.request = request; } public JSONObject getOuter() { return outer; } public void setOuter(JSONObject outer) { this.outer = outer; } public SQLConfig getJoinConfig() { return joinConfig; } public void setJoinConfig(SQLConfig joinConfig) { this.joinConfig = joinConfig; } public SQLConfig getCacheConfig() { return cacheConfig; } public void setCacheConfig(SQLConfig cacheConfig) { this.cacheConfig = cacheConfig; } public SQLConfig getOuterConfig() { return outerConfig; } public void setOuterConfig(SQLConfig outerConfig) { this.outerConfig = outerConfig; } public boolean isOne2One() { return ! isOne2Many(); } public boolean isOne2Many() { return count != 1 || (path != null && path.contains("[]")); // TODO 必须保证一对一时不会传包含 [] 的 path } public boolean isAppJoin() { return "@".equals(getJoinType()); } public boolean isLeftJoin() { return "<".equals(getJoinType()); } public boolean isRightJoin() { return ">".equals(getJoinType()); } public boolean isCrossJoin() { return "*".equals(getJoinType()); } public boolean isInnerJoin() { return "&".equals(getJoinType()); } public boolean isFullJoin() { String jt = getJoinType(); return "".equals(jt) || "|".equals(jt); } public boolean isOuterJoin() { return "!".equals(getJoinType()); } public boolean isSideJoin() { return "^".equals(getJoinType()); } public boolean isAntiJoin() { return "(".equals(getJoinType()); } public boolean isForeignJoin() { return ")".equals(getJoinType()); } public boolean isLeftOrRightJoin() { String jt = getJoinType(); return "<".equals(jt) || ">".equals(jt); } public boolean canCacheViceTable() { String jt = getJoinType(); return "@".equals(jt) || "<".equals(jt) || ">".equals(jt) || "&".equals(jt) || "*".equals(jt) || ")".equals(jt); // 副表是按常规条件查询,缓存会导致其它同表同条件对象查询结果集为空 return ! isFullJoin(); // ! - OUTER, ( - FOREIGN 都需要缓存空副表数据,避免多余的查询 } public boolean isSQLJoin() { return ! isAppJoin(); } public static boolean isSQLJoin(Join j) { return j != null && j.isSQLJoin(); } public static boolean isAppJoin(Join j) { return j != null && j.isAppJoin(); } public static boolean isLeftOrRightJoin(Join j) { return j != null && j.isLeftOrRightJoin(); } public static class On { private String originKey; private String originValue; private Logic logic; // & | ! private String relateType; // "" - 一对一, "{}" - 一对多, "<>" - 多对一, > , <= , != private String key; // id private String targetTable; // Moment private String targetAlias; // main private String targetKey; // userId public String getOriginKey() { return originKey; } public void setOriginKey(String originKey) { this.originKey = originKey; } public String getOriginValue() { return originValue; } public void setOriginValue(String originValue) { this.originValue = originValue; } public Logic getLogic() { return logic; } public void setLogic(Logic logic) { this.logic = logic; } public String getRelateType() { return relateType; } public void setRelateType(String relateType) { this.relateType = relateType; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public void setTargetTable(String targetTable) { this.targetTable = targetTable; } public String getTargetTable() { return targetTable; } public void setTargetAlias(String targetAlias) { this.targetAlias = targetAlias; } public String getTargetAlias() { return targetAlias; } public String getTargetKey() { return targetKey; } public void setTargetKey(String targetKey) { this.targetKey = targetKey; } public void setKeyAndType(String joinType, String table, @NotNull String originKey) throws Exception { //id, id@, id{}@, contactIdList<>@ ... if (originKey.endsWith("@")) { originKey = originKey.substring(0, originKey.length() - 1); } else { //TODO 暂时只允许 User.id = Moment.userId 字段关联,不允许 User.id = 82001 这种 throw new IllegalArgumentException(joinType + "/.../" + table + "/" + originKey + " 中字符 " + originKey + " 不合法!join:'.../refKey'" + " 中 refKey 必须以 @ 结尾!"); } String k; if (originKey.endsWith("{}")) { setRelateType("{}"); k = originKey.substring(0, originKey.length() - 2); } else if (originKey.endsWith("<>")) { setRelateType("<>"); k = originKey.substring(0, originKey.length() - 2); } else if (originKey.endsWith("$")) { // key%$:"a" -> key LIKE '%a%'; key?%$:"a" -> key LIKE 'a%'; key_?$:"a" -> key LIKE '_a'; key_%$:"a" -> key LIKE '_a%' k = originKey.substring(0, originKey.length() - 1); char c = k.isEmpty() ? 0 : k.charAt(k.length() - 1); String t = "$"; if (c == '%' || c == '_' || c == '?') { t = c + t; k = k.substring(0, k.length() - 1); char c2 = k.isEmpty() ? 0 : k.charAt(k.length() - 1); if (c2 == '%' || c2 == '_' || c2 == '?') { if (c2 == c) { throw new IllegalArgumentException(originKey + ":value 中字符 " + k + " 不合法!key$:value 中不允许 key 中有连续相同的占位符!"); } t = c2 + t; k = k.substring(0, k.length() - 1); } else if (c == '?') { throw new IllegalArgumentException(originKey + ":value 中字符 " + originKey + " 不合法!key$:value 中不允许只有单独的 '?',必须和 '%', '_' 之一配合使用 !"); } } setRelateType(t); } else if (originKey.endsWith("~")) { boolean ignoreCase = originKey.endsWith("*~"); setRelateType(ignoreCase ? "*~" : "~"); k = originKey.substring(0, originKey.length() - (ignoreCase ? 2 : 1)); } else if (originKey.endsWith(">=")) { setRelateType(">="); k = originKey.substring(0, originKey.length() - 2); } else if (originKey.endsWith("<=")) { setRelateType("<="); k = originKey.substring(0, originKey.length() - 2); } else if (originKey.endsWith(">")) { setRelateType(">"); k = originKey.substring(0, originKey.length() - 1); } else if (originKey.endsWith("<")) { setRelateType("<"); k = originKey.substring(0, originKey.length() - 1); } else { setRelateType(""); k = originKey; } if (k != null && (k.contains("&") || k.contains("|"))) { throw new UnsupportedOperationException(joinType + "/.../" + table + "/" + originKey + " 中字符 " + k + " 不合法!与或非逻辑符仅支持 '!' 非逻辑符 !"); } //TODO if (c3 == '-') { // 表示 key 和 value 顺序反过来: value LIKE key Logic l = new Logic(k); setLogic(l); if (StringUtil.isName(l.getKey()) == false) { throw new IllegalArgumentException(joinType + "/.../" + table + "/" + originKey + " 中字符 " + l.getKey() + " 不合法!必须符合字段命名格式!"); } setKey(l.getKey()); } } }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/orm/Join.java
161
package com.neo.model; import javax.persistence.*; import java.io.Serializable; import java.util.List; @Entity public class UserInfo implements Serializable { @Id @GeneratedValue private Integer uid; @Column(unique =true) private String username;//帐号 private String name;//名称(昵称或者真实姓名,不同系统不同定义) private String password; //密码; private String salt;//加密密码的盐 private byte state;//用户状态,0:创建未认证(比如没有激活,没有输入验证码等等)--等待验证的用户 , 1:正常状态,2:用户被锁定. @ManyToMany(fetch= FetchType.EAGER)//立即从数据库中进行加载数据; @JoinTable(name = "SysUserRole", joinColumns = { @JoinColumn(name = "uid") }, inverseJoinColumns ={@JoinColumn(name = "roleId") }) private List<SysRole> roleList;// 一个用户具有多个角色 public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public byte getState() { return state; } public void setState(byte state) { this.state = state; } public List<SysRole> getRoleList() { return roleList; } public void setRoleList(List<SysRole> roleList) { this.roleList = roleList; } /** * 密码盐. * @return */ public String getCredentialsSalt(){ return this.username+this.salt; } //重新对盐重新进行了定义,用户名+salt,这样就更加不容易被破解 }
ityouknow/spring-boot-examples
2.x/spring-boot-shiro/src/main/java/com/neo/model/UserInfo.java
162
package org.ansj.dic; import org.nlpcn.commons.lang.util.logging.Log; import org.nlpcn.commons.lang.util.logging.LogFactory; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; /** * 加载词典用的类 * * @author ansj */ public class DicReader { private static final Log logger = LogFactory.getLog(); public static BufferedReader getReader(String name) { // maven工程修改词典加载方式 InputStream in = DicReader.class.getResourceAsStream("/" + name); try { return new BufferedReader(new InputStreamReader(in, "UTF-8")); } catch (UnsupportedEncodingException e) { logger.warn("不支持的编码", e); } return null; } public static InputStream getInputStream(String name) { // maven工程修改词典加载方式 InputStream in = DicReader.class.getResourceAsStream("/" + name); return in; } }
NLPchina/ansj_seg
src/main/java/org/ansj/dic/DicReader.java
165
package com.taobao.arthas.core.advisor; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.common.concurrent.ConcurrentWeakKeyHashMap; import com.taobao.arthas.core.server.ArthasBootstrap; import com.taobao.arthas.core.shell.system.ExecStatus; import com.taobao.arthas.core.shell.system.Process; import com.taobao.arthas.core.shell.system.ProcessAware; /** * * TODO line 的记录 listener方式? 还是有string为key,不过 classname|method|desc|num 这样子? * 判断是否已插入了,可以在两行中间查询,有没有 SpyAPI 的invoke? * * TODO trace的怎么搞? trace 只记录一次就可以了 classname|method|desc|trace ? 怎么避免 trace 到 * SPY的invoke ?直接忽略? * * TODO trace命令可以动态的增加 新的函数进去不?只要关联上同一个 Listener应该是可以的。 * * TODO 在SPY里放很多的 Object数组,然后动态的设置进去? 比如有新的 Listener来的时候。 这样子连查表都不用了。 甚至可以动态生成 * 存放这些 Listener数组的类? 这样子的话,只要有 Binding那里,查询到一个具体分配好的类, 这样子就可以了? * 甚至每个ClassLoader里都动态生成这样子的 存放类,那么这样子不可以避免查 ClassLoader了么? * * 动态为每一个增强类,生成一个新的类,新的类里,有各种的 ID 数组,保存每一个类的每一种 trace 点的信息?? * * 多个 watch命令 对同一个类,现在的逻辑是,每个watch都有一个自己的 TransForm,但不会重复增强,因为做了判断。 * watch命令停止时,也没有去掉增强的代码。 只有reset时 才会去掉。 * * 其实用户想查看局部变量,并不是想查看哪一行! 而是想看某个函数里子调用时的 局部变量的值! 所以实际上是想要一个新的命令,比如 watchinmethod * , 可以 在某个子调用里, * * TODO 现在的trace 可以输出行号,可能不是很精确,但是可以对应上的。 这个在新的方式里怎么支持? 增加一个 linenumber binding? * 从mehtodNode,向上查找到最近的行号? * * TODO 防止重复增强,最重要的应该还是动态增加 annotation,这个才是真正可以做到某一行,某一个子 invoke 都能识别出来的! 无论是 * transform多少次! 字节码怎么动态加 annotation ? annotation里签名用 url ?的key/value方式表达! * 这样子可以有效还原信息 * * TODO 是否考虑一个 trace /watch命令之后,得到一个具体的 Listener ID, 允许在另外的窗口里,再次 * trace/watch时指定这个ID,就会查找到,并处理。 这样子的话,真正达到了动态灵活的,一层一层增加的trace ! * * * @author hengyunabc 2020-04-24 * */ public class AdviceListenerManager { private static final Logger logger = LoggerFactory.getLogger(AdviceListenerManager.class); private static final FakeBootstrapClassLoader FAKEBOOTSTRAPCLASSLOADER = new FakeBootstrapClassLoader(); static { // 清理失效的 AdviceListener ArthasBootstrap.getInstance().getScheduledExecutorService().scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { for (Entry<ClassLoader, ClassLoaderAdviceListenerManager> entry : adviceListenerMap.entrySet()) { ClassLoaderAdviceListenerManager adviceListenerManager = entry.getValue(); synchronized (adviceListenerManager) { for (Entry<String, List<AdviceListener>> eee : adviceListenerManager.map.entrySet()) { List<AdviceListener> listeners = eee.getValue(); List<AdviceListener> newResult = new ArrayList<AdviceListener>(); for (AdviceListener listener : listeners) { if (listener instanceof ProcessAware) { ProcessAware processAware = (ProcessAware) listener; Process process = processAware.getProcess(); if (process == null) { continue; } ExecStatus status = process.status(); if (!status.equals(ExecStatus.TERMINATED)) { newResult.add(listener); } } } if (newResult.size() != listeners.size()) { adviceListenerManager.map.put(eee.getKey(), newResult); } } } } } catch (Throwable e) { try { logger.error("clean AdviceListener error", e); } catch (Throwable t) { // ignore } } } }, 3, 3, TimeUnit.SECONDS); } private static final ConcurrentWeakKeyHashMap<ClassLoader, ClassLoaderAdviceListenerManager> adviceListenerMap = new ConcurrentWeakKeyHashMap<ClassLoader, ClassLoaderAdviceListenerManager>(); static class ClassLoaderAdviceListenerManager { private ConcurrentHashMap<String, List<AdviceListener>> map = new ConcurrentHashMap<String, List<AdviceListener>>(); private String key(String className, String methodName, String methodDesc) { return className + methodName + methodDesc; } private String keyForTrace(String className, String owner, String methodName, String methodDesc) { return className + owner + methodName + methodDesc; } public void registerAdviceListener(String className, String methodName, String methodDesc, AdviceListener listener) { synchronized (this) { className = className.replace('/', '.'); String key = key(className, methodName, methodDesc); List<AdviceListener> listeners = map.get(key); if (listeners == null) { listeners = new ArrayList<AdviceListener>(); map.put(key, listeners); } if (!listeners.contains(listener)) { listeners.add(listener); } } } public List<AdviceListener> queryAdviceListeners(String className, String methodName, String methodDesc) { className = className.replace('/', '.'); String key = key(className, methodName, methodDesc); List<AdviceListener> listeners = map.get(key); return listeners; } public void registerTraceAdviceListener(String className, String owner, String methodName, String methodDesc, AdviceListener listener) { className = className.replace('/', '.'); String key = keyForTrace(className, owner, methodName, methodDesc); List<AdviceListener> listeners = map.get(key); if (listeners == null) { listeners = new ArrayList<AdviceListener>(); map.put(key, listeners); } if (!listeners.contains(listener)) { listeners.add(listener); } } public List<AdviceListener> queryTraceAdviceListeners(String className, String owner, String methodName, String methodDesc) { className = className.replace('/', '.'); String key = keyForTrace(className, owner, methodName, methodDesc); List<AdviceListener> listeners = map.get(key); return listeners; } } public static void registerAdviceListener(ClassLoader classLoader, String className, String methodName, String methodDesc, AdviceListener listener) { classLoader = wrap(classLoader); className = className.replace('/', '.'); ClassLoaderAdviceListenerManager manager = adviceListenerMap.get(classLoader); if (manager == null) { manager = new ClassLoaderAdviceListenerManager(); adviceListenerMap.put(classLoader, manager); } manager.registerAdviceListener(className, methodName, methodDesc, listener); } public static void updateAdviceListeners() { } public static List<AdviceListener> queryAdviceListeners(ClassLoader classLoader, String className, String methodName, String methodDesc) { classLoader = wrap(classLoader); className = className.replace('/', '.'); ClassLoaderAdviceListenerManager manager = adviceListenerMap.get(classLoader); if (manager != null) { return manager.queryAdviceListeners(className, methodName, methodDesc); } return null; } public static void registerTraceAdviceListener(ClassLoader classLoader, String className, String owner, String methodName, String methodDesc, AdviceListener listener) { classLoader = wrap(classLoader); className = className.replace('/', '.'); ClassLoaderAdviceListenerManager manager = adviceListenerMap.get(classLoader); if (manager == null) { manager = new ClassLoaderAdviceListenerManager(); adviceListenerMap.put(classLoader, manager); } manager.registerTraceAdviceListener(className, owner, methodName, methodDesc, listener); } public static List<AdviceListener> queryTraceAdviceListeners(ClassLoader classLoader, String className, String owner, String methodName, String methodDesc) { classLoader = wrap(classLoader); className = className.replace('/', '.'); ClassLoaderAdviceListenerManager manager = adviceListenerMap.get(classLoader); if (manager != null) { return manager.queryTraceAdviceListeners(className, owner, methodName, methodDesc); } return null; } private static ClassLoader wrap(ClassLoader classLoader) { if (classLoader != null) { return classLoader; } return FAKEBOOTSTRAPCLASSLOADER; } private static class FakeBootstrapClassLoader extends ClassLoader { } }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/advisor/AdviceListenerManager.java
167
package me.zhyd.oauth.utils; import java.nio.charset.StandardCharsets; /** * 该配置仅用于支持 PKCE 模式的平台,针对无服务应用,不推荐使用隐式授权,推荐使用 PKCE 模式 * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @version 1.0.0 * @since 1.0.0 */ public class PkceUtil { public static String generateCodeVerifier() { String randomStr = RandomUtil.randomString(50); return Base64Utils.encodeUrlSafe(randomStr); } /** * 适用于 OAuth 2.0 PKCE 增强协议 * * @param codeChallengeMethod s256 / plain * @param codeVerifier 客户端生产的校验码 * @return code challenge */ public static String generateCodeChallenge(String codeChallengeMethod, String codeVerifier) { if ("S256".equalsIgnoreCase(codeChallengeMethod)) { // https://tools.ietf.org/html/rfc7636#section-4.2 // code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) return newStringUsAscii(Base64Utils.encodeUrlSafe(Sha256.digest(codeVerifier), true)); } else { return codeVerifier; } } public static String newStringUsAscii(byte[] bytes) { return new String(bytes, StandardCharsets.US_ASCII); } }
justauth/JustAuth
src/main/java/me/zhyd/oauth/utils/PkceUtil.java
168
/** * @author Anonymous * @since 2019/12/6 */ public class Solution { /** * 查找数组中出现次数超过一次的数字 * * @param array 数组 * @return 返回该数,不存在则返回0 */ public int MoreThanHalfNum_Solution(int[] array) { if (array == null || array.length == 0) { return 0; } int res = array[0]; int times = 1; for (int i = 1; i < array.length; ++i) { if (times == 0) { res = array[i]; times = 1; } else if (array[i] == res) { ++times; } else { --times; } } return isMoreThanHalf(array, res) ? res : 0; } /** * 判断val元素是否真的超过数组元素个数的一半 * * @param array 数组 * @param val 某元素 * @return boolean */ private boolean isMoreThanHalf(int[] array, int val) { int cnt = 0; for (int e : array) { if (e == val) { ++cnt; } } return cnt * 2 > array.length; } }
geekxh/hello-algorithm
算法读物/剑指offer/39_MoreThanHalfNumber/Solution.java
170
package com.xkcoding.rbac.security.util; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.xkcoding.rbac.security.common.Consts; import com.xkcoding.rbac.security.common.Status; import com.xkcoding.rbac.security.config.JwtConfig; import com.xkcoding.rbac.security.exception.SecurityException; import com.xkcoding.rbac.security.vo.UserPrincipal; import io.jsonwebtoken.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import javax.servlet.http.HttpServletRequest; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * <p> * JWT 工具类 * </p> * * @author yangkai.shen * @date Created in 2018-12-07 13:42 */ @EnableConfigurationProperties(JwtConfig.class) @Configuration @Slf4j public class JwtUtil { @Autowired private JwtConfig jwtConfig; @Autowired private StringRedisTemplate stringRedisTemplate; /** * 创建JWT * * @param rememberMe 记住我 * @param id 用户id * @param subject 用户名 * @param roles 用户角色 * @param authorities 用户权限 * @return JWT */ public String createJWT(Boolean rememberMe, Long id, String subject, List<String> roles, Collection<? extends GrantedAuthority> authorities) { Date now = new Date(); JwtBuilder builder = Jwts.builder().setId(id.toString()).setSubject(subject).setIssuedAt(now).signWith(SignatureAlgorithm.HS256, jwtConfig.getKey()).claim("roles", roles).claim("authorities", authorities); // 设置过期时间 Long ttl = rememberMe ? jwtConfig.getRemember() : jwtConfig.getTtl(); if (ttl > 0) { builder.setExpiration(DateUtil.offsetMillisecond(now, ttl.intValue())); } String jwt = builder.compact(); // 将生成的JWT保存至Redis stringRedisTemplate.opsForValue().set(Consts.REDIS_JWT_KEY_PREFIX + subject, jwt, ttl, TimeUnit.MILLISECONDS); return jwt; } /** * 创建JWT * * @param authentication 用户认证信息 * @param rememberMe 记住我 * @return JWT */ public String createJWT(Authentication authentication, Boolean rememberMe) { UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); return createJWT(rememberMe, userPrincipal.getId(), userPrincipal.getUsername(), userPrincipal.getRoles(), userPrincipal.getAuthorities()); } /** * 解析JWT * * @param jwt JWT * @return {@link Claims} */ public Claims parseJWT(String jwt) { try { Claims claims = Jwts.parser().setSigningKey(jwtConfig.getKey()).parseClaimsJws(jwt).getBody(); String username = claims.getSubject(); String redisKey = Consts.REDIS_JWT_KEY_PREFIX + username; // 校验redis中的JWT是否存在 Long expire = stringRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS); if (Objects.isNull(expire) || expire <= 0) { throw new SecurityException(Status.TOKEN_EXPIRED); } // 校验redis中的JWT是否与当前的一致,不一致则代表用户已注销/用户在不同设备登录,均代表JWT已过期 String redisToken = stringRedisTemplate.opsForValue().get(redisKey); if (!StrUtil.equals(jwt, redisToken)) { throw new SecurityException(Status.TOKEN_OUT_OF_CTRL); } return claims; } catch (ExpiredJwtException e) { log.error("Token 已过期"); throw new SecurityException(Status.TOKEN_EXPIRED); } catch (UnsupportedJwtException e) { log.error("不支持的 Token"); throw new SecurityException(Status.TOKEN_PARSE_ERROR); } catch (MalformedJwtException e) { log.error("Token 无效"); throw new SecurityException(Status.TOKEN_PARSE_ERROR); } catch (SignatureException e) { log.error("无效的 Token 签名"); throw new SecurityException(Status.TOKEN_PARSE_ERROR); } catch (IllegalArgumentException e) { log.error("Token 参数不存在"); throw new SecurityException(Status.TOKEN_PARSE_ERROR); } } /** * 设置JWT过期 * * @param request 请求 */ public void invalidateJWT(HttpServletRequest request) { String jwt = getJwtFromRequest(request); String username = getUsernameFromJWT(jwt); // 从redis中清除JWT stringRedisTemplate.delete(Consts.REDIS_JWT_KEY_PREFIX + username); } /** * 根据 jwt 获取用户名 * * @param jwt JWT * @return 用户名 */ public String getUsernameFromJWT(String jwt) { Claims claims = parseJWT(jwt); return claims.getSubject(); } /** * 从 request 的 header 中获取 JWT * * @param request 请求 * @return JWT */ public String getJwtFromRequest(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (StrUtil.isNotBlank(bearerToken) && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); } return null; } }
xkcoding/spring-boot-demo
demo-rbac-security/src/main/java/com/xkcoding/rbac/security/util/JwtUtil.java
171
/** * IK 中文分词 版本 5.0 * IK Analyzer release 5.0 * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * 源代码由林良益([email protected])提供 * 版权声明 2012,乌龙茶工作室 * provided by Linliangyi and copyright 2012 by Oolong studio * */ package org.wltea.analyzer.core; import org.wltea.analyzer.dic.Dictionary; import org.wltea.analyzer.dic.Hit; import java.util.LinkedList; import java.util.List; /** * 中文-日韩文子分词器 */ class CJKSegmenter implements ISegmenter { //子分词器标签 static final String SEGMENTER_NAME = "CJK_SEGMENTER"; //待处理的分词hit队列 private List<Hit> tmpHits; CJKSegmenter(){ this.tmpHits = new LinkedList<Hit>(); } /* (non-Javadoc) * @see org.wltea.analyzer.core.ISegmenter#analyze(org.wltea.analyzer.core.AnalyzeContext) */ public void analyze(AnalyzeContext context) { if(CharacterUtil.CHAR_USELESS != context.getCurrentCharType()){ //优先处理tmpHits中的hit if(!this.tmpHits.isEmpty()){ //处理词段队列 Hit[] tmpArray = this.tmpHits.toArray(new Hit[this.tmpHits.size()]); for(Hit hit : tmpArray){ hit = Dictionary.getSingleton().matchWithHit(context.getSegmentBuff(), context.getCursor() , hit); if(hit.isMatch()){ //输出当前的词 Lexeme newLexeme = new Lexeme(context.getBufferOffset() , hit.getBegin() , context.getCursor() - hit.getBegin() + 1 , Lexeme.TYPE_CNWORD); context.addLexeme(newLexeme); if(!hit.isPrefix()){//不是词前缀,hit不需要继续匹配,移除 this.tmpHits.remove(hit); } }else if(hit.isUnmatch()){ //hit不是词,移除 this.tmpHits.remove(hit); } } } //********************************* //再对当前指针位置的字符进行单字匹配 Hit singleCharHit = Dictionary.getSingleton().matchInMainDict(context.getSegmentBuff(), context.getCursor(), 1); if(singleCharHit.isMatch()){//首字成词 //输出当前的词 Lexeme newLexeme = new Lexeme(context.getBufferOffset() , context.getCursor() , 1 , Lexeme.TYPE_CNWORD); context.addLexeme(newLexeme); //同时也是词前缀 if(singleCharHit.isPrefix()){ //前缀匹配则放入hit列表 this.tmpHits.add(singleCharHit); } }else if(singleCharHit.isPrefix()){//首字为词前缀 //前缀匹配则放入hit列表 this.tmpHits.add(singleCharHit); } }else{ //遇到CHAR_USELESS字符 //清空队列 this.tmpHits.clear(); } //判断缓冲区是否已经读完 if(context.isBufferConsumed()){ //清空队列 this.tmpHits.clear(); } //判断是否锁定缓冲区 if(this.tmpHits.size() == 0){ context.unlockBuffer(SEGMENTER_NAME); }else{ context.lockBuffer(SEGMENTER_NAME); } } /* (non-Javadoc) * @see org.wltea.analyzer.core.ISegmenter#reset() */ public void reset() { //清空队列 this.tmpHits.clear(); } }
infinilabs/analysis-ik
core/src/main/java/org/wltea/analyzer/core/CJKSegmenter.java
172
/* * 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.mvp; import android.app.Activity; import android.content.Intent; import androidx.annotation.NonNull; import com.jess.arms.utils.ArmsUtils; import static com.jess.arms.utils.Preconditions.checkNotNull; /** * ================================================ * 框架要求框架中的每个 View 都需要实现此类, 以满足规范 * <p> * 为了满足部分人的诉求以及向下兼容, {@link IView} 中的部分方法使用 JAVA 1.8 的默认方法实现, 这样实现类可以按实际需求选择是否实现某些方法 * 不实现则使用默认方法中的逻辑, 不清楚默认方法的请自行学习 * * @see <a href="https://github.com/JessYanCoding/MVPArms/wiki#2.4.2">View wiki 官方文档</a> * Created by JessYan on 4/22/2016 * <a href="mailto:[email protected]">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * ================================================ */ public interface IView { /** * 显示加载 */ default void showLoading() { } /** * 隐藏加载 */ default void hideLoading() { } /** * 显示信息 * * @param message 消息内容, 不能为 {@code null} */ void showMessage(@NonNull String message); /** * 跳转 {@link Activity} * * @param intent {@code intent} 不能为 {@code null} */ default void launchActivity(@NonNull Intent intent) { checkNotNull(intent); ArmsUtils.startActivity(intent); } /** * 杀死自己 */ default void killMyself() { } }
JessYanCoding/MVPArms
arms/src/main/java/com/jess/arms/mvp/IView.java
173
package com.example.gsyvideoplayer; import android.annotation.TargetApi; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.ViewCompat; import android.transition.Transition; import android.view.View; import android.widget.ImageView; import com.example.gsyvideoplayer.databinding.ActivityPlayBinding; import com.example.gsyvideoplayer.listener.OnTransitionListener; import com.example.gsyvideoplayer.model.SwitchVideoModel; import com.shuyu.gsyvideoplayer.GSYVideoManager; import com.shuyu.gsyvideoplayer.utils.OrientationUtils; import java.util.ArrayList; import java.util.List; /** * 单独的视频播放页面 * Created by shuyu on 2016/11/11. */ public class PlayActivity extends AppCompatActivity { public final static String IMG_TRANSITION = "IMG_TRANSITION"; public final static String TRANSITION = "TRANSITION"; OrientationUtils orientationUtils; private boolean isTransition; private Transition transition; private ActivityPlayBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityPlayBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); isTransition = getIntent().getBooleanExtra(TRANSITION, false); init(); } private void init() { String url = "https://res.exexm.com/cw_145225549855002"; //String url = "http://7xse1z.com1.z0.glb.clouddn.com/1491813192"; //需要路径的 //videoPlayer.setUp(url, true, new File(FileUtils.getPath()), ""); //借用了jjdxm_ijkplayer的URL String source1 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear1/prog_index.m3u8"; String name = "普通"; SwitchVideoModel switchVideoModel = new SwitchVideoModel(name, source1); String source2 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear3/prog_index.m3u8"; String name2 = "清晰"; SwitchVideoModel switchVideoModel2 = new SwitchVideoModel(name2, source2); List<SwitchVideoModel> list = new ArrayList<>(); list.add(switchVideoModel); list.add(switchVideoModel2); binding.videoPlayer.setUp(list, false, "测试视频"); //增加封面 ImageView imageView = new ImageView(this); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.mipmap.xxx1); binding.videoPlayer.setThumbImageView(imageView); //增加title binding.videoPlayer.getTitleTextView().setVisibility(View.VISIBLE); //videoPlayer.setShowPauseCover(false); //videoPlayer.setSpeed(2f); //设置返回键 binding.videoPlayer.getBackButton().setVisibility(View.VISIBLE); //设置旋转 orientationUtils = new OrientationUtils(this, binding.videoPlayer); //设置全屏按键功能,这是使用的是选择屏幕,而不是全屏 binding.videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ------- !!!如果不需要旋转屏幕,可以不调用!!!------- // 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false) orientationUtils.resolveByClick(); } }); //videoPlayer.setBottomProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setDialogVolumeProgressBar(getResources().getDrawable(R.drawable.video_new_volume_progress_bg)); //videoPlayer.setDialogProgressBar(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setBottomShowProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_seekbar_progress), //getResources().getDrawable(R.drawable.video_new_seekbar_thumb)); //videoPlayer.setDialogProgressColor(getResources().getColor(R.color.colorAccent), -11); //是否可以滑动调整 binding.videoPlayer.setIsTouchWiget(true); //设置返回按键功能 binding.videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); //过渡动画 initTransition(); } @Override protected void onPause() { super.onPause(); binding.videoPlayer.onVideoPause(); } @Override protected void onResume() { super.onResume(); binding.videoPlayer.onVideoResume(); } @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected void onDestroy() { super.onDestroy(); if (orientationUtils != null) orientationUtils.releaseListener(); } @Override public void onBackPressed() { //先返回正常状态 if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { binding.videoPlayer.getFullscreenButton().performClick(); return; } //释放所有 binding.videoPlayer.setVideoAllCallBack(null); GSYVideoManager.releaseAllVideos(); if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { super.onBackPressed(); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); overridePendingTransition(androidx.appcompat.R.anim.abc_fade_in, androidx.appcompat.R.anim.abc_fade_out); } }, 500); } } private void initTransition() { if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { postponeEnterTransition(); ViewCompat.setTransitionName(binding.videoPlayer, IMG_TRANSITION); addTransitionListener(); startPostponedEnterTransition(); } else { binding.videoPlayer.startPlayLogic(); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean addTransitionListener() { transition = getWindow().getSharedElementEnterTransition(); if (transition != null) { transition.addListener(new OnTransitionListener() { @Override public void onTransitionEnd(Transition transition) { super.onTransitionEnd(transition); binding.videoPlayer.startPlayLogic(); transition.removeListener(this); } }); return true; } return false; } }
CarGuo/GSYVideoPlayer
app/src/main/java/com/example/gsyvideoplayer/PlayActivity.java
174
package me.yokeyword.sample; import android.app.Application; import me.yokeyword.fragmentation.Fragmentation; import me.yokeyword.fragmentation.helper.ExceptionHandler; /** * Created by YoKey on 16/11/23. */ public class App extends Application { @Override public void onCreate() { super.onCreate(); Fragmentation.builder() // 设置 栈视图 模式为 (默认)悬浮球模式 SHAKE: 摇一摇唤出 NONE:隐藏, 仅在Debug环境生效 .stackViewMode(Fragmentation.BUBBLE) .debug(true) // 实际场景建议.debug(BuildConfig.DEBUG) /** * 可以获取到{@link me.yokeyword.fragmentation.exception.AfterSaveStateTransactionWarning} * 在遇到After onSaveInstanceState时,不会抛出异常,会回调到下面的ExceptionHandler */ .handleException(new ExceptionHandler() { @Override public void onException(Exception e) { // 以Bugtags为例子: 把捕获到的 Exception 传到 Bugtags 后台。 // Bugtags.sendException(e); } }) .install(); } }
YoKeyword/Fragmentation
demo/src/main/java/me/yokeyword/sample/App.java
175
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.common.utils; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.LocaleResolver; import com.google.common.collect.Lists; /** * 字符串工具类, 继承org.apache.commons.lang3.StringUtils类 * @author ThinkGem * @version 2013-05-22 */ public class StringUtils extends org.apache.commons.lang3.StringUtils { private static final char SEPARATOR = '_'; private static final String CHARSET_NAME = "UTF-8"; /** * 转换为字节数组 * @param str * @return */ public static byte[] getBytes(String str){ if (str != null){ try { return str.getBytes(CHARSET_NAME); } catch (UnsupportedEncodingException e) { return null; } }else{ return null; } } /** * 转换为Boolean类型 * 'true', 'on', 'y', 't', 'yes' or '1' (case insensitive) will return true. Otherwise, false is returned. */ public static Boolean toBoolean(final Object val){ if (val == null){ return false; } return BooleanUtils.toBoolean(val.toString()) || "1".equals(val.toString()); } /** * 转换为字节数组 * @param str * @return */ public static String toString(byte[] bytes){ try { return new String(bytes, CHARSET_NAME); } catch (UnsupportedEncodingException e) { return EMPTY; } } /** * 如果对象为空,则使用defaultVal值 * see: ObjectUtils.toString(obj, defaultVal) * @param obj * @param defaultVal * @return */ public static String toString(final Object obj, final String defaultVal) { return obj == null ? defaultVal : obj.toString(); } /** * 是否包含字符串 * @param str 验证字符串 * @param strs 字符串组 * @return 包含返回true */ public static boolean inString(String str, String... strs){ if (str != null){ for (String s : strs){ if (str.equals(trim(s))){ return true; } } } return false; } /** * 替换掉HTML标签方法 */ public static String replaceHtml(String html) { if (isBlank(html)){ return ""; } String regEx = "<.+?>"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(html); String s = m.replaceAll(""); return s; } /** * 替换为手机识别的HTML,去掉样式及属性,保留回车。 * @param html * @return */ public static String replaceMobileHtml(String html){ if (html == null){ return ""; } return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>"); } /** * 替换为手机识别的HTML,去掉样式及属性,保留回车。 * @param txt * @return */ public static String toHtml(String txt){ if (txt == null){ return ""; } return replace(replace(Encodes.escapeHtml(txt), "\n", "<br/>"), "\t", "&nbsp; &nbsp; "); } /** * 缩略字符串(不区分中英文字符) * @param str 目标字符串 * @param length 截取长度 * @return */ public static String abbr(String str, int length) { if (str == null) { return ""; } try { StringBuilder sb = new StringBuilder(); int currentLength = 0; for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) { currentLength += String.valueOf(c).getBytes("GBK").length; if (currentLength <= length - 3) { sb.append(c); } else { sb.append("..."); break; } } return sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } public static String abbr2(String param, int length) { if (param == null) { return ""; } StringBuffer result = new StringBuffer(); int n = 0; char temp; boolean isCode = false; // 是不是HTML代码 boolean isHTML = false; // 是不是HTML特殊字符,如&nbsp; for (int i = 0; i < param.length(); i++) { temp = param.charAt(i); if (temp == '<') { isCode = true; } else if (temp == '&') { isHTML = true; } else if (temp == '>' && isCode) { n = n - 1; isCode = false; } else if (temp == ';' && isHTML) { isHTML = false; } try { if (!isCode && !isHTML) { n += String.valueOf(temp).getBytes("GBK").length; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (n <= length - 3) { result.append(temp); } else { result.append("..."); break; } } // 取出截取字符串中的HTML标记 String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2"); // 去掉不需要结素标记的HTML标记 temp_result = temp_result .replaceAll( "</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", ""); // 去掉成对的HTML标记 temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2"); // 用正则表达式取出标记 Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>"); Matcher m = p.matcher(temp_result); List<String> endHTML = Lists.newArrayList(); while (m.find()) { endHTML.add(m.group(1)); } // 补全不成对的HTML标记 for (int i = endHTML.size() - 1; i >= 0; i--) { result.append("</"); result.append(endHTML.get(i)); result.append(">"); } return result.toString(); } /** * 转换为Double类型 */ public static Double toDouble(Object val){ if (val == null){ return 0D; } try { return Double.valueOf(trim(val.toString())); } catch (Exception e) { return 0D; } } /** * 转换为Float类型 */ public static Float toFloat(Object val){ return toDouble(val).floatValue(); } /** * 转换为Long类型 */ // public static Long toLong(Object val){ // return toDouble(val).longValue(); // } public static Long toLong(Object val) { if (val == null) { return 0L; } try { return Long.valueOf(trim(val.toString())); } catch (Exception e) { return 0L; } } /** * 转换为Integer类型 */ public static Integer toInteger(Object val){ return toLong(val).intValue(); } /** * 获得i18n字符串 */ public static String getMessage(String code, Object[] args) { LocaleResolver localLocaleResolver = (LocaleResolver) SpringContextHolder.getBean(LocaleResolver.class); HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); Locale localLocale = localLocaleResolver.resolveLocale(request); return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale); } /** * 获得用户远程地址 */ public static String getRemoteAddr(HttpServletRequest request){ String remoteAddr = request.getHeader("X-Real-IP"); if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("X-Forwarded-For"); }else if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("Proxy-Client-IP"); }else if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("WL-Proxy-Client-IP"); } return remoteAddr != null ? remoteAddr : request.getRemoteAddr(); } /** * 驼峰命名法工具 * @return * toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCamelCase(String s) { if (s == null) { return null; } s = s.toLowerCase(); StringBuilder sb = new StringBuilder(s.length()); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == SEPARATOR) { upperCase = true; } else if (upperCase) { sb.append(Character.toUpperCase(c)); upperCase = false; } else { sb.append(c); } } return sb.toString(); } /** * 驼峰命名法工具 * @return * toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCapitalizeCamelCase(String s) { if (s == null) { return null; } s = toCamelCase(s); return s.substring(0, 1).toUpperCase() + s.substring(1); } /** * 驼峰命名法工具 * @return * toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toUnderScoreCase(String s) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean nextUpperCase = true; if (i < (s.length() - 1)) { nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); } if ((i > 0) && Character.isUpperCase(c)) { if (!upperCase || !nextUpperCase) { sb.append(SEPARATOR); } upperCase = true; } else { upperCase = false; } sb.append(Character.toLowerCase(c)); } return sb.toString(); } /** * 转换为JS获取对象值,生成三目运算返回结果 * @param objectString 对象串 * 例如:row.user.id * 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id */ public static String jsGetVal(String objectString){ StringBuilder result = new StringBuilder(); StringBuilder val = new StringBuilder(); String[] vals = split(objectString, "."); for (int i=0; i<vals.length; i++){ val.append("." + vals[i]); result.append("!"+(val.substring(1))+"?'':"); } result.append(val.substring(1)); return result.toString(); } }
thinkgem/jeesite
src/main/java/com/thinkgem/jeesite/common/utils/StringUtils.java
176
package org.wltea.analyzer.dic; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedAction; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpHead; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.logging.log4j.Logger; import org.wltea.analyzer.cfg.Configuration; import org.wltea.analyzer.help.ESPluginLoggerFactory; public class Monitor implements Runnable { private static final Logger logger = ESPluginLoggerFactory.getLogger(Monitor.class.getName()); private static CloseableHttpClient httpclient = HttpClients.createDefault(); /* * 上次更改时间 */ private String last_modified; /* * 资源属性 */ private String eTags; /* * 请求地址 */ private String location; private Configuration configuration; public Monitor(String location, Configuration cfg) { this.location = location; this.last_modified = null; this.eTags = null; this.configuration = cfg; } public void run() { configuration.check(); AccessController.doPrivileged((PrivilegedAction<Void>) () -> { this.runUnprivileged(); return null; }); } /** * 监控流程: * ①向词库服务器发送Head请求 * ②从响应中获取Last-Modify、ETags字段值,判断是否变化 * ③如果未变化,休眠1min,返回第①步 * ④如果有变化,重新加载词典 * ⑤休眠1min,返回第①步 */ public void runUnprivileged() { //超时设置 RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10*1000) .setConnectTimeout(10*1000).setSocketTimeout(15*1000).build(); HttpHead head = new HttpHead(location); head.setConfig(rc); //设置请求头 if (last_modified != null) { head.setHeader("If-Modified-Since", last_modified); } if (eTags != null) { head.setHeader("If-None-Match", eTags); } CloseableHttpResponse response = null; try { response = httpclient.execute(head); //返回200 才做操作 if(response.getStatusLine().getStatusCode()==200){ if (((response.getLastHeader("Last-Modified")!=null) && !response.getLastHeader("Last-Modified").getValue().equalsIgnoreCase(last_modified)) ||((response.getLastHeader("ETag")!=null) && !response.getLastHeader("ETag").getValue().equalsIgnoreCase(eTags))) { // 远程词库有更新,需要重新加载词典,并修改last_modified,eTags Dictionary.getSingleton().reLoadMainDict(); last_modified = response.getLastHeader("Last-Modified")==null?null:response.getLastHeader("Last-Modified").getValue(); eTags = response.getLastHeader("ETag")==null?null:response.getLastHeader("ETag").getValue(); } }else if (response.getStatusLine().getStatusCode()==304) { //没有修改,不做操作 //noop }else{ logger.info("remote_ext_dict {} return bad code {}" , location , response.getStatusLine().getStatusCode() ); } } catch (Exception e) { logger.error("remote_ext_dict {} error!",e , location); }finally{ try { if (response != null) { response.close(); } } catch (IOException e) { logger.error(e.getMessage(), e); } } } }
infinilabs/analysis-ik
core/src/main/java/org/wltea/analyzer/dic/Monitor.java
178
/** * Author: GcsSloop * <p> * Created Date: 16/5/31 * <p> * Copyright (C) 2016 GcsSloop. * <p> * GitHub: https://github.com/GcsSloop */ public class SearchView extends View { // 画笔 private Paint mPaint; // View 宽高 private int mViewWidth; private int mViewHeight; public SearchView(Context context) { this(context,null); } public SearchView(Context context, AttributeSet attrs) { super(context, attrs); initAll(); } public void initAll() { initPaint(); initPath(); initListener(); initHandler(); initAnimator(); // 进入开始动画 mCurrentState = State.STARTING; mStartingAnimator.start(); } // 这个视图拥有的状态 public static enum State { NONE, STARTING, SEARCHING, ENDING } // 当前的状态(非常重要) private State mCurrentState = State.NONE; // 放大镜与外部圆环 private Path path_srarch; private Path path_circle; // 测量Path 并截取部分的工具 private PathMeasure mMeasure; // 默认的动效周期 2s private int defaultDuration = 2000; // 控制各个过程的动画 private ValueAnimator mStartingAnimator; private ValueAnimator mSearchingAnimator; private ValueAnimator mEndingAnimator; // 动画数值(用于控制动画状态,因为同一时间内只允许有一种状态出现,具体数值处理取决于当前状态) private float mAnimatorValue = 0; // 动效过程监听器 private ValueAnimator.AnimatorUpdateListener mUpdateListener; private Animator.AnimatorListener mAnimatorListener; // 用于控制动画状态转换 private Handler mAnimatorHandler; // 判断是否已经搜索结束 private boolean isOver = false; private int count = 0; private void initPaint() { mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.WHITE); mPaint.setStrokeWidth(15); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setAntiAlias(true); } private void initPath() { path_srarch = new Path(); path_circle = new Path(); mMeasure = new PathMeasure(); // 注意,不要到360度,否则内部会自动优化,测量不能取到需要的数值 RectF oval1 = new RectF(-50, -50, 50, 50); // 放大镜圆环 path_srarch.addArc(oval1, 45, 359.9f); RectF oval2 = new RectF(-100, -100, 100, 100); // 外部圆环 path_circle.addArc(oval2, 45, -359.9f); float[] pos = new float[2]; mMeasure.setPath(path_circle, false); // 放大镜把手的位置 mMeasure.getPosTan(0, pos, null); path_srarch.lineTo(pos[0], pos[1]); // 放大镜把手 Log.i("TAG", "pos=" + pos[0] + ":" + pos[1]); } private void initListener() { mUpdateListener = new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mAnimatorValue = (float) animation.getAnimatedValue(); invalidate(); } }; mAnimatorListener = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { // getHandle发消息通知动画状态更新 mAnimatorHandler.sendEmptyMessage(0); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }; } private void initHandler() { mAnimatorHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (mCurrentState) { case STARTING: // 从开始动画转换好搜索动画 isOver = false; mCurrentState = State.SEARCHING; mStartingAnimator.removeAllListeners(); mSearchingAnimator.start(); break; case SEARCHING: if (!isOver) { // 如果搜索未结束 则继续执行搜索动画 mSearchingAnimator.start(); Log.e("Update", "RESTART"); count++; if (count>2){ // count大于2则进入结束状态 isOver = true; } } else { // 如果搜索已经结束 则进入结束动画 mCurrentState = State.ENDING; mEndingAnimator.start(); } break; case ENDING: // 从结束动画转变为无状态 mCurrentState = State.NONE; break; } } }; } private void initAnimator() { mStartingAnimator = ValueAnimator.ofFloat(0, 1).setDuration(defaultDuration); mSearchingAnimator = ValueAnimator.ofFloat(0, 1).setDuration(defaultDuration); mEndingAnimator = ValueAnimator.ofFloat(1, 0).setDuration(defaultDuration); mStartingAnimator.addUpdateListener(mUpdateListener); mSearchingAnimator.addUpdateListener(mUpdateListener); mEndingAnimator.addUpdateListener(mUpdateListener); mStartingAnimator.addListener(mAnimatorListener); mSearchingAnimator.addListener(mAnimatorListener); mEndingAnimator.addListener(mAnimatorListener); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mViewWidth = w; mViewHeight = h; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawSearch(canvas); } private void drawSearch(Canvas canvas) { mPaint.setColor(Color.WHITE); canvas.translate(mViewWidth / 2, mViewHeight / 2); canvas.drawColor(Color.parseColor("#0082D7")); switch (mCurrentState) { case NONE: canvas.drawPath(path_srarch, mPaint); break; case STARTING: mMeasure.setPath(path_srarch, false); Path dst = new Path(); mMeasure.getSegment(mMeasure.getLength() * mAnimatorValue, mMeasure.getLength(), dst, true); canvas.drawPath(dst, mPaint); break; case SEARCHING: mMeasure.setPath(path_circle, false); Path dst2 = new Path(); float stop = mMeasure.getLength() * mAnimatorValue; float start = (float) (stop - ((0.5 - Math.abs(mAnimatorValue - 0.5)) * 200f)); mMeasure.getSegment(start, stop, dst2, true); canvas.drawPath(dst2, mPaint); break; case ENDING: mMeasure.setPath(path_srarch, false); Path dst3 = new Path(); mMeasure.getSegment(mMeasure.getLength() * mAnimatorValue, mMeasure.getLength(), dst3, true); canvas.drawPath(dst3, mPaint); break; } } }
GcsSloop/AndroidNote
CustomView/Advance/Code/SearchView.java
179
/* * 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.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Toast; import com.lzy.demo.R; import com.lzy.demo.base.BaseDetailActivity; import com.lzy.demo.utils.Urls; import com.lzy.okgo.OkGo; import com.lzy.okgo.adapter.Call; import com.lzy.okgo.convert.StringConvert; import com.lzy.okgo.model.Response; import butterknife.ButterKnife; import butterknife.OnClick; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/11 * 描 述: * 修订历史: * ================================================ */ public class SyncActivity extends BaseDetailActivity { private Handler handler = new InnerHandler(); private class InnerHandler extends Handler { @Override public void handleMessage(Message msg) { String data = (String) msg.obj; System.out.println("同步请求的数据:" + data); Toast.makeText(getApplicationContext(), "同步请求成功" + data, Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_sync); ButterKnife.bind(this); setTitle("同步请求"); } @Override protected void onDestroy() { super.onDestroy(); //Activity销毁时,取消网络请求 OkGo.getInstance().cancelTag(this); } @OnClick(R.id.sync) public void sync(View view) { new Thread(new Runnable() { @Override public void run() { try { // //同步会阻塞主线程,必须开线程 // Response response = OkGo.get(Urls.URL_JSONOBJECT)// // .tag(this)// // .headers("header1", "headerValue1")// // .params("param1", "paramValue1")// // .execute(); //不传callback即为同步请求 Call<String> call = OkGo.<String>get(Urls.URL_JSONOBJECT)// .tag(this)// .headers("header1", "headerValue1")// .params("param1", "paramValue1")// .converter(new StringConvert())// .adapt(); Response<String> response = call.execute(); Message message = Message.obtain(); message.obj = response.body(); handler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } } }).start(); } }
jeasonlzy/okhttp-OkGo
demo/src/main/java/com/lzy/demo/okgo/SyncActivity.java
180
package com.taobao.rigel.rap.common.base; import com.google.gson.reflect.TypeToken; import com.opensymphony.xwork2.ActionSupport; import com.taobao.rigel.rap.account.bo.Role; import com.taobao.rigel.rap.account.bo.User; import com.taobao.rigel.rap.account.service.AccountMgr; import com.taobao.rigel.rap.common.service.impl.ContextManager; import com.taobao.rigel.rap.common.bo.RapError; import com.taobao.rigel.rap.common.config.SystemSettings; import com.taobao.rigel.rap.common.utils.CacheUtils; import com.taobao.rigel.rap.common.utils.CommonUtils; import com.taobao.rigel.rap.organization.bo.Corporation; import java.util.*; public class ActionBase extends ActionSupport { public static String JSON_ERROR = "json-error"; public static String LOGIN_WARN_MSG = "您登录过期啦,不要乱动哦,请打开新页面登录后再提交吧 > 。<"; public static String LOGIN_HINT_MSG = "您尚未登录,或登录已过期,请登录后再试。"; public static String ACCESS_DENY = "您无权访问该页面或数据,请联系系统管理员。"; private boolean isOpSuccess = false; private boolean isReturnUrlFirstSet; private boolean isLoginCtlHidden; private int num; private String returnUrl; private AccountMgr accountMgr; private boolean isOk = true; private String json; private String errMsg; public boolean isOpSuccess() { return isOpSuccess; } public void setIsOpSuccess(boolean isOpSuccess) { this.isOpSuccess = isOpSuccess; } public List<Map<String, Object>> getCorpList() { String [] cacheKey = new String[]{CacheUtils.KEY_CORP_LIST_TOP_ITEMS, new Integer(getCurUserId()).toString()}; String cache = CacheUtils.get(cacheKey); List<Map<String, Object>> corpList = new ArrayList<Map<String, Object>>(); if (cache != null) { corpList = CommonUtils.gson.fromJson(cache, new TypeToken<ArrayList<Corporation>>(){}.getType()); } else { List<Corporation> list = accountMgr.getCorporationListWithPager(getCurUserId(), 1, 20); for (Corporation c : list) { corpList.add(c.toMap()); } CacheUtils.put(cacheKey, CommonUtils.gson.toJson(corpList)); } return corpList; } public List<Map<String, Object>> getAllCorpList() { String [] cacheKey = new String[]{CacheUtils.KEY_CORP_LIST, new Integer(getCurUserId()).toString()}; String cache = CacheUtils.get(cacheKey); List<Map<String, Object>> corpList = new ArrayList<Map<String, Object>>(); if (cache != null) { corpList = CommonUtils.gson.fromJson(cache, new TypeToken<ArrayList<Corporation>>(){}.getType()); } else { List<Corporation> list = accountMgr.getCorporationListWithPager(getCurUserId(), 1, 999); for (Corporation c : list) { corpList.add(c.toMap()); } CacheUtils.put(cacheKey, CommonUtils.gson.toJson(corpList)); } return corpList; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public boolean isLoginCtlHidden() { return isLoginCtlHidden; } public void setLoginCtlHidden(boolean isLoginCtlHidden) { this.isLoginCtlHidden = isLoginCtlHidden; } public String getReturnUrl() { return returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public Long getServerTime() { return new Date().getTime(); } public AccountMgr getAccountMgr() { return accountMgr; } public void setAccountMgr(AccountMgr accountMgr) { this.accountMgr = accountMgr; } public String getCurAccount() { return isUserLogined() ? ContextManager.currentSession() .get(ContextManager.KEY_ACCOUNT).toString() : null; } public boolean getIsLogined() { return isUserLogined(); } protected boolean isUserLogined() { return ContextManager.currentSession().get(ContextManager.KEY_ACCOUNT) != null; } public int getCountOfOnlineUserList() { Map app = ContextManager.getApplication(); String key = ContextManager.KEY_COUNT_OF_ONLINE_USER_LIST; if (app.get(key) == null) { return 0; } else { return (Integer) app.get(key); } } protected int getCurUserId() { Object userIdObj = ContextManager.currentSession().get( ContextManager.KEY_USER_ID); if (userIdObj == null) return -1; return (Integer) userIdObj; } public User getCurUser() { if (isUserLogined()) { User user = new User(); Map session = ContextManager.currentSession(); user.setName((String)session.get(ContextManager.KEY_NAME)); user.setAccount((String)session.get(ContextManager.KEY_ACCOUNT)); user.setRoleList((Set<Role>)session.get(ContextManager.KEY_ROLE_LIST)); user.setId((Integer)session.get(ContextManager.KEY_USER_ID)); String empId = (String) session.get(ContextManager.KEY_EMP_ID); user.setEmpId(empId); return user; } else { return null; } } public boolean getIsOk() { return isOk; } public void setIsOk(boolean isOk) { this.isOk = isOk; } public boolean isReturnUrlFirstSet() { return isReturnUrlFirstSet; } public void setRelativeReturnUrl(String returnUrl) { this.returnUrl = SystemSettings.projectContext + returnUrl; this.isReturnUrlFirstSet = true; } public String getJson() { if (json == null || json.isEmpty()) { return new RapError().toString(); } return json; } public void setJson(String json) { this.json = json; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.isLoginCtlHidden = true; this.errMsg = errMsg; this.isOk = false; } public void plsLogin() { setErrMsg(LOGIN_HINT_MSG); } }
thx/RAP
src/main/java/com/taobao/rigel/rap/common/base/ActionBase.java
181
/** * File: binary_tree.java * Created Time: 2022-11-25 * Author: krahets ([email protected]) */ package chapter_tree; import utils.*; public class binary_tree { public static void main(String[] args) { /* 初始化二叉树 */ // 初始化节点 TreeNode n1 = new TreeNode(1); TreeNode n2 = new TreeNode(2); TreeNode n3 = new TreeNode(3); TreeNode n4 = new TreeNode(4); TreeNode n5 = new TreeNode(5); // 构建节点之间的引用(指针) n1.left = n2; n1.right = n3; n2.left = n4; n2.right = n5; System.out.println("\n初始化二叉树\n"); PrintUtil.printTree(n1); /* 插入与删除节点 */ TreeNode P = new TreeNode(0); // 在 n1 -> n2 中间插入节点 P n1.left = P; P.left = n2; System.out.println("\n插入节点 P 后\n"); PrintUtil.printTree(n1); // 删除节点 P n1.left = n2; System.out.println("\n删除节点 P 后\n"); PrintUtil.printTree(n1); } }
krahets/hello-algo
codes/java/chapter_tree/binary_tree.java
182
package com.crossoverjie.red; import java.util.LinkedList; import java.util.List; /** * Function: 模拟微信红包生成,以分为单位 * * @author crossoverJie * Date: 03/01/2018 16:52 * @since JDK 1.8 */ public class RedPacket { /** * 生成红包最小值 1分 */ private static final int MIN_MONEY = 1; /** * 生成红包最大值 200人民币 */ private static final int MAX_MONEY = 200 * 100; /** * 小于最小值 */ private static final int LESS = -1; /** * 大于最大值 */ private static final int MORE = -2; /** * 正常值 */ private static final int OK = 1; /** * 最大的红包是平均值的 TIMES 倍,防止某一次分配红包较大 */ private static final double TIMES = 2.1F; private int recursiveCount = 0; public List<Integer> splitRedPacket(int money, int count) { List<Integer> moneys = new LinkedList<>(); //金额检查,如果最大红包 * 个数 < 总金额;则需要调大最小红包 MAX_MONEY if (MAX_MONEY * count <= money) { System.err.println("请调大最小红包金额 MAX_MONEY=[" + MAX_MONEY + "]"); return moneys ; } //计算出最大红包 int max = (int) ((money / count) * TIMES); max = max > MAX_MONEY ? MAX_MONEY : max; for (int i = 0; i < count; i++) { //随机获取红包 int redPacket = randomRedPacket(money, MIN_MONEY, max, count - i); moneys.add(redPacket); //总金额每次减少 money -= redPacket; } return moneys; } private int randomRedPacket(int totalMoney, int minMoney, int maxMoney, int count) { //只有一个红包直接返回 if (count == 1) { return totalMoney; } if (minMoney == maxMoney) { return minMoney; } //如果最大金额大于了剩余金额 则用剩余金额 因为这个 money 每分配一次都会减小 maxMoney = maxMoney > totalMoney ? totalMoney : maxMoney; //在 minMoney到maxMoney 生成一个随机红包 int redPacket = (int) (Math.random() * (maxMoney - minMoney) + minMoney); int lastMoney = totalMoney - redPacket; int status = checkMoney(lastMoney, count - 1); //正常金额 if (OK == status) { return redPacket; } //如果生成的金额不合法 则递归重新生成 if (LESS == status) { recursiveCount++; System.out.println("recursiveCount==" + recursiveCount); return randomRedPacket(totalMoney, minMoney, redPacket, count); } if (MORE == status) { recursiveCount++; System.out.println("recursiveCount===" + recursiveCount); return randomRedPacket(totalMoney, redPacket, maxMoney, count); } return redPacket; } /** * 校验剩余的金额的平均值是否在 最小值和最大值这个范围内 * * @param lastMoney * @param count * @return */ private int checkMoney(int lastMoney, int count) { double avg = lastMoney / count; if (avg < MIN_MONEY) { return LESS; } if (avg > MAX_MONEY) { return MORE; } return OK; } public static void main(String[] args) { RedPacket redPacket = new RedPacket(); List<Integer> redPackets = redPacket.splitRedPacket(20000, 100); System.out.println(redPackets); int sum = 0; for (Integer red : redPackets) { sum += red; } System.out.println(sum); } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/red/RedPacket.java
183
public class GenericArray<T> { private T[] data; private int size; // 根据传入容量,构造Array public GenericArray(int capacity) { data = (T[]) new Object[capacity]; size = 0; } // 无参构造方法,默认数组容量为10 public GenericArray() { this(10); } // 获取数组容量 public int getCapacity() { return data.length; } // 获取当前元素个数 public int count() { return size; } // 判断数组是否为空 public boolean isEmpty() { return size == 0; } // 修改 index 位置的元素 public void set(int index, T e) { checkIndex(index); data[index] = e; } // 获取对应 index 位置的元素 public T get(int index) { checkIndex(index); return data[index]; } // 查看数组是否包含元素e public boolean contains(T e) { for (int i = 0; i < size; i++) { if (data[i].equals(e)) { return true; } } return false; } // 获取对应元素的下标, 未找到,返回 -1 public int find(T e) { for ( int i = 0; i < size; i++) { if (data[i].equals(e)) { return i; } } return -1; } // 在 index 位置,插入元素e, 时间复杂度 O(m+n) public void add(int index, T e) { checkIndexForAdd(index); // 如果当前元素个数等于数组容量,则将数组扩容为原来的2倍 if (size == data.length) { resize(2 * data.length); } for (int i = size - 1; i >= index; i--) { data[i + 1] = data[i]; } data[index] = e; size++; } // 向数组头插入元素 public void addFirst(T e) { add(0, e); } // 向数组尾插入元素 public void addLast(T e) { add(size, e); } // 删除 index 位置的元素,并返回 public T remove(int index) { checkIndex(index); T ret = data[index]; for (int i = index + 1; i < size; i++) { data[i - 1] = data[i]; } size --; data[size] = null; // 缩容 if (size == data.length / 4 && data.length / 2 != 0) { resize(data.length / 2); } return ret; } // 删除第一个元素 public T removeFirst() { return remove(0); } // 删除末尾元素 public T removeLast() { return remove(size - 1); } // 从数组中删除指定元素 public void removeElement(T e) { int index = find(e); if (index != -1) { remove(index); } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(String.format("Array size = %d, capacity = %d \n", size, data.length)); builder.append('['); for (int i = 0; i < size; i++) { builder.append(data[i]); if (i != size - 1) { builder.append(", "); } } builder.append(']'); return builder.toString(); } // 扩容方法,时间复杂度 O(n) private void resize(int capacity) { T[] newData = (T[]) new Object[capacity]; for (int i = 0; i < size; i++) { newData[i] = data[i]; } data = newData; } private void checkIndex(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Add failed! Require index >=0 and index < size."); } } private void checkIndexForAdd(int index) { if(index < 0 || index > size) { throw new IllegalArgumentException("remove failed! Require index >=0 and index <= size."); } } }
wangzheng0822/algo
java/05_array/GenericArray.java
184
package cn.hutool.http; import cn.hutool.core.convert.Convert; import cn.hutool.core.io.FastByteArrayOutputStream; import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.StreamProgress; import cn.hutool.core.io.resource.BytesResource; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ObjUtil; import cn.hutool.core.util.ReUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; import cn.hutool.http.cookie.GlobalCookieManager; import java.io.Closeable; import java.io.EOFException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpCookie; import java.nio.charset.Charset; import java.util.List; import java.util.Map.Entry; /** * Http响应类<br> * 非线程安全对象 * * @author Looly */ public class HttpResponse extends HttpBase<HttpResponse> implements Closeable { /** * Http配置 */ protected HttpConfig config; /** * 持有连接对象 */ protected HttpConnection httpConnection; /** * Http请求原始流 */ protected InputStream in; /** * 是否异步,异步下只持有流,否则将在初始化时直接读取body内容 */ private volatile boolean isAsync; /** * 响应状态码 */ protected int status; /** * 是否忽略读取Http响应体 */ private final boolean ignoreBody; /** * 从响应中获取的编码 */ private Charset charsetFromResponse; /** * 构造 * * @param httpConnection {@link HttpConnection} * @param config Http配置 * @param charset 编码,从请求编码中获取默认编码 * @param isAsync 是否异步 * @param isIgnoreBody 是否忽略读取响应体 * @since 3.1.2 */ protected HttpResponse(HttpConnection httpConnection, HttpConfig config, Charset charset, boolean isAsync, boolean isIgnoreBody) { this.httpConnection = httpConnection; this.config = config; this.charset = charset; this.isAsync = isAsync; this.ignoreBody = isIgnoreBody; initWithDisconnect(); } /** * 获取状态码 * * @return 状态码 */ public int getStatus() { return this.status; } /** * 请求是否成功,判断依据为:状态码范围在200~299内。 * * @return 是否成功请求 * @since 4.1.9 */ public boolean isOk() { return this.status >= 200 && this.status < 300; } /** * 同步<br> * 如果为异步状态,则暂时不读取服务器中响应的内容,而是持有Http链接的{@link InputStream}。<br> * 当调用此方法时,异步状态转为同步状态,此时从Http链接流中读取body内容并暂存在内容中。如果已经是同步状态,则不进行任何操作。 * * @return this */ public HttpResponse sync() { return this.isAsync ? forceSync() : this; } // ---------------------------------------------------------------- Http Response Header start /** * 获取内容编码 * * @return String */ public String contentEncoding() { return header(Header.CONTENT_ENCODING); } /** * 获取内容长度,以下情况长度无效: * <ul> * <li>Transfer-Encoding: Chunked</li> * <li>Content-Encoding: XXX</li> * </ul> * 参考:https://blog.csdn.net/jiang7701037/article/details/86304302 * * @return 长度,-1表示服务端未返回或长度无效 * @since 5.7.9 */ public long contentLength() { long contentLength = Convert.toLong(header(Header.CONTENT_LENGTH), -1L); if (contentLength > 0 && (isChunked() || StrUtil.isNotBlank(contentEncoding()))) { //按照HTTP协议规范,在 Transfer-Encoding和Content-Encoding设置后 Content-Length 无效。 contentLength = -1; } return contentLength; } /** * 是否为gzip压缩过的内容 * * @return 是否为gzip压缩过的内容 */ public boolean isGzip() { final String contentEncoding = contentEncoding(); return "gzip".equalsIgnoreCase(contentEncoding); } /** * 是否为zlib(Deflate)压缩过的内容 * * @return 是否为zlib(Deflate)压缩过的内容 * @since 4.5.7 */ public boolean isDeflate() { final String contentEncoding = contentEncoding(); return "deflate".equalsIgnoreCase(contentEncoding); } /** * 是否为Transfer-Encoding:Chunked的内容 * * @return 是否为Transfer-Encoding:Chunked的内容 * @since 4.6.2 */ public boolean isChunked() { final String transferEncoding = header(Header.TRANSFER_ENCODING); return "Chunked".equalsIgnoreCase(transferEncoding); } /** * 获取本次请求服务器返回的Cookie信息 * * @return Cookie字符串 * @since 3.1.1 */ public String getCookieStr() { return header(Header.SET_COOKIE); } /** * 获取Cookie * * @return Cookie列表 * @since 3.1.1 */ public List<HttpCookie> getCookies() { return GlobalCookieManager.getCookies(this.httpConnection); } /** * 获取Cookie * * @param name Cookie名 * @return {@link HttpCookie} * @since 4.1.4 */ public HttpCookie getCookie(String name) { List<HttpCookie> cookie = getCookies(); if (null != cookie) { for (HttpCookie httpCookie : cookie) { if (httpCookie.getName().equals(name)) { return httpCookie; } } } return null; } /** * 获取Cookie值 * * @param name Cookie名 * @return Cookie值 * @since 4.1.4 */ public String getCookieValue(String name) { final HttpCookie cookie = getCookie(name); return (null == cookie) ? null : cookie.getValue(); } // ---------------------------------------------------------------- Http Response Header end // ---------------------------------------------------------------- Body start /** * 获得服务区响应流<br> * 异步模式下获取Http原生流,同步模式下获取获取到的在内存中的副本<br> * 如果想在同步模式下获取流,请先调用{@link #sync()}方法强制同步<br> * 流获取后处理完毕需关闭此类 * * @return 响应流 */ public InputStream bodyStream() { if (isAsync) { return this.in; } return null == this.body ? null : this.body.getStream(); } /** * 获取响应流字节码<br> * 此方法会转为同步模式 * * @return byte[] */ @Override public byte[] bodyBytes() { sync(); return super.bodyBytes(); } /** * 设置主体字节码<br> * 需在此方法调用前使用charset方法设置编码,否则使用默认编码UTF-8 * * @param bodyBytes 主体 * @return this */ public HttpResponse body(byte[] bodyBytes) { sync(); if (null != bodyBytes) { this.body = new BytesResource(bodyBytes); } return this; } /** * 获取响应主体 * * @return String * @throws HttpException 包装IO异常 */ public String body() throws HttpException { return HttpUtil.getString(bodyBytes(), this.charset, null == this.charsetFromResponse); } /** * 将响应内容写出到{@link OutputStream}<br> * 异步模式下直接读取Http流写出,同步模式下将存储在内存中的响应内容写出<br> * 写出后会关闭Http流(异步模式) * * @param out 写出的流 * @param isCloseOut 是否关闭输出流 * @param streamProgress 进度显示接口,通过实现此接口显示下载进度 * @return 写出bytes数 * @since 3.3.2 */ public long writeBody(OutputStream out, boolean isCloseOut, StreamProgress streamProgress) { Assert.notNull(out, "[out] must be not null!"); final long contentLength = contentLength(); try { return copyBody(bodyStream(), out, contentLength, streamProgress, this.config.ignoreEOFError); } finally { IoUtil.close(this); if (isCloseOut) { IoUtil.close(out); } } } /** * 将响应内容写出到文件<br> * 异步模式下直接读取Http流写出,同步模式下将存储在内存中的响应内容写出<br> * 写出后会关闭Http流(异步模式) * * @param targetFileOrDir 写出到的文件或目录 * @param streamProgress 进度显示接口,通过实现此接口显示下载进度 * @return 写出bytes数 * @since 3.3.2 */ public long writeBody(File targetFileOrDir, StreamProgress streamProgress) { Assert.notNull(targetFileOrDir, "[targetFileOrDir] must be not null!"); final File outFile = completeFileNameFromHeader(targetFileOrDir); return writeBody(FileUtil.getOutputStream(outFile), true, streamProgress); } /** * 将响应内容写出到文件-避免未完成的文件<br> * 异步模式下直接读取Http流写出,同步模式下将存储在内存中的响应内容写出<br> * 写出后会关闭Http流(异步模式)<br> * 来自:https://gitee.com/dromara/hutool/pulls/407<br> * 此方法原理是先在目标文件同级目录下创建临时文件,下载之,等下载完毕后重命名,避免因下载错误导致的文件不完整。 * * @param targetFileOrDir 写出到的文件或目录 * @param tempFileSuffix 临时文件后缀,默认".temp" * @param streamProgress 进度显示接口,通过实现此接口显示下载进度 * @return 写出bytes数 * @since 5.7.12 */ public long writeBody(File targetFileOrDir, String tempFileSuffix, StreamProgress streamProgress) { Assert.notNull(targetFileOrDir, "[targetFileOrDir] must be not null!"); File outFile = completeFileNameFromHeader(targetFileOrDir); if (StrUtil.isBlank(tempFileSuffix)) { tempFileSuffix = ".temp"; } else { tempFileSuffix = StrUtil.addPrefixIfNot(tempFileSuffix, StrUtil.DOT); } // 目标文件真实名称 final String fileName = outFile.getName(); // 临时文件名称 final String tempFileName = fileName + tempFileSuffix; // 临时文件 outFile = new File(outFile.getParentFile(), tempFileName); long length; try { length = writeBody(outFile, streamProgress); // 重命名下载好的临时文件 FileUtil.rename(outFile, fileName, true); } catch (Throwable e) { // 异常则删除临时文件 FileUtil.del(outFile); throw new HttpException(e); } return length; } /** * 将响应内容写出到文件<br> * 异步模式下直接读取Http流写出,同步模式下将存储在内存中的响应内容写出<br> * 写出后会关闭Http流(异步模式) * * @param targetFileOrDir 写出到的文件 * @param streamProgress 进度显示接口,通过实现此接口显示下载进度 * @return 写出的文件 * @since 5.6.4 */ public File writeBodyForFile(File targetFileOrDir, StreamProgress streamProgress) { Assert.notNull(targetFileOrDir, "[targetFileOrDir] must be not null!"); final File outFile = completeFileNameFromHeader(targetFileOrDir); writeBody(FileUtil.getOutputStream(outFile), true, streamProgress); return outFile; } /** * 将响应内容写出到文件<br> * 异步模式下直接读取Http流写出,同步模式下将存储在内存中的响应内容写出<br> * 写出后会关闭Http流(异步模式) * * @param targetFileOrDir 写出到的文件或目录 * @return 写出bytes数 * @since 3.3.2 */ public long writeBody(File targetFileOrDir) { return writeBody(targetFileOrDir, null); } /** * 将响应内容写出到文件<br> * 异步模式下直接读取Http流写出,同步模式下将存储在内存中的响应内容写出<br> * 写出后会关闭Http流(异步模式) * * @param targetFileOrDir 写出到的文件或目录的路径 * @return 写出bytes数 * @since 3.3.2 */ public long writeBody(String targetFileOrDir) { return writeBody(FileUtil.file(targetFileOrDir)); } // ---------------------------------------------------------------- Body end @Override public void close() { IoUtil.close(this.in); this.in = null; // 关闭连接 this.httpConnection.disconnectQuietly(); } @Override public String toString() { StringBuilder sb = StrUtil.builder(); sb.append("Response Headers: ").append(StrUtil.CRLF); for (Entry<String, List<String>> entry : this.headers.entrySet()) { sb.append(" ").append(entry).append(StrUtil.CRLF); } sb.append("Response Body: ").append(StrUtil.CRLF); sb.append(" ").append(this.body()).append(StrUtil.CRLF); return sb.toString(); } /** * 从响应头补全下载文件名 * * @param targetFileOrDir 目标文件夹或者目标文件 * @return File 保存的文件 * @since 5.4.1 */ public File completeFileNameFromHeader(File targetFileOrDir) { if (false == targetFileOrDir.isDirectory()) { // 非目录直接返回 return targetFileOrDir; } // 从头信息中获取文件名 String fileName = getFileNameFromDisposition(null); if (StrUtil.isBlank(fileName)) { final String path = httpConnection.getUrl().getPath(); // 从路径中获取文件名 fileName = StrUtil.subSuf(path, path.lastIndexOf('/') + 1); if (StrUtil.isBlank(fileName)) { // 编码后的路径做为文件名 fileName = URLUtil.encodeQuery(path, charset); } else { // issue#I4K0FS@Gitee fileName = URLUtil.decode(fileName, charset); } } return FileUtil.file(targetFileOrDir, fileName); } /** * 从Content-Disposition头中获取文件名 * @param paramName 文件参数名 * * @return 文件名,empty表示无 */ public String getFileNameFromDisposition(String paramName) { paramName = ObjUtil.defaultIfNull(paramName, "filename"); String fileName = null; final String disposition = header(Header.CONTENT_DISPOSITION); if (StrUtil.isNotBlank(disposition)) { fileName = ReUtil.get(paramName+"=\"(.*?)\"", disposition, 1); if (StrUtil.isBlank(fileName)) { fileName = StrUtil.subAfter(disposition, paramName + "=", true); } } return fileName; } // ---------------------------------------------------------------- Private method start /** * 初始化Http响应,并在报错时关闭连接。<br> * 初始化包括: * * <pre> * 1、读取Http状态 * 2、读取头信息 * 3、持有Http流,并不关闭流 * </pre> * * @return this * @throws HttpException IO异常 */ private HttpResponse initWithDisconnect() throws HttpException { try { init(); } catch (HttpException e) { this.httpConnection.disconnectQuietly(); throw e; } return this; } /** * 初始化Http响应<br> * 初始化包括: * * <pre> * 1、读取Http状态 * 2、读取头信息 * 3、持有Http流,并不关闭流 * </pre> * * @return this * @throws HttpException IO异常 */ private HttpResponse init() throws HttpException { // 获取响应状态码 try { this.status = httpConnection.responseCode(); } catch (IOException e) { if (false == (e instanceof FileNotFoundException)) { throw new HttpException(e); } // 服务器无返回内容,忽略之 } // 读取响应头信息 try { this.headers = httpConnection.headers(); } catch (IllegalArgumentException e) { // ignore // StaticLog.warn(e, e.getMessage()); } // 存储服务端设置的Cookie信息 GlobalCookieManager.store(httpConnection); // 获取响应编码 final Charset charset = httpConnection.getCharset(); this.charsetFromResponse = charset; if (null != charset) { this.charset = charset; } // 获取响应内容流 this.in = new HttpInputStream(this); // 同步情况下强制同步 return this.isAsync ? this : forceSync(); } /** * 强制同步,用于初始化<br> * 强制同步后变化如下: * * <pre> * 1、读取body内容到内存 * 2、异步状态设为false(变为同步状态) * 3、关闭Http流 * 4、断开与服务器连接 * </pre> * * @return this */ private HttpResponse forceSync() { // 非同步状态转为同步状态 try { this.readBody(this.in); } catch (IORuntimeException e) { //noinspection StatementWithEmptyBody if (e.getCause() instanceof FileNotFoundException) { // 服务器无返回内容,忽略之 } else { throw new HttpException(e); } } finally { if (this.isAsync) { this.isAsync = false; } this.close(); } return this; } /** * 读取主体,忽略EOFException异常 * * @param in 输入流 * @throws IORuntimeException IO异常 */ private void readBody(InputStream in) throws IORuntimeException { if (ignoreBody) { return; } final long contentLength = contentLength(); final FastByteArrayOutputStream out = new FastByteArrayOutputStream((int) contentLength); copyBody(in, out, contentLength, null, this.config.ignoreEOFError); this.body = new BytesResource(out.toByteArray()); } /** * 将响应内容写出到{@link OutputStream}<br> * 异步模式下直接读取Http流写出,同步模式下将存储在内存中的响应内容写出<br> * 写出后会关闭Http流(异步模式) * * @param in 输入流 * @param out 写出的流 * @param contentLength 总长度,-1表示未知 * @param streamProgress 进度显示接口,通过实现此接口显示下载进度 * @param isIgnoreEOFError 是否忽略响应读取时可能的EOF异常 * @return 拷贝长度 */ private static long copyBody(InputStream in, OutputStream out, long contentLength, StreamProgress streamProgress, boolean isIgnoreEOFError) { if (null == out) { throw new NullPointerException("[out] is null!"); } long copyLength = -1; try { copyLength = IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE, contentLength, streamProgress); } catch (IORuntimeException e) { //noinspection StatementWithEmptyBody if (isIgnoreEOFError && (e.getCause() instanceof EOFException || StrUtil.containsIgnoreCase(e.getMessage(), "Premature EOF"))) { // 忽略读取HTTP流中的EOF错误 } else { throw e; } } return copyLength; } // ---------------------------------------------------------------- Private method end }
dromara/hutool
hutool-http/src/main/java/cn/hutool/http/HttpResponse.java
185
H 1520728398 tags: Backtracking, Trie 可以开Trie class, 里面用到TrieNode. 开Trie(words) 可以直接initalize with for loop TrieNode 里面可以有一个 List<String> startWith: 记录可以到达这个点的所有string: 有点像树形, ancestor形状的存储. 神操作: 根据square的性质, 如果选中了list of words, 设定 int prefixIndex = list.size(). 取出list里面的所有word[prefixedIndex], 并且加在一起, 就是下一个word candidate的 prefix. 形象一点: list = ["ball", "area"]; prefixIndex = list.size(); ball[prefixIndex] = 'l'; area[prefixIndex] = 'e'; //then candidatePrefix = ball[prefixIndex] + area[prefixIndex] = "le"; 这里就可以用到Trie的那个 findByPrefix function, 在每个点, 都存有所有这个点能产生的candidate. 这时, 试一试所有candidate: dfs 能想到这种倒转的结构来存prefix candidates 在 Trie里面, 这个想法非常值得思考. ``` /* Given a set of words (without duplicates), find all word squares you can build from them. A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns). For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically. b a l l a r e a l e a d l a d y Note: There are at least 1 and at most 1000 words. All words will have the exact same length. Word length is at least 1 and at most 5. Each word contains only lowercase English alphabet a-z. Example 1: Input: ["area","lead","wall","lady","ball"] Output: [ [ "wall", "area", "lead", "lady" ], [ "ball", "area", "lead", "lady" ] ] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). Example 2: Input: ["abat","baba","atan","atal"] Output: [ [ "baba", "abat", "baba", "atan" ], [ "baba", "abat", "baba", "atal" ] ] Explanation: The output consists of two word squares. The order of output does not matter (just the order of words in each word square matters). */ /* Thoughts: Characteristic: 1. When 1st row/word is picked, the 2nd position in the string will be the next wordCandidate's prefix. 2. When 2 words are picked, the 3rd postion of both strings will add together as next wordCandidate's prefix Build Trie that stores all possible candidates at current node. This time, put trie creation logic in Trie itself, since we are building the structure with input DFS: 1. Pick list of candidates 2. Based on size of the list, find the prefix, and find all futurer candidates. 3. add each candidate (backtracking), and DFS */ class Solution { // Define TrieNode class TrieNode { TrieNode [] children = new TrieNode[26]; List<String> startWith = new ArrayList<>(); } // Define Trie class Trie { TrieNode root = new TrieNode(); // Build the trie and add list of startWith/candidates on node. public Trie(String[] words) { for (String word: words) { TrieNode node = root; for (char c: word.toCharArray()) { int index = c - 'a'; if (node.children[index] == null) { node.children[index] = new TrieNode(); } node.children[index].startWith.add(word); node = node.children[index]; } } } // Get list of candidates for given prefix public List<String> findByPrefix(String prefix) { List<String> candidates = new ArrayList<>(); if (prefix == null || prefix.length() == 0) { return candidates; } TrieNode node = root; for (char c : prefix.toCharArray()) { int index = c - 'a'; if (node.children[index] == null) { return candidates; } node = node.children[index]; } candidates.addAll(node.startWith); return node.startWith; } } public Trie trie; public int length; public List<List<String>> wordSquares(String[] words) { List<List<String>> rst = new ArrayList<>(); if (words == null || words.length == 0) { return rst; } length = words[0].length(); trie = new Trie(words); for (String word: words) { List<String> selected = new ArrayList<>(); selected.add(word); dfs(rst, selected); } return rst; } // Find the word private void dfs(List<List<String>> rst, List<String> selected) { if (selected.size() == length) { rst.add(new ArrayList<>(selected)); return; } int prefixIndex = selected.size(); StringBuffer sb = new StringBuffer(); for (String word: selected) { sb.append(word.charAt(prefixIndex)); } List<String> newCandidates = trie.findByPrefix(sb.toString()); for (String candidate: newCandidates) { selected.add(candidate); dfs(rst, selected); //Backtracking selected.remove(selected.size() - 1); } } } ```
awangdev/leet-code
Java/Word Squares.java
186
package com.blankj.utildebug.base.view; import android.content.Context; import android.util.AttributeSet; import com.blankj.utilcode.util.KeyboardUtils; import com.blankj.utilcode.util.StringUtils; /** * <pre> * author: blankj * blog : http://blankj.com * time : 2019/09/06 * desc : * </pre> */ public class SearchEditText extends FloatEditText { private static final long LIMIT = 200; private OnTextChangedListener mListener; private String mStartSearchText = "";// 记录开始输入前的文本内容 private Runnable mAction = new Runnable() { @Override public void run() { if (mListener != null) { // 判断最终和开始前是否一致 if (!StringUtils.equals(mStartSearchText, getText().toString())) { mStartSearchText = getText().toString();// 更新 mStartSearchText mListener.onTextChanged(mStartSearchText); } } } }; public SearchEditText(Context context) { this(context, null); } public SearchEditText(Context context, AttributeSet attrs) { super(context, attrs); } /** * 在 LIMIT 时间内连续输入不触发文本变化 */ public void setOnTextChangedListener(OnTextChangedListener listener) { mListener = listener; } public void reset() { mStartSearchText = ""; setText(""); KeyboardUtils.hideSoftInput(this); } @Override protected void onTextChanged(final CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); // 移除上一次的回调 removeCallbacks(mAction); postDelayed(mAction, LIMIT); } @Override protected void onDetachedFromWindow() { removeCallbacks(mAction); KeyboardUtils.hideSoftInput(this); super.onDetachedFromWindow(); } public interface OnTextChangedListener { void onTextChanged(String text); } }
Blankj/AndroidUtilCode
lib/utildebug/src/main/java/com/blankj/utildebug/base/view/SearchEditText.java
187
package me.zhyd.oauth.config; import me.zhyd.oauth.enums.AuthResponseStatus; import me.zhyd.oauth.exception.AuthException; import me.zhyd.oauth.model.AuthCallback; import me.zhyd.oauth.request.AuthDefaultRequest; /** * OAuth平台的API地址的统一接口,提供以下方法: * 1) {@link AuthSource#authorize()}: 获取授权url. 必须实现 * 2) {@link AuthSource#accessToken()}: 获取accessToken的url. 必须实现 * 3) {@link AuthSource#userInfo()}: 获取用户信息的url. 必须实现 * 4) {@link AuthSource#revoke()}: 获取取消授权的url. 非必须实现接口(部分平台不支持) * 5) {@link AuthSource#refresh()}: 获取刷新授权的url. 非必须实现接口(部分平台不支持) * <p> * 注: * ①、如需通过JustAuth扩展实现第三方授权,请参考{@link AuthDefaultSource}自行创建对应的枚举类并实现{@link AuthSource}接口 * ②、如果不是使用的枚举类,那么在授权成功后获取用户信息时,需要单独处理source字段的赋值 * ③、如果扩展了对应枚举类时,在{@link me.zhyd.oauth.request.AuthRequest#login(AuthCallback)}中可以通过{@code xx.toString()}获取对应的source * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @version 1.0 * @since 1.12.0 */ public interface AuthSource { /** * 授权的api * * @return url */ String authorize(); /** * 获取accessToken的api * * @return url */ String accessToken(); /** * 获取用户信息的api * * @return url */ String userInfo(); /** * 取消授权的api * * @return url */ default String revoke() { throw new AuthException(AuthResponseStatus.UNSUPPORTED); } /** * 刷新授权的api * * @return url */ default String refresh() { throw new AuthException(AuthResponseStatus.UNSUPPORTED); } /** * 获取Source的字符串名字 * * @return name */ default String getName() { if (this instanceof Enum) { return String.valueOf(this); } return this.getClass().getSimpleName(); } /** * 平台对应的 AuthRequest 实现类,必须继承自 {@link AuthDefaultRequest} * * @return class */ Class<? extends AuthDefaultRequest> getTargetClass(); }
justauth/JustAuth
src/main/java/me/zhyd/oauth/config/AuthSource.java
188
package com.xkcoding.rbac.security.common; /** * <p> * 常量池 * </p> * * @author yangkai.shen * @date Created in 2018-12-10 15:03 */ public interface Consts { /** * 启用 */ Integer ENABLE = 1; /** * 禁用 */ Integer DISABLE = 0; /** * 页面 */ Integer PAGE = 1; /** * 按钮 */ Integer BUTTON = 2; /** * JWT 在 Redis 中保存的key前缀 */ String REDIS_JWT_KEY_PREFIX = "security:jwt:"; /** * 星号 */ String SYMBOL_STAR = "*"; /** * 邮箱符号 */ String SYMBOL_EMAIL = "@"; /** * 默认当前页码 */ Integer DEFAULT_CURRENT_PAGE = 1; /** * 默认每页条数 */ Integer DEFAULT_PAGE_SIZE = 10; /** * 匿名用户 用户名 */ String ANONYMOUS_NAME = "匿名用户"; }
xkcoding/spring-boot-demo
demo-rbac-security/src/main/java/com/xkcoding/rbac/security/common/Consts.java
189
/*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.model; import apijson.MethodAccess; /**SQL Server 在 sys 下的字段(列名) * @author Lemon */ @MethodAccess(POST = {}, PUT = {}, DELETE = {}) public class AllColumn { public static final String TAG = "AllColumn"; public static final String TABLE_NAME = "ALL_TAB_COLUMNS"; }
Tencent/APIJSON
APIJSONORM/src/main/java/apijson/orm/model/AllColumn.java
190
package org.nutz.dao; import org.nutz.castor.Castors; import org.nutz.dao.impl.sql.NutSql; import org.nutz.dao.impl.sql.ValueEscaper; import org.nutz.dao.impl.sql.callback.FetchBlobCallback; import org.nutz.dao.impl.sql.callback.FetchBooleanCallback; import org.nutz.dao.impl.sql.callback.FetchDoubleCallback; import org.nutz.dao.impl.sql.callback.FetchEntityCallback; import org.nutz.dao.impl.sql.callback.FetchFloatCallback; import org.nutz.dao.impl.sql.callback.FetchIntegerCallback; import org.nutz.dao.impl.sql.callback.FetchLongCallback; import org.nutz.dao.impl.sql.callback.FetchMapCallback; import org.nutz.dao.impl.sql.callback.FetchRecordCallback; import org.nutz.dao.impl.sql.callback.FetchStringCallback; import org.nutz.dao.impl.sql.callback.FetchTimestampCallback; import org.nutz.dao.impl.sql.callback.QueryBooleanCallback; import org.nutz.dao.impl.sql.callback.QueryEntityCallback; import org.nutz.dao.impl.sql.callback.QueryIntCallback; import org.nutz.dao.impl.sql.callback.QueryLongCallback; import org.nutz.dao.impl.sql.callback.QueryMapCallback; import org.nutz.dao.impl.sql.callback.QueryRecordCallback; import org.nutz.dao.impl.sql.callback.QueryStringArrayCallback; import org.nutz.dao.impl.sql.callback.QueryStringCallback; import org.nutz.dao.sql.Sql; import org.nutz.dao.sql.SqlCallback; import org.nutz.lang.Mirror; import org.nutz.lang.born.Borning; /** * 提供了 Sql 相关的帮助函数 * * @author zozoh([email protected]) */ public abstract class Sqls { private static final ValueEscaper ES_FLD_VAL = new ValueEscaper(); private static final ValueEscaper ES_SQL_FLD = new ValueEscaper(); private static final ValueEscaper ES_CND_VAL = new ValueEscaper(); private static Borning<? extends Sql> sqlBorning; static { ES_FLD_VAL.add('\'', "''").add('\\', "\\\\").ready(); ES_SQL_FLD.add('\'', "''").add('\\', "\\\\").add('$', "$$").add('@', "@@").ready(); ES_CND_VAL.add('\'', "''").add('\\', "\\\\").add('_', "\\_").add('%', "\\%").ready(); setSqlBorning(NutSql.class); } /** * 改变 Sql 接口的实现类,如果你调用了这个方法,以后你再调用本类其他帮助函数创建的 SQL 就是你提供的这个实现类 * <p> * 默认的,将用 org.nutz.dao.sql.impl.sql.NutSql 作为实现类 * <p> * 你给出的 Sql 实现类必须有一个可访问的构造函数,接受一个字符串型参数 * * @param type * 你的 Sql 接口实现类 */ public static <T extends Sql> void setSqlBorning(Class<T> type) { sqlBorning = Mirror.me(type).getBorningByArgTypes(String.class); } /** * 创建了一个 Sql 对象。 * <p> * 传入的 Sql 语句支持变量和参数占位符: * <ul> * <li>变量: 格式为 <b>$XXXX</b>,在执行前,会被预先替换 * <li>参数: 格式为<b>@XXXX</b>,在执行前,会替换为 '?',用以构建 PreparedStatement * </ul> * * @param sql * Sql 语句 * @return Sql 对象 * * @see org.nutz.dao.sql.Sql */ public static Sql create(String sql) { return sqlBorning.born(sql); } /** * 创建了一个 Sql 对象。 * <p> * 传入的 Sql 语句支持变量和参数占位符: * <ul> * <li>变量: 格式为 <b>$XXXX</b>,在执行前,会被预先替换 * <li>参数: 格式为<b>@XXXX</b>,在执行前,会替换为 '?',用以构建 PreparedStatement * </ul> * * @param fmt * 格式字符,格式参看 String.format 函数 * @param args * 格式字符串的参数 * @return Sql 对象 */ public static Sql createf(String fmt, Object... args) { return create(String.format(fmt, args)); } /** * 创建一个获取单个实体对象的 Sql。 * <p> * 这个函数除了执行 create(String)外,还会为这个 Sql 语句设置回调,用来获取实体对象。 * <p> * <b style=color:red>注意:</b>返回的 Sql 对象在执行前,一定要通过 setEntity 设置 * 一个有效的实体,否则,会抛出异常。 * * @param sql * Sql 语句 * @return Sql 对象 * * @see org.nutz.dao.sql.Sql * @see org.nutz.dao.entity.Entity */ public static Sql fetchEntity(String sql) { return create(sql).setCallback(callback.entity()); } /** * 创建一个获取单个 Record 对象的 Sql。 * <p> * 这个函数除了执行 create(String)外,还会为这个 Sql 语句设置回调,用来获取实体对象。 * * @param sql * Sql 语句 * @return Sql 对象 * * @see org.nutz.dao.sql.Sql * @see org.nutz.dao.entity.Entity */ public static Sql fetchRecord(String sql) { return create(sql).setCallback(callback.record()); } /** * 创建一个获取整数的 Sql。 * <p> * 这个函数除了执行 create(String)外,还会为这个 Sql 语句设置回调,用来获取整数值。 * <p> * <b style=color:red>注意:</b>你的 Sql 语句返回的 ResultSet 的第一列必须是数字 * * @param sql * Sql 语句 * @return Sql 对象 * * @see org.nutz.dao.sql.Sql */ public static Sql fetchInt(String sql) { return create(sql).setCallback(callback.integer()); } /** * @see #fetchInt(String) */ public static Sql fetchLong(String sql) { return create(sql).setCallback(callback.longValue()); } /** * @see #fetchInt(String) */ public static Sql fetchFloat(String sql) { return create(sql).setCallback(callback.floatValue()); } /** * @see #fetchInt(String) */ public static Sql fetchDouble(String sql) { return create(sql).setCallback(callback.doubleValue()); } /** * @see #fetchInt(String) */ public static Sql fetchTimestamp(String sql) { return create(sql).setCallback(callback.timestamp()); } /** * 创建一个获取字符串的 Sql。 * <p> * 这个函数除了执行 create(String)外,还会为这个 Sql 语句设置回调,用来获取字符串。 * <p> * <b style=color:red>注意:</b>你的 Sql 语句返回的 ResultSet 的第一列必须是字符串 * * @param sql * Sql 语句 * @return Sql 对象 * * @see org.nutz.dao.sql.Sql */ public static Sql fetchString(String sql) { return create(sql).setCallback(callback.str()); } public static Sql queryString(String sql) { return create(sql).setCallback(callback.strs()); } /** * 创建一个获取一组实体对象的 Sql。 * <p> * 这个函数除了执行 create(String)外,还会为这个 Sql 语句设置回调,用来获取一组实体对象。 * <p> * <b style=color:red>注意:</b>返回的 Sql 对象在执行前,一定要通过 setEntity 设置 * 一个有效的实体,否则,会抛出异常。 * * @param sql * Sql 语句 * @return Sql 对象 * * @see org.nutz.dao.sql.Sql * @see org.nutz.dao.entity.Entity */ public static Sql queryEntity(String sql) { return create(sql).setCallback(callback.entities()); } /** * 创建一个获取一组 Record 实体对象的 Sql。 * <p> * 这个函数除了执行 create(String)外,还会为这个 Sql 语句设置回调,用来获取一组实体对象。 * * @param sql * Sql 语句 * @return Sql 对象 */ public static Sql queryRecord(String sql) { return create(sql).setCallback(callback.records()); } /** * 一些内置的回调对象 */ public static CallbackFactory callback = new CallbackFactory(); public static class CallbackFactory { /** * @return 从 ResultSet获取一个对象的回调对象 */ public SqlCallback entity() { return entity(null); } public SqlCallback entity(String prefix) { return new FetchEntityCallback(prefix); } /** * @return 从 ResultSet 获取一个 Record 的回调对象 */ public SqlCallback record() { return new FetchRecordCallback(); } /** * @return 从 ResultSet 获取一个整数的回调对象 */ public SqlCallback integer() { return new FetchIntegerCallback(); } /** * @return 从 ResultSet 获取一个长整型数的回调对象 */ public SqlCallback longValue() { return new FetchLongCallback(); } /** * @return 从 ResultSet 获取一个浮点数的回调对象 */ public SqlCallback floatValue() { return new FetchFloatCallback(); } /** * @return 从 ResultSet 获取一个双精度浮点数的回调对象 */ public SqlCallback doubleValue() { return new FetchDoubleCallback(); } /** * @return 从 ResultSet 获取一个时间戳对象的回调对象 */ public SqlCallback timestamp() { return new FetchTimestampCallback(); } /** * @return 从 ResultSet 获取一个字符串的回调对象 */ public SqlCallback str() { return new FetchStringCallback(); } /** * @return 从 ResultSet 获得一个整数数组的回调对象 */ public SqlCallback ints() { return new QueryIntCallback(); } /** * @return 从 ResultSet 获得一个长整型数组的回调对象 */ public SqlCallback longs() { return new QueryLongCallback(); } /** * @return 从 ResultSet 获得一个字符串数组的回调对象 */ public SqlCallback strs() { return new QueryStringArrayCallback(); } /** * @return 从 ResultSet 获得一个字符串列表的回调对象 */ public SqlCallback strList() { return new QueryStringCallback(); } /** * @return 从 ResultSet获取一组对象的回调对象 */ public SqlCallback entities() { return entities(null); } public SqlCallback entities(String prefix) { return new QueryEntityCallback(prefix); } /** * @return 从 ResultSet 获取一组 Record 的回调对象 */ public SqlCallback records() { return new QueryRecordCallback(); } public SqlCallback bool() { return new FetchBooleanCallback(); } public SqlCallback bools() { return new QueryBooleanCallback(); } /** * 与record()类似,但区分大小写 */ public SqlCallback map() { return FetchMapCallback.me; } /** * 与records()类似,但区分大小写 * @return List<Map>回调 */ public SqlCallback maps() { return QueryMapCallback.me; } /** * @return 从 ResultSet 获得一个blob的回调对象 */ public SqlCallback blob() { return new FetchBlobCallback(); } } /** * 格式化值,根据值的类型,生成 SQL 字段值的部分,它会考虑 SQL 注入 * * @param v * 字段值 * @return 格式化后的 Sql 字段值,可以直接拼装在 SQL 里面 */ public static CharSequence formatFieldValue(Object v) { if (null == v) return "NULL"; else if (Sqls.isNotNeedQuote(v.getClass())) return Sqls.escapeFieldValue(v.toString()); else return new StringBuilder("'").append(Sqls.escapeFieldValue(Castors.me().castToString(v))) .append('\''); } /** * 格式化值,根据值的类型,生成 SQL 字段值的部分,它会考虑 SQL 注入,以及 SQL 的 '$' 和 '@' 转义 * * @param v * 字段值 * @return 格式化后的 Sql 字段值,可以直接拼装在 SQL 里面 */ public static CharSequence formatSqlFieldValue(Object v) { if (null == v) return "NULL"; else if (Sqls.isNotNeedQuote(v.getClass())) return Sqls.escapeSqlFieldValue(v.toString()); else return new StringBuilder("'").append(Sqls.escapeSqlFieldValue(v.toString())) .append('\''); } /** * 将 SQL 的字段值进行转意,可以用来防止 SQL 注入攻击 * * @param s * 字段值 * @return 格式化后的 Sql 字段值,可以直接拼装在 SQL 里面 */ public static CharSequence escapeFieldValue(CharSequence s) { if (null == s) return null; return ES_FLD_VAL.escape(s); } /** * 将 SQL 的字段值进行转意,可以用来防止 SQL 注入攻击,<br> * 同时,它也会将 Sql 的特殊标记 '$' 和 '@' 进行转译 * * @param s * 字段值 * @return 格式化后的 Sql 字段值,可以直接拼装在 SQL 里面 */ public static CharSequence escapeSqlFieldValue(CharSequence s) { if (null == s) return null; return ES_SQL_FLD.escape(s); } /** * 将 SQL 的 WHERE 条件值进行转意,可以用来防止 SQL 注入攻击 * * @param s * 字段值 * @return 格式化后的 Sql 字段值,可以直接拼装在 SQL 里面 */ public static CharSequence escapteConditionValue(CharSequence s) { if (null == s) return null; return ES_CND_VAL.escape(s); } /** * 判断一个值,在 SQL 中是否需要单引号 * * @param type * 类型 * @return 是否需要加上单引号 */ public static boolean isNotNeedQuote(Class<?> type) { Mirror<?> me = Mirror.me(type); return me.isBoolean() || me.isPrimitiveNumber(); } }
nutzam/nutz
src/org/nutz/dao/Sqls.java
191
package com.taobao.arthas.common; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * from spring * @version $Id: ReflectUtils.java,v 1.30 2009/01/11 19:47:49 herbyderby Exp $ */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class ReflectUtils { private ReflectUtils() { } private static final Map primitives = new HashMap(8); private static final Map transforms = new HashMap(8); private static final ClassLoader defaultLoader = ReflectUtils.class.getClassLoader(); // SPRING PATCH BEGIN private static final Method privateLookupInMethod; private static final Method lookupDefineClassMethod; private static final Method classLoaderDefineClassMethod; private static final ProtectionDomain PROTECTION_DOMAIN; private static final Throwable THROWABLE; private static final List<Method> OBJECT_METHODS = new ArrayList<Method>(); static { Method privateLookupIn; Method lookupDefineClass; Method classLoaderDefineClass; ProtectionDomain protectionDomain; Throwable throwable = null; try { privateLookupIn = (Method) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { try { return MethodHandles.class.getMethod("privateLookupIn", Class.class, MethodHandles.Lookup.class); } catch (NoSuchMethodException ex) { return null; } } }); lookupDefineClass = (Method) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { try { return MethodHandles.Lookup.class.getMethod("defineClass", byte[].class); } catch (NoSuchMethodException ex) { return null; } } }); classLoaderDefineClass = (Method) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { return ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE, ProtectionDomain.class); } }); protectionDomain = getProtectionDomain(ReflectUtils.class); AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { Method[] methods = Object.class.getDeclaredMethods(); for (Method method : methods) { if ("finalize".equals(method.getName()) || (method.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) > 0) { continue; } OBJECT_METHODS.add(method); } return null; } }); } catch (Throwable t) { privateLookupIn = null; lookupDefineClass = null; classLoaderDefineClass = null; protectionDomain = null; throwable = t; } privateLookupInMethod = privateLookupIn; lookupDefineClassMethod = lookupDefineClass; classLoaderDefineClassMethod = classLoaderDefineClass; PROTECTION_DOMAIN = protectionDomain; THROWABLE = throwable; } // SPRING PATCH END private static final String[] CGLIB_PACKAGES = { "java.lang", }; static { primitives.put("byte", Byte.TYPE); primitives.put("char", Character.TYPE); primitives.put("double", Double.TYPE); primitives.put("float", Float.TYPE); primitives.put("int", Integer.TYPE); primitives.put("long", Long.TYPE); primitives.put("short", Short.TYPE); primitives.put("boolean", Boolean.TYPE); transforms.put("byte", "B"); transforms.put("char", "C"); transforms.put("double", "D"); transforms.put("float", "F"); transforms.put("int", "I"); transforms.put("long", "J"); transforms.put("short", "S"); transforms.put("boolean", "Z"); } public static ProtectionDomain getProtectionDomain(final Class source) { if (source == null) { return null; } return (ProtectionDomain) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return source.getProtectionDomain(); } }); } public static Constructor findConstructor(String desc) { return findConstructor(desc, defaultLoader); } public static Constructor findConstructor(String desc, ClassLoader loader) { try { int lparen = desc.indexOf('('); String className = desc.substring(0, lparen).trim(); return getClass(className, loader).getConstructor(parseTypes(desc, loader)); } catch (ClassNotFoundException ex) { throw new ReflectException(ex); } catch (NoSuchMethodException ex) { throw new ReflectException(ex); } } public static Method findMethod(String desc) { return findMethod(desc, defaultLoader); } public static Method findMethod(String desc, ClassLoader loader) { try { int lparen = desc.indexOf('('); int dot = desc.lastIndexOf('.', lparen); String className = desc.substring(0, dot).trim(); String methodName = desc.substring(dot + 1, lparen).trim(); return getClass(className, loader).getDeclaredMethod(methodName, parseTypes(desc, loader)); } catch (ClassNotFoundException ex) { throw new ReflectException(ex); } catch (NoSuchMethodException ex) { throw new ReflectException(ex); } } private static Class[] parseTypes(String desc, ClassLoader loader) throws ClassNotFoundException { int lparen = desc.indexOf('('); int rparen = desc.indexOf(')', lparen); List params = new ArrayList(); int start = lparen + 1; for (;;) { int comma = desc.indexOf(',', start); if (comma < 0) { break; } params.add(desc.substring(start, comma).trim()); start = comma + 1; } if (start < rparen) { params.add(desc.substring(start, rparen).trim()); } Class[] types = new Class[params.size()]; for (int i = 0; i < types.length; i++) { types[i] = getClass((String) params.get(i), loader); } return types; } private static Class getClass(String className, ClassLoader loader) throws ClassNotFoundException { return getClass(className, loader, CGLIB_PACKAGES); } private static Class getClass(String className, ClassLoader loader, String[] packages) throws ClassNotFoundException { String save = className; int dimensions = 0; int index = 0; while ((index = className.indexOf("[]", index) + 1) > 0) { dimensions++; } StringBuilder brackets = new StringBuilder(className.length() - dimensions); for (int i = 0; i < dimensions; i++) { brackets.append('['); } className = className.substring(0, className.length() - 2 * dimensions); String prefix = (dimensions > 0) ? brackets + "L" : ""; String suffix = (dimensions > 0) ? ";" : ""; try { return Class.forName(prefix + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } for (int i = 0; i < packages.length; i++) { try { return Class.forName(prefix + packages[i] + '.' + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } } if (dimensions == 0) { Class c = (Class) primitives.get(className); if (c != null) { return c; } } else { String transform = (String) transforms.get(className); if (transform != null) { try { return Class.forName(brackets + transform, false, loader); } catch (ClassNotFoundException ignore) { } } } throw new ClassNotFoundException(save); } public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; public static Object newInstance(Class type) { return newInstance(type, EMPTY_CLASS_ARRAY, null); } public static Object newInstance(Class type, Class[] parameterTypes, Object[] args) { return newInstance(getConstructor(type, parameterTypes), args); } public static Object newInstance(final Constructor cstruct, final Object[] args) { boolean flag = cstruct.isAccessible(); try { if (!flag) { cstruct.setAccessible(true); } Object result = cstruct.newInstance(args); return result; } catch (InstantiationException e) { throw new ReflectException(e); } catch (IllegalAccessException e) { throw new ReflectException(e); } catch (InvocationTargetException e) { throw new ReflectException(e.getTargetException()); } finally { if (!flag) { cstruct.setAccessible(flag); } } } public static Constructor getConstructor(Class type, Class[] parameterTypes) { try { Constructor constructor = type.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor; } catch (NoSuchMethodException e) { throw new ReflectException(e); } } public static String[] getNames(Class[] classes) { if (classes == null) return null; String[] names = new String[classes.length]; for (int i = 0; i < names.length; i++) { names[i] = classes[i].getName(); } return names; } public static Class[] getClasses(Object[] objects) { Class[] classes = new Class[objects.length]; for (int i = 0; i < objects.length; i++) { classes[i] = objects[i].getClass(); } return classes; } public static Method findNewInstance(Class iface) { Method m = findInterfaceMethod(iface); if (!m.getName().equals("newInstance")) { throw new IllegalArgumentException(iface + " missing newInstance method"); } return m; } public static Method[] getPropertyMethods(PropertyDescriptor[] properties, boolean read, boolean write) { Set methods = new HashSet(); for (int i = 0; i < properties.length; i++) { PropertyDescriptor pd = properties[i]; if (read) { methods.add(pd.getReadMethod()); } if (write) { methods.add(pd.getWriteMethod()); } } methods.remove(null); return (Method[]) methods.toArray(new Method[methods.size()]); } public static PropertyDescriptor[] getBeanProperties(Class type) { return getPropertiesHelper(type, true, true); } public static PropertyDescriptor[] getBeanGetters(Class type) { return getPropertiesHelper(type, true, false); } public static PropertyDescriptor[] getBeanSetters(Class type) { return getPropertiesHelper(type, false, true); } private static PropertyDescriptor[] getPropertiesHelper(Class type, boolean read, boolean write) { try { BeanInfo info = Introspector.getBeanInfo(type, Object.class); PropertyDescriptor[] all = info.getPropertyDescriptors(); if (read && write) { return all; } List properties = new ArrayList(all.length); for (int i = 0; i < all.length; i++) { PropertyDescriptor pd = all[i]; if ((read && pd.getReadMethod() != null) || (write && pd.getWriteMethod() != null)) { properties.add(pd); } } return (PropertyDescriptor[]) properties.toArray(new PropertyDescriptor[properties.size()]); } catch (IntrospectionException e) { throw new ReflectException(e); } } public static Method findDeclaredMethod(final Class type, final String methodName, final Class[] parameterTypes) throws NoSuchMethodException { Class cl = type; while (cl != null) { try { return cl.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { cl = cl.getSuperclass(); } } throw new NoSuchMethodException(methodName); } public static List addAllMethods(final Class type, final List list) { if (type == Object.class) { list.addAll(OBJECT_METHODS); } else list.addAll(java.util.Arrays.asList(type.getDeclaredMethods())); Class superclass = type.getSuperclass(); if (superclass != null) { addAllMethods(superclass, list); } Class[] interfaces = type.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { addAllMethods(interfaces[i], list); } return list; } public static List addAllInterfaces(Class type, List list) { Class superclass = type.getSuperclass(); if (superclass != null) { list.addAll(Arrays.asList(type.getInterfaces())); addAllInterfaces(superclass, list); } return list; } public static Method findInterfaceMethod(Class iface) { if (!iface.isInterface()) { throw new IllegalArgumentException(iface + " is not an interface"); } Method[] methods = iface.getDeclaredMethods(); if (methods.length != 1) { throw new IllegalArgumentException("expecting exactly 1 method in " + iface); } return methods[0]; } // SPRING PATCH BEGIN public static Class defineClass(String className, byte[] b, ClassLoader loader) throws Exception { return defineClass(className, b, loader, null, null); } public static Class defineClass(String className, byte[] b, ClassLoader loader, ProtectionDomain protectionDomain) throws Exception { return defineClass(className, b, loader, protectionDomain, null); } public static Class defineClass(String className, byte[] b, ClassLoader loader, ProtectionDomain protectionDomain, Class<?> contextClass) throws Exception { Class c = null; // 在 jdk 17之后,需要hack方式来调用 #2659 if (c == null && classLoaderDefineClassMethod != null) { Lookup implLookup = UnsafeUtils.implLookup(); MethodHandle unreflect = implLookup.unreflect(classLoaderDefineClassMethod); if (protectionDomain == null) { protectionDomain = PROTECTION_DOMAIN; } try { c = (Class) unreflect.invoke(loader, className, b, 0, b.length, protectionDomain); } catch (InvocationTargetException ex) { throw new ReflectException(ex.getTargetException()); } catch (Throwable ex) { // Fall through if setAccessible fails with InaccessibleObjectException on JDK // 9+ // (on the module path and/or with a JVM bootstrapped with // --illegal-access=deny) if (!ex.getClass().getName().endsWith("InaccessibleObjectException")) { throw new ReflectException(ex); } } } // Preferred option: JDK 9+ Lookup.defineClass API if ClassLoader matches if (contextClass != null && contextClass.getClassLoader() == loader && privateLookupInMethod != null && lookupDefineClassMethod != null) { try { MethodHandles.Lookup lookup = (MethodHandles.Lookup) privateLookupInMethod.invoke(null, contextClass, MethodHandles.lookup()); c = (Class) lookupDefineClassMethod.invoke(lookup, b); } catch (InvocationTargetException ex) { Throwable target = ex.getTargetException(); if (target.getClass() != LinkageError.class && target.getClass() != IllegalArgumentException.class) { throw new ReflectException(target); } // in case of plain LinkageError (class already defined) // or IllegalArgumentException (class in different package): // fall through to traditional ClassLoader.defineClass below } catch (Throwable ex) { throw new ReflectException(ex); } } // Classic option: protected ClassLoader.defineClass method if (c == null && classLoaderDefineClassMethod != null) { if (protectionDomain == null) { protectionDomain = PROTECTION_DOMAIN; } Object[] args = new Object[] { className, b, 0, b.length, protectionDomain }; try { if (!classLoaderDefineClassMethod.isAccessible()) { classLoaderDefineClassMethod.setAccessible(true); } c = (Class) classLoaderDefineClassMethod.invoke(loader, args); } catch (InvocationTargetException ex) { throw new ReflectException(ex.getTargetException()); } catch (Throwable ex) { // Fall through if setAccessible fails with InaccessibleObjectException on JDK // 9+ // (on the module path and/or with a JVM bootstrapped with // --illegal-access=deny) if (!ex.getClass().getName().endsWith("InaccessibleObjectException")) { throw new ReflectException(ex); } } } // Fallback option: JDK 9+ Lookup.defineClass API even if ClassLoader does not // match if (c == null && contextClass != null && contextClass.getClassLoader() != loader && privateLookupInMethod != null && lookupDefineClassMethod != null) { try { MethodHandles.Lookup lookup = (MethodHandles.Lookup) privateLookupInMethod.invoke(null, contextClass, MethodHandles.lookup()); c = (Class) lookupDefineClassMethod.invoke(lookup, b); } catch (InvocationTargetException ex) { throw new ReflectException(ex.getTargetException()); } catch (Throwable ex) { throw new ReflectException(ex); } } // No defineClass variant available at all? if (c == null) { throw new ReflectException(THROWABLE); } // Force static initializers to run. Class.forName(className, true, loader); return c; } // SPRING PATCH END public static int findPackageProtected(Class[] classes) { for (int i = 0; i < classes.length; i++) { if (!Modifier.isPublic(classes[i].getModifiers())) { return i; } } return 0; } }
alibaba/arthas
common/src/main/java/com/taobao/arthas/common/ReflectUtils.java
193
/* * 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.backend.heartbeat; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import io.mycat.backend.datasource.PhysicalDBPool; import io.mycat.backend.datasource.PhysicalDatasource; import io.mycat.backend.mysql.nio.MySQLDataSource; import io.mycat.config.model.DataHostConfig; import io.mycat.sqlengine.OneRawSQLQueryResultHandler; import io.mycat.sqlengine.SQLJob; import io.mycat.sqlengine.SQLQueryResult; import io.mycat.sqlengine.SQLQueryResultListener; import io.mycat.util.TimeUtil; /** * @author mycat */ public class MySQLDetector implements SQLQueryResultListener<SQLQueryResult<Map<String, String>>> { private MySQLHeartbeat heartbeat; private long heartbeatTimeout; private final AtomicBoolean isQuit; private volatile long lastSendQryTime; private volatile long lasstReveivedQryTime; private volatile SQLJob sqlJob; private static final String[] MYSQL_SLAVE_STAUTS_COLMS = new String[] { "Seconds_Behind_Master", "Slave_IO_Running", "Slave_SQL_Running", "Slave_IO_State", "Master_Host", "Master_User", "Master_Port", "Connect_Retry", "Last_IO_Error", "Last_SQL_Error", "Last_SQL_Errno"}; private static final String[] MYSQL_CLUSTER_STAUTS_COLMS = new String[] { "Variable_name", "Value"}; public MySQLDetector(MySQLHeartbeat heartbeat) { this.heartbeat = heartbeat; this.isQuit = new AtomicBoolean(false); } public MySQLHeartbeat getHeartbeat() { return heartbeat; } public long getHeartbeatTimeout() { return heartbeatTimeout; } public void setHeartbeatTimeout(long heartbeatTimeout) { this.heartbeatTimeout = heartbeatTimeout; } public boolean isHeartbeatTimeout() { return TimeUtil.currentTimeMillis() > Math.max(lastSendQryTime, lasstReveivedQryTime) + heartbeatTimeout; } public long getLastSendQryTime() { return lastSendQryTime; } public long getLasstReveivedQryTime() { return lasstReveivedQryTime; } public void heartbeat() { lastSendQryTime = System.currentTimeMillis(); MySQLDataSource ds = heartbeat.getSource(); String databaseName = ds.getDbPool().getSchemas()[0]; String[] fetchColms={}; if (heartbeat.getSource().getHostConfig().isShowSlaveSql() ) { fetchColms=MYSQL_SLAVE_STAUTS_COLMS; } if (heartbeat.getSource().getHostConfig().isShowClusterSql() ) { fetchColms=MYSQL_CLUSTER_STAUTS_COLMS; } OneRawSQLQueryResultHandler resultHandler = new OneRawSQLQueryResultHandler( fetchColms, this); sqlJob = new SQLJob(heartbeat.getHeartbeatSQL(), databaseName, resultHandler, ds); sqlJob.run(); } public void quit() { if (isQuit.compareAndSet(false, true)) { close("heart beat quit"); } } public boolean isQuit() { return isQuit.get(); } @Override public void onResult(SQLQueryResult<Map<String, String>> result) { if (result.isSuccess()) { int balance = heartbeat.getSource().getDbPool().getBalance(); PhysicalDatasource source = heartbeat.getSource(); int switchType = source.getHostConfig().getSwitchType(); Map<String, String> resultResult = result.getResult(); if ( resultResult!=null&& !resultResult.isEmpty() &&switchType == DataHostConfig.SYN_STATUS_SWITCH_DS && source.getHostConfig().isShowSlaveSql()) { String Slave_IO_Running = resultResult != null ? resultResult.get("Slave_IO_Running") : null; String Slave_SQL_Running = resultResult != null ? resultResult.get("Slave_SQL_Running") : null; String Last_SQL_Error = resultResult != null ? resultResult.get("Last_SQL_Error") : null; Last_SQL_Error = Last_SQL_Error == null ? "" : Last_SQL_Error; if ("".equals(Last_SQL_Error) && Slave_IO_Running != null && Slave_IO_Running.equals(Slave_SQL_Running) && Slave_SQL_Running.equals("Yes") && source.isSalveOrRead()) { heartbeat.setDbSynStatus(DBHeartbeat.DB_SYN_NORMAL); String Seconds_Behind_Master = resultResult.get( "Seconds_Behind_Master"); if (null == Seconds_Behind_Master ){ MySQLHeartbeat.LOGGER.warn("Master is down but its relay log is clean."); heartbeat.setSlaveBehindMaster(0); }else if(!"".equals(Seconds_Behind_Master)) { int Behind_Master = Integer.parseInt(Seconds_Behind_Master); if ( Behind_Master > source.getHostConfig().getSlaveThreshold() ) { MySQLHeartbeat.LOGGER.warn("found MySQL master/slave Replication delay !!! " + heartbeat.getSource().getConfig() + ", binlog sync time delay: " + Behind_Master + "s" ); } heartbeat.setSlaveBehindMaster( Behind_Master ); } } else if( source.isSalveOrRead() ) { //String Last_IO_Error = resultResult != null ? resultResult.get("Last_IO_Error") : null; MySQLHeartbeat.LOGGER.warn("found MySQL master/slave Replication err !!! " + heartbeat.getSource().getConfig() + ", " + resultResult); heartbeat.setDbSynStatus(DBHeartbeat.DB_SYN_ERROR); } heartbeat.getAsynRecorder().set(resultResult, switchType); heartbeat.setResult(MySQLHeartbeat.OK_STATUS, this, null); } else if ( resultResult!=null&& !resultResult.isEmpty() && switchType==DataHostConfig.CLUSTER_STATUS_SWITCH_DS && source.getHostConfig().isShowClusterSql() ) { //String Variable_name = resultResult != null ? resultResult.get("Variable_name") : null; String wsrep_cluster_status = resultResult != null ? resultResult.get("wsrep_cluster_status") : null;// Primary String wsrep_connected = resultResult != null ? resultResult.get("wsrep_connected") : null;// ON String wsrep_ready = resultResult != null ? resultResult.get("wsrep_ready") : null;// ON if ("ON".equals(wsrep_connected) && "ON".equals(wsrep_ready) && "Primary".equals(wsrep_cluster_status)) { heartbeat.setDbSynStatus(DBHeartbeat.DB_SYN_NORMAL); heartbeat.setResult(MySQLHeartbeat.OK_STATUS, this, null); } else { MySQLHeartbeat.LOGGER.warn("found MySQL cluster status err !!! " + heartbeat.getSource().getConfig() + " wsrep_cluster_status: "+ wsrep_cluster_status + " wsrep_connected: "+ wsrep_connected + " wsrep_ready: "+ wsrep_ready ); heartbeat.setDbSynStatus(DBHeartbeat.DB_SYN_ERROR); heartbeat.setResult(MySQLHeartbeat.ERROR_STATUS, this, null); } heartbeat.getAsynRecorder().set(resultResult, switchType); } else { heartbeat.setResult(MySQLHeartbeat.OK_STATUS, this, null); } //监测数据库同步状态,在 switchType=-1或者1的情况下,也需要收集主从同步状态 heartbeat.getAsynRecorder().set(resultResult, switchType); } else { MySQLHeartbeat.LOGGER.warn("heart beat error: " + heartbeat.getSource().getName() + "/" + heartbeat.getSource().getHostConfig().getName() + " retry=" + heartbeat.getHeartbeatRetry() + " tmo=" + heartbeat.getHeartbeatTimeout()); heartbeat.setResult(MySQLHeartbeat.ERROR_STATUS, this, null); } lasstReveivedQryTime = System.currentTimeMillis(); heartbeat.getRecorder().set((lasstReveivedQryTime - lastSendQryTime)); } public void close(String msg) { SQLJob curJob = sqlJob; if (curJob != null && !curJob.isFinished()) { curJob.teminate(msg); sqlJob = null; } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/backend/heartbeat/MySQLDetector.java
194
package com.dianping.cat.context.context; import com.dianping.cat.Cat; import com.dianping.cat.context.CatConstantsExt; import com.dianping.cat.context.CatContextImpl; import feign.RequestInterceptor; import feign.RequestTemplate; /** * 适用于使用feign调用其他SpringCloud微服务的调用链上下文传递场景 * 作用:在使用feign请求其他微服务时,自动生成context上下文,并将相应参数rootId、parentId、childId放入header * 使用方法:在需要添加catcontext的feign service接口中,@FeignClient注解添加此类的configuration配置, * 如:@FeignClient(name="account-manage", configuration = CatFeignConfiguration.class) * * @author soar * @date 2019-01-10 */ public class CatFeignConfiguration implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { com.dianping.cat.context.CatContextImpl catContext = new CatContextImpl(); Cat.logRemoteCallClient(catContext,Cat.getManager().getDomain()); requestTemplate.header(CatConstantsExt.CAT_HTTP_HEADER_ROOT_MESSAGE_ID,catContext.getProperty(Cat.Context.ROOT)); requestTemplate.header(CatConstantsExt.CAT_HTTP_HEADER_PARENT_MESSAGE_ID,catContext.getProperty(Cat.Context.PARENT)); requestTemplate.header(CatConstantsExt.CAT_HTTP_HEADER_CHILD_MESSAGE_ID,catContext.getProperty(Cat.Context.CHILD)); } }
dianping/cat
integration/context/CatFeignConfiguration.java
195
package cn.itcast_12; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; /* * JDK4以后,出现了新IO。在nio包下。和以前的IO相比,它是把文件映射到内存,效率更高。 * JDK7出现了几个新东西: * Path:与平台无关的路径。 * Paths:包含了返回Path的静态方法。 * public static Path get(URI uri):根据给定的URI来确定文件路径。 * Files:操作文件的工具类。提供了大量的方法,简单了解如下方法 * public static long copy(Path source, OutputStream out) :复制文件 * public static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options): * 把集合的数据写到文件。 */ public class JDK7Demo { public static void main(String[] args) throws IOException { // public static long copy(Path source, OutputStream out) // Files.copy(Paths.get("a.txt"), new FileOutputStream("b.txt")); // Files.copy(Paths.get("d:\\mn.bmp"), new FileOutputStream("mn.bmp")); // 把集合数据写到文本文件 // ArrayList<String> array = new ArrayList<String>(); // array.add("hello"); // array.add("world"); // array.add("java"); // Files.write(Paths.get("array.txt"), array, Charset.forName("GBK")); } }
DuGuQiuBai/Java
day22/code/day22_IO/src/cn/itcast_12/JDK7Demo.java
196
/* * 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; /** * 分页查询接口 * * @author liuzh_3nofxnp * @since 2015-12-18 18:51 */ public interface ISelect { /** * 在接口中调用自己的查询方法,不要在该方法内写过多代码,只要一行查询方法最好 */ void doSelect(); }
pagehelper/Mybatis-PageHelper
src/main/java/com/github/pagehelper/ISelect.java
198
/* * Copyright 2019-2020 Zheng Jie * * 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 me.zhengjie; import io.swagger.annotations.Api; import me.zhengjie.annotation.rest.AnonymousGetMapping; import me.zhengjie.utils.SpringContextHolder; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.ApplicationPidFileWriter; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.bind.annotation.RestController; /** * 开启审计功能 -> @EnableJpaAuditing * * @author Zheng Jie * @date 2018/11/15 9:20:19 */ @EnableAsync @RestController @Api(hidden = true) @SpringBootApplication @EnableTransactionManagement @EnableJpaAuditing(auditorAwareRef = "auditorAware") public class AppRun { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(AppRun.class); // 监控应用的PID,启动时可指定PID路径:--spring.pid.file=/home/eladmin/app.pid // 或者在 application.yml 添加文件路径,方便 kill,kill `cat /home/eladmin/app.pid` springApplication.addListeners(new ApplicationPidFileWriter()); springApplication.run(args); } @Bean public SpringContextHolder springContextHolder() { return new SpringContextHolder(); } /** * 访问首页提示 * * @return / */ @AnonymousGetMapping("/") public String index() { return "Backend service started successfully"; } }
elunez/eladmin
eladmin-system/src/main/java/me/zhengjie/AppRun.java
199
class Solution { public int findMaximumXOR(int[] numbers) { int max = 0; int mask = 0; for (int i = 30; i >= 0; i--) { int current = 1 << i; // 期望的二进制前缀 mask = mask ^ current; // 在当前前缀下, 数组内的前缀位数所有情况集合 Set<Integer> set = new HashSet<>(); for (int j = 0, k = numbers.length; j < k; j++) { set.add(mask & numbers[j]); } // 期望最终异或值的从右数第i位为1, 再根据异或运算的特性推算假设是否成立 int flag = max | current; for (Integer prefix : set) { if (set.contains(prefix ^ flag)) { max = flag; break; } } } return max; } }
doocs/leetcode
lcof2/剑指 Offer II 067. 最大的异或/Solution.java
200
package com.macro.mall.controller; import cn.hutool.core.collection.CollUtil; import cn.hutool.json.JSONUtil; import com.macro.mall.common.api.CommonResult; import com.macro.mall.dto.BucketPolicyConfigDto; import com.macro.mall.dto.MinioUploadDto; import io.minio.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.v3.oas.annotations.tags.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.text.SimpleDateFormat; import java.util.Date; /** * MinIO对象存储管理Controller * Created by macro on 2019/12/25. */ @Controller @Api(tags = "MinioController") @Tag(name = "MinioController", description = "MinIO对象存储管理") @RequestMapping("/minio") public class MinioController { private static final Logger LOGGER = LoggerFactory.getLogger(MinioController.class); @Value("${minio.endpoint}") private String ENDPOINT; @Value("${minio.bucketName}") private String BUCKET_NAME; @Value("${minio.accessKey}") private String ACCESS_KEY; @Value("${minio.secretKey}") private String SECRET_KEY; @ApiOperation("文件上传") @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public CommonResult upload(@RequestPart("file") MultipartFile file) { try { //创建一个MinIO的Java客户端 MinioClient minioClient =MinioClient.builder() .endpoint(ENDPOINT) .credentials(ACCESS_KEY,SECRET_KEY) .build(); boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build()); if (isExist) { LOGGER.info("存储桶已经存在!"); } else { //创建存储桶并设置只读权限 minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build()); BucketPolicyConfigDto bucketPolicyConfigDto = createBucketPolicyConfigDto(BUCKET_NAME); SetBucketPolicyArgs setBucketPolicyArgs = SetBucketPolicyArgs.builder() .bucket(BUCKET_NAME) .config(JSONUtil.toJsonStr(bucketPolicyConfigDto)) .build(); minioClient.setBucketPolicy(setBucketPolicyArgs); } String filename = file.getOriginalFilename(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // 设置存储对象名称 String objectName = sdf.format(new Date()) + "/" + filename; // 使用putObject上传一个文件到存储桶中 PutObjectArgs putObjectArgs = PutObjectArgs.builder() .bucket(BUCKET_NAME) .object(objectName) .contentType(file.getContentType()) .stream(file.getInputStream(), file.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE).build(); minioClient.putObject(putObjectArgs); LOGGER.info("文件上传成功!"); MinioUploadDto minioUploadDto = new MinioUploadDto(); minioUploadDto.setName(filename); minioUploadDto.setUrl(ENDPOINT + "/" + BUCKET_NAME + "/" + objectName); return CommonResult.success(minioUploadDto); } catch (Exception e) { e.printStackTrace(); LOGGER.info("上传发生错误: {}!", e.getMessage()); } return CommonResult.failed(); } /** * 创建存储桶的访问策略,设置为只读权限 */ private BucketPolicyConfigDto createBucketPolicyConfigDto(String bucketName) { BucketPolicyConfigDto.Statement statement = BucketPolicyConfigDto.Statement.builder() .Effect("Allow") .Principal("*") .Action("s3:GetObject") .Resource("arn:aws:s3:::"+bucketName+"/*.**").build(); return BucketPolicyConfigDto.builder() .Version("2012-10-17") .Statement(CollUtil.toList(statement)) .build(); } @ApiOperation("文件删除") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("objectName") String objectName) { try { MinioClient minioClient = MinioClient.builder() .endpoint(ENDPOINT) .credentials(ACCESS_KEY,SECRET_KEY) .build(); minioClient.removeObject(RemoveObjectArgs.builder().bucket(BUCKET_NAME).object(objectName).build()); return CommonResult.success(null); } catch (Exception e) { e.printStackTrace(); } return CommonResult.failed(); } }
macrozheng/mall
mall-admin/src/main/java/com/macro/mall/controller/MinioController.java
201
package cc.mrbird; import cc.mrbird.demo.config.WebConfig; import cc.mrbird.demo.service.CalculateService; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.Arrays; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { ConfigurableApplicationContext context1 = new SpringApplicationBuilder(DemoApplication.class) .web(WebApplicationType.NONE) .profiles("java7") .run(args); // 返回 IOC 容器,使用注解配置,传入配置类 ApplicationContext context = new AnnotationConfigApplicationContext(WebConfig.class); System.out.println("容器创建完毕"); // User user = context.getBean(User.class); // System.out.println(user); // 查看 User 这个类在 Spring 容器中叫啥玩意 // String[] beanNames = context.getBeanNamesForType(User.class); // Arrays.stream(beanNames).forEach(System.out::println); // 查看基于注解的 IOC容器中所有组件名称 String[] beanNames = context.getBeanDefinitionNames(); Arrays.stream(beanNames).forEach(System.out::println); // 组件的作用域 // Object user1 = context.getBean("user"); // Object user2 = context.getBean("user"); // System.out.println(user1 == user2); // 测试懒加载 // Object user1 = context.getBean("user"); // Object user2 = context.getBean("user"); // 测试 Profile CalculateService service = context1.getBean(CalculateService.class); System.out.println("求合结果: " + service.sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); // FactoryBean测试 Object cherry = context.getBean("cherryFactoryBean"); System.out.println(cherry.getClass()); Object cherryFactoryBean = context.getBean("&cherryFactoryBean"); System.out.println(cherryFactoryBean.getClass()); } }
wuyouzhuguli/SpringAll
50.Spring-Regist-Bean/src/main/java/cc/mrbird/DemoApplication.java
202
package com.neo.model; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; @Document(indexName = "customer", type = "customer", shards = 1, replicas = 0, refreshInterval = "-1") public class Customer { //Id注解加上后,在Elasticsearch里相应于该列就是主键了,在查询时就可以直接用主键查询 @Id private String id; private String userName; private String address; private int age; public Customer() { } public Customer(String userName, String address, int age) { this.userName = userName; this.address = address; this.age = age; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getAddress() { return address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Customer{" + "id='" + id + '\'' + ", userName='" + userName + '\'' + ", address='" + address + '\'' + ", age=" + age + '}'; } }
ityouknow/spring-boot-examples
2.x/spring-boot-elasticsearch/src/main/java/com/neo/model/Customer.java
205
/** * Copyright (c) 2011-2023, James Zhan 詹波 ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jfinal.kit; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import com.jfinal.json.Json; /** * Kv (Key Value) * * Example: * Kv para = Kv.by("id", 123); * User user = user.findFirst(getSqlPara("find", para)); */ @SuppressWarnings({"rawtypes", "unchecked"}) public class Kv extends HashMap { private static final long serialVersionUID = -808251639784763326L; public Kv() { } public static Kv of(Object key, Object value) { return new Kv().set(key, value); } public static Kv by(Object key, Object value) { return new Kv().set(key, value); } public static Kv create() { return new Kv(); } public Kv set(Object key, Object value) { super.put(key, value); return this; } public Kv setIfNotBlank(Object key, String value) { if (StrKit.notBlank(value)) { set(key, value); } return this; } public Kv setIfNotNull(Object key, Object value) { if (value != null) { set(key, value); } return this; } public Kv set(Map map) { super.putAll(map); return this; } public Kv set(Kv kv) { super.putAll(kv); return this; } public Kv delete(Object key) { super.remove(key); return this; } public <T> T getAs(Object key) { return (T)get(key); } public <T> T getAs(Object key, T defaultValue) { Object ret = get(key); return ret != null ? (T) ret : defaultValue; } public String getStr(Object key) { Object s = get(key); return s != null ? s.toString() : null; } public Integer getInt(Object key) { return TypeKit.toInt(get(key)); } public Long getLong(Object key) { return TypeKit.toLong(get(key)); } public BigDecimal getBigDecimal(Object key) { return TypeKit.toBigDecimal(get(key)); } public Double getDouble(Object key) { return TypeKit.toDouble(get(key)); } public Float getFloat(Object key) { return TypeKit.toFloat(get(key)); } public Number getNumber(Object key) { return TypeKit.toNumber(get(key)); } public Boolean getBoolean(Object key) { return TypeKit.toBoolean(get(key)); } public java.util.Date getDate(Object key) { return TypeKit.toDate(get(key)); } public java.time.LocalDateTime getLocalDateTime(Object key) { return TypeKit.toLocalDateTime(get(key)); } /** * key 存在,并且 value 不为 null */ public boolean notNull(Object key) { return get(key) != null; } /** * key 不存在,或者 key 存在但 value 为null */ public boolean isNull(Object key) { return get(key) == null; } /** * key 存在,并且 value 为 true,则返回 true */ public boolean isTrue(Object key) { Object value = get(key); return value != null && TypeKit.toBoolean(value); } /** * key 存在,并且 value 为 false,则返回 true */ public boolean isFalse(Object key) { Object value = get(key); return value != null && !TypeKit.toBoolean(value); } public String toJson() { return Json.getJson().toJson(this); } public boolean equals(Object kv) { return kv instanceof Kv && super.equals(kv); } public Kv keep(String... keys) { if (keys != null && keys.length > 0) { Kv newKv = Kv.create(); for (String k : keys) { if (containsKey(k)) { // 避免将并不存在的变量存为 null newKv.put(k, get(k)); } } clear(); putAll(newKv); } else { clear(); } return this; } public <K, V>Map<K, V> toMap() { return this; } }
jfinal/jfinal
src/main/java/com/jfinal/kit/Kv.java
206
package org.nlpcn.es4sql.domain; import org.nlpcn.es4sql.parse.ChildrenType; import org.nlpcn.es4sql.parse.NestedType; /** * 搜索域 * * @author ansj * */ public class Field implements Cloneable{ protected String name; //zhongshu-comment 在这里拼上script(....) private String alias; private NestedType nested; private ChildrenType children; public Field(String name, String alias) { this.name = name; this.alias = alias; this.nested = null; this.children = null; } public Field(String name, String alias, NestedType nested, ChildrenType children) { this.name = name; this.alias = alias; this.nested = nested; this.children = children; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public boolean isNested() { return this.nested != null; } public boolean isReverseNested() { return this.nested != null && this.nested.isReverse(); } public void setNested(NestedType nested){ this.nested = nested; } public String getNestedPath() { if(this.nested == null ) return null; return this.nested.path; } public boolean isChildren() { return this.children != null; } public void setChildren(ChildrenType children){ this.children = children; } public String getChildType() { if(this.children == null ) return null; return this.children.childType; } @Override public String toString() { return this.name; } @Override public boolean equals(Object obj) { if(obj == null) return false; if(obj.getClass() != this.getClass()) return false; Field other = (Field) obj; boolean namesAreEqual = (other.getName() == null && this.name == null ) || other.getName().equals(this.name) ; if(!namesAreEqual) return false; return (other.getAlias() == null && this.alias == null ) || other.getAlias().equals(this.alias) ; } @Override protected Object clone() throws CloneNotSupportedException { return new Field(new String(this.name), new String(this.alias)); } }
NLPchina/elasticsearch-sql
src/main/java/org/nlpcn/es4sql/domain/Field.java
207
package com.zheng.common.util; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.concurrent.locks.ReentrantLock; /** * Redis 工具类 * Created by shuzheng on 2016/11/26. */ public class RedisUtil { protected static ReentrantLock lockPool = new ReentrantLock(); protected static ReentrantLock lockJedis = new ReentrantLock(); private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class); // Redis服务器IP private static String IP = PropertiesFileUtil.getInstance("redis").get("master.redis.ip"); // Redis的端口号 private static int PORT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.port"); // 访问密码 private static String PASSWORD = AESUtil.aesDecode(PropertiesFileUtil.getInstance("redis").get("master.redis.password")); // 可用连接实例的最大数目,默认值为8; // 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。 private static int MAX_ACTIVE = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_active"); // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。 private static int MAX_IDLE = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_idle"); // 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException; private static int MAX_WAIT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_wait"); // 超时时间 private static int TIMEOUT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.timeout"); // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的; private static boolean TEST_ON_BORROW = false; private static JedisPool jedisPool = null; /** * redis过期时间,以秒为单位 */ // 一小时 public final static int EXRP_HOUR = 60 * 60; // 一天 public final static int EXRP_DAY = 60 * 60 * 24; // 一个月 public final static int EXRP_MONTH = 60 * 60 * 24 * 30; /** * 初始化Redis连接池 */ private static void initialPool() { try { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(MAX_ACTIVE); config.setMaxIdle(MAX_IDLE); config.setMaxWaitMillis(MAX_WAIT); config.setTestOnBorrow(TEST_ON_BORROW); jedisPool = new JedisPool(config, IP, PORT, TIMEOUT); } catch (Exception e) { LOGGER.error("First create JedisPool error : " + e); } } /** * 在多线程环境同步初始化 */ private static synchronized void poolInit() { if (null == jedisPool) { initialPool(); } } /** * 同步获取Jedis实例 * @return Jedis */ public synchronized static Jedis getJedis() { poolInit(); Jedis jedis = null; try { if (null != jedisPool) { jedis = jedisPool.getResource(); try { jedis.auth(PASSWORD); } catch (Exception e) { } } } catch (Exception e) { LOGGER.error("Get jedis error : " + e); } return jedis; } /** * 设置 String * @param key * @param value */ public synchronized static void set(String key, String value) { try { value = StringUtils.isBlank(value) ? "" : value; Jedis jedis = getJedis(); jedis.set(key, value); jedis.close(); } catch (Exception e) { LOGGER.error("Set key error : " + e); } } /** * 设置 byte[] * @param key * @param value */ public synchronized static void set(byte[] key, byte[] value) { try { Jedis jedis = getJedis(); jedis.set(key, value); jedis.close(); } catch (Exception e) { LOGGER.error("Set key error : " + e); } } /** * 设置 String 过期时间 * @param key * @param value * @param seconds 以秒为单位 */ public synchronized static void set(String key, String value, int seconds) { try { value = StringUtils.isBlank(value) ? "" : value; Jedis jedis = getJedis(); jedis.setex(key, seconds, value); jedis.close(); } catch (Exception e) { LOGGER.error("Set keyex error : " + e); } } /** * 设置 byte[] 过期时间 * @param key * @param value * @param seconds 以秒为单位 */ public synchronized static void set(byte[] key, byte[] value, int seconds) { try { Jedis jedis = getJedis(); jedis.set(key, value); jedis.expire(key, seconds); jedis.close(); } catch (Exception e) { LOGGER.error("Set key error : " + e); } } /** * 获取String值 * @param key * @return value */ public synchronized static String get(String key) { Jedis jedis = getJedis(); if (null == jedis) { return null; } String value = jedis.get(key); jedis.close(); return value; } /** * 获取byte[]值 * @param key * @return value */ public synchronized static byte[] get(byte[] key) { Jedis jedis = getJedis(); if (null == jedis) { return null; } byte[] value = jedis.get(key); jedis.close(); return value; } /** * 删除值 * @param key */ public synchronized static void remove(String key) { try { Jedis jedis = getJedis(); jedis.del(key); jedis.close(); } catch (Exception e) { LOGGER.error("Remove keyex error : " + e); } } /** * 删除值 * @param key */ public synchronized static void remove(byte[] key) { try { Jedis jedis = getJedis(); jedis.del(key); jedis.close(); } catch (Exception e) { LOGGER.error("Remove keyex error : " + e); } } /** * lpush * @param key * @param key */ public synchronized static void lpush(String key, String... strings) { try { Jedis jedis = RedisUtil.getJedis(); jedis.lpush(key, strings); jedis.close(); } catch (Exception e) { LOGGER.error("lpush error : " + e); } } /** * lrem * @param key * @param count * @param value */ public synchronized static void lrem(String key, long count, String value) { try { Jedis jedis = RedisUtil.getJedis(); jedis.lrem(key, count, value); jedis.close(); } catch (Exception e) { LOGGER.error("lpush error : " + e); } } /** * sadd * @param key * @param value * @param seconds */ public synchronized static void sadd(String key, String value, int seconds) { try { Jedis jedis = RedisUtil.getJedis(); jedis.sadd(key, value); jedis.expire(key, seconds); jedis.close(); } catch (Exception e) { LOGGER.error("sadd error : " + e); } } /** * incr * @param key * @return value */ public synchronized static Long incr(String key) { Jedis jedis = getJedis(); if (null == jedis) { return null; } long value = jedis.incr(key); jedis.close(); return value; } /** * decr * @param key * @return value */ public synchronized static Long decr(String key) { Jedis jedis = getJedis(); if (null == jedis) { return null; } long value = jedis.decr(key); jedis.close(); return value; } }
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/util/RedisUtil.java
208
package org.pdown.gui.extension.mitm.util; import com.github.monkeywie.proxyee.crt.CertUtil; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyPair; import java.security.MessageDigest; import java.security.cert.X509Certificate; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.pdown.core.util.FileUtil; import org.pdown.core.util.OsUtil; import org.pdown.gui.DownApplication; import org.pdown.gui.util.ExecUtil; import sun.security.x509.X500Name; /** * 用于处理系统的证书安装、查询和卸载 */ public class ExtensionCertUtil { /** * 在指定目录生成一个ca证书和私钥 */ public static void buildCert(String path, String subjectName) throws Exception { //生成ca证书和私钥 KeyPair keyPair = CertUtil.genKeyPair(); File priKeyFile = FileUtil.createFile(path + File.separator + ".ca_pri.der", true); File caCertFile = FileUtil.createFile(path + File.separator + "ca.crt", false); Files.write(Paths.get(priKeyFile.toURI()), keyPair.getPrivate().getEncoded()); Files.write(Paths.get(caCertFile.toURI()), CertUtil.genCACert( "C=CN, ST=GD, L=SZ, O=lee, OU=study, CN=" + subjectName, new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650)), keyPair) .getEncoded()); } /** * 安装证书 */ public static void installCert(File file) throws IOException { String path = file.getPath(); if (OsUtil.isWindows()) { ExecUtil.execBlock("certutil", "-addstore", "-user", "root", path); } else if (OsUtil.isMac()) { ExecUtil.httpGet("http://127.0.0.1:" + DownApplication.macToolPort + "/cert/install?path=" + URLEncoder.encode(path, "utf-8")); } } /** * 通过证书subjectName和sha1,判断系统是否已安装该证书 */ public static boolean isInstalledCert(File file) throws Exception { if (!file.exists()) { return false; } if (OsUtil.isUnix()) { return true; } X509Certificate cert = CertUtil.loadCert(file.toURI()); String subjectName = ((X500Name) cert.getSubjectDN()).getCommonName(); String sha1 = getCertSHA1(cert); return findCertList(subjectName).toUpperCase().replaceAll("\\s", "").indexOf(":" + sha1.toUpperCase()) != -1; } /** * 通过证书subjectName,判断系统是否已安装此subjectName的证书 */ public static boolean existsCert(String subjectName) throws IOException { if (OsUtil.isWindows() && findCertList(subjectName).toUpperCase().indexOf("=====") != -1) { return true; } else if (OsUtil.isMac() && findCertList(subjectName).toUpperCase().indexOf("BEGIN CERTIFICATE") != -1) { return true; } return false; } /** * 通过证书name,卸载证书 */ public static void uninstallCert(String subjectName) throws IOException { if (OsUtil.isWindows()) { Pattern pattern = Pattern.compile("(?i)\\(sha1\\):\\s(.*)\r?\n"); String certList = findCertList(subjectName); Matcher matcher = pattern.matcher(certList); while (matcher.find()) { String hash = matcher.group(1).replaceAll("\\s", ""); ExecUtil.execBlock("certutil", "-delstore", "-user", "root", hash); } } else if (OsUtil.isMac()) { String certList = findCertList(subjectName); Pattern pattern = Pattern.compile("(?i)SHA-1 hash:\\s(.*)\r?\n"); Matcher matcher = pattern.matcher(certList); while (matcher.find()) { String hash = matcher.group(1); ExecUtil.httpGet("http://127.0.0.1:" + DownApplication.macToolPort + "/cert/uninstall" + "?hash=" + hash); } } } //查询证书列表 private static String findCertList(String subjectName) throws IOException { if (OsUtil.isWindows()) { return ExecUtil.exec("certutil ", "-store", "-user", "root", subjectName); } else if (OsUtil.isMac()) { return ExecUtil.exec("security", "find-certificate", "-a", "-c", subjectName, "-p", "-Z", "/Library/Keychains/System.keychain"); } return null; } private static String getCertSHA1(X509Certificate certificate) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] der = certificate.getEncoded(); md.update(der); return btsToHex(md.digest()); } private static String btsToHex(byte[] bts) { StringBuilder str = new StringBuilder(); for (byte b : bts) { str.append(String.format("%2s", Integer.toHexString(b & 0xFF)).replace(" ", "0")); } return str.toString(); } public static void main(String[] args) throws Exception { String subjectName = "ProxyeeDown CA"; String path = "f:/test/"; File certFile = new File(path + "ca.crt"); //证书还未安装 if (!isInstalledCert(certFile)) { if (existsCert(subjectName)) { //存在无用证书需要卸载 uninstallCert(subjectName); } //生成新的证书 buildCert(path, subjectName); //安装 installCert(certFile); } } }
proxyee-down-org/proxyee-down
main/src/main/java/org/pdown/gui/extension/mitm/util/ExtensionCertUtil.java
213
package com.macro.mall.portal.service; import com.macro.mall.model.CmsSubject; import com.macro.mall.model.PmsProduct; import com.macro.mall.model.PmsProductCategory; import com.macro.mall.portal.domain.HomeContentResult; import java.util.List; /** * 首页内容管理Service * Created by macro on 2019/1/28. */ public interface HomeService { /** * 获取首页内容 */ HomeContentResult content(); /** * 首页商品推荐 */ List<PmsProduct> recommendProductList(Integer pageSize, Integer pageNum); /** * 获取商品分类 * @param parentId 0:获取一级分类;其他:获取指定二级分类 */ List<PmsProductCategory> getProductCateList(Long parentId); /** * 根据专题分类分页获取专题 * @param cateId 专题分类id */ List<CmsSubject> getSubjectList(Long cateId, Integer pageSize, Integer pageNum); /** * 分页获取人气推荐商品 */ List<PmsProduct> hotProductList(Integer pageNum, Integer pageSize); /** * 分页获取新品推荐商品 */ List<PmsProduct> newProductList(Integer pageNum, Integer pageSize); }
macrozheng/mall
mall-portal/src/main/java/com/macro/mall/portal/service/HomeService.java
215
package cn.hutool.cache.impl; import cn.hutool.core.lang.mutable.Mutable; import cn.hutool.core.map.FixedLinkedHashMap; import java.util.Iterator; /** * LRU (least recently used)最近最久未使用缓存<br> * 根据使用时间来判定对象是否被持续缓存<br> * 当对象被访问时放入缓存,当缓存满了,最久未被使用的对象将被移除。<br> * 此缓存基于LinkedHashMap,因此当被缓存的对象每被访问一次,这个对象的key就到链表头部。<br> * 这个算法简单并且非常快,他比FIFO有一个显著优势是经常使用的对象不太可能被移除缓存。<br> * 缺点是当缓存满时,不能被很快的访问。 * @author Looly,jodd * * @param <K> 键类型 * @param <V> 值类型 */ public class LRUCache<K, V> extends ReentrantCache<K, V> { private static final long serialVersionUID = 1L; /** * 构造<br> * 默认无超时 * @param capacity 容量 */ public LRUCache(int capacity) { this(capacity, 0); } /** * 构造 * @param capacity 容量 * @param timeout 默认超时时间,单位:毫秒 */ public LRUCache(int capacity, long timeout) { if(Integer.MAX_VALUE == capacity) { capacity -= 1; } this.capacity = capacity; this.timeout = timeout; //链表key按照访问顺序排序,调用get方法后,会将这次访问的元素移至头部 final FixedLinkedHashMap<Mutable<K>, CacheObj<K, V>> fixedLinkedHashMap = new FixedLinkedHashMap<>(capacity); fixedLinkedHashMap.setRemoveListener(entry -> { if(null != listener){ listener.onRemove(entry.getKey().get(), entry.getValue().getValue()); } }); cacheMap = fixedLinkedHashMap; } // ---------------------------------------------------------------- prune /** * 只清理超时对象,LRU的实现会交给{@code LinkedHashMap} */ @Override protected int pruneCache() { if (isPruneExpiredActive() == false) { return 0; } int count = 0; Iterator<CacheObj<K, V>> values = cacheObjIter(); CacheObj<K, V> co; while (values.hasNext()) { co = values.next(); if (co.isExpired()) { values.remove(); onRemove(co.key, co.obj); count++; } } return count; } }
dromara/hutool
hutool-cache/src/main/java/cn/hutool/cache/impl/LRUCache.java
216
package org.jeecg.common.system.vo; import java.io.Serializable; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * @Description: 字典类 * @author: jeecg-boot */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @JsonIgnoreProperties(ignoreUnknown = true) public class DictModel implements Serializable{ private static final long serialVersionUID = 1L; public DictModel() { } public DictModel(String value, String text) { this.value = value; this.text = text; } public DictModel(String value, String text, String color) { this.value = value; this.text = text; this.color = color; } /** * 字典value */ private String value; /** * 字典文本 */ private String text; /** * 字典颜色 */ private String color; /** * 特殊用途: JgEditableTable * @return */ public String getTitle() { return this.text; } /** * 特殊用途: vue3 Select组件 */ public String getLabel() { return this.text; } /** * 用于表单设计器 关联记录表数据存储 * QQYUN-5595【表单设计器】他表字段 导入没有翻译 */ private JSONObject jsonObject; }
jeecgboot/jeecg-boot
jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/DictModel.java
217
/* * 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.okrx2; import com.lzy.demo.base.MainFragment; import com.lzy.demo.model.ItemModel; import java.util.List; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/6/9 * 描 述: * 修订历史: * ================================================ */ public class OkRxFragment extends MainFragment { @Override public void fillData(List<ItemModel> items) { items.add(new ItemModel("OkRx是OkGo结合RxJava的扩展项目\n" +// "OkRx2是OkGo结合RxJava2的扩展项目\n" +// "他们的使用方法完全一样,在此不做演示,详细请看OkRx2的使用介绍", // "1.完美结合RxJava\n" +// "2.比Retrofit更简单方便\n" +// "3.网络请求和RxJava调用,一条链点到底\n" +// "4.支持JSON数据的自动解析转换")); } @Override public void onItemClick(int position) { } }
jeasonlzy/okhttp-OkGo
demo/src/main/java/com/lzy/demo/okrx2/OkRxFragment.java
218
/* * 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.config; /** * 处理能力标识定义 * * @author mycat */ public interface Capabilities { /** * server capabilities * * <pre> * server: 11110111 11111111 * client_cmd: 11 10100110 10000101 * client_jdbc:10 10100010 10001111 * * @see http://dev.mysql.com/doc/refman/5.1/en/mysql-real-connect.html * </pre> */ // new more secure passwords public static final int CLIENT_LONG_PASSWORD = 1; // Found instead of affected rows // 返回找到(匹配)的行数,而不是改变了的行数。 public static final int CLIENT_FOUND_ROWS = 2; // Get all column flags public static final int CLIENT_LONG_FLAG = 4; // One can specify db on connect public static final int CLIENT_CONNECT_WITH_DB = 8; // Don't allow database.table.column // 不允许“数据库名.表名.列名”这样的语法。这是对于ODBC的设置。 // 当使用这样的语法时解析器会产生一个错误,这对于一些ODBC的程序限制bug来说是有用的。 public static final int CLIENT_NO_SCHEMA = 16; // Can use compression protocol // 使用压缩协议 public static final int CLIENT_COMPRESS = 32; // Odbc client public static final int CLIENT_ODBC = 64; // Can use LOAD DATA LOCAL public static final int CLIENT_LOCAL_FILES = 128; // Ignore spaces before '(' // 允许在函数名后使用空格。所有函数名可以预留字。 public static final int CLIENT_IGNORE_SPACE = 256; // New 4.1 protocol This is an interactive client public static final int CLIENT_PROTOCOL_41 = 512; // This is an interactive client // 允许使用关闭连接之前的不活动交互超时的描述,而不是等待超时秒数。 // 客户端的会话等待超时变量变为交互超时变量。 public static final int CLIENT_INTERACTIVE = 1024; // Switch to SSL after handshake // 使用SSL。这个设置不应该被应用程序设置,他应该是在客户端库内部是设置的。 // 可以在调用mysql_real_connect()之前调用mysql_ssl_set()来代替设置。 public static final int CLIENT_SSL = 2048; // IGNORE sigpipes // 阻止客户端库安装一个SIGPIPE信号处理器。 // 这个可以用于当应用程序已经安装该处理器的时候避免与其发生冲突。 public static final int CLIENT_IGNORE_SIGPIPE = 4096; // Client knows about transactions public static final int CLIENT_TRANSACTIONS = 8192; // Old flag for 4.1 protocol public static final int CLIENT_RESERVED = 16384; // New 4.1 authentication public static final int CLIENT_SECURE_CONNECTION = 32768; // Enable/disable multi-stmt support // 通知服务器客户端可以发送多条语句(由分号分隔)。如果该标志为没有被设置,多条语句执行。 public static final int CLIENT_MULTI_STATEMENTS = 65536; // Enable/disable multi-results // 通知服务器客户端可以处理由多语句或者存储过程执行生成的多结果集。 // 当打开CLIENT_MULTI_STATEMENTS时,这个标志自动的被打开。 public static final int CLIENT_MULTI_RESULTS = 131072; public static final int CLIENT_PLUGIN_AUTH = 0x00080000; // 524288 }
MyCATApache/Mycat-Server
src/main/java/io/mycat/config/Capabilities.java
219
/* * 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.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.LinkedHashMap; import java.util.Map; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.unidal.lookup.annotation.Named; import com.dianping.cat.Cat; @Named public class IpService implements Initializable { private static final String OTHER = "其他"; private int[] m_areaIds; private Map<Integer, Area> m_areas; private int[] m_corpIds; private Map<Integer, Corporation> m_corps; private long[] m_ends; private long[] m_starts; private int[] m_foreignAreaIds; private Map<Integer, Area> m_foreignAreas; private long[] m_foreignEnds; private long[] m_foreignStarts; private String FOREIGN_OTHER = "国外其他"; private String FOREIGN = "国外"; private IpInfo buildDefaultIpInfo(String nation, String other) { IpInfo ipInfo = new IpInfo(); ipInfo.setNation(nation); ipInfo.setProvince(other); ipInfo.setCity(other); ipInfo.setChannel(other); return ipInfo; } private IpInfo findChinaIp(long ip) { int low = 0, high = m_starts.length - 1, mid; while (low <= high) { mid = (low + high) / 2; if (ip >= m_starts[mid] && ip <= m_ends[mid]) { IpInfo ipInfo = new IpInfo(); Area area = m_areas.get(m_areaIds[mid]); if (area != null) { ipInfo.setNation(area.getNation()); ipInfo.setProvince(area.getProvince()); ipInfo.setCity(area.getCity()); } else { ipInfo.setNation(OTHER); ipInfo.setProvince(OTHER); ipInfo.setCity(OTHER); } Corporation corp = m_corps.get(m_corpIds[mid]); if (corp != null) { ipInfo.setChannel(corp.getName()); } else { ipInfo.setChannel(OTHER); } return ipInfo; } else if (ip < m_starts[mid]) { high = mid - 1; } else { low = mid + 1; } } return null; } private IpInfo findForeignIp(long ip) { int low = 0, high = m_foreignStarts.length - 1, mid; while (low <= high) { mid = (low + high) / 2; if (ip >= m_foreignStarts[mid] && ip <= m_foreignEnds[mid]) { IpInfo ipInfo = new IpInfo(); Area area = m_foreignAreas.get(m_foreignAreaIds[mid]); if (area != null) { ipInfo.setNation(area.getNation()); ipInfo.setProvince(area.getProvince()); ipInfo.setCity(area.getCity()); } else { ipInfo.setNation(FOREIGN); ipInfo.setProvince(FOREIGN_OTHER); ipInfo.setCity(FOREIGN_OTHER); } ipInfo.setChannel(FOREIGN_OTHER); return ipInfo; } else if (ip < m_foreignStarts[mid]) { high = mid - 1; } else { low = mid + 1; } } return buildDefaultIpInfo(FOREIGN, FOREIGN_OTHER); } private IpInfo findIpInfo(long ip) { IpInfo ipInfo = findChinaIp(ip); if (ipInfo == null) { ipInfo = findForeignIp(ip); } return ipInfo; } public IpInfo findIpInfoByString(String ip) { try { String[] segments = ip.split("\\."); if (segments.length != 4) { return null; } long ip_num = Long.parseLong(segments[0]) << 24; ip_num += Integer.parseInt(segments[1]) << 16; ip_num += Integer.parseInt(segments[2]) << 8; ip_num += Integer.parseInt(segments[3]); return findIpInfo(ip_num); } catch (Exception e) { return null; } } private void initAreaMap(InputStream areaFile) { try { BufferedReader areaReader = new BufferedReader(new InputStreamReader(areaFile)); String line; String[] strs; int id; m_areas = new LinkedHashMap<Integer, Area>(); while ((line = areaReader.readLine()) != null) { strs = line.split(":"); id = Integer.parseInt(strs[1]); String[] areaStr = strs[0].split("\\|"); Area area = new Area(); area.setAreaId(id); area.setNation(areaStr[0]); area.setProvince(areaStr[1]); area.setCity(areaStr[2]); m_areas.put(id, area); } areaReader.close(); } catch (Exception e) { Cat.logError(e); } } private void initCorpMap(InputStream corpFile) { try { BufferedReader corpReader = new BufferedReader(new InputStreamReader(corpFile)); String line; String[] strs; int id; m_corps = new LinkedHashMap<Integer, Corporation>(); while ((line = corpReader.readLine()) != null) { strs = line.split(":"); Corporation corp = new Corporation(); id = Integer.parseInt(strs[1]); corp.setCorporationId(id); corp.setName(strs[0]); m_corps.put(id, corp); } corpReader.close(); } catch (Exception e) { Cat.logError(e); } } private void initForeignAreaMap(InputStream areaFile) { try { BufferedReader areaReader = new BufferedReader(new InputStreamReader(areaFile)); String line; String[] strs; String[] ids; m_foreignAreas = new LinkedHashMap<Integer, Area>(); while ((line = areaReader.readLine()) != null) { strs = line.split(":"); ids = strs[1].split(","); Area area = new Area(); area.setNation("国外"); area.setProvince(strs[0]); area.setCity(strs[0]); for (String id : ids) { m_foreignAreas.put(Integer.valueOf(id), area); } } areaReader.close(); } catch (Exception e) { Cat.logError(e); } } public void initForeignIpTable(InputStream ipFile) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(ipFile)); int size = Integer.parseInt(reader.readLine()); String line; String[] strs; m_foreignStarts = new long[size]; m_foreignEnds = new long[size]; m_foreignAreaIds = new int[size]; for (int i = 0; i < size; i++) { line = reader.readLine(); strs = line.split(":"); m_foreignStarts[i] = Long.parseLong(strs[0]); m_foreignEnds[i] = Long.parseLong(strs[1]); m_foreignAreaIds[i] = Integer.parseInt(strs[2]); } } catch (IOException e) { Cat.logError(e); } finally { try { reader.close(); } catch (Exception e) { Cat.logError(e); } } } @Override public void initialize() throws InitializationException { InputStream areaFile = IpService.class.getClassLoader().getResourceAsStream("ip/area_china"); InputStream corpFile = IpService.class.getClassLoader().getResourceAsStream("ip/corp_china"); InputStream ipFile = IpService.class.getClassLoader().getResourceAsStream("ip/iptable_china"); initAreaMap(areaFile); initCorpMap(corpFile); initIpTable(ipFile); InputStream foreignAreaFile = IpService.class.getClassLoader().getResourceAsStream("ip/area_foreign"); InputStream foreignIpFile = IpService.class.getClassLoader().getResourceAsStream("ip/iptable_foreign"); initForeignAreaMap(foreignAreaFile); initForeignIpTable(foreignIpFile); } public void initIpTable(InputStream ipFile) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(ipFile)); int size = Integer.parseInt(reader.readLine()); String line; String[] strs; m_starts = new long[size]; m_ends = new long[size]; m_areaIds = new int[size]; m_corpIds = new int[size]; for (int i = 0; i < size; i++) { line = reader.readLine(); strs = line.split(":"); m_starts[i] = Long.parseLong(strs[0]); m_ends[i] = Long.parseLong(strs[1]); m_areaIds[i] = Integer.parseInt(strs[2]); m_corpIds[i] = Integer.parseInt(strs[3]); } } catch (IOException e) { Cat.logError(e); } finally { try { reader.close(); } catch (Exception e) { Cat.logError(e); } } } public static class Area { private Integer m_areaId; private String m_city; private String m_nation; private String m_province; public Integer getAreaId() { return m_areaId; } public void setAreaId(Integer areaId) { m_areaId = areaId; } public String getCity() { return m_city; } public void setCity(String city) { m_city = city; } public String getNation() { return m_nation; } public void setNation(String nation) { m_nation = nation; } public String getProvince() { return m_province; } public void setProvince(String province) { m_province = province; } } public static class Corporation { private Integer m_corporationId; private String m_name; public Integer getCorporationId() { return m_corporationId; } public void setCorporationId(Integer corporationId) { m_corporationId = corporationId; } public String getName() { return m_name; } public void setName(String name) { m_name = name; } } public static class IpInfo { private String m_channel; private String m_city; private String m_nation; private String m_province; private String m_longitude; private String m_latitude; public String getChannel() { return m_channel; } public void setChannel(String name) { m_channel = name; } public String getCity() { return m_city; } public void setCity(String city) { m_city = city; } public String getNation() { return m_nation; } public void setNation(String nation) { m_nation = nation; } public String getProvince() { return m_province; } public void setProvince(String province) { m_province = province; } public String getLongitude() { return m_longitude; } public void setLongitude(String longitude) { m_longitude = longitude; } public String getLatitude() { return m_latitude; } public void setLatitude(String latitude) { m_latitude = latitude; } } }
dianping/cat
cat-core/src/main/java/com/dianping/cat/service/IpService.java
220
M tags: Array, Greedy, Pruning, Adjacency Matrix, Graph time: O(n) space: O(1) 有n个人, 其中有个人是celebrity, 注意必要条件 `Celeb knows nobody; Everyone else knows the celeb`. 找到celeb Note: the relationship graph can be presented as an adjacency matrix, but graph is not directly used in this problem. #### Pruning - Given assumption: 1) `only 1 celebrity`, 2) person k, who knows nobody ahead of him or after him. - if first pass finds candidate, `person k`, it means: - person [0, k-1] are not celebrity: they know a previous or current candidate - person k knows no one between [k + 1, n): k+1 to n-1 can not be the celebrity either. - person k is just the last standing possible celebrity - second pass validation: we do not know if `knows(celeb, [0~k-1] )`. Do a final O(n) check - time:O(n), space O(1) - DO NOT: Brutle compare all -> all: O(n^2) handshakes. ##### 思考逻辑 - 先写出来[0 ~ n - 1], 最简单的方式 O(n^2) 检查, 记录每个人的状态. - 逐渐发现, 因为 celeb 谁都不会认识, 那么当任何candidate knows anyone, 他自身就不是celeb. - 我们可以greedy地, 一旦fail一个, 就立刻假设下一个是celeb candidate - 最终还是要检查一遍, 避免错漏. - 想一下happy case: 如果 celeb=0, 那么 know(celeb, i) 永远都是false, 然后 celeb一直保持0, 坚持到verify所有人. ``` /* Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n). There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1. Example 1: Input: graph = [ [1,1,0], [0,1,0], [1,1,1] ] Output: 1 Explanation: There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. Example 2: Input: graph = [ [1,0,1], [1,1,0], [0,1,1] ] Output: -1 Explanation: There is no celebrity. Note: The directed graph is represented as an adjacency matrix, which is an n x n matrix where a[i][j] = 1 means person i knows person j while a[i][j] = 0 means the contrary. Remember that you won't have direct access to the adjacency matrix. */ /* The knows API is defined in the parent class Relation. boolean knows(int a, int b); */ public class Solution extends Relation { public int findCelebrity(int n) { if (n <= 1) return -1; int celeb = 0; // first pass: find 1 possible candidate k, by pruning [0~k] candidates and (k+1~n) for (int i = 0; i < n; i++) { if (celeb != i && knows(celeb, i)) celeb = i; } // second pass: simple validate if celeb is real for (int i = 0; i < n; i++) { if (celeb != i && !(knows(i, celeb) && !knows(celeb, i))) return -1; } return celeb; } } ```
awangdev/leet-code
Java/277. Find the Celebrity.java
221
package org.nutz.dao; import java.lang.reflect.Array; import java.util.Collection; import org.nutz.dao.entity.Entity; import org.nutz.dao.entity.MappingField; import org.nutz.dao.impl.SimpleNesting; import org.nutz.dao.jdbc.ValueAdaptor; import org.nutz.dao.pager.Pager; import org.nutz.dao.sql.Criteria; import org.nutz.dao.sql.GroupBy; import org.nutz.dao.sql.OrderBy; import org.nutz.dao.sql.Pojo; import org.nutz.dao.util.Daos; import org.nutz.dao.util.cnd.SimpleCondition; import org.nutz.dao.util.cri.Exps; import org.nutz.dao.util.cri.NestExps; import org.nutz.dao.util.cri.SimpleCriteria; import org.nutz.dao.util.cri.SqlExpression; import org.nutz.dao.util.cri.SqlExpressionGroup; import org.nutz.dao.util.lambda.LambdaQuery; import org.nutz.dao.util.lambda.PFun; import org.nutz.lang.Lang; import org.nutz.lang.Strings; import org.nutz.lang.segment.CharSegment; import org.nutz.lang.util.Callback2; /** * 是 Condition 的一个实现,这个类给你比较方便的方法来构建 Condition 接口的实例。 * * <h4>在 Dao 接口中使用</h4><br> * * 比如一个通常的查询: * <p> * List<Pet> pets = dao.query(Pet.class, * Cnd.where("name","LIKE","B%").asc("name"), null); * * <h4>链式赋值示例</h4><br> * Cnd.where("id", ">", 34).and("name","LIKE","T%").asc("name"); <br> * 相当于<br> * WHERE id>34 AND name LIKE 'T%' ORDER BY name ASC * <p> * Cnd.orderBy().desc("id"); <br> * 相当于<br> * ORDER BY id DESC * * <p/> * <b>带括号的条件语句<b/> where (name="wendal" or age<18) and location != "地球" * <p/> * <code>Cnd.where(Cnd.exps("name", "=", "wendal").or("age", "<", 18)).and("location", "!=", "地球")</code> * * <p/> * <b>静态条件,直接拼入sql,不做任何转义. Oracle的日期传Date对象,而非用to_date等数据库方法</b> * <p/> * <code>Cnd.where(new Static("ct < to_date('2015-06-26')")).and(...........) </code> * <p/> * * <p/> * <b>between用法</b> * <p/> * <code>Cnd.where("age", "between", new Object[]{19,29}).and(...........) </code> * <p/> * * <h4 style=color:red>你还需要知道的是:</h4><br> * <ul> * <li>你设置的字段名,是 java 的字段名 -- 如果 Entity 里有,那么会被转换成数据库字段名 * <li>如果你设置的是 entity 中不存在的 java 字段名,则被认为是数据库字段名,将直接使用 * <li>你的值,如果是字符串,或者其他类字符串对象(某种 CharSequence),那么在转换成 SQL 时,会正确被单引号包裹 * <li>你的值如果是不可理解的自定义对象,会被转化成字符串处理 * </ul> * * @author zozoh([email protected]) * @author 蛋蛋 [[email protected]] * @see org.nutz.dao.Condition */ public class Cnd implements OrderBy, Criteria, GroupBy { private static final long serialVersionUID = 1L; /** * 用字符串和参数格式化出一个条件语句,注意,不会抹除特殊字符 * * @param format * sql条件 * @param args * 参数 * @return 条件对象 */ public static Condition format(String format, Object... args) { return Strings.isBlank(format) ? null : new SimpleCondition(format, args); } /*** * 直接用字符串生成一个条件对象 * * @param str * sql条件 * @return 条件对象 */ public static Condition wrap(String str) { return Strings.isBlank(str) ? null : new SimpleCondition(str); } /** * 使用CharSegment拼装一个条件对象 * * @param sql * sql模板 * @param value * 参数 * @return 条件对象 * @see org.nutz.lang.segment.CharSegment */ public static Condition wrap(String sql, Object value) { return Strings.isBlank(sql) ? null : new SimpleCondition(new CharSegment(sql).setBy(value)); } /** * 生成一个条件表达式 * * @param name * Java属性或字段名称 * @param op * 操作符,可以是 = like 等等 * @param value * 参数值. * @return 条件表达式 */ public static SqlExpression exp(String name, String op, Object value) { if (value != null && value instanceof Nesting) { return NestExps.create(name, op, (Nesting) value); } return Exps.create(name, op, value); } /** * 生成一个条件表达式 * * @param name * lambda表达式 * @param op * 操作符,可以是 = like 等等 * @param value * 参数值. * @return 条件表达式 */ public static <T> SqlExpression exp(PFun<T, ?> name, String op, Object value) { if (value != null && value instanceof Nesting) { return NestExps.create(name, op, (Nesting) value); } return Exps.create(name, op, value); } /** * 生成一个条件表达式组 * * @param name * Java属性或字段名称 * @param op * 操作符,可以是 = like 等等 * @param value * 参数值. * @return 条件表达式组 */ public static SqlExpressionGroup exps(String name, String op, Object value) { return exps(exp(name, op, value)); } /** * 生成一个条件表达式组 * * @param name * lambda表达式 * @param op * 操作符,可以是 = like 等等 * @param value * 参数值. * @return 条件表达式组 */ public static <T> SqlExpressionGroup exps(PFun<T, ?> name, String op, Object value) { return exps(exp(name, op, value)); } /** * 将一个条件表达式封装为条件表达式组 * * @param exp * 原本的条件表达式 * @return 条件表达式组 */ public static SqlExpressionGroup exps(SqlExpression exp) { return new SqlExpressionGroup().and(exp); } /** * 生成一个新的Cnd实例 * * @param name * java属性或字段名称, 推荐用Java属性 * @param op * 操作符,可以是= like等等 * @param value * 参数值. 如果操作符是between,参数值需要是new Object[]{12,39}形式 * @return Cnd实例 */ public static Cnd where(String name, String op, Object value) { return new Cnd(Cnd.exp(name, op, value)); } /** * 生成一个新的Cnd实例 * * @param name * lambda表达式 * @param op * 操作符,可以是= like等等 * @param value * 参数值. 如果操作符是between,参数值需要是new Object[]{12,39}形式 * @return Cnd实例 */ public static <T> Cnd where(PFun<T, ?> name, String op, Object value) { return new Cnd(Cnd.exp(name, op, value)); } /** * 用一个条件表达式构建一个Cnd实例 * * @param e * 条件表达式 * @return Cnd实例 */ public static Cnd where(SqlExpression e) { return new Cnd(e); } /** * 生成一个简单条件对象 */ public static SimpleCriteria cri() { return new SimpleCriteria(); } /** * 单纯生成一个Orderby条件 * * @return OrderBy实例 */ public static OrderBy orderBy() { return new Cnd(); } /** * @return 一个 Cnd 的实例 * @deprecated Since 1.b.50 不推荐使用这个函数构建 Cnd 的实例,因为看起来语意不明的样子 */ @Deprecated public static Cnd limit() { return new Cnd(); } /** * @return 一个 Cnd 的实例 */ public static Cnd NEW() { return new Cnd(); } /** * 用SimpleCriteria生成一个Cnd实例 * * @param cri * SimpleCriteria实例 * @return Cnd实例 */ public static Cnd byCri(SimpleCriteria cri) { return new Cnd().setCri(cri); } /*------------------------------------------------------------------*/ protected SimpleCriteria cri; protected Cnd() { cri = new SimpleCriteria(); } private Cnd setCri(SimpleCriteria cri) { this.cri = cri; return this; } /** * 获取内部的where属性 * * @return SimpleCriteria实例 */ public SimpleCriteria getCri() { return cri; } protected Cnd(SqlExpression exp) { this(); cri.where().and(exp); } /** * 按Java属性/字段属性进行升序. <b>不进行SQL特殊字符抹除<b/> cnd.asc("age") * * @param name * Java属性/字段属性 */ @Override public OrderBy asc(String name) { cri.asc(name); return this; } /** * 按Java属性/字段属性进行升序. <b>不进行SQL特殊字符抹除<b/> cnd.asc("age") * * @param name * Lambda表达式 */ @Override public <T> OrderBy asc(PFun<T, ?> name) { return asc(LambdaQuery.resolve(name)); } /** * 按Java属性/字段属性进行降序. <b>不进行SQL特殊字符抹除<b/> cnd.desc("age") * * @param name * Java属性/字段属性 */ @Override public OrderBy desc(String name) { cri.desc(name); return this; } /** * 按Java属性/字段属性进行降序. <b>不进行SQL特殊字符抹除<b/> cnd.desc("age") * * @param name * Lambda表达式 */ @Override public <T> OrderBy desc(PFun<T, ?> name) { return desc(LambdaQuery.resolve(name)); } /** * 当dir为asc时判断为升序,否则判定为降序. cnd.orderBy("age", "asc") * * @param name * Java属性/字段属性 * @param dir * asc或其他 * @return OrderBy实例,事实上就是当前对象 */ @Override public OrderBy orderBy(String name, String dir) { if ("asc".equalsIgnoreCase(dir)) { this.asc(name); } else { this.desc(name); } return this; } /** * 当dir为asc时判断为升序,否则判定为降序. cnd.orderBy("age", "asc") * * @param name * Lambda表达式 * @param dir * asc或其他 * @return OrderBy实例,事实上就是当前对象 */ @Override public <T> OrderBy orderBy(PFun<T, ?> name, String dir) { return orderBy(LambdaQuery.resolve(name),dir); } /** * Cnd.where(...).and(Cnd.exp(.........)) 或 * Cnd.where(...).and(Cnd.exps(.........)) * * @param exp * 条件表达式 * @return 当前对象,用于链式调用 */ public Cnd and(SqlExpression exp) { cri.where().and(exp); return this; } /** * Cnd.where(...).and("age", "<", 40) * * @param name * Java属性或字段名称,推荐用Java属性,如果有的话 * @param op * 操作符,可以是 = like等 * @param value * 参数值, 如果是between的话需要传入new Object[]{19,28} * @return 当前对象,用于链式调用 */ public Cnd and(String name, String op, Object value) { return and(Cnd.exp(name, op, value)); } /** * Cnd.where(...).and("age", "<", 40) * * @param name * Lambda表达式 * @param op * 操作符,可以是 = like等 * @param value * 参数值, 如果是between的话需要传入new Object[]{19,28} * @return 当前对象,用于链式调用 */ public <T> Cnd and(PFun<T, ?> name, String op, Object value) { return and(Cnd.exp(name, op, value)); } /** * Cnd.where(...).or(Cnd.exp(.........)) 或 * Cnd.where(...).or(Cnd.exps(.........)) * * @param exp * 条件表达式 * @return 当前对象,用于链式调用 */ public Cnd or(SqlExpression exp) { cri.where().or(exp); return this; } /** * Cnd.where(...).or("age", "<", 40) * * @param name * Java属性或字段名称,推荐用Java属性,如果有的话 * @param op * 操作符,可以是 = like等 * @param value * 参数值, 如果是between的话需要传入new Object[]{19,28} * @return 当前对象,用于链式调用 */ public Cnd or(String name, String op, Object value) { return or(Cnd.exp(name, op, value)); } /** * Cnd.where(...).or("age", "<", 40) * * @param name * Java属性或字段名称,推荐用Java属性,如果有的话 * @param op * 操作符,可以是 = like等 * @param value * 参数值, 如果是between的话需要传入new Object[]{19,28} * @return 当前对象,用于链式调用 */ public <T> Cnd or(PFun<T, ?> name, String op, Object value) { return or(Cnd.exp(name, op, value)); } /** * and一个条件表达式并且取非 * * @param exp * 条件表达式 * @return 当前对象,用于链式调用 */ public Cnd andNot(SqlExpression exp) { cri.where().and(exp.setNot(true)); return this; } /** * and一个条件,并且取非 * * @param name * Java属性或字段名称,推荐用Java属性,如果有的话 * @param op * 操作符,可以是 = like等 * @param value * 参数值, 如果是between的话需要传入new Object[]{19,28} * @return 当前对象,用于链式调用 */ public Cnd andNot(String name, String op, Object value) { return andNot(Cnd.exp(name, op, value)); } /** * and一个条件,并且取非 * * @param name * Lambda表达式 * @param op * 操作符,可以是 = like等 * @param value * 参数值, 如果是between的话需要传入new Object[]{19,28} * @return 当前对象,用于链式调用 */ public <T> Cnd andNot(PFun<T, ?> name, String op, Object value) { return andNot(Cnd.exp(name, op, value)); } /** * @see Cnd#andNot(SqlExpression) */ public Cnd orNot(SqlExpression exp) { cri.where().or(exp.setNot(true)); return this; } /** * @see Cnd#andNot(String, String, Object) */ public Cnd orNot(String name, String op, Object value) { return orNot(Cnd.exp(name, op, value)); } /** * @see Cnd#andNot(String, String, Object) */ public <T> Cnd orNot(PFun<T, ?> name, String op, Object value) { return orNot(Cnd.exp(name, op, value)); } /** * 获取分页对象,默认是null */ @Override public Pager getPager() { return cri.getPager(); } /** * 根据实体Entity将本对象转化为sql语句, 条件表达式中的name属性将转化为数据库字段名称 */ @Override public String toSql(Entity<?> en) { return cri.toSql(en); } /** * 判断两个Cnd是否相等 */ @Override public boolean equals(Object obj) { return cri.equals(obj); } /** * 直接转为SQL语句, 如果setPojo未曾调用, 条件表达式中的name属性未映射为数据库字段 */ @Override public String toString() { return cri.toString(); } /** * 关联的Pojo,可以用于toString时的name属性映射 */ @Override public void setPojo(Pojo pojo) { cri.setPojo(pojo); } /** * 获取已设置的Pojo, 默认为null */ @Override public Pojo getPojo() { return cri.getPojo(); } @Override public void joinSql(Entity<?> en, StringBuilder sb) { cri.joinSql(en, sb); } @Override public int joinAdaptor(Entity<?> en, ValueAdaptor[] adaptors, int off) { return cri.joinAdaptor(en, adaptors, off); } @Override public int joinParams(Entity<?> en, Object obj, Object[] params, int off) { return cri.joinParams(en, obj, params, off); } @Override public int paramCount(Entity<?> en) { return cri.paramCount(en); } /** * 获取Cnd中的where部分,注意,对SqlExpressionGroup的修改也会反映到Cnd中,因为是同一个对象 */ @Override public SqlExpressionGroup where() { return cri.where(); } /** * 分组 * * @param names * java属性或数据库字段名称 */ @Override public GroupBy groupBy(String... names) { cri.groupBy(names); return this; } /** * 分组 * * @param names * Lambda表达式 */ @Override public <T> GroupBy groupBy(PFun<T, ?>... names) { cri.groupBy(names); return this; } /** * 分组中的having条件 * * @param cnd * 条件语句 */ @Override public GroupBy having(Condition cnd) { cri.having(cnd); return this; } /** * 单独获取排序条件,建议使用asc或desc,而非直接取出排序条件. 取出的对象仅包含分组条件, 不包含where等部分 */ @Override public OrderBy getOrderBy() { return cri.getOrderBy(); } /** * 分页 * * @param pageNumber * 页数, 若小于1则代表全部记录 * @param pageSize * 每页数量 * @return 当前对象,用于链式调用 */ public Cnd limit(int pageNumber, int pageSize) { cri.setPager(pageNumber, pageSize); return this; } /** * 设置每页大小,并设置页数为1 * * @param pageSize * 每页大小 * @return 当前对象,用于链式调用 */ @Deprecated public Cnd limit(int pageSize) { cri.setPager(1, pageSize); return this; } /** * 直接设置分页对象, 可以new Pager或dao.createPager得到 * * @param pager * 分页对象 * @return 当前对象,用于链式调用 */ public Cnd limit(Pager pager) { cri.setPager(pager); return this; } protected static FieldMatcher dftFromFieldMatcher = new FieldMatcher().setIgnoreNull(true).setIgnoreZero(true); /** * 用默认规则(忽略零值和空值)生成Cnd实例 * * @param dao * Dao实例,不能为null * @param obj * 对象, 若为null,则返回值为null, 不可以是Class/字符串/数值/布尔类型 * @return Cnd实例 */ public static Cnd from(Dao dao, Object obj) { return from(dao, obj, dftFromFieldMatcher); } /** * 根据一个对象生成Cnd条件, FieldMatcher详细控制. * <p/> * <code>assertEquals(" WHERE name='wendal' AND age=0", Cnd.from(dao, pet, FieldMatcher.make("age|name", null, true).setIgnoreDate(true)).toString());</code> * * @param dao * Dao实例 * @param obj * 基对象,不可以是Class,字符串,数值和Boolean * @param matcher * 过滤字段属性, * 可配置哪些字段可用/不可用/是否忽略空值/是否忽略0值/是否忽略java.util.Date类及其子类的对象/是否忽略@Id所标注的主键属性/是否忽略 * \@Name 所标注的主键属性/是否忽略 \@Pk 所引用的复合主键 * @return Cnd条件 */ public static Cnd from(Dao dao, Object obj, FieldMatcher matcher) { final SqlExpressionGroup exps = new SqlExpressionGroup(); boolean re = Daos.filterFields(obj, matcher, dao, new Callback2<MappingField, Object>() { @Override public void invoke(MappingField mf, Object val) { exps.and(mf.getName(), "=", val); } }); if (re) return Cnd.where(exps); return null; } /** * 若value为null/空白字符串/空集合/空数组,则本条件不添加. * * @see Cnd#and(String, String, Object) */ public Cnd andEX(String name, String op, Object value) { return and(Cnd.expEX(name, op, value)); } /** * 若value为null/空白字符串/空集合/空数组,则本条件不添加. * * @see Cnd#and(String, String, Object) */ public <T> Cnd andEX(PFun<T, ?> name, String op, Object value) { return and(Cnd.expEX(name, op, value)); } /** * 若value为null/空白字符串/空集合/空数组,则本条件不添加. * * @see Cnd#or(String, String, Object) */ public Cnd orEX(String name, String op, Object value) { return or(Cnd.expEX(name, op, value)); } /** * 若value为null/空白字符串/空集合/空数组,则本条件不添加. * * @see Cnd#or(String, String, Object) */ public <T> Cnd orEX(PFun<T, ?> name, String op, Object value) { return or(Cnd.expEX(name, op, value)); } public static SqlExpression expEX(String name, String op, Object value) { if (_ex(value)) return null; return Cnd.exp(name, op, value); } public static <T> SqlExpression expEX(PFun<T, ?> name, String op, Object value) { return expEX(LambdaQuery.resolve(name),op,value); } public static SqlExpression leftLikeEX(String name, Object value) { if (_ex(value)) return null; return Cnd.exp(name, "like", String.format("%%%s", value)); } public static <T> SqlExpression leftLikeEX(PFun<T, ?> name, Object value) { return leftLikeEX(LambdaQuery.resolve(name), value); } public static SqlExpression rightLikeEX(String name, Object value) { if (_ex(value)) return null; return Cnd.exp(name, "like", String.format("%s%%", value)); } public static <T> SqlExpression rightLikeEX(PFun<T, ?> name, Object value) { return rightLikeEX(LambdaQuery.resolve(name), value); } public static SqlExpression likeEX(String name, Object value) { if (_ex(value)) return null; return Cnd.exp(name, "like", String.format("%%%s%%", value)); } public static <T> SqlExpression likeEX(PFun<T, ?> name, Object value) { return likeEX(LambdaQuery.resolve(name),value); } @SuppressWarnings("rawtypes") public static boolean _ex(Object value) { return value == null || (value instanceof CharSequence && Strings.isBlank((CharSequence) value)) || (value instanceof Collection && ((Collection) value).isEmpty()) || (value.getClass().isArray() && Array.getLength(value) == 0); } @Override public GroupBy getGroupBy() { return cri.getGroupBy(); } /** * 构造一个可嵌套条件,需要dao支持才能映射类与表和属性与列 */ public static Nesting nst(Dao dao) { return new SimpleNesting(dao); } /** * 克隆当前Cnd实例 * * @return 一模一样的兄弟 */ @Override public Cnd clone() { return Lang.fromBytes(Lang.toBytes(this), Cnd.class); } /** * 仅拷贝where条件, 不拷贝排序/分组/分页 */ public Cnd cloneWhere() { return Cnd.where(this.cri.where().clone()); } }
nutzam/nutz
src/org/nutz/dao/Cnd.java
223
/** * File: heap_sort.java * Created Time: 2023-05-26 * Author: krahets ([email protected]) */ package chapter_sorting; import java.util.Arrays; public class heap_sort { /* 堆的长度为 n ,从节点 i 开始,从顶至底堆化 */ public static void siftDown(int[] nums, int n, int i) { while (true) { // 判断节点 i, l, r 中值最大的节点,记为 ma int l = 2 * i + 1; int r = 2 * i + 2; int ma = i; if (l < n && nums[l] > nums[ma]) ma = l; if (r < n && nums[r] > nums[ma]) ma = r; // 若节点 i 最大或索引 l, r 越界,则无须继续堆化,跳出 if (ma == i) break; // 交换两节点 int temp = nums[i]; nums[i] = nums[ma]; nums[ma] = temp; // 循环向下堆化 i = ma; } } /* 堆排序 */ public static void heapSort(int[] nums) { // 建堆操作:堆化除叶节点以外的其他所有节点 for (int i = nums.length / 2 - 1; i >= 0; i--) { siftDown(nums, nums.length, i); } // 从堆中提取最大元素,循环 n-1 轮 for (int i = nums.length - 1; i > 0; i--) { // 交换根节点与最右叶节点(交换首元素与尾元素) int tmp = nums[0]; nums[0] = nums[i]; nums[i] = tmp; // 以根节点为起点,从顶至底进行堆化 siftDown(nums, i, 0); } } public static void main(String[] args) { int[] nums = { 4, 1, 3, 1, 5, 2 }; heapSort(nums); System.out.println("堆排序完成后 nums = " + Arrays.toString(nums)); } }
krahets/hello-algo
codes/java/chapter_sorting/heap_sort.java
225
package com.taobao.arthas.core.view; import com.taobao.arthas.core.util.StringUtils; import java.util.ArrayList; import java.util.List; /** * 阶梯缩进控件 * Created by vlinux on 15/5/8. */ public class LadderView implements View { // 分隔符 private static final String LADDER_CHAR = "`-"; // 缩进符 private static final String STEP_CHAR = " "; // 缩进长度 private static final int INDENT_STEP = 2; private final List<String> items = new ArrayList<String>(); @Override public String draw() { final StringBuilder ladderSB = new StringBuilder(); int deep = 0; for (String item : items) { // 第一个条目不需要分隔符 if (deep == 0) { ladderSB .append(item) .append("\n"); } // 其他的需要添加分隔符 else { ladderSB .append(StringUtils.repeat(STEP_CHAR, deep * INDENT_STEP)) .append(LADDER_CHAR) .append(item) .append("\n"); } deep++; } return ladderSB.toString(); } /** * 添加一个项目 * * @param item 项目 * @return this */ public LadderView addItem(String item) { items.add(item); return this; } }
alibaba/arthas
core/src/main/java/com/taobao/arthas/core/view/LadderView.java
226
package com.zheng.common.base; /** * 统一返回结果类 * Created by shuzheng on 2017/2/18. */ public class BaseResult { /** * 状态码:1成功,其他为失败 */ public int code; /** * 成功为success,其他为失败原因 */ public String message; /** * 数据结果集 */ public Object data; public BaseResult(int code, String message, Object data) { this.code = code; this.message = message; this.data = data; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
shuzheng/zheng
zheng-common/src/main/java/com/zheng/common/base/BaseResult.java
227
package com.xkcoding.codegen.entity; import lombok.Data; /** * <p> * 列属性: https://blog.csdn.net/lkforce/article/details/79557482 * </p> * * @author yangkai.shen * @date Created in 2019-03-22 09:46 */ @Data public class ColumnEntity { /** * 列表 */ private String columnName; /** * 数据类型 */ private String dataType; /** * 备注 */ private String comments; /** * 驼峰属性 */ private String caseAttrName; /** * 普通属性 */ private String lowerAttrName; /** * 属性类型 */ private String attrType; /** * jdbc类型 */ private String jdbcType; /** * 其他信息 */ private String extra; }
xkcoding/spring-boot-demo
demo-codegen/src/main/java/com/xkcoding/codegen/entity/ColumnEntity.java
229
/* * 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.http; import androidx.annotation.NonNull; import okhttp3.HttpUrl; /** * ================================================ * 针对于 BaseUrl 在 App 启动时不能确定,需要请求服务器接口动态获取的应用场景 * <p> * Created by JessYan on 11/07/2017 14:58 * <a href="mailto:[email protected]">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * ================================================ */ public interface BaseUrl { /** * 在调用 Retrofit API 接口之前,使用 Okhttp 或其他方式,请求到正确的 BaseUrl 并通过此方法返回 * * @return */ @NonNull HttpUrl url(); }
JessYanCoding/MVPArms
arms/src/main/java/com/jess/arms/http/BaseUrl.java
230
package org.ansj.domain; import org.ansj.util.MathUtil; import org.nlpcn.commons.lang.util.StringUtil; import java.io.Serializable; import java.util.List; import java.util.Map; public class Term implements Serializable { /** * */ private static final long serialVersionUID = 1L; // 当前词 private String name; // private String realName; // 当前词的起始位置 private int offe; // 词性列表 private TermNatures termNatures = TermNatures.NULL; // 词性列表 private AnsjItem item = AnsjItem.NULL; // 同一行内数据 private Term next; // 分数 private double score = 0; // 本身分数 private double selfScore = 1; // 起始位置 private Term from; // 到达位置 private Term to; // 本身这个term的词性.需要在词性识别之后才会有值,默认是空 private Nature nature = Nature.NULL; //是否是一个新词 private boolean newWord; //同义词 private List<String> synonyms; private List<Term> subTerm = null; public Term(String name, int offe, AnsjItem item) { super(); this.name = name; this.offe = offe; this.item = item; if (item.termNatures != null) { this.termNatures = item.termNatures; if (termNatures.nature != null) { this.nature = termNatures.nature; } } } public Term(String name, int offe, TermNatures termNatures) { super(); this.name = name; this.offe = offe; this.termNatures = termNatures; if (termNatures.nature != null) { this.nature = termNatures.nature; } } public Term(String name, int offe, String natureStr, int natureFreq) { super(); this.name = name; this.offe = offe; TermNature termNature = new TermNature(natureStr, natureFreq); this.nature = termNature.nature; this.termNatures = new TermNatures(termNature); } // 可以到达的位置 public int toValue() { return offe + name.length(); } public int getOffe() { return offe; } public void setOffe(int offe) { this.offe = offe; } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * 核心构建最优的路径 * * @param from * @param relationMap */ public void setPathScore(Term from, Map<String, Double> relationMap) { // 维特比进行最优路径的构建 double score = MathUtil.compuScore(from, this, relationMap); if (this.from == null || this.score == 0 || this.score >= score) { this.setFromAndScore(from, score); } } /** * 核心分数的最优的路径,越小越好 * * @param from */ public void setPathSelfScore(Term from, boolean asc) { double score = this.selfScore + from.score; // 维特比进行最优路径的构建 if (this.from == null) { this.setFromAndScore(from, score); } else { if ((this.score > score) == asc) { this.setFromAndScore(from, score); } } } private void setFromAndScore(Term from, double score) { this.from = from; this.score = score; } /** * 进行term合并 * * @param to */ public Term merage(Term to) { this.name = this.name + to.getName(); if (StringUtil.isNotBlank(this.realName) && StringUtil.isNotBlank(to.getRealName())) { this.realName = this.realName + to.getRealName(); } this.setTo(to.to); return this; } /** * 进行term合并,能合并空白字符 * * @param to */ public Term merageWithBlank(Term to) { this.name = this.name + to.getName(); this.realName = this.realName + to.getRealName(); this.setTo(to.to); return this; } /** * 更新偏移量 * * @param offe */ public void updateOffe(int offe) { this.offe += offe; } public Term next() { return next; } /** * 返回他自己 * * @param next 设置他的下一个 * @return */ public Term setNext(Term next) { this.next = next; return this; } public Term from() { return from; } public Term to() { return to; } public void setFrom(Term from) { this.from = from; } public void setTo(Term to) { this.to = to; } /** * 获得这个term的所有词性 * * @return */ public TermNatures termNatures() { return termNatures; } public void setNature(Nature nature) { this.nature = nature; } /** * 获得这个词的词性.词性计算后才可生效 * * @return */ public Nature natrue() { return nature; } public String getNatureStr() { return nature.natureStr; } @Override public String toString() { if ("null".equals(nature.natureStr)) { return this.getRealName(); } return this.getRealName() + "/" + nature.natureStr; } /** * 将term的所有分数置为0 */ public void clearScore() { this.score = 0; this.selfScore = 0; } public void setSubTerm(List<Term> subTerm) { this.subTerm = subTerm; } public List<Term> getSubTerm() { return subTerm; } public String getRealName() { if (realName == null) { return name; } return realName; } public String getRealNameIfnull() { return realName; } public void setRealName(String realName) { this.realName = realName; } public double score() { return this.score; } public void score(double score) { this.score = score; } public double selfScore() { return this.selfScore; } public void selfScore(double selfScore) { this.selfScore = selfScore; } public AnsjItem item() { return this.item; } public boolean isNewWord() { return newWord; } public void setNewWord(boolean newWord) { this.newWord = newWord; } public void updateTermNaturesAndNature(TermNatures termNatures) { this.termNatures = termNatures; this.nature = termNatures.nature; } public List<String> getSynonyms() { return synonyms; } public void setSynonyms(List<String> synonyms) { this.synonyms = synonyms; } }
NLPchina/ansj_seg
src/main/java/org/ansj/domain/Term.java
231
/** * IK 中文分词 版本 5.0 * IK Analyzer release 5.0 * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * 源代码由林良益([email protected])提供 * 版权声明 2012,乌龙茶工作室 * provided by Linliangyi and copyright 2012 by Oolong studio * * 字符集识别工具类 */ package org.wltea.analyzer.core; /** * * 字符集识别工具类 */ class CharacterUtil { public static final int CHAR_USELESS = 0; public static final int CHAR_ARABIC = 0X00000001; public static final int CHAR_ENGLISH = 0X00000002; public static final int CHAR_CHINESE = 0X00000004; public static final int CHAR_OTHER_CJK = 0X00000008; /** * 识别字符类型 * @param input * @return int CharacterUtil定义的字符类型常量 */ static int identifyCharType(char input){ if(input >= '0' && input <= '9'){ return CHAR_ARABIC; }else if((input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z')){ return CHAR_ENGLISH; }else { Character.UnicodeBlock ub = Character.UnicodeBlock.of(input); if(ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A){ //目前已知的中文字符UTF-8集合 return CHAR_CHINESE; }else if(ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS //全角数字字符和日韩字符 //韩文字符集 || ub == Character.UnicodeBlock.HANGUL_SYLLABLES || ub == Character.UnicodeBlock.HANGUL_JAMO || ub == Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO //日文字符集 || ub == Character.UnicodeBlock.HIRAGANA //平假名 || ub == Character.UnicodeBlock.KATAKANA //片假名 || ub == Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS){ return CHAR_OTHER_CJK; } } //其他的不做处理的字符 return CHAR_USELESS; } /** * 进行字符规格化(全角转半角,大写转小写处理) * @param input * @return char */ static char regularize(char input,boolean lowercase){ if (input == 12288) { input = (char) 32; }else if (input > 65280 && input < 65375) { input = (char) (input - 65248); }else if (input >= 'A' && input <= 'Z' && lowercase) { input += 32; } return input; } }
infinilabs/analysis-ik
core/src/main/java/org/wltea/analyzer/core/CharacterUtil.java
232
/* * Copyright 2019-2020 Zheng Jie * * 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 me.zhengjie.aspect; import lombok.extern.slf4j.Slf4j; import me.zhengjie.domain.SysLog; import me.zhengjie.service.SysLogService; import me.zhengjie.utils.RequestHolder; import me.zhengjie.utils.SecurityUtils; import me.zhengjie.utils.StringUtils; import me.zhengjie.utils.ThrowableUtil; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; /** * @author Zheng Jie * @date 2018-11-24 */ @Component @Aspect @Slf4j public class LogAspect { private final SysLogService sysLogService; ThreadLocal<Long> currentTime = new ThreadLocal<>(); public LogAspect(SysLogService sysLogService) { this.sysLogService = sysLogService; } /** * 配置切入点 */ @Pointcut("@annotation(me.zhengjie.annotation.Log)") public void logPointcut() { // 该方法无方法体,主要为了让同类中其他方法使用此切入点 } /** * 配置环绕通知,使用在方法logPointcut()上注册的切入点 * * @param joinPoint join point for advice */ @Around("logPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { Object result; currentTime.set(System.currentTimeMillis()); result = joinPoint.proceed(); SysLog sysLog = new SysLog("INFO",System.currentTimeMillis() - currentTime.get()); currentTime.remove(); HttpServletRequest request = RequestHolder.getHttpServletRequest(); sysLogService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request),joinPoint, sysLog); return result; } /** * 配置异常通知 * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "logPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { SysLog sysLog = new SysLog("ERROR",System.currentTimeMillis() - currentTime.get()); currentTime.remove(); sysLog.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes()); HttpServletRequest request = RequestHolder.getHttpServletRequest(); sysLogService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint)joinPoint, sysLog); } public String getUsername() { try { return SecurityUtils.getCurrentUsername(); }catch (Exception e){ return ""; } } }
elunez/eladmin
eladmin-logging/src/main/java/me/zhengjie/aspect/LogAspect.java
234
package com.blankj.subutil.util; import androidx.collection.SimpleArrayMap; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 16/11/16 * desc : 拼音相关工具类 * </pre> */ public final class PinyinUtils { private PinyinUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * 汉字转拼音 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String ccs2Pinyin(final CharSequence ccs) { return ccs2Pinyin(ccs, ""); } /** * 汉字转拼音 * * @param ccs 汉字字符串(Chinese characters) * @param split 汉字拼音之间的分隔符 * @return 拼音 */ public static String ccs2Pinyin(final CharSequence ccs, final CharSequence split) { if (ccs == null || ccs.length() == 0) return null; StringBuilder sb = new StringBuilder(); for (int i = 0, len = ccs.length(); i < len; i++) { char ch = ccs.charAt(i); if (ch >= 0x4E00 && ch <= 0x9FA5) { int sp = (ch - 0x4E00) * 6; sb.append(pinyinTable.substring(sp, sp + 6).trim()); } else { sb.append(ch); } sb.append(split); } return sb.toString(); } /** * 获取第一个汉字首字母 * * @param ccs 汉字字符串(Chinese characters) * @return 拼音 */ public static String getPinyinFirstLetter(final CharSequence ccs) { if (ccs == null || ccs.length() == 0) return null; return ccs2Pinyin(String.valueOf(ccs.charAt(0))).substring(0, 1); } /** * 获取所有汉字的首字母 * * @param ccs 汉字字符串(Chinese characters) * @return 所有汉字的首字母 */ public static String getPinyinFirstLetters(final CharSequence ccs) { return getPinyinFirstLetters(ccs, ""); } /** * 获取所有汉字的首字母 * * @param ccs 汉字字符串(Chinese characters) * @param split 首字母之间的分隔符 * @return 所有汉字的首字母 */ public static String getPinyinFirstLetters(final CharSequence ccs, final CharSequence split) { if (ccs == null || ccs.length() == 0) return null; int len = ccs.length(); StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append(ccs2Pinyin(String.valueOf(ccs.charAt(i))).substring(0, 1)).append(split); } return sb.toString(); } /** * 根据名字获取姓氏的拼音 * * @param name 名字 * @return 姓氏的拼音 */ public static String getSurnamePinyin(final CharSequence name) { if (name == null || name.length() == 0) return null; if (name.length() >= 2) { CharSequence str = name.subSequence(0, 2); if (str.equals("澹台")) return "tantai"; else if (str.equals("尉迟")) return "yuchi"; else if (str.equals("万俟")) return "moqi"; else if (str.equals("单于")) return "chanyu"; } char ch = name.charAt(0); if (SURNAMES.containsKey(ch)) { return SURNAMES.get(ch); } if (ch >= 0x4E00 && ch <= 0x9FA5) { int sp = (ch - 0x4E00) * 6; return pinyinTable.substring(sp, sp + 6).trim(); } else { return String.valueOf(ch); } } /** * 根据名字获取姓氏的首字母 * * @param name 名字 * @return 姓氏的首字母 */ public static String getSurnameFirstLetter(final CharSequence name) { String surname = getSurnamePinyin(name); if (surname == null || surname.length() == 0) return null; return String.valueOf(surname.charAt(0)); } // 多音字姓氏映射表 private static final SimpleArrayMap<Character, String> SURNAMES; /** * 获取拼音对照表,对比过pinyin4j和其他方式,这样查表设计的好处就是读取快 * <p>当该类加载后会一直占有123KB的内存</p> * <p>如果你想存进文件,然后读取操作的话也是可以,但速度肯定没有这样空间换时间快,毕竟现在设备内存都很大</p> * <p>如需更多用法可以用pinyin4j开源库</p> */ private static final String pinyinTable; static { SURNAMES = new SimpleArrayMap<>(35); SURNAMES.put('乐', "yue"); SURNAMES.put('乘', "sheng"); SURNAMES.put('乜', "nie"); SURNAMES.put('仇', "qiu"); SURNAMES.put('会', "gui"); SURNAMES.put('便', "pian"); SURNAMES.put('区', "ou"); SURNAMES.put('单', "shan"); SURNAMES.put('参', "shen"); SURNAMES.put('句', "gou"); SURNAMES.put('召', "shao"); SURNAMES.put('员', "yun"); SURNAMES.put('宓', "fu"); SURNAMES.put('弗', "fei"); SURNAMES.put('折', "she"); SURNAMES.put('曾', "zeng"); SURNAMES.put('朴', "piao"); SURNAMES.put('查', "zha"); SURNAMES.put('洗', "xian"); SURNAMES.put('盖', "ge"); SURNAMES.put('祭', "zhai"); SURNAMES.put('种', "chong"); SURNAMES.put('秘', "bi"); SURNAMES.put('繁', "po"); SURNAMES.put('缪', "miao"); SURNAMES.put('能', "nai"); SURNAMES.put('蕃', "pi"); SURNAMES.put('覃', "qin"); SURNAMES.put('解', "xie"); SURNAMES.put('谌', "shan"); SURNAMES.put('适', "kuo"); SURNAMES.put('都', "du"); SURNAMES.put('阿', "e"); SURNAMES.put('难', "ning"); SURNAMES.put('黑', "he"); //noinspection StringBufferReplaceableByString pinyinTable = new StringBuilder(125412) .append("yi ding kao qi shang xia none wan zhang san shang xia ji bu yu mian gai chou chou zhuan qie pi shi shi qiu bing ye cong dong si cheng diu qiu liang diu you liang yan bing sang shu jiu ge ya qiang zhong ji jie feng guan chuan chan lin zhuo zhu none wan dan wei zhu jing li ju pie fu yi yi nai none jiu jiu tuo me yi none zhi wu zha hu fa le zhong ping pang qiao hu guai cheng cheng yi yin none mie jiu qi ye xi xiang gai diu none none shu none shi ji nang jia none shi none none mai luan none ru xi yan fu sha na gan none none none none qian zhi gui gan luan lin yi jue le none yu zheng shi shi er chu yu kui yu yun hu qi wu jing si sui gen gen ya xie ya qi ya ji tou wang kang ta jiao hai yi chan heng mu none xiang jing ting liang heng jing ye qin bo you xie dan lian duo wei ren ren ji none wang yi shen ren le ding ze jin pu chou ba zhang jin jie bing reng cong fo san lun none cang zi shi ta zhang fu xian xian cha hong tong ren qian gan ge di dai ling yi chao chang sa shang yi mu men ren jia chao yang qian zhong pi wan wu jian jia yao feng cang ren wang fen di fang zhong qi pei yu diao dun wen yi xin kang yi ji ai wu ji fu fa xiu jin bei chen fu tang zhong you huo hui yu cui yun san wei chuan che ya xian shang chang lun cang xun xin wei zhu chi xuan nao bo gu ni ni xie ban xu ling zhou shen qu si beng si jia pi yi si ai zheng dian han mai dan zhu bu qu bi shao ci wei di zhu zuo you yang ti zhan he bi tuo she yu yi fo zuo gou ning tong ni xuan ju yong wa qian none ka none pei huai he lao xiang ge yang bai fa ming jia nai bing ji heng huo gui quan tiao jiao ci yi shi xing shen tuo kan zhi gai lai yi chi kua guang li yin shi mi zhu xu you an lu mou er lun dong cha chi xun gong zhou yi ru jian xia jia zai lu: none jiao zhen ce qiao kuai chai ning nong jin wu hou jiong cheng zhen cuo chou qin lu: ju shu ting shen tuo bo nan hao bian tui yu xi cu e qiu xu kuang ku wu jun yi fu lang zu qiao li yong hun jing xian san pai su fu xi li mian ping bao yu si xia xin xiu yu ti che chou none yan liang li lai si jian xiu fu he ju xiao pai jian biao ti fei feng ya an bei yu xin bi chi chang zhi bing zan yao cui lia wan lai cang zong ge guan bei tian shu shu men dao tan jue chui xing peng tang hou yi qi ti gan jing jie xu chang jie fang zhi kong juan zong ju qian ni lun zhuo wo luo song leng hun dong zi ben wu ju nai cai jian zhai ye zhi sha qing none ying cheng qian yan nuan zhong chun jia jie wei yu bing ruo ti wei pian yan feng tang wo e xie che sheng kan di zuo cha ting bei ye huang yao zhan qiu yan you jian xu zha chai fu bi zhi zong mian ji yi xie xun si duan ce zhen ou tou tou bei za lou jie wei fen chang kui sou chi su xia fu yuan rong li ru yun gou ma bang dian tang hao jie xi shan qian jue cang chu san bei xiao yong yao ta suo wang fa bing jia dai zai tang none bin chu nuo zan lei cui yong zao zong peng song ao chuan yu zhai zu shang qian") .append("g qiang chi sha han zhang qing yan di xi lou bei piao jin lian lu man qian xian qiu ying dong zhuan xiang shan qiao jiong tui zun pu xi lao chang guang liao qi deng chan wei zhang fan hui chuan tie dan jiao jiu seng fen xian jue e jiao jian tong lin bo gu xian su xian jiang min ye jin jia qiao pi feng zhou ai sai yi jun nong shan yi dang jing xuan kuai jian chu dan jiao sha zai none bin an ru tai chou chai lan ni jin qian meng wu neng qiong ni chang lie lei lu: kuang bao du biao zan zhi si you hao qin chen li teng wei long chu chan rang shu hui li luo zan nuo tang yan lei nang er wu yun zan yuan xiong chong zhao xiong xian guang dui ke dui mian tu chang er dui er jin tu si yan yan shi shi dang qian dou fen mao xin dou bai jing li kuang ru wang nei quan liang yu ba gong liu xi none lan gong tian guan xing bing qi ju dian zi none yang jian shou ji yi ji chan jiong mao ran nei yuan mao gang ran ce jiong ce zai gua jiong mao zhou mao gou xu mian mi rong yin xie kan jun nong yi mi shi guan meng zhong zui yuan ming kou none fu xie mi bing dong tai gang feng bing hu chong jue hu kuang ye leng pan fu min dong xian lie xia jian jing shu mei shang qi gu zhun song jing liang qing diao ling dong gan jian yin cou ai li cang ming zhun cui si duo jin lin lin ning xi du ji fan fan fan feng ju chu none feng none none fu feng ping feng kai huang kai gan deng ping qu xiong kuai tu ao chu ji dang han han zao dao diao dao ren ren chuangfen qie yi ji kan qian cun chu wen ji dan xing hua wan jue li yue lie liu ze gang chuangfu chu qu ju shan min ling zhong pan bie jie jie bao li shan bie chan jing gua gen dao chuangkui ku duo er zhi shua quan cha ci ke jie gui ci gui kai duo ji ti jing lou luo ze yuan cuo xue ke la qian cha chuan gua jian cuo li ti fei pou chan qi chuangzi gang wan bo ji duo qing yan zhuo jian ji bo yan ju huo sheng jian duo duan wu gua fu sheng jian ge zha kai chuangjuan chan tuan lu li fou shan piao kou jiao gua qiao jue hua zha zhuo lian ju pi liu gui jiao gui jian jian tang huo ji jian yi jian zhi chan cuan mo li zhu li ya quan ban gong jia wu mai lie jing keng xie zhi dong zhu nu jie qu shao yi zhu mo li jing lao lao juan kou yang wa xiao mou kuang jie lie he shi ke jing hao bo min chi lang yong yong mian ke xun juan qing lu bu meng lai le kai mian dong xu xu kan wu yi xun weng sheng lao mu lu piao shi ji qin qiang jiao quan xiang yi qiao fan juan tong ju dan xie mai xun xun lu: li che rang quan bao shao yun jiu bao gou wu yun none none gai gai bao cong none xiong peng ju tao ge pu an pao fu gong da jiu qiong bi hua bei nao chi fang jiu yi za jiang kang jiang kuang hu xia qu fan gui qie cang kuang fei hu yu gui kui hui dan kui lian lian suan du jiu qu xi pi qu yi an yan bian ni qu shi xin qian nian sa zu sheng wu hui ban shi xi wan hua xie wan bei zu zhuo xie dan mai nan dan ji bo shuai bu kuang bian bu zhan ka lu you lu xi gua wo xie jie jie wei ang qiong zhi mao yin we") .append("i shao ji que luan shi juan xie xu jin que wu ji e qing xi none chang han e ting li zhe an li ya ya yan she zhi zha pang none ke ya zhi ce pang ti li she hou ting zui cuo fei yuan ce yuan xiang yan li jue sha dian chu jiu qin ao gui yan si li chang lan li yan yan yuan si si lin qiu qu qu none lei du xian zhuan san can can san can ai dai you cha ji you shuangfan shou guai ba fa ruo shi shu zhui qu shou bian xu jia pan sou ji yu sou die rui cong kou gu ju ling gua tao kou zhi jiao zhao ba ding ke tai chi shi you qiu po ye hao si tan chi le diao ji none hong mie yu mang chi ge xuan yao zi he ji diao cun tong ming hou li tu xiang zha he ye lu: a ma ou xue yi jun chou lin tun yin fei bi qin qin jie pou fou ba dun fen e han ting hang shun qi hu zhi yin wu wu chao na chuo xi chui dou wen hou ou wu gao ya jun lu: e ge mei dai qi cheng wu gao fu jiao hong chi sheng na tun m yi dai ou li bei yuan guo none qiang wu e shi quan pen wen ni mou ling ran you di zhou shi zhou zhan ling yi qi ping zi gua ci wei xu he nao xia pei yi xiao shen hu ming da qu ju gan za tuo duo pou pao bie fu bi he za he hai jiu yong fu da zhou wa ka gu ka zuo bu long dong ning zha si xian huo qi er e guang zha xi yi lie zi mie mi zhi yao ji zhou ge shuai zan xiao ke hui kua huai tao xian e xuan xiu guo yan lao yi ai pin shen tong hong xiong duo wa ha zai you di pai xiang ai gen kuang ya da xiao bi hui none hua none kuai duo none ji nong mou yo hao yuan long pou mang ge e chi shao li na zu he ku xiao xian lao bei zhe zha liang ba mi le sui fou bu han heng geng shuo ge you yan gu gu bai han suo chun yi ai jia tu xian guan li xi tang zuo miu che wu zao ya dou qi di qin ma none gong dou none lao liang suo zao huan none gou ji zuo wo feng yin hu qi shou wei shua chang er li qiang an jie yo nian yu tian lai sha xi tuo hu ai zhou nou ken zhuo zhuo shang di heng lin a xiao xiang tun wu wen cui jie hu qi qi tao dan dan wan zi bi cui chuo he ya qi zhe fei liang xian pi sha la ze qing gua pa zhe se zhuan nie guo luo yan di quan tan bo ding lang xiao none tang chi ti an jiu dan ka yong wei nan shan yu zhe la jie hou han die zhou chai kuai re yu yin zan yao wo mian hu yun chuan hui huan huan xi he ji kui zhong wei sha xu huang du nie xuan liang yu sang chi qiao yan dan pen shi li yo zha wei miao ying pen none kui xi yu jie lou ku cao huo ti yao he a xiu qiang se yong su hong xie ai suo ma cha hai ke da sang chen ru sou gong ji pang wu qian shi ge zi jie luo weng wa si chi hao suo jia hai suo qin nie he none sai ng ge na dia ai none tong bi ao ao lian cui zhe mo sou sou tan di qi jiao chong jiao kai tan san cao jia none xiao piao lou ga gu xiao hu hui guo ou xian ze chang xu po de ma ma hu lei du ga tang ye beng ying none jiao mi xiao hua ") .append("mai ran zuo peng lao xiao ji zhu chao kui zui xiao si hao fu liao qiao xi xu chan dan hei xun wu zun pan chi kui can zan cu dan yu tun cheng jiao ye xi qi hao lian xu deng hui yin pu jue qin xun nie lu si yan ying da zhan o zhou jin nong hui hui qi e zao yi shi jiao yuan ai yong xue kuai yu pen dao ga xin dun dang none sai pi pi yin zui ning di han ta huo ru hao xia yan duo pi chou ji jin hao ti chang none none ca ti lu hui bao you nie yin hu mo huang zhe li liu none nang xiao mo yan li lu long mo dan chen pin pi xiang huo mo xi duo ku yan chan ying rang dian la ta xiao jiao chuo huan huo zhuan nie xiao ca li chan chai li yi luo nang zan su xi none jian za zhu lan nie nang none none wei hui yin qiu si nin jian hui xin yin nan tuan tuan dun kang yuan jiong pian yun cong hu hui yuan e guo kun cong wei tu wei lun guo jun ri ling gu guo tai guo tu you guo yin hun pu yu han yuan lun quan yu qing guo chui wei yuan quan ku pu yuan yuan e tu tu tu tuan lu:e hui yi yuan luan luan tu ya tu ting sheng yan lu none ya zai wei ge yu wu gui pi yi di qian qian zhen zhuo dang qia none none kuang chang qi nie mo ji jia zhi zhi ban xun tou qin fen jun keng dun fang fen ben tan kan huai zuo keng bi xing di jing ji kuai di jing jian tan li ba wu fen zhui po pan tang kun qu tan zhi tuo gan ping dian wa ni tai pi jiong yang fo ao liu qiu mu ke gou xue ba chi che ling zhu fu hu zhi chui la long long lu ao none pao none xing tong ji ke lu ci chi lei gai yin hou dui zhao fu guang yao duo duo gui cha yang yin fa gou yuan die xie ken shang shou e none dian hong ya kua da none dang kai none nao an xing xian huan bang pei ba yi yin han xu chui cen geng ai peng fang que yong jun jia di mai lang xuan cheng shan jin zhe lie lie pu cheng none bu shi xun guo jiong ye nian di yu bu wu juan sui pi cheng wan ju lun zheng kong zhong dong dai tan an cai shu beng kan zhi duo yi zhi yi pei ji zhun qi sao ju ni ku ke tang kun ni jian dui jin gang yu e peng gu tu leng none ya qian none an chen duo nao tu cheng yin hun bi lian guo die zhuan hou bao bao yu di mao jie ruan e geng kan zong yu huang e yao yan bao ji mei chang du tuo an feng zhong jie zhen heng gang chuan jian none lei gang huang leng duan wan xuan ji ji kuai ying ta cheng yong kai su su shi mi ta weng cheng tu tang qiao zhong li peng bang sai zang dui tian wu cheng xun ge zhen ai gong yan kan tian yuan wen xie liu none lang chang peng beng chen lu lu ou qian mei mo zhuan shuangshu lou chi man biao jing ce shu di zhang kan yong dian chen zhi ji guo qiang jin di shang mu cui yan ta zeng qi qiang liang none zhui qiao zeng xu shan shan ba pu kuai dong fan que mo dun dun zun zui sheng duo duo tan deng mu fen huang tan da ye chu none ao qiang ji qiao ken yi pi bi dian jiang ye yong xue tan lan ju huai dang rang qian xuan lan mi he kai ya dao hao ruan none lei kuang lu yan tan wei huai long long rui li ") .append(" lin rang chan xun yan lei ba none shi ren none zhuangzhuangsheng yi mai qiao zhu zhuanghu hu kun yi hu xu kun shou mang zun shou yi zhi gu chu xiang feng bei none bian sui qun ling fu zuo xia xiong none nao xia kui xi wai yuan mao su duo duo ye qing none gou gou qi meng meng yin huo chen da ze tian tai fu guai yao yang hang gao shi ben tai tou yan bi yi kua jia duo none kuang yun jia ba en lian huan di yan pao juan qi nai feng xie fen dian none kui zou huan qi kai she ben yi jiang tao zhuangben xi huang fei diao sui beng dian ao she weng pan ao wu ao jiang lian duo yun jiang shi fen huo bei lian che nu: nu ding nai qian jian ta jiu nan cha hao xian fan ji shuo ru fei wang hong zhuangfu ma dan ren fu jing yan xie wen zhong pa du ji keng zhong yao jin yun miao pei chi yue zhuangniu yan na xin fen bi yu tuo feng yuan fang wu yu gui du ba ni zhou zhou zhao da nai yuan tou xuan zhi e mei mo qi bi shen qie e he xu fa zheng ni ban mu fu ling zi zi shi ran shan yang qian jie gu si xing wei zi ju shan pin ren yao tong jiang shu ji gai shang kuo juan jiao gou lao jian jian yi nian zhi ji ji xian heng guang jun kua yan ming lie pei yan you yan cha xian yin chi gui quan zi song wei hong wa lou ya rao jiao luan ping xian shao li cheng xie mang none suo mu wei ke lai chuo ding niang keng nan yu na pei sui juan shen zhi han di zhuange pin tui xian mian wu yan wu xi yan yu si yu wa li xian ju qu chui qi xian zhui dong chang lu ai e e lou mian cong pou ju po cai ling wan biao xiao shu qi hui fu wo rui tan fei none jie tian ni quan jing hun jing qian dian xing hu wan lai bi yin chou chuo fu jing lun yan lan kun yin ya none li dian xian none hua ying chan shen ting yang yao wu nan chuo jia tou xu yu wei ti rou mei dan ruan qin none wu qian chun mao fu jie duan xi zhong mei huang mian an ying xuan none wei mei yuan zhen qiu ti xie tuo lian mao ran si pian wei wa jiu hu ao none bao xu tou gui zou yao pi xi yuan ying rong ru chi liu mei pan ao ma gou kui qin jia sao zhen yuan cha yong ming ying ji su niao xian tao pang lang niao bao ai pi pin yi piao yu lei xuan man yi zhang kang yong ni li di gui yan jin zhuan chang ce han nen lao mo zhe hu hu ao nen qiang none bi gu wu qiao tuo zhan mao xian xian mo liao lian hua gui deng zhi xu none hua xi hui rao xi yan chan jiao mei fan fan xian yi wei chan fan shi bi shan sui qiang lian huan none niao dong yi can ai niang ning ma tiao chou jin ci yu pin none xu nai yan tai ying can niao none ying mian none ma shen xing ni du liu yuan lan yan shuangling jiao niang lan xian ying shuangshuai quan mi li luan yan zhu lan zi jie jue jue kong yun zi zi cun sun fu bei zi xiao xin meng si tai bao ji gu nu xue none chan hai luan sun nao mie cong jian shu chan ya zi ni fu zi li xue bo ru nai nie nie ying luan mian ning rong ta gui zhai qiong yu shou an tu song wan rou yao hong yi jing zhun mi guai dang hong zong guan zhou ding wa") .append("n yi bao shi shi chong shen ke xuan shi you huan yi tiao shi xian gong cheng qun gong xiao zai zha bao hai yan xiao jia shen chen rong huang mi kou kuan bin su cai zan ji yuan ji yin mi kou qing he zhen jian fu ning bing huan mei qin han yu shi ning jin ning zhi yu bao kuan ning qin mo cha ju gua qin hu wu liao shi ning zhai shen wei xie kuan hui liao jun huan yi yi bao qin chong bao feng cun dui si xun dao lu: dui shou po feng zhuan fu she ke jiang jiang zhuan wei zun xun shu dui dao xiao ji shao er er er ga jian shu chen shang shang yuan ga chang liao xian xian none wang wang you liao liao yao mang wang wang wang ga yao duo kui zhong jiu gan gu gan gan gan gan shi yin chi kao ni jin wei niao ju pi ceng xi bi ju jie tian qu ti jie wu diao shi shi ping ji xie chen xi ni zhan xi none man e lou ping ti fei shu xie tu lu: lu: xi ceng lu: ju xie ju jue liao jue shu xi che tun ni shan wa xian li e none none long yi qi ren wu han shen yu chu sui qi none yue ban yao ang ya wu jie e ji qian fen wan qi cen qian qi cha jie qu gang xian ao lan dao ba zhai zuo yang ju gang ke gou xue bo li tiao qu yan fu xiu jia ling tuo pei you dai kuang yue qu hu po min an tiao ling chi none dong none kui xiu mao tong xue yi none he ke luo e fu xun die lu lang er gai quan tong yi mu shi an wei hu zhi mi li ji tong kui you none xia li yao jiao zheng luan jiao e e yu ye bu qiao qun feng feng nao li you xian hong dao shen cheng tu geng jun hao xia yin wu lang kan lao lai xian que kong chong chong ta none hua ju lai qi min kun kun zu gu cui ya ya gang lun lun leng jue duo cheng guo yin dong han zheng wei yao pi yan song jie beng zu jue dong zhan gu yin zi ze huang yu wei yang feng qiu dun ti yi zhi shi zai yao e zhu kan lu: yan mei gan ji ji huan ting sheng mei qian wu yu zong lan jie yan yan wei zong cha sui rong ke qin yu qi lou tu dui xi weng cang dang rong jie ai liu wu song qiao zi wei beng dian cuo qian yong nie cuo ji none none song zong jiang liao none chan di cen ding tu lou zhang zhan zhan ao cao qu qiang zui zui dao dao xi yu bo long xiang ceng bo qin jiao yan lao zhan lin liao liao jin deng duo zun jiao gui yao qiao yao jue zhan yi xue nao ye ye yi e xian ji xie ke sui di ao zui none yi rong dao ling za yu yue yin none jie li sui long long dian ying xi ju chan ying kui yan wei nao quan chao cuan luan dian dian nie yan yan yan nao yan chuan gui chuan zhou huang jing xun chao chao lie gong zuo qiao ju gong none wu none none cha qiu qiu ji yi si ba zhi zhao xiang yi jin xun juan none xun jin fu za bi shi bu ding shuai fan nie shi fen pa zhi xi hu dan wei zhang tang dai ma pei pa tie fu lian zhi zhou bo zhi di mo yi yi ping qia juan ru shuai dai zhen shui qiao zhen shi qun xi bang dai gui chou ping zhang sha wan dai wei chang sha qi ze guo mao du hou zhen xu mi wei wo fu yi bang ping none gong pan huang dao mi jia teng hui zhong sen ") .append("man mu biao guo ze mu bang zhang jiong chan fu zhi hu fan chuangbi bi none mi qiao dan fen meng bang chou mie chu jie xian lan gan ping nian jian bing bing xing gan yao huan you you ji guang pi ting ze guang zhuangmo qing bi qin dun chuanggui ya bai jie xu lu wu none ku ying di pao dian ya miao geng ci fu tong pang fei xiang yi zhi tiao zhi xiu du zuo xiao tu gui ku pang ting you bu bing cheng lai bi ji an shu kang yong tuo song shu qing yu yu miao sou ce xiang fei jiu he hui liu sha lian lang sou jian pou qing jiu jiu qin ao kuo lou yin liao dai lu yi chu chan tu si xin miao chang wu fei guang none guai bi qiang xie lin lin liao lu none ying xian ting yong li ting yin xun yan ting di po jian hui nai hui gong nian kai bian yi qi nong fen ju yan yi zang bi yi yi er san shi er shi shi gong diao yin hu fu hong wu tui chi qiang ba shen di zhang jue tao fu di mi xian hu chao nu jing zhen yi mi quan wan shao ruo xuan jing diao zhang jiang qiang beng dan qiang bi bi she dan jian gou none fa bi kou none bie xiao dan kuang qiang hong mi kuo wan jue ji ji gui dang lu lu tuan hui zhi hui hui yi yi yi yi huo huo shan xing zhang tong yan yan yu chi cai biao diao bin peng yong piao zhang ying chi chi zhuo tuo ji pang zhong yi wang che bi di ling fu wang zheng cu wang jing dai xi xun hen yang huai lu: hou wang cheng zhi xu jing tu cong none lai cong de pai xi none qi chang zhi cong zhou lai yu xie jie jian chi jia bian huang fu xun wei pang yao wei xi zheng piao chi de zheng zhi bie de chong che jiao wei jiao hui mei long xiang bao qu xin xin bi yi le ren dao ding gai ji ren ren chan tan te te gan qi dai cun zhi wang mang xi fan ying tian min min zhong chong wu ji wu xi ye you wan zong zhong kuai yu bian zhi chi cui chen tai tun qian nian hun xiong niu wang xian xin kang hu kai fen huai tai song wu ou chang chuangju yi bao chao min pi zuo zen yang kou ban nu nao zheng pa bu tie hu hu ju da lian si zhou di dai yi tu you fu ji peng xing yuan ni guai fu xi bi you qie xuan zong bing huang xu chu pi xi xi tan none zong dui none none yi chi nen xun shi xi lao heng kuang mou zhi xie lian tiao huang die hao kong gui heng xi xiao shu sai hu qiu yang hui hui chi jia yi xiong guai lin hui zi xu chi xiang nu: hen en ke dong tian gong quan xi qia yue peng ken de hui e none tong yan kai ce nao yun mang yong yong juan mang kun qiao yue yu yu jie xi zhe lin ti han hao qie ti bu yi qian hui xi bei man yi heng song quan cheng kui wu wu you li liang huan cong yi yue li nin nao e que xuan qian wu min cong fei bei de cui chang men li ji guan guan xing dao qi kong tian lun xi kan kun ni qing chou dun guo chan jing wan yuan jin ji lin yu huo he quan yan ti ti nie wang chuo hu hun xi chang xin wei hui e rui zong jian yong dian ju can cheng de bei qie can dan guan duo nao yun xiang zhui die huang chun qiong re xing ce bian hun zong ti qiao chou bei xuan wei ge qian wei yu yu bi xuan huan") .append(" min bi yi mian yong kai dang yin e chen mou qia ke yu ai qie yan nuo gan yun zong sai leng fen none kui kui que gong yun su su qi yao song huang none gu ju chuangta xie kai zheng yong cao sun shen bo kai yuan xie hun yong yang li sao tao yin ci xu qian tai huang yun shen ming none she cong piao mo mu guo chi can can can cui min ni zhang tong ao shuangman guan que zao jiu hui kai lian ou song jin yin lu: shang wei tuan man qian zhe yong qing kang di zhi lu: juan qi qi yu ping liao zong you chuangzhi tong cheng qi qu peng bei bie chun jiao zeng chi lian ping kui hui qiao cheng yin yin xi xi dan tan duo dui dui su jue ce xiao fan fen lao lao chong han qi xian min jing liao wu can jue chou xian tan sheng pi yi chu xian nao dan tan jing song han jiao wei huan dong qin qin qu cao ken xie ying ao mao yi lin se jun huai men lan ai lin yan gua xia chi yu yin dai meng ai meng dui qi mo lan men chou zhi nuo nuo yan yang bo zhi xing kuang you fu liu mie cheng none chan meng lan huai xuan rang chan ji ju huan she yi lian nan mi tang jue gang gang zhuangge yue wu jian xu shu rong xi cheng wo jie ge jian qiang huo qiang zhan dong qi jia die cai jia ji shi kan ji kui gai deng zhan chuangge jian jie yu jian yan lu xi zhan xi xi chuo dai qu hu hu hu e shi li mao hu li fang suo bian dian jiong shang yi yi shan hu fei yan shou shou cai zha qiu le pu ba da reng fu none zai tuo zhang diao kang yu ku han shen cha chi gu kou wu tuo qian zhi cha kuo men sao yang niu ban che rao xi qian ban jia yu fu ao xi pi zhi zi e dun zhao cheng ji yan kuang bian chao ju wen hu yue jue ba qin zhen zheng yun wan na yi shu zhua pou tou dou kang zhe pou fu pao ba ao ze tuan kou lun qiang none hu bao bing zhi peng tan pu pi tai yao zhen zha yang bao he ni yi di chi pi za mo mo chen ya chou qu min chu jia fu zha zhu dan chai mu nian la fu pao ban pai lin na guai qian ju tuo ba tuo tuo ao ju zhuo pan zhao bai bai di ni ju kuo long jian qia yong lan ning bo ze qian hen kuo shi jie zheng nin gong gong quan shuan tun zan kao chi xie ce hui pin zhuai shi na bo chi gua zhi kuo duo duo zhi qie an nong zhen ge jiao kua dong ru tiao lie zha lu: die wa jue none ju zhi luan ya wo ta xie nao dang jiao zheng ji hui xian none ai tuo nuo cuo bo geng ti zhen cheng suo suo keng mei long ju peng jian yi ting shan nuo wan xie cha feng jiao wu jun jiu tong kun huo tu zhuo pou lu: ba han shao nie juan she shu ye jue bu huan bu jun yi zhai lu: sou tuo lao sun bang jian huan dao none wan qin peng she lie min men fu bai ju dao wo ai juan yue zong chen chui jie tu ben na nian nuo zu wo xi xian cheng dian sao lun qing gang duo shou diao pou di zhang gun ji tao qia qi pai shu qian ling ye ya jue zheng liang gua yi huo shan ding lu:e cai tan che bing jie ti kong tui yan cuo zou ju tian qian ken bai shou jie lu guai none none zhi dan none chan sao guan peng yuan nuo jian zheng jiu jian yu ya") .append("n kui nan hong rou pi wei sai zou xuan miao ti nie cha shi zong zhen yi shun heng bian yang huan yan zan an xu ya wo ke chuai ji ti la la cheng kai jiu jiu tu jie hui geng chong shuo she xie yuan qian ye cha zha bei yao none none lan wen qin chan ge lou zong geng jiao gou qin yong que chou chuai zhan sun sun bo chu rong bang cuo sao ke yao dao zhi nu xie jian sou qiu gao xian shuo sang jin mie e chui nuo shan ta jie tang pan ban da li tao hu zhi wa xia qian wen qiang chen zhen e xie nuo quan cha zha ge wu en she gong she shu bai yao bin sou tan sha chan suo liao chong chuangguo bing feng shuai di qi none zhai lian cheng chi guan lu luo lou zong gai hu zha chuangtang hua cui nai mo jiang gui ying zhi ao zhi chi man shan kou shu suo tuan zhao mo mo zhe chan keng biao jiang yin gou qian liao ji ying jue pie pie lao dun xian ruan kui zan yi xian cheng cheng sa nao heng si han huang da zun nian lin zheng hui zhuangjiao ji cao dan dan che bo che jue xiao liao ben fu qiao bo cuo zhuo zhuan tuo pu qin dun nian none xie lu jiao cuan ta han qiao zhua jian gan yong lei kuo lu shan zhuo ze pu chuo ji dang se cao qing jing huan jie qin kuai dan xie ge pi bo ao ju ye none none sou mi ji tai zhuo dao xing lan ca ju ye ru ye ye ni huo ji bin ning ge zhi jie kuo mo jian xie lie tan bai sou lu lu:e rao zhi pan yang lei sa shu zan nian xian jun huo lu:e la han ying lu long qian qian zan qian lan san ying mei rang chan none cuan xie she luo jun mi li zan luan tan zuan li dian wa dang jiao jue lan li nang zhi gui gui qi xin po po shou kao you gai gai gong gan ban fang zheng bo dian kou min wu gu ge ce xiao mi chu ge di xu jiao min chen jiu shen duo yu chi ao bai xu jiao duo lian nie bi chang dian duo yi gan san ke yan dun qi dou xiao duo jiao jing yang xia hun shu ai qiao ai zheng di zhen fu shu liao qu xiong xi jiao none qiao zhuo yi lian bi li xue xiao wen xue qi qi zhai bin jue zhai lang fei ban ban lan yu lan wei dou sheng liao jia hu xie jia yu zhen jiao wo tiao dou jin chi yin fu qiang zhan qu zhuo zhan duan zhuo si xin zhuo zhuo qin lin zhuo chu duan zhu fang xie hang wu shi pei you none pang qi zhan mao lu: pei pi liu fu fang xuan jing jing ni zu zhao yi liu shao jian none yi qi zhi fan piao fan zhan guai sui yu wu ji ji ji huo ri dan jiu zhi zao xie tiao xun xu ga la gan han tai di xu chan shi kuang yang shi wang min min tun chun wu yun bei ang ze ban jie kun sheng hu fang hao gui chang xuan ming hun fen qin hu yi xi xin yan ze fang tan shen ju yang zan bing xing ying xuan pei zhen ling chun hao mei zuo mo bian xu hun zhao zong shi shi yu fei die mao ni chang wen dong ai bing ang zhou long xian kuang tiao chao shi huang huang xuan kui xu jiao jin zhi jin shang tong hong yan gai xiang shai xiao ye yun hui han han jun wan xian kun zhou xi sheng sheng bu zhe zhe wu han hui hao chen wan tian zhuo zui zhou pu jing xi shan yi xi qing qi jing gui zhen yi zhi an wan lin ") .append("liang chang wang xiao zan none xuan geng yi xia yun hui fu min kui he ying du wei shu qing mao nan jian nuan an yang chun yao suo pu ming jiao kai gao weng chang qi hao yan li ai ji gui men zan xie hao mu mo cong ni zhang hui bao han xuan chuan liao xian dan jing pie lin tun xi yi ji kuang dai ye ye li tan tong xiao fei qin zhao hao yi xiang xing sen jiao bao jing none ai ye ru shu meng xun yao pu li chen kuang die none yan huo lu xi rong long nang luo luan shai tang yan chu yue yue qu ye geng zhuai hu he shu cao cao sheng man ceng ceng ti zui can xu hui yin qie fen pi yue you ruan peng ban fu ling fei qu none nu: tiao shuo zhen lang lang juan ming huang wang tun chao ji qi ying zong wang tong lang none meng long mu deng wei mo ben zha zhu shu none zhu ren ba po duo duo dao li qiu ji jiu bi xiu ting ci sha none za quan qian yu gan wu cha shan xun fan wu zi li xing cai cun ren shao zhe di zhang mang chi yi gu gong du yi qi shu gang tiao none none none lai shan mang yang ma miao si yuan hang fei bei jie dong gao yao xian chu chun pa shu hua xin chou zhu chou song ban song ji yue yun gou ji mao pi bi wang ang fang fen yi fu nan xi hu ya dou xun zhen yao lin rui e mei zhao guo zhi zong yun none dou shu zao none li lu jian cheng song qiang feng nan xiao xian ku ping tai xi zhi guai xiao jia jia gou bao mo yi ye sang shi nie bi tuo yi ling bing ni la he ban fan zhong dai ci yang fu bo mou gan qi ran rou mao zhao song zhe xia you shen ju tuo zuo nan ning yong di zhi zha cha dan gu none jiu ao fu jian bo duo ke nai zhu bi liu chai zha si zhu pei shi guai cha yao cheng jiu shi zhi liu mei none rong zha none biao zhan zhi long dong lu none li lan yong shu xun shuan qi zhen qi li chi xiang zhen li su gua kan bing ren xiao bo ren bing zi chou yi ci xu zhu jian zui er er yu fa gong kao lao zhan li none yang he gen zhi chi ge zai luan fa jie heng gui tao guang wei kuang ru an an juan yi zhuo ku zhi qiong tong sang sang huan jie jiu xue duo zhui yu zan none ying none none zhan ya rao zhen dang qi qiao hua gui jiang zhuangxun suo suo zhen bei ting kuo jing bo ben fu rui tong jue xi lang liu feng qi wen jun gan cu liang qiu ting you mei bang long peng zhuangdi xuan tu zao ao gu bi di han zi zhi ren bei geng jian huan wan nuo jia tiao ji xiao lu: kuan shao cen fen song meng wu li li dou cen ying suo ju ti xie kun zhuo shu chan fan wei jing li bing none none tao zhi lai lian jian zhuo ling li qi bing lun cong qian mian qi qi cai gun chan de fei pai bang pou hun zong cheng zao ji li peng yu yu gu hun dong tang gang wang di xi fan cheng zhan qi yuan yan yu quan yi sen ren chui leng qi zhuo fu ke lai zou zou zhao guan fen fen chen qiong nie wan guo lu hao jie yi chou ju ju cheng zuo liang qiang zhi zhui ya ju bei jiao zhuo zi bin peng ding chu shan none none jian gui xi du qian none kui none luo zhi none none none none peng shan none tuo sen duo ye fu wei wei duan jia zong") .append(" jian yi shen xi yan yan chuan zhan chun yu he zha wo bian bi yao huo xu ruo yang la yan ben hun kui jie kui si feng xie tuo ji jian mu mao chu hu hu lian leng ting nan yu you mei song xuan xuan ying zhen pian die ji jie ye chu shun yu cou wei mei di ji jie kai qiu ying rou heng lou le none gui pin none gai tan lan yun yu chen lu: ju none none none xie jia yi zhan fu nuo mi lang rong gu jian ju ta yao zhen bang sha yuan zi ming su jia yao jie huang gan fei zha qian ma sun yuan xie rong shi zhi cui yun ting liu rong tang que zhai si sheng ta ke xi gu qi kao gao sun pan tao ge xun dian nou ji shuo gou chui qiang cha qian huai mei xu gang gao zhuo tuo qiao yang dian jia jian zui none long bin zhu none xi qi lian hui yong qian guo gai gai tuan hua qi sen cui beng you hu jiang hu huan kui yi yi gao kang gui gui cao man jin di zhuangle lang chen cong li xiu qing shuangfan tong guan ji suo lei lu liang mi lou chao su ke chu tang biao lu jiu shu zha shu zhang men mo niao yang tiao peng zhu sha xi quan heng jian cong none none qiang none ying er xin zhi qiao zui cong pu shu hua kui zhen zun yue zhan xi xun dian fa gan mo wu qiao rao lin liu qiao xian run fan zhan tuo lao yun shun tui cheng tang meng ju cheng su jue jue tan hui ji nuo xiang tuo ning rui zhu tong zeng fen qiong ran heng cen gu liu lao gao chu none none none none ji dou none lu none none yuan ta shu jiang tan lin nong yin xi sui shan zui xuan cheng gan ju zui yi qin pu yan lei feng hui dang ji sui bo bi ding chu zhua gui ji jia jia qing zhe jian qiang dao yi biao song she lin li cha meng yin tao tai mian qi none bin huo ji qian mi ning yi gao jian yin er qing yan qi mi zhao gui chun ji kui po deng chu none mian you zhi guang qian lei lei sa lu none cuan lu: mie hui ou lu: zhi gao du yuan li fei zhu sou lian none chu none zhu lu yan li zhu chen jie e su huai nie yu long lai none xian none ju xiao ling ying jian yin you ying xiang nong bo chan lan ju shuangshe wei cong quan qu none none yu luo li zan luan dang jue none lan lan zhu lei li ba nang yu ling none qian ci huan xin yu yu qian ou xu chao chu qi kai yi jue xi xu xia yu kuai lang kuan shuo xi e yi qi hu chi qin kuan kan kuan kan chuan sha none yin xin xie yu qian xiao yi ge wu tan jin ou hu ti huan xu pen xi xiao hu she none lian chu yi kan yu chuo huan zhi zheng ci bu wu qi bu bu wai ju qian chi se chi se zhong sui sui li cuo yu li gui dai dai si jian zhe mo mo yao mo cu yang tian sheng dai shang xu xun shu can jue piao qia qiu su qing yun lian yi fou zhi ye can hun dan ji ye none yun wen chou bin ti jin shang yin diao cu hui cuan yi dan du jiang lian bin du jian jian shu ou duan zhu yin qing yi sha ke ke yao xun dian hui hui gu que ji yi ou hui duan yi xiao wu guan mu mei mei ai zuo du yu bi bi bi pi pi bi chan mao none none pi none jia zhan sai mu tuo xun er rong xian ju mu hao qiu dou none ta") .append("n pei ju duo cui bi san none mao sui shu yu tuo he jian ta san lu: mu li tong rong chang pu lu zhan sao zhan meng lu qu die shi di min jue mang qi pie nai qi dao xian chuan fen ri nei none fu shen dong qing qi yin xi hai yang an ya ke qing ya dong dan lu: qing yang yun yun shui shui zheng bing yong dang shui le ni tun fan gui ting zhi qiu bin ze mian cuan hui diao han cha zhuo chuan wan fan dai xi tuo mang qiu qi shan pai han qian wu wu xun si ru gong jiang chi wu none none tang zhi chi qian mi gu wang qing jing rui jun hong tai quan ji bian bian gan wen zhong fang xiong jue hu none qi fen xu xu qin yi wo yun yuan hang yan shen chen dan you dun hu huo qi mu rou mei ta mian wu chong tian bi sha zhi pei pan zhui za gou liu mei ze feng ou li lun cang feng wei hu mo mei shu ju zan tuo tuo duo he li mi yi fu fei you tian zhi zhao gu zhan yan si kuang jiong ju xie qiu yi jia zhong quan bo hui mi ben zhuo chu le you gu hong gan fa mao si hu ping ci fan zhi su ning cheng ling pao bo qi si ni ju yue zhu sheng lei xuan xue fu pan min tai yang ji yong guan beng xue long lu dan luo xie po ze jing yin zhou jie yi hui hui zui cheng yin wei hou jian yang lie si ji er xing fu sa zi zhi yin wu xi kao zhu jiang luo none an dong yi mou lei yi mi quan jin po wei xiao xie hong xu su kuang tao qie ju er zhou ru ping xun xiong zhi guang huan ming huo wa qia pai wu qu liu yi jia jing qian jiang jiao zhen shi zhuo ce none hui ji liu chan hun hu nong xun jin lie qiu wei zhe jun han bang mang zhuo you xi bo dou huan hong yi pu ying lan hao lang han li geng fu wu li chun feng yi yu tong lao hai jin jia chong weng mei sui cheng pei xian shen tu kun pin nie han jing xiao she nian tu yong xiao xian ting e su tun juan cen ti li shui si lei shui tao du lao lai lian wei wo yun huan di none run jian zhang se fu guan xing shou shuan ya chuo zhang ye kong wan han tuo dong he wo ju gan liang hun ta zhuo dian qie de juan zi xi xiao qi gu guo han lin tang zhou peng hao chang shu qi fang chi lu nao ju tao cong lei zhi peng fei song tian pi dan yu ni yu lu gan mi jing ling lun yin cui qu huai yu nian shen piao chun hu yuan lai hun qing yan qian tian miao zhi yin mi ben yuan wen re fei qing yuan ke ji she yuan se lu zi du none jian mian pi xi yu yuan shen shen rou huan zhu jian nuan yu qiu ting qu du feng zha bo wo wo di wei wen ru xie ce wei ge gang yan hong xuan mi ke mao ying yan you hong miao xing mei zai hun nai kui shi e pai mei lian qi qi mei tian cou wei can tuan mian xu mo xu ji pen jian jian hu feng xiang yi yin zhan shi jie zhen huang tan yu bi min shi tu sheng yong ju zhong none qiu jiao none yin tang long huo yuan nan ban you quan chui liang chan yan chun nie zi wan shi man ying la kui none jian xu lou gui gai none none po jin gui tang yuan suo yuan lian yao meng zhun sheng ke tai ta wa liu gou sao ming zha shi yi lun ma pu wei li ") .append("cai wu xi wen qiang ce shi su yi zhen sou yun xiu yin rong hun su su ni ta shi ru wei pan chu chu pang weng cang mie he dian hao huang xi zi di zhi ying fu jie hua ge zi tao teng sui bi jiao hui gun yin gao long zhi yan she man ying chun lu: lan luan xiao bin tan yu xiu hu bi biao zhi jiang kou shen shang di mi ao lu hu hu you chan fan yong gun man qing yu piao ji ya jiao qi xi ji lu lu: long jin guo cong lou zhi gai qiang li yan cao jiao cong chun tuan ou teng ye xi mi tang mo shang han lian lan wa li qian feng xuan yi man zi mang kang luo peng shu zhang zhang chong xu huan kuo jian yan chuangliao cui ti yang jiang cong ying hong xiu shu guan ying xiao none none xu lian zhi wei pi yu jiao po xiang hui jie wu pa ji pan wei xiao qian qian xi lu xi sun dun huang min run su liao zhen zhong yi di wan dan tan chao xun kui none shao tu zhu sa hei bi shan chan chan shu tong pu lin wei se se cheng jiong cheng hua jiao lao che gan cun heng si shu peng han yun liu hong fu hao he xian jian shan xi ao lu lan none yu lin min zao dang huan ze xie yu li shi xue ling man zi yong kuai can lian dian ye ao huan lian chan man dan dan yi sui pi ju ta qin ji zhuo lian nong guo jin fen se ji sui hui chu ta song ding se zhu lai bin lian mi shi shu mi ning ying ying meng jin qi bi ji hao ru zui wo tao yin yin dui ci huo jing lan jun ai pu zhuo wei bin gu qian xing bin kuo fei none bin jian dui luo luo lu: li you yang lu si jie ying du wang hui xie pan shen biao chan mie liu jian pu se cheng gu bin huo xian lu qin han ying rong li jing xiao ying sui wei xie huai hao zhu long lai dui fan hu lai none none ying mi ji lian jian ying fen lin yi jian yue chan dai rang jian lan fan shuangyuan zhuo feng she lei lan cong qu yong qian fa guan que yan hao none sa zan luan yan li mi dan tan dang jiao chan none hao ba zhu lan lan nang wan luan quan xian yan gan yan yu huo biao mie guang deng hui xiao xiao none hong ling zao zhuan jiu zha xie chi zhuo zai zai can yang qi zhong fen niu gui wen po yi lu chui pi kai pan yan kai pang mu chao liao gui kang dun guang xin zhi guang xin wei qiang bian da xia zheng zhu ke zhao fu ba duo duo ling zhuo xuan ju tan pao jiong pao tai tai bing yang tong han zhu zha dian wei shi lian chi ping none hu shuo lan ting jiao xu xing quan lie huan yang xiao xiu xian yin wu zhou yao shi wei tong tong zai kai hong luo xia zhu xuan zheng po yan hui guang zhe hui kao none fan shao ye hui none tang jin re none xi fu jiong che pu jing zhuo ting wan hai peng lang shan hu feng chi rong hu none shu lang xun xun jue xiao xi yan han zhuangqu di xie qi wu none none han yan huan men ju dao bei fen lin kun hun chun xi cui wu hong ju fu yue jiao cong feng ping qiong cui xi qiong xin zhuo yan yan yi jue yu gang ran pi yan none sheng chang shao none none none none chen he kui zhong duan ya hui feng lian xuan xing huang jiao jian bi ying zhu wei tuan tian xi nuan nuan chan yan jiong jiong yu mei sha wu ye ") .append(" xin qiong rou mei huan xu zhao wei fan qiu sui yang lie zhu none gao gua bao hu yun xia none none bian wei tui tang chao shan yun bo huang xie xi wu xi yun he he xi yun xiong nai kao none yao xun ming lian ying wen rong none none qiang liu xi bi biao cong lu jian shu yi lou feng sui yi teng jue zong yun hu yi zhi ao wei liao han ou re jiong man none shang cuan zeng jian xi xi xi yi xiao chi huang chan ye qian ran yan xian qiao zun deng dun shen jiao fen si liao yu lin tong shao fen fan yan xun lan mei tang yi jing men none none ying yu yi xue lan tai zao can sui xi que cong lian hui zhu xie ling wei yi xie zhao hui none none lan ru xian kao xun jin chou dao yao he lan biao rong li mo bao ruo di lu: ao xun kuang shuo none li lu jue liao yan xi xie long yan none rang yue lan cong jue tong guan none che mi tang lan zhu lan ling cuan yu zhua lan pa zheng pao zhao yuan ai wei none jue jue fu ye ba die ye yao zu shuanger pan chuan ke zang zang qiang die qiang pian ban pan shao jian pai du yong tou tou bian die bang bo bang you none du ya cheng niu cheng pin jiu mou ta mu lao ren mang fang mao mu ren wu yan fa bei si jian gu you gu sheng mu di qian quan quan zi te xi mang keng qian wu gu xi li li pou ji gang zhi ben quan run du ju jia jian feng pian ke ju kao chu xi bei luo jie ma san wei li dun tong se jiang xi li du lie pi piao bao xi chou wei kui chou quan quan ba fan qiu bo chai chuo an jie zhuangguang ma you kang bo hou ya han huan zhuangyun kuang niu di qing zhong yun bei pi ju ni sheng pao xia tuo hu ling fei pi ni sheng you gou yue ju dan bo gu xian ning huan hen jiao he zhao ji huan shan ta rong shou tong lao du xia shi kuai zheng yu sun yu bi mang xi juan li xia yin suan lang bei zhi yan sha li zhi xian jing han fei yao ba qi ni biao yin li lie jian qiang kun yan guo zong mi chang yi zhi zheng ya meng cai cu she lie none luo hu zong hu wei feng wo yuan xing zhu mao wei yuan xian tuan ya nao xie jia hou bian you you mei cha yao sun bo ming hua yuan sou ma yuan dai yu shi hao none yi zhen chuanghao man jing jiang mo zhang chan ao ao hao cui ben jue bi bi huang bu lin yu tong yao liao shuo xiao shou none xi ge juan du hui kuai xian xie ta xian xun ning bian huo nou meng lie nao guang shou lu ta xian mi rang huan nao luo xian qi qu xuan miao zi lu: lu yu su wang qiu ga ding le ba ji hong di chuan gan jiu yu qi yu yang ma hong wu fu min jie ya bin bian beng yue jue yun jue wan jian mei dan pi wei huan xian qiang ling dai yi an ping dian fu xuan xi bo ci gou jia shao po ci ke ran sheng shen yi zu jia min shan liu bi zhen zhen jue fa long jin jiao jian li guang xian zhou gong yan xiu yang xu luo su zhu qin ken xun bao er xiang yao xia heng gui chong xu ban pei none dang ying hun wen e cheng ti wu wu cheng jun mei bei ting xian chuo han xuan yan qiu quan lang li xiu fu liu ya xi ling li jin lian suo suo none wan dian bing zhan cui min yu") .append(" ju chen lai wen sheng wei dian chu zhuo pei cheng hu qi e kun chang qi beng wan lu cong guan yan diao bei lin qin pi pa qiang zhuo qin fa none qiong du jie hun yu mao mei chun xuan ti xing dai rou min zhen wei ruan huan xie chuan jian zhuan yang lian quan xia duan yuan ye nao hu ying yu huang rui se liu none rong suo yao wen wu jin jin ying ma tao liu tang li lang gui tian qiang cuo jue zhao yao ai bin tu chang kun zhuan cong jin yi cui cong qi li ying suo qiu xuan ao lian man zhang yin none ying wei lu wu deng none zeng xun qu dang lin liao qiong su huang gui pu jing fan jin liu ji none jing ai bi can qu zao dang jiao gun tan hui huan se sui tian none yu jin fu bin shu wen zui lan xi ji xuan ruan huo gai lei du li zhi rou li zan qiong zhe gui sui la long lu li zan lan ying mi xiang xi guan dao zan huan gua bao die pao hu zhi piao ban rang li wa none jiang qian ban pen fang dan weng ou none none none hu ling yi ping ci none juan chang chi none dang meng bu chui ping bian zhou zhen none ci ying qi xian lou di ou meng zhuan beng lin zeng wu pi dan weng ying yan gan dai shen tian tian han chang sheng qing shen chan chan rui sheng su shen yong shuai lu fu yong beng none ning tian you jia shen zha dian fu nan dian ping ding hua ting quan zai meng bi qi liu xun liu chang mu yun fan fu geng tian jie jie quan wei fu tian mu none pan jiang wa da nan liu ben zhen chu mu mu ce none gai bi da zhi lu:e qi lu:e pan none fan hua yu yu mu jun yi liu she die chou hua dang chuo ji wan jiang cheng chang tun lei ji cha liu die tuan lin jiang jiang chou bo die die pi nie dan shu shu zhi yi chuangnai ding bi jie liao gong ge jiu zhou xia shan xu nu:e li yang chen you ba jie jue xi xia cui bi yi li zong chuangfeng zhu pao pi gan ke ci xie qi dan zhen fa zhi teng ju ji fei ju dian jia xuan zha bing nie zheng yong jing quan chong tong yi jie wei hui duo yang chi zhi hen ya mei dou jing xiao tong tu mang pi xiao suan pu li zhi cuo duo wu sha lao shou huan xian yi peng zhang guan tan fei ma lin chi ji tian an chi bi bi min gu dui e wei yu cui ya zhu xi dan shen zhong ji yu hou feng la yang shen tu yu gua wen huan ku jia yin yi lou sao jue chi xi guan yi wen ji chuangban lei liu chai shou nu:e dian da bie tan zhang biao shen cu luo yi zong chou zhang zhai sou suo que diao lou lou mo jin yin ying huang fu liao long qiao liu lao xian fei dan yin he ai ban xian guan guai nong yu wei yi yong pi lei li shu dan lin dian lin lai bie ji chi yang xuan jie zheng none li huo lai ji dian xian ying yin qu yong tan dian luo luan luan bo none gui po fa deng fa bai bai qie bi zao zao mao de pa jie huang gui ci ling gao mo ji jiao peng gao ai e hao han bi wan chou qian xi ai jiong hao huang hao ze cui hao xiao ye po hao jiao ai xing huang li piao he jiao pi gan pao zhou jun qiu cun que zha gu jun jun zhou zha gu zhan du min qi ying yu bei zhao zhong pen he ying he yi bo wan he ang zhan yan jian ") .append("he yu kui fan gai dao pan fu qiu sheng dao lu zhan meng lu jin xu jian pan guan an lu xu zhou dang an gu li mu ding gan xu mang mang zhi qi wan tian xiang dun xin xi pan feng dun min ming sheng shi yun mian pan fang miao dan mei mao kan xian kou shi yang zheng yao shen huo da zhen kuang ju shen yi sheng mei mo zhu zhen zhen mian di yuan die yi zi zi chao zha xuan bing mi long sui tong mi die yi er ming xuan chi kuang juan mou zhen tiao yang yan mo zhong mai zhe zheng mei suo shao han huan di cheng cuo juan e wan xian xi kun lai jian shan tian hun wan ling shi qiong lie ya jing zheng li lai sui juan shui sui du pi pi mu hun ni lu gao jie cai zhou yu hun ma xia xing hui gun none chun jian mei du hou xuan ti kui gao rui mao xu fa wen miao chou kui mi weng kou dang chen ke sou xia qiong mao ming man shui ze zhang yi diao kou mo shun cong lou chi man piao cheng ji meng huan run pie xi qiao pu zhu deng shen shun liao che xian kan ye xu tong wu lin kui jian ye ai hui zhan jian gu zhao ju wei chou ji ning xun yao huo meng mian bin mian li guang jue xuan mian huo lu meng long guan man xi chu tang kan zhu mao jin lin yu shuo ce jue shi yi shen zhi hou shen ying ju zhou jiao cuo duan ai jiao zeng huo bai shi ding qi ji zi gan wu tuo ku qiang xi fan kuang dang ma sha dan jue li fu min nuo hua kang zhi qi kan jie fen e ya pi zhe yan sui zhuan che dun pan yan none feng fa mo zha qu yu ke tuo tuo di zhai zhen e fu mu zhu la bian nu ping peng ling pao le po bo po shen za ai li long tong none li kuang chu keng quan zhu kuang gui e nao jia lu wei ai luo ken xing yan dong peng xi none hong shuo xia qiao none wei qiao none keng xiao que chan lang hong yu xiao xia mang long none che che wo liu ying mang que yan cuo kun yu none none lu chen jian none song zhuo keng peng yan zhui kong ceng qi zong qing lin jun bo ding min diao jian he liu ai sui que ling bei yin dui wu qi lun wan dian gang bei qi chen ruan yan die ding zhou tuo jie ying bian ke bi wei shuo zhen duan xia dang ti nao peng jian di tan cha none qi none feng xuan que que ma gong nian su e ci liu si tang bang hua pi wei sang lei cuo tian xia xi lian pan wei yun dui zhe ke la none qing gun zhuan chan qi ao peng lu lu kan qiang chen yin lei biao qi mo qi cui zong qing chuo none ji shan lao qu zeng deng jian xi lin ding dian huang pan za qiao di li jian jiao xi zhang qiao dun jian yu zhui he huo zhai lei ke chu ji que dang wo jiang pi pi yu pin qi ai ke jian yu ruan meng pao zi bo none mie ca xian kuang lei lei zhi li li fan que pao ying li long long mo bo shuangguan lan zan yan shi shi li reng she yue si qi ta ma xie yao xian zhi qi zhi beng shu chong none yi shi you zhi tiao fu fu mi zu zhi suan mei zuo qu hu zhu shen sui ci chai mi lu: yu xiang wu tiao piao zhu gui xia zhi ji gao zhen gao shui jin zhen gai kun di dao huo tao qi gu guan zui ling lu bing jin dao zhi lu shan bei zhe hui you xi ") .append(" yin zi huo zhen fu yuan wu xian yang ti yi mei si di none zhuo zhen yong ji gao tang chi ma ta none xuan qi yu xi ji si chan xuan hui sui li nong ni dao li rang yue ti zan lei rou yu yu li xie qin he tu xiu si ren tu zi cha gan yi xian bing nian qiu qiu zhong fen hao yun ke miao zhi jing bi zhi yu mi ku ban pi ni li you zu pi ba ling mo cheng nian qin yang zuo zhi zhi shu ju zi tai ji cheng tong zhi huo he yin zi zhi jie ren du yi zhu hui nong fu xi kao lang fu ze shui lu: kun gan jing ti cheng tu shao shui ya lun lu gu zuo ren zhun bang bai ji zhi zhi kun leng peng ke bing chou zui yu su none none yi xi bian ji fu bi nuo jie zhong zong xu cheng dao wen lian zi yu ji xu zhen zhi dao jia ji gao gao gu rong sui none ji kang mu shan men zhi ji lu su ji ying wen qiu se none yi huang qie ji sui xiao pu jiao zhuo tong none lu: sui nong se hui rang nuo yu none ji tui wen cheng huo gong lu: biao none rang jue li zan xue wa jiu qiong xi qiong kong yu sen jing yao chuan zhun tu lao qie zhai yao bian bao yao bing yu zhu jiao qiao diao wu gui yao zhi chuan yao tiao jiao chuangjiong xiao cheng kou cuan wo dan ku ke zhui xu su none kui dou none yin wo wa ya yu ju qiong yao yao tiao liao yu tian diao ju liao xi wu kui chuangju none kuan long cheng cui piao zao cuan qiao qiong dou zao zao qie li chu shi fu qian chu hong qi qian gong shi shu miao ju zhan zhu ling long bing jing jing zhang yi si jun hong tong song jing diao yi shu jing qu jie ping duan shao zhuan ceng deng cun huai jing kan jing zhu zhu le peng yu chi gan mang zhu none du ji xiao ba suan ji zhen zhao sun ya zhui yuan hu gang xiao cen pi bi jian yi dong shan sheng xia di zhu na chi gu li qie min bao tiao si fu ce ben fa da zi di ling ze nu fu gou fan jia ge fan shi mao po none jian qiong long none bian luo gui qu chi yin yao xian bi qiong gua deng jiao jin quan sun ru fa kuang zhu tong ji da hang ce zhong kou lai bi shai dang zheng ce fu yun tu pa li lang ju guan jian han tong xia zhi cheng suan shi zhu zuo xiao shao ting jia yan gao kuai gan chou kuang gang yun none qian xiao jian pu lai zou bi bi bi ge chi guai yu jian zhao gu chi zheng qing sha zhou lu bo ji lin suan jun fu zha gu kong qian qian jun chui guan yuan ce ju bo ze qie tuo luo dan xiao ruo jian none bian sun xiang xian ping zhen sheng hu shi zhu yue chun fu wu dong shuo ji jie huang xing mei fan chuan zhuan pian feng zhu hong qie hou qiu miao qian none kui none lou yun he tang yue chou gao fei ruo zheng gou nie qian xiao cuan gong pang du li bi zhuo chu shai chi zhu qiang long lan jian bu li hui bi di cong yan peng sen cuan pai piao dou yu mie zhuan ze xi guo yi hu chan kou cu ping zao ji gui su lou zha lu nian suo cuan none suo le duan liang xiao bo mi shai dang liao dan dian fu jian min kui dai qiao deng huang sun lao zan xiao lu shi zan none pai qi pai gan ju du lu yan bo dang sai ke gou qian lian bu zhou lai none la") .append("n kui yu yue hao zhen tai ti mi chou ji none qi teng zhuan zhou fan sou zhou qian kuo teng lu lu jian tuo ying yu lai long none lian lan qian yue zhong qu lian bian duan zuan li shai luo ying yue zhuo xu mi di fan shen zhe shen nu: xie lei xian zi ni cun zhang qian none bi ban wu sha kang rou fen bi cui yin li chi tai none ba li gan ju po mo cu zhan zhou li su tiao li xi su hong tong zi ce yue zhou lin zhuangbai none fen mian qu none liang xian fu liang can jing li yue lu ju qi cui bai chang lin zong jing guo none san san tang bian rou mian hou xu zong hu jian zan ci li xie fu nuo bei gu xiu gao tang qiu none cao zhuangtang mi san fen zao kang jiang mo san san nuo chi liang jiang kuai bo huan shu zong jian nuo tuan nie li zuo di nie tiao lan mi mi jiu xi gong zheng jiu you ji cha zhou xun yue hong yu he wan ren wen wen qiu na zi tou niu fou jie shu chun pi yin sha hong zhi ji fen yun ren dan jin su fang suo cui jiu zha ba jin fu zhi qi zi chou hong zha lei xi fu xie shen bei zhu qu ling zhu shao gan yang fu tuo zhen dai chu shi zhong xian zu jiong ban ju pa shu zui kuang jing ren heng xie jie zhu chou gua bai jue kuang hu ci geng geng tao xie ku jiao quan gai luo xuan beng xian fu gei tong rong tiao yin lei xie quan xu hai die tong si jiang xiang hui jue zhi jian juan chi mian zhen lu: cheng qiu shu bang tong xiao wan qin geng xiu ti xiu xie hong xi fu ting sui dui kun fu jing hu zhi yan jiong feng ji xu none zong lin duo li lu: liang chou quan shao qi qi zhun qi wan qian xian shou wei qi tao wan gang wang beng zhui cai guo cui lun liu qi zhan bei chuo ling mian qi jie tan zong gun zou yi zi xing liang jin fei rui min yu zong fan lu: xu none shang none xu xiang jian ke xian ruan mian ji duan zhong di min miao yuan xie bao si qiu bian huan geng zong mian wei fu wei yu gou miao jie lian zong bian yun yin ti gua zhi yun cheng chan dai jia yuan zong xu sheng none geng none ying jin yi zhui ni bang gu pan zhou jian cuo quan shuangyun xia shuai xi rong tao fu yun zhen gao ru hu zai teng xian su zhen zong tao huang cai bi feng cu li suo yin xi zong lei zhuan qian man zhi lu: mo piao lian mi xuan zong ji shan sui fan shuai beng yi sao mou zhou qiang hun xian xi none xiu ran xuan hui qiao zeng zuo zhi shan san lin yu fan liao chuo zun jian rao chan rui xiu hui hua zuan xi qiang none da sheng hui xi se jian jiang huan qiao cong jie jiao bo chan yi nao sui yi shai xu ji bin qian jian pu xun zuan qi peng li mo lei xie zuan kuang you xu lei xian chan none lu chan ying cai xiang xian zui zuan luo xi dao lan lei lian mi jiu yu hong zhou xian he yue ji wan kuang ji ren wei yun hong chun pi sha gang na ren zong lun fen zhi wen fang zhu zhen niu shu xian gan xie fu lian zu shen xi zhi zhong zhou ban fu chu shao yi jing dai bang rong jie ku rao die hang hui ji xuan jiang luo jue jiao tong geng xiao juan xiu xi sui tao ji ti ji xu ling yin xu qi fei chuo shang gun sheng wei mian shou beng chou tao liu quan ") .append("zong zhan wan lu: zhui zi ke xiang jian mian lan ti miao ji yun hui si duo duan bian xian gou zhui huan di lu: bian min yuan jin fu ru zhen feng cui gao chan li yi jian bin piao man lei ying suo mou sao xie liao shan zeng jiang qian qiao huan jiao zuan fou xie gang fou que fou que bo ping hou none gang ying ying qing xia guan zun tan none qing weng ying lei tan lu guan wang gang wang wang han none luo fu mi fa gu zhu ju mao gu min gang ba gua ti juan fu lin yan zhao zui gua zhuo yu zhi an fa lan shu si pi ma liu ba fa li chao wei bi ji zeng tong liu ji juan mi zhao luo pi ji ji luan yang mie qiang ta mei yang you you fen ba gao yang gu qiang zang gao ling yi zhu di xiu qiang yi xian rong qun qun qian huan suo xian yi yang qiang xian yu geng jie tang yuan xi fan shan fen shan lian lei geng nou qiang chan yu gong yi chong weng fen hong chi chi cui fu xia pen yi la yi pi ling liu zhi qu xi xie xiang xi xi qi qiao hui hui shu se hong jiang zhai cui fei tao sha chi zhu jian xuan shi pian zong wan hui hou he he han ao piao yi lian qu none lin pen qiao ao fan yi hui xuan dao yao lao none kao mao zhe qi gou gou gou die die er shua ruan er nai zhuan lei ting zi geng chao hao yun pa pi chi si qu jia ju huo chu lao lun ji tang ou lou nou jiang pang ze lou ji lao huo you mo huai er zhe ding ye da song qin yun chi dan dan hong geng zhi none nie dan zhen che ling zheng you wa liao long zhi ning tiao er ya die guo none lian hao sheng lie pin jing ju bi di guo wen xu ping cong none none ting yu cong kui lian kui cong lian weng kui lian lian cong ao sheng song ting kui nie zhi dan ning none ji ting ting long yu yu zhao si su yi su si zhao zhao rou yi lei ji qiu ken cao ge di huan huang yi ren xiao ru zhou yuan du gang rong gan cha wo chang gu zhi qin fu fei ban pei pang jian fang zhun you na ang ken ran gong yu wen yao jin pi qian xi xi fei ken jing tai shen zhong zhang xie shen wei zhou die dan fei ba bo qu tian bei gua tai zi ku zhi ni ping zi fu pang zhen xian zuo pei jia sheng zhi bao mu qu hu ke yi yin xu yang long dong ka lu jing nu yan pang kua yi guang hai ge dong zhi jiao xiong xiong er an xing pian neng zi none cheng tiao zhi cui mei xie cui xie mo mai ji xie none kuai sa zang qi nao mi nong luan wan bo wen wan qiu jiao jing you heng cuo lie shan ting mei chun shen xie none juan cu xiu xin tuo pao cheng nei fu dou tuo niao nao pi gu luo li lian zhang cui jie liang shui pi biao lun pian guo juan chui dan tian nei jing jie la ye a ren shen chuo fu fu ju fei qiang wan dong pi guo zong ding wu mei ruan zhuan zhi cou gua ou di an xing nao shu shuan nan yun zhong rou e sai tu yao jian wei jiao yu jia duan bi chang fu xian ni mian wa teng tui bang qian lu: wa shou tang su zhui ge yi bo liao ji pi xie gao lu: bin none chang lu guo pang chuai biao jiang fu tang mo xi zhuan lu: jiao ying lu: zhi xue chun lin tong peng ni chuai liao cui gui xiao teng fan zhi jiao shan hu ") .append(" cui run xin sui fen ying shan gua dan kuai nong tun lian bei yong jue chu yi juan la lian sao tun gu qi cui bin xun nao huo zang xian biao xing kuan la yan lu hu za luo qu zang luan ni za chen qian wo guang zang lin guang zi jiao nie chou ji gao chou mian nie zhi zhi ge jian die zhi xiu tai zhen jiu xian yu cha yao yu chong xi xi jiu yu yu xing ju jiu xin she she she jiu shi tan shu shi tian dan pu pu guan hua tian chuan shun xia wu zhou dao chuan shan yi none pa tai fan ban chuan hang fang ban bi lu zhong jian cang ling zhu ze duo bo xian ge chuan jia lu hong pang xi none fu zao feng li shao yu lang ting none wei bo meng nian ju huang shou zong bian mao die none bang cha yi sou cang cao lou dai none yao chong none dang qiang lu yi jie jian huo meng qi lu lu chan shuanggen liang jian jian se yan fu ping yan yan cao cao yi le ting jiao ai nai tiao jiao jie peng wan yi chai mian mi gan qian yu yu shao xiong du xia qi mang zi hui sui zhi xiang bi fu tun wei wu zhi qi shan wen qian ren fou kou jie lu zhu ji qin qi yan fen ba rui xin ji hua hua fang wu jue gou zhi yun qin ao chu mao ya fei reng hang cong yin you bian yi none wei li pi e xian chang cang zhu su yi yuan ran ling tai tiao di miao qing li rao ke mu pei bao gou min yi yi ju pie ruo ku zhu ni bo bing shan qiu yao xian ben hong ying zha dong ju die nie gan hu ping mei fu sheng gu bi wei fu zhuo mao fan qie mao mao ba zi mo zi di chi gou jing long none niao none xue ying qiong ge ming li rong yin gen qian chai chen yu xiu zi lie wu duo kui ce jian ci gou guang mang cha jiao jiao fu yu zhu zi jiang hui yin cha fa rong ru chong mang tong zhong none zhu xun huan kua quan gai da jing xing chuan cao jing er an shou chi ren jian ti huang ping li jin lao rong zhuangda jia rao bi ce qiao hui ji dang none rong hun ying luo ying qian jin sun yin mai hong zhou yao du wei chu dou fu ren yin he bi bu yun di tu sui sui cheng chen wu bie xi geng li pu zhu mo li zhuangji duo qiu sha suo chen feng ju mei meng xing jing che xin jun yan ting you cuo guan han you cuo jia wang you niu shao xian lang fu e mo wen jie nan mu kan lai lian shi wo tu xian huo you ying ying none chun mang mang ci yu jing di qu dong jian zou gu la lu ju wei jun nie kun he pu zai gao guo fu lun chang chou song chui zhan men cai ba li tu bo han bao qin juan xi qin di jie pu dang jin zhao tai geng hua gu ling fei jin an wang beng zhou yan zu jian lin tan shu tian dao hu ji he cui tao chun bei chang huan fei lai qi meng ping wei dan sha huan yan yi tiao qi wan ce nai none tuo jiu tie luo none none meng none none ding ying ying ying xiao sa qiu ke xiang wan yu yu fu lian xuan xuan nan ze wo chun xiao yu pian mao an e luo ying huo gua jiang wan zuo zuo ju bao rou xi xie an qu jian fu lu: lu: pen feng hong hong hou yan tu zhu zi xiang shen ge qia jing mi huang shen pu ge dong zhou qian wei bo wei pa ji hu zang ji") .append("a duan yao jun cong quan wei xian kui ting hun xi shi qi lan zong yao yuan mei yun shu di zhuan guan none qiong chan kai kui none jiang lou wei pai none sou yin shi chun shi yun zhen lang nu meng he que suan yuan li ju xi bang chu xu tu liu huo zhen qian zu po cuo yuan chu yu kuai pan pu pu na shuo xi fen yun zheng jian ji ruo cang en mi hao sun zhen ming none xu liu xi gu lang rong weng gai cuo shi tang luo ru suo xian bei yao gui bi zong gun none xiu ce none lan none ji li can lang yu none ying mo diao xiu wu tong zhu peng an lian cong xi ping qiu jin chun jie wei tui cao yu yi ji liao bi lu xu bu zhang luo qiang man yan leng ji biao gun han di su lu she shang di mie xun man bo di cuo zhe sen xuan yu hu ao mi lou cu zhong cai po jiang mi cong niao hui jun yin jian nian shu yin kui chen hu sha kou qian ma cang ze qiang dou lian lin kou ai bi li wei ji qian sheng fan meng ou chan dian xun jiao rui rui lei yu qiao chu hua jian mai yun bao you qu lu rao hui e ti fei jue zui fa ru fen kui shun rui ya xu fu jue dang wu tong si xiao xi yong wen shao qi jian yun sun ling yu xia weng ji hong si deng lei xuan yun yu xi hao bo hao ai wei hui wei ji ci xiang luan mie yi leng jiang can shen qiang lian ke yuan da ti tang xue bi zhan sun lian fan ding xiao gu xie shu jian kao hong sa xin xun yao bai sou shu xun dui pin wei neng chou mai ru piao tai qi zao chen zhen er ni ying gao cong xiao qi fa jian xu kui jie bian di mi lan jin zang miao qiong qie xian none ou xian su lu: yi xu xie li yi la lei jiao di zhi pi teng yao mo huan biao fan sou tan tui qiong qiao wei liu hui shu gao yun none li zhu zhu ai lin zao xuan chen lai huo tuo wu rui rui qi heng lu su tui mang yun pin yu xun ji jiong xuan mo none su jiong none nie bo rang yi xian yu ju lian lian yin qiang ying long tou wei yue ling qu yao fan mi lan kui lan ji dang none lei lei tong feng zhi wei kui zhan huai li ji mi lei huai luo ji nao lu jian none none lei quan xiao yi luan men bie hu hu lu nu:e lu: zhi xiao qian chu hu xu cuo fu xu xu lu hu yu hao jiao ju guo bao yan zhan zhan kui ban xi shu chong qiu diao ji qiu ding shi none di zhe she yu gan zi hong hui meng ge sui xia chai shi yi ma xiang fang e pa chi qian wen wen rui bang pi yue yue jun qi ran yin qi can yuan jue hui qian qi zhong ya hao mu wang fen fen hang gong zao fu ran jie fu chi dou bao xian ni te qiu you zha ping chi you he han ju li fu ran zha gou pi bo xian zhu diao bie bing gu ran qu she tie ling gu dan gu ying li cheng qu mou ge ci hui hui mang fu yang wa lie zhu yi xian kuo jiao li yi ping ji ha she yi wang mo qiong qie gui gong zhi man none zhe jia nao si qi xing lie qiu shao yong jia tui che bai e han shu xuan feng shen zhen fu xian zhe wu fu li lang bi chu yuan you jie dan yan ting dian tui hui wo zhi song fei ju mi qi qi yu jun la meng qiang si xi ") .append("lun li die tiao tao kun gan han yu bang fei pi wei dun yi yuan su quan qian rui ni qing wei liang guo wan dong e ban zhuo wang can yang ying guo chan none la ke ji xie ting mai xu mian yu jie shi xuan huang yan bian rou wei fu yuan mei wei fu ruan xie you you mao xia ying shi chong tang zhu zong ti fu yuan kui meng la du hu qiu die li gua yun ju nan lou chun rong ying jiang tun lang pang si xi xi xi yuan weng lian sou ban rong rong ji wu xiu han qin yi bi hua tang yi du nai he hu xi ma ming yi wen ying teng yu cang none none man none shang shi cao chi di ao lu wei zhi tang chen piao qu pi yu jian luo lou qin zhong yin jiang shuai wen jiao wan zhe zhe ma ma guo liao mao xi cong li man xiao none zhang mang xiang mo zi si qiu te zhi peng peng jiao qu bie liao pan gui xi ji zhuan huang fei lao jue jue hui yin chan jiao shan rao xiao wu chong xun si none cheng dang li xie shan yi jing da chan qi zi xiang she luo qin ying chai li ze xuan lian zhu ze xie mang xie qi rong jian meng hao ru huo zhuo jie bin he mie fan lei jie la mi li chun li qiu nie lu du xiao zhu long li long feng ye pi rang gu juan ying none xi can qu quan du can man qu jie zhu zha xue huang nu: pei nu: xin zhong mo er mie mie shi xing yan kan yuan none ling xuan shu xian tong long jie xian ya hu wei dao chong wei dao zhun heng qu yi yi bu gan yu biao cha yi shan chen fu gun fen shuai jie na zhong dan ri zhong zhong xie qi xie ran zhi ren qin jin jun yuan mei chai ao niao hui ran jia tuo ling dai bao pao yao zuo bi shao tan ju he xue xiu zhen yi pa bo di wa fu gun zhi zhi ran pan yi mao none na kou xuan chan qu bei yu xi none bo none fu yi chi ku ren jiang jia cun mo jie er ge ru zhu gui yin cai lie none none zhuangdang none kun ken niao shu jia kun cheng li juan shen pou ge yi yu chen liu qiu qun ji yi bu zhuangshui sha qun li lian lian ku jian fou tan bi gun tao yuan ling chi chang chou duo biao liang shang pei pei fei yuan luo guo yan du ti zhi ju qi ji zhi gua ken none ti shi fu chong xie bian die kun duan xiu xiu he yuan bao bao fu yu tuan yan hui bei chu lu: none none yun ta gou da huai rong yuan ru nai jiong suo ban tun chi sang niao ying jie qian huai ku lian lan li zhe shi lu: yi die xie xian wei biao cao ji qiang sen bao xiang none pu jian zhuan jian zui ji dan za fan bo xiang xin bie rao man lan ao duo hui cao sui nong chan lian bi jin dang shu tan bi lan pu ru zhi none shu wa shi bai xie bo chen lai long xi xian lan zhe dai none zan shi jian pan yi none ya xi xi yao feng tan none none fu ba he ji ji jian guan bian yan gui jue pian mao mi mi mie shi si zhan luo jue mo tiao lian yao zhi jun xi shan wei xi tian yu lan e du qin pang ji ming ping gou qu zhan jin guan deng jian luo qu jian wei jue qu luo lan shen di guan jian guan yan gui mi shi chan lan jue ji xi di tian yu gou jin qu jiao jiu jin cu jue zhi chao ji gu dan zui di shan") .append("g hua quan ge zhi jie gui gong chu jie huan qiu xing su ni ji lu zhi zhu bi xing hu shang gong zhi xue chu xi yi li jue xi yan xi yan yan ding fu qiu qiu jiao hong ji fan xun diao hong cha tao xu jie yi ren xun yin shan qi tuo ji xun yin e fen ya yao song shen yin xin jue xiao ne chen you zhi xiong fang xin chao she xian sa zhun xu yi yi su chi he shen he xu zhen zhu zheng gou zi zi zhan gu fu jian die ling di yang li nao pan zhou gan shi ju ao zha tuo yi qu zhao ping bi xiong chu ba da zu tao zhu ci zhe yong xu xun yi huang he shi cha jiao shi hen cha gou gui quan hui jie hua gai xiang hui shen chou tong mi zhan ming e hui yan xiong gua er beng tiao chi lei zhu kuang kua wu yu teng ji zhi ren su lang e kuang e^ shi ting dan bei chan you heng qiao qin shua an yu xiao cheng jie xian wu wu gao song pu hui jing shuo zhen shuo du none chang shui jie ke qu cong xiao sui wang xuan fei chi ta yi na yin diao pi chuo chan chen zhun ji qi tan chui wei ju qing jian zheng ze zou qian zhuo liang jian zhu hao lun shen biao huai pian yu die xu pian shi xuan shi hun hua e zhong di xie fu pu ting jian qi yu zi chuan xi hui yin an xian nan chen feng zhu yang yan heng xuan ge nuo qi mou ye wei none teng zou shan jian bo none huang huo ge ying mi xiao mi xi qiang chen nu:e si su bang chi qian shi jiang yuan xie xue tao yao yao hu yu biao cong qing li mo mo shang zhe miu jian ze zha lian lou can ou guan xi zhuo ao ao jin zhe yi hu jiang man chao han hua chan xu zeng se xi she dui zheng nao lan e ying jue ji zun jiao bo hui zhuan wu jian zha shi qiao tan zen pu sheng xuan zao zhan dang sui qian ji jiao jing lian nou yi ai zhan pi hui hua yi yi shan rang nou qian zhui ta hu zhou hao ni ying jian yu jian hui du zhe xuan zan lei shen wei chan li yi bian zhe yan e chou wei chou yao chan rang yin lan chen huo zhe huan zan yi dang zhan yan du yan ji ding fu ren ji jie hong tao rang shan qi tuo xun yi xun ji ren jiang hui ou ju ya ne xu e lun xiong song feng she fang jue zheng gu he ping zu shi xiong zha su zhen di zhou ci qu zhao bi yi yi kuang lei shi gua shi jie hui cheng zhu shen hua dan gou quan gui xun yi zheng gai xiang cha hun xu zhou jie wu yu qiao wu gao you hui kuang shuo song ei qing zhu zou nuo du zhuo fei ke wei yu shei shen diao chan liang zhun sui tan shen yi mou chen die huang jian xie xue ye wei e yu xuan chan zi an yan di mi pian xu mo dang su xie yao bang shi qian mi jin man zhe jian miu tan jian qiao lan pu jue yan qian zhan chen gu qian hong ya jue hong han hong qi xi huo liao han du long dou jiang qi chi feng deng wan bi shu xian feng zhi zhi yan yan shi chu hui tun yi tun yi jian ba hou e cu xiang huan jian ken gai qu fu xi bin hao yu zhu jia fen xi hu wen huan bin di zong fen yi zhi bao chai han pi na pi gou duo you diao mo si xiu huan kun he he mo an mao li ni bi yu jia tuan mao pi xi e ju") .append(" mo chu tan huan qu bei zhen yuan fu cai gong te yi hang wan pin huo fan tan guan ze zhi er zhu shi bi zi er gui pian bian mai dai sheng kuang fei tie yi chi mao he bi lu lin hui gai pian zi jia xu zei jiao gai zang jian ying xun zhen she bin bin qiu she chuan zang zhou lai zan si chen shang tian pei geng xian mai jian sui fu dan cong cong zhi ji zhang du jin xiong shun yun bao zai lai feng cang ji sheng ai zhuan fu gou sai ze liao wei bai chen zhuan zhi zhui biao yun zeng tan zan yan none shan wan ying jin gan xian zang bi du shu yan none xuan long gan zang bei zhen fu yuan gong cai ze xian bai zhang huo zhi fan tan pin bian gou zhu guan er jian bi shi tie gui kuang dai mao fei he yi zei zhi jia hui zi lin lu zang zi gai jin qiu zhen lai she fu du ji shu shang ci bi zhou geng pei dan lai feng zhui fu zhuan sai ze yan zan yun zeng shan ying gan chi xi she nan xiong xi cheng he cheng zhe xia tang zou zou li jiu fu zhao gan qi shan qiong qin xian ci jue qin chi ci chen chen die ju chao di se zhan zhu yue qu jie chi chu gua xue zi tiao duo lie gan suo cu xi zhao su yin ju jian que tang chuo cui lu qu dang qiu zi ti qu chi huang qiao qiao yao zao yue none zan zan zu pa bao ku he dun jue fu chen jian fang zhi ta yue pa qi yue qiang tuo tai yi nian ling mei ba die ku tuo jia ci pao qia zhu ju die zhi fu pan ju shan bo ni ju li gen yi ji dai xian jiao duo chu quan kua zhuai gui qiong kui xiang chi lu beng zhi jia tiao cai jian da qiao bi xian duo ji ju ji shu tu chu xing nie xiao bo xue qun mou shu liang yong jiao chou xiao none ta jian qi wo wei chuo jie ji nie ju ju lun lu leng huai ju chi wan quan ti bo zu qie qi cu zong cai zong pan zhi zheng dian zhi yu duo dun chun yong zhong di zha chen chuai jian gua tang ju fu zu die pian rou nuo ti cha tui jian dao cuo xi ta qiang zhan dian ti ji nie pan liu zhan bi chong lu liao cu tang dai su xi kui ji zhi qiang di man zong lian beng zao nian bie tui ju deng ceng xian fan chu zhong dun bo cu zu jue jue lin ta qiao qiao pu liao dun cuan kuang zao ta bi bi zhu ju chu qiao dun chou ji wu yue nian lin lie zhi li zhi chan chu duan wei long lin xian wei zuan lan xie rang xie nie ta qu jie cuan zuan xi kui jue lin shen gong dan none qu ti duo duo gong lang none luo ai ji ju tang none none yan none kang qu lou lao duo zhi none ti dao none yu che ya gui jun wei yue xin di xuan fan ren shan qiang shu tun chen dai e na qi mao ruan ren qian zhuan hong hu qu huang di ling dai ao zhen fan kuang ang peng bei gu gu pao zhu rong e ba zhou zhi yao ke yi qing shi ping er qiong ju jiao guang lu kai quan zhou zai zhi ju liang yu shao you huan yun zhe wan fu qing zhou ni ling zhe zhan liang zi hui wang chuo guo kan yi peng qian gun nian ping guan bei lun pai liang ruan rou ji yang xian chuan cou chun ge you hong shu fu zi fu wen ben zhan yu wen tao gu zhen xia yuan lu jiu chao zhuan wei hun none che jiao zhan ") .append("pu lao fen fan lin ge se kan huan yi ji dui er yu xian hong lei pei li li lu lin che ya gui xuan dai ren zhuan e lun ruan hong gu ke lu zhou zhi yi hu zhen li yao qing shi zai zhi jiao zhou quan lu jiao zhe fu liang nian bei hui gun wang liang chuo zi cou fu ji wen shu pei yuan xia zhan lu zhe lin xin gu ci ci pi zui bian la la ci xue ban bian bian bian none bian ban ci bian bian chen ru nong nong zhen chuo chuo none reng bian bian none none liao da chan gan qian yu yu qi xun yi guo mai qi za wang none zhun ying ti yun jin hang ya fan wu ta e hai zhei none jin yuan wei lian chi che ni tiao zhi yi jiong jia chen dai er di po wang die ze tao shu tuo none jing hui tong you mi beng ji nai yi jie zhui lie xun tui song shi tao pang hou ni dun jiong xuan xun bu you xiao qiu tou zhu qiu di di tu jing ti dou yi zhe tong guang wu shi cheng su zao qun feng lian suo hui li none zui ben cuo jue beng huan dai lu you zhou jin yu chuo kui wei ti yi da yuan luo bi nuo yu dang sui dun sui yan chuan chi ti yu shi zhen you yun e bian guo e xia huang qiu dao da wei none yi gou yao chu liu xun ta di chi yuan su ta qian none yao guan zhang ao shi ce su su zao zhe dun zhi lou chi cuo lin zun rao qian xuan yu yi wu liao ju shi bi yao mai xie sui huan zhan deng er miao bian bian la li yuan you luo li yi ting deng qi yong shan han yu mang ru qiong none kuang fu kang bin fang xing nei none shen bang yuan cun huo xie bang wu ju you han tai qiu bi pi bing shao bei wa di zou ye lin kuang gui zhu shi ku yu gai he qie zhi ji xun hou xing jiao xi gui nuo lang jia kuai zheng lang yun yan cheng dou xi lu: fu wu fu gao hao lang jia geng jun ying bo xi bei li yun bu xiao qi pi qing guo none tan zou ping lai ni chen you bu xiang dan ju yong qiao yi dou yan mei ruo bei e yu juan yu yun hou kui xiang xiang sou tang ming xi ru chu zi zou ju wu xiang yun hao yong bi mao chao fu liao yin zhuan hu qiao yan zhang fan wu xu deng bi xin bi ceng wei zheng mao shan lin po dan meng ye cao kuai feng meng zou kuang lian zan chan you qi yan chan cuo ling huan xi feng zan li you ding qiu zhuo pei zhou yi gan yu jiu yan zui mao dan xu tou zhen fen none none yun tai tian qia tuo zuo han gu su fa chou dai ming lao chuo chou you tong zhi xian jiang cheng yin tu jiao mei ku suan lei pu zui hai yan shi niang wei lu lan yan tao pei zhan chun tan zui chuo cu kun ti xian du hu xu xing tan qiu chun yun fa ke sou mi quan chou cuo yun yong ang zha hai tang jiang piao lao yu li zao lao yi jiang bu jiao xi tan fa nong yi li ju yan yi niang ru xun chou yan ling mi mi niang xin jiao shi mi yan bian cai shi you shi shi li zhong ye liang li jin jin ga yi liao dao zhao ding li qiu he fu zhen zhi ba luan fu nai diao shan qiao kou chuan zi fan yu hua han gong qi mang jian di si xi yi chai ta tu xi nu: qian none jian pi ye yin ba fang chen jian tou yue yan fu bu ") .append(" na xin e jue dun gou yin qian ban ji ren chao niu fen yun yi qin pi guo hong yin jun shi yi zhong nie gai ri huo tai kang none lu none none duo zi ni tu shi min gu ke ling bing yi gu ba pi yu si zuo bu you dian jia zhen shi shi tie ju zhan ta she xuan zhao bao he bi sheng chu shi bo zhu chi za po tong qian fu zhai liu qian fu li yue pi yang ban bo jie gou shu zheng mu ni xi di jia mu tan shen yi si kuang ka bei jian tong xing hong jiao chi er ge bing shi mou jia yin jun zhou chong shang tong mo lei ji yu xu ren cun zhi qiong shan chi xian xing quan pi yi zhu hou ming kua yao xian xian xiu jun cha lao ji yong ru mi yi yin guang an diu you se kao qian luan none ai diao han rui shi keng qiu xiao zhe xiu zang ti cuo gua gong zhong dou lu: mei lang wan xin yun bei wu su yu chan ting bo han jia hong cuan feng chan wan zhi si xuan wu wu tiao gong zhuo lu:e xing qin shen han none ye chu zeng ju xian e mang pu li shi rui cheng gao li te none zhu none tu liu zui ju chang yuan jian gang diao tao chang lun guo ling bei lu li qing pei juan min zui peng an pi xian ya zhui lei a kong ta kun du wei chui zi zheng ben nie cong chun tan ding qi qian zhuo qi yu jin guan mao chang dian xi lian tao gu cuo shu zhen lu meng lu hua biao ga lai ken zhui none nai wan zan none de xian none huo liang none men kai ying di lian guo xian du tu wei cong fu rou ji e rou chen ti zha hong yang duan xia yu keng xing huang wei fu zhao cha qie she hong kui nuo mou qiao qiao hou zhen huo huan ye min jian duan jian si kui hu xuan zang jie zhen bian zhong zi xiu ye mei pai ai jie none mei cha ta bang xia lian suo xi liu zu ye nou weng rong tang suo qiang ge shuo chui bo pan ta bi sang gang zi wu ying huang tiao liu kai sun sha sou wan hao zhen zhen luo yi yuan tang nie xi jia ge ma juan rong none suo none none none na lu suo kou zu tuan xiu guan xuan lian shou ao man mo luo bi wei liu di qiao huo yin lu ao keng qiang cui qi chang tang man yong chan feng jing biao shu lou xiu cong long zan jian cao li xia xi kang none beng none none zheng lu hua ji pu hui qiang po lin suo xiu san cheng kui san liu nao huang pie sui fan qiao chuan yang tang xiang jue jiao zun liao jie lao dui tan zan ji jian zhong deng lou ying dui jue nou ti pu tie none none ding shan kai jian fei sui lu juan hui yu lian zhuo qiao qian zhuo lei bi tie huan ye duo guo dang ju fen da bei yi ai dang xun diao zhu heng zhui ji nie ta huo qing bin ying kui ning xu jian jian qiang cha zhi mie li lei ji zuan kuang shang peng la du shuo chuo lu: biao bao lu none none long e lu xin jian lan bo jian yao chan xiang jian xi guan cang nie lei cuan qu pan luo zuan luan zao nie jue tang shu lan jin ga yi zhen ding zhao po liao tu qian chuan shan sa fan diao men nu: yang chai xing gai bu tai ju dun chao zhong na bei gang ban qian yao qin jun wu gou kang fang huo tou niu ba yu qian zheng qian gu bo ke po bu bo yue zuan mu tan jia dian you ti") .append("e bo ling shuo qian mao bao shi xuan tuo bi ni pi duo xing kao lao er mang ya you cheng jia ye nao zhi dang tong lu: diao yin kai zha zhu xian ting diu xian hua quan sha ha yao ge ming zheng se jiao yi chan chong tang an yin ru zhu lao pu wu lai te lian keng xiao suo li zeng chu guo gao e xiu cuo lu:e feng xin liu kai jian rui ti lang qin ju a qing zhe nuo cuo mao ben qi de ke kun chang xi gu luo chui zhui jin zhi xian juan huo pei tan ding jian ju meng zi qie ying kai qiang si e cha qiao zhong duan sou huang huan ai du mei lou zi fei mei mo zhen bo ge nie tang juan nie na liu hao bang yi jia bin rong biao tang man luo beng yong jing di zu xuan liu chan jue liao pu lu dun lan pu cuan qiang deng huo lei huan zhuo lian yi cha biao la chan xiang chang chang jiu ao die qu liao mi zhang men ma shuan shan huo men yan bi han bi none kai kang beng hong run san xian xian jian min xia min dou zha nao none peng ke ling bian bi run he guan ge he fa chu hong gui min none kun lang lu: ting sha yan yue yue chan qu lin chang shai kun yan min yan e hun yu wen xiang none xiang qu yao wen ban an wei yin kuo que lan du none none tian nie da kai he que chuangguan dou qi kui tang guan piao kan xi hui chan pi dang huan ta wen none men shuan shan yan han bi wen chuangrun wei xian hong jian min kang men zha nao gui wen ta min lu: kai fa ge he kun jiu yue lang du yu yan chang xi wen hun yan yan chan lan qu hui kuo que he tian da que kan huan fu fu le dui xin qian wu yi tuo yin yang dou e sheng ban pei keng yun ruan zhi pi jing fang yang yin zhen jie cheng e qu di zu zuo dian ling a tuo tuo po bing fu ji lu long chen xing duo lou mo jiang shu duo xian er gui wu gai shan jun qiao xing chun fu bi shan shan sheng zhi pu dou yuan zhen chu xian zhi nie yun xian pei pei zou yi dui lun yin ju chui chen pi ling tao xian lu none xian yin zhu yang reng shan chong yan yin yu ti yu long wei wei nie dui sui an huang jie sui yin gai yan hui ge yun wu wei ai xi tang ji zhang dao ao xi yin sa rao lin tui deng pi sui sui yu xian fen ni er ji dao xi yin zhi hui long xi li li li zhui he zhi sun juan nan yi que yan qin ya xiong ya ji gu huan zhi gou jun ci yong ju chu hu za luo yu chou diao sui han huo shuangguan chu za yong ji sui chou liu li nan xue za ji ji yu yu xue na fou se mu wen fen pang yun li li yang ling lei an bao meng dian dang hang wu zhao xu ji mu chen xiao zha ting zhen pei mei ling qi chou huo sha fei weng zhan ying ni chou tun lin none dong ying wu ling shuangling xia hong yin mai mo yun liu meng bin wu wei kuo yin xi yi ai dan deng xian yu lu long dai ji pang yang ba pi wei none xi ji mai meng meng lei li huo ai fei dai long ling ai feng li bao none he he bing qing qing jing qi zhen jing cheng qing jing jing dian jing tian fei fei kao mi mian mian pao ye tian hui ye ge ding ren jian ren di du wu ren qin jin xue niu ba yin sa ren ") .append("mo zu da ban yi yao tao bei jia hong pao yang mo yin jia tao ji xie an an hen gong gong da qiao ting man ying sui tiao qiao xuan kong beng ta zhang bing kuo ju la xie rou bang yi qiu qiu he xiao mu ju jian bian di jian none tao gou ta bei xie pan ge bi kuo tang lou gui qiao xue ji jian jiang chan da huo xian qian du wa jian lan wei ren fu mei juan ge wei qiao han chang none rou xun she wei ge bei tao gou yun gao bi wei hui shu wa du wei ren fu han wei yun tao jiu jiu xian xie xian ji yin za yun shao luo peng huang ying yun peng yin yin xiang hu ye ding qing pan xiang shun han xu yi xu gu song kui qi hang yu wan ban dun di dan pan po ling cheng jing lei he qiao e e wei jie gua shen yi yi ke dui pian ping lei fu jia tou hui kui jia le ting cheng ying jun hu han jing tui tui pin lai tui zi zi chui ding lai yan han qian ke cui jiong qin yi sai ti e e yan hun kan yong zhuan yan xian xin yi yuan sang dian dian jiang ku lei liao piao yi man qi yao hao qiao gu xun qian hui zhan ru hong bin xian pin lu lan nie quan ye ding qing han xiang shun xu xu wan gu dun qi ban song hang yu lu ling po jing jie jia ting he ying jiong ke yi pin hui tui han ying ying ke ti yong e zhuan yan e nie man dian sang hao lei zhan ru pin quan feng biao none fu xia zhan biao sa fa tai lie gua xuan shao ju biao si wei yang yao sou kai sao fan liu xi liao piao piao liu biao biao biao liao none se feng biao feng yang zhan biao sa ju si sou yao liu piao biao biao fei fan fei fei shi shi can ji ding si tuo jian sun xiang tun ren yu juan chi yin fan fan sun yin zhu yi zhai bi jie tao liu ci tie si bao shi duo hai ren tian jiao jia bing yao tong ci xiang yang yang er yan le yi can bo nei e bu jun dou su yu shi yao hun guo shi jian zhui bing xian bu ye tan fei zhang wei guan e nuan hun hu huang tie hui jian hou he xing fen wei gu cha song tang bo gao xi kui liu sou tao ye yun mo tang man bi yu xiu jin san kui zhuan shan chi dan yi ji rao cheng yong tao hui xiang zhan fen hai meng yan mo chan xiang luo zuan nang shi ding ji tuo xing tun xi ren yu chi fan yin jian shi bao si duo yi er rao xiang he le jiao xi bing bo dou e yu nei jun guo hun xian guan cha kui gu sou chan ye mo bo liu xiu jin man san zhuan nang shou kui guo xiang fen ba ni bi bo tu han fei jian yan ai fu xian wen xin fen bin xing ma yu feng han di tuo tuo chi xun zhu zhi pei xin ri sa yin wen zhi dan lu: you bo bao kuai tuo yi qu wen qu jiong bo zhao yuan peng zhou ju zhu nu ju pi zang jia ling zhen tai fu yang shi bi tuo tuo si liu ma pian tao zhi rong teng dong xun quan shen jiong er hai bo none yin luo none dan xie liu ju song qin mang liang han tu xuan tui jun e cheng xing ai lu zhui zhou she pian kun tao lai zong ke qi qi yan fei sao yan jie yao wu pian cong pian qian fei huang jian huo yu ti quan xia zong kui rou si gua tuo kui sou qian cheng zhi liu pang teng xi cao ") .append(" du yan yuan zou sao shan li zhi shuanglu xi luo zhang mo ao can piao cong qu bi zhi yu xu hua bo su xiao lin zhan dun liu tuo zeng tan jiao tie yan luo zhan jing yi ye tuo bin zou yan peng lu: teng xiang ji shuangju xi huan li biao ma yu tuo xun chi qu ri bo lu: zang shi si fu ju zou zhu tuo nu jia yi tai xiao ma yin jiao hua luo hai pian biao li cheng yan xing qin jun qi qi ke zhui zong su can pian zhi kui sao wu ao liu qian shan piao luo cong zhan zhou ji shuangxiang gu wei wei wei yu gan yi ang tou jie bo bi ci ti di ku hai qiao hou kua ge tui geng pian bi ke qia yu sui lou bo xiao bang bo cuo kuan bin mo liao lou nao du zang sui ti bin kuan lu gao gao qiao kao qiao lao zao biao kun kun ti fang xiu ran mao dan kun bin fa tiao pi zi fa ran ti pao pi mao fu er rong qu none xiu gua ji peng zhua shao sha ti li bin zong ti peng song zheng quan zong shun jian duo hu la jiu qi lian zhen bin peng mo san man man seng xu lie qian qian nong huan kuai ning bin lie rang dou dou nao hong xi dou kan dou dou jiu chang yu yu li juan fu qian gui zong liu gui shang yu gui mei ji qi jie kui hun ba po mei xu yan xiao liang yu tui qi wang liang wei jian chi piao bi mo ji xu chou yan zhan yu dao ren ji ba hong tuo diao ji yu e que sha hang tun mo gai shen fan yuan pi lu wen hu lu za fang fen na you none none he xia qu han pi ling tuo ba qiu ping fu bi ji wei ju diao ba you gun pi nian xing tai bao fu zha ju gu none none none ta jie shua hou xiang er an wei tiao zhu yin lie luo tong yi qi bing wei jiao pu gui xian ge hui none none kao none duo jun ti mian shao za suo qin yu nei zhe gun geng none wu qiu ting fu huan chou li sha sha gao meng none none none none yong ni zi qi qing xiang nei chun ji diao qie gu zhou dong lai fei ni yi kun lu jiu chang jing lun ling zou li meng zong zhi nian none none none shi sao hun ti hou xing ju la zong ji bian bian huan quan ji wei wei yu chun rou die huang lian yan qiu qiu jian bi e yang fu sai jian ha tuo hu none ruo none wen jian hao wu pang sao liu ma shi shi guan zi teng ta yao ge rong qian qi wen ruo none lian ao le hui min ji tiao qu jian sao man xi qiu biao ji ji zhu jiang qiu zhuan yong zhang kang xue bie jue qu xiang bo jiao xun su huang zun shan shan fan gui lin xun miao xi none xiang fen guan hou kuai zei sao zhan gan gui sheng li chang none none ai ru ji xu huo none li lie li mie zhen xiang e lu guan li xian yu dao ji you tun lu fang ba ke ba ping nian lu you zha fu ba bao hou pi tai gui jie kao wei er tong zei hou kuai ji jiao xian zha xiang xun geng li lian jian li shi tiao gun sha huan jun ji yong qing ling qi zou fei kun chang gu ni nian diao jing shen shi zi fen die bi chang ti wen wei sai e qiu fu huang quan jiang bian sao ao qi ta guan yao pang jian le biao xue bie man min yong wei xi gui shan lin zun hu gan li shan guan niao yi fu li jiu bu ya") .append("n fu diao ji feng none gan shi feng ming bao yuan zhi hu qian fu fen wen jian shi yu fou yiao ju jue pi huan zhen bao yan ya zheng fang feng wen ou te jia nu ling mie fu tuo wen li bian zhi ge yuan zi qu xiao chi dan ju you gu zhong yu yang rong ya zhi yu none ying zhui wu er gua ai zhi yan heng jiao ji lie zhu ren ti hong luo ru mou ge ren jiao xiu zhou chi luo none none none luan jia ji yu huan tuo bu wu juan yu bo xun xun bi xi jun ju tu jing ti e e kuang hu wu shen la none none lu bing shu fu an zhao peng qin qian bei diao lu que jian ju tu ya yuan qi li ye zhui kong duo kun sheng qi jing ni e jing zi lai dong qi chun geng ju qu none none ji shu none chi miao rou fu qiu ti hu ti e jie mao fu chun tu yan he yuan pian yun mei hu ying dun mu ju none cang fang ge ying yuan xuan weng shi he chu tang xia ruo liu ji gu jian zhun han zi ci yi yao yan ji li tian kou ti ti ni tu ma jiao liu zhen chen li zhuan zhe ao yao yi ou chi zhi liao rong lou bi shuangzhuo yu wu jue yin tan si jiao yi hua bi ying su huang fan jiao liao yan kao jiu xian xian tu mai zun yu ying lu tuan xian xue yi pi shu luo qi yi ji zhe yu zhan ye yang pi ning hu mi ying meng di yue yu lei bo lu he long shuangyue ying guan qu li luan niao jiu ji yuan ming shi ou ya cang bao zhen gu dong lu ya xiao yang ling chi qu yuan xue tuo si zhi er gua xiu heng zhou ge luan hong wu bo li juan hu e yu xian ti wu que miao an kun bei peng qian chun geng yuan su hu he e gu qiu ci mei wu yi yao weng liu ji yi jian he yi ying zhe liu liao jiao jiu yu lu huan zhan ying hu meng guan shuanglu jin ling jian xian cuo jian jian yan cuo lu you cu ji biao cu pao zhu jun zhu jian mi mi wu liu chen jun lin ni qi lu jiu jun jing li xiang yan jia mi li she zhang lin jing qi ling yan cu mai mai ge chao fu mian mian fu pao qu qu mou fu xian lai qu mian chi feng fu qu mian ma ma mo hui none zou nen fen huang huang jin guang tian tou hong xi kuang hong shu li nian chi hei hei yi qian zhen xi tuan mo mo qian dai chu you dian yi xia yan qu mei yan qing yu li dang du can yin an yan tan an zhen dai can yi mei dan yan du lu zhi fen fu fu min min yuan cu qu chao wa zhu zhi mang ao bie tuo bi yuan chao tuo ding mi nai ding zi gu gu dong fen tao yuan pi chang gao qi yuan tang teng shu shu fen fei wen ba diao tuo tong qu sheng shi you shi ting wu nian jing hun ju yan tu si xi xian yan lei bi yao yan han hui wu hou xi ge zha xiu weng zha nong nang qi zhai ji zi ji ji qi ji chi chen chen he ya ken xie bao ze shi zi chi nian ju tiao ling ling chu quan xie yin nie jiu nie chuo kun yu chu yi ni cuo chuo qu nian xian yu e wo yi chi zou dian chu jin ya chi chen he yin ju ling bao tiao zi yin yu chuo qu wo long pang gong pang yan long long gong kan ta ling ta long gong kan gui qiu bie gui yue chui he jue ") .append("xie yue ").toString(); } }
Blankj/AndroidUtilCode
lib/subutil/src/main/java/com/blankj/subutil/util/PinyinUtils.java
235
package com.blankj.utilcode.util; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkCapabilities; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.text.format.Formatter; import androidx.annotation.NonNull; import androidx.annotation.RequiresPermission; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CopyOnWriteArraySet; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.ACCESS_NETWORK_STATE; import static android.Manifest.permission.ACCESS_WIFI_STATE; import static android.Manifest.permission.CHANGE_WIFI_STATE; import static android.Manifest.permission.INTERNET; import static android.content.Context.WIFI_SERVICE; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2016/08/02 * desc : utils about network * </pre> */ public final class NetworkUtils { private NetworkUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } public enum NetworkType { NETWORK_ETHERNET, NETWORK_WIFI, NETWORK_5G, NETWORK_4G, NETWORK_3G, NETWORK_2G, NETWORK_UNKNOWN, NETWORK_NO } /** * Open the settings of wireless. */ public static void openWirelessSettings() { Utils.getApp().startActivity( new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ); } /** * Return whether network is connected. * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p> * * @return {@code true}: connected<br>{@code false}: disconnected */ @RequiresPermission(ACCESS_NETWORK_STATE) public static boolean isConnected() { NetworkInfo info = getActiveNetworkInfo(); return info != null && info.isConnected(); } /** * Return whether network is available. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param consumer The consumer. * @return the task */ @RequiresPermission(INTERNET) public static Utils.Task<Boolean> isAvailableAsync(@NonNull final Utils.Consumer<Boolean> consumer) { return UtilsBridge.doAsync(new Utils.Task<Boolean>(consumer) { @RequiresPermission(INTERNET) @Override public Boolean doInBackground() { return isAvailable(); } }); } /** * Return whether network is available. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @return {@code true}: yes<br>{@code false}: no */ @RequiresPermission(INTERNET) public static boolean isAvailable() { return isAvailableByDns() || isAvailableByPing(null); } /** * Return whether network is available using ping. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * <p>The default ping ip: 223.5.5.5</p> * * @param consumer The consumer. */ @RequiresPermission(INTERNET) public static void isAvailableByPingAsync(final Utils.Consumer<Boolean> consumer) { isAvailableByPingAsync("", consumer); } /** * Return whether network is available using ping. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param ip The ip address. * @param consumer The consumer. * @return the task */ @RequiresPermission(INTERNET) public static Utils.Task<Boolean> isAvailableByPingAsync(final String ip, @NonNull final Utils.Consumer<Boolean> consumer) { return UtilsBridge.doAsync(new Utils.Task<Boolean>(consumer) { @RequiresPermission(INTERNET) @Override public Boolean doInBackground() { return isAvailableByPing(ip); } }); } /** * Return whether network is available using ping. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * <p>The default ping ip: 223.5.5.5</p> * * @return {@code true}: yes<br>{@code false}: no */ @RequiresPermission(INTERNET) public static boolean isAvailableByPing() { return isAvailableByPing(""); } /** * Return whether network is available using ping. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param ip The ip address. * @return {@code true}: yes<br>{@code false}: no */ @RequiresPermission(INTERNET) public static boolean isAvailableByPing(final String ip) { final String realIp = TextUtils.isEmpty(ip) ? "223.5.5.5" : ip; ShellUtils.CommandResult result = ShellUtils.execCmd(String.format("ping -c 1 %s", realIp), false); return result.result == 0; } /** * Return whether network is available using domain. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param consumer The consumer. */ @RequiresPermission(INTERNET) public static void isAvailableByDnsAsync(final Utils.Consumer<Boolean> consumer) { isAvailableByDnsAsync("", consumer); } /** * Return whether network is available using domain. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param domain The name of domain. * @param consumer The consumer. * @return the task */ @RequiresPermission(INTERNET) public static Utils.Task isAvailableByDnsAsync(final String domain, @NonNull final Utils.Consumer<Boolean> consumer) { return UtilsBridge.doAsync(new Utils.Task<Boolean>(consumer) { @RequiresPermission(INTERNET) @Override public Boolean doInBackground() { return isAvailableByDns(domain); } }); } /** * Return whether network is available using domain. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @return {@code true}: yes<br>{@code false}: no */ @RequiresPermission(INTERNET) public static boolean isAvailableByDns() { return isAvailableByDns(""); } /** * Return whether network is available using domain. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param domain The name of domain. * @return {@code true}: yes<br>{@code false}: no */ @RequiresPermission(INTERNET) public static boolean isAvailableByDns(final String domain) { final String realDomain = TextUtils.isEmpty(domain) ? "www.baidu.com" : domain; InetAddress inetAddress; try { inetAddress = InetAddress.getByName(realDomain); return inetAddress != null; } catch (UnknownHostException e) { e.printStackTrace(); return false; } } /** * Return whether mobile data is enabled. * * @return {@code true}: enabled<br>{@code false}: disabled */ public static boolean getMobileDataEnabled() { try { TelephonyManager tm = (TelephonyManager) Utils.getApp().getSystemService(Context.TELEPHONY_SERVICE); if (tm == null) return false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return tm.isDataEnabled(); } @SuppressLint("PrivateApi") Method getMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("getDataEnabled"); if (null != getMobileDataEnabledMethod) { return (boolean) getMobileDataEnabledMethod.invoke(tm); } } catch (Exception e) { e.printStackTrace(); } return false; } /** * Returns true if device is connecting to the internet via a proxy, works for both Wi-Fi and Mobile Data. * * @return true if using proxy to connect to the internet. */ public static boolean isBehindProxy(){ return !(System.getProperty("http.proxyHost") == null || System.getProperty("http.proxyPort") == null); } /** * Returns true if device is connecting to the internet via a VPN. * * @return true if using VPN to conncet to the internet. */ public static boolean isUsingVPN(){ ConnectivityManager cm = (ConnectivityManager) com.blankj.utilcode.util.Utils.getApp().getSystemService(Context.CONNECTIVITY_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { return cm.getNetworkInfo(ConnectivityManager.TYPE_VPN).isConnectedOrConnecting(); } else { return cm.getNetworkInfo(NetworkCapabilities.TRANSPORT_VPN).isConnectedOrConnecting(); } } /** * Return whether using mobile data. * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p> * * @return {@code true}: yes<br>{@code false}: no */ @RequiresPermission(ACCESS_NETWORK_STATE) public static boolean isMobileData() { NetworkInfo info = getActiveNetworkInfo(); return null != info && info.isAvailable() && info.getType() == ConnectivityManager.TYPE_MOBILE; } /** * Return whether using 4G. * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p> * * @return {@code true}: yes<br>{@code false}: no */ @RequiresPermission(ACCESS_NETWORK_STATE) public static boolean is4G() { NetworkInfo info = getActiveNetworkInfo(); return info != null && info.isAvailable() && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE; } /** * Return whether using 4G. * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p> * * @return {@code true}: yes<br>{@code false}: no */ @RequiresPermission(ACCESS_NETWORK_STATE) public static boolean is5G() { NetworkInfo info = getActiveNetworkInfo(); return info != null && info.isAvailable() && info.getSubtype() == TelephonyManager.NETWORK_TYPE_NR; } /** * Return whether wifi is enabled. * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />}</p> * * @return {@code true}: enabled<br>{@code false}: disabled */ @RequiresPermission(ACCESS_WIFI_STATE) public static boolean getWifiEnabled() { @SuppressLint("WifiManagerLeak") WifiManager manager = (WifiManager) Utils.getApp().getSystemService(WIFI_SERVICE); if (manager == null) return false; return manager.isWifiEnabled(); } /** * Enable or disable wifi. * <p>Must hold {@code <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />}</p> * * @param enabled True to enabled, false otherwise. */ @RequiresPermission(CHANGE_WIFI_STATE) public static void setWifiEnabled(final boolean enabled) { @SuppressLint("WifiManagerLeak") WifiManager manager = (WifiManager) Utils.getApp().getSystemService(WIFI_SERVICE); if (manager == null) return; if (enabled == manager.isWifiEnabled()) return; manager.setWifiEnabled(enabled); } /** * Return whether wifi is connected. * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p> * * @return {@code true}: connected<br>{@code false}: disconnected */ @RequiresPermission(ACCESS_NETWORK_STATE) public static boolean isWifiConnected() { ConnectivityManager cm = (ConnectivityManager) Utils.getApp().getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; NetworkInfo ni = cm.getActiveNetworkInfo(); return ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI; } /** * Return whether wifi is available. * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />}, * {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @return {@code true}: available<br>{@code false}: unavailable */ @RequiresPermission(allOf = {ACCESS_WIFI_STATE, INTERNET}) public static boolean isWifiAvailable() { return getWifiEnabled() && isAvailable(); } /** * Return whether wifi is available. * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />}, * {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param consumer The consumer. * @return the task */ @RequiresPermission(allOf = {ACCESS_WIFI_STATE, INTERNET}) public static Utils.Task<Boolean> isWifiAvailableAsync(@NonNull final Utils.Consumer<Boolean> consumer) { return UtilsBridge.doAsync(new Utils.Task<Boolean>(consumer) { @RequiresPermission(allOf = {ACCESS_WIFI_STATE, INTERNET}) @Override public Boolean doInBackground() { return isWifiAvailable(); } }); } /** * Return the name of network operate. * * @return the name of network operate */ public static String getNetworkOperatorName() { TelephonyManager tm = (TelephonyManager) Utils.getApp().getSystemService(Context.TELEPHONY_SERVICE); if (tm == null) return ""; return tm.getNetworkOperatorName(); } /** * Return type of network. * <p>Must hold {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p> * * @return type of network * <ul> * <li>{@link NetworkUtils.NetworkType#NETWORK_ETHERNET} </li> * <li>{@link NetworkUtils.NetworkType#NETWORK_WIFI } </li> * <li>{@link NetworkUtils.NetworkType#NETWORK_4G } </li> * <li>{@link NetworkUtils.NetworkType#NETWORK_3G } </li> * <li>{@link NetworkUtils.NetworkType#NETWORK_2G } </li> * <li>{@link NetworkUtils.NetworkType#NETWORK_UNKNOWN } </li> * <li>{@link NetworkUtils.NetworkType#NETWORK_NO } </li> * </ul> */ @RequiresPermission(ACCESS_NETWORK_STATE) public static NetworkType getNetworkType() { if (isEthernet()) { return NetworkType.NETWORK_ETHERNET; } NetworkInfo info = getActiveNetworkInfo(); if (info != null && info.isAvailable()) { if (info.getType() == ConnectivityManager.TYPE_WIFI) { return NetworkType.NETWORK_WIFI; } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) { switch (info.getSubtype()) { case TelephonyManager.NETWORK_TYPE_GSM: case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: return NetworkType.NETWORK_2G; case TelephonyManager.NETWORK_TYPE_TD_SCDMA: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: return NetworkType.NETWORK_3G; case TelephonyManager.NETWORK_TYPE_IWLAN: case TelephonyManager.NETWORK_TYPE_LTE: return NetworkType.NETWORK_4G; case TelephonyManager.NETWORK_TYPE_NR: return NetworkType.NETWORK_5G; default: String subtypeName = info.getSubtypeName(); if (subtypeName.equalsIgnoreCase("TD-SCDMA") || subtypeName.equalsIgnoreCase("WCDMA") || subtypeName.equalsIgnoreCase("CDMA2000")) { return NetworkType.NETWORK_3G; } else { return NetworkType.NETWORK_UNKNOWN; } } } else { return NetworkType.NETWORK_UNKNOWN; } } return NetworkType.NETWORK_NO; } /** * Return whether using ethernet. * <p>Must hold * {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />}</p> * * @return {@code true}: yes<br>{@code false}: no */ @RequiresPermission(ACCESS_NETWORK_STATE) private static boolean isEthernet() { final ConnectivityManager cm = (ConnectivityManager) Utils.getApp().getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; final NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET); if (info == null) return false; NetworkInfo.State state = info.getState(); if (null == state) return false; return state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING; } @RequiresPermission(ACCESS_NETWORK_STATE) private static NetworkInfo getActiveNetworkInfo() { ConnectivityManager cm = (ConnectivityManager) Utils.getApp().getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return null; return cm.getActiveNetworkInfo(); } /** * Return the ip address. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param useIPv4 True to use ipv4, false otherwise. * @param consumer The consumer. * @return the task */ public static Utils.Task<String> getIPAddressAsync(final boolean useIPv4, @NonNull final Utils.Consumer<String> consumer) { return UtilsBridge.doAsync(new Utils.Task<String>(consumer) { @RequiresPermission(INTERNET) @Override public String doInBackground() { return getIPAddress(useIPv4); } }); } /** * Return the ip address. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param useIPv4 True to use ipv4, false otherwise. * @return the ip address */ @RequiresPermission(INTERNET) public static String getIPAddress(final boolean useIPv4) { try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); LinkedList<InetAddress> adds = new LinkedList<>(); while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); // To prevent phone of xiaomi return "10.0.2.15" if (!ni.isUp() || ni.isLoopback()) continue; Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { adds.addFirst(addresses.nextElement()); } } for (InetAddress add : adds) { if (!add.isLoopbackAddress()) { String hostAddress = add.getHostAddress(); boolean isIPv4 = hostAddress.indexOf(':') < 0; if (useIPv4) { if (isIPv4) return hostAddress; } else { if (!isIPv4) { int index = hostAddress.indexOf('%'); return index < 0 ? hostAddress.toUpperCase() : hostAddress.substring(0, index).toUpperCase(); } } } } } catch (SocketException e) { e.printStackTrace(); } return ""; } /** * Return the ip address of broadcast. * * @return the ip address of broadcast */ public static String getBroadcastIpAddress() { try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); LinkedList<InetAddress> adds = new LinkedList<>(); while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); if (!ni.isUp() || ni.isLoopback()) continue; List<InterfaceAddress> ias = ni.getInterfaceAddresses(); for (int i = 0, size = ias.size(); i < size; i++) { InterfaceAddress ia = ias.get(i); InetAddress broadcast = ia.getBroadcast(); if (broadcast != null) { return broadcast.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } return ""; } /** * Return the domain address. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param domain The name of domain. * @param consumer The consumer. * @return the task */ @RequiresPermission(INTERNET) public static Utils.Task<String> getDomainAddressAsync(final String domain, @NonNull final Utils.Consumer<String> consumer) { return UtilsBridge.doAsync(new Utils.Task<String>(consumer) { @RequiresPermission(INTERNET) @Override public String doInBackground() { return getDomainAddress(domain); } }); } /** * Return the domain address. * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p> * * @param domain The name of domain. * @return the domain address */ @RequiresPermission(INTERNET) public static String getDomainAddress(final String domain) { InetAddress inetAddress; try { inetAddress = InetAddress.getByName(domain); return inetAddress.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); return ""; } } /** * Return the ip address by wifi. * * @return the ip address by wifi */ @RequiresPermission(ACCESS_WIFI_STATE) public static String getIpAddressByWifi() { @SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) Utils.getApp().getSystemService(Context.WIFI_SERVICE); if (wm == null) return ""; return Formatter.formatIpAddress(wm.getDhcpInfo().ipAddress); } /** * Return the gate way by wifi. * * @return the gate way by wifi */ @RequiresPermission(ACCESS_WIFI_STATE) public static String getGatewayByWifi() { @SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) Utils.getApp().getSystemService(Context.WIFI_SERVICE); if (wm == null) return ""; return Formatter.formatIpAddress(wm.getDhcpInfo().gateway); } /** * Return the net mask by wifi. * * @return the net mask by wifi */ @RequiresPermission(ACCESS_WIFI_STATE) public static String getNetMaskByWifi() { @SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) Utils.getApp().getSystemService(Context.WIFI_SERVICE); if (wm == null) return ""; return Formatter.formatIpAddress(wm.getDhcpInfo().netmask); } /** * Return the server address by wifi. * * @return the server address by wifi */ @RequiresPermission(ACCESS_WIFI_STATE) public static String getServerAddressByWifi() { @SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) Utils.getApp().getSystemService(Context.WIFI_SERVICE); if (wm == null) return ""; return Formatter.formatIpAddress(wm.getDhcpInfo().serverAddress); } /** * Return the ssid. * * @return the ssid. */ @RequiresPermission(ACCESS_WIFI_STATE) public static String getSSID() { WifiManager wm = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(WIFI_SERVICE); if (wm == null) return ""; WifiInfo wi = wm.getConnectionInfo(); if (wi == null) return ""; String ssid = wi.getSSID(); if (TextUtils.isEmpty(ssid)) { return ""; } if (ssid.length() > 2 && ssid.charAt(0) == '"' && ssid.charAt(ssid.length() - 1) == '"') { return ssid.substring(1, ssid.length() - 1); } return ssid; } /** * Register the status of network changed listener. * * @param listener The status of network changed listener */ @RequiresPermission(ACCESS_NETWORK_STATE) public static void registerNetworkStatusChangedListener(final OnNetworkStatusChangedListener listener) { NetworkChangedReceiver.getInstance().registerListener(listener); } /** * Return whether the status of network changed listener has been registered. * * @param listener The listener * @return true to registered, false otherwise. */ public static boolean isRegisteredNetworkStatusChangedListener(final OnNetworkStatusChangedListener listener) { return NetworkChangedReceiver.getInstance().isRegistered(listener); } /** * Unregister the status of network changed listener. * * @param listener The status of network changed listener. */ public static void unregisterNetworkStatusChangedListener(final OnNetworkStatusChangedListener listener) { NetworkChangedReceiver.getInstance().unregisterListener(listener); } @RequiresPermission(allOf = {ACCESS_WIFI_STATE, ACCESS_COARSE_LOCATION}) public static WifiScanResults getWifiScanResult() { WifiScanResults result = new WifiScanResults(); if (!getWifiEnabled()) return result; @SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) Utils.getApp().getSystemService(WIFI_SERVICE); //noinspection ConstantConditions List<ScanResult> results = wm.getScanResults(); if (results != null) { result.setAllResults(results); } return result; } private static final long SCAN_PERIOD_MILLIS = 3000; private static final Set<Utils.Consumer<WifiScanResults>> SCAN_RESULT_CONSUMERS = new CopyOnWriteArraySet<>(); private static Timer sScanWifiTimer; private static WifiScanResults sPreWifiScanResults; @RequiresPermission(allOf = {ACCESS_WIFI_STATE, CHANGE_WIFI_STATE, ACCESS_COARSE_LOCATION}) public static void addOnWifiChangedConsumer(final Utils.Consumer<WifiScanResults> consumer) { if (consumer == null) return; UtilsBridge.runOnUiThread(new Runnable() { @Override public void run() { if (SCAN_RESULT_CONSUMERS.isEmpty()) { SCAN_RESULT_CONSUMERS.add(consumer); startScanWifi(); return; } consumer.accept(sPreWifiScanResults); SCAN_RESULT_CONSUMERS.add(consumer); } }); } private static void startScanWifi() { sPreWifiScanResults = new WifiScanResults(); sScanWifiTimer = new Timer(); sScanWifiTimer.schedule(new TimerTask() { @RequiresPermission(allOf = {ACCESS_WIFI_STATE, CHANGE_WIFI_STATE, ACCESS_COARSE_LOCATION}) @Override public void run() { startScanWifiIfEnabled(); WifiScanResults scanResults = getWifiScanResult(); if (isSameScanResults(sPreWifiScanResults.allResults, scanResults.allResults)) { return; } sPreWifiScanResults = scanResults; UtilsBridge.runOnUiThread(new Runnable() { @Override public void run() { for (Utils.Consumer<WifiScanResults> consumer : SCAN_RESULT_CONSUMERS) { consumer.accept(sPreWifiScanResults); } } }); } }, 0, SCAN_PERIOD_MILLIS); } @RequiresPermission(allOf = {ACCESS_WIFI_STATE, CHANGE_WIFI_STATE}) private static void startScanWifiIfEnabled() { if (!getWifiEnabled()) return; @SuppressLint("WifiManagerLeak") WifiManager wm = (WifiManager) Utils.getApp().getSystemService(WIFI_SERVICE); //noinspection ConstantConditions wm.startScan(); } public static void removeOnWifiChangedConsumer(final Utils.Consumer<WifiScanResults> consumer) { if (consumer == null) return; UtilsBridge.runOnUiThread(new Runnable() { @Override public void run() { SCAN_RESULT_CONSUMERS.remove(consumer); if (SCAN_RESULT_CONSUMERS.isEmpty()) { stopScanWifi(); } } }); } private static void stopScanWifi() { if (sScanWifiTimer != null) { sScanWifiTimer.cancel(); sScanWifiTimer = null; } } private static boolean isSameScanResults(List<ScanResult> l1, List<ScanResult> l2) { if (l1 == null && l2 == null) { return true; } if (l1 == null || l2 == null) { return false; } if (l1.size() != l2.size()) { return false; } for (int i = 0; i < l1.size(); i++) { ScanResult r1 = l1.get(i); ScanResult r2 = l2.get(i); if (!isSameScanResultContent(r1, r2)) { return false; } } return true; } private static boolean isSameScanResultContent(ScanResult r1, ScanResult r2) { return r1 != null && r2 != null && UtilsBridge.equals(r1.BSSID, r2.BSSID) && UtilsBridge.equals(r1.SSID, r2.SSID) && UtilsBridge.equals(r1.capabilities, r2.capabilities) && r1.level == r2.level; } public static final class NetworkChangedReceiver extends BroadcastReceiver { private static NetworkChangedReceiver getInstance() { return LazyHolder.INSTANCE; } private NetworkType mType; private Set<OnNetworkStatusChangedListener> mListeners = new HashSet<>(); @RequiresPermission(ACCESS_NETWORK_STATE) void registerListener(final OnNetworkStatusChangedListener listener) { if (listener == null) return; UtilsBridge.runOnUiThread(new Runnable() { @Override @RequiresPermission(ACCESS_NETWORK_STATE) public void run() { int preSize = mListeners.size(); mListeners.add(listener); if (preSize == 0 && mListeners.size() == 1) { mType = getNetworkType(); IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); Utils.getApp().registerReceiver(NetworkChangedReceiver.getInstance(), intentFilter); } } }); } boolean isRegistered(final OnNetworkStatusChangedListener listener) { if (listener == null) return false; return mListeners.contains(listener); } void unregisterListener(final OnNetworkStatusChangedListener listener) { if (listener == null) return; UtilsBridge.runOnUiThread(new Runnable() { @Override public void run() { int preSize = mListeners.size(); mListeners.remove(listener); if (preSize == 1 && mListeners.size() == 0) { Utils.getApp().unregisterReceiver(NetworkChangedReceiver.getInstance()); } } }); } @Override public void onReceive(Context context, Intent intent) { if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { // debouncing UtilsBridge.runOnUiThreadDelayed(new Runnable() { @Override @RequiresPermission(ACCESS_NETWORK_STATE) public void run() { NetworkType networkType = NetworkUtils.getNetworkType(); if (mType == networkType) return; mType = networkType; if (networkType == NetworkType.NETWORK_NO) { for (OnNetworkStatusChangedListener listener : mListeners) { listener.onDisconnected(); } } else { for (OnNetworkStatusChangedListener listener : mListeners) { listener.onConnected(networkType); } } } }, 1000); } } private static class LazyHolder { private static final NetworkChangedReceiver INSTANCE = new NetworkChangedReceiver(); } } // /** // * Register the status of network changed listener. // */ // @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) // @RequiresPermission(ACCESS_NETWORK_STATE) // public static void registerNetworkStatusChangedListener() { // ConnectivityManager cm = (ConnectivityManager) Utils.getApp().getSystemService(Context.CONNECTIVITY_SERVICE); // if (cm == null) return; // NetworkCallbackImpl networkCallback = NetworkCallbackImpl.LazyHolder.INSTANCE; // NetworkRequest.Builder builder = new NetworkRequest.Builder(); // NetworkRequest request = builder.build(); // cm.registerNetworkCallback(new NetworkRequest.Builder().build(), networkCallback); // } // // // @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) // public static final class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback { // // @Override // public void onAvailable(@NonNull Network network) { // super.onAvailable(network); // LogUtils.d(TAG, "onAvailable: " + network); // } // // @Override // public void onLosing(@NonNull Network network, int maxMsToLive) { // super.onLosing(network, maxMsToLive); // LogUtils.d(TAG, "onLosing: " + network); // } // // @Override // public void onLost(@NonNull Network network) { // super.onLost(network); // LogUtils.e(TAG, "onLost: " + network); // } // // @Override // public void onUnavailable() { // super.onUnavailable(); // LogUtils.e(TAG, "onUnavailable"); // } // // @Override // public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities cap) { // super.onCapabilitiesChanged(network, cap); // if (cap.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) { // if (cap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { // LogUtils.d(TAG, "onCapabilitiesChanged: 网络类型为wifi"); // } else if (cap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { // LogUtils.d(TAG, "onCapabilitiesChanged: 蜂窝网络"); // } else { // LogUtils.d(TAG, "onCapabilitiesChanged: 其他网络"); // } // LogUtils.d(TAG, "onCapabilitiesChanged: " + network + ", " + cap); // } // } // // @Override // public void onLinkPropertiesChanged(@NonNull Network network, @NonNull LinkProperties lp) { // super.onLinkPropertiesChanged(network, lp); // LogUtils.d(TAG, "onLinkPropertiesChanged: " + network + ", " + lp); // } // // @Override // public void onBlockedStatusChanged(@NonNull Network network, boolean blocked) { // super.onBlockedStatusChanged(network, blocked); // LogUtils.d(TAG, "onBlockedStatusChanged: " + network + ", " + blocked); // } // // private static class LazyHolder { // private static final NetworkCallbackImpl INSTANCE = new NetworkCallbackImpl(); // } // } public interface OnNetworkStatusChangedListener { void onDisconnected(); void onConnected(NetworkType networkType); } public static final class WifiScanResults { private List<ScanResult> allResults = new ArrayList<>(); private List<ScanResult> filterResults = new ArrayList<>(); public WifiScanResults() { } public List<ScanResult> getAllResults() { return allResults; } public List<ScanResult> getFilterResults() { return filterResults; } public void setAllResults(List<ScanResult> allResults) { this.allResults = allResults; filterResults = filterScanResult(allResults); } private static List<ScanResult> filterScanResult(final List<ScanResult> results) { if (results == null || results.isEmpty()) { return new ArrayList<>(); } LinkedHashMap<String, ScanResult> map = new LinkedHashMap<>(results.size()); for (ScanResult result : results) { if (TextUtils.isEmpty(result.SSID)) { continue; } ScanResult resultInMap = map.get(result.SSID); if (resultInMap != null && resultInMap.level >= result.level) { continue; } map.put(result.SSID, result); } return new ArrayList<>(map.values()); } } }
Blankj/AndroidUtilCode
lib/utilcode/src/main/java/com/blankj/utilcode/util/NetworkUtils.java
236
package org.xutils; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import org.xutils.common.util.KeyValue; import org.xutils.db.Selector; import org.xutils.db.sqlite.SqlInfo; import org.xutils.db.sqlite.WhereBuilder; import org.xutils.db.table.DbModel; import org.xutils.db.table.TableEntity; import org.xutils.ex.DbException; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.util.List; /** * 数据库访问接口 */ public interface DbManager extends Closeable { DaoConfig getDaoConfig(); SQLiteDatabase getDatabase(); /** * 保存实体类或实体类的List到数据库, * 如果该类型的id是自动生成的, 则保存完后会给id赋值. */ boolean saveBindingId(Object entity) throws DbException; /** * 保存或更新实体类或实体类的List到数据库, 根据id对应的数据是否存在. */ void saveOrUpdate(Object entity) throws DbException; /** * 保存实体类或实体类的List到数据库 */ void save(Object entity) throws DbException; /** * 保存或更新实体类或实体类的List到数据库, 根据id和其他唯一索引判断数据是否存在. */ void replace(Object entity) throws DbException; ///////////// delete void deleteById(Class<?> entityType, Object idValue) throws DbException; void delete(Object entity) throws DbException; void delete(Class<?> entityType) throws DbException; int delete(Class<?> entityType, WhereBuilder whereBuilder) throws DbException; ///////////// update void update(Object entity, String... updateColumnNames) throws DbException; int update(Class<?> entityType, WhereBuilder whereBuilder, KeyValue... nameValuePairs) throws DbException; ///////////// find <T> T findById(Class<T> entityType, Object idValue) throws DbException; <T> T findFirst(Class<T> entityType) throws DbException; <T> List<T> findAll(Class<T> entityType) throws DbException; <T> Selector<T> selector(Class<T> entityType) throws DbException; DbModel findDbModelFirst(SqlInfo sqlInfo) throws DbException; List<DbModel> findDbModelAll(SqlInfo sqlInfo) throws DbException; ///////////// table /** * 获取表信息 */ <T> TableEntity<T> getTable(Class<T> entityType) throws DbException; /** * 删除表 */ void dropTable(Class<?> entityType) throws DbException; /** * 添加一列, * 新的entityType中必须定义了这个列的属性. */ void addColumn(Class<?> entityType, String column) throws DbException; ///////////// db /** * 删除库 */ void dropDb() throws DbException; /** * 关闭数据库. * 同一个库是单实例的, 尽量不要调用这个方法, 会自动释放. */ void close() throws IOException; ///////////// custom int executeUpdateDelete(SqlInfo sqlInfo) throws DbException; int executeUpdateDelete(String sql) throws DbException; void execNonQuery(SqlInfo sqlInfo) throws DbException; void execNonQuery(String sql) throws DbException; Cursor execQuery(SqlInfo sqlInfo) throws DbException; Cursor execQuery(String sql) throws DbException; public interface DbOpenListener { void onDbOpened(DbManager db) throws DbException; } public interface DbUpgradeListener { void onUpgrade(DbManager db, int oldVersion, int newVersion) throws DbException; } public interface TableCreateListener { void onTableCreated(DbManager db, TableEntity<?> table); } public static class DaoConfig { private File dbDir; private String dbName = "xUtils.db"; // default db name private int dbVersion = 1; private boolean allowTransaction = true; private DbUpgradeListener dbUpgradeListener; private TableCreateListener tableCreateListener; private DbOpenListener dbOpenListener; public DaoConfig() { } public DaoConfig setDbDir(File dbDir) { this.dbDir = dbDir; return this; } public DaoConfig setDbName(String dbName) { if (!TextUtils.isEmpty(dbName)) { this.dbName = dbName; } return this; } public DaoConfig setDbVersion(int dbVersion) { this.dbVersion = dbVersion; return this; } public DaoConfig setAllowTransaction(boolean allowTransaction) { this.allowTransaction = allowTransaction; return this; } public DaoConfig setDbOpenListener(DbOpenListener dbOpenListener) { this.dbOpenListener = dbOpenListener; return this; } public DaoConfig setDbUpgradeListener(DbUpgradeListener dbUpgradeListener) { this.dbUpgradeListener = dbUpgradeListener; return this; } public DaoConfig setTableCreateListener(TableCreateListener tableCreateListener) { this.tableCreateListener = tableCreateListener; return this; } public File getDbDir() { return dbDir; } public String getDbName() { return dbName; } public int getDbVersion() { return dbVersion; } public boolean isAllowTransaction() { return allowTransaction; } public DbOpenListener getDbOpenListener() { return dbOpenListener; } public DbUpgradeListener getDbUpgradeListener() { return dbUpgradeListener; } public TableCreateListener getTableCreateListener() { return tableCreateListener; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DaoConfig daoConfig = (DaoConfig) o; if (!dbName.equals(daoConfig.dbName)) return false; return dbDir == null ? daoConfig.dbDir == null : dbDir.equals(daoConfig.dbDir); } @Override public int hashCode() { int result = dbName.hashCode(); result = 31 * result + (dbDir != null ? dbDir.hashCode() : 0); return result; } @Override public String toString() { return String.valueOf(dbDir) + "/" + dbName; } } }
wyouflf/xUtils3
xutils/src/main/java/org/xutils/DbManager.java
237
package com.alibaba.otter.canal.admin; /** * Canal Admin动态管理接口 * * @author agapple 2019年8月24日 下午9:45:49 * @since 1.1.4 */ public interface CanalAdmin { /** * 校验账号密码 */ boolean auth(String user, String passwd, byte[] seed); /** * 获取Canal Server状态, 1代表运行/0代表不运行 * * @return 状态代码 */ boolean check(); /** * 启动Canal Server * * @return 是否成功 */ boolean start(); /** * 停止Canal Server * * @return 是否成功 */ boolean stop(); /** * 重启Canal Server * * @return 是否成功 */ boolean restart(); /** * 获取所有当前节点下运行中的实例 * * @return 实例信息 */ String getRunningInstances(); /** * 通过实例名检查 * * @param destination * @return */ boolean checkInstance(String destination); /** * 通过实例名启动实例 * * @param destination 实例名 * @return 是否成功 */ boolean startInstance(String destination); /** * 通过实例名关闭实例 * * @param destination 实例名 * @return 是否成功 */ boolean stopInstance(String destination); /** * 通过实例名释放,主要针对cluster模式有效(通知当前主机释放instance运行交给其他人来抢占) * * @param destination 实例名 * @return 是否成功 */ boolean releaseInstance(String destination); /** * 通过实例名重启实例 * * @param destination 实例名 * @return 是否成功 */ boolean restartInstance(String destination); /** * 获取Canal Server日志列表 * * @return 日志信息 */ String listCanalLog(); /** * 获取Canal Server日志 * * @return 日志信息 */ String canalLog(int lines); /** * 获取Instance的机器日志列表 * * @param destination */ String listInstanceLog(String destination); /** * 通过实例名获取实例日志 * * @return 日志信息 */ String instanceLog(String destination, String fileName, int lines); }
alibaba/canal
server/src/main/java/com/alibaba/otter/canal/admin/CanalAdmin.java
238
package com.vip.vjtools.vjtop; import java.io.IOException; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.lang.management.ThreadInfo; import java.util.Locale; import java.util.Map; import com.sun.management.GarbageCollectorMXBean; import com.vip.vjtools.vjtop.data.PerfData; import com.vip.vjtools.vjtop.data.ProcFileData; import com.vip.vjtools.vjtop.data.jmx.JmxClient; import com.vip.vjtools.vjtop.data.jmx.JmxGarbageCollectorManager; import com.vip.vjtools.vjtop.data.jmx.JmxMemoryPoolManager; import com.vip.vjtools.vjtop.util.Formats; import com.vip.vjtools.vjtop.util.Utils; import sun.management.counter.Counter; import sun.management.counter.LongCounter; import sun.management.counter.StringCounter; @SuppressWarnings("restriction") public class VMInfo { private JmxClient jmxClient = null; private PerfData perfData = null; public boolean perfDataSupport = false; public VMInfoState state = VMInfoState.INIT; public String pid; private int jmxUpdateErrorCount; // 静态数据// private long startTime = 0; public String osUser; public String vmArgs = ""; public String jvmVersion = ""; public int jvmMajorVersion; public String permGenName; public long threadStackSize; public long maxDirectMemorySize; public int processors; public boolean isLinux; public boolean ioDataSupport = true;// 不是同一个用户,不能读/proc/PID/io public boolean processDataSupport = true; public boolean threadCpuTimeSupported; public boolean threadMemoryAllocatedSupported; public boolean threadContentionMonitoringSupported; public WarningRule warningRule = new WarningRule(); // 动态数据// public Rate upTimeMills = new Rate(); public Rate cpuTimeNanos = new Rate(); public long rss; public long peakRss; public long swap; public long osThreads; public Rate readBytes = new Rate(); public Rate writeBytes = new Rate(); public double cpuLoad = 0.0; public double singleCoreCpuLoad = 0.0; public String ygcStrategy = ""; public Rate ygcCount = new Rate(); public Rate ygcTimeMills = new Rate(); public String fullgcStrategy = ""; public Rate fullgcCount = new Rate(); public Rate fullgcTimeMills = new Rate(); public String currentGcCause = ""; public long threadActive; public long threadDaemon; public long threadPeak; public Rate threadNew = new Rate(); public Rate classLoaded = new Rate(); public long classUnLoaded; public Rate safepointCount = new Rate(); public Rate safepointTimeMills = new Rate(); public Rate safepointSyncTimeMills = new Rate(); public Usage eden; public Usage sur; public Usage old; public Usage perm; public Usage codeCache; public Usage ccs; public Usage direct; public Usage map; private LongCounter threadLiveCounter; private LongCounter threadDaemonCounter; private LongCounter threadPeakCounter; private LongCounter threadStartedCounter; private LongCounter classUnloadCounter; private LongCounter classLoadedCounter; private LongCounter ygcCountCounter; private LongCounter ygcTimeCounter; private LongCounter fullGcCountCounter; private LongCounter fullgcTimeCounter; private LongCounter safepointCountCounter; private LongCounter safepointTimeCounter; private LongCounter safepointSyncTimeCounter; private StringCounter currentGcCauseCounter; public VMInfo(JmxClient jmxClient, String vmId) throws Exception { this.jmxClient = jmxClient; this.state = VMInfoState.ATTACHED; this.pid = vmId; init(); } private VMInfo() { } /** * 创建JMX连接并构造VMInfo实例 */ public static VMInfo processNewVM(String pid, String jmxHostAndPort) { try { final JmxClient jmxClient = new JmxClient(); jmxClient.connect(pid, jmxHostAndPort); // 注册JMXClient注销的钩子 Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { jmxClient.disconnect(); } })); return new VMInfo(jmxClient, pid); } catch (Exception e) { e.printStackTrace(System.out); } return createDeadVM(pid, VMInfoState.ERROR_DURING_ATTACH); } /** * Creates a dead VMInfo, representing a jvm in a given state which cannot * be attached or other monitoring issues occurred. */ public static VMInfo createDeadVM(String pid, VMInfoState state) { VMInfo vmInfo = new VMInfo(); vmInfo.state = state; vmInfo.pid = pid; return vmInfo; } /** * 初始化静态数据 */ private void init() throws IOException { Map<String, Counter> perfCounters = null; try { perfData = PerfData.connect(Integer.parseInt(pid)); perfCounters = perfData.getAllCounters(); initPerfCounters(perfCounters); perfDataSupport = true; } catch (Throwable ignored) { } if (perfDataSupport) { vmArgs = (String) perfCounters.get("java.rt.vmArgs").getValue(); } else { vmArgs = Formats.join(jmxClient.getRuntimeMXBean().getInputArguments(), " "); } startTime = jmxClient.getRuntimeMXBean().getStartTime(); Map<String, String> taregetVMSystemProperties = jmxClient.getRuntimeMXBean().getSystemProperties(); osUser = taregetVMSystemProperties.get("user.name"); jvmVersion = taregetVMSystemProperties.get("java.version"); jvmMajorVersion = Utils.getJavaMajorVersion(taregetVMSystemProperties.get("java.specification.version")); permGenName = jvmMajorVersion >= 8 ? "metaspace" : "perm"; threadStackSize = 1024 * Long.parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("ThreadStackSize").getValue()); maxDirectMemorySize = Long .parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("MaxDirectMemorySize").getValue()); maxDirectMemorySize = maxDirectMemorySize == 0 ? -1 : maxDirectMemorySize; processors = jmxClient.getOperatingSystemMXBean().getAvailableProcessors(); warningRule.updateProcessor(processors); isLinux = System.getProperty("os.name").toLowerCase(Locale.US).contains("linux"); } public void initThreadInfoAbility() throws IOException { threadCpuTimeSupported = jmxClient.getThreadMXBean().isThreadCpuTimeSupported(); threadMemoryAllocatedSupported = jmxClient.getThreadMXBean().isThreadAllocatedMemorySupported(); threadContentionMonitoringSupported = jmxClient.getThreadMXBean().isThreadContentionMonitoringEnabled(); } /** * Updates all jvm metrics to the most recent remote values */ public void update(boolean needJvmInfo) { if (state == VMInfoState.ERROR_DURING_ATTACH || state == VMInfoState.DETACHED) { return; } try { int lastJmxErrorCount = jmxUpdateErrorCount; // 将UPDTATE_ERROR重置开始新一轮循环 state = VMInfoState.ATTACHED; // 清空JMX内部缓存 jmxClient.flush(); updateUpTime(); if (needJvmInfo) { if (isLinux) { updateProcessStatus(); updateIO(); } updateCpu(); updateThreads(); updateClassLoader(); updateMemoryPool(); updateGC(); updateSafepoint(); } // 无新异常,状态重新判定为正常 if (jmxUpdateErrorCount == lastJmxErrorCount) { jmxUpdateErrorCount = 0; } } catch (Throwable e) { // 其他非JMX异常,直接退出 e.printStackTrace(); System.out.flush(); state = VMInfoState.DETACHED; } } private void updateUpTime() { upTimeMills.update(System.currentTimeMillis() - startTime); warningRule.updateInterval(Math.max(1, upTimeMills.delta / 1000)); } private void updateProcessStatus() { if (!processDataSupport) { return; } Map<String, String> procStatus = ProcFileData.getProcStatus(pid); if (procStatus.isEmpty()) { processDataSupport = false; return; } rss = Formats.parseFromSize(procStatus.get("VmRSS")); peakRss = Formats.parseFromSize(procStatus.get("VmHWM")); swap = Formats.parseFromSize(procStatus.get("VmSwap")); osThreads = Long.parseLong(procStatus.get("Threads")); } private void updateIO() { if (!ioDataSupport) { return; } Map<String, String> procIo = ProcFileData.getProcIO(pid); if (procIo.isEmpty()) { ioDataSupport = false; return; } readBytes.update(Formats.parseFromSize(procIo.get("read_bytes"))); writeBytes.update(Formats.parseFromSize(procIo.get("write_bytes"))); readBytes.caculateRatePerSecond(upTimeMills.delta); writeBytes.caculateRatePerSecond(upTimeMills.delta); } private void updateCpu() { if (!isJmxStateOk()) { return; } try { cpuTimeNanos.update(jmxClient.getOperatingSystemMXBean().getProcessCpuTime()); singleCoreCpuLoad = Utils.calcLoad(cpuTimeNanos.delta / Utils.NANOS_TO_MILLS, upTimeMills.delta); cpuLoad = singleCoreCpuLoad / processors; } catch (Exception e) { handleJmxFetchDataError(e); } } private void updateThreads() { if (perfDataSupport) { threadActive = threadLiveCounter.longValue(); threadDaemon = threadDaemonCounter.longValue(); threadPeak = threadPeakCounter.longValue(); threadNew.update(threadStartedCounter.longValue()); } else if (isJmxStateOk()) { try { threadActive = jmxClient.getThreadMXBean().getThreadCount(); threadDaemon = jmxClient.getThreadMXBean().getDaemonThreadCount(); threadPeak = jmxClient.getThreadMXBean().getPeakThreadCount(); threadNew.update(jmxClient.getThreadMXBean().getTotalStartedThreadCount()); } catch (Exception e) { handleJmxFetchDataError(e); } } } private void updateClassLoader() { // 优先从perfData取值,注意此处loadedClasses 等于JMX的TotalLoadedClassCount if (perfDataSupport) { classUnLoaded = classUnloadCounter.longValue(); classLoaded.update(classLoadedCounter.longValue() - classUnLoaded); } else if (isJmxStateOk()) { try { classUnLoaded = jmxClient.getClassLoadingMXBean().getUnloadedClassCount(); classLoaded.update(jmxClient.getClassLoadingMXBean().getLoadedClassCount()); } catch (Exception e) { handleJmxFetchDataError(e); } } } private void updateMemoryPool() { if (!isJmxStateOk()) { return; } try { JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager(); MemoryPoolMXBean edenMXBean = memoryPoolManager.getEdenMemoryPool(); if (edenMXBean != null) { eden = new Usage(edenMXBean.getUsage()); } else { eden = new Usage(); } MemoryPoolMXBean oldMXBean = memoryPoolManager.getOldMemoryPool(); if (oldMXBean != null) { old = new Usage(oldMXBean.getUsage()); warningRule.updateOld(old.max); } else { old = new Usage(); } MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool(); if (survivorMemoryPool != null) { sur = new Usage(survivorMemoryPool.getUsage()); } else { sur = new Usage(); } MemoryPoolMXBean permMXBean = memoryPoolManager.getPermMemoryPool(); if (permMXBean != null) { perm = new Usage(permMXBean.getUsage()); warningRule.updatePerm(perm.max); } else { perm = new Usage(); } if (jvmMajorVersion >= 8) { MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool(); if (compressedClassSpaceMemoryPool != null) { ccs = new Usage(compressedClassSpaceMemoryPool.getUsage()); } else { ccs = new Usage(); } } MemoryPoolMXBean memoryPoolMXBean = memoryPoolManager.getCodeCacheMemoryPool(); if (memoryPoolMXBean != null) { codeCache = new Usage(memoryPoolMXBean.getUsage()); } else { codeCache = new Usage(); } direct = new Usage(jmxClient.getBufferPoolManager().getDirectBufferPoolUsed(), jmxClient.getBufferPoolManager().getDirectBufferPoolCapacity(), maxDirectMemorySize); // 取巧用法,将count 放入无用的max中。 long mapUsed = jmxClient.getBufferPoolManager().getMappedBufferPoolUsed(); map = new Usage(mapUsed, jmxClient.getBufferPoolManager().getMappedBufferPoolCapacity(), mapUsed == 0 ? 0 : jmxClient.getBufferPoolManager().getMappedBufferPoolCount()); } catch (Exception e) { handleJmxFetchDataError(e); } } private void updateGC() { if (perfDataSupport) { ygcCount.update(ygcCountCounter.longValue()); ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter)); if (fullGcCountCounter != null) { fullgcCount.update(fullGcCountCounter.longValue()); fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter)); } } else if (isJmxStateOk()) { try { JmxGarbageCollectorManager gcManager = jmxClient.getGarbageCollectorManager(); GarbageCollectorMXBean ygcMXBean = gcManager.getYoungCollector(); ygcStrategy = gcManager.getYgcStrategy(); ygcCount.update(ygcMXBean.getCollectionCount()); ygcTimeMills.update(ygcMXBean.getCollectionTime()); GarbageCollectorMXBean fullgcMXBean = gcManager.getFullCollector(); if (fullgcMXBean != null) { fullgcStrategy = gcManager.getFgcStrategy(); fullgcCount.update(fullgcMXBean.getCollectionCount()); fullgcTimeMills.update(fullgcMXBean.getCollectionTime()); } } catch (Exception e) { handleJmxFetchDataError(e); } } } private void updateSafepoint() { if (!perfDataSupport) { return; } safepointCount.update(safepointCountCounter.longValue()); safepointTimeMills.update(perfData.tickToMills(safepointTimeCounter)); safepointSyncTimeMills.update(perfData.tickToMills(safepointSyncTimeCounter)); currentGcCause = (String) currentGcCauseCounter.getValue(); } public long[] getAllThreadIds() throws IOException { return jmxClient.getThreadMXBean().getAllThreadIds(); } public long[] getThreadCpuTime(long[] tids) throws IOException { return jmxClient.getThreadMXBean().getThreadCpuTime(tids); } public long[] getThreadUserTime(long[] tids) throws IOException { return jmxClient.getThreadMXBean().getThreadUserTime(tids); } public ThreadInfo[] getThreadInfo(long[] tids) throws IOException { return jmxClient.getThreadMXBean().getThreadInfo(tids); } public ThreadInfo getThreadInfo(long tid, int maxDepth) throws IOException { return jmxClient.getThreadMXBean().getThreadInfo(tid, maxDepth); } public ThreadInfo[] getThreadInfo(long[] tids, int maxDepth) throws IOException { return jmxClient.getThreadMXBean().getThreadInfo(tids, maxDepth); } public ThreadInfo[] getAllThreadInfo() throws IOException { return jmxClient.getThreadMXBean().dumpAllThreads(false, false); } public long[] getThreadAllocatedBytes(long[] tids) throws IOException { return jmxClient.getThreadMXBean().getThreadAllocatedBytes(tids); } private void initPerfCounters(Map<String, Counter> perfCounters) { threadLiveCounter = (LongCounter) perfCounters.get("java.threads.live"); threadDaemonCounter = (LongCounter) perfCounters.get("java.threads.daemon"); threadPeakCounter = (LongCounter) perfCounters.get("java.threads.livePeak"); threadStartedCounter = (LongCounter) perfCounters.get("java.threads.started"); classUnloadCounter = (LongCounter) perfCounters.get("java.cls.unloadedClasses"); classLoadedCounter = (LongCounter) perfCounters.get("java.cls.loadedClasses"); ygcCountCounter = (LongCounter) perfCounters.get("sun.gc.collector.0.invocations"); ygcTimeCounter = (LongCounter) perfCounters.get("sun.gc.collector.0.time"); fullGcCountCounter = (LongCounter) perfCounters.get("sun.gc.collector.1.invocations"); fullgcTimeCounter = (LongCounter) perfCounters.get("sun.gc.collector.1.time"); safepointCountCounter = (LongCounter) perfCounters.get("sun.rt.safepoints"); safepointTimeCounter = (LongCounter) perfCounters.get("sun.rt.safepointTime"); safepointSyncTimeCounter = (LongCounter) perfCounters.get("sun.rt.safepointSyncTime"); currentGcCauseCounter = (StringCounter) perfCounters.get("sun.gc.cause"); } public void handleJmxFetchDataError(Throwable e) { System.out.println(""); e.printStackTrace(); System.out.flush(); jmxUpdateErrorCount++; // 连续三次刷新周期JMX 获取数据失败则退出 if (jmxUpdateErrorCount > 3) { state = VMInfoState.DETACHED; } else { state = VMInfoState.ATTACHED_UPDATE_ERROR; } } public boolean isJmxStateOk() { return state != VMInfoState.ATTACHED_UPDATE_ERROR && state != VMInfoState.DETACHED; } public enum VMInfoState { INIT, ERROR_DURING_ATTACH, ATTACHED, ATTACHED_UPDATE_ERROR, DETACHED } public static class Rate { private long last = -1; public long current = -1; public long delta = 0; public long ratePerSecond = 0; public void update(long current) { this.current = current; if (last != -1) { delta = current - last; } last = current; } public void caculateRatePerSecond(long deltaTimeMills) { if (delta != 0) { ratePerSecond = delta * 1000 / deltaTimeMills; } } } public static class Usage { public long used = -1; public long committed = -1; public long max = -1; public Usage() { } public Usage(long used, long committed, long max) { this.used = used; this.committed = committed; this.max = max; } public Usage(MemoryUsage jmxUsage) { this(jmxUsage.getUsed(), jmxUsage.getCommitted(), jmxUsage.getMax()); } } }
vipshop/vjtools
vjtop/src/main/java/com/vip/vjtools/vjtop/VMInfo.java
239
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.filter.config; import com.alibaba.druid.filter.FilterAdapter; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.alibaba.druid.proxy.jdbc.DataSourceProxy; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import com.alibaba.druid.util.JdbcUtils; import com.alibaba.druid.util.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.security.PublicKey; import java.sql.SQLException; import java.util.Properties; /** * <pre> * 这个类主要是负责两个事情, 解密, 和下载远程的配置文件 * [解密] * * DruidDataSource dataSource = new DruidDataSource(); * //dataSource.setXXX 其他设置 * //下面两步很重要 * //启用config filter * dataSource.setFilters("config"); * //使用RSA解密(使用默认密钥) * dataSource.setConnectionPropertise("config.decrypt=true"); * dataSource.setPassword("加密的密文"); * * [远程配置文件] * DruidDataSource dataSource = new DruidDataSource(); * //下面两步很重要 * //启用config filter * dataSource.setFilters("config"); * //使用RSA解密(使用默认密钥) * dataSource.setConnectionPropertise("config.file=http://localhost:8080/remote.propreties;"); * * [Spring的配置解密] * * &lt;bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"&gt; * &lt;property name="password" value="加密的密文" /&gt; * &lt;!-- 其他的属性设置 --&gt; * &lt;property name="filters" value="config" /&gt; * &lt;property name="connectionProperties" value="config.decrypt=true" /&gt; * &lt;/bean&gt; * * [Spring的配置远程配置文件] * * &lt;bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"&gt; * &lt;property name="filters" value="config" /&gt; * &lt;property name="connectionProperties" value="config.file=http://localhost:8080/remote.propreties; /&gt; * &lt;/bean&gt; * * [使用系统属性配置远程文件] * java -Ddruid.config.file=file:///home/test/my.properties ... * * 远程配置文件格式: * 1. 其他的属性KEY请查看 @see com.alibaba.druid.pool.DruidDataSourceFactory * 2. config filter 相关设置: * #远程文件路径 * config.file=http://xxxxx(http://开头或者file:开头) * * #RSA解密, Key不指定, 使用默认的 * config.decrypt=true * config.decrypt.key=密钥字符串 * config.decrypt.keyFile=密钥文件路径 * config.decrypt.x509File=证书路径 * * </pre> * * @author Jonas Yang */ public class ConfigFilter extends FilterAdapter { private static final Log LOG = LogFactory.getLog(ConfigFilter.class); public static final String CONFIG_FILE = "config.file"; public static final String CONFIG_DECRYPT = "config.decrypt"; public static final String CONFIG_KEY = "config.decrypt.key"; public static final String SYS_PROP_CONFIG_FILE = "druid.config.file"; public static final String SYS_PROP_CONFIG_DECRYPT = "druid.config.decrypt"; public static final String SYS_PROP_CONFIG_KEY = "druid.config.decrypt.key"; public ConfigFilter() { } public void init(DataSourceProxy dataSourceProxy) { if (!(dataSourceProxy instanceof DruidDataSource)) { throw new IllegalArgumentException("ConfigLoader only support DruidDataSource"); } DruidDataSource dataSource = (DruidDataSource) dataSourceProxy; Properties connectionProperties = dataSource.getConnectProperties(); Properties configFileProperties = loadPropertyFromConfigFile(connectionProperties); // 判断是否需要解密,如果需要就进行解密行动 boolean decrypt = isDecrypt(connectionProperties, configFileProperties); if (configFileProperties == null) { if (decrypt) { decrypt(dataSource, null); } return; } if (decrypt) { decrypt(dataSource, configFileProperties); } try { DruidDataSourceFactory.config(dataSource, configFileProperties); } catch (SQLException e) { throw new IllegalArgumentException("Config DataSource error.", e); } } public boolean isDecrypt(Properties connectionProperties, Properties configFileProperties) { String decrypterId = connectionProperties.getProperty(CONFIG_DECRYPT); if (decrypterId == null || decrypterId.length() == 0) { if (configFileProperties != null) { decrypterId = configFileProperties.getProperty(CONFIG_DECRYPT); } } if (decrypterId == null || decrypterId.length() == 0) { decrypterId = System.getProperty(SYS_PROP_CONFIG_DECRYPT); } return Boolean.valueOf(decrypterId); } Properties loadPropertyFromConfigFile(Properties connectionProperties) { String configFile = connectionProperties.getProperty(CONFIG_FILE); if (configFile == null) { configFile = System.getProperty(SYS_PROP_CONFIG_FILE); } if (configFile != null && configFile.length() > 0) { if (LOG.isInfoEnabled()) { LOG.info("DruidDataSource Config File load from : " + configFile); } Properties info = loadConfig(configFile); if (info == null) { throw new IllegalArgumentException( "Cannot load remote config file from the [config.file=" + configFile + "]."); } return info; } return null; } public void decrypt(DruidDataSource dataSource, Properties info) { try { String encryptedPassword = null; if (info != null) { encryptedPassword = info.getProperty(DruidDataSourceFactory.PROP_PASSWORD); } if (encryptedPassword == null || encryptedPassword.length() == 0) { encryptedPassword = dataSource.getConnectProperties().getProperty(DruidDataSourceFactory.PROP_PASSWORD); } if (encryptedPassword == null || encryptedPassword.length() == 0) { encryptedPassword = dataSource.getPassword(); } PublicKey publicKey = getPublicKey(dataSource.getConnectProperties(), info); String passwordPlainText = ConfigTools.decrypt(publicKey, encryptedPassword); if (info != null) { info.setProperty(DruidDataSourceFactory.PROP_PASSWORD, passwordPlainText); } else { dataSource.setPassword(passwordPlainText); } } catch (Exception e) { throw new IllegalArgumentException("Failed to decrypt.", e); } } public PublicKey getPublicKey(Properties connectionProperties, Properties configFileProperties) { String key = null; if (configFileProperties != null) { key = configFileProperties.getProperty(CONFIG_KEY); } if (StringUtils.isEmpty(key) && connectionProperties != null) { key = connectionProperties.getProperty(CONFIG_KEY); } if (StringUtils.isEmpty(key)) { key = System.getProperty(SYS_PROP_CONFIG_KEY); } return ConfigTools.getPublicKey(key); } public Properties loadConfig(String filePath) { Properties properties = new Properties(); InputStream inStream = null; try { boolean xml = false; if (filePath.startsWith("file://")) { filePath = filePath.substring("file://".length()); inStream = getFileAsStream(filePath); xml = filePath.endsWith(".xml"); } else if (filePath.startsWith("http://") || filePath.startsWith("https://")) { URL url = new URL(filePath); inStream = url.openStream(); xml = url.getPath().endsWith(".xml"); } else if (filePath.startsWith("classpath:")) { String resourcePath = filePath.substring("classpath:".length()); inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath); // 在classpath下应该也可以配置xml文件吧? xml = resourcePath.endsWith(".xml"); } else { inStream = getFileAsStream(filePath); xml = filePath.endsWith(".xml"); } if (inStream == null) { LOG.error("load config file error, file : " + filePath); return null; } if (xml) { properties.loadFromXML(inStream); } else { properties.load(inStream); } return properties; } catch (Exception ex) { LOG.error("load config file error, file : " + filePath, ex); return null; } finally { JdbcUtils.close(inStream); } } private InputStream getFileAsStream(String filePath) throws FileNotFoundException { InputStream inStream = null; File file = new File(filePath); if (file.exists()) { inStream = new FileInputStream(file); } else { inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath); } return inStream; } }
alibaba/druid
core/src/main/java/com/alibaba/druid/filter/config/ConfigFilter.java
240
package com.alibaba.otter.canal.sink.entry; import java.util.ArrayList; import java.util.List; import com.alibaba.otter.canal.protocol.CanalEntry.EntryType; import com.alibaba.otter.canal.sink.AbstractCanalEventDownStreamHandler; import com.alibaba.otter.canal.store.model.Event; /** * 处理一下一下heartbeat数据 * * @author jianghang 2013-10-8 下午6:03:53 * @since 1.0.12 */ public class HeartBeatEntryEventHandler extends AbstractCanalEventDownStreamHandler<List<Event>> { public List<Event> before(List<Event> events) { boolean existHeartBeat = false; for (Event event : events) { if (event.getEntryType() == EntryType.HEARTBEAT) { existHeartBeat = true; break; } } if (!existHeartBeat) { return events; } else { // 目前heartbeat和其他事件是分离的,保险一点还是做一下检查处理 List<Event> result = new ArrayList<>(); for (Event event : events) { if (event.getEntryType() != EntryType.HEARTBEAT) { result.add(event); } } return result; } } }
alibaba/canal
sink/src/main/java/com/alibaba/otter/canal/sink/entry/HeartBeatEntryEventHandler.java
242
/** * This file is part of FNLP (formerly FudanNLP). * * FNLP is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FNLP is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FudanNLP. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2009-2014 www.fnlp.org. All rights reserved. */ package org.fnlp.nlp.cn; import java.lang.Character.UnicodeBlock; /** * 判断语言是否为中英文 * @author Xipeng Qiu E-mail: [email protected] * @version 创建时间:2015年4月17日 上午10:44:19 */ public class LangDetection { public static String detect(String str){ char[] ch = str.toCharArray(); if(isChinese(ch)) return "cn"; else return "en"; } public static boolean isChinese(char[] ch){ for(int i=0;i<ch.length;i++){ if(isChinese(ch[i])) return true; } return false; } private static boolean isChinese(char c) { UnicodeBlock ub = UnicodeBlock.of(c); if(ub==UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS|| ub == UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A|| ub == UnicodeBlock.GENERAL_PUNCTUATION|| ub == UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION|| ub == UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) return true; return false; } /** * @param args */ public static void main(String[] args) { String str; str = "."; System.out.println(LangDetection.detect(str)+":\t"+str); str = "you and me"; System.out.println(LangDetection.detect(str)+":\t"+str); str = "()"; System.out.println(LangDetection.detect(str)+":\t"+str); str = "。"; System.out.println(LangDetection.detect(str)+":\t"+str); str = "我们"; System.out.println(LangDetection.detect(str)+":\t"+str); str = "我们and"; System.out.println(LangDetection.detect(str)+":\t"+str); str = "《and"; System.out.println(LangDetection.detect(str)+":\t"+str); } }
FudanNLP/fnlp
fnlp-core/src/main/java/org/fnlp/nlp/cn/LangDetection.java
243
package com.unity3d.player; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import com.unity3d.player.UnityPlayerActivity; public class PrivacyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!isTaskRoot()) { Intent intent = getIntent(); String action = intent.getAction(); if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) { finish(); return; } } // 隐私协议相关 SharedPreferences base = getSharedPreferences("base", MODE_PRIVATE); Boolean anInt = base.getBoolean("isFirstStartJynew", true); if (anInt == true) { AlertDialog.Builder dialog = new AlertDialog.Builder(PrivacyActivity.this); dialog.setTitle("侠启游戏隐私政策"); //设置标题 dialog.setMessage( "\n" + "更新日期:2023年04月13日\n" + "\n" + "生效日期:2023年04月13日\n" + "\n\n" + "欢迎您选择由侠启游戏(以下简称“我们”或“侠启”)提供的游戏《群侠传,启动!》。我们深知个人信息对您的重要性,将尽全力保护您的个人信息安全。我们严格遵守法律法规,遵循以下隐私保护原则,为您提供更加安全、可靠的服务:\n" + "\n" + "安全可靠:我们尽力通过合理有效的信息安全技术及管理流程,防止您的信息泄露。\n" + "\n" + "合理必要:我们根据合法、正当、必要的原则,仅收集实现产品功能所必要的信息。\n" + "\n" + "保护隐私:我们仅在征得您同意的前提下合法收集、使用您的个人信息。\n" + "\n" + "希望您仔细阅读《隐私政策》(以下简称“本政策”),详细了解我们收集的信息以及这些信息的使用方式和途径,以便您更好地了解我们的服务并作出适当的选择。\n" + "\n" + "若您使用侠启游戏提供服务,即表示您同意我们在本政策中所述内容。\n" + "\n" + "我们会出于以下目的,收集和使用您的个人信息:\n" + "\n" + "1 为帮助您完成注册及登录,收集您在使用我们服务时主动提供的信息\n" + "\n" + "1.1 您在注册帐户时填写的信息\n" + "\n" + "包括您在注册帐户时所填写的昵称、手机号码。\n" + "\n" + "1.2 您在使用服务时上传的信息\n" + "\n" + "包括您在使用App时,上传的头像、照片、图片、文字。\n" + "\n" + "1.3 您通过我们的客服或参加我们举办的活动时所提交的信息\n" + "\n" + "包括您参与我们线上活动时填写的调查问卷中可能包含您的姓名、电话、家庭地址信息。\n" + "\n" + "我们的部分服务可能需要您提供特定的个人敏感信息来实现特定功能。若您选择不提供该类信息,则可能无法正常使用服务中的特定功能,但不影响您使用服务中的其他功能。若您主动提供您的个人敏感信息,即表示您同意我们按本政策所述目的和方式来处理您的个人敏感信息。\n" + "\n" + "2 为提供游戏基本功能,维护网络及运营安全,收集使用服务时获取的信息\n" + "\n" + "2.1 日志信息。当您使用我们的服务时,我们可能会自动收集相关信息并存储为服务日志信息\n" + "\n" + "(1) 设备信息。例如,例如,设备型号、系统名称、系统版本、MAC 地址、IMEI、Android ID信息。\n" + "\n" + "(2) 软件信息。例如,软件的版本号、浏览器类型、广告标识符。\n" + "\n" + "(3) IP地址、网卡(MAC)地址。\n" + "\n" + "(4) 服务日志信息。例如,您在使用我们服务时搜索、查看的信息、服务故障信息、引荐网址信息。\n" + "\n" + "(5) 通讯日志信息。例如,您在使用我们服务时曾经通讯的账户、通讯时间和时长。\n" + "\n" + "2.2 位置信息。当您使用与位置有关的服务时,我们可能会记录您设备所在的位置信息,以便为您提供相关服务\n" + "\n" + "(1) 在您使用服务时,我们可能会通过IP地址、GPS、WiFi或基站途径获取您的地理位置、语言所在地、时区信息;\n" + "\n" + "(2) 您或其他用户在使用服务时提供的信息中可能包含您所在地理位置信息,例如您提供的帐号信息中可能包含的您所在地区信息,您或其他人共享的照片包含的地理标记信息;\n" + "\n" + "3 为向您提供互动、发布、信息推送、产品/服务营销推广和满意度调研服务,其他相关信息\n" + "\n" + "3.1 为了帮助您更好地使用我们的产品或服务,我们会收集相关信息\n" + "\n" + "例如,我们收集的好友列表。\n" + "\n" + "3.2 其他用户分享的信息中含有您的信息\n" + "\n" + "例如,其他用户发布的照片或分享的视频中可能包含您的信息。\n" + "\n" + "3.3 从第三方合作伙伴获取的信息\n" + "\n" + "我们可能会获得您在使用第三方合作伙伴服务时所产生或分享的信息。例如,您使用第三方合作伙伴提供的支付服务时,我们会获得您登录第三方合作伙伴服务的名称、登录时间,方便您进行授权管理。请您仔细阅读第三方合作伙伴服务的用户协议或隐私政策。\n" + "\n" + "我们如何使用收集的信息\n" + "\n" + "我们将严格遵守法律法规以及与用户的约定,将收集的信息用于以下用途。\n" + "\n" + "1 向您提供服务。\n" + "\n" + "2 产品开发和服务优化。例如,当我们的系统发生故障时,我们会记录和分析系统故障时产生的信息,优化我们的服务。\n" + "\n" + "3 安全保障。例如,我们会将您的信息用于身份验证、安全防范、反诈骗监测、存档备份、客户的安全服务用途。\n" + "\n" + "4 评估、改善我们的广告投放和其他促销及推广活动的效果。\n" + "\n" + "5 管理软件。例如,进行软件认证、软件升级。\n" + "\n" + "6 邀请您参与有关我们服务的调查。\n" + "\n" + "为了确保服务的安全,帮助我们更好地了解我们应用程序的运行情况,我们可能记录相关信息,例如,您使用应用程序的频率、故障信息、总体使用情况、性能数据以及应用程序的来源。我们不会将我们存储在分析软件中的信息与您在应用程序中提供的个人身份信息相结合。\n" + "\n" + "谁在使用收集的信息\n" + "\n" + "您提供的信息主要由我们使用,并可能会被分享给第三方合作伙伴(第三方服务供应商、承包商、代理、广告合作伙伴、应用开发者,例如,代表我们推送通知的通讯服务提供商、我们聘请来提供第三方数据统计和分析服务的公司)(他们可能并非位于您所在的法域)这些信息将仅用于以下用途:\n" + "\n" + "1 向您提供我们的服务;\n" + "\n" + "2 理解、维护和改善我们的服务。\n" + "\n" + "我们仅会出于合法、正当、必要、特定、明确的目的共享您的个人信息,并且只会共享提供服务所必要的个人信息。\n" + "\n" + "对我们与之共享个人信息的公司、组织和个人,我们会与其签署严格的保密协定,要求他们按照我们的说明、本隐私政策以及其他任何相关的保密和安全措施来处理个人信息。\n" + "\n" + "我们可能基于以下目的披露您的个人信息:\n" + "\n" + "1 遵守适用的法律法规有关规定;\n" + "\n" + "2 遵守法院判决、裁定或其他法律程序的规定;\n" + "\n" + "3 遵守相关政府机关或其他法定授权组织的要求;\n" + "\n" + "4 我们有理由确信需要遵守法律法规有关规定;\n" + "\n" + "5 为执行相关服务协议或本政策、维护社会公共利益,为保护我们的客户、我们或我们的关联公司、其他用户或雇员的人身财产安全或其他合法权益合理且必要的用途。\n" + "\n" + "您所享有的权利\n" + "\n" + "按照中国相关的法律、法规、标准,以及其他国家、地区的通行做法,我们保障您对自己的个人信息行使以下权利:\n" + "\n" + "1 您有权访问您的个人信息,法律法规规定的例外情况除外。您访问、修改的范围和方式将取决于您使用的具体服务。在您访问、修改相关信息时,我们可能会要求您进行身份验证,以保障账号安全。\n" + "\n" + "2 当您发现我们处理的关于您的个人信息有错误时,您有权更正。但请您理解,由于技术所限、法律或监管要求,我们可能无法满足您的所有要求。\n" + "\n" + "未成年人保护\n" + "\n" + "若您是18周岁以下的未成年人,在使用侠启的服务前,应事先取得您的家长或法定监护人的同意。若您是未成年人的监护人,当您对您所监护的未成年人的个人信息有相关疑问时,请与我们联系。\n" + "\n" + "联系我们\n" + "\n" + "如您对本政策或其他相关事宜有疑问,请通过电子邮件地址[email protected]与我们联系。\n" + "\n" + "适用范围\n" + "\n" + "我们的所有服务均适用本政策。但某些服务有其特定的隐私指引/声明,该特定隐私指引/声明更具体地说明我们在该服务中如何处理您的信息。如本政策与特定服务的隐私指引/声明有不一致之处,请以该特定隐私指引/声明为准。\n" + "\n" + "变更\n" + "\n" + "我们可能适时修订本政策内容。在该种情况下,若您继续使用我们的服务,即表示同意受经修订的政策约束。\n" + "\n" + "第三方服务(SDK)共享清单\n" + "\n" + "为保障游戏的稳定运行,和实现产品内的支付相关功能,我们需要在您使用对应功能时向第三方共享您的个人信息。部分功能通过接入由第三方提供的软件工具开发包(SDK)的形式实现。如果您未使用相关功能,我们不会将您的个人信息与第三方共享。\n" + "\n" + "我们将可能与游戏产品存在信息共享的主体,以及涉及个人信息类型、使用目的、处理方式信息展示如下。您还可以通过第三方网站链接查看第三方收集使用个人信息的规则,具体请以其公示的官方说明为准。\n" + "\n" + "我们将督促相关第三方按照我们在《侠启游戏隐私政策》中与您的约定收集和使用您的个人信息,并采取适当的安全技术和管理措施保障您的个人信息安全。我们也会对接入的第三方软件工具开发包(SDK)进行严格的安全监测,以保护您的个人信息安全。\n" + "\n" + "以下为具体的第三方服务共享清单:\n" + "\n" + "第三方 SDK 名称:Unity 3D\n" + "\n" + "应用场景: 框架\n" + "\n" + "可能收集的个人信息的类型:读取设备信息(设备型号、系统名称、系统版本、MAC 地址、IMEI、Android ID)、访问相机、应用安装列表、任务列表、网络状态信息、设备传感器)\n" + "\n" + "第三方 SDK 提供方:Unity Technologies\n" + "\n" + "隐私政策链接:https://unity.com/cn/legal/privacy-policy\n" + "\n" + "侠启游戏 版权所有\n" + "\n"); //设置内容 dialog.setCancelable(true); //是否可以取消 dialog.setNegativeButton("拒绝", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); android.os.Process.killProcess(android.os.Process.myPid()); } }); dialog.setPositiveButton("同意", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SharedPreferences.Editor editor = base.edit(); editor.putBoolean("isFirstStartJynew", false); editor.commit(); // 玩家点击同意后,跳转到 Unity 的 Activity Intent intent = new Intent(PrivacyActivity.this, UnityPlayerActivity.class); startActivity(intent); } }); dialog.show(); } else { // 已经同意过了,直接跳转到 Unity 的 Activity Intent intent = new Intent(PrivacyActivity.this, UnityPlayerActivity.class); startActivity(intent); } } }
jynew/jynew
jyx2/Assets/Plugins/Android/com/unity3d/player/PrivacyActivity.java
244
package java.util; import sun.misc.SharedSecrets; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; /** * 概述: * List接口可调整大小的数组实现。实现所有可选的List操作,并允许所有元素,包括null,元素可重复。 * 除了列表接口外,该类提供了一种方法来操作该数组的大小来存储该列表中的数组的大小。 * 时间复杂度: * 方法size、isEmpty、get、set、iterator和listIterator的调用是常数时间的。 * 添加删除的时间复杂度为O(N)。其他所有操作也都是线性时间复杂度。 * 容量: * 每个ArrayList都有容量,容量大小至少为List元素的长度,默认初始化为10。 * 容量可以自动增长。 * 如果提前知道数组元素较多,可以在添加元素前通过调用ensureCapacity()方法提前增加容量以减小后期容量自动增长的开销。 * 也可以通过带初始容量的构造器初始化这个容量。 * 线程不安全: * ArrayList不是线程安全的。 * 如果需要应用到多线程中,需要在外部做同步 * modCount: * 定义在AbstractList中:protected transient int modCount = 0; * 已从结构上修改此列表的次数。从结构上修改是指更改列表的大小,或者打乱列表,从而使正在进行的迭代产生错误的结果。 * 此字段由iterator和listiterator方法返回的迭代器和列表迭代器实现使用。 * 如果意外更改了此字段中的值,则迭代器(或列表迭代器)将抛出concurrentmodificationexception来响应next、remove、previous、set或add操作。 * 在迭代期间面临并发修改时,它提供了快速失败 行为,而不是非确定性行为。 * 子类是否使用此字段是可选的。 * 如果子类希望提供快速失败迭代器(和列表迭代器),则它只需在其 add(int,e)和remove(int)方法(以及它所重写的、导致列表结构上修改的任何其他方法)中增加此字段。 * 对add(int, e)或remove(int)的单个调用向此字段添加的数量不得超过 1,否则迭代器(和列表迭代器)将抛出虚假的 concurrentmodificationexceptions。 * 如果某个实现不希望提供快速失败迭代器,则可以忽略此字段。 * transient: * 默认情况下,对象的所有成员变量都将被持久化.在某些情况下,如果你想避免持久化对象的一些成员变量,你可以使用transient关键字来标记他们,transient也是java中的保留字(JDK 1.8) */ public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; /** * 默认容量 */ private static final int DEFAULT_CAPACITY = 10; /** * 空的对象数组 */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * 默认的空数组 * 无参构造函数创建的数组 */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /** * 存放数据的数组的缓存变量,不可序列化 */ transient Object[] elementData; /** * 元素数量 * * @serial */ private int size; /** * 带有容量initialCapacity的构造方法 * * @param initialCapacity 初始容量列表的初始容量 * @throws IllegalArgumentException 如果指定容量为负 */ public ArrayList(int initialCapacity) { // 如果初始化时ArrayList大小大于0 if (initialCapacity > 0) { // new一个该大小的object数组赋给elementData this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) {// 如果大小为0 // 将空数组赋给elementData this.elementData = EMPTY_ELEMENTDATA; } else {// 小于0 // 则抛出IllegalArgumentException异常 throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); } } /** * 不带参数的构造方法 */ public ArrayList() { // 直接将空数组赋给elementData this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * 带参数Collection的构造方法 * * @param c 其元素将被放入此列表中的集合 * @throws NullPointerException 如果指定的集合是空的 */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toarray可能(错误地)不返回对象[](见JAVA BUG编号6260652) if (elementData.getClass() != Object[].class) { elementData = Arrays.copyOf(elementData, size, Object[].class); } } else { // 使用空数组 this.elementData = EMPTY_ELEMENTDATA; } } /** * 因为容量常常会大于实际元素的数量。内存紧张时,可以调用该方法删除预留的位置,调整容量为元素实际数量。 * 如果确定不会再有元素添加进来时也可以调用该方法来节约空间 */ public void trimToSize() { modCount++; // 如果size小于length if (size < elementData.length) { // 重新将elementData设置大小为size elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } /** * 使用指定参数设置数组容量 * * @param minCapacity 所需的最小容量 */ public void ensureCapacity(int minCapacity) { //如果数组为空,容量预取0,否则去默认值(10) int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) // any size if not default element table ? 0 // larger than default for default empty table. It's already // supposed to be at default size. : DEFAULT_CAPACITY; //若参数大于预设的容量,在使用该参数进一步设置数组容量 if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } } private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } /** * 得到最小扩容量 * * @param minCapacity */ private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } /** * 判断是否需要扩容 * * @param minCapacity */ private void ensureExplicitCapacity(int minCapacity) { modCount++; // 如果最小需要空间比elementData的内存空间要大,则需要扩容 if (minCapacity - elementData.length > 0) grow(minCapacity); } /** * 数组的最大容量,可能会导致内存溢出(VM内存限制) */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 扩容,以确保它可以至少持有由参数指定的元素的数目 * * @param minCapacity 所需的最小容量 */ private void grow(int minCapacity) { // 获取到ArrayList中elementData数组的内存空间长度 int oldCapacity = elementData.length; // 扩容至原来的1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); // 再判断一下新数组的容量够不够,够了就直接使用这个长度创建新数组, // 不够就将数组长度设置为需要的长度 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //若预设值大于默认的最大值检查是否溢出 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // 调用Arrays.copyOf方法将elementData数组指向新的内存空间时newCapacity的连续空间 // 并将elementData的数据复制到新的内存空间 elementData = Arrays.copyOf(elementData, newCapacity); } /** * 检查是否溢出,若没有溢出,返回最大整数值(java中的int为4字节,所以最大为0x7fffffff)或默认最大值 * * @param minCapacity * @return */ private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) //溢出 throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } /** * 返回ArrayList的大小 * * @return ArrayList中的元素数量 */ public int size() { return size; } /** * 返回是否为空 * * @return true 如果ArrayList中无元素 */ public boolean isEmpty() { return size == 0; } /** * 是否包含一个数 返回bool * * @param o 检测o是否为ArrayList中元素 * @return true 如果ArrayList中包含o元素 */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * 返回一个值在数组首次出现的位置,会根据是否为null使用不同方式判断。不存在就返回-1。时间复杂度为O(N) * * @param o * @return */ public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i] == null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; } /** * 返回一个值在数组最后一次出现的位置,会根据是否为null使用不同方式判断。不存在就返回-1。时间复杂度为O(N) * * @param o * @return */ public int lastIndexOf(Object o) { if (o == null) { for (int i = size - 1; i >= 0; i--) if (elementData[i] == null) return i; } else { for (int i = size - 1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } /** * 返回副本,元素本身没有被复制,复制过程数组发生改变会抛出异常 * * @return v ArrayList副本 */ public Object clone() { try { // 调用父类(翻看源码可见是Object类)的clone方法得到一个ArrayList副本 ArrayList<?> v = (ArrayList<?>) super.clone(); // 调用Arrays类的copyOf,将ArrayList的elementData数组赋值给副本的elementData数组 v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; // 返回副本v return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } } /** * 转换为Object数组,使用Arrays.copyOf()方法 * * @return 一个数组包含所有列表中的元素, 且顺序正确 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** * 将ArrayList里面的元素赋值到一个数组中去 * 如果a的长度小于ArrayList的长度,直接调用Arrays类的copyOf,返回一个比a数组长度要大的新数组,里面元素就是ArrayList里面的元素; * 如果a的长度比ArrayList的长度大,那么就调用System.arraycopy,将ArrayList的elementData数组赋值到a数组,然后把a数组的size位置赋值为空。 * * @param a 如果它的长度大的话,列表元素将存储在这个数组中; 否则,将为此分配一个相同运行时类型的新数组。 * @return 一个包含ArrayList元素的数组 * @throws ArrayStoreException 将与数组类型不兼容的值赋值给数组元素时抛出的异常 * @throws NullPointerException 数组为空 */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) // 创建一个新的a的运行时类型数组,内容不变 return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } /** * 返回指定位置的值,因为是数组,所以速度特别快 * * @param index * @return */ @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } /** * 返回指定位置的值,但是会先检查这个位置数否超出数组长度 * * @param index 要返回的元素的索引 * @return ArrayList中指定位置的元素 * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { // 检查是否越界 rangeCheck(index); // 返回ArrayList的elementData数组index位置的元素 return elementData(index); } /** * 设置指定位置为一个新值,并返回之前的值,会检查这个位置是否超出数组长度 * * @param index 要替换的元素的索引 * @param element 要存储在指定位置的元素 * @return 之前在指定位置的元素 * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { // 检查是否越界 rangeCheck(index); // 调用elementData(index)获取到当前位置的值 E oldValue = elementData(index); // 将element赋值到ArrayList的elementData数组的第index位置 elementData[index] = element; return oldValue; } /** * 添加一个值,首先会确保容量 * * @param e 要添加到此列表中的元素 * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { // 扩容 ensureCapacityInternal(size + 1); // Increments modCount!! // 将e赋值给elementData的size+1的位置 elementData[size++] = e; return true; } /** * 在ArrayList的index位置,添加元素element,会检查添加的位置和容量 * * @param index 指定元素将被插入的索引 * @param element 要插入的元素 * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { // 判断index是否越界 rangeCheckForAdd(index); // 扩容 ensureCapacityInternal(size + 1); // Increments modCount!! //public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) //src:源数组; srcPos:源数组要复制的起始位置; dest:目的数组; destPos:目的数组放置的起始位置; length:复制的长度 // 将elementData从index位置开始,复制到elementData的index+1开始的连续空间 System.arraycopy(elementData, index, elementData, index + 1, size - index); // 在elementData的index位置赋值element elementData[index] = element; // ArrayList的大小加一 size++; } /** * 在ArrayList的移除index位置的元素,会检查添加的位置,返回之前的值 * * @param index 要删除的元素的索引 * @return 从ArrayList中删除的元素 * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { // 判断是否越界 rangeCheck(index); modCount++; // 读取旧值 E oldValue = elementData(index); // 获取index位置开始到最后一个位置的个数 int numMoved = size - index - 1; if (numMoved > 0) // 将elementData数组index+1位置开始拷贝到elementData从index开始的空间 System.arraycopy(elementData, index + 1, elementData, index, numMoved); // 使size-1 ,设置elementData的size位置为空,让GC来清理内存空间 elementData[--size] = null; //便于垃圾回收器回收 return oldValue; } /** * 在ArrayList的移除对象为O的元素,跟indexOf方法思想基本一致 * * @param o 要从该列表中删除的元素(如果存在) * @return true 如果这个列表包含指定的元素 */ public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } /** * 快速删除指定位置的值,之所以叫快速,应该是不需要检查和返回值,因为只内部使用 * * @param index */ private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index + 1, elementData, index, numMoved); // 使size-1 ,设置elementData的size位置为空,让GC来清理内存空间 elementData[--size] = null; //便于垃圾回收器回收 } /** * 清空数组,把每一个值设为null,方便垃圾回收(不同于reset,数组默认大小有改变的话不会重置) */ public void clear() { modCount++; //便于垃圾回收器回收 for (int i = 0; i < size; i++) elementData[i] = null; //把size设置为0,以便我们不会浏览到null值的内存空间 size = 0; } /** * 添加一个集合的元素到末端,若要添加的集合为空返回false * * @param c 包含要添加到此列表中的元素的集合 * @return true 如果该列表因添加而改变 * @throws NullPointerException 如果指定的集合是空的 */ public boolean addAll(Collection<? extends E> c) { // 将c转换为数组a Object[] a = c.toArray(); // 获取a占的内存空间长度赋值给numNew int numNew = a.length; // 扩容至size + numNew ensureCapacityInternal(size + numNew); // Increments modCount // 将a的第0位开始拷贝至elementData的size位开始,拷贝长度为numNew System.arraycopy(a, 0, elementData, size, numNew); // 将size增加numNew size += numNew; // 如果c为空,返回false,c不为空,返回true return numNew != 0; } /** * 从第index位开始,将c全部拷贝到ArrayList,若要添加的集合为空返回false * * @param index 在哪个索引处插入指定集合中的第一个元素 * @param c 包含要添加到此列表中的元素的集合 * @return true 如果该列表因添加而改变 * @throws IndexOutOfBoundsException {@inheritDoc} * @throws NullPointerException 如果指定的集合是空的 */ public boolean addAll(int index, Collection<? extends E> c) { // 判断index大于size或者是小于0,如果是,则抛出IndexOutOfBoundsException异常 rangeCheckForAdd(index); // 将c转换为数组a Object[] a = c.toArray(); int numNew = a.length; // 扩容至size + numNew ensureCapacityInternal(size + numNew); // Increments modCount // 获取需要添加的个数 int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; } /** * 删除指定范围元素。参数为开始删的位置和结束位置 * * @throws IndexOutOfBoundsException if {@code fromIndex} or * {@code toIndex} is out of range * ({@code fromIndex < 0 || * fromIndex >= size() || * toIndex > size() || * toIndex < fromIndex}) */ protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex;//后段保留的长度 System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); //便于垃圾回收期回收 int newSize = size - (toIndex - fromIndex); for (int i = newSize; i < size; i++) { elementData[i] = null; } size = newSize; } /** * 检查index是否超出数组长度 用于添加元素时 */ private void rangeCheck(int index) { // 如果下标超过ArrayList的数组长度 if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * 检查是否溢出 */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * 抛出的异常的详情 */ private String outOfBoundsMsg(int index) { return "Index: " + index + ", Size: " + size; } /** * ArrayList移除集合c中的所有元素 * * @param c 包含要从此列表中移除的元素的集合 * @return {@code true} 如果该列表因移除而改变 * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>), * or if the specified collection is null * @see Collection#contains(Object) */ public boolean removeAll(Collection<?> c) { // 如果c为空,则抛出空指针异常 Objects.requireNonNull(c); // 调用batchRemove移除c中的元素 return batchRemove(c, false); } /** * 仅保留指定集合c中的元素 * * @param c collection containing elements to be retained in this list * @return {@code true} if this list changed as a result of the call * @throws ClassCastException if the class of an element of this list * is incompatible with the specified collection * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if this list contains a null element and the * specified collection does not permit null elements * (<a href="Collection.html#optional-restrictions">optional</a>), * or if the specified collection is null * @see Collection#contains(Object) */ public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); // 调用batchRemove保留c中的元素 return batchRemove(c, true); } /** * 根据complement值,将ArrayList中包含c中元素的元素删除或者保留 * * @param c * @param complement true时从数组保留指定集合中元素的值,为false时从数组删除指定集合中元素的值。 * @return 数组中重复的元素都会被删除(而不是仅删除一次或几次),有任何删除操作都会返回true */ private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; // 定义一个w,一个r,两个同时右移 int r = 0, w = 0; boolean modified = false; try { // r先右移 for (; r < size; r++) // 如果c中不包含elementData[r]这个元素 if (c.contains(elementData[r]) == complement) // 则直接将r位置的元素赋值给w位置的元素,w自增 elementData[w++] = elementData[r]; } finally { // 防止抛出异常导致上面r的右移过程没完成 if (r != size) { // 将r未右移完成的位置的元素赋值给w右边位置的元素 System.arraycopy(elementData, r, elementData, w, size - r); // 修改w值增加size-r w += size - r; } // 如果有被覆盖掉的元素,则将w后面的元素都赋值为null if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w;//改变的次数 //新的大小为保留的元素的个数 size = w; modified = true; } } return modified; } /** * 保存数组实例的状态到一个流(即序列化)。写入过程数组被更改会抛出异常 * * @serialData The length of the array backing the <tt>ArrayList</tt> * instance is emitted (int), followed by all of its elements * (each an <tt>Object</tt>) in the proper order. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out element count, and any hidden stuff int expectedModCount = modCount; //执行默认的反序列化/序列化过程。将当前类的非静态和非瞬态字段写入此流 s.defaultWriteObject(); // 写入大小 s.writeInt(size); // 按顺序写入所有元素 for (int i = 0; i < size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** * 从流中重构ArrayList实例(即反序列化)。 */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // 执行默认的序列化/反序列化过程 s.defaultReadObject(); // 读入数组长度 s.readInt(); // ignored if (size > 0) { // 像clone()方法 ,但根据大小而不是容量分配数组 int capacity = calculateCapacity(elementData, size); SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity); ensureCapacityInternal(size); Object[] a = elementData; //读入所有元素 for (int i = 0; i < size; i++) { a[i] = s.readObject(); } } } /** * 返回一个从index开始的ListIterator对象 * * @throws IndexOutOfBoundsException {@inheritDoc} */ public ListIterator<E> listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: " + index); return new ListItr(index); } /** * 返回一个ListIterator对象,ListItr为ArrayList的一个内部类,其实现了ListIterator<E> 接口 * * @see #listIterator(int) */ public ListIterator<E> listIterator() { return new ListItr(0); } /** * 返回一个Iterator对象,Itr为ArrayList的一个内部类,其实现了Iterator<E>接口 * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { return new Itr(); } /** * 通用的迭代器实现 */ private class Itr implements Iterator<E> { int cursor; //游标,下一个元素的索引,默认初始化为0 int lastRet = -1; //上次访问的元素的位置 int expectedModCount = modCount;//迭代过程不运行修改数组,否则就抛出异常 //是否还有下一个 public boolean hasNext() { return cursor != size; } //下一个元素 @SuppressWarnings("unchecked") public E next() { checkForComodification();//检查数组是否被修改 int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1;//向后移动游标 return (E) elementData[lastRet = i];//设置访问的位置并返回这个值 } //删除元素 public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification();//检查数组是否被修改 try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } //检查数组是否被修改 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** * ListIterator迭代器实现 */ private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } /** * Returns a view of the portion of this list between the specified * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If * {@code fromIndex} and {@code toIndex} are equal, the returned list is * empty.) The returned list is backed by this list, so non-structural * changes in the returned list are reflected in this list, and vice-versa. * The returned list supports all of the optional list operations. * <p> * <p>This method eliminates the need for explicit range operations (of * the sort that commonly exist for arrays). Any operation that expects * a list can be used as a range operation by passing a subList view * instead of a whole list. For example, the following idiom * removes a range of elements from a list: * <pre> * list.subList(from, to).clear(); * </pre> * Similar idioms may be constructed for {@link #indexOf(Object)} and * {@link #lastIndexOf(Object)}, and all of the algorithms in the * {@link Collections} class can be applied to a subList. * <p> * <p>The semantics of the list returned by this method become undefined if * the backing list (i.e., this list) is <i>structurally modified</i> in * any way other than via the returned list. (Structural modifications are * those that change the size of this list, or otherwise perturb it in such * a fashion that iterations in progress may yield incorrect results.) * * @throws IndexOutOfBoundsException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); } /** * 安全检查 * * @param fromIndex * @param toIndex * @param size */ static void subListRangeCheck(int fromIndex, int toIndex, int size) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > size) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } /** * 子数组 */ private class SubList extends AbstractList<E> implements RandomAccess { private final AbstractList<E> parent; private final int parentOffset; private final int offset; int size; SubList(AbstractList<E> parent, int offset, int fromIndex, int toIndex) { this.parent = parent; this.parentOffset = fromIndex; this.offset = offset + fromIndex; this.size = toIndex - fromIndex; this.modCount = ArrayList.this.modCount; } public E set(int index, E e) { rangeCheck(index); checkForComodification(); E oldValue = ArrayList.this.elementData(offset + index); ArrayList.this.elementData[offset + index] = e; return oldValue; } public E get(int index) { rangeCheck(index); checkForComodification(); return ArrayList.this.elementData(offset + index); } public int size() { checkForComodification(); return this.size; } public void add(int index, E e) { rangeCheckForAdd(index); checkForComodification(); parent.add(parentOffset + index, e); this.modCount = parent.modCount; this.size++; } public E remove(int index) { rangeCheck(index); checkForComodification(); E result = parent.remove(parentOffset + index); this.modCount = parent.modCount; this.size--; return result; } protected void removeRange(int fromIndex, int toIndex) { checkForComodification(); parent.removeRange(parentOffset + fromIndex, parentOffset + toIndex); this.modCount = parent.modCount; this.size -= toIndex - fromIndex; } public boolean addAll(Collection<? extends E> c) { return addAll(this.size, c); } public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); int cSize = c.size(); if (cSize == 0) return false; checkForComodification(); parent.addAll(parentOffset + index, c); this.modCount = parent.modCount; this.size += cSize; return true; } public Iterator<E> iterator() { return listIterator(); } public ListIterator<E> listIterator(final int index) { checkForComodification(); rangeCheckForAdd(index); final int offset = this.offset; return new ListIterator<E>() { int cursor = index; int lastRet = -1; int expectedModCount = ArrayList.this.modCount; public boolean hasNext() { return cursor != SubList.this.size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= SubList.this.size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[offset + (lastRet = i)]; } public boolean hasPrevious() { return cursor != 0; } @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[offset + (lastRet = i)]; } @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = SubList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[offset + (i++)]); } // update once at end of iteration to reduce heap write traffic lastRet = cursor = i; checkForComodification(); } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { SubList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = ArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(offset + lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } public void add(E e) { checkForComodification(); try { int i = cursor; SubList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = ArrayList.this.modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (expectedModCount != ArrayList.this.modCount) throw new ConcurrentModificationException(); } }; } /** * 返回指定范围的子数组 * * @param fromIndex * @param toIndex * @return */ public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, offset, fromIndex, toIndex); } private void rangeCheck(int index) { if (index < 0 || index >= this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private void rangeCheckForAdd(int index) { if (index < 0 || index > this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } private String outOfBoundsMsg(int index) { return "Index: " + index + ", Size: " + this.size; } private void checkForComodification() { if (ArrayList.this.modCount != this.modCount) throw new ConcurrentModificationException(); } public Spliterator<E> spliterator() { checkForComodification(); return new ArrayListSpliterator<E>(ArrayList.this, offset, offset + this.size, this.modCount); } } @Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); final int expectedModCount = modCount; @SuppressWarnings("unchecked") final E[] elementData = (E[]) this.elementData; final int size = this.size; for (int i = 0; modCount == expectedModCount && i < size; i++) { action.accept(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em> * and <em>fail-fast</em> {@link Spliterator} over the elements in this * list. * <p> * <p>The {@code Spliterator} reports {@link Spliterator#SIZED}, * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}. * Overriding implementations should document the reporting of additional * characteristic values. * * @return a {@code Spliterator} over the elements in this list * @since 1.8 */ @Override public Spliterator<E> spliterator() { return new ArrayListSpliterator<>(this, 0, -1, 0); } /** * Index-based split-by-two, lazily initialized Spliterator */ static final class ArrayListSpliterator<E> implements Spliterator<E> { /** * 如果ArrayLists是不可变的,或者在结构上不可变(不添加,删除等),我们可以用Arrays.spliterator实现它们的分割器。 * 相反,我们在遍历期间检测到尽可能多的干扰而不会影响性能。 * 我们主要依靠modCounts。这些不能保证检测到并发冲突,有时对线程内干扰过于保守,但在实践中检测到足够的问题是值得的。 * 为了实现这一点,我们 * (1)懒惰地初始化fence和expectedModCount,直到我们需要提交到我们正在检查的状态的最后一点;从而提高精度。 * (这不适用于SubLists,它会使用当前非惰性值的分割符)。 * (2)我们在forEach(对性能最敏感的方法)结束时只执行一次ConcurrentModificationException检查。 * 当使用forEach(而不是迭代器)时,我们通常只能在行为之后检测干扰,而不是之前。 * 进一步的CME触发检查适用于所有其他可能的违反假设的情况,例如null或过小的elementData数组,因为它的大小()只能由于干扰而发生。 * 这允许forEach的内循环在没有任何进一步检查的情况下运行,并且简化了lambda分辨率。虽然这需要进行多次检查,但请注意,在list.stream()。 * forEach(a)的常见情况中,除forEach本身之外,不会执行任何检查或其他计算。其他较少使用的方法无法利用这些优化的大部分优势。 */ private final ArrayList<E> list; private int index; // current index, modified on advance/split private int fence; // -1 until used; then one past last index private int expectedModCount; // initialized when fence set /** * Create new spliterator covering the given range */ ArrayListSpliterator(ArrayList<E> list, int origin, int fence, int expectedModCount) { this.list = list; // OK if null unless traversed this.index = origin; this.fence = fence; this.expectedModCount = expectedModCount; } private int getFence() { // initialize fence to size on first use int hi; // (a specialized variant appears in method forEach) ArrayList<E> lst; if ((hi = fence) < 0) { if ((lst = list) == null) hi = fence = 0; else { expectedModCount = lst.modCount; hi = fence = lst.size; } } return hi; } public ArrayListSpliterator<E> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid) ? null : // divide range in half unless too small new ArrayListSpliterator<E>(list, lo, index = mid, expectedModCount); } public boolean tryAdvance(Consumer<? super E> action) { if (action == null) throw new NullPointerException(); int hi = getFence(), i = index; if (i < hi) { index = i + 1; @SuppressWarnings("unchecked") E e = (E) list.elementData[i]; action.accept(e); if (list.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } return false; } public void forEachRemaining(Consumer<? super E> action) { int i, hi, mc; // hoist accesses and checks from loop ArrayList<E> lst; Object[] a; if (action == null) throw new NullPointerException(); if ((lst = list) != null && (a = lst.elementData) != null) { if ((hi = fence) < 0) { mc = lst.modCount; hi = lst.size; } else mc = expectedModCount; if ((i = index) >= 0 && (index = hi) <= a.length) { for (; i < hi; ++i) { @SuppressWarnings("unchecked") E e = (E) a[i]; action.accept(e); } if (lst.modCount == mc) return; } } throw new ConcurrentModificationException(); } public long estimateSize() { return (long) (getFence() - index); } public int characteristics() { return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; } } @Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); // figure out which elements are to be removed // any exception thrown from the filter predicate at this stage // will leave the collection unmodified int removeCount = 0; final BitSet removeSet = new BitSet(size); final int expectedModCount = modCount; final int size = this.size; for (int i = 0; modCount == expectedModCount && i < size; i++) { @SuppressWarnings("unchecked") final E element = (E) elementData[i]; if (filter.test(element)) { removeSet.set(i); removeCount++; } } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } // shift surviving elements left over the spaces left by removed elements final boolean anyToRemove = removeCount > 0; if (anyToRemove) { final int newSize = size - removeCount; for (int i = 0, j = 0; (i < size) && (j < newSize); i++, j++) { i = removeSet.nextClearBit(i); elementData[j] = elementData[i]; } for (int k = newSize; k < size; k++) { elementData[k] = null; // Let gc do its work } this.size = newSize; if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } return anyToRemove; } @Override @SuppressWarnings("unchecked") public void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); final int expectedModCount = modCount; final int size = this.size; for (int i = 0; modCount == expectedModCount && i < size; i++) { elementData[i] = operator.apply((E) elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } @Override @SuppressWarnings("unchecked") public void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, size, c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } }
wupeixuan/JDKSourceCode1.8
src/java/util/ArrayList.java
249
package com.alibaba.datax.common.spi; import java.util.List; import com.alibaba.datax.common.base.BaseObject; import com.alibaba.datax.common.plugin.AbstractJobPlugin; import com.alibaba.datax.common.plugin.AbstractTaskPlugin; import com.alibaba.datax.common.util.Configuration; import com.alibaba.datax.common.plugin.RecordSender; /** * 每个Reader插件在其内部内部实现Job、Task两个内部类。 * * * */ public abstract class Reader extends BaseObject { /** * 每个Reader插件必须实现Job内部类。 * * */ public static abstract class Job extends AbstractJobPlugin { /** * 切分任务 * * @param adviceNumber * * 着重说明下,adviceNumber是框架建议插件切分的任务数,插件开发人员最好切分出来的任务数>= * adviceNumber。<br> * <br> * 之所以采取这个建议是为了给用户最好的实现,例如框架根据计算认为用户数据存储可以支持100个并发连接, * 并且用户认为需要100个并发。 此时,插件开发人员如果能够根据上述切分规则进行切分并做到>=100连接信息, * DataX就可以同时启动100个Channel,这样给用户最好的吞吐量 <br> * 例如用户同步一张Mysql单表,但是认为可以到10并发吞吐量,插件开发人员最好对该表进行切分,比如使用主键范围切分, * 并且如果最终切分任务数到>=10,我们就可以提供给用户最大的吞吐量。 <br> * <br> * 当然,我们这里只是提供一个建议值,Reader插件可以按照自己规则切分。但是我们更建议按照框架提供的建议值来切分。 <br> * <br> * 对于ODPS写入OTS而言,如果存在预排序预切分问题,这样就可能只能按照分区信息切分,无法更细粒度切分, * 这类情况只能按照源头物理信息切分规则切分。 <br> * <br> * * * */ public abstract List<Configuration> split(int adviceNumber); } public static abstract class Task extends AbstractTaskPlugin { public abstract void startRead(RecordSender recordSender); } }
alibaba/DataX
common/src/main/java/com/alibaba/datax/common/spi/Reader.java
250
package com.xkcoding.cache.redis.service.impl; import com.google.common.collect.Maps; import com.xkcoding.cache.redis.entity.User; import com.xkcoding.cache.redis.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.Map; /** * <p> * UserService * </p> * * @author yangkai.shen * @date Created in 2018-11-15 16:45 */ @Service @Slf4j public class UserServiceImpl implements UserService { /** * 模拟数据库 */ private static final Map<Long, User> DATABASES = Maps.newConcurrentMap(); /** * 初始化数据 */ static { DATABASES.put(1L, new User(1L, "user1")); DATABASES.put(2L, new User(2L, "user2")); DATABASES.put(3L, new User(3L, "user3")); } /** * 保存或修改用户 * * @param user 用户对象 * @return 操作结果 */ @CachePut(value = "user", key = "#user.id") @Override public User saveOrUpdate(User user) { DATABASES.put(user.getId(), user); log.info("保存用户【user】= {}", user); return user; } /** * 获取用户 * * @param id key值 * @return 返回结果 */ @Cacheable(value = "user", key = "#id") @Override public User get(Long id) { // 我们假设从数据库读取 log.info("查询用户【id】= {}", id); return DATABASES.get(id); } /** * 删除 * * @param id key值 */ @CacheEvict(value = "user", key = "#id") @Override public void delete(Long id) { DATABASES.remove(id); log.info("删除用户【id】= {}", id); } }
xkcoding/spring-boot-demo
demo-cache-redis/src/main/java/com/xkcoding/cache/redis/service/impl/UserServiceImpl.java
252
/* * 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.okgo.https; import com.lzy.okgo.utils.OkLogger; import java.io.IOException; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/11 * 描 述:Https相关的工具类 * 修订历史: * ================================================ */ public class HttpsUtils { public static class SSLParams { public SSLSocketFactory sSLSocketFactory; public X509TrustManager trustManager; } public static SSLParams getSslSocketFactory() { return getSslSocketFactoryBase(null, null, null); } /** * https单向认证 * 可以额外配置信任服务端的证书策略,否则默认是按CA证书去验证的,若不是CA可信任的证书,则无法通过验证 */ public static SSLParams getSslSocketFactory(X509TrustManager trustManager) { return getSslSocketFactoryBase(trustManager, null, null); } /** * https单向认证 * 用含有服务端公钥的证书校验服务端证书 */ public static SSLParams getSslSocketFactory(InputStream... certificates) { return getSslSocketFactoryBase(null, null, null, certificates); } /** * https双向认证 * bksFile 和 password -> 客户端使用bks证书校验服务端证书 * certificates -> 用含有服务端公钥的证书校验服务端证书 */ public static SSLParams getSslSocketFactory(InputStream bksFile, String password, InputStream... certificates) { return getSslSocketFactoryBase(null, bksFile, password, certificates); } /** * https双向认证 * bksFile 和 password -> 客户端使用bks证书校验服务端证书 * X509TrustManager -> 如果需要自己校验,那么可以自己实现相关校验,如果不需要自己校验,那么传null即可 */ public static SSLParams getSslSocketFactory(InputStream bksFile, String password, X509TrustManager trustManager) { return getSslSocketFactoryBase(trustManager, bksFile, password); } private static SSLParams getSslSocketFactoryBase(X509TrustManager trustManager, InputStream bksFile, String password, InputStream... certificates) { SSLParams sslParams = new SSLParams(); try { KeyManager[] keyManagers = prepareKeyManager(bksFile, password); TrustManager[] trustManagers = prepareTrustManager(certificates); X509TrustManager manager; if (trustManager != null) { //优先使用用户自定义的TrustManager manager = trustManager; } else if (trustManagers != null) { //然后使用默认的TrustManager manager = chooseTrustManager(trustManagers); } else { //否则使用不安全的TrustManager manager = UnSafeTrustManager; } // 创建TLS类型的SSLContext对象, that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); // 用上面得到的trustManagers初始化SSLContext,这样sslContext就会信任keyStore中的证书 // 第一个参数是授权的密钥管理器,用来授权验证,比如授权自签名的证书验证。第二个是被授权的证书管理器,用来验证服务器端的证书 sslContext.init(keyManagers, new TrustManager[]{manager}, null); // 通过sslContext获取SSLSocketFactory对象 sslParams.sSLSocketFactory = sslContext.getSocketFactory(); sslParams.trustManager = manager; return sslParams; } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } catch (KeyManagementException e) { throw new AssertionError(e); } } private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) { try { if (bksFile == null || password == null) return null; KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(bksFile, password.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientKeyStore, password.toCharArray()); return kmf.getKeyManagers(); } catch (Exception e) { OkLogger.printStackTrace(e); } return null; } private static TrustManager[] prepareTrustManager(InputStream... certificates) { if (certificates == null || certificates.length <= 0) return null; try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // 创建一个默认类型的KeyStore,存储我们信任的证书 KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); int index = 0; for (InputStream certStream : certificates) { String certificateAlias = Integer.toString(index++); // 证书工厂根据证书文件的流生成证书 cert Certificate cert = certificateFactory.generateCertificate(certStream); // 将 cert 作为可信证书放入到keyStore中 keyStore.setCertificateEntry(certificateAlias, cert); try { if (certStream != null) certStream.close(); } catch (IOException e) { OkLogger.printStackTrace(e); } } //我们创建一个默认类型的TrustManagerFactory TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); //用我们之前的keyStore实例初始化TrustManagerFactory,这样tmf就会信任keyStore中的证书 tmf.init(keyStore); //通过tmf获取TrustManager数组,TrustManager也会信任keyStore中的证书 return tmf.getTrustManagers(); } catch (Exception e) { OkLogger.printStackTrace(e); } return null; } private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) { for (TrustManager trustManager : trustManagers) { if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } } return null; } /** * 为了解决客户端不信任服务器数字证书的问题,网络上大部分的解决方案都是让客户端不对证书做任何检查, * 这是一种有很大安全漏洞的办法 */ public static X509TrustManager UnSafeTrustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } }; /** * 此类是用于主机名验证的基接口。 在握手期间,如果 URL 的主机名和服务器的标识主机名不匹配, * 则验证机制可以回调此接口的实现程序来确定是否应该允许此连接。策略可以是基于证书的或依赖于其他验证方案。 * 当验证 URL 主机名使用的默认规则失败时使用这些回调。如果主机名是可接受的,则返回 true */ public static HostnameVerifier UnSafeHostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; }
jeasonlzy/okhttp-OkGo
okgo/src/main/java/com/lzy/okgo/https/HttpsUtils.java
253
/** * 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; /** * @author yuyh. * @date 2016/8/4. */ public class ChapterRead extends Base { /** * title : 1,相亲 * body : 月湾咖啡厅,苏锦一进门就瞧见了那个相亲对象。 他正坐在向阳的9号桌上。 身上穿的是一件大海蓝的衬衫,没系领带,发型清爽,五官端正,淡淡的阳光照在他脸上,衬得他冷峻毕露。 乍一看,威势十足,竟惹得边上几个年轻小姑娘频频侧目。 这人,的确长着一副好皮囊,怪不得王阿婆一个劲儿的向她夸: “你只要见,保管觉得好。那种人,只有他挑人,没人会挑他的。” 现在看来好像有点道理。 门口,有道长廊镜,苏锦转头看了看自己这身打扮。 长款黑色雪纺衬衣,底下配一条白色九分裤,露着白藕似的胳膊,最能显示女性魅力的中发被她扎成了马尾,清水芙蓉似的脸孔,没上妆,显得素净清秀。 先头,王阿婆一个劲儿的叮嘱她:“去的时候,打扮打扮!那孩子眼界高着呢!” 她没打扮,素面朝天,这才是最真实的她。 “你好,我叫苏锦!你是靳恒远先生吗?” 苏锦走了过去,声音温温婉婉。 正在用手机看着股市行情的男人抬起头,看到她时,目光闪了一下,站起时收了手机微一笑。 这一笑,让他那显得疏离的脸孔多了几分亲切。 “对,我是靳恒远!苏小姐是吗?请坐!” 靳恒远很绅士的给她拉开椅子,嗓音低低富有磁性,极为好听。 “谢谢!” 苏锦坐下,点了一杯咖啡,呷了几口,才说话:“靳先生的一些生平,我多少听王阿婆说了一些。” 男人正打量她,她有点不自在的捋了捋耳边的发。 相亲相亲,总得让人看的。 好在,他的目光并不让人觉得讨厌。 “哦,不知道王婆是怎么自卖自夸的?” 靳恒远挺风趣的反问。 苏锦扯了扯嘴角。 其实她所知甚少。 “靳先生今年三十二岁了是吗?” 比她大了足足六岁,算是个老男人了。 不过见到本人,看着挺年轻。 “嗯!” “像靳先生这样仪表堂堂的男士,怎么会至今未婚?” “工作太忙,耽误了,等到想要结婚的时候,才发现和自己年纪相仿的异性,孩子都满地跑了……” 靳恒远微一笑,喝了一口咖啡。 “苏小姐对相亲对象有什么要求吗?” “我要求不高!”苏锦说:“品性要正,责任感要强,必须忠于婚姻。” “对车房没要求?” 靳恒远睨了一眼,那一眼,好像很有深意。 苏锦微微笑了一个。 现在女性找老公,车房已经成了标配,哪怕在这样一个小县城:女孩子谁不想嫁个家境好的男人,把日子过舒坦了。 要不然怎么会说结婚是女人第二次投胎? 第一次谁也没得选择,第二次必须千挑万选,这要选错了,那一辈子就全毁了。 只是苏锦的心,早死了,如今的她,相亲,只是为了给母亲一个交代。 “没要求。” 她吐出三字。 …… 淡淡的咖啡香,飘散在空气中,两个陌生的男女,不咸不淡聊着天。 过了一会儿,苏锦看了一下手表: “靳先生,该了解的,我们都已经谈了,如果你认为我们合适,我想明天就去领证。” 靳恒远眉一挑,但笑不笑:“苏小姐就这么急着结婚,不怕我是骗子?” 苏锦淡一笑:“王阿婆眼光一向很挑,她介绍的人,一定不差。” “苏小姐就这么相信王阿婆?” “我信。另外,我妈妈得了肝癌,晚期。她希望在临走之前看到我找到一个好归宿。在时间上,我耗不起。” 一般来说,没有人肯这么草率同意婚事的。 苏锦以为他会拒绝,这样她就可以顺水推舟了,王阿婆那边也好交待。 “明天不行。明天我要出差,这几天都会在外地。要领下午就去。” 靳恒远看了看手机上的钟点。 “你要没意见,我现在回去拿证件,两点半,我们在民政局见。” 苏锦:“……” - - - 题外话 - - - 待续…… 新文,全新尝试,喜欢的亲请多多支持,谢谢! */ public Chapter chapter; public static class Chapter implements Serializable{ public String title; public String body; public String cpContent; public Chapter(String title, String body) { this.title = title; this.body = body; } public Chapter(String title, String body, String cpContent) { this.title = title; this.body = body; this.cpContent = cpContent; } } }
smuyyh/BookReader
app/src/main/java/com/justwayward/reader/bean/ChapterRead.java
254
package com.github.ompc.greys.core.util; /** * 代码锁<br/> * 什么叫代码锁?代码锁的出现是由于在字节码中,我们无法用简单的if语句来判定这段代码是生成的还是原有的。 * 这会导致一些监控逻辑的混乱,比如trace命令如果不使用代码锁保护,将能看到Greys所植入的代码并进行跟踪 * Created by [email protected] on 15/5/28. */ public interface CodeLock { /** * 根据字节码流锁或解锁代码<br/> * 通过对字节码流的判断,决定当前代码是锁定和解锁 * * @param opcode 字节码 */ void code(int opcode); /** * 判断当前代码是否还在锁定中 * * @return true/false */ boolean isLock(); /** * 将一个代码块纳入代码锁保护范围 * * @param block 代码块 */ void lock(Block block); /** * 代码块 */ interface Block { /** * 代码 */ void code(); } }
oldmanpushcart/greys-anatomy
core/src/main/java/com/github/ompc/greys/core/util/CodeLock.java
255
/* * Copyright 2009-2011 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.session; import java.io.Closeable; import java.sql.Connection; import java.util.List; import java.util.Map; import org.apache.ibatis.executor.BatchResult; /** * The primary Java interface for working with MyBatis. * Through this interface you can execute commands, get mappers and manage transactions. * * @author Clinton Begin */ /** * 这是MyBatis主要的一个类,用来执行SQL,获取映射器,管理事务 * * 通常情况下,我们在应用程序中使用的Mybatis的API就是这个接口定义的方法。 * */ public interface SqlSession extends Closeable { /** * Retrieve a single row mapped from the statement key * 根据指定的SqlID获取一条记录的封装对象 * @param <T> the returned object type 封装之后的对象类型 * @param statement sqlID * @return Mapped object 封装之后的对象 */ <T> T selectOne(String statement); /** * Retrieve a single row mapped from the statement key and parameter. * 根据指定的SqlID获取一条记录的封装对象,只不过这个方法容许我们可以给sql传递一些参数 * 一般在实际使用中,这个参数传递的是pojo,或者Map或者ImmutableMap * @param <T> the returned object type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @return Mapped object */ <T> T selectOne(String statement, Object parameter); /** * Retrieve a list of mapped objects from the statement key and parameter. * 根据指定的sqlId获取多条记录 * @param <E> the returned list element type * @param statement Unique identifier matching the statement to use. * @return List of mapped object */ <E> List<E> selectList(String statement); /** * Retrieve a list of mapped objects from the statement key and parameter. * 获取多条记录,这个方法容许我们可以传递一些参数 * @param <E> the returned list element type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @return List of mapped object */ <E> List<E> selectList(String statement, Object parameter); /** * Retrieve a list of mapped objects from the statement key and parameter, * within the specified row bounds. * 获取多条记录,这个方法容许我们可以传递一些参数,不过这个方法容许我们进行 * 分页查询。 * * 需要注意的是默认情况下,Mybatis为了扩展性,仅仅支持内存分页。也就是会先把 * 所有的数据查询出来以后,然后在内存中进行分页。因此在实际的情况中,需要注意 * 这一点。 * * 一般情况下公司都会编写自己的Mybatis 物理分页插件 * @param <E> the returned list element type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @param rowBounds Bounds to limit object retrieval * @return List of mapped object */ <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds); /** * The selectMap is a special case in that it is designed to convert a list * of results into a Map based on one of the properties in the resulting * objects. * Eg. Return a of Map[Integer,Author] for selectMap("selectAuthors","id") * 将查询到的结果列表转换为Map类型。 * @param <K> the returned Map keys type * @param <V> the returned Map values type * @param statement Unique identifier matching the statement to use. * @param mapKey The property to use as key for each value in the list. 这个参数会作为结果map的key * @return Map containing key pair data. */ <K, V> Map<K, V> selectMap(String statement, String mapKey); /** * The selectMap is a special case in that it is designed to convert a list * of results into a Map based on one of the properties in the resulting * objects. * 将查询到的结果列表转换为Map类型。这个方法容许我们传入需要的参数 * @param <K> the returned Map keys type * @param <V> the returned Map values type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @param mapKey The property to use as key for each value in the list. * @return Map containing key pair data. */ <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey); /** * The selectMap is a special case in that it is designed to convert a list * of results into a Map based on one of the properties in the resulting * objects. * 获取多条记录,加上分页,并存入Map * @param <K> the returned Map keys type * @param <V> the returned Map values type * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @param mapKey The property to use as key for each value in the list. * @param rowBounds Bounds to limit object retrieval * @return Map containing key pair data. */ <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds); /** * Retrieve a single row mapped from the statement key and parameter * using a {@code ResultHandler}. * * @param statement Unique identifier matching the statement to use. * @param parameter A parameter object to pass to the statement. * @param handler ResultHandler that will handle each retrieved row * @return Mapped object */ void select(String statement, Object parameter, ResultHandler handler); /** * Retrieve a single row mapped from the statement * using a {@code ResultHandler}. * 获取一条记录,并转交给ResultHandler处理。这个方法容许我们自己定义对 * 查询到的行的处理方式。不过一般用的并不是很多 * @param statement Unique identifier matching the statement to use. * @param handler ResultHandler that will handle each retrieved row * @return Mapped object */ void select(String statement, ResultHandler handler); /** * Retrieve a single row mapped from the statement key and parameter * using a {@code ResultHandler} and {@code RowBounds} * 获取一条记录,加上分页,并转交给ResultHandler处理 * @param statement Unique identifier matching the statement to use. * @param rowBounds RowBound instance to limit the query results * @param handler ResultHandler that will handle each retrieved row * @return Mapped object */ void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler); /** * Execute an insert statement. * 插入记录。一般情况下这个语句在实际项目中用的并不是太多,而且更多使用带参数的insert函数 * @param statement Unique identifier matching the statement to execute. * @return int The number of rows affected by the insert. */ int insert(String statement); /** * Execute an insert statement with the given parameter object. Any generated * autoincrement values or selectKey entries will modify the given parameter * object properties. Only the number of rows affected will be returned. * 插入记录,容许传入参数。 * @param statement Unique identifier matching the statement to execute. * @param parameter A parameter object to pass to the statement. * @return int The number of rows affected by the insert. 注意返回的是受影响的行数 */ int insert(String statement, Object parameter); /** * Execute an update statement. The number of rows affected will be returned. * 更新记录。返回的是受影响的行数 * @param statement Unique identifier matching the statement to execute. * @return int The number of rows affected by the update. */ int update(String statement); /** * Execute an update statement. The number of rows affected will be returned. * 更新记录 * @param statement Unique identifier matching the statement to execute. * @param parameter A parameter object to pass to the statement. * @return int The number of rows affected by the update. 返回的是受影响的行数 */ int update(String statement, Object parameter); /** * Execute a delete statement. The number of rows affected will be returned. * 删除记录 * @param statement Unique identifier matching the statement to execute. * @return int The number of rows affected by the delete. 返回的是受影响的行数 */ int delete(String statement); /** * Execute a delete statement. The number of rows affected will be returned. * 删除记录 * @param statement Unique identifier matching the statement to execute. * @param parameter A parameter object to pass to the statement. * @return int The number of rows affected by the delete. 返回的是受影响的行数 */ int delete(String statement, Object parameter); //以下是事务控制方法,commit,rollback /** * Flushes batch statements and commits database connection. * Note that database connection will not be committed if no updates/deletes/inserts were called. * To force the commit call {@link SqlSession#commit(boolean)} */ void commit(); /** * Flushes batch statements and commits database connection. * @param force forces connection commit */ void commit(boolean force); /** * Discards pending batch statements and rolls database connection back. * Note that database connection will not be rolled back if no updates/deletes/inserts were called. * To force the rollback call {@link SqlSession#rollback(boolean)} */ void rollback(); /** * Discards pending batch statements and rolls database connection back. * Note that database connection will not be rolled back if no updates/deletes/inserts were called. * @param force forces connection rollback */ void rollback(boolean force); /** * Flushes batch statements. * 刷新批处理语句,返回批处理结果 * @return BatchResult list of updated records * @since 3.0.6 */ List<BatchResult> flushStatements(); /** * Closes the session * 关闭Session */ @Override void close(); /** * Clears local session cache * 清理Session缓存 */ void clearCache(); /** * Retrieves current configuration * 得到配置 * @return Configuration */ Configuration getConfiguration(); /** * Retrieves a mapper. * 得到映射器 * 这个巧妙的使用了泛型,使得类型安全 * 到了MyBatis 3,还可以用注解,这样xml都不用写了 * @param <T> the mapper type * @param type Mapper interface class * @return a mapper bound to this SqlSession */ <T> T getMapper(Class<T> type); /** * Retrieves inner database connection * 得到数据库连接 * @return Connection */ Connection getConnection(); }
tuguangquan/mybatis
src/main/java/org/apache/ibatis/session/SqlSession.java
258
package com.ysj.tinySpring.aop; import org.aopalliance.intercept.MethodInterceptor; /** * AdvisedSupport封装了TargetSource, MethodInterceptor和MethodMatcher * */ public class AdvisedSupport { // 要拦截的对象 private TargetSource targetSource; /** * 方法拦截器 * Spring的AOP只支持方法级别的调用,所以其实在AopProxy里,我们只需要将MethodInterceptor放入对象的方法调用 */ private MethodInterceptor methodInterceptor; // 方法匹配器,判断是否是需要拦截的方法 private MethodMatcher methodMatcher; public TargetSource getTargetSource() { return targetSource; } public void setTargetSource(TargetSource targetSource) { this.targetSource = targetSource; } public MethodInterceptor getMethodInterceptor() { return methodInterceptor; } public void setMethodInterceptor(MethodInterceptor methodInterceptor) { this.methodInterceptor = methodInterceptor; } public MethodMatcher getMethodMatcher() { return methodMatcher; } public void setMethodMatcher(MethodMatcher methodMatcher) { this.methodMatcher = methodMatcher; } }
code4craft/tiny-spring
src+/main/java/com/ysj/tinySpring/aop/AdvisedSupport.java
259
package com.wm.remusic.json; /** * Created by wm on 2016/4/15. */ public class GeDanSrcInfo { /** * listid : 6506 * title : 只剩孤独 与我狂欢 * pic_300 : http://c.hiphotos.baidu.com/ting/pic/item/63d0f703918fa0ece1dd6ea4219759ee3d6ddb05.jpg * pic_500 : http://a.hiphotos.baidu.com/ting/pic/item/09fa513d269759eed04a6a62b5fb43166d22df05.jpg * pic_w700 : http://c.hiphotos.baidu.com/ting/pic/item/6a63f6246b600c33846cd4611d4c510fd9f9a105.jpg * width : 375 * height : 375 * listenum : 53078 * collectnum : 368 * tag : 欧美,孤独,华语,夜晚 * desc : 我们无法抗拒孤独。就好比是一次没有烟火的狂欢,但在心底迸射出的热情赤诚火热。时间,让我们体验过热闹,也让我们学会独处。 * url : http://music.baidu.com/songlist/6506 */ private String listid; private String title; private String pic_300; private String pic_500; private String pic_w700; private String width; private String height; private String listenum; private String collectnum; private String tag; private String desc; private String url; public String getListid() { return listid; } public void setListid(String listid) { this.listid = listid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPic_300() { return pic_300; } public void setPic_300(String pic_300) { this.pic_300 = pic_300; } public String getPic_500() { return pic_500; } public void setPic_500(String pic_500) { this.pic_500 = pic_500; } public String getPic_w700() { return pic_w700; } public void setPic_w700(String pic_w700) { this.pic_w700 = pic_w700; } public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public String getListenum() { return listenum; } public void setListenum(String listenum) { this.listenum = listenum; } public String getCollectnum() { return collectnum; } public void setCollectnum(String collectnum) { this.collectnum = collectnum; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
aa112901/remusic
app/src/main/java/com/wm/remusic/json/GeDanSrcInfo.java
260
/* * (C) Copyright 2015-2016 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. * * Contributors: * [email protected] (夜色) */ package com.mpush.core.server; import com.mpush.api.connection.ConnectionManager; import com.mpush.api.protocol.Command; import com.mpush.api.service.Listener; import com.mpush.common.MessageDispatcher; import com.mpush.core.MPushServer; import com.mpush.core.handler.GatewayPushHandler; import com.mpush.netty.server.NettyTCPServer; import com.mpush.tools.config.CC; import com.mpush.tools.config.CC.mp.net.rcv_buf; import com.mpush.tools.config.CC.mp.net.snd_buf; import com.mpush.tools.thread.NamedPoolThreadFactory; import com.mpush.tools.thread.ThreadNames; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.sctp.nio.NioSctpServerChannel; import io.netty.channel.udt.nio.NioUdtProvider; import io.netty.handler.traffic.GlobalChannelTrafficShapingHandler; import java.nio.channels.spi.SelectorProvider; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import static com.mpush.tools.config.CC.mp.net.gateway_server_bind_ip; import static com.mpush.tools.config.CC.mp.net.gateway_server_port; import static com.mpush.tools.config.CC.mp.net.traffic_shaping.gateway_server.*; import static com.mpush.tools.config.CC.mp.net.write_buffer_water_mark.gateway_server_high; import static com.mpush.tools.config.CC.mp.net.write_buffer_water_mark.gateway_server_low; import static com.mpush.tools.thread.ThreadNames.T_TRAFFIC_SHAPING; /** * Created by ohun on 2015/12/30. * * @author [email protected] */ public final class GatewayServer extends NettyTCPServer { private ServerChannelHandler channelHandler; private ConnectionManager connectionManager; private MessageDispatcher messageDispatcher; private GlobalChannelTrafficShapingHandler trafficShapingHandler; private ScheduledExecutorService trafficShapingExecutor; private MPushServer mPushServer; public GatewayServer(MPushServer mPushServer) { super(gateway_server_port, gateway_server_bind_ip); this.mPushServer = mPushServer; this.messageDispatcher = new MessageDispatcher(); this.connectionManager = new ServerConnectionManager(false); this.channelHandler = new ServerChannelHandler(false, connectionManager, messageDispatcher); } @Override public void init() { super.init(); messageDispatcher.register(Command.GATEWAY_PUSH, () -> new GatewayPushHandler(mPushServer.getPushCenter())); if (CC.mp.net.traffic_shaping.gateway_server.enabled) {//启用流量整形,限流 trafficShapingExecutor = Executors.newSingleThreadScheduledExecutor(new NamedPoolThreadFactory(T_TRAFFIC_SHAPING)); trafficShapingHandler = new GlobalChannelTrafficShapingHandler( trafficShapingExecutor, write_global_limit, read_global_limit, write_channel_limit, read_channel_limit, check_interval); } } @Override public void stop(Listener listener) { super.stop(listener); if (trafficShapingHandler != null) { trafficShapingHandler.release(); trafficShapingExecutor.shutdown(); } if (connectionManager != null) { connectionManager.destroy(); } } @Override protected String getBossThreadName() { return ThreadNames.T_GATEWAY_BOSS; } @Override protected String getWorkThreadName() { return ThreadNames.T_GATEWAY_WORKER; } @Override protected int getIoRate() { return 100; } @Override protected int getWorkThreadNum() { return CC.mp.thread.pool.gateway_server_work; } @Override protected void initPipeline(ChannelPipeline pipeline) { super.initPipeline(pipeline); if (trafficShapingHandler != null) { pipeline.addFirst(trafficShapingHandler); } } @Override protected void initOptions(ServerBootstrap b) { super.initOptions(b); if (snd_buf.gateway_server > 0) b.childOption(ChannelOption.SO_SNDBUF, snd_buf.gateway_server); if (rcv_buf.gateway_server > 0) b.childOption(ChannelOption.SO_RCVBUF, rcv_buf.gateway_server); /** * 这个坑其实也不算坑,只是因为懒,该做的事情没做。一般来讲我们的业务如果比较小的时候我们用同步处理,等业务到一定规模的时候,一个优化手段就是异步化。 * 异步化是提高吞吐量的一个很好的手段。但是,与异步相比,同步有天然的负反馈机制,也就是如果后端慢了,前面也会跟着慢起来,可以自动的调节。 * 但是异步就不同了,异步就像决堤的大坝一样,洪水是畅通无阻。如果这个时候没有进行有效的限流措施就很容易把后端冲垮。 * 如果一下子把后端冲垮倒也不是最坏的情况,就怕把后端冲的要死不活。 * 这个时候,后端就会变得特别缓慢,如果这个时候前面的应用使用了一些无界的资源等,就有可能把自己弄死。 * 那么现在要介绍的这个坑就是关于Netty里的ChannelOutboundBuffer这个东西的。 * 这个buffer是用在netty向channel write数据的时候,有个buffer缓冲,这样可以提高网络的吞吐量(每个channel有一个这样的buffer)。 * 初始大小是32(32个元素,不是指字节),但是如果超过32就会翻倍,一直增长。 * 大部分时候是没有什么问题的,但是在碰到对端非常慢(对端慢指的是对端处理TCP包的速度变慢,比如对端负载特别高的时候就有可能是这个情况)的时候就有问题了, * 这个时候如果还是不断地写数据,这个buffer就会不断地增长,最后就有可能出问题了(我们的情况是开始吃swap,最后进程被linux killer干掉了)。 * 为什么说这个地方是坑呢,因为大部分时候我们往一个channel写数据会判断channel是否active,但是往往忽略了这种慢的情况。 * * 那这个问题怎么解决呢?其实ChannelOutboundBuffer虽然无界,但是可以给它配置一个高水位线和低水位线, * 当buffer的大小超过高水位线的时候对应channel的isWritable就会变成false, * 当buffer的大小低于低水位线的时候,isWritable就会变成true。所以应用应该判断isWritable,如果是false就不要再写数据了。 * 高水位线和低水位线是字节数,默认高水位是64K,低水位是32K,我们可以根据我们的应用需要支持多少连接数和系统资源进行合理规划。 */ if (gateway_server_low > 0 && gateway_server_high > 0) { b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( gateway_server_low, gateway_server_high )); } } @Override public ChannelFactory<? extends ServerChannel> getChannelFactory() { if (CC.mp.net.tcpGateway()) return super.getChannelFactory(); if (CC.mp.net.udtGateway()) return NioUdtProvider.BYTE_ACCEPTOR; if (CC.mp.net.sctpGateway()) return NioSctpServerChannel::new; return super.getChannelFactory(); } @Override public SelectorProvider getSelectorProvider() { if (CC.mp.net.tcpGateway()) return super.getSelectorProvider(); if (CC.mp.net.udtGateway()) return NioUdtProvider.BYTE_PROVIDER; if (CC.mp.net.sctpGateway()) return super.getSelectorProvider(); return super.getSelectorProvider(); } @Override public ChannelHandler getChannelHandler() { return channelHandler; } public ConnectionManager getConnectionManager() { return connectionManager; } public MessageDispatcher getMessageDispatcher() { return messageDispatcher; } }
mpusher/mpush
mpush-core/src/main/java/com/mpush/core/server/GatewayServer.java
261
package com.mossle.api.tenant; public class TenantDTO { /** 普通的管理后台的类型. */ public static final String TYPE_DEFAULT = "default"; /** cms前端显示静态页面的类型. */ public static final String TYPE_CMS = "cms"; /** 数据库里的逻辑id. */ private String id; /** 用户可以理解的名称 */ private String name; /** 可以放到url里的代码. */ private String code; /** 与外部系统协商的唯一标识. */ private String ref; /** 这个应用的资源是否会被其他应用共享. */ private boolean shared; /** 我们可以认为每个scope都是一个租户,每个租户当然需要关联一种登录的方式. */ private String userRepoRef; /** 类型. */ private String type; public String getId() { return id; } public void setId(String id) { if (id == null) { id = ""; } else { this.id = id.trim().toLowerCase(); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getRef() { return ref; } public void setRef(String ref) { this.ref = ref; } public boolean isShared() { return shared; } public void setShared(boolean shared) { this.shared = shared; } public String getUserRepoRef() { return userRepoRef; } public void setUserRepoRef(String userRepoRef) { this.userRepoRef = userRepoRef; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
xuhuisheng/lemon
src/main/java/com/mossle/api/tenant/TenantDTO.java
262
/* * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved. * * https://www.mall4j.com/ * * 未经允许,不可做商业用途! * * 版权所有,侵权必究! */ package com.yami.shop.bean.enums; /** * @author lanhai */ public enum SmsType { /** *发送验证码 */ VALID(0,"SMS_152288010","感谢您对xxx的支持。您的验证码是${code},请勿把验证码泄漏给第三方。"), /** * 商品库存不足通知 */ STOCKS_ARM(1,"SMS_152288054","尊敬的${name},感谢您对xxx的支持。您的${prodName}库存仅剩${num},为免影响您的客户下单,请及时补货!"), /** * 行业客户审核通过通知 */ DISTRIBUTOR_PASS_AUDIT(2,"SMS_152283207","尊敬的${name},感谢您对xxx的支持。您提交的资料已审核通过!祝您购物愉快!"), /** * 分销商订单购买成功通知 */ DISTRIBUTOR_BUY_SUCCESS(3,"SMS_152283148","尊敬的${name},感谢您对xxx的支持。您的订单${orderNumber}已确认成功,我们会尽快发货!"), /** * 用户发货通知 */ NOTIFY_DVY(4,"SMS_152283152","尊敬的${name},感谢您对xxx的支持。您的订单${orderNumber}已通过${dvyName}发货,快递单号是:${dvyFlowId}。请注意查收。"), /** * 代理商审核通知 */ AGENT_PASS_AUDIT(5,"SMS_152288028","尊敬的${name},感谢您对xxx的支持。您提交的代理商申请已审核通过!请重新登陆获取新的会员信息。"), /** * 代理商商品被购买通知 */ NOTIFY_BUY(6,"SMS_152288372","尊敬的${name},感谢您对xxx的支持。与您有关联的订单${orderNumber}已生成,客户${buyerName},提货${prodName},数量${buyNum},剩余库存为${stockNum}。"), /** * 代理商新增分销商通知 */ ADD_DISTRIBUTOR(7,"SMS_152283192","尊敬的${name},感谢您对xxx的支持。您有新增绑定客户资料生成:客户${userName},联系方式${mobilePhone},联系地址${addr},合计共有客户${number}名。"), /** * 代理商解除与分销商合作通知 */ UNBINDING(8,"SMS_152283198","尊敬的${name},感谢您对xxx的支持。您已成功解除与此客户的绑定关系:客户${userName},联系方式${mobilePhone},联系地址${addr},现合计共有客户${number}名。"), /** * 代理商补货订单模板 */ AGENT_BUY_SUCCESS(9,"SMS_152288475","尊敬的${name},感谢您对xxx的支持。您的补货订单${orderNumber}已完成入库,${prodName}剩余库存为${stockNum}。"), /** * 普通用户下单成功通知 */ USER_BUY_SUCCESS(10,"SMS_152288329","亲爱的客户,感谢您对xxx的支持。您的订单${orderNumber}已支付成功。我们会尽快发货!") ; private Integer num; private String templateCode; private String content; public Integer value() { return num; } SmsType(Integer num,String templateCode,String content){ this.num = num; this.templateCode = templateCode; this.content = content; } public static SmsType instance(Integer value) { SmsType[] enums = values(); for (SmsType statusEnum : enums) { if (statusEnum.value().equals(value)) { return statusEnum; } } return null; } public String getTemplateCode() { return this.templateCode; } public String getContent() { return this.content; } }
gz-yami/mall4j
yami-shop-bean/src/main/java/com/yami/shop/bean/enums/SmsType.java
263
package com.mossle.security.api; /** * 获取用户信息. * * 存在的问题是,如果只从一个用户资源库读取用户,可以保证username唯一 但是如果需要整个多个用户资源库,可能出现用户名不唯一的情况 这时要根据username与repoCode结合确认唯一的用户 * * 第二个问题是,我们一般不需要把所有app的权限都返回给某一个app 所以还需要根据appId进一步筛选 */ public interface UserFetcher { UserInfo getUserInfo(String username); UserInfo getUserInfo(String username, String tenantId); UserInfo getUserInfo(String username, String userRepoRef, String tenantId); }
xuhuisheng/lemon
src/main/java/com/mossle/security/api/UserFetcher.java
264
__________________________________________________________________________________________________ sample 0 ms submission class Solution { public int consecutiveNumbersSum(int N) { while ((N & 1) == 0) N >>= 1; int ans = 1, d = 3; while (d * d <= N) { int e = 0; while (N % d == 0) { N /= d; e++; } ans *= e + 1; d += 2; } if (N > 1) ans <<= 1; return ans; } } __________________________________________________________________________________________________ sample 31764 kb submission class Solution { public int consecutiveNumbersSum(int N) { int ans = 0; for (int m = 1; ; m++) { int mx = N - m * (m-1) / 2; if (mx <= 0) break; if (mx % m == 0) ans++; } return ans; } /* 这道题的要求的另一种说法: 把N表示成一个等差数列(公差为1)的和 我们不妨设这个数列的首项是x,项数为m,则这个数列的和就是[x + (x + (m-1))]m / 2 = mx + m(m-1)/2 = N 接下来,一个很自然的想法就是,枚举m,通过上式判断对于相应的m是否存在合法的x。 x = ((N - m(m-1)/2)) / m 显然枚举的复杂度是O(sqrt(N))。因为m能取到的最大值显然是sqrt(n)数量级的 */ } __________________________________________________________________________________________________
strengthen/LeetCode
Java/829.java
265
__________________________________________________________________________________________________ sample 1 ms submission /* 自己最开始的想法错了。统计个数的方法无法区分是不是连续,所以像"abaa",["ab"]这个例子本来应该是0,但是我的方法就会返回1。后来看了discuss排名第二的解法,是用双指针来做。我们用i和就分别表示S和word的指针,如果i和j位置不相等就直接返回false,否则我们分别得到重复字母的长度len1和len2。然后的判断逻辑就跟我自己想法中的判断逻辑一样了 */ class Solution { public int expressiveWords(String S, String[] words) { int res = 0; for (String word : words) { if (check(S, word)) { res++; } } return res; } public boolean check(String s, String word) { int i = 0, j = 0; while (i < s.length() && j < word.length()) { if (s.charAt(i) != word.charAt(j)) { return false; } int len1 = getRepeatedLength(s, i); int len2 = getRepeatedLength(word, j); if (len1 < 3 && len1 != len2) { return false; } if (len1 >= 3 && len2 > len1) { return false; } i += len1; j += len2; } //这个不要忘了 return i == s.length() && j == word.length(); } public int getRepeatedLength(String s, int index) { char c = s.charAt(index); int count = 0; while (index < s.length() && s.charAt(index) == c) { count++; index++; } return count; } } __________________________________________________________________________________________________ sample 36996 kb submission class Solution { List<Pair> sMap; public int expressiveWords(String S, String[] words) { sMap = new ArrayList<>(); int start = 0, pt = 0; while(pt < S.length()){ while(pt+1 < S.length() && S.charAt(pt) == S.charAt(pt+1)){ pt++; } sMap.add(new Pair(S.charAt(pt), pt - start + 1)); pt = start = pt + 1; } int tot = 0; for(String word : words){ if(isStretchy(word)){ tot += 1; } } return tot; } public boolean isStretchy(String word){ int start = 0; int pt = 0; Pair p; int i=0; for(; i < sMap.size(); i++){ p = sMap.get(i); if(pt < word.length()){ if(p.let != word.charAt(pt)){ return false; } while(pt<word.length() && word.charAt(pt)==p.let){ pt++; } if(p.count < pt-start || (p.count > pt-start) && p.count < 3){ return false; } start = pt; } else{ break; } } if(pt == word.length() && i == sMap.size()){ return true; } else{ return false; } } class Pair{ Pair(char let, int num){ this.let = let; this.count = num; } char let; int count; } } __________________________________________________________________________________________________
strengthen/LeetCode
Java/809.java
266
__________________________________________________________________________________________________ sample 0 ms submission class Solution { // e.g. 1993->9913 rather than 9193 /* 找到每个数字右边的最大数字(包括其自身),这样我们再从高位像低位遍历,如果某一位上的数字小于其右边的最大数字,说明需要调换,由于最大数字可能不止出现一次,我们希望能跟较低位的数字置换,这样置换后的数字最大,所以我们就从低位向高位遍历来找那个最大的数字,找到后进行调换即可。 */ public int maximumSwap(int num) { char[] s = Integer.toString(num).toCharArray(); int t = -1; for (int i = 0; i < s.length - 1; i++) if (s[i] < s[i + 1]) { t = i; // 找出单调增的第一个位置 break; } if (t == -1) return Integer.valueOf(new String(s)); int maxIdx = t; for (int i = t + 1; i < s.length; i++){ if (s[maxIdx] <= s[i]) maxIdx = i; //找出单调增的第一个位置后面最大数出现的最后一个位置maxIdx } for (int i = 0; i < s.length; i++){ if (s[i] < s[maxIdx]) { swap(s, i, maxIdx); break; } } return Integer.valueOf(new String(s)); } private void swap(char[] s, int idx1, int idx2){ char temp = s[idx1]; s[idx1] = s[idx2]; s[idx2] = temp; } } __________________________________________________________________________________________________ sample 31616 kb submission class Solution { public int maximumSwap(int num) { char[] arr = String.valueOf(num).toCharArray(); int[] last = new int[10]; for(int i=0; i<arr.length; i++){ last[arr[i]-'0']=i;//last occurance of this digit; } for(int i=0; i<arr.length; i++){ for(int d=9; d>arr[i]-'0'; d--){ if(last[d]>i){ swap(arr, i, last[d]); return Integer.valueOf(new String(arr)); } } } return num; } private void swap(char[] arr, int i, int j){ char tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } __________________________________________________________________________________________________
strengthen/LeetCode
Java/670.java
267
__________________________________________________________________________________________________ sample 1 ms submission class Solution { private int min = Integer.MAX_VALUE, max = 0; public List<String> wordBreak(String s, List<String> wordDict) { HashSet<String> set = new HashSet<String>(); for(String word:wordDict){ set.add(word); int curLen = word.length(); min = (curLen<min)? curLen:min; max = (curLen>max)? curLen:max; } List<String> result = new ArrayList<String>(); boolean[] invalid = new boolean[s.length()]; //invalid[i]: [i:] is unbreakable seperate(s, result, new StringBuilder(), 0, set, invalid); return result; } public boolean seperate(String s,List<String> res, StringBuilder tmp, int index,HashSet<String> set, boolean[] invalid){ if(index == s.length()){ res.add(tmp.toString().trim()); return true; } boolean breakable = false; int prelen = tmp.length(); int rightbound = Math.min(s.length(),index+max); for(int end = index+1; end<=rightbound; end++){ int curLen = end-index; if(end<s.length()&&invalid[end]){ continue; } String cur = s.substring(index, end); if(set.contains(cur)){ tmp.append(" ").append(cur); breakable |= seperate(s,res,tmp,end,set, invalid); tmp.setLength(prelen); } } invalid[index] = !breakable; return breakable; } } __________________________________________________________________________________________________ sample 34792 kb submission /* 像这种返回结果要列举所有情况的题,十有八九都是要用递归来做的!!!。 当我们一时半会没有啥思路的时候,先不要考虑代码如何实现,如果就给你一个s和wordDict,不看Output的内容,你会怎么找出结果。比如对于例子1,博主可能会先扫一遍wordDict数组,看有没有单词可以当s的开头,那么我们可以发现cat和cats都可以,比如我们先选了cat,那么此时s就变成了 "sanddog",我们再在数组里找单词,发现了sand可以,最后剩一个dog,也在数组中,于是一个结果就出来了。然后回到开头选cats的话,那么此时s就变成了 "anddog",我们再在数组里找单词,发现了and可以,最后剩一个dog,也在数组中,于是另一个结果也就出来了。那么这个查询的方法很适合用递归来实现,因为s改变后,查询的机制并不变,很适合调用递归函数。 再者,我们要明确的是,如果不用记忆数组做减少重复计算的优化,那么递归方法跟brute force没什么区别,大概率无法通过OJ。所以我们要避免重复计算!!!!! ,如何避免呢,还是看上面的分析,如果当s变成 "sanddog"的时候,那么此时我们知道其可以拆分成sand和dog,当某个时候如果我们又遇到了这个 "sanddog"的时候,我们难道还需要再调用递归算一遍吗,当然不希望啦,所以我们要将这个中间结果保存起来,由于我们必须要同时保存s和其所有的拆分的字符串,那么可以使用一个HashMap,来建立二者之间的映射,那么在递归函数中,我们首先检测当前s是否已经有映射,有的话直接返回即可,如果s为空了,我们如何处理呢,题目中说了给定的s不会为空,但是我们递归函数处理时s是会变空的,这时候我们是直接返回空集吗,这里有个小trick,我们其实放一个空字符串返回,为啥要这么做呢?我们观察题目中的Output,发现单词之间是有空格,而最后一个单词后面没有空格,所以这个空字符串就起到了标记当前单词是最后一个,那么我们就不要再加空格了。接着往下看,我们遍历wordDict数组,如果某个单词是s字符串中的开头单词的话,我们对后面部分调用递归函数,将结果保存到rem中,然后遍历里面的所有字符串,和当前的单词拼接起来,这里就用到了我们前面说的trick。for循环结束后,记得返回结果res之前建立其和s之间的映射,方便下次使用, */ //这道题的主要一点就是要在递归的时候避免重复计算,因为会超时,所以需要用map纪录每个word 开头以后,后面能被分成的状况 class Solution { public List<String> wordBreak(String s, List<String> wordDict) { return DFS(s, wordDict, new HashMap<String, List<String>>()); } private List<String> DFS(String s, List<String> wordDict, Map<String, List<String>> map) { //这说明s后面的分成情况之前就已经计算过,所以只要直接拿来就可以 if (map.containsKey(s)) return map.get(s); //若不是之前就计算过的,那么subRes就是该s分割以后的结果情况 List<String> subRes = new ArrayList<>(); //说明上一层分割的是最后一个,那么我们需要在他的subRes中加个空,告诉上一层已经没有了 if (s.length() == 0) { subRes.add(""); return subRes; } //因为分割到哪个部分都需要重新过dict中的word,因为不知道是从哪里起头的 for (String w : wordDict) { if (s.startsWith(w)) { //s.substring(w.length()),表示的是取idx为w.length()开始,到结束的字符串 List<String> subString = DFS(s.substring(w.length()), wordDict, map); //因为res 是List<String>的形式,所以只能一个一个string的往上加,不能直接加一个List<String>的subString结果 for (String sub : subString) { subRes.add(w + (sub.isEmpty() ? "" : " ") + sub); } } } //每一层递归结束后把该层递归开始的s,以及其后面的分割情况加入map中纪录起来 map.put(s, subRes); return subRes; } } __________________________________________________________________________________________________
strengthen/LeetCode
Java/140.java
268
package cn.iocoder.springboot.labs.lab69; import cn.iocoder.springboot.labs.lab69.service.UserServiceImpl; import org.apache.commons.io.IOUtils; import sun.misc.ProxyGenerator; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Proxy; /** * 生成 JDK {@link Proxy} 的示例代码 * * 生成后,我们可以反编译查看具体的类 */ public class GenerateProxyMain { public static void main(String[] args) throws IOException { // 生成字节码 byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy11", UserServiceImpl.class.getInterfaces()); // 写入到磁盘 IOUtils.write(classFile, new FileOutputStream("/Users/yunai/ls/$Proxy11.class")); } }
yudaocode/SpringBoot-Labs
lab-69-proxy/lab-69-proxy-jdk/src/main/java/cn/iocoder/springboot/labs/lab69/GenerateProxyMain.java
269
/* * Copyright 2018-present KunMinX * * 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.kunminx.puremusic.data.bean; /** * Create by KunMinX at 20/04/26 * <p> * bean,原始数据,只读 * Java 我们通过移除 setter * kotlin 直接将字段设为 val 即可 */ public class User { private final String name; private final String password; public User(String name, String password) { this.name = name; this.password = password; } public String getName() { return name; } public String getPassword() { return password; } }
KunMinX/Jetpack-MVVM-Best-Practice
app/src/main/java/com/kunminx/puremusic/data/bean/User.java
270
/* * Tencent is pleased to support the open source community by making QMUI_Android available. * * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.qmuiteam.qmui.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.RelativeLayout; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.collection.SimpleArrayMap; import androidx.core.view.WindowInsetsCompat; import com.qmuiteam.qmui.R; import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton; import com.qmuiteam.qmui.layout.QMUIFrameLayout; import com.qmuiteam.qmui.qqface.QMUIQQFaceView; import com.qmuiteam.qmui.skin.QMUISkinValueBuilder; import com.qmuiteam.qmui.skin.defaultAttr.IQMUISkinDefaultAttrProvider; import com.qmuiteam.qmui.util.QMUIWindowInsetHelper; import com.qmuiteam.qmui.widget.textview.QMUISpanTouchFixTextView; /** * 这是一个对 {@link QMUITopBar} 的代理类,需要它的原因是: * 我们用 fitSystemWindows 实现沉浸式状态栏后,需要将 {@link QMUITopBar} 的背景衍生到状态栏后面,这个时候 fitSystemWindows 是通过 * 更改 padding 实现的,而 {@link QMUITopBar} 是在高度固定的前提下做各种行为的,例如按钮的垂直居中,因此我们需要在外面包裹一层并消耗 padding * * @author cginechen * @date 2016-11-26 */ public class QMUITopBarLayout extends QMUIFrameLayout implements IQMUISkinDefaultAttrProvider { private QMUITopBar mTopBar; private SimpleArrayMap<String, Integer> mDefaultSkinAttrs = new SimpleArrayMap<>(2); public QMUITopBarLayout(Context context) { this(context, null); } public QMUITopBarLayout(Context context, AttributeSet attrs) { this(context, attrs, R.attr.QMUITopBarStyle); } public QMUITopBarLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mDefaultSkinAttrs.put(QMUISkinValueBuilder.BOTTOM_SEPARATOR, R.attr.qmui_skin_support_topbar_separator_color); mDefaultSkinAttrs.put(QMUISkinValueBuilder.BACKGROUND, R.attr.qmui_skin_support_topbar_bg); mTopBar = new QMUITopBar(context, attrs, defStyleAttr); mTopBar.setBackground(null); mTopBar.setVisibility(View.VISIBLE); // reset these field because mTopBar will set same value with QMUITopBarLayout from attrs mTopBar.setFitsSystemWindows(false); mTopBar.setId(View.generateViewId()); mTopBar.updateBottomDivider(0, 0, 0, 0); FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, mTopBar.getTopBarHeight()); addView(mTopBar, lp); QMUIWindowInsetHelper.handleWindowInsets(this, WindowInsetsCompat.Type.statusBars() | WindowInsetsCompat.Type.displayCutout(), true, true); } public QMUITopBar getTopBar() { return mTopBar; } public void setCenterView(View view) { mTopBar.setCenterView(view); } public QMUIQQFaceView setTitle(int resId) { return mTopBar.setTitle(resId); } public QMUIQQFaceView setTitle(String title) { return mTopBar.setTitle(title); } public void showTitleView(boolean toShow) { mTopBar.showTitleView(toShow); } public QMUISpanTouchFixTextView setSubTitle(int resId) { return mTopBar.setSubTitle(resId); } public QMUISpanTouchFixTextView setSubTitle(CharSequence subTitle) { return mTopBar.setSubTitle(subTitle); } @Nullable public QMUIQQFaceView getTitleView(){ return mTopBar.getTitleView(); } @Nullable public QMUISpanTouchFixTextView getSubTitleView(){ return mTopBar.getSubTitleView(); } public void setTitleGravity(int gravity) { mTopBar.setTitleGravity(gravity); } public void addLeftView(View view, int viewId) { mTopBar.addLeftView(view, viewId); } public void addLeftView(View view, int viewId, RelativeLayout.LayoutParams layoutParams) { mTopBar.addLeftView(view, viewId, layoutParams); } public void addRightView(View view, int viewId) { mTopBar.addRightView(view, viewId); } public void addRightView(View view, int viewId, RelativeLayout.LayoutParams layoutParams) { mTopBar.addRightView(view, viewId, layoutParams); } public QMUIAlphaImageButton addRightImageButton(int drawableResId, int viewId) { return mTopBar.addRightImageButton(drawableResId, viewId); } public QMUIAlphaImageButton addRightImageButton(int drawableResId, boolean followTintColor, int viewId) { return mTopBar.addRightImageButton(drawableResId, followTintColor, viewId); } public QMUIAlphaImageButton addRightImageButton(int drawableResId, boolean followTintColor, int viewId, int iconWidth, int iconHeight) { return mTopBar.addRightImageButton(drawableResId, followTintColor, viewId, iconWidth, iconHeight); } public QMUIAlphaImageButton addLeftImageButton(int drawableResId, int viewId) { return mTopBar.addLeftImageButton(drawableResId, viewId); } public QMUIAlphaImageButton addLeftImageButton(int drawableResId, boolean followTintColor, int viewId) { return mTopBar.addLeftImageButton(drawableResId, followTintColor, viewId); } public QMUIAlphaImageButton addLeftImageButton(int drawableResId, boolean followTintColor, int viewId, int iconWidth, int iconHeight) { return mTopBar.addLeftImageButton(drawableResId, followTintColor, viewId, iconWidth, iconHeight); } public Button addLeftTextButton(int stringResId, int viewId) { return mTopBar.addLeftTextButton(stringResId, viewId); } public Button addLeftTextButton(String buttonText, int viewId) { return mTopBar.addLeftTextButton(buttonText, viewId); } public Button addRightTextButton(int stringResId, int viewId) { return mTopBar.addRightTextButton(stringResId, viewId); } public Button addRightTextButton(String buttonText, int viewId) { return mTopBar.addRightTextButton(buttonText, viewId); } public QMUIAlphaImageButton addLeftBackImageButton() { return mTopBar.addLeftBackImageButton(); } public void removeAllLeftViews() { mTopBar.removeAllLeftViews(); } public void removeAllRightViews() { mTopBar.removeAllRightViews(); } public void removeCenterViewAndTitleView() { mTopBar.removeCenterViewAndTitleView(); } /** * 设置 TopBar 背景的透明度 * * @param alpha 取值范围:[0, 255],255表示不透明 */ public void setBackgroundAlpha(int alpha) { this.getBackground().mutate().setAlpha(alpha); } /** * 根据当前 offset、透明度变化的初始 offset 和目标 offset,计算并设置 Topbar 的透明度 * * @param currentOffset 当前 offset * @param alphaBeginOffset 透明度开始变化的offset,即当 currentOffset == alphaBeginOffset 时,透明度为0 * @param alphaTargetOffset 透明度变化的目标offset,即当 currentOffset == alphaTargetOffset 时,透明度为1 */ public int computeAndSetBackgroundAlpha(int currentOffset, int alphaBeginOffset, int alphaTargetOffset) { double alpha = (float) (currentOffset - alphaBeginOffset) / (alphaTargetOffset - alphaBeginOffset); alpha = Math.max(0, Math.min(alpha, 1)); // from 0 to 1 int alphaInt = (int) (alpha * 255); this.setBackgroundAlpha(alphaInt); return alphaInt; } public void setDefaultSkinAttr(String name, int attr) { mDefaultSkinAttrs.put(name, attr); } @Override public SimpleArrayMap<String, Integer> getDefaultSkinAttrs() { return mDefaultSkinAttrs; } public void eachLeftRightView(@NonNull QMUITopBar.Action action){ mTopBar.eachLeftRightView(action); } }
Tencent/QMUI_Android
qmui/src/main/java/com/qmuiteam/qmui/widget/QMUITopBarLayout.java
272
package sort; /** * @author wangjunwei87 * @since 2019-03-10 */ public class KthSmallest { public static int kthSmallest(int[] arr, int k) { if (arr == null || arr.length < k) { return -1; } int partition = partition(arr, 0, arr.length - 1); while (partition + 1 != k) { if (partition + 1 < k) { partition = partition(arr, partition + 1, arr.length - 1); } else { partition = partition(arr, 0, partition - 1); } } return arr[partition]; } private static int partition(int[] arr, int p, int r) { int pivot = arr[r]; int i = p; for (int j = p; j < r; j++) { // 这里要是 <= ,不然会出现死循环,比如查找数组 [1,1,2] 的第二小的元素 if (arr[j] <= pivot) { swap(arr, i, j); i++; } } swap(arr, i, r); return i; } private static void swap(int[] arr, int i, int j) { if (i == j) { return; } int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }
wangzheng0822/algo
java/12_sorts/KthSmallest.java